合并桌面与云部署修复,保留官网截图更新
- 作者
- Lee-xeo
- 时间
- 2026/11/06 15:13
- 提交
- 8b9a855
这是一个合并提交,下面是和第一个上一提交相比的改动。
这是一个合并提交,下面是和第一个上一提交相比的改动。
| @@ -3043,6 +3043,36 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| 3043 | 3043 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 3044 | 3044 | SOFTWARE. |
| 3045 | 3045 | |
| 3046 | 新增:================================================================================ | |
| 3047 | 新增:github.com/godbus/dbus/v5 v5.1.0: LICENSE | |
| 3048 | 新增:================================================================================ | |
| 3049 | 新增: | |
| 3050 | 新增:Copyright (c) 2013, Georg Reinke (<guelfey at gmail dot com>), Google | |
| 3051 | 新增:All rights reserved. | |
| 3052 | 新增: | |
| 3053 | 新增:Redistribution and use in source and binary forms, with or without | |
| 3054 | 新增:modification, are permitted provided that the following conditions | |
| 3055 | 新增:are met: | |
| 3056 | 新增: | |
| 3057 | 新增:1. Redistributions of source code must retain the above copyright notice, | |
| 3058 | 新增:this list of conditions and the following disclaimer. | |
| 3059 | 新增: | |
| 3060 | 新增:2. Redistributions in binary form must reproduce the above copyright | |
| 3061 | 新增:notice, this list of conditions and the following disclaimer in the | |
| 3062 | 新增:documentation and/or other materials provided with the distribution. | |
| 3063 | 新增: | |
| 3064 | 新增:THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS | |
| 3065 | 新增:"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT | |
| 3066 | 新增:LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR | |
| 3067 | 新增:A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT | |
| 3068 | 新增:HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
| 3069 | 新增:SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED | |
| 3070 | 新增:TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | |
| 3071 | 新增:PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF | |
| 3072 | 新增:LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING | |
| 3073 | 新增:NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS | |
| 3074 | 新增:SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
| 3075 | 新增: | |
| 3046 | 3076 | ================================================================================ |
| 3047 | 3077 | github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8: LICENSE |
| 3048 | 3078 | ================================================================================ |
| @@ -1 +1 @@ | ||
| 1 | 删除:0.1.5-alpha.2 | |
| 1 | 新增:0.1.6-alpha-preview | |
| @@ -50,11 +50,25 @@ apt_get() { | ||
| 50 | 50 | # leave the previously trusted key usable on the next setup attempt. |
| 51 | 51 | install_repository_key() ( |
| 52 | 52 | set -euo pipefail |
| 53 | 删除: local url="$1" target="$2" stage replacement='' | |
| 53 | 新增: local url="$1" target="$2" stage replacement='' attempt status=1 | |
| 54 | 54 | stage="$(mktemp)" |
| 55 | 55 | trap 'rm -f "$stage"; if [ -n "$replacement" ]; then sudo rm -f "$replacement"; fi' EXIT |
| 56 | 删除: curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --show-error --silent \ | |
| 57 | 删除: --retry 3 --retry-all-errors --retry-max-time 120 --connect-timeout 15 --max-time 30 "$url" -o "$stage" </dev/null | |
| 56 | 新增: if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then | |
| 57 | 新增: for attempt in 1 2 3 4; do | |
| 58 | 新增: if cage_curl_download "$stage" --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --show-error --silent \ | |
| 59 | 新增: --connect-timeout 15 "$url" -o "$stage" </dev/null; then | |
| 60 | 新增: status=0 | |
| 61 | 新增: break | |
| 62 | 新增: else | |
| 63 | 新增: status=$? | |
| 64 | 新增: fi | |
| 65 | 新增: if [ "$attempt" != 4 ]; then sleep "$attempt"; fi | |
| 66 | 新增: done | |
| 67 | 新增: [ "$status" = 0 ] || return "$status" | |
| 68 | 新增: else | |
| 69 | 新增: curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location --show-error --silent \ | |
| 70 | 新增: --retry 3 --retry-all-errors --retry-max-time 120 --connect-timeout 15 --max-time 30 "$url" -o "$stage" </dev/null | |
| 71 | 新增: fi | |
| 58 | 72 | test -s "$stage" |
| 59 | 73 | if [[ "$target" == *.asc ]]; then |
| 60 | 74 | grep -q '^-----BEGIN PGP PUBLIC KEY BLOCK-----' "$stage" |
| @@ -141,8 +155,10 @@ echo "Installing base packages..." | ||
| 141 | 155 | if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then |
| 142 | 156 | # This runs in the guest, through its configured DNS and proxy-only route. |
| 143 | 157 | echo "Checking guest DNS for Debian packages..." |
| 144 | 删除: if ! timeout 30 getent ahostsv4 deb.debian.org >/dev/null; then | |
| 145 | 删除: echo 'Guest DNS could not resolve deb.debian.org. Check Cage Network & Proxy / DNS settings, apply and retry. Host internet access alone does not verify guest DNS.' >&2 | |
| 158 | 新增: if ! timeout 15 getent ahostsv4 mirrors.nju.edu.cn >/dev/null && | |
| 159 | 新增: ! timeout 15 getent ahostsv4 mirrors.ustc.edu.cn >/dev/null && | |
| 160 | 新增: ! timeout 15 getent ahostsv4 deb.debian.org >/dev/null; then | |
| 161 | 新增: echo 'Guest DNS could not resolve the Debian download sources. Check Cage Network & Proxy / DNS settings, apply and retry.' >&2 | |
| 146 | 162 | exit 1 |
| 147 | 163 | fi |
| 148 | 164 | fi |
| @@ -155,6 +171,12 @@ apt_get install -y --no-install-recommends \ | ||
| 155 | 171 | ca-certificates sshfs \ |
| 156 | 172 | libssl-dev libreadline-dev zlib1g-dev libyaml-dev libffi-dev |
| 157 | 173 | |
| 174 | 新增:# Cage's download inactivity monitor needs Python even when an optional | |
| 175 | 新增:# language preinstall is disabled. Keep standalone agent-vm choices intact. | |
| 176 | 新增:if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then | |
| 177 | 新增: apt_get install -y --no-install-recommends python3 | |
| 178 | 新增:fi | |
| 179 | 新增: | |
| 158 | 180 | # sshfs 3.7.6 (and Debian's 3.7.3-1.2~deb13u1) refuses symlinks whose target |
| 159 | 181 | # is absolute or contains "..", with EPERM: contain_symlinks, on by default |
| 160 | 182 | # (CVE-2026-47187). That breaks every node_modules/.bin link in a share. It |
| @@ -271,7 +293,11 @@ if [[ "$INSTALL_CHROMIUM" == "1" ]]; then | ||
| 271 | 293 | # xauth: xvfb-run needs it, and it is only a Recommends of xvfb. |
| 272 | 294 | # fonts-dejavu-core: with Liberation alone, fontconfig resolves the generic |
| 273 | 295 | # sans-serif and serif to Liberation Mono. |
| 274 | 删除: apt_get install -y --no-install-recommends chromium fonts-liberation fonts-dejavu-core xvfb xauth | |
| 296 | 新增: chromium_packages=(chromium fonts-liberation fonts-dejavu-core xvfb xauth) | |
| 297 | 新增: if [[ "${CLAUDE_CAGE:-}" == 1 ]]; then | |
| 298 | 新增: cage_cache_chromium --no-install-recommends "${chromium_packages[@]}" | |
| 299 | 新增: fi | |
| 300 | 新增: apt_get install -y --no-install-recommends "${chromium_packages[@]}" | |
| 275 | 301 | sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome |
| 276 | 302 | sudo ln -sf /usr/bin/chromium /usr/bin/google-chrome-stable |
| 277 | 303 | sudo mkdir -p /opt/google/chrome |
| @@ -0,0 +1,172 @@ | ||
| 1 | 新增:// cage-client contains the desktop connection service without Lima, virtual | |
| 2 | 新增:// machine assets or a local workload launcher. Native shells use the same | |
| 3 | 新增:// desktop/file-command contract as the full application. | |
| 4 | 新增:package main | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "fmt" | |
| 10 | 新增: "io" | |
| 11 | 新增: "os" | |
| 12 | 新增: "os/exec" | |
| 13 | 新增: "os/signal" | |
| 14 | 新增: "path/filepath" | |
| 15 | 新增: "syscall" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/workbench" | |
| 21 | 新增:) | |
| 22 | 新增: | |
| 23 | 新增:func main() { | |
| 24 | 新增: if err := run(os.Args[1:]); err != nil { | |
| 25 | 新增: diagnostics.Log("error", "client", err.Error()) | |
| 26 | 新增: _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) | |
| 27 | 新增: os.Exit(1) | |
| 28 | 新增: } | |
| 29 | 新增:} | |
| 30 | 新增: | |
| 31 | 新增:func run(args []string) error { | |
| 32 | 新增: if len(args) == 0 || args[0] == "help" || args[0] == "--help" { | |
| 33 | 新增: fmt.Println("Cage remote client " + version.Version + "\nCommands: desktop --json, serve, prepare-update. Workloads run on the selected remote host.") | |
| 34 | 新增: return nil | |
| 35 | 新增: } | |
| 36 | 新增: config := os.Getenv(cage.ConfigEnv) | |
| 37 | 新增: if config == "" { | |
| 38 | 新增: home, err := os.UserHomeDir() | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return err | |
| 41 | 新增: } | |
| 42 | 新增: config = filepath.Join(home, ".claude-cage", "client", "config.json") | |
| 43 | 新增: } | |
| 44 | 新增: config, err := filepath.Abs(config) | |
| 45 | 新增: if err != nil { | |
| 46 | 新增: return err | |
| 47 | 新增: } | |
| 48 | 新增: diagnostics.SetDefault(diagnostics.New(filepath.Dir(config))) | |
| 49 | 新增: printJSON := func(value any, err error) error { | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: return json.NewEncoder(os.Stdout).Encode(value) | |
| 54 | 新增: } | |
| 55 | 新增: switch args[0] { | |
| 56 | 新增: case "serve": | |
| 57 | 新增: return workbench.ServeClient(config) | |
| 58 | 新增: case "log-relay": | |
| 59 | 新增: if len(args) != 2 || args[1] != "controller" { | |
| 60 | 新增: return errors.New("unsupported client service") | |
| 61 | 新增: } | |
| 62 | 新增: return relay(config) | |
| 63 | 新增: case "desktop": | |
| 64 | 新增: options := workbench.DesktopOptions{} | |
| 65 | 新增: for _, argument := range args[1:] { | |
| 66 | 新增: switch argument { | |
| 67 | 新增: case "--json": | |
| 68 | 新增: case "--existing": | |
| 69 | 新增: options.UseExisting = true | |
| 70 | 新增: case "--complete-update": | |
| 71 | 新增: options.CompleteUpdate = true | |
| 72 | 新增: default: | |
| 73 | 新增: return errors.New("unsupported desktop option") | |
| 74 | 新增: } | |
| 75 | 新增: } | |
| 76 | 新增: return printJSON(workbench.Desktop(config, options)) | |
| 77 | 新增: case "prepare-update": | |
| 78 | 新增: stop := false | |
| 79 | 新增: for _, argument := range args[1:] { | |
| 80 | 新增: switch argument { | |
| 81 | 新增: case "--json": | |
| 82 | 新增: case "--stop": | |
| 83 | 新增: stop = true | |
| 84 | 新增: default: | |
| 85 | 新增: return errors.New("unsupported update option") | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增: return printJSON(workbench.PrepareUpdate(config, stop)) | |
| 89 | 新增: case "diagnostic-event": | |
| 90 | 新增: var event struct { | |
| 91 | 新增: Source string `json:"source"` | |
| 92 | 新增: Message string `json:"message"` | |
| 93 | 新增: } | |
| 94 | 新增: if json.NewDecoder(io.LimitReader(os.Stdin, 32<<10)).Decode(&event) != nil || event.Source != "native" { | |
| 95 | 新增: return errors.New("invalid diagnostic event") | |
| 96 | 新增: } | |
| 97 | 新增: return diagnostics.New(filepath.Dir(config)).Record("error", event.Source, event.Message) | |
| 98 | 新增: case "diagnostics": | |
| 99 | 新增: connection := "" | |
| 100 | 新增: if len(args) == 5 && args[1] == "--json" && args[2] == "--connection" { | |
| 101 | 新增: connection = args[3] | |
| 102 | 新增: args = []string{args[0], args[1], args[4]} | |
| 103 | 新增: } | |
| 104 | 新增: if len(args) != 3 || args[1] != "--json" { | |
| 105 | 新增: return errors.New("diagnostics --json /absolute/path.zip") | |
| 106 | 新增: } | |
| 107 | 新增: if err := workbench.ExportDiagnosticsForConnection(config, connection, args[2]); err != nil { | |
| 108 | 新增: return err | |
| 109 | 新增: } | |
| 110 | 新增: return printJSON(map[string]string{"status": "ok"}, nil) | |
| 111 | 新增: case "upload-files", "browser-file": | |
| 112 | 新增: if len(args) < 4 || args[1] != "--json" { | |
| 113 | 新增: return errors.New("invalid file command") | |
| 114 | 新增: } | |
| 115 | 新增: connection := "" | |
| 116 | 新增: if args[2] == "--connection" { | |
| 117 | 新增: if len(args) < 6 || args[3] == "" { | |
| 118 | 新增: return errors.New("missing connection identity") | |
| 119 | 新增: } | |
| 120 | 新增: connection = args[3] | |
| 121 | 新增: args = append(append([]string{}, args[:2]...), args[4:]...) | |
| 122 | 新增: } | |
| 123 | 新增: if args[0] == "upload-files" { | |
| 124 | 新增: if len(args) < 5 { | |
| 125 | 新增: return errors.New("no selected files") | |
| 126 | 新增: } | |
| 127 | 新增: return printJSON(workbench.UploadHostFilesForConnection(config, connection, args[2], args[3], args[4:])) | |
| 128 | 新增: } | |
| 129 | 新增: if len(args) < 4 || len(args) > 5 { | |
| 130 | 新增: return errors.New("invalid download command") | |
| 131 | 新增: } | |
| 132 | 新增: destination := "" | |
| 133 | 新增: if len(args) == 5 { | |
| 134 | 新增: destination = args[4] | |
| 135 | 新增: } | |
| 136 | 新增: return printJSON(workbench.BrowserFileForConnection(config, connection, args[2], args[3], destination)) | |
| 137 | 新增: case "app-update": | |
| 138 | 新增: return printJSON(map[string]any{"phase": "manual", "currentVersion": version.Version, "message": "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"}, nil) | |
| 139 | 新增: default: | |
| 140 | 新增: return errors.New("轻量客户端只负责连接;请在远程工作台管理运行环境") | |
| 141 | 新增: } | |
| 142 | 新增:} | |
| 143 | 新增: | |
| 144 | 新增:func relay(config string) error { | |
| 145 | 新增: executable, err := os.Executable() | |
| 146 | 新增: if err != nil { | |
| 147 | 新增: return err | |
| 148 | 新增: } | |
| 149 | 新增: cmd := exec.Command(executable, "serve") | |
| 150 | 新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+config) | |
| 151 | 新增: store := diagnostics.New(filepath.Dir(config)) | |
| 152 | 新增: out, stderr := store.Stream("client", "info"), store.Stream("client", "error") | |
| 153 | 新增: defer out.Close() | |
| 154 | 新增: defer stderr.Close() | |
| 155 | 新增: cmd.Stdout, cmd.Stderr = out, stderr | |
| 156 | 新增: if err := cmd.Start(); err != nil { | |
| 157 | 新增: return err | |
| 158 | 新增: } | |
| 159 | 新增: signals := make(chan os.Signal, 1) | |
| 160 | 新增: signal.Notify(signals, os.Interrupt, syscall.SIGTERM) | |
| 161 | 新增: defer signal.Stop(signals) | |
| 162 | 新增: done := make(chan struct{}) | |
| 163 | 新增: defer close(done) | |
| 164 | 新增: go func() { | |
| 165 | 新增: select { | |
| 166 | 新增: case sig := <-signals: | |
| 167 | 新增: _ = cmd.Process.Signal(sig) | |
| 168 | 新增: case <-done: | |
| 169 | 新增: } | |
| 170 | 新增: }() | |
| 171 | 新增: return cmd.Wait() | |
| 172 | 新增:} | |
| @@ -0,0 +1,145 @@ | ||
| 1 | 新增:package main | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/signal" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "runtime" | |
| 13 | 新增: "syscall" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/workbench" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:func configureContainer(configPath string) error { | |
| 22 | 新增: if runtime.GOOS != "linux" { | |
| 23 | 新增: return errors.New("容器服务端需要 Linux;本机可使用轻量客户端连接") | |
| 24 | 新增: } | |
| 25 | 新增: profile := filepath.Dir(configPath) | |
| 26 | 新增: entries, err := os.ReadDir(filepath.Join(profile, "state", "lima")) | |
| 27 | 新增: if err != nil && !os.IsNotExist(err) { | |
| 28 | 新增: return err | |
| 29 | 新增: } | |
| 30 | 新增: if len(entries) > 0 { | |
| 31 | 新增: return errors.New("此配置已有虚拟机数据;请为云端容器使用独立配置,原有数据保持不变") | |
| 32 | 新增: } | |
| 33 | 新增: var config containerenv.Config | |
| 34 | 新增: decoder := json.NewDecoder(io.LimitReader(os.Stdin, 64<<10)) | |
| 35 | 新增: decoder.DisallowUnknownFields() | |
| 36 | 新增: if err := decoder.Decode(&config); err != nil { | |
| 37 | 新增: return errors.New("容器配置格式无效") | |
| 38 | 新增: } | |
| 39 | 新增: var extra any | |
| 40 | 新增: if decoder.Decode(&extra) != io.EOF { | |
| 41 | 新增: return errors.New("只接受一份容器配置") | |
| 42 | 新增: } | |
| 43 | 新增: if _, err := containerenv.Configure(profile, config); err != nil { | |
| 44 | 新增: return err | |
| 45 | 新增: } | |
| 46 | 新增: return json.NewEncoder(os.Stdout).Encode(map[string]bool{"configured": true}) | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func containerOperation(configPath string, args []string, cfg cage.Config) (bool, error) { | |
| 50 | 新增: profile := filepath.Dir(configPath) | |
| 51 | 新增: if !containerenv.Configured(profile) { | |
| 52 | 新增: return false, nil | |
| 53 | 新增: } | |
| 54 | 新增: switch args[0] { | |
| 55 | 新增: case "setup", "up", "login", "stop", "list", "info", "doctor", "name", "run", "shell", "claude", "update-tools", "access": | |
| 56 | 新增: default: | |
| 57 | 新增: return false, nil | |
| 58 | 新增: } | |
| 59 | 新增: if runtime.GOOS != "linux" { | |
| 60 | 新增: return true, errors.New("容器运行环境只能在 Linux 服务端使用") | |
| 61 | 新增: } | |
| 62 | 新增: if args[0] == "access" { | |
| 63 | 新增: return true, errors.New("容器工作环境使用 Cage 工作台的受认证入口,不提供旧版独立查看器凭据") | |
| 64 | 新增: } | |
| 65 | 新增: if args[0] != "run" && args[0] != "claude" && len(args) != 1 { | |
| 66 | 新增: return true, errors.New("该容器管理命令不接受额外参数") | |
| 67 | 新增: } | |
| 68 | 新增: environment, err := containerenv.Load(profile) | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: return true, err | |
| 71 | 新增: } | |
| 72 | 新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 73 | 新增: defer cancel() | |
| 74 | 新增: switch args[0] { | |
| 75 | 新增: case "stop": | |
| 76 | 新增: if len(args) != 1 { | |
| 77 | 新增: return true, errors.New("容器配置只管理自身的持久环境") | |
| 78 | 新增: } | |
| 79 | 新增: if err := environment.Stop(ctx); err != nil { | |
| 80 | 新增: return true, err | |
| 81 | 新增: } | |
| 82 | 新增: return true, managedproxy.Stop(profile) | |
| 83 | 新增: case "list", "info": | |
| 84 | 新增: state, err := environment.State(ctx) | |
| 85 | 新增: if err != nil { | |
| 86 | 新增: return true, err | |
| 87 | 新增: } | |
| 88 | 新增: return true, json.NewEncoder(os.Stdout).Encode(state) | |
| 89 | 新增: case "doctor": | |
| 90 | 新增: inspection, err := environment.Inspect(ctx) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: return true, err | |
| 93 | 新增: } | |
| 94 | 新增: return true, json.NewEncoder(os.Stdout).Encode(inspection) | |
| 95 | 新增: case "name": | |
| 96 | 新增: fmt.Println(environment.Name()) | |
| 97 | 新增: return true, nil | |
| 98 | 新增: case "setup": | |
| 99 | 新增: return true, environment.Prepare(ctx, os.Stdout) | |
| 100 | 新增: } | |
| 101 | 新增: if err := cfg.RequireManagedProxy(profile); err != nil { | |
| 102 | 新增: return true, err | |
| 103 | 新增: } | |
| 104 | 新增: if err := cfg.CheckRunning(filepath.Join(profile, "state")); err != nil { | |
| 105 | 新增: return true, err | |
| 106 | 新增: } | |
| 107 | 新增: if err := os.MkdirAll(cage.EnvironmentDir(profile), 0700); err != nil { | |
| 108 | 新增: return true, err | |
| 109 | 新增: } | |
| 110 | 新增: if err := environment.Prepare(ctx, os.Stdout); err != nil { | |
| 111 | 新增: return true, err | |
| 112 | 新增: } | |
| 113 | 新增: state, err := environment.State(ctx) | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: return true, err | |
| 116 | 新增: } | |
| 117 | 新增: needsServices := !state.Ready || args[0] == "up" || args[0] == "login" | |
| 118 | 新增: if err := environment.Start(ctx, configPath, os.Stdout); err != nil { | |
| 119 | 新增: return true, err | |
| 120 | 新增: } | |
| 121 | 新增: if needsServices { | |
| 122 | 新增: if err := workbench.RunMaintenanceScript(ctx, configPath, cfg.StartScript(), os.Stdout, os.Stderr); err != nil { | |
| 123 | 新增: return true, err | |
| 124 | 新增: } | |
| 125 | 新增: } | |
| 126 | 新增: switch args[0] { | |
| 127 | 新增: case "up": | |
| 128 | 新增: fmt.Println("Cage 容器服务已启动;工作台完成网络检查后才会放行外网。") | |
| 129 | 新增: return true, nil | |
| 130 | 新增: case "update-tools": | |
| 131 | 新增: return true, workbench.RunMaintenanceScript(ctx, configPath, cage.ToolsUpdateScript(), os.Stdout, os.Stderr) | |
| 132 | 新增: case "login": | |
| 133 | 新增: return true, workbench.RunEnvironmentCommand(ctx, configPath, []string{"claude", "auth", "login"}, os.Stdin, os.Stdout, os.Stderr, true) | |
| 134 | 新增: case "shell": | |
| 135 | 新增: return true, workbench.RunEnvironmentCommand(ctx, configPath, []string{"/bin/bash", "-l"}, os.Stdin, os.Stdout, os.Stderr, true) | |
| 136 | 新增: case "claude": | |
| 137 | 新增: return true, workbench.RunEnvironmentCommand(ctx, configPath, append([]string{"claude"}, args[1:]...), os.Stdin, os.Stdout, os.Stderr, true) | |
| 138 | 新增: case "run": | |
| 139 | 新增: if len(args) < 2 { | |
| 140 | 新增: return true, errors.New("cage run 需要指定命令") | |
| 141 | 新增: } | |
| 142 | 新增: return true, workbench.RunEnvironmentCommand(ctx, configPath, args[1:], os.Stdin, os.Stdout, os.Stderr, false) | |
| 143 | 新增: } | |
| 144 | 新增: return true, nil | |
| 145 | 新增:} | |
| @@ -12,9 +12,11 @@ import ( | ||
| 12 | 12 | "strings" |
| 13 | 13 | "time" |
| 14 | 14 | |
| 15 | 新增: agentvm "github.com/sylvinus/agent-vm" | |
| 15 | 16 | "github.com/sylvinus/agent-vm/internal/appupdate" |
| 16 | 17 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/cli" |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 18 | 20 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 19 | 21 | "github.com/sylvinus/agent-vm/internal/host" |
| 20 | 22 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| @@ -31,6 +33,8 @@ const help = `Claude Cage — local isolated Claude development | ||
| 31 | 33 | |
| 32 | 34 | cage desktop Open the unified Cage workbench (desktop launcher) |
| 33 | 35 | cage serve Run its private localhost control service |
| 36 | 新增:cage server-entry --json Issue a private SSH remote connection entry | |
| 37 | 新增:cage container-configure --json Configure a Linux container from JSON stdin | |
| 34 | 38 | cage init Create a private profile; add and select nodes in Cage settings |
| 35 | 39 | cage check Verify proxy transport (no VM required) |
| 36 | 40 | cage proxy-start Start Cage's bundled proxy core with the applied node |
| @@ -95,6 +99,99 @@ func run() int { | ||
| 95 | 99 | } |
| 96 | 100 | store := diagnostics.New(filepath.Dir(path)) |
| 97 | 101 | diagnostics.SetDefault(store) |
| 102 | 新增: if args[0] == "container-runtime" { | |
| 103 | 新增: if len(args) != 2 { | |
| 104 | 新增: return fail(fmt.Errorf("container-runtime prepare|start|stop|inspect")) | |
| 105 | 新增: } | |
| 106 | 新增: environment, err := containerenv.Load(filepath.Dir(path)) | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: return fail(err) | |
| 109 | 新增: } | |
| 110 | 新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 111 | 新增: defer cancel() | |
| 112 | 新增: switch args[1] { | |
| 113 | 新增: case "prepare": | |
| 114 | 新增: err = environment.Prepare(ctx, os.Stdout) | |
| 115 | 新增: case "start": | |
| 116 | 新增: err = environment.Start(ctx, path, os.Stdout) | |
| 117 | 新增: case "stop": | |
| 118 | 新增: err = environment.Stop(ctx) | |
| 119 | 新增: case "inspect": | |
| 120 | 新增: inspection, inspectErr := environment.Inspect(ctx) | |
| 121 | 新增: err = inspectErr | |
| 122 | 新增: if err == nil { | |
| 123 | 新增: err = json.NewEncoder(os.Stdout).Encode(inspection) | |
| 124 | 新增: } | |
| 125 | 新增: default: | |
| 126 | 新增: err = fmt.Errorf("container-runtime prepare|start|stop|inspect") | |
| 127 | 新增: } | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: return fail(err) | |
| 130 | 新增: } | |
| 131 | 新增: return 0 | |
| 132 | 新增: } | |
| 133 | 新增: if args[0] == "container-configure" { | |
| 134 | 新增: if len(args) != 2 || args[1] != "--json" { | |
| 135 | 新增: return fail(fmt.Errorf("container-configure --json < configuration.json")) | |
| 136 | 新增: } | |
| 137 | 新增: if err := configureContainer(path); err != nil { | |
| 138 | 新增: return fail(err) | |
| 139 | 新增: } | |
| 140 | 新增: return 0 | |
| 141 | 新增: } | |
| 142 | 新增: if args[0] == "container-install-script" { | |
| 143 | 新增: if len(args) != 2 { | |
| 144 | 新增: return fail(fmt.Errorf("container-install-script tools|services")) | |
| 145 | 新增: } | |
| 146 | 新增: script, err := containerInstallScript(args[1]) | |
| 147 | 新增: if err != nil { | |
| 148 | 新增: return fail(err) | |
| 149 | 新增: } | |
| 150 | 新增: _, err = io.WriteString(os.Stdout, script) | |
| 151 | 新增: if err != nil { | |
| 152 | 新增: return 1 | |
| 153 | 新增: } | |
| 154 | 新增: return 0 | |
| 155 | 新增: } | |
| 156 | 新增: if args[0] == "container-network" { | |
| 157 | 新增: if len(args) != 1 { | |
| 158 | 新增: return 2 | |
| 159 | 新增: } | |
| 160 | 新增: environment, err := containerenv.Load(filepath.Dir(path)) | |
| 161 | 新增: if err != nil { | |
| 162 | 新增: return fail(err) | |
| 163 | 新增: } | |
| 164 | 新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 165 | 新增: defer cancel() | |
| 166 | 新增: if err := environment.ServeNetwork(ctx, path); err != nil { | |
| 167 | 新增: return fail(err) | |
| 168 | 新增: } | |
| 169 | 新增: return 0 | |
| 170 | 新增: } | |
| 171 | 新增: if args[0] == "container-tap" { | |
| 172 | 新增: if len(args) != 1 { | |
| 173 | 新增: return 2 | |
| 174 | 新增: } | |
| 175 | 新增: ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 176 | 新增: defer cancel() | |
| 177 | 新增: if err := containerenv.RunTAP(ctx, os.Stdin, os.Stdout); err != nil { | |
| 178 | 新增: return fail(err) | |
| 179 | 新增: } | |
| 180 | 新增: return 0 | |
| 181 | 新增: } | |
| 182 | 新增: if args[0] == "server-entry" { | |
| 183 | 新增: if len(args) != 2 || args[1] != "--json" { | |
| 184 | 新增: return fail(fmt.Errorf("server-entry --json")) | |
| 185 | 新增: } | |
| 186 | 新增: entry, err := workbench.ServerEntry(path) | |
| 187 | 新增: if err != nil { | |
| 188 | 新增: return fail(err) | |
| 189 | 新增: } | |
| 190 | 新增: if err := json.NewEncoder(os.Stdout).Encode(entry); err != nil { | |
| 191 | 新增: return 1 | |
| 192 | 新增: } | |
| 193 | 新增: return 0 | |
| 194 | 新增: } | |
| 98 | 195 | if args[0] == "diagnostic-event" { |
| 99 | 196 | var event struct { |
| 100 | 197 | Source string `json:"source"` |
| @@ -112,10 +209,15 @@ func run() int { | ||
| 112 | 209 | return 0 |
| 113 | 210 | } |
| 114 | 211 | if args[0] == "diagnostics" { |
| 212 | 新增: connection := "" | |
| 213 | 新增: if len(args) == 5 && args[1] == "--json" && args[2] == "--connection" { | |
| 214 | 新增: connection = args[3] | |
| 215 | 新增: args = []string{args[0], args[1], args[4]} | |
| 216 | 新增: } | |
| 115 | 217 | if len(args) != 3 || args[1] != "--json" { |
| 116 | 218 | return fail(fmt.Errorf("diagnostics --json /absolute/path.zip")) |
| 117 | 219 | } |
| 118 | 删除: if err := workbench.ExportDiagnostics(path, args[2]); err != nil { | |
| 220 | 新增: if err := workbench.ExportDiagnosticsForConnection(workbench.DesktopHelperConfig(path, connection), connection, args[2]); err != nil { | |
| 119 | 221 | diagnostics.Log("error", "command", err.Error()) |
| 120 | 222 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| 121 | 223 | return 1 |
| @@ -132,11 +234,19 @@ func run() int { | ||
| 132 | 234 | if args[0] == "app-update" { |
| 133 | 235 | return appupdate.Run(path, args[1:], os.Stdout) |
| 134 | 236 | } |
| 237 | 新增: connectionID := "" | |
| 238 | 新增: if (args[0] == "upload-files" || args[0] == "browser-file") && len(args) >= 3 && args[2] == "--connection" { | |
| 239 | 新增: if len(args) < 4 || args[3] == "" { | |
| 240 | 新增: return fail(fmt.Errorf("missing file connection identity")) | |
| 241 | 新增: } | |
| 242 | 新增: connectionID = args[3] | |
| 243 | 新增: args = append(append([]string{}, args[:2]...), args[4:]...) | |
| 244 | 新增: } | |
| 135 | 245 | if args[0] == "upload-files" { |
| 136 | 246 | if len(args) < 5 || args[1] != "--json" { |
| 137 | 247 | return fail(fmt.Errorf("upload-files --json browser|desktop|terminal ID PATH...")) |
| 138 | 248 | } |
| 139 | 删除: result, err := workbench.UploadHostFiles(path, args[2], args[3], args[4:]) | |
| 249 | 新增: result, err := workbench.UploadHostFilesForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3], args[4:]) | |
| 140 | 250 | if err != nil { |
| 141 | 251 | diagnostics.Log("error", "command", err.Error()) |
| 142 | 252 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| @@ -153,7 +263,7 @@ func run() int { | ||
| 153 | 263 | if len(args) == 5 { |
| 154 | 264 | destination = args[4] |
| 155 | 265 | } |
| 156 | 删除: result, err := workbench.BrowserFile(path, args[2], args[3], destination) | |
| 266 | 新增: result, err := workbench.BrowserFileForConnection(workbench.DesktopHelperConfig(path, connectionID), connectionID, args[2], args[3], destination) | |
| 157 | 267 | if err != nil { |
| 158 | 268 | diagnostics.Log("error", "command", err.Error()) |
| 159 | 269 | _ = json.NewEncoder(os.Stdout).Encode(map[string]string{"status": "error", "message": err.Error()}) |
| @@ -162,6 +272,12 @@ func run() int { | ||
| 162 | 272 | _ = json.NewEncoder(os.Stdout).Encode(result) |
| 163 | 273 | return 0 |
| 164 | 274 | } |
| 275 | 新增: if args[0] == "serve-desktop" { | |
| 276 | 新增: if err := workbench.ServeDesktop(path); err != nil { | |
| 277 | 新增: return fail(err) | |
| 278 | 新增: } | |
| 279 | 新增: return 0 | |
| 280 | 新增: } | |
| 165 | 281 | if args[0] == "serve" { |
| 166 | 282 | if err := workbench.Serve(path); err != nil { |
| 167 | 283 | return fail(err) |
| @@ -183,7 +299,7 @@ func run() int { | ||
| 183 | 299 | return fail(fmt.Errorf("unknown desktop option: %s", argument)) |
| 184 | 300 | } |
| 185 | 301 | } |
| 186 | 删除: entry, err := workbench.Desktop(path, options) | |
| 302 | 新增: entry, err := workbench.DesktopEntry(path, options) | |
| 187 | 303 | if err != nil { |
| 188 | 304 | if returnJSON { |
| 189 | 305 | diagnostics.Log("error", "command", err.Error()) |
| @@ -218,7 +334,7 @@ func run() int { | ||
| 218 | 334 | return fail(fmt.Errorf("unknown prepare-update option: %s", argument)) |
| 219 | 335 | } |
| 220 | 336 | } |
| 221 | 删除: result, err := workbench.PrepareUpdate(path, stop) | |
| 337 | 新增: result, err := workbench.PrepareDesktopUpdate(path, stop) | |
| 222 | 338 | if err != nil { |
| 223 | 339 | if returnJSON { |
| 224 | 340 | diagnostics.Log("error", "command", err.Error()) |
| @@ -259,7 +375,28 @@ func run() int { | ||
| 259 | 375 | } |
| 260 | 376 | |
| 261 | 377 | os.Setenv(cage.ConfigEnv, path) |
| 262 | 删除: state := filepath.Join(filepath.Dir(path), "state") | |
| 378 | 新增: profile := filepath.Dir(path) | |
| 379 | 新增: state := filepath.Join(profile, "state") | |
| 380 | 新增: os.Unsetenv("CAGE_LIMA_CACHE_DIR") | |
| 381 | 新增: os.Unsetenv("CAGE_LOGICAL_LIMA_HOME") | |
| 382 | 新增: if !containerenv.Configured(profile) { | |
| 383 | 新增: lease, location, err := cage.AcquireStorageUse(profile) | |
| 384 | 新增: if err != nil { | |
| 385 | 新增: return fail(err) | |
| 386 | 新增: } | |
| 387 | 新增: defer lease.Close() | |
| 388 | 新增: if location.Custom { | |
| 389 | 新增: // Resolve the profile prefix once, as Lima did before migration. | |
| 390 | 新增: // Keep state itself logical so its original disk and socket paths survive. | |
| 391 | 新增: realProfile, err := filepath.EvalSymlinks(profile) | |
| 392 | 新增: if err != nil { | |
| 393 | 新增: return fail(err) | |
| 394 | 新增: } | |
| 395 | 新增: state = filepath.Join(realProfile, "state") | |
| 396 | 新增: os.Setenv("CAGE_LIMA_CACHE_DIR", filepath.Join(location.Directory, "cache", "lima")) | |
| 397 | 新增: os.Setenv("CAGE_LOGICAL_LIMA_HOME", filepath.Join(state, "lima")) | |
| 398 | 新增: } | |
| 399 | 新增: } | |
| 263 | 400 | os.Setenv("AGENT_VM_STATE_DIR", state) |
| 264 | 401 | os.Setenv("AGENT_VM_LIMA_HOME", filepath.Join(state, "lima")) |
| 265 | 402 | // Do not inherit host proxy settings or credentials into VM operations. |
| @@ -275,6 +412,12 @@ func run() int { | ||
| 275 | 412 | } |
| 276 | 413 | return 0 |
| 277 | 414 | } |
| 415 | 新增: if handled, err := containerOperation(path, args, cfg); handled { | |
| 416 | 新增: if err != nil { | |
| 417 | 新增: return fail(err) | |
| 418 | 新增: } | |
| 419 | 新增: return 0 | |
| 420 | 新增: } | |
| 278 | 421 | // Every Cage operation targets this profile's one persistent environment. |
| 279 | 422 | switch args[0] { |
| 280 | 423 | case "up", "login", "shell", "run", "claude", "stop", "doctor", "access", "name": |
| @@ -370,6 +513,26 @@ func run() int { | ||
| 370 | 513 | return cli.Main(args, cli.Stdio()) |
| 371 | 514 | } |
| 372 | 515 | |
| 516 | 新增:func containerInstallScript(kind string) (string, error) { | |
| 517 | 新增: switch kind { | |
| 518 | 新增: case "services": | |
| 519 | 新增: return cage.GuestSetup, nil | |
| 520 | 新增: case "tools": | |
| 521 | 新增: script := "export CLAUDE_CAGE=1\n" + cage.ToolInstallPrelude() | |
| 522 | 新增: enabled := map[string]bool{"NODE": true, "PYTHON": true, "CHROMIUM": true, "CLAUDE": true, "CODE_SERVER": true} | |
| 523 | 新增: for _, name := range []string{"PYTHON", "NODE", "RUBY", "RUST", "GOLANG", "DOCKER", "CHROMIUM", "GH", "CLAUDE", "OPENCODE", "CODEX", "VIBE", "PI", "CODE_SERVER", "CODE_CLAUDE", "CODE_OPENCODE", "CODE_CODEX", "CODE_VIBE", "MCP_CHROME", "MCP_PLAYWRIGHT"} { | |
| 524 | 新增: value := "0" | |
| 525 | 新增: if enabled[name] { | |
| 526 | 新增: value = "1" | |
| 527 | 新增: } | |
| 528 | 新增: script += "export AGENT_VM_INSTALL_" + name + "=" + value + "\n" | |
| 529 | 新增: } | |
| 530 | 新增: return script + agentvm.SetupScript, nil | |
| 531 | 新增: default: | |
| 532 | 新增: return "", fmt.Errorf("container-install-script tools|services") | |
| 533 | 新增: } | |
| 534 | 新增:} | |
| 535 | 新增: | |
| 373 | 536 | // Service assets exceed Windows' command-line limit. Give only this internal |
| 374 | 537 | // invocation a script stream; interactive login and ordinary run keep stdin. |
| 375 | 538 | func runGuestServiceStart(script string, stdio cli.IO, invoke func([]string, cli.IO) int) int { |
| @@ -45,7 +45,7 @@ func proxyCommand(command, profile string, cfg cage.Config) error { | ||
| 45 | 45 | if err = managedproxy.Write(path, data); err != nil { |
| 46 | 46 | return err |
| 47 | 47 | } |
| 48 | 删除: files, _ := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-gate.json")) | |
| 48 | 新增: files := managedGateFiles(profile) | |
| 49 | 49 | for _, file := range files { |
| 50 | 50 | if client, e := cage.OpenGateClient(filepath.Dir(file)); e == nil { |
| 51 | 51 | if _, e = client.Status(context.Background()); e == nil { |
| @@ -59,7 +59,7 @@ func proxyCommand(command, profile string, cfg cage.Config) error { | ||
| 59 | 59 | } |
| 60 | 60 | |
| 61 | 61 | func closeManagedGates(profile string) error { |
| 62 | 删除: files, _ := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-gate.json")) | |
| 62 | 新增: files := managedGateFiles(profile) | |
| 63 | 63 | for _, file := range files { |
| 64 | 64 | if client, e := cage.OpenGateClient(filepath.Dir(file)); e == nil { |
| 65 | 65 | if _, e = client.Status(context.Background()); e == nil { |
| @@ -71,3 +71,9 @@ func closeManagedGates(profile string) error { | ||
| 71 | 71 | } |
| 72 | 72 | return nil |
| 73 | 73 | } |
| 74 | 新增: | |
| 75 | 新增:func managedGateFiles(profile string) []string { | |
| 76 | 新增: files, _ := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-gate.json")) | |
| 77 | 新增: containers, _ := filepath.Glob(filepath.Join(profile, "state", "container", "*", "cage-gate.json")) | |
| 78 | 新增: return append(files, containers...) | |
| 79 | 新增:} | |
| @@ -0,0 +1,43 @@ | ||
| 1 | 新增:# The default base is the official Debian 13 multi-platform manifest. | |
| 2 | 新增:# A build may select another verified Debian 13 base with BASE_IMAGE. | |
| 3 | 新增:ARG BASE_IMAGE=debian:13-slim@sha256:a72b4433de1cf7d6bae0c4cee74d0547f58601a643b3375f070c51600d63b6b2 | |
| 4 | 新增:FROM ${BASE_IMAGE} | |
| 5 | 新增: | |
| 6 | 新增:ENV container=docker | |
| 7 | 新增:COPY restore-apt-sources.sh /usr/local/lib/cage-image-restore-sources | |
| 8 | 新增:ARG DEBIAN_MIRROR=http://deb.debian.org | |
| 9 | 新增:RUN sed -i "s#http://deb.debian.org#${DEBIAN_MIRROR}#g" /etc/apt/sources.list.d/debian.sources \ | |
| 10 | 新增: && printf '#!/bin/sh\nexit 101\n' > /usr/sbin/policy-rc.d \ | |
| 11 | 新增: && chmod 0755 /usr/sbin/policy-rc.d \ | |
| 12 | 新增: && apt-get update \ | |
| 13 | 新增: && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \ | |
| 14 | 新增: systemd systemd-sysv dbus dbus-user-session libpam-systemd sudo \ | |
| 15 | 新增: openssh-server openssh-client iproute2 fuse3 sshfs socat \ | |
| 16 | 新增: ca-certificates curl git jq python3 python3-apt zsh procps \ | |
| 17 | 新增: && rm /usr/sbin/policy-rc.d \ | |
| 18 | 新增: && rm -rf /var/lib/apt/lists/* \ | |
| 19 | 新增: && useradd --create-home --uid 1000 --user-group --shell /bin/bash cage \ | |
| 20 | 新增: && printf 'cage ALL=(ALL) NOPASSWD: ALL\n' > /etc/sudoers.d/cage \ | |
| 21 | 新增: && chmod 0440 /etc/sudoers.d/cage \ | |
| 22 | 新增: && printf 'user_allow_other\n' > /etc/fuse.conf \ | |
| 23 | 新增: && install -d -m 0700 -o cage -g cage /home/cage/.ssh \ | |
| 24 | 新增: && install -d -m 0755 /etc/systemd/system.conf.d \ | |
| 25 | 新增: && printf '[Manager]\nDefaultTasksMax=infinity\n' > /etc/systemd/system.conf.d/90-cage-container.conf \ | |
| 26 | 新增: && install -d -m 0755 /etc/ssh/sshd_config.d /etc/systemd/system/ssh.service.d \ | |
| 27 | 新增: && printf '%s\n' 'PermitRootLogin no' 'PasswordAuthentication no' \ | |
| 28 | 新增: 'KbdInteractiveAuthentication no' 'AuthenticationMethods publickey' \ | |
| 29 | 新增: 'AuthorizedKeysFile /etc/ssh/cage_authorized_keys' 'AllowTcpForwarding yes' \ | |
| 30 | 新增: 'GatewayPorts no' 'X11Forwarding no' 'AllowUsers cage' \ | |
| 31 | 新增: > /etc/ssh/sshd_config.d/10-cage.conf \ | |
| 32 | 新增: && printf '[Service]\nExecStartPre=\nExecStartPre=/usr/bin/ssh-keygen -A\nExecStartPre=/usr/sbin/sshd -t\n' \ | |
| 33 | 新增: > /etc/systemd/system/ssh.service.d/10-cage-hostkeys.conf \ | |
| 34 | 新增: && systemctl enable ssh.service \ | |
| 35 | 新增: && rm -f /etc/ssh/ssh_host_* /etc/machine-id /var/lib/dbus/machine-id \ | |
| 36 | 新增: && touch /etc/machine-id \ | |
| 37 | 新增: && ln -s /etc/machine-id /var/lib/dbus/machine-id \ | |
| 38 | 新增: && sh /usr/local/lib/cage-image-restore-sources | |
| 39 | 新增: | |
| 40 | 新增:# PID 1 owns its services. Container stop must let systemd stop them in order. | |
| 41 | 新增:# Persistent files remain in the same container until an explicit migration. | |
| 42 | 新增:STOPSIGNAL SIGRTMIN+3 | |
| 43 | 新增:CMD ["/sbin/init"] | |
| @@ -0,0 +1,183 @@ | ||
| 1 | 新增:# 云端运行环境的构建与运维 | |
| 2 | 新增: | |
| 3 | 新增:本目录面向部署 Cage 的维护者。云端运行控制服务和持久容器,本地客户端通过 SSH 使用工作台。容器文件系统、浏览器资料、开发工具及网络出口留在服务器;控制端口保持回环监听。运行边界见[云端部署设计](../../docs/design/cloud-deployment.md)。 | |
| 4 | 新增: | |
| 5 | 新增:这里提供开发构建材料,尚未发布云端镜像或安装包。`Dockerfile.guest` 构建 Debian 13 基础层,完整工具与 Cage 服务继续使用仓库中的共同安装脚本。基础层本身不能当作完整工作环境交付。本轮镜像与实机验证使用 Linux amd64;终端、浏览器、编辑器及 Claude Desktop 的 Chat/Code 安装路径可在无 KVM 容器内运行,依赖嵌套虚拟机的 Cowork 不在支持承诺内。Desktop 已验证安装、启动及欢迎页,未使用真实第三方账户验收聊天。 | |
| 6 | 新增: | |
| 7 | 新增:## 从 Cage 侧栏部署 | |
| 8 | 新增: | |
| 9 | 新增:用普通 SSH 用户连接下文列出的 Linux amd64 主机。首次部署使用空的配置目录,用户核验指纹并点击「部署并连接」后,桌面端传输与客户端同版本的 Linux 服务端、代理核心和安装脚本。服务器下载并校验容器引擎和固定摘要的 Debian 基础镜像,执行与本机环境共用的工具安装脚本。服务器在配置目录的 `cloud-host/` 下保存程序和私有引擎,在 systemd 用户目录注册以配置路径区分的服务。工作台就绪后即可创建或解锁服务器上的 Cage 账户。再次连接会沿用该实例,服务停止时会自动启动。部署中断后可用同一安装包重试。 | |
| 10 | 新增: | |
| 11 | 新增:桌面构建自动生成现场安装所需的材料。制作可选的私有离线包时,先准备 Linux amd64 的 Cage 后端、下文构建的完整镜像目录和两份校验过的 Docker 存档。设置 `CAGE_SERVER_BINARY`、`CAGE_GUEST_BUILD`、`CAGE_DOCKER_DOWNLOADS` 后运行 `bash deploy/cloud/pack-kit.sh`。用 `CAGE_CLOUD_KIT` 指定归档绝对路径。桌面程序按需从磁盘流式上传。 | |
| 12 | 新增: | |
| 13 | 新增:## 服务器前提 | |
| 14 | 新增: | |
| 15 | 新增:当前构建基线为 Linux x86_64、cgroup v2、systemd 用户服务及 rootless Docker 29.9.1。服务器无需 KVM。运行用户须有可用的多 UID/GID 用户命名空间、至少 65,536 个 subordinate UID/GID,以及可访问的 `/dev/fuse`、`/dev/net/tun`。`newuidmap`、`newgidmap` 可通过发行版的 setuid 或文件 capability 实现映射。 | |
| 16 | 新增: | |
| 17 | 新增:宿主需提供 OpenSSH、curl、tar、sha256sum、iproute2 与 iptables;Cage 服务端不依赖 GTK 或 WebKit。实际运行还会检查用户 cgroup 委派和父层资源上限。缺少前提时应修复服务器配置,不能通过 `--privileged`、宿主网络、宿主 PID、Docker socket 挂载或整个宿主 cgroup 的可写绑定启动工作环境。 | |
| 18 | 新增: | |
| 19 | 新增:每个用户的数据根默认为 `~/.claude-cage`。容器引擎的数据固定在 `~/.claude-cage/container-engine/data`,与版本号和可执行文件目录分开。显式使用其他 `CLAUDE_CAGE_CONFIG` 时,须同步修改两个用户服务中的绝对配置路径和引擎数据根;后续升级继续使用同一组路径。 | |
| 20 | 新增: | |
| 21 | 新增:## 准备独立的 rootless 引擎 | |
| 22 | 新增: | |
| 23 | 新增:[runtime-artifacts.json](runtime-artifacts.json) 固定官方静态发行物及其 SHA-256。Docker 主程序与 rootless extras 必须使用同一版本。以下是首次安装流程,以普通用户执行,安装在自己的配置目录,不修改已运行的系统 Docker。已有 Cage 引擎先按文末的停止与更新流程处理,不能在运行期间直接解包覆盖程序。 | |
| 24 | 新增: | |
| 25 | 新增:```sh | |
| 26 | 新增:cage_engine_root="$HOME/.claude-cage/container-engine" | |
| 27 | 新增:install -d -m 700 "$cage_engine_root/tools" "$cage_engine_root/downloads" \ | |
| 28 | 新增: "$cage_engine_root/data" "$cage_engine_root/client" | |
| 29 | 新增:curl --fail --location --proto '=https' --tlsv1.2 \ | |
| 30 | 新增: https://download.docker.com/linux/static/stable/x86_64/docker-29.9.1.tgz \ | |
| 31 | 新增: -o "$cage_engine_root/downloads/docker-29.9.1.tgz" | |
| 32 | 新增:curl --fail --location --proto '=https' --tlsv1.2 \ | |
| 33 | 新增: https://download.docker.com/linux/static/stable/x86_64/docker-rootless-extras-29.9.1.tgz \ | |
| 34 | 新增: -o "$cage_engine_root/downloads/docker-rootless-extras-29.9.1.tgz" | |
| 35 | 新增:printf '%s %s\n' \ | |
| 36 | 新增: c158ecc55adb3afb01bbd3539ed3b997d20c26dbdc418080506cc1bf5243ff57 \ | |
| 37 | 新增: "$cage_engine_root/downloads/docker-29.9.1.tgz" \ | |
| 38 | 新增: c87668896a3fced2e715324e9fb6a0634aba3e5d8408a471f6bc23dc476662af \ | |
| 39 | 新增: "$cage_engine_root/downloads/docker-rootless-extras-29.9.1.tgz" | sha256sum -c - | |
| 40 | 新增:tar -xzf "$cage_engine_root/downloads/docker-29.9.1.tgz" --strip-components=1 -C "$cage_engine_root/tools" | |
| 41 | 新增:tar -xzf "$cage_engine_root/downloads/docker-rootless-extras-29.9.1.tgz" --strip-components=1 -C "$cage_engine_root/tools" | |
| 42 | 新增:if [ ! -e "$cage_engine_root/daemon.json" ]; then | |
| 43 | 新增: (umask 077; printf '{}\n' > "$cage_engine_root/daemon.json") | |
| 44 | 新增:fi | |
| 45 | 新增:install -d -m 700 "$HOME/.config/systemd/user" | |
| 46 | 新增:if [ ! -e "$HOME/.config/systemd/user/cage-container-engine.service" ]; then | |
| 47 | 新增: install -m 644 deploy/cloud/cage-container-engine.service "$HOME/.config/systemd/user/" | |
| 48 | 新增:else | |
| 49 | 新增: printf '保留已有 cage-container-engine.service,请核对其中的路径。\n' | |
| 50 | 新增:fi | |
| 51 | 新增:systemctl --user daemon-reload | |
| 52 | 新增:systemctl --user enable --now cage-container-engine.service | |
| 53 | 新增:``` | |
| 54 | 新增: | |
| 55 | 新增:连接该引擎时显式指定私有 socket 和独立的客户端配置,避免操作系统 Docker: | |
| 56 | 新增: | |
| 57 | 新增:```sh | |
| 58 | 新增:export DOCKER_HOST="unix:///run/user/$(id -u)/cage-container-engine/docker.sock" | |
| 59 | 新增:export DOCKER_CONFIG="$HOME/.claude-cage/container-engine/client" | |
| 60 | 新增:cage_engine="$HOME/.claude-cage/container-engine/tools/docker" | |
| 61 | 新增:"$cage_engine" info --format '{{json .SecurityOptions}} {{.CgroupDriver}} {{.CgroupVersion}}' | |
| 62 | 新增:``` | |
| 63 | 新增: | |
| 64 | 新增:输出必须包含 `name=rootless`,cgroup 驱动为 `systemd`、版本为 `2`。用户未启用 linger 时,最后一个登录会话结束后用户服务可能停止。无人登录时常驻需要服务器管理员为该用户启用 linger;测试环境不自动修改此设置。[Docker rootless 前提与用户服务说明](https://docs.docker.com/engine/security/rootless/) | |
| 65 | 新增: | |
| 66 | 新增:## 构建完整客体镜像 | |
| 67 | 新增: | |
| 68 | 新增:先从同一份源码构建 Linux Cage 后端:`make cage GOOS=linux GOARCH=amd64 CGO_ENABLED=0`。构建会生成工作台资产及 `_output/bin/cage`;不运行发布或版本修改流程。 | |
| 69 | 新增: | |
| 70 | 新增:通过 `Dockerfile.guest` 构建基础层,再创建独立的镜像构建容器。构建容器不挂载项目、个人主目录、代理配置或账户;安装下载使用单独的构建网络。默认 Debian 镜像已经固定 digest,APT 继续验证发行版签名。若部署网络需要镜像站,只调整构建阶段的 Debian 软件源,保留签名验证;基础层和完整镜像提交前均恢复 `deb.debian.org` 官方源,以符合运行环境的维护下载来源限制。 | |
| 71 | 新增: | |
| 72 | 新增:使用[完整镜像构建脚本](build-guest.sh)建立本次构建独占的父 slice、网络和容器。脚本检查实际 rootless 引擎和父层上限,再执行共同安装脚本;命名带唯一后缀,避免覆盖已有环境。 | |
| 73 | 新增: | |
| 74 | 新增:```sh | |
| 75 | 新增:CAGE_SERVER_BINARY="$PWD/_output/bin/cage" \ | |
| 76 | 新增:CAGE_CONTAINER_ENGINE="$cage_engine" \ | |
| 77 | 新增: bash deploy/cloud/build-guest.sh | |
| 78 | 新增:``` | |
| 79 | 新增: | |
| 80 | 新增:完整镜像的安装顺序与本地 Cage 一致: | |
| 81 | 新增: | |
| 82 | 新增:```sh | |
| 83 | 新增:# CAGE_BUILD_CONTAINER 是本次新建的镜像构建容器,须由操作者明确指定。 | |
| 84 | 新增:_output/bin/cage container-install-script tools | | |
| 85 | 新增: "$cage_engine" exec --interactive --user cage --workdir /home/cage "$CAGE_BUILD_CONTAINER" bash -l | |
| 86 | 新增:_output/bin/cage container-install-script services | | |
| 87 | 新增: "$cage_engine" exec --interactive --user cage --workdir /home/cage "$CAGE_BUILD_CONTAINER" zsh -l | |
| 88 | 新增:``` | |
| 89 | 新增: | |
| 90 | 新增:第一步仅选择 Python、Node、Chromium、Claude Code 和 code-server,复用 `ToolInstallPrelude` 与 `agent-vm.setup.sh`;第二步复用 `GuestSetup`。服务安装需要容器内 systemd 正在运行,不能把第二步直接塞进普通 `Dockerfile RUN`。容器模式跳过 zram;Chromium 沙箱保持开启。基础层将容器内 systemd 的 `DefaultTasksMax` 设为 `infinity`,单个服务不再受默认百分比派生的小限额约束。运行工作环境由宿主父 slice 实施 1024 个进程/线程的硬上限;独立镜像构建仍使用 2 CPU、4 GiB 内存、512 个进程/线程的预算。初始化浏览器资料的 `StartScript` 留到工作环境首次启动,不能在基础镜像内预建浏览器密码或控制凭据。 | |
| 91 | 新增: | |
| 92 | 新增:在 rootless Docker 中,systemd 的启动入口为: | |
| 93 | 新增: | |
| 94 | 新增:```sh | |
| 95 | 新增:umount /sys/fs/cgroup | |
| 96 | 新增:mount -t cgroup2 none /sys/fs/cgroup | |
| 97 | 新增:exec /sbin/init | |
| 98 | 新增:``` | |
| 99 | 新增: | |
| 100 | 新增:这些命令只能在已经配置为私有用户、PID、IPC、网络和 cgroup 命名空间的容器中执行。容器采用 `/run`、`/tmp` 临时文件系统,只额外提供 `/dev/fuse`、`/dev/net/tun` 以及用户命名空间内的 `SYS_ADMIN`、`NET_ADMIN`。工作环境由 Cage 创建,使用 `network=none` 和专门的宿主父 slice 限额;镜像构建容器的联网与生命周期由构建步骤单独管理。引擎将容器主机名固定为 `cage`,并添加 `cage:127.0.1.1` 别名,保证无默认网络时也能解析自身主机名。容器可管理自己的 cgroup 子层,CPU、内存和 PID 硬上限须放在它看不到的宿主父层。 | |
| 101 | 新增: | |
| 102 | 新增:提交完整镜像前,仅清理本次新建构建容器:停止 SSH 和 Cage 服务,移除生成的 SSH host keys、`cage_authorized_keys`、journal、APT 缓存和临时下载,将 `/etc/machine-id` 清空。确认其中没有账户文件、浏览器控制凭据、浏览器密码、Claude 登录态、代理凭据或用户项目,再停止并提交镜像,记录 SHA-256 image ID。不得对已有工作环境执行这一清理;已有容器的整个可写文件系统都属于持久数据。 | |
| 103 | 新增: | |
| 104 | 新增:脚本默认生成本地 `cage-guest:development` 镜像,并在 `_output/cloud-images/build.*` 保存 image ID、导出的 `cage-guest.tar`、`SHA256SUMS`、安装脚本和日志。成功后只回收当轮创建的构建容器与网络;失败时保留它们供检查。没有推送镜像、创建 Git 标签或发布版本的步骤。 | |
| 105 | 新增: | |
| 106 | 新增:离线准备了相同 Debian 基底时,可用 `CAGE_GUEST_BASE_IMAGE` 指定已经校验的本地 image ID;它必须固定为 SHA-256。需要其他 Debian 镜像站时,`CAGE_DEBIAN_MIRROR` 接受 HTTP(S) 源站地址,例如 `http://mirrors.aliyun.com`,APT 签名验证保持开启。[软件源恢复脚本](restore-apt-sources.sh)在提交镜像前校验并恢复 Debian 主仓库和安全仓库的官方 URI,保留发行版、组件与签名密钥配置,不改 NodeSource 等其他来源。 | |
| 107 | 新增: | |
| 108 | 新增:## 安装并连接控制服务 | |
| 109 | 新增: | |
| 110 | 新增:将同一次构建的 Cage 后端与校验过的 Linux Mihomo 放到 `~/.local/lib/cage/`,分别命名为 `cage`、`mihomo`。Mihomo 的固定下载来源和校验沿用 `scripts/fetch-linux-proxy-core.sh`。 | |
| 111 | 新增: | |
| 112 | 新增:下面的示例从 `build-guest.sh` 输出的 `Artifacts` 目录读取 `image-id`。如果在另一台机器构建,先把该目录中的 `image-id`、`cage-guest.tar`、`SHA256SUMS` 复制到服务器;示例会校验归档并加载到私有引擎。 | |
| 113 | 新增: | |
| 114 | 新增:默认使用 `~/.claude-cage/config.json`,已经显式设置的 `CLAUDE_CAGE_CONFIG` 会保留。`init` 只在配置不存在时执行,其文件创建也使用排他模式;已有配置不覆盖。`container-configure` 通过标准输入接收 JSON,已有容器配置仅接受完全相同的参数,换镜像或资源配置需要按迁移流程处理。已有 VM 数据的配置目录会被拒绝,不能用此流程覆盖本地环境。 | |
| 115 | 新增: | |
| 116 | 新增:```sh | |
| 117 | 新增:( | |
| 118 | 新增: set -eu | |
| 119 | 新增: printf '粘贴 build-guest.sh 输出的 Artifacts 绝对目录:' | |
| 120 | 新增: IFS= read -r cage_build_output | |
| 121 | 新增: case "$cage_build_output" in /*) ;; *) echo '需要绝对目录。' >&2; exit 1 ;; esac | |
| 122 | 新增: | |
| 123 | 新增: cage_binary="$HOME/.local/lib/cage/cage" | |
| 124 | 新增: cage_engine="$HOME/.claude-cage/container-engine/tools/docker" | |
| 125 | 新增: cage_socket="unix:///run/user/$(id -u)/cage-container-engine/docker.sock" | |
| 126 | 新增: export DOCKER_HOST="$cage_socket" | |
| 127 | 新增: export DOCKER_CONFIG="$HOME/.claude-cage/container-engine/client" | |
| 128 | 新增: unset DOCKER_CONTEXT | |
| 129 | 新增: export CLAUDE_CAGE_CONFIG="${CLAUDE_CAGE_CONFIG:-$HOME/.claude-cage/config.json}" | |
| 130 | 新增: case "$CLAUDE_CAGE_CONFIG" in /*) ;; *) echo '配置路径必须是绝对路径。' >&2; exit 1 ;; esac | |
| 131 | 新增: | |
| 132 | 新增: (cd "$cage_build_output" && sha256sum -c SHA256SUMS) | |
| 133 | 新增: cage_image_id=$(cat "$cage_build_output/image-id") | |
| 134 | 新增: printf '%s\n' "$cage_image_id" | grep -Eq '^sha256:[a-f0-9]{64}$' | |
| 135 | 新增: "$cage_engine" load --input "$cage_build_output/cage-guest.tar" | |
| 136 | 新增: "$cage_engine" image inspect "$cage_image_id" >/dev/null | |
| 137 | 新增: if [ ! -e "$CLAUDE_CAGE_CONFIG" ]; then | |
| 138 | 新增: "$cage_binary" init | |
| 139 | 新增: else | |
| 140 | 新增: printf '保留已有配置:%s\n' "$CLAUDE_CAGE_CONFIG" | |
| 141 | 新增: fi | |
| 142 | 新增: | |
| 143 | 新增: "$cage_binary" container-configure --json <<JSON | |
| 144 | 新增:{ | |
| 145 | 新增: "engine": "docker", | |
| 146 | 新增: "executable": "$cage_engine", | |
| 147 | 新增: "socket": "$cage_socket", | |
| 148 | 新增: "image": "$cage_image_id", | |
| 149 | 新增: "cpus": 2, | |
| 150 | 新增: "memory_bytes": 4294967296 | |
| 151 | 新增:} | |
| 152 | 新增:JSON | |
| 153 | 新增: "$cage_binary" setup | |
| 154 | 新增:) | |
| 155 | 新增:``` | |
| 156 | 新增: | |
| 157 | 新增:最后一步准备离线的持久容器,不放行业务网络。若使用了自定义配置或引擎目录,先把下列用户服务中的路径同步为同一组绝对路径,再启动控制服务。 | |
| 158 | 新增: | |
| 159 | 新增:```sh | |
| 160 | 新增:if [ ! -e "$HOME/.config/systemd/user/cage-server.service" ]; then | |
| 161 | 新增: install -m 644 deploy/cloud/cage-server.service "$HOME/.config/systemd/user/" | |
| 162 | 新增:else | |
| 163 | 新增: printf '保留已有 cage-server.service,请核对其中的配置路径。\n' | |
| 164 | 新增:fi | |
| 165 | 新增:systemctl --user daemon-reload | |
| 166 | 新增:systemctl --user enable --now cage-server.service | |
| 167 | 新增:``` | |
| 168 | 新增: | |
| 169 | 新增:打开同一个 Cage 应用,在「SSH」侧栏点击加号,保存服务器地址、SSH 用户和认证方式。选中主机后连接并核验服务器主机密钥。如果本机仍在运行,确认卡片会展示停止本机和保留本机的选项。工作台继续使用服务器自己的账户;远程项目选择的是服务器目录。无需将控制服务、VNC、编辑器或容器端口发布到公网。 | |
| 170 | 新增: | |
| 171 | 新增:## 停止、更新与恢复 | |
| 172 | 新增: | |
| 173 | 新增:关闭本地窗口或断开 SSH 连接保留远端环境。需要停止任务时,先在 Cage 中停止环境,再停止 `cage-server.service`;确认不再需要运行容器后才能停止 `cage-container-engine.service`。 | |
| 174 | 新增: | |
| 175 | 新增:更新前保存任务并停止环境,保留配置目录、引擎 `data` 目录和服务器项目。替换应用文件后使用相同配置路径恢复服务。镜像升级需要显式迁移已有完整文件系统;不能用删除容器、替换 data-root 或重新创建账户完成升级。禁止对保存工作环境的引擎执行 `docker system prune` 或批量 `docker rm`。 | |
| 176 | 新增: | |
| 177 | 新增:诊断优先检查用户服务状态、当前配置下的容器网络日志及实际 rootless/cgroup 状态。无登录常驻、宿主重启恢复和各客户端的原生交互分别验收,不能由单次容器启动结果代替。 | |
| 178 | 新增: | |
| 179 | 新增:## 实机验证范围 | |
| 180 | 新增: | |
| 181 | 新增:普通无 KVM VPS 上的 rootless Docker 已完成 systemd、FUSE/SSHFS、受控网络、资源父层、持久化与工作台真实操作验证。Podman 尚未实测,其他发行版和 ARM64 也不在本轮结论内。 | |
| 182 | 新增: | |
| 183 | 新增:构建脚本已检查 shell 语法,并实际运行到独立父 slice、网络、固定 Debian 基底构建、systemd 与共同工具安装入口;完整工具安装、身份清理、镜像检查和导出分别完成了真实验证。整段自动脚本未从头到尾重复执行完毕。测试用户未开启 linger,也未执行服务器重启,因此无人登录常驻与重启恢复仍需单独验收。 | |
| @@ -0,0 +1,150 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/../.." | |
| 4 | 新增: | |
| 5 | 新增:[[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { | |
| 6 | 新增: echo 'Build the guest image on x86_64 Linux.' >&2; exit 1; | |
| 7 | 新增:} | |
| 8 | 新增:cage_binary="${CAGE_SERVER_BINARY:-$PWD/_output/bin/cage}" | |
| 9 | 新增:cage_engine="${CAGE_CONTAINER_ENGINE:-$HOME/.claude-cage/container-engine/tools/docker}" | |
| 10 | 新增:cage_socket="${DOCKER_HOST:-unix:///run/user/$(id -u)/cage-container-engine/docker.sock}" | |
| 11 | 新增:cage_tag="${CAGE_GUEST_IMAGE_TAG:-cage-guest:development}" | |
| 12 | 新增:[[ "$cage_binary" == /* && -x "$cage_binary" && "$cage_engine" == /* && -x "$cage_engine" ]] || { | |
| 13 | 新增: echo 'CAGE_SERVER_BINARY and CAGE_CONTAINER_ENGINE must name executable absolute paths.' >&2; exit 1; | |
| 14 | 新增:} | |
| 15 | 新增:[[ "$cage_socket" == unix:///* && "$cage_socket" != *$'\n'* ]] || { | |
| 16 | 新增: echo 'Use a local rootless Docker Unix socket.' >&2; exit 1; | |
| 17 | 新增:} | |
| 18 | 新增:[[ "$cage_tag" =~ ^[a-z0-9][a-z0-9./:_-]*$ ]] || { echo 'Invalid local image tag.' >&2; exit 1; } | |
| 19 | 新增: | |
| 20 | 新增:cage_evidence=${CAGE_IMAGE_BUILD_DIR:-"$PWD/_output/cloud-images"} | |
| 21 | 新增:mkdir -p "$cage_evidence" | |
| 22 | 新增:cage_stage=$(mktemp -d "$cage_evidence/build.XXXXXX") | |
| 23 | 新增:chmod 0700 "$cage_stage" | |
| 24 | 新增:mkdir -m 700 "$cage_stage/client" | |
| 25 | 新增:engine() { | |
| 26 | 新增: env -u DOCKER_CONTEXT -u DOCKER_TLS_VERIFY -u DOCKER_CERT_PATH \ | |
| 27 | 新增: "$cage_engine" --host "$cage_socket" --config "$cage_stage/client" "$@" | |
| 28 | 新增:} | |
| 29 | 新增:[[ "$(engine info --format '{{json .SecurityOptions}}')" == *'"name=rootless"'* ]] || { | |
| 30 | 新增: echo 'The selected Docker daemon is not rootless.' >&2; exit 1; | |
| 31 | 新增:} | |
| 32 | 新增:[[ "$(engine info --format '{{.CgroupDriver}} {{.CgroupVersion}}')" == 'systemd 2' ]] || { | |
| 33 | 新增: echo 'Rootless Docker must use systemd and cgroup v2.' >&2; exit 1; | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:cage_build_id="$(date +%Y%m%d%H%M%S)$$" | |
| 37 | 新增:cage_slice="cageimage${cage_build_id}.slice" | |
| 38 | 新增:cage_anchor="cageimage${cage_build_id}.service" | |
| 39 | 新增:cage_network="cage-image-$cage_build_id" | |
| 40 | 新增:cage_builder="cage-image-$cage_build_id" | |
| 41 | 新增:cage_base="cage-base:build-$cage_build_id" | |
| 42 | 新增:cage_base_args=() | |
| 43 | 新增:if [[ -n "${CAGE_GUEST_BASE_IMAGE:-}" ]]; then | |
| 44 | 新增: [[ "$CAGE_GUEST_BASE_IMAGE" =~ ^(sha256:|[a-zA-Z0-9][a-zA-Z0-9./:_-]*@sha256:)[a-f0-9]{64}$ ]] || { | |
| 45 | 新增: echo 'CAGE_GUEST_BASE_IMAGE must use a fixed image ID or registry digest.' >&2; exit 1; | |
| 46 | 新增: } | |
| 47 | 新增: cage_base_args+=(--build-arg "BASE_IMAGE=$CAGE_GUEST_BASE_IMAGE") | |
| 48 | 新增:fi | |
| 49 | 新增:if [[ -n "${CAGE_DEBIAN_MIRROR:-}" ]]; then | |
| 50 | 新增: [[ "$CAGE_DEBIAN_MIRROR" =~ ^https?://[a-zA-Z0-9.-]+(:[0-9]+)?$ ]] || { | |
| 51 | 新增: echo 'CAGE_DEBIAN_MIRROR must be an HTTP(S) mirror origin.' >&2; exit 1; | |
| 52 | 新增: } | |
| 53 | 新增: cage_base_args+=(--build-arg "DEBIAN_MIRROR=$CAGE_DEBIAN_MIRROR") | |
| 54 | 新增:fi | |
| 55 | 新增:cage_container_id='' | |
| 56 | 新增:cage_network_id='' | |
| 57 | 新增:cage_completed=false | |
| 58 | 新增:finish() { | |
| 59 | 新增: local result=$? | |
| 60 | 新增: if [[ "$cage_completed" == true || -n "${CAGE_IMAGE_ID_OUTPUT:-}" ]]; then | |
| 61 | 新增: # These IDs were created by this invocation and contain build data only. | |
| 62 | 新增: [[ -z "$cage_container_id" ]] || engine rm -f "$cage_container_id" >/dev/null || true | |
| 63 | 新增: [[ -z "$cage_network_id" ]] || engine network rm "$cage_network_id" >/dev/null || true | |
| 64 | 新增: systemctl --user stop "$cage_anchor" || true | |
| 65 | 新增: else | |
| 66 | 新增: printf 'Build incomplete. Retained its container %s and evidence in %s.\n' "$cage_container_id" "$cage_stage" >&2 | |
| 67 | 新增: fi | |
| 68 | 新增: exit "$result" | |
| 69 | 新增:} | |
| 70 | 新增:trap finish EXIT | |
| 71 | 新增: | |
| 72 | 新增:systemd-run --user --unit "$cage_anchor" --slice "$cage_slice" /usr/bin/sleep infinity | |
| 73 | 新增:systemctl --user set-property --runtime "$cage_slice" MemoryMax=4G CPUQuota=200% TasksMax=512 | |
| 74 | 新增:cage_parent=$(systemctl --user show "$cage_slice" -p ControlGroup --value) | |
| 75 | 新增:[[ "$(cat "/sys/fs/cgroup$cage_parent/memory.max")" == 4294967296 && | |
| 76 | 新增: "$(cat "/sys/fs/cgroup$cage_parent/pids.max")" == 512 ]] || { | |
| 77 | 新增: echo 'The build parent cgroup limits were not applied.' >&2; exit 1; | |
| 78 | 新增:} | |
| 79 | 新增:read -r cage_cpu_quota cage_cpu_period < "/sys/fs/cgroup$cage_parent/cpu.max" | |
| 80 | 新增:[[ "$cage_cpu_quota" =~ ^[0-9]+$ && "$cage_cpu_period" =~ ^[0-9]+$ && | |
| 81 | 新增: "$cage_cpu_quota" -eq $((2 * cage_cpu_period)) ]] || { | |
| 82 | 新增: echo 'The build parent CPU limit was not applied.' >&2; exit 1; | |
| 83 | 新增:} | |
| 84 | 新增:cage_network_id=$(engine network create --label "cn.cage.image-build=$cage_build_id" "$cage_network") | |
| 85 | 新增: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 | |
| 87 | 新增:cage_container_id=$(engine create --name "$cage_builder" --label "cn.cage.image-build=$cage_build_id" \ | |
| 88 | 新增: --hostname cage --add-host cage:127.0.1.1 \ | |
| 89 | 新增: --network "$cage_network" --cgroupns private --cgroup-parent "$cage_slice" --ipc private \ | |
| 90 | 新增: --cpus 2 --memory 4g --memory-swap 4g --pids-limit 512 \ | |
| 91 | 新增: --cap-add SYS_ADMIN --cap-add NET_ADMIN --device /dev/fuse --device /dev/net/tun \ | |
| 92 | 新增: --tmpfs /run --tmpfs /tmp --stop-signal SIGRTMIN+3 --stop-timeout 30 \ | |
| 93 | 新增: --entrypoint /bin/sh "$cage_base" \ | |
| 94 | 新增: -ec 'umount /sys/fs/cgroup; mount -t cgroup2 none /sys/fs/cgroup; exec /sbin/init') | |
| 95 | 新增:engine start "$cage_container_id" >/dev/null | |
| 96 | 新增:for ((attempt=0; attempt<50; attempt++)); do | |
| 97 | 新增: if engine exec "$cage_container_id" sh -c 'systemctl is-active --quiet ssh && systemctl is-active --quiet dbus' >/dev/null 2>&1; then break; fi | |
| 98 | 新增: sleep .2 | |
| 99 | 新增:done | |
| 100 | 新增:engine exec "$cage_container_id" sh -c 'systemctl is-active --quiet ssh && systemctl is-active --quiet dbus' | |
| 101 | 新增:if [[ -n "${CAGE_DEBIAN_MIRROR:-}" ]]; then | |
| 102 | 新增: engine exec "$cage_container_id" python3 -c \ | |
| 103 | 新增: 'from pathlib import Path; import sys; p=Path("/etc/apt/sources.list.d/debian.sources"); p.write_text(p.read_text().replace("http://deb.debian.org", sys.argv[1]))' \ | |
| 104 | 新增: "$CAGE_DEBIAN_MIRROR" | |
| 105 | 新增:fi | |
| 106 | 新增:CLAUDE_CAGE_CONFIG="$cage_stage/profile/config.json" "$cage_binary" container-install-script tools > "$cage_stage/install-tools.sh" | |
| 107 | 新增:CLAUDE_CAGE_CONFIG="$cage_stage/profile/config.json" "$cage_binary" container-install-script services > "$cage_stage/install-services.sh" | |
| 108 | 新增:engine exec --interactive --user cage --workdir /home/cage "$cage_container_id" bash -l \ | |
| 109 | 新增: < "$cage_stage/install-tools.sh" > "$cage_stage/tools.log" 2>&1 | |
| 110 | 新增:engine exec --interactive --user cage --workdir /home/cage "$cage_container_id" zsh -l \ | |
| 111 | 新增: < "$cage_stage/install-services.sh" > "$cage_stage/services.log" 2>&1 | |
| 112 | 新增:engine cp "$cage_binary" "$cage_container_id:/usr/local/lib/cage-runtime" | |
| 113 | 新增: | |
| 114 | 新增:# No StartScript or account login is run while constructing this image. | |
| 115 | 新增:engine exec --interactive "$cage_container_id" sh -s > "$cage_stage/identity-cleanup.log" 2>&1 <<'GUEST' | |
| 116 | 新增:set -eu | |
| 117 | 新增:test ! -e /etc/claude-cage/browser-control.json | |
| 118 | 新增:test ! -e /home/cage/.config/claude-cage/browser-password | |
| 119 | 新增:test ! -e /home/cage/.claude/.credentials.json | |
| 120 | 新增:test ! -e /home/cage/.claude.json | |
| 121 | 新增:test ! -e /home/cage/.claude-cage/account.json | |
| 122 | 新增:sh /usr/local/lib/cage-image-restore-sources | |
| 123 | 新增:systemctl stop ssh cage-audio | |
| 124 | 新增:systemctl stop [email protected] [email protected] [email protected] 2>/dev/null || true | |
| 125 | 新增:systemctl stop systemd-journald.service systemd-journald.socket systemd-journald-dev-log.socket systemd-journald-audit.socket 2>/dev/null || true | |
| 126 | 新增:if systemctl is-active --quiet ssh cage-audio [email protected]; then exit 1; fi | |
| 127 | 新增:rm -f /etc/ssh/ssh_host_* /etc/ssh/cage_authorized_keys | |
| 128 | 新增:rm -rf /home/cage/.cache/cage/downloads /home/cage/.cache/mise /home/cage/.npm /home/cage/.config/code-server /home/cage/.config/pulse | |
| 129 | 新增:rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/* /var/log/journal/* /run/log/journal/* | |
| 130 | 新增:find /var/log -type f -exec truncate -s 0 {} + | |
| 131 | 新增:: > /etc/machine-id | |
| 132 | 新增:chmod 0755 /usr/local/lib/cage-runtime | |
| 133 | 新增:GUEST | |
| 134 | 新增:engine stop "$cage_container_id" >/dev/null | |
| 135 | 新增:engine commit --change 'ENTRYPOINT []' --change 'CMD ["/sbin/init"]' --change 'STOPSIGNAL SIGRTMIN+3' \ | |
| 136 | 新增: "$cage_container_id" "$cage_tag" > "$cage_stage/image-id" | |
| 137 | 新增:cage_image_id=$(cat "$cage_stage/image-id") | |
| 138 | 新增:[[ "$cage_image_id" =~ ^sha256:[a-f0-9]{64}$ ]] || { echo 'Invalid committed image identity.' >&2; exit 1; } | |
| 139 | 新增:engine run --rm --network none --read-only --cap-drop ALL --security-opt no-new-privileges \ | |
| 140 | 新增: --cgroup-parent "$cage_slice" --cpus 1 --memory 256m --pids-limit 64 --entrypoint /bin/sh "$cage_image_id" -ec \ | |
| 141 | 新增: 'test ! -s /etc/machine-id; test -z "$(find /etc/ssh -maxdepth 1 -name "ssh_host_*" -print -quit)"; test ! -e /etc/ssh/cage_authorized_keys; test ! -e /etc/claude-cage/browser-control.json; test ! -e /home/cage/.config/claude-cage/browser-password; test ! -e /home/cage/.claude/.credentials.json; test ! -e /home/cage/.claude-cage; test ! -e /home/cage/.config/code-server/config.yaml; test ! -e /home/cage/.config/pulse/cookie; test ! -e /etc/systemd/system/cage-memory.service; test -x /usr/local/lib/cage-runtime; test -s /usr/local/lib/cage-browser-agent.mjs; grep -qx "URIs: http://deb.debian.org/debian" /etc/apt/sources.list.d/debian.sources; grep -qx "URIs: http://deb.debian.org/debian-security" /etc/apt/sources.list.d/debian.sources; test "$(grep -c "^URIs:" /etc/apt/sources.list.d/debian.sources)" = 2; printf "image identity and software source checks passed\n"' \ | |
| 142 | 新增: > "$cage_stage/image-check.log" | |
| 143 | 新增:if [[ -n "${CAGE_IMAGE_ID_OUTPUT:-}" ]]; then | |
| 144 | 新增: cp "$cage_stage/image-id" "$CAGE_IMAGE_ID_OUTPUT" | |
| 145 | 新增:else | |
| 146 | 新增: engine save --output "$cage_stage/cage-guest.tar" "$cage_image_id" | |
| 147 | 新增: (cd "$cage_stage" && sha256sum cage-guest.tar > SHA256SUMS) | |
| 148 | 新增:fi | |
| 149 | 新增:cage_completed=true | |
| 150 | 新增:printf 'Built %s\nImage ID: %s\nArtifacts: %s\n' "$cage_tag" "$(cat "$cage_stage/image-id")" "$cage_stage" | |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:[Unit] | |
| 2 | 新增:Description=Cage private rootless container engine | |
| 3 | 新增:Documentation=https://docs.docker.com/engine/security/rootless/ | |
| 4 | 新增: | |
| 5 | 新增:[Service] | |
| 6 | 新增:Environment=PATH=%h/.claude-cage/container-engine/tools:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin | |
| 7 | 新增:Environment=XDG_RUNTIME_DIR=%t | |
| 8 | 新增:Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=%t/bus | |
| 9 | 新增:Environment=DOCKER_CONFIG=%h/.claude-cage/container-engine/client | |
| 10 | 新增:Environment=DOCKERD_ROOTLESS_ROOTLESSKIT_STATE_DIR=%t/cage-container-engine/rootlesskit | |
| 11 | 新增:Environment=DOCKERD_ROOTLESS_ROOTLESSKIT_NET=gvisor-tap-vsock | |
| 12 | 新增:RuntimeDirectory=cage-container-engine | |
| 13 | 新增:RuntimeDirectoryMode=0700 | |
| 14 | 新增:ExecStart=%h/.claude-cage/container-engine/tools/dockerd-rootless.sh --config-file=%h/.claude-cage/container-engine/daemon.json --data-root=%h/.claude-cage/container-engine/data --exec-root=%t/cage-container-engine/exec --pidfile=%t/cage-container-engine/docker.pid --host=unix://%t/cage-container-engine/docker.sock --storage-driver=overlay2 --exec-opt=native.cgroupdriver=systemd --userland-proxy=false --bridge=none | |
| 15 | 新增:Delegate=yes | |
| 16 | 新增:KillMode=mixed | |
| 17 | 新增:TimeoutStartSec=120 | |
| 18 | 新增:TimeoutStopSec=120 | |
| 19 | 新增:Restart=on-failure | |
| 20 | 新增:RestartSec=3 | |
| 21 | 新增: | |
| 22 | 新增:[Install] | |
| 23 | 新增:WantedBy=default.target | |
| @@ -0,0 +1,17 @@ | ||
| 1 | 新增:[Unit] | |
| 2 | 新增:Description=Cage cloud control service | |
| 3 | 新增:Requires=cage-container-engine.service | |
| 4 | 新增:After=cage-container-engine.service | |
| 5 | 新增: | |
| 6 | 新增:[Service] | |
| 7 | 新增:Environment=CLAUDE_CAGE_CONFIG=%h/.claude-cage/config.json | |
| 8 | 新增:Environment=PATH=%h/.local/lib/cage:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin | |
| 9 | 新增:WorkingDirectory=%h | |
| 10 | 新增:ExecStart=%h/.local/lib/cage/cage serve | |
| 11 | 新增:KillMode=mixed | |
| 12 | 新增:TimeoutStopSec=120 | |
| 13 | 新增:Restart=on-failure | |
| 14 | 新增:RestartSec=3 | |
| 15 | 新增: | |
| 16 | 新增:[Install] | |
| 17 | 新增:WantedBy=default.target | |
| @@ -0,0 +1,7 @@ | ||
| 1 | 新增:// Package cloud carries the remote lifecycle script shipped with the desktop app. | |
| 2 | 新增:package cloud | |
| 3 | 新增: | |
| 4 | 新增:import _ "embed" | |
| 5 | 新增: | |
| 6 | 新增://go:embed lifecycle.sh | |
| 7 | 新增:var Lifecycle string | |
| @@ -0,0 +1,186 @@ | ||
| 1 | 新增:# Invoked over a host-key verified SSH connection. Stdout is protocol data. | |
| 2 | 新增:set -eu | |
| 3 | 新增:umask 077 | |
| 4 | 新增:action=$1 | |
| 5 | 新增:exe=$2 | |
| 6 | 新增:config=${3:-"$HOME/.claude-cage/config.json"} | |
| 7 | 新增:export CLAUDE_CAGE_CONFIG="$config" | |
| 8 | 新增:profile=$(dirname -- "$config") | |
| 9 | 新增:root="$profile/cloud-host" | |
| 10 | 新增:key=$(printf %s "$config" | sha256sum | cut -c1-16) | |
| 11 | 新增:unit=cage-cloud-$key | |
| 12 | 新增:engine=$unit-engine | |
| 13 | 新增:units="${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user" | |
| 14 | 新增:owned() { [[ -f "$root/owner" && $(cat "$root/owner") == "$config" ]]; } | |
| 15 | 新增:exists() { [[ -e "$1" || -L "$1" ]]; } | |
| 16 | 新增:installed() { owned && [[ -e "$root/ready" ]]; } | |
| 17 | 新增:manual() { | |
| 18 | 新增: if [[ "$exe" != cage ]]; then [[ -x "$exe" ]] && printf '%s' "$exe" | |
| 19 | 新增: elif command -v cage >/dev/null; then command -v cage | |
| 20 | 新增: elif [[ -x "$HOME/.local/lib/cage/cage" ]]; then printf '%s' "$HOME/.local/lib/cage/cage" | |
| 21 | 新增: else return 1 | |
| 22 | 新增: fi | |
| 23 | 新增:} | |
| 24 | 新增:preflight() { | |
| 25 | 新增: [[ $(uname -s) == Linux && $(uname -m) == x86_64 && $(id -u) != 0 ]] || exit 61 | |
| 26 | 新增: [[ -c /dev/fuse && -c /dev/net/tun && -f /sys/fs/cgroup/cgroup.controllers ]] || exit 62 | |
| 27 | 新增: for tool in newuidmap newgidmap iptables ip tar sha256sum systemctl flock; do command -v "$tool" >/dev/null || exit 62; done | |
| 28 | 新增: systemctl --user show-environment >/dev/null || exit 63 | |
| 29 | 新增: for map in /etc/subuid /etc/subgid; do | |
| 30 | 新增: awk -F: -v user="$(id -un)" -v uid="$(id -u)" '($1==user || $1==uid) && $3>=65536 {ok=1} END {exit !ok}' "$map" || exit 62 | |
| 31 | 新增: done | |
| 32 | 新增: # Unit templates and JSON below deliberately accept portable absolute paths. | |
| 33 | 新增: [[ "$config" =~ ^/[a-zA-Z0-9._/-]+$ && "$config" != *'/../'* && "$profile" != / ]] || exit 64 | |
| 34 | 新增:} | |
| 35 | 新增:vacant() { | |
| 36 | 新增: if exists "$root"; then owned || exit 65 | |
| 37 | 新增: elif exists "$profile" && [[ -n $(ls -A -- "$profile") ]]; then exit 65 | |
| 38 | 新增: fi | |
| 39 | 新增:} | |
| 40 | 新增:case "$action" in | |
| 41 | 新增:probe) | |
| 42 | 新增: if [[ "$exe" == cage ]] && installed; then printf managed | |
| 43 | 新增: elif binary=$(manual); then | |
| 44 | 新增: # Match the service's exact profile before starting a manual installation. | |
| 45 | 新增: if [[ " $(systemctl --user show cage-server.service -p Environment --value) " == *" CLAUDE_CAGE_CONFIG=$config "* ]] && | |
| 46 | 新增: [[ "$(systemctl --user show cage-server.service -p ExecStart --value)" == *"path=$binary ;"* ]]; then printf manual | |
| 47 | 新增: else | |
| 48 | 新增: exec "$binary" server-entry --json | |
| 49 | 新增: fi | |
| 50 | 新增: elif [[ "$exe" != cage ]]; then exit 66 | |
| 51 | 新增: else preflight; vacant; printf missing | |
| 52 | 新增: fi ;; | |
| 53 | 新增:entry) | |
| 54 | 新增: if [[ "$exe" == cage ]] && installed; then binary="$root/bin/cage"; else binary=$(manual); fi | |
| 55 | 新增: exec "$binary" server-entry --json ;; | |
| 56 | 新增:start) | |
| 57 | 新增: if [[ "$exe" == cage ]] && installed; then systemctl --user start "$unit.service" | |
| 58 | 新增: else systemctl --user start cage-server.service; fi ;; | |
| 59 | 新增:install) | |
| 60 | 新增: preflight; vacant | |
| 61 | 新增: [[ "$exe" == cage ]] || exit 66 | |
| 62 | 新增: digest=$4 | |
| 63 | 新增: [[ "$digest" =~ ^[0-9a-f]{64}$ ]] | |
| 64 | 新增: mkdir -p -- "$profile" | |
| 65 | 新增: if mkdir -- "$root" 2>/dev/null; then printf '%s' "$config" > "$root/owner"; fi | |
| 66 | 新增: owned || exit 65 | |
| 67 | 新增: exec 9>"$root/install.lock" | |
| 68 | 新增: flock -n 9 || exit 67 | |
| 69 | 新增: installed && { cat >/dev/null; exit 0; } | |
| 70 | 新增: [[ $(df -Pk "$root" | awk 'END {print $4}') -gt 7340032 ]] || exit 68 | |
| 71 | 新增: if exists "$root/kit-id"; then [[ $(cat "$root/kit-id") == "$digest" ]] || exit 65; fi | |
| 72 | 新增: stage=$(mktemp -d "$root/upload.XXXXXX") | |
| 73 | 新增: trap 'rm -rf -- "$stage"' EXIT | |
| 74 | 新增: cat > "$stage/payload.tar" | |
| 75 | 新增: (cd "$stage"; printf '%s payload.tar\n' "$digest" | sha256sum -c --status -) || exit 69 | |
| 76 | 新增: printf '%s' "$digest" > "$root/kit-id" | |
| 77 | 新增: tar -xf "$stage/payload.tar" -C "$stage" | |
| 78 | 新增: rm "$stage/payload.tar" | |
| 79 | 新增: mkdir -p "$root/bin" "$root/engine/tools" "$root/engine/client" "$units" | |
| 80 | 新增: if [[ -f "$stage/engine-downloads" ]]; then | |
| 81 | 新增: for name in cage mihomo; do gzip -dc "$stage/$name.gz" > "$stage/$name"; done | |
| 82 | 新增: mkdir -p "$root/downloads" | |
| 83 | 新增: while read -r checksum name url; do | |
| 84 | 新增: cached="$root/downloads/$name" | |
| 85 | 新增: if ! (cd "$root/downloads"; printf '%s %s\n' "$checksum" "$name" | sha256sum -c --status -) 2>/dev/null; then | |
| 86 | 新增: # Fixed-size ranges also work through mirrors which truncate a large response. | |
| 87 | 新增: if [[ -f "$cached.part" ]] && printf '%s %s\n' "$checksum" "$cached.part" | sha256sum -c --status -; then | |
| 88 | 新增: mv "$cached.part" "$cached" | |
| 89 | 新增: ln "$cached" "$stage/$name" | |
| 90 | 新增: continue | |
| 91 | 新增: fi | |
| 92 | 新增: length=0 | |
| 93 | 新增: while [[ $length -eq 0 || $offset -lt $length ]]; do | |
| 94 | 新增: offset=$(stat -c %s "$cached.part" 2>/dev/null || echo 0) | |
| 95 | 新增: end=$((offset + 4194303)) | |
| 96 | 新增: ok=false | |
| 97 | 新增: for source in "$url" "https://mirrors.ustc.edu.cn/docker-ce/linux/static/stable/x86_64/$name" "https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/static/stable/x86_64/$name"; do | |
| 98 | 新增: if curl -fsSL --connect-timeout 8 --max-time 90 --range "$offset-$end" -D "$stage/headers" -o "$stage/chunk" "$source"; then | |
| 99 | 新增: range=$(tr -d '\r' < "$stage/headers" | awk 'tolower($1)=="content-range:" {print $3}' | tail -1) | |
| 100 | 新增: if [[ "$range" =~ ^([0-9]+)-([0-9]+)/([0-9]+)$ ]]; then | |
| 101 | 新增: first=${BASH_REMATCH[1]} last=${BASH_REMATCH[2]} total=${BASH_REMATCH[3]} | |
| 102 | 新增: if (( first == offset && last <= end && last < total && total < 268435456 && last-first+1 == $(stat -c %s "$stage/chunk") )); then | |
| 103 | 新增: cat "$stage/chunk" >> "$cached.part"; length=$total; offset=$((last+1)); ok=true; break | |
| 104 | 新增: fi | |
| 105 | 新增: elif printf '%s %s\n' "$checksum" "$stage/chunk" | sha256sum -c --status -; then | |
| 106 | 新增: mv "$stage/chunk" "$cached.part"; length=1; offset=1; ok=true; break | |
| 107 | 新增: fi | |
| 108 | 新增: fi | |
| 109 | 新增: done | |
| 110 | 新增: [[ "$ok" == true ]] || exit 74 | |
| 111 | 新增: done | |
| 112 | 新增: printf '%s %s\n' "$checksum" "$cached.part" | sha256sum -c --status - || { rm -f "$cached.part"; exit 69; } | |
| 113 | 新增: mv "$cached.part" "$cached" | |
| 114 | 新增: fi | |
| 115 | 新增: ln "$cached" "$stage/$name" | |
| 116 | 新增: done < "$stage/engine-downloads" | |
| 117 | 新增: fi | |
| 118 | 新增: for name in cage mihomo; do | |
| 119 | 新增: if ! cmp -s "$stage/$name" "$root/bin/$name"; then | |
| 120 | 新增: install -m 700 "$stage/$name" "$root/bin/$name.new" | |
| 121 | 新增: mv "$root/bin/$name.new" "$root/bin/$name" | |
| 122 | 新增: fi | |
| 123 | 新增: done | |
| 124 | 新增: eng="$root/engine" | |
| 125 | 新增: if [[ ! -f "$eng/tools/.complete" ]]; then | |
| 126 | 新增: for tgz in "$stage"/docker-*.tgz; do tar -xzf "$tgz" --strip-components=1 -C "$eng/tools"; done | |
| 127 | 新增: touch "$eng/tools/.complete" | |
| 128 | 新增: fi | |
| 129 | 新增: [[ -f "$eng/daemon.json" ]] || printf '{}\n' > "$eng/daemon.json" | |
| 130 | 新增: # Install only our units. An existing independent service must never be replaced. | |
| 131 | 新增: write_unit() { | |
| 132 | 新增: local name=$1 src=$2 | |
| 133 | 新增: sed -e "s|%h/.claude-cage/container-engine|$eng|g" \ | |
| 134 | 新增: -e "s|%h/.claude-cage/config.json|$config|g" -e "s|%h/.local/lib/cage|$root/bin|g" \ | |
| 135 | 新增: -e "s|cage-container-engine|$engine|g" "$src" > "$stage/$name" | |
| 136 | 新增: if exists "$units/$name"; then cmp -s "$stage/$name" "$units/$name" || exit 65 | |
| 137 | 新增: else ln "$stage/$name" "$units/$name" 2>/dev/null || ( set -C; cat "$stage/$name" > "$units/$name" ); fi | |
| 138 | 新增: } | |
| 139 | 新增: write_unit "$engine.service" "$stage/cage-container-engine.service" | |
| 140 | 新增: write_unit "$unit.service" "$stage/cage-server.service" | |
| 141 | 新增: systemctl --user daemon-reload | |
| 142 | 新增: systemctl --user start "$engine.service" || exit 70 | |
| 143 | 新增: export DOCKER_HOST="unix:///run/user/$(id -u)/$engine/docker.sock" DOCKER_CONFIG="$eng/client" | |
| 144 | 新增: unset DOCKER_CONTEXT | |
| 145 | 新增: docker="$eng/tools/docker" | |
| 146 | 新增: for i in {1..120}; do "$docker" info >/dev/null 2>&1 && break; sleep 1; done | |
| 147 | 新增: [[ $("$docker" info --format '{{json .SecurityOptions}} {{.CgroupDriver}} {{.CgroupVersion}}') == *'name=rootless'*' systemd 2' ]] || exit 70 | |
| 148 | 新增: if [[ -f "$stage/engine-downloads" ]]; then | |
| 149 | 新增: if [[ ! -f "$root/image-id" ]]; then | |
| 150 | 新增: base=$(sed -n 's/^ARG BASE_IMAGE=//p' "$stage/deploy/cloud/Dockerfile.guest") | |
| 151 | 新增: ref=${base#*@} | |
| 152 | 新增: [[ "$ref" =~ ^sha256:[0-9a-f]{64}$ ]] | |
| 153 | 新增: for repo in docker.io/library/debian docker.m.daocloud.io/library/debian docker.1ms.run/library/debian public.ecr.aws/docker/library/debian; do | |
| 154 | 新增: if timeout 120 "$docker" pull "$repo@$ref" >> "$root/build.log" 2>&1; then | |
| 155 | 新增: base_id=$("$docker" image inspect --format '{{.Id}}' "$repo@$ref") | |
| 156 | 新增: break | |
| 157 | 新增: fi | |
| 158 | 新增: done | |
| 159 | 新增: [[ -n "${base_id:-}" ]] || exit 75 | |
| 160 | 新增: mirror=http://deb.debian.org | |
| 161 | 新增: best=0 | |
| 162 | 新增: for site in http://deb.debian.org http://mirrors.ustc.edu.cn http://mirrors.nju.edu.cn; do | |
| 163 | 新增: rate=$(curl -fsSL --range 0-131071 --max-time 4 -o /dev/null -w '%{speed_download}' "$site/debian/dists/trixie/main/binary-amd64/Packages.xz") || continue | |
| 164 | 新增: rate=${rate%%.*} | |
| 165 | 新增: if [[ "$rate" =~ ^[0-9]+$ ]] && ((rate > best)); then mirror=$site; best=$rate; fi | |
| 166 | 新增: done | |
| 167 | 新增: CAGE_DEBIAN_MIRROR="$mirror" CAGE_CONTAINER_ENGINE="$docker" CAGE_SERVER_BINARY="$root/bin/cage" CAGE_GUEST_BASE_IMAGE="$base_id" \ | |
| 168 | 新增: CAGE_IMAGE_BUILD_DIR="$root/build" CAGE_IMAGE_ID_OUTPUT="$root/image-id.new" \ | |
| 169 | 新增: bash "$stage/deploy/cloud/build-guest.sh" >> "$root/build.log" 2>&1 || exit 76 | |
| 170 | 新增: mv "$root/image-id.new" "$root/image-id" | |
| 171 | 新增: fi | |
| 172 | 新增: image=$(cat "$root/image-id") | |
| 173 | 新增: else | |
| 174 | 新增: image=$(cat "$stage/image-id") | |
| 175 | 新增: "$docker" image inspect "$image" >/dev/null 2>&1 || "$docker" load -i "$stage/guest.tar.zst" >/dev/null || exit 71 | |
| 176 | 新增: fi | |
| 177 | 新增: [[ "$image" =~ ^sha256:[0-9a-f]{64}$ ]] | |
| 178 | 新增: "$docker" image inspect "$image" >/dev/null || exit 71 | |
| 179 | 新增: cage="$root/bin/cage" | |
| 180 | 新增: [[ -e "$config" ]] || "$cage" init >/dev/null | |
| 181 | 新增: printf '{"engine":"docker","executable":"%s","socket":"%s","image":"%s","cpus":2,"memory_bytes":4294967296}\n' "$docker" "$DOCKER_HOST" "$image" | "$cage" container-configure --json >/dev/null | |
| 182 | 新增: "$cage" setup >"$root/setup.log" 2>&1 || exit 72 | |
| 183 | 新增: systemctl --user enable --now "$unit.service" || exit 73 | |
| 184 | 新增: touch "$root/ready" ;; | |
| 185 | 新增:*) exit 2 ;; | |
| 186 | 新增:esac | |
| @@ -0,0 +1,27 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:# Inputs: trusted Linux Cage build, the verified guest build directory, Docker archives. | |
| 3 | 新增:set -euo pipefail | |
| 4 | 新增:cd "$(dirname "$0")/../.." | |
| 5 | 新增:: "${CAGE_SERVER_BINARY:?Specify the Linux amd64 Cage binary}" | |
| 6 | 新增:: "${CAGE_GUEST_BUILD:?Specify the build-guest.sh output directory}" | |
| 7 | 新增:: "${CAGE_DOCKER_DOWNLOADS:?Specify the directory containing the two pinned Docker archives}" | |
| 8 | 新增:target="${CAGE_KIT_OUTPUT:-$PWD/_output/cloud-kit}" | |
| 9 | 新增:mkdir -p "$target" | |
| 10 | 新增:stage=$(mktemp -d "$target/kit.XXXXXX") | |
| 11 | 新增:trap 'rm -rf "$stage"' EXIT | |
| 12 | 新增:(cd "$CAGE_GUEST_BUILD"; shasum -a 256 -c SHA256SUMS) | |
| 13 | 新增:grep -Exq 'sha256:[a-f0-9]{64}' "$CAGE_GUEST_BUILD/image-id" | |
| 14 | 新增:cp "$CAGE_GUEST_BUILD/image-id" "$stage/" | |
| 15 | 新增:zstd -q -T2 -4 "$CAGE_GUEST_BUILD/cage-guest.tar" -o "$stage/guest.tar.zst" | |
| 16 | 新增:cp "$CAGE_SERVER_BINARY" "$stage/cage" | |
| 17 | 新增:bash scripts/fetch-linux-proxy-core.sh | |
| 18 | 新增:cp _output/linux-deps/mihomo "$stage/" | |
| 19 | 新增:cp deploy/cloud/*.service "$stage/" | |
| 20 | 新增:while read -r digest archive; do | |
| 21 | 新增: cp "$CAGE_DOCKER_DOWNLOADS/$archive" "$stage/" | |
| 22 | 新增: (cd "$stage"; printf '%s %s\n' "$digest" "$archive" | shasum -a 256 -c -) | |
| 23 | 新增:done < <(node -e 'for(const a of require("./deploy/cloud/runtime-artifacts.json").artifacts)console.log(a.sha256,a.file)') | |
| 24 | 新增:name=cloud-linux-amd64.tar | |
| 25 | 新增:COPYFILE_DISABLE=1 tar -cf "$stage/$name" -C "$stage" cage mihomo cage-container-engine.service cage-server.service image-id guest.tar.zst docker-29.9.1.tgz docker-rootless-extras-29.9.1.tgz | |
| 26 | 新增:shasum -a 256 "$stage/$name" | cut -d' ' -f1 > "$stage/$name.sha256" | |
| 27 | 新增:mv "$stage/$name" "$stage/$name.sha256" "$target/" | |
| @@ -0,0 +1,28 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:# Build mirrors are temporary. Runtime maintenance admits official origins. | |
| 3 | 新增:set -eu | |
| 4 | 新增:python3 - <<'PY' | |
| 5 | 新增:from pathlib import Path | |
| 6 | 新增:from urllib.parse import urlsplit | |
| 7 | 新增: | |
| 8 | 新增:source = Path('/etc/apt/sources.list.d/debian.sources') | |
| 9 | 新增:rows = source.read_text().splitlines() | |
| 10 | 新增:seen = set() | |
| 11 | 新增:for index, row in enumerate(rows): | |
| 12 | 新增: if not row.startswith('URIs:'): | |
| 13 | 新增: continue | |
| 14 | 新增: entries = row.split()[1:] | |
| 15 | 新增: if len(entries) != 1: | |
| 16 | 新增: raise SystemExit('Unexpected Debian source layout; source file was not changed.') | |
| 17 | 新增: uri = urlsplit(entries[0]) | |
| 18 | 新增: path = uri.path.rstrip('/') | |
| 19 | 新增: if uri.scheme not in ('http', 'https') or path not in ('/debian', '/debian-security') or uri.query or uri.fragment: | |
| 20 | 新增: raise SystemExit('Unexpected Debian source origin; source file was not changed.') | |
| 21 | 新增: if path in seen: | |
| 22 | 新增: raise SystemExit('Duplicate Debian source; source file was not changed.') | |
| 23 | 新增: seen.add(path) | |
| 24 | 新增: rows[index] = 'URIs: http://deb.debian.org' + path | |
| 25 | 新增:if seen != {'/debian', '/debian-security'}: | |
| 26 | 新增: raise SystemExit('Both Debian archive and security sources are required; source file was not changed.') | |
| 27 | 新增:source.write_text('\n'.join(rows) + '\n') | |
| 28 | 新增:PY | |
| @@ -0,0 +1,16 @@ | ||
| 1 | 新增:{ | |
| 2 | 新增: "platform": "linux-amd64", | |
| 3 | 新增: "dockerVersion": "29.9.1", | |
| 4 | 新增: "artifacts": [ | |
| 5 | 新增: { | |
| 6 | 新增: "file": "docker-29.9.1.tgz", | |
| 7 | 新增: "url": "https://download.docker.com/linux/static/stable/x86_64/docker-29.9.1.tgz", | |
| 8 | 新增: "sha256": "c158ecc55adb3afb01bbd3539ed3b997d20c26dbdc418080506cc1bf5243ff57" | |
| 9 | 新增: }, | |
| 10 | 新增: { | |
| 11 | 新增: "file": "docker-rootless-extras-29.9.1.tgz", | |
| 12 | 新增: "url": "https://download.docker.com/linux/static/stable/x86_64/docker-rootless-extras-29.9.1.tgz", | |
| 13 | 新增: "sha256": "c87668896a3fced2e715324e9fb6a0634aba3e5d8408a471f6bc23dc476662af" | |
| 14 | 新增: } | |
| 15 | 新增: ] | |
| 16 | 新增:} | |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import Foundation |
| 2 | 2 | import Security |
| 3 | 3 | import LocalAuthentication |
| 4 | 新增:import CryptoKit | |
| 4 | 5 | |
| 5 | 6 | struct CageAccountError: LocalizedError { |
| 6 | 7 | let message: String |
| @@ -19,12 +20,13 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 19 | 20 | }() |
| 20 | 21 | private let base: URL |
| 21 | 22 | private let ticket: String |
| 23 | 新增: private let connection: String | |
| 22 | 24 | |
| 23 | 删除: init(entry: URL) throws { | |
| 25 | 新增: init(entry: URL, connection: String = "local") throws { | |
| 24 | 26 | guard entry.scheme == "http", entry.host == "localhost", let ticket = entry.fragment, !ticket.isEmpty else { throw CageAccountError("本地账户连接无效") } |
| 25 | 27 | var parts = URLComponents(url: entry, resolvingAgainstBaseURL: false)! |
| 26 | 28 | parts.fragment = nil; parts.path = ""; parts.query = nil |
| 27 | 删除: base = parts.url!; self.ticket = ticket | |
| 29 | 新增: base = parts.url!; self.ticket = ticket; self.connection = connection | |
| 28 | 30 | super.init() |
| 29 | 31 | } |
| 30 | 32 | deinit { session.invalidateAndCancel() } |
| @@ -32,8 +34,10 @@ final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Send | ||
| 32 | 34 | private func call(_ path: String, _ body: [String: Any]? = nil) async throws -> [String: Any] { |
| 33 | 35 | var request = URLRequest(url: base.appendingPathComponent("api/account" + path)) |
| 34 | 36 | if path == "@session" { request.url = base.appendingPathComponent("api/session") } |
| 37 | 新增: if path == "@context" { request.url = base.appendingPathComponent("api/client/context") } | |
| 35 | 38 | request.httpMethod = body == nil ? "GET" : "POST" |
| 36 | 39 | request.setValue(base.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), forHTTPHeaderField: "Origin") |
| 40 | 新增: request.setValue(connection, forHTTPHeaderField: "X-Cage-Connection") | |
| 37 | 41 | if let body { request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.httpBody = try JSONSerialization.data(withJSONObject: body) } |
| 38 | 42 | let (data, response) = try await session.data(for: request) |
| 39 | 43 | guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { |
| @@ -125,7 +129,21 @@ extension CageAccountDevice { | ||
| 125 | 129 | defer { session.invalidateAndCancel() } |
| 126 | 130 | _ = try await call("@session", ["token": ticket]) |
| 127 | 131 | let account = try await call("") |
| 128 | 删除: guard let binding = account["device_binding"] as? String, binding.count == 64 else { throw CageAccountError("当前后台不支持快捷登录,请先完成更新") } | |
| 132 | 新增: guard let accountBinding = account["device_binding"] as? String, accountBinding.count == 64 else { throw CageAccountError("当前后台不支持快捷登录,请先完成更新") } | |
| 133 | 新增: var binding = accountBinding | |
| 134 | 新增: if connection != "local" { | |
| 135 | 新增: let selected = try await call("@context") | |
| 136 | 新增: guard selected["connection_id"] as? String == connection else { throw CageAccountError("工作环境已切换,请重新解锁") } | |
| 137 | 新增: if selected["mode"] as? String == "remote" { | |
| 138 | 新增: guard let host = selected["host_id"] as? String, !host.isEmpty, | |
| 139 | 新增: let fingerprint = selected["host_fingerprint"] as? String, fingerprint.hasPrefix("SHA256:"), | |
| 140 | 新增: let instance = selected["instance_id"] as? String, instance.count == 64 else { throw CageAccountError("远程连接已经切换,请重新解锁当前主机") } | |
| 141 | 新增: let scoped = ["remote", host, fingerprint, instance, accountBinding].joined(separator: "\u{0}") | |
| 142 | 新增: binding = SHA256.hash(data: Data(scoped.utf8)).map { String(format: "%02x", $0) }.joined() | |
| 143 | 新增: } else if selected["mode"] as? String != "local" { | |
| 144 | 新增: throw CageAccountError("请先选择工作环境") | |
| 145 | 新增: } | |
| 146 | 新增: } | |
| 129 | 147 | let context = LAContext() |
| 130 | 148 | let biometricAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) |
| 131 | 149 | if operation == "status" { |
| @@ -209,6 +209,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 209 | 209 | } |
| 210 | 210 | DispatchQueue.global(qos: .userInitiated).async { |
| 211 | 211 | let process = Process(); process.executableURL = executable; process.arguments = ["desktop", "--json"] + options |
| 212 | 新增: var environment = ProcessInfo.processInfo.environment | |
| 213 | 新增: environment["CAGE_DESKTOP_OWNER_PID"] = String(ProcessInfo.processInfo.processIdentifier) | |
| 214 | 新增: process.environment = environment | |
| 212 | 215 | let output = Pipe(); process.standardOutput = output; process.standardError = FileHandle.nullDevice |
| 213 | 216 | do { |
| 214 | 217 | try process.run() |
| @@ -242,9 +245,9 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 242 | 245 | } |
| 243 | 246 | } |
| 244 | 247 | } |
| 245 | 删除: private func browserFile(_ operation: String, id: String, path: String? = nil, reply: @escaping (Any?, String?) -> Void) { | |
| 248 | 新增: private func browserFile(_ operation: String, id: String, connection: String = "local", path: String? = nil, reply: @escaping (Any?, String?) -> Void) { | |
| 246 | 249 | guard UUID(uuidString: id) != nil else { reply(nil,"下载标识无效"); return } |
| 247 | 删除: fileCommand(["browser-file", "--json", operation, id] + (path.map { [$0] } ?? []), reply: reply) | |
| 250 | 新增: fileCommand(["browser-file", "--json", "--connection", connection, operation, id] + (path.map { [$0] } ?? []), reply: reply) | |
| 248 | 251 | } |
| 249 | 252 | private func fileCommand(_ arguments: [String], reply: @escaping (Any?, String?) -> Void) { |
| 250 | 253 | guard let executable = Bundle.main.url(forResource: "cage", withExtension: nil) else { reply(nil,"无法找到文件传递组件"); return } |
| @@ -308,13 +311,14 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 308 | 311 | let operation = body["operation"] as? String, ["status", "enable", "disable", "unlock"].contains(operation) else { replyHandler(nil,"账户操作正在进行或后台需要更新,请稍后重试"); return } |
| 309 | 312 | accountDeviceBusy = true |
| 310 | 313 | let kind = body["kind"] as? String |
| 314 | 新增: let connection = body["connection_id"] as? String ?? "local" | |
| 311 | 315 | requestEntry { result in |
| 312 | 316 | guard case .success(let entry) = result, let url = entry.url else { |
| 313 | 317 | self.accountDeviceBusy = false; replyHandler(nil,"无法连接本地账户,请重新打开 Cage"); return |
| 314 | 318 | } |
| 315 | 319 | Task.detached { |
| 316 | 320 | do { |
| 317 | 删除: let client = try CageAccountDevice(entry: url) | |
| 321 | 新增: let client = try CageAccountDevice(entry: url, connection: connection) | |
| 318 | 322 | let value = try await client.handle(operation: operation, kind: kind) |
| 319 | 323 | await MainActor.run { self.accountDeviceBusy = false; replyHandler(value,nil) } |
| 320 | 324 | } catch { |
| @@ -329,7 +333,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 329 | 333 | panel.beginSheetModal(for: window) { response in |
| 330 | 334 | self.nativeFilePanelOpen = false |
| 331 | 335 | guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return } |
| 332 | 删除: self.fileCommand(["diagnostics", "--json", url.path], reply: replyHandler) | |
| 336 | 新增: self.fileCommand(["diagnostics", "--json", "--connection", body["connection_id"] as? String ?? "local", url.path], reply: replyHandler) | |
| 333 | 337 | } |
| 334 | 338 | case "workbenchReady": |
| 335 | 339 | guard !controllerNeedsUpdate else { replyHandler(nil,"后台版本尚未同步,更新未完成"); return } |
| @@ -379,7 +383,7 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 379 | 383 | let files = fileSelections.removeValue(forKey: selection), files.expires > Date() else { |
| 380 | 384 | replyHandler(nil,"文件选择已过期,请重新复制或选择文件"); return |
| 381 | 385 | } |
| 382 | 删除: fileCommand(["upload-files", "--json", target, id] + files.paths, reply: replyHandler) | |
| 386 | 新增: fileCommand(["upload-files", "--json", "--connection", body["connection_id"] as? String ?? "local", target, id] + files.paths, reply: replyHandler) | |
| 383 | 387 | case "clipboardWrite": |
| 384 | 388 | guard let text = body["text"] as? String else { replyHandler(nil,"缺少文本"); return } |
| 385 | 389 | NSPasteboard.general.clearContents(); NSPasteboard.general.setString(text, forType:.string); replyHandler(true,nil) |
| @@ -392,11 +396,11 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 392 | 396 | panel.beginSheetModal(for: window) { response in |
| 393 | 397 | self.nativeFilePanelOpen = false |
| 394 | 398 | guard response == .OK, let url = panel.url else { replyHandler(["canceled":true],nil); return } |
| 395 | 删除: self.browserFile("save",id:id,path:url.path,reply:replyHandler) | |
| 399 | 新增: self.browserFile("save",id:id,connection:body["connection_id"] as? String ?? "local",path:url.path,reply:replyHandler) | |
| 396 | 400 | } |
| 397 | 401 | case "browserDownloadAction": |
| 398 | 402 | guard let id = body["id"] as? String, let operation = body["operation"] as? String, ["open","reveal"].contains(operation) else { replyHandler(nil,"下载操作无效"); return } |
| 399 | 删除: browserFile(operation,id:id,reply:replyHandler) | |
| 403 | 新增: browserFile(operation,id:id,connection:body["connection_id"] as? String ?? "local",reply:replyHandler) | |
| 400 | 404 | case "importTheme": |
| 401 | 405 | let panel = NSOpenPanel() |
| 402 | 406 | panel.allowedContentTypes = [.json]; panel.allowsMultipleSelection = false |
| @@ -426,7 +430,10 @@ final class CageApp: NSObject, NSApplicationDelegate, NSWindowDelegate, WKNaviga | ||
| 426 | 430 | catch { replyHandler(nil, "主题未能导出,请检查保存位置的权限") } |
| 427 | 431 | } |
| 428 | 432 | case "chooseFolder": |
| 429 | 删除: let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false; panel.prompt = "共享此项目"; panel.message = "仅此文件夹会与 Cage 共享。请选择具体项目。" | |
| 433 | 新增: let panel = NSOpenPanel(); panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true; panel.allowsMultipleSelection = false | |
| 434 | 新增: let storage = (body["purpose"] as? String) == "environmentStorage" | |
| 435 | 新增: panel.prompt = storage ? "选择文件夹" : "共享此项目" | |
| 436 | 新增: panel.message = storage ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。" | |
| 430 | 437 | nativeFilePanelOpen = true |
| 431 | 438 | panel.beginSheetModal(for:window) { response in self.nativeFilePanelOpen = false; replyHandler(response == .OK ? panel.url?.path : "",nil) } |
| 432 | 439 | case "refreshSession": |
| @@ -6,11 +6,12 @@ import Darwin | ||
| 6 | 6 | let cageUpdateBundleID = "io.github.lee-xeo.claude-cage" |
| 7 | 7 | |
| 8 | 8 | enum CageProfile { |
| 9 | 新增: static var clientOnly: Bool { Bundle.main.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true } | |
| 9 | 10 | static func configURL() -> URL { |
| 10 | 11 | if let path = ProcessInfo.processInfo.environment["CLAUDE_CAGE_CONFIG"], !path.isEmpty { |
| 11 | 12 | return URL(fileURLWithPath: path).standardizedFileURL |
| 12 | 13 | } |
| 13 | 删除: return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".claude-cage/config.json") | |
| 14 | 新增: return FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(clientOnly ? ".claude-cage/client/config.json" : ".claude-cage/config.json") | |
| 14 | 15 | } |
| 15 | 16 | |
| 16 | 17 | // Every helper and relaunched app inherits the same absolute profile, even |
| @@ -268,6 +269,12 @@ final class CageAppUpdater { | ||
| 268 | 269 | } |
| 269 | 270 | } |
| 270 | 271 | func handle(_ operation: String) -> [String: Any] { |
| 272 | 新增: if Bundle(url: bundleURL)?.object(forInfoDictionaryKey: "CageClientOnly") as? Bool == true { | |
| 273 | 新增: if state["phase"] as? String != "manual" || operation != "status" { | |
| 274 | 新增: change(["phase": "manual", "message": "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"]) | |
| 275 | 新增: } | |
| 276 | 新增: return state | |
| 277 | 新增: } | |
| 271 | 278 | let busy = ["checking", "downloading", "downloaded", "verifying", "installing"].contains(state["phase"] as? String ?? "") |
| 272 | 279 | switch operation { |
| 273 | 280 | case "status": break |
| @@ -14,6 +14,9 @@ | ||
| 14 | 14 | #ifndef CAGE_VERSION |
| 15 | 15 | #define CAGE_VERSION "development" |
| 16 | 16 | #endif |
| 17 | 新增:#ifndef CAGE_CLIENT_ONLY | |
| 18 | 新增:#define CAGE_CLIENT_ONLY 0 | |
| 19 | 新增:#endif | |
| 17 | 20 | #define MAX_THEME (256 * 1024) |
| 18 | 21 | #define MAX_MESSAGE (2 * 1024 * 1024) |
| 19 | 22 | |
| @@ -157,6 +160,11 @@ static void backend_arguments(const char *const *args, guint seconds, BackendCal | ||
| 157 | 160 | GError *error = NULL; |
| 158 | 161 | GSubprocessLauncher *launcher = g_subprocess_launcher_new(G_SUBPROCESS_FLAGS_STDOUT_PIPE | G_SUBPROCESS_FLAGS_STDERR_SILENCE); |
| 159 | 162 | g_subprocess_launcher_setenv(launcher, "CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 163 | 新增: if (g_strcmp0(args[1], "desktop") == 0) { | |
| 164 | 新增: char owner[32]; | |
| 165 | 新增: g_snprintf(owner, sizeof(owner), "%ld", (long)getpid()); | |
| 166 | 新增: g_subprocess_launcher_setenv(launcher, "CAGE_DESKTOP_OWNER_PID", owner, TRUE); | |
| 167 | 新增: } | |
| 160 | 168 | GSubprocess *process = g_subprocess_launcher_spawnv(launcher, args, &error); |
| 161 | 169 | g_object_unref(launcher); |
| 162 | 170 | if (!process) { |
| @@ -487,9 +495,12 @@ static gboolean start_smoke(gpointer data) { | ||
| 487 | 495 | "let unauthenticatedBridgeDenied=false;try{await window.webkit.messageHandlers.cageTransport.postMessage({token:'invalid',request:{action:'clipboardRead'}});}catch{unauthenticatedBridgeDenied=true;}" |
| 488 | 496 | "stage='account-device';const native=await bridge.postMessage({action:'accountDevice',operation:'status'});" |
| 489 | 497 | "stage='app-update';const update=await bridge.postMessage({action:'appUpdate',operation:'status'});" |
| 490 | 删除: "stage='account';const accountResponse=await fetch('/api/account');const account=await accountResponse.json();" | |
| 491 | 删除: "stage='status';const stateResponse=await fetch('/api/status');const state=await stateResponse.json();" | |
| 492 | 删除: "stage='settings';const settingsResponse=await fetch('/api/settings');await settingsResponse.json();" | |
| 498 | 新增: "stage='context';const context=await (await fetch('/api/client/context')).json();" | |
| 499 | 新增: "if(context.desktop_gateway&&context.mode!=='local')throw new Error('local workbench not selected');" | |
| 500 | 新增: "const scoped={headers:{'X-Cage-Connection':context.connection_id}};" | |
| 501 | 新增: "stage='account';const accountResponse=await fetch('/api/account',scoped);const account=await accountResponse.json();" | |
| 502 | 新增: "stage='status';const stateResponse=await fetch('/api/status',scoped);const state=await stateResponse.json();" | |
| 503 | 新增: "stage='settings';const settingsResponse=await fetch('/api/settings',scoped);await settingsResponse.json();" | |
| 493 | 504 | "const root=document.getElementById('root');" |
| 494 | 505 | "const rendered=!!root&&root.innerText.trim().length>40&&root.querySelectorAll('button').length>3;" |
| 495 | 506 | "const success=rendered&&accountResponse.ok&&account.unlocked===true&&stateResponse.ok&&settingsResponse.ok&&native.supported===false&&update.phase==='manual'&&unauthenticatedBridgeDenied&&storageMarkerMatched;" |
| @@ -532,7 +543,8 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 532 | 543 | char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SAVE, "导出诊断包", "cage-diagnostics.zip"); |
| 533 | 544 | if (!path) reply_json(reply, context, "{\"canceled\":true}"); |
| 534 | 545 | else { |
| 535 | 删除: const char *args[] = {app.backend, "diagnostics", "--json", path, NULL}; | |
| 546 | 新增: const char *connection = text_member(request, "connection_id"); | |
| 547 | 新增: const char *args[] = {app.backend, "diagnostics", "--json", "--connection", *connection ? connection : "local", path, NULL}; | |
| 536 | 548 | backend_arguments(args, 60, browser_file_finished, pending_reply(reply, context)); |
| 537 | 549 | g_free(path); |
| 538 | 550 | } |
| @@ -556,9 +568,13 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 556 | 568 | reply_error(reply, "更新操作无效。"); |
| 557 | 569 | else { |
| 558 | 570 | char *version = quote(CAGE_VERSION); |
| 559 | 删除: char *state = g_strdup_printf("{\"phase\":\"manual\",\"currentVersion\":%s,\"message\":\"Linux 版本使用系统安装包更新。请保存工作、停止环境并退出 Cage,再安装新版 .deb;用户数据会保留。\"}", version); | |
| 571 | 新增: const char *update_message = CAGE_CLIENT_ONLY | |
| 572 | 新增: ? "轻量客户端使用独立安装包更新。退出客户端后更换程序;连接配置会保留,云端任务继续运行。" | |
| 573 | 新增: : "Linux 版本使用系统安装包更新。请保存工作、停止环境并退出 Cage,再安装新版 .deb;用户数据会保留。"; | |
| 574 | 新增: char *message = quote(update_message); | |
| 575 | 新增: char *state = g_strdup_printf("{\"phase\":\"manual\",\"currentVersion\":%s,\"message\":%s}", version, message); | |
| 560 | 576 | reply_json(reply, context, state); |
| 561 | 删除: g_free(state); g_free(version); | |
| 577 | 新增: g_free(state); g_free(version); g_free(message); | |
| 562 | 578 | } |
| 563 | 579 | } else if (!strcmp(name, "saveBrowserDownload") || !strcmp(name, "browserDownloadAction")) { |
| 564 | 580 | const char *id = text_member(request, "id"); |
| @@ -581,7 +597,8 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 581 | 597 | } |
| 582 | 598 | if (!strcmp(operation,"save") && !path) reply_json(reply,context,"{\"canceled\":true}"); |
| 583 | 599 | else { |
| 584 | 删除: const char *args[] = {app.backend,"browser-file","--json",operation,id,path,NULL}; | |
| 600 | 新增: const char *connection = text_member(request, "connection_id"); | |
| 601 | 新增: const char *args[] = {app.backend,"browser-file","--json","--connection",*connection ? connection : "local",operation,id,path,NULL}; | |
| 585 | 602 | backend_arguments(args,1800,browser_file_finished,pending_reply(reply,context)); |
| 586 | 603 | } |
| 587 | 604 | g_free(path); |
| @@ -589,7 +606,9 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 589 | 606 | } else if (!strcmp(name, "chooseFolder")) { |
| 590 | 607 | if (app.picker_open) reply_error(reply, "请先完成当前文件选择。"); |
| 591 | 608 | else { |
| 592 | 删除: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, "仅此文件夹会与 Cage 共享。请选择具体项目。", NULL); | |
| 609 | 新增: const char *prompt = !strcmp(text_member(request, "purpose"), "environmentStorage") | |
| 610 | 新增: ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。"; | |
| 611 | 新增: char *path = choose_file(GTK_FILE_CHOOSER_ACTION_SELECT_FOLDER, prompt, NULL); | |
| 593 | 612 | reply_string(reply, context, path ? path : ""); |
| 594 | 613 | g_free(path); |
| 595 | 614 | } |
| @@ -627,9 +646,10 @@ static gboolean bridge_received(WebKitUserContentManager *manager, JSCValue *val | ||
| 627 | 646 | } else { |
| 628 | 647 | GPtrArray *paths = g_ptr_array_ref(selected->paths); |
| 629 | 648 | g_hash_table_remove(file_selections, token); |
| 630 | 删除: const char **args = g_new0(const char *, paths->len + 6); | |
| 631 | 删除: args[0] = app.backend; args[1] = "upload-files"; args[2] = "--json"; args[3] = target; args[4] = id; | |
| 632 | 删除: for (guint i = 0; i < paths->len; i++) args[i + 5] = g_ptr_array_index(paths, i); | |
| 649 | 新增: const char *connection = text_member(request, "connection_id"); | |
| 650 | 新增: const char **args = g_new0(const char *, paths->len + 8); | |
| 651 | 新增: args[0] = app.backend; args[1] = "upload-files"; args[2] = "--json"; args[3] = "--connection"; args[4] = *connection ? connection : "local"; args[5] = target; args[6] = id; | |
| 652 | 新增: for (guint i = 0; i < paths->len; i++) args[i + 7] = g_ptr_array_index(paths, i); | |
| 633 | 653 | backend_arguments(args, 1800, browser_file_finished, pending_reply(reply, context)); |
| 634 | 654 | g_free(args); g_ptr_array_unref(paths); |
| 635 | 655 | } |
| @@ -1000,6 +1020,7 @@ int main(int argc, char **argv) { | ||
| 1000 | 1020 | if (!g_file_test(app.backend, G_FILE_TEST_IS_EXECUTABLE)) { g_printerr("安装目录缺少 Cage 后台,请重新安装。\n"); return 1; } |
| 1001 | 1021 | const char *configured = g_getenv("CLAUDE_CAGE_CONFIG"); |
| 1002 | 1022 | app.profile = configured && *configured ? g_canonicalize_filename(configured, NULL) |
| 1023 | 新增: : CAGE_CLIENT_ONLY ? g_build_filename(g_get_home_dir(), ".claude-cage", "client", "config.json", NULL) | |
| 1003 | 1024 | : g_build_filename(g_get_home_dir(), ".claude-cage", "config.json", NULL); |
| 1004 | 1025 | g_setenv("CLAUDE_CAGE_CONFIG", app.profile, TRUE); |
| 1005 | 1026 | g_log_set_default_handler(diagnostic_glib, NULL); |
| @@ -17,7 +17,9 @@ const output = resolve(outputArgument); | ||
| 17 | 17 | const root = await mkdtemp(join(tmpdir(), 'cage-linux-smoke-')); |
| 18 | 18 | // Cage places the default workspace beside the profile; both stay in this |
| 19 | 19 | // fixture directory so cleanup also removes the temporary workspace. |
| 20 | 删除:const env = { ...process.env, CLAUDE_CAGE_CONFIG: join(root, 'profile', 'config.json') }; | |
| 20 | 新增:// Keep the selected gateway alive for the two native storage phases. The | |
| 21 | 新增:// native windows register their own owners in addition to this test process. | |
| 22 | 新增:const env = { ...process.env, CLAUDE_CAGE_CONFIG: join(root, 'profile', 'config.json'), CAGE_DESKTOP_OWNER_PID: String(process.pid) }; | |
| 21 | 23 | let clean = false; |
| 22 | 24 | let result = 1; |
| 23 | 25 | |
| @@ -78,13 +80,36 @@ try { | ||
| 78 | 80 | if (!authenticate.ok) throw new Error('Session authentication failed.'); |
| 79 | 81 | const cookie = authenticate.headers.get('set-cookie')?.split(';')[0]; |
| 80 | 82 | if (!cookie) throw new Error('Authenticated response did not create a session cookie.'); |
| 83 | 新增: async function api(path, body, generation) { | |
| 84 | 新增: const headers = { Origin: url.origin, Cookie: cookie }; | |
| 85 | 新增: if (body !== undefined) headers['Content-Type'] = 'application/json'; | |
| 86 | 新增: if (generation) headers['X-Cage-Connection'] = generation; | |
| 87 | 新增: const response = await fetch(url.origin + '/api/' + path, { | |
| 88 | 新增: method: body === undefined ? 'GET' : 'POST', redirect: 'error', headers, | |
| 89 | 新增: body: body === undefined ? undefined : JSON.stringify(body), | |
| 90 | 新增: }); | |
| 91 | 新增: if (!response.ok) throw new Error(`Isolated smoke API ${path} failed with ${response.status}.`); | |
| 92 | 新增: return response.json(); | |
| 93 | 新增: } | |
| 94 | 新增: let current = await api('client/context'); | |
| 95 | 新增: if (!current.desktop_gateway || current.mode !== 'none') throw new Error('A fresh full Cage must start at the environment picker.'); | |
| 96 | 新增: const idle = await api('client/local-status'); | |
| 97 | 新增: if (!idle.known || idle.service_running || idle.running) throw new Error('The desktop picker started a local workload.'); | |
| 98 | 新增: const original = current.connection_id; | |
| 99 | 新增: const pending = await api('client/candidate', { connection_id: original, mode: 'local' }); | |
| 100 | 新增: const deadline = Date.now() + 30000; | |
| 101 | 新增: while (true) { | |
| 102 | 新增: current = await api('client/context'); | |
| 103 | 新增: if (current.connection_id !== original || current.candidate?.id !== pending.id) throw new Error('The local candidate lost its original desktop view.'); | |
| 104 | 新增: if (current.candidate.connection.state === 'connected') break; | |
| 105 | 新增: if (current.candidate.connection.state === 'failed' || Date.now() > deadline) throw new Error('Could not open the local test workbench.'); | |
| 106 | 新增: await new Promise((r) => setTimeout(r, 100)); | |
| 107 | 新增: } | |
| 108 | 新增: current = await api('client/commit', { connection_id: original, candidate_id: pending.id, local_action: 'auto' }); | |
| 109 | 新增: if (current.mode !== 'local' || current.connection_id === original) throw new Error('Local workbench generation was not selected.'); | |
| 81 | 110 | const password = randomBytes(24).toString('base64url'); |
| 82 | 删除: const account = await fetch(url.origin + '/api/account/create', { | |
| 83 | 删除: method: 'POST', redirect: 'error', | |
| 84 | 删除: headers: { 'Origin': url.origin, 'Content-Type': 'application/json', 'Cookie': cookie }, | |
| 85 | 删除: body: JSON.stringify({ username: 'Linux Smoke', password, confirm_password: password }), | |
| 86 | 删除: }); | |
| 87 | 删除: if (!account.ok || !(await account.json()).unlocked) throw new Error('Could not prepare the isolated unlocked test account.'); | |
| 111 | 新增: const account = await api('account/create', { username: 'Linux Smoke', password, confirm_password: password }, current.connection_id); | |
| 112 | 新增: if (!account.unlocked) throw new Error('Could not prepare the isolated unlocked test account.'); | |
| 88 | 113 | env.CAGE_SMOKE_STORAGE_MARKER = randomBytes(24).toString('hex'); |
| 89 | 114 | for (const phase of ['seed', 'verify']) { |
| 90 | 115 | env.CAGE_SMOKE_STORAGE_PHASE = phase; |
| @@ -34,6 +34,12 @@ internal sealed class AppUpdater : IDisposable | ||
| 34 | 34 | |
| 35 | 35 | public Dictionary<string, object?> Handle(string operation) |
| 36 | 36 | { |
| 37 | 新增: if (Backend.ClientOnly) | |
| 38 | 新增: { | |
| 39 | 新增: if (state["phase"] as string != "manual" || operation != "status") | |
| 40 | 新增: Change("manual", "轻量客户端使用独立安装包更新;连接配置会保留,云端任务不受影响。"); | |
| 41 | 新增: return new(state); | |
| 42 | 新增: } | |
| 37 | 43 | switch (operation) |
| 38 | 44 | { |
| 39 | 45 | case "status": break; |
| @@ -6,9 +6,10 @@ namespace Cage.Windows; | ||
| 6 | 6 | |
| 7 | 7 | internal static class Backend |
| 8 | 8 | { |
| 9 | 新增: public static bool ClientOnly => File.Exists(Path.Combine(AppContext.BaseDirectory, "resources", "client-only")); | |
| 9 | 10 | private static string ConfigPath => Path.GetFullPath( |
| 10 | 11 | Environment.GetEnvironmentVariable("CLAUDE_CAGE_CONFIG") is { Length: > 0 } configured |
| 11 | 删除: ? configured : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude-cage", "config.json")); | |
| 12 | 新增: ? configured : Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".claude-cage", ClientOnly ? "client" : "", "config.json")); | |
| 12 | 13 | public static string Root => Path.GetDirectoryName(ConfigPath)!; |
| 13 | 14 | public static string Executable => Path.Combine(AppContext.BaseDirectory, "resources", "cage.exe"); |
| 14 | 15 | |
| @@ -22,6 +23,7 @@ internal static class Backend | ||
| 22 | 23 | // Helpers execute outside the installed directory. Keep an explicitly |
| 23 | 24 | // selected relative profile bound to the same absolute file. |
| 24 | 25 | start.Environment["CLAUDE_CAGE_CONFIG"] = ConfigPath; |
| 26 | 新增: if (arguments.Length > 0 && arguments[0] == "desktop") start.Environment["CAGE_DESKTOP_OWNER_PID"] = Environment.ProcessId.ToString(); | |
| 25 | 27 | foreach (var arg in arguments) start.ArgumentList.Add(arg); |
| 26 | 28 | return start; |
| 27 | 29 | } |
| @@ -226,7 +226,8 @@ internal sealed class MainWindow : Form | ||
| 226 | 226 | using (var picker = new SaveFileDialog { Title = "导出诊断包", Filter = "诊断包 (*.zip)|*.zip", FileName = "cage-diagnostics.zip", DefaultExt = "zip", AddExtension = true }) |
| 227 | 227 | { |
| 228 | 228 | if (picker.ShowDialog(this) != DialogResult.OK) { result = new { canceled = true }; break; } |
| 229 | 删除: var exported = await Backend.Json(["diagnostics", "--json", picker.FileName], lifetime.Token, TimeSpan.FromSeconds(60)); | |
| 229 | 新增: var connection = request.Text("connection_id"); | |
| 230 | 新增: var exported = await Backend.Json(["diagnostics", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, picker.FileName], lifetime.Token, TimeSpan.FromSeconds(60)); | |
| 230 | 231 | if (exported.Exit != 0) throw new IOException(exported.Data.Text("message")); |
| 231 | 232 | result = exported.Data; |
| 232 | 233 | } |
| @@ -257,7 +258,7 @@ internal sealed class MainWindow : Form | ||
| 257 | 258 | } |
| 258 | 259 | break; |
| 259 | 260 | case "chooseFolder": |
| 260 | 删除: using (var picker = new FolderBrowserDialog { Description = "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true }) | |
| 261 | 新增: using (var picker = new FolderBrowserDialog { Description = request.Text("purpose") == "environmentStorage" ? "请选择用于保存镜像和虚拟磁盘的空文件夹。" : "仅此文件夹会与 Cage 共享。请选择具体项目。", UseDescriptionForTitle = true, ShowNewFolderButton = true }) | |
| 261 | 262 | result = picker.ShowDialog(this) == DialogResult.OK ? picker.SelectedPath : ""; |
| 262 | 263 | break; |
| 263 | 264 | case "clipboardRead": result = Clipboard.ContainsText() ? Clipboard.GetText() : ""; break; |
| @@ -268,7 +269,8 @@ internal sealed class MainWindow : Form | ||
| 268 | 269 | if (!Guid.TryParse(downloadID, out _)) throw new InvalidDataException("下载标识无效"); |
| 269 | 270 | var operation = request.Text("action") == "saveBrowserDownload" ? "save" : request.Text("operation"); |
| 270 | 271 | if (operation is not ("save" or "open" or "reveal")) throw new InvalidDataException("下载操作无效"); |
| 271 | 删除: var arguments = new List<string> { "browser-file", "--json", operation, downloadID }; | |
| 272 | 新增: var connection = request.Text("connection_id"); | |
| 273 | 新增: var arguments = new List<string> { "browser-file", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, operation, downloadID }; | |
| 272 | 274 | if (operation == "save") |
| 273 | 275 | { |
| 274 | 276 | var fileName = Path.GetFileName(request.Text("name")); |
| @@ -305,7 +307,8 @@ internal sealed class MainWindow : Form | ||
| 305 | 307 | if (target is not ("browser" or "desktop" or "terminal") || !(target == "terminal" ? System.Text.RegularExpressions.Regex.IsMatch(uploadID, "^[a-f0-9]{16}$") : Guid.TryParse(uploadID, out _))) throw new InvalidDataException("文件上传目标无效"); |
| 306 | 308 | if (!fileSelections.Remove(request.Text("selection"), out var selected) || selected.Expires <= DateTime.UtcNow) |
| 307 | 309 | throw new InvalidDataException("文件选择已过期,请重新复制或选择文件"); |
| 308 | 删除: var arguments = new List<string> { "upload-files", "--json", target, uploadID }; | |
| 310 | 新增: var connection = request.Text("connection_id"); | |
| 311 | 新增: var arguments = new List<string> { "upload-files", "--json", "--connection", string.IsNullOrEmpty(connection) ? "local" : connection, target, uploadID }; | |
| 309 | 312 | arguments.AddRange(selected.Paths); |
| 310 | 313 | var response = await Backend.Json(arguments.ToArray(), lifetime.Token, TimeSpan.FromMinutes(30)); |
| 311 | 314 | if (response.Exit != 0) throw new IOException(response.Data.Text("message")); |
| @@ -33,7 +33,7 @@ internal static class Program | ||
| 33 | 33 | return 1; |
| 34 | 34 | } |
| 35 | 35 | var sid = WindowsIdentity.GetCurrent().User?.Value ?? Environment.UserName; |
| 36 | 删除: var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sid)))[..24]; | |
| 36 | 新增: var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(sid + "\0" + Path.GetFullPath(Backend.Root).TrimEnd(Path.DirectorySeparatorChar).ToUpperInvariant())))[..24]; | |
| 37 | 37 | using var mutex = new Mutex(true, @"Local\Cage-" + key, out var owner); |
| 38 | 38 | if (!owner) |
| 39 | 39 | { |
| @@ -22,6 +22,8 @@ | ||
| 22 | 22 | |---|---| |
| 23 | 23 | | 从源码构建、修改和验证代码 | [参与开发](../CONTRIBUTING.md) | |
| 24 | 24 | | 理解工作台、浏览器与后台的职责 | [工作台设计](design/workbench.md) | |
| 25 | 新增:| 在同一个 Cage 中选择本机或远程,按需启用本机运行环境 | [桌面入口与资源设计](design/desktop-environments.md) | | |
| 26 | 新增:| 将运行环境部署到无 KVM 的 Linux 云服务器,再从桌面连接 | [云端部署设计](design/cloud-deployment.md) · [部署文件](../deploy/cloud/) | | |
| 25 | 27 | | 保存网站账号密码,了解本地加密与填充范围 | [使用密码保险箱](getting-started.md#保存网站账号密码) · [密码保险箱设计](design/password-vault.md) | |
| 26 | 28 | | 将多个订阅用于新建的 Claude Code 终端,了解调度、额度与 Desktop 的适用范围 | [账号面板](design/workbench.md#claude-code-账号面板) · [调研与集成取舍](research/2026-11-04-claude-account-pool.md) | |
| 27 | 29 | | 评估主机输入法、原位拼音与候选窗跟随 | [原生输入法研究](research/2026-11-04-native-ime.md) | |
| @@ -0,0 +1,98 @@ | ||
| 1 | 新增:# 云服务器部署与桌面远程连接 | |
| 2 | 新增: | |
| 3 | 新增:Cage 可以把工作环境放在用户自己的 Linux 服务器上。本地电脑显示同一套工作台,负责键盘、输入法、剪贴板和明确选择的文件传输;服务器运行终端、浏览器、编辑器与 Claude Desktop,并保存项目、账户和网络配置。目标服务器无需 KVM,采用 rootless 容器运行环境。 | |
| 4 | 新增: | |
| 5 | 新增:本文面向维护者,说明本地与云端如何协作、数据保存在哪里,以及必须验证的边界。服务器前提和安装步骤见[部署说明](../../deploy/cloud/README.md)。 | |
| 6 | 新增: | |
| 7 | 新增:## 从本地进入云端工作台 | |
| 8 | 新增: | |
| 9 | 新增:用户在工作台左侧栏打开“SSH”,添加服务器名称、SSH 地址、端口、用户名和本机密钥文件或 SSH agent。自定义安装可在“云端安装路径”填写服务器上的程序和配置路径。首次连接需要核对 SSH 主机指纹;指纹变化时停止连接,要求重新核对。密钥口令只参与本次连接,不保存到主机配置。 | |
| 10 | 新增: | |
| 11 | 新增:SSH 身份验证完成后,客户端检测云端 Cage。已就绪的服务直接连接,已停止且能确认归属的用户服务自动启动。空配置目录须由用户点击「部署并连接」,客户端才上传程序和安装脚本。服务器准备独立的 rootless 引擎,从 Debian 基础镜像安装工作环境。云端就绪后,客户端取得一次性入口,在连接服务内换取会话。工作台随后显示服务器的账户解锁页。打开项目时选择服务器目录;上传仍使用本机文件选择器;下载记录区分服务器文件与已经另存到本机的副本。客户端始终显示当前主机,避免在错误的环境操作。 | |
| 12 | 新增: | |
| 13 | 新增:同一个 Cage 应用提供本机与 SSH 两种运行方式。选择 SSH 时在左栏管理连接,打开应用默认进入本机首页,本机虚拟机由用户手动启动。本机存在运行中的环境或任务时,连接卡片提供停止、保留与取消。进程与数据归属见[桌面入口与资源设计](desktop-environments.md)。SSH 连接由客户端内置的 Go 实现负责,三个平台复用各自的原生窗口、文件选择器、剪贴板和输入法。Windows 需要 WebView2,Linux 需要 GTK/WebKitGTK。 | |
| 14 | 新增: | |
| 15 | 新增:## 整体关系 | |
| 16 | 新增: | |
| 17 | 新增:```mermaid | |
| 18 | 新增:flowchart LR | |
| 19 | 新增: subgraph Client[用户电脑] | |
| 20 | 新增: UI[随客户端安装的工作台] | |
| 21 | 新增: Native[原生窗口与本机文件操作] | |
| 22 | 新增: Connection[本地连接服务] | |
| 23 | 新增: UI --> Connection | |
| 24 | 新增: UI --> Native | |
| 25 | 新增: Native --> Connection | |
| 26 | 新增: end | |
| 27 | 新增: subgraph Server[用户的 Linux 云服务器] | |
| 28 | 新增: Control[常驻 Cage 控制服务] | |
| 29 | 新增: Files[已授权项目目录] | |
| 30 | 新增: Proxy[内置代理与网络门槛] | |
| 31 | 新增: Network[gVisor 用户态网络] | |
| 32 | 新增: Container[独立用户命名空间中的持久容器] | |
| 33 | 新增: Control --> Container | |
| 34 | 新增: Control --> Files | |
| 35 | 新增: Files -->|受目录约束的 SFTP / SSHFS| Container | |
| 36 | 新增: Container -->|唯一 TAP 网络设备| Network | |
| 37 | 新增: Network --> Proxy | |
| 38 | 新增: end | |
| 39 | 新增: Connection -->|SSH 内的 HTTP / WebSocket / SSE| Control | |
| 40 | 新增: Proxy --> Internet[已选择的外部代理] | |
| 41 | 新增:``` | |
| 42 | 新增: | |
| 43 | 新增:云端控制服务保持回环监听,SSH 承担加密连接与主机身份验证。浏览器、桌面、声音和终端复用现有业务协议,不分别开放公网端口。本地只代理业务 API,不加载云端提供的工作台 HTML 或脚本;原生桥仍只接受本地受认证页面的调用。 | |
| 44 | 新增: | |
| 45 | 新增:## 谁保存什么 | |
| 46 | 新增: | |
| 47 | 新增:| 数据或操作 | 本地电脑 | 云服务器 | | |
| 48 | 新增:| --- | --- | --- | | |
| 49 | 新增:| 服务器连接配置 | 私有 `remote-hosts.json`;不保存密钥内容和口令 | 不保存客户端私钥 | | |
| 50 | 新增:| 项目与工具 | 只保存用户明确下载的副本 | 持久项目目录及完整容器文件系统 | | |
| 51 | 新增:| Cage 账户、浏览器资料、保险箱 | 提供解锁与使用界面 | 当前服务器配置的真源 | | |
| 52 | 新增:| 网络节点、出口、DNS、时区和语言 | 显示与操作配置 | 执行配置并负责失败关闭 | | |
| 53 | 新增:| 键盘习惯与界面布局 | 按客户端和远端实例保存 | 不因另一台客户端的键盘改变运行环境 | | |
| 54 | 新增:| 网站上传与本机下载 | 选择文件、读取内容、另存、打开本机记录 | 接收上传内容,提供下载字节 | | |
| 55 | 新增:| 快捷登录 | macOS 钥匙串保存受保护的设备凭据 | 保存对应授权;Windows/Linux 沿用密码入口 | | |
| 56 | 新增: | |
| 57 | 新增:默认服务端配置仍位于 `~/.claude-cage`。统一桌面入口将连接记录放在本机配置目录的 `desktop-entry/` 子目录,首次启动兼容原配置目录和旧开发客户端 `client/` 中的主机列表与云端下载记录。显式配置路径会转为绝对路径,并传给启动和文件助手。容器的完整可写文件系统属于 rootless 引擎的数据目录;图形化部署将引擎数据放在服务端配置目录的 `cloud-host/engine/data/`,手动部署示例使用 `container-engine/data/`,并记录实际存储位置。停止、更新应用和卸载管理程序均不得删除容器、引擎数据、账户或项目。 | |
| 58 | 新增: | |
| 59 | 新增:macOS 的远程快捷登录同时绑定本机连接配置、已经核对的 SSH 指纹、云端实例身份和账户身份。两台服务器即使使用同样的目录,也不会共用本机钥匙串凭据。账户仍沿用每种快捷登录一份授权的现有模型;此功能不引入多租户或团队权限。 | |
| 60 | 新增: | |
| 61 | 新增:## 连接身份与断线行为 | |
| 62 | 新增: | |
| 63 | 新增:本机的一条连接配置由 `host_id` 标识;一份云端持久数据由随机生成并持久保存的 `instance_id` 标识;每次认证连接生成新的 `connection_id`。云端实例身份是 64 位小写十六进制字符串,不随 IP、端口、版本或进程变化。 | |
| 64 | 新增: | |
| 65 | 新增:HTTP、文件助手、WebSocket 和 SSE 都绑定发起时的连接。切换主机或断开后,旧连接的请求被取消或拒绝;文件选择器、输入法与异步响应的迟到结果不能进入新主机。连接失败不会自动改为操作本地 Cage,也不会重放可能已经成功的修改请求。 | |
| 66 | 新增: | |
| 67 | 新增:退出桌面应用或断开 SSH 释放本地连接。隐藏窗口与退出分别处理。云端服务、终端和浏览器继续运行,重连读取已有会话。“锁定 Cage”与“停止环境”仍是明确的云端操作。客户端更新只管理本地程序与连接;服务器更新需要独立保存工作并停止相关服务。 | |
| 68 | 新增: | |
| 69 | 新增:## 无 KVM 容器的隔离方式 | |
| 70 | 新增: | |
| 71 | 新增:服务器需要 cgroup v2、可委派的 CPU/内存/进程数控制器、用户命名空间、FUSE、TUN 和可用的 rootless 容器引擎。当前验收使用独立的 rootless Docker;Podman 的命令适配存在,但没有真实验收时应标为未验证。Docker 的 systemd 容器在自己的 cgroup 命名空间内挂载委派的 cgroup2,不能绑定宿主的整棵 cgroup 文件系统。 | |
| 72 | 新增: | |
| 73 | 新增:工作容器以 `network=none` 创建,不发布容器端口。容器内部的 TAP 助手将以太网帧送到宿主 Cage 网络进程。这个网络进程调用已有的 TCP 目的地限制、代理拨号、DNS 与联网授权门槛;三个钩子均必须存在,不能回落到宿主直连。停止网关后关闭所有出站连接,容器保留离线文件和进程。 | |
| 74 | 新增: | |
| 75 | 新增:TAP 助手、systemd 和 SSHFS 所需权限局限在 rootless 用户命名空间内。容器不使用特权模式,不接入宿主网络或进程命名空间,不获得 Docker socket,也不直接绑定宿主项目目录。项目继续通过现有受目录约束的文件传输服务共享,保留 Git 元数据保护。容器内跳过 zram、内核模块与 swap 初始化,资源限制由服务器的 cgroup 承担。 | |
| 76 | 新增: | |
| 77 | 新增:每次完整启动时,运行环境先在容器自己的挂载命名空间建立共享传播组,再启动项目共享与应用。这样,已经运行的浏览器和编辑器也能看到后来添加的项目;应用的子命名空间只接收项目挂载,不向宿主反向传播。重连不会重设传播组或重启应用。旧容器若仍使用不兼容的私有挂载状态,界面要求先保存工作、停止并重新启动环境,保留原容器和完整文件系统。 | |
| 78 | 新增: | |
| 79 | 新增:CPU、内存与进程数的硬上限设在宿主用户 systemd 管理的父级资源组。容器只能看到自己的子级 cgroup,内部 root 可以管理服务分配,但提高内层上限仍受外部父级限制。启动时核验引擎的 cgroup v2/systemd 模式、实际父级归属和内核读回值;核验失败时不发布环境就绪状态,界面明确显示资源限制尚未通过核验。 | |
| 80 | 新增: | |
| 81 | 新增:容器与云主机共享内核,其隔离强度与原有虚拟机不同。云主机管理员仍能访问此用户的进程和数据;该运行方式不提供互不信任租户之间的安全保证。Cage 的网络检查只报告实际策略与采样证据,不宣称完整的容器逃逸防护审计已经完成。 | |
| 82 | 新增: | |
| 83 | 新增:Docker 普通 bridge 默认提供出网能力;`internal` 网络仍允许访问网关对应的宿主服务,因此两者均不能直接替代 Cage 的受控网络。[Docker bridge](https://docs.docker.com/engine/network/drivers/bridge/) · [internal 网络边界](https://docs.docker.com/reference/cli/docker/network/create/#network-internal-mode---internal)。rootless 资源限制依赖 cgroup v2 与 systemd,部署时必须核对实际生效的限制。[Docker rootless 资源限制](https://docs.docker.com/engine/security/rootless/tips/#limiting-resources)。 | |
| 84 | 新增: | |
| 85 | 新增:## 维护者从哪里修改 | |
| 86 | 新增: | |
| 87 | 新增:| 范围 | 主要入口 | | |
| 88 | 新增:| --- | --- | | |
| 89 | 新增:| 主机配置、SSH、指纹、握手与连接代次 | `internal/remotehost/` | | |
| 90 | 新增:| 本地业务转发、入口身份和文件助手 | `internal/workbench/remote_gateway.go`、`remote_entry.go`、`remote_files.go` | | |
| 91 | 新增:| 容器生命周期、真实状态、TAP、SSH 与受控网络 | `internal/containerenv/` | | |
| 92 | 新增:| 现有工作台的运行方式分派 | `internal/workbench/runtime.go`、`resources.go`、`safety.go` | | |
| 93 | 新增:| 云端 CLI 与脚本导出 | `cmd/cage/container.go`、`cmd/cage/main.go` | | |
| 94 | 新增:| 统一桌面入口、按需本机控制服务、SSH 切换 | `cmd/cage/`、`internal/workbench/desktop_entry.go`、`desktop_gateway.go`、`desktop_local.go` | | |
| 95 | 新增:| 工作环境选择、连接状态与远程目录 | `ui/src/remote-hosts.jsx`、`client-context.mjs`、`project-dialog.jsx` | | |
| 96 | 新增:| 原生文件、登录、更新与数据目录 | `desktop/Cage.swift`、`desktop/AccountDevice.swift`、`desktop/windows/`、`desktop/linux/` | | |
| 97 | 新增: | |
| 98 | 新增:原有本地虚拟机实现继续拥有其磁盘、网络与平台能力。容器使用真实的 `state/container/environment/` 目录、容器标识与运行检查,不生成虚假的 Lima 配置来通过现有判断。 | |
| @@ -6,6 +6,8 @@ | ||
| 6 | 6 | |
| 7 | 7 | 桌面窗口加载 React 工作台。工作台通过本机受认证的 HTTP、WebSocket 和 SSE 接口调用控制服务;控制服务协调同一份配置的持久 VM、项目共享、终端与浏览器。客机中的网页、编辑器和终端进程不获得主机管理接口的凭据。 |
| 8 | 8 | |
| 9 | 新增:远程模式由本地连接服务提供应用自带的工作台,再通过 SSH 转发业务接口。云端控制服务协调持久容器、服务器项目与网络门槛,桌面断开连接后云端任务继续。两端的身份边界见[云端部署设计](cloud-deployment.md)。桌面连接服务的退出条件以及本机控制服务按需启动、按状态回收的方案见[桌面入口与资源设计](desktop-environments.md)。 | |
| 10 | 新增: | |
| 9 | 11 | `internal/workbench/` 内的入口按职责组织,服务接口保持包内可见。当前只有工作台调用这些服务,尚未引入新的界面框架或公共 SDK。 |
| 10 | 12 | |
| 11 | 13 | | 位置 | 负责什么 | 由谁持有资源 | |
| @@ -0,0 +1,58 @@ | ||
| 1 | 新增:# 同一个 Cage 中的本机与远程环境 | |
| 2 | 新增: | |
| 3 | 新增:桌面产品只提供一个 Cage 图标、一套工作台和一条更新路径。远程工作台顶部显示所连接的主机。工作台从左侧栏的「SSH」打开主机列表。从只用云端的电脑打开 Cage,应当可以直接连接服务器,本机虚拟机无需启动。 | |
| 4 | 新增: | |
| 5 | 新增:完整桌面应用默认打开本机工作台,由本机控制服务提供账户和首页。macOS 上已验证连接真实 SSH、释放空闲本机后台和重新进入本机的流程。运行中环境的停止确认、任务状态变化与取消在隔离用例中验证。 | |
| 6 | 新增: | |
| 7 | 新增:## 打开与切换 | |
| 8 | 新增: | |
| 9 | 新增:首次打开直接进入原有本机账户页或本机工作台。打开首页只连接本机控制服务。已停止的虚拟机要等用户点击「启动 Cage 环境」才启动。即使虚拟机一直处于停止状态,用户仍可从侧栏「SSH」添加主机并进入远程工作台。主动断开远程时留在 SSH 主机列表。 | |
| 10 | 新增: | |
| 11 | 新增:进入工作台后,点击侧栏「SSH」,左侧项目栏在原位换为主机列表,右侧仍显示当前工作。用加号新建主机配置,选择已保存的主机后可连接、编辑或移除,返回箭头切回项目栏。本机仍运行时,验证目标成功后弹出确认卡片,显示已知的活动终端或正在执行的操作。提交选择后,终端、项目和浏览器随当前环境切换。远程主机缺少 Cage 服务时,在该主机下显示部署入口或说明。已有部署直接连接。服务器条件见[部署说明](../../deploy/cloud/README.md)。 | |
| 12 | 新增: | |
| 13 | 新增:| 用户操作 | 本机如何处理 | | |
| 14 | 新增:| --- | --- | | |
| 15 | 新增:| 从已停止的本机环境切到远程 | 先验证远端可用。本入口启动的控制服务确认空闲且可以退出后,关闭其监测、代理和进程,进入远程工作台。独立启动的服务沿用自己的生命周期。 | | |
| 16 | 新增:| 连接另一台远程主机时,本机仍在运行 | 远端可用后,在当前页展示本机正在运行的环境、已知任务及终端,提供「停止本机并切换」「保留本机运行并切换」「取消」。停止会结束运行中的程序,用户可以返回保存工作。 | | |
| 17 | 新增:| 保留本机任务,稍后想释放内存 | 窗口持续显示「本机也在运行」,可回到本机继续原终端,也可从这里明确停止本机。只有本机控制服务确认停止并退出后,才显示已释放。 | | |
| 18 | 新增:| 远程断线,或从远程切回本机 | 断线时显示原主机和「重新连接」,云端任务继续。用户明确选本机时才接入本机服务。退出 Cage 释放客户端的 SSH、画面和音频连接。 | | |
| 19 | 新增: | |
| 20 | 新增:运行着的虚拟机本身就需要内存,即使当前没有打开终端,也要让用户决定是否停止。缺少可靠的运行状态时显示「本机状态待确认」。正进行安装、迁移或已有其他调用者占用环境时,由本机控制服务决定是否可以停止,并说明原因。窗口未观察到活动不能作为自动停止的依据。 | |
| 21 | 新增: | |
| 22 | 新增:## 谁负责释放内存 | |
| 23 | 新增: | |
| 24 | 新增:同一个应用包内分开两种进程职责。原生窗口和轻量连接服务随桌面使用,负责环境选择、SSH、原生文件操作和工作台接口转发。本机控制服务随本机工作负载运行,负责账户、虚拟机、终端、挂载、代理和网络检查。保留任务时也保留保护这些任务的网络控制。云端控制服务由服务器独立管理。 | |
| 25 | 新增: | |
| 26 | 新增:```mermaid | |
| 27 | 新增:flowchart LR | |
| 28 | 新增: A["一个 Cage 窗口"] --> B["环境选择与连接服务"] | |
| 29 | 新增: B -->|"选远程 · SSH"| C["服务器上的 Cage"] | |
| 30 | 新增: C --> D["云端容器、项目与网络"] | |
| 31 | 新增: B -->|"选本机 · 受认证的本机连接"| E["本机控制服务"] | |
| 32 | 新增: E --> F["本机虚拟机、项目与代理"] | |
| 33 | 新增:``` | |
| 34 | 新增: | |
| 35 | 新增:打开本机首页时虚拟机保持其原有运行状态。进入工作台后再加载所需界面模块,终端、画面解码和音频按视图开启,并在离开时释放连接与缓冲。原生窗口、系统 WebView、SSH 和正在显示的画面仍会占用本机内存。安装在磁盘上的程序和持久虚拟磁盘,与这些正在占用内存的进程分开管理。首次选本机再检查 Linux 的虚拟化依赖、Windows 的虚拟化能力和 macOS 的本机运行组件。离开本机不卸载组件或删除磁盘。 | |
| 36 | 新增: | |
| 37 | 新增:本机控制服务可以复用现有的私有控制记录、令牌和进程身份检查。连接服务必须有独立的锁、控制记录、认证和退出路径。当前完整服务会启动监测,退出时还会关闭终端、共享和代理,直接用它兼任轻量入口会影响留下的本机任务。[服务初始化](../../internal/workbench/server.go) · [已有后台认证](../../internal/workbench/desktop.go) · [退出与资源回收](../../internal/workbench/lifecycle.go) | |
| 38 | 新增: | |
| 39 | 新增:## 切换过程中保护工作 | |
| 40 | 新增: | |
| 41 | 新增:发起切换时,当前工作台仍拥有原环境。连接服务先验证目标的主机身份、协议和控制服务可达性,候选连接仅可执行握手。验证失败或用户取消就关闭候选连接,原工作台继续使用。云端 Cage 账户的解锁仍属于目标环境。 | |
| 42 | 新增: | |
| 43 | 新增:选择停止本机后,先冻结旧窗口的新业务操作,由原控制服务在操作锁内复核环境身份和任务,执行停止并核对该次作业结果。接着核实该配置的虚拟机、代理与本机控制服务已退出,再切换工作台。停止失败就显示本机实际状态和恢复操作。若本机已成功停止而远程随后断线,显示「本机已停止」和远端重连入口,避免把已完成的停止伪装成一次完整回滚。选择保留时只关闭旧窗口的显示连接,并按现有账户离开规则清理解锁材料,保留本机任务所属的控制服务。 | |
| 44 | 新增: | |
| 45 | 新增:每次成功进入本机或远程都生成新的连接标识。工作台重新绑定终端、下载、上传和输入事件,旧标识的请求失效。特别是从本机切到远程再切回本机,先前文件选择器的回调仍应失效。在远程工作台选择「停止本机环境」须使用明确指向本机配置的管理操作,按本机账户规则授权。本机账户锁定时,卡片提供「返回本机解锁」,取消尚未提交的连接并进入本机。随后用本机控制服务的作业结果更新提示,云端任务继续。 | |
| 46 | 新增: | |
| 47 | 新增:首版每份配置一个活动工作台,再次打开同一配置聚焦已有窗口。三平台均区分窗口隐藏与应用退出。隐藏窗口释放无订阅的画面、音频与解码资源。应用正常退出或窗口进程异常终止时,轻量连接服务关闭 SSH、监听器及附属日志进程后退出。 | |
| 48 | 新增: | |
| 49 | 新增:## 已有用户与验收 | |
| 50 | 新增: | |
| 51 | 新增:沿用 Cage 的应用身份和原本机配置路径,原账户、快捷登录、项目和虚拟磁盘继续由本机控制服务管理。主机列表、上次选择和远程文件的本机保存记录归入口管理。兼容已有完整应用与独立开发客户端的两处记录时,保留主机 UUID、SSH 指纹和云端实例标识。同一主机标识有冲突时,两份记录都列出;来自旧独立入口的冲突项分配新标识,首次连接重新核对指纹。显式指定的配置路径继续限定各自的数据范围。原生快捷登录按环境类型核对账户绑定,单独校验本次连接标识。更新面向同一个桌面应用,当前选中的服务器不会接收桌面更新的停止命令。 | |
| 52 | 新增: | |
| 53 | 新增:实际验收需在 macOS、Windows、Linux 用隔离配置跑四条路径。 | |
| 54 | 新增: | |
| 55 | 新增:1. 本机环境原本已停止。从打开 Cage 到远程编辑文件,再断线重连,记录进程启动事件。确认本机虚拟机全程保持停止,切到远程后释放入口启动的空闲本机控制服务。 | |
| 56 | 新增:2. 本机终端持续写入时切到远程。取消、远程握手失败和「保留运行」都应能回到同一个继续写入的终端。选择「停止并切换」后核对本机进程退出、磁盘和已保存文件保留,云端任务照常运行。 | |
| 57 | 新增:3. 同一窗口走本机 → 远程 → 本机,验证先前延迟的文件操作被拒绝。在远程工作台停止本机后,验证云端终端中的任务继续运行。正常退出和窗口进程异常终止后,只应留下用户明确保留的本机工作负载及其控制服务。 | |
| 58 | 新增:4. 在相同窗口大小、标签数和静置时间下,记录本机首页、远程工作台、本机运行、释放后远程工作台的进程树、内存和空闲 CPU。将窗口与 WebView、连接服务、虚拟化进程、代理分别列出,以各平台合适的内存指标对照。内存收益待实测后公布。 | |
| @@ -68,7 +68,7 @@ Linux 将核心作为普通用户的独立后台进程运行,窗口关闭后 | ||
| 68 | 68 | |
| 69 | 69 | Cage 的环境组件同步、固定工具升级和 Claude Desktop 安装需要在业务网络尚未放行时下载依赖。这些操作使用短时维护通道:固定安装脚本经 SSH 连接主机上的认证代理,再通过当前所选节点访问软件源。维护操作不授予业务联网权限,不解除人工暂停,也不向普通终端注入代理凭据。 |
| 70 | 70 | |
| 71 | 删除:维护代理只接受 Debian、NodeSource、GitHub 发布文件、npm 和 Anthropic 下载服务的指定域名,限定 HTTP 80 与 HTTPS 443;HTTP 请求限于 GET/HEAD,HTTPS 按目标域名限制隧道。它不校验 HTTPS 隧道内的具体请求路径,安装器继续负责软件包签名或摘要校验。临时凭据经 SSH 标准输入传递;任务结束、失败或取消时关闭代理及连接并清理凭据。所选代理不可用时失败,不回退主机直连。此路径由三平台共用的后端和客机安装脚本实现。 | |
| 71 | 新增:维护代理只接受 Debian、NodeSource、GitHub 发布文件、npm、Anthropic 下载服务和 Cage 选用的国内镜像域名。HTTP 请求限于 80 端口的 GET/HEAD,HTTPS 隧道按目标域名和 443 端口授权。APT 按 Debian 官方签名索引中的摘要验证从南大、中科大下载的 Chromium 安全更新包。来自中科大的 code-server 和来自 npmmirror 的 mise 采用 Cage 固定的归档摘要,npmmirror 上的 Claude Code 可执行包采用 npm 官方提供的完整性摘要。各安装器负责校验隧道内下载的内容。临时凭据经 SSH 标准输入传递,任务结束、失败或取消时关闭连接并清理凭据。三个平台共用这条路径,所选代理不可用时下载失败。 | |
| 72 | 72 | |
| 73 | 73 | ## 与本机 Clash 共存 |
| 74 | 74 | |
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | # Cage 工作台 |
| 2 | 2 | |
| 3 | 删除:Cage 面向在本机项目中编码的用户。主界面管理本地项目、网页、终端和文件编辑器;设置页集中管理环境配置。界面采用 Codex 桌面端的侧栏与内容区结构,保留 Cage 的名称和图标,提供单个本地账户,不连接云端账户服务。 | |
| 3 | 新增:Cage 面向在本机或自有服务器项目中工作的用户。主界面管理当前工作环境的项目、网页、终端和文件编辑器;设置页集中管理环境配置。界面采用 Codex 桌面端的侧栏与内容区结构,保留 Cage 的名称和图标。每份环境配置提供一个独立账户,不依赖集中式云端账户服务。 | |
| 4 | 新增: | |
| 5 | 新增:工作台左侧的“SSH”在原位打开主机列表,顶部显示当前环境。远程模式保持相同的工作台,项目目录和应用运行在服务器,本地负责原生输入与明确的文件传输。同一桌面入口的启动顺序和本机内存释放方案见[桌面环境切换设计](desktop-environments.md)。下文的虚拟机、主机共享与本机安装说明描述本地运行方式。无 KVM 容器、SSH 连接与两端数据归属见[云服务器部署](cloud-deployment.md)。 | |
| 4 | 6 | |
| 5 | 7 | ## 本地账户与锁定 |
| 6 | 8 | |
| @@ -179,7 +181,7 @@ Chromium 通过继承的私有调试管道接受标签与导航命令,不开 | ||
| 179 | 181 | |
| 180 | 182 | 日常入口免密。App 持有主机私有启动密钥,通过 localhost 换取有效期 60 秒的一次性入口,再建立 HttpOnly 会话;浏览器和编辑器的内部凭据由工作台管理。链接消费后从地址栏移除,不能重复使用。直接打开一个未认证的控制地址会要求从 App 或启动器进入,不提供人工密码表单。 |
| 181 | 183 | |
| 182 | 删除:虚拟显示由 Xtigervnc 提供,直接监听仅限 guest 私有 Unix socket;X0tigervnc 负责文本剪贴板与显示传输。轻量窗口管理器让 kiosk Chromium 随显示区域调整,不提供桌面壳。工作台通过浏览器控制器调整显示模式,以 2 倍像素呈现;画面连接断开时按有上限的间隔重试,不因此重启 VM 或终端。 | |
| 184 | 新增:虚拟显示由 Xtigervnc 提供,直接监听仅限 guest 私有 Unix socket;X0tigervnc 负责文本剪贴板与显示传输。Chromium 以普通全屏模式运行,隐藏原生浏览器栏并允许用户通过 F12 打开开发者工具;kiosk 模式会禁止开发者工具。轻量窗口管理器让 Chromium 随显示区域调整,不提供桌面壳。工作台通过浏览器控制器调整显示模式,以 2 倍像素呈现;画面连接断开时按有上限的间隔重试,不因此重启 VM 或终端。 | |
| 183 | 185 | |
| 184 | 186 | ### 网页复制按钮 |
| 185 | 187 | |
| @@ -2,7 +2,9 @@ | ||
| 2 | 2 | |
| 3 | 3 | 这份指南从安装应用开始,带你完成代理配置、启动环境和第一次项目操作。Cage 在主机上运行一个持久 Linux 环境,终端、浏览器和编辑器都使用这个环境;日常使用只需打开 Cage 应用。 |
| 4 | 4 | |
| 5 | 删除:## 准备好三样东西 | |
| 5 | 新增:打开 Cage 默认进入本机首页。要使用服务器,在侧栏点「SSH 主机」,用加号保存地址、SSH 用户和密钥,然后点「连接此主机」。首次连接须核对主机指纹。服务器已就绪时直接进入远程工作台,已部署的服务停止时会自动启动。首次安装会显示「部署并连接」,点击后 Cage 通过 SSH 上传部署包并准备容器,本机虚拟机可以一直关闭。如果本机环境正在运行,切换前可选择保留或停止。[支持的服务器和部署条件](../deploy/cloud/README.md) | |
| 6 | 新增: | |
| 7 | 新增:## 使用本机环境前的准备 | |
| 6 | 8 | |
| 7 | 9 | | 需要准备 | 说明 | |
| 8 | 10 | |---|---| |
| @@ -20,12 +22,31 @@ | ||
| 20 | 22 | |---|---| |
| 21 | 23 | | macOS | 下载 Apple Silicon `.dmg`,打开后将 Cage 拖入 Applications(应用程序),再从“应用程序”启动。 | |
| 22 | 24 | | Windows | 下载 x64 `.exe` 安装器,运行后从开始菜单打开 Cage。预览包会标明“未签名”,用于手动安装测试,不能自动安装更新。详见 [Windows 指南](windows.md)。 | |
| 23 | 删除:| Linux | 下载 x86_64 `.deb`,使用 `sudo apt install ./Cage-<版本>-linux-amd64.deb` 安装,再从应用菜单打开 Cage。尚无公开包时按 [Linux 指南](linux.md)构建。 | | |
| 25 | 新增:| Linux | 下载 x86_64 `.deb`,使用 `sudo apt install ./Cage-<版本>-linux-amd64.deb` 安装。缺少 QEMU、GTK、WebKitGTK、OpenSSH 等主机依赖时,APT 会从系统配置的软件源补齐,再从应用菜单打开 Cage。详见 [Linux 指南](linux.md)。 | | |
| 24 | 26 | |
| 25 | 27 | 无需先安装开发工具或 Clash。签名、公证和平台验证情况以该安装包的 Release 说明为准。如果系统拒绝打开,先按[安装问题](troubleshooting.md#下载或安装受阻)核对版本与来源。下述代理、环境和项目操作共用。 |
| 26 | 28 | |
| 27 | 29 | 首次打开时创建一个本地账户:设置用户名和至少 8 个字符的密码。Mac 首次创建时默认勾选“记住登录”,可取消勾选;之后也可在“设置 → 账户”中关闭,关闭后的选择会保留。账户只用于本机 Cage;从左下角头像菜单打开“设置”,即可在“账户”中更换头像、用户名和密码。请妥善保存密码,首版没有在线找回。它不替代 Claude 账号,也不会加密项目文件或整个虚拟磁盘。 |
| 28 | 30 | |
| 31 | 新增:### 选择环境存储位置 | |
| 32 | 新增: | |
| 33 | 新增:Windows 安装器中选择的是程序目录。如果希望镜像下载和虚拟磁盘都放在 D 盘,首次打开工作台后,点击“选择环境存储位置”,选一个专用空文件夹,例如 `D:\CageData`,点击“使用此位置”,再启动环境。macOS 和 Linux 的本机工作台也提供这个入口。默认设置下,虚拟磁盘在用户主目录的 `.claude-cage/state/lima`,镜像下载缓存在系统用户缓存目录下的 `lima`(Windows 为 `%LOCALAPPDATA%\lima`)。 | |
| 34 | 新增: | |
| 35 | 新增:选择支持私有文件权限和稀疏文件的本地磁盘。Windows 可用 NTFS,Linux 可用 ext4、XFS 或 Btrfs。Mac 需要 APFS 卷并启用所有权。使用 Mac 外接盘时,在 Finder 的磁盘“显示简介”中取消“忽略此宗卷的所有权”。 | |
| 36 | 新增: | |
| 37 | 新增:已有环境可在“设置 → 环境与恢复 → 本机环境存储”换盘。先保存终端和编辑器中的工作,选择空文件夹并确认迁移。Cage 会停止环境,复制并校验数据,然后切换目录。手动启动环境,核对原先的文件和登录状态后,可以清理面板显示的旧备份以释放空间。目标盘需有足够的可用空间,使用外接盘时每次启动前都要接回原盘。账户配置保存在原用户目录,共享项目仍从各自的项目文件夹打开。旧的系统用户缓存可能还供其他 Lima 实例使用,迁移会将它留在原处。 | |
| 38 | 新增: | |
| 39 | 新增:### 首次启动下载什么 | |
| 40 | 新增: | |
| 41 | 新增:| 内容 | 来源与用途 | | |
| 42 | 新增:|---|---| | |
| 43 | 新增:| Debian 13 基础镜像 | 按处理器架构下载一份,约 320–325 MiB。优先尝试南大、中科大的镜像,再尝试 Debian 官方源,使用 Cage 固定的 SHA-512 校验。 | | |
| 44 | 新增:| Linux 软件包 | Debian 提供 Chromium、Python、Git、编译工具、远程桌面、字体和系统依赖。常规软件包优先使用国内镜像。安全更新的版本和摘要由 Debian 官方签名索引确定。Chromium 浏览器和公共资源包(chromium-common)优先从南大、中科大下载相同版本,通过 APT 校验后安装。镜像缺包或校验失败会自动尝试下一来源,最后回到官方。 | | |
| 45 | 新增:| Node.js、编辑器与工具管理器 | Node.js 24 通过 NodeSource 安装。mise 优先从 npmmirror 下载上游发布的对应架构可执行包。code-server 优先从中科大下载固定版本的 Debian 安装包。两者都按 Cage 固定的 SHA-256 校验,公共镜像不可用时自动回到各自的 GitHub Release。编辑器还会从 SchemaStore 等来源预取 JSON 校验规则供离线使用,缺少某条规则只影响对应文件的校验。 | | |
| 46 | 新增:| Claude Code | npm 官方注册表提供版本与完整性信息。较大的 Linux 可执行包优先从 npmmirror 下载,使用 npm 官方摘要校验。 | | |
| 47 | 新增: | |
| 48 | 新增:首次安装和工具升级会自动选择下载来源,无需手动补缓存。中科大的 code-server 镜像只保留最近版本;Cage 固定的版本缺失时,会直接从 GitHub 下载该版本。下载仍经过当前选择的 Cage 代理。初始虚拟磁盘的容量上限为 24 GiB,下载流量与实际占用取决于架构、软件包版本和已有缓存。以后启动会复用已安装的环境。需要 Claude Desktop 时,在工作台单独安装,届时才访问 Anthropic 的软件源。 | |
| 49 | 新增: | |
| 29 | 50 | ## 2. 导入并选择代理 |
| 30 | 51 | |
| 31 | 52 | 进入工作台后点击“配置网络与代理”。之后也可以从左下角“设置 → 网络与代理”进入。没有节点时点击“添加来源”,选择一种导入方式: |
| @@ -52,7 +73,7 @@ HTTP/SOCKS5 服务可通过“订阅 → 添加来源 → 手动节点”录入 | ||
| 52 | 73 | |
| 53 | 74 | 如果出现“启动前,保护本机 Git”,请阅读说明,再点击“启用保护并继续”。这会将当前主机用户的一项全局 Git 设置改为 `safe.bareRepository=explicit`,防止 Git 自动识别共享目录中的裸仓库并使用其中的配置。普通 `.git` 项目的提交、拉取、历史和远程地址不受影响;使用裸仓库时需要通过 `--git-dir` 明确指定。设置也会影响本机其他 Git 工具,Cage 仅在你明确确认后修改,重新检查通过后才启动环境。也可以选择“暂不启动”。 |
| 54 | 75 | |
| 55 | 删除:第一次启动会依次准备镜像、安装工具、连接浏览器并执行检查;界面显示当前阶段,“操作详情”提供进一步信息。Git 检查未通过时,按[启动前 Git 检查](troubleshooting.md#启动前的-git-检查未通过)处理,无需重新配置代理。 | |
| 76 | 新增:第一次启动时,工作台会显示当前正在下载或安装的组件。下载 Debian 镜像时可以看到已接收的数据量,服务器提供文件总大小时也会显示百分比。下载 mise、Claude Code 和网页编辑器时,可以看到当前文件已接收的数据量。安装软件包时显示组件名称,点击“操作详情”可查看安装日志。下载中断后,可以点击“继续安装”,Cage 会尝试从已保存的位置续传。环境启动后会连接浏览器并执行网络检查。Git 检查未通过时,按[启动前 Git 检查](troubleshooting.md#启动前的-git-检查未通过)处理,无需重新配置代理。 | |
| 56 | 77 | |
| 57 | 78 | 环境启动后先关闭业务外网,执行 11 项关键检查,覆盖出口、DNS、系统和浏览器配置、文件共享、宿主管理接口、代理故障关闭、UDP、IPv6 与出口规则。首次构建基础镜像没有项目挂载,需要经指定代理下载工具。 |
| 58 | 79 | |
| @@ -1,6 +1,8 @@ | ||
| 1 | 1 | # Linux 安装、使用与验收 |
| 2 | 2 | |
| 3 | 删除:Cage 的 Linux 桌面版面向 Debian 12、Ubuntu 24.04 的 x86_64 电脑,使用 GTK 3 与 WebKitGTK 显示工作台。项目、终端、浏览器、编辑器和内置代理沿用其他平台的操作方式;所有项目共用一个持久 Linux 虚拟机。 | |
| 3 | 新增:Cage 的 Linux 桌面版面向 Debian 12、Ubuntu 24.04 的 x86_64 电脑,使用 GTK 3 与 WebKitGTK 显示工作台。项目、终端、浏览器、编辑器和内置代理沿用其他平台的操作方式。选择本机时,所有本机项目共用一个持久 Linux 虚拟机。 | |
| 4 | 新增: | |
| 5 | 新增:同一个桌面应用也可以从侧栏 SSH 连接已部署 Cage 的服务器。使用远程工作台只需本机图形依赖,本机模式另需 KVM 和虚拟机工具。云服务器的无 KVM 容器部署见[云端部署设计](design/cloud-deployment.md)和[部署说明](../deploy/cloud/README.md)。 | |
| 4 | 6 | |
| 5 | 7 | Linux 支持处于开发验收阶段。安装包及真实测试范围以对应发行说明为准;云服务器中的窗口测试不能代表所有桌面环境、显卡和输入法均已通过验收。ARM64、RPM 发行版及 Wayland 的完整交互尚未验收。 |
| 6 | 8 | |
| @@ -32,7 +34,7 @@ Cage 日常以普通用户运行。不要用 `sudo cage-desktop` 启动工作台 | ||
| 32 | 34 | sudo apt install ./Cage-<版本>-linux-amd64.deb |
| 33 | 35 | ``` |
| 34 | 36 | |
| 35 | 删除:安装器随附 Cage 后台、工作台和 Mihomo 代理核心。APT 从系统软件源安装 WebKitGTK、QEMU、OVMF 虚拟机固件及 OpenSSH 等依赖;无需安装 Go、Node.js、Docker 或其他代理客户端。首次启动环境仍需联网下载 Linux 镜像与客机工具。 | |
| 37 | 新增:安装器随附 Cage 后台、工作台和 Mihomo 代理核心。APT 安装 WebKitGTK 等图形依赖。只连接 SSH 主机时可直接打开应用。要使用本机环境,请再运行 `sudo apt install qemu-system-x86 qemu-utils ovmf openssh-client iproute2 git` 并确认 KVM 可用。首次启动本机环境时会下载 Linux 镜像与客机工具。 | |
| 36 | 38 | |
| 37 | 39 | 从应用菜单打开 **Cage**,也可运行 `cage-desktop`。系统包名和后台命令为 `claude-cage`,避免与发行版自带的同名 Wayland 程序冲突。导入自己的代理、选择节点,再按[开始使用](getting-started.md#2-导入并选择代理)打开项目。项目路径例如 `/home/alice/Projects/demo`,只共享默认工作区与明确选择的目录;项目中的修改和删除会同步到主机。Git 元数据保护沿用现有约束,提交在主机 Git 中完成。 |
| 38 | 40 | |
| @@ -0,0 +1,11 @@ | ||
| 1 | 新增:# Cage v0.1.6-alpha-preview | |
| 2 | 新增: | |
| 3 | 新增:从工作台侧栏的「SSH 主机」可以连接云端 Cage,文件、项目和网络都在所选服务器上。首次部署时核对主机指纹,点击「部署并连接」后,服务器从 Debian 基础镜像安装环境。服务已停止时,重连会启动服务。支持配置了 systemd 用户服务、cgroup v2 和 rootless 容器所需权限的 Linux x86_64 VPS,无需 KVM。 | |
| 4 | 新增: | |
| 5 | 新增:打开 Cage 仍默认进入本机工作台。连接服务器无需先启动本机虚拟机。本机有任务时可以选择继续运行,或在切换前停止它以释放内存。 | |
| 6 | 新增: | |
| 7 | 新增:- 支持选择环境存储位置,改进持久磁盘路径、可用空间检查和迁移。首次安装会显示下载与准备进度,修复弱网下的组件获取和重试。 | |
| 8 | 新增:- 修复 Windows 虚拟机固件查找和 WHPX CPU 配置,改进 Linux 安装依赖检测。 | |
| 9 | 新增:- 改进浏览器开发者工具、下载处理与网络恢复。新的网络授权生效后会清除已解决的监测错误。 | |
| 10 | 新增: | |
| 11 | 新增:macOS 安装包适用于 Apple Silicon。Windows x64 提供需手动安装的未签名预览包。Linux x86_64 使用 DEB 安装或更新。升级前请保存工作并退出 Cage。 | |
| @@ -63,6 +63,6 @@ DMG 提交已 Accepted 时,直接对原 DMG 执行 `xcrun stapler staple`、`x | ||
| 63 | 63 | |
| 64 | 64 | ## 客机工具版本与来源 |
| 65 | 65 | |
| 66 | 删除:`internal/cage/tool-versions.env` 保存 Cage 首装和受管升级使用的最低版本及平台摘要,`guest-tools.sh` 是共用安装器。code-server 固定为 [4.144.0 官方发行版](https://github.com/coder/code-server/releases/tag/v4.144.0),mise 固定为 [2026.10.25 官方发行版](https://github.com/jdx/mise/releases/tag/v2026.10.25);arm64 与 amd64 资产的 SHA-256 来自各项目 GitHub Release API 的资产 `digest` 字段。安装器下载指定版本并核对固定摘要,失败时不运行包安装。Claude Code 使用 npm 的固定版本 `2.1.314`,npm 校验注册表的包完整性。Chromium 从 Debian 的签名软件源更新,采用软件源维护的版本。 | |
| 66 | 新增:`internal/cage/tool-versions.env` 保存 Cage 首装和受管升级使用的最低版本及平台摘要,`guest-tools.sh` 是共用安装器。code-server 固定为 [4.145.0 官方发行版](https://github.com/coder/code-server/releases/tag/v4.145.0),mise 固定为 [2026.10.25 官方发行版](https://github.com/jdx/mise/releases/tag/v2026.10.25);arm64 与 amd64 资产的 SHA-256 来自各项目 GitHub Release API 的资产 `digest` 字段。code-server 首选中科大固定版本的 .deb,缺包时自动回到 GitHub。mise 首选 npmmirror 上的上游平台包,各架构的 npm 归档和 GitHub 发布归档分别固定 SHA-256。调整 mise 版本时,从 npm 官方注册表核对完整性,并比对两个归档内可执行文件的字节。校验失败的文件不能安装。Claude Code 使用 npm 的固定版本 `2.1.314`,npm 校验注册表的包完整性。Chromium 采用 Debian 签名软件源选定的版本。对 Debian 官方安全库中的 chromium 和 chromium-common,先从南大、中科大取同一 .deb,使用官方索引中的 SHA-256 验证,再交给原 APT 操作安装。自定义安全仓库或缺少 python3-apt 的精简环境继续使用原 APT 配置。 | |
| 67 | 67 | |
| 68 | 68 | 升级这些最低版本时,需要同时核对官方资产、更新摘要并验证现有持久环境,不能只改显示版本。受管升级保留较新的已安装版本,不清理用户配置,不重建 Linux 磁盘。组件脚本与工具包分别维护:组件摘要正确只证明 Cage 脚本匹配,不表示所有工具已升级或已完成漏洞审计。 |
| @@ -65,9 +65,11 @@ Cage 需要先选择自己的代理。首次首页点击“配置网络与代理 | ||
| 65 | 65 | |
| 66 | 66 | 固定摘要的 Linux 镜像,以及 code-server、mise、Claude Code 原生包,会保留未完成下载并有限重试。再次启动时会尝试续传;服务器不支持续传时重新下载该文件。完整校验通过后才使用文件。APT 使用自己的软件包缓存与下载重试机制。不要清空个人数据目录或重建账户来处理下载失败。 |
| 67 | 67 | |
| 68 | 新增:镜像和开发工具下载以最后一次收到文件数据的时刻为起点,连续 60 秒没有新数据才视为超时;持续收到数据时继续等待,不设最低下载速度或下载总时限。连接建立仍有独立超时。自动重试用尽后,安装页面保留失败信息,点击“继续安装”可重新尝试,并复用已保存的下载;重复失败后仍可手动继续。 | |
| 69 | 新增: | |
| 68 | 70 | | 操作详情中的错误 | 处理方式 | |
| 69 | 71 | | --- | --- | |
| 70 | 删除:| `Guest DNS could not resolve deb.debian.org` | 客机未能解析 Debian 下载地址。检查“网络与代理”的节点与 DNS 设置,应用后重试。宿主浏览器能上网不足以证明此通路可用;更换 DoH 地址后仍通过同一代理访问。 | | |
| 72 | 新增:| `Guest DNS could not resolve the Debian download sources` | Linux 环境未能解析 Debian 下载源。检查“网络与代理”的节点与 DNS 设置,应用后重试。 | | |
| 71 | 73 | | `Download interrupted; partial data is saved` 或 `partial data retained` | 未完成文件已保留,网络恢复后重试。操作详情会显示重试次数或已保存的字节数。 | |
| 72 | 74 | | `checksum mismatch` | 文件未通过完整性校验,安装被拒绝,损坏的未完成文件会移除。重试会重新下载,不应跳过校验。 | |
| 73 | 75 | | NodeSource 公钥下载失败 | 下载会有限重试,成功前保留已有公钥。持续失败时检查节点到 `deb.nodesource.com` 的连接后重试。 | |
| @@ -6,6 +6,8 @@ Windows 实现和安装器处于开发验收阶段。源码构建成功不代表 | ||
| 6 | 6 | |
| 7 | 7 | 当前开发包已在 Windows 11 Pro 24H2(26100)的 Intel x64 实体机验证安装、覆盖安装、原生工作台、QEMU/WHPX 启动、十一项关键安全检查、中文空格路径共享、终端输入与缩放,以及浏览器和编辑器操作。暂停外网后客机 HTTPS 请求被阻断,重新检测后恢复;配置和项目文件在覆盖安装后保留。卸载保留数据及拒绝未签名更新也已实测。Windows 10 的实机兼容性和可信签名版本之间的完整升级仍待验证。 |
| 8 | 8 | |
| 9 | 新增:Windows 11 x64(内部版本 26200)另已在普通账户的原生工作台验证首次选 D 盘、显示真实下载字节、断点续传、已有环境从 C 盘迁到 D 盘并启动,以及迁移中断恢复。迁移后核对了虚拟机内文件、内置编辑器登录会话和本机测试账户。 | |
| 10 | 新增: | |
| 9 | 11 | ## 安装前准备 |
| 10 | 12 | |
| 11 | 13 | | 项目 | 要求 | |
| @@ -27,7 +29,7 @@ DISM /Online /Enable-Feature /FeatureName:HypervisorPlatform /All | ||
| 27 | 29 | |
| 28 | 30 | 1. 在[项目主页](https://lee-xeo.github.io/Claude-Cage/#download)点击“下载应用”并选择 Windows,核对对应发行条目的 `SHA256SUMS`。签名安装包名为 `Cage-<版本>-windows-amd64-setup.exe`;当前公开预览包名为 `Cage-<版本>-windows-amd64-setup-unsigned.exe`,主页标明“预览版 · 未签名”。未签名包可能触发未知发布者提示,需手动安装和更新。 |
| 29 | 31 | 2. 运行安装程序,选择安装位置。安装器随附 .NET 桌面运行组件、WebView2 安装程序、QEMU、OpenSSH 客户端和代理核心,无需另装 Go、Node.js 或 Clash。 |
| 30 | 删除:3. 从开始菜单启动 Cage,按[开始使用](getting-started.md#2-导入并选择代理)导入并选择代理。首次启动下载 Linux 镜像及开发工具,通过网络检查后即可使用。 | |
| 32 | 新增:3. 从开始菜单启动 Cage。如果 C 盘空间有限,在工作台点击“选择环境存储位置”,选择其他磁盘的专用空文件夹,再导入代理并启动环境。首次下载的 Linux 镜像、后续安装的工具和虚拟磁盘可以一起放在所选盘。已有环境也可以从设置迁移。见[选盘与迁移步骤](getting-started.md#选择环境存储位置)和[首次下载清单](getting-started.md#首次启动下载什么)。 | |
| 31 | 33 | |
| 32 | 34 | 安装器不设置系统代理,不安装 SSH 服务,不把随附工具加入系统 PATH。WebView2 是 Microsoft 提供的系统浏览器运行时,其安装与维护由 Microsoft 安装程序负责。 |
| 33 | 35 | |
| @@ -51,6 +53,8 @@ Windows 快捷键以 `Ctrl` 为主:`Ctrl+O` 打开项目、`Ctrl+T` 新建网 | ||
| 51 | 53 | |
| 52 | 54 | ## 常见启动问题 |
| 53 | 55 | |
| 56 | 新增:本地开发包已适配含中文的安装目录。启动时优先读取随附 QEMU 的 UEFI 固件,无需在用户目录另存副本。在默认虚拟 CPU 配置下,Cage 会向 Windows 虚拟机监控程序平台查询可用指令;Claude Code 需要客机提供 SSE4.2。自行指定了虚拟 CPU 型号的环境仍沿用该设置。这两项修复尚未进入公开的 `v0.1.5-alpha.2` 安装包。 | |
| 57 | 新增: | |
| 54 | 58 | - 提示虚拟化不可用:检查 BIOS/UEFI 的虚拟化开关及 Windows 虚拟机监控程序平台,重启后再试。远程或嵌套虚拟机还需要外层宿主允许嵌套虚拟化。 |
| 55 | 59 | - 提示缺少 WebView2:重新运行完整安装程序。不要从第三方站点下载同名 DLL。 |
| 56 | 60 | - 工作台能打开,环境不能联网:检查 Cage 内是否已选择节点及网络检查结果。Windows 浏览器能联网不表示 Cage 节点已配置。 |
| @@ -23,6 +23,7 @@ require ( | ||
| 23 | 23 | github.com/containerd/continuity v0.5.0 |
| 24 | 24 | github.com/coreos/go-semver v0.3.1 |
| 25 | 25 | github.com/docker/go-units v0.5.0 |
| 26 | 新增: github.com/google/uuid v1.6.0 | |
| 26 | 27 | github.com/lima-vm/lima/v2 v2.0.0 |
| 27 | 28 | github.com/lima-vm/sshocker v0.3.11 |
| 28 | 29 | github.com/mattn/go-isatty v0.0.24 |
| @@ -73,6 +74,7 @@ require ( | ||
| 73 | 74 | github.com/go-ini/ini v1.67.0 // indirect |
| 74 | 75 | github.com/goccy/go-json v0.10.6 // indirect |
| 75 | 76 | github.com/goccy/go-yaml v1.19.2 // indirect |
| 77 | 新增: github.com/godbus/dbus/v5 v5.1.0 // indirect | |
| 76 | 78 | github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 // indirect |
| 77 | 79 | github.com/google/btree v1.1.3 // indirect |
| 78 | 80 | github.com/google/go-cmp v0.7.0 // indirect |
| @@ -124,6 +124,8 @@ github.com/goccy/go-json v0.10.6 h1:p8HrPJzOakx/mn/bQtjgNjdTcN+/S6FcG2CTtQOrHVU= | ||
| 124 | 124 | github.com/goccy/go-json v0.10.6/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= |
| 125 | 125 | github.com/goccy/go-yaml v1.19.2 h1:PmFC1S6h8ljIz6gMRBopkjP1TVT7xuwrButHID66PoM= |
| 126 | 126 | github.com/goccy/go-yaml v1.19.2/go.mod h1:XBurs7gK8ATbW4ZPGKgcbrY1Br56PdM69F7LkFRi1kA= |
| 127 | 新增:github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= | |
| 128 | 新增:github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= | |
| 127 | 129 | github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= |
| 128 | 130 | github.com/golang/groupcache v0.0.0-20200121045136-8c9f03a8e57e/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= |
| 129 | 131 | github.com/golang/groupcache v0.0.0-20241129210726-2c02b8208cf8 h1:f+oWsMOmNPc8JmEHVZIycC7hBoQxHH9pNKQORJNozsQ= |
| @@ -45,6 +45,11 @@ const splitURL = `chrome-extension://${extensionId}/control.html`; | ||
| 45 | 45 | let splitView = null, splitSession, splitOpening, resizeTimer; |
| 46 | 46 | const favicons = new Map(), faviconRequests = new Map(), documents = new Map(); |
| 47 | 47 | |
| 48 | 新增:function isBrowserTab(target) { | |
| 49 | 新增: return target.type === "page" && target.url !== splitURL && | |
| 50 | 新增: !target.url.startsWith("devtools://") && !auditContexts.has(target.browserContextId); | |
| 51 | 新增:} | |
| 52 | 新增: | |
| 48 | 53 | const flags = [ |
| 49 | 54 | `--load-extension=${splitDirectory}`, |
| 50 | 55 | "--user-data-dir=/home/cage-browser/profile", |
| @@ -52,7 +57,9 @@ const flags = [ | ||
| 52 | 57 | // The pipe manages tabs for a human-operated browser. Keep it private while |
| 53 | 58 | // preventing its presence alone from enabling Blink's automation marker. |
| 54 | 59 | "--disable-blink-features=AutomationControlled", |
| 55 | 删除: "--kiosk", | |
| 60 | 新增: // Kiosk mode blocks Chromium's DevTools UI, including F12. Ordinary | |
| 61 | 新增: // fullscreen keeps the guest browser chrome hidden while allowing inspection. | |
| 62 | 新增: "--start-fullscreen", | |
| 56 | 63 | "--no-first-run", |
| 57 | 64 | "--restore-last-session", |
| 58 | 65 | "--no-default-browser-check", |
| @@ -167,7 +174,7 @@ chrome.stdio[4].on("data", (chunk) => { | ||
| 167 | 174 | event.method === "Target.targetInfoChanged" |
| 168 | 175 | ) { |
| 169 | 176 | const t = p.targetInfo; |
| 170 | 删除: if (t.type === "page" && t.url !== splitURL && !auditContexts.has(t.browserContextId)) { | |
| 177 | 新增: if (isBrowserTab(t)) { | |
| 171 | 178 | const fresh = !targets.has(t.targetId); |
| 172 | 179 | targets.set(t.targetId, loginBrowser.tab(t, targets.get(t.targetId))); |
| 173 | 180 | if (fresh) void session(t.targetId).catch(() => {}); |
| @@ -432,7 +439,7 @@ async function restartEditor(workspace) { | ||
| 432 | 439 | async function tabState() { |
| 433 | 440 | const { targetInfos } = await cdp("Target.getTargets"); |
| 434 | 441 | for (const tab of targetInfos) |
| 435 | 删除: if (tab.type === "page" && tab.url !== splitURL && !auditContexts.has(tab.browserContextId)) | |
| 442 | 新增: if (isBrowserTab(tab)) | |
| 436 | 443 | targets.set(tab.targetId, loginBrowser.tab(tab, targets.get(tab.targetId))); |
| 437 | 444 | await refreshNavigation(); |
| 438 | 445 | return publicState(); |
| @@ -763,7 +770,7 @@ server.listen(18500, "127.0.0.1"); | ||
| 763 | 770 | await cdp("Target.setDiscoverTargets", { discover: true }); |
| 764 | 771 | const { targetInfos } = await cdp("Target.getTargets"); |
| 765 | 772 | for (const t of targetInfos) |
| 766 | 删除: if (t.type === "page" && t.url !== splitURL) targets.set(t.targetId, t); | |
| 773 | 新增: if (isBrowserTab(t)) targets.set(t.targetId, t); | |
| 767 | 774 | await cdp("Browser.setDownloadBehavior", { |
| 768 | 775 | behavior: "allowAndName", |
| 769 | 776 | downloadPath, |
| @@ -0,0 +1,111 @@ | ||
| 1 | 新增:"""Prefetch only the Chromium archives selected by the upcoming APT transaction.""" | |
| 2 | 新增: | |
| 3 | 新增:import os | |
| 4 | 新增:import subprocess | |
| 5 | 新增:import sys | |
| 6 | 新增:from pathlib import Path | |
| 7 | 新增:from urllib.parse import urlsplit | |
| 8 | 新增: | |
| 9 | 新增:# Older or minimal container images can still use their normal apt-get install. | |
| 10 | 新增:try: | |
| 11 | 新增: import apt | |
| 12 | 新增: import apt_pkg | |
| 13 | 新增: from apt.progress.base import AcquireProgress | |
| 14 | 新增:except ImportError: | |
| 15 | 新增: print("Using configured APT sources (python3-apt unavailable).") | |
| 16 | 新增: sys.exit(0) | |
| 17 | 新增: | |
| 18 | 新增: | |
| 19 | 新增:MIRRORS = ("https://mirrors.nju.edu.cn/debian-security/", "https://mirrors.ustc.edu.cn/debian-security/") | |
| 20 | 新增:SECURITY_LIST = Path("/etc/apt/mirrors/debian-security.list") | |
| 21 | 新增:OFFICIAL = ("https://deb.debian.org/debian-security/", "https://security.debian.org/debian-security/") | |
| 22 | 新增: | |
| 23 | 新增: | |
| 24 | 新增:def stock_security_uri(uri): | |
| 25 | 新增: # The Debian cloud image delegates this URI to a separate security list. | |
| 26 | 新增: # A customized list or other repository keeps its own download routes. | |
| 27 | 新增: if uri.startswith("mirror+file:" + str(SECURITY_LIST) + "/"): | |
| 28 | 新增: if not SECURITY_LIST.is_file(): | |
| 29 | 新增: return False | |
| 30 | 新增: return SECURITY_LIST.read_text().strip().rstrip("/") + "/" in OFFICIAL | |
| 31 | 新增: site = urlsplit(uri) | |
| 32 | 新增: return (site.scheme in ("http", "https") and site.netloc in ("deb.debian.org", "security.debian.org") | |
| 33 | 新增: and site.path.startswith("/debian-security/")) | |
| 34 | 新增: | |
| 35 | 新增: | |
| 36 | 新增:class Progress(AcquireProgress): | |
| 37 | 新增: def __init__(self, package, size): | |
| 38 | 新增: super().__init__() | |
| 39 | 新增: self.package = package | |
| 40 | 新增: self.size = size | |
| 41 | 新增: self.previous = -1 | |
| 42 | 新增: | |
| 43 | 新增: def report(self, received): | |
| 44 | 新增: if os.environ.get("CAGE_SETUP_PROGRESS") == "1" and received != self.previous: | |
| 45 | 新增: print(f"CAGE_TOOL_BYTES {self.package}.deb {received} {self.size}", flush=True) | |
| 46 | 新增: self.previous = received | |
| 47 | 新增: | |
| 48 | 新增: def pulse(self, owner): | |
| 49 | 新增: self.report(min(int(self.current_bytes), self.size)) | |
| 50 | 新增: return True | |
| 51 | 新增: | |
| 52 | 新增: | |
| 53 | 新增:def fetch(package, version, target): | |
| 54 | 新增: hashes = apt_pkg.HashStringList() | |
| 55 | 新增: hashes.append(apt_pkg.HashString("SHA256", version.sha256)) | |
| 56 | 新增: partial = target.parent / "partial" / (target.name + ".cage") | |
| 57 | 新增: for mirror in MIRRORS: | |
| 58 | 新增: print(f"Downloading {package} {version.version} from {mirror}", flush=True) | |
| 59 | 新增: progress = Progress(package, version.size) | |
| 60 | 新增: acquire = apt_pkg.Acquire(progress) | |
| 61 | 新增: item = apt_pkg.AcquireFile(acquire, mirror + version.filename, hashes, version.size, destfile=str(partial)) | |
| 62 | 新增: acquire.run() | |
| 63 | 新增: if item.complete and item.status == item.STAT_DONE and hashes.verify_file(str(partial)): | |
| 64 | 新增: # APT has verified the official digest. Publish on this volume | |
| 65 | 新增: # under its own archive lock; never expose an unverified .deb. | |
| 66 | 新增: partial.chmod(0o644) | |
| 67 | 新增: partial.replace(target) | |
| 68 | 新增: progress.report(version.size) | |
| 69 | 新增: return | |
| 70 | 新增: if item.status == item.STAT_AUTH_ERROR or item.complete: | |
| 71 | 新增: partial.unlink(missing_ok=True) | |
| 72 | 新增: # APT quarantines responses with an incorrect digest under .FAILED. | |
| 73 | 新增: Path(str(partial) + ".FAILED").unlink(missing_ok=True) | |
| 74 | 新增: print(f"Mirror could not supply the authenticated {package} archive.", flush=True) | |
| 75 | 新增: print(f"Using the official Debian security source for {package}.", flush=True) | |
| 76 | 新增: | |
| 77 | 新增: | |
| 78 | 新增:def prefetch(install_options): | |
| 79 | 新增: # --print-uris resolves the same install/options without installing. Its | |
| 80 | 新增: # destination names include APT's architecture and any escaped epoch. | |
| 81 | 新增: plan = subprocess.check_output( | |
| 82 | 新增: ["apt-get", "--print-uris", "install", "-y", *install_options], text=True | |
| 83 | 新增: ) | |
| 84 | 新增: cache = apt.Cache() | |
| 85 | 新增: archives = Path(apt_pkg.config.find_dir("Dir::Cache::archives")) | |
| 86 | 新增: apt_pkg.config.set("Acquire::Retries", "0") | |
| 87 | 新增: apt_pkg.config.set("Acquire::https::Timeout", "60") | |
| 88 | 新增: with apt_pkg.FileLock(str(archives / "lock")): | |
| 89 | 新增: for line in plan.splitlines(): | |
| 90 | 新增: if not line.startswith("'"): | |
| 91 | 新增: continue | |
| 92 | 新增: uri, filename, *_ = line.split() | |
| 93 | 新增: package = filename.partition("_")[0] | |
| 94 | 新增: if package not in ("chromium", "chromium-common") or Path(filename).name != filename: | |
| 95 | 新增: continue | |
| 96 | 新增: candidate = cache[package].candidate | |
| 97 | 新增: if not candidate or candidate.uri != uri.strip("'") or not stock_security_uri(candidate.uri): | |
| 98 | 新增: continue | |
| 99 | 新增: origin = candidate.origins[0] | |
| 100 | 新增: if not (origin.trusted and origin.origin == "Debian" and origin.label == "Debian-Security" and candidate.sha256): | |
| 101 | 新增: continue | |
| 102 | 新增: fetch(package, candidate, archives / filename) | |
| 103 | 新增: | |
| 104 | 新增: | |
| 105 | 新增:if __name__ == "__main__": | |
| 106 | 新增: try: | |
| 107 | 新增: prefetch(sys.argv[1:]) | |
| 108 | 新增: except (OSError, apt_pkg.Error, subprocess.CalledProcessError) as error: | |
| 109 | 新增: # apt-get owns dependency resolution, the installation, and its error | |
| 110 | 新增: # messages, including in the presence of concurrent package operations. | |
| 111 | 新增: print(f"Using configured APT sources ({type(error).__name__}).", flush=True) | |
| @@ -16,7 +16,7 @@ sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null | ||
| 16 | 16 | temporary=$(mktemp -d) |
| 17 | 17 | trap 'rm -rf "$temporary"' EXIT |
| 18 | 18 | printf '正在验证 Anthropic 安装源…\n' |
| 19 | 删除:curl --proto '=https' --proto-redir '=https' -fSL --connect-timeout 15 --max-time 90 https://downloads.claude.ai/claude-desktop/key.asc -o "$temporary/key.asc" | |
| 19 | 新增:cage_curl_download "$temporary/key.asc" --proto '=https' --proto-redir '=https' -fSL --connect-timeout 15 https://downloads.claude.ai/claude-desktop/key.asc -o "$temporary/key.asc" | |
| 20 | 20 | fingerprint=$(gpg --batch --show-keys --with-colons "$temporary/key.asc" | awk -F: '$1 == "fpr" {print $10; exit}') |
| 21 | 21 | test "$fingerprint" = 31DDDE24DDFAB679F42D7BD2BAA929FF1A7ECACE || { echo 'Anthropic signing key did not match; installation stopped.' >&2; exit 1; } |
| 22 | 22 | sudo install -m 0644 "$temporary/key.asc" /usr/share/keyrings/claude-desktop-archive-keyring.asc |
| @@ -26,7 +26,7 @@ func guestOpenScript() string { | ||
| 26 | 26 | } |
| 27 | 27 | |
| 28 | 28 | func ClaudeDesktopInstallScript() string { |
| 29 | 删除: return claudeDesktopInstall + "\n" + ClaudeDesktopProvisionScript() | |
| 29 | 新增: return ToolInstallPrelude() + claudeDesktopInstall + "\n" + ClaudeDesktopProvisionScript() | |
| 30 | 30 | } |
| 31 | 31 | |
| 32 | 32 | // Provisioning is independent of the browser and never restarts it. Desktop |
| @@ -111,7 +111,7 @@ func TestClaudeDesktopInstallerRejectsUntrustedKey(t *testing.T) { | ||
| 111 | 111 | t.Fatal(err) |
| 112 | 112 | } |
| 113 | 113 | } |
| 114 | 删除: cmd := exec.Command("bash", "-c", claudeDesktopInstall) | |
| 114 | 新增: cmd := exec.Command("bash", "-c", ClaudeDesktopInstallScript()) | |
| 115 | 115 | cmd.Env = append(os.Environ(), "HOME="+dir, "PATH="+dir+":"+os.Getenv("PATH")) |
| 116 | 116 | out, err := cmd.CombinedOutput() |
| 117 | 117 | if err == nil || !strings.Contains(string(out), "signing key did not match") { |
| @@ -0,0 +1,16 @@ | ||
| 1 | 新增:#!/bin/sh | |
| 2 | 新增:# The Debian cloud image uses separate lists for its archive and security | |
| 3 | 新增:# updates. Replace only the stock archive list, preserving customized sources. | |
| 4 | 新增:if [ -f /etc/apt/mirrors/debian.list ] && [ "$(cat /etc/apt/mirrors/debian.list)" = "https://deb.debian.org/debian" ]; then | |
| 5 | 新增: sudo sh -eu <<'CAGE_DEBIAN_MIRRORS' | |
| 6 | 新增:list=/etc/apt/mirrors/debian.list | |
| 7 | 新增:stage=$(mktemp "$list.XXXXXX") | |
| 8 | 新增:trap 'rm -f "$stage"' EXIT | |
| 9 | 新增:printf '%s\tpriority:%s\n' \ | |
| 10 | 新增: https://mirrors.nju.edu.cn/debian 1 \ | |
| 11 | 新增: https://mirrors.ustc.edu.cn/debian 2 \ | |
| 12 | 新增: https://deb.debian.org/debian 3 > "$stage" | |
| 13 | 新增:chmod 0644 "$stage" | |
| 14 | 新增:mv -f "$stage" "$list" | |
| 15 | 新增:CAGE_DEBIAN_MIRRORS | |
| 16 | 新增:fi | |
| @@ -2,8 +2,10 @@ package cage | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "encoding/json" |
| 5 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 5 | 6 | "os" |
| 6 | 7 | "path/filepath" |
| 8 | 新增: "strings" | |
| 7 | 9 | |
| 8 | 10 | "github.com/sylvinus/agent-vm/internal/vmname" |
| 9 | 11 | ) |
| @@ -21,7 +23,7 @@ func EnvironmentDir(profile string) string { | ||
| 21 | 23 | Workspace string `json:"workspace"` |
| 22 | 24 | } |
| 23 | 25 | if b, err := os.ReadFile(filepath.Join(profile, "workbench.json")); err == nil && json.Unmarshal(b, &legacy) == nil && filepath.IsAbs(legacy.Workspace) { |
| 24 | 删除: if _, err := os.Stat(filepath.Join(profile, "state", "lima", vmname.Name(legacy.Workspace), "lima.yaml")); err == nil { | |
| 26 | 新增: if _, err := os.Stat(filepath.Join(profile, "state", "lima", InstanceName(profile, legacy.Workspace), "lima.yaml")); err == nil { | |
| 25 | 27 | return legacy.Workspace |
| 26 | 28 | } |
| 27 | 29 | } |
| @@ -31,3 +33,43 @@ func EnvironmentDir(profile string) string { | ||
| 31 | 33 | } |
| 32 | 34 | return path |
| 33 | 35 | } |
| 36 | 新增: | |
| 37 | 新增:// InstanceName is shared by the controller and each Cage CLI subprocess. | |
| 38 | 新增:// It uses the same spelling as the CLI's AbsDir, including Windows drives. | |
| 39 | 新增:func InstanceName(profile, workspace string) string { | |
| 40 | 新增: home := filepath.Join(profile, "state", "lima") | |
| 41 | 新增: _, err := os.Stat(filepath.Join(profile, locationFile)) | |
| 42 | 新增: logical := err == nil | |
| 43 | 新增: if logical { | |
| 44 | 新增: if real, e := filepath.EvalSymlinks(profile); e == nil { | |
| 45 | 新增: home = filepath.Join(real, "state", "lima") | |
| 46 | 新增: } | |
| 47 | 新增: } | |
| 48 | 新增: dir := paths.Host(filepath.Clean(workspace)) | |
| 49 | 新增: expected := vmname.HomeLimit(home, logical).Name(dir) | |
| 50 | 新增: if _, err := os.Stat(filepath.Join(home, expected)); err == nil { | |
| 51 | 新增: return expected | |
| 52 | 新增: } | |
| 53 | 新增: // A profile restored from a different path can contain an instance made | |
| 54 | 新增: // under a previous socket limit. Only accept a unique, valid truncation | |
| 55 | 新增: // of this exact workspace's name, confirmed by a persistent Lima config. | |
| 56 | 新增: entries, _ := os.ReadDir(home) | |
| 57 | 新增: var old string | |
| 58 | 新增: for _, entry := range entries { | |
| 59 | 新增: name := entry.Name() | |
| 60 | 新增: if !entry.IsDir() || !strings.HasSuffix(name, expected[len(expected)-9:]) || vmname.Limit(len(name)).Name(dir) != name { | |
| 61 | 新增: continue | |
| 62 | 新增: } | |
| 63 | 新增: if _, err := os.Stat(filepath.Join(home, name, "lima.yaml")); err != nil { | |
| 64 | 新增: continue | |
| 65 | 新增: } | |
| 66 | 新增: if old != "" { | |
| 67 | 新增: return expected | |
| 68 | 新增: } | |
| 69 | 新增: old = name | |
| 70 | 新增: } | |
| 71 | 新增: if old != "" { | |
| 72 | 新增: return old | |
| 73 | 新增: } | |
| 74 | 新增: return expected | |
| 75 | 新增:} | |
| @@ -1,23 +1,23 @@ | ||
| 1 | 1 | package cage |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "encoding/json" | |
| 4 | 5 | "os" |
| 5 | 6 | "path/filepath" |
| 6 | 7 | "testing" |
| 7 | 删除: | |
| 8 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 9 | 8 | ) |
| 10 | 9 | |
| 11 | 10 | func TestEnvironmentIdentitySurvivesProjectSelectionAndLegacyUpgrade(t *testing.T) { |
| 12 | 11 | profile := t.TempDir() |
| 13 | 12 | legacy, _ := filepath.EvalSymlinks(t.TempDir()) |
| 14 | 删除: if err := os.WriteFile(filepath.Join(profile, "workbench.json"), []byte(`{"workspace":"`+legacy+`"}`), 0600); err != nil { | |
| 13 | 新增: prefs, _ := json.Marshal(map[string]string{"workspace": legacy}) | |
| 14 | 新增: if err := os.WriteFile(filepath.Join(profile, "workbench.json"), prefs, 0600); err != nil { | |
| 15 | 15 | t.Fatal(err) |
| 16 | 16 | } |
| 17 | 17 | if EnvironmentDir(profile) == legacy { |
| 18 | 18 | t.Fatal("selected project without an existing VM became the environment") |
| 19 | 19 | } |
| 20 | 删除: vmDir := filepath.Join(profile, "state", "lima", vmname.Name(legacy)) | |
| 20 | 新增: vmDir := filepath.Join(profile, "state", "lima", InstanceName(profile, legacy)) | |
| 21 | 21 | if err := os.MkdirAll(vmDir, 0700); err != nil { |
| 22 | 22 | t.Fatal(err) |
| 23 | 23 | } |
| @@ -27,7 +27,8 @@ func TestEnvironmentIdentitySurvivesProjectSelectionAndLegacyUpgrade(t *testing. | ||
| 27 | 27 | if EnvironmentDir(profile) != legacy { |
| 28 | 28 | t.Fatal("existing VM disk was not retained during upgrade") |
| 29 | 29 | } |
| 30 | 删除: if err := os.WriteFile(filepath.Join(profile, "environment.json"), []byte(`{"directory":"`+legacy+`"}`), 0600); err != nil { | |
| 30 | 新增: saved, _ := json.Marshal(map[string]string{"directory": legacy}) | |
| 31 | 新增: if err := os.WriteFile(filepath.Join(profile, "environment.json"), saved, 0600); err != nil { | |
| 31 | 32 | t.Fatal(err) |
| 32 | 33 | } |
| 33 | 34 | if err := os.WriteFile(filepath.Join(profile, "workbench.json"), []byte(`{"workspace":"/different-project"}`), 0600); err != nil { |
| @@ -127,7 +127,7 @@ func StartGateControl(configPath, instanceDir string, gate *EgressGate) (func(), | ||
| 127 | 127 | } else { |
| 128 | 128 | operationError = gate.SyncProxyRevision(cfg) |
| 129 | 129 | if operationError == nil { |
| 130 | 删除: operationError = cfg.RecordRunning(filepath.Dir(filepath.Dir(instanceDir)), filepath.Base(instanceDir)) | |
| 130 | 新增: operationError = cfg.RecordRunningAt(instanceDir) | |
| 131 | 131 | } |
| 132 | 132 | } |
| 133 | 133 | case "check": |
| @@ -1,5 +1,8 @@ | ||
| 1 | 1 | # A small compressed swap area absorbs short allocation bursts while the host |
| 2 | 2 | # adjusts the balloon. It consumes RAM only as used and is bounded at 2 GiB. |
| 3 | 新增:# Containers share the host kernel. Their memory and swap limits belong to | |
| 4 | 新增:# the container cgroup; never load host modules or create swap devices here. | |
| 5 | 新增:if ! systemd-detect-virt --container --quiet; then | |
| 3 | 6 | sudo tee /usr/local/bin/cage-memory-start >/dev/null <<'SCRIPT' |
| 4 | 7 | #!/bin/sh |
| 5 | 8 | set -eu |
| @@ -37,3 +40,4 @@ sudo systemctl enable cage-memory.service >/dev/null | ||
| 37 | 40 | if ! sudo systemctl start cage-memory.service; then |
| 38 | 41 | printf 'Compressed memory reserve unavailable; automatic host memory management remains enabled.\n' >&2 |
| 39 | 42 | fi |
| 43 | 新增:fi | |
| @@ -7,41 +7,124 @@ cage_tool_version() { | ||
| 7 | 7 | awk '$1 ~ /^v?[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$/ && !found { print $1; found=1 }' |
| 8 | 8 | } |
| 9 | 9 | |
| 10 | 新增:# curl flushes every received chunk with --no-buffer. Watch actual file growth, | |
| 11 | 新增:# including single bytes, instead of imposing a minimum speed or total duration. | |
| 12 | 新增:# Keep curl's HTTP status output and exit codes for the caller's retry policy. | |
| 13 | 新增:cage_curl_download() { | |
| 14 | 新增: python3 - "$@" <<'CAGE_DOWNLOAD_IDLE' | |
| 15 | 新增:import os | |
| 16 | 新增:import signal | |
| 17 | 新增:import subprocess | |
| 18 | 新增:import sys | |
| 19 | 新增:import time | |
| 20 | 新增: | |
| 21 | 新增:artifact = sys.argv[1] | |
| 22 | 新增:idle_timeout = 60 | |
| 23 | 新增: | |
| 24 | 新增:def size(): | |
| 25 | 新增: try: | |
| 26 | 新增: return os.stat(artifact).st_size | |
| 27 | 新增: except FileNotFoundError: | |
| 28 | 新增: return 0 | |
| 29 | 新增: | |
| 30 | 新增:def stop(signum, frame): | |
| 31 | 新增: sys.exit(128 + signum) | |
| 32 | 新增: | |
| 33 | 新增:signal.signal(signal.SIGTERM, stop) | |
| 34 | 新增:received = size() | |
| 35 | 新增:name = os.path.basename(artifact).removesuffix(".part").removesuffix(".mirror") | |
| 36 | 新增:show_progress = os.environ.get("CAGE_SETUP_PROGRESS") == "1" | |
| 37 | 新增:def report(count): | |
| 38 | 新增: if show_progress: | |
| 39 | 新增: print(f"CAGE_TOOL_BYTES {name} {count}", file=sys.stderr, flush=True) | |
| 40 | 新增:report(received) | |
| 41 | 新增:last_received = time.monotonic() | |
| 42 | 新增:meter = ["--silent", "--show-error"] if show_progress else [] | |
| 43 | 新增:process = subprocess.Popen(["curl", "--no-buffer", *meter, *sys.argv[2:]], stdin=subprocess.DEVNULL) | |
| 44 | 新增:try: | |
| 45 | 新增: while True: | |
| 46 | 新增: try: | |
| 47 | 新增: status = process.wait(timeout=min(1, idle_timeout)) | |
| 48 | 新增: report(size()) | |
| 49 | 新增: break | |
| 50 | 新增: except subprocess.TimeoutExpired: | |
| 51 | 新增: current = size() | |
| 52 | 新增: if current > received: | |
| 53 | 新增: report(current) | |
| 54 | 新增: last_received = time.monotonic() | |
| 55 | 新增: received = current | |
| 56 | 新增: if time.monotonic() - last_received >= idle_timeout: | |
| 57 | 新增: print("Download received no data for 60 seconds; retrying with saved partial data.", file=sys.stderr) | |
| 58 | 新增: status = 28 | |
| 59 | 新增: break | |
| 60 | 新增:finally: | |
| 61 | 新增: if process.poll() is None: | |
| 62 | 新增: process.terminate() | |
| 63 | 新增: try: | |
| 64 | 新增: process.wait(timeout=5) | |
| 65 | 新增: except subprocess.TimeoutExpired: | |
| 66 | 新增: process.kill() | |
| 67 | 新增: process.wait() | |
| 68 | 新增:sys.exit(status if status >= 0 else 128 - status) | |
| 69 | 新增:CAGE_DOWNLOAD_IDLE | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 10 | 72 | # The caller holds the checksum directory lock. Partial files survive a failed |
| 11 | 73 | # attempt; only a complete checksum-verified artifact is eligible for install. |
| 12 | 74 | cage_download_tool() ( |
| 13 | 75 | set -euo pipefail |
| 14 | 删除: local url="$1" checksum="$2" artifact="$3" hash="${4:-sha256sum}" attempt status http | |
| 76 | 新增: local upstream="$1" checksum="$2" artifact="$3" hash="${4:-sha256sum}" mirror="${5:-}" | |
| 77 | 新增: local attempts="${6:-4}" attempt status http url part host | |
| 15 | 78 | if [ -f "$artifact" ]; then |
| 16 | 79 | if printf '%s %s\n' "$checksum" "$artifact" | "$hash" --check --status; then return 0; fi |
| 17 | 80 | rm -f "$artifact" |
| 18 | 81 | fi |
| 19 | 删除: for attempt in 1 2 3 4; do | |
| 20 | 删除: printf 'Downloading %s (attempt %s/4; resume from %s bytes).\n' "${artifact##*/}" "$attempt" "$(if [ -f "$artifact.part" ]; then wc -c < "$artifact.part"; else echo 0; fi)" | |
| 21 | 删除: if http="$(curl --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location \ | |
| 22 | 删除: --connect-timeout 15 --max-time 1800 --speed-limit 1024 --speed-time 60 \ | |
| 23 | 删除: --continue-at - --write-out '%{http_code}' "$url" -o "$artifact.part" </dev/null)"; then | |
| 82 | 新增: for ((attempt=1; attempt<=attempts; attempt++)); do | |
| 83 | 新增: url="$upstream" | |
| 84 | 新增: part="$artifact.part" | |
| 85 | 新增: if [ "$attempt" = 1 ] && [ -n "$mirror" ] && [ ! -s "$part" ]; then | |
| 86 | 新增: url="$mirror" | |
| 87 | 新增: part="$artifact.mirror.part" | |
| 88 | 新增: fi | |
| 89 | 新增: host="${url#https://}" | |
| 90 | 新增: printf 'Downloading %s from %s (attempt %s/%s; resume from %s bytes).\n' "${artifact##*/}" "${host%%/*}" "$attempt" "$attempts" "$(if [ -f "$part" ]; then wc -c < "$part"; else echo 0; fi)" | |
| 91 | 新增: if http="$(cage_curl_download "$part" --proto '=https' --proto-redir '=https' --tlsv1.2 --fail --location \ | |
| 92 | 新增: --connect-timeout 15 \ | |
| 93 | 新增: --continue-at - --write-out '%{http_code}' "$url" -o "$part" </dev/null)"; then | |
| 24 | 94 | status=0 |
| 25 | 95 | else |
| 26 | 96 | status=$? |
| 27 | 97 | fi |
| 28 | 98 | # A previous attempt can have received the whole body before cancellation. |
| 29 | 99 | if [ "$status" = 0 ] || [ "$http" = 416 ]; then |
| 30 | 删除: if printf '%s %s\n' "$checksum" "$artifact.part" | "$hash" --check --status; then | |
| 31 | 删除: mv -f "$artifact.part" "$artifact" | |
| 100 | 新增: if printf '%s %s\n' "$checksum" "$part" | "$hash" --check --status; then | |
| 101 | 新增: mv -f "$part" "$artifact" || return 1 | |
| 102 | 新增: rm -f "$artifact.mirror.part" | |
| 32 | 103 | return 0 |
| 33 | 104 | fi |
| 34 | 删除: rm -f "$artifact.part" | |
| 105 | 新增: rm -f "$part" | |
| 106 | 新增: if [ "$url" != "$upstream" ]; then | |
| 107 | 新增: echo 'Mirror checksum mismatch; retrying from the official source.' >&2 | |
| 108 | 新增: continue | |
| 109 | 新增: fi | |
| 35 | 110 | echo 'Tool checksum mismatch; installation refused. Retry downloads a fresh copy.' >&2 |
| 36 | 111 | return 1 |
| 37 | 112 | fi |
| 113 | 新增: if [ "$url" != "$upstream" ]; then | |
| 114 | 新增: if [ "$http" = 404 ]; then | |
| 115 | 新增: echo 'This version is missing on the mirror; trying the official source.' >&2 | |
| 116 | 新增: else | |
| 117 | 新增: echo 'Mirror download interrupted; trying the official source.' >&2 | |
| 118 | 新增: fi | |
| 119 | 新增: continue | |
| 120 | 新增: fi | |
| 38 | 121 | case "$status" in |
| 39 | 122 | 33|36) rm -f "$artifact.part" ;; # Server cannot resume: next attempt starts at zero. |
| 40 | 123 | 5|6|7|18|28|35|52|55|56|92) ;; # Connection, partial body, TLS EOF or timeout. |
| 41 | 124 | 22) case "$http" in 408|429|500|502|503|504) ;; *) return "$status" ;; esac ;; |
| 42 | 125 | *) return "$status" ;; |
| 43 | 126 | esac |
| 44 | 删除: if [ "$attempt" != 4 ]; then sleep "$attempt"; fi | |
| 127 | 新增: if [ "$attempt" != "$attempts" ]; then sleep "$attempt"; fi | |
| 45 | 128 | done |
| 46 | 129 | echo 'Download interrupted; partial data is saved. Retry setup to continue.' >&2 |
| 47 | 130 | return "$status" |
| @@ -63,13 +146,49 @@ cage_cache_claude() ( | ||
| 63 | 146 | mkdir -p "$cache" |
| 64 | 147 | exec 9>"$cache/lock" |
| 65 | 148 | flock -w 60 9 |
| 66 | 删除: cage_download_tool "$url" "$checksum" "$cache/$package.tgz" sha512sum | |
| 149 | 新增: local mirror="https://cdn.npmmirror.com/packages/%40anthropic-ai/$package/$wanted/$package-$wanted.tgz" | |
| 150 | 新增: cage_download_tool "$url" "$checksum" "$cache/$package.tgz" sha512sum "$mirror" | |
| 67 | 151 | npm cache add --offline --ignore-scripts "$cache/$package.tgz" </dev/null |
| 68 | 152 | ) |
| 69 | 153 | |
| 154 | 新增:# Both archives contain the same release executable, but npm and GitHub | |
| 155 | 新增:# package it differently. Keep their partials and checksum checks separate. | |
| 156 | 新增:# The caller holds the original release's cache lock for the whole install. | |
| 157 | 新增:cage_install_mise() ( | |
| 158 | 新增: set -euo pipefail | |
| 159 | 新增: local wanted="$1" arch="$2" release_url="$3" release_sum="$4" cache="$5" | |
| 160 | 新增: local archive="$cache/mise.tar.gz" member=mise/bin/mise npm_arch=x64 | |
| 161 | 新增: local npm_sum="$CAGE_MISE_NPM_AMD64_SHA256" npm_url npm_archive stage | |
| 162 | 新增: if [ "$arch" = arm64 ]; then | |
| 163 | 新增: npm_arch=arm64 | |
| 164 | 新增: npm_sum="$CAGE_MISE_NPM_ARM64_SHA256" | |
| 165 | 新增: fi | |
| 166 | 新增: if [ ! -f "$archive" ] && [ ! -s "$archive.part" ]; then | |
| 167 | 新增: npm_url="https://cdn.npmmirror.com/packages/%40jdxcode/mise-linux-$npm_arch/$wanted/mise-linux-$npm_arch-$wanted.tgz" | |
| 168 | 新增: npm_archive="$cache/$npm_sum/mise.tar.gz" | |
| 169 | 新增: mkdir -p "${npm_archive%/*}" | |
| 170 | 新增: if cage_download_tool "$npm_url" "$npm_sum" "$npm_archive" sha256sum '' 1; then | |
| 171 | 新增: archive="$npm_archive" | |
| 172 | 新增: member=package/bin/mise | |
| 173 | 新增: else | |
| 174 | 新增: echo 'mise mirror unavailable or failed verification; trying the official release.' >&2 | |
| 175 | 新增: fi | |
| 176 | 新增: fi | |
| 177 | 新增: if [ "$member" = mise/bin/mise ]; then | |
| 178 | 新增: cage_download_tool "$release_url" "$release_sum" "$archive" || return $? | |
| 179 | 新增: fi | |
| 180 | 新增: if [ "${CAGE_SETUP_PROGRESS:-}" = 1 ]; then echo 'Installing mise...'; fi | |
| 181 | 新增: mkdir -p "$HOME/.local/bin" | |
| 182 | 新增: stage="$(mktemp "$HOME/.local/bin/.mise-new-XXXXXX")" | |
| 183 | 新增: trap 'rm -f "$stage"' EXIT | |
| 184 | 新增: tar -xOzf "$archive" "$member" >"$stage" || return $? | |
| 185 | 新增: chmod 0755 "$stage" || return $? | |
| 186 | 新增: mv -f "$stage" "$HOME/.local/bin/mise" | |
| 187 | 新增:) | |
| 188 | 新增: | |
| 70 | 189 | cage_install_tool() ( |
| 71 | 190 | set -euo pipefail |
| 72 | 删除: local tool="$1" arch current='' wanted url checksum artifact | |
| 191 | 新增: local tool="$1" arch current='' wanted url checksum artifact mirror='' | |
| 73 | 192 | arch="$(dpkg --print-architecture)" |
| 74 | 193 | case "$arch" in arm64|amd64) ;; *) echo 'Cage tool packages support arm64 and amd64.' >&2; exit 1 ;; esac |
| 75 | 194 | case "$tool" in |
| @@ -78,16 +197,21 @@ cage_install_tool() ( | ||
| 78 | 197 | if command -v code-server >/dev/null; then current="$(code-server --version | cage_tool_version)" || current=''; fi |
| 79 | 198 | url="https://github.com/coder/code-server/releases/download/v$wanted/code-server_${wanted}_${arch}.deb" |
| 80 | 199 | if [ "$arch" = arm64 ]; then checksum="$CAGE_CODE_SERVER_ARM64_SHA256"; else checksum="$CAGE_CODE_SERVER_AMD64_SHA256"; fi |
| 200 | 新增: mirror="https://mirrors.ustc.edu.cn/github-release/coder/code-server/v$wanted/code-server_${wanted}_${arch}.deb" | |
| 81 | 201 | artifact=code-server.deb |
| 82 | 202 | ;; |
| 83 | 203 | mise) |
| 84 | 204 | wanted="$CAGE_MISE_VERSION" |
| 85 | 删除: if [ -x "$HOME/.local/bin/mise" ]; then current="$("$HOME/.local/bin/mise" --version | cage_tool_version)" || current=''; fi | |
| 205 | 新增: if [ -x "$HOME/.local/bin/mise" ]; then current="$(MISE_DISABLE_UPDATE_WARNING=1 "$HOME/.local/bin/mise" --version | cage_tool_version)" || current=''; fi | |
| 86 | 206 | if [ "$arch" = arm64 ]; then checksum="$CAGE_MISE_ARM64_SHA256"; else checksum="$CAGE_MISE_AMD64_SHA256"; fi |
| 87 | 207 | url="https://github.com/jdx/mise/releases/download/v$wanted/mise-v$wanted-linux-$(if [ "$arch" = arm64 ]; then echo arm64; else echo x64; fi).tar.gz" |
| 88 | 208 | artifact=mise.tar.gz |
| 89 | 209 | ;; |
| 90 | 210 | claude) |
| 211 | 新增: if [ "$arch" = amd64 ] && [ -r /proc/cpuinfo ] && ! grep -Eq '^flags[[:space:]]*:.*[[:space:]]sse4_2([[:space:]]|$)' /proc/cpuinfo; then | |
| 212 | 新增: echo 'Claude Code 需要 SSE4.2 指令。当前 x86_64 客机未提供该指令,请检查宿主 CPU、虚拟化平台和虚拟 CPU 配置后重启环境。' >&2 | |
| 213 | 新增: exit 1 | |
| 214 | 新增: fi | |
| 91 | 215 | wanted="$CAGE_CLAUDE_VERSION" |
| 92 | 216 | if command -v claude >/dev/null; then current="$(DISABLE_AUTOUPDATER=1 claude --version | cage_tool_version)" || current=''; fi |
| 93 | 217 | ;; |
| @@ -100,23 +224,20 @@ cage_install_tool() ( | ||
| 100 | 224 | if [ "$tool" = claude ]; then |
| 101 | 225 | export npm_config_fetch_retries=3 npm_config_fetch_timeout=120000 |
| 102 | 226 | cage_cache_claude "$arch" "$wanted" |
| 227 | 新增: if [ "${CAGE_SETUP_PROGRESS:-}" = 1 ]; then echo "Installing Claude Code..."; fi | |
| 103 | 228 | npm install --registry=https://registry.npmjs.org --prefix "$HOME/.local" --global "@anthropic-ai/claude-code@$wanted" </dev/null |
| 104 | 229 | exit 0 |
| 105 | 230 | fi |
| 106 | 删除: local cache="$HOME/.cache/cage/downloads/$checksum" stage | |
| 231 | 新增: local cache="$HOME/.cache/cage/downloads/$checksum" | |
| 107 | 232 | mkdir -p "$cache" |
| 108 | 233 | # First setup and maintenance can both reach this helper in a Linux guest. |
| 109 | 234 | exec 9>"$cache/lock" |
| 110 | 235 | flock -w 60 9 |
| 111 | 删除: cage_download_tool "$url" "$checksum" "$cache/$artifact" | |
| 112 | 删除: stage="$(mktemp -d)" | |
| 113 | 删除: trap 'rm -rf "$stage"' EXIT | |
| 114 | 删除: if [ "$tool" = code-server ]; then | |
| 115 | 删除: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o Acquire::Retries=3 install -y --no-install-recommends "$cache/$artifact" </dev/null | |
| 116 | 删除: else | |
| 117 | 删除: tar -xzf "$cache/$artifact" -C "$stage" | |
| 118 | 删除: mkdir -p "$HOME/.local/bin" | |
| 119 | 删除: install -m 0755 "$stage/mise/bin/mise" "$HOME/.local/bin/.mise-new" | |
| 120 | 删除: mv -f "$HOME/.local/bin/.mise-new" "$HOME/.local/bin/mise" | |
| 236 | 新增: if [ "$tool" = mise ]; then | |
| 237 | 新增: cage_install_mise "$wanted" "$arch" "$url" "$checksum" "$cache" | |
| 238 | 新增: exit $? | |
| 121 | 239 | fi |
| 240 | 新增: cage_download_tool "$url" "$checksum" "$cache/$artifact" sha256sum "$mirror" | |
| 241 | 新增: if [ "${CAGE_SETUP_PROGRESS:-}" = 1 ]; then printf 'Installing %s...\n' "$tool"; fi | |
| 242 | 新增: sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get -o Acquire::Retries=3 install -y --no-install-recommends "$cache/$artifact" </dev/null | |
| 122 | 243 | ) |
| @@ -158,7 +158,24 @@ var toolVersions string | ||
| 158 | 158 | //go:embed guest-tools.sh |
| 159 | 159 | var guestTools string |
| 160 | 160 | |
| 161 | 删除:func ToolInstallPrelude() string { return toolVersions + "\n" + guestTools + "\n" } | |
| 161 | 新增://go:embed debian-mirrors.sh | |
| 162 | 新增:var DebianMirrorsScript string | |
| 163 | 新增: | |
| 164 | 新增://go:embed chromium-download.py | |
| 165 | 新增:var chromiumDownload string | |
| 166 | 新增: | |
| 167 | 新增:func ToolInstallPrelude() string { | |
| 168 | 新增: return toolVersions + "\n" + guestTools + ` | |
| 169 | 新增:cage_cache_chromium() { | |
| 170 | 新增: local status=0 | |
| 171 | 新增: sudo env APT_CONFIG="${CAGE_APT_CONFIG:-}" CAGE_SETUP_PROGRESS="${CAGE_SETUP_PROGRESS:-}" /usr/bin/python3 -I - "$@" <<'CAGE_CHROMIUM_DOWNLOAD' || status=$? | |
| 172 | 新增:` + chromiumDownload + ` | |
| 173 | 新增:CAGE_CHROMIUM_DOWNLOAD | |
| 174 | 新增: if (( status >= 128 )); then return "$status"; fi | |
| 175 | 新增: if (( status != 0 )); then echo 'Chromium mirror prefetch unavailable; continuing with APT.' >&2; fi | |
| 176 | 新增:} | |
| 177 | 新增:` | |
| 178 | 新增:} | |
| 162 | 179 | |
| 163 | 180 | func RequiredToolVersions() map[string]string { |
| 164 | 181 | result := map[string]string{"chromium": "Debian security repository"} |
| @@ -183,6 +200,7 @@ func ToolsUpdateScript() string { | ||
| 183 | 200 | return "set -euo pipefail\nexport PATH=\"$HOME/.local/bin:$PATH\"\n" + ToolInstallPrelude() + ` |
| 184 | 201 | sudo env DEBIAN_FRONTEND=noninteractive dpkg --configure -a </dev/null |
| 185 | 202 | sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get update </dev/null |
| 203 | 新增:cage_cache_chromium --only-upgrade chromium | |
| 186 | 204 | sudo env DEBIAN_FRONTEND=noninteractive APT_CONFIG="${CAGE_APT_CONFIG:-/dev/null}" apt-get install -y --only-upgrade chromium </dev/null |
| 187 | 205 | cage_install_tool mise |
| 188 | 206 | cage_install_tool code-server |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "os/exec" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func TestContainerMemorySetupNeverInvokesKernelOrSwapCommands(t *testing.T) { | |
| 12 | 新增: bash, err := exec.LookPath("bash") | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: t.Skip("bash is unavailable") | |
| 15 | 新增: } | |
| 16 | 新增: directory := t.TempDir() | |
| 17 | 新增: // Every host-changing operation in this script requires sudo. A container | |
| 18 | 新增: // detection must skip the entire block, including installation of services. | |
| 19 | 新增: for name, body := range map[string]string{"systemd-detect-virt": "#!/bin/sh\nexit 0\n", "sudo": "#!/bin/sh\necho unexpected-host-operation >&2\nexit 91\n"} { | |
| 20 | 新增: if err := os.WriteFile(filepath.Join(directory, name), []byte(body), 0700); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: } | |
| 24 | 新增: cmd := exec.Command(bash, "-e", "-s") | |
| 25 | 新增: cmd.Env = []string{"PATH=" + directory} | |
| 26 | 新增: cmd.Stdin = strings.NewReader(guestMemory) | |
| 27 | 新增: if output, err := cmd.CombinedOutput(); err != nil || len(output) > 0 { | |
| 28 | 新增: t.Fatalf("container touched kernel setup: %v %s", err, output) | |
| 29 | 新增: } | |
| 30 | 新增:} | |
| @@ -0,0 +1,131 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "archive/tar" | |
| 5 | 新增: "bytes" | |
| 6 | 新增: "compress/gzip" | |
| 7 | 新增: "crypto/sha256" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增: "testing" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func miseArchive(t *testing.T, member, content string) ([]byte, string) { | |
| 17 | 新增: t.Helper() | |
| 18 | 新增: var buffer bytes.Buffer | |
| 19 | 新增: z := gzip.NewWriter(&buffer) | |
| 20 | 新增: w := tar.NewWriter(z) | |
| 21 | 新增: if err := w.WriteHeader(&tar.Header{Name: member, Mode: 0755, Size: int64(len(content))}); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: if _, err := w.Write([]byte(content)); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: if err := w.Close(); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: if err := z.Close(); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: data := buffer.Bytes() | |
| 34 | 新增: return data, fmt.Sprintf("%x", sha256.Sum256(data)) | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func TestMiseArchivesHaveIndependentPinsResumeAndFallback(t *testing.T) { | |
| 38 | 新增: for _, tc := range []struct{ arch, mode, sources string }{ | |
| 39 | 新增: {"amd64", "fresh", "npm:0"}, {"arm64", "fresh", "npm:0"}, | |
| 40 | 新增: {"amd64", "bad-mirror", "npm:0 release:0"}, | |
| 41 | 新增: {"arm64", "cached-release", ""}, {"amd64", "partial-release", "release:7"}, {"arm64", "partial-npm", "npm:7"}, | |
| 42 | 新增: {"amd64", "both-corrupt", "npm:0 release:0"}, | |
| 43 | 新增: } { | |
| 44 | 新增: t.Run(tc.arch+"/"+tc.mode, func(t *testing.T) { | |
| 45 | 新增: dir := t.TempDir() | |
| 46 | 新增: binary := "#!/bin/sh\necho 2026.10.25\n# " + tc.arch + "\n" | |
| 47 | 新增: npm, nh := miseArchive(t, "package/bin/mise", binary) | |
| 48 | 新增: release, rh := miseArchive(t, "mise/bin/mise", binary) | |
| 49 | 新增: cache := filepath.Join(dir, ".cache", "cage", "downloads", rh) | |
| 50 | 新增: write := func(path string, data []byte, mode os.FileMode) { | |
| 51 | 新增: t.Helper() | |
| 52 | 新增: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: if err := os.WriteFile(path, data, mode); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: } | |
| 59 | 新增: write(filepath.Join(dir, "npm-input"), npm, 0600) | |
| 60 | 新增: write(filepath.Join(dir, "release-input"), release, 0600) | |
| 61 | 新增: switch tc.mode { | |
| 62 | 新增: case "cached-release": | |
| 63 | 新增: write(filepath.Join(cache, "mise.tar.gz"), release, 0600) | |
| 64 | 新增: case "partial-release": | |
| 65 | 新增: write(filepath.Join(cache, "mise.tar.gz.part"), release[:7], 0600) | |
| 66 | 新增: case "partial-npm": | |
| 67 | 新增: write(filepath.Join(cache, nh, "mise.tar.gz.part"), npm[:7], 0600) | |
| 68 | 新增: } | |
| 69 | 新增: if _, err := exec.LookPath("shasum"); err == nil { | |
| 70 | 新增: write(filepath.Join(dir, "sha256sum"), []byte("#!/bin/sh\nexec shasum -a 256 \"$@\"\n"), 0755) | |
| 71 | 新增: } else if _, err = exec.LookPath("sha256sum"); err != nil { | |
| 72 | 新增: t.Skip("SHA-256 command unavailable") | |
| 73 | 新增: } | |
| 74 | 新增: for name, cmd := range map[string]string{ | |
| 75 | 新增: "flock": "exit 0", | |
| 76 | 新增: "dpkg": "if [ \"$1\" = --print-architecture ]; then echo \"$TEST_ARCH\"; else test \"$2\" = \"$4\"; fi", | |
| 77 | 新增: "curl": `set -eu | |
| 78 | 新增:while [ "$#" -gt 0 ]; do | |
| 79 | 新增: case "$1" in | |
| 80 | 新增: "https://cdn.npmmirror.com/packages/%40jdxcode/mise-linux-$NPM_ARCH/2026.10.25/mise-linux-$NPM_ARCH-2026.10.25.tgz") src=npm ;; | |
| 81 | 新增: "https://github.com/jdx/mise/releases/download/v2026.10.25/mise-v2026.10.25-linux-$NPM_ARCH.tar.gz") src=release ;; | |
| 82 | 新增: -o) shift; out=$1 ;; | |
| 83 | 新增: esac | |
| 84 | 新增: shift | |
| 85 | 新增:done | |
| 86 | 新增:n=0 | |
| 87 | 新增:if [ -f "$out" ]; then n=$(wc -c <"$out" | tr -d ' '); fi | |
| 88 | 新增:printf '%s:%s\n' "$src" "$n" >> "$HOME/sources" | |
| 89 | 新增:if [ "$TEST_MODE" = both-corrupt ] || { [ "$src" = npm ] && [ "$TEST_MODE" = bad-mirror ]; }; then | |
| 90 | 新增: printf wrong-archive >"$out" | |
| 91 | 新增:else | |
| 92 | 新增: dd if="$HOME/$src-input" bs=1 skip="$n" 2>/dev/null >>"$out" | |
| 93 | 新增:fi | |
| 94 | 新增:printf 200`, | |
| 95 | 新增: } { | |
| 96 | 新增: write(filepath.Join(dir, name), []byte("#!/bin/sh\n"+cmd+"\n"), 0755) | |
| 97 | 新增: } | |
| 98 | 新增: npmArch := tc.arch | |
| 99 | 新增: if npmArch == "amd64" { | |
| 100 | 新增: npmArch = "x64" | |
| 101 | 新增: } | |
| 102 | 新增: script := ToolInstallPrelude() + fmt.Sprintf("\nCAGE_MISE_%s_SHA256=%s\nCAGE_MISE_NPM_%s_SHA256=%s\n", strings.ToUpper(tc.arch), rh, strings.ToUpper(tc.arch), nh) + "cage_install_tool mise" | |
| 103 | 新增: run := func() ([]byte, error) { | |
| 104 | 新增: cmd := exec.CommandContext(t.Context(), "bash", "-c", script) | |
| 105 | 新增: cmd.Env = append(os.Environ(), "HOME="+dir, "PATH="+dir+":"+os.Getenv("PATH"), "NPM_ARCH="+npmArch, "TEST_ARCH="+tc.arch, "TEST_MODE="+tc.mode, "CAGE_SETUP_PROGRESS=1") | |
| 106 | 新增: return cmd.CombinedOutput() | |
| 107 | 新增: } | |
| 108 | 新增: out, err := run() | |
| 109 | 新增: got, fileErr := os.ReadFile(filepath.Join(dir, ".local", "bin", "mise")) | |
| 110 | 新增: if tc.mode == "both-corrupt" { | |
| 111 | 新增: if err == nil || !os.IsNotExist(fileErr) { | |
| 112 | 新增: t.Fatalf("corrupted tool installed: %s", out) | |
| 113 | 新增: } | |
| 114 | 新增: } else { | |
| 115 | 新增: if err != nil || fileErr != nil || string(got) != binary { | |
| 116 | 新增: t.Fatalf("mise installation: %v %v %s", err, fileErr, out) | |
| 117 | 新增: } | |
| 118 | 新增: if tc.sources != "" && !strings.Contains(string(out), "CAGE_TOOL_BYTES mise.tar.gz ") { | |
| 119 | 新增: t.Fatalf("missing byte progress: %s", out) | |
| 120 | 新增: } | |
| 121 | 新增: if out, err = run(); err != nil || !strings.Contains(string(out), "already meets") { | |
| 122 | 新增: t.Fatalf("installed version was not reused: %v %s", err, out) | |
| 123 | 新增: } | |
| 124 | 新增: } | |
| 125 | 新增: sources, _ := os.ReadFile(filepath.Join(dir, "sources")) | |
| 126 | 新增: if got := strings.Join(strings.Fields(string(sources)), " "); got != tc.sources { | |
| 127 | 新增: t.Fatalf("sources %q want %q", got, tc.sources) | |
| 128 | 新增: } | |
| 129 | 新增: }) | |
| 130 | 新增: } | |
| 131 | 新增:} | |
| @@ -15,6 +15,7 @@ import ( | ||
| 15 | 15 | "strings" |
| 16 | 16 | "sync/atomic" |
| 17 | 17 | "testing" |
| 18 | 新增: "time" | |
| 18 | 19 | ) |
| 19 | 20 | |
| 20 | 21 | func TestGuestManifestIsPublishedOnlyAfterSuccessfulServiceStart(t *testing.T) { |
| @@ -97,6 +98,114 @@ cage_download_tool "$DOWNLOAD_URL" "$DOWNLOAD_HASH" "$HOME/package"`) | ||
| 97 | 98 | } |
| 98 | 99 | } |
| 99 | 100 | |
| 101 | 新增:func TestToolDownloadIdleTimeoutAndManualResume(t *testing.T) { | |
| 102 | 新增: for _, tool := range []string{"curl", "python3", "bash", "shasum"} { | |
| 103 | 新增: if _, err := exec.LookPath(tool); err != nil { | |
| 104 | 新增: t.Skip(tool + " unavailable") | |
| 105 | 新增: } | |
| 106 | 新增: } | |
| 107 | 新增: for _, mode := range []string{"slow", "stalled", "no-body"} { | |
| 108 | 新增: t.Run(mode, func(t *testing.T) { | |
| 109 | 新增: dir := t.TempDir() | |
| 110 | 新增: for name, body := range map[string]string{ | |
| 111 | 新增: "sha256sum": "#!/bin/sh\nexec shasum -a 256 \"$@\"\n", | |
| 112 | 新增: "sleep": "#!/bin/sh\nexit 0\n", | |
| 113 | 新增: } { | |
| 114 | 新增: if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0755); err != nil { | |
| 115 | 新增: t.Fatal(err) | |
| 116 | 新增: } | |
| 117 | 新增: } | |
| 118 | 新增: const data = "abcdefghijklmnop" | |
| 119 | 新增: var calls atomic.Int32 | |
| 120 | 新增: var recovered atomic.Bool | |
| 121 | 新增: s := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 122 | 新增: call := calls.Add(1) | |
| 123 | 新增: offset := 0 | |
| 124 | 新增: if mode == "stalled" { | |
| 125 | 新增: offset = int(call - 1) | |
| 126 | 新增: } | |
| 127 | 新增: wantRange := "" | |
| 128 | 新增: if offset > 0 { | |
| 129 | 新增: wantRange = fmt.Sprintf("bytes=%d-", offset) | |
| 130 | 新增: } | |
| 131 | 新增: if r.Header.Get("Range") != wantRange { | |
| 132 | 新增: t.Errorf("range = %q, want %q", r.Header.Get("Range"), wantRange) | |
| 133 | 新增: } | |
| 134 | 新增: w.Header().Set("Content-Length", fmt.Sprint(len(data)-offset)) | |
| 135 | 新增: if offset > 0 { | |
| 136 | 新增: w.Header().Set("Content-Range", fmt.Sprintf("bytes %d-%d/%d", offset, len(data)-1, len(data))) | |
| 137 | 新增: w.WriteHeader(http.StatusPartialContent) | |
| 138 | 新增: } | |
| 139 | 新增: if recovered.Load() { | |
| 140 | 新增: fmt.Fprint(w, data[offset:]) | |
| 141 | 新增: return | |
| 142 | 新增: } | |
| 143 | 新增: if mode == "slow" { | |
| 144 | 新增: for i := range len(data) { | |
| 145 | 新增: fmt.Fprint(w, data[i:i+1]) | |
| 146 | 新增: w.(http.Flusher).Flush() | |
| 147 | 新增: select { | |
| 148 | 新增: case <-r.Context().Done(): | |
| 149 | 新增: return | |
| 150 | 新增: case <-time.After(100 * time.Millisecond): | |
| 151 | 新增: } | |
| 152 | 新增: } | |
| 153 | 新增: return | |
| 154 | 新增: } | |
| 155 | 新增: if mode == "stalled" { | |
| 156 | 新增: fmt.Fprint(w, data[offset:offset+1]) | |
| 157 | 新增: } | |
| 158 | 新增: w.(http.Flusher).Flush() | |
| 159 | 新增: <-r.Context().Done() | |
| 160 | 新增: })) | |
| 161 | 新增: defer s.Close() | |
| 162 | 新增: ca := filepath.Join(dir, "ca.pem") | |
| 163 | 新增: if err := os.WriteFile(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: s.Certificate().Raw}), 0600); err != nil { | |
| 164 | 新增: t.Fatal(err) | |
| 165 | 新增: } | |
| 166 | 新增: hash := sha256.Sum256([]byte(data)) | |
| 167 | 新增: run := func() ([]byte, error) { | |
| 168 | 新增: // Shorten only the test's idle interval; use the real curl, TLS, | |
| 169 | 新增: // filesystem, checksum, automatic retries and manual continuation. | |
| 170 | 新增: prelude := strings.Replace(ToolInstallPrelude(), "idle_timeout = 60", "idle_timeout = 0.5", 1) | |
| 171 | 新增: cmd := exec.CommandContext(t.Context(), "bash", "-c", prelude+`cage_download_tool "$DOWNLOAD_URL" "$DOWNLOAD_HASH" "$HOME/package"`) | |
| 172 | 新增: cmd.Env = append(os.Environ(), "CAGE_SETUP_PROGRESS=1", "HOME="+dir, "PATH="+dir+":"+os.Getenv("PATH"), "CURL_CA_BUNDLE="+ca, "DOWNLOAD_URL="+s.URL, fmt.Sprintf("DOWNLOAD_HASH=%x", hash), "NO_PROXY=127.0.0.1", "no_proxy=127.0.0.1") | |
| 173 | 新增: return cmd.CombinedOutput() | |
| 174 | 新增: } | |
| 175 | 新增: out, err := run() | |
| 176 | 新增: if mode == "slow" { | |
| 177 | 新增: if !strings.Contains(string(out), "CAGE_TOOL_BYTES package 0") || !strings.Contains(string(out), "CAGE_TOOL_BYTES package 16") { | |
| 178 | 新增: t.Fatalf("real tool transfer did not publish its byte counts: %s", out) | |
| 179 | 新增: } | |
| 180 | 新增: if err != nil || calls.Load() != 1 { | |
| 181 | 新增: t.Fatalf("progressing download interrupted: %v calls=%d %s", err, calls.Load(), out) | |
| 182 | 新增: } | |
| 183 | 新增: } else { | |
| 184 | 新增: if err == nil || calls.Load() != 4 || !strings.Contains(string(out), "no data") { | |
| 185 | 新增: t.Fatalf("stalled download did not exhaust idle retries: %v calls=%d %s", err, calls.Load(), out) | |
| 186 | 新增: } | |
| 187 | 新增: if _, err := os.Stat(filepath.Join(dir, "package")); !os.IsNotExist(err) { | |
| 188 | 新增: t.Fatal("incomplete file published") | |
| 189 | 新增: } | |
| 190 | 新增: if mode == "stalled" { | |
| 191 | 新增: got, err := os.ReadFile(filepath.Join(dir, "package.part")) | |
| 192 | 新增: if err != nil || string(got) != data[:4] { | |
| 193 | 新增: t.Fatalf("partial data lost: %q %v", got, err) | |
| 194 | 新增: } | |
| 195 | 新增: } | |
| 196 | 新增: recovered.Store(true) | |
| 197 | 新增: if out, err := run(); err != nil || calls.Load() != 5 { | |
| 198 | 新增: t.Fatalf("manual continuation failed: %v calls=%d %s", err, calls.Load(), out) | |
| 199 | 新增: } | |
| 200 | 新增: } | |
| 201 | 新增: got, err := os.ReadFile(filepath.Join(dir, "package")) | |
| 202 | 新增: if err != nil || string(got) != data { | |
| 203 | 新增: t.Fatalf("download not verified and published: %q %v", got, err) | |
| 204 | 新增: } | |
| 205 | 新增: }) | |
| 206 | 新增: } | |
| 207 | 新增:} | |
| 208 | 新增: | |
| 100 | 209 | func TestClaudeNativeCacheUsesGuestArchitectureAndIntegrity(t *testing.T) { |
| 101 | 210 | if _, err := exec.LookPath("jq"); err != nil { |
| 102 | 211 | t.Skip("jq unavailable") |
| @@ -113,7 +222,22 @@ func TestClaudeNativeCacheUsesGuestArchitectureAndIntegrity(t *testing.T) { | ||
| 113 | 222 | "dpkg": "#!/bin/sh\nif [ \"$1\" = --print-architecture ]; then echo \"$TEST_ARCH\"; else exit 1; fi\n", |
| 114 | 223 | "claude": "#!/bin/sh\necho 1.0.0\n", |
| 115 | 224 | "flock": "#!/bin/sh\nexit 0\n", |
| 116 | 删除: "curl": "#!/bin/sh\nwhile [ \"$#\" -gt 0 ]; do if [ \"$1\" = -o ]; then shift; printf native-package > \"$1\"; printf 200; exit; fi; shift; done\nexit 1\n", | |
| 225 | 新增: "curl": `#!/bin/sh | |
| 226 | 新增:while [ "$#" -gt 0 ]; do | |
| 227 | 新增: case "$1" in | |
| 228 | 新增: https://cdn.npmmirror.com/packages/%40anthropic-ai/"$TEST_PACKAGE"/2.1.314/"$TEST_PACKAGE"-2.1.314.tgz) | |
| 229 | 新增: body=native-package | |
| 230 | 新增: [ "$TEST_ARCH" != amd64 ] || body=corrupt-mirror | |
| 231 | 新增: echo mirror >> "$HOME/sources";; | |
| 232 | 新增: https://registry.npmjs.org/"$TEST_PACKAGE".tgz) | |
| 233 | 新增: body=native-package | |
| 234 | 新增: echo upstream >> "$HOME/sources";; | |
| 235 | 新增: -o) shift; printf %s "${body:?unexpected source}" > "$1"; printf 200; exit;; | |
| 236 | 新增: esac | |
| 237 | 新增: shift | |
| 238 | 新增:done | |
| 239 | 新增:exit 1 | |
| 240 | 新增:`, | |
| 117 | 241 | "npm": `#!/bin/sh |
| 118 | 242 | case "$1" in |
| 119 | 243 | view) |
| @@ -141,7 +265,13 @@ esac | ||
| 141 | 265 | t.Fatal(err) |
| 142 | 266 | } |
| 143 | 267 | } |
| 144 | 删除: cmd := exec.Command("bash", "-c", ToolInstallPrelude()+"cage_install_tool claude") | |
| 268 | 新增: // The simulated amd64 guest may be running on an arm64 test host. | |
| 269 | 新增: cpuinfo := filepath.Join(dir, "cpuinfo") | |
| 270 | 新增: if err := os.WriteFile(cpuinfo, []byte("flags\t: ssse3 sse4_1 sse4_2 popcnt\n"), 0600); err != nil { | |
| 271 | 新增: t.Fatal(err) | |
| 272 | 新增: } | |
| 273 | 新增: prelude := strings.ReplaceAll(ToolInstallPrelude(), "/proc/cpuinfo", `"$HOME/cpuinfo"`) | |
| 274 | 新增: cmd := exec.Command("bash", "-c", prelude+"cage_install_tool claude") | |
| 145 | 275 | cmd.Env = append(os.Environ(), "HOME="+dir, "PATH="+dir+":"+os.Getenv("PATH"), "TEST_ARCH="+arch, "TEST_PACKAGE="+packageName, "TEST_INTEGRITY="+base64.StdEncoding.EncodeToString(hash[:])) |
| 146 | 276 | if out, err := cmd.CombinedOutput(); err != nil { |
| 147 | 277 | t.Fatalf("%v %s", err, out) |
| @@ -149,6 +279,23 @@ esac | ||
| 149 | 279 | if _, err := os.Stat(filepath.Join(dir, "installed")); err != nil { |
| 150 | 280 | t.Fatal(err) |
| 151 | 281 | } |
| 282 | 新增: want := "mirror\n" | |
| 283 | 新增: if arch == "amd64" { | |
| 284 | 新增: want += "upstream\n" | |
| 285 | 新增: } | |
| 286 | 新增: if got, err := os.ReadFile(filepath.Join(dir, "sources")); err != nil || string(got) != want { | |
| 287 | 新增: t.Fatalf("sources: %q, want %q (%v)", got, want, err) | |
| 288 | 新增: } | |
| 289 | 新增: if arch == "amd64" { | |
| 290 | 新增: if err := os.WriteFile(cpuinfo, []byte("flags\t: sse2 sse4a popcnt\n"), 0600); err != nil { | |
| 291 | 新增: t.Fatal(err) | |
| 292 | 新增: } | |
| 293 | 新增: retry := exec.Command("bash", "-c", prelude+"cage_install_tool claude") | |
| 294 | 新增: retry.Env = cmd.Env | |
| 295 | 新增: if out, err := retry.CombinedOutput(); err == nil || !strings.Contains(string(out), "需要 SSE4.2") { | |
| 296 | 新增: t.Fatalf("missing guest CPU feature should stop Claude setup: %v %s", err, out) | |
| 297 | 新增: } | |
| 298 | 新增: } | |
| 152 | 299 | }) |
| 153 | 300 | } |
| 154 | 301 | } |
| @@ -165,6 +312,17 @@ func TestGeneratedGuestScriptsParseAsBash(t *testing.T) { | ||
| 165 | 312 | } |
| 166 | 313 | } |
| 167 | 314 | |
| 315 | 新增:func TestChromiumPrefetchFallsBackButPropagatesCancellation(t *testing.T) { | |
| 316 | 新增: for _, status := range []int{1, 143} { | |
| 317 | 新增: cmd := exec.Command("bash", "-c", fmt.Sprintf("set -e\nsudo() { cat >/dev/null; return %d; }\n", status)+ToolInstallPrelude()+"cage_cache_chromium --only-upgrade chromium\necho normal-apt") | |
| 318 | 新增: out, err := cmd.CombinedOutput() | |
| 319 | 新增: fellBack := err == nil && strings.Contains(string(out), "normal-apt") | |
| 320 | 新增: if (status == 1 && !fellBack) || (status == 143 && (err == nil || cmd.ProcessState.ExitCode() != 143)) { | |
| 321 | 新增: t.Fatalf("prefetch exit %d: %v %s", status, err, out) | |
| 322 | 新增: } | |
| 323 | 新增: } | |
| 324 | 新增:} | |
| 325 | 新增: | |
| 168 | 326 | func TestPinnedToolInstallerRejectsWrongHashBeforeInstalling(t *testing.T) { |
| 169 | 327 | dir := t.TempDir() |
| 170 | 328 | commands := map[string]string{ |
| @@ -28,6 +28,12 @@ func (c Config) RecordRunning(state, name string) error { | ||
| 28 | 28 | return errors.New("invalid cage instance name") |
| 29 | 29 | } |
| 30 | 30 | dir := filepath.Join(state, "lima", name) |
| 31 | 新增: return c.RecordRunningAt(dir) | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:// RecordRunningAt records the network owner's identity in the runtime's real | |
| 35 | 新增:// instance directory; container environments do not create Lima metadata. | |
| 36 | 新增:func (c Config) RecordRunningAt(dir string) error { | |
| 31 | 37 | b, _ := json.Marshal(runningProfile{PID: os.Getpid(), Fingerprint: c.Fingerprint(), JobID: os.Getenv(JobEnv)}) |
| 32 | 38 | f, err := os.CreateTemp(dir, ".running-*") |
| 33 | 39 | if err != nil { |
| @@ -51,6 +57,11 @@ func (c Config) CheckRunning(state string) error { | ||
| 51 | 57 | if err != nil { |
| 52 | 58 | return err |
| 53 | 59 | } |
| 60 | 新增: containerRecords, err := filepath.Glob(filepath.Join(state, "container", "*", "cage-running.json")) | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: return err | |
| 63 | 新增: } | |
| 64 | 新增: files = append(files, containerRecords...) | |
| 54 | 65 | for _, file := range files { |
| 55 | 66 | b, err := os.ReadFile(file) |
| 56 | 67 | if err != nil { |
| @@ -0,0 +1,607 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/rand" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "runtime" | |
| 13 | 新增: "strconv" | |
| 14 | 新增: "strings" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:type StorageLocation struct { | |
| 21 | 新增: Directory string `json:"directory"` | |
| 22 | 新增: Custom bool `json:"custom"` | |
| 23 | 新增: HasEnvironment bool `json:"has_environment"` | |
| 24 | 新增: Backup string `json:"backup,omitempty"` | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:type storageRecord struct { | |
| 28 | 新增: Directory string `json:"directory"` | |
| 29 | 新增: ID string `json:"id"` | |
| 30 | 新增: Backups []string `json:"backups,omitempty"` | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:const locationFile = "environment-storage.json" | |
| 34 | 新增:const pendingFile = "environment-storage-pending.json" | |
| 35 | 新增:const storageMarker = ".cage-storage-id" | |
| 36 | 新增: | |
| 37 | 新增:type storageMove struct { | |
| 38 | 新增: Next storageRecord | |
| 39 | 新增: // Previous anchor is retained when the old storage is a directory. | |
| 40 | 新增: // If it was a link, only the link is discarded after commit. | |
| 41 | 新增: PreviousCustom bool | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func readStorageRecord(profile string) (storageRecord, error) { | |
| 45 | 新增: var r storageRecord | |
| 46 | 新增: b, err := os.ReadFile(filepath.Join(profile, locationFile)) | |
| 47 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 48 | 新增: return r, nil | |
| 49 | 新增: } | |
| 50 | 新增: if err != nil { | |
| 51 | 新增: return r, err | |
| 52 | 新增: } | |
| 53 | 新增: if err = json.Unmarshal(b, &r); err != nil || !filepath.IsAbs(r.Directory) || !validStorageID(r.ID) { | |
| 54 | 新增: return storageRecord{}, errors.New("Cage 环境存储配置损坏,请先恢复配置") | |
| 55 | 新增: } | |
| 56 | 新增: return r, nil | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:func validStorageID(id string) bool { | |
| 60 | 新增: return len(id) == 32 && strings.Trim(id, "0123456789abcdef") == "" | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func writeStorageJSON(path string, value any) error { | |
| 64 | 新增: data, err := json.Marshal(value) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return err | |
| 67 | 新增: } | |
| 68 | 新增: f, err := os.CreateTemp(filepath.Dir(path), ".storage-config-*") | |
| 69 | 新增: if err != nil { | |
| 70 | 新增: return err | |
| 71 | 新增: } | |
| 72 | 新增: defer os.Remove(f.Name()) | |
| 73 | 新增: _, err = f.Write(data) | |
| 74 | 新增: if err == nil { | |
| 75 | 新增: err = f.Sync() | |
| 76 | 新增: } | |
| 77 | 新增: if err = errors.Join(err, f.Close()); err != nil { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: return renameStorage(f.Name(), path) | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func sameStoragePath(a, b string) bool { | |
| 84 | 新增: a, b = filepath.Clean(a), filepath.Clean(b) | |
| 85 | 新增: if runtime.GOOS == "windows" || runtime.GOOS == "darwin" { | |
| 86 | 新增: return strings.EqualFold(a, b) | |
| 87 | 新增: } | |
| 88 | 新增: return a == b | |
| 89 | 新增:} | |
| 90 | 新增: | |
| 91 | 新增:// Resolve the existing prefix too: both a new data directory and an offline | |
| 92 | 新增:// project grant can have a final component which does not exist yet. | |
| 93 | 新增:func StoragePhysicalPath(path string) (string, error) { | |
| 94 | 新增: if !filepath.IsAbs(path) { | |
| 95 | 新增: return "", errors.New("请选择绝对路径") | |
| 96 | 新增: } | |
| 97 | 新增: path = filepath.Clean(path) | |
| 98 | 新增: real, err := paths.Resolve(path) | |
| 99 | 新增: if err == nil { | |
| 100 | 新增: return real, nil | |
| 101 | 新增: } | |
| 102 | 新增: if !os.IsNotExist(err) || filepath.Dir(path) == path { | |
| 103 | 新增: return "", err | |
| 104 | 新增: } | |
| 105 | 新增: if _, err = os.Lstat(path); err == nil || !os.IsNotExist(err) { | |
| 106 | 新增: return "", errors.New("目录包含无法解析的链接") | |
| 107 | 新增: } | |
| 108 | 新增: parent, err := StoragePhysicalPath(filepath.Dir(path)) | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: return "", err | |
| 111 | 新增: } | |
| 112 | 新增: return filepath.Join(parent, filepath.Base(path)), nil | |
| 113 | 新增:} | |
| 114 | 新增: | |
| 115 | 新增:func StorageContains(parent, child string) bool { | |
| 116 | 新增: rel, err := filepath.Rel(paths.Fold(filepath.Clean(parent)), paths.Fold(filepath.Clean(child))) | |
| 117 | 新增: return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:func StoragePathsOverlap(a, b string) bool { | |
| 121 | 新增: return StorageContains(a, b) || StorageContains(b, a) | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:// Upgrades replace the entire application folder including its resources. | |
| 125 | 新增:func runningApplicationDir() (string, error) { | |
| 126 | 新增: exe, err := os.Executable() | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: return "", err | |
| 129 | 新增: } | |
| 130 | 新增: exe, err = paths.Resolve(exe) | |
| 131 | 新增: if err != nil { | |
| 132 | 新增: return "", err | |
| 133 | 新增: } | |
| 134 | 新增: dir := filepath.Dir(exe) | |
| 135 | 新增: for parent := dir; parent != filepath.Dir(parent); parent = filepath.Dir(parent) { | |
| 136 | 新增: if strings.EqualFold(filepath.Ext(parent), ".app") { | |
| 137 | 新增: return parent, nil | |
| 138 | 新增: } | |
| 139 | 新增: } | |
| 140 | 新增: if strings.EqualFold(filepath.Base(dir), "resources") { | |
| 141 | 新增: return filepath.Dir(dir), nil | |
| 142 | 新增: } | |
| 143 | 新增: return dir, nil | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:// StoragePrivatePaths reports every externally located copy, including old | |
| 147 | 新增:// disks retained for recovery. The main profile itself is already private. | |
| 148 | 新增:func StoragePrivatePaths(profile string) ([]string, error) { | |
| 149 | 新增: r, err := readStorageRecord(profile) | |
| 150 | 新增: if err != nil { | |
| 151 | 新增: return nil, err | |
| 152 | 新增: } | |
| 153 | 新增: private := append([]string(nil), r.Backups...) | |
| 154 | 新增: if r.Directory != "" { | |
| 155 | 新增: private = append(private, r.Directory) | |
| 156 | 新增: } else if _, e := os.Readlink(storageAnchor(profile)); e == nil { | |
| 157 | 新增: real, e := paths.Resolve(storageAnchor(profile)) | |
| 158 | 新增: if e != nil { | |
| 159 | 新增: return nil, e | |
| 160 | 新增: } | |
| 161 | 新增: private = append(private, real) | |
| 162 | 新增: } | |
| 163 | 新增: // A partially copied environment must also be protected from new shares. | |
| 164 | 新增: b, err := os.ReadFile(filepath.Join(profile, pendingFile)) | |
| 165 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 166 | 新增: return private, nil | |
| 167 | 新增: } | |
| 168 | 新增: if err != nil { | |
| 169 | 新增: return nil, err | |
| 170 | 新增: } | |
| 171 | 新增: var p storageMove | |
| 172 | 新增: if err = json.Unmarshal(b, &p); err != nil { | |
| 173 | 新增: return nil, err | |
| 174 | 新增: } | |
| 175 | 新增: return append(private, p.Next.Directory), nil | |
| 176 | 新增:} | |
| 177 | 新增: | |
| 178 | 新增:func storageAnchor(profile string) string { return filepath.Join(profile, "state") } | |
| 179 | 新增: | |
| 180 | 新增:func getStorageLocation(profile string) (StorageLocation, error) { | |
| 181 | 新增: r, err := readStorageRecord(profile) | |
| 182 | 新增: if err != nil { | |
| 183 | 新增: return StorageLocation{}, err | |
| 184 | 新增: } | |
| 185 | 新增: anchor := storageAnchor(profile) | |
| 186 | 新增: loc := StorageLocation{Directory: anchor, Custom: r.Directory != ""} | |
| 187 | 新增: if loc.Custom { | |
| 188 | 新增: loc.Directory = r.Directory | |
| 189 | 新增: real, err := paths.Resolve(anchor) | |
| 190 | 新增: target, te := paths.Resolve(filepath.Join(r.Directory, "state")) | |
| 191 | 新增: marker, me := os.ReadFile(filepath.Join(r.Directory, storageMarker)) | |
| 192 | 新增: if err != nil || te != nil || me != nil || string(marker) != r.ID || !sameStoragePath(real, target) { | |
| 193 | 新增: return loc, fmt.Errorf("环境存储不可用,请重新连接原磁盘:%s", r.Directory) | |
| 194 | 新增: } | |
| 195 | 新增: if err = localStorageVolume(target); err != nil { | |
| 196 | 新增: return loc, err | |
| 197 | 新增: } | |
| 198 | 新增: } else if _, e := os.Readlink(anchor); e == nil { | |
| 199 | 新增: // Older installs may have an operator-managed symlink. Keep their | |
| 200 | 新增: // original cache, VM identity and path resolution on ordinary starts. | |
| 201 | 新增: real, e := paths.Resolve(anchor) | |
| 202 | 新增: if e != nil { | |
| 203 | 新增: return loc, e | |
| 204 | 新增: } | |
| 205 | 新增: fi, e := os.Stat(real) | |
| 206 | 新增: if e != nil || !fi.IsDir() { | |
| 207 | 新增: return loc, fmt.Errorf("环境目录不可用:%s", anchor) | |
| 208 | 新增: } | |
| 209 | 新增: if _, e = os.Stat(filepath.Join(filepath.Dir(real), storageMarker)); !errors.Is(e, os.ErrNotExist) { | |
| 210 | 新增: return loc, errors.New("环境存储配置缺失,请恢复原有配置") | |
| 211 | 新增: } | |
| 212 | 新增: loc.Directory = real | |
| 213 | 新增: } else if info, err := os.Lstat(anchor); err == nil && !info.IsDir() { | |
| 214 | 新增: return loc, fmt.Errorf("环境目录类型异常:%s", anchor) | |
| 215 | 新增: } else if err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 216 | 新增: return loc, err | |
| 217 | 新增: } | |
| 218 | 新增: if len(r.Backups) > 0 { | |
| 219 | 新增: loc.Backup = r.Backups[len(r.Backups)-1] | |
| 220 | 新增: } | |
| 221 | 新增: entries, err := os.ReadDir(filepath.Join(anchor, "lima")) | |
| 222 | 新增: if err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 223 | 新增: return loc, err | |
| 224 | 新增: } | |
| 225 | 新增: for _, entry := range entries { | |
| 226 | 新增: if entry.IsDir() && !strings.HasPrefix(entry.Name(), "_") { | |
| 227 | 新增: loc.HasEnvironment = true | |
| 228 | 新增: break | |
| 229 | 新增: } | |
| 230 | 新增: } | |
| 231 | 新增: return loc, nil | |
| 232 | 新增:} | |
| 233 | 新增: | |
| 234 | 新增:func GetStorageLocation(profile string) (StorageLocation, error) { | |
| 235 | 新增: lock, err := openStorageLock(profile, false) | |
| 236 | 新增: if err != nil { | |
| 237 | 新增: return StorageLocation{}, err | |
| 238 | 新增: } | |
| 239 | 新增: defer lock.Close() | |
| 240 | 新增: return getStorageLocation(profile) | |
| 241 | 新增:} | |
| 242 | 新增: | |
| 243 | 新增:// AcquireStorageUse holds the same shared lease for the entire Cage command, | |
| 244 | 新增:// including detached hostagents. A migration cannot run in the launch window. | |
| 245 | 新增:func AcquireStorageUse(profile string) (*os.File, StorageLocation, error) { | |
| 246 | 新增: lock, err := openStorageLock(profile, false) | |
| 247 | 新增: if err != nil { | |
| 248 | 新增: return nil, StorageLocation{}, err | |
| 249 | 新增: } | |
| 250 | 新增: loc, err := getStorageLocation(profile) | |
| 251 | 新增: if err != nil { | |
| 252 | 新增: lock.Close() | |
| 253 | 新增: return nil, loc, err | |
| 254 | 新增: } | |
| 255 | 新增: return lock, loc, nil | |
| 256 | 新增:} | |
| 257 | 新增: | |
| 258 | 新增:func openStorageLock(profile string, exclusive bool) (*os.File, error) { | |
| 259 | 新增: f, err := os.OpenFile(filepath.Join(profile, "environment-storage.lock"), os.O_CREATE|os.O_RDWR, 0600) | |
| 260 | 新增: if err != nil { | |
| 261 | 新增: return nil, err | |
| 262 | 新增: } | |
| 263 | 新增: ok, err := lockStorageFile(f, exclusive) | |
| 264 | 新增: if err != nil || !ok { | |
| 265 | 新增: f.Close() | |
| 266 | 新增: if err == nil { | |
| 267 | 新增: err = errors.New("环境正在运行或迁移中,请停止环境并等待当前操作完成") | |
| 268 | 新增: } | |
| 269 | 新增: return nil, err | |
| 270 | 新增: } | |
| 271 | 新增: if _, err = os.Stat(filepath.Join(profile, pendingFile)); errors.Is(err, os.ErrNotExist) { | |
| 272 | 新增: return f, nil | |
| 273 | 新增: } | |
| 274 | 新增: if err != nil { | |
| 275 | 新增: f.Close() | |
| 276 | 新增: return nil, err | |
| 277 | 新增: } | |
| 278 | 新增: if !exclusive { | |
| 279 | 新增: f.Close() | |
| 280 | 新增: // Acquire exclusively before attempting recovery, then reacquire a | |
| 281 | 新增: // shared lease. Recheck the journal once more under the new lease. | |
| 282 | 新增: w, err := openStorageLock(profile, true) | |
| 283 | 新增: if err != nil { | |
| 284 | 新增: return nil, err | |
| 285 | 新增: } | |
| 286 | 新增: w.Close() | |
| 287 | 新增: return openStorageLock(profile, false) | |
| 288 | 新增: } | |
| 289 | 新增: if err = recoverStorage(profile); err != nil { | |
| 290 | 新增: f.Close() | |
| 291 | 新增: return nil, err | |
| 292 | 新增: } | |
| 293 | 新增: return f, nil | |
| 294 | 新增:} | |
| 295 | 新增: | |
| 296 | 新增:func ValidateStorageTarget(profile, directory string) error { | |
| 297 | 新增: if _, err := os.Readlink(storageAnchor(profile)); err == nil { | |
| 298 | 新增: r, err := readStorageRecord(profile) | |
| 299 | 新增: if err != nil { | |
| 300 | 新增: return err | |
| 301 | 新增: } | |
| 302 | 新增: if r.Directory == "" { | |
| 303 | 新增: return errors.New("当前环境使用手动配置的目录链接。请先恢复原目录,再使用 Cage 迁移") | |
| 304 | 新增: } | |
| 305 | 新增: } | |
| 306 | 新增: if !filepath.IsAbs(directory) || filepath.Clean(directory) == filepath.VolumeName(directory)+string(os.PathSeparator) { | |
| 307 | 新增: return errors.New("请选择本地磁盘上的专用绝对路径,不能使用磁盘根目录") | |
| 308 | 新增: } | |
| 309 | 新增: target, err := StoragePhysicalPath(directory) | |
| 310 | 新增: if err != nil { | |
| 311 | 新增: return err | |
| 312 | 新增: } | |
| 313 | 新增: // Check the actual mount, including junctions and symlinked parents. | |
| 314 | 新增: existing := target | |
| 315 | 新增: for { | |
| 316 | 新增: if _, err = os.Stat(existing); err == nil { | |
| 317 | 新增: break | |
| 318 | 新增: } | |
| 319 | 新增: if !errors.Is(err, os.ErrNotExist) || filepath.Dir(existing) == existing { | |
| 320 | 新增: return err | |
| 321 | 新增: } | |
| 322 | 新增: existing = filepath.Dir(existing) | |
| 323 | 新增: } | |
| 324 | 新增: if sameStoragePath(existing, target) { | |
| 325 | 新增: root, e := storageMountRoot(existing) | |
| 326 | 新增: if e != nil { | |
| 327 | 新增: return e | |
| 328 | 新增: } | |
| 329 | 新增: if root { | |
| 330 | 新增: return errors.New("请在磁盘内新建专用文件夹,不能使用卷根目录") | |
| 331 | 新增: } | |
| 332 | 新增: } | |
| 333 | 新增: if err = localStorageVolume(existing); err != nil { | |
| 334 | 新增: return err | |
| 335 | 新增: } | |
| 336 | 新增: private, err := StoragePrivatePaths(profile) | |
| 337 | 新增: if err != nil { | |
| 338 | 新增: return err | |
| 339 | 新增: } | |
| 340 | 新增: private = append(private, profile, EnvironmentDir(profile)) | |
| 341 | 新增: app, err := runningApplicationDir() | |
| 342 | 新增: if err != nil { | |
| 343 | 新增: return err | |
| 344 | 新增: } | |
| 345 | 新增: private = append(private, app) | |
| 346 | 新增: for _, p := range private { | |
| 347 | 新增: real, e := StoragePhysicalPath(p) | |
| 348 | 新增: if e != nil && !errors.Is(e, os.ErrNotExist) { | |
| 349 | 新增: return e | |
| 350 | 新增: } | |
| 351 | 新增: if StoragePathsOverlap(directory, p) || (real != "" && StoragePathsOverlap(target, real)) { | |
| 352 | 新增: return errors.New("请选择独立空目录,不能与程序、配置、工作区、现有存储或备份重叠") | |
| 353 | 新增: } | |
| 354 | 新增: } | |
| 355 | 新增: if info, e := os.Lstat(directory); e == nil && (!info.IsDir() || info.Mode()&(os.ModeSymlink|os.ModeIrregular) != 0) { | |
| 356 | 新增: return errors.New("目标必须是本地真实目录") | |
| 357 | 新增: } else if e != nil && !errors.Is(e, os.ErrNotExist) { | |
| 358 | 新增: return e | |
| 359 | 新增: } | |
| 360 | 新增: entries, err := os.ReadDir(directory) | |
| 361 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 362 | 新增: return nil | |
| 363 | 新增: } | |
| 364 | 新增: if err != nil { | |
| 365 | 新增: return err | |
| 366 | 新增: } | |
| 367 | 新增: if len(entries) > 0 { | |
| 368 | 新增: return errors.New("环境存储需要专用空目录,请新建文件夹") | |
| 369 | 新增: } | |
| 370 | 新增: return nil | |
| 371 | 新增:} | |
| 372 | 新增: | |
| 373 | 新增:func stoppedStorage(source string) error { | |
| 374 | 新增: // Examine every instance, including interrupted base construction. | |
| 375 | 新增: instances, err := os.ReadDir(filepath.Join(source, "lima")) | |
| 376 | 新增: if errors.Is(err, os.ErrNotExist) { | |
| 377 | 新增: return nil | |
| 378 | 新增: } | |
| 379 | 新增: if err != nil { | |
| 380 | 新增: return err | |
| 381 | 新增: } | |
| 382 | 新增: for _, inst := range instances { | |
| 383 | 新增: if !inst.IsDir() || strings.HasPrefix(inst.Name(), "_") { | |
| 384 | 新增: continue | |
| 385 | 新增: } | |
| 386 | 新增: dir := filepath.Join(source, "lima", inst.Name()) | |
| 387 | 新增: entries, err := os.ReadDir(dir) | |
| 388 | 新增: if err != nil { | |
| 389 | 新增: return err | |
| 390 | 新增: } | |
| 391 | 新增: for _, entry := range entries { | |
| 392 | 新增: name := entry.Name() | |
| 393 | 新增: if !strings.HasSuffix(name, ".pid") && name != "cage-running.json" { | |
| 394 | 新增: continue | |
| 395 | 新增: } | |
| 396 | 新增: data, err := os.ReadFile(filepath.Join(dir, name)) | |
| 397 | 新增: if err != nil { | |
| 398 | 新增: return err | |
| 399 | 新增: } | |
| 400 | 新增: var pid int | |
| 401 | 新增: if name == "cage-running.json" { | |
| 402 | 新增: var record runningProfile | |
| 403 | 新增: err = json.Unmarshal(data, &record) | |
| 404 | 新增: pid = record.PID | |
| 405 | 新增: } else { | |
| 406 | 新增: pid, err = strconv.Atoi(strings.TrimSpace(string(data))) | |
| 407 | 新增: } | |
| 408 | 新增: if err != nil || pid < 1 { | |
| 409 | 新增: return fmt.Errorf("无法核验虚拟机进程记录 %s", name) | |
| 410 | 新增: } | |
| 411 | 新增: if profileProcessAlive(pid) { | |
| 412 | 新增: return fmt.Errorf("请先停止虚拟机 %s,再迁移环境", inst.Name()) | |
| 413 | 新增: } | |
| 414 | 新增: } | |
| 415 | 新增: } | |
| 416 | 新增: return nil | |
| 417 | 新增:} | |
| 418 | 新增: | |
| 419 | 新增:func MoveStorage(ctx context.Context, profile, directory string, expected StorageLocation, report func(copied, total int64)) (loc StorageLocation, err error) { | |
| 420 | 新增: lock, err := openStorageLock(profile, true) | |
| 421 | 新增: if err != nil { | |
| 422 | 新增: return loc, err | |
| 423 | 新增: } | |
| 424 | 新增: defer lock.Close() | |
| 425 | 新增: loc, err = getStorageLocation(profile) | |
| 426 | 新增: if err != nil { | |
| 427 | 新增: return loc, err | |
| 428 | 新增: } | |
| 429 | 新增: if !sameStoragePath(expected.Directory, loc.Directory) || expected.HasEnvironment != loc.HasEnvironment { | |
| 430 | 新增: return loc, errors.New("环境或存储位置已改变,请重新选择") | |
| 431 | 新增: } | |
| 432 | 新增: if err = ValidateStorageTarget(profile, directory); err != nil { | |
| 433 | 新增: return loc, err | |
| 434 | 新增: } | |
| 435 | 新增: directory, err = StoragePhysicalPath(directory) | |
| 436 | 新增: if err != nil { | |
| 437 | 新增: return loc, err | |
| 438 | 新增: } | |
| 439 | 新增: anchor := storageAnchor(profile) | |
| 440 | 新增: if err = stoppedStorage(anchor); err != nil { | |
| 441 | 新增: return loc, err | |
| 442 | 新增: } | |
| 443 | 新增: previous, err := readStorageRecord(profile) | |
| 444 | 新增: if err != nil { | |
| 445 | 新增: return loc, err | |
| 446 | 新增: } | |
| 447 | 新增: var token [16]byte | |
| 448 | 新增: if _, err = rand.Read(token[:]); err != nil { | |
| 449 | 新增: return loc, err | |
| 450 | 新增: } | |
| 451 | 新增: id := fmt.Sprintf("%x", token) | |
| 452 | 新增: next := storageRecord{Directory: directory, ID: id, Backups: append([]string(nil), previous.Backups...)} | |
| 453 | 新增: anchorBackup := filepath.Join(profile, "state-backup-"+id) | |
| 454 | 新增: src := anchor | |
| 455 | 新增: info, statErr := os.Lstat(anchor) | |
| 456 | 新增: if statErr != nil && !errors.Is(statErr, os.ErrNotExist) { | |
| 457 | 新增: return loc, statErr | |
| 458 | 新增: } | |
| 459 | 新增: if statErr == nil { | |
| 460 | 新增: backup := anchorBackup | |
| 461 | 新增: if loc.Custom { | |
| 462 | 新增: backup = loc.Directory | |
| 463 | 新增: src = filepath.Join(loc.Directory, "state") | |
| 464 | 新增: } | |
| 465 | 新增: next.Backups = append(next.Backups, backup) | |
| 466 | 新增: } | |
| 467 | 新增: move := storageMove{Next: next, PreviousCustom: loc.Custom} | |
| 468 | 新增: if err = host.EnsurePrivateDir(directory); err != nil { | |
| 469 | 新增: if errors.Is(err, os.ErrPermission) { | |
| 470 | 新增: return loc, fmt.Errorf("无法将目标目录设为仅当前用户可访问。请选择自己新建且可以修改权限的空文件夹:%w", err) | |
| 471 | 新增: } | |
| 472 | 新增: return loc, err | |
| 473 | 新增: } | |
| 474 | 新增: if err = ValidateStorageTarget(profile, directory); err != nil { | |
| 475 | 新增: return loc, err | |
| 476 | 新增: } | |
| 477 | 新增: if err = writeStorageJSON(filepath.Join(profile, pendingFile), move); err != nil { | |
| 478 | 新增: return loc, err | |
| 479 | 新增: } | |
| 480 | 新增: // Recovery only removes files under the newly claimed target with a | |
| 481 | 新增: // matching random identity. It never recursively removes an old copy. | |
| 482 | 新增: defer func() { | |
| 483 | 新增: if recErr := recoverStorage(profile); recErr != nil { | |
| 484 | 新增: err = errors.Join(err, fmt.Errorf("恢复迁移:%w", recErr)) | |
| 485 | 新增: } | |
| 486 | 新增: }() | |
| 487 | 新增: if err = claimStorageTarget(directory, id); err != nil { | |
| 488 | 新增: return loc, err | |
| 489 | 新增: } | |
| 490 | 新增: destState := filepath.Join(directory, "state") | |
| 491 | 新增: if err = os.Mkdir(destState, 0700); err != nil { | |
| 492 | 新增: return loc, err | |
| 493 | 新增: } | |
| 494 | 新增: // An independently created state directory must never be mistaken for | |
| 495 | 新增: // one owned by this transfer when recovering after a failed mkdir. | |
| 496 | 新增: if err = claimStorageTarget(destState, id); err != nil { | |
| 497 | 新增: _ = os.Remove(destState) | |
| 498 | 新增: return loc, err | |
| 499 | 新增: } | |
| 500 | 新增: if info != nil { | |
| 501 | 新增: if err = copyStorage(ctx, src, destState, report); err != nil { | |
| 502 | 新增: return loc, err | |
| 503 | 新增: } | |
| 504 | 新增: } | |
| 505 | 新增: staged := filepath.Join(profile, ".storage-link-"+id) | |
| 506 | 新增: if err = linkStorage(staged, destState); err != nil { | |
| 507 | 新增: return loc, err | |
| 508 | 新增: } | |
| 509 | 新增: if err = syncStorageDir(directory); err != nil { | |
| 510 | 新增: return loc, err | |
| 511 | 新增: } | |
| 512 | 新增: if err = ctx.Err(); err != nil { | |
| 513 | 新增: return loc, err | |
| 514 | 新增: } | |
| 515 | 新增: if info != nil { | |
| 516 | 新增: if err = renameStorage(anchor, anchorBackup); err != nil { | |
| 517 | 新增: return loc, err | |
| 518 | 新增: } | |
| 519 | 新增: } | |
| 520 | 新增: if err = renameStorage(staged, anchor); err != nil { | |
| 521 | 新增: return loc, err | |
| 522 | 新增: } | |
| 523 | 新增: if err = writeStorageJSON(filepath.Join(profile, locationFile), next); err != nil { | |
| 524 | 新增: return loc, err | |
| 525 | 新增: } | |
| 526 | 新增: return getStorageLocation(profile) | |
| 527 | 新增:} | |
| 528 | 新增: | |
| 529 | 新增:func claimStorageTarget(dir, id string) error { | |
| 530 | 新增: f, err := os.OpenFile(filepath.Join(dir, storageMarker), os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600) | |
| 531 | 新增: if err != nil { | |
| 532 | 新增: return err | |
| 533 | 新增: } | |
| 534 | 新增: _, err = io.WriteString(f, id) | |
| 535 | 新增: if err == nil { | |
| 536 | 新增: err = f.Sync() | |
| 537 | 新增: } | |
| 538 | 新增: return errors.Join(err, f.Close()) | |
| 539 | 新增:} | |
| 540 | 新增: | |
| 541 | 新增:func recoverStorage(profile string) error { | |
| 542 | 新增: journal := filepath.Join(profile, pendingFile) | |
| 543 | 新增: b, err := os.ReadFile(journal) | |
| 544 | 新增: if err != nil { | |
| 545 | 新增: return err | |
| 546 | 新增: } | |
| 547 | 新增: var p storageMove | |
| 548 | 新增: if err = json.Unmarshal(b, &p); err != nil { | |
| 549 | 新增: return err | |
| 550 | 新增: } | |
| 551 | 新增: next := p.Next | |
| 552 | 新增: if !validStorageID(next.ID) || !filepath.IsAbs(next.Directory) { | |
| 553 | 新增: return errors.New("存储迁移记录损坏") | |
| 554 | 新增: } | |
| 555 | 新增: r, err := readStorageRecord(profile) | |
| 556 | 新增: if err != nil { | |
| 557 | 新增: return err | |
| 558 | 新增: } | |
| 559 | 新增: old := filepath.Join(profile, "state-backup-"+next.ID) | |
| 560 | 新增: stage := filepath.Join(profile, ".storage-link-"+next.ID) | |
| 561 | 新增: anchor := storageAnchor(profile) | |
| 562 | 新增: dest := filepath.Join(next.Directory, "state") | |
| 563 | 新增: if r.ID == next.ID { | |
| 564 | 新增: if token, e := os.ReadFile(filepath.Join(dest, storageMarker)); e == nil && string(token) == next.ID { | |
| 565 | 新增: if err = os.Remove(filepath.Join(dest, storageMarker)); err != nil { | |
| 566 | 新增: return err | |
| 567 | 新增: } | |
| 568 | 新增: } | |
| 569 | 新增: if p.PreviousCustom { | |
| 570 | 新增: if err = os.Remove(old); err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 571 | 新增: return err | |
| 572 | 新增: } | |
| 573 | 新增: } | |
| 574 | 新增: } else { | |
| 575 | 新增: if t, e := os.Readlink(anchor); e == nil && sameStoragePath(t, dest) { | |
| 576 | 新增: if err = os.Remove(anchor); err != nil { | |
| 577 | 新增: return err | |
| 578 | 新增: } | |
| 579 | 新增: } | |
| 580 | 新增: if _, e := os.Lstat(old); e == nil { | |
| 581 | 新增: if _, e = os.Lstat(anchor); !errors.Is(e, os.ErrNotExist) { | |
| 582 | 新增: return fmt.Errorf("请保留旧环境并检查迁移目录:%s", old) | |
| 583 | 新增: } | |
| 584 | 新增: if err = renameStorage(old, anchor); err != nil { | |
| 585 | 新增: return err | |
| 586 | 新增: } | |
| 587 | 新增: } else if !errors.Is(e, os.ErrNotExist) { | |
| 588 | 新增: return e | |
| 589 | 新增: } | |
| 590 | 新增: // Disconnected destination disks never prevent resuming the old copy. | |
| 591 | 新增: marker := filepath.Join(next.Directory, storageMarker) | |
| 592 | 新增: if token, e := os.ReadFile(marker); e == nil && string(token) == next.ID { | |
| 593 | 新增: if owner, e := os.ReadFile(filepath.Join(dest, storageMarker)); e == nil && string(owner) == next.ID { | |
| 594 | 新增: if err = os.RemoveAll(dest); err != nil { | |
| 595 | 新增: return err | |
| 596 | 新增: } | |
| 597 | 新增: } | |
| 598 | 新增: if err = os.Remove(marker); err != nil { | |
| 599 | 新增: return err | |
| 600 | 新增: } | |
| 601 | 新增: } | |
| 602 | 新增: } | |
| 603 | 新增: if err = os.Remove(stage); err != nil && !errors.Is(err, os.ErrNotExist) { | |
| 604 | 新增: return err | |
| 605 | 新增: } | |
| 606 | 新增: return os.Remove(journal) | |
| 607 | 新增:} | |
| @@ -0,0 +1,188 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/sha256" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "io/fs" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// Copy cold VM disks without expanding their zero-filled regions. Hash the | |
| 17 | 新增:// written copy independently before switching any path used by the runtime. | |
| 18 | 新增:func copyStorage(ctx context.Context, source, target string, report func(int64, int64)) error { | |
| 19 | 新增: var total, copied int64 | |
| 20 | 新增: var last time.Time | |
| 21 | 新增: err := filepath.WalkDir(source, func(path string, d fs.DirEntry, err error) error { | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return err | |
| 24 | 新增: } | |
| 25 | 新增: if err := ctx.Err(); err != nil { | |
| 26 | 新增: return err | |
| 27 | 新增: } | |
| 28 | 新增: if d.Type().IsRegular() { | |
| 29 | 新增: info, err := d.Info() | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: return err | |
| 32 | 新增: } | |
| 33 | 新增: total += info.Size() | |
| 34 | 新增: } | |
| 35 | 新增: return nil | |
| 36 | 新增: }) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return err | |
| 39 | 新增: } | |
| 40 | 新增: if report != nil { | |
| 41 | 新增: report(0, total) | |
| 42 | 新增: } | |
| 43 | 新增: buf := make([]byte, 1<<20) | |
| 44 | 新增: zero := make([]byte, len(buf)) | |
| 45 | 新增: progress := func(n int) { | |
| 46 | 新增: copied += int64(n) | |
| 47 | 新增: if report != nil && time.Since(last) > 250*time.Millisecond { | |
| 48 | 新增: report(copied, total) | |
| 49 | 新增: last = time.Now() | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: err = filepath.WalkDir(source, func(path string, d fs.DirEntry, err error) error { | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: return err | |
| 55 | 新增: } | |
| 56 | 新增: if err := ctx.Err(); err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: rel, err := filepath.Rel(source, path) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: return err | |
| 62 | 新增: } | |
| 63 | 新增: if rel == "." { | |
| 64 | 新增: return nil | |
| 65 | 新增: } | |
| 66 | 新增: out := filepath.Join(target, rel) | |
| 67 | 新增: info, err := d.Info() | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: switch { | |
| 72 | 新增: case d.IsDir(): | |
| 73 | 新增: return os.Mkdir(out, info.Mode().Perm()|0700) | |
| 74 | 新增: case d.Type().IsRegular(): | |
| 75 | 新增: return copyStorageFile(ctx, path, out, info, buf, zero, progress) | |
| 76 | 新增: case d.Type()&os.ModeSocket != 0: | |
| 77 | 新增: // The stopped guest recreates its local IPC sockets on startup. | |
| 78 | 新增: return nil | |
| 79 | 新增: case d.Type()&os.ModeSymlink != 0: | |
| 80 | 新增: link, err := os.Readlink(path) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: return err | |
| 83 | 新增: } | |
| 84 | 新增: if filepath.IsAbs(link) || !filepath.IsLocal(filepath.Clean(filepath.Join(filepath.Dir(rel), link))) { | |
| 85 | 新增: return fmt.Errorf("环境包含指向外部的链接,未切换存储:%s", rel) | |
| 86 | 新增: } | |
| 87 | 新增: return os.Symlink(link, out) | |
| 88 | 新增: default: | |
| 89 | 新增: return fmt.Errorf("环境含有无法复制的特殊文件,未切换存储:%s", rel) | |
| 90 | 新增: } | |
| 91 | 新增: }) | |
| 92 | 新增: if err == nil { | |
| 93 | 新增: err = filepath.WalkDir(target, func(path string, entry fs.DirEntry, err error) error { | |
| 94 | 新增: if err != nil { | |
| 95 | 新增: return err | |
| 96 | 新增: } | |
| 97 | 新增: if entry.IsDir() { | |
| 98 | 新增: return syncStorageDir(path) | |
| 99 | 新增: } | |
| 100 | 新增: return nil | |
| 101 | 新增: }) | |
| 102 | 新增: } | |
| 103 | 新增: if err == nil && report != nil { | |
| 104 | 新增: report(total, total) | |
| 105 | 新增: } | |
| 106 | 新增: return err | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:func copyStorageFile(ctx context.Context, source, target string, info fs.FileInfo, buf, zero []byte, progress func(int)) error { | |
| 110 | 新增: in, err := os.Open(source) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return err | |
| 113 | 新增: } | |
| 114 | 新增: defer in.Close() | |
| 115 | 新增: out, err := os.OpenFile(target, os.O_CREATE|os.O_EXCL|os.O_RDWR, 0600) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: return err | |
| 118 | 新增: } | |
| 119 | 新增: defer out.Close() | |
| 120 | 新增: if info.Size() >= 1<<20 { | |
| 121 | 新增: if err = sparseStorageFile(out); err != nil { | |
| 122 | 新增: return fmt.Errorf("目标磁盘不支持稀疏文件:%w", err) | |
| 123 | 新增: } | |
| 124 | 新增: } | |
| 125 | 新增: hash := sha256.New() | |
| 126 | 新增: var size int64 | |
| 127 | 新增: for { | |
| 128 | 新增: if err := ctx.Err(); err != nil { | |
| 129 | 新增: return err | |
| 130 | 新增: } | |
| 131 | 新增: n, e := in.Read(buf) | |
| 132 | 新增: if n > 0 { | |
| 133 | 新增: data := buf[:n] | |
| 134 | 新增: hash.Write(data) | |
| 135 | 新增: if bytes.Equal(data, zero[:n]) { | |
| 136 | 新增: _, err = out.Seek(int64(n), io.SeekCurrent) | |
| 137 | 新增: } else { | |
| 138 | 新增: _, err = out.Write(data) | |
| 139 | 新增: } | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return err | |
| 142 | 新增: } | |
| 143 | 新增: size += int64(n) | |
| 144 | 新增: progress(n) | |
| 145 | 新增: } | |
| 146 | 新增: if e == io.EOF { | |
| 147 | 新增: break | |
| 148 | 新增: } | |
| 149 | 新增: if e != nil { | |
| 150 | 新增: return e | |
| 151 | 新增: } | |
| 152 | 新增: } | |
| 153 | 新增: if size != info.Size() { | |
| 154 | 新增: return errors.New("复制期间源文件大小发生变化,已取消迁移") | |
| 155 | 新增: } | |
| 156 | 新增: if err = out.Truncate(size); err != nil { | |
| 157 | 新增: return err | |
| 158 | 新增: } | |
| 159 | 新增: if err = out.Sync(); err != nil { | |
| 160 | 新增: return err | |
| 161 | 新增: } | |
| 162 | 新增: if _, err = out.Seek(0, io.SeekStart); err != nil { | |
| 163 | 新增: return err | |
| 164 | 新增: } | |
| 165 | 新增: verify := sha256.New() | |
| 166 | 新增: for { | |
| 167 | 新增: if err := ctx.Err(); err != nil { | |
| 168 | 新增: return err | |
| 169 | 新增: } | |
| 170 | 新增: n, e := out.Read(buf) | |
| 171 | 新增: if n > 0 { | |
| 172 | 新增: verify.Write(buf[:n]) | |
| 173 | 新增: } | |
| 174 | 新增: if e == io.EOF { | |
| 175 | 新增: break | |
| 176 | 新增: } | |
| 177 | 新增: if e != nil { | |
| 178 | 新增: return e | |
| 179 | 新增: } | |
| 180 | 新增: } | |
| 181 | 新增: if !bytes.Equal(hash.Sum(nil), verify.Sum(nil)) { | |
| 182 | 新增: return fmt.Errorf("文件校验失败:%s", filepath.Base(source)) | |
| 183 | 新增: } | |
| 184 | 新增: if err = os.Chtimes(target, info.ModTime(), info.ModTime()); err != nil { | |
| 185 | 新增: return err | |
| 186 | 新增: } | |
| 187 | 新增: return out.Chmod(info.Mode().Perm()) | |
| 188 | 新增:} | |
| @@ -0,0 +1,245 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strconv" | |
| 9 | 新增: "testing" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func newStorageFixture(t *testing.T) (string, string) { | |
| 13 | 新增: t.Helper() | |
| 14 | 新增: root, err := filepath.EvalSymlinks(t.TempDir()) | |
| 15 | 新增: if err != nil { | |
| 16 | 新增: t.Fatal(err) | |
| 17 | 新增: } | |
| 18 | 新增: profile := filepath.Join(root, "profile") | |
| 19 | 新增: if err := os.Mkdir(profile, 0700); err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: return profile, root | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:func writeStorageFixture(t *testing.T, path string, data []byte) { | |
| 26 | 新增: t.Helper() | |
| 27 | 新增: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: if err := os.WriteFile(path, data, 0600); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func assertStorageFile(t *testing.T, path string, want []byte) { | |
| 36 | 新增: t.Helper() | |
| 37 | 新增: b, err := os.ReadFile(path) | |
| 38 | 新增: if err != nil || !bytes.Equal(b, want) { | |
| 39 | 新增: t.Fatalf("storage content mismatch in %s: %v", path, err) | |
| 40 | 新增: } | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:func TestStorageMovePreservesLegacyDiskAndColdBackup(t *testing.T) { | |
| 44 | 新增: profile, root := newStorageFixture(t) | |
| 45 | 新增: file := filepath.Join("lima", "instance", "disk") | |
| 46 | 新增: payload := make([]byte, (3<<20)+41) | |
| 47 | 新增: copy(payload, []byte("guest header")) | |
| 48 | 新增: copy(payload[3<<20:], []byte("guest tail")) | |
| 49 | 新增: writeStorageFixture(t, filepath.Join(profile, "state", file), payload) | |
| 50 | 新增: writeStorageFixture(t, filepath.Join(profile, "account.json"), []byte("account")) | |
| 51 | 新增: target := filepath.Join(root, "中文 folder") | |
| 52 | 新增: loc, err := MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil) | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: t.Fatal(err) | |
| 55 | 新增: } | |
| 56 | 新增: if !loc.Custom || !loc.HasEnvironment || loc.Backup == "" { | |
| 57 | 新增: t.Fatal(loc) | |
| 58 | 新增: } | |
| 59 | 新增: if info, err := os.Stat(filepath.Join(target, "state", file)); err != nil || info.Size() != int64(len(payload)) { | |
| 60 | 新增: t.Fatalf("stored disk size: %v %v", info, err) | |
| 61 | 新增: } | |
| 62 | 新增: assertStorageFile(t, filepath.Join(loc.Backup, file), payload) | |
| 63 | 新增: assertStorageFile(t, filepath.Join(profile, "state", file), payload) | |
| 64 | 新增: assertStorageFile(t, filepath.Join(profile, "account.json"), []byte("account")) | |
| 65 | 新增: old := loc.Backup | |
| 66 | 新增: target2 := filepath.Join(root, "second") | |
| 67 | 新增: loc, err = MoveStorage(context.Background(), profile, target2, storageExpectation(t, profile), nil) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: t.Fatal(err) | |
| 70 | 新增: } | |
| 71 | 新增: if loc.Backup != target { | |
| 72 | 新增: t.Fatal(loc) | |
| 73 | 新增: } | |
| 74 | 新增: assertStorageFile(t, filepath.Join(target, "state", file), payload) | |
| 75 | 新增: assertStorageFile(t, filepath.Join(profile, "state", file), payload) | |
| 76 | 新增: paths, err := StoragePrivatePaths(profile) | |
| 77 | 新增: if err != nil || len(paths) != 3 || paths[0] != old { | |
| 78 | 新增: t.Fatalf("private paths %v, %v", paths, err) | |
| 79 | 新增: } | |
| 80 | 新增: if err := os.Rename(target2, target2+"-offline"); err != nil { | |
| 81 | 新增: t.Fatal(err) | |
| 82 | 新增: } | |
| 83 | 新增: if _, _, err := AcquireStorageUse(profile); err == nil { | |
| 84 | 新增: t.Fatal("started with missing volume") | |
| 85 | 新增: } | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func TestStorageRefusesBusyAndRollsBackCancelledCopy(t *testing.T) { | |
| 89 | 新增: profile, root := newStorageFixture(t) | |
| 90 | 新增: lease, _, err := AcquireStorageUse(profile) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: target := filepath.Join(root, "new") | |
| 95 | 新增: if _, err = MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil); err == nil { | |
| 96 | 新增: t.Fatal("concurrent move admitted") | |
| 97 | 新增: } | |
| 98 | 新增: lease.Close() | |
| 99 | 新增: instance := filepath.Join(profile, "state", "lima", "vm") | |
| 100 | 新增: pid := filepath.Join(instance, "qemu.pid") | |
| 101 | 新增: writeStorageFixture(t, pid, []byte(strconv.Itoa(os.Getpid()))) | |
| 102 | 新增: if _, err = MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil); err == nil { | |
| 103 | 新增: t.Fatal("running VM admitted") | |
| 104 | 新增: } | |
| 105 | 新增: if err = os.Remove(pid); err != nil { | |
| 106 | 新增: t.Fatal(err) | |
| 107 | 新增: } | |
| 108 | 新增: writeStorageFixture(t, filepath.Join(instance, "disk"), []byte("original")) | |
| 109 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 110 | 新增: defer cancel() | |
| 111 | 新增: if _, err = MoveStorage(ctx, profile, target, storageExpectation(t, profile), func(int64, int64) { cancel() }); err == nil { | |
| 112 | 新增: t.Fatal("ignored cancel") | |
| 113 | 新增: } | |
| 114 | 新增: assertStorageFile(t, filepath.Join(instance, "disk"), []byte("original")) | |
| 115 | 新增: if _, err := MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil); err != nil { | |
| 116 | 新增: t.Fatal("retry after cancellation:", err) | |
| 117 | 新增: } | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:func TestStorageFirstUseAndCrashRollback(t *testing.T) { | |
| 121 | 新增: profile, root := newStorageFixture(t) | |
| 122 | 新增: first := filepath.Join(root, "fresh") | |
| 123 | 新增: loc, err := MoveStorage(context.Background(), profile, first, storageExpectation(t, profile), nil) | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: t.Fatal(err) | |
| 126 | 新增: } | |
| 127 | 新增: if loc.HasEnvironment || loc.Backup != "" || !loc.Custom { | |
| 128 | 新增: t.Fatal(loc) | |
| 129 | 新增: } | |
| 130 | 新增: payload := []byte("preserved") | |
| 131 | 新增: writeStorageFixture(t, filepath.Join(profile, "state", "user-data"), payload) | |
| 132 | 新增: target := filepath.Join(root, "interrupted") | |
| 133 | 新增: id := "1234567890abcdef1234567890abcdef" | |
| 134 | 新增: if err = os.MkdirAll(filepath.Join(target, "state"), 0700); err != nil { | |
| 135 | 新增: t.Fatal(err) | |
| 136 | 新增: } | |
| 137 | 新增: if err = claimStorageTarget(target, id); err != nil { | |
| 138 | 新增: t.Fatal(err) | |
| 139 | 新增: } | |
| 140 | 新增: if err = claimStorageTarget(filepath.Join(target, "state"), id); err != nil { | |
| 141 | 新增: t.Fatal(err) | |
| 142 | 新增: } | |
| 143 | 新增: p := storageMove{Next: storageRecord{Directory: target, ID: id}, PreviousCustom: true} | |
| 144 | 新增: if err = writeStorageJSON(filepath.Join(profile, pendingFile), p); err != nil { | |
| 145 | 新增: t.Fatal(err) | |
| 146 | 新增: } | |
| 147 | 新增: if err = os.Rename(storageAnchor(profile), filepath.Join(profile, "state-backup-"+id)); err != nil { | |
| 148 | 新增: t.Fatal(err) | |
| 149 | 新增: } | |
| 150 | 新增: if err = linkStorage(storageAnchor(profile), filepath.Join(target, "state")); err != nil { | |
| 151 | 新增: t.Fatal(err) | |
| 152 | 新增: } | |
| 153 | 新增: loc, err = GetStorageLocation(profile) | |
| 154 | 新增: if err != nil || loc.Directory != first { | |
| 155 | 新增: t.Fatalf("recovery: %+v %v", loc, err) | |
| 156 | 新增: } | |
| 157 | 新增: assertStorageFile(t, filepath.Join(profile, "state", "user-data"), payload) | |
| 158 | 新增: if _, err := MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil); err != nil { | |
| 159 | 新增: t.Fatal("retry after crash:", err) | |
| 160 | 新增: } | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:func TestStorageRollbackLeavesUnownedDestinationUntouched(t *testing.T) { | |
| 164 | 新增: profile, root := newStorageFixture(t) | |
| 165 | 新增: target := filepath.Join(root, "external") | |
| 166 | 新增: id := "abcdef1234567890abcdef1234567890" | |
| 167 | 新增: foreign := filepath.Join(target, "state", "user-files") | |
| 168 | 新增: writeStorageFixture(t, foreign, []byte("existing")) | |
| 169 | 新增: if err := claimStorageTarget(target, id); err != nil { | |
| 170 | 新增: t.Fatal(err) | |
| 171 | 新增: } | |
| 172 | 新增: if err := writeStorageJSON(filepath.Join(profile, pendingFile), storageMove{Next: storageRecord{Directory: target, ID: id}}); err != nil { | |
| 173 | 新增: t.Fatal(err) | |
| 174 | 新增: } | |
| 175 | 新增: if _, err := GetStorageLocation(profile); err != nil { | |
| 176 | 新增: t.Fatal(err) | |
| 177 | 新增: } | |
| 178 | 新增: assertStorageFile(t, foreign, []byte("existing")) | |
| 179 | 新增:} | |
| 180 | 新增: | |
| 181 | 新增:func storageExpectation(t *testing.T, profile string) StorageLocation { | |
| 182 | 新增: t.Helper() | |
| 183 | 新增: loc, err := GetStorageLocation(profile) | |
| 184 | 新增: if err != nil { | |
| 185 | 新增: t.Fatal(err) | |
| 186 | 新增: } | |
| 187 | 新增: return loc | |
| 188 | 新增:} | |
| 189 | 新增: | |
| 190 | 新增:// An attached test volume lets native QA exercise a genuine cross-volume | |
| 191 | 新增:// copy. The parent is never modified beyond the unique temporary folder. | |
| 192 | 新增:func TestStorageAcrossMountedVolume(t *testing.T) { | |
| 193 | 新增: base := os.Getenv("CAGE_TEST_STORAGE_VOLUME") | |
| 194 | 新增: if base == "" { | |
| 195 | 新增: t.Skip("set CAGE_TEST_STORAGE_VOLUME to a writable second volume") | |
| 196 | 新增: } | |
| 197 | 新增: profile, _ := newStorageFixture(t) | |
| 198 | 新增: testDir, err := os.MkdirTemp(base, "cage-storage-test-*") | |
| 199 | 新增: if err != nil { | |
| 200 | 新增: t.Fatal(err) | |
| 201 | 新增: } | |
| 202 | 新增: t.Cleanup(func() { os.RemoveAll(testDir) }) | |
| 203 | 新增: data := make([]byte, 2<<20) | |
| 204 | 新增: copy(data[len(data)-32:], []byte("second volume")) | |
| 205 | 新增: rel := filepath.Join("lima", "guest", "disk") | |
| 206 | 新增: writeStorageFixture(t, filepath.Join(profile, "state", rel), data) | |
| 207 | 新增: loc, err := MoveStorage(context.Background(), profile, testDir, storageExpectation(t, profile), nil) | |
| 208 | 新增: if err != nil { | |
| 209 | 新增: t.Fatal(err) | |
| 210 | 新增: } | |
| 211 | 新增: assertStorageFile(t, filepath.Join(testDir, "state", rel), data) | |
| 212 | 新增: assertStorageFile(t, filepath.Join(loc.Backup, rel), data) | |
| 213 | 新增: assertStorageFile(t, filepath.Join(profile, "state", rel), data) | |
| 214 | 新增:} | |
| 215 | 新增: | |
| 216 | 新增:func TestStorageRejectsStaleFirstUseDecision(t *testing.T) { | |
| 217 | 新增: profile, root := newStorageFixture(t) | |
| 218 | 新增: fresh := storageExpectation(t, profile) | |
| 219 | 新增: data := []byte("already running user data") | |
| 220 | 新增: disk := filepath.Join(profile, "state", "lima", "vm", "disk") | |
| 221 | 新增: writeStorageFixture(t, disk, data) | |
| 222 | 新增: if _, err := MoveStorage(context.Background(), profile, filepath.Join(root, "target"), fresh, nil); err == nil { | |
| 223 | 新增: t.Fatal("silently migrated a disk created after first-use confirmation") | |
| 224 | 新增: } | |
| 225 | 新增: assertStorageFile(t, disk, data) | |
| 226 | 新增:} | |
| 227 | 新增: | |
| 228 | 新增:func TestStorageResolvesAliasesToPrivateDisk(t *testing.T) { | |
| 229 | 新增: profile, root := newStorageFixture(t) | |
| 230 | 新增: target := filepath.Join(root, "private disk") | |
| 231 | 新增: loc, err := MoveStorage(context.Background(), profile, target, storageExpectation(t, profile), nil) | |
| 232 | 新增: if err != nil { | |
| 233 | 新增: t.Fatal(err) | |
| 234 | 新增: } | |
| 235 | 新增: alias := filepath.Join(root, "project-looking-alias") | |
| 236 | 新增: if err := linkStorage(alias, loc.Directory); err != nil { | |
| 237 | 新增: t.Fatal(err) | |
| 238 | 新增: } | |
| 239 | 新增: defer os.Remove(alias) | |
| 240 | 新增: logical := filepath.Join(alias, "state", "future-file") | |
| 241 | 新增: physical, err := StoragePhysicalPath(logical) | |
| 242 | 新增: if err != nil || !StorageContains(target, physical) { | |
| 243 | 新增: t.Fatalf("private path escaped through alias: %s: %v", physical, err) | |
| 244 | 新增: } | |
| 245 | 新增:} | |
| @@ -0,0 +1,54 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package cage | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "errors" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "syscall" | |
| 10 | 新增: | |
| 11 | 新增: "golang.org/x/sys/unix" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func lockStorageFile(f *os.File, exclusive bool) (bool, error) { | |
| 15 | 新增: mode := unix.LOCK_SH | |
| 16 | 新增: if exclusive { | |
| 17 | 新增: mode = unix.LOCK_EX | |
| 18 | 新增: } | |
| 19 | 新增: err := unix.Flock(int(f.Fd()), mode|unix.LOCK_NB) | |
| 20 | 新增: if errors.Is(err, unix.EWOULDBLOCK) { | |
| 21 | 新增: return false, nil | |
| 22 | 新增: } | |
| 23 | 新增: return err == nil, err | |
| 24 | 新增:} | |
| 25 | 新增:func linkStorage(link, target string) error { return os.Symlink(target, link) } | |
| 26 | 新增:func sparseStorageFile(*os.File) error { return nil } | |
| 27 | 新增: | |
| 28 | 新增:func storageMountRoot(path string) (bool, error) { | |
| 29 | 新增: fi, err := os.Stat(path) | |
| 30 | 新增: if err != nil { | |
| 31 | 新增: return false, err | |
| 32 | 新增: } | |
| 33 | 新增: parent, err := os.Stat(filepath.Dir(path)) | |
| 34 | 新增: if err != nil { | |
| 35 | 新增: return false, err | |
| 36 | 新增: } | |
| 37 | 新增: return fi.Sys().(*syscall.Stat_t).Dev != parent.Sys().(*syscall.Stat_t).Dev, nil | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func syncStorageDir(path string) error { | |
| 41 | 新增: f, err := os.Open(path) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return err | |
| 44 | 新增: } | |
| 45 | 新增: defer f.Close() | |
| 46 | 新增: return f.Sync() | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:func renameStorage(from, to string) error { | |
| 50 | 新增: if err := os.Rename(from, to); err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: return syncStorageDir(filepath.Dir(to)) | |
| 54 | 新增:} | |
| @@ -0,0 +1,24 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: | |
| 6 | 新增: "golang.org/x/sys/unix" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func localStorageVolume(path string) error { | |
| 10 | 新增: var info unix.Statfs_t | |
| 11 | 新增: if err := unix.Statfs(path, &info); err != nil { | |
| 12 | 新增: return err | |
| 13 | 新增: } | |
| 14 | 新增: if info.Flags&unix.MNT_LOCAL == 0 { | |
| 15 | 新增: return errors.New("环境存储需要本地磁盘") | |
| 16 | 新增: } | |
| 17 | 新增: if unix.ByteSliceToString(info.Fstypename[:]) != "apfs" { | |
| 18 | 新增: return errors.New("请选择本地 APFS 卷,环境需要私有文件权限和稀疏磁盘支持") | |
| 19 | 新增: } | |
| 20 | 新增: if info.Flags&unix.MNT_IGNORE_OWNERSHIP != 0 { | |
| 21 | 新增: return errors.New("请在 Finder 的磁盘“显示简介”中取消“忽略此宗卷的所有权”,或选择其他 APFS 磁盘") | |
| 22 | 新增: } | |
| 23 | 新增: return nil | |
| 24 | 新增:} | |
| @@ -0,0 +1,18 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "strings" | |
| 6 | 新增: "testing" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func TestStorageRefusesVolumeWithIgnoredOwnership(t *testing.T) { | |
| 10 | 新增: path := os.Getenv("CAGE_TEST_NOOWNERS_VOLUME") | |
| 11 | 新增: if path == "" { | |
| 12 | 新增: t.Skip("set CAGE_TEST_NOOWNERS_VOLUME to a test volume mounted noowners") | |
| 13 | 新增: } | |
| 14 | 新增: err := localStorageVolume(path) | |
| 15 | 新增: if err == nil || !strings.Contains(err.Error(), "所有权") { | |
| 16 | 新增: t.Fatalf("noowners volume check: %v", err) | |
| 17 | 新增: } | |
| 18 | 新增:} | |
| @@ -0,0 +1,21 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: | |
| 6 | 新增: "golang.org/x/sys/unix" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:func localStorageVolume(path string) error { | |
| 10 | 新增: var info unix.Statfs_t | |
| 11 | 新增: if err := unix.Statfs(path, &info); err != nil { | |
| 12 | 新增: return err | |
| 13 | 新增: } | |
| 14 | 新增: // Only admit filesystems with local disk, private mode and sparse-file | |
| 15 | 新增: // semantics. FUSE in particular may represent a remote mount. | |
| 16 | 新增: switch uint32(info.Type) { | |
| 17 | 新增: case unix.EXT4_SUPER_MAGIC, unix.XFS_SUPER_MAGIC, unix.BTRFS_SUPER_MAGIC, unix.F2FS_SUPER_MAGIC, unix.OVERLAYFS_SUPER_MAGIC, 0x2fc12fc1 /* zfs */, 0xca451a4e /* bcachefs */ : | |
| 18 | 新增: return nil | |
| 19 | 新增: } | |
| 20 | 新增: return errors.New("请选择支持私有权限和稀疏文件的本地磁盘(例如 ext4、XFS 或 Btrfs)") | |
| 21 | 新增:} | |
| @@ -0,0 +1,7 @@ | ||
| 1 | 新增://go:build !windows && !linux && !darwin | |
| 2 | 新增: | |
| 3 | 新增:package cage | |
| 4 | 新增: | |
| 5 | 新增:import "errors" | |
| 6 | 新增: | |
| 7 | 新增:func localStorageVolume(string) error { return errors.New("此平台不支持自定义环境存储") } | |
| @@ -0,0 +1,130 @@ | ||
| 1 | 新增:package cage | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/binary" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "strings" | |
| 9 | 新增: | |
| 10 | 新增: "golang.org/x/sys/windows" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func lockStorageFile(f *os.File, exclusive bool) (bool, error) { | |
| 14 | 新增: flags := uint32(windows.LOCKFILE_FAIL_IMMEDIATELY) | |
| 15 | 新增: if exclusive { | |
| 16 | 新增: flags |= windows.LOCKFILE_EXCLUSIVE_LOCK | |
| 17 | 新增: } | |
| 18 | 新增: err := windows.LockFileEx(windows.Handle(f.Fd()), flags, 0, 1, 0, new(windows.Overlapped)) | |
| 19 | 新增: if errors.Is(err, windows.ERROR_LOCK_VIOLATION) { | |
| 20 | 新增: return false, nil | |
| 21 | 新增: } | |
| 22 | 新增: return err == nil, err | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:func localStorageVolume(path string) error { | |
| 26 | 新增: volume := filepath.VolumeName(path) | |
| 27 | 新增: if len(volume) != 2 || strings.HasPrefix(path, `\\`) { | |
| 28 | 新增: return errors.New("请使用本地磁盘上的文件夹") | |
| 29 | 新增: } | |
| 30 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: return err | |
| 33 | 新增: } | |
| 34 | 新增: var volumePath [32768]uint16 | |
| 35 | 新增: if err = windows.GetVolumePathName(name, &volumePath[0], uint32(len(volumePath))); err != nil { | |
| 36 | 新增: return err | |
| 37 | 新增: } | |
| 38 | 新增: root := &volumePath[0] | |
| 39 | 新增: switch windows.GetDriveType(root) { | |
| 40 | 新增: case windows.DRIVE_FIXED, windows.DRIVE_REMOVABLE: | |
| 41 | 新增: default: | |
| 42 | 新增: return errors.New("请选择已连接的本地磁盘") | |
| 43 | 新增: } | |
| 44 | 新增: var flags uint32 | |
| 45 | 新增: if err = windows.GetVolumeInformation(root, nil, 0, nil, nil, &flags, nil, 0); err != nil { | |
| 46 | 新增: return err | |
| 47 | 新增: } | |
| 48 | 新增: const required = windows.FILE_PERSISTENT_ACLS | windows.FILE_SUPPORTS_SPARSE_FILES | |
| 49 | 新增: if flags&required != required { | |
| 50 | 新增: return errors.New("请使用支持私有文件权限和稀疏磁盘的本地卷,例如 NTFS") | |
| 51 | 新增: } | |
| 52 | 新增: return nil | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:// A mount-point reparse point works without Developer Mode or administrator | |
| 56 | 新增:// privileges. Use the native API so directory names are never shell input. | |
| 57 | 新增:func linkStorage(link, target string) (err error) { | |
| 58 | 新增: sub, err := windows.UTF16FromString(`\??\` + target) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: return err | |
| 61 | 新增: } | |
| 62 | 新增: label, err := windows.UTF16FromString(target) | |
| 63 | 新增: if err != nil { | |
| 64 | 新增: return err | |
| 65 | 新增: } | |
| 66 | 新增: data := make([]byte, 16+2*(len(sub)+len(label))) | |
| 67 | 新增: if len(data) > 16*1024 { | |
| 68 | 新增: return errors.New("存储路径过长") | |
| 69 | 新增: } | |
| 70 | 新增: binary.LittleEndian.PutUint32(data, windows.IO_REPARSE_TAG_MOUNT_POINT) | |
| 71 | 新增: binary.LittleEndian.PutUint16(data[4:], uint16(len(data)-8)) | |
| 72 | 新增: binary.LittleEndian.PutUint16(data[10:], uint16(2*(len(sub)-1))) | |
| 73 | 新增: binary.LittleEndian.PutUint16(data[12:], uint16(2*len(sub))) | |
| 74 | 新增: binary.LittleEndian.PutUint16(data[14:], uint16(2*(len(label)-1))) | |
| 75 | 新增: for i, c := range append(sub, label...) { | |
| 76 | 新增: binary.LittleEndian.PutUint16(data[16+i*2:], c) | |
| 77 | 新增: } | |
| 78 | 新增: if err = os.Mkdir(link, 0700); err != nil { | |
| 79 | 新增: return err | |
| 80 | 新增: } | |
| 81 | 新增: defer func() { | |
| 82 | 新增: if err != nil { | |
| 83 | 新增: _ = os.Remove(link) | |
| 84 | 新增: } | |
| 85 | 新增: }() | |
| 86 | 新增: path, err := windows.UTF16PtrFromString(link) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: h, err := windows.CreateFile(path, windows.GENERIC_WRITE, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_OPEN_REPARSE_POINT|windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: return err | |
| 93 | 新增: } | |
| 94 | 新增: defer windows.CloseHandle(h) | |
| 95 | 新增: var n uint32 | |
| 96 | 新增: return windows.DeviceIoControl(h, windows.FSCTL_SET_REPARSE_POINT, &data[0], uint32(len(data)), nil, 0, &n, nil) | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:func sparseStorageFile(f *os.File) error { | |
| 100 | 新增: var n uint32 | |
| 101 | 新增: return windows.DeviceIoControl(windows.Handle(f.Fd()), windows.FSCTL_SET_SPARSE, nil, 0, nil, 0, &n, nil) | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 104 | 新增:func storageMountRoot(path string) (bool, error) { | |
| 105 | 新增: name, err := windows.UTF16PtrFromString(path) | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return false, err | |
| 108 | 新增: } | |
| 109 | 新增: var root [32768]uint16 | |
| 110 | 新增: if err = windows.GetVolumePathName(name, &root[0], uint32(len(root))); err != nil { | |
| 111 | 新增: return false, err | |
| 112 | 新增: } | |
| 113 | 新增: return sameStoragePath(path, windows.UTF16ToString(root[:])), nil | |
| 114 | 新增:} | |
| 115 | 新增: | |
| 116 | 新增:// Windows commits the link and record renames with MOVEFILE_WRITE_THROUGH. | |
| 117 | 新增:// Flushing a directory via an ordinary user handle is unsupported. | |
| 118 | 新增:func syncStorageDir(string) error { return nil } | |
| 119 | 新增: | |
| 120 | 新增:func renameStorage(from, to string) error { | |
| 121 | 新增: src, err := windows.UTF16PtrFromString(from) | |
| 122 | 新增: if err != nil { | |
| 123 | 新增: return err | |
| 124 | 新增: } | |
| 125 | 新增: dst, err := windows.UTF16PtrFromString(to) | |
| 126 | 新增: if err != nil { | |
| 127 | 新增: return err | |
| 128 | 新增: } | |
| 129 | 新增: return windows.MoveFileEx(src, dst, windows.MOVEFILE_REPLACE_EXISTING|windows.MOVEFILE_WRITE_THROUGH) | |
| 130 | 新增:} | |
| @@ -1,8 +1,10 @@ | ||
| 1 | 1 | # Fixed upstream release assets; provenance is documented in docs/releasing.md. |
| 2 | 删除:CAGE_CODE_SERVER_VERSION=4.144.0 | |
| 3 | 删除:CAGE_CODE_SERVER_ARM64_SHA256=6baef72b340da08e76e5cf1e9504f657d00e80c8776bdaf86e97c30a80cd48e8 | |
| 4 | 删除:CAGE_CODE_SERVER_AMD64_SHA256=45f5533b502edac68b7eb09c5cec44fd281f80264af9a87fde0bfb2c5e190615 | |
| 2 | 新增:CAGE_CODE_SERVER_VERSION=4.145.0 | |
| 3 | 新增:CAGE_CODE_SERVER_ARM64_SHA256=43813b81df484b49facf19d99faaa51683a2cdd8c652dc97ebddefa9cbe7fd6a | |
| 4 | 新增:CAGE_CODE_SERVER_AMD64_SHA256=43fa1dc0e7929753bb3442e4ef40d4beb8bb5f8fe63601ede31b305536e6275b | |
| 5 | 5 | CAGE_MISE_VERSION=2026.10.25 |
| 6 | 6 | CAGE_MISE_ARM64_SHA256=a7d1e2add53441ff76e7e971e7a3fb15c117741836ce51c026f5fb7eebe7dbcf |
| 7 | 7 | CAGE_MISE_AMD64_SHA256=199966edaad1b208eb4c72955f1722dafb8fa799f575db720dea05aaa8216546 |
| 8 | 新增:CAGE_MISE_NPM_ARM64_SHA256=e60a51a1fd16a6fe2c6f821075000b9528f7281f42c33a9b9f812429d83a1824 | |
| 9 | 新增:CAGE_MISE_NPM_AMD64_SHA256=70150a3b5f53f524273c34a8eeff9ec9b2f343a4f066889470b5d368f9f7c3a8 | |
| 8 | 10 | CAGE_CLAUDE_VERSION=2.1.314 |
| @@ -7,6 +7,7 @@ import ( | ||
| 7 | 7 | "path/filepath" |
| 8 | 8 | "sync" |
| 9 | 9 | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 10 | 11 | "github.com/sylvinus/agent-vm/internal/paths" |
| 11 | 12 | "github.com/sylvinus/agent-vm/internal/state" |
| 12 | 13 | "github.com/sylvinus/agent-vm/internal/ui" |
| @@ -16,9 +17,12 @@ import ( | ||
| 16 | 17 | |
| 17 | 18 | // app is what the commands work with. |
| 18 | 19 | type app struct { |
| 19 | 删除: io IO | |
| 20 | 删除: ui *ui.UI | |
| 21 | 删除: state state.Dir | |
| 20 | 新增: io IO | |
| 21 | 新增: ui *ui.UI | |
| 22 | 新增: state state.Dir | |
| 23 | 新增: privateStorage []string | |
| 24 | 新增: names vmname.Limit | |
| 25 | 新增: cageProfile string | |
| 22 | 26 | |
| 23 | 27 | migrateOnce sync.Once |
| 24 | 28 | migrate func() // moves 0.2's VMs, when set |
| @@ -105,7 +109,7 @@ func (e *app) migrateOld(ctx context.Context, old, now string) { | ||
| 105 | 109 | if v.Running { |
| 106 | 110 | state, running = " (running)", true |
| 107 | 111 | } |
| 108 | 删除: fmt.Fprintf(w, " %s, as %s%s\n", v.Name, vmname.FromOld(v.Name), state) | |
| 112 | 新增: fmt.Fprintf(w, " %s, as %s%s\n", v.Name, e.names.FromOld(v.Name), state) | |
| 109 | 113 | } |
| 110 | 114 | canAsk := e.ui.CanAsk() |
| 111 | 115 | if running && canAsk { |
| @@ -122,7 +126,7 @@ func (e *app) migrateOld(ctx context.Context, old, now string) { | ||
| 122 | 126 | failed = true |
| 123 | 127 | continue |
| 124 | 128 | } |
| 125 | 删除: to := vmname.FromOld(v.Name) | |
| 129 | 新增: to := e.names.FromOld(v.Name) | |
| 126 | 130 | fmt.Fprintf(w, "Moving %s...\n", v.Name) |
| 127 | 131 | if err := vm.MoveOld(ctx, old, now, v.Name, to); err != nil { |
| 128 | 132 | fmt.Fprintf(w, "Error: could not move %s: %v. It stays in %s.\n", v.Name, err, old) |
| @@ -174,11 +178,17 @@ func newApp(io IO) (*app, error) { | ||
| 174 | 178 | e := &app{io: io, ui: u, state: st} |
| 175 | 179 | // Names that fit this machine's socket paths (a long home, a long user |
| 176 | 180 | // name): cut in their folder part, not refused. |
| 177 | 删除: vmname.MaxLen = vm.MaxName(LimaHome(st)) | |
| 181 | 新增: e.names = vmname.Limit(vm.MaxName(LimaHome(st))) | |
| 178 | 182 | e.migrate = func() { e.migrateOld(context.Background(), oldLimaHome(), LimaHome(st)) } |
| 179 | 183 | // Cage owns a separate profile; it never imports another tool's VMs. |
| 180 | 删除: if os.Getenv("CLAUDE_CAGE_CONFIG") != "" { | |
| 184 | 新增: if config := os.Getenv(cage.ConfigEnv); config != "" { | |
| 181 | 185 | e.migrate = nil |
| 186 | 新增: e.cageProfile = filepath.Dir(config) | |
| 187 | 新增: e.privateStorage, err = cage.StoragePrivatePaths(filepath.Dir(config)) | |
| 188 | 新增: if err != nil { | |
| 189 | 新增: return nil, err | |
| 190 | 新增: } | |
| 191 | 新增: e.privateStorage = append(e.privateStorage, filepath.Dir(config)) | |
| 182 | 192 | } |
| 183 | 193 | e.newBack = func() (vm.Backend, error) { |
| 184 | 194 | // Every VM there is agent-vm's: list, rm and destroy-all take them |
| @@ -190,3 +200,10 @@ func newApp(io IO) (*app, error) { | ||
| 190 | 200 | } |
| 191 | 201 | return e, nil |
| 192 | 202 | } |
| 203 | 新增: | |
| 204 | 新增:func (e *app) instanceName(dir string) string { | |
| 205 | 新增: if e.cageProfile != "" { | |
| 206 | 新增: return cage.InstanceName(e.cageProfile, dir) | |
| 207 | 新增: } | |
| 208 | 新增: return e.names.Name(dir) | |
| 209 | 新增:} | |
| @@ -97,7 +97,7 @@ func (e *app) main(ctx context.Context, args []string) int { | ||
| 97 | 97 | case "licenses": |
| 98 | 98 | return licensesCmd(args, io) |
| 99 | 99 | case "name": |
| 100 | 删除: return nameCmd(args, io) | |
| 100 | 新增: return e.nameCmd(args, io) | |
| 101 | 101 | case "list", "status": |
| 102 | 102 | return e.listCmd(ctx, args) |
| 103 | 103 | case "stop": |
| @@ -195,7 +195,7 @@ func updateCommandFor(exe string) string { | ||
| 195 | 195 | } |
| 196 | 196 | |
| 197 | 197 | // `name [dir]`: the VM name of a directory, the current one by default. |
| 198 | 删除:func nameCmd(args []string, io IO) int { | |
| 198 | 新增:func (e *app) nameCmd(args []string, io IO) int { | |
| 199 | 199 | dir := "" |
| 200 | 200 | if len(args) > 0 { |
| 201 | 201 | dir = args[0] |
| @@ -205,7 +205,7 @@ func nameCmd(args []string, io IO) int { | ||
| 205 | 205 | fmt.Fprintf(io.Stderr, "Error: %v\n", err) |
| 206 | 206 | return 1 |
| 207 | 207 | } |
| 208 | 删除: fmt.Fprintln(io.Stdout, vmname.Name(abs)) | |
| 208 | 新增: fmt.Fprintln(io.Stdout, e.instanceName(abs)) | |
| 209 | 209 | return 0 |
| 210 | 210 | } |
| 211 | 211 | |
| @@ -66,7 +66,7 @@ func (e *app) inVM(ctx context.Context, opts VMOpts, fn session) int { | ||
| 66 | 66 | if opts.Scratch { |
| 67 | 67 | return e.scratch(ctx, cleanup, opts, dir, fn) |
| 68 | 68 | } |
| 69 | 删除: s := &start{app: e, ctx: ctx, opts: opts, dir: dir, name: vmname.Name(dir)} | |
| 69 | 新增: s := &start{app: e, ctx: ctx, opts: opts, dir: dir, name: e.instanceName(dir)} | |
| 70 | 70 | if os.Getenv("CLAUDE_CAGE_CONFIG") != "" { |
| 71 | 71 | b, err := s.backend() |
| 72 | 72 | if err != nil { |
| @@ -260,7 +260,7 @@ func (e *app) scratch(ctx, cleanup context.Context, opts VMOpts, dir string, fn | ||
| 260 | 260 | for _, left := range unknown { |
| 261 | 261 | fmt.Fprintf(e.io.Stderr, "Note: scratch VM '%s' has a record without a process number, so it is not known whether a run still uses it: left alone. 'agent-vm rm %s' deletes it.\n", left, left) |
| 262 | 262 | } |
| 263 | 删除: name, err := vmname.Scratch(dir) | |
| 263 | 新增: name, err := e.names.Scratch(dir) | |
| 264 | 264 | if err != nil { |
| 265 | 265 | fmt.Fprintf(e.io.Stderr, "Error: %v\n", err) |
| 266 | 266 | return 1 |
| @@ -87,9 +87,6 @@ func (e *app) doctorCmd(ctx context.Context, args []string) int { | ||
| 87 | 87 | d.line("warn", "could not read the host's CPU or RAM: --cpus and --memory are not clamped") |
| 88 | 88 | } |
| 89 | 89 | dir := LimaHome(e.state) |
| 90 | 删除: if _, err := os.Stat(dir); err != nil { | |
| 91 | 删除: dir, _ = os.UserHomeDir() | |
| 92 | 删除: } | |
| 93 | 90 | switch free, ok := host.FreeGiB(dir); { |
| 94 | 91 | case !ok: |
| 95 | 92 | d.line("warn", "could not read the free disk space") |
| @@ -281,7 +278,7 @@ func (d *doctor) directory(ctx context.Context, dir string, protects bool, getVM | ||
| 281 | 278 | } |
| 282 | 279 | scan := e.scan(ctx, dir) |
| 283 | 280 | names := scan.Names() |
| 284 | 删除: name := vmname.Name(dir) | |
| 281 | 新增: name := e.instanceName(dir) | |
| 285 | 282 | inst, err := getVM(name) |
| 286 | 283 | switch { |
| 287 | 284 | case err != nil: |
| @@ -23,11 +23,13 @@ import ( | ||
| 23 | 23 | func (e *app) refs() []mounts.Ref { |
| 24 | 24 | self := "" |
| 25 | 25 | if exe, err := os.Executable(); err == nil { |
| 26 | 删除: if p, err := filepath.EvalSymlinks(exe); err == nil { | |
| 26 | 新增: if p, err := paths.Resolve(exe); err == nil { | |
| 27 | 27 | self = paths.Host(filepath.Dir(p)) |
| 28 | 28 | } |
| 29 | 29 | } |
| 30 | 删除: return mounts.Refs(paths.Home(), self, string(e.state), LimaHome(e.state), oldLimaHome()) | |
| 30 | 新增: private := []string{LimaHome(e.state), oldLimaHome()} | |
| 31 | 新增: private = append(private, e.privateStorage...) | |
| 32 | 新增: return mounts.Refs(paths.Home(), self, string(e.state), private...) | |
| 31 | 33 | } |
| 32 | 34 | |
| 33 | 35 | // entries are the usable entries of ~/.agent-vm/volumes for the project |
| @@ -79,7 +81,7 @@ func (e *app) infoCmd(ctx context.Context, args []string) int { | ||
| 79 | 81 | fmt.Fprintf(e.io.Stderr, "Error: %v\n", err) |
| 80 | 82 | return 1 |
| 81 | 83 | } |
| 82 | 删除: name := vmname.Name(dir) | |
| 84 | 新增: name := e.instanceName(dir) | |
| 83 | 85 | w := e.io.Stdout |
| 84 | 86 | fmt.Fprintf(w, "version=%s\n", version.Version) |
| 85 | 87 | fmt.Fprintf(w, "template=%s\n", vmname.Template) |
| @@ -533,7 +533,11 @@ func (e *app) buildBase(ctx context.Context, in install, disk, memory, cpus int) | ||
| 533 | 533 | |
| 534 | 534 | func cageInstallEnv() string { |
| 535 | 535 | if os.Getenv("CLAUDE_CAGE_CONFIG") != "" { |
| 536 | 删除: return "export CLAUDE_CAGE=1\n" + cage.ToolInstallPrelude() | |
| 536 | 新增: progress := "" | |
| 537 | 新增: if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 538 | 新增: progress = "export CAGE_SETUP_PROGRESS=1\n" | |
| 539 | 新增: } | |
| 540 | 新增: return "set -e\nexport CLAUDE_CAGE=1\n" + progress + cage.DebianMirrorsScript + "\n" + cage.ToolInstallPrelude() | |
| 537 | 541 | } |
| 538 | 542 | return "" |
| 539 | 543 | } |
| @@ -28,7 +28,7 @@ func (e *app) target(ctx context.Context, verb string, args []string) (name stri | ||
| 28 | 28 | fmt.Fprintf(e.io.Stderr, "Error: %v\n", err) |
| 29 | 29 | return "", 1 |
| 30 | 30 | } |
| 31 | 删除: name = vmname.Name(wd) | |
| 31 | 新增: name = e.instanceName(wd) | |
| 32 | 32 | case 1: |
| 33 | 33 | name = args[0] |
| 34 | 34 | default: |
| @@ -209,7 +209,7 @@ func (e *app) listCmd(ctx context.Context, args []string) int { | ||
| 209 | 209 | } |
| 210 | 210 | current := "" |
| 211 | 211 | if wd, err := vmname.AbsDir(""); err == nil { |
| 212 | 删除: current = vmname.Name(wd) | |
| 212 | 新增: current = e.instanceName(wd) | |
| 213 | 213 | } |
| 214 | 214 | vms, err := e.lookVMs(ctx) |
| 215 | 215 | if err != nil { |
| @@ -0,0 +1,185 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/ed25519" | |
| 7 | 新增: "crypto/rand" | |
| 8 | 新增: "encoding/pem" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "fmt" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path/filepath" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 18 | 新增: "golang.org/x/crypto/ssh" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:func (r *Runtime) ensureSSHKey() ([]byte, error) { | |
| 22 | 新增: if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { | |
| 23 | 新增: return nil, err | |
| 24 | 新增: } | |
| 25 | 新增: path := filepath.Join(r.InstanceDir(), "id_ed25519") | |
| 26 | 新增: if data, err := os.ReadFile(path); err == nil { | |
| 27 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 28 | 新增: return nil, err | |
| 29 | 新增: } | |
| 30 | 新增: key, err := ssh.ParsePrivateKey(data) | |
| 31 | 新增: if err != nil { | |
| 32 | 新增: return nil, errors.New("容器 SSH 密钥无效;未覆盖现有密钥") | |
| 33 | 新增: } | |
| 34 | 新增: return ssh.MarshalAuthorizedKey(key.PublicKey()), nil | |
| 35 | 新增: } else if !os.IsNotExist(err) { | |
| 36 | 新增: return nil, err | |
| 37 | 新增: } | |
| 38 | 新增: _, private, err := ed25519.GenerateKey(rand.Reader) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return nil, err | |
| 41 | 新增: } | |
| 42 | 新增: block, err := ssh.MarshalPrivateKey(private, "Cage container") | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return nil, err | |
| 45 | 新增: } | |
| 46 | 新增: file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0600) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return nil, err | |
| 49 | 新增: } | |
| 50 | 新增: err = pem.Encode(file, block) | |
| 51 | 新增: if closeErr := file.Close(); err == nil { | |
| 52 | 新增: err = closeErr | |
| 53 | 新增: } | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: return nil, err | |
| 56 | 新增: } | |
| 57 | 新增: key, err := ssh.NewPublicKey(private.Public()) | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return nil, err | |
| 60 | 新增: } | |
| 61 | 新增: return ssh.MarshalAuthorizedKey(key), nil | |
| 62 | 新增:} | |
| 63 | 新增: | |
| 64 | 新增:// InstallAccess provisions only this runtime's generated public key. Private | |
| 65 | 新增:// SSH keys stay in the host profile. It does not expose a container port. | |
| 66 | 新增:func (r *Runtime) InstallAccess(ctx context.Context) error { | |
| 67 | 新增: inspection, err := r.Inspect(ctx) | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: if !inspection.State.Running { | |
| 72 | 新增: return errors.New("请先启动容器") | |
| 73 | 新增: } | |
| 74 | 新增: public, err := r.ensureSSHKey() | |
| 75 | 新增: if err != nil { | |
| 76 | 新增: return err | |
| 77 | 新增: } | |
| 78 | 新增: command := r.command(ctx, "exec", "-i", "--user", "0", inspection.State.ContainerID, "/bin/sh", "-c", `set -eu | |
| 79 | 新增:test -d /home/cage | |
| 80 | 新增:umask 077 | |
| 81 | 新增:cat > /etc/ssh/cage_authorized_keys | |
| 82 | 新增:chmod 0644 /etc/ssh/cage_authorized_keys | |
| 83 | 新增:ssh-keygen -A | |
| 84 | 新增:cat /etc/ssh/ssh_host_ed25519_key.pub | |
| 85 | 新增:`) | |
| 86 | 新增: command.Stdin = bytes.NewReader(public) | |
| 87 | 新增: var output bytes.Buffer | |
| 88 | 新增: command.Stdout = &limitedWriter{writer: &output, left: 4096} | |
| 89 | 新增: if err := command.Run(); err != nil { | |
| 90 | 新增: return errors.New("无法配置容器 SSH 访问") | |
| 91 | 新增: } | |
| 92 | 新增: key, _, _, rest, err := ssh.ParseAuthorizedKey(output.Bytes()) | |
| 93 | 新增: if err != nil || len(bytes.TrimSpace(rest)) != 0 || key.Type() != ssh.KeyAlgoED25519 { | |
| 94 | 新增: return errors.New("容器 SSH 主机密钥无效") | |
| 95 | 新增: } | |
| 96 | 新增: line := "cage-container-" + r.identity + " " + strings.TrimSpace(string(ssh.MarshalAuthorizedKey(key))) + "\n" | |
| 97 | 新增: path := filepath.Join(r.InstanceDir(), "known_hosts") | |
| 98 | 新增: if old, err := os.ReadFile(path); err == nil { | |
| 99 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 100 | 新增: return err | |
| 101 | 新增: } | |
| 102 | 新增: if !bytes.Equal(old, []byte(line)) { | |
| 103 | 新增: return errors.New("容器 SSH 主机密钥已变化;拒绝覆盖信任记录") | |
| 104 | 新增: } | |
| 105 | 新增: return nil | |
| 106 | 新增: } else if !os.IsNotExist(err) { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: return os.WriteFile(path, []byte(line), 0600) | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:func sshConfigValue(value string) (string, error) { | |
| 113 | 新增: if strings.ContainsAny(value, "\x00\r\n") { | |
| 114 | 新增: return "", errors.New("SSH 配置路径无效") | |
| 115 | 新增: } | |
| 116 | 新增: return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value) + `"`, nil | |
| 117 | 新增:} | |
| 118 | 新增: | |
| 119 | 新增:func (r *Runtime) writeSSHConfig(port int) error { | |
| 120 | 新增: if port < 1024 || port > 65535 { | |
| 121 | 新增: return errors.New("容器 SSH 入口端口无效") | |
| 122 | 新增: } | |
| 123 | 新增: identity, err := sshConfigValue(filepath.Join(r.InstanceDir(), "id_ed25519")) | |
| 124 | 新增: if err != nil { | |
| 125 | 新增: return err | |
| 126 | 新增: } | |
| 127 | 新增: known, err := sshConfigValue(filepath.Join(r.InstanceDir(), "known_hosts")) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: return err | |
| 130 | 新增: } | |
| 131 | 新增: data := fmt.Sprintf("Host cage-container\n HostName 127.0.0.1\n Port %d\n User cage\n IdentityFile %s\n IdentitiesOnly yes\n HostKeyAlias cage-container-%s\n HostKeyAlgorithms ssh-ed25519\n UserKnownHostsFile %s\n StrictHostKeyChecking yes\n PasswordAuthentication no\n KbdInteractiveAuthentication no\n ForwardAgent no\n ForwardX11 no\n PermitLocalCommand no\n", port, identity, r.identity, known) | |
| 132 | 新增: return os.WriteFile(r.SSHConfig(), []byte(data), 0600) | |
| 133 | 新增:} | |
| 134 | 新增: | |
| 135 | 新增:// Stop retains the complete container filesystem and host profile. Only the | |
| 136 | 新增:// exact, labelled container of this profile is ever stopped; no rm is issued. | |
| 137 | 新增:func (r *Runtime) Stop(ctx context.Context) error { | |
| 138 | 新增: if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: unlock, err := lockRuntime(ctx, filepath.Join(r.InstanceDir(), "lifecycle.lock")) | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: defer unlock() | |
| 146 | 新增: rootless, _, err := r.engineSecurity(ctx) | |
| 147 | 新增: if err != nil { | |
| 148 | 新增: return err | |
| 149 | 新增: } | |
| 150 | 新增: if !rootless { | |
| 151 | 新增: return errors.New("拒绝操作非 rootless 容器引擎") | |
| 152 | 新增: } | |
| 153 | 新增: container, err := r.inspectContainer(ctx) | |
| 154 | 新增: if err != nil { | |
| 155 | 新增: return err | |
| 156 | 新增: } | |
| 157 | 新增: if container == nil { | |
| 158 | 新增: return nil | |
| 159 | 新增: } | |
| 160 | 新增: if client, err := cage.OpenGateClient(r.InstanceDir()); err == nil { | |
| 161 | 新增: closeCtx, cancel := context.WithTimeout(ctx, 3*time.Second) | |
| 162 | 新增: _, _ = client.Close(closeCtx, "容器正在停止") | |
| 163 | 新增: cancel() | |
| 164 | 新增: } | |
| 165 | 新增: if container.State.Running { | |
| 166 | 新增: if _, err = r.output(ctx, "stop", "--time", "20", container.ID); err != nil { | |
| 167 | 新增: return err | |
| 168 | 新增: } | |
| 169 | 新增: } | |
| 170 | 新增: // Wait for the old network owner's deferred cleanup before allowing another | |
| 171 | 新增: // Start to publish new credentials or runtime records in the same directory. | |
| 172 | 新增: cleanupCtx, cancel := context.WithTimeout(ctx, 10*time.Second) | |
| 173 | 新增: defer cancel() | |
| 174 | 新增: release, err := lockRuntime(cleanupCtx, filepath.Join(r.InstanceDir(), "network.lock")) | |
| 175 | 新增: if err != nil { | |
| 176 | 新增: return errors.New("容器已停止,网络服务仍在退出;原文件保留,请稍后重试") | |
| 177 | 新增: } | |
| 178 | 新增: defer release() | |
| 179 | 新增: for _, name := range []string{"network.json", "cage-running.json"} { | |
| 180 | 新增: if err := os.Remove(filepath.Join(r.InstanceDir(), name)); err != nil && !os.IsNotExist(err) { | |
| 181 | 新增: return err | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: return nil | |
| 185 | 新增:} | |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/ecdsa" | |
| 5 | 新增: "crypto/ed25519" | |
| 6 | 新增: "crypto/elliptic" | |
| 7 | 新增: "crypto/rand" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "net" | |
| 10 | 新增: "os" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "golang.org/x/crypto/ssh" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func TestGuestSSHNegotiatesPinnedHostKeyAndRejectsReplacement(t *testing.T) { | |
| 19 | 新增: r := newRuntime(t.TempDir(), fixtureConfig()) | |
| 20 | 新增: if _, err := r.ensureSSHKey(); err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: _, private, err := ed25519.GenerateKey(rand.Reader) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: pinned, err := ssh.NewSignerFromKey(private) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: other, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: ecdsaHost, err := ssh.NewSignerFromKey(other) | |
| 36 | 新增: if err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: known := fmt.Sprintf("cage-container-%s %s", r.identity, ssh.MarshalAuthorizedKey(pinned.PublicKey())) | |
| 40 | 新增: if err := os.WriteFile(filepath.Join(r.InstanceDir(), "known_hosts"), []byte(known), 0600); err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: configuration, err := r.guestSSHConfiguration() | |
| 44 | 新增: if err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: for _, replacement := range []bool{false, true} { | |
| 48 | 新增: hostKey := pinned | |
| 49 | 新增: if replacement { | |
| 50 | 新增: _, private, err := ed25519.GenerateKey(rand.Reader) | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: hostKey, err = ssh.NewSignerFromKey(private) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: } | |
| 59 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: t.Fatal(err) | |
| 62 | 新增: } | |
| 63 | 新增: serverDone := make(chan struct{}) | |
| 64 | 新增: go func() { | |
| 65 | 新增: defer close(serverDone) | |
| 66 | 新增: connection, err := listener.Accept() | |
| 67 | 新增: if err != nil { | |
| 68 | 新增: return | |
| 69 | 新增: } | |
| 70 | 新增: defer connection.Close() | |
| 71 | 新增: _ = connection.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 72 | 新增: serverConfig := &ssh.ServerConfig{NoClientAuth: true} | |
| 73 | 新增: serverConfig.AddHostKey(ecdsaHost) | |
| 74 | 新增: serverConfig.AddHostKey(hostKey) | |
| 75 | 新增: server, _, _, err := ssh.NewServerConn(connection, serverConfig) | |
| 76 | 新增: if err == nil { | |
| 77 | 新增: server.Close() | |
| 78 | 新增: } | |
| 79 | 新增: }() | |
| 80 | 新增: connection, err := net.DialTimeout("tcp", listener.Addr().String(), time.Second) | |
| 81 | 新增: if err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增: _ = connection.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 85 | 新增: client, _, _, err := ssh.NewClientConn(connection, "cage-container-"+r.identity+":22", configuration) | |
| 86 | 新增: if replacement && err == nil { | |
| 87 | 新增: t.Error("replaced guest host key was accepted") | |
| 88 | 新增: } | |
| 89 | 新增: if !replacement && err != nil { | |
| 90 | 新增: t.Errorf("pinned ED25519 key was not negotiated alongside ECDSA: %v", err) | |
| 91 | 新增: } | |
| 92 | 新增: if client != nil { | |
| 93 | 新增: client.Close() | |
| 94 | 新增: } | |
| 95 | 新增: connection.Close() | |
| 96 | 新增: listener.Close() | |
| 97 | 新增: <-serverDone | |
| 98 | 新增: } | |
| 99 | 新增:} | |
| @@ -0,0 +1,161 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "encoding/hex" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "regexp" | |
| 12 | 新增: "strings" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:const profileLabel = "cn.cage.profile" | |
| 18 | 新增: | |
| 19 | 新增:type Config struct { | |
| 20 | 新增: Engine string `json:"engine"` | |
| 21 | 新增: Executable string `json:"executable"` | |
| 22 | 新增: Socket string `json:"socket,omitempty"` | |
| 23 | 新增: Image string `json:"image"` | |
| 24 | 新增: CPUs int `json:"cpus"` | |
| 25 | 新增: MemoryBytes int64 `json:"memory_bytes"` | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:type Runtime struct { | |
| 29 | 新增: profile string | |
| 30 | 新增: config Config | |
| 31 | 新增: identity string | |
| 32 | 新增:} | |
| 33 | 新增: | |
| 34 | 新增:var imageIDPattern = regexp.MustCompile(`^(?:sha256:|[a-zA-Z0-9][a-zA-Z0-9./:_-]*@sha256:)[a-f0-9]{64}$`) | |
| 35 | 新增: | |
| 36 | 新增:func (c Config) Validate() error { | |
| 37 | 新增: if c.Engine != "docker" && c.Engine != "podman" { | |
| 38 | 新增: return errors.New("容器引擎必须是 rootless Docker 或 Podman") | |
| 39 | 新增: } | |
| 40 | 新增: if !filepath.IsAbs(c.Executable) || strings.ContainsAny(c.Executable, "\x00\r\n") { | |
| 41 | 新增: return errors.New("容器引擎必须使用绝对路径") | |
| 42 | 新增: } | |
| 43 | 新增: if c.Engine == "docker" && (!strings.HasPrefix(c.Socket, "unix:///") || strings.ContainsAny(c.Socket, "\x00\r\n?#")) { | |
| 44 | 新增: return errors.New("Docker 必须使用独立的本机 rootless Unix socket") | |
| 45 | 新增: } | |
| 46 | 新增: if c.Engine == "podman" && c.Socket != "" { | |
| 47 | 新增: return errors.New("Podman 运行环境不使用远程服务 socket") | |
| 48 | 新增: } | |
| 49 | 新增: if !imageIDPattern.MatchString(c.Image) { | |
| 50 | 新增: return errors.New("容器镜像必须固定为 SHA-256 image ID 或 registry digest") | |
| 51 | 新增: } | |
| 52 | 新增: if c.CPUs < 1 || c.CPUs > 256 || c.MemoryBytes < 512<<20 { | |
| 53 | 新增: return errors.New("容器 CPU 或内存限制无效") | |
| 54 | 新增: } | |
| 55 | 新增: return nil | |
| 56 | 新增:} | |
| 57 | 新增: | |
| 58 | 新增:func Configured(profile string) bool { | |
| 59 | 新增: _, err := os.Lstat(filepath.Join(profile, "container.json")) | |
| 60 | 新增: return !os.IsNotExist(err) | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func Load(profile string) (*Runtime, error) { | |
| 64 | 新增: profile, err := filepath.Abs(profile) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return nil, err | |
| 67 | 新增: } | |
| 68 | 新增: path := filepath.Join(profile, "container.json") | |
| 69 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 70 | 新增: return nil, err | |
| 71 | 新增: } | |
| 72 | 新增: file, err := os.Open(path) | |
| 73 | 新增: if err != nil { | |
| 74 | 新增: return nil, err | |
| 75 | 新增: } | |
| 76 | 新增: defer file.Close() | |
| 77 | 新增: var config Config | |
| 78 | 新增: decoder := json.NewDecoder(io.LimitReader(file, 64<<10)) | |
| 79 | 新增: decoder.DisallowUnknownFields() | |
| 80 | 新增: if err := decoder.Decode(&config); err != nil { | |
| 81 | 新增: return nil, errors.New("容器配置格式无效") | |
| 82 | 新增: } | |
| 83 | 新增: var extra any | |
| 84 | 新增: if decoder.Decode(&extra) != io.EOF { | |
| 85 | 新增: return nil, errors.New("容器配置必须只有一个 JSON 对象") | |
| 86 | 新增: } | |
| 87 | 新增: if err := config.Validate(); err != nil { | |
| 88 | 新增: return nil, err | |
| 89 | 新增: } | |
| 90 | 新增: return newRuntime(profile, config), nil | |
| 91 | 新增:} | |
| 92 | 新增: | |
| 93 | 新增:func Configure(profile string, config Config) (*Runtime, error) { | |
| 94 | 新增: if err := config.Validate(); err != nil { | |
| 95 | 新增: return nil, err | |
| 96 | 新增: } | |
| 97 | 新增: profile, err := filepath.Abs(profile) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return nil, err | |
| 100 | 新增: } | |
| 101 | 新增: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 102 | 新增: return nil, err | |
| 103 | 新增: } | |
| 104 | 新增: // Changing a runtime would strand the full persistent filesystem. Require | |
| 105 | 新增: // an explicit migration path rather than silently creating another one. | |
| 106 | 新增: if Configured(profile) { | |
| 107 | 新增: existing, err := Load(profile) | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: return nil, err | |
| 110 | 新增: } | |
| 111 | 新增: if existing.config != config { | |
| 112 | 新增: return nil, errors.New("已有容器配置不能直接替换;请保留现有环境并执行迁移") | |
| 113 | 新增: } | |
| 114 | 新增: return existing, nil | |
| 115 | 新增: } | |
| 116 | 新增: if err := writePrivateJSON(filepath.Join(profile, "container.json"), config); err != nil { | |
| 117 | 新增: return nil, err | |
| 118 | 新增: } | |
| 119 | 新增: return newRuntime(profile, config), nil | |
| 120 | 新增:} | |
| 121 | 新增: | |
| 122 | 新增:func newRuntime(profile string, config Config) *Runtime { | |
| 123 | 新增: digest := sha256.Sum256([]byte(profile)) | |
| 124 | 新增: return &Runtime{profile: profile, config: config, identity: hex.EncodeToString(digest[:16])} | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:func (r *Runtime) Config() Config { return r.config } | |
| 128 | 新增:func (r *Runtime) InstanceDir() string { | |
| 129 | 新增: return filepath.Join(r.profile, "state", "container", "environment") | |
| 130 | 新增:} | |
| 131 | 新增:func (r *Runtime) SSHConfig() string { return filepath.Join(r.InstanceDir(), "ssh.config") } | |
| 132 | 新增:func (r *Runtime) SSHTarget() string { return "cage-container" } | |
| 133 | 新增:func (r *Runtime) Name() string { return "cage-" + r.identity } | |
| 134 | 新增: | |
| 135 | 新增:func writePrivateJSON(path string, value any) error { | |
| 136 | 新增: if err := host.EnsurePrivateDir(filepath.Dir(path)); err != nil { | |
| 137 | 新增: return err | |
| 138 | 新增: } | |
| 139 | 新增: data, err := json.Marshal(value) | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return err | |
| 142 | 新增: } | |
| 143 | 新增: file, err := os.CreateTemp(filepath.Dir(path), ".container-*") | |
| 144 | 新增: if err != nil { | |
| 145 | 新增: return err | |
| 146 | 新增: } | |
| 147 | 新增: defer os.Remove(file.Name()) | |
| 148 | 新增: if err = host.ProtectFile(file.Name()); err == nil { | |
| 149 | 新增: _, err = file.Write(data) | |
| 150 | 新增: } | |
| 151 | 新增: if err == nil { | |
| 152 | 新增: err = file.Sync() | |
| 153 | 新增: } | |
| 154 | 新增: if closeErr := file.Close(); err == nil { | |
| 155 | 新增: err = closeErr | |
| 156 | 新增: } | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: return err | |
| 159 | 新增: } | |
| 160 | 新增: return os.Rename(file.Name(), path) | |
| 161 | 新增:} | |
| @@ -0,0 +1,134 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "strings" | |
| 7 | 新增: "testing" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func fixtureConfig() Config { | |
| 11 | 新增: return Config{Engine: "docker", Executable: filepath.Join(os.TempDir(), "cage-test-bin", "docker"), Socket: "unix:///tmp/cage-test.sock", Image: "sha256:" + strings.Repeat("a", 64), CPUs: 2, MemoryBytes: 4 << 30} | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:func TestConfigRequiresPinnedLocalRootlessEngine(t *testing.T) { | |
| 15 | 新增: for _, change := range []func(*Config){ | |
| 16 | 新增: func(c *Config) { c.Socket = "tcp://127.0.0.1:2375" }, | |
| 17 | 新增: func(c *Config) { c.Socket = "unix:///tmp/cage.sock\n--privileged" }, | |
| 18 | 新增: func(c *Config) { c.Image = "debian:13" }, | |
| 19 | 新增: func(c *Config) { c.Executable = "docker" }, | |
| 20 | 新增: } { | |
| 21 | 新增: config := fixtureConfig() | |
| 22 | 新增: change(&config) | |
| 23 | 新增: if config.Validate() == nil { | |
| 24 | 新增: t.Fatalf("accepted unsafe config %+v", config) | |
| 25 | 新增: } | |
| 26 | 新增: } | |
| 27 | 新增: profile := t.TempDir() | |
| 28 | 新增: current, err := Configure(profile, fixtureConfig()) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: reloaded, err := Load(profile) | |
| 33 | 新增: if err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: if current.Name() != reloaded.Name() || current.Config() != reloaded.Config() { | |
| 37 | 新增: t.Fatal("configuration identity did not persist") | |
| 38 | 新增: } | |
| 39 | 新增: changed := fixtureConfig() | |
| 40 | 新增: changed.Image = "sha256:" + strings.Repeat("b", 64) | |
| 41 | 新增: if _, err := Configure(profile, changed); err == nil { | |
| 42 | 新增: t.Fatal("replacement would strand original writable root filesystem") | |
| 43 | 新增: } | |
| 44 | 新增: if err := os.WriteFile(filepath.Join(profile, "container.json"), []byte(`{"engine":"docker","privileged":true}`), 0600); err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: if _, err := Load(profile); err == nil { | |
| 48 | 新增: t.Fatal("unknown configuration field accepted") | |
| 49 | 新增: } | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:func TestRejectContainerEscapeConfiguration(t *testing.T) { | |
| 53 | 新增: valid := &engineContainer{} | |
| 54 | 新增: valid.HostConfig.NetworkMode = "none" | |
| 55 | 新增: valid.HostConfig.CgroupnsMode = "private" | |
| 56 | 新增: valid.HostConfig.IpcMode = "private" | |
| 57 | 新增: if err := checkContainerConfiguration(valid); err != nil { | |
| 58 | 新增: t.Fatal(err) | |
| 59 | 新增: } | |
| 60 | 新增: valid.HostConfig.ExtraHosts = []string{"cage:127.0.1.1"} | |
| 61 | 新增: if err := checkContainerConfiguration(valid); err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: for _, mutate := range []func(*engineContainer){ | |
| 65 | 新增: func(c *engineContainer) { c.HostConfig.Privileged = true }, | |
| 66 | 新增: func(c *engineContainer) { c.HostConfig.NetworkMode = "bridge" }, | |
| 67 | 新增: func(c *engineContainer) { c.HostConfig.NetworkMode = "host" }, | |
| 68 | 新增: func(c *engineContainer) { c.HostConfig.PidMode = "host" }, | |
| 69 | 新增: func(c *engineContainer) { c.HostConfig.PidMode = "container:other" }, | |
| 70 | 新增: func(c *engineContainer) { c.HostConfig.CgroupnsMode = "host" }, | |
| 71 | 新增: func(c *engineContainer) { c.HostConfig.Binds = []string{"/:/host"} }, | |
| 72 | 新增: func(c *engineContainer) { c.HostConfig.ExtraHosts = []string{"cage:host-gateway"} }, | |
| 73 | 新增: func(c *engineContainer) { c.HostConfig.ExtraHosts = []string{"cage:192.168.64.1"} }, | |
| 74 | 新增: func(c *engineContainer) { c.HostConfig.CapAdd = []string{"ALL"} }, | |
| 75 | 新增: func(c *engineContainer) { | |
| 76 | 新增: c.Mounts = append(c.Mounts, struct{ Type, Source, Destination string }{"bind", "/var/run/docker.sock", "/run/docker.sock"}) | |
| 77 | 新增: }, | |
| 78 | 新增: } { | |
| 79 | 新增: c := &engineContainer{} | |
| 80 | 新增: c.HostConfig.NetworkMode = "none" | |
| 81 | 新增: c.HostConfig.CgroupnsMode = "private" | |
| 82 | 新增: c.HostConfig.IpcMode = "private" | |
| 83 | 新增: mutate(c) | |
| 84 | 新增: if checkContainerConfiguration(c) == nil { | |
| 85 | 新增: t.Fatal("unsafe container configuration accepted") | |
| 86 | 新增: } | |
| 87 | 新增: } | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:func TestCreateResolvesHostnameWithinContainerLoopback(t *testing.T) { | |
| 91 | 新增: for _, engine := range []string{"docker", "podman"} { | |
| 92 | 新增: config := fixtureConfig() | |
| 93 | 新增: config.Engine = engine | |
| 94 | 新增: runtime := newRuntime(t.TempDir(), config) | |
| 95 | 新增: args := runtime.createArguments() | |
| 96 | 新增: found := false | |
| 97 | 新增: for i, arg := range args { | |
| 98 | 新增: if arg == "--add-host" && i+1 < len(args) { | |
| 99 | 新增: if args[i+1] != "cage:127.0.1.1" { | |
| 100 | 新增: t.Fatalf("%s resolves cage outside its loopback: %q", engine, args[i+1]) | |
| 101 | 新增: } | |
| 102 | 新增: found = true | |
| 103 | 新增: } | |
| 104 | 新增: } | |
| 105 | 新增: if !found { | |
| 106 | 新增: t.Fatalf("%s does not resolve the container hostname", engine) | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:func TestSSHKeyIsStableAndHostKeyPathsAreQuoted(t *testing.T) { | |
| 112 | 新增: r := newRuntime(filepath.Join(t.TempDir(), "profile with spaces"), fixtureConfig()) | |
| 113 | 新增: first, err := r.ensureSSHKey() | |
| 114 | 新增: if err != nil { | |
| 115 | 新增: t.Fatal(err) | |
| 116 | 新增: } | |
| 117 | 新增: second, err := r.ensureSSHKey() | |
| 118 | 新增: if err != nil { | |
| 119 | 新增: t.Fatal(err) | |
| 120 | 新增: } | |
| 121 | 新增: if string(first) != string(second) { | |
| 122 | 新增: t.Fatal("SSH key changed on reconnect") | |
| 123 | 新增: } | |
| 124 | 新增: if err := r.writeSSHConfig(17770); err != nil { | |
| 125 | 新增: t.Fatal(err) | |
| 126 | 新增: } | |
| 127 | 新增: data, err := os.ReadFile(r.SSHConfig()) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: t.Fatal(err) | |
| 130 | 新增: } | |
| 131 | 新增: if !strings.Contains(string(data), "StrictHostKeyChecking yes") || !strings.Contains(string(data), `IdentityFile "`) { | |
| 132 | 新增: t.Fatal("SSH trust or paths were not preserved") | |
| 133 | 新增: } | |
| 134 | 新增:} | |
| @@ -0,0 +1,333 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "strings" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:type State struct { | |
| 16 | 新增: Exists bool `json:"exists"` | |
| 17 | 新增: Running bool `json:"running"` | |
| 18 | 新增: Ready bool `json:"ready"` | |
| 19 | 新增: ContainerID string `json:"container_id,omitempty"` | |
| 20 | 新增: PID int `json:"pid,omitempty"` | |
| 21 | 新增: MemoryBytes int64 `json:"memory_bytes"` | |
| 22 | 新增: CPUs int `json:"cpus"` | |
| 23 | 新增: BrowserAddress string `json:"browser_address,omitempty"` | |
| 24 | 新增: VNCAddress string `json:"vnc_address,omitempty"` | |
| 25 | 新增: StoragePath string `json:"storage_path,omitempty"` | |
| 26 | 新增: ResourcesVerified bool `json:"resources_verified"` | |
| 27 | 新增: ResourceError string `json:"resource_error,omitempty"` | |
| 28 | 新增: PIDs int64 `json:"pids"` | |
| 29 | 新增: MountsReady bool `json:"mounts_ready"` | |
| 30 | 新增: MountError string `json:"mount_error,omitempty"` | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:type Inspection struct { | |
| 34 | 新增: State State `json:"state"` | |
| 35 | 新增: Rootless bool `json:"rootless"` | |
| 36 | 新增: NetworkConfined bool `json:"network_confined"` | |
| 37 | 新增: FilesystemConfined bool `json:"filesystem_confined"` | |
| 38 | 新增: Evidence string `json:"evidence"` | |
| 39 | 新增: MountPropagation MountPropagation `json:"mount_propagation"` | |
| 40 | 新增:} | |
| 41 | 新增: | |
| 42 | 新增:type engineContainer struct { | |
| 43 | 新增: ID string `json:"Id"` | |
| 44 | 新增: Image string `json:"Image"` | |
| 45 | 新增: State struct { | |
| 46 | 新增: Running bool | |
| 47 | 新增: Pid int | |
| 48 | 新增: } | |
| 49 | 新增: Config struct { | |
| 50 | 新增: Labels map[string]string | |
| 51 | 新增: Image string | |
| 52 | 新增: } | |
| 53 | 新增: HostConfig struct { | |
| 54 | 新增: Privileged bool | |
| 55 | 新增: NetworkMode string | |
| 56 | 新增: PidMode string | |
| 57 | 新增: IpcMode string | |
| 58 | 新增: CgroupnsMode string | |
| 59 | 新增: CgroupParent string | |
| 60 | 新增: UsernsMode string | |
| 61 | 新增: Binds []string | |
| 62 | 新增: ExtraHosts []string | |
| 63 | 新增: CapAdd []string | |
| 64 | 新增: Memory int64 | |
| 65 | 新增: NanoCpus int64 | |
| 66 | 新增: Devices []struct { | |
| 67 | 新增: PathOnHost string | |
| 68 | 新增: PathInContainer string | |
| 69 | 新增: } | |
| 70 | 新增: } | |
| 71 | 新增: Mounts []struct { | |
| 72 | 新增: Type string | |
| 73 | 新增: Source string | |
| 74 | 新增: Destination string | |
| 75 | 新增: } | |
| 76 | 新增:} | |
| 77 | 新增: | |
| 78 | 新增:func (r *Runtime) command(ctx context.Context, args ...string) *exec.Cmd { | |
| 79 | 新增: if r.config.Engine == "docker" { | |
| 80 | 新增: // Docker's normal client config can inject the user's proxy URLs and | |
| 81 | 新增: // credentials into new containers. Use a profile-private empty config. | |
| 82 | 新增: args = append([]string{"--config", filepath.Join(r.InstanceDir(), "client-config"), "--host", r.config.Socket}, args...) | |
| 83 | 新增: } | |
| 84 | 新增: command := exec.CommandContext(ctx, r.config.Executable, args...) | |
| 85 | 新增: for _, entry := range os.Environ() { | |
| 86 | 新增: name, _, _ := strings.Cut(entry, "=") | |
| 87 | 新增: switch name { | |
| 88 | 新增: case "DOCKER_HOST", "DOCKER_CONTEXT", "DOCKER_CONFIG", "CONTAINER_HOST", "CONTAINER_CONNECTION": | |
| 89 | 新增: continue | |
| 90 | 新增: } | |
| 91 | 新增: command.Env = append(command.Env, entry) | |
| 92 | 新增: } | |
| 93 | 新增: return command | |
| 94 | 新增:} | |
| 95 | 新增: | |
| 96 | 新增:func (r *Runtime) output(ctx context.Context, args ...string) ([]byte, error) { | |
| 97 | 新增: command := r.command(ctx, args...) | |
| 98 | 新增: var output, diagnostic bytes.Buffer | |
| 99 | 新增: command.Stdout = &limitedWriter{writer: &output, left: 1 << 20} | |
| 100 | 新增: command.Stderr = &limitedWriter{writer: &diagnostic, left: 4096} | |
| 101 | 新增: if err := command.Run(); err != nil { | |
| 102 | 新增: return nil, fmt.Errorf("容器引擎操作失败: %w: %s", err, strings.TrimSpace(diagnostic.String())) | |
| 103 | 新增: } | |
| 104 | 新增: return output.Bytes(), nil | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:type limitedWriter struct { | |
| 108 | 新增: writer *bytes.Buffer | |
| 109 | 新增: left int | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:func (w *limitedWriter) Write(data []byte) (int, error) { | |
| 113 | 新增: if len(data) > w.left { | |
| 114 | 新增: return 0, errors.New("container engine output limit exceeded") | |
| 115 | 新增: } | |
| 116 | 新增: n, err := w.writer.Write(data) | |
| 117 | 新增: w.left -= n | |
| 118 | 新增: return n, err | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func (r *Runtime) inspectContainer(ctx context.Context) (*engineContainer, error) { | |
| 122 | 新增: // Query only this exact managed name. An empty result is absence, while | |
| 123 | 新增: // engine/permission failures remain errors rather than triggering creation. | |
| 124 | 新增: data, err := r.output(ctx, "container", "ls", "--all", "--filter", "label="+profileLabel+"="+r.identity, "--format", "{{.ID}}") | |
| 125 | 新增: if err != nil { | |
| 126 | 新增: return nil, err | |
| 127 | 新增: } | |
| 128 | 新增: id := strings.TrimSpace(string(data)) | |
| 129 | 新增: if id == "" { | |
| 130 | 新增: return nil, nil | |
| 131 | 新增: } | |
| 132 | 新增: if strings.ContainsAny(id, " \r\n\t") { | |
| 133 | 新增: return nil, errors.New("容器标识不唯一") | |
| 134 | 新增: } | |
| 135 | 新增: data, err = r.output(ctx, "container", "inspect", id) | |
| 136 | 新增: if err != nil { | |
| 137 | 新增: return nil, err | |
| 138 | 新增: } | |
| 139 | 新增: var found []engineContainer | |
| 140 | 新增: if json.Unmarshal(data, &found) != nil || len(found) != 1 || found[0].Config.Labels[profileLabel] != r.identity { | |
| 141 | 新增: return nil, errors.New("容器身份与当前 Cage 配置不匹配") | |
| 142 | 新增: } | |
| 143 | 新增: return &found[0], nil | |
| 144 | 新增:} | |
| 145 | 新增: | |
| 146 | 新增:func (r *Runtime) State(ctx context.Context) (State, error) { | |
| 147 | 新增: container, err := r.inspectContainer(ctx) | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: return State{}, err | |
| 150 | 新增: } | |
| 151 | 新增: if container == nil { | |
| 152 | 新增: storage, err := r.StoragePath(ctx) | |
| 153 | 新增: return State{CPUs: r.config.CPUs, MemoryBytes: r.config.MemoryBytes, StoragePath: storage}, err | |
| 154 | 新增: } | |
| 155 | 新增: state := State{Exists: true, Running: container.State.Running, ContainerID: container.ID, PID: container.State.Pid, MemoryBytes: container.HostConfig.Memory, CPUs: int(container.HostConfig.NanoCpus / 1e9)} | |
| 156 | 新增: state.StoragePath, err = r.StoragePath(ctx) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: return State{}, err | |
| 159 | 新增: } | |
| 160 | 新增: if state.Running { | |
| 161 | 新增: mounts, mountErr := r.inspectMounts(container) | |
| 162 | 新增: if mountErr != nil { | |
| 163 | 新增: state.MountError = mountErr.Error() | |
| 164 | 新增: } else { | |
| 165 | 新增: state.MountsReady = mounts.Ready() | |
| 166 | 新增: } | |
| 167 | 新增: resources, resourceErr := r.verifyResources(ctx, container.ID) | |
| 168 | 新增: if resourceErr != nil { | |
| 169 | 新增: state.MemoryBytes = 0 | |
| 170 | 新增: state.CPUs = 0 | |
| 171 | 新增: state.ResourceError = resourceErr.Error() | |
| 172 | 新增: } else { | |
| 173 | 新增: state.MemoryBytes = resources.MemoryBytes | |
| 174 | 新增: state.CPUs = resources.CPUs | |
| 175 | 新增: state.PIDs = resources.PIDs | |
| 176 | 新增: state.ResourcesVerified = true | |
| 177 | 新增: } | |
| 178 | 新增: if record, err := r.networkState(ctx, container.ID); err == nil { | |
| 179 | 新增: state.Ready = state.ResourcesVerified && state.MountsReady | |
| 180 | 新增: state.BrowserAddress = record.BrowserAddress | |
| 181 | 新增: state.VNCAddress = record.VNCAddress | |
| 182 | 新增: } | |
| 183 | 新增: } | |
| 184 | 新增: return state, nil | |
| 185 | 新增:} | |
| 186 | 新增: | |
| 187 | 新增:// StoragePath reports the engine's actual persistent storage location. An | |
| 188 | 新增:// explicitly supplied rootless engine may already store data outside the | |
| 189 | 新增:// profile; this path is never treated as disposable or removed by Cage. | |
| 190 | 新增:func (r *Runtime) StoragePath(ctx context.Context) (string, error) { | |
| 191 | 新增: format := "{{.DockerRootDir}}" | |
| 192 | 新增: if r.config.Engine == "podman" { | |
| 193 | 新增: format = "{{.Store.GraphRoot}}" | |
| 194 | 新增: } | |
| 195 | 新增: data, err := r.output(ctx, "info", "--format", format) | |
| 196 | 新增: if err != nil { | |
| 197 | 新增: return "", err | |
| 198 | 新增: } | |
| 199 | 新增: path := strings.TrimSpace(string(data)) | |
| 200 | 新增: if !filepath.IsAbs(path) || strings.ContainsAny(path, "\x00\r\n") { | |
| 201 | 新增: return "", errors.New("容器持久存储位置无效") | |
| 202 | 新增: } | |
| 203 | 新增: return path, nil | |
| 204 | 新增:} | |
| 205 | 新增: | |
| 206 | 新增:func (r *Runtime) rootlessEngine(ctx context.Context) (bool, error) { | |
| 207 | 新增: rootless, limited, err := r.engineSecurity(ctx) | |
| 208 | 新增: if err != nil { | |
| 209 | 新增: return false, err | |
| 210 | 新增: } | |
| 211 | 新增: if !limited { | |
| 212 | 新增: return false, errors.New("容器引擎必须使用 systemd 和 cgroup v2,以执行 CPU、内存与进程数限额") | |
| 213 | 新增: } | |
| 214 | 新增: return rootless, nil | |
| 215 | 新增:} | |
| 216 | 新增: | |
| 217 | 新增:// Shutdown still works if an engine loses its resource-controller support. | |
| 218 | 新增:// Starting and inspecting enforce the stronger rootlessEngine precondition. | |
| 219 | 新增:func (r *Runtime) engineSecurity(ctx context.Context) (rootless, limited bool, err error) { | |
| 220 | 新增: if r.config.Engine == "docker" { | |
| 221 | 新增: data, err := r.output(ctx, "info", "--format", "{{json .SecurityOptions}}\n{{.CgroupDriver}}\n{{.CgroupVersion}}") | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: return false, false, err | |
| 224 | 新增: } | |
| 225 | 新增: var options []string | |
| 226 | 新增: lines := strings.Split(strings.TrimSpace(string(data)), "\n") | |
| 227 | 新增: if len(lines) != 3 || json.Unmarshal([]byte(lines[0]), &options) != nil { | |
| 228 | 新增: return false, false, errors.New("无法确认 Docker 安全配置") | |
| 229 | 新增: } | |
| 230 | 新增: limited = lines[1] == "systemd" && lines[2] == "2" | |
| 231 | 新增: for _, option := range options { | |
| 232 | 新增: if option == "name=rootless" || strings.HasPrefix(option, "name=rootless,") { | |
| 233 | 新增: return true, limited, nil | |
| 234 | 新增: } | |
| 235 | 新增: } | |
| 236 | 新增: return false, limited, nil | |
| 237 | 新增: } | |
| 238 | 新增: data, err := r.output(ctx, "info", "--format", "{{.Host.Security.Rootless}}\n{{.Host.CgroupManager}}\n{{.Host.CgroupVersion}}") | |
| 239 | 新增: if err != nil { | |
| 240 | 新增: return false, false, err | |
| 241 | 新增: } | |
| 242 | 新增: lines := strings.Split(strings.TrimSpace(string(data)), "\n") | |
| 243 | 新增: if len(lines) != 3 { | |
| 244 | 新增: return false, false, errors.New("无法确认 Podman 安全配置") | |
| 245 | 新增: } | |
| 246 | 新增: return lines[0] == "true", lines[1] == "systemd" && (lines[2] == "v2" || lines[2] == "2"), nil | |
| 247 | 新增:} | |
| 248 | 新增: | |
| 249 | 新增:func checkContainerConfiguration(container *engineContainer) error { | |
| 250 | 新增: config := container.HostConfig | |
| 251 | 新增: if config.Privileged || config.NetworkMode != "none" || (config.PidMode != "" && config.PidMode != "private") || config.IpcMode != "private" || config.CgroupnsMode != "private" { | |
| 252 | 新增: return errors.New("容器必须使用独立命名空间和禁用默认网络,不能启用特权模式") | |
| 253 | 新增: } | |
| 254 | 新增: if len(config.Binds) > 0 { | |
| 255 | 新增: return errors.New("容器不能直接挂载宿主目录") | |
| 256 | 新增: } | |
| 257 | 新增: for _, entry := range config.ExtraHosts { | |
| 258 | 新增: if entry != "cage:127.0.1.1" { | |
| 259 | 新增: return errors.New("容器只允许 Cage 主机名的固定回环地址") | |
| 260 | 新增: } | |
| 261 | 新增: } | |
| 262 | 新增: for _, mount := range container.Mounts { | |
| 263 | 新增: if mount.Type == "bind" || mount.Type == "volume" { | |
| 264 | 新增: return errors.New("容器存在未经 Cage 文件共享授权的挂载") | |
| 265 | 新增: } | |
| 266 | 新增: } | |
| 267 | 新增: for _, device := range config.Devices { | |
| 268 | 新增: if (device.PathOnHost != "/dev/fuse" && device.PathOnHost != "/dev/net/tun") || device.PathOnHost != device.PathInContainer { | |
| 269 | 新增: return errors.New("容器存在额外宿主设备") | |
| 270 | 新增: } | |
| 271 | 新增: } | |
| 272 | 新增: for _, capability := range config.CapAdd { | |
| 273 | 新增: capability = strings.TrimPrefix(capability, "CAP_") | |
| 274 | 新增: if capability != "NET_ADMIN" && capability != "SYS_ADMIN" { | |
| 275 | 新增: return errors.New("容器存在额外系统权限") | |
| 276 | 新增: } | |
| 277 | 新增: } | |
| 278 | 新增: return nil | |
| 279 | 新增:} | |
| 280 | 新增: | |
| 281 | 新增:func (r *Runtime) Inspect(ctx context.Context) (Inspection, error) { | |
| 282 | 新增: rootless, err := r.rootlessEngine(ctx) | |
| 283 | 新增: if err != nil { | |
| 284 | 新增: return Inspection{}, err | |
| 285 | 新增: } | |
| 286 | 新增: if !rootless { | |
| 287 | 新增: return Inspection{}, errors.New("Cage 容器必须由独立 rootless 引擎运行") | |
| 288 | 新增: } | |
| 289 | 新增: container, err := r.inspectContainer(ctx) | |
| 290 | 新增: if err != nil { | |
| 291 | 新增: return Inspection{}, err | |
| 292 | 新增: } | |
| 293 | 新增: if container == nil { | |
| 294 | 新增: return Inspection{Rootless: true}, nil | |
| 295 | 新增: } | |
| 296 | 新增: if err := checkContainerConfiguration(container); err != nil { | |
| 297 | 新增: return Inspection{}, err | |
| 298 | 新增: } | |
| 299 | 新增: if container.HostConfig.CgroupParent != r.resourceSlice() { | |
| 300 | 新增: return Inspection{}, errors.New("已有容器缺少当前配置的宿主资源边界;保留原数据,拒绝无约束启动") | |
| 301 | 新增: } | |
| 302 | 新增: state := State{Exists: true, Running: container.State.Running, ContainerID: container.ID, PID: container.State.Pid, MemoryBytes: container.HostConfig.Memory, CPUs: int(container.HostConfig.NanoCpus / 1e9)} | |
| 303 | 新增: state.StoragePath, err = r.StoragePath(ctx) | |
| 304 | 新增: if err != nil { | |
| 305 | 新增: return Inspection{}, err | |
| 306 | 新增: } | |
| 307 | 新增: result := Inspection{State: state, Rootless: true, Evidence: "rootless 引擎;无默认网络或宿主目录挂载;等待运行中的网络与文件共享检查"} | |
| 308 | 新增: if state.Running { | |
| 309 | 新增: mounts, err := r.inspectMounts(container) | |
| 310 | 新增: if err != nil { | |
| 311 | 新增: return Inspection{}, err | |
| 312 | 新增: } | |
| 313 | 新增: result.MountPropagation = mounts | |
| 314 | 新增: result.State.MountsReady = mounts.Ready() | |
| 315 | 新增: resources, err := r.verifyResources(ctx, container.ID) | |
| 316 | 新增: if err != nil { | |
| 317 | 新增: return Inspection{}, err | |
| 318 | 新增: } | |
| 319 | 新增: result.State.MemoryBytes = resources.MemoryBytes | |
| 320 | 新增: result.State.CPUs = resources.CPUs | |
| 321 | 新增: result.State.PIDs = resources.PIDs | |
| 322 | 新增: result.State.ResourcesVerified = true | |
| 323 | 新增: if record, err := r.networkState(ctx, container.ID); err == nil { | |
| 324 | 新增: result.State.Ready = mounts.Ready() | |
| 325 | 新增: result.State.BrowserAddress = record.BrowserAddress | |
| 326 | 新增: result.State.VNCAddress = record.VNCAddress | |
| 327 | 新增: result.NetworkConfined = true | |
| 328 | 新增: result.FilesystemConfined = mounts.Ready() | |
| 329 | 新增: result.Evidence = "实际 rootless 容器无默认网络或宿主目录挂载;当前外置网络门槛身份已验证,唯一 TAP 通道由宿主接收;默认项目经受限 SFTP 共享并完成双端读写验证" | |
| 330 | 新增: } | |
| 331 | 新增: } | |
| 332 | 新增: return result, nil | |
| 333 | 新增:} | |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "encoding/binary" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// A compromised guest can replace its helper. Validate framing again before | |
| 12 | 新增:// the shared netstack allocates packets or indexes the Ethernet header. | |
| 13 | 新增:type boundedFrameConnection struct { | |
| 14 | 新增: net.Conn | |
| 15 | 新增: pending []byte | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func (c *boundedFrameConnection) Read(output []byte) (int, error) { | |
| 19 | 新增: if len(output) == 0 { | |
| 20 | 新增: return 0, nil | |
| 21 | 新增: } | |
| 22 | 新增: if len(c.pending) == 0 { | |
| 23 | 新增: buffer := make([]byte, maxFrameSize+4) | |
| 24 | 新增: frame, err := readFrame(c.Conn, buffer[4:]) | |
| 25 | 新增: if err != nil { | |
| 26 | 新增: return 0, err | |
| 27 | 新增: } | |
| 28 | 新增: mac, _ := net.ParseMAC(GuestMAC) | |
| 29 | 新增: if !bytes.Equal(frame[6:12], mac) { | |
| 30 | 新增: return 0, errors.New("unexpected container Ethernet source") | |
| 31 | 新增: } | |
| 32 | 新增: binary.BigEndian.PutUint32(buffer[:4], uint32(len(frame))) | |
| 33 | 新增: c.pending = buffer[:4+len(frame)] | |
| 34 | 新增: } | |
| 35 | 新增: n := copy(output, c.pending) | |
| 36 | 新增: c.pending = c.pending[n:] | |
| 37 | 新增: return n, nil | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:// A TAP read returns exactly one Ethernet frame. Jumbo frames are disabled; | |
| 41 | 新增:// the small allowance includes Ethernet/VLAN headers above the configured MTU. | |
| 42 | 新增:const maxFrameSize = NetworkMTU + 64 | |
| 43 | 新增: | |
| 44 | 新增:func writeFrame(writer io.Writer, frame []byte) error { | |
| 45 | 新增: if len(frame) < 14 || len(frame) > maxFrameSize { | |
| 46 | 新增: return errors.New("invalid container Ethernet frame length") | |
| 47 | 新增: } | |
| 48 | 新增: var header [4]byte | |
| 49 | 新增: binary.BigEndian.PutUint32(header[:], uint32(len(frame))) | |
| 50 | 新增: if err := writeAll(writer, header[:]); err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: return writeAll(writer, frame) | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:func readFrame(reader io.Reader, buffer []byte) ([]byte, error) { | |
| 57 | 新增: var header [4]byte | |
| 58 | 新增: if _, err := io.ReadFull(reader, header[:]); err != nil { | |
| 59 | 新增: return nil, err | |
| 60 | 新增: } | |
| 61 | 新增: size := binary.BigEndian.Uint32(header[:]) | |
| 62 | 新增: if size < 14 || size > maxFrameSize || int(size) > len(buffer) { | |
| 63 | 新增: return nil, errors.New("invalid container Ethernet frame length") | |
| 64 | 新增: } | |
| 65 | 新增: frame := buffer[:int(size)] | |
| 66 | 新增: _, err := io.ReadFull(reader, frame) | |
| 67 | 新增: return frame, err | |
| 68 | 新增:} | |
| 69 | 新增: | |
| 70 | 新增:func writeAll(writer io.Writer, data []byte) error { | |
| 71 | 新增: for len(data) > 0 { | |
| 72 | 新增: n, err := writer.Write(data) | |
| 73 | 新增: if n < 0 || n > len(data) { | |
| 74 | 新增: return io.ErrShortWrite | |
| 75 | 新增: } | |
| 76 | 新增: data = data[n:] | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: if n == 0 { | |
| 81 | 新增: return io.ErrShortWrite | |
| 82 | 新增: } | |
| 83 | 新增: } | |
| 84 | 新增: return nil | |
| 85 | 新增:} | |
| @@ -0,0 +1,137 @@ | ||
| 1 | 新增://go:build linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "os" | |
| 10 | 新增: "path/filepath" | |
| 11 | 新增: "strconv" | |
| 12 | 新增: "strings" | |
| 13 | 新增: | |
| 14 | 新增: systemd "github.com/coreos/go-systemd/v22/dbus" | |
| 15 | 新增: "github.com/godbus/dbus/v5" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func userSystemd(ctx context.Context) (*systemd.Conn, error) { | |
| 19 | 新增: return systemd.NewConnection(func() (*dbus.Conn, error) { | |
| 20 | 新增: connection, err := dbus.Dial("unix:path=/run/user/"+strconv.Itoa(os.Getuid())+"/bus", dbus.WithContext(ctx)) | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: return nil, err | |
| 23 | 新增: } | |
| 24 | 新增: if err = connection.Auth([]dbus.Auth{dbus.AuthExternal(strconv.Itoa(os.Getuid()))}); err == nil { | |
| 25 | 新增: err = connection.Hello() | |
| 26 | 新增: } | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: connection.Close() | |
| 29 | 新增: return nil, err | |
| 30 | 新增: } | |
| 31 | 新增: return connection, nil | |
| 32 | 新增: }) | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:// The outer slice belongs to the host user manager and remains outside the | |
| 36 | 新增:// container's cgroup namespace. Guest root may manage its own systemd subtree | |
| 37 | 新增:// but cannot raise these ancestor limits. | |
| 38 | 新增:func (r *Runtime) ensureResourceSlice(ctx context.Context) error { | |
| 39 | 新增: connection, err := userSystemd(ctx) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: return fmt.Errorf("无法连接宿主用户 systemd 以设置容器资源上限: %w", err) | |
| 42 | 新增: } | |
| 43 | 新增: defer connection.Close() | |
| 44 | 新增: properties := []systemd.Property{ | |
| 45 | 新增: systemd.PropDescription("Cage container " + r.identity), | |
| 46 | 新增: {Name: "MemoryMax", Value: dbus.MakeVariant(uint64(r.config.MemoryBytes))}, | |
| 47 | 新增: {Name: "CPUQuotaPerSecUSec", Value: dbus.MakeVariant(uint64(r.config.CPUs) * 1000000)}, | |
| 48 | 新增: {Name: "TasksMax", Value: dbus.MakeVariant(uint64(PIDLimit))}, | |
| 49 | 新增: } | |
| 50 | 新增: // Querying a valid slice name first can make systemd synthesize an inactive | |
| 51 | 新增: // default unit. Creating the transient unit directly also handles that | |
| 52 | 新增: // implicit unit, without mistaking it for someone else's configured slice. | |
| 53 | 新增: result := make(chan string, 1) | |
| 54 | 新增: _, err = connection.StartTransientUnitContext(ctx, r.resourceSlice(), "fail", properties, result) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: var busError dbus.Error | |
| 57 | 新增: if !errors.As(err, &busError) || busError.Name != "org.freedesktop.systemd1.UnitExists" { | |
| 58 | 新增: return err | |
| 59 | 新增: } | |
| 60 | 新增: current, err := connection.GetUnitPropertiesContext(ctx, r.resourceSlice()) | |
| 61 | 新增: if err != nil { | |
| 62 | 新增: return err | |
| 63 | 新增: } | |
| 64 | 新增: if current["Description"] != "Cage container "+r.identity { | |
| 65 | 新增: return errors.New("容器资源 slice 名称已被其他单元占用") | |
| 66 | 新增: } | |
| 67 | 新增: if err := connection.SetUnitPropertiesContext(ctx, r.resourceSlice(), true, properties[1:]...); err != nil { | |
| 68 | 新增: return err | |
| 69 | 新增: } | |
| 70 | 新增: if _, err := connection.StartUnitContext(ctx, r.resourceSlice(), "replace", result); err != nil { | |
| 71 | 新增: return err | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: select { | |
| 75 | 新增: case state := <-result: | |
| 76 | 新增: if state != "done" { | |
| 77 | 新增: return fmt.Errorf("容器资源 slice 启动失败: %s", state) | |
| 78 | 新增: } | |
| 79 | 新增: case <-ctx.Done(): | |
| 80 | 新增: return ctx.Err() | |
| 81 | 新增: } | |
| 82 | 新增: _, err = r.readParentLimits(ctx, connection, "") | |
| 83 | 新增: return err | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:func (r *Runtime) readParentLimits(ctx context.Context, connection *systemd.Conn, containerID string) (resourceEvidence, error) { | |
| 87 | 新增: parent, err := connection.GetAllPropertiesContext(ctx, r.resourceSlice()) | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: return resourceEvidence{}, err | |
| 90 | 新增: } | |
| 91 | 新增: if parent["Description"] != "Cage container "+r.identity || parent["ActiveState"] != "active" { | |
| 92 | 新增: return resourceEvidence{}, errors.New("容器的宿主资源边界未运行") | |
| 93 | 新增: } | |
| 94 | 新增: parentPath, ok := parent["ControlGroup"].(string) | |
| 95 | 新增: if !ok || !strings.HasPrefix(parentPath, "/") || filepath.Clean(parentPath) != parentPath || filepath.Base(parentPath) != r.resourceSlice() { | |
| 96 | 新增: return resourceEvidence{}, errors.New("宿主资源 cgroup 路径无效") | |
| 97 | 新增: } | |
| 98 | 新增: if containerID != "" { | |
| 99 | 新增: prefix := "docker-" | |
| 100 | 新增: if r.config.Engine == "podman" { | |
| 101 | 新增: prefix = "libpod-" | |
| 102 | 新增: } | |
| 103 | 新增: scope, err := connection.GetAllPropertiesContext(ctx, prefix+containerID+".scope") | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: return resourceEvidence{}, err | |
| 106 | 新增: } | |
| 107 | 新增: path, ok := scope["ControlGroup"].(string) | |
| 108 | 新增: if !ok || !strings.HasPrefix(path, parentPath+"/") || scope["ActiveState"] != "active" { | |
| 109 | 新增: return resourceEvidence{}, errors.New("实际容器未处于 Cage 的宿主资源边界内") | |
| 110 | 新增: } | |
| 111 | 新增: } | |
| 112 | 新增: root := filepath.Join("/sys/fs/cgroup", parentPath) | |
| 113 | 新增: var evidence strings.Builder | |
| 114 | 新增: for _, file := range []string{"memory.max", "cpu.max", "pids.max"} { | |
| 115 | 新增: data, err := os.ReadFile(filepath.Join(root, file)) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: return resourceEvidence{}, err | |
| 118 | 新增: } | |
| 119 | 新增: evidence.WriteString(strings.TrimSpace(string(data))) | |
| 120 | 新增: evidence.WriteByte('\n') | |
| 121 | 新增: } | |
| 122 | 新增: mounts, err := os.ReadFile("/proc/self/mountinfo") | |
| 123 | 新增: if err != nil { | |
| 124 | 新增: return resourceEvidence{}, err | |
| 125 | 新增: } | |
| 126 | 新增: evidence.Write(mounts) | |
| 127 | 新增: return parseResourceEvidence(evidence.String(), r.config) | |
| 128 | 新增:} | |
| 129 | 新增: | |
| 130 | 新增:func (r *Runtime) verifyHostResources(ctx context.Context, containerID string) (resourceEvidence, error) { | |
| 131 | 新增: connection, err := userSystemd(ctx) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: return resourceEvidence{}, err | |
| 134 | 新增: } | |
| 135 | 新增: defer connection.Close() | |
| 136 | 新增: return r.readParentLimits(ctx, connection, containerID) | |
| 137 | 新增:} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增://go:build !linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func (r *Runtime) ensureResourceSlice(context.Context) error { | |
| 11 | 新增: return errors.New("容器资源边界仅支持 Linux") | |
| 12 | 新增:} | |
| 13 | 新增:func (r *Runtime) verifyHostResources(context.Context, string) (resourceEvidence, error) { | |
| 14 | 新增: return resourceEvidence{}, errors.New("容器资源边界仅支持 Linux") | |
| 15 | 新增:} | |
| @@ -0,0 +1,65 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "strconv" | |
| 6 | 新增: "strings" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:type MountPropagation struct { | |
| 10 | 新增: PrivateNamespace bool `json:"private_namespace"` | |
| 11 | 新增: SharedGroup uint64 `json:"shared_group,omitempty"` | |
| 12 | 新增: DetachedFromHost bool `json:"detached_from_host"` | |
| 13 | 新增:} | |
| 14 | 新增: | |
| 15 | 新增:func (m MountPropagation) Ready() bool { | |
| 16 | 新增: return m.PrivateNamespace && m.DetachedFromHost && m.SharedGroup != 0 | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:func rootMountPropagation(containerMounts, hostMounts string) (MountPropagation, error) { | |
| 20 | 新增: var root []string | |
| 21 | 新增: for _, line := range strings.Split(containerMounts, "\n") { | |
| 22 | 新增: fields := strings.Fields(line) | |
| 23 | 新增: if len(fields) > 6 && fields[4] == "/" { | |
| 24 | 新增: root = fields | |
| 25 | 新增: break | |
| 26 | 新增: } | |
| 27 | 新增: } | |
| 28 | 新增: if root == nil { | |
| 29 | 新增: return MountPropagation{}, errors.New("无法核验容器根挂载") | |
| 30 | 新增: } | |
| 31 | 新增: result := MountPropagation{DetachedFromHost: true} | |
| 32 | 新增: for _, field := range root[6:] { | |
| 33 | 新增: if field == "-" { | |
| 34 | 新增: break | |
| 35 | 新增: } | |
| 36 | 新增: if strings.HasPrefix(field, "master:") || strings.HasPrefix(field, "propagate_from:") { | |
| 37 | 新增: return MountPropagation{}, errors.New("容器根仍有外部挂载传播关系") | |
| 38 | 新增: } | |
| 39 | 新增: if strings.HasPrefix(field, "shared:") { | |
| 40 | 新增: group, err := strconv.ParseUint(strings.TrimPrefix(field, "shared:"), 10, 64) | |
| 41 | 新增: if err != nil || group == 0 { | |
| 42 | 新增: return MountPropagation{}, errors.New("容器共享挂载组无效") | |
| 43 | 新增: } | |
| 44 | 新增: result.SharedGroup = group | |
| 45 | 新增: } | |
| 46 | 新增: } | |
| 47 | 新增: if result.SharedGroup != 0 { | |
| 48 | 新增: group := strconv.FormatUint(result.SharedGroup, 10) | |
| 49 | 新增: for _, line := range strings.Split(hostMounts, "\n") { | |
| 50 | 新增: fields := strings.Fields(line) | |
| 51 | 新增: if len(fields) < 7 { | |
| 52 | 新增: continue | |
| 53 | 新增: } | |
| 54 | 新增: for _, field := range fields[6:] { | |
| 55 | 新增: if field == "-" { | |
| 56 | 新增: break | |
| 57 | 新增: } | |
| 58 | 新增: if field == "shared:"+group || field == "master:"+group || field == "propagate_from:"+group { | |
| 59 | 新增: return MountPropagation{}, errors.New("容器共享挂载组与宿主关联,拒绝连接") | |
| 60 | 新增: } | |
| 61 | 新增: } | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: return result, nil | |
| 65 | 新增:} | |
| @@ -0,0 +1,94 @@ | ||
| 1 | 新增://go:build linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strconv" | |
| 11 | 新增: "strings" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// Read procfs from the host, not through a guest command or a guest-supplied | |
| 15 | 新增:// path. Correlate the global PID with the exact engine container scope first. | |
| 16 | 新增:func (r *Runtime) inspectMounts(container *engineContainer) (MountPropagation, error) { | |
| 17 | 新增: if !container.State.Running || container.State.Pid < 2 { | |
| 18 | 新增: return MountPropagation{}, nil | |
| 19 | 新增: } | |
| 20 | 新增: process := filepath.Join("/proc", strconv.Itoa(container.State.Pid)) | |
| 21 | 新增: cgroups, err := os.ReadFile(filepath.Join(process, "cgroup")) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return MountPropagation{}, err | |
| 24 | 新增: } | |
| 25 | 新增: prefix := "docker-" | |
| 26 | 新增: if r.config.Engine == "podman" { | |
| 27 | 新增: prefix = "libpod-" | |
| 28 | 新增: } | |
| 29 | 新增: scope := "/" + prefix + container.ID + ".scope" | |
| 30 | 新增: owned := false | |
| 31 | 新增: for _, line := range strings.Split(string(cgroups), "\n") { | |
| 32 | 新增: parts := strings.SplitN(line, ":", 3) | |
| 33 | 新增: if len(parts) == 3 && (strings.HasSuffix(parts[2], scope) || strings.Contains(parts[2], scope+"/")) { | |
| 34 | 新增: owned = true | |
| 35 | 新增: } | |
| 36 | 新增: } | |
| 37 | 新增: if !owned { | |
| 38 | 新增: return MountPropagation{}, errors.New("无法匹配容器全局进程身份,未读取其他进程的挂载") | |
| 39 | 新增: } | |
| 40 | 新增: for _, namespace := range []string{"mnt", "user"} { | |
| 41 | 新增: host, err := os.Readlink(filepath.Join("/proc/self/ns", namespace)) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return MountPropagation{}, err | |
| 44 | 新增: } | |
| 45 | 新增: guest, err := os.Readlink(filepath.Join(process, "ns", namespace)) | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: return MountPropagation{}, err | |
| 48 | 新增: } | |
| 49 | 新增: if host == guest { | |
| 50 | 新增: return MountPropagation{}, errors.New("容器必须使用独立用户与挂载命名空间") | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: mounts, err := os.ReadFile(filepath.Join(process, "mountinfo")) | |
| 54 | 新增: if err != nil { | |
| 55 | 新增: return MountPropagation{}, err | |
| 56 | 新增: } | |
| 57 | 新增: hostMounts, err := os.ReadFile("/proc/self/mountinfo") | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: return MountPropagation{}, err | |
| 60 | 新增: } | |
| 61 | 新增: result, err := rootMountPropagation(string(mounts), string(hostMounts)) | |
| 62 | 新增: if err != nil { | |
| 63 | 新增: return MountPropagation{}, err | |
| 64 | 新增: } | |
| 65 | 新增: result.PrivateNamespace = true | |
| 66 | 新增: return result, nil | |
| 67 | 新增:} | |
| 68 | 新增: | |
| 69 | 新增:// Called only after this Start booted a stopped container, before any project | |
| 70 | 新增:// share or Cage application is started. Detach inherited propagation first, | |
| 71 | 新增:// then establish a new group entirely inside the private container namespace. | |
| 72 | 新增:func (r *Runtime) initializeMounts(ctx context.Context, containerID string) error { | |
| 73 | 新增: container, err := r.inspectContainer(ctx) | |
| 74 | 新增: if err != nil { | |
| 75 | 新增: return err | |
| 76 | 新增: } | |
| 77 | 新增: if container == nil || container.ID != containerID || !container.State.Running { | |
| 78 | 新增: return errors.New("容器启动身份已变化") | |
| 79 | 新增: } | |
| 80 | 新增: if _, err := r.inspectMounts(container); err != nil { | |
| 81 | 新增: return err | |
| 82 | 新增: } | |
| 83 | 新增: if _, err := r.output(ctx, "exec", "--user", "0", containerID, "/bin/sh", "-c", "set -eu; mount --make-rprivate /; mount --make-rshared /"); err != nil { | |
| 84 | 新增: return err | |
| 85 | 新增: } | |
| 86 | 新增: state, err := r.inspectMounts(container) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: if !state.Ready() { | |
| 91 | 新增: return errors.New("容器项目挂载传播未能初始化") | |
| 92 | 新增: } | |
| 93 | 新增: return nil | |
| 94 | 新增:} | |
| @@ -0,0 +1,15 @@ | ||
| 1 | 新增://go:build !linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:func (r *Runtime) inspectMounts(*engineContainer) (MountPropagation, error) { | |
| 11 | 新增: return MountPropagation{}, errors.New("容器挂载检查仅支持 Linux") | |
| 12 | 新增:} | |
| 13 | 新增:func (r *Runtime) initializeMounts(context.Context, string) error { | |
| 14 | 新增: return errors.New("容器挂载初始化仅支持 Linux") | |
| 15 | 新增:} | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import "testing" | |
| 4 | 新增: | |
| 5 | 新增:func TestMountPropagationDistinguishesPrivateAndIsolatedSharedRoot(t *testing.T) { | |
| 6 | 新增: host := "24 1 8:1 / / rw,relatime shared:1 - ext4 /dev/root rw\n" | |
| 7 | 新增: private := "755 705 0:65 / / rw,relatime - overlay overlay rw\n" | |
| 8 | 新增: state, err := rootMountPropagation(private, host) | |
| 9 | 新增: if err != nil || state.SharedGroup != 0 { | |
| 10 | 新增: t.Fatalf("private root: %+v %v", state, err) | |
| 11 | 新增: } | |
| 12 | 新增: shared := "755 705 0:65 / / rw,relatime shared:457 - overlay overlay rw\n" | |
| 13 | 新增: state, err = rootMountPropagation(shared, host) | |
| 14 | 新增: if err != nil || state.SharedGroup != 457 || !state.DetachedFromHost { | |
| 15 | 新增: t.Fatalf("isolated root: %+v %v", state, err) | |
| 16 | 新增: } | |
| 17 | 新增: for _, unsafe := range []string{ | |
| 18 | 新增: "755 705 0:65 / / rw,relatime shared:457 master:1 - overlay overlay rw\n", | |
| 19 | 新增: "755 705 0:65 / / rw,relatime shared:1 - overlay overlay rw\n", | |
| 20 | 新增: "755 705 0:65 / / rw,relatime shared:broken - overlay overlay rw\n", | |
| 21 | 新增: } { | |
| 22 | 新增: if _, err := rootMountPropagation(unsafe, host); err == nil { | |
| 23 | 新增: t.Fatalf("accepted unsafe propagation: %s", unsafe) | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| @@ -0,0 +1,161 @@ | ||
| 1 | 新增:// Package containerenv runs the Linux Cage environment without a nested VM. | |
| 2 | 新增:// The host owns the network stack and its policy; a container only exchanges | |
| 3 | 新增:// Ethernet frames over a process pipe and receives no host network interface. | |
| 4 | 新增:package containerenv | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "os/exec" | |
| 12 | 新增: "sync" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/containers/gvisor-tap-vsock/pkg/types" | |
| 16 | 新增: "github.com/containers/gvisor-tap-vsock/pkg/virtualnetwork" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:const ( | |
| 21 | 新增: GuestIP = "192.168.64.2" | |
| 22 | 新增: GatewayIP = "192.168.64.1" | |
| 23 | 新增: GuestMAC = "5a:94:ef:e4:0c:02" | |
| 24 | 新增: GatewayMAC = "5a:94:ef:e4:0c:01" | |
| 25 | 新增: TapName = "cagetap0" | |
| 26 | 新增: NetworkMTU = 1500 | |
| 27 | 新增:) | |
| 28 | 新增: | |
| 29 | 新增:// Network owns the only path between the container and the outside network. | |
| 30 | 新增:// The caller must close the process endpoint when Run returns. A gate starts | |
| 31 | 新增:// closed; connecting SSH does not authorize any guest outbound traffic. | |
| 32 | 新增:type Network struct { | |
| 33 | 新增: Gate *cage.EgressGate | |
| 34 | 新增: stack *virtualnetwork.VirtualNetwork | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func networkConfiguration(gate *cage.EgressGate) types.Configuration { | |
| 38 | 新增: return types.Configuration{ | |
| 39 | 新增: MTU: NetworkMTU, | |
| 40 | 新增: Subnet: "192.168.64.0/24", GatewayIP: GatewayIP, | |
| 41 | 新增: GatewayMacAddress: GatewayMAC, | |
| 42 | 新增: DHCPStaticLeases: map[string]string{GuestIP: GuestMAC}, | |
| 43 | 新增: // No NAT-to-host entries and no automatically published ports. | |
| 44 | 新增: NAT: map[string]string{}, Forwards: map[string]string{}, | |
| 45 | 新增: Ec2MetadataAccess: false, | |
| 46 | 新增: Outbound: gate.Allows, DialContext: gate.DialContext, | |
| 47 | 新增: DNSExchange: gate.ExchangeDNS, | |
| 48 | 新增: } | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func NewNetwork(cfg cage.Config) (*Network, error) { | |
| 52 | 新增: gate, err := cage.NewEgressGate(cfg) | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: return nil, err | |
| 55 | 新增: } | |
| 56 | 新增: configuration := networkConfiguration(gate) | |
| 57 | 新增: stack, err := virtualnetwork.New(&configuration) | |
| 58 | 新增: if err != nil { | |
| 59 | 新增: gate.Close("容器网络初始化失败") | |
| 60 | 新增: return nil, err | |
| 61 | 新增: } | |
| 62 | 新增: return &Network{Gate: gate, stack: stack}, nil | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:// Run consumes the documented four-byte big-endian frame length followed by | |
| 66 | 新增:// an Ethernet frame. AcceptQemu names the wire format, not a VM dependency. | |
| 67 | 新增:func (n *Network) Run(ctx context.Context, endpoint net.Conn) error { | |
| 68 | 新增: stop := context.AfterFunc(ctx, func() { _ = endpoint.Close() }) | |
| 69 | 新增: defer stop() | |
| 70 | 新增: defer n.Gate.Close("容器网络连接已断开") | |
| 71 | 新增: defer endpoint.Close() | |
| 72 | 新增: return n.stack.AcceptQemu(ctx, &boundedFrameConnection{Conn: endpoint}) | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:// ServeSSH only accepts the listener supplied by the host. It never listens | |
| 76 | 新增:// inside the virtual gateway, so a guest cannot use this as a reverse proxy. | |
| 77 | 新增:func (n *Network) ServeSSH(ctx context.Context, listener net.Listener) error { | |
| 78 | 新增: address, ok := listener.Addr().(*net.TCPAddr) | |
| 79 | 新增: if !ok || !address.IP.IsLoopback() { | |
| 80 | 新增: return errors.New("容器 SSH 入口必须监听本机回环地址") | |
| 81 | 新增: } | |
| 82 | 新增: ctx, cancel := context.WithCancel(ctx) | |
| 83 | 新增: stop := context.AfterFunc(ctx, func() { _ = listener.Close() }) | |
| 84 | 新增: defer stop() | |
| 85 | 新增: var active sync.WaitGroup | |
| 86 | 新增: defer func() { cancel(); _ = listener.Close(); active.Wait() }() | |
| 87 | 新增: for { | |
| 88 | 新增: local, err := listener.Accept() | |
| 89 | 新增: if err != nil { | |
| 90 | 新增: if ctx.Err() != nil { | |
| 91 | 新增: return ctx.Err() | |
| 92 | 新增: } | |
| 93 | 新增: return err | |
| 94 | 新增: } | |
| 95 | 新增: active.Add(1) | |
| 96 | 新增: go func() { | |
| 97 | 新增: defer active.Done() | |
| 98 | 新增: defer local.Close() | |
| 99 | 新增: cancelLocal := context.AfterFunc(ctx, func() { _ = local.Close() }) | |
| 100 | 新增: defer cancelLocal() | |
| 101 | 新增: dialCtx, cancel := context.WithTimeout(ctx, 5*time.Second) | |
| 102 | 新增: remote, err := n.stack.DialContextTCP(dialCtx, GuestIP+":22") | |
| 103 | 新增: cancel() | |
| 104 | 新增: if err != nil { | |
| 105 | 新增: return | |
| 106 | 新增: } | |
| 107 | 新增: defer remote.Close() | |
| 108 | 新增: cancelRemote := context.AfterFunc(ctx, func() { _ = remote.Close() }) | |
| 109 | 新增: defer cancelRemote() | |
| 110 | 新增: done := make(chan struct{}) | |
| 111 | 新增: go func() { _, _ = io.Copy(remote, local); _ = remote.Close(); _ = local.Close(); close(done) }() | |
| 112 | 新增: _, _ = io.Copy(local, remote) | |
| 113 | 新增: _ = local.Close() | |
| 114 | 新增: _ = remote.Close() | |
| 115 | 新增: <-done | |
| 116 | 新增: }() | |
| 117 | 新增: } | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:// ProcessEndpoint connects an exec -i process to the frame protocol. The | |
| 121 | 新增:// process must emit only frames on stdout; diagnostics belong to stderr. | |
| 122 | 新增:// Closing the endpoint terminates this process and releases both pipes. | |
| 123 | 新增:func ProcessEndpoint(command *exec.Cmd) (net.Conn, func() error, error) { | |
| 124 | 新增: input, err := command.StdinPipe() | |
| 125 | 新增: if err != nil { | |
| 126 | 新增: return nil, nil, err | |
| 127 | 新增: } | |
| 128 | 新增: output, err := command.StdoutPipe() | |
| 129 | 新增: if err != nil { | |
| 130 | 新增: input.Close() | |
| 131 | 新增: return nil, nil, err | |
| 132 | 新增: } | |
| 133 | 新增: if err = command.Start(); err != nil { | |
| 134 | 新增: input.Close() | |
| 135 | 新增: output.Close() | |
| 136 | 新增: return nil, nil, err | |
| 137 | 新增: } | |
| 138 | 新增: endpoint, bridge := net.Pipe() | |
| 139 | 新增: var closeOnce sync.Once | |
| 140 | 新增: closeProcess := func() { | |
| 141 | 新增: closeOnce.Do(func() { _ = input.Close(); _ = output.Close(); _ = bridge.Close(); _ = command.Process.Kill() }) | |
| 142 | 新增: } | |
| 143 | 新增: var copies sync.WaitGroup | |
| 144 | 新增: copies.Add(2) | |
| 145 | 新增: go func() { defer copies.Done(); defer closeProcess(); _, _ = io.Copy(input, bridge) }() | |
| 146 | 新增: go func() { defer copies.Done(); defer closeProcess(); _, _ = io.Copy(bridge, output) }() | |
| 147 | 新增: var waitOnce sync.Once | |
| 148 | 新增: var waitErr error | |
| 149 | 新增: wait := func() error { | |
| 150 | 新增: waitOnce.Do(func() { _ = endpoint.Close(); closeProcess(); copies.Wait(); waitErr = command.Wait() }) | |
| 151 | 新增: return waitErr | |
| 152 | 新增: } | |
| 153 | 新增: return &processConnection{Conn: endpoint, closeProcess: closeProcess}, wait, nil | |
| 154 | 新增:} | |
| 155 | 新增: | |
| 156 | 新增:type processConnection struct { | |
| 157 | 新增: net.Conn | |
| 158 | 新增: closeProcess func() | |
| 159 | 新增:} | |
| 160 | 新增: | |
| 161 | 新增:func (c *processConnection) Close() error { err := c.Conn.Close(); c.closeProcess(); return err } | |
| @@ -0,0 +1,164 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/binary" | |
| 7 | 新增: "io" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "testing" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/google/gopacket" | |
| 15 | 新增: "github.com/google/gopacket/layers" | |
| 16 | 新增: "github.com/miekg/dns" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:func TestFramesRejectInvalidLengthsAndTruncation(t *testing.T) { | |
| 21 | 新增: for _, size := range []uint32{0, 13, maxFrameSize + 1, 0xffffffff} { | |
| 22 | 新增: var header [4]byte | |
| 23 | 新增: binary.BigEndian.PutUint32(header[:], size) | |
| 24 | 新增: if _, err := readFrame(bytes.NewReader(header[:]), make([]byte, maxFrameSize)); err == nil { | |
| 25 | 新增: t.Fatalf("accepted frame size %d", size) | |
| 26 | 新增: } | |
| 27 | 新增: } | |
| 28 | 新增: var stream bytes.Buffer | |
| 29 | 新增: frame := bytes.Repeat([]byte{1}, 64) | |
| 30 | 新增: if err := writeFrame(&stream, frame); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: if _, err := readFrame(bytes.NewReader(stream.Bytes()[:stream.Len()-1]), make([]byte, maxFrameSize)); err != io.ErrUnexpectedEOF { | |
| 34 | 新增: t.Fatalf("truncated frame: %v", err) | |
| 35 | 新增: } | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func TestContainerNetworkARPAndClosedDNS(t *testing.T) { | |
| 39 | 新增: network, err := NewNetwork(cage.DefaultConfig()) | |
| 40 | 新增: if err != nil { | |
| 41 | 新增: t.Fatal(err) | |
| 42 | 新增: } | |
| 43 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 44 | 新增: defer cancel() | |
| 45 | 新增: host, guest := net.Pipe() | |
| 46 | 新增: defer guest.Close() | |
| 47 | 新增: done := make(chan error, 1) | |
| 48 | 新增: go func() { done <- network.Run(ctx, host) }() | |
| 49 | 新增: defer func() { | |
| 50 | 新增: cancel() | |
| 51 | 新增: guest.Close() | |
| 52 | 新增: select { | |
| 53 | 新增: case <-done: | |
| 54 | 新增: case <-time.After(time.Second): | |
| 55 | 新增: t.Error("network did not stop") | |
| 56 | 新增: } | |
| 57 | 新增: }() | |
| 58 | 新增: _ = guest.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 59 | 新增: guestMAC, _ := net.ParseMAC(GuestMAC) | |
| 60 | 新增: gatewayMAC, _ := net.ParseMAC(GatewayMAC) | |
| 61 | 新增: arp := &layers.ARP{AddrType: layers.LinkTypeEthernet, Protocol: layers.EthernetTypeIPv4, HwAddressSize: 6, ProtAddressSize: 4, Operation: layers.ARPRequest, SourceHwAddress: guestMAC, SourceProtAddress: net.ParseIP(GuestIP).To4(), DstHwAddress: make([]byte, 6), DstProtAddress: net.ParseIP(GatewayIP).To4()} | |
| 62 | 新增: ethernet := &layers.Ethernet{SrcMAC: guestMAC, DstMAC: net.HardwareAddr{255, 255, 255, 255, 255, 255}, EthernetType: layers.EthernetTypeARP} | |
| 63 | 新增: buffer := gopacket.NewSerializeBuffer() | |
| 64 | 新增: if err := gopacket.SerializeLayers(buffer, gopacket.SerializeOptions{FixLengths: true}, ethernet, arp); err != nil { | |
| 65 | 新增: t.Fatal(err) | |
| 66 | 新增: } | |
| 67 | 新增: if err := writeFrame(guest, buffer.Bytes()); err != nil { | |
| 68 | 新增: t.Fatal(err) | |
| 69 | 新增: } | |
| 70 | 新增: response, err := readFrame(guest, make([]byte, maxFrameSize)) | |
| 71 | 新增: if err != nil { | |
| 72 | 新增: t.Fatal(err) | |
| 73 | 新增: } | |
| 74 | 新增: packet := gopacket.NewPacket(response, layers.LayerTypeEthernet, gopacket.Default) | |
| 75 | 新增: answer, ok := packet.Layer(layers.LayerTypeARP).(*layers.ARP) | |
| 76 | 新增: if !ok || answer.Operation != layers.ARPReply || !bytes.Equal(answer.SourceHwAddress, gatewayMAC) { | |
| 77 | 新增: t.Fatal("virtual gateway did not answer ARP") | |
| 78 | 新增: } | |
| 79 | 新增: | |
| 80 | 新增: query := new(dns.Msg) | |
| 81 | 新增: query.SetQuestion("example.com.", dns.TypeA) | |
| 82 | 新增: payload, _ := query.Pack() | |
| 83 | 新增: ip := &layers.IPv4{Version: 4, IHL: 5, TTL: 64, Protocol: layers.IPProtocolUDP, SrcIP: net.ParseIP(GuestIP), DstIP: net.ParseIP(GatewayIP)} | |
| 84 | 新增: udp := &layers.UDP{SrcPort: 41000, DstPort: 53} | |
| 85 | 新增: _ = udp.SetNetworkLayerForChecksum(ip) | |
| 86 | 新增: ethernet = &layers.Ethernet{SrcMAC: guestMAC, DstMAC: gatewayMAC, EthernetType: layers.EthernetTypeIPv4} | |
| 87 | 新增: buffer = gopacket.NewSerializeBuffer() | |
| 88 | 新增: if err := gopacket.SerializeLayers(buffer, gopacket.SerializeOptions{FixLengths: true, ComputeChecksums: true}, ethernet, ip, udp, gopacket.Payload(payload)); err != nil { | |
| 89 | 新增: t.Fatal(err) | |
| 90 | 新增: } | |
| 91 | 新增: if err := writeFrame(guest, buffer.Bytes()); err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: response, err = readFrame(guest, make([]byte, maxFrameSize)) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: t.Fatal(err) | |
| 97 | 新增: } | |
| 98 | 新增: packet = gopacket.NewPacket(response, layers.LayerTypeEthernet, gopacket.Default) | |
| 99 | 新增: dnsLayer := packet.Layer(layers.LayerTypeDNS) | |
| 100 | 新增: if dnsLayer == nil { | |
| 101 | 新增: t.Fatalf("expected DNS refusal, got %v", packet) | |
| 102 | 新增: } | |
| 103 | 新增: if network.Gate.Status().Counters.DNSDenied == 0 { | |
| 104 | 新增: t.Fatal("DNS bypassed the closed host gate") | |
| 105 | 新增: } | |
| 106 | 新增:} | |
| 107 | 新增: | |
| 108 | 新增:func TestHostRejectsGuestMalformedFrames(t *testing.T) { | |
| 109 | 新增: for _, size := range []uint32{0, 13, 0xffffffff} { | |
| 110 | 新增: network, err := NewNetwork(cage.DefaultConfig()) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: t.Fatal(err) | |
| 113 | 新增: } | |
| 114 | 新增: host, guest := net.Pipe() | |
| 115 | 新增: done := make(chan error, 1) | |
| 116 | 新增: go func() { done <- network.Run(context.Background(), host) }() | |
| 117 | 新增: var header [4]byte | |
| 118 | 新增: binary.BigEndian.PutUint32(header[:], size) | |
| 119 | 新增: _, _ = guest.Write(header[:]) | |
| 120 | 新增: guest.Close() | |
| 121 | 新增: select { | |
| 122 | 新增: case err := <-done: | |
| 123 | 新增: if err == nil { | |
| 124 | 新增: t.Errorf("accepted size %d", size) | |
| 125 | 新增: } | |
| 126 | 新增: case <-time.After(time.Second): | |
| 127 | 新增: t.Fatal("malformed guest frame blocked host") | |
| 128 | 新增: } | |
| 129 | 新增: } | |
| 130 | 新增:} | |
| 131 | 新增: | |
| 132 | 新增:func TestProcessEndpointClosesIdleProcess(t *testing.T) { | |
| 133 | 新增: if os.Getenv("CAGE_CONTAINER_PIPE_TEST") == "1" { | |
| 134 | 新增: _, _ = io.Copy(os.Stdout, os.Stdin) | |
| 135 | 新增: os.Exit(0) | |
| 136 | 新增: } | |
| 137 | 新增: command := exec.Command(os.Args[0], "-test.run=^TestProcessEndpointClosesIdleProcess$") | |
| 138 | 新增: command.Env = append(os.Environ(), "CAGE_CONTAINER_PIPE_TEST=1") | |
| 139 | 新增: endpoint, wait, err := ProcessEndpoint(command) | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: t.Fatal(err) | |
| 142 | 新增: } | |
| 143 | 新增: _ = endpoint.SetDeadline(time.Now().Add(3 * time.Second)) | |
| 144 | 新增: done := make(chan error, 1) | |
| 145 | 新增: go func() { _, err := endpoint.Write([]byte("frame")); done <- err }() | |
| 146 | 新增: got := make([]byte, 5) | |
| 147 | 新增: if _, err := io.ReadFull(endpoint, got); err != nil { | |
| 148 | 新增: t.Fatal(err) | |
| 149 | 新增: } | |
| 150 | 新增: if string(got) != "frame" { | |
| 151 | 新增: t.Fatalf("pipe payload %q", got) | |
| 152 | 新增: } | |
| 153 | 新增: if err := <-done; err != nil { | |
| 154 | 新增: t.Fatal(err) | |
| 155 | 新增: } | |
| 156 | 新增: endpoint.Close() | |
| 157 | 新增: waited := make(chan struct{}) | |
| 158 | 新增: go func() { _ = wait(); close(waited) }() | |
| 159 | 新增: select { | |
| 160 | 新增: case <-waited: | |
| 161 | 新增: case <-time.After(time.Second): | |
| 162 | 新增: t.Fatal("idle helper was not reaped") | |
| 163 | 新增: } | |
| 164 | 新增:} | |
| @@ -0,0 +1,110 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "fmt" | |
| 7 | 新增: "io" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strconv" | |
| 11 | 新增: "strings" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// Docker supplies a read-only cgroup mount. In the container's private cgroup | |
| 17 | 新增:// and user namespaces, mount cgroup2 afresh so systemd sees only its delegated | |
| 18 | 新增:// subtree. No host filesystem is bound into the container. | |
| 19 | 新增:const dockerInit = `set -eu | |
| 20 | 新增:umount /sys/fs/cgroup | |
| 21 | 新增:mount -t cgroup2 none /sys/fs/cgroup | |
| 22 | 新增:exec /sbin/init | |
| 23 | 新增:` | |
| 24 | 新增: | |
| 25 | 新增:func (r *Runtime) createArguments() []string { | |
| 26 | 新增: args := []string{"create", "--name", r.Name(), "--label", profileLabel + "=" + r.identity, "--network", "none", "--cgroupns", "private", "--cgroup-parent", r.resourceSlice(), "--ipc", "private", "--hostname", "cage", "--add-host", "cage:127.0.1.1", "--cpus", strconv.Itoa(r.config.CPUs), "--memory", strconv.FormatInt(r.config.MemoryBytes, 10), "--pids-limit", strconv.Itoa(PIDLimit), "--device", "/dev/fuse", "--device", "/dev/net/tun", "--cap-add", "SYS_ADMIN", "--cap-add", "NET_ADMIN", "--tmpfs", "/run", "--tmpfs", "/tmp", "--stop-signal", "SIGRTMIN+3", "--stop-timeout", "30"} | |
| 27 | 新增: if r.config.Engine == "podman" { | |
| 28 | 新增: return append(args, "--http-proxy=false", "--systemd", "always", "--pull", "never", "--entrypoint", "/sbin/init", r.config.Image) | |
| 29 | 新增: } | |
| 30 | 新增: return append(args, "--pull", "never", "--entrypoint", "/bin/sh", r.config.Image, "-c", dockerInit) | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:// Prepare creates one stopped, persistent container from a locally available | |
| 34 | 新增:// pinned image. It never pulls an image, removes a container, or rebuilds an | |
| 35 | 新增:// existing writable layer. Guest tooling is installed over the guarded SSH | |
| 36 | 新增:// maintenance path after Start establishes the network and protected share. | |
| 37 | 新增:func (r *Runtime) Prepare(ctx context.Context, log io.Writer) error { | |
| 38 | 新增: if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { | |
| 39 | 新增: return err | |
| 40 | 新增: } | |
| 41 | 新增: unlock, err := lockRuntime(ctx, filepath.Join(r.InstanceDir(), "lifecycle.lock")) | |
| 42 | 新增: if err != nil { | |
| 43 | 新增: return err | |
| 44 | 新增: } | |
| 45 | 新增: defer unlock() | |
| 46 | 新增: rootless, err := r.rootlessEngine(ctx) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: if !rootless { | |
| 51 | 新增: return errors.New("Cage 只允许使用独立 rootless 容器引擎") | |
| 52 | 新增: } | |
| 53 | 新增: if err := r.ensureResourceSlice(ctx); err != nil { | |
| 54 | 新增: return err | |
| 55 | 新增: } | |
| 56 | 新增: container, err := r.inspectContainer(ctx) | |
| 57 | 新增: if err != nil { | |
| 58 | 新增: return err | |
| 59 | 新增: } | |
| 60 | 新增: if container != nil { | |
| 61 | 新增: if err := checkContainerConfiguration(container); err != nil { | |
| 62 | 新增: return err | |
| 63 | 新增: } | |
| 64 | 新增: if container.HostConfig.CgroupParent != r.resourceSlice() { | |
| 65 | 新增: return errors.New("已有容器缺少宿主资源边界;未重建或删除原数据") | |
| 66 | 新增: } | |
| 67 | 新增: return r.recordStorage(ctx, container.ID) | |
| 68 | 新增: } | |
| 69 | 新增: for _, device := range []string{"/dev/fuse", "/dev/net/tun"} { | |
| 70 | 新增: info, err := os.Stat(device) | |
| 71 | 新增: if err != nil || info.Mode()&os.ModeDevice == 0 { | |
| 72 | 新增: return fmt.Errorf("服务器缺少容器所需设备 %s", device) | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: image, err := r.output(ctx, "image", "inspect", "--format", "{{.Id}}", r.config.Image) | |
| 76 | 新增: if err != nil { | |
| 77 | 新增: return errors.New("指定的固定容器基础镜像尚未安装,请先完成服务器部署") | |
| 78 | 新增: } | |
| 79 | 新增: if !imageIDPattern.MatchString(strings.TrimSpace(string(image))) { | |
| 80 | 新增: return errors.New("容器基础镜像没有有效 SHA-256 标识") | |
| 81 | 新增: } | |
| 82 | 新增: if _, err := r.output(ctx, r.createArguments()...); err != nil { | |
| 83 | 新增: return err | |
| 84 | 新增: } | |
| 85 | 新增: container, err = r.inspectContainer(ctx) | |
| 86 | 新增: if err != nil { | |
| 87 | 新增: return err | |
| 88 | 新增: } | |
| 89 | 新增: if container == nil { | |
| 90 | 新增: return errors.New("容器创建后未能验证身份") | |
| 91 | 新增: } | |
| 92 | 新增: if err := checkContainerConfiguration(container); err != nil { | |
| 93 | 新增: return err | |
| 94 | 新增: } | |
| 95 | 新增: if err := r.recordStorage(ctx, container.ID); err != nil { | |
| 96 | 新增: return err | |
| 97 | 新增: } | |
| 98 | 新增: if log != nil { | |
| 99 | 新增: fmt.Fprintln(log, "Cage container prepared with a persistent filesystem and no default network.") | |
| 100 | 新增: } | |
| 101 | 新增: return nil | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 104 | 新增:func (r *Runtime) recordStorage(ctx context.Context, containerID string) error { | |
| 105 | 新增: path, err := r.StoragePath(ctx) | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: return writePrivateJSON(filepath.Join(r.InstanceDir(), "storage.json"), map[string]string{"engine": r.config.Engine, "container_id": containerID, "storage_path": path}) | |
| 110 | 新增:} | |
| @@ -0,0 +1,43 @@ | ||
| 1 | 新增://go:build linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os" | |
| 9 | 新增: "os/exec" | |
| 10 | 新增: "syscall" | |
| 11 | 新增: "time" | |
| 12 | 新增: | |
| 13 | 新增: "golang.org/x/sys/unix" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func detachWorker(command *exec.Cmd) { command.SysProcAttr = &syscall.SysProcAttr{Setsid: true} } | |
| 17 | 新增:func tryLockRuntime(path string) (func(), error) { | |
| 18 | 新增: file, err := os.OpenFile(path, os.O_CREATE|os.O_RDWR, 0600) | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: return nil, err | |
| 21 | 新增: } | |
| 22 | 新增: if err = unix.Flock(int(file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { | |
| 23 | 新增: file.Close() | |
| 24 | 新增: return nil, err | |
| 25 | 新增: } | |
| 26 | 新增: return func() { _ = unix.Flock(int(file.Fd()), unix.LOCK_UN); _ = file.Close() }, nil | |
| 27 | 新增:} | |
| 28 | 新增:func lockRuntime(ctx context.Context, path string) (func(), error) { | |
| 29 | 新增: for { | |
| 30 | 新增: unlock, err := tryLockRuntime(path) | |
| 31 | 新增: if err == nil { | |
| 32 | 新增: return unlock, nil | |
| 33 | 新增: } | |
| 34 | 新增: if !errors.Is(err, unix.EWOULDBLOCK) { | |
| 35 | 新增: return nil, err | |
| 36 | 新增: } | |
| 37 | 新增: select { | |
| 38 | 新增: case <-ctx.Done(): | |
| 39 | 新增: return nil, ctx.Err() | |
| 40 | 新增: case <-time.After(100 * time.Millisecond): | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增:} | |
| @@ -0,0 +1,17 @@ | ||
| 1 | 新增://go:build !linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "os/exec" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func detachWorker(*exec.Cmd) {} | |
| 12 | 新增:func tryLockRuntime(string) (func(), error) { | |
| 13 | 新增: return nil, errors.New("容器运行环境仅支持 Linux 服务器") | |
| 14 | 新增:} | |
| 15 | 新增:func lockRuntime(context.Context, string) (func(), error) { | |
| 16 | 新增: return nil, errors.New("容器运行环境仅支持 Linux 服务器") | |
| 17 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "strconv" | |
| 7 | 新增: "strings" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:const PIDLimit = 1024 | |
| 11 | 新增: | |
| 12 | 新增:type resourceEvidence struct { | |
| 13 | 新增: MemoryBytes int64 `json:"memory_bytes"` | |
| 14 | 新增: CPUs int `json:"cpus"` | |
| 15 | 新增: PIDs int64 `json:"pids"` | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:func (r *Runtime) resourceSlice() string { return "cage" + r.identity + ".slice" } | |
| 19 | 新增: | |
| 20 | 新增:// Read the host-owned parent cgroup, outside the guest's writable namespace, | |
| 21 | 新增:// and verify that systemd placed this exact container scope underneath it. | |
| 22 | 新增:func (r *Runtime) verifyResources(ctx context.Context, containerID string) (resourceEvidence, error) { | |
| 23 | 新增: return r.verifyHostResources(ctx, containerID) | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func parseResourceEvidence(data string, configuration Config) (resourceEvidence, error) { | |
| 27 | 新增: lines := strings.SplitN(strings.TrimSpace(data), "\n", 4) | |
| 28 | 新增: if len(lines) != 4 { | |
| 29 | 新增: return resourceEvidence{}, errors.New("容器未返回完整 cgroup 资源限额") | |
| 30 | 新增: } | |
| 31 | 新增: memory, memoryErr := strconv.ParseInt(strings.TrimSpace(lines[0]), 10, 64) | |
| 32 | 新增: cpu := strings.Fields(lines[1]) | |
| 33 | 新增: pids, pidErr := strconv.ParseInt(strings.TrimSpace(lines[2]), 10, 64) | |
| 34 | 新增: if memoryErr != nil || pidErr != nil || len(cpu) != 2 { | |
| 35 | 新增: return resourceEvidence{}, errors.New("容器 CPU、内存或进程数限额未生效") | |
| 36 | 新增: } | |
| 37 | 新增: quota, quotaErr := strconv.ParseInt(cpu[0], 10, 64) | |
| 38 | 新增: period, periodErr := strconv.ParseInt(cpu[1], 10, 64) | |
| 39 | 新增: if quotaErr != nil || periodErr != nil || period < 1000 || period > 1000000 || quota != int64(configuration.CPUs)*period || memory != configuration.MemoryBytes || pids != PIDLimit { | |
| 40 | 新增: return resourceEvidence{}, errors.New("容器内核资源限额与配置不一致,拒绝继续启动") | |
| 41 | 新增: } | |
| 42 | 新增: cgroup2 := false | |
| 43 | 新增: for _, mount := range strings.Split(lines[3], "\n") { | |
| 44 | 新增: fields := strings.Fields(mount) | |
| 45 | 新增: if len(fields) > 6 && fields[4] == "/sys/fs/cgroup" && strings.Contains(mount, " - cgroup2 ") { | |
| 46 | 新增: cgroup2 = true | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增: if !cgroup2 { | |
| 50 | 新增: return resourceEvidence{}, errors.New("容器资源限额缺少 cgroup v2 内核挂载证据") | |
| 51 | 新增: } | |
| 52 | 新增: return resourceEvidence{MemoryBytes: memory, CPUs: configuration.CPUs, PIDs: pids}, nil | |
| 53 | 新增:} | |
| @@ -0,0 +1,26 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "strings" | |
| 5 | 新增: "testing" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:func TestKernelResourceEvidenceRejectsIgnoredOrDifferentLimits(t *testing.T) { | |
| 9 | 新增: valid := "4294967296\n200000 100000\n1024\n698 756 0:25 / /sys/fs/cgroup rw,relatime - cgroup2 none rw\n" | |
| 10 | 新增: if evidence, err := parseResourceEvidence(valid, fixtureConfig()); err != nil || evidence.CPUs != 2 || evidence.MemoryBytes != 4<<30 || evidence.PIDs != 1024 { | |
| 11 | 新增: t.Fatalf("valid cgroup evidence: %+v %v", evidence, err) | |
| 12 | 新增: } | |
| 13 | 新增: for _, broken := range []string{ | |
| 14 | 新增: strings.Replace(valid, "4294967296", "max", 1), | |
| 15 | 新增: strings.Replace(valid, "200000 100000", "max 100000", 1), | |
| 16 | 新增: strings.Replace(valid, "1024", "max", 1), | |
| 17 | 新增: strings.Replace(valid, "1024", "512", 1), | |
| 18 | 新增: strings.Replace(valid, "200000 100000", "400000 100000", 1), | |
| 19 | 新增: strings.Replace(valid, "cgroup2", "tmpfs", 1), | |
| 20 | 新增: strings.Replace(valid, "/sys/fs/cgroup", "/somewhere", 1), | |
| 21 | 新增: } { | |
| 22 | 新增: if _, err := parseResourceEvidence(broken, fixtureConfig()); err == nil { | |
| 23 | 新增: t.Fatalf("accepted non-enforced resource evidence %q", broken) | |
| 24 | 新增: } | |
| 25 | 新增: } | |
| 26 | 新增:} | |
| @@ -0,0 +1,154 @@ | ||
| 1 | 新增://go:build linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "fmt" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "os" | |
| 12 | 新增: "os/exec" | |
| 13 | 新增: "strings" | |
| 14 | 新增: "time" | |
| 15 | 新增: | |
| 16 | 新增: "golang.org/x/sys/unix" | |
| 17 | 新增:) | |
| 18 | 新增: | |
| 19 | 新增:// RunTAP is an internal guest-only helper. Its stdout is exclusively framed | |
| 20 | 新增:// Ethernet data. The caller connects it to the host-owned network stack. | |
| 21 | 新增:func RunTAP(ctx context.Context, input io.Reader, output io.Writer) error { | |
| 22 | 新增: if err := requirePrivateGuestNetwork(); err != nil { | |
| 23 | 新增: return err | |
| 24 | 新增: } | |
| 25 | 新增: // A disconnected engine exec can take a moment to deliver EOF to its old | |
| 26 | 新增: // helper. Wait for that non-persistent TAP to vanish; never delete an | |
| 27 | 新增: // interface or take over another process's file descriptor. | |
| 28 | 新增: waitCtx, cancel := context.WithTimeout(ctx, 5*time.Second) | |
| 29 | 新增: defer cancel() | |
| 30 | 新增: for { | |
| 31 | 新增: interfaces, err := net.Interfaces() | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return err | |
| 34 | 新增: } | |
| 35 | 新增: oldTap := false | |
| 36 | 新增: for _, iface := range interfaces { | |
| 37 | 新增: if iface.Name == TapName { | |
| 38 | 新增: oldTap = true | |
| 39 | 新增: } else if iface.Name != "lo" { | |
| 40 | 新增: return errors.New("容器存在额外网络接口,拒绝启动 TAP") | |
| 41 | 新增: } | |
| 42 | 新增: } | |
| 43 | 新增: if !oldTap { | |
| 44 | 新增: break | |
| 45 | 新增: } | |
| 46 | 新增: select { | |
| 47 | 新增: case <-waitCtx.Done(): | |
| 48 | 新增: return errors.New("旧容器网络接口仍未退出,请稍后重连") | |
| 49 | 新增: case <-time.After(100 * time.Millisecond): | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: // An unattached TUN fd reports POLLERR. Registering it with Go's poller | |
| 53 | 新增: // before TUNSETIFF races with an irreversible "not pollable" error. | |
| 54 | 新增: // Attach the device first, then wrap the nonblocking descriptor. | |
| 55 | 新增: fd, err := unix.Open("/dev/net/tun", unix.O_RDWR|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) | |
| 56 | 新增: if err != nil { | |
| 57 | 新增: return err | |
| 58 | 新增: } | |
| 59 | 新增: request, err := unix.NewIfreq(TapName) | |
| 60 | 新增: if err != nil { | |
| 61 | 新增: _ = unix.Close(fd) | |
| 62 | 新增: return err | |
| 63 | 新增: } | |
| 64 | 新增: request.SetUint16(unix.IFF_TAP | unix.IFF_NO_PI) | |
| 65 | 新增: if err := unix.IoctlIfreq(fd, unix.TUNSETIFF, request); err != nil { | |
| 66 | 新增: _ = unix.Close(fd) | |
| 67 | 新增: return err | |
| 68 | 新增: } | |
| 69 | 新增: file := os.NewFile(uintptr(fd), "/dev/net/tun") | |
| 70 | 新增: if file == nil { | |
| 71 | 新增: _ = unix.Close(fd) | |
| 72 | 新增: return errors.New("无法管理容器 TAP 文件描述符") | |
| 73 | 新增: } | |
| 74 | 新增: defer file.Close() | |
| 75 | 新增: for _, arguments := range [][]string{ | |
| 76 | 新增: {"link", "set", "dev", TapName, "address", GuestMAC, "mtu", fmt.Sprint(NetworkMTU)}, | |
| 77 | 新增: {"link", "set", "dev", "lo", "up"}, | |
| 78 | 新增: {"address", "add", GuestIP + "/24", "dev", TapName}, | |
| 79 | 新增: {"link", "set", "dev", TapName, "up"}, | |
| 80 | 新增: {"route", "add", "default", "via", GatewayIP, "dev", TapName}, | |
| 81 | 新增: } { | |
| 82 | 新增: if result, err := exec.CommandContext(ctx, "ip", arguments...).CombinedOutput(); err != nil { | |
| 83 | 新增: return fmt.Errorf("configure container TAP: %w: %.1024s", err, result) | |
| 84 | 新增: } | |
| 85 | 新增: } | |
| 86 | 新增: // The host resolver must never be inherited by the workload. Write through | |
| 87 | 新增: // the engine's resolv.conf mount; do not replace the mount or a symlink. | |
| 88 | 新增: info, err := os.Lstat("/etc/resolv.conf") | |
| 89 | 新增: if err != nil || !info.Mode().IsRegular() { | |
| 90 | 新增: return errors.New("容器 DNS 配置必须是普通文件") | |
| 91 | 新增: } | |
| 92 | 新增: if err = os.WriteFile("/etc/resolv.conf", []byte("nameserver "+GatewayIP+"\noptions timeout:2 attempts:2\n"), 0644); err != nil { | |
| 93 | 新增: return err | |
| 94 | 新增: } | |
| 95 | 新增: stop := context.AfterFunc(ctx, func() { _ = file.Close() }) | |
| 96 | 新增: defer stop() | |
| 97 | 新增: ended := make(chan error, 1) | |
| 98 | 新增: go func() { | |
| 99 | 新增: buffer := make([]byte, maxFrameSize) | |
| 100 | 新增: for { | |
| 101 | 新增: frame, err := readFrame(input, buffer) | |
| 102 | 新增: if err == nil { | |
| 103 | 新增: var n int | |
| 104 | 新增: n, err = file.Write(frame) | |
| 105 | 新增: if err == nil && n != len(frame) { | |
| 106 | 新增: err = io.ErrShortWrite | |
| 107 | 新增: } | |
| 108 | 新增: } | |
| 109 | 新增: if err != nil { | |
| 110 | 新增: _ = file.Close() | |
| 111 | 新增: ended <- err | |
| 112 | 新增: return | |
| 113 | 新增: } | |
| 114 | 新增: } | |
| 115 | 新增: }() | |
| 116 | 新增: buffer := make([]byte, maxFrameSize) | |
| 117 | 新增: for { | |
| 118 | 新增: n, err := file.Read(buffer) | |
| 119 | 新增: if err == nil { | |
| 120 | 新增: err = writeFrame(output, buffer[:n]) | |
| 121 | 新增: } | |
| 122 | 新增: if err != nil { | |
| 123 | 新增: if ctx.Err() != nil { | |
| 124 | 新增: return ctx.Err() | |
| 125 | 新增: } | |
| 126 | 新增: select { | |
| 127 | 新增: case inputErr := <-ended: | |
| 128 | 新增: return inputErr | |
| 129 | 新增: default: | |
| 130 | 新增: return err | |
| 131 | 新增: } | |
| 132 | 新增: } | |
| 133 | 新增: } | |
| 134 | 新增:} | |
| 135 | 新增: | |
| 136 | 新增:func requirePrivateGuestNetwork() error { | |
| 137 | 新增: if os.Geteuid() != 0 { | |
| 138 | 新增: return errors.New("容器 TAP helper 必须以容器内 root 运行") | |
| 139 | 新增: } | |
| 140 | 新增: uidMap, err := os.ReadFile("/proc/self/uid_map") | |
| 141 | 新增: if err != nil { | |
| 142 | 新增: return err | |
| 143 | 新增: } | |
| 144 | 新增: fields := strings.Fields(string(uidMap)) | |
| 145 | 新增: if len(fields) == 3 && fields[0] == "0" && fields[1] == "0" && fields[2] == "4294967295" { | |
| 146 | 新增: return errors.New("容器 TAP helper 拒绝在宿主用户命名空间运行") | |
| 147 | 新增: } | |
| 148 | 新增: if _, first := os.Stat("/run/.containerenv"); first != nil { | |
| 149 | 新增: if _, second := os.Stat("/.dockerenv"); second != nil { | |
| 150 | 新增: return errors.New("容器 TAP helper 只能在 Cage 容器内运行") | |
| 151 | 新增: } | |
| 152 | 新增: } | |
| 153 | 新增: return nil | |
| 154 | 新增:} | |
| @@ -0,0 +1,13 @@ | ||
| 1 | 新增://go:build !linux | |
| 2 | 新增: | |
| 3 | 新增:package containerenv | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func RunTAP(context.Context, io.Reader, io.Writer) error { | |
| 12 | 新增: return errors.New("Cage 容器运行环境仅支持 Linux 服务器") | |
| 13 | 新增:} | |
| @@ -0,0 +1,494 @@ | ||
| 1 | 新增:package containerenv | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "crypto/rand" | |
| 7 | 新增: "encoding/hex" | |
| 8 | 新增: "encoding/json" | |
| 9 | 新增: "errors" | |
| 10 | 新增: "fmt" | |
| 11 | 新增: "io" | |
| 12 | 新增: "net" | |
| 13 | 新增: "os" | |
| 14 | 新增: "os/exec" | |
| 15 | 新增: "path/filepath" | |
| 16 | 新增: "strconv" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "al.essio.dev/pkg/shellescape" | |
| 20 | 新增: "github.com/lima-vm/sshocker/pkg/reversesshfs" | |
| 21 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 22 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 23 | 新增: "github.com/sylvinus/agent-vm/internal/mounts" | |
| 24 | 新增: "golang.org/x/crypto/ssh" | |
| 25 | 新增: "golang.org/x/crypto/ssh/knownhosts" | |
| 26 | 新增:) | |
| 27 | 新增: | |
| 28 | 新增:const guestHelper = "/usr/local/lib/cage-runtime" | |
| 29 | 新增: | |
| 30 | 新增:type networkRecord struct { | |
| 31 | 新增: ContainerID string `json:"container_id"` | |
| 32 | 新增: PID int `json:"pid"` | |
| 33 | 新增: RunID string `json:"run_id"` | |
| 34 | 新增: SSHAddress string `json:"ssh_address"` | |
| 35 | 新增: BrowserAddress string `json:"browser_address"` | |
| 36 | 新增: VNCAddress string `json:"vnc_address"` | |
| 37 | 新增: Shared bool `json:"shared"` | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func (r *Runtime) networkState(ctx context.Context, containerID string) (networkRecord, error) { | |
| 41 | 新增: path := filepath.Join(r.InstanceDir(), "network.json") | |
| 42 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 43 | 新增: return networkRecord{}, err | |
| 44 | 新增: } | |
| 45 | 新增: data, err := os.ReadFile(path) | |
| 46 | 新增: if err != nil || len(data) > 8192 { | |
| 47 | 新增: return networkRecord{}, errors.New("容器连接记录不可用") | |
| 48 | 新增: } | |
| 49 | 新增: var record networkRecord | |
| 50 | 新增: if json.Unmarshal(data, &record) != nil || record.ContainerID != containerID || record.RunID == "" || !record.Shared { | |
| 51 | 新增: return record, errors.New("容器连接记录不属于当前运行环境") | |
| 52 | 新增: } | |
| 53 | 新增: for _, address := range []string{record.SSHAddress, record.BrowserAddress, record.VNCAddress} { | |
| 54 | 新增: host, port, err := net.SplitHostPort(address) | |
| 55 | 新增: number, parseErr := strconv.Atoi(port) | |
| 56 | 新增: ip := net.ParseIP(host) | |
| 57 | 新增: if err != nil || parseErr != nil || ip == nil || !ip.IsLoopback() || number < 1024 || number > 65535 { | |
| 58 | 新增: return record, errors.New("容器连接入口无效") | |
| 59 | 新增: } | |
| 60 | 新增: } | |
| 61 | 新增: client, err := cage.OpenGateClient(r.InstanceDir()) | |
| 62 | 新增: if err != nil { | |
| 63 | 新增: return record, err | |
| 64 | 新增: } | |
| 65 | 新增: status, err := client.Status(ctx) | |
| 66 | 新增: if err != nil || status.RunID != record.RunID { | |
| 67 | 新增: return record, errors.New("容器网络控制服务尚未连接") | |
| 68 | 新增: } | |
| 69 | 新增: return record, nil | |
| 70 | 新增:} | |
| 71 | 新增: | |
| 72 | 新增:// Start starts an existing prepared container and its host network worker. | |
| 73 | 新增:// Parent cancellation before readiness terminates only this newly created | |
| 74 | 新增:// worker; the persistent container and all of its files remain available. | |
| 75 | 新增:func (r *Runtime) Start(ctx context.Context, configPath string, log io.Writer) error { | |
| 76 | 新增: cfg, err := cage.Load(configPath) | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: return err | |
| 79 | 新增: } | |
| 80 | 新增: if err := cfg.RequireManagedProxy(r.profile); err != nil { | |
| 81 | 新增: return err | |
| 82 | 新增: } | |
| 83 | 新增: if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { | |
| 84 | 新增: return err | |
| 85 | 新增: } | |
| 86 | 新增: unlock, err := lockRuntime(ctx, filepath.Join(r.InstanceDir(), "lifecycle.lock")) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return err | |
| 89 | 新增: } | |
| 90 | 新增: defer unlock() | |
| 91 | 新增: if err := r.ensureResourceSlice(ctx); err != nil { | |
| 92 | 新增: return err | |
| 93 | 新增: } | |
| 94 | 新增: inspection, err := r.Inspect(ctx) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: return err | |
| 97 | 新增: } | |
| 98 | 新增: if !inspection.State.Exists { | |
| 99 | 新增: return errors.New("容器尚未准备,请先运行 Cage 容器安装") | |
| 100 | 新增: } | |
| 101 | 新增: if inspection.State.Running { | |
| 102 | 新增: if !inspection.State.MountsReady { | |
| 103 | 新增: return errors.New("容器的项目挂载尚未初始化,请先完整停止环境再启动;文件和登录状态会保留") | |
| 104 | 新增: } | |
| 105 | 新增: if _, err := r.networkState(ctx, inspection.State.ContainerID); err == nil { | |
| 106 | 新增: client, err := cage.OpenGateClient(r.InstanceDir()) | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: return err | |
| 109 | 新增: } | |
| 110 | 新增: state, err := client.Status(ctx) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: return err | |
| 113 | 新增: } | |
| 114 | 新增: if state.Configuration != cfg.Fingerprint() { | |
| 115 | 新增: return errors.New("容器运行配置已变化,请先停止环境后重新启动") | |
| 116 | 新增: } | |
| 117 | 新增: return nil | |
| 118 | 新增: } | |
| 119 | 新增: } else if _, err := r.output(ctx, "start", inspection.State.ContainerID); err != nil { | |
| 120 | 新增: return err | |
| 121 | 新增: } | |
| 122 | 新增: if _, err := r.verifyResources(ctx, inspection.State.ContainerID); err != nil { | |
| 123 | 新增: if !inspection.State.Running { | |
| 124 | 新增: stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) | |
| 125 | 新增: _, _ = r.output(stopCtx, "stop", "--time", "20", inspection.State.ContainerID) | |
| 126 | 新增: cancel() | |
| 127 | 新增: } | |
| 128 | 新增: return err | |
| 129 | 新增: } | |
| 130 | 新增: if !inspection.State.Running { | |
| 131 | 新增: if err := r.initializeMounts(ctx, inspection.State.ContainerID); err != nil { | |
| 132 | 新增: stopCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second) | |
| 133 | 新增: _, _ = r.output(stopCtx, "stop", "--time", "20", inspection.State.ContainerID) | |
| 134 | 新增: cancel() | |
| 135 | 新增: return err | |
| 136 | 新增: } | |
| 137 | 新增: } | |
| 138 | 新增: if err := r.InstallAccess(ctx); err != nil { | |
| 139 | 新增: return err | |
| 140 | 新增: } | |
| 141 | 新增: executable, err := os.Executable() | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: return err | |
| 144 | 新增: } | |
| 145 | 新增: if _, err := r.output(ctx, "cp", executable, inspection.State.ContainerID+":"+guestHelper); err != nil { | |
| 146 | 新增: return err | |
| 147 | 新增: } | |
| 148 | 新增: if _, err := r.output(ctx, "exec", "--user", "0", inspection.State.ContainerID, "chmod", "0755", guestHelper); err != nil { | |
| 149 | 新增: return err | |
| 150 | 新增: } | |
| 151 | 新增: file, err := os.OpenFile(filepath.Join(r.InstanceDir(), "network.log"), os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0600) | |
| 152 | 新增: if err != nil { | |
| 153 | 新增: return err | |
| 154 | 新增: } | |
| 155 | 新增: command := exec.Command(executable, "container-network") | |
| 156 | 新增: command.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) | |
| 157 | 新增: command.Stdout, command.Stderr = file, file | |
| 158 | 新增: detachWorker(command) | |
| 159 | 新增: if err := command.Start(); err != nil { | |
| 160 | 新增: file.Close() | |
| 161 | 新增: return err | |
| 162 | 新增: } | |
| 163 | 新增: done := make(chan error, 1) | |
| 164 | 新增: go func() { done <- command.Wait(); file.Close() }() | |
| 165 | 新增: ticker := time.NewTicker(200 * time.Millisecond) | |
| 166 | 新增: defer ticker.Stop() | |
| 167 | 新增: timeout := time.NewTimer(45 * time.Second) | |
| 168 | 新增: defer timeout.Stop() | |
| 169 | 新增: for { | |
| 170 | 新增: select { | |
| 171 | 新增: case err := <-done: | |
| 172 | 新增: return fmt.Errorf("容器网络服务退出,请查看容器网络日志: %w", err) | |
| 173 | 新增: case <-ctx.Done(): | |
| 174 | 新增: _ = command.Process.Kill() | |
| 175 | 新增: <-done | |
| 176 | 新增: return ctx.Err() | |
| 177 | 新增: case <-timeout.C: | |
| 178 | 新增: _ = command.Process.Kill() | |
| 179 | 新增: <-done | |
| 180 | 新增: return errors.New("容器连接超时;容器文件保留,请查看网络日志") | |
| 181 | 新增: case <-ticker.C: | |
| 182 | 新增: checkCtx, cancel := context.WithTimeout(ctx, time.Second) | |
| 183 | 新增: record, err := r.networkState(checkCtx, inspection.State.ContainerID) | |
| 184 | 新增: cancel() | |
| 185 | 新增: if err == nil && record.PID == command.Process.Pid { | |
| 186 | 新增: if log != nil { | |
| 187 | 新增: fmt.Fprintln(log, "Cage container network and protected project share are ready.") | |
| 188 | 新增: } | |
| 189 | 新增: return nil | |
| 190 | 新增: } | |
| 191 | 新增: } | |
| 192 | 新增: } | |
| 193 | 新增:} | |
| 194 | 新增: | |
| 195 | 新增:// ServeNetwork runs in the dedicated `cage container-network` process. It is | |
| 196 | 新增:// independent of viewer connections. Exiting closes the gate, every proxy | |
| 197 | 新增:// connection and the sole TAP; it never adds a fallback network. | |
| 198 | 新增:func (r *Runtime) ServeNetwork(ctx context.Context, configPath string) error { | |
| 199 | 新增: if err := host.EnsurePrivateDir(r.InstanceDir()); err != nil { | |
| 200 | 新增: return err | |
| 201 | 新增: } | |
| 202 | 新增: unlock, err := tryLockRuntime(filepath.Join(r.InstanceDir(), "network.lock")) | |
| 203 | 新增: if err != nil { | |
| 204 | 新增: return err | |
| 205 | 新增: } | |
| 206 | 新增: defer unlock() | |
| 207 | 新增: ctx, cancel := context.WithCancel(ctx) | |
| 208 | 新增: defer cancel() | |
| 209 | 新增: stopWatch, err := cage.WatchJobStop(r.profile, os.Getenv(cage.JobEnv), cancel) | |
| 210 | 新增: if err != nil { | |
| 211 | 新增: return err | |
| 212 | 新增: } | |
| 213 | 新增: defer stopWatch() | |
| 214 | 新增: inspection, err := r.Inspect(ctx) | |
| 215 | 新增: if err != nil { | |
| 216 | 新增: return err | |
| 217 | 新增: } | |
| 218 | 新增: if !inspection.State.Running { | |
| 219 | 新增: return errors.New("容器未运行") | |
| 220 | 新增: } | |
| 221 | 新增: if !inspection.State.MountsReady { | |
| 222 | 新增: return errors.New("容器项目挂载尚未初始化,请完整停止后重新启动") | |
| 223 | 新增: } | |
| 224 | 新增: cfg, err := cage.Load(configPath) | |
| 225 | 新增: if err != nil { | |
| 226 | 新增: return err | |
| 227 | 新增: } | |
| 228 | 新增: if err := cfg.RequireManagedProxy(r.profile); err != nil { | |
| 229 | 新增: return err | |
| 230 | 新增: } | |
| 231 | 新增: network, err := NewNetwork(cfg) | |
| 232 | 新增: if err != nil { | |
| 233 | 新增: return err | |
| 234 | 新增: } | |
| 235 | 新增: defer network.Gate.Close("容器网络服务已停止") | |
| 236 | 新增: command := r.command(ctx, "exec", "-i", "--user", "0", inspection.State.ContainerID, guestHelper, "container-tap") | |
| 237 | 新增: command.Stderr = os.Stderr | |
| 238 | 新增: endpoint, wait, err := ProcessEndpoint(command) | |
| 239 | 新增: if err != nil { | |
| 240 | 新增: return err | |
| 241 | 新增: } | |
| 242 | 新增: defer func() { endpoint.Close(); _ = wait() }() | |
| 243 | 新增: networkDone := make(chan error, 1) | |
| 244 | 新增: go func() { err := network.Run(ctx, endpoint); cancel(); networkDone <- err }() | |
| 245 | 新增: client, err := r.connectGuestSSH(ctx, network) | |
| 246 | 新增: if err != nil { | |
| 247 | 新增: return err | |
| 248 | 新增: } | |
| 249 | 新增: defer client.Close() | |
| 250 | 新增: interruptSSH := context.AfterFunc(ctx, func() { _ = client.Close() }) | |
| 251 | 新增: defer interruptSSH() | |
| 252 | 新增: shareDone, stopShare, err := r.shareEnvironment(ctx, client) | |
| 253 | 新增: if err != nil { | |
| 254 | 新增: return err | |
| 255 | 新增: } | |
| 256 | 新增: defer stopShare() | |
| 257 | 新增: sshListener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 258 | 新增: if err != nil { | |
| 259 | 新增: return err | |
| 260 | 新增: } | |
| 261 | 新增: defer sshListener.Close() | |
| 262 | 新增: browserListener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 263 | 新增: if err != nil { | |
| 264 | 新增: return err | |
| 265 | 新增: } | |
| 266 | 新增: defer browserListener.Close() | |
| 267 | 新增: vncListener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 268 | 新增: if err != nil { | |
| 269 | 新增: return err | |
| 270 | 新增: } | |
| 271 | 新增: defer vncListener.Close() | |
| 272 | 新增: if err := r.writeSSHConfig(sshListener.Addr().(*net.TCPAddr).Port); err != nil { | |
| 273 | 新增: return err | |
| 274 | 新增: } | |
| 275 | 新增: serviceDone := make(chan error, 3) | |
| 276 | 新增: go func() { serviceDone <- network.ServeSSH(ctx, sshListener) }() | |
| 277 | 新增: go func() { serviceDone <- serveGuestService(ctx, client, browserListener, "127.0.0.1:18500") }() | |
| 278 | 新增: go func() { serviceDone <- serveGuestService(ctx, client, vncListener, "127.0.0.1:15900") }() | |
| 279 | 新增: stopGate, err := cage.StartGateControl(configPath, r.InstanceDir(), network.Gate) | |
| 280 | 新增: if err != nil { | |
| 281 | 新增: return err | |
| 282 | 新增: } | |
| 283 | 新增: defer stopGate() | |
| 284 | 新增: if err := cfg.RecordRunningAt(r.InstanceDir()); err != nil { | |
| 285 | 新增: return err | |
| 286 | 新增: } | |
| 287 | 新增: defer os.Remove(filepath.Join(r.InstanceDir(), "cage-running.json")) | |
| 288 | 新增: record := networkRecord{ContainerID: inspection.State.ContainerID, PID: os.Getpid(), RunID: network.Gate.Status().RunID, SSHAddress: sshListener.Addr().String(), BrowserAddress: browserListener.Addr().String(), VNCAddress: vncListener.Addr().String(), Shared: true} | |
| 289 | 新增: if err := writePrivateJSON(filepath.Join(r.InstanceDir(), "network.json"), record); err != nil { | |
| 290 | 新增: return err | |
| 291 | 新增: } | |
| 292 | 新增: defer os.Remove(filepath.Join(r.InstanceDir(), "network.json")) | |
| 293 | 新增: select { | |
| 294 | 新增: case <-ctx.Done(): | |
| 295 | 新增: return ctx.Err() | |
| 296 | 新增: case err := <-networkDone: | |
| 297 | 新增: return err | |
| 298 | 新增: case err := <-shareDone: | |
| 299 | 新增: return fmt.Errorf("受限项目共享已断开: %w", err) | |
| 300 | 新增: case err := <-serviceDone: | |
| 301 | 新增: return err | |
| 302 | 新增: } | |
| 303 | 新增:} | |
| 304 | 新增: | |
| 305 | 新增:func (r *Runtime) connectGuestSSH(ctx context.Context, network *Network) (*ssh.Client, error) { | |
| 306 | 新增: configuration, err := r.guestSSHConfiguration() | |
| 307 | 新增: if err != nil { | |
| 308 | 新增: return nil, err | |
| 309 | 新增: } | |
| 310 | 新增: deadline := time.NewTimer(30 * time.Second) | |
| 311 | 新增: defer deadline.Stop() | |
| 312 | 新增: for { | |
| 313 | 新增: attemptCtx, cancel := context.WithTimeout(ctx, 2*time.Second) | |
| 314 | 新增: connection, err := network.stack.DialContextTCP(attemptCtx, GuestIP+":22") | |
| 315 | 新增: if err == nil { | |
| 316 | 新增: _ = connection.SetDeadline(time.Now().Add(2 * time.Second)) | |
| 317 | 新增: stop := context.AfterFunc(attemptCtx, func() { _ = connection.Close() }) | |
| 318 | 新增: transport, channels, requests, handshakeErr := ssh.NewClientConn(connection, "cage-container-"+r.identity+":22", configuration) | |
| 319 | 新增: stop() | |
| 320 | 新增: cancel() | |
| 321 | 新增: if handshakeErr == nil { | |
| 322 | 新增: _ = connection.SetDeadline(time.Time{}) | |
| 323 | 新增: return ssh.NewClient(transport, channels, requests), nil | |
| 324 | 新增: } | |
| 325 | 新增: _ = connection.Close() | |
| 326 | 新增: var mismatch *knownhosts.KeyError | |
| 327 | 新增: if errors.As(handshakeErr, &mismatch) { | |
| 328 | 新增: return nil, errors.New("容器 SSH 主机身份不匹配") | |
| 329 | 新增: } | |
| 330 | 新增: } else { | |
| 331 | 新增: cancel() | |
| 332 | 新增: } | |
| 333 | 新增: select { | |
| 334 | 新增: case <-ctx.Done(): | |
| 335 | 新增: return nil, ctx.Err() | |
| 336 | 新增: case <-deadline.C: | |
| 337 | 新增: return nil, errors.New("容器 SSH 未能就绪") | |
| 338 | 新增: case <-time.After(200 * time.Millisecond): | |
| 339 | 新增: } | |
| 340 | 新增: } | |
| 341 | 新增:} | |
| 342 | 新增: | |
| 343 | 新增:func (r *Runtime) guestSSHConfiguration() (*ssh.ClientConfig, error) { | |
| 344 | 新增: private, err := os.ReadFile(filepath.Join(r.InstanceDir(), "id_ed25519")) | |
| 345 | 新增: if err != nil { | |
| 346 | 新增: return nil, err | |
| 347 | 新增: } | |
| 348 | 新增: signer, err := ssh.ParsePrivateKey(private) | |
| 349 | 新增: if err != nil { | |
| 350 | 新增: return nil, err | |
| 351 | 新增: } | |
| 352 | 新增: check, err := knownhosts.New(filepath.Join(r.InstanceDir(), "known_hosts")) | |
| 353 | 新增: if err != nil { | |
| 354 | 新增: return nil, err | |
| 355 | 新增: } | |
| 356 | 新增: configuration := &ssh.ClientConfig{User: "cage", Auth: []ssh.AuthMethod{ssh.PublicKeys(signer)}, HostKeyCallback: check, HostKeyAlgorithms: []string{ssh.KeyAlgoED25519}} | |
| 357 | 新增: return configuration, nil | |
| 358 | 新增:} | |
| 359 | 新增: | |
| 360 | 新增:func serveGuestService(ctx context.Context, client *ssh.Client, listener net.Listener, target string) error { | |
| 361 | 新增: stop := context.AfterFunc(ctx, func() { _ = listener.Close() }) | |
| 362 | 新增: defer stop() | |
| 363 | 新增: for { | |
| 364 | 新增: local, err := listener.Accept() | |
| 365 | 新增: if err != nil { | |
| 366 | 新增: return err | |
| 367 | 新增: } | |
| 368 | 新增: go func() { | |
| 369 | 新增: defer local.Close() | |
| 370 | 新增: interrupt := context.AfterFunc(ctx, func() { _ = local.Close() }) | |
| 371 | 新增: defer interrupt() | |
| 372 | 新增: remote, err := client.Dial("tcp", target) | |
| 373 | 新增: if err != nil { | |
| 374 | 新增: return | |
| 375 | 新增: } | |
| 376 | 新增: defer remote.Close() | |
| 377 | 新增: interruptRemote := context.AfterFunc(ctx, func() { _ = remote.Close() }) | |
| 378 | 新增: defer interruptRemote() | |
| 379 | 新增: done := make(chan struct{}) | |
| 380 | 新增: go func() { _, _ = io.Copy(remote, local); _ = remote.Close(); _ = local.Close(); close(done) }() | |
| 381 | 新增: _, _ = io.Copy(local, remote) | |
| 382 | 新增: _ = local.Close() | |
| 383 | 新增: _ = remote.Close() | |
| 384 | 新增: <-done | |
| 385 | 新增: }() | |
| 386 | 新增: } | |
| 387 | 新增:} | |
| 388 | 新增: | |
| 389 | 新增:func (r *Runtime) shareEnvironment(ctx context.Context, client *ssh.Client) (<-chan error, func(), error) { | |
| 390 | 新增: ctx, cancel := context.WithTimeout(ctx, 15*time.Second) | |
| 391 | 新增: defer cancel() | |
| 392 | 新增: workspace := cage.EnvironmentDir(r.profile) | |
| 393 | 新增: if err := host.EnsurePrivateDir(workspace); err != nil { | |
| 394 | 新增: return nil, nil, err | |
| 395 | 新增: } | |
| 396 | 新增: quoted := shellescape.Quote(workspace) | |
| 397 | 新增: prepare, err := client.NewSession() | |
| 398 | 新增: if err != nil { | |
| 399 | 新增: return nil, nil, err | |
| 400 | 新增: } | |
| 401 | 新增: interrupt := context.AfterFunc(ctx, func() { _ = prepare.Close() }) | |
| 402 | 新增: err = prepare.Run("if mountpoint -q " + quoted + "; then fusermount3 -uz " + quoted + "; fi; sudo mkdir -p " + quoted + " && sudo chown cage:cage " + quoted) | |
| 403 | 新增: interrupt() | |
| 404 | 新增: prepare.Close() | |
| 405 | 新增: if err != nil { | |
| 406 | 新增: return nil, nil, errors.New("无法准备容器项目共享目录") | |
| 407 | 新增: } | |
| 408 | 新增: probe, err := os.CreateTemp(workspace, ".cage-mount-probe-*") | |
| 409 | 新增: if err != nil { | |
| 410 | 新增: return nil, nil, err | |
| 411 | 新增: } | |
| 412 | 新增: defer os.Remove(probe.Name()) | |
| 413 | 新增: var nonce [24]byte | |
| 414 | 新增: if _, err = rand.Read(nonce[:]); err != nil { | |
| 415 | 新增: probe.Close() | |
| 416 | 新增: return nil, nil, err | |
| 417 | 新增: } | |
| 418 | 新增: challenge := hex.EncodeToString(nonce[:]) | |
| 419 | 新增: _, err = probe.WriteString(challenge) | |
| 420 | 新增: probe.Close() | |
| 421 | 新增: if err != nil { | |
| 422 | 新增: return nil, nil, err | |
| 423 | 新增: } | |
| 424 | 新增: session, err := client.NewSession() | |
| 425 | 新增: if err != nil { | |
| 426 | 新增: return nil, nil, err | |
| 427 | 新增: } | |
| 428 | 新增: reader, err := session.StdoutPipe() | |
| 429 | 新增: if err != nil { | |
| 430 | 新增: session.Close() | |
| 431 | 新增: return nil, nil, err | |
| 432 | 新增: } | |
| 433 | 新增: writer, err := session.StdinPipe() | |
| 434 | 新增: if err != nil { | |
| 435 | 新增: session.Close() | |
| 436 | 新增: return nil, nil, err | |
| 437 | 新增: } | |
| 438 | 新增: session.Stderr = os.Stderr | |
| 439 | 新增: if err = session.Start("exec sshfs " + shellescape.Quote(":"+workspace) + " " + quoted + " -o slave,allow_other,cache=no,nodev,nosuid"); err != nil { | |
| 440 | 新增: session.Close() | |
| 441 | 新增: return nil, nil, err | |
| 442 | 新增: } | |
| 443 | 新增: stop := func() { _ = writer.Close(); _ = session.Close() } | |
| 444 | 新增: done := make(chan error, 1) | |
| 445 | 新增: go func() { | |
| 446 | 新增: err := reversesshfs.ServeConfined(&shareTransport{Reader: reader, Writer: writer, close: stop}, workspace, false, mounts.BaseNames) | |
| 447 | 新增: stop() | |
| 448 | 新增: _ = session.Wait() | |
| 449 | 新增: done <- err | |
| 450 | 新增: }() | |
| 451 | 新增: deadline := time.NewTimer(15 * time.Second) | |
| 452 | 新增: defer deadline.Stop() | |
| 453 | 新增: for { | |
| 454 | 新增: check, err := client.NewSession() | |
| 455 | 新增: if err != nil { | |
| 456 | 新增: stop() | |
| 457 | 新增: return nil, nil, err | |
| 458 | 新增: } | |
| 459 | 新增: var value bytes.Buffer | |
| 460 | 新增: check.Stdout = &value | |
| 461 | 新增: interrupt := context.AfterFunc(ctx, func() { _ = check.Close() }) | |
| 462 | 新增: err = check.Run("cat " + shellescape.Quote(probe.Name())) | |
| 463 | 新增: interrupt() | |
| 464 | 新增: check.Close() | |
| 465 | 新增: if err == nil && value.String() == challenge { | |
| 466 | 新增: return done, stop, nil | |
| 467 | 新增: } | |
| 468 | 新增: select { | |
| 469 | 新增: case <-ctx.Done(): | |
| 470 | 新增: stop() | |
| 471 | 新增: return nil, nil, ctx.Err() | |
| 472 | 新增: case <-deadline.C: | |
| 473 | 新增: stop() | |
| 474 | 新增: return nil, nil, errors.New("容器项目共享验证超时") | |
| 475 | 新增: case err := <-done: | |
| 476 | 新增: stop() | |
| 477 | 新增: return nil, nil, fmt.Errorf("容器项目共享失败: %w", err) | |
| 478 | 新增: case <-time.After(150 * time.Millisecond): | |
| 479 | 新增: } | |
| 480 | 新增: } | |
| 481 | 新增:} | |
| 482 | 新增: | |
| 483 | 新增:func (r *Runtime) GuestCommand(ctx context.Context, args ...string) *exec.Cmd { | |
| 484 | 新增: base := []string{"-F", r.SSHConfig(), "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "ForwardAgent=no", "-o", "ClearAllForwardings=yes", "-o", "ConnectTimeout=3"} | |
| 485 | 新增: return exec.CommandContext(ctx, "ssh", append(base, args...)...) | |
| 486 | 新增:} | |
| 487 | 新增: | |
| 488 | 新增:type shareTransport struct { | |
| 489 | 新增: io.Reader | |
| 490 | 新增: io.Writer | |
| 491 | 新增: close func() | |
| 492 | 新增:} | |
| 493 | 新增: | |
| 494 | 新增:func (s *shareTransport) Close() error { s.close(); return nil } | |
| @@ -2,13 +2,14 @@ package host | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| 5 | 新增: "fmt" | |
| 6 | 新增: "os" | |
| 5 | 7 | "path/filepath" |
| 6 | 8 | "strings" |
| 7 | 9 | "testing" |
| 8 | 10 | ) |
| 9 | 11 | |
| 10 | 删除:// A VM folder not made yet: the free space of the home folder, where it | |
| 11 | 删除:// will be. | |
| 12 | 新增:// A VM folder not made yet uses its nearest existing parent. | |
| 12 | 13 | func TestWarnDiskSpace(t *testing.T) { |
| 13 | 14 | t.Setenv("HOME", t.TempDir()) |
| 14 | 15 | missing := filepath.Join(t.TempDir(), "not", "yet") |
| @@ -24,3 +25,34 @@ func TestWarnDiskSpace(t *testing.T) { | ||
| 24 | 25 | t.Errorf("warned: %q", b.String()) |
| 25 | 26 | } |
| 26 | 27 | } |
| 28 | 新增: | |
| 29 | 新增:// Native QA passes a profile-side junction to a second volume with different | |
| 30 | 新增:// free space. The missing child models Lima's first launch before setup. | |
| 31 | 新增:func TestDiskSpaceBeforeVMDirectoryExists(t *testing.T) { | |
| 32 | 新增: alias, target := os.Getenv("CAGE_TEST_DISK_SPACE_ALIAS"), os.Getenv("CAGE_TEST_DISK_SPACE_VOLUME") | |
| 33 | 新增: if alias == "" || target == "" { | |
| 34 | 新增: t.Skip("requires a test link to a second volume") | |
| 35 | 新增: } | |
| 36 | 新增: missing := filepath.Join(alias, "cage-disk-qa-absent", "lima") | |
| 37 | 新增: if _, err := os.Stat(missing); !os.IsNotExist(err) { | |
| 38 | 新增: t.Fatal("expected missing QA child", err) | |
| 39 | 新增: } | |
| 40 | 新增: want, ok := FreeGiB(target) | |
| 41 | 新增: if !ok { | |
| 42 | 新增: t.Fatal("cannot read physical volume") | |
| 43 | 新增: } | |
| 44 | 新增: got, ok := FreeGiB(missing) | |
| 45 | 新增: if !ok || got != want { | |
| 46 | 新增: t.Fatalf("logical free = %d, expected physical free = %d (ok=%v)", got, want, ok) | |
| 47 | 新增: } | |
| 48 | 新增: var warning bytes.Buffer | |
| 49 | 新增: WarnDiskSpace(missing, want, &warning) | |
| 50 | 新增: if warning.Len() != 0 { | |
| 51 | 新增: t.Fatal("spurious low space warning", warning.String()) | |
| 52 | 新增: } | |
| 53 | 新增: WarnDiskSpace(missing, want+1, &warning) | |
| 54 | 新增: if !strings.Contains(warning.String(), fmt.Sprintf("~%d GiB free", want)) { | |
| 55 | 新增: t.Fatalf("wrong preflight warning %q", warning.String()) | |
| 56 | 新增: } | |
| 57 | 新增: t.Logf("first-run space check: %d GiB available on target", got) | |
| 58 | 新增:} | |
| @@ -4,8 +4,8 @@ package host | ||
| 4 | 4 | |
| 5 | 5 | import "golang.org/x/sys/unix" |
| 6 | 6 | |
| 7 | 删除:// FreeGiB is the space free for an unprivileged user on dir's file system. | |
| 8 | 删除:func FreeGiB(dir string) (int, bool) { | |
| 7 | 新增:// freeGiB is the space free for an unprivileged user on dir's file system. | |
| 8 | 新增:func freeGiB(dir string) (int, bool) { | |
| 9 | 9 | var st unix.Statfs_t |
| 10 | 10 | if err := unix.Statfs(dir+"/.", &st); err != nil { |
| 11 | 11 | return 0, false |
| @@ -2,8 +2,8 @@ package host | ||
| 2 | 2 | |
| 3 | 3 | import "golang.org/x/sys/windows" |
| 4 | 4 | |
| 5 | 删除:// FreeGiB is the space free for this user on dir's volume. | |
| 6 | 删除:func FreeGiB(dir string) (int, bool) { | |
| 5 | 新增:// freeGiB is the space free for this user on dir's volume. | |
| 6 | 新增:func freeGiB(dir string) (int, bool) { | |
| 7 | 7 | p, err := windows.UTF16PtrFromString(dir) |
| 8 | 8 | if err != nil { |
| 9 | 9 | return 0, false |
| @@ -5,11 +5,13 @@ import ( | ||
| 5 | 5 | "fmt" |
| 6 | 6 | "io" |
| 7 | 7 | "os" |
| 8 | 新增: "path/filepath" | |
| 8 | 9 | "regexp" |
| 9 | 10 | "runtime" |
| 10 | 11 | "strconv" |
| 11 | 12 | |
| 12 | 13 | "github.com/pbnjay/memory" |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 13 | 15 | ) |
| 14 | 16 | |
| 15 | 17 | // A VM handed more CPU or RAM than the host can spare makes the host |
| @@ -77,6 +79,28 @@ func Cap(kind string, val int, warn io.Writer) int { | ||
| 77 | 79 | return val |
| 78 | 80 | } |
| 79 | 81 | |
| 82 | 新增:// FreeGiB reports available space on the physical volume where dir will | |
| 83 | 新增:// be created. A first-run Lima home can be a missing child of a junction. | |
| 84 | 新增:func FreeGiB(dir string) (int, bool) { | |
| 85 | 新增: for { | |
| 86 | 新增: real, err := paths.Resolve(dir) | |
| 87 | 新增: if err == nil { | |
| 88 | 新增: return freeGiB(real) | |
| 89 | 新增: } | |
| 90 | 新增: if !os.IsNotExist(err) { | |
| 91 | 新增: return 0, false | |
| 92 | 新增: } | |
| 93 | 新增: if _, err = os.Lstat(dir); !os.IsNotExist(err) { | |
| 94 | 新增: return 0, false | |
| 95 | 新增: } | |
| 96 | 新增: parent := filepath.Dir(dir) | |
| 97 | 新增: if parent == dir { | |
| 98 | 新增: return 0, false | |
| 99 | 新增: } | |
| 100 | 新增: dir = parent | |
| 101 | 新增: } | |
| 102 | 新增:} | |
| 103 | 新增: | |
| 80 | 104 | // WarnDiskSpace warns when the file system of dir has less free space than |
| 81 | 105 | // a disk of want GiB. Disks are sparse, allocated as they fill: a warning, |
| 82 | 106 | // not an error. |
| @@ -84,11 +108,6 @@ func WarnDiskSpace(dir string, want int, warn io.Writer) { | ||
| 84 | 108 | if want == 0 { |
| 85 | 109 | return |
| 86 | 110 | } |
| 87 | 删除: if _, err := os.Stat(dir); err != nil { | |
| 88 | 删除: if h, err := os.UserHomeDir(); err == nil { | |
| 89 | 删除: dir = h | |
| 90 | 删除: } | |
| 91 | 删除: } | |
| 92 | 111 | free, ok := FreeGiB(dir) |
| 93 | 112 | if ok && free < want { |
| 94 | 113 | fmt.Fprintf(warn, "Warning: ~%d GiB free for a %d GiB VM disk (sparse: allocated as used).\n", free, want) |
| @@ -33,11 +33,25 @@ func protectPrivate(path string, dir bool) error { | ||
| 33 | 33 | if err != nil { |
| 34 | 34 | return err |
| 35 | 35 | } |
| 36 | 删除: // Elevated Windows processes may create files owned by Administrators. | |
| 37 | 删除: // Preserve the same per-user contract for elevated and normal launches by | |
| 38 | 删除: // explicitly assigning the current user's SID as well as the private ACL. | |
| 39 | 删除: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, | |
| 40 | 删除: windows.OWNER_SECURITY_INFORMATION|windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, sid, nil, acl, nil) | |
| 36 | 新增: // An owner may replace its DACL even when the parent granted only Modify. | |
| 37 | 新增: // Requesting WRITE_OWNER on that path would deny a normal user's install. | |
| 38 | 新增: current, err := windows.GetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return err | |
| 41 | 新增: } | |
| 42 | 新增: owner, _, err := current.Owner() | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return err | |
| 45 | 新增: } | |
| 46 | 新增: information := windows.SECURITY_INFORMATION(windows.DACL_SECURITY_INFORMATION | windows.PROTECTED_DACL_SECURITY_INFORMATION) | |
| 47 | 新增: var newOwner *windows.SID | |
| 48 | 新增: if owner == nil || !windows.EqualSid(owner, sid) { | |
| 49 | 新增: // An elevated process can create objects owned by Administrators. | |
| 50 | 新增: // Transfer them to the user so both normal and elevated launches work. | |
| 51 | 新增: information |= windows.OWNER_SECURITY_INFORMATION | |
| 52 | 新增: newOwner = sid | |
| 53 | 新增: } | |
| 54 | 新增: return windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, information, newOwner, nil, acl, nil) | |
| 41 | 55 | } |
| 42 | 56 | |
| 43 | 57 | func checkPrivate(path string, _ os.FileInfo) error { |
| @@ -38,3 +38,73 @@ func TestPrivateFileRejectsEveryoneReadACL(t *testing.T) { | ||
| 38 | 38 | t.Fatalf("restricted DACL rejected: %v", err) |
| 39 | 39 | } |
| 40 | 40 | } |
| 41 | 新增: | |
| 42 | 新增:// Ownership grants WRITE_DAC but does not automatically grant WRITE_OWNER. | |
| 43 | 新增:// Explicitly withholding WRITE_OWNER makes this regression deterministic even | |
| 44 | 新增:// when the test runner's temporary directory normally grants full control. | |
| 45 | 新增:func TestProtectPrivateDoesNotRequireChangingAnExistingOwner(t *testing.T) { | |
| 46 | 新增: dir := filepath.Join(t.TempDir(), "selected") | |
| 47 | 新增: if err := os.Mkdir(dir, 0700); err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: sid, err := privateSID() | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: current, err := windows.GetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: owner, _, err := current.Owner() | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: t.Fatal(err) | |
| 61 | 新增: } | |
| 62 | 新增: if !windows.EqualSid(owner, sid) { | |
| 63 | 新增: if err := windows.SetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION, sid, nil, nil, nil); err != nil { | |
| 64 | 新增: t.Fatal(err) | |
| 65 | 新增: } | |
| 66 | 新增: } | |
| 67 | 新增: sd, err := windows.SecurityDescriptorFromString("D:P(D;;WO;;;" + sid.String() + ")(A;;FA;;;" + sid.String() + ")(A;;FA;;;SY)") | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: t.Fatal(err) | |
| 70 | 新增: } | |
| 71 | 新增: acl, _, err := sd.DACL() | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: t.Fatal(err) | |
| 74 | 新增: } | |
| 75 | 新增: if err := windows.SetNamedSecurityInfo(dir, windows.SE_FILE_OBJECT, windows.DACL_SECURITY_INFORMATION|windows.PROTECTED_DACL_SECURITY_INFORMATION, nil, nil, acl, nil); err != nil { | |
| 76 | 新增: t.Fatal(err) | |
| 77 | 新增: } | |
| 78 | 新增: if err := EnsurePrivateDir(dir); err != nil { | |
| 79 | 新增: t.Fatalf("owner cannot secure directory: %v", err) | |
| 80 | 新增: } | |
| 81 | 新增: if err := checkPrivate(dir, nil); err != nil { | |
| 82 | 新增: t.Fatal(err) | |
| 83 | 新增: } | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:func TestProtectPrivateAdoptsAdministratorOwnedFile(t *testing.T) { | |
| 87 | 新增: if !windows.GetCurrentProcessToken().IsElevated() { | |
| 88 | 新增: t.Skip("requires an elevated Windows token") | |
| 89 | 新增: } | |
| 90 | 新增: path := filepath.Join(t.TempDir(), "credential") | |
| 91 | 新增: if err := os.WriteFile(path, []byte("test"), 0600); err != nil { | |
| 92 | 新增: t.Fatal(err) | |
| 93 | 新增: } | |
| 94 | 新增: admin, err := windows.CreateWellKnownSid(windows.WinBuiltinAdministratorsSid) | |
| 95 | 新增: if err != nil { | |
| 96 | 新增: t.Fatal(err) | |
| 97 | 新增: } | |
| 98 | 新增: if err := windows.SetNamedSecurityInfo(path, windows.SE_FILE_OBJECT, windows.OWNER_SECURITY_INFORMATION, admin, nil, nil, nil); err != nil { | |
| 99 | 新增: t.Fatal(err) | |
| 100 | 新增: } | |
| 101 | 新增: if err := CheckPrivateFile(path); err == nil { | |
| 102 | 新增: t.Fatal("group-owned file treated as private before repair") | |
| 103 | 新增: } | |
| 104 | 新增: if err := ProtectFile(path); err != nil { | |
| 105 | 新增: t.Fatal(err) | |
| 106 | 新增: } | |
| 107 | 新增: if err := CheckPrivateFile(path); err != nil { | |
| 108 | 新增: t.Fatal(err) | |
| 109 | 新增: } | |
| 110 | 新增:} | |
| @@ -0,0 +1,35 @@ | ||
| 1 | 新增:package managedproxy | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "runtime" | |
| 10 | 新增: "strconv" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:// ConfirmStopped performs no cleanup. Linux and Windows remove their private | |
| 14 | 新增:// process record only after stopping the identified process. launchd retains | |
| 15 | 新增:// its plist even after bootout, so an existing plist needs a service lookup. | |
| 16 | 新增:func ConfirmStopped(ctx context.Context, profile string) error { | |
| 17 | 新增: path := filepath.Join(Dir(profile), "managed-process.json") | |
| 18 | 新增: if runtime.GOOS == "darwin" { | |
| 19 | 新增: path = servicePath(profile) | |
| 20 | 新增: } | |
| 21 | 新增: if _, err := os.Lstat(path); os.IsNotExist(err) { | |
| 22 | 新增: return nil | |
| 23 | 新增: } else if err != nil { | |
| 24 | 新增: return err | |
| 25 | 新增: } | |
| 26 | 新增: if runtime.GOOS == "darwin" { | |
| 27 | 新增: name := "gui/" + strconv.Itoa(os.Getuid()) + "/" + label(profile) | |
| 28 | 新增: err := exec.CommandContext(ctx, "/bin/launchctl", "print", name).Run() | |
| 29 | 新增: var exit *exec.ExitError | |
| 30 | 新增: if errors.As(err, &exit) && exit.ExitCode() == 113 { | |
| 31 | 新增: return nil | |
| 32 | 新增: } // service not found | |
| 33 | 新增: } | |
| 34 | 新增: return errors.New("无法确认此配置的代理进程已经退出") | |
| 35 | 新增:} | |
| @@ -8,8 +8,8 @@ import ( | ||
| 8 | 8 | "strconv" |
| 9 | 9 | "strings" |
| 10 | 10 | |
| 11 | 新增: vm "github.com/sylvinus/agent-vm/internal/mounts/spec" | |
| 11 | 12 | "github.com/sylvinus/agent-vm/internal/paths" |
| 12 | 删除: "github.com/sylvinus/agent-vm/internal/vm" | |
| 13 | 13 | ) |
| 14 | 14 | |
| 15 | 15 | // FileMount is a single file of ~/.agent-vm/volumes: hardlinked into a |
| @@ -124,9 +124,11 @@ func Stage(src, dst string, warn io.Writer) bool { | ||
| 124 | 124 | // The file itself: link(2) links a symlink as one (stow's dotfiles), which |
| 125 | 125 | // would leave dst pointing out of the folder the VM is given. The checks |
| 126 | 126 | // made on src were on that file too (UnsafeLocation). |
| 127 | 删除: if p, err := filepath.EvalSymlinks(src); err == nil { | |
| 128 | 删除: src = p | |
| 127 | 新增: physical, err := paths.Resolve(src) | |
| 128 | 新增: if err != nil { | |
| 129 | 新增: return false | |
| 129 | 130 | } |
| 131 | 新增: src = physical | |
| 130 | 132 | if os.Link(src, dst) == nil { |
| 131 | 133 | return true |
| 132 | 134 | } |
| @@ -0,0 +1,16 @@ | ||
| 1 | 新增:// Package spec defines shared-folder data without importing a VM runtime. | |
| 2 | 新增:// Desktop connection clients validate project paths without bundling Lima. | |
| 3 | 新增:package spec | |
| 4 | 新增: | |
| 5 | 新增:type Mount struct { | |
| 6 | 新增: Location string `json:"location"` | |
| 7 | 新增: MountPoint string `json:"mountPoint,omitempty"` | |
| 8 | 新增: Writable bool `json:"writable"` | |
| 9 | 新增: SSHFS *SSHFS `json:"sshfs,omitempty"` | |
| 10 | 新增:} | |
| 11 | 新增: | |
| 12 | 新增:type SSHFS struct { | |
| 13 | 新增: SFTPDriver string `json:"sftpDriver,omitempty"` | |
| 14 | 新增: Cache *bool `json:"cache,omitempty"` | |
| 15 | 新增: ReadonlyNames []string `json:"readonlyNames,omitempty"` | |
| 16 | 新增:} | |
| @@ -8,7 +8,6 @@ package paths | ||
| 8 | 8 | |
| 9 | 9 | import ( |
| 10 | 10 | "os" |
| 11 | 删除: "path/filepath" | |
| 12 | 11 | "runtime" |
| 13 | 12 | "strings" |
| 14 | 13 | "unicode/utf8" |
| @@ -36,10 +35,10 @@ func Home() string { | ||
| 36 | 35 | return Host(h) |
| 37 | 36 | } |
| 38 | 37 | |
| 39 | 删除:// Real is p with its links resolved (filepath.EvalSymlinks), spelled as | |
| 38 | 新增:// Real is p with its links resolved (including directory junctions), spelled as | |
| 40 | 39 | // Host does. |
| 41 | 40 | func Real(p string) (string, error) { |
| 42 | 删除: r, err := filepath.EvalSymlinks(p) | |
| 41 | 新增: r, err := Resolve(p) | |
| 43 | 42 | return Host(r), err |
| 44 | 43 | } |
| 45 | 44 | |
| @@ -7,8 +7,8 @@ import ( | ||
| 7 | 7 | "github.com/sylvinus/agent-vm/internal/bashref" |
| 8 | 8 | ) |
| 9 | 9 | |
| 10 | 删除:// windows makes the host a Windows one for the test. | |
| 11 | 删除:func windows(t *testing.T, on bool) { | |
| 10 | 新增:// simulateWindows makes the host a Windows one for the test. | |
| 11 | 新增:func simulateWindows(t *testing.T, on bool) { | |
| 12 | 12 | old := Windows |
| 13 | 13 | Windows = func() bool { return on } |
| 14 | 14 | t.Cleanup(func() { Windows = old }) |
| @@ -16,7 +16,7 @@ func windows(t *testing.T, on bool) { | ||
| 16 | 16 | |
| 17 | 17 | // On Windows, a drive is the root: ".." stops there, and C:/x is absolute. |
| 18 | 18 | func TestWindowsPaths(t *testing.T) { |
| 19 | 删除: windows(t, true) | |
| 19 | 新增: simulateWindows(t, true) | |
| 20 | 20 | for _, c := range [][3]string{ |
| 21 | 21 | {"C:/Users/me", "proj", "C:/Users/me/proj"}, |
| 22 | 22 | {"C:/Users/me", "../../../x", "C:/x"}, |
| @@ -51,7 +51,7 @@ func TestWindowsPaths(t *testing.T) { | ||
| 51 | 51 | t.Errorf("In, case ignored: %q %v", rel, ok) |
| 52 | 52 | } |
| 53 | 53 | // Elsewhere, none of it. |
| 54 | 删除: windows(t, false) | |
| 54 | 新增: simulateWindows(t, false) | |
| 55 | 55 | if Guest("C:/x") != "C:/x" || FromGitBash("/c/x") != "/c/x" || IsAbs("C:/x") || Host(`a\b`) != `a\b` || Join("C:", "x") != "C:/x" { |
| 56 | 56 | t.Error("not Windows") |
| 57 | 57 | } |
| @@ -0,0 +1,8 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package paths | |
| 4 | 新增: | |
| 5 | 新增:import "path/filepath" | |
| 6 | 新增: | |
| 7 | 新增:// Resolve returns the physical path using the platform's native separators. | |
| 8 | 新增:func Resolve(path string) (string, error) { return filepath.EvalSymlinks(path) } | |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:package paths | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "strings" | |
| 7 | 新增: | |
| 8 | 新增: "golang.org/x/sys/windows" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// Resolve follows directory junctions as well as symbolic links. EvalSymlinks | |
| 12 | 新增:// may leave an NTFS mount-point reparse record in its original DOS spelling. | |
| 13 | 新增:// Ask the kernel which object the open handle actually refers to instead. | |
| 14 | 新增:func Resolve(path string) (string, error) { | |
| 15 | 新增: abs, err := filepath.Abs(path) | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: return "", err | |
| 18 | 新增: } | |
| 19 | 新增: name := abs | |
| 20 | 新增: switch { | |
| 21 | 新增: case strings.HasPrefix(name, `\\?\`), strings.HasPrefix(name, `\\.\`): | |
| 22 | 新增: case strings.HasPrefix(name, `\\`): | |
| 23 | 新增: name = `\\?\UNC\` + name[2:] | |
| 24 | 新增: default: | |
| 25 | 新增: name = `\\?\` + name | |
| 26 | 新增: } | |
| 27 | 新增: ptr, err := windows.UTF16PtrFromString(name) | |
| 28 | 新增: if err != nil { | |
| 29 | 新增: return "", err | |
| 30 | 新增: } | |
| 31 | 新增: h, err := windows.CreateFile(ptr, windows.FILE_READ_ATTRIBUTES, windows.FILE_SHARE_READ|windows.FILE_SHARE_WRITE|windows.FILE_SHARE_DELETE, nil, windows.OPEN_EXISTING, windows.FILE_FLAG_BACKUP_SEMANTICS, 0) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return "", &os.PathError{Op: "resolve", Path: path, Err: err} | |
| 34 | 新增: } | |
| 35 | 新增: defer windows.CloseHandle(h) | |
| 36 | 新增: buf := make([]uint16, 512) | |
| 37 | 新增: for { | |
| 38 | 新增: n, err := windows.GetFinalPathNameByHandle(h, &buf[0], uint32(len(buf)), 0) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return "", &os.PathError{Op: "resolve", Path: path, Err: err} | |
| 41 | 新增: } | |
| 42 | 新增: if n >= uint32(len(buf)) { | |
| 43 | 新增: buf = make([]uint16, n+1) | |
| 44 | 新增: continue | |
| 45 | 新增: } | |
| 46 | 新增: result := windows.UTF16ToString(buf[:n]) | |
| 47 | 新增: if strings.HasPrefix(result, `\\?\UNC\`) { | |
| 48 | 新增: return `\\` + result[8:], nil | |
| 49 | 新增: } | |
| 50 | 新增: if strings.HasPrefix(result, `\\?\`) && len(result) >= 7 && result[5] == ':' { | |
| 51 | 新增: return result[4:], nil | |
| 52 | 新增: } | |
| 53 | 新增: return result, nil | |
| 54 | 新增: } | |
| 55 | 新增:} | |
| @@ -0,0 +1,18 @@ | ||
| 1 | 新增://go:build !windows | |
| 2 | 新增: | |
| 3 | 新增:package remotehost | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func dialAgent(ctx context.Context) (net.Conn, error) { | |
| 13 | 新增: path := os.Getenv("SSH_AUTH_SOCK") | |
| 14 | 新增: if path == "" { | |
| 15 | 新增: return nil, errors.New("SSH agent unavailable") | |
| 16 | 新增: } | |
| 17 | 新增: return (&net.Dialer{}).DialContext(ctx, "unix", path) | |
| 18 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增://go:build windows | |
| 2 | 新增: | |
| 3 | 新增:package remotehost | |
| 4 | 新增: | |
| 5 | 新增:import ( | |
| 6 | 新增: "context" | |
| 7 | 新增: "github.com/Microsoft/go-winio" | |
| 8 | 新增: "net" | |
| 9 | 新增: "os" | |
| 10 | 新增: "strings" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func dialAgent(ctx context.Context) (net.Conn, error) { | |
| 14 | 新增: path := os.Getenv("SSH_AUTH_SOCK") | |
| 15 | 新增: if path == "" { | |
| 16 | 新增: path = `\\.\pipe\openssh-ssh-agent` | |
| 17 | 新增: } | |
| 18 | 新增: if strings.HasPrefix(path, `\\.\pipe\`) { | |
| 19 | 新增: return winio.DialPipeContext(ctx, path) | |
| 20 | 新增: } | |
| 21 | 新增: return (&net.Dialer{}).DialContext(ctx, "unix", path) | |
| 22 | 新增:} | |
| @@ -0,0 +1,363 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "errors" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net" | |
| 10 | 新增: "net/http" | |
| 11 | 新增: "net/http/cookiejar" | |
| 12 | 新增: "net/url" | |
| 13 | 新增: "os" | |
| 14 | 新增: "strconv" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "sync" | |
| 17 | 新增: "time" | |
| 18 | 新增: | |
| 19 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 20 | 新增: "golang.org/x/crypto/ssh" | |
| 21 | 新增: "golang.org/x/crypto/ssh/agent" | |
| 22 | 新增:) | |
| 23 | 新增: | |
| 24 | 新增:func shellQuote(value string) string { return "'" + strings.ReplaceAll(value, "'", "'\"'\"'") + "'" } | |
| 25 | 新增: | |
| 26 | 新增:// ServerEntryCommand accepts two path fields, never an arbitrary shell command. | |
| 27 | 新增:func ServerEntryCommand(p HostProfile) (string, error) { | |
| 28 | 新增: p, err := normalizeProfile(p) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: return "", err | |
| 31 | 新增: } | |
| 32 | 新增: command := shellQuote(p.Executable) + " server-entry --json" | |
| 33 | 新增: if p.ConfigPath != "" { | |
| 34 | 新增: command = "env CLAUDE_CAGE_CONFIG=" + shellQuote(p.ConfigPath) + " " + command | |
| 35 | 新增: } | |
| 36 | 新增: return "exec " + command, nil | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:// ValidateManifest limits every forwarded connection to a declared loopback | |
| 40 | 新增:// service. Instance identity persists independently of network addresses. | |
| 41 | 新增:func ValidateManifest(m ServerManifest) error { | |
| 42 | 新增: if m.APIProtocol != APIProtocol { | |
| 43 | 新增: return failure("protocol_incompatible", "云端 Cage 协议与客户端不兼容,请更新到兼容版本") | |
| 44 | 新增: } | |
| 45 | 新增: if !instancePattern.MatchString(m.InstanceID) || m.Platform != "linux" || (m.Runtime != "container" && m.Runtime != "lima") || len(m.Version) > 128 || hasControl(m.Version) { | |
| 46 | 新增: return failure("manifest_invalid", "云端 Cage 身份响应无效") | |
| 47 | 新增: } | |
| 48 | 新增: u, err := url.Parse(m.Origin) | |
| 49 | 新增: if err != nil || u.Scheme != "http" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || (u.Hostname() != "localhost" && u.Hostname() != "127.0.0.1" && u.Hostname() != "::1") { | |
| 50 | 新增: return failure("origin_refused", "云端服务必须使用明确的本机回环地址") | |
| 51 | 新增: } | |
| 52 | 新增: port, err := strconv.Atoi(u.Port()) | |
| 53 | 新增: if err != nil || port < 1 || port > 65535 { | |
| 54 | 新增: return failure("origin_refused", "云端服务端口无效") | |
| 55 | 新增: } | |
| 56 | 新增: if len(m.Ticket) < 32 || len(m.Ticket) > 512 || hasControl(m.Ticket) || len(m.Capabilities) > 64 { | |
| 57 | 新增: return failure("manifest_invalid", "云端 Cage 连接票据无效") | |
| 58 | 新增: } | |
| 59 | 新增: for key := range m.Capabilities { | |
| 60 | 新增: if key == "" || len(key) > 64 || hasControl(key) { | |
| 61 | 新增: return failure("manifest_invalid", "云端能力声明无效") | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: return nil | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func authentication(ctx context.Context, p HostProfile, secrets ConnectSecrets) (ssh.AuthMethod, func(), error) { | |
| 68 | 新增: if p.Auth.Kind == "agent" { | |
| 69 | 新增: conn, err := dialAgent(ctx) | |
| 70 | 新增: if err != nil { | |
| 71 | 新增: return nil, nil, failure("agent_unavailable", "无法连接本机 SSH agent,请启动 agent 或选择密钥文件") | |
| 72 | 新增: } | |
| 73 | 新增: _ = conn.SetDeadline(time.Now().Add(15 * time.Second)) | |
| 74 | 新增: stop := context.AfterFunc(ctx, func() { _ = conn.Close() }) | |
| 75 | 新增: signers, err := agent.NewClient(conn).Signers() | |
| 76 | 新增: if err != nil || len(signers) == 0 { | |
| 77 | 新增: stop() | |
| 78 | 新增: conn.Close() | |
| 79 | 新增: return nil, nil, failure("agent_unavailable", "SSH agent 中没有可用密钥") | |
| 80 | 新增: } | |
| 81 | 新增: return ssh.PublicKeys(signers...), func() { stop(); conn.Close() }, nil | |
| 82 | 新增: } | |
| 83 | 新增: if err := host.CheckPrivateFile(p.Auth.IdentityFile); err != nil { | |
| 84 | 新增: return nil, nil, failure("identity_permissions", "SSH 密钥不存在或文件权限不安全") | |
| 85 | 新增: } | |
| 86 | 新增: f, err := os.Open(p.Auth.IdentityFile) | |
| 87 | 新增: if err != nil { | |
| 88 | 新增: return nil, nil, failure("identity_read", "无法读取 SSH 密钥文件") | |
| 89 | 新增: } | |
| 90 | 新增: key, err := io.ReadAll(io.LimitReader(f, (1<<20)+1)) | |
| 91 | 新增: f.Close() | |
| 92 | 新增: defer clear(key) | |
| 93 | 新增: if err != nil || len(key) > 1<<20 { | |
| 94 | 新增: return nil, nil, failure("identity_read", "SSH 密钥文件无效或过大") | |
| 95 | 新增: } | |
| 96 | 新增: var signer ssh.Signer | |
| 97 | 新增: if len(secrets.Passphrase) > 0 { | |
| 98 | 新增: signer, err = ssh.ParsePrivateKeyWithPassphrase(key, secrets.Passphrase) | |
| 99 | 新增: } else { | |
| 100 | 新增: signer, err = ssh.ParsePrivateKey(key) | |
| 101 | 新增: } | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: var missing *ssh.PassphraseMissingError | |
| 104 | 新增: if errors.As(err, &missing) { | |
| 105 | 新增: return nil, nil, failure("passphrase_required", "此 SSH 密钥需要口令") | |
| 106 | 新增: } | |
| 107 | 新增: return nil, nil, failure("identity_invalid", "SSH 密钥或口令无效") | |
| 108 | 新增: } | |
| 109 | 新增: return ssh.PublicKeys(signer), func() {}, nil | |
| 110 | 新增:} | |
| 111 | 新增: | |
| 112 | 新增:type limitedOutput struct { | |
| 113 | 新增: bytes.Buffer | |
| 114 | 新增: limit int | |
| 115 | 新增:} | |
| 116 | 新增: | |
| 117 | 新增:func (w *limitedOutput) Write(p []byte) (int, error) { | |
| 118 | 新增: if w.Len()+len(p) > w.limit { | |
| 119 | 新增: return 0, errors.New("SSH response exceeds limit") | |
| 120 | 新增: } | |
| 121 | 新增: return w.Buffer.Write(p) | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:func connect(lifetime context.Context, p HostProfile, secrets ConnectSecrets, phase func(string)) (*Session, error) { | |
| 125 | 新增: p, err := normalizeProfile(p) | |
| 126 | 新增: if err != nil { | |
| 127 | 新增: return nil, err | |
| 128 | 新增: } | |
| 129 | 新增: bootstrap, cancelBootstrap := context.WithTimeout(lifetime, 45*time.Second) | |
| 130 | 新增: defer cancelBootstrap() | |
| 131 | 新增: phase("ssh_auth") | |
| 132 | 新增: auth, cleanup, err := authentication(bootstrap, p, secrets) | |
| 133 | 新增: if err != nil { | |
| 134 | 新增: return nil, err | |
| 135 | 新增: } | |
| 136 | 新增: defer cleanup() | |
| 137 | 新增: phase("ssh_connect") | |
| 138 | 新增: address := net.JoinHostPort(p.Host, strconv.Itoa(p.Port)) | |
| 139 | 新增: raw, err := (&net.Dialer{Timeout: 15 * time.Second}).DialContext(bootstrap, "tcp", address) | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return nil, failure("ssh_connect_failed", "无法连接 SSH 主机,请检查地址、端口和网络") | |
| 142 | 新增: } | |
| 143 | 新增: complete := false | |
| 144 | 新增: defer func() { | |
| 145 | 新增: if !complete { | |
| 146 | 新增: raw.Close() | |
| 147 | 新增: } | |
| 148 | 新增: }() | |
| 149 | 新增: _ = raw.SetDeadline(time.Now().Add(20 * time.Second)) | |
| 150 | 新增: stopBootstrap := context.AfterFunc(bootstrap, func() { raw.Close() }) | |
| 151 | 新增: defer stopBootstrap() | |
| 152 | 新增: var keyError *Error | |
| 153 | 新增: config := &ssh.ClientConfig{User: p.User, Auth: []ssh.AuthMethod{auth}, HostKeyCallback: func(_ string, _ net.Addr, key ssh.PublicKey) error { | |
| 154 | 新增: observed := &HostKey{Algorithm: key.Type(), Fingerprint: ssh.FingerprintSHA256(key)} | |
| 155 | 新增: if p.HostKey == nil { | |
| 156 | 新增: keyError = &Error{Code: "host_key_unknown", Message: "请核对并确认 SSH 主机密钥指纹后重新连接", HostKey: observed} | |
| 157 | 新增: return keyError | |
| 158 | 新增: } | |
| 159 | 新增: if p.HostKey.Algorithm != observed.Algorithm || p.HostKey.Fingerprint != observed.Fingerprint { | |
| 160 | 新增: keyError = &Error{Code: "host_key_changed", Message: "SSH 主机密钥已变化,请核对主机身份后更新指纹", HostKey: observed} | |
| 161 | 新增: return keyError | |
| 162 | 新增: } | |
| 163 | 新增: return nil | |
| 164 | 新增: }} | |
| 165 | 新增: if p.HostKey != nil { | |
| 166 | 新增: config.HostKeyAlgorithms = []string{p.HostKey.Algorithm} | |
| 167 | 新增: if p.HostKey.Algorithm == ssh.KeyAlgoRSA { | |
| 168 | 新增: // The public-key type is ssh-rsa, while modern RSA signatures use | |
| 169 | 新增: // the SHA-2 negotiation names. Do not enable obsolete SHA-1 signatures. | |
| 170 | 新增: config.HostKeyAlgorithms = []string{ssh.KeyAlgoRSASHA512, ssh.KeyAlgoRSASHA256} | |
| 171 | 新增: } | |
| 172 | 新增: } | |
| 173 | 新增: sshConn, channels, requests, err := ssh.NewClientConn(raw, address, config) | |
| 174 | 新增: if err != nil { | |
| 175 | 新增: if keyError != nil { | |
| 176 | 新增: return nil, keyError | |
| 177 | 新增: } | |
| 178 | 新增: return nil, failure("ssh_auth_failed", "SSH 认证未完成,请检查用户名和密钥") | |
| 179 | 新增: } | |
| 180 | 新增: _ = raw.SetDeadline(time.Time{}) | |
| 181 | 新增: client := ssh.NewClient(sshConn, channels, requests) | |
| 182 | 新增: defer func() { | |
| 183 | 新增: if !complete { | |
| 184 | 新增: client.Close() | |
| 185 | 新增: } | |
| 186 | 新增: }() | |
| 187 | 新增: phase("server_handshake") | |
| 188 | 新增: if !stopBootstrap() || bootstrap.Err() != nil { | |
| 189 | 新增: return nil, failure("ssh_timeout", "SSH 认证超时") | |
| 190 | 新增: } | |
| 191 | 新增: timeout := 2 * time.Minute | |
| 192 | 新增: if secrets.Deploy { | |
| 193 | 新增: timeout = 90 * time.Minute | |
| 194 | 新增: } | |
| 195 | 新增: ready, cancelReady := context.WithTimeout(lifetime, timeout) | |
| 196 | 新增: defer cancelReady() | |
| 197 | 新增: stopReady := context.AfterFunc(ready, func() { client.Close() }) | |
| 198 | 新增: defer stopReady() | |
| 199 | 新增: output, err := cloudEntry(ready, client, p, secrets.Deploy, phase) | |
| 200 | 新增: if err != nil { | |
| 201 | 新增: return nil, err | |
| 202 | 新增: } | |
| 203 | 新增: var manifest ServerManifest | |
| 204 | 新增: decoder := json.NewDecoder(bytes.NewReader(output)) | |
| 205 | 新增: decoder.DisallowUnknownFields() | |
| 206 | 新增: if decoder.Decode(&manifest) != nil { | |
| 207 | 新增: return nil, failure("manifest_invalid", "云端 Cage 未返回有效连接信息") | |
| 208 | 新增: } | |
| 209 | 新增: var extra any | |
| 210 | 新增: if decoder.Decode(&extra) != io.EOF { | |
| 211 | 新增: return nil, failure("manifest_invalid", "云端 Cage 返回了多余连接信息") | |
| 212 | 新增: } | |
| 213 | 新增: if err = ValidateManifest(manifest); err != nil { | |
| 214 | 新增: return nil, err | |
| 215 | 新增: } | |
| 216 | 新增: origin, _ := url.Parse(manifest.Origin) | |
| 217 | 新增: targetHost := origin.Hostname() | |
| 218 | 新增: if targetHost == "localhost" { | |
| 219 | 新增: targetHost = "127.0.0.1" | |
| 220 | 新增: } | |
| 221 | 新增: target := net.JoinHostPort(targetHost, origin.Port()) | |
| 222 | 新增: life, cancelLife := context.WithCancel(lifetime) | |
| 223 | 新增: transport := &http.Transport{Proxy: nil, ForceAttemptHTTP2: false, MaxIdleConns: 32, MaxIdleConnsPerHost: 16, IdleConnTimeout: 60 * time.Second, ResponseHeaderTimeout: 30 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { | |
| 224 | 新增: if network != "tcp" || address != origin.Host { | |
| 225 | 新增: return nil, failure("origin_refused", "拒绝访问云端声明之外的服务") | |
| 226 | 新增: } | |
| 227 | 新增: return client.DialContext(ctx, "tcp", target) | |
| 228 | 新增: }} | |
| 229 | 新增: jar, _ := cookiejar.New(nil) | |
| 230 | 新增: bound := &sessionTransport{base: transport, jar: jar, origin: manifest.Origin, ctx: life} | |
| 231 | 新增: var once sync.Once | |
| 232 | 新增: s := &Session{Manifest: manifest.Public(), Transport: bound, Context: life, Origin: manifest.Origin} | |
| 233 | 新增: s.close = func() error { | |
| 234 | 新增: once.Do(func() { cancelLife(); transport.CloseIdleConnections(); client.Close() }) | |
| 235 | 新增: return nil | |
| 236 | 新增: } | |
| 237 | 新增: bound.invalidate = s.Close | |
| 238 | 新增: s.Client = &http.Client{Transport: bound, CheckRedirect: func(*http.Request, []*http.Request) error { | |
| 239 | 新增: return failure("redirect_refused", "云端服务重定向已拒绝") | |
| 240 | 新增: }} | |
| 241 | 新增: body, _ := json.Marshal(map[string]string{"token": manifest.Ticket}) | |
| 242 | 新增: manifest.Ticket = "" | |
| 243 | 新增: req, _ := http.NewRequestWithContext(ready, "POST", s.Origin+"/api/session", bytes.NewReader(body)) | |
| 244 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 245 | 新增: response, err := s.Client.Do(req) | |
| 246 | 新增: clear(body) | |
| 247 | 新增: if err != nil { | |
| 248 | 新增: s.Close() | |
| 249 | 新增: return nil, failure("server_session_failed", "无法建立云端 Cage 会话") | |
| 250 | 新增: } | |
| 251 | 新增: io.Copy(io.Discard, io.LimitReader(response.Body, 4096)) | |
| 252 | 新增: response.Body.Close() | |
| 253 | 新增: if response.StatusCode != http.StatusOK || len(jar.Cookies(origin)) == 0 { | |
| 254 | 新增: s.Close() | |
| 255 | 新增: return nil, failure("server_session_failed", "云端 Cage 未接受连接票据") | |
| 256 | 新增: } | |
| 257 | 新增: if ready.Err() != nil { | |
| 258 | 新增: s.Close() | |
| 259 | 新增: return nil, failure("connection_cancelled", "远程连接已取消") | |
| 260 | 新增: } | |
| 261 | 新增: stopReady() | |
| 262 | 新增: complete = true | |
| 263 | 新增: go func() { _ = client.Wait(); s.Close() }() | |
| 264 | 新增: context.AfterFunc(life, func() { s.Close() }) | |
| 265 | 新增: return s, nil | |
| 266 | 新增:} | |
| 267 | 新增: | |
| 268 | 新增:type sessionTransport struct { | |
| 269 | 新增: base *http.Transport | |
| 270 | 新增: jar http.CookieJar | |
| 271 | 新增: origin string | |
| 272 | 新增: ctx context.Context | |
| 273 | 新增: invalidate func() error | |
| 274 | 新增:} | |
| 275 | 新增: | |
| 276 | 新增:func (t *sessionTransport) RoundTrip(request *http.Request) (*http.Response, error) { | |
| 277 | 新增: if request.URL.Scheme+"://"+request.URL.Host != t.origin || request.URL.User != nil { | |
| 278 | 新增: return nil, failure("origin_refused", "拒绝访问云端声明之外的服务") | |
| 279 | 新增: } | |
| 280 | 新增: if err := t.ctx.Err(); err != nil { | |
| 281 | 新增: return nil, failure("connection_changed", "远程连接已断开") | |
| 282 | 新增: } | |
| 283 | 新增: ctx, cancel := context.WithCancel(request.Context()) | |
| 284 | 新增: stop := context.AfterFunc(t.ctx, cancel) | |
| 285 | 新增: finish := func() { stop(); cancel() } | |
| 286 | 新增: req := request.Clone(ctx) | |
| 287 | 新增: req.Header = request.Header.Clone() | |
| 288 | 新增: req.Host = req.URL.Host | |
| 289 | 新增: req.Header.Del("Cookie") | |
| 290 | 新增: req.Header.Del("Authorization") | |
| 291 | 新增: req.Header.Del("Proxy-Authorization") | |
| 292 | 新增: req.Header.Del("Idempotency-Key") | |
| 293 | 新增: req.Header.Del("X-Idempotency-Key") | |
| 294 | 新增: req.GetBody = nil | |
| 295 | 新增: req.Header.Set("Origin", t.origin) | |
| 296 | 新增: for _, cookie := range t.jar.Cookies(req.URL) { | |
| 297 | 新增: req.AddCookie(cookie) | |
| 298 | 新增: } | |
| 299 | 新增: response, err := t.base.RoundTrip(req) | |
| 300 | 新增: if err != nil { | |
| 301 | 新增: finish() | |
| 302 | 新增: return nil, failure("remote_request_failed", "远程请求中断,请检查连接;已提交的操作不会自动重发") | |
| 303 | 新增: } | |
| 304 | 新增: if response.StatusCode == http.StatusUnauthorized { | |
| 305 | 新增: response.Body.Close() | |
| 306 | 新增: finish() | |
| 307 | 新增: if t.invalidate != nil { | |
| 308 | 新增: _ = t.invalidate() | |
| 309 | 新增: } | |
| 310 | 新增: return nil, failure("remote_session_expired", "云端会话已失效,请重新连接并核对云端任务") | |
| 311 | 新增: } | |
| 312 | 新增: t.jar.SetCookies(req.URL, response.Cookies()) | |
| 313 | 新增: response.Header.Del("Set-Cookie") | |
| 314 | 新增: if response.StatusCode >= 300 && response.StatusCode < 400 && response.Header.Get("Location") != "" { | |
| 315 | 新增: response.Body.Close() | |
| 316 | 新增: finish() | |
| 317 | 新增: return nil, failure("redirect_refused", "云端服务重定向已拒绝") | |
| 318 | 新增: } | |
| 319 | 新增: if rw, ok := response.Body.(io.ReadWriteCloser); ok { | |
| 320 | 新增: response.Body = &cancelReadWriteCloser{ReadWriteCloser: rw, finish: finish} | |
| 321 | 新增: } else { | |
| 322 | 新增: response.Body = &cancelReadCloser{ReadCloser: response.Body, finish: finish} | |
| 323 | 新增: } | |
| 324 | 新增: return response, nil | |
| 325 | 新增:} | |
| 326 | 新增: | |
| 327 | 新增:type cancelReadCloser struct { | |
| 328 | 新增: io.ReadCloser | |
| 329 | 新增: finish func() | |
| 330 | 新增: once sync.Once | |
| 331 | 新增:} | |
| 332 | 新增: | |
| 333 | 新增:func (b *cancelReadCloser) Read(p []byte) (int, error) { | |
| 334 | 新增: n, e := b.ReadCloser.Read(p) | |
| 335 | 新增: if e != nil { | |
| 336 | 新增: b.once.Do(b.finish) | |
| 337 | 新增: } | |
| 338 | 新增: return n, e | |
| 339 | 新增:} | |
| 340 | 新增:func (b *cancelReadCloser) Close() error { | |
| 341 | 新增: err := b.ReadCloser.Close() | |
| 342 | 新增: b.once.Do(b.finish) | |
| 343 | 新增: return err | |
| 344 | 新增:} | |
| 345 | 新增: | |
| 346 | 新增:type cancelReadWriteCloser struct { | |
| 347 | 新增: io.ReadWriteCloser | |
| 348 | 新增: finish func() | |
| 349 | 新增: once sync.Once | |
| 350 | 新增:} | |
| 351 | 新增: | |
| 352 | 新增:func (b *cancelReadWriteCloser) Read(p []byte) (int, error) { | |
| 353 | 新增: n, e := b.ReadWriteCloser.Read(p) | |
| 354 | 新增: if e != nil { | |
| 355 | 新增: b.once.Do(b.finish) | |
| 356 | 新增: } | |
| 357 | 新增: return n, e | |
| 358 | 新增:} | |
| 359 | 新增:func (b *cancelReadWriteCloser) Close() error { | |
| 360 | 新增: err := b.ReadWriteCloser.Close() | |
| 361 | 新增: b.once.Do(b.finish) | |
| 362 | 新增: return err | |
| 363 | 新增:} | |
| @@ -0,0 +1,588 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/ecdsa" | |
| 6 | 新增: "crypto/ed25519" | |
| 7 | 新增: "crypto/elliptic" | |
| 8 | 新增: "crypto/rand" | |
| 9 | 新增: "crypto/rsa" | |
| 10 | 新增: "crypto/x509" | |
| 11 | 新增: "encoding/json" | |
| 12 | 新增: "encoding/pem" | |
| 13 | 新增: "errors" | |
| 14 | 新增: "fmt" | |
| 15 | 新增: "io" | |
| 16 | 新增: "net" | |
| 17 | 新增: "net/http" | |
| 18 | 新增: "net/http/httptest" | |
| 19 | 新增: "net/http/httputil" | |
| 20 | 新增: "net/url" | |
| 21 | 新增: "os" | |
| 22 | 新增: "os/exec" | |
| 23 | 新增: "path/filepath" | |
| 24 | 新增: "runtime" | |
| 25 | 新增: "strconv" | |
| 26 | 新增: "strings" | |
| 27 | 新增: "sync" | |
| 28 | 新增: "sync/atomic" | |
| 29 | 新增: "testing" | |
| 30 | 新增: "time" | |
| 31 | 新增: | |
| 32 | 新增: "github.com/gorilla/websocket" | |
| 33 | 新增: "golang.org/x/crypto/ssh" | |
| 34 | 新增:) | |
| 35 | 新增: | |
| 36 | 新增:type sshFixture struct { | |
| 37 | 新增: profile HostProfile | |
| 38 | 新增: manifest ServerManifest | |
| 39 | 新增: commands chan string | |
| 40 | 新增: connections sync.Map | |
| 41 | 新增: listener net.Listener | |
| 42 | 新增: forwardCount atomic.Int64 | |
| 43 | 新增:} | |
| 44 | 新增: | |
| 45 | 新增:func newFixture(t *testing.T, handler http.Handler, extraHostKeys ...ssh.Signer) *sshFixture { | |
| 46 | 新增: t.Helper() | |
| 47 | 新增: httpServer := httptest.NewServer(handler) | |
| 48 | 新增: t.Cleanup(httpServer.Close) | |
| 49 | 新增: _, hostPrivate, _ := ed25519.GenerateKey(rand.Reader) | |
| 50 | 新增: hostSigner, _ := ssh.NewSignerFromKey(hostPrivate) | |
| 51 | 新增: _, clientPrivate, _ := ed25519.GenerateKey(rand.Reader) | |
| 52 | 新增: clientSigner, _ := ssh.NewSignerFromKey(clientPrivate) | |
| 53 | 新增: keyBytes, _ := x509.MarshalPKCS8PrivateKey(clientPrivate) | |
| 54 | 新增: keyPath := filepath.Join(t.TempDir(), "identity") | |
| 55 | 新增: if err := os.WriteFile(keyPath, pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyBytes}), 0600); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: listener, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: t.Fatal(err) | |
| 61 | 新增: } | |
| 62 | 新增: f := &sshFixture{listener: listener, commands: make(chan string, 8), manifest: ServerManifest{APIProtocol: 1, InstanceID: strings.Repeat("a", 64), Version: "test", Platform: "linux", Runtime: "container", Origin: httpServer.URL, Ticket: strings.Repeat("t", 64), Capabilities: map[string]bool{"terminal": true}}} | |
| 63 | 新增: f.profile = HostProfile{ID: newID(), Name: "fixture", Host: "127.0.0.1", Port: listener.Addr().(*net.TCPAddr).Port, User: "cage", Auth: AuthConfig{Kind: "key_file", IdentityFile: keyPath}, HostKey: &HostKey{Algorithm: hostSigner.PublicKey().Type(), Fingerprint: ssh.FingerprintSHA256(hostSigner.PublicKey())}} | |
| 64 | 新增: config := &ssh.ServerConfig{PublicKeyCallback: func(_ ssh.ConnMetadata, key ssh.PublicKey) (*ssh.Permissions, error) { | |
| 65 | 新增: if string(key.Marshal()) != string(clientSigner.PublicKey().Marshal()) { | |
| 66 | 新增: return nil, errors.New("wrong key") | |
| 67 | 新增: } | |
| 68 | 新增: return nil, nil | |
| 69 | 新增: }} | |
| 70 | 新增: config.AddHostKey(hostSigner) | |
| 71 | 新增: for _, key := range extraHostKeys { | |
| 72 | 新增: config.AddHostKey(key) | |
| 73 | 新增: } | |
| 74 | 新增: go func() { | |
| 75 | 新增: for { | |
| 76 | 新增: conn, err := listener.Accept() | |
| 77 | 新增: if err != nil { | |
| 78 | 新增: return | |
| 79 | 新增: } | |
| 80 | 新增: f.connections.Store(conn, true) | |
| 81 | 新增: go func() { | |
| 82 | 新增: defer f.connections.Delete(conn) | |
| 83 | 新增: defer conn.Close() | |
| 84 | 新增: server, channels, requests, err := ssh.NewServerConn(conn, config) | |
| 85 | 新增: if err != nil { | |
| 86 | 新增: return | |
| 87 | 新增: } | |
| 88 | 新增: defer server.Close() | |
| 89 | 新增: go ssh.DiscardRequests(requests) | |
| 90 | 新增: for channel := range channels { | |
| 91 | 新增: go f.channel(channel) | |
| 92 | 新增: } | |
| 93 | 新增: }() | |
| 94 | 新增: } | |
| 95 | 新增: }() | |
| 96 | 新增: t.Cleanup(func() { | |
| 97 | 新增: listener.Close() | |
| 98 | 新增: f.connections.Range(func(key, value any) bool { key.(net.Conn).Close(); return true }) | |
| 99 | 新增: }) | |
| 100 | 新增: return f | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:func (f *sshFixture) channel(in ssh.NewChannel) { | |
| 104 | 新增: switch in.ChannelType() { | |
| 105 | 新增: case "session": | |
| 106 | 新增: channel, requests, err := in.Accept() | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: return | |
| 109 | 新增: } | |
| 110 | 新增: defer channel.Close() | |
| 111 | 新增: for request := range requests { | |
| 112 | 新增: if request.Type != "exec" { | |
| 113 | 新增: request.Reply(false, nil) | |
| 114 | 新增: continue | |
| 115 | 新增: } | |
| 116 | 新增: var command struct{ Command string } | |
| 117 | 新增: ssh.Unmarshal(request.Payload, &command) | |
| 118 | 新增: f.commands <- command.Command | |
| 119 | 新增: request.Reply(true, nil) | |
| 120 | 新增: json.NewEncoder(channel).Encode(f.manifest) | |
| 121 | 新增: channel.SendRequest("exit-status", false, ssh.Marshal(struct{ Code uint32 }{0})) | |
| 122 | 新增: return | |
| 123 | 新增: } | |
| 124 | 新增: case "direct-tcpip": | |
| 125 | 新增: var forward struct { | |
| 126 | 新增: Host string | |
| 127 | 新增: Port uint32 | |
| 128 | 新增: Origin string | |
| 129 | 新增: OriginPort uint32 | |
| 130 | 新增: } | |
| 131 | 新增: if ssh.Unmarshal(in.ExtraData(), &forward) != nil { | |
| 132 | 新增: in.Reject(ssh.Prohibited, "invalid") | |
| 133 | 新增: return | |
| 134 | 新增: } | |
| 135 | 新增: u, _ := url.Parse(f.manifest.Origin) | |
| 136 | 新增: port, _ := strconv.Atoi(u.Port()) | |
| 137 | 新增: if forward.Host != "127.0.0.1" || int(forward.Port) != port { | |
| 138 | 新增: in.Reject(ssh.Prohibited, "wrong destination") | |
| 139 | 新增: return | |
| 140 | 新增: } | |
| 141 | 新增: peer, err := net.Dial("tcp", net.JoinHostPort(forward.Host, strconv.Itoa(int(forward.Port)))) | |
| 142 | 新增: if err != nil { | |
| 143 | 新增: in.Reject(ssh.ConnectionFailed, "dial") | |
| 144 | 新增: return | |
| 145 | 新增: } | |
| 146 | 新增: defer peer.Close() | |
| 147 | 新增: channel, requests, err := in.Accept() | |
| 148 | 新增: if err != nil { | |
| 149 | 新增: return | |
| 150 | 新增: } | |
| 151 | 新增: defer channel.Close() | |
| 152 | 新增: f.forwardCount.Add(1) | |
| 153 | 新增: go ssh.DiscardRequests(requests) | |
| 154 | 新增: done := make(chan struct{}) | |
| 155 | 新增: go func() { io.Copy(peer, channel); peer.Close(); close(done) }() | |
| 156 | 新增: io.Copy(channel, peer) | |
| 157 | 新增: channel.Close() | |
| 158 | 新增: <-done | |
| 159 | 新增: default: | |
| 160 | 新增: in.Reject(ssh.UnknownChannelType, "unsupported") | |
| 161 | 新增: } | |
| 162 | 新增:} | |
| 163 | 新增: | |
| 164 | 新增:func fixtureHandler(t *testing.T, next http.Handler) http.Handler { | |
| 165 | 新增: t.Helper() | |
| 166 | 新增: return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 167 | 新增: if r.Header.Get("Origin") != "http://"+r.Host { | |
| 168 | 新增: http.Error(w, "origin", 403) | |
| 169 | 新增: return | |
| 170 | 新增: } | |
| 171 | 新增: if r.URL.Path == "/api/session" { | |
| 172 | 新增: var body struct{ Token string } | |
| 173 | 新增: json.NewDecoder(r.Body).Decode(&body) | |
| 174 | 新增: if body.Token != strings.Repeat("t", 64) { | |
| 175 | 新增: http.Error(w, "ticket", 401) | |
| 176 | 新增: return | |
| 177 | 新增: } | |
| 178 | 新增: http.SetCookie(w, &http.Cookie{Name: "remote_session", Value: "private-cookie", Path: "/", HttpOnly: true, SameSite: http.SameSiteStrictMode}) | |
| 179 | 新增: io.WriteString(w, `{"ok":true}`) | |
| 180 | 新增: return | |
| 181 | 新增: } | |
| 182 | 新增: cookie, err := r.Cookie("remote_session") | |
| 183 | 新增: if err != nil || cookie.Value != "private-cookie" || r.Header.Get("Authorization") != "" || strings.Contains(r.Header.Get("Cookie"), "local-secret") { | |
| 184 | 新增: http.Error(w, "auth", 401) | |
| 185 | 新增: return | |
| 186 | 新增: } | |
| 187 | 新增: next.ServeHTTP(w, r) | |
| 188 | 新增: }) | |
| 189 | 新增:} | |
| 190 | 新增: | |
| 191 | 新增:func connectFixture(t *testing.T, f *sshFixture) *Session { | |
| 192 | 新增: t.Helper() | |
| 193 | 新增: s, err := connect(context.Background(), f.profile, ConnectSecrets{}, func(string) {}) | |
| 194 | 新增: if err != nil { | |
| 195 | 新增: t.Fatal(err) | |
| 196 | 新增: } | |
| 197 | 新增: t.Cleanup(func() { s.Close() }) | |
| 198 | 新增: return s | |
| 199 | 新增:} | |
| 200 | 新增: | |
| 201 | 新增:func TestSSHSessionHTTPWebSocketSSEAndCancellation(t *testing.T) { | |
| 202 | 新增: sseEnded := make(chan struct{}) | |
| 203 | 新增: f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 204 | 新增: switch r.URL.Path { | |
| 205 | 新增: case "/check": | |
| 206 | 新增: io.WriteString(w, "authenticated") | |
| 207 | 新增: case "/stream": | |
| 208 | 新增: w.Header().Set("Content-Type", "text/event-stream") | |
| 209 | 新增: io.WriteString(w, "data: ready\n\n") | |
| 210 | 新增: w.(http.Flusher).Flush() | |
| 211 | 新增: <-r.Context().Done() | |
| 212 | 新增: close(sseEnded) | |
| 213 | 新增: case "/ws": | |
| 214 | 新增: connection, err := (&websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return r.Header.Get("Origin") == "http://"+r.Host }}).Upgrade(w, r, nil) | |
| 215 | 新增: if err != nil { | |
| 216 | 新增: return | |
| 217 | 新增: } | |
| 218 | 新增: defer connection.Close() | |
| 219 | 新增: kind, data, err := connection.ReadMessage() | |
| 220 | 新增: if err == nil { | |
| 221 | 新增: connection.WriteMessage(kind, data) | |
| 222 | 新增: } | |
| 223 | 新增: default: | |
| 224 | 新增: http.NotFound(w, r) | |
| 225 | 新增: } | |
| 226 | 新增: }))) | |
| 227 | 新增: s := connectFixture(t, f) | |
| 228 | 新增: if command := <-f.commands; command != "exec 'cage' server-entry --json" { | |
| 229 | 新增: t.Fatalf("command = %q", command) | |
| 230 | 新增: } | |
| 231 | 新增: req, _ := http.NewRequest("GET", s.Origin+"/check", nil) | |
| 232 | 新增: req.Header.Set("Cookie", "local=local-secret") | |
| 233 | 新增: req.Header.Set("Authorization", "Bearer local-secret") | |
| 234 | 新增: response, err := s.Client.Do(req) | |
| 235 | 新增: if err != nil { | |
| 236 | 新增: t.Fatal(err) | |
| 237 | 新增: } | |
| 238 | 新增: body, _ := io.ReadAll(response.Body) | |
| 239 | 新增: response.Body.Close() | |
| 240 | 新增: if string(body) != "authenticated" { | |
| 241 | 新增: t.Fatalf("HTTP = %d %q", response.StatusCode, body) | |
| 242 | 新增: } | |
| 243 | 新增: u, _ := url.Parse(s.Origin) | |
| 244 | 新增: proxy := httputil.NewSingleHostReverseProxy(u) | |
| 245 | 新增: proxy.Transport = s.Transport | |
| 246 | 新增: gateway := httptest.NewServer(proxy) | |
| 247 | 新增: defer gateway.Close() | |
| 248 | 新增: ws, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(gateway.URL, "http")+"/ws", nil) | |
| 249 | 新增: if err != nil { | |
| 250 | 新增: t.Fatal(err) | |
| 251 | 新增: } | |
| 252 | 新增: defer ws.Close() | |
| 253 | 新增: if err = ws.WriteMessage(websocket.TextMessage, []byte("hello")); err != nil { | |
| 254 | 新增: t.Fatal(err) | |
| 255 | 新增: } | |
| 256 | 新增: _, message, err := ws.ReadMessage() | |
| 257 | 新增: if err != nil || string(message) != "hello" { | |
| 258 | 新增: t.Fatalf("websocket: %q %v", message, err) | |
| 259 | 新增: } | |
| 260 | 新增: stream, err := s.Client.Get(s.Origin + "/stream") | |
| 261 | 新增: if err != nil { | |
| 262 | 新增: t.Fatal(err) | |
| 263 | 新增: } | |
| 264 | 新增: first := make([]byte, len("data: ready\n\n")) | |
| 265 | 新增: if _, err = io.ReadFull(stream.Body, first); err != nil { | |
| 266 | 新增: t.Fatal(err) | |
| 267 | 新增: } | |
| 268 | 新增: s.Close() | |
| 269 | 新增: stream.Body.Close() | |
| 270 | 新增: select { | |
| 271 | 新增: case <-sseEnded: | |
| 272 | 新增: case <-time.After(3 * time.Second): | |
| 273 | 新增: t.Fatal("SSE remained open after disconnect") | |
| 274 | 新增: } | |
| 275 | 新增: if _, err = s.Client.Get(s.Origin + "/check"); err == nil { | |
| 276 | 新增: t.Fatal("closed session accepted request") | |
| 277 | 新增: } | |
| 278 | 新增:} | |
| 279 | 新增: | |
| 280 | 新增:func TestHostKeyRequiresExplicitMatchingPin(t *testing.T) { | |
| 281 | 新增: f := newFixture(t, fixtureHandler(t, http.NotFoundHandler())) | |
| 282 | 新增: for _, code := range []string{"host_key_unknown", "host_key_changed"} { | |
| 283 | 新增: p := f.profile | |
| 284 | 新增: if code == "host_key_unknown" { | |
| 285 | 新增: p.HostKey = nil | |
| 286 | 新增: } else { | |
| 287 | 新增: p.HostKey = &HostKey{Algorithm: p.HostKey.Algorithm, Fingerprint: "SHA256:" + strings.Repeat("A", 43)} | |
| 288 | 新增: } | |
| 289 | 新增: _, err := connect(context.Background(), p, ConnectSecrets{}, func(string) {}) | |
| 290 | 新增: var structured *Error | |
| 291 | 新增: if !errors.As(err, &structured) || structured.Code != code || structured.HostKey == nil || structured.HostKey.Fingerprint != f.profile.HostKey.Fingerprint { | |
| 292 | 新增: t.Fatalf("%s: %#v", code, err) | |
| 293 | 新增: } | |
| 294 | 新增: } | |
| 295 | 新增: if f.forwardCount.Load() != 0 { | |
| 296 | 新增: t.Fatal("untrusted host reached HTTP service") | |
| 297 | 新增: } | |
| 298 | 新增:} | |
| 299 | 新增: | |
| 300 | 新增:func TestPinnedHostKeySelectsMatchingAlgorithmOnMultiKeyServer(t *testing.T) { | |
| 301 | 新增: ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) | |
| 302 | 新增: if err != nil { | |
| 303 | 新增: t.Fatal(err) | |
| 304 | 新增: } | |
| 305 | 新增: ecdsaSigner, err := ssh.NewSignerFromKey(ecdsaKey) | |
| 306 | 新增: if err != nil { | |
| 307 | 新增: t.Fatal(err) | |
| 308 | 新增: } | |
| 309 | 新增: rsaKey, err := rsa.GenerateKey(rand.Reader, 2048) | |
| 310 | 新增: if err != nil { | |
| 311 | 新增: t.Fatal(err) | |
| 312 | 新增: } | |
| 313 | 新增: rsaSigner, err := ssh.NewSignerFromKey(rsaKey) | |
| 314 | 新增: if err != nil { | |
| 315 | 新增: t.Fatal(err) | |
| 316 | 新增: } | |
| 317 | 新增: f := newFixture(t, fixtureHandler(t, http.NotFoundHandler()), ecdsaSigner, rsaSigner) | |
| 318 | 新增: // The stored ED25519 key must win even if the client's default preference | |
| 319 | 新增: // would negotiate the server's ECDSA key first. | |
| 320 | 新增: connectFixture(t, f).Close() | |
| 321 | 新增: // RSA's public key type differs from its SHA-2 signature algorithm names. | |
| 322 | 新增: f.profile.HostKey = &HostKey{Algorithm: ssh.KeyAlgoRSA, Fingerprint: ssh.FingerprintSHA256(rsaSigner.PublicKey())} | |
| 323 | 新增: connectFixture(t, f).Close() | |
| 324 | 新增:} | |
| 325 | 新增: | |
| 326 | 新增:func TestOriginRedirectAndMutationReplayRefused(t *testing.T) { | |
| 327 | 新增: var mutations atomic.Int64 | |
| 328 | 新增: f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 329 | 新增: if r.URL.Path == "/redirect" { | |
| 330 | 新增: http.Redirect(w, r, "http://public.example/private", 302) | |
| 331 | 新增: return | |
| 332 | 新增: } | |
| 333 | 新增: if r.URL.Path == "/mutation" { | |
| 334 | 新增: mutations.Add(1) | |
| 335 | 新增: conn, _, _ := w.(http.Hijacker).Hijack() | |
| 336 | 新增: conn.Close() | |
| 337 | 新增: return | |
| 338 | 新增: } | |
| 339 | 新增: io.WriteString(w, "ok") | |
| 340 | 新增: }))) | |
| 341 | 新增: s := connectFixture(t, f) | |
| 342 | 新增: if _, err := s.Client.Get("http://public.example/check"); err == nil { | |
| 343 | 新增: t.Fatal("arbitrary destination accepted") | |
| 344 | 新增: } | |
| 345 | 新增: if _, err := s.Client.Get(s.Origin + "/redirect"); err == nil { | |
| 346 | 新增: t.Fatal("redirect accepted") | |
| 347 | 新增: } | |
| 348 | 新增: req, _ := http.NewRequest("POST", s.Origin+"/mutation", strings.NewReader("operation")) | |
| 349 | 新增: req.Header.Set("Idempotency-Key", "do-not-replay") | |
| 350 | 新增: if _, err := s.Client.Do(req); err == nil { | |
| 351 | 新增: t.Fatal("missing mutation response accepted") | |
| 352 | 新增: } | |
| 353 | 新增: if mutations.Load() != 1 { | |
| 354 | 新增: t.Fatalf("mutation count = %d", mutations.Load()) | |
| 355 | 新增: } | |
| 356 | 新增:} | |
| 357 | 新增: | |
| 358 | 新增:func TestServerEntryCommandQuotesPaths(t *testing.T) { | |
| 359 | 新增: if runtime.GOOS == "windows" { | |
| 360 | 新增: t.Skip("POSIX server command is executed by the remote Linux shell") | |
| 361 | 新增: } | |
| 362 | 新增: dir := t.TempDir() | |
| 363 | 新增: executable := filepath.Join(dir, "cage ' literal") | |
| 364 | 新增: if err := os.WriteFile(executable, []byte("#!/bin/sh\nprintf '%s\\n%s\\n%s\\n' \"$CLAUDE_CAGE_CONFIG\" \"$1\" \"$2\"\n"), 0700); err != nil { | |
| 365 | 新增: t.Fatal(err) | |
| 366 | 新增: } | |
| 367 | 新增: p := HostProfile{Name: "test", Host: "localhost", User: "user", Auth: AuthConfig{Kind: "agent"}, Executable: executable, ConfigPath: filepath.Join(dir, "a'$(touch injected).json")} | |
| 368 | 新增: command, err := ServerEntryCommand(p) | |
| 369 | 新增: if err != nil { | |
| 370 | 新增: t.Fatal(err) | |
| 371 | 新增: } | |
| 372 | 新增: cmd := exec.Command("sh", "-c", command) | |
| 373 | 新增: cmd.Dir = dir | |
| 374 | 新增: output, err := cmd.Output() | |
| 375 | 新增: if err != nil { | |
| 376 | 新增: t.Fatal(err) | |
| 377 | 新增: } | |
| 378 | 新增: if string(output) != p.ConfigPath+"\nserver-entry\n--json\n" { | |
| 379 | 新增: t.Fatalf("command output = %q", output) | |
| 380 | 新增: } | |
| 381 | 新增: if _, err = os.Stat(filepath.Join(dir, "injected")); !os.IsNotExist(err) { | |
| 382 | 新增: t.Fatal("shell substitution executed") | |
| 383 | 新增: } | |
| 384 | 新增:} | |
| 385 | 新增: | |
| 386 | 新增:func TestManifestRejectsRemoteTargets(t *testing.T) { | |
| 387 | 新增: manifest := ServerManifest{APIProtocol: 1, InstanceID: strings.Repeat("a", 64), Platform: "linux", Runtime: "container", Origin: "http://localhost:17800", Ticket: strings.Repeat("t", 64)} | |
| 388 | 新增: for _, origin := range []string{"https://localhost:17800", "http://example.com:80", "http://127.0.0.1:17800/path", "http://user@localhost:17800", "http://localhost:17800?x=1", "http://localhost:17800#x", "http://localhost"} { | |
| 389 | 新增: manifest.Origin = origin | |
| 390 | 新增: if ValidateManifest(manifest) == nil { | |
| 391 | 新增: t.Errorf("accepted %s", origin) | |
| 392 | 新增: } | |
| 393 | 新增: } | |
| 394 | 新增: manifest.Origin = "http://localhost:17800" | |
| 395 | 新增: if err := ValidateManifest(manifest); err != nil { | |
| 396 | 新增: t.Fatal(err) | |
| 397 | 新增: } | |
| 398 | 新增: manifest.APIProtocol = 2 | |
| 399 | 新增: if err := ValidateManifest(manifest); err == nil { | |
| 400 | 新增: t.Fatal("accepted unknown protocol") | |
| 401 | 新增: } | |
| 402 | 新增: manifest.APIProtocol = APIProtocol | |
| 403 | 新增: manifest.InstanceID = newID() | |
| 404 | 新增: if err := ValidateManifest(manifest); err == nil { | |
| 405 | 新增: t.Fatal("accepted an instance identity that cannot be used by file and account consumers") | |
| 406 | 新增: } | |
| 407 | 新增:} | |
| 408 | 新增: | |
| 409 | 新增:func waitState(t *testing.T, m *Manager, want string) ConnectionState { | |
| 410 | 新增: t.Helper() | |
| 411 | 新增: deadline := time.Now().Add(5 * time.Second) | |
| 412 | 新增: for time.Now().Before(deadline) { | |
| 413 | 新增: state := m.Snapshot() | |
| 414 | 新增: if state.State == want { | |
| 415 | 新增: return state | |
| 416 | 新增: } | |
| 417 | 新增: if state.State == "failed" && want != "failed" { | |
| 418 | 新增: t.Fatalf("connection failed: %+v", state) | |
| 419 | 新增: } | |
| 420 | 新增: time.Sleep(time.Millisecond * 5) | |
| 421 | 新增: } | |
| 422 | 新增: t.Fatalf("state never became %s: %+v", want, m.Snapshot()) | |
| 423 | 新增: return ConnectionState{} | |
| 424 | 新增:} | |
| 425 | 新增: | |
| 426 | 新增:func TestManagerGenerationAndDisconnectDoNotStopServer(t *testing.T) { | |
| 427 | 新增: var stopCalls atomic.Int64 | |
| 428 | 新增: f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 429 | 新增: if strings.Contains(r.URL.Path, "stop") || strings.Contains(r.URL.Path, "suspend") { | |
| 430 | 新增: stopCalls.Add(1) | |
| 431 | 新增: } | |
| 432 | 新增: io.WriteString(w, "ok") | |
| 433 | 新增: }))) | |
| 434 | 新增: store := NewStore(t.TempDir()) | |
| 435 | 新增: p := f.profile | |
| 436 | 新增: p.ID = "" | |
| 437 | 新增: p, err := store.Upsert(p) | |
| 438 | 新增: if err != nil { | |
| 439 | 新增: t.Fatal(err) | |
| 440 | 新增: } | |
| 441 | 新增: m := NewManager(store) | |
| 442 | 新增: defer m.Close() | |
| 443 | 新增: first, err := m.Connect(p.ID, ConnectSecrets{}) | |
| 444 | 新增: if err != nil { | |
| 445 | 新增: t.Fatal(err) | |
| 446 | 新增: } | |
| 447 | 新增: waitState(t, m, "connected") | |
| 448 | 新增: old, err := m.Acquire(first.ConnectionID) | |
| 449 | 新增: if err != nil { | |
| 450 | 新增: t.Fatal(err) | |
| 451 | 新增: } | |
| 452 | 新增: if err = m.Disconnect(first.ConnectionID); err != nil { | |
| 453 | 新增: t.Fatal(err) | |
| 454 | 新增: } | |
| 455 | 新增: select { | |
| 456 | 新增: case <-old.Context.Done(): | |
| 457 | 新增: case <-time.After(time.Second): | |
| 458 | 新增: t.Fatal("connection not cancelled") | |
| 459 | 新增: } | |
| 460 | 新增: second, err := m.Connect(p.ID, ConnectSecrets{}) | |
| 461 | 新增: if err != nil { | |
| 462 | 新增: t.Fatal(err) | |
| 463 | 新增: } | |
| 464 | 新增: state := waitState(t, m, "connected") | |
| 465 | 新增: if second.ConnectionID == first.ConnectionID || state.InstanceID != f.manifest.InstanceID { | |
| 466 | 新增: t.Fatal("incorrect identity lifecycle") | |
| 467 | 新增: } | |
| 468 | 新增: if _, err = m.Acquire(first.ConnectionID); err == nil { | |
| 469 | 新增: t.Fatal("obsolete connection acquired") | |
| 470 | 新增: } | |
| 471 | 新增: if err = m.Disconnect(first.ConnectionID); err == nil { | |
| 472 | 新增: t.Fatal("old generation disconnected new connection") | |
| 473 | 新增: } | |
| 474 | 新增: if _, err = m.Acquire(second.ConnectionID); err != nil { | |
| 475 | 新增: t.Fatal(err) | |
| 476 | 新增: } | |
| 477 | 新增: if stopCalls.Load() != 0 { | |
| 478 | 新增: t.Fatal("disconnect stopped remote environment") | |
| 479 | 新增: } | |
| 480 | 新增: encoded, _ := json.Marshal(state) | |
| 481 | 新增: if strings.Contains(string(encoded), strings.Repeat("t", 64)) || strings.Contains(string(encoded), "private-cookie") { | |
| 482 | 新增: t.Fatal("connection secrets leaked into state") | |
| 483 | 新增: } | |
| 484 | 新增: f.connections.Range(func(key, value any) bool { key.(net.Conn).Close(); return true }) | |
| 485 | 新增: waitState(t, m, "failed") | |
| 486 | 新增:} | |
| 487 | 新增: | |
| 488 | 新增:func TestExpiredHTTPServerSessionInvalidatesLiveSSHConnectionWithoutReplay(t *testing.T) { | |
| 489 | 新增: var expired atomic.Bool | |
| 490 | 新增: var requests atomic.Int64 | |
| 491 | 新增: f := newFixture(t, fixtureHandler(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 492 | 新增: requests.Add(1) | |
| 493 | 新增: if expired.Load() { | |
| 494 | 新增: http.Error(w, "expired server cookie", http.StatusUnauthorized) | |
| 495 | 新增: return | |
| 496 | 新增: } | |
| 497 | 新增: io.WriteString(w, "ok") | |
| 498 | 新增: }))) | |
| 499 | 新增: store := NewStore(t.TempDir()) | |
| 500 | 新增: p := f.profile | |
| 501 | 新增: p.ID = "" | |
| 502 | 新增: p, err := store.Upsert(p) | |
| 503 | 新增: if err != nil { | |
| 504 | 新增: t.Fatal(err) | |
| 505 | 新增: } | |
| 506 | 新增: manager := NewManager(store) | |
| 507 | 新增: defer manager.Close() | |
| 508 | 新增: state, err := manager.Connect(p.ID, ConnectSecrets{}) | |
| 509 | 新增: if err != nil { | |
| 510 | 新增: t.Fatal(err) | |
| 511 | 新增: } | |
| 512 | 新增: waitState(t, manager, "connected") | |
| 513 | 新增: session, err := manager.Acquire(state.ConnectionID) | |
| 514 | 新增: if err != nil { | |
| 515 | 新增: t.Fatal(err) | |
| 516 | 新增: } | |
| 517 | 新增: response, err := session.Client.Get(session.Origin + "/ready") | |
| 518 | 新增: if err != nil { | |
| 519 | 新增: t.Fatal(err) | |
| 520 | 新增: } | |
| 521 | 新增: response.Body.Close() | |
| 522 | 新增: if session.Context.Err() != nil { | |
| 523 | 新增: t.Fatal("SSH session was already closed before server expiry") | |
| 524 | 新增: } | |
| 525 | 新增: expired.Store(true) | |
| 526 | 新增: before := requests.Load() | |
| 527 | 新增: request, _ := http.NewRequest("POST", session.Origin+"/mutation", strings.NewReader(`{"operation":"start"}`)) | |
| 528 | 新增: _, err = session.Client.Do(request) | |
| 529 | 新增: var structured *Error | |
| 530 | 新增: if !errors.As(err, &structured) || structured.Code != "remote_session_expired" { | |
| 531 | 新增: t.Fatalf("session expiry = %v", err) | |
| 532 | 新增: } | |
| 533 | 新增: failed := waitState(t, manager, "failed") | |
| 534 | 新增: if failed.Message != "远程连接已中断,请重新连接并核对云端任务" { | |
| 535 | 新增: t.Fatalf("misleading recovery message: %s", failed.Message) | |
| 536 | 新增: } | |
| 537 | 新增: if requests.Load() != before+1 { | |
| 538 | 新增: t.Fatal("request was replayed after server session expiry") | |
| 539 | 新增: } | |
| 540 | 新增: if _, err := manager.Acquire(state.ConnectionID); err == nil { | |
| 541 | 新增: t.Fatal("expired session remained available") | |
| 542 | 新增: } | |
| 543 | 新增:} | |
| 544 | 新增: | |
| 545 | 新增:func TestStorePreservesIndependentUpdatesAndRejectsUnsafeFiles(t *testing.T) { | |
| 546 | 新增: dir := t.TempDir() | |
| 547 | 新增: var group sync.WaitGroup | |
| 548 | 新增: errs := make(chan error, 12) | |
| 549 | 新增: for i := 0; i < 12; i++ { | |
| 550 | 新增: group.Add(1) | |
| 551 | 新增: go func(i int) { | |
| 552 | 新增: defer group.Done() | |
| 553 | 新增: _, err := NewStore(dir).Upsert(HostProfile{Name: fmt.Sprint(i), Host: "localhost", User: "cage", Auth: AuthConfig{Kind: "agent"}}) | |
| 554 | 新增: errs <- err | |
| 555 | 新增: }(i) | |
| 556 | 新增: } | |
| 557 | 新增: group.Wait() | |
| 558 | 新增: close(errs) | |
| 559 | 新增: for err := range errs { | |
| 560 | 新增: if err != nil { | |
| 561 | 新增: t.Fatal(err) | |
| 562 | 新增: } | |
| 563 | 新增: } | |
| 564 | 新增: profiles, err := NewStore(dir).List() | |
| 565 | 新增: if err != nil || len(profiles) != 12 { | |
| 566 | 新增: t.Fatalf("profiles=%d err=%v", len(profiles), err) | |
| 567 | 新增: } | |
| 568 | 新增: if err = NewStore(dir).Delete(profiles[0].ID); err != nil { | |
| 569 | 新增: t.Fatal(err) | |
| 570 | 新增: } | |
| 571 | 新增: if _, err = NewStore(dir).Get(profiles[0].ID); err == nil { | |
| 572 | 新增: t.Fatal("deleted host retained") | |
| 573 | 新增: } | |
| 574 | 新增: if runtime.GOOS != "windows" { | |
| 575 | 新增: if err = os.Chmod(filepath.Join(dir, "remote-hosts.json"), 0644); err != nil { | |
| 576 | 新增: t.Fatal(err) | |
| 577 | 新增: } | |
| 578 | 新增: if _, err = NewStore(dir).List(); err == nil { | |
| 579 | 新增: t.Fatal("world-readable configuration accepted") | |
| 580 | 新增: } | |
| 581 | 新增: } | |
| 582 | 新增: other := t.TempDir() | |
| 583 | 新增: if err = os.Symlink(filepath.Join(dir, "remote-hosts.json"), filepath.Join(other, "remote-hosts.json")); err == nil { | |
| 584 | 新增: if _, err = NewStore(other).List(); err == nil { | |
| 585 | 新增: t.Fatal("symlink config accepted") | |
| 586 | 新增: } | |
| 587 | 新增: } | |
| 588 | 新增:} | |
| @@ -0,0 +1,153 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "io" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "regexp" | |
| 10 | 新增: "strconv" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/deploy/cloud" | |
| 15 | 新增: "golang.org/x/crypto/ssh" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func runSSH(client *ssh.Client, command string, input io.Reader) ([]byte, error) { | |
| 19 | 新增: session, err := client.NewSession() | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: return nil, err | |
| 22 | 新增: } | |
| 23 | 新增: defer session.Close() | |
| 24 | 新增: out := &limitedOutput{limit: 64 << 10} | |
| 25 | 新增: session.Stdout, session.Stderr, session.Stdin = out, io.Discard, input | |
| 26 | 新增: err = session.Run(command) | |
| 27 | 新增: return out.Bytes(), err | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func lifecycleCommand(p HostProfile, action string, extra ...string) string { | |
| 31 | 新增: args := []string{"bash", "-c", cloud.Lifecycle, "cage-cloud", action, p.Executable, p.ConfigPath} | |
| 32 | 新增: args = append(args, extra...) | |
| 33 | 新增: for i := range args { | |
| 34 | 新增: args[i] = shellQuote(args[i]) | |
| 35 | 新增: } | |
| 36 | 新增: return strings.Join(args, " ") | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:func deploymentError(err error) error { | |
| 40 | 新增: var exit *ssh.ExitError | |
| 41 | 新增: if errors.As(err, &exit) { | |
| 42 | 新增: messages := map[int]string{ | |
| 43 | 新增: 61: "需要 Linux x86_64 服务器,请使用普通 SSH 用户登录", | |
| 44 | 新增: 62: "服务器缺少 rootless 容器所需的用户映射、工具、FUSE、TUN 或 cgroup v2", | |
| 45 | 新增: 63: "SSH 用户的 systemd 用户服务不可用", | |
| 46 | 新增: 64: "自动部署需要由字母、数字、点、短横线、下划线和斜杠组成的绝对配置路径", | |
| 47 | 新增: 65: "目标目录或服务已属于其他配置。请选择空的配置目录,或填写已安装的 Cage 程序路径", | |
| 48 | 新增: 66: "找不到指定的 Cage 程序。首次自动部署请将程序路径设为 cage", | |
| 49 | 新增: 67: "此服务器正在部署 Cage,请稍后重新连接", | |
| 50 | 新增: 68: "配置目录所在磁盘需要至少 7 GiB 可用空间", | |
| 51 | 新增: 69: "部署包传输校验失败,请重新部署", | |
| 52 | 新增: 70: "服务器的独立容器引擎启动失败,请检查用户服务日志和 cgroup 委派", | |
| 53 | 新增: 71: "服务器无法加载或校验工作环境镜像,请检查磁盘空间", | |
| 54 | 新增: 72: "服务器准备工作环境失败,可查看配置目录中的 cloud-host/setup.log 后重试", | |
| 55 | 新增: 74: "下载容器引擎失败,请检查服务器的网络后重试", | |
| 56 | 新增: 75: "服务器无法获取固定版本的 Debian 基础镜像,请检查云端网络后重试", | |
| 57 | 新增: 76: "服务器安装工具失败。详细日志位于配置目录的 cloud-host/build 下", | |
| 58 | 新增: 73: "云端 Cage 用户服务启动失败,请检查服务器用户服务日志", | |
| 59 | 新增: } | |
| 60 | 新增: if message := messages[exit.ExitStatus()]; message != "" { | |
| 61 | 新增: return failure("cloud_setup_failed", message) | |
| 62 | 新增: } | |
| 63 | 新增: } | |
| 64 | 新增: return failure("server_entry_failed", "云端 Cage 未就绪,请检查服务器上的 Cage 程序、配置路径和用户服务") | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:// SSH reads the archive as a stream. Report whole percentages without loading it into memory. | |
| 68 | 新增:type uploadProgress struct { | |
| 69 | 新增: size, sent int64 | |
| 70 | 新增: last int | |
| 71 | 新增: phase func(string) | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 74 | 新增:func (p *uploadProgress) Write(data []byte) (int, error) { | |
| 75 | 新增: p.sent += int64(len(data)) | |
| 76 | 新增: percent := int(p.sent * 100 / p.size) | |
| 77 | 新增: if percent != p.last { | |
| 78 | 新增: p.last = percent | |
| 79 | 新增: if percent == 100 { | |
| 80 | 新增: p.phase("cloud_install") | |
| 81 | 新增: } else { | |
| 82 | 新增: p.phase("cloud_upload_" + strconv.Itoa(percent)) | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 85 | 新增: return len(data), nil | |
| 86 | 新增:} | |
| 87 | 新增: | |
| 88 | 新增:func cloudEntry(ctx context.Context, client *ssh.Client, p HostProfile, deploy bool, phase func(string)) ([]byte, error) { | |
| 89 | 新增: command, err := ServerEntryCommand(p) | |
| 90 | 新增: if err != nil { | |
| 91 | 新增: return nil, err | |
| 92 | 新增: } | |
| 93 | 新增: if out, err := runSSH(client, command, nil); err == nil { | |
| 94 | 新增: return out, nil | |
| 95 | 新增: } | |
| 96 | 新增: phase("cloud_detect") | |
| 97 | 新增: out, err := runSSH(client, lifecycleCommand(p, "probe"), nil) | |
| 98 | 新增: if err != nil { | |
| 99 | 新增: return nil, deploymentError(err) | |
| 100 | 新增: } | |
| 101 | 新增: switch string(out) { | |
| 102 | 新增: case "missing": | |
| 103 | 新增: if !deploy { | |
| 104 | 新增: return nil, failure("deployment_required", "此主机尚未部署 Cage。部署将在 SSH 用户的目录中安装 Cage 和独立容器环境。") | |
| 105 | 新增: } | |
| 106 | 新增: binary, err := os.Executable() | |
| 107 | 新增: if err != nil { | |
| 108 | 新增: return nil, err | |
| 109 | 新增: } | |
| 110 | 新增: payload := filepath.Join(filepath.Dir(binary), "cloud-linux-amd64.tar") | |
| 111 | 新增: sum, err := os.ReadFile(payload + ".sha256") | |
| 112 | 新增: digest := strings.TrimSpace(string(sum)) | |
| 113 | 新增: if err != nil || !regexp.MustCompile("^[a-f0-9]{64}$").MatchString(digest) { | |
| 114 | 新增: return nil, failure("payload_missing", "此客户端缺少云端部署包,请安装包含部署包的 Cage") | |
| 115 | 新增: } | |
| 116 | 新增: file, err := os.Open(payload) | |
| 117 | 新增: if err != nil { | |
| 118 | 新增: return nil, failure("payload_missing", "无法读取云端部署包,请检查 Cage 安装") | |
| 119 | 新增: } | |
| 120 | 新增: defer file.Close() | |
| 121 | 新增: info, err := file.Stat() | |
| 122 | 新增: if err != nil || !info.Mode().IsRegular() || info.Size() == 0 { | |
| 123 | 新增: return nil, failure("payload_missing", "云端部署包无效,请检查 Cage 安装") | |
| 124 | 新增: } | |
| 125 | 新增: input := io.TeeReader(file, &uploadProgress{size: info.Size(), phase: phase}) | |
| 126 | 新增: phase("cloud_upload_0") | |
| 127 | 新增: if _, err = runSSH(client, lifecycleCommand(p, "install", digest), input); err != nil { | |
| 128 | 新增: return nil, deploymentError(err) | |
| 129 | 新增: } | |
| 130 | 新增: case "manual", "managed": | |
| 131 | 新增: if out, err := runSSH(client, lifecycleCommand(p, "entry"), nil); err == nil { | |
| 132 | 新增: return out, nil | |
| 133 | 新增: } | |
| 134 | 新增: phase("cloud_start") | |
| 135 | 新增: if _, err := runSSH(client, lifecycleCommand(p, "start"), nil); err != nil { | |
| 136 | 新增: return nil, deploymentError(err) | |
| 137 | 新增: } | |
| 138 | 新增: default: | |
| 139 | 新增: return out, nil | |
| 140 | 新增: } | |
| 141 | 新增: phase("server_handshake") | |
| 142 | 新增: for i := 0; i < 40; i++ { | |
| 143 | 新增: if out, err := runSSH(client, lifecycleCommand(p, "entry"), nil); err == nil { | |
| 144 | 新增: return out, nil | |
| 145 | 新增: } | |
| 146 | 新增: select { | |
| 147 | 新增: case <-ctx.Done(): | |
| 148 | 新增: return nil, ctx.Err() | |
| 149 | 新增: case <-time.After(500 * time.Millisecond): | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: return nil, failure("server_start_timeout", "云端服务已请求启动,但连接入口尚未就绪,请检查用户服务日志后重连") | |
| 153 | 新增:} | |
| @@ -0,0 +1,46 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "reflect" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:// ImportOnce runs under the new desktop profile's controller lock. Old | |
| 10 | 新增:// profiles remain independently usable. A saved empty list is authoritative. | |
| 11 | 新增:func (s *Store) ImportOnce(directories ...string) error { | |
| 12 | 新增: s.mu.Lock() | |
| 13 | 新增: defer s.mu.Unlock() | |
| 14 | 新增: if _, err := os.Lstat(filepath.Join(s.profile, "remote-hosts.json")); !os.IsNotExist(err) { | |
| 15 | 新增: return err | |
| 16 | 新增: } | |
| 17 | 新增: var merged []HostProfile | |
| 18 | 新增: seen := make(map[string]HostProfile) | |
| 19 | 新增: for _, directory := range directories { | |
| 20 | 新增: profiles, err := NewStore(directory).List() | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: for _, p := range profiles { | |
| 25 | 新增: if old, exists := seen[p.ID]; exists { | |
| 26 | 新增: if reflect.DeepEqual(old, p) { | |
| 27 | 新增: continue | |
| 28 | 新增: } | |
| 29 | 新增: // A divergent device binding must be trusted again. Keep both | |
| 30 | 新增: // choices; do not silently change the pin of an existing host. | |
| 31 | 新增: p.ID = newID() | |
| 32 | 新增: p.HostKey = nil | |
| 33 | 新增: p.Name = "旧入口 · " + p.Name | |
| 34 | 新增: if len(p.Name) > 200 { | |
| 35 | 新增: p.Name = old.Name | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: if len(merged) >= 100 { | |
| 39 | 新增: return failure("profile_limit", "已有主机列表合计超过 100 项,请整理后重试;原配置已保留") | |
| 40 | 新增: } | |
| 41 | 新增: seen[p.ID] = p | |
| 42 | 新增: merged = append(merged, p) | |
| 43 | 新增: } | |
| 44 | 新增: } | |
| 45 | 新增: return s.write(merged) | |
| 46 | 新增:} | |
| @@ -0,0 +1,57 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/url" | |
| 9 | 新增: "sync" | |
| 10 | 新增: "syscall" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// LocalSession attaches the gateway to a controller after its private launch | |
| 15 | 新增:// ticket has been exchanged. It shares the SSH transport's cookie, origin, | |
| 16 | 新增:// redirect and stream cancellation rules. Closing it only closes this view. | |
| 17 | 新增:func LocalSession(ctx context.Context, origin string, manifest PublicManifest, jar http.CookieJar) (*Session, error) { | |
| 18 | 新增: u, err := url.Parse(origin) | |
| 19 | 新增: if err != nil || u.Scheme != "http" || u.Hostname() != "localhost" || u.Port() == "" || u.User != nil || origin != "http://"+u.Host || jar == nil || len(jar.Cookies(u)) == 0 { | |
| 20 | 新增: return nil, errors.New("本机控制服务会话无效") | |
| 21 | 新增: } | |
| 22 | 新增: endpoint := net.JoinHostPort("127.0.0.1", u.Port()) | |
| 23 | 新增: dial := &net.Dialer{Timeout: 5 * time.Second} | |
| 24 | 新增: life, cancel := context.WithCancel(ctx) | |
| 25 | 新增: base := &http.Transport{MaxIdleConnsPerHost: 16, IdleConnTimeout: time.Minute, ResponseHeaderTimeout: 30 * time.Second, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) { | |
| 26 | 新增: if network != "tcp" || address != u.Host { | |
| 27 | 新增: return nil, errors.New("本机服务地址已改变") | |
| 28 | 新增: } | |
| 29 | 新增: conn, err := dial.DialContext(ctx, "tcp4", endpoint) | |
| 30 | 新增: if errors.Is(err, syscall.ECONNREFUSED) { | |
| 31 | 新增: cancel() | |
| 32 | 新增: } | |
| 33 | 新增: return conn, err | |
| 34 | 新增: }} | |
| 35 | 新增: bound := &sessionTransport{base: base, jar: jar, origin: origin, ctx: life} | |
| 36 | 新增: transport := localViewTransport{bound} | |
| 37 | 新增: s := &Session{Manifest: manifest, Origin: origin, Context: life, Transport: transport} | |
| 38 | 新增: var once sync.Once | |
| 39 | 新增: s.close = func() error { | |
| 40 | 新增: once.Do(func() { cancel(); base.CloseIdleConnections() }) | |
| 41 | 新增: return nil | |
| 42 | 新增: } | |
| 43 | 新增: bound.invalidate = s.Close | |
| 44 | 新增: s.Client = &http.Client{Transport: transport, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("本机服务重定向已拒绝") }} | |
| 45 | 新增: context.AfterFunc(life, func() { _ = s.Close() }) | |
| 46 | 新增: return s, nil | |
| 47 | 新增:} | |
| 48 | 新增: | |
| 49 | 新增:type localViewTransport struct{ base *sessionTransport } | |
| 50 | 新增: | |
| 51 | 新增:func (t localViewTransport) RoundTrip(r *http.Request) (*http.Response, error) { | |
| 52 | 新增: // An older full controller can also route remote sessions. Pin the local | |
| 53 | 新增: // side of this hop even if some other caller changes that controller's mode. | |
| 54 | 新增: req := r.Clone(r.Context()) | |
| 55 | 新增: req.Header.Set("X-Cage-Connection", "local") | |
| 56 | 新增: return t.base.RoundTrip(req) | |
| 57 | 新增:} | |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "net" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "net/http/cookiejar" | |
| 8 | 新增: "net/url" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "testing" | |
| 11 | 新增: "time" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestLocalSessionMarksRefusedControllerLostButAllowsRequestCancellation(t *testing.T) { | |
| 15 | 新增: l, err := net.Listen("tcp4", "127.0.0.1:0") | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Fatal(err) | |
| 18 | 新增: } | |
| 19 | 新增: origin := "http://localhost:" + strconv.Itoa(l.Addr().(*net.TCPAddr).Port) | |
| 20 | 新增: u, _ := url.Parse(origin) | |
| 21 | 新增: jar, _ := cookiejar.New(nil) | |
| 22 | 新增: jar.SetCookies(u, []*http.Cookie{{Name: "private", Value: "test", Path: "/"}}) | |
| 23 | 新增: s, err := LocalSession(context.Background(), origin, PublicManifest{}, jar) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: l.Close() | |
| 26 | 新增: t.Fatal(err) | |
| 27 | 新增: } | |
| 28 | 新增: defer s.Close() | |
| 29 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 30 | 新增: cancel() | |
| 31 | 新增: req, _ := http.NewRequestWithContext(ctx, "GET", origin+"/api/account", nil) | |
| 32 | 新增: if _, err = s.Client.Do(req); err == nil || s.Context.Err() != nil { | |
| 33 | 新增: l.Close() | |
| 34 | 新增: t.Fatal("cancelled request invalidated view", err) | |
| 35 | 新增: } | |
| 36 | 新增: if err = l.Close(); err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: if _, err = s.Client.Get(origin + "/api/account"); err == nil { | |
| 40 | 新增: t.Fatal("closed controller accepted request") | |
| 41 | 新增: } | |
| 42 | 新增: select { | |
| 43 | 新增: case <-s.Context.Done(): | |
| 44 | 新增: case <-time.After(time.Second): | |
| 45 | 新增: t.Fatal("closed controller retained a ready view") | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -0,0 +1,176 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "maps" | |
| 7 | 新增: "sync" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:type Manager struct { | |
| 11 | 新增: mu sync.Mutex | |
| 12 | 新增: store *Store | |
| 13 | 新增: state ConnectionState | |
| 14 | 新增: session *Session | |
| 15 | 新增: cancel context.CancelFunc | |
| 16 | 新增: closed bool | |
| 17 | 新增: workers sync.WaitGroup | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func NewManager(store *Store) *Manager { | |
| 21 | 新增: return &Manager{store: store, state: ConnectionState{State: "disconnected"}} | |
| 22 | 新增:} | |
| 23 | 新增: | |
| 24 | 新增:func cloneState(state ConnectionState) ConnectionState { | |
| 25 | 新增: if state.HostKey != nil { | |
| 26 | 新增: key := *state.HostKey | |
| 27 | 新增: state.HostKey = &key | |
| 28 | 新增: } | |
| 29 | 新增: if state.Manifest != nil { | |
| 30 | 新增: manifest := *state.Manifest | |
| 31 | 新增: manifest.Capabilities = maps.Clone(manifest.Capabilities) | |
| 32 | 新增: state.Manifest = &manifest | |
| 33 | 新增: } | |
| 34 | 新增: return state | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func (m *Manager) Snapshot() ConnectionState { | |
| 38 | 新增: m.mu.Lock() | |
| 39 | 新增: defer m.mu.Unlock() | |
| 40 | 新增: return cloneState(m.state) | |
| 41 | 新增:} | |
| 42 | 新增: | |
| 43 | 新增:// Connect starts asynchronously. The caller can poll Snapshot. A previous | |
| 44 | 新增:// connection must be disconnected first; failure never switches host silently. | |
| 45 | 新增:func (m *Manager) Connect(hostID string, secrets ConnectSecrets) (ConnectionState, error) { | |
| 46 | 新增: p, err := m.store.Get(hostID) | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return ConnectionState{}, err | |
| 49 | 新增: } | |
| 50 | 新增: m.mu.Lock() | |
| 51 | 新增: defer m.mu.Unlock() | |
| 52 | 新增: if m.closed { | |
| 53 | 新增: return ConnectionState{}, failure("manager_closed", "远程连接服务已关闭") | |
| 54 | 新增: } | |
| 55 | 新增: if m.state.State == "connecting" || m.state.State == "connected" { | |
| 56 | 新增: return cloneState(m.state), failure("connection_active", "请先断开当前连接,再连接其他主机") | |
| 57 | 新增: } | |
| 58 | 新增: if m.cancel != nil { | |
| 59 | 新增: m.cancel() | |
| 60 | 新增: } | |
| 61 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 62 | 新增: m.cancel = cancel | |
| 63 | 新增: id := newID() | |
| 64 | 新增: m.state = ConnectionState{State: "connecting", ConnectionID: id, HostID: p.ID, Phase: "ssh_connect", Message: "正在连接远程主机"} | |
| 65 | 新增: private := ConnectSecrets{Deploy: secrets.Deploy, Passphrase: append([]byte(nil), secrets.Passphrase...)} | |
| 66 | 新增: m.workers.Add(1) | |
| 67 | 新增: go func() { | |
| 68 | 新增: defer m.workers.Done() | |
| 69 | 新增: m.run(ctx, p, id, private) | |
| 70 | 新增: }() | |
| 71 | 新增: return cloneState(m.state), nil | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 74 | 新增:func (m *Manager) run(ctx context.Context, p HostProfile, id string, secrets ConnectSecrets) { | |
| 75 | 新增: defer clear(secrets.Passphrase) | |
| 76 | 新增: session, err := connect(ctx, p, secrets, func(phase string) { | |
| 77 | 新增: m.mu.Lock() | |
| 78 | 新增: defer m.mu.Unlock() | |
| 79 | 新增: if m.state.ConnectionID == id && m.state.State == "connecting" { | |
| 80 | 新增: m.state.Phase = phase | |
| 81 | 新增: } | |
| 82 | 新增: }) | |
| 83 | 新增: m.mu.Lock() | |
| 84 | 新增: if m.state.ConnectionID != id || m.state.State != "connecting" || ctx.Err() != nil { | |
| 85 | 新增: m.mu.Unlock() | |
| 86 | 新增: if session != nil { | |
| 87 | 新增: session.Close() | |
| 88 | 新增: } | |
| 89 | 新增: return | |
| 90 | 新增: } | |
| 91 | 新增: if err != nil { | |
| 92 | 新增: m.state.State = "failed" | |
| 93 | 新增: m.state.Message = "远程连接未完成" | |
| 94 | 新增: m.state.ErrorCode = "connection_failed" | |
| 95 | 新增: var structured *Error | |
| 96 | 新增: if errors.As(err, &structured) { | |
| 97 | 新增: m.state.ErrorCode = structured.Code | |
| 98 | 新增: m.state.Message = structured.Message | |
| 99 | 新增: m.state.HostKey = structured.HostKey | |
| 100 | 新增: } | |
| 101 | 新增: if m.cancel != nil { | |
| 102 | 新增: m.cancel() | |
| 103 | 新增: m.cancel = nil | |
| 104 | 新增: } | |
| 105 | 新增: m.mu.Unlock() | |
| 106 | 新增: return | |
| 107 | 新增: } | |
| 108 | 新增: session.Ref = ConnectionRef{ID: id, HostID: p.ID, InstanceID: session.Manifest.InstanceID} | |
| 109 | 新增: m.session = session | |
| 110 | 新增: manifest := session.Manifest | |
| 111 | 新增: m.state = ConnectionState{State: "connected", ConnectionID: id, HostID: p.ID, InstanceID: manifest.InstanceID, Message: "已连接", Manifest: &manifest} | |
| 112 | 新增: m.mu.Unlock() | |
| 113 | 新增: <-session.Context.Done() | |
| 114 | 新增: m.mu.Lock() | |
| 115 | 新增: defer m.mu.Unlock() | |
| 116 | 新增: if m.state.ConnectionID == id && m.state.State == "connected" { | |
| 117 | 新增: m.session = nil | |
| 118 | 新增: m.state.State = "failed" | |
| 119 | 新增: m.state.ErrorCode = "connection_lost" | |
| 120 | 新增: m.state.Message = "远程连接已中断,请重新连接并核对云端任务" | |
| 121 | 新增: } | |
| 122 | 新增:} | |
| 123 | 新增: | |
| 124 | 新增:// Acquire refuses obsolete connection generations. Every runtime request and | |
| 125 | 新增:// native file operation must carry the ID captured by its originating view. | |
| 126 | 新增:func (m *Manager) Acquire(connectionID string) (*Session, error) { | |
| 127 | 新增: m.mu.Lock() | |
| 128 | 新增: defer m.mu.Unlock() | |
| 129 | 新增: if connectionID == "" || m.state.State != "connected" || m.state.ConnectionID != connectionID || m.session == nil || m.session.Context.Err() != nil { | |
| 130 | 新增: return nil, failure("connection_changed", "连接已断开或切换,请重新连接后重试") | |
| 131 | 新增: } | |
| 132 | 新增: return m.session, nil | |
| 133 | 新增:} | |
| 134 | 新增: | |
| 135 | 新增:func (m *Manager) Disconnect(connectionID string) error { | |
| 136 | 新增: m.mu.Lock() | |
| 137 | 新增: if m.state.State == "disconnected" { | |
| 138 | 新增: m.mu.Unlock() | |
| 139 | 新增: return nil | |
| 140 | 新增: } | |
| 141 | 新增: if connectionID == "" || m.state.ConnectionID != connectionID { | |
| 142 | 新增: m.mu.Unlock() | |
| 143 | 新增: return failure("connection_changed", "连接已切换,未断开其他连接") | |
| 144 | 新增: } | |
| 145 | 新增: cancel, session := m.cancel, m.session | |
| 146 | 新增: m.cancel = nil | |
| 147 | 新增: m.session = nil | |
| 148 | 新增: m.state = ConnectionState{State: "disconnected"} | |
| 149 | 新增: m.mu.Unlock() | |
| 150 | 新增: if cancel != nil { | |
| 151 | 新增: cancel() | |
| 152 | 新增: } | |
| 153 | 新增: if session != nil { | |
| 154 | 新增: return session.Close() | |
| 155 | 新增: } | |
| 156 | 新增: return nil | |
| 157 | 新增:} | |
| 158 | 新增: | |
| 159 | 新增:func (m *Manager) Close() error { | |
| 160 | 新增: m.mu.Lock() | |
| 161 | 新增: m.closed = true | |
| 162 | 新增: cancel, session := m.cancel, m.session | |
| 163 | 新增: m.cancel = nil | |
| 164 | 新增: m.session = nil | |
| 165 | 新增: m.state = ConnectionState{State: "disconnected"} | |
| 166 | 新增: m.mu.Unlock() | |
| 167 | 新增: if cancel != nil { | |
| 168 | 新增: cancel() | |
| 169 | 新增: } | |
| 170 | 新增: var err error | |
| 171 | 新增: if session != nil { | |
| 172 | 新增: err = session.Close() | |
| 173 | 新增: } | |
| 174 | 新增: m.workers.Wait() | |
| 175 | 新增: return err | |
| 176 | 新增:} | |
| @@ -0,0 +1,233 @@ | ||
| 1 | 新增:package remotehost | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/rand" | |
| 5 | 新增: "encoding/base64" | |
| 6 | 新增: "encoding/hex" | |
| 7 | 新增: "encoding/json" | |
| 8 | 新增: "errors" | |
| 9 | 新增: "io" | |
| 10 | 新增: "net" | |
| 11 | 新增: "os" | |
| 12 | 新增: "path" | |
| 13 | 新增: "path/filepath" | |
| 14 | 新增: "regexp" | |
| 15 | 新增: "strings" | |
| 16 | 新增: "sync" | |
| 17 | 新增: | |
| 18 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 19 | 新增:) | |
| 20 | 新增: | |
| 21 | 新增:var uuidPattern = regexp.MustCompile(`^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$`) | |
| 22 | 新增:var instancePattern = regexp.MustCompile(`^[a-f0-9]{64}$`) | |
| 23 | 新增:var hostnamePattern = regexp.MustCompile(`^[A-Za-z0-9](?:[A-Za-z0-9.-]*[A-Za-z0-9])?$`) | |
| 24 | 新增:var storeLocks sync.Map | |
| 25 | 新增: | |
| 26 | 新增:type Store struct { | |
| 27 | 新增: profile string | |
| 28 | 新增: mu *sync.Mutex | |
| 29 | 新增:} | |
| 30 | 新增:type storedHosts struct { | |
| 31 | 新增: Version int `json:"version"` | |
| 32 | 新增: Hosts []HostProfile `json:"hosts"` | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func NewStore(profileDir string) *Store { | |
| 36 | 新增: absolute, err := filepath.Abs(profileDir) | |
| 37 | 新增: if err == nil { | |
| 38 | 新增: profileDir = absolute | |
| 39 | 新增: } | |
| 40 | 新增: lock, _ := storeLocks.LoadOrStore(filepath.Clean(profileDir), &sync.Mutex{}) | |
| 41 | 新增: return &Store{profile: profileDir, mu: lock.(*sync.Mutex)} | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:func newID() string { | |
| 45 | 新增: var raw [16]byte | |
| 46 | 新增: if _, err := rand.Read(raw[:]); err != nil { | |
| 47 | 新增: panic(err) | |
| 48 | 新增: } | |
| 49 | 新增: raw[6] = (raw[6] & 15) | 64 | |
| 50 | 新增: raw[8] = (raw[8] & 63) | 128 | |
| 51 | 新增: s := hex.EncodeToString(raw[:]) | |
| 52 | 新增: return s[:8] + "-" + s[8:12] + "-" + s[12:16] + "-" + s[16:20] + "-" + s[20:] | |
| 53 | 新增:} | |
| 54 | 新增: | |
| 55 | 新增:func hasControl(s string) bool { | |
| 56 | 新增: return strings.ContainsFunc(s, func(r rune) bool { return r < 32 || r == 127 }) | |
| 57 | 新增:} | |
| 58 | 新增: | |
| 59 | 新增:func normalizeProfile(p HostProfile) (HostProfile, error) { | |
| 60 | 新增: p.Name = strings.TrimSpace(p.Name) | |
| 61 | 新增: p.Host = strings.TrimSpace(p.Host) | |
| 62 | 新增: p.User = strings.TrimSpace(p.User) | |
| 63 | 新增: if p.Port == 0 { | |
| 64 | 新增: p.Port = 22 | |
| 65 | 新增: } | |
| 66 | 新增: if p.Executable == "" { | |
| 67 | 新增: p.Executable = "cage" | |
| 68 | 新增: } | |
| 69 | 新增: if p.ID != "" && !uuidPattern.MatchString(p.ID) { | |
| 70 | 新增: return p, failure("invalid_profile", "主机标识无效") | |
| 71 | 新增: } | |
| 72 | 新增: if p.Name == "" || len(p.Name) > 200 || hasControl(p.Name) { | |
| 73 | 新增: return p, failure("invalid_profile", "请填写有效的主机名称") | |
| 74 | 新增: } | |
| 75 | 新增: if p.Host == "" || len(p.Host) > 253 || (net.ParseIP(p.Host) == nil && !hostnamePattern.MatchString(p.Host)) || strings.Contains(p.Host, "..") { | |
| 76 | 新增: return p, failure("invalid_profile", "请填写主机名或 IP 地址") | |
| 77 | 新增: } | |
| 78 | 新增: if p.Port < 1 || p.Port > 65535 || p.User == "" || len(p.User) > 128 || hasControl(p.User) { | |
| 79 | 新增: return p, failure("invalid_profile", "SSH 用户名或端口无效") | |
| 80 | 新增: } | |
| 81 | 新增: if p.Auth.Kind != "key_file" && p.Auth.Kind != "agent" { | |
| 82 | 新增: return p, failure("invalid_profile", "请选择 SSH 密钥文件或本机 SSH agent") | |
| 83 | 新增: } | |
| 84 | 新增: if p.Auth.Kind == "key_file" && (!filepath.IsAbs(p.Auth.IdentityFile) || hasControl(p.Auth.IdentityFile)) { | |
| 85 | 新增: return p, failure("invalid_profile", "SSH 密钥文件需要使用本机绝对路径") | |
| 86 | 新增: } | |
| 87 | 新增: if p.Auth.Kind == "agent" { | |
| 88 | 新增: p.Auth.IdentityFile = "" | |
| 89 | 新增: } | |
| 90 | 新增: if (p.Executable != "cage" && !path.IsAbs(p.Executable)) || hasControl(p.Executable) || len(p.Executable) > 4096 { | |
| 91 | 新增: return p, failure("invalid_profile", "云端 Cage 程序需要使用绝对路径或 cage") | |
| 92 | 新增: } | |
| 93 | 新增: if (p.ConfigPath != "" && !path.IsAbs(p.ConfigPath)) || hasControl(p.ConfigPath) || len(p.ConfigPath) > 4096 { | |
| 94 | 新增: return p, failure("invalid_profile", "云端配置文件需要使用绝对路径") | |
| 95 | 新增: } | |
| 96 | 新增: if p.HostKey != nil { | |
| 97 | 新增: key := *p.HostKey | |
| 98 | 新增: raw, err := base64.RawStdEncoding.DecodeString(strings.TrimPrefix(key.Fingerprint, "SHA256:")) | |
| 99 | 新增: if key.Algorithm == "" || len(key.Algorithm) > 128 || hasControl(key.Algorithm) || !strings.HasPrefix(key.Fingerprint, "SHA256:") || err != nil || len(raw) != 32 { | |
| 100 | 新增: return p, failure("invalid_profile", "SSH 主机密钥指纹无效") | |
| 101 | 新增: } | |
| 102 | 新增: p.HostKey = &key | |
| 103 | 新增: } | |
| 104 | 新增: return p, nil | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:func (s *Store) read() ([]HostProfile, error) { | |
| 108 | 新增: filename := filepath.Join(s.profile, "remote-hosts.json") | |
| 109 | 新增: if err := host.CheckPrivateFile(filename); err != nil { | |
| 110 | 新增: if os.IsNotExist(err) { | |
| 111 | 新增: return []HostProfile{}, nil | |
| 112 | 新增: } | |
| 113 | 新增: return nil, failure("profile_permissions", "远程主机配置权限不安全") | |
| 114 | 新增: } | |
| 115 | 新增: f, err := os.Open(filename) | |
| 116 | 新增: if err != nil { | |
| 117 | 新增: return nil, failure("profile_read", "无法读取远程主机配置") | |
| 118 | 新增: } | |
| 119 | 新增: defer f.Close() | |
| 120 | 新增: info, err := f.Stat() | |
| 121 | 新增: if err != nil || info.Size() > 1<<20 { | |
| 122 | 新增: return nil, failure("profile_invalid", "远程主机配置过大或无法读取") | |
| 123 | 新增: } | |
| 124 | 新增: var data storedHosts | |
| 125 | 新增: decoder := json.NewDecoder(io.LimitReader(f, 1<<20)) | |
| 126 | 新增: decoder.DisallowUnknownFields() | |
| 127 | 新增: if decoder.Decode(&data) != nil || data.Version != 1 || len(data.Hosts) > 100 { | |
| 128 | 新增: return nil, failure("profile_invalid", "远程主机配置损坏,现有文件未修改") | |
| 129 | 新增: } | |
| 130 | 新增: var extra any | |
| 131 | 新增: if decoder.Decode(&extra) != io.EOF { | |
| 132 | 新增: return nil, failure("profile_invalid", "远程主机配置内容无效") | |
| 133 | 新增: } | |
| 134 | 新增: seen := map[string]bool{} | |
| 135 | 新增: for i, p := range data.Hosts { | |
| 136 | 新增: normalized, err := normalizeProfile(p) | |
| 137 | 新增: if err != nil || p.ID == "" || seen[p.ID] { | |
| 138 | 新增: return nil, failure("profile_invalid", "远程主机配置内容无效") | |
| 139 | 新增: } | |
| 140 | 新增: data.Hosts[i] = normalized | |
| 141 | 新增: seen[p.ID] = true | |
| 142 | 新增: } | |
| 143 | 新增: if data.Hosts == nil { | |
| 144 | 新增: data.Hosts = []HostProfile{} | |
| 145 | 新增: } | |
| 146 | 新增: return data.Hosts, nil | |
| 147 | 新增:} | |
| 148 | 新增: | |
| 149 | 新增:func (s *Store) write(profiles []HostProfile) error { | |
| 150 | 新增: if err := host.EnsurePrivateDir(s.profile); err != nil { | |
| 151 | 新增: return failure("profile_permissions", "无法创建私有远程主机配置目录") | |
| 152 | 新增: } | |
| 153 | 新增: file, err := os.CreateTemp(s.profile, ".remote-hosts-*") | |
| 154 | 新增: if err != nil { | |
| 155 | 新增: return failure("profile_write", "无法保存远程主机配置") | |
| 156 | 新增: } | |
| 157 | 新增: tmp := file.Name() | |
| 158 | 新增: defer os.Remove(tmp) | |
| 159 | 新增: if err = host.ProtectFile(tmp); err == nil { | |
| 160 | 新增: err = json.NewEncoder(file).Encode(storedHosts{1, profiles}) | |
| 161 | 新增: } | |
| 162 | 新增: if err == nil { | |
| 163 | 新增: err = file.Sync() | |
| 164 | 新增: } | |
| 165 | 新增: err = errors.Join(err, file.Close()) | |
| 166 | 新增: if err == nil { | |
| 167 | 新增: err = os.Rename(tmp, filepath.Join(s.profile, "remote-hosts.json")) | |
| 168 | 新增: } | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: return failure("profile_write", "远程主机配置未能保存,现有文件保持不变") | |
| 171 | 新增: } | |
| 172 | 新增: return nil | |
| 173 | 新增:} | |
| 174 | 新增: | |
| 175 | 新增:func (s *Store) List() ([]HostProfile, error) { s.mu.Lock(); defer s.mu.Unlock(); return s.read() } | |
| 176 | 新增:func (s *Store) Get(id string) (HostProfile, error) { | |
| 177 | 新增: profiles, err := s.List() | |
| 178 | 新增: if err != nil { | |
| 179 | 新增: return HostProfile{}, err | |
| 180 | 新增: } | |
| 181 | 新增: for _, p := range profiles { | |
| 182 | 新增: if p.ID == id { | |
| 183 | 新增: return p, nil | |
| 184 | 新增: } | |
| 185 | 新增: } | |
| 186 | 新增: return HostProfile{}, failure("host_not_found", "远程主机配置已不存在") | |
| 187 | 新增:} | |
| 188 | 新增:func (s *Store) Upsert(profile HostProfile) (HostProfile, error) { | |
| 189 | 新增: profile, err := normalizeProfile(profile) | |
| 190 | 新增: if err != nil { | |
| 191 | 新增: return profile, err | |
| 192 | 新增: } | |
| 193 | 新增: s.mu.Lock() | |
| 194 | 新增: defer s.mu.Unlock() | |
| 195 | 新增: profiles, err := s.read() | |
| 196 | 新增: if err != nil { | |
| 197 | 新增: return profile, err | |
| 198 | 新增: } | |
| 199 | 新增: if profile.ID == "" { | |
| 200 | 新增: if len(profiles) >= 100 { | |
| 201 | 新增: return profile, failure("profile_limit", "最多保存 100 台远程主机") | |
| 202 | 新增: } | |
| 203 | 新增: profile.ID = newID() | |
| 204 | 新增: profiles = append(profiles, profile) | |
| 205 | 新增: } else { | |
| 206 | 新增: found := false | |
| 207 | 新增: for i, p := range profiles { | |
| 208 | 新增: if p.ID == profile.ID { | |
| 209 | 新增: profiles[i] = profile | |
| 210 | 新增: found = true | |
| 211 | 新增: break | |
| 212 | 新增: } | |
| 213 | 新增: } | |
| 214 | 新增: if !found { | |
| 215 | 新增: return profile, failure("host_not_found", "远程主机配置已不存在") | |
| 216 | 新增: } | |
| 217 | 新增: } | |
| 218 | 新增: return profile, s.write(profiles) | |
| 219 | 新增:} | |
| 220 | 新增:func (s *Store) Delete(id string) error { | |
| 221 | 新增: s.mu.Lock() | |
| 222 | 新增: defer s.mu.Unlock() | |
| 223 | 新增: profiles, err := s.read() | |
| 224 | 新增: if err != nil { | |
| 225 | 新增: return err | |
| 226 | 新增: } | |
| 227 | 新增: for i, p := range profiles { | |
| 228 | 新增: if p.ID == id { | |
| 229 | 新增: return s.write(append(profiles[:i], profiles[i+1:]...)) | |
| 230 | 新增: } | |
| 231 | 新增: } | |
| 232 | 新增: return failure("host_not_found", "远程主机配置已不存在") | |
| 233 | 新增:} | |
| @@ -0,0 +1,114 @@ | ||
| 1 | 新增:// Package remotehost owns saved remote hosts and authenticated connections. | |
| 2 | 新增:// It does not execute workloads, stop remote services, or expose SSH credentials | |
| 3 | 新增:// to the workbench page. | |
| 4 | 新增:package remotehost | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "context" | |
| 8 | 新增: "net/http" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:const APIProtocol = 1 | |
| 12 | 新增: | |
| 13 | 新增:type AuthConfig struct { | |
| 14 | 新增: Kind string `json:"kind"` | |
| 15 | 新增: IdentityFile string `json:"identity_file,omitempty"` | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:type HostKey struct { | |
| 19 | 新增: Algorithm string `json:"algorithm"` | |
| 20 | 新增: Fingerprint string `json:"fingerprint"` | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:type HostProfile struct { | |
| 24 | 新增: ID string `json:"id"` | |
| 25 | 新增: Name string `json:"name"` | |
| 26 | 新增: Host string `json:"host"` | |
| 27 | 新增: Port int `json:"port"` | |
| 28 | 新增: User string `json:"user"` | |
| 29 | 新增: Auth AuthConfig `json:"auth"` | |
| 30 | 新增: HostKey *HostKey `json:"host_key,omitempty"` | |
| 31 | 新增: Executable string `json:"executable,omitempty"` | |
| 32 | 新增: ConfigPath string `json:"config_path,omitempty"` | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:type PublicManifest struct { | |
| 36 | 新增: APIProtocol int `json:"api_protocol"` | |
| 37 | 新增: InstanceID string `json:"instance_id"` | |
| 38 | 新增: Version string `json:"version"` | |
| 39 | 新增: Platform string `json:"platform"` | |
| 40 | 新增: Runtime string `json:"runtime"` | |
| 41 | 新增: Capabilities map[string]bool `json:"capabilities"` | |
| 42 | 新增:} | |
| 43 | 新增: | |
| 44 | 新增:// ServerManifest is the private SSH command response. Never return it from a | |
| 45 | 新增:// browser API: Ticket is consumed only inside the connector. | |
| 46 | 新增:type ServerManifest struct { | |
| 47 | 新增: APIProtocol int `json:"api_protocol"` | |
| 48 | 新增: InstanceID string `json:"instance_id"` | |
| 49 | 新增: Version string `json:"version"` | |
| 50 | 新增: Platform string `json:"platform"` | |
| 51 | 新增: Runtime string `json:"runtime"` | |
| 52 | 新增: Capabilities map[string]bool `json:"capabilities"` | |
| 53 | 新增: Origin string `json:"origin"` | |
| 54 | 新增: Ticket string `json:"ticket"` | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func (m ServerManifest) Public() PublicManifest { | |
| 58 | 新增: return PublicManifest{m.APIProtocol, m.InstanceID, m.Version, m.Platform, m.Runtime, m.Capabilities} | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:// ConnectSecrets are never serialized or persisted. Connect copies the | |
| 62 | 新增:// passphrase before returning and clears that copy after SSH authentication. | |
| 63 | 新增:type ConnectSecrets struct { | |
| 64 | 新增: Deploy bool `json:"-"` | |
| 65 | 新增: Passphrase []byte `json:"-"` | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:type ConnectionRef struct { | |
| 69 | 新增: ID string `json:"connection_id"` | |
| 70 | 新增: HostID string `json:"host_id"` | |
| 71 | 新增: InstanceID string `json:"instance_id"` | |
| 72 | 新增:} | |
| 73 | 新增: | |
| 74 | 新增:type ConnectionState struct { | |
| 75 | 新增: State string `json:"state"` | |
| 76 | 新增: ConnectionID string `json:"connection_id,omitempty"` | |
| 77 | 新增: HostID string `json:"host_id,omitempty"` | |
| 78 | 新增: InstanceID string `json:"instance_id,omitempty"` | |
| 79 | 新增: Phase string `json:"phase,omitempty"` | |
| 80 | 新增: Message string `json:"message,omitempty"` | |
| 81 | 新增: ErrorCode string `json:"error_code,omitempty"` | |
| 82 | 新增: HostKey *HostKey `json:"host_key,omitempty"` | |
| 83 | 新增: Manifest *PublicManifest `json:"manifest,omitempty"` | |
| 84 | 新增:} | |
| 85 | 新增: | |
| 86 | 新增:type Error struct { | |
| 87 | 新增: Code string `json:"code"` | |
| 88 | 新增: Message string `json:"message"` | |
| 89 | 新增: HostKey *HostKey `json:"host_key,omitempty"` | |
| 90 | 新增:} | |
| 91 | 新增: | |
| 92 | 新增:func (e *Error) Error() string { return e.Message } | |
| 93 | 新增: | |
| 94 | 新增:func failure(code, message string) error { return &Error{Code: code, Message: message} } | |
| 95 | 新增: | |
| 96 | 新增:// Session remains pinned to one authenticated remote instance. Transport is | |
| 97 | 新增:// suitable for HTTP reverse proxies, including WebSocket upgrades and SSE. | |
| 98 | 新增:// Its URL must use Origin; it injects the private upstream session cookie. | |
| 99 | 新增:type Session struct { | |
| 100 | 新增: Ref ConnectionRef | |
| 101 | 新增: Manifest PublicManifest | |
| 102 | 新增: Client *http.Client | |
| 103 | 新增: Transport http.RoundTripper | |
| 104 | 新增: Context context.Context | |
| 105 | 新增: Origin string | |
| 106 | 新增: close func() error | |
| 107 | 新增:} | |
| 108 | 新增: | |
| 109 | 新增:func (s *Session) Close() error { | |
| 110 | 新增: if s == nil || s.close == nil { | |
| 111 | 新增: return nil | |
| 112 | 新增: } | |
| 113 | 新增: return s.close() | |
| 114 | 新增:} | |
| @@ -35,6 +35,7 @@ import ( | ||
| 35 | 35 | "github.com/lima-vm/lima/v2/pkg/sshutil" |
| 36 | 36 | "github.com/lima-vm/lima/v2/pkg/store" |
| 37 | 37 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 38 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 38 | 39 | |
| 39 | 40 | "github.com/sylvinus/agent-vm/internal/cage" |
| 40 | 41 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| @@ -56,23 +57,8 @@ type Lima struct { | ||
| 56 | 57 | // home (UNIX_PATH_MAX: 104 bytes on macOS), and Lima's 76 at most. Lima |
| 57 | 58 | // resolves the home's symlinks: so does this, as far as it exists. |
| 58 | 59 | func MaxName(home string) int { |
| 59 | 删除: real, rest := home, "" | |
| 60 | 删除: for { | |
| 61 | 删除: if p, err := filepath.EvalSymlinks(real); err == nil { | |
| 62 | 删除: real = filepath.Join(p, rest) | |
| 63 | 删除: break | |
| 64 | 删除: } | |
| 65 | 删除: parent := filepath.Dir(real) | |
| 66 | 删除: if parent == real { | |
| 67 | 删除: real = home | |
| 68 | 删除: break | |
| 69 | 删除: } | |
| 70 | 删除: rest = filepath.Join(filepath.Base(real), rest) | |
| 71 | 删除: real = parent | |
| 72 | 删除: } | |
| 73 | 删除: // <home>/<name>/<socket>, shorter than UnixPathMax (its NUL). | |
| 74 | 删除: n := osutil.UnixPathMax - 1 - len(real) - len("/") - len("/"+filenames.LongestSock) | |
| 75 | 删除: return min(n, 76) | |
| 60 | 新增: stable := os.Getenv("CAGE_LOGICAL_LIMA_HOME") | |
| 61 | 新增: return int(vmname.HomeLimit(home, stable != "" && filepath.Clean(home) == filepath.Clean(stable))) | |
| 76 | 62 | } |
| 77 | 63 | |
| 78 | 64 | // NewLima keeps its VMs in home (LIMA_HOME), and writes Lima's guest agent |
| @@ -332,6 +318,16 @@ func (l *Lima) Create(ctx context.Context, name, template string, s Settings, lo | ||
| 332 | 318 | if err != nil { |
| 333 | 319 | return err |
| 334 | 320 | } |
| 321 | 新增: if template == "template:debian-13" { | |
| 322 | 新增: images, err := cageDebianImages(tmpl.Config.Images) | |
| 323 | 新增: if err != nil { | |
| 324 | 新增: return err | |
| 325 | 新增: } | |
| 326 | 新增: e = append(e, ".images = "+string(images)) | |
| 327 | 新增: // cloud-init rewrites Debian's mirror list after bootcmd. | |
| 328 | 新增: // Configure it immediately before Lima installs dependencies. | |
| 329 | 新增: e = append(e, `.provision += [{"mode": "dependency", "script": `+strconv.Quote(cage.DebianMirrorsScript)+`}]`) | |
| 330 | 新增: } | |
| 335 | 331 | tz, _ := json.Marshal(cfg.Timezone) |
| 336 | 332 | e = append(e, ".propagateProxyEnv = false", `.env = {"http_proxy":"","https_proxy":"","ftp_proxy":"","no_proxy":"","HTTP_PROXY":"","HTTPS_PROXY":"","FTP_PROXY":"","NO_PROXY":"","ALL_PROXY":"","all_proxy":""}`, ".timezone = "+string(tz), ".user.name = \"cage\"", ".user.home = \"/home/cage\"", ".user.uid = 1000") |
| 337 | 333 | } |
| @@ -345,6 +341,28 @@ func (l *Lima) Create(ctx context.Context, name, template string, s Settings, lo | ||
| 345 | 341 | }) |
| 346 | 342 | } |
| 347 | 343 | |
| 344 | 新增:// All three locations must supply the exact release pinned by the embedded | |
| 345 | 新增:// template. In particular, never accept an unpinned daily image on fallback. | |
| 346 | 新增:func cageDebianImages(images []limatype.Image) ([]byte, error) { | |
| 347 | 新增: const upstream = "https://cloud.debian.org/images/cloud/" | |
| 348 | 新增: var candidates []limatype.Image | |
| 349 | 新增: for _, img := range images { | |
| 350 | 新增: suffix, ok := strings.CutPrefix(img.Location, upstream) | |
| 351 | 新增: if !ok || img.Variant != "genericcloud" || img.Digest.Validate() != nil || img.Digest.Algorithm() != "sha512" { | |
| 352 | 新增: continue | |
| 353 | 新增: } | |
| 354 | 新增: for _, base := range []string{"https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/", upstream} { | |
| 355 | 新增: candidate := img | |
| 356 | 新增: candidate.Location = base + suffix | |
| 357 | 新增: candidates = append(candidates, candidate) | |
| 358 | 新增: } | |
| 359 | 新增: } | |
| 360 | 新增: if len(candidates) == 0 { | |
| 361 | 新增: return nil, errors.New("embedded Debian template contains no pinned cloud image") | |
| 362 | 新增: } | |
| 363 | 新增: return json.Marshal(candidates) | |
| 364 | 新增:} | |
| 365 | 新增: | |
| 348 | 366 | func (l *Lima) Clone(ctx context.Context, from, to string) error { |
| 349 | 367 | inst, err := l.inspect(ctx, from) |
| 350 | 368 | if err != nil { |
| @@ -2,6 +2,7 @@ package vm | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 新增: "encoding/json" | |
| 5 | 6 | "errors" |
| 6 | 7 | "io" |
| 7 | 8 | "os" |
| @@ -22,6 +23,7 @@ import ( | ||
| 22 | 23 | "github.com/lima-vm/lima/v2/pkg/limayaml" |
| 23 | 24 | "github.com/lima-vm/lima/v2/pkg/portfwd" |
| 24 | 25 | |
| 26 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 25 | 27 | "github.com/sylvinus/agent-vm/internal/limaembed" |
| 26 | 28 | "github.com/sylvinus/agent-vm/internal/paths" |
| 27 | 29 | ) |
| @@ -43,6 +45,53 @@ func newTestLima(t *testing.T) *Lima { | ||
| 43 | 45 | return l |
| 44 | 46 | } |
| 45 | 47 | |
| 48 | 新增:func TestCageDebianMirrors(t *testing.T) { | |
| 49 | 新增: l := newTestLima(t) | |
| 50 | 新增: config := filepath.Join(t.TempDir(), "config.json") | |
| 51 | 新增: data, err := json.Marshal(cage.DefaultConfig()) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: if err := os.WriteFile(config, data, 0600); err != nil { | |
| 56 | 新增: t.Fatal(err) | |
| 57 | 新增: } | |
| 58 | 新增: t.Setenv(cage.ConfigEnv, config) | |
| 59 | 新增: none := []Mount{} | |
| 60 | 新增: ctx := context.Background() | |
| 61 | 新增: if err := l.Create(ctx, "base", "template:debian-13", Settings{Mounts: &none}, io.Discard); err != nil { | |
| 62 | 新增: t.Fatal(err) | |
| 63 | 新增: } | |
| 64 | 新增: instance, err := l.inspect(ctx, "base") | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: t.Fatal(err) | |
| 67 | 新增: } | |
| 68 | 新增: earlyAPT := false | |
| 69 | 新增: for _, step := range instance.Config.Provision { | |
| 70 | 新增: if step.Mode == limatype.ProvisionModeDependency && step.Script != nil && *step.Script == cage.DebianMirrorsScript { | |
| 71 | 新增: earlyAPT = true | |
| 72 | 新增: } | |
| 73 | 新增: } | |
| 74 | 新增: if !earlyAPT { | |
| 75 | 新增: t.Fatal("cloud-init could fetch packages before Debian mirrors are set") | |
| 76 | 新增: } | |
| 77 | 新增: for _, arch := range []limatype.Arch{"x86_64", "aarch64"} { | |
| 78 | 新增: var images []limatype.Image | |
| 79 | 新增: for _, image := range instance.Config.Images { | |
| 80 | 新增: if image.Arch == arch { | |
| 81 | 新增: images = append(images, image) | |
| 82 | 新增: } | |
| 83 | 新增: } | |
| 84 | 新增: if len(images) != 3 { | |
| 85 | 新增: t.Fatalf("%s: expected two mirrors and one upstream, got %+v", arch, images) | |
| 86 | 新增: } | |
| 87 | 新增: for i, base := range []string{"https://mirrors.nju.edu.cn/debian-cdimage/cloud/", "https://mirrors.ustc.edu.cn/debian-cdimage/cloud/", "https://cloud.debian.org/images/cloud/"} { | |
| 88 | 新增: if !strings.HasPrefix(images[i].Location, base) || images[i].Digest != images[2].Digest || images[i].Digest.Validate() != nil { | |
| 89 | 新增: t.Fatalf("unexpected image or missing pin: %+v", images[i]) | |
| 90 | 新增: } | |
| 91 | 新增: } | |
| 92 | 新增: } | |
| 93 | 新增:} | |
| 94 | 新增: | |
| 46 | 95 | // What agent-vm does to a VM without booting it: create, edit its shares, |
| 47 | 96 | // clone, delete. |
| 48 | 97 | func TestLimaLifecycle(t *testing.T) { |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:package vm | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: "testing" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype/dirnames" | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestStorageMoveKeepsLimaIdentityAndSocketPaths(t *testing.T) { | |
| 15 | 新增: root, err := filepath.EvalSymlinks(t.TempDir()) | |
| 16 | 新增: if err != nil { | |
| 17 | 新增: t.Fatal(err) | |
| 18 | 新增: } | |
| 19 | 新增: profile := filepath.Join(root, "profile") | |
| 20 | 新增: home := filepath.Join(profile, "state", "lima") | |
| 21 | 新增: if err := os.MkdirAll(filepath.Join(home, "guest"), 0700); err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: t.Setenv("LIMA_HOME", home) | |
| 25 | 新增: t.Setenv("CAGE_LOGICAL_LIMA_HOME", "") | |
| 26 | 新增: before, err := dirnames.InstanceDir("guest") | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: limit := MaxName(home) | |
| 31 | 新增: expected, err := cage.GetStorageLocation(profile) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: t.Fatal(err) | |
| 34 | 新增: } | |
| 35 | 新增: target := filepath.Join(root, strings.Repeat("physical-path-", 4)) | |
| 36 | 新增: if _, err := cage.MoveStorage(context.Background(), profile, target, expected, nil); err != nil { | |
| 37 | 新增: t.Fatal(err) | |
| 38 | 新增: } | |
| 39 | 新增: t.Setenv("CAGE_LOGICAL_LIMA_HOME", home) | |
| 40 | 新增: after, err := dirnames.InstanceDir("guest") | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: t.Fatal(err) | |
| 43 | 新增: } | |
| 44 | 新增: if after != before || MaxName(home) != limit { | |
| 45 | 新增: t.Fatalf("migration changed the instance path/name limit: before %s/%d, after %s/%d", before, limit, after, MaxName(home)) | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -7,6 +7,8 @@ import ( | ||
| 7 | 7 | "context" |
| 8 | 8 | "errors" |
| 9 | 9 | "io" |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/mounts/spec" | |
| 10 | 12 | ) |
| 11 | 13 | |
| 12 | 14 | // ErrNotFound is returned for a VM that does not exist. |
| @@ -68,22 +70,10 @@ type Instance struct { | ||
| 68 | 70 | } |
| 69 | 71 | |
| 70 | 72 | // Mount is a host folder shared with the guest. |
| 71 | 删除:type Mount struct { | |
| 72 | 删除: Location string `json:"location"` // on the host | |
| 73 | 删除: MountPoint string `json:"mountPoint,omitempty"` // in the guest; Location's spelling when empty | |
| 74 | 删除: Writable bool `json:"writable"` | |
| 75 | 删除: SSHFS *SSHFS `json:"sshfs,omitempty"` | |
| 76 | 删除:} | |
| 73 | 新增:type Mount = spec.Mount | |
| 77 | 74 | |
| 78 | 75 | // SSHFS options of a reverse-sshfs share. |
| 79 | 删除:type SSHFS struct { | |
| 80 | 删除: SFTPDriver string `json:"sftpDriver,omitempty"` | |
| 81 | 删除: // Cache is sshfs's own; nil for the backend's default. | |
| 82 | 删除: Cache *bool `json:"cache,omitempty"` | |
| 83 | 删除: // ReadonlyNames are read-only at any depth under the share, whatever | |
| 84 | 删除: // the guest does: .git and the like. | |
| 85 | 删除: ReadonlyNames []string `json:"readonlyNames,omitempty"` | |
| 86 | 删除:} | |
| 76 | 新增:type SSHFS = spec.SSHFS | |
| 87 | 77 | |
| 88 | 78 | // ReverseSSHFS is the mount type whose shares the host serves over SFTP, |
| 89 | 79 | // which is where readonlyNames are enforced. |
| @@ -0,0 +1,30 @@ | ||
| 1 | 新增:package vmname | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "path/filepath" | |
| 5 | 新增: | |
| 6 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype/filenames" | |
| 7 | 新增: "github.com/lima-vm/lima/v2/pkg/osutil" | |
| 8 | 新增:) | |
| 9 | 新增: | |
| 10 | 新增:// HomeLimit fits the longest Lima socket in this profile's UNIX socket path. | |
| 11 | 新增:// A Cage-managed storage link keeps the original logical home after migration. | |
| 12 | 新增:func HomeLimit(home string, logical bool) Limit { | |
| 13 | 新增: real, rest := home, "" | |
| 14 | 新增: for !logical { | |
| 15 | 新增: if p, err := filepath.EvalSymlinks(real); err == nil { | |
| 16 | 新增: real = filepath.Join(p, rest) | |
| 17 | 新增: break | |
| 18 | 新增: } | |
| 19 | 新增: parent := filepath.Dir(real) | |
| 20 | 新增: if parent == real { | |
| 21 | 新增: real = home | |
| 22 | 新增: break | |
| 23 | 新增: } | |
| 24 | 新增: rest = filepath.Join(filepath.Base(real), rest) | |
| 25 | 新增: real = parent | |
| 26 | 新增: } | |
| 27 | 新增: // <home>/<name>/<socket>, shorter than UnixPathMax (its NUL). | |
| 28 | 新增: n := osutil.UnixPathMax - 1 - len(real) - len("/") - len("/"+filenames.LongestSock) | |
| 29 | 新增: return Limit(max(1, min(n, 76))) | |
| 30 | 新增:} | |
| @@ -27,10 +27,9 @@ const Template = "base" | ||
| 27 | 27 | // The names Scratch makes. |
| 28 | 28 | var scratchRe = regexp.MustCompile(`^[A-Za-z0-9-]+-scratch-[0-9a-f]{8}$`) |
| 29 | 29 | |
| 30 | 删除:// MaxLen is the longest name a VM may have: Lima's 76 characters, or less | |
| 31 | 删除:// where its sockets would not fit under the Lima home (set from it, see | |
| 32 | 删除:// vm.MaxName). Names longer are cut in their folder part (fit). | |
| 33 | 删除:var MaxLen = 76 | |
| 30 | 新增:// Limit is the instance-name length supported by one Lima home. Zero | |
| 31 | 新增:// selects Lima's normal 76-byte cap. | |
| 32 | 新增:type Limit int | |
| 34 | 33 | |
| 35 | 34 | // Name is the VM of the project dir, spelled as `pwd` spells it: the name |
| 36 | 35 | // hashes that string, so /tmp/ and /tmp give one VM and a symlink to the |
| @@ -38,19 +37,24 @@ var MaxLen = 76 | ||
| 38 | 37 | // other characters than ASCII letters and digits made one "-" ("project" |
| 39 | 38 | // when nothing is left), and hash 8 hex digits of the path's SHA-256. On |
| 40 | 39 | // Windows, the path as Git Bash spelled it (/c/...), as 0.2 hashed it. |
| 41 | 删除:func Name(dir string) string { | |
| 40 | 新增:func Name(dir string) string { return Limit(0).Name(dir) } | |
| 41 | 新增: | |
| 42 | 新增:func (limit Limit) Name(dir string) string { | |
| 42 | 43 | dir = paths.Guest(dir) |
| 43 | 44 | sum := sha256.Sum256([]byte(dir)) |
| 44 | 45 | b := base(dir, 0) |
| 45 | 46 | if b == "" { |
| 46 | 47 | b = "project" |
| 47 | 48 | } |
| 48 | 删除: return fit(b, "-"+hex.EncodeToString(sum[:])[:8]) | |
| 49 | 新增: return limit.fit(b, "-"+hex.EncodeToString(sum[:])[:8]) | |
| 49 | 50 | } |
| 50 | 51 | |
| 51 | 52 | // fit is b+suffix, b cut to keep it within MaxLen, never to nothing. |
| 52 | 删除:func fit(b, suffix string) string { | |
| 53 | 删除: if n := MaxLen - len(suffix); len(b) > n { | |
| 53 | 新增:func (limit Limit) fit(b, suffix string) string { | |
| 54 | 新增: if limit == 0 { | |
| 55 | 新增: limit = 76 | |
| 56 | 新增: } | |
| 57 | 新增: if n := int(limit) - len(suffix); len(b) > n { | |
| 54 | 58 | b = strings.TrimRight(b[:max(n, 1)], "-") |
| 55 | 59 | if b == "" { |
| 56 | 60 | b = "p" |
| @@ -61,13 +65,15 @@ func fit(b, suffix string) string { | ||
| 61 | 65 | |
| 62 | 66 | // FromOld is the name of the VM 0.2 named old: without OldPrefix, its base |
| 63 | 67 | // template Template, cut as Name cuts a name too long here. |
| 64 | 删除:func FromOld(old string) string { | |
| 68 | 新增:func FromOld(old string) string { return Limit(0).FromOld(old) } | |
| 69 | 新增: | |
| 70 | 新增:func (limit Limit) FromOld(old string) string { | |
| 65 | 71 | if old == OldPrefix+"base" { |
| 66 | 72 | return Template |
| 67 | 73 | } |
| 68 | 74 | n := strings.TrimPrefix(old, OldPrefix) |
| 69 | 75 | if i := strings.LastIndexByte(n, '-'); i > 0 { |
| 70 | 删除: return fit(n[:i], n[i:]) | |
| 76 | 新增: return limit.fit(n[:i], n[i:]) | |
| 71 | 77 | } |
| 72 | 78 | return n |
| 73 | 79 | } |
| @@ -76,7 +82,9 @@ func FromOld(old string) string { | ||
| 76 | 82 | // never the folder's VM and several can run at once. Short enough for Lima: |
| 77 | 83 | // 76 characters, and a socket path under the Lima home of at most 104 on |
| 78 | 84 | // macOS. |
| 79 | 删除:func Scratch(dir string) (string, error) { | |
| 85 | 新增:func Scratch(dir string) (string, error) { return Limit(0).Scratch(dir) } | |
| 86 | 新增: | |
| 87 | 新增:func (limit Limit) Scratch(dir string) (string, error) { | |
| 80 | 88 | var b [4]byte |
| 81 | 89 | if _, err := rand.Read(b[:]); err != nil { |
| 82 | 90 | return "", fmt.Errorf("cannot read random bytes to name the VM: %w", err) |
| @@ -85,7 +93,7 @@ func Scratch(dir string) (string, error) { | ||
| 85 | 93 | if name == "" { |
| 86 | 94 | name = "project" |
| 87 | 95 | } |
| 88 | 删除: return fit(name, "-scratch-"+hex.EncodeToString(b[:])), nil | |
| 96 | 新增: return limit.fit(name, "-scratch-"+hex.EncodeToString(b[:])), nil | |
| 89 | 97 | } |
| 90 | 98 | |
| 91 | 99 | // IsScratch reports whether name looks like one Scratch makes. It only |
| @@ -67,11 +67,9 @@ func TestNameBash(t *testing.T) { | ||
| 67 | 67 | // A name longer than this machine allows is cut in its folder part, the |
| 68 | 68 | // hash of the whole path kept; 0.2's name of the same folder is cut alike. |
| 69 | 69 | func TestNameFits(t *testing.T) { |
| 70 | 删除: old := MaxLen | |
| 71 | 删除: t.Cleanup(func() { MaxLen = old }) | |
| 72 | 删除: MaxLen = 20 | |
| 70 | 新增: limit := Limit(20) | |
| 73 | 71 | dir := "/home/u/" + strings.Repeat("long-folder-", 4) |
| 74 | 删除: n := Name(dir) | |
| 72 | 新增: n := limit.Name(dir) | |
| 75 | 73 | full := strings.TrimSuffix(strings.Repeat("long-folder-", 4), "-") |
| 76 | 74 | // The hash is of the whole path, whatever the cut. |
| 77 | 75 | sum := sha256.Sum256([]byte(paths.Guest(dir))) |
| @@ -79,19 +77,16 @@ func TestNameFits(t *testing.T) { | ||
| 79 | 77 | if n != "long-folder"+hash { |
| 80 | 78 | t.Errorf("Name = %q, want %q", n, "long-folder"+hash) |
| 81 | 79 | } |
| 82 | 删除: if other := Name("/elsewhere/" + strings.Repeat("long-folder-", 4)); other == n { | |
| 80 | 新增: if other := limit.Name("/elsewhere/" + strings.Repeat("long-folder-", 4)); other == n { | |
| 83 | 81 | t.Error("two folders, one name") |
| 84 | 82 | } |
| 85 | 删除: MaxLen = 76 | |
| 86 | 83 | oldName := OldPrefix + Name(dir) |
| 87 | 删除: MaxLen = 20 | |
| 88 | 删除: if FromOld(oldName) != n { | |
| 89 | 删除: t.Errorf("FromOld(%q) = %q, Name %q", oldName, FromOld(oldName), n) | |
| 84 | 新增: if limit.FromOld(oldName) != n { | |
| 85 | 新增: t.Errorf("FromOld(%q) = %q, Name %q", oldName, limit.FromOld(oldName), n) | |
| 90 | 86 | } |
| 91 | 删除: if s, _ := Scratch(dir); len(s) > 20 || !IsScratch(s) { | |
| 87 | 新增: if s, _ := limit.Scratch(dir); len(s) > 20 || !IsScratch(s) { | |
| 92 | 88 | t.Errorf("Scratch = %q", s) |
| 93 | 89 | } |
| 94 | 删除: MaxLen = 76 | |
| 95 | 90 | if Name(dir) != full+hash { |
| 96 | 91 | t.Errorf("cut though it fits: %q", Name(dir)) |
| 97 | 92 | } |
| @@ -7,7 +7,6 @@ import ( | ||
| 7 | 7 | "time" |
| 8 | 8 | |
| 9 | 9 | "github.com/gorilla/websocket" |
| 10 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 11 | 10 | ) |
| 12 | 11 | |
| 13 | 12 | const audioCaptureCommand = "exec /usr/bin/parec --server=unix:/run/cage-audio/native --record --raw --format=s16le --rate=48000 --channels=2 --device=cage_output.monitor --latency-msec=20" |
| @@ -43,7 +42,7 @@ func (s *Server) audio(w http.ResponseWriter, r *http.Request) { | ||
| 43 | 42 | defer func() { s.mu.Lock(); s.audioClients--; s.mu.Unlock() }() |
| 44 | 43 | ctx, cancel := context.WithCancel(r.Context()) |
| 45 | 44 | defer cancel() |
| 46 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", audioCaptureCommand) | |
| 45 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", audioCaptureCommand) | |
| 47 | 46 | pipe, err := cmd.StdoutPipe() |
| 48 | 47 | if err != nil { |
| 49 | 48 | http.Error(w, "声音连接未能建立", http.StatusBadGateway) |
| @@ -17,10 +17,11 @@ import ( | ||
| 17 | 17 | ) |
| 18 | 18 | |
| 19 | 19 | type SavedDownload struct { |
| 20 | 删除: ID string `json:"id"` | |
| 21 | 删除: Name string `json:"name"` | |
| 22 | 删除: Path string `json:"path"` | |
| 23 | 删除: SavedAt time.Time `json:"saved_at"` | |
| 20 | 新增: InstanceID string `json:"instance_id,omitempty"` | |
| 21 | 新增: ID string `json:"id"` | |
| 22 | 新增: Name string `json:"name"` | |
| 23 | 新增: Path string `json:"path"` | |
| 24 | 新增: SavedAt time.Time `json:"saved_at"` | |
| 24 | 25 | } |
| 25 | 26 | |
| 26 | 27 | func savedDownloadPath(profile, id string) string { |
| @@ -80,7 +81,11 @@ func rememberDownload(profile string, saved SavedDownload, firstOnly bool) error | ||
| 80 | 81 | return writePrivate(savedDownloadPath(profile, saved.ID), saved) |
| 81 | 82 | } |
| 82 | 83 | func (s *Server) savedBrowserDownloads(w http.ResponseWriter, r *http.Request) { |
| 83 | 删除: entries, err := os.ReadDir(filepath.Join(s.profile, "browser-downloads")) | |
| 84 | 新增: serveSavedDownloads(w, s.profile) | |
| 85 | 新增:} | |
| 86 | 新增: | |
| 87 | 新增:func serveSavedDownloads(w http.ResponseWriter, profile string) { | |
| 88 | 新增: entries, err := os.ReadDir(filepath.Join(profile, "browser-downloads")) | |
| 84 | 89 | if err != nil && !os.IsNotExist(err) { |
| 85 | 90 | http.Error(w, "无法读取已保存的位置", 500) |
| 86 | 91 | return |
| @@ -91,7 +96,7 @@ func (s *Server) savedBrowserDownloads(w http.ResponseWriter, r *http.Request) { | ||
| 91 | 96 | if len(name) != 41 { |
| 92 | 97 | continue |
| 93 | 98 | } |
| 94 | 删除: if saved, err := readSavedDownload(s.profile, name[:36]); err == nil { | |
| 99 | 新增: if saved, err := readSavedDownload(profile, name[:36]); err == nil { | |
| 95 | 100 | records = append(records, saved) |
| 96 | 101 | } |
| 97 | 102 | } |
| @@ -105,6 +110,10 @@ func (s *Server) savedBrowserDownloads(w http.ResponseWriter, r *http.Request) { | ||
| 105 | 110 | // BrowserFile is called by native dialogs, which supply the chosen path. HTTP |
| 106 | 111 | // clients can stream known downloads but cannot supply an arbitrary host path. |
| 107 | 112 | func BrowserFile(configPath, action, id, destination string) (SavedDownload, error) { |
| 113 | 新增: return BrowserFileForConnection(configPath, "", action, id, destination) | |
| 114 | 新增:} | |
| 115 | 新增: | |
| 116 | 新增:func BrowserFileForConnection(configPath, connectionID, action, id, destination string) (SavedDownload, error) { | |
| 108 | 117 | var result SavedDownload |
| 109 | 118 | if !browserFileID.MatchString(id) || (action != "save" && action != "open" && action != "reveal") { |
| 110 | 119 | return result, errors.New("下载操作无效") |
| @@ -119,12 +128,36 @@ func BrowserFile(configPath, action, id, destination string) (SavedDownload, err | ||
| 119 | 128 | if err != nil || status != 200 { |
| 120 | 129 | return result, errors.New("无法连接下载会话") |
| 121 | 130 | } |
| 131 | 新增: connection, err := client.bindConnection(connectionID) | |
| 132 | 新增: if err != nil { | |
| 133 | 新增: return result, err | |
| 134 | 新增: } | |
| 135 | 新增: profile := filepath.Dir(configPath) | |
| 136 | 新增: if connection.DesktopGateway && connection.Mode == "local" { | |
| 137 | 新增: profile = filepath.Dir(profile) | |
| 138 | 新增: } | |
| 139 | 新增: saveProfile, err := clientDownloadProfile(profile, connection) | |
| 140 | 新增: if err != nil { | |
| 141 | 新增: return result, err | |
| 142 | 新增: } | |
| 122 | 143 | var item browserDownloadInfo |
| 123 | 删除: status, err = client.call("GET", "/api/browser/files/downloads/"+id, nil, &item) | |
| 124 | 删除: if err != nil || status != 200 { | |
| 125 | 删除: return result, errors.New("下载文件不可用,请确认 Cage 已解锁且下载已完成") | |
| 144 | 新增: if connection.Mode == "remote" && action != "save" { | |
| 145 | 新增: saved, readErr := readSavedDownload(saveProfile, id) | |
| 146 | 新增: if readErr != nil || saved.InstanceID != connection.InstanceID { | |
| 147 | 新增: return result, errors.New("请先将文件另存为到本机,再打开或显示所在位置") | |
| 148 | 新增: } | |
| 149 | 新增: result = saved | |
| 150 | 新增: } else { | |
| 151 | 新增: status, err = client.call("GET", "/api/browser/files/downloads/"+id, nil, &item) | |
| 152 | 新增: if err != nil || status != 200 { | |
| 153 | 新增: return result, errors.New("下载文件不可用,请确认 Cage 已解锁且下载已完成") | |
| 154 | 新增: } | |
| 155 | 新增: result = SavedDownload{ID: id, Name: item.Name, Path: item.Path} | |
| 156 | 新增: if connection.Mode == "remote" { | |
| 157 | 新增: result.Path = "" | |
| 158 | 新增: result.InstanceID = connection.InstanceID | |
| 159 | 新增: } | |
| 126 | 160 | } |
| 127 | 删除: result = SavedDownload{ID: id, Name: item.Name, Path: item.Path} | |
| 128 | 161 | if action == "save" { |
| 129 | 162 | if !filepath.IsAbs(destination) || filepath.Base(destination) == "." { |
| 130 | 163 | return result, errors.New("保存位置无效") |
| @@ -150,7 +183,7 @@ func BrowserFile(configPath, action, id, destination string) (SavedDownload, err | ||
| 150 | 183 | } |
| 151 | 184 | result.Path = destination |
| 152 | 185 | result.Name = filepath.Base(destination) |
| 153 | 删除: if err = rememberDownload(client.profile, result, false); err != nil { | |
| 186 | 新增: if err = rememberDownload(saveProfile, result, false); err != nil { | |
| 154 | 187 | return result, err |
| 155 | 188 | } |
| 156 | 189 | } else { |
| @@ -5,7 +5,11 @@ import ( | ||
| 5 | 5 | "encoding/json" |
| 6 | 6 | "errors" |
| 7 | 7 | "io" |
| 8 | 新增: "net" | |
| 8 | 9 | "net/http" |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 9 | 13 | ) |
| 10 | 14 | |
| 11 | 15 | var ( |
| @@ -38,6 +42,23 @@ func (s *Server) browserClient() *browserClient { | ||
| 38 | 42 | defer s.mu.Unlock() |
| 39 | 43 | if s.browserControl == nil { |
| 40 | 44 | s.browserControl = newBrowserClient(s.lifetimeContextLocked()) |
| 45 | 新增: if containerenv.Configured(s.profile) { | |
| 46 | 新增: transport := s.browserControl.http.Transport.(*http.Transport) | |
| 47 | 新增: transport.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { | |
| 48 | 新增: environment, err := containerenv.Load(s.profile) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: return nil, err | |
| 51 | 新增: } | |
| 52 | 新增: state, err := environment.State(ctx) | |
| 53 | 新增: if err != nil { | |
| 54 | 新增: return nil, err | |
| 55 | 新增: } | |
| 56 | 新增: if !state.Ready { | |
| 57 | 新增: return nil, errBrowserNotReady | |
| 58 | 新增: } | |
| 59 | 新增: return (&net.Dialer{Timeout: 3 * time.Second}).DialContext(ctx, network, state.BrowserAddress) | |
| 60 | 新增: } | |
| 61 | 新增: } | |
| 41 | 62 | } |
| 42 | 63 | return s.browserControl |
| 43 | 64 | } |
| @@ -11,7 +11,6 @@ import ( | ||
| 11 | 11 | "time" |
| 12 | 12 | |
| 13 | 13 | "github.com/sylvinus/agent-vm/internal/cage" |
| 14 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 15 | 14 | ) |
| 16 | 15 | |
| 17 | 16 | type claudeDesktopState struct { |
| @@ -114,7 +113,7 @@ func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) { | ||
| 114 | 113 | } |
| 115 | 114 | ctx, cancel := context.WithTimeout(s.operationContext(), 55*time.Second) |
| 116 | 115 | defer cancel() |
| 117 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", "/usr/local/bin/cage-claude-start") | |
| 116 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/usr/local/bin/cage-claude-start") | |
| 118 | 117 | cmd.Stdin = bytes.NewReader(key) |
| 119 | 118 | cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution() |
| 120 | 119 | if err = cmd.Run(); err != nil { |
| @@ -134,7 +133,7 @@ func (s *Server) runDesktopScript(script string, timeout time.Duration) error { | ||
| 134 | 133 | // A guest cgroup owns apt and all descendants, including across SSH loss. |
| 135 | 134 | // The application's persistent service is separate from this operation. |
| 136 | 135 | command := fmt.Sprintf("sudo systemd-run --quiet --pipe --wait --collect --unit=cage-desktop-operation --property=User=cage --property=RuntimeMaxSec=%d --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=/home/cage /bin/bash -se", int(timeout.Seconds())) |
| 137 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", command) | |
| 136 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command) | |
| 138 | 137 | cmd.Stdin = strings.NewReader(script) |
| 139 | 138 | cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution() |
| 140 | 139 | if err := cmd.Run(); err != nil { |
| @@ -206,7 +205,7 @@ func (s *Server) claudeDesktopVNC(w http.ResponseWriter, r *http.Request) { | ||
| 206 | 205 | defer cancel() |
| 207 | 206 | // No extra localhost port or public VNC listener on the host. SSH is bound |
| 208 | 207 | // to this profile's single guest and carries the authenticated RFB session. |
| 209 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", "exec socat STDIO UNIX-CONNECT:/run/cage-desktop/vnc.sock") | |
| 208 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "exec socat STDIO UNIX-CONNECT:/run/cage-desktop/vnc.sock") | |
| 210 | 209 | reader, err := cmd.StdoutPipe() |
| 211 | 210 | if err != nil { |
| 212 | 211 | http.Error(w, "无法连接应用画面", 502) |
| @@ -1,11 +1,16 @@ | ||
| 1 | 1 | package workbench |
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 新增: "context" | |
| 4 | 5 | "encoding/json" |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 5 | 8 | "net/http" |
| 6 | 9 | "os" |
| 7 | 10 | "path/filepath" |
| 11 | 新增: "time" | |
| 8 | 12 | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 9 | 14 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 10 | 15 | "github.com/sylvinus/agent-vm/internal/version" |
| 11 | 16 | ) |
| @@ -29,8 +34,9 @@ func (identity ControllerIdentity) matches(other ControllerIdentity) bool { | ||
| 29 | 34 | } |
| 30 | 35 | |
| 31 | 36 | type launchResponse struct { |
| 32 | 删除: URL string `json:"url"` | |
| 33 | 删除: Controller ControllerIdentity `json:"controller"` | |
| 37 | 新增: DesktopGateway bool `json:"desktop_gateway,omitempty"` | |
| 38 | 新增: URL string `json:"url"` | |
| 39 | 新增: Controller ControllerIdentity `json:"controller"` | |
| 34 | 40 | } |
| 35 | 41 | |
| 36 | 42 | func (s *Server) launcherAuthenticated(w http.ResponseWriter, r *http.Request) bool { |
| @@ -55,6 +61,11 @@ func (s *Server) handoff(w http.ResponseWriter, r *http.Request) { | ||
| 55 | 61 | http.Error(w, "请先保存工作并停止环境,再完成更新。", http.StatusConflict) |
| 56 | 62 | return |
| 57 | 63 | } |
| 64 | 新增: s.handoffLocked(w) | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:// handoffLocked takes ownership of the operation lock and releases it on all paths. | |
| 68 | 新增:func (s *Server) handoffLocked(w http.ResponseWriter) { | |
| 58 | 69 | s.mu.Lock() |
| 59 | 70 | if s.closing { |
| 60 | 71 | s.mu.Unlock() |
| @@ -93,24 +104,49 @@ func (s *Server) handoff(w http.ResponseWriter, r *http.Request) { | ||
| 93 | 104 | } |
| 94 | 105 | |
| 95 | 106 | func controllerHasVM(profile string) bool { |
| 107 | 新增: running, err := controllerVMState(profile) | |
| 108 | 新增: return err != nil || running | |
| 109 | 新增:} | |
| 110 | 新增: | |
| 111 | 新增:// Callers that display a state must distinguish a missing VM from a failed probe. | |
| 112 | 新增:func controllerVMState(profile string) (bool, error) { | |
| 113 | 新增: owners, err := controllerVMOwners(profile) | |
| 114 | 新增: return len(owners) != 0, err | |
| 115 | 新增:} | |
| 116 | 新增: | |
| 117 | 新增:func controllerVMOwners(profile string) ([]string, error) { | |
| 118 | 新增: if containerenv.Configured(profile) { | |
| 119 | 新增: environment, err := containerenv.Load(profile) | |
| 120 | 新增: if err != nil { | |
| 121 | 新增: return nil, err | |
| 122 | 新增: } | |
| 123 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 124 | 新增: defer cancel() | |
| 125 | 新增: state, err := environment.State(ctx) | |
| 126 | 新增: if err != nil || !state.Running { | |
| 127 | 新增: return nil, err | |
| 128 | 新增: } | |
| 129 | 新增: return []string{fmt.Sprintf("%s/%d", state.ContainerID, state.PID)}, nil | |
| 130 | 新增: } | |
| 96 | 131 | records, err := filepath.Glob(filepath.Join(profile, "state", "lima", "*", "cage-running.json")) |
| 97 | 132 | if err != nil { |
| 98 | 删除: return true | |
| 133 | 新增: return nil, err | |
| 99 | 134 | } |
| 135 | 新增: var owners []string | |
| 100 | 136 | for _, path := range records { |
| 101 | 137 | b, err := os.ReadFile(path) |
| 102 | 138 | if err != nil { |
| 103 | 删除: return true | |
| 139 | 新增: return nil, err | |
| 104 | 140 | } |
| 105 | 141 | var record struct { |
| 106 | 142 | PID int `json:"pid"` |
| 107 | 143 | } |
| 108 | 144 | if json.Unmarshal(b, &record) != nil || record.PID <= 0 { |
| 109 | 删除: return true | |
| 145 | 新增: return nil, errors.New("环境进程记录无效") | |
| 110 | 146 | } |
| 111 | 147 | if processExists(record.PID) { |
| 112 | 删除: return true | |
| 148 | 新增: owners = append(owners, fmt.Sprintf("%s/%d", filepath.Base(filepath.Dir(path)), record.PID)) | |
| 113 | 149 | } |
| 114 | 150 | } |
| 115 | 删除: return false | |
| 151 | 新增: return owners, nil | |
| 116 | 152 | } |
| @@ -2,6 +2,7 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "bytes" |
| 5 | 新增: "context" | |
| 5 | 6 | "encoding/json" |
| 6 | 7 | "errors" |
| 7 | 8 | "fmt" |
| @@ -27,6 +28,7 @@ type DesktopResult struct { | ||
| 27 | 28 | } |
| 28 | 29 | type controllerClient struct { |
| 29 | 30 | profile, origin string |
| 31 | 新增: connectionID string | |
| 30 | 32 | record controlFile |
| 31 | 33 | launch launchResponse |
| 32 | 34 | client *http.Client |
| @@ -34,7 +36,7 @@ type controllerClient struct { | ||
| 34 | 36 | |
| 35 | 37 | var errControllerUnavailable = errors.New("control service is unavailable") |
| 36 | 38 | |
| 37 | 删除:func connectController(profile string) (*controllerClient, error) { | |
| 39 | 新增:func openController(profile string) (*controllerClient, error) { | |
| 38 | 40 | path := filepath.Join(profile, "control.json") |
| 39 | 41 | if err := host.CheckPrivateFile(path); err != nil { |
| 40 | 42 | if os.IsNotExist(err) { |
| @@ -55,6 +57,15 @@ func connectController(profile string) (*controllerClient, error) { | ||
| 55 | 57 | } |
| 56 | 58 | jar, _ := cookiejar.New(nil) |
| 57 | 59 | c := &controllerClient{profile: profile, record: record, origin: fmt.Sprintf("http://localhost:%d", record.Port), client: &http.Client{Timeout: 5 * time.Second, Jar: jar, Transport: &http.Transport{Proxy: nil}, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }}} |
| 60 | 新增: return c, nil | |
| 61 | 新增:} | |
| 62 | 新增: | |
| 63 | 新增:func connectController(profile string) (*controllerClient, error) { | |
| 64 | 新增: c, err := openController(profile) | |
| 65 | 新增: if err != nil { | |
| 66 | 新增: return nil, err | |
| 67 | 新增: } | |
| 68 | 新增: record := c.record | |
| 58 | 69 | status, err := c.call("POST", "/api/launch", map[string]string{"token": record.Token}, &c.launch) |
| 59 | 70 | if err != nil { |
| 60 | 71 | c.close() |
| @@ -81,6 +92,10 @@ func connectController(profile string) (*controllerClient, error) { | ||
| 81 | 92 | } |
| 82 | 93 | func (c *controllerClient) close() { c.client.CloseIdleConnections() } |
| 83 | 94 | func (c *controllerClient) call(method, path string, input, output any) (int, error) { |
| 95 | 新增: return c.callContext(context.Background(), method, path, input, output) | |
| 96 | 新增:} | |
| 97 | 新增: | |
| 98 | 新增:func (c *controllerClient) callContext(ctx context.Context, method, path string, input, output any) (int, error) { | |
| 84 | 99 | var body []byte |
| 85 | 100 | var err error |
| 86 | 101 | if input != nil { |
| @@ -89,12 +104,15 @@ func (c *controllerClient) call(method, path string, input, output any) (int, er | ||
| 89 | 104 | return 0, err |
| 90 | 105 | } |
| 91 | 106 | } |
| 92 | 删除: req, err := http.NewRequest(method, c.origin+path, bytes.NewReader(body)) | |
| 107 | 新增: req, err := http.NewRequestWithContext(ctx, method, c.origin+path, bytes.NewReader(body)) | |
| 93 | 108 | if err != nil { |
| 94 | 109 | return 0, err |
| 95 | 110 | } |
| 96 | 111 | req.Header.Set("Origin", c.origin) |
| 97 | 112 | req.Header.Set("Content-Type", "application/json") |
| 113 | 新增: if c.connectionID != "" { | |
| 114 | 新增: req.Header.Set(connectionHeader, c.connectionID) | |
| 115 | 新增: } | |
| 98 | 116 | res, err := c.client.Do(req) |
| 99 | 117 | if err != nil { |
| 100 | 118 | return 0, err |
| @@ -114,7 +132,10 @@ func pendingUpdate(c *controllerClient) DesktopResult { | ||
| 114 | 132 | // Desktop never silently loads a different build's UI. Completing an update is |
| 115 | 133 | // an explicit user action because it stops the existing environment's work. |
| 116 | 134 | func Desktop(configPath string, options DesktopOptions) (DesktopResult, error) { |
| 117 | 删除: profile := filepath.Dir(configPath) | |
| 135 | 新增: return desktopLaunch(filepath.Dir(configPath), false, options, func() error { return startController(configPath) }) | |
| 136 | 新增:} | |
| 137 | 新增: | |
| 138 | 新增:func desktopLaunch(profile string, gateway bool, options DesktopOptions, start func() error) (DesktopResult, error) { | |
| 118 | 139 | want, err := currentController() |
| 119 | 140 | if err != nil { |
| 120 | 141 | return DesktopResult{}, err |
| @@ -122,8 +143,16 @@ func Desktop(configPath string, options DesktopOptions) (DesktopResult, error) { | ||
| 122 | 143 | current, err := connectController(profile) |
| 123 | 144 | if err == nil { |
| 124 | 145 | defer current.close() |
| 146 | 新增: if current.launch.DesktopGateway != gateway { | |
| 147 | 新增: return DesktopResult{}, errors.New("此目录已被另一种 Cage 服务使用,请核对配置路径") | |
| 148 | 新增: } | |
| 125 | 149 | if options.CompleteUpdate { |
| 126 | 删除: if err = current.stopAndHandoff(); err != nil { | |
| 150 | 新增: if current.launch.DesktopGateway { | |
| 151 | 新增: err = current.releaseDesktopEntry() | |
| 152 | 新增: } else { | |
| 153 | 新增: err = current.stopAndHandoff() | |
| 154 | 新增: } | |
| 155 | 新增: if err != nil { | |
| 127 | 156 | return DesktopResult{}, err |
| 128 | 157 | } |
| 129 | 158 | } else if want.matches(current.launch.Controller) || options.UseExisting { |
| @@ -150,13 +179,16 @@ func Desktop(configPath string, options DesktopOptions) (DesktopResult, error) { | ||
| 150 | 179 | } else if !errors.Is(err, errControllerUnavailable) { |
| 151 | 180 | return DesktopResult{}, err |
| 152 | 181 | } |
| 153 | 删除: if err = startController(configPath); err != nil { | |
| 182 | 新增: if err = start(); err != nil { | |
| 154 | 183 | return DesktopResult{}, err |
| 155 | 184 | } |
| 156 | 185 | for i := 0; i < 60; i++ { |
| 157 | 186 | c, readErr := connectController(profile) |
| 158 | 187 | if readErr == nil { |
| 159 | 188 | c.close() |
| 189 | 新增: if c.launch.DesktopGateway != gateway { | |
| 190 | 新增: return DesktopResult{}, errors.New("打开期间控制服务身份发生变化,请重新选择") | |
| 191 | 新增: } | |
| 160 | 192 | if want.matches(c.launch.Controller) { |
| 161 | 193 | return DesktopResult{Status: "ready", URL: c.launch.URL, Controller: c.launch.Controller}, nil |
| 162 | 194 | } |
| @@ -231,6 +263,25 @@ func (c *controllerClient) stopAndHandoff() error { | ||
| 231 | 263 | if status != http.StatusOK { |
| 232 | 264 | return errors.New("无法建立停止会话,请重试。") |
| 233 | 265 | } |
| 266 | 新增: var clientContext ClientContext | |
| 267 | 新增: contextStatus, contextErr := c.call("GET", "/api/client/context", nil, &clientContext) | |
| 268 | 新增: if contextErr == nil && contextStatus == http.StatusOK && (clientContext.Mode == "remote" || clientContext.ClientOnly) { | |
| 269 | 新增: path := "/api/client/local" | |
| 270 | 新增: if clientContext.ClientOnly { | |
| 271 | 新增: path = "/api/client/disconnect" | |
| 272 | 新增: } | |
| 273 | 新增: status, err = c.call("POST", path, map[string]string{"connection_id": clientContext.ConnectionID}, nil) | |
| 274 | 新增: if err != nil || status != http.StatusOK { | |
| 275 | 新增: return errors.New("无法断开本地远程连接,未继续更新") | |
| 276 | 新增: } | |
| 277 | 新增: if clientContext.ClientOnly { | |
| 278 | 新增: status, err = c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) | |
| 279 | 新增: if err != nil || status != http.StatusOK { | |
| 280 | 新增: return errors.New("本地连接服务尚未退出,请稍后重试") | |
| 281 | 新增: } | |
| 282 | 新增: return c.waitForExit() | |
| 283 | 新增: } | |
| 284 | 新增: } | |
| 234 | 285 | var requested Job |
| 235 | 286 | status, err = c.call("POST", "/api/stop", map[string]any{}, &requested) |
| 236 | 287 | if err != nil { |
| @@ -321,19 +372,24 @@ func (c *controllerClient) waitForExit() error { | ||
| 321 | 372 | return errors.New("后台尚未退出,未强制结束进程。请稍后重试更新。") |
| 322 | 373 | } |
| 323 | 374 | func startController(configPath string) error { |
| 324 | 删除: profile := filepath.Dir(configPath) | |
| 325 | 删除: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 326 | 删除: return err | |
| 327 | 删除: } | |
| 328 | 375 | exe, err := os.Executable() |
| 329 | 376 | if err != nil { |
| 330 | 377 | return err |
| 331 | 378 | } |
| 379 | 新增: return startControllerExecutable(configPath, exe) | |
| 380 | 新增:} | |
| 381 | 新增: | |
| 382 | 新增:func startControllerExecutable(configPath, exe string, extraEnv ...string) error { | |
| 383 | 新增: profile := filepath.Dir(configPath) | |
| 384 | 新增: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 385 | 新增: return err | |
| 386 | 新增: } | |
| 332 | 387 | cmd := exec.Command(exe, "log-relay", "controller") |
| 333 | 388 | cmd.Dir = profile |
| 334 | 389 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+configPath) |
| 390 | 新增: cmd.Env = append(cmd.Env, extraEnv...) | |
| 335 | 391 | detachController(cmd) |
| 336 | 删除: if err = cmd.Start(); err != nil { | |
| 392 | 新增: if err := cmd.Start(); err != nil { | |
| 337 | 393 | return err |
| 338 | 394 | } |
| 339 | 395 | return cmd.Process.Release() |
| @@ -0,0 +1,207 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strconv" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// The entry and the local workload must never share a controller lock, | |
| 17 | 新增:// shutdown hook or service cookie, even with an explicitly selected profile. | |
| 18 | 新增:func desktopConfigPath(fullConfig string) string { | |
| 19 | 新增: return filepath.Join(filepath.Dir(fullConfig), "desktop-entry", "config.json") | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:// DesktopHelperConfig routes native calls that captured a selected connection. | |
| 23 | 新增:// Plain CLI operations and older clients using the legacy "local" identity | |
| 24 | 新增:// continue to address the original workload profile. | |
| 25 | 新增:func DesktopHelperConfig(fullConfig, connection string) string { | |
| 26 | 新增: if connection != "" && connection != "local" { | |
| 27 | 新增: entry := desktopConfigPath(fullConfig) | |
| 28 | 新增: if _, err := os.Lstat(filepath.Join(filepath.Dir(entry), "control.json")); !os.IsNotExist(err) { | |
| 29 | 新增: return entry | |
| 30 | 新增: } | |
| 31 | 新增: } | |
| 32 | 新增: return fullConfig | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func DesktopEntry(fullConfig string, opts DesktopOptions) (DesktopResult, error) { | |
| 36 | 新增: // Explicit legacy recovery opens its own already-authenticated UI so the | |
| 37 | 新增: // user can save active work before switching backend versions. | |
| 38 | 新增: if opts.UseExisting { | |
| 39 | 新增: c, err := connectController(filepath.Dir(fullConfig)) | |
| 40 | 新增: if err == nil { | |
| 41 | 新增: defer c.close() | |
| 42 | 新增: want, err := currentController() | |
| 43 | 新增: if err != nil { | |
| 44 | 新增: return DesktopResult{}, err | |
| 45 | 新增: } | |
| 46 | 新增: if !want.matches(c.launch.Controller) { | |
| 47 | 新增: return DesktopResult{Status: "existing", URL: c.launch.URL, Controller: c.launch.Controller, Legacy: c.launch.Controller.Protocol == 0}, nil | |
| 48 | 新增: } | |
| 49 | 新增: } else if !errors.Is(err, errControllerUnavailable) { | |
| 50 | 新增: return DesktopResult{}, err | |
| 51 | 新增: } | |
| 52 | 新增: } | |
| 53 | 新增: if opts.CompleteUpdate { | |
| 54 | 新增: if _, err := PrepareDesktopUpdate(fullConfig, true); err != nil { | |
| 55 | 新增: return DesktopResult{}, err | |
| 56 | 新增: } | |
| 57 | 新增: opts.CompleteUpdate = false | |
| 58 | 新增: } | |
| 59 | 新增: profile := filepath.Dir(desktopConfigPath(fullConfig)) | |
| 60 | 新增: owner := 0 | |
| 61 | 新增: if value := os.Getenv("CAGE_DESKTOP_OWNER_PID"); value != "" { | |
| 62 | 新增: var err error | |
| 63 | 新增: if owner, err = strconv.Atoi(value); err != nil || owner < 2 { | |
| 64 | 新增: return DesktopResult{}, errors.New("桌面窗口进程标识无效") | |
| 65 | 新增: } | |
| 66 | 新增: } | |
| 67 | 新增: result, err := desktopLaunch(profile, true, opts, func() error { | |
| 68 | 新增: if err := host.EnsurePrivateDir(profile); err != nil { | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: exe, err := os.Executable() | |
| 72 | 新增: if err != nil { | |
| 73 | 新增: return err | |
| 74 | 新增: } | |
| 75 | 新增: cmd := exec.Command(exe, "serve-desktop") | |
| 76 | 新增: cmd.Dir = profile | |
| 77 | 新增: cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+fullConfig) | |
| 78 | 新增: detachController(cmd) | |
| 79 | 新增: if err := cmd.Start(); err != nil { | |
| 80 | 新增: return err | |
| 81 | 新增: } | |
| 82 | 新增: return cmd.Process.Release() | |
| 83 | 新增: }) | |
| 84 | 新增: if err != nil || owner == 0 || result.URL == "" { | |
| 85 | 新增: return result, err | |
| 86 | 新增: } | |
| 87 | 新增: c, err := connectController(profile) | |
| 88 | 新增: if err != nil { | |
| 89 | 新增: return DesktopResult{}, err | |
| 90 | 新增: } | |
| 91 | 新增: defer c.close() | |
| 92 | 新增: if !c.launch.DesktopGateway || c.launch.Controller.PID != result.Controller.PID { | |
| 93 | 新增: return DesktopResult{}, errors.New("桌面连接服务身份不匹配") | |
| 94 | 新增: } | |
| 95 | 新增: code, err := c.call("POST", "/api/desktop-owner", map[string]any{"token": c.record.Token, "pid": owner}, nil) | |
| 96 | 新增: if err != nil || code != http.StatusOK { | |
| 97 | 新增: return DesktopResult{}, errors.New("无法关联桌面窗口和连接服务") | |
| 98 | 新增: } | |
| 99 | 新增: return result, nil | |
| 100 | 新增:} | |
| 101 | 新增: | |
| 102 | 新增:func (s *Server) registerDesktopOwner(w http.ResponseWriter, r *http.Request) { | |
| 103 | 新增: var input struct { | |
| 104 | 新增: Token string `json:"token"` | |
| 105 | 新增: PID int `json:"pid"` | |
| 106 | 新增: } | |
| 107 | 新增: if !readJSON(w, r, &input) { | |
| 108 | 新增: return | |
| 109 | 新增: } | |
| 110 | 新增: if !equalSecret(input.Token, s.token) || input.PID < 2 || !processExists(input.PID) { | |
| 111 | 新增: http.Error(w, "桌面窗口身份无效", http.StatusForbidden) | |
| 112 | 新增: return | |
| 113 | 新增: } | |
| 114 | 新增: s.mu.Lock() | |
| 115 | 新增: defer s.mu.Unlock() | |
| 116 | 新增: if s.closing { | |
| 117 | 新增: http.Error(w, "桌面入口正在退出", http.StatusConflict) | |
| 118 | 新增: return | |
| 119 | 新增: } | |
| 120 | 新增: if s.windowOwners == nil { | |
| 121 | 新增: s.windowOwners = make(map[int]bool) | |
| 122 | 新增: } | |
| 123 | 新增: s.windowOwners[input.PID] = true | |
| 124 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 125 | 新增:} | |
| 126 | 新增: | |
| 127 | 新增:func (s *Server) watchDesktopOwners(done <-chan struct{}) { | |
| 128 | 新增: // The native process also supplies its PID to a newly launched gateway. | |
| 129 | 新增: // This covers a window killed before it can finish registering via HTTP. | |
| 130 | 新增: initial, _ := strconv.Atoi(os.Getenv("CAGE_DESKTOP_OWNER_PID")) | |
| 131 | 新增: if initial > 1 { | |
| 132 | 新增: s.mu.Lock() | |
| 133 | 新增: if s.windowOwners == nil { | |
| 134 | 新增: s.windowOwners = make(map[int]bool) | |
| 135 | 新增: } | |
| 136 | 新增: s.windowOwners[initial] = true | |
| 137 | 新增: s.mu.Unlock() | |
| 138 | 新增: } | |
| 139 | 新增: ticker := time.NewTicker(time.Second) | |
| 140 | 新增: defer ticker.Stop() | |
| 141 | 新增: for { | |
| 142 | 新增: select { | |
| 143 | 新增: case <-done: | |
| 144 | 新增: return | |
| 145 | 新增: case <-ticker.C: | |
| 146 | 新增: s.mu.Lock() | |
| 147 | 新增: hadOwners := len(s.windowOwners) > 0 | |
| 148 | 新增: for pid := range s.windowOwners { | |
| 149 | 新增: if !processExists(pid) { | |
| 150 | 新增: delete(s.windowOwners, pid) | |
| 151 | 新增: } | |
| 152 | 新增: } | |
| 153 | 新增: exit := hadOwners && len(s.windowOwners) == 0 | |
| 154 | 新增: if exit { | |
| 155 | 新增: s.closing = true | |
| 156 | 新增: } | |
| 157 | 新增: s.mu.Unlock() | |
| 158 | 新增: if exit { | |
| 159 | 新增: s.shutdown() | |
| 160 | 新增: return | |
| 161 | 新增: } | |
| 162 | 新增: } | |
| 163 | 新增: } | |
| 164 | 新增:} | |
| 165 | 新增: | |
| 166 | 新增:func (s *Server) handoffEntry(w http.ResponseWriter, r *http.Request) { | |
| 167 | 新增: if !s.launcherAuthenticated(w, r) { | |
| 168 | 新增: return | |
| 169 | 新增: } | |
| 170 | 新增: jsonReply(w, map[string]bool{"stopping": true}) | |
| 171 | 新增: _ = http.NewResponseController(w).Flush() | |
| 172 | 新增: go s.shutdown() | |
| 173 | 新增:} | |
| 174 | 新增: | |
| 175 | 新增:func (c *controllerClient) releaseDesktopEntry() error { | |
| 176 | 新增: if !c.launch.DesktopGateway { | |
| 177 | 新增: return errors.New("无法核对桌面连接服务身份") | |
| 178 | 新增: } | |
| 179 | 新增: status, err := c.call("POST", "/api/handoff", map[string]string{"token": c.record.Token}, nil) | |
| 180 | 新增: if err != nil || status != http.StatusOK { | |
| 181 | 新增: return errors.New("桌面连接服务未能退出") | |
| 182 | 新增: } | |
| 183 | 新增: return c.waitForExit() | |
| 184 | 新增:} | |
| 185 | 新增: | |
| 186 | 新增:// Inspect/stop the actual local workload before replacing the installed | |
| 187 | 新增:// executable. The gateway release is always scoped to client connections. | |
| 188 | 新增:func PrepareDesktopUpdate(fullConfig string, stop bool) (DesktopResult, error) { | |
| 189 | 新增: result, err := PrepareUpdate(fullConfig, stop) | |
| 190 | 新增: if err != nil || result.Status != "prepared" { | |
| 191 | 新增: return result, err | |
| 192 | 新增: } | |
| 193 | 新增: profile := filepath.Dir(desktopConfigPath(fullConfig)) | |
| 194 | 新增: c, err := connectController(profile) | |
| 195 | 新增: if errors.Is(err, errControllerUnavailable) { | |
| 196 | 新增: // Absence and an unresponsive but locked gateway are different. | |
| 197 | 新增: return PrepareUpdate(desktopConfigPath(fullConfig), false) | |
| 198 | 新增: } | |
| 199 | 新增: if err != nil { | |
| 200 | 新增: return DesktopResult{}, err | |
| 201 | 新增: } | |
| 202 | 新增: defer c.close() | |
| 203 | 新增: if err = c.releaseDesktopEntry(); err != nil { | |
| 204 | 新增: return DesktopResult{}, err | |
| 205 | 新增: } | |
| 206 | 新增: return result, nil | |
| 207 | 新增:} | |
| @@ -0,0 +1,527 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "runtime" | |
| 8 | 新增: "strings" | |
| 9 | 新增: "sync" | |
| 10 | 新增: "time" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/diagnostics" | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:// The shell owns connection views. The local controller owns its workload, | |
| 17 | 新增:// the original configuration and the stop/handoff decision. | |
| 18 | 新增:type DesktopLocalController interface { | |
| 19 | 新增: Status(context.Context) (DesktopLocalStatus, error) | |
| 20 | 新增: Connect(context.Context) (*remotehost.Session, error) | |
| 21 | 新增: Release(context.Context, DesktopLocalStatus, bool) error | |
| 22 | 新增: ReleaseOwnedIdle(context.Context, DesktopLocalStatus) (bool, error) | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:type DesktopLocalStatus struct { | |
| 26 | 新增: Available bool `json:"available"` | |
| 27 | 新增: Known bool `json:"known"` | |
| 28 | 新增: ServiceRunning bool `json:"service_running"` | |
| 29 | 新增: Running bool `json:"running"` | |
| 30 | 新增: Busy bool `json:"busy"` | |
| 31 | 新增: LiveTerminals int `json:"live_terminals"` | |
| 32 | 新增: ControllerID string `json:"controller_id,omitempty"` | |
| 33 | 新增: Message string `json:"message,omitempty"` | |
| 34 | 新增:} | |
| 35 | 新增: | |
| 36 | 新增:var ( | |
| 37 | 新增: errDesktopLocalLocked = errors.New("请先切回本机解锁账户,再停止本机环境") | |
| 38 | 新增: errViewChanged = errors.New("工作环境已切换,请刷新后重试") | |
| 39 | 新增: errCandidateChanged = errors.New("候选连接已取消或发生变化,请重新选择") | |
| 40 | 新增:) | |
| 41 | 新增: | |
| 42 | 新增:type desktopCandidate struct { | |
| 43 | 新增: ID string `json:"id"` | |
| 44 | 新增: Mode string `json:"mode"` | |
| 45 | 新增: Connection remotehost.ConnectionState `json:"connection"` | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:// One target per connection generation. An SSH candidate has its own manager, | |
| 49 | 新增:// so opening a second host never closes or reroutes the current workbench. | |
| 50 | 新增:type desktopTarget struct { | |
| 51 | 新增: id, mode string | |
| 52 | 新增: remote *remotehost.Manager | |
| 53 | 新增: ctx context.Context | |
| 54 | 新增: cancel context.CancelFunc | |
| 55 | 新增: mu sync.Mutex | |
| 56 | 新增: session *remotehost.Session | |
| 57 | 新增: localErr error | |
| 58 | 新增: localDone chan struct{} | |
| 59 | 新增:} | |
| 60 | 新增: | |
| 61 | 新增:func (t *desktopTarget) state() remotehost.ConnectionState { | |
| 62 | 新增: if t.remote != nil { | |
| 63 | 新增: return t.remote.Snapshot() | |
| 64 | 新增: } | |
| 65 | 新增: t.mu.Lock() | |
| 66 | 新增: defer t.mu.Unlock() | |
| 67 | 新增: state := remotehost.ConnectionState{State: "connecting", ConnectionID: t.id, Phase: "local_connect", Message: "正在连接本机工作台"} | |
| 68 | 新增: switch { | |
| 69 | 新增: case t.localErr != nil: | |
| 70 | 新增: state.State, state.Phase, state.ErrorCode, state.Message = "failed", "", "local_unavailable", t.localErr.Error() | |
| 71 | 新增: case t.session != nil && t.session.Context.Err() == nil: | |
| 72 | 新增: manifest := t.session.Manifest | |
| 73 | 新增: state.State, state.Phase, state.Message = "connected", "", "已连接本机环境" | |
| 74 | 新增: state.InstanceID, state.Manifest = manifest.InstanceID, &manifest | |
| 75 | 新增: case t.session != nil || t.ctx.Err() != nil: | |
| 76 | 新增: state.State, state.Phase, state.ErrorCode, state.Message = "failed", "", "connection_lost", "本机工作台连接已断开,请重新连接" | |
| 77 | 新增: } | |
| 78 | 新增: return state | |
| 79 | 新增:} | |
| 80 | 新增: | |
| 81 | 新增:func (t *desktopTarget) acquire() (*remotehost.Session, error) { | |
| 82 | 新增: if t.remote != nil { | |
| 83 | 新增: return t.remote.Acquire(t.id) | |
| 84 | 新增: } | |
| 85 | 新增: t.mu.Lock() | |
| 86 | 新增: defer t.mu.Unlock() | |
| 87 | 新增: if t.session == nil || t.ctx.Err() != nil || t.session.Context.Err() != nil { | |
| 88 | 新增: return nil, errors.New("本机工作台尚未连接") | |
| 89 | 新增: } | |
| 90 | 新增: return t.session, nil | |
| 91 | 新增:} | |
| 92 | 新增: | |
| 93 | 新增:func (t *desktopTarget) close() { | |
| 94 | 新增: if t == nil { | |
| 95 | 新增: return | |
| 96 | 新增: } | |
| 97 | 新增: t.cancel() | |
| 98 | 新增: if t.remote != nil { | |
| 99 | 新增: _ = t.remote.Close() | |
| 100 | 新增: return | |
| 101 | 新增: } | |
| 102 | 新增: if t.localDone != nil { | |
| 103 | 新增: <-t.localDone | |
| 104 | 新增: } | |
| 105 | 新增: t.mu.Lock() | |
| 106 | 新增: s := t.session | |
| 107 | 新增: t.mu.Unlock() | |
| 108 | 新增: if s != nil { | |
| 109 | 新增: _ = s.Close() | |
| 110 | 新增: } | |
| 111 | 新增:} | |
| 112 | 新增: | |
| 113 | 新增:func (t *desktopTarget) candidate() *desktopCandidate { | |
| 114 | 新增: if t == nil { | |
| 115 | 新增: return nil | |
| 116 | 新增: } | |
| 117 | 新增: return &desktopCandidate{ID: t.id, Mode: t.mode, Connection: t.state()} | |
| 118 | 新增:} | |
| 119 | 新增: | |
| 120 | 新增:type desktopGateway struct { | |
| 121 | 新增: // A slow stop can serialize selection changes, but status and requests for | |
| 122 | 新增: // the current workbench must remain available while it finishes. | |
| 123 | 新增: change sync.Mutex | |
| 124 | 新增: mu sync.RWMutex | |
| 125 | 新增: store *remotehost.Store | |
| 126 | 新增: local DesktopLocalController | |
| 127 | 新增: generation string | |
| 128 | 新增: active, pending *desktopTarget | |
| 129 | 新增: closed bool | |
| 130 | 新增: departing bool | |
| 131 | 新增:} | |
| 132 | 新增: | |
| 133 | 新增:func newDesktopGateway(profile string, local DesktopLocalController) *remoteGateway { | |
| 134 | 新增: g := newRemoteGateway(profile) | |
| 135 | 新增: g.desktop = &desktopGateway{local: local, store: g.store, generation: randomToken()} | |
| 136 | 新增: return g | |
| 137 | 新增:} | |
| 138 | 新增: | |
| 139 | 新增:func (d *desktopGateway) context() ClientContext { | |
| 140 | 新增: d.mu.RLock() | |
| 141 | 新增: generation, active, pending := d.generation, d.active, d.pending | |
| 142 | 新增: d.mu.RUnlock() | |
| 143 | 新增: c := ClientContext{DesktopGateway: true, Mode: "none", ConnectionID: generation, ClientPlatform: runtime.GOOS, State: remotehost.ConnectionState{State: "disconnected"}, Candidate: pending.candidate()} | |
| 144 | 新增: if active == nil { | |
| 145 | 新增: return c | |
| 146 | 新增: } | |
| 147 | 新增: c.Mode, c.State = active.mode, active.state() | |
| 148 | 新增: c.HostID, c.InstanceID = c.State.HostID, c.State.InstanceID | |
| 149 | 新增: if active.mode == "local" { | |
| 150 | 新增: c.Name, c.ServerPlatform = "本机环境", runtime.GOOS | |
| 151 | 新增: } else { | |
| 152 | 新增: c.ServerPlatform = "linux" | |
| 153 | 新增: if p, err := d.store.Get(c.HostID); err == nil { | |
| 154 | 新增: c.Name = p.Name | |
| 155 | 新增: if p.HostKey != nil { | |
| 156 | 新增: c.HostFingerprint = p.HostKey.Fingerprint | |
| 157 | 新增: } | |
| 158 | 新增: } | |
| 159 | 新增: } | |
| 160 | 新增: return c | |
| 161 | 新增:} | |
| 162 | 新增: | |
| 163 | 新增:type switchRequest struct { | |
| 164 | 新增: ConnectionID string `json:"connection_id"` | |
| 165 | 新增: CandidateID string `json:"candidate_id,omitempty"` | |
| 166 | 新增: Mode string `json:"mode,omitempty"` | |
| 167 | 新增: HostID string `json:"host_id,omitempty"` | |
| 168 | 新增: Deploy bool `json:"deploy,omitempty"` | |
| 169 | 新增: Passphrase string `json:"passphrase,omitempty"` | |
| 170 | 新增: LocalAction string `json:"local_action,omitempty"` | |
| 171 | 新增: LocalControllerID string `json:"local_controller_id,omitempty"` | |
| 172 | 新增:} | |
| 173 | 新增: | |
| 174 | 新增:func (d *desktopGateway) checkGeneration(id string) error { | |
| 175 | 新增: d.mu.RLock() | |
| 176 | 新增: defer d.mu.RUnlock() | |
| 177 | 新增: if d.closed || id == "" || id != d.generation { | |
| 178 | 新增: return errViewChanged | |
| 179 | 新增: } | |
| 180 | 新增: return nil | |
| 181 | 新增:} | |
| 182 | 新增: | |
| 183 | 新增:// The selected route stays available throughout the candidate handshake. | |
| 184 | 新增:func (d *desktopGateway) prepare(in switchRequest) (*desktopCandidate, error) { | |
| 185 | 新增: d.change.Lock() | |
| 186 | 新增: defer d.change.Unlock() | |
| 187 | 新增: if err := d.checkGeneration(in.ConnectionID); err != nil { | |
| 188 | 新增: return nil, err | |
| 189 | 新增: } | |
| 190 | 新增: if d.pending != nil { | |
| 191 | 新增: return nil, errors.New("请先取消当前候选连接") | |
| 192 | 新增: } | |
| 193 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 194 | 新增: t := &desktopTarget{mode: in.Mode, ctx: ctx, cancel: cancel} | |
| 195 | 新增: switch in.Mode { | |
| 196 | 新增: case "remote": | |
| 197 | 新增: t.remote = remotehost.NewManager(d.store) | |
| 198 | 新增: secret := []byte(in.Passphrase) | |
| 199 | 新增: st, err := t.remote.Connect(in.HostID, remotehost.ConnectSecrets{Passphrase: secret, Deploy: in.Deploy}) | |
| 200 | 新增: clear(secret) | |
| 201 | 新增: if err != nil { | |
| 202 | 新增: t.close() | |
| 203 | 新增: return nil, err | |
| 204 | 新增: } | |
| 205 | 新增: t.id = st.ConnectionID | |
| 206 | 新增: case "local": | |
| 207 | 新增: if d.active != nil && d.active.mode == "local" && d.active.state().State == "connected" { | |
| 208 | 新增: t.close() | |
| 209 | 新增: return nil, errors.New("已连接当前本机工作台") | |
| 210 | 新增: } | |
| 211 | 新增: t.id = randomToken() | |
| 212 | 新增: if d.local == nil { | |
| 213 | 新增: t.close() | |
| 214 | 新增: return nil, errors.New("本机运行组件不可用") | |
| 215 | 新增: } | |
| 216 | 新增: t.localDone = make(chan struct{}) | |
| 217 | 新增: go func() { | |
| 218 | 新增: defer close(t.localDone) | |
| 219 | 新增: session, err := d.local.Connect(ctx) | |
| 220 | 新增: t.mu.Lock() | |
| 221 | 新增: t.session, t.localErr = session, err | |
| 222 | 新增: t.mu.Unlock() | |
| 223 | 新增: }() | |
| 224 | 新增: default: | |
| 225 | 新增: t.close() | |
| 226 | 新增: return nil, errors.New("请选择本机或远程主机") | |
| 227 | 新增: } | |
| 228 | 新增: d.mu.Lock() | |
| 229 | 新增: d.pending = t | |
| 230 | 新增: d.mu.Unlock() | |
| 231 | 新增: return t.candidate(), nil | |
| 232 | 新增:} | |
| 233 | 新增: | |
| 234 | 新增:func (d *desktopGateway) matchesCandidate(in switchRequest) (*desktopTarget, error) { | |
| 235 | 新增: if err := d.checkGeneration(in.ConnectionID); err != nil { | |
| 236 | 新增: return nil, err | |
| 237 | 新增: } | |
| 238 | 新增: if d.pending == nil || in.CandidateID == "" || in.CandidateID != d.pending.id { | |
| 239 | 新增: return nil, errCandidateChanged | |
| 240 | 新增: } | |
| 241 | 新增: return d.pending, nil | |
| 242 | 新增:} | |
| 243 | 新增: | |
| 244 | 新增:func (d *desktopGateway) cancelCandidate(in switchRequest) error { | |
| 245 | 新增: d.change.Lock() | |
| 246 | 新增: defer d.change.Unlock() | |
| 247 | 新增: t, err := d.matchesCandidate(in) | |
| 248 | 新增: if err != nil { | |
| 249 | 新增: return err | |
| 250 | 新增: } | |
| 251 | 新增: d.mu.Lock() | |
| 252 | 新增: d.pending = nil | |
| 253 | 新增: d.mu.Unlock() | |
| 254 | 新增: d.discard(t) | |
| 255 | 新增: return nil | |
| 256 | 新增:} | |
| 257 | 新增: | |
| 258 | 新增:// A cancelled local candidate may have started an idle controller. Its owner | |
| 259 | 新增:// can release that exact fresh process after rechecking its private launch ID. | |
| 260 | 新增:func (d *desktopGateway) discard(t *desktopTarget) { | |
| 261 | 新增: t.close() | |
| 262 | 新增: if t == nil || t.mode != "local" || t.session == nil { | |
| 263 | 新增: return | |
| 264 | 新增: } | |
| 265 | 新增: if owner, ok := d.local.(interface { | |
| 266 | 新增: ReleaseUnused(context.Context, *remotehost.Session) error | |
| 267 | 新增: }); ok { | |
| 268 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) | |
| 269 | 新增: defer cancel() | |
| 270 | 新增: if err := owner.ReleaseUnused(ctx, t.session); err != nil { | |
| 271 | 新增: diagnostics.Log("warn", "controller", "取消本机候选后未能确认空闲服务已释放") | |
| 272 | 新增: } | |
| 273 | 新增: } | |
| 274 | 新增:} | |
| 275 | 新增: | |
| 276 | 新增:func (d *desktopGateway) stopLocal(ctx context.Context, expected string) error { | |
| 277 | 新增: if d.local == nil || expected == "" { | |
| 278 | 新增: return errors.New("无法确认本机后台身份,请刷新本机状态") | |
| 279 | 新增: } | |
| 280 | 新增: st, err := d.local.Status(ctx) | |
| 281 | 新增: if err != nil { | |
| 282 | 新增: return err | |
| 283 | 新增: } | |
| 284 | 新增: if !st.Known || st.ControllerID != expected { | |
| 285 | 新增: return errors.New("本机后台已变化,请刷新状态后再停止") | |
| 286 | 新增: } | |
| 287 | 新增: return d.local.Release(ctx, st, true) | |
| 288 | 新增:} | |
| 289 | 新增: | |
| 290 | 新增:func (d *desktopGateway) stopLocalCard(ctx context.Context, in switchRequest) error { | |
| 291 | 新增: d.change.Lock() | |
| 292 | 新增: defer d.change.Unlock() | |
| 293 | 新增: if err := d.checkGeneration(in.ConnectionID); err != nil { | |
| 294 | 新增: return err | |
| 295 | 新增: } | |
| 296 | 新增: selected := d.active != nil && d.active.mode == "local" | |
| 297 | 新增: if selected { | |
| 298 | 新增: resume := d.freezeView() | |
| 299 | 新增: defer resume() | |
| 300 | 新增: } | |
| 301 | 新增: if err := d.stopLocal(ctx, in.LocalControllerID); err != nil { | |
| 302 | 新增: return err | |
| 303 | 新增: } | |
| 304 | 新增: if selected { | |
| 305 | 新增: d.clearSelection() | |
| 306 | 新增: } | |
| 307 | 新增: return nil | |
| 308 | 新增:} | |
| 309 | 新增: | |
| 310 | 新增:func suspendLocalView(ctx context.Context, t *desktopTarget) error { | |
| 311 | 新增: session, err := t.acquire() | |
| 312 | 新增: if err != nil { | |
| 313 | 新增: return err | |
| 314 | 新增: } | |
| 315 | 新增: req, err := http.NewRequestWithContext(ctx, http.MethodPost, session.Origin+"/api/account/suspend", strings.NewReader("{}")) | |
| 316 | 新增: if err != nil { | |
| 317 | 新增: return err | |
| 318 | 新增: } | |
| 319 | 新增: req.Header.Set("Origin", session.Origin) | |
| 320 | 新增: req.Header.Set("Content-Type", "application/json") | |
| 321 | 新增: response, err := session.Client.Do(req) | |
| 322 | 新增: if err != nil { | |
| 323 | 新增: return errors.New("未能锁定本机会话,请重新连接本机工作台") | |
| 324 | 新增: } | |
| 325 | 新增: defer response.Body.Close() | |
| 326 | 新增: if response.StatusCode != http.StatusOK && response.StatusCode != http.StatusNoContent && response.StatusCode != http.StatusLocked { | |
| 327 | 新增: return errors.New("本机工作台未确认账户锁定") | |
| 328 | 新增: } | |
| 329 | 新增: return nil | |
| 330 | 新增:} | |
| 331 | 新增: | |
| 332 | 新增:func (d *desktopGateway) leaveLocal(ctx context.Context, in switchRequest, old *desktopTarget) error { | |
| 333 | 新增: switch in.LocalAction { | |
| 334 | 新增: case "stop": | |
| 335 | 新增: return d.stopLocal(ctx, in.LocalControllerID) | |
| 336 | 新增: case "keep": | |
| 337 | 新增: if old != nil && old.mode == "local" { | |
| 338 | 新增: return suspendLocalView(ctx, old) | |
| 339 | 新增: } | |
| 340 | 新增: return nil | |
| 341 | 新增: case "", "auto": | |
| 342 | 新增: if d.local == nil { | |
| 343 | 新增: return nil | |
| 344 | 新增: } | |
| 345 | 新增: st, err := d.local.Status(ctx) | |
| 346 | 新增: if err != nil || !st.Known || st.Running || st.Busy || st.LiveTerminals > 0 { | |
| 347 | 新增: return errors.New("本机环境可能仍有任务,请选择保留运行或停止本机") | |
| 348 | 新增: } | |
| 349 | 新增: if !st.ServiceRunning { | |
| 350 | 新增: return nil | |
| 351 | 新增: } | |
| 352 | 新增: released, err := d.local.ReleaseOwnedIdle(ctx, st) | |
| 353 | 新增: if err != nil { | |
| 354 | 新增: return err | |
| 355 | 新增: } | |
| 356 | 新增: if !released && old != nil && old.mode == "local" && old.state().State == "connected" { | |
| 357 | 新增: return suspendLocalView(ctx, old) | |
| 358 | 新增: } | |
| 359 | 新增: return nil | |
| 360 | 新增: default: | |
| 361 | 新增: return errors.New("本机处理方式无效") | |
| 362 | 新增: } | |
| 363 | 新增:} | |
| 364 | 新增: | |
| 365 | 新增:func (d *desktopGateway) commit(ctx context.Context, in switchRequest) error { | |
| 366 | 新增: d.change.Lock() | |
| 367 | 新增: defer d.change.Unlock() | |
| 368 | 新增: t, err := d.matchesCandidate(in) | |
| 369 | 新增: if err != nil { | |
| 370 | 新增: return err | |
| 371 | 新增: } | |
| 372 | 新增: if _, err = t.acquire(); err != nil { | |
| 373 | 新增: return errors.New("候选工作台尚未连接,当前工作台已保留") | |
| 374 | 新增: } | |
| 375 | 新增: old := d.active | |
| 376 | 新增: if old != nil && old.mode == "local" { | |
| 377 | 新增: resume := d.freezeView() | |
| 378 | 新增: defer resume() | |
| 379 | 新增: } | |
| 380 | 新增: if t.mode == "remote" { | |
| 381 | 新增: if err = d.leaveLocal(ctx, in, old); err != nil { | |
| 382 | 新增: return err | |
| 383 | 新增: } | |
| 384 | 新增: } | |
| 385 | 新增: if _, err = t.acquire(); err != nil { | |
| 386 | 新增: return errors.New("候选工作台连接已中断,请重新连接") | |
| 387 | 新增: } | |
| 388 | 新增: d.mu.Lock() | |
| 389 | 新增: d.generation, d.active, d.pending = t.id, t, nil | |
| 390 | 新增: d.mu.Unlock() | |
| 391 | 新增: old.close() | |
| 392 | 新增: return nil | |
| 393 | 新增:} | |
| 394 | 新增: | |
| 395 | 新增:// While a confirmed switch releases or suspends the old controller, another | |
| 396 | 新增:// window must not start new work through that view. A failed commit reopens | |
| 397 | 新增:// admission to the same generation. | |
| 398 | 新增:func (d *desktopGateway) freezeView() func() { | |
| 399 | 新增: d.mu.Lock() | |
| 400 | 新增: d.departing = true | |
| 401 | 新增: d.mu.Unlock() | |
| 402 | 新增: return func() { | |
| 403 | 新增: d.mu.Lock() | |
| 404 | 新增: d.departing = false | |
| 405 | 新增: d.mu.Unlock() | |
| 406 | 新增: } | |
| 407 | 新增:} | |
| 408 | 新增: | |
| 409 | 新增:func (d *desktopGateway) disconnect(ctx context.Context, in switchRequest) error { | |
| 410 | 新增: d.change.Lock() | |
| 411 | 新增: defer d.change.Unlock() | |
| 412 | 新增: if err := d.checkGeneration(in.ConnectionID); err != nil { | |
| 413 | 新增: return err | |
| 414 | 新增: } | |
| 415 | 新增: resume := d.freezeView() | |
| 416 | 新增: defer resume() | |
| 417 | 新增: if t := d.active; t != nil && t.mode == "local" && t.state().State == "connected" { | |
| 418 | 新增: if err := suspendLocalView(ctx, t); err != nil { | |
| 419 | 新增: return err | |
| 420 | 新增: } | |
| 421 | 新增: } | |
| 422 | 新增: d.clearSelection() | |
| 423 | 新增: return nil | |
| 424 | 新增:} | |
| 425 | 新增: | |
| 426 | 新增:// Called with change locked. Invalidate before closing transports so stale | |
| 427 | 新增:// callbacks cannot submit commands to a newly chosen target. | |
| 428 | 新增:func (d *desktopGateway) clearSelection() { | |
| 429 | 新增: d.mu.Lock() | |
| 430 | 新增: old, pending := d.active, d.pending | |
| 431 | 新增: d.active, d.pending, d.generation = nil, nil, randomToken() | |
| 432 | 新增: d.mu.Unlock() | |
| 433 | 新增: d.discard(old) | |
| 434 | 新增: d.discard(pending) | |
| 435 | 新增:} | |
| 436 | 新增: | |
| 437 | 新增:func (d *desktopGateway) acquire(id string) (*remotehost.Session, bool, error) { | |
| 438 | 新增: d.mu.RLock() | |
| 439 | 新增: defer d.mu.RUnlock() | |
| 440 | 新增: if d.closed || d.active == nil { | |
| 441 | 新增: return nil, false, errViewChanged | |
| 442 | 新增: } | |
| 443 | 新增: if d.departing || id == "" || id != d.generation { | |
| 444 | 新增: return nil, d.active.mode == "remote", errViewChanged | |
| 445 | 新增: } | |
| 446 | 新增: session, err := d.active.acquire() | |
| 447 | 新增: return session, d.active.mode == "remote", err | |
| 448 | 新增:} | |
| 449 | 新增: | |
| 450 | 新增:func (d *desktopGateway) close() { | |
| 451 | 新增: d.change.Lock() | |
| 452 | 新增: defer d.change.Unlock() | |
| 453 | 新增: if d.closed { | |
| 454 | 新增: return | |
| 455 | 新增: } | |
| 456 | 新增: d.mu.Lock() | |
| 457 | 新增: d.closed = true | |
| 458 | 新增: d.mu.Unlock() | |
| 459 | 新增: if t := d.active; t != nil && t.mode == "local" && t.state().State == "connected" { | |
| 460 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 461 | 新增: _ = suspendLocalView(ctx, t) | |
| 462 | 新增: cancel() | |
| 463 | 新增: } | |
| 464 | 新增: d.clearSelection() | |
| 465 | 新增:} | |
| 466 | 新增: | |
| 467 | 新增:func (d *desktopGateway) handle(path string, w http.ResponseWriter, r *http.Request) bool { | |
| 468 | 新增: if path == "local-status" && r.Method == http.MethodGet { | |
| 469 | 新增: if d.local == nil { | |
| 470 | 新增: jsonReply(w, DesktopLocalStatus{Known: true}) | |
| 471 | 新增: return true | |
| 472 | 新增: } | |
| 473 | 新增: st, err := d.local.Status(r.Context()) | |
| 474 | 新增: if err != nil { | |
| 475 | 新增: http.Error(w, err.Error(), http.StatusServiceUnavailable) | |
| 476 | 新增: return true | |
| 477 | 新增: } | |
| 478 | 新增: jsonReply(w, st) | |
| 479 | 新增: return true | |
| 480 | 新增: } | |
| 481 | 新增: switch path { | |
| 482 | 新增: case "candidate", "commit", "cancel", "disconnect", "local-stop": | |
| 483 | 新增: case "local", "connect": | |
| 484 | 新增: http.Error(w, "请通过候选连接选择工作环境", http.StatusConflict) | |
| 485 | 新增: return true | |
| 486 | 新增: default: | |
| 487 | 新增: return false | |
| 488 | 新增: } | |
| 489 | 新增: if r.Method != http.MethodPost { | |
| 490 | 新增: http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) | |
| 491 | 新增: return true | |
| 492 | 新增: } | |
| 493 | 新增: var in switchRequest | |
| 494 | 新增: if !readJSON(w, r, &in) { | |
| 495 | 新增: return true | |
| 496 | 新增: } | |
| 497 | 新增: var err error | |
| 498 | 新增: switch path { | |
| 499 | 新增: case "candidate": | |
| 500 | 新增: var c *desktopCandidate | |
| 501 | 新增: c, err = d.prepare(in) | |
| 502 | 新增: if err == nil { | |
| 503 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 504 | 新增: w.WriteHeader(http.StatusAccepted) | |
| 505 | 新增: jsonReply(w, c) | |
| 506 | 新增: return true | |
| 507 | 新增: } | |
| 508 | 新增: case "commit": | |
| 509 | 新增: err = d.commit(r.Context(), in) | |
| 510 | 新增: case "cancel": | |
| 511 | 新增: err = d.cancelCandidate(in) | |
| 512 | 新增: case "disconnect": | |
| 513 | 新增: err = d.disconnect(r.Context(), in) | |
| 514 | 新增: case "local-stop": | |
| 515 | 新增: err = d.stopLocalCard(r.Context(), in) | |
| 516 | 新增: } | |
| 517 | 新增: if err != nil { | |
| 518 | 新增: code := http.StatusConflict | |
| 519 | 新增: if errors.Is(err, errDesktopLocalLocked) { | |
| 520 | 新增: code = http.StatusLocked | |
| 521 | 新增: } | |
| 522 | 新增: http.Error(w, err.Error(), code) | |
| 523 | 新增: return true | |
| 524 | 新增: } | |
| 525 | 新增: jsonReply(w, d.context()) | |
| 526 | 新增: return true | |
| 527 | 新增:} | |
| @@ -0,0 +1,295 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/http/httptest" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "sync/atomic" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增: | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:type gatewayLocalFixture struct { | |
| 19 | 新增: endpoint *httptest.Server | |
| 20 | 新增: connections, suspended, commands atomic.Int32 | |
| 21 | 新增: status DesktopLocalStatus | |
| 22 | 新增: release func(DesktopLocalStatus, bool) error | |
| 23 | 新增: owned bool | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func gatewayFixture(t *testing.T) (*Server, *gatewayLocalFixture) { | |
| 27 | 新增: t.Helper() | |
| 28 | 新增: s := testServer(t) | |
| 29 | 新增: f := &gatewayLocalFixture{status: DesktopLocalStatus{Known: true, Available: true}} | |
| 30 | 新增: f.endpoint = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 31 | 新增: w.Header().Set("Content-Type", "application/json") | |
| 32 | 新增: switch r.URL.Path { | |
| 33 | 新增: case "/api/account/suspend": | |
| 34 | 新增: var input map[string]any | |
| 35 | 新增: if r.Header.Get("Content-Type") != "application/json" || json.NewDecoder(r.Body).Decode(&input) != nil { | |
| 36 | 新增: http.Error(w, "invalid account request", 400) | |
| 37 | 新增: return | |
| 38 | 新增: } | |
| 39 | 新增: f.suspended.Add(1) | |
| 40 | 新增: default: | |
| 41 | 新增: f.commands.Add(1) | |
| 42 | 新增: } | |
| 43 | 新增: _, _ = w.Write([]byte(`{"upstream":"local-controller"}`)) | |
| 44 | 新增: })) | |
| 45 | 新增: t.Cleanup(f.endpoint.Close) | |
| 46 | 新增: s.remote = newDesktopGateway(s.profile, f) | |
| 47 | 新增: t.Cleanup(s.remote.close) | |
| 48 | 新增: return s, f | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func (f *gatewayLocalFixture) Connect(ctx context.Context) (*remotehost.Session, error) { | |
| 52 | 新增: f.connections.Add(1) | |
| 53 | 新增: return &remotehost.Session{Origin: f.endpoint.URL, Client: f.endpoint.Client(), Transport: f.endpoint.Client().Transport, Context: ctx, Manifest: remotehost.PublicManifest{Platform: "linux", InstanceID: strings.Repeat("a", 64)}}, nil | |
| 54 | 新增:} | |
| 55 | 新增:func (f *gatewayLocalFixture) Status(context.Context) (DesktopLocalStatus, error) { | |
| 56 | 新增: return f.status, nil | |
| 57 | 新增:} | |
| 58 | 新增:func (f *gatewayLocalFixture) Release(_ context.Context, expected DesktopLocalStatus, stop bool) error { | |
| 59 | 新增: if f.release == nil { | |
| 60 | 新增: return errors.New("unexpected release") | |
| 61 | 新增: } | |
| 62 | 新增: return f.release(expected, stop) | |
| 63 | 新增:} | |
| 64 | 新增: | |
| 65 | 新增:func (f *gatewayLocalFixture) ReleaseOwnedIdle(context.Context, DesktopLocalStatus) (bool, error) { | |
| 66 | 新增: return f.owned, nil | |
| 67 | 新增:} | |
| 68 | 新增: | |
| 69 | 新增:func candidateState(t *testing.T, d *desktopGateway, want string) *desktopCandidate { | |
| 70 | 新增: t.Helper() | |
| 71 | 新增: deadline := time.Now().Add(time.Second * 5) | |
| 72 | 新增: for time.Now().Before(deadline) { | |
| 73 | 新增: c := d.context().Candidate | |
| 74 | 新增: if c != nil && c.Connection.State == want { | |
| 75 | 新增: return c | |
| 76 | 新增: } | |
| 77 | 新增: time.Sleep(time.Millisecond * 5) | |
| 78 | 新增: } | |
| 79 | 新增: t.Fatalf("candidate did not reach %s: %+v", want, d.context().Candidate) | |
| 80 | 新增: return nil | |
| 81 | 新增:} | |
| 82 | 新增: | |
| 83 | 新增:func gatewayRequest(s *Server, path, generation string) *httptest.ResponseRecorder { | |
| 84 | 新增: r := httptest.NewRequest("GET", s.origin+path, nil) | |
| 85 | 新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 86 | 新增: if generation != "" { | |
| 87 | 新增: r.Header.Set(connectionHeader, generation) | |
| 88 | 新增: } | |
| 89 | 新增: w := httptest.NewRecorder() | |
| 90 | 新增: s.handler().ServeHTTP(w, r) | |
| 91 | 新增: return w | |
| 92 | 新增:} | |
| 93 | 新增: | |
| 94 | 新增:func chooseLocal(t *testing.T, d *desktopGateway, id string) string { | |
| 95 | 新增: t.Helper() | |
| 96 | 新增: c, e := d.prepare(switchRequest{ConnectionID: id, Mode: "local"}) | |
| 97 | 新增: if e != nil { | |
| 98 | 新增: t.Fatal(e) | |
| 99 | 新增: } | |
| 100 | 新增: candidateState(t, d, "connected") | |
| 101 | 新增: if e = d.commit(context.Background(), switchRequest{ConnectionID: id, CandidateID: c.ID}); e != nil { | |
| 102 | 新增: t.Fatal(e) | |
| 103 | 新增: } | |
| 104 | 新增: return c.ID | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:func TestDesktopCandidateFailurePreservesLiveViewAndStaleLocalIDs(t *testing.T) { | |
| 108 | 新增: s, f := gatewayFixture(t) | |
| 109 | 新增: d := s.remote.desktop | |
| 110 | 新增: none := d.context().ConnectionID | |
| 111 | 新增: if c := d.context(); c.Mode != "none" || c.ConnectionID == "" || f.connections.Load() != 0 { | |
| 112 | 新增: t.Fatal("cold shell started a local controller", c) | |
| 113 | 新增: } | |
| 114 | 新增: if got := gatewayRequest(s, "/api/account", none); got.Code != 409 { | |
| 115 | 新增: t.Fatal("unselected view exposed a local business API", got.Code) | |
| 116 | 新增: } | |
| 117 | 新增: local := chooseLocal(t, d, none) | |
| 118 | 新增: if got := gatewayRequest(s, "/api/status", local); got.Code != 200 || !strings.Contains(got.Body.String(), "local-controller") { | |
| 119 | 新增: t.Fatal("selected view did not go to the local controller", got.Code, got.Body.String()) | |
| 120 | 新增: } | |
| 121 | 新增: // The SSH connector fails on our nonexistent fixture key, before network access. | |
| 122 | 新增: host, err := s.remote.store.Upsert(remotehost.HostProfile{Name: "fixture", Host: "127.0.0.1", Port: 22, User: "cage", Auth: remotehost.AuthConfig{Kind: "key_file", IdentityFile: filepath.Join(t.TempDir(), "absent")}}) | |
| 123 | 新增: if err != nil { | |
| 124 | 新增: t.Fatal(err) | |
| 125 | 新增: } | |
| 126 | 新增: remote, err := d.prepare(switchRequest{ConnectionID: local, Mode: "remote", HostID: host.ID}) | |
| 127 | 新增: if err != nil { | |
| 128 | 新增: t.Fatal(err) | |
| 129 | 新增: } | |
| 130 | 新增: candidateState(t, d, "failed") | |
| 131 | 新增: if got := gatewayRequest(s, "/api/status", remote.ID); got.Code != 409 { | |
| 132 | 新增: t.Fatal("uncommitted target dispatched a business API", got.Code) | |
| 133 | 新增: } | |
| 134 | 新增: if err = d.commit(context.Background(), switchRequest{ConnectionID: local, CandidateID: remote.ID, LocalAction: "stop"}); err == nil { | |
| 135 | 新增: t.Fatal("failed candidate could stop or replace the current view") | |
| 136 | 新增: } | |
| 137 | 新增: if got := gatewayRequest(s, "/api/status", local); got.Code != 200 || f.commands.Load() != 2 || f.suspended.Load() != 0 { | |
| 138 | 新增: t.Fatal("candidate failure affected the live view") | |
| 139 | 新增: } | |
| 140 | 新增: if err = d.cancelCandidate(switchRequest{ConnectionID: local, CandidateID: remote.ID}); err != nil { | |
| 141 | 新增: t.Fatal(err) | |
| 142 | 新增: } | |
| 143 | 新增: if err = d.disconnect(context.Background(), switchRequest{ConnectionID: local}); err != nil { | |
| 144 | 新增: t.Fatal(err) | |
| 145 | 新增: } | |
| 146 | 新增: second := chooseLocal(t, d, d.context().ConnectionID) | |
| 147 | 新增: if second == local || f.suspended.Load() != 1 { | |
| 148 | 新增: t.Fatal("local reconnection reused a generation or failed to suspend the old view") | |
| 149 | 新增: } | |
| 150 | 新增: for _, stale := range []string{"", none, "local", local, remote.ID} { | |
| 151 | 新增: if got := gatewayRequest(s, "/api/status", stale); got.Code != 409 { | |
| 152 | 新增: t.Fatalf("obsolete ID %q reached local runtime, code %d", stale, got.Code) | |
| 153 | 新增: } | |
| 154 | 新增: } | |
| 155 | 新增: if got := gatewayRequest(s, "/api/status", second); got.Code != 200 { | |
| 156 | 新增: t.Fatal("current connection rejected", got.Code) | |
| 157 | 新增: } | |
| 158 | 新增:} | |
| 159 | 新增: | |
| 160 | 新增:func TestDesktopRemoteCommitRequiresDecisionBeforeReleasingObservedLocal(t *testing.T) { | |
| 161 | 新增: s, f := gatewayFixture(t) | |
| 162 | 新增: d := s.remote.desktop | |
| 163 | 新增: original := chooseLocal(t, d, d.context().ConnectionID) | |
| 164 | 新增: f.status = DesktopLocalStatus{Available: true, Known: true, Running: true, ServiceRunning: true, LiveTerminals: 1, ControllerID: "current-controller"} | |
| 165 | 新增: // Supply a completed transport here; SSH key authentication and forwarding | |
| 166 | 新增: // are tested by remotehost's real SSH fixture. This test owns the commit race. | |
| 167 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 168 | 新增: session, err := f.Connect(ctx) | |
| 169 | 新增: if err != nil { | |
| 170 | 新增: t.Fatal(err) | |
| 171 | 新增: } | |
| 172 | 新增: candidate := &desktopTarget{id: "remote-generation", mode: "remote", ctx: ctx, cancel: cancel, session: session} | |
| 173 | 新增: d.mu.Lock() | |
| 174 | 新增: d.pending = candidate | |
| 175 | 新增: d.mu.Unlock() | |
| 176 | 新增: in := switchRequest{ConnectionID: original, CandidateID: candidate.id, LocalAction: "auto"} | |
| 177 | 新增: if err := d.commit(context.Background(), in); err == nil { | |
| 178 | 新增: t.Fatal("auto released a busy local controller") | |
| 179 | 新增: } | |
| 180 | 新增: in.LocalAction = "stop" | |
| 181 | 新增: in.LocalControllerID = "obsolete-controller" | |
| 182 | 新增: if err := d.commit(context.Background(), in); err == nil { | |
| 183 | 新增: t.Fatal("obsolete controller ID stopped the replacement") | |
| 184 | 新增: } | |
| 185 | 新增: in.LocalControllerID = f.status.ControllerID | |
| 186 | 新增: f.release = func(observed DesktopLocalStatus, stop bool) error { | |
| 187 | 新增: if !stop || observed.ControllerID != f.status.ControllerID { | |
| 188 | 新增: t.Fatal("wrong stop target") | |
| 189 | 新增: } | |
| 190 | 新增: if got := gatewayRequest(s, "/api/status", original); got.Code != http.StatusConflict { | |
| 191 | 新增: t.Fatal("another window admitted a business request while releasing the local controller") | |
| 192 | 新增: } | |
| 193 | 新增: return errDesktopLocalLocked | |
| 194 | 新增: } | |
| 195 | 新增: if err := d.commit(context.Background(), in); !errors.Is(err, errDesktopLocalLocked) { | |
| 196 | 新增: t.Fatalf("locked account result %v", err) | |
| 197 | 新增: } | |
| 198 | 新增: if d.context().ConnectionID != original || f.suspended.Load() != 0 { | |
| 199 | 新增: t.Fatal("failed stop changed current selection") | |
| 200 | 新增: } | |
| 201 | 新增: if got := gatewayRequest(s, "/api/status", original); got.Code != http.StatusOK { | |
| 202 | 新增: t.Fatal("failed stop left admission frozen for the retained local view") | |
| 203 | 新增: } | |
| 204 | 新增: in.LocalAction = "keep" | |
| 205 | 新增: if err := d.commit(context.Background(), in); err != nil { | |
| 206 | 新增: t.Fatal(err) | |
| 207 | 新增: } | |
| 208 | 新增: if now := d.context(); now.Mode != "remote" || now.ConnectionID != candidate.id || now.Candidate != nil || f.suspended.Load() != 1 { | |
| 209 | 新增: t.Fatalf("incorrect committed view or unsuspended previous view: %+v", now) | |
| 210 | 新增: } | |
| 211 | 新增: if got := gatewayRequest(s, "/api/status", original); got.Code != 409 { | |
| 212 | 新增: t.Fatal("old local request reached selected remote") | |
| 213 | 新增: } | |
| 214 | 新增: if err := d.disconnect(context.Background(), switchRequest{ConnectionID: original}); err == nil { | |
| 215 | 新增: t.Fatal("stale disconnect closed remote selection") | |
| 216 | 新增: } | |
| 217 | 新增:} | |
| 218 | 新增: | |
| 219 | 新增:func TestRemoteToRemoteSwitchHonorsBackgroundLocalDecision(t *testing.T) { | |
| 220 | 新增: for _, action := range []string{"keep", "stop"} { | |
| 221 | 新增: t.Run(action, func(t *testing.T) { | |
| 222 | 新增: s, local := gatewayFixture(t) | |
| 223 | 新增: d := s.remote.desktop | |
| 224 | 新增: local.status = DesktopLocalStatus{Known: true, Available: true, ServiceRunning: true, Running: true, LiveTerminals: 1, ControllerID: "background-controller"} | |
| 225 | 新增: // Use already authenticated views to isolate the decision made after | |
| 226 | 新增: // B's handshake while A is still the selected workbench. | |
| 227 | 新增: remoteView := func(id string) *desktopTarget { | |
| 228 | 新增: ctx, cancel := context.WithCancel(context.Background()) | |
| 229 | 新增: session, err := local.Connect(ctx) | |
| 230 | 新增: if err != nil { | |
| 231 | 新增: t.Fatal(err) | |
| 232 | 新增: } | |
| 233 | 新增: return &desktopTarget{id: id, mode: "remote", ctx: ctx, cancel: cancel, session: session} | |
| 234 | 新增: } | |
| 235 | 新增: a, b := remoteView("remote-A"), remoteView("remote-B") | |
| 236 | 新增: d.mu.Lock() | |
| 237 | 新增: d.generation, d.active, d.pending = a.id, a, b | |
| 238 | 新增: d.mu.Unlock() | |
| 239 | 新增: request := switchRequest{ConnectionID: a.id, CandidateID: b.id, LocalAction: "auto"} | |
| 240 | 新增: if err := d.commit(context.Background(), request); err == nil { | |
| 241 | 新增: t.Fatal("background local work did not require an explicit choice") | |
| 242 | 新增: } | |
| 243 | 新增: if got := gatewayRequest(s, "/api/status", a.id); got.Code != http.StatusOK { | |
| 244 | 新增: t.Fatal("A became unavailable while waiting for the local decision") | |
| 245 | 新增: } | |
| 246 | 新增: request.LocalAction, request.LocalControllerID = action, local.status.ControllerID | |
| 247 | 新增: stops := 0 | |
| 248 | 新增: local.release = func(expected DesktopLocalStatus, stop bool) error { | |
| 249 | 新增: stops++ | |
| 250 | 新增: if !stop || expected.ControllerID != local.status.ControllerID { | |
| 251 | 新增: t.Fatal("stopped the wrong controller") | |
| 252 | 新增: } | |
| 253 | 新增: if got := gatewayRequest(s, "/api/status", a.id); got.Code != http.StatusOK { | |
| 254 | 新增: t.Fatal("A was released before the local stop completed") | |
| 255 | 新增: } | |
| 256 | 新增: return nil | |
| 257 | 新增: } | |
| 258 | 新增: if err := d.commit(context.Background(), request); err != nil { | |
| 259 | 新增: t.Fatal(err) | |
| 260 | 新增: } | |
| 261 | 新增: if (action == "stop" && stops != 1) || (action == "keep" && stops != 0) || local.suspended.Load() != 0 { | |
| 262 | 新增: t.Fatalf("incorrect workload action: stop count %d, account suspensions %d", stops, local.suspended.Load()) | |
| 263 | 新增: } | |
| 264 | 新增: if d.context().ConnectionID != b.id || a.ctx.Err() == nil { | |
| 265 | 新增: t.Fatal("successful commit did not switch exclusively to B") | |
| 266 | 新增: } | |
| 267 | 新增: }) | |
| 268 | 新增: } | |
| 269 | 新增:} | |
| 270 | 新增: | |
| 271 | 新增:func TestRemoteAutoReleasesOnlyOwnedLocalService(t *testing.T) { | |
| 272 | 新增: for _, tc := range []struct { | |
| 273 | 新增: name string | |
| 274 | 新增: localView, owned bool | |
| 275 | 新增: wantSuspend int32 | |
| 276 | 新增: }{ | |
| 277 | 新增: {"external-service-with-no-local-view", false, false, 0}, | |
| 278 | 新增: {"external-service-with-local-view", true, false, 1}, | |
| 279 | 新增: {"owned-service-with-local-view", true, true, 0}, | |
| 280 | 新增: } { | |
| 281 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 282 | 新增: s, f := gatewayFixture(t) | |
| 283 | 新增: d := s.remote.desktop | |
| 284 | 新增: f.status = DesktopLocalStatus{Known: true, Available: true, ServiceRunning: true, ControllerID: "idle-service"} | |
| 285 | 新增: f.owned = tc.owned | |
| 286 | 新增: if tc.localView { | |
| 287 | 新增: chooseLocal(t, d, d.context().ConnectionID) | |
| 288 | 新增: } | |
| 289 | 新增: err := d.leaveLocal(context.Background(), switchRequest{LocalAction: "auto"}, d.active) | |
| 290 | 新增: if err != nil || f.suspended.Load() != tc.wantSuspend { | |
| 291 | 新增: t.Fatalf("auto used the wrong owner or directly stopped a controller: err=%v suspensions=%d", err, f.suspended.Load()) | |
| 292 | 新增: } | |
| 293 | 新增: }) | |
| 294 | 新增: } | |
| 295 | 新增:} | |
| @@ -0,0 +1,78 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: "strings" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func importDesktopConnections(full, entry string) error { | |
| 14 | 新增: old := []string{full, filepath.Join(full, "client")} | |
| 15 | 新增: if err := remotehost.NewStore(entry).ImportOnce(old...); err != nil { | |
| 16 | 新增: return err | |
| 17 | 新增: } | |
| 18 | 新增: marker := filepath.Join(entry, "downloads-imported.json") | |
| 19 | 新增: if err := host.CheckPrivateFile(marker); err == nil { | |
| 20 | 新增: return nil | |
| 21 | 新增: } else if !os.IsNotExist(err) { | |
| 22 | 新增: return err | |
| 23 | 新增: } | |
| 24 | 新增: // Import private records only, never copy a downloaded file or follow a | |
| 25 | 新增: // saved user path. A retry after interruption preserves the newest record. | |
| 26 | 新增: for _, profile := range old { | |
| 27 | 新增: root := filepath.Join(profile, "remote-downloads") | |
| 28 | 新增: info, err := os.Lstat(root) | |
| 29 | 新增: if os.IsNotExist(err) { | |
| 30 | 新增: continue | |
| 31 | 新增: } | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: return err | |
| 34 | 新增: } | |
| 35 | 新增: if !info.IsDir() { | |
| 36 | 新增: return errors.New("旧入口下载记录目录无效") | |
| 37 | 新增: } | |
| 38 | 新增: instances, err := os.ReadDir(root) | |
| 39 | 新增: if err != nil { | |
| 40 | 新增: return err | |
| 41 | 新增: } | |
| 42 | 新增: for _, instance := range instances { | |
| 43 | 新增: if !instance.IsDir() || !remoteInstanceID.MatchString(instance.Name()) { | |
| 44 | 新增: continue | |
| 45 | 新增: } | |
| 46 | 新增: from := filepath.Join(root, instance.Name()) | |
| 47 | 新增: files, err := os.ReadDir(filepath.Join(from, "browser-downloads")) | |
| 48 | 新增: if os.IsNotExist(err) { | |
| 49 | 新增: continue | |
| 50 | 新增: } | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: return err | |
| 53 | 新增: } | |
| 54 | 新增: to := filepath.Join(entry, "remote-downloads", instance.Name()) | |
| 55 | 新增: for _, file := range files { | |
| 56 | 新增: id := strings.TrimSuffix(file.Name(), ".json") | |
| 57 | 新增: if !file.Type().IsRegular() || !browserFileID.MatchString(id) { | |
| 58 | 新增: continue | |
| 59 | 新增: } | |
| 60 | 新增: record, err := readSavedDownload(from, id) | |
| 61 | 新增: if err != nil || record.InstanceID != instance.Name() { | |
| 62 | 新增: continue | |
| 63 | 新增: } | |
| 64 | 新增: current, err := readSavedDownload(to, id) | |
| 65 | 新增: if err == nil && !record.SavedAt.After(current.SavedAt) { | |
| 66 | 新增: continue | |
| 67 | 新增: } | |
| 68 | 新增: if err != nil && !os.IsNotExist(err) { | |
| 69 | 新增: return err | |
| 70 | 新增: } | |
| 71 | 新增: if err = writePrivate(savedDownloadPath(to, id), record); err != nil { | |
| 72 | 新增: return err | |
| 73 | 新增: } | |
| 74 | 新增: } | |
| 75 | 新增: } | |
| 76 | 新增: } | |
| 77 | 新增: return writePrivate(marker, struct{}{}) | |
| 78 | 新增:} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "os" | |
| 5 | 新增: "path/filepath" | |
| 6 | 新增: "testing" | |
| 7 | 新增: "time" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestDesktopImportPreservesBothLegacyProfilesAndRemovedHost(t *testing.T) { | |
| 13 | 新增: full := t.TempDir() | |
| 14 | 新增: entry := filepath.Dir(desktopConfigPath(filepath.Join(full, "config.json"))) | |
| 15 | 新增: client := filepath.Join(full, "client") | |
| 16 | 新增: first, err := remotehost.NewStore(full).Upsert(remotehost.HostProfile{Name: "full", Host: "full.example", User: "test", Auth: remotehost.AuthConfig{Kind: "agent"}}) | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: other, err := remotehost.NewStore(client).Upsert(remotehost.HostProfile{Name: "client", Host: "client.example", User: "test", Auth: remotehost.AuthConfig{Kind: "agent"}}) | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: t.Fatal(err) | |
| 23 | 新增: } | |
| 24 | 新增: id := "722f6417-7290-42d6-95f9-8de08970f23d" | |
| 25 | 新增: instance := randomToken() | |
| 26 | 新增: saved := SavedDownload{ID: id, InstanceID: instance, Name: "result.txt", Path: filepath.Join(t.TempDir(), "result.txt"), SavedAt: time.Now().UTC()} | |
| 27 | 新增: if err := writePrivate(savedDownloadPath(filepath.Join(client, "remote-downloads", instance), id), saved); err != nil { | |
| 28 | 新增: t.Fatal(err) | |
| 29 | 新增: } | |
| 30 | 新增: if err := importDesktopConnections(full, entry); err != nil { | |
| 31 | 新增: t.Fatal(err) | |
| 32 | 新增: } | |
| 33 | 新增: dest := remotehost.NewStore(entry) | |
| 34 | 新增: if _, err = dest.Get(first.ID); err != nil { | |
| 35 | 新增: t.Fatal(err) | |
| 36 | 新增: } | |
| 37 | 新增: if _, err = dest.Get(other.ID); err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: result, err := readSavedDownload(filepath.Join(entry, "remote-downloads", instance), id) | |
| 41 | 新增: if err != nil || result.Path != saved.Path || !result.SavedAt.Equal(saved.SavedAt) { | |
| 42 | 新增: t.Fatalf("imported saved download: %+v %v", result, err) | |
| 43 | 新增: } | |
| 44 | 新增: if err = dest.Delete(first.ID); err != nil { | |
| 45 | 新增: t.Fatal(err) | |
| 46 | 新增: } | |
| 47 | 新增: if err = importDesktopConnections(full, entry); err != nil { | |
| 48 | 新增: t.Fatal(err) | |
| 49 | 新增: } | |
| 50 | 新增: hosts, err := dest.List() | |
| 51 | 新增: if err != nil || len(hosts) != 1 || hosts[0].ID != other.ID { | |
| 52 | 新增: t.Fatalf("restored deleted host: %+v %v", hosts, err) | |
| 53 | 新增: } | |
| 54 | 新增: if _, err = remotehost.NewStore(full).Get(first.ID); err != nil { | |
| 55 | 新增: t.Fatal("old profile was modified") | |
| 56 | 新增: } | |
| 57 | 新增: if _, err = os.Stat(saved.Path); !os.IsNotExist(err) { | |
| 58 | 新增: t.Fatal("migration touched actual destination") | |
| 59 | 新增: } | |
| 60 | 新增:} | |
| @@ -0,0 +1,379 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "net/url" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "runtime" | |
| 11 | 新增: "sync" | |
| 12 | 新增: "time" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 16 | 新增: "github.com/sylvinus/agent-vm/internal/managedproxy" | |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 18 | 新增:) | |
| 19 | 新增: | |
| 20 | 新增:type desktopLocal struct { | |
| 21 | 新增: config, profile, executable string | |
| 22 | 新增: mu sync.Mutex | |
| 23 | 新增: ownedLaunch string | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:func NewDesktopLocalController(configPath, fullExecutable string) DesktopLocalController { | |
| 27 | 新增: return &desktopLocal{config: configPath, profile: filepath.Dir(configPath), executable: fullExecutable} | |
| 28 | 新增:} | |
| 29 | 新增: | |
| 30 | 新增:func (d *desktopLocal) available() bool { | |
| 31 | 新增: info, err := os.Stat(d.executable) | |
| 32 | 新增: return filepath.IsAbs(d.executable) && err == nil && info.Mode().IsRegular() && (runtime.GOOS == "windows" || info.Mode()&0111 != 0) | |
| 33 | 新增:} | |
| 34 | 新增: | |
| 35 | 新增:func (d *desktopLocal) controllerLockFree() bool { | |
| 36 | 新增: path := filepath.Join(d.profile, "control.lock") | |
| 37 | 新增: if err := host.CheckPrivateFile(path); err != nil { | |
| 38 | 新增: return os.IsNotExist(err) | |
| 39 | 新增: } | |
| 40 | 新增: f, err := os.OpenFile(path, os.O_RDWR, 0) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: return false | |
| 43 | 新增: } | |
| 44 | 新增: defer f.Close() | |
| 45 | 新增: if lockController(f) != nil { | |
| 46 | 新增: return false | |
| 47 | 新增: } | |
| 48 | 新增: return unlockController(f) == nil | |
| 49 | 新增:} | |
| 50 | 新增: | |
| 51 | 新增:func (c *controllerClient) localControl(ctx context.Context, action string, input desktopLocalRequest) (desktopLocalReply, error) { | |
| 52 | 新增: var reply desktopLocalReply | |
| 53 | 新增: input.Token = c.record.Token | |
| 54 | 新增: status, err := c.callContext(ctx, http.MethodPost, "/api/desktop-local/"+action, input, &reply) | |
| 55 | 新增: if err != nil { | |
| 56 | 新增: return reply, err | |
| 57 | 新增: } | |
| 58 | 新增: switch status { | |
| 59 | 新增: case http.StatusOK: | |
| 60 | 新增: if action == "status" && (reply.OwnerID != localControllerID(c.record.Token) || reply.Identity.PID != c.record.PID || reply.Identity.Protocol != controlProtocol || !reply.Identity.matches(c.record.Controller) || !remoteInstanceID.MatchString(reply.InstanceID)) { | |
| 61 | 新增: return reply, errors.New("无法确认本机控制服务身份") | |
| 62 | 新增: } | |
| 63 | 新增: return reply, nil | |
| 64 | 新增: case http.StatusLocked: | |
| 65 | 新增: return reply, errDesktopLocalLocked | |
| 66 | 新增: case http.StatusNotFound: | |
| 67 | 新增: return reply, errors.New("当前本机后台版本不支持环境切换,请先在原工作台保存任务并完成后台更新") | |
| 68 | 新增: case http.StatusConflict: | |
| 69 | 新增: return reply, errors.New("本机仍有操作或状态已变化,请重新确认") | |
| 70 | 新增: default: | |
| 71 | 新增: return reply, errors.New("本机控制服务未接受此操作") | |
| 72 | 新增: } | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:// offlineStatus uses only existing private records. A live lock, orphan VM, | |
| 76 | 新增:// or proxy without a reachable controller is unknown, never a released state. | |
| 77 | 新增:func (d *desktopLocal) offlineStatus(ctx context.Context, available bool) DesktopLocalStatus { | |
| 78 | 新增: st := DesktopLocalStatus{Available: available, Message: "本机状态待确认,请返回本机检查已有后台"} | |
| 79 | 新增: if !d.controllerLockFree() { | |
| 80 | 新增: st.ServiceRunning = true | |
| 81 | 新增: return st | |
| 82 | 新增: } | |
| 83 | 新增: // A container host requires an explicit engine probe. Listing the desktop | |
| 84 | 新增: // selector must not contact or start a container engine. | |
| 85 | 新增: if containerenv.Configured(d.profile) { | |
| 86 | 新增: return st | |
| 87 | 新增: } | |
| 88 | 新增: running, err := controllerVMState(d.profile) | |
| 89 | 新增: if err != nil || running { | |
| 90 | 新增: st.Running = running | |
| 91 | 新增: return st | |
| 92 | 新增: } | |
| 93 | 新增: if managedproxy.ConfirmStopped(ctx, d.profile) != nil { | |
| 94 | 新增: return st | |
| 95 | 新增: } | |
| 96 | 新增: st.Known, st.Message = true, "" | |
| 97 | 新增: return st | |
| 98 | 新增:} | |
| 99 | 新增: | |
| 100 | 新增:func (d *desktopLocal) Status(ctx context.Context) (DesktopLocalStatus, error) { | |
| 101 | 新增: available := d.available() | |
| 102 | 新增: c, err := openController(d.profile) | |
| 103 | 新增: if errors.Is(err, errControllerUnavailable) { | |
| 104 | 新增: return d.offlineStatus(ctx, available), nil | |
| 105 | 新增: } | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return DesktopLocalStatus{Available: available, Message: "本机后台记录无效,请检查本机配置"}, nil | |
| 108 | 新增: } | |
| 109 | 新增: defer c.close() | |
| 110 | 新增: view, err := c.localControl(ctx, "status", desktopLocalRequest{}) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: if !processExists(c.record.PID) { | |
| 113 | 新增: return d.offlineStatus(ctx, available), nil | |
| 114 | 新增: } | |
| 115 | 新增: return DesktopLocalStatus{Available: available, ServiceRunning: true, Message: "无法确认已有本机后台的状态或版本"}, nil | |
| 116 | 新增: } | |
| 117 | 新增: view.Available = available | |
| 118 | 新增: return view.DesktopLocalStatus, nil | |
| 119 | 新增:} | |
| 120 | 新增: | |
| 121 | 新增:func (d *desktopLocal) Connect(ctx context.Context) (_ *remotehost.Session, returned error) { | |
| 122 | 新增: st, err := d.Status(ctx) | |
| 123 | 新增: if err != nil { | |
| 124 | 新增: return nil, err | |
| 125 | 新增: } | |
| 126 | 新增: if !st.Available { | |
| 127 | 新增: return nil, errors.New("此安装缺少本机运行组件") | |
| 128 | 新增: } | |
| 129 | 新增: if !st.Known && st.ServiceRunning && st.ControllerID == "" { | |
| 130 | 新增: handed, err := d.handoffOldLocal(ctx) | |
| 131 | 新增: if err != nil { | |
| 132 | 新增: return nil, err | |
| 133 | 新增: } | |
| 134 | 新增: if handed { | |
| 135 | 新增: st, err = d.Status(ctx) | |
| 136 | 新增: if err != nil || !st.Known || st.ServiceRunning { | |
| 137 | 新增: return nil, errors.New("已有本机服务尚未完全退出,请刷新状态后重试") | |
| 138 | 新增: } | |
| 139 | 新增: } | |
| 140 | 新增: } | |
| 141 | 新增: // Explicit local selection may reattach an orphan workload to its owner. | |
| 142 | 新增: // Untrusted records or a live lock with no reachable service cannot be taken over. | |
| 143 | 新增: if !st.Known && !st.ServiceRunning { | |
| 144 | 新增: c, recordErr := openController(d.profile) | |
| 145 | 新增: if c != nil { | |
| 146 | 新增: c.close() | |
| 147 | 新增: } | |
| 148 | 新增: if (recordErr != nil && !errors.Is(recordErr, errControllerUnavailable)) || !d.controllerLockFree() { | |
| 149 | 新增: return nil, errors.New(st.Message) | |
| 150 | 新增: } | |
| 151 | 新增: } | |
| 152 | 新增: if err = ctx.Err(); err != nil { | |
| 153 | 新增: return nil, err | |
| 154 | 新增: } | |
| 155 | 新增: var launchID string | |
| 156 | 新增: if !st.ServiceRunning { | |
| 157 | 新增: launchID = randomToken() | |
| 158 | 新增: if err = startControllerExecutable(d.config, d.executable, "CAGE_DESKTOP_START_ID="+launchID); err != nil { | |
| 159 | 新增: return nil, err | |
| 160 | 新增: } | |
| 161 | 新增: defer func() { | |
| 162 | 新增: if returned != nil { | |
| 163 | 新增: d.releaseFailedLaunch(launchID) | |
| 164 | 新增: } | |
| 165 | 新增: }() | |
| 166 | 新增: } | |
| 167 | 新增: bootstrap, cancel := context.WithTimeout(ctx, 12*time.Second) | |
| 168 | 新增: defer cancel() | |
| 169 | 新增: for { | |
| 170 | 新增: c, err := openController(d.profile) | |
| 171 | 新增: if err == nil { | |
| 172 | 新增: view, probeErr := c.localControl(bootstrap, "status", desktopLocalRequest{}) | |
| 173 | 新增: if probeErr == nil { | |
| 174 | 新增: defer c.close() | |
| 175 | 新增: if st.ControllerID != "" && view.ControllerID != st.ControllerID { | |
| 176 | 新增: return nil, errors.New("本机后台已变化,请重新选择") | |
| 177 | 新增: } | |
| 178 | 新增: life := ctx | |
| 179 | 新增: if launchID != "" && view.LaunchID == launchID { | |
| 180 | 新增: life = context.WithValue(ctx, localLaunchKey{}, launchID) | |
| 181 | 新增: } | |
| 182 | 新增: session, err := d.localSession(life, bootstrap, c, view) | |
| 183 | 新增: if err == nil && launchID != "" && view.LaunchID == launchID { | |
| 184 | 新增: d.mu.Lock() | |
| 185 | 新增: d.ownedLaunch = launchID | |
| 186 | 新增: d.mu.Unlock() | |
| 187 | 新增: } | |
| 188 | 新增: return session, err | |
| 189 | 新增: } | |
| 190 | 新增: c.close() | |
| 191 | 新增: if launchID == "" { | |
| 192 | 新增: return nil, probeErr | |
| 193 | 新增: } | |
| 194 | 新增: } else if !errors.Is(err, errControllerUnavailable) { | |
| 195 | 新增: return nil, err | |
| 196 | 新增: } | |
| 197 | 新增: select { | |
| 198 | 新增: case <-bootstrap.Done(): | |
| 199 | 新增: return nil, errors.New("无法连接本机控制服务,请检查本机状态") | |
| 200 | 新增: case <-time.After(100 * time.Millisecond): | |
| 201 | 新增: } | |
| 202 | 新增: } | |
| 203 | 新增:} | |
| 204 | 新增: | |
| 205 | 新增:type localLaunchKey struct{} | |
| 206 | 新增: | |
| 207 | 新增:// Automatic release is limited to a controller started by this gateway. | |
| 208 | 新增:// A standalone cage serve may be idle between requests and still have other callers. | |
| 209 | 新增:func (d *desktopLocal) ReleaseOwnedIdle(ctx context.Context, expected DesktopLocalStatus) (bool, error) { | |
| 210 | 新增: d.mu.Lock() | |
| 211 | 新增: id := d.ownedLaunch | |
| 212 | 新增: d.mu.Unlock() | |
| 213 | 新增: if id == "" { | |
| 214 | 新增: return false, nil | |
| 215 | 新增: } | |
| 216 | 新增: c, err := openController(d.profile) | |
| 217 | 新增: if err != nil { | |
| 218 | 新增: return false, err | |
| 219 | 新增: } | |
| 220 | 新增: defer c.close() | |
| 221 | 新增: view, err := c.localControl(ctx, "status", desktopLocalRequest{}) | |
| 222 | 新增: if err != nil { | |
| 223 | 新增: return false, err | |
| 224 | 新增: } | |
| 225 | 新增: if view.LaunchID != id { | |
| 226 | 新增: return false, nil | |
| 227 | 新增: } | |
| 228 | 新增: if !expected.Known || !view.Known || view.ControllerID != expected.ControllerID || view.Busy || view.Running || view.LiveTerminals > 0 { | |
| 229 | 新增: return false, errors.New("本机后台或任务状态已变化,请重新确认") | |
| 230 | 新增: } | |
| 231 | 新增: if err := d.Release(ctx, expected, false); err != nil { | |
| 232 | 新增: return false, err | |
| 233 | 新增: } | |
| 234 | 新增: return true, nil | |
| 235 | 新增:} | |
| 236 | 新增: | |
| 237 | 新增:// ReleaseUnused handles a prepared local view that the user never entered. | |
| 238 | 新增:// A previous controller, including an idle one, belongs to its original owner. | |
| 239 | 新增:func (d *desktopLocal) ReleaseUnused(ctx context.Context, session *remotehost.Session) error { | |
| 240 | 新增: if session == nil || session.Context == nil { | |
| 241 | 新增: return nil | |
| 242 | 新增: } | |
| 243 | 新增: id, _ := session.Context.Value(localLaunchKey{}).(string) | |
| 244 | 新增: if id == "" { | |
| 245 | 新增: return nil | |
| 246 | 新增: } | |
| 247 | 新增: c, err := openController(d.profile) | |
| 248 | 新增: if errors.Is(err, errControllerUnavailable) { | |
| 249 | 新增: return nil | |
| 250 | 新增: } | |
| 251 | 新增: if err != nil { | |
| 252 | 新增: return err | |
| 253 | 新增: } | |
| 254 | 新增: defer c.close() | |
| 255 | 新增: view, err := c.localControl(ctx, "status", desktopLocalRequest{}) | |
| 256 | 新增: if err != nil { | |
| 257 | 新增: return err | |
| 258 | 新增: } | |
| 259 | 新增: if view.LaunchID != id || !view.Known || view.Busy || view.Running || view.LiveTerminals > 0 { | |
| 260 | 新增: return nil | |
| 261 | 新增: } | |
| 262 | 新增: return d.Release(ctx, view.DesktopLocalStatus, false) | |
| 263 | 新增:} | |
| 264 | 新增: | |
| 265 | 新增:// The process started for a cancelled handshake may publish its record after | |
| 266 | 新增:// cancellation. Only hand off a controller bearing this launcher's own nonce. | |
| 267 | 新增:func (d *desktopLocal) releaseFailedLaunch(id string) { | |
| 268 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 12*time.Second) | |
| 269 | 新增: defer cancel() | |
| 270 | 新增: for ctx.Err() == nil { | |
| 271 | 新增: c, err := openController(d.profile) | |
| 272 | 新增: if err == nil { | |
| 273 | 新增: view, err := c.localControl(ctx, "status", desktopLocalRequest{}) | |
| 274 | 新增: c.close() | |
| 275 | 新增: if err == nil { | |
| 276 | 新增: if view.LaunchID == id && view.Known && !view.Busy && !view.Running && view.LiveTerminals == 0 { | |
| 277 | 新增: _ = d.Release(ctx, view.DesktopLocalStatus, false) | |
| 278 | 新增: } | |
| 279 | 新增: return | |
| 280 | 新增: } | |
| 281 | 新增: } | |
| 282 | 新增: select { | |
| 283 | 新增: case <-ctx.Done(): | |
| 284 | 新增: return | |
| 285 | 新增: case <-time.After(150 * time.Millisecond): | |
| 286 | 新增: } | |
| 287 | 新增: } | |
| 288 | 新增:} | |
| 289 | 新增: | |
| 290 | 新增:func (d *desktopLocal) localSession(life, bootstrap context.Context, c *controllerClient, view desktopLocalReply) (*remotehost.Session, error) { | |
| 291 | 新增: var launch launchResponse | |
| 292 | 新增: status, err := c.callContext(bootstrap, "POST", "/api/launch", map[string]string{"token": c.record.Token}, &launch) | |
| 293 | 新增: if err != nil || status != http.StatusOK || launch.Controller != view.Identity { | |
| 294 | 新增: return nil, errors.New("本机后台身份已变化,请重新选择") | |
| 295 | 新增: } | |
| 296 | 新增: u, err := url.Parse(launch.URL) | |
| 297 | 新增: if err != nil || u.Scheme+"://"+u.Host != c.origin || u.User != nil || u.Fragment == "" { | |
| 298 | 新增: return nil, errors.New("本机连接入口无效") | |
| 299 | 新增: } | |
| 300 | 新增: status, err = c.callContext(bootstrap, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil) | |
| 301 | 新增: if err != nil || status != http.StatusOK { | |
| 302 | 新增: return nil, errors.New("本机会话认证失败") | |
| 303 | 新增: } | |
| 304 | 新增: var m RemoteEntry | |
| 305 | 新增: status, err = c.callContext(bootstrap, "GET", "/api/remote/manifest", nil, &m) | |
| 306 | 新增: if err != nil || status != http.StatusOK || m.InstanceID != view.InstanceID || m.APIProtocol != remoteAPIProtocol || m.Origin != c.origin || m.Platform != runtime.GOOS { | |
| 307 | 新增: return nil, errors.New("本机工作台版本或环境身份不符") | |
| 308 | 新增: } | |
| 309 | 新增: manifest := remotehost.PublicManifest{APIProtocol: m.APIProtocol, InstanceID: m.InstanceID, Version: m.Version, Platform: m.Platform, Runtime: m.Runtime, Capabilities: m.Capabilities} | |
| 310 | 新增: return remotehost.LocalSession(life, c.origin, manifest, c.client.Jar) | |
| 311 | 新增:} | |
| 312 | 新增: | |
| 313 | 新增:func (d *desktopLocal) Release(ctx context.Context, expected DesktopLocalStatus, stop bool) error { | |
| 314 | 新增: if !expected.Known || !expected.ServiceRunning || expected.ControllerID == "" { | |
| 315 | 新增: return errors.New("请先确认本机控制服务身份") | |
| 316 | 新增: } | |
| 317 | 新增: c, err := openController(d.profile) | |
| 318 | 新增: if err != nil { | |
| 319 | 新增: return errors.New("本机控制服务已变化,请刷新后重试") | |
| 320 | 新增: } | |
| 321 | 新增: defer c.close() | |
| 322 | 新增: ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) | |
| 323 | 新增: defer cancel() | |
| 324 | 新增: request := desktopLocalRequest{ControllerID: expected.ControllerID, Stop: stop, Running: expected.Running, Terminals: expected.LiveTerminals} | |
| 325 | 新增: reply, err := c.localControl(ctx, "release", request) | |
| 326 | 新增: if err != nil { | |
| 327 | 新增: return err | |
| 328 | 新增: } | |
| 329 | 新增: if reply.JobRunning { | |
| 330 | 新增: jobID := reply.JobID | |
| 331 | 新增: if jobID == "" || !stop { | |
| 332 | 新增: return errors.New("本机停止作业身份无效") | |
| 333 | 新增: } | |
| 334 | 新增: for { | |
| 335 | 新增: select { | |
| 336 | 新增: case <-ctx.Done(): | |
| 337 | 新增: return ctx.Err() | |
| 338 | 新增: case <-time.After(150 * time.Millisecond): | |
| 339 | 新增: } | |
| 340 | 新增: view, err := c.localControl(ctx, "status", desktopLocalRequest{}) | |
| 341 | 新增: if err != nil { | |
| 342 | 新增: return err | |
| 343 | 新增: } | |
| 344 | 新增: if view.JobID != jobID || view.JobFailed { | |
| 345 | 新增: return errors.New("本机停止作业已变化或失败,请回到本机确认状态") | |
| 346 | 新增: } | |
| 347 | 新增: if view.JobRunning { | |
| 348 | 新增: continue | |
| 349 | 新增: } | |
| 350 | 新增: if !view.Known || view.Busy || view.Running || view.LiveTerminals != 0 { | |
| 351 | 新增: return errors.New("本机工作尚未完全停止") | |
| 352 | 新增: } | |
| 353 | 新增: _, err = c.localControl(ctx, "release", desktopLocalRequest{ControllerID: view.ControllerID, JobID: jobID}) | |
| 354 | 新增: if err != nil { | |
| 355 | 新增: return err | |
| 356 | 新增: } | |
| 357 | 新增: break | |
| 358 | 新增: } | |
| 359 | 新增: } | |
| 360 | 新增: if err = c.waitForExit(); err != nil { | |
| 361 | 新增: return err | |
| 362 | 新增: } | |
| 363 | 新增: for processExists(c.record.PID) { | |
| 364 | 新增: select { | |
| 365 | 新增: case <-ctx.Done(): | |
| 366 | 新增: return errors.New("本机控制进程仍未退出") | |
| 367 | 新增: case <-time.After(75 * time.Millisecond): | |
| 368 | 新增: } | |
| 369 | 新增: } | |
| 370 | 新增: // Unlike a cold selector probe, this explicit release may query an existing | |
| 371 | 新增: // local container engine to verify that its workload actually stopped. | |
| 372 | 新增: if _, err := os.Lstat(filepath.Join(d.profile, "control.json")); !os.IsNotExist(err) || !d.controllerLockFree() { | |
| 373 | 新增: return errors.New("本机控制服务状态已变化,请重新确认") | |
| 374 | 新增: } | |
| 375 | 新增: if running, err := controllerVMState(d.profile); err != nil || running || managedproxy.ConfirmStopped(ctx, d.profile) != nil { | |
| 376 | 新增: return errors.New("本机资源状态待确认") | |
| 377 | 新增: } | |
| 378 | 新增: return nil | |
| 379 | 新增:} | |
| @@ -0,0 +1,133 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "crypto/sha256" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "os" | |
| 8 | 新增: "sort" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// The launcher authenticates these requests with the private controller record. | |
| 12 | 新增:// The browser-facing gateway never forwards this endpoint or exposes its token. | |
| 13 | 新增:type desktopLocalRequest struct { | |
| 14 | 新增: Token string `json:"token"` | |
| 15 | 新增: ControllerID string `json:"controller_id,omitempty"` | |
| 16 | 新增: Stop bool `json:"stop,omitempty"` | |
| 17 | 新增: Running bool `json:"running,omitempty"` | |
| 18 | 新增: Terminals int `json:"terminals,omitempty"` | |
| 19 | 新增: JobID string `json:"job_id,omitempty"` | |
| 20 | 新增:} | |
| 21 | 新增: | |
| 22 | 新增:type desktopLocalReply struct { | |
| 23 | 新增: DesktopLocalStatus | |
| 24 | 新增: Identity ControllerIdentity `json:"identity"` | |
| 25 | 新增: OwnerID string `json:"owner_id"` | |
| 26 | 新增: InstanceID string `json:"instance_id"` | |
| 27 | 新增: LaunchID string `json:"launch_id,omitempty"` | |
| 28 | 新增: JobID string `json:"job_id,omitempty"` | |
| 29 | 新增: JobRunning bool `json:"job_running,omitempty"` | |
| 30 | 新增: JobFailed bool `json:"job_failed,omitempty"` | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:func localControllerID(token string) string { | |
| 34 | 新增: return fmt.Sprintf("%x", sha256.Sum256([]byte("desktop-local\x00"+token))) | |
| 35 | 新增:} | |
| 36 | 新增: | |
| 37 | 新增:func (s *Server) desktopLocalSnapshot() desktopLocalReply { | |
| 38 | 新增: job := s.jobs.snapshot() | |
| 39 | 新增: reply := desktopLocalReply{ | |
| 40 | 新增: DesktopLocalStatus: DesktopLocalStatus{Available: true, ServiceRunning: true}, | |
| 41 | 新增: Identity: s.identity, OwnerID: localControllerID(s.token), InstanceID: s.instanceID, | |
| 42 | 新增: LaunchID: os.Getenv("CAGE_DESKTOP_START_ID"), JobID: job.ID, JobRunning: job.Running, JobFailed: job.Error != "", | |
| 43 | 新增: } | |
| 44 | 新增: owners, err := controllerVMOwners(s.profile) | |
| 45 | 新增: reply.Running = len(owners) != 0 | |
| 46 | 新增: if err != nil { | |
| 47 | 新增: reply.Message = "本机环境状态待确认" | |
| 48 | 新增: return reply | |
| 49 | 新增: } | |
| 50 | 新增: reply.Known = true | |
| 51 | 新增: var terminals []string | |
| 52 | 新增: for _, session := range s.terminals.snapshot() { | |
| 53 | 新增: if session["closed"] == false { | |
| 54 | 新增: reply.LiveTerminals++ | |
| 55 | 新增: id, _ := session["id"].(string) | |
| 56 | 新增: terminals = append(terminals, id) | |
| 57 | 新增: } | |
| 58 | 新增: } | |
| 59 | 新增: s.mu.Lock() | |
| 60 | 新增: reply.Busy = s.closing || job.Running | |
| 61 | 新增: s.mu.Unlock() | |
| 62 | 新增: if s.remote != nil && s.remote.isRemote() { | |
| 63 | 新增: reply.Busy = true | |
| 64 | 新增: } | |
| 65 | 新增: if reply.Busy { | |
| 66 | 新增: reply.Message = "本机控制服务正在执行操作或被其他入口使用" | |
| 67 | 新增: } | |
| 68 | 新增: // The same owner can acquire new work while the confirmation dialog is | |
| 69 | 新增: // open. Bind its public stop confirmation to the observed workload too. | |
| 70 | 新增: sort.Strings(terminals) | |
| 71 | 新增: reply.ControllerID = fmt.Sprintf("%x", sha256.Sum256([]byte(fmt.Sprintf("%s\x00%q\x00%s\x00%t\x00%q", reply.OwnerID, owners, job.ID, reply.Busy, terminals)))) | |
| 72 | 新增: return reply | |
| 73 | 新增:} | |
| 74 | 新增: | |
| 75 | 新增:func (s *Server) desktopLocalControl(w http.ResponseWriter, r *http.Request) { | |
| 76 | 新增: var request desktopLocalRequest | |
| 77 | 新增: if !readJSON(w, r, &request) { | |
| 78 | 新增: return | |
| 79 | 新增: } | |
| 80 | 新增: if s.clientOnly || !equalSecret(request.Token, s.token) { | |
| 81 | 新增: http.Error(w, "Launcher refused", http.StatusUnauthorized) | |
| 82 | 新增: return | |
| 83 | 新增: } | |
| 84 | 新增: switch r.PathValue("action") { | |
| 85 | 新增: case "status": | |
| 86 | 新增: jsonReply(w, s.desktopLocalSnapshot()) | |
| 87 | 新增: case "release": | |
| 88 | 新增: if !s.op.TryLock() { | |
| 89 | 新增: http.Error(w, "本机正在执行操作,请稍后重试", http.StatusConflict) | |
| 90 | 新增: return | |
| 91 | 新增: } | |
| 92 | 新增: view := s.desktopLocalSnapshot() | |
| 93 | 新增: if !view.Known || view.Busy || request.ControllerID != view.ControllerID || request.Running != view.Running || request.Terminals != view.LiveTerminals || (request.JobID != "" && request.JobID != view.JobID) { | |
| 94 | 新增: s.op.Unlock() | |
| 95 | 新增: http.Error(w, "本机任务或控制服务已变化,请重新确认", http.StatusConflict) | |
| 96 | 新增: return | |
| 97 | 新增: } | |
| 98 | 新增: if !view.Running && view.LiveTerminals == 0 { | |
| 99 | 新增: s.handoffLocked(w) | |
| 100 | 新增: return | |
| 101 | 新增: } | |
| 102 | 新增: defer s.op.Unlock() | |
| 103 | 新增: if !request.Stop { | |
| 104 | 新增: http.Error(w, "本机环境仍在运行", http.StatusConflict) | |
| 105 | 新增: return | |
| 106 | 新增: } | |
| 107 | 新增: if _, unlocked := s.account.access(); !unlocked { | |
| 108 | 新增: http.Error(w, "请先返回本机解锁,再停止本机环境", http.StatusLocked) | |
| 109 | 新增: return | |
| 110 | 新增: } | |
| 111 | 新增: // This stop may not cancel another admitted operation. Check and submit | |
| 112 | 新增: // under the same admission lock used by submitJob, then let the existing | |
| 113 | 新增: // job manager execute stopEnvironment under the operation lock. | |
| 114 | 新增: s.mu.Lock() | |
| 115 | 新增: if s.closing || s.jobs.snapshot().Running { | |
| 116 | 新增: s.mu.Unlock() | |
| 117 | 新增: http.Error(w, "本机正在执行操作,请稍后重试", http.StatusConflict) | |
| 118 | 新增: return | |
| 119 | 新增: } | |
| 120 | 新增: job, err := s.jobs.submit(&s.op, "stop", s.safety.pauseVersion, nil, nil, func() error { | |
| 121 | 新增: _ = s.pauseNetworkNow("正在停止本机环境") | |
| 122 | 新增: return s.stopEnvironment() | |
| 123 | 新增: }) | |
| 124 | 新增: s.mu.Unlock() | |
| 125 | 新增: if err != nil { | |
| 126 | 新增: requestError(w, err) | |
| 127 | 新增: return | |
| 128 | 新增: } | |
| 129 | 新增: jsonReply(w, desktopLocalReply{JobID: job.ID, JobRunning: true}) | |
| 130 | 新增: default: | |
| 131 | 新增: http.NotFound(w, r) | |
| 132 | 新增: } | |
| 133 | 新增:} | |
| @@ -0,0 +1,78 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "crypto/sha256" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "io" | |
| 9 | 新增: "net/http" | |
| 10 | 新增: "net/url" | |
| 11 | 新增: "os" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:const previousLocalWorkbench = "请用 cage desktop --existing 打开已有本机工作台,保存并停止任务后重试" | |
| 15 | 新增: | |
| 16 | 新增:// Only explicit local selection calls this path. An older full controller | |
| 17 | 新增:// can release an idle profile via its own authenticated update handoff. Its | |
| 18 | 新增:// process and workloads remain under its control throughout this exchange. | |
| 19 | 新增:func (d *desktopLocal) handoffOldLocal(ctx context.Context) (bool, error) { | |
| 20 | 新增: c, err := connectController(d.profile) | |
| 21 | 新增: if err != nil { | |
| 22 | 新增: return false, errors.New("无法认证已有本机后台。" + previousLocalWorkbench) | |
| 23 | 新增: } | |
| 24 | 新增: defer c.close() | |
| 25 | 新增: id := c.launch.Controller | |
| 26 | 新增: if c.launch.DesktopGateway || id.Protocol != controlProtocol || id.PID != c.record.PID || !id.matches(c.record.Controller) || !remoteInstanceID.MatchString(id.Build) { | |
| 27 | 新增: return false, errors.New("已有本机后台身份或协议不兼容。" + previousLocalWorkbench) | |
| 28 | 新增: } | |
| 29 | 新增: u, _ := url.Parse(c.launch.URL) // connectController verified the origin and ticket. | |
| 30 | 新增: status, err := c.callContext(ctx, "POST", "/api/session", map[string]string{"token": u.Fragment}, nil) | |
| 31 | 新增: if err != nil || status != http.StatusOK || len(c.client.Jar.Cookies(u)) == 0 { | |
| 32 | 新增: return false, errors.New("无法建立已有本机后台的会话。" + previousLocalWorkbench) | |
| 33 | 新增: } | |
| 34 | 新增: // Old controllers can answer 401 before the cookie and 423 while locked, | |
| 35 | 新增: // even for an unknown route. A working modern route must never be replaced. | |
| 36 | 新增: status, err = c.callContext(ctx, "POST", "/api/desktop-local/status", desktopLocalRequest{Token: c.record.Token}, nil) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return false, err | |
| 39 | 新增: } | |
| 40 | 新增: switch status { | |
| 41 | 新增: case http.StatusOK: | |
| 42 | 新增: return false, nil | |
| 43 | 新增: case http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusLocked: | |
| 44 | 新增: default: | |
| 45 | 新增: return false, errors.New("无法确认已有本机后台版本。" + previousLocalWorkbench) | |
| 46 | 新增: } | |
| 47 | 新增: f, err := os.Open(d.executable) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: return false, err | |
| 50 | 新增: } | |
| 51 | 新增: defer f.Close() | |
| 52 | 新增: h := sha256.New() | |
| 53 | 新增: if _, err = io.Copy(h, f); err != nil { | |
| 54 | 新增: return false, err | |
| 55 | 新增: } | |
| 56 | 新增: if id.Build == fmt.Sprintf("%x", h.Sum(nil)) { | |
| 57 | 新增: return false, errors.New("本机后台的启动器接口不可用。" + previousLocalWorkbench) | |
| 58 | 新增: } | |
| 59 | 新增: var selection ClientContext | |
| 60 | 新增: status, err = c.callContext(ctx, "GET", "/api/client/context", nil, &selection) | |
| 61 | 新增: if err != nil || (status != http.StatusOK && status != http.StatusNotFound && status != http.StatusLocked) { | |
| 62 | 新增: return false, errors.New("无法确认旧工作台的连接状态。" + previousLocalWorkbench) | |
| 63 | 新增: } | |
| 64 | 新增: if status == http.StatusOK && (selection.ClientOnly || selection.Mode != "local") { | |
| 65 | 新增: return false, errors.New("已有工作台正在管理其他连接。" + previousLocalWorkbench) | |
| 66 | 新增: } | |
| 67 | 新增: var ack struct { | |
| 68 | 新增: Stopping bool `json:"stopping"` | |
| 69 | 新增: } | |
| 70 | 新增: status, err = c.callContext(ctx, "POST", "/api/handoff", map[string]string{"token": c.record.Token}, &ack) | |
| 71 | 新增: if err != nil || status != http.StatusOK || !ack.Stopping { | |
| 72 | 新增: return false, errors.New("旧版本机后台仍在使用,或尚未确认空闲退出。" + previousLocalWorkbench) | |
| 73 | 新增: } | |
| 74 | 新增: if err := c.waitForExit(); err != nil { | |
| 75 | 新增: return false, err | |
| 76 | 新增: } | |
| 77 | 新增: return true, nil | |
| 78 | 新增:} | |
| @@ -0,0 +1,200 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "encoding/json" | |
| 6 | 新增: "errors" | |
| 7 | 新增: "fmt" | |
| 8 | 新增: "net/http" | |
| 9 | 新增: "os" | |
| 10 | 新增: "os/exec" | |
| 11 | 新增: "path/filepath" | |
| 12 | 新增: "testing" | |
| 13 | 新增: "time" | |
| 14 | 新增:) | |
| 15 | 新增: | |
| 16 | 新增:func TestDesktopLocalProbeLeavesColdProfileUntouched(t *testing.T) { | |
| 17 | 新增: root := t.TempDir() | |
| 18 | 新增: exe, err := os.Executable() | |
| 19 | 新增: if err != nil { | |
| 20 | 新增: t.Fatal(err) | |
| 21 | 新增: } | |
| 22 | 新增: d := NewDesktopLocalController(filepath.Join(root, "local", "config.json"), exe) | |
| 23 | 新增: st, err := d.Status(context.Background()) | |
| 24 | 新增: if err != nil || !st.Available || !st.Known || st.Running || st.ServiceRunning { | |
| 25 | 新增: t.Fatalf("cold probe: %+v %v", st, err) | |
| 26 | 新增: } | |
| 27 | 新增: if entries, err := os.ReadDir(root); err != nil || len(entries) != 0 { | |
| 28 | 新增: t.Fatalf("probe initialized a local workload: %v %v", entries, err) | |
| 29 | 新增: } | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:func TestDesktopLocalReleaseHasIndependentLauncherAndAccountGuards(t *testing.T) { | |
| 33 | 新增: s := testServer(t) | |
| 34 | 新增: path := filepath.Join(s.profile, "state", "lima", "fixture", "cage-running.json") | |
| 35 | 新增: if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil { | |
| 36 | 新增: t.Fatal(err) | |
| 37 | 新增: } | |
| 38 | 新增: if err := writePrivate(path, map[string]int{"pid": os.Getpid()}); err != nil { | |
| 39 | 新增: t.Fatal(err) | |
| 40 | 新增: } | |
| 41 | 新增: s.account.lock() | |
| 42 | 新增: observed := s.desktopLocalSnapshot().ControllerID | |
| 43 | 新增: for _, tc := range []struct { | |
| 44 | 新增: name, token, identity string | |
| 45 | 新增: stop bool | |
| 46 | 新增: status int | |
| 47 | 新增: }{ | |
| 48 | 新增: {"browser cookie cannot stop", "", observed, true, 401}, | |
| 49 | 新增: {"previous controller", s.token, "previous", true, 409}, | |
| 50 | 新增: {"idle handoff cannot stop workload", s.token, observed, false, 409}, | |
| 51 | 新增: {"locked account", s.token, observed, true, 423}, | |
| 52 | 新增: } { | |
| 53 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 54 | 新增: b, _ := json.Marshal(desktopLocalRequest{Token: tc.token, ControllerID: tc.identity, Running: true, Stop: tc.stop}) | |
| 55 | 新增: got := request(s, "POST", "/api/desktop-local/release", s.origin, string(b), true) | |
| 56 | 新增: if got.Code != tc.status || s.jobs.snapshot().ID != "" { | |
| 57 | 新增: t.Fatalf("result=%d, job=%+v", got.Code, s.jobs.snapshot()) | |
| 58 | 新增: } | |
| 59 | 新增: }) | |
| 60 | 新增: } | |
| 61 | 新增: s.setJobForTest(Job{ID: "another-completed-job"}) | |
| 62 | 新增: b, _ := json.Marshal(desktopLocalRequest{Token: s.token, ControllerID: observed, Running: true, Stop: true}) | |
| 63 | 新增: if w := request(s, "POST", "/api/desktop-local/release", s.origin, string(b), true); w.Code != http.StatusConflict { | |
| 64 | 新增: t.Fatalf("old workload confirmation was accepted: %d", w.Code) | |
| 65 | 新增: } | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:func TestDesktopLocalStopMustFinishItsOwnJobBeforeHandoff(t *testing.T) { | |
| 69 | 新增: s := testServer(t) | |
| 70 | 新增: s.terminals.sessions = map[string]*terminalSession{"live": {id: "live"}} | |
| 71 | 新增: exited := make(chan struct{}) | |
| 72 | 新增: s.shutdown = func() { close(exited) } | |
| 73 | 新增: release := func(input desktopLocalRequest) (int, desktopLocalReply) { | |
| 74 | 新增: input.Token = s.token | |
| 75 | 新增: b, _ := json.Marshal(input) | |
| 76 | 新增: w := request(s, "POST", "/api/desktop-local/release", s.origin, string(b), false) | |
| 77 | 新增: var reply desktopLocalReply | |
| 78 | 新增: if w.Code == 200 { | |
| 79 | 新增: if err := json.Unmarshal(w.Body.Bytes(), &reply); err != nil { | |
| 80 | 新增: t.Fatal(err) | |
| 81 | 新增: } | |
| 82 | 新增: } | |
| 83 | 新增: return w.Code, reply | |
| 84 | 新增: } | |
| 85 | 新增: view := s.desktopLocalSnapshot() | |
| 86 | 新增: code, job := release(desktopLocalRequest{ControllerID: view.ControllerID, Terminals: 1, Stop: true}) | |
| 87 | 新增: if code != 200 || !job.JobRunning || job.JobID == "" { | |
| 88 | 新增: t.Fatalf("stop %d %+v", code, job) | |
| 89 | 新增: } | |
| 90 | 新增: deadline := time.Now().Add(5 * time.Second) | |
| 91 | 新增: for { | |
| 92 | 新增: view = s.desktopLocalSnapshot() | |
| 93 | 新增: if !view.JobRunning || time.Now().After(deadline) { | |
| 94 | 新增: break | |
| 95 | 新增: } | |
| 96 | 新增: time.Sleep(10 * time.Millisecond) | |
| 97 | 新增: } | |
| 98 | 新增: if view.JobID != job.JobID || view.JobFailed || view.JobRunning || view.LiveTerminals != 0 { | |
| 99 | 新增: t.Fatalf("job outcome %+v", view) | |
| 100 | 新增: } | |
| 101 | 新增: if code, _ := release(desktopLocalRequest{ControllerID: view.ControllerID, JobID: "different"}); code != 409 { | |
| 102 | 新增: t.Fatalf("handoff for different job %d", code) | |
| 103 | 新增: } | |
| 104 | 新增: if code, _ := release(desktopLocalRequest{ControllerID: view.ControllerID, JobID: job.JobID}); code != 200 { | |
| 105 | 新增: t.Fatalf("handoff %d", code) | |
| 106 | 新增: } | |
| 107 | 新增: select { | |
| 108 | 新增: case <-exited: | |
| 109 | 新增: case <-time.After(time.Second): | |
| 110 | 新增: t.Fatal("approved idle owner did not exit") | |
| 111 | 新增: } | |
| 112 | 新增:} | |
| 113 | 新增: | |
| 114 | 新增:// A real full controller owns the lock and launch ticket. This test never | |
| 115 | 新增:// boots a VM. It verifies that closing a view preserves its controller and | |
| 116 | 新增:// that only its currently reported identity can release the idle process. | |
| 117 | 新增:func TestDesktopLocalAuthenticatedViewAndIdleExit(t *testing.T) { | |
| 118 | 新增: profile := filepath.Join(t.TempDir(), "local") | |
| 119 | 新增: config := filepath.Join(profile, "config.json") | |
| 120 | 新增: exe, err := os.Executable() | |
| 121 | 新增: if err != nil { | |
| 122 | 新增: t.Fatal(err) | |
| 123 | 新增: } | |
| 124 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 25*time.Second) | |
| 125 | 新增: defer cancel() | |
| 126 | 新增: cmd := exec.CommandContext(ctx, exe, "-test.run=^TestServeShutdownHandoff$", "-test.timeout=25s") | |
| 127 | 新增: cmd.Env = append(os.Environ(), "CAGE_TEST_SHUTDOWN_CONFIG="+config) | |
| 128 | 新增: if err := cmd.Start(); err != nil { | |
| 129 | 新增: t.Fatal(err) | |
| 130 | 新增: } | |
| 131 | 新增: done := make(chan struct{}) | |
| 132 | 新增: var waitErr error | |
| 133 | 新增: go func() { waitErr = cmd.Wait(); close(done) }() | |
| 134 | 新增: t.Cleanup(func() { | |
| 135 | 新增: cancel() | |
| 136 | 新增: select { | |
| 137 | 新增: case <-done: | |
| 138 | 新增: case <-time.After(3 * time.Second): | |
| 139 | 新增: } | |
| 140 | 新增: }) | |
| 141 | 新增: d := NewDesktopLocalController(config, exe) | |
| 142 | 新增: var st DesktopLocalStatus | |
| 143 | 新增: for { | |
| 144 | 新增: st, err = d.Status(ctx) | |
| 145 | 新增: if err == nil && st.Known && st.ServiceRunning { | |
| 146 | 新增: break | |
| 147 | 新增: } | |
| 148 | 新增: select { | |
| 149 | 新增: case <-ctx.Done(): | |
| 150 | 新增: t.Fatal("controller did not start") | |
| 151 | 新增: case <-done: | |
| 152 | 新增: t.Fatal("controller exited", waitErr) | |
| 153 | 新增: case <-time.After(50 * time.Millisecond): | |
| 154 | 新增: } | |
| 155 | 新增: } | |
| 156 | 新增: session, err := d.Connect(ctx) | |
| 157 | 新增: if err != nil { | |
| 158 | 新增: t.Fatal(err) | |
| 159 | 新增: } | |
| 160 | 新增: t.Cleanup(func() { _ = session.Close() }) | |
| 161 | 新增: req, _ := http.NewRequestWithContext(ctx, "GET", session.Origin+"/api/account", nil) | |
| 162 | 新增: req.Header.Set("Cookie", "untrusted=123") | |
| 163 | 新增: req.Header.Set("Origin", "https://not-the-controller.invalid") | |
| 164 | 新增: res, err := session.Client.Do(req) | |
| 165 | 新增: if err != nil { | |
| 166 | 新增: t.Fatal(err) | |
| 167 | 新增: } | |
| 168 | 新增: res.Body.Close() | |
| 169 | 新增: if res.StatusCode != http.StatusOK { | |
| 170 | 新增: t.Fatalf("authenticated view: %d", res.StatusCode) | |
| 171 | 新增: } | |
| 172 | 新增: if err = session.Close(); err != nil { | |
| 173 | 新增: t.Fatal(err) | |
| 174 | 新增: } | |
| 175 | 新增: after, err := d.Status(ctx) | |
| 176 | 新增: if err != nil || !after.ServiceRunning || after.ControllerID != st.ControllerID { | |
| 177 | 新增: t.Fatalf("view closed controller: %+v %v", after, err) | |
| 178 | 新增: } | |
| 179 | 新增: if released, err := d.(*desktopLocal).ReleaseOwnedIdle(ctx, after); err != nil || released { | |
| 180 | 新增: t.Fatalf("independently started service auto-release: released=%v err=%v", released, err) | |
| 181 | 新增: } | |
| 182 | 新增: if after, err = d.Status(ctx); err != nil || !after.ServiceRunning || after.ControllerID != st.ControllerID { | |
| 183 | 新增: t.Fatalf("independent owner was lost: %+v %v", after, err) | |
| 184 | 新增: } | |
| 185 | 新增: stale := st | |
| 186 | 新增: stale.ControllerID = fmt.Sprintf("%064x", 1) | |
| 187 | 新增: if err = d.Release(ctx, stale, false); err == nil { | |
| 188 | 新增: t.Fatal("stale handoff accepted") | |
| 189 | 新增: } | |
| 190 | 新增: if err = d.Release(ctx, st, false); err != nil { | |
| 191 | 新增: t.Fatal(err) | |
| 192 | 新增: } | |
| 193 | 新增: <-done | |
| 194 | 新增: if waitErr != nil { | |
| 195 | 新增: t.Fatal(waitErr) | |
| 196 | 新增: } | |
| 197 | 新增: if _, err := os.Stat(filepath.Join(profile, "control.json")); !errors.Is(err, os.ErrNotExist) { | |
| 198 | 新增: t.Fatalf("released controller record still exists: %v", err) | |
| 199 | 新增: } | |
| 200 | 新增:} | |
| @@ -101,6 +101,10 @@ CAGE_DIAGNOSTIC_JOURNAL`) | ||
| 101 | 101 | // controller authenticates through the native launch ticket; offline recovery |
| 102 | 102 | // exports host logs only. No raw configuration is exported. |
| 103 | 103 | func ExportDiagnostics(configPath, destination string) error { |
| 104 | 新增: return ExportDiagnosticsForConnection(configPath, "", destination) | |
| 105 | 新增:} | |
| 106 | 新增: | |
| 107 | 新增:func ExportDiagnosticsForConnection(configPath, connectionID, destination string) error { | |
| 104 | 108 | if !filepath.IsAbs(destination) { |
| 105 | 109 | return errors.New("请选择本机绝对保存路径") |
| 106 | 110 | } |
| @@ -120,6 +124,9 @@ func ExportDiagnostics(configPath, destination string) error { | ||
| 120 | 124 | export := func() error { |
| 121 | 125 | c, e := connectController(profile) |
| 122 | 126 | if e != nil { |
| 127 | 新增: if connectionID != "" && connectionID != "local" { | |
| 128 | 新增: return errors.New("远程连接不可用,无法导出云端诊断包") | |
| 129 | 新增: } | |
| 123 | 130 | if e := store.ImportLegacy(profile); e != nil { |
| 124 | 131 | return e |
| 125 | 132 | } |
| @@ -135,6 +142,9 @@ func ExportDiagnostics(configPath, destination string) error { | ||
| 135 | 142 | if e != nil || code != 200 { |
| 136 | 143 | return errors.New("无法创建诊断导出会话,请重新打开 Cage") |
| 137 | 144 | } |
| 145 | 新增: if _, err := c.bindConnection(connectionID); err != nil { | |
| 146 | 新增: return err | |
| 147 | 新增: } | |
| 138 | 148 | c.client.Timeout = 30 * time.Second |
| 139 | 149 | req, _ := http.NewRequest("GET", c.origin+"/api/diagnostics/export", nil) |
| 140 | 150 | response, e := c.client.Do(req) |
| @@ -0,0 +1,113 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "testing" | |
| 9 | 新增: | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func TestStorageFirstSelectionAndMigrationThroughWorkbench(t *testing.T) { | |
| 14 | 新增: s := testServer(t) | |
| 15 | 新增: const endpoint = "/api/environment/storage" | |
| 16 | 新增: query := func() cage.StorageLocation { | |
| 17 | 新增: t.Helper() | |
| 18 | 新增: r := request(s, "GET", endpoint, s.origin, "", true) | |
| 19 | 新增: var loc cage.StorageLocation | |
| 20 | 新增: if r.Code != 200 || json.Unmarshal(r.Body.Bytes(), &loc) != nil { | |
| 21 | 新增: t.Fatalf("%d %s", r.Code, r.Body.String()) | |
| 22 | 新增: } | |
| 23 | 新增: return loc | |
| 24 | 新增: } | |
| 25 | 新增: previous := query() | |
| 26 | 新增: if previous.HasEnvironment { | |
| 27 | 新增: t.Fatal("fresh profile reported an environment") | |
| 28 | 新增: } | |
| 29 | 新增: target := filepath.Join(t.TempDir(), "Cage 空间") | |
| 30 | 新增: write := func(target string, prior cage.StorageLocation) Job { | |
| 31 | 新增: t.Helper() | |
| 32 | 新增: body, _ := json.Marshal(map[string]any{"directory": target, "previous": prior.Directory, "migrate": prior.HasEnvironment}) | |
| 33 | 新增: r := request(s, "POST", endpoint, s.origin, string(body), true) | |
| 34 | 新增: if r.Code != http.StatusOK { | |
| 35 | 新增: t.Fatal(r.Code, r.Body.String()) | |
| 36 | 新增: } | |
| 37 | 新增: return awaitJobIdle(t, &s.jobs) | |
| 38 | 新增: } | |
| 39 | 新增: if job := write(target, previous); job.Error != "" { | |
| 40 | 新增: t.Fatal(job) | |
| 41 | 新增: } | |
| 42 | 新增: location := query() | |
| 43 | 新增: real, err := filepath.EvalSymlinks(target) | |
| 44 | 新增: if err != nil || location.Directory != real || !location.Custom { | |
| 45 | 新增: t.Fatal(location, real, err) | |
| 46 | 新增: } | |
| 47 | 新增: for _, path := range []string{target, filepath.Dir(target), filepath.Join(target, "state")} { | |
| 48 | 新增: if _, err := validateWorkspace(path, s.profile); err == nil { | |
| 49 | 新增: t.Fatal("environment storage exposed as project", path) | |
| 50 | 新增: } | |
| 51 | 新增: } | |
| 52 | 新增: project := t.TempDir() | |
| 53 | 新增: if err := s.rememberSharedProject(project); err != nil { | |
| 54 | 新增: t.Fatal(err) | |
| 55 | 新增: } | |
| 56 | 新增: if job := write(filepath.Join(project, "private-disks"), location); job.Error == "" { | |
| 57 | 新增: t.Fatal("saved project accepted as environment storage") | |
| 58 | 新增: } | |
| 59 | 新增: staleTarget := filepath.Join(t.TempDir(), "old-window") | |
| 60 | 新增: if job := write(staleTarget, previous); job.Error == "" { | |
| 61 | 新增: t.Fatal("stale window redirected the active environment", job) | |
| 62 | 新增: } | |
| 63 | 新增: if _, err := os.Stat(staleTarget); !os.IsNotExist(err) { | |
| 64 | 新增: t.Fatal("stale request created a destination", err) | |
| 65 | 新增: } | |
| 66 | 新增: // A disk added between showing the form and submitting it must now require | |
| 67 | 新增: // the migration confirmation. Exercise the subsequent cold move through | |
| 68 | 新增: // the same authenticated HTTP operation used by the settings page. | |
| 69 | 新增: relativeDisk := filepath.Join("state", "lima", "fixture", "diffdisk") | |
| 70 | 新增: if err := os.MkdirAll(filepath.Dir(filepath.Join(target, relativeDisk)), 0700); err != nil { | |
| 71 | 新增: t.Fatal(err) | |
| 72 | 新增: } | |
| 73 | 新增: if err := os.WriteFile(filepath.Join(target, relativeDisk), []byte("isolated VM disk"), 0600); err != nil { | |
| 74 | 新增: t.Fatal(err) | |
| 75 | 新增: } | |
| 76 | 新增: second := filepath.Join(t.TempDir(), "Cage 环境") | |
| 77 | 新增: if job := write(second, location); job.Error == "" { | |
| 78 | 新增: t.Fatal("unconfirmed migration was accepted") | |
| 79 | 新增: } | |
| 80 | 新增: from := query() | |
| 81 | 新增: if !from.HasEnvironment { | |
| 82 | 新增: t.Fatal("disk was not discovered") | |
| 83 | 新增: } | |
| 84 | 新增: if job := write(second, from); job.Error != "" { | |
| 85 | 新增: t.Fatal(job) | |
| 86 | 新增: } | |
| 87 | 新增: moved := query() | |
| 88 | 新增: if !moved.HasEnvironment || moved.Backup != from.Directory { | |
| 89 | 新增: t.Fatal(moved) | |
| 90 | 新增: } | |
| 91 | 新增: for _, root := range []string{moved.Backup, moved.Directory} { | |
| 92 | 新增: data, err := os.ReadFile(filepath.Join(root, relativeDisk)) | |
| 93 | 新增: if err != nil || string(data) != "isolated VM disk" { | |
| 94 | 新增: t.Fatal(root, err) | |
| 95 | 新增: } | |
| 96 | 新增: } | |
| 97 | 新增:} | |
| 98 | 新增: | |
| 99 | 新增:func TestStorageChangeIsLocalAndRequiresUnlockedSession(t *testing.T) { | |
| 100 | 新增: s := testServer(t) | |
| 101 | 新增: const endpoint = "/api/environment/storage" | |
| 102 | 新增: s.remote = newRemoteGateway(s.profile) | |
| 103 | 新增: defer s.remote.manager.Close() | |
| 104 | 新增: s.remote.setRemote(true) | |
| 105 | 新增: if r := request(s, "POST", endpoint, s.origin, "{}", true); r.Code != http.StatusForbidden { | |
| 106 | 新增: t.Fatal("remote connection routed a storage request", r.Code) | |
| 107 | 新增: } | |
| 108 | 新增: s.remote.setRemote(false) | |
| 109 | 新增: s.account.lock() | |
| 110 | 新增: if r := request(s, "POST", endpoint, s.origin, "{}", true); r.Code != http.StatusLocked { | |
| 111 | 新增: t.Fatal("locked user could change storage", r.Code) | |
| 112 | 新增: } | |
| 113 | 新增:} | |
| @@ -0,0 +1,47 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/url" | |
| 6 | 新增: "os" | |
| 7 | 新增: "os/exec" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "testing" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/mounts" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:// NTFS junctions are available to ordinary users. Exercise the same private | |
| 15 | 新增:// directory through an unrelated DOS path in both sharing entry points. | |
| 16 | 新增:func TestWindowsJunctionCannotExposePrivateDirectory(t *testing.T) { | |
| 17 | 新增: s := testServer(t) | |
| 18 | 新增: parent := t.TempDir() | |
| 19 | 新增: alias := filepath.Join(parent, "环境别名") | |
| 20 | 新增: cmd := exec.Command("cmd.exe", "/d", "/v:off", "/c", "mklink", "/J", alias, s.profile) | |
| 21 | 新增: if out, err := cmd.CombinedOutput(); err != nil { | |
| 22 | 新增: t.Fatalf("create directory junction: %v, %s", err, out) | |
| 23 | 新增: } | |
| 24 | 新增: if err := os.Mkdir(filepath.Join(s.profile, "stored-data"), 0700); err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: for _, dir := range []string{alias, filepath.Join(alias, "stored-data")} { | |
| 28 | 新增: if _, err := validateWorkspace(dir, s.profile); err == nil { | |
| 29 | 新增: t.Fatal("private alias accepted as a workbench project", dir) | |
| 30 | 新增: } | |
| 31 | 新增: if _, denied := mounts.UnsafeProject(dir, mounts.Refs("", "", s.profile)); !denied { | |
| 32 | 新增: t.Fatal("private alias accepted as a CLI share", dir) | |
| 33 | 新增: } | |
| 34 | 新增: if w := request(s, "GET", "/api/projects/directories?path="+url.QueryEscape(dir), "", "", true); w.Code != 403 { | |
| 35 | 新增: t.Fatal("private alias browsable", w.Code) | |
| 36 | 新增: } | |
| 37 | 新增: } | |
| 38 | 新增: visible := filepath.Join(parent, "public") | |
| 39 | 新增: if err := os.Mkdir(visible, 0700); err != nil { | |
| 40 | 新增: t.Fatal(err) | |
| 41 | 新增: } | |
| 42 | 新增: w := request(s, "GET", "/api/projects/directories?path="+url.QueryEscape(parent), "", "", true) | |
| 43 | 新增: var listing struct{ Directories []struct{ Name string } } | |
| 44 | 新增: if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &listing) != nil || len(listing.Directories) != 1 || listing.Directories[0].Name != "public" { | |
| 45 | 新增: t.Fatal("directory picker exposed the private alias or hid the safe sibling", w.Code, w.Body.String()) | |
| 46 | 新增: } | |
| 47 | 新增:} | |
| @@ -2,14 +2,13 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "encoding/json" |
| 5 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 5 | 6 | "io" |
| 6 | 7 | "net/http" |
| 7 | 8 | "os" |
| 8 | 9 | "path/filepath" |
| 9 | 10 | "strings" |
| 10 | 11 | "testing" |
| 11 | 删除: | |
| 12 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 13 | 12 | ) |
| 14 | 13 | |
| 15 | 14 | type browserTransport func(*http.Request) (*http.Response, error) |
| @@ -42,7 +41,7 @@ func TestEnvironmentEntryPreservesLiveProject(t *testing.T) { | ||
| 42 | 41 | s := testServer(t) |
| 43 | 42 | s.preferences.Workspace, _ = filepath.EvalSymlinks(t.TempDir()) |
| 44 | 43 | workspace := s.workspace() |
| 45 | 删除: path := filepath.Join(s.profile, "state", "lima", vmname.Name(workspace), "cage-running.json") | |
| 44 | 新增: path := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, workspace), "cage-running.json") | |
| 46 | 45 | if err := writePrivate(filepath.Join(filepath.Dir(path), "lima.yaml"), map[string]string{}); err != nil { |
| 47 | 46 | t.Fatal(err) |
| 48 | 47 | } |
| @@ -14,7 +14,6 @@ import ( | ||
| 14 | 14 | "time" |
| 15 | 15 | |
| 16 | 16 | "al.essio.dev/pkg/shellescape" |
| 17 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 18 | 17 | ) |
| 19 | 18 | |
| 20 | 19 | var terminalFileID = regexp.MustCompile(`^[a-f0-9]{16}$`) |
| @@ -38,7 +37,7 @@ func (s *Server) guestFiles(ctx context.Context, target, method, path string, bo | ||
| 38 | 37 | } |
| 39 | 38 | script += " " + shellescape.Quote("http://localhost"+path) |
| 40 | 39 | } |
| 41 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", script) | |
| 40 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script) | |
| 42 | 41 | cmd.Stdin = body |
| 43 | 42 | pipe, err := cmd.StdoutPipe() |
| 44 | 43 | if err != nil { |
| @@ -94,6 +94,10 @@ func streamSelectedHostFiles(client *http.Client, origin, target, id string, fil | ||
| 94 | 94 | // UploadHostFiles is a native-only entry point. Paths come from an OS picker or |
| 95 | 95 | // a user-initiated clipboard snapshot, never an HTTP request or a guest page. |
| 96 | 96 | func UploadHostFiles(configPath, target, id string, paths []string) (map[string]any, error) { |
| 97 | 新增: return UploadHostFilesForConnection(configPath, "", target, id, paths) | |
| 98 | 新增:} | |
| 99 | 新增: | |
| 100 | 新增:func UploadHostFilesForConnection(configPath, connectionID, target, id string, paths []string) (map[string]any, error) { | |
| 97 | 101 | if (target != "browser" && target != "desktop" && target != "terminal") || !validFileTargetID(target, id) { |
| 98 | 102 | return nil, errors.New("文件上传目标无效") |
| 99 | 103 | } |
| @@ -116,6 +120,9 @@ func UploadHostFiles(configPath, target, id string, paths []string) (map[string] | ||
| 116 | 120 | if err != nil || status != http.StatusOK { |
| 117 | 121 | return nil, errors.New("无法连接文件上传会话") |
| 118 | 122 | } |
| 123 | 新增: if _, err = client.bindConnection(connectionID); err != nil { | |
| 124 | 新增: return nil, err | |
| 125 | 新增: } | |
| 119 | 126 | client.client.Timeout = 30 * time.Minute |
| 120 | 127 | pathsResult, err := streamSelectedHostFiles(client.client, client.origin, target, id, files) |
| 121 | 128 | if err != nil { |
| @@ -11,8 +11,6 @@ import ( | ||
| 11 | 11 | "net/http" |
| 12 | 12 | "strings" |
| 13 | 13 | "time" |
| 14 | 删除: | |
| 15 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 16 | 14 | ) |
| 17 | 15 | |
| 18 | 16 | const maxImageBytes = 20 << 20 |
| @@ -97,7 +95,7 @@ func (s *Server) guestImage(ctx context.Context, target string, data []byte) (ma | ||
| 97 | 95 | if target == "desktop" { |
| 98 | 96 | script = "systemctl is-active --quiet cage-claude-desktop.service && sudo -H -u cage env DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority /usr/local/bin/cage-image-input paste" |
| 99 | 97 | } |
| 100 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", script) | |
| 98 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script) | |
| 101 | 99 | cmd.Stdin = bytes.NewReader(data) |
| 102 | 100 | pipe, err := cmd.StdoutPipe() |
| 103 | 101 | if err != nil { |
| @@ -0,0 +1,105 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "bytes" | |
| 5 | 新增: "context" | |
| 6 | 新增: "encoding/json" | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "strings" | |
| 10 | 新增: "sync" | |
| 11 | 新增: "testing" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/cli" | |
| 15 | 新增: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 16 | 新增:) | |
| 17 | 新增: | |
| 18 | 新增:func TestControllerNamesMatchCLIForIndependentProfiles(t *testing.T) { | |
| 19 | 新增: base := os.TempDir() | |
| 20 | 新增: if filepath.Separator == '/' { | |
| 21 | 新增: base = "/tmp" | |
| 22 | 新增: } | |
| 23 | 新增: root, err := os.MkdirTemp(base, "vn") | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: t.Fatal(err) | |
| 26 | 新增: } | |
| 27 | 新增: defer os.RemoveAll(root) | |
| 28 | 新增: root, err = filepath.EvalSymlinks(root) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: workspace := filepath.Join(root, strings.Repeat("long-directory-", 6)) | |
| 33 | 新增: if err = os.Mkdir(workspace, 0700); err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增: saved, err := json.Marshal(map[string]string{"directory": workspace}) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: t.Fatal(err) | |
| 39 | 新增: } | |
| 40 | 新增: a := &Server{profile: filepath.Join(root, "a")} | |
| 41 | 新增: b := &Server{profile: filepath.Join(root, "another-profile")} | |
| 42 | 新增: cliName := func(s *Server) string { | |
| 43 | 新增: t.Helper() | |
| 44 | 新增: t.Setenv(cage.ConfigEnv, filepath.Join(s.profile, "config.json")) | |
| 45 | 新增: t.Setenv("AGENT_VM_STATE_DIR", filepath.Join(s.profile, "state")) | |
| 46 | 新增: t.Setenv("AGENT_VM_LIMA_HOME", filepath.Join(s.profile, "state", "lima")) | |
| 47 | 新增: var out, stderr bytes.Buffer | |
| 48 | 新增: if n := cli.Main([]string{"name", workspace}, cli.IO{Stdout: &out, Stderr: &stderr}); n != 0 { | |
| 49 | 新增: t.Fatalf("CLI name: %s", stderr.String()) | |
| 50 | 新增: } | |
| 51 | 新增: return strings.TrimSpace(out.String()) | |
| 52 | 新增: } | |
| 53 | 新增: for _, s := range []*Server{a, b} { | |
| 54 | 新增: if err = os.Mkdir(s.profile, 0700); err != nil { | |
| 55 | 新增: t.Fatal(err) | |
| 56 | 新增: } | |
| 57 | 新增: if err = os.WriteFile(filepath.Join(s.profile, "environment.json"), saved, 0600); err != nil { | |
| 58 | 新增: t.Fatal(err) | |
| 59 | 新增: } | |
| 60 | 新增: } | |
| 61 | 新增: an, bn := cliName(a), cliName(b) | |
| 62 | 新增: if an == bn || len(bn) >= len(an) || len(an) >= 76 { | |
| 63 | 新增: t.Fatalf("test requires different truncations: %q, %q", an, bn) | |
| 64 | 新增: } | |
| 65 | 新增: var wg sync.WaitGroup | |
| 66 | 新增: for s, want := range map[*Server]string{a: an, b: bn} { | |
| 67 | 新增: wg.Add(1) | |
| 68 | 新增: go func() { | |
| 69 | 新增: defer wg.Done() | |
| 70 | 新增: for i := 0; i < 20; i++ { | |
| 71 | 新增: if got := s.sshTarget(); got != "lima-"+want { | |
| 72 | 新增: t.Errorf("SSH target %s; CLI name %s", got, want) | |
| 73 | 新增: return | |
| 74 | 新增: } | |
| 75 | 新增: if got := filepath.Base(s.instanceDir()); got != want { | |
| 76 | 新增: t.Errorf("instance directory %s; CLI name %s", got, want) | |
| 77 | 新增: return | |
| 78 | 新增: } | |
| 79 | 新增: } | |
| 80 | 新增: }() | |
| 81 | 新增: } | |
| 82 | 新增: wg.Wait() | |
| 83 | 新增: loc, err := cage.GetStorageLocation(b.profile) | |
| 84 | 新增: if err != nil { | |
| 85 | 新增: t.Fatal(err) | |
| 86 | 新增: } | |
| 87 | 新增: if _, err = cage.MoveStorage(context.Background(), b.profile, filepath.Join(root, strings.Repeat("data-", 10)), loc, nil); err != nil { | |
| 88 | 新增: t.Fatal(err) | |
| 89 | 新增: } | |
| 90 | 新增: if got := cliName(b); got != bn || b.sshTarget() != "lima-"+bn { | |
| 91 | 新增: t.Fatalf("storage migration changed VM name: %s -> %s", bn, got) | |
| 92 | 新增: } | |
| 93 | 新增: // Preserve a stopped VM restored from an earlier, shorter socket path. | |
| 94 | 新增: old := vmname.Limit(len(bn) + 4).Name(workspace) | |
| 95 | 新增: dir := filepath.Join(b.profile, "state", "lima", old) | |
| 96 | 新增: if err = os.MkdirAll(dir, 0700); err != nil { | |
| 97 | 新增: t.Fatal(err) | |
| 98 | 新增: } | |
| 99 | 新增: if err = os.WriteFile(filepath.Join(dir, "lima.yaml"), []byte("{}"), 0600); err != nil { | |
| 100 | 新增: t.Fatal(err) | |
| 101 | 新增: } | |
| 102 | 新增: if got := cliName(b); got != old || b.sshTarget() != "lima-"+old { | |
| 103 | 新增: t.Fatalf("existing disk %s not reused; CLI picked %s", old, got) | |
| 104 | 新增: } | |
| 105 | 新增:} | |
| @@ -9,7 +9,6 @@ import ( | ||
| 9 | 9 | "time" |
| 10 | 10 | |
| 11 | 11 | "github.com/sylvinus/agent-vm/internal/cage" |
| 12 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 13 | 12 | ) |
| 14 | 13 | |
| 15 | 14 | func TestStopPreemptsJobWithoutLosingStopResult(t *testing.T) { |
| @@ -59,7 +58,7 @@ func TestPauseBypassesBusyQueueAndRevokesCheck(t *testing.T) { | ||
| 59 | 58 | if err != nil { |
| 60 | 59 | t.Fatal(err) |
| 61 | 60 | } |
| 62 | 删除: dir := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 61 | 新增: dir := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) | |
| 63 | 62 | if err = os.MkdirAll(dir, 0700); err != nil { |
| 64 | 63 | t.Fatal(err) |
| 65 | 64 | } |
| @@ -6,16 +6,18 @@ import ( | ||
| 6 | 6 | "fmt" |
| 7 | 7 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 8 | 8 | "runtime/debug" |
| 9 | 新增: "strings" | |
| 9 | 10 | "sync" |
| 10 | 11 | ) |
| 11 | 12 | |
| 12 | 13 | type Job struct { |
| 13 | 删除: ID string `json:"id"` | |
| 14 | 删除: Kind string `json:"kind"` | |
| 15 | 删除: Running bool `json:"running"` | |
| 16 | 删除: Message string `json:"message"` | |
| 17 | 删除: Error string `json:"error,omitempty"` | |
| 18 | 删除: Log string `json:"log,omitempty"` | |
| 14 | 新增: SetupProgress *SetupProgress `json:"setup_progress,omitempty"` | |
| 15 | 新增: ID string `json:"id"` | |
| 16 | 新增: Kind string `json:"kind"` | |
| 17 | 新增: Running bool `json:"running"` | |
| 18 | 新增: Message string `json:"message"` | |
| 19 | 新增: Error string `json:"error,omitempty"` | |
| 20 | 新增: Log string `json:"log,omitempty"` | |
| 19 | 21 | } |
| 20 | 22 | |
| 21 | 23 | var ( |
| @@ -72,6 +74,14 @@ func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uin | ||
| 72 | 74 | execution := &jobExecution{owner: m, id: m.state.ID, ctx: ctx, pauseVersion: pauseVersion} |
| 73 | 75 | execution.log = diagnostics.NewStream(diagnostics.Default(), "task/"+kind, "info", func(line string) { |
| 74 | 76 | if m.state.ID == execution.id { |
| 77 | 新增: if m.state.SetupProgress != nil { | |
| 78 | 新增: if p := parseSetupProgress(line); p != nil { | |
| 79 | 新增: m.state.SetupProgress = p | |
| 80 | 新增: if strings.HasPrefix(line, "CAGE_") { | |
| 81 | 新增: return | |
| 82 | 新增: } | |
| 83 | 新增: } | |
| 84 | 新增: } | |
| 75 | 85 | m.state.Log += line |
| 76 | 86 | if len(m.state.Log) > 24000 { |
| 77 | 87 | m.state.Log = m.state.Log[len(m.state.Log)-24000:] |
| @@ -17,7 +17,6 @@ import ( | ||
| 17 | 17 | "al.essio.dev/pkg/shellescape" |
| 18 | 18 | |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/cage" |
| 20 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 21 | 20 | ) |
| 22 | 21 | |
| 23 | 22 | // Only distribution/tool origins are reachable through this temporary channel. |
| @@ -49,7 +48,12 @@ func maintenanceDestination(address string, connect bool) bool { | ||
| 49 | 48 | if !connect && port != "80" { |
| 50 | 49 | return false |
| 51 | 50 | } |
| 52 | 删除: return maintenanceOrigins[strings.ToLower(host)] | |
| 51 | 新增: host = strings.ToLower(host) | |
| 52 | 新增: switch host { | |
| 53 | 新增: case "mirrors.nju.edu.cn", "mirrors.ustc.edu.cn", "cdn.npmmirror.com": | |
| 54 | 新增: return connect | |
| 55 | 新增: } | |
| 56 | 新增: return maintenanceOrigins[host] | |
| 53 | 57 | } |
| 54 | 58 | func (p *maintenanceProxy) track(conn net.Conn) bool { |
| 55 | 59 | p.mu.Lock() |
| @@ -164,7 +168,7 @@ cage_maintenance_dir=$(mktemp -d) | ||
| 164 | 168 | trap 'rm -rf "$cage_maintenance_dir"' EXIT |
| 165 | 169 | export CAGE_INSTALL_PROXY='http://cage-install:%[email protected]:%d' |
| 166 | 170 | export CAGE_APT_CONFIG="$cage_maintenance_dir/apt.conf" |
| 167 | 删除:printf 'Acquire::http::Proxy "%%s";\nAcquire::https::Proxy "%%s";\n' "$CAGE_INSTALL_PROXY" "$CAGE_INSTALL_PROXY" > "$CAGE_APT_CONFIG" | |
| 171 | 新增:printf 'Acquire::http::Proxy "%%s";\nAcquire::https::Proxy "%%s";\nAcquire::Retries "3";\nAcquire::http::Timeout "60";\nAcquire::https::Timeout "60";\n' "$CAGE_INSTALL_PROXY" "$CAGE_INSTALL_PROXY" > "$CAGE_APT_CONFIG" | |
| 168 | 172 | unset ALL_PROXY all_proxy NO_PROXY no_proxy FTP_PROXY ftp_proxy |
| 169 | 173 | export http_proxy="$CAGE_INSTALL_PROXY" https_proxy="$CAGE_INSTALL_PROXY" HTTP_PROXY="$CAGE_INSTALL_PROXY" HTTPS_PROXY="$CAGE_INSTALL_PROXY" |
| 170 | 174 | ( |
| @@ -187,7 +191,9 @@ func RunMaintenanceScript(ctx context.Context, configPath, script string, stdout | ||
| 187 | 191 | if err != nil { |
| 188 | 192 | return err |
| 189 | 193 | } |
| 190 | 删除: ctx, cancel := context.WithTimeout(ctx, 30*time.Minute) | |
| 194 | 新增: // Each download detects inactivity; cancellation still closes forwarding | |
| 195 | 新增: // and stops the guest operation without imposing a total install duration. | |
| 196 | 新增: ctx, cancel := context.WithCancel(ctx) | |
| 191 | 197 | defer cancel() |
| 192 | 198 | listener, err := net.Listen("tcp", "127.0.0.1:0") |
| 193 | 199 | if err != nil { |
| @@ -203,9 +209,9 @@ func RunMaintenanceScript(ctx context.Context, configPath, script string, stdout | ||
| 203 | 209 | defer stop() |
| 204 | 210 | s := &Server{profile: profile} |
| 205 | 211 | forward := fmt.Sprintf("127.0.0.1:%d:%s", maintenancePort, listener.Addr().String()) |
| 206 | 删除: command := "sudo systemd-run --quiet --pipe --wait --collect --unit=cage-maintenance-operation --property=User=cage --property=RuntimeMaxSec=1800 --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=" + shellescape.Quote(guestPath(s.environmentDir())) + " /bin/bash -se" | |
| 207 | 删除: cmd := s.sshCommandWithForwarding(ctx, "-o", "ExitOnForwardFailure=yes", "-R", forward, "-T", "lima-"+vmname.Name(s.environmentDir()), "--", command) | |
| 208 | 删除: cmd.Stdin = strings.NewReader(maintenanceScript(script, proxy.token)) | |
| 212 | 新增: command := "sudo systemd-run --quiet --pipe --wait --collect --unit=cage-maintenance-operation --property=User=cage --property=RuntimeMaxSec=infinity --property=KillMode=control-group --setenv=HOME=/home/cage --working-directory=" + shellescape.Quote(guestPath(s.environmentDir())) + " /bin/bash -se" | |
| 213 | 新增: cmd := s.sshCommandWithForwarding(ctx, "-o", "ExitOnForwardFailure=yes", "-R", forward, "-T", s.sshTarget(), "--", command) | |
| 214 | 新增: cmd.Stdin = strings.NewReader(maintenanceScript(cage.DebianMirrorsScript+"\n"+script, proxy.token)) | |
| 209 | 215 | cmd.Stdout = stdout |
| 210 | 216 | cmd.Stderr = stderr |
| 211 | 217 | if err = cmd.Run(); err != nil { |
| @@ -127,6 +127,11 @@ func TestMaintenanceClosesTLSConnectionsAndRefusesBusinessHosts(t *testing.T) { | ||
| 127 | 127 | t.Fatal("business or non-HTTPS destination accepted", address) |
| 128 | 128 | } |
| 129 | 129 | } |
| 130 | 新增: for _, host := range []string{"mirrors.nju.edu.cn", "mirrors.ustc.edu.cn", "cdn.npmmirror.com"} { | |
| 131 | 新增: if !maintenanceDestination(host+":443", true) || maintenanceDestination(host+":80", false) || maintenanceDestination(host+".evil.test:443", true) { | |
| 132 | 新增: t.Fatalf("unexpected mirror policy for %s", host) | |
| 133 | 新增: } | |
| 134 | 新增: } | |
| 130 | 135 | } |
| 131 | 136 | |
| 132 | 137 | func TestMaintenanceScriptUsesPrivateTemporaryConfiguration(t *testing.T) { |
| @@ -10,7 +10,6 @@ import ( | ||
| 10 | 10 | "time" |
| 11 | 11 | |
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 14 | 13 | ) |
| 15 | 14 | |
| 16 | 15 | func reloadedIntentServer(t *testing.T, previous *Server) *Server { |
| @@ -131,7 +130,7 @@ func TestQueuedSettingsApplyCannotClearLaterPersistentPause(t *testing.T) { | ||
| 131 | 130 | s, gate := interfaceMonitorServer(t) |
| 132 | 131 | pauseProxyNetwork(t, s) |
| 133 | 132 | // Keep the real settings write, but there is no live VM to stop in this fixture. |
| 134 | 删除: if err := os.Remove(filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json")); err != nil { | |
| 133 | 新增: if err := os.Remove(filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json")); err != nil { | |
| 135 | 134 | t.Fatal(err) |
| 136 | 135 | } |
| 137 | 136 | cfg, err := loadConfig(s.configPath) |
| @@ -41,9 +41,11 @@ func (s *Server) recoverNetwork() { | ||
| 41 | 41 | if blocked || r.RunID == "" { |
| 42 | 42 | return |
| 43 | 43 | } |
| 44 | 删除: // A healthy browser alone is insufficient when the guest remains under pressure. | |
| 44 | 新增: // The resource manager refreshes UpdatedAt even when a sample fails. | |
| 45 | 新增: // Only a recent pressure measurement should postpone the full gate check. | |
| 45 | 46 | resources, err := cage.ReadResourceStatus(s.instanceDir()) |
| 46 | 删除: if err == nil && (resources.Pressure || resources.HostPressure || resources.Error != "") { | |
| 47 | 新增: guestPressure := resources.Pressure && time.Since(resources.ObservedAt) <= 10*time.Second | |
| 48 | 新增: if err == nil && (guestPressure || resources.HostPressure) { | |
| 47 | 49 | return |
| 48 | 50 | } |
| 49 | 51 | _, _ = s.submitJob("network-recovery", func() error { return s.runNetworkRecovery(r, s.runSafetyCheck) }) |
| @@ -108,10 +110,6 @@ func (s *Server) finishNetworkRecovery(expected networkRecovery, err error) erro | ||
| 108 | 110 | } |
| 109 | 111 | if err == nil || s.closing || s.networkPaused || s.safety.pauseVersion != expected.PauseVersion || errors.Is(err, context.Canceled) { |
| 110 | 112 | s.recovery = networkRecovery{} |
| 111 | 删除: if err == nil { | |
| 112 | 删除: s.networkError = "" | |
| 113 | 删除: s.safety.Error = "" | |
| 114 | 删除: } | |
| 115 | 113 | return err |
| 116 | 114 | } |
| 117 | 115 | if current.RunID != "" { |
| @@ -3,12 +3,46 @@ package workbench | ||
| 3 | 3 | import ( |
| 4 | 4 | "context" |
| 5 | 5 | "errors" |
| 6 | 新增: "path/filepath" | |
| 6 | 7 | "testing" |
| 7 | 8 | "time" |
| 8 | 9 | |
| 9 | 10 | "github.com/sylvinus/agent-vm/internal/cage" |
| 10 | 11 | ) |
| 11 | 12 | |
| 13 | 新增:func TestNetworkRecoveryAdmissionRequiresObservedPressureToDefer(t *testing.T) { | |
| 14 | 新增: now := time.Now() | |
| 15 | 新增: for _, tc := range []struct { | |
| 16 | 新增: name string | |
| 17 | 新增: status cage.ResourceStatus | |
| 18 | 新增: wantJob bool | |
| 19 | 新增: }{ | |
| 20 | 新增: {"memory target could not be applied", cage.ResourceStatus{ObservedAt: now, Error: "内存目标未能应用,保持当前配置"}, true}, | |
| 21 | 新增: {"failed sample retains stale guest pressure", cage.ResourceStatus{ObservedAt: now.Add(-time.Minute), Error: "资源采样暂时不可用,已暂停内存回收", Pressure: true}, true}, | |
| 22 | 新增: {"current guest pressure", cage.ResourceStatus{ObservedAt: now, Pressure: true}, false}, | |
| 23 | 新增: {"current host pressure", cage.ResourceStatus{HostPressure: true}, false}, | |
| 24 | 新增: } { | |
| 25 | 新增: t.Run(tc.name, func(t *testing.T) { | |
| 26 | 新增: s, gate := failedMonitoringServer(t) | |
| 27 | 新增: s.recovery.Next = time.Now().Add(-time.Second) | |
| 28 | 新增: tc.status.Version, tc.status.UpdatedAt = 1, time.Now() | |
| 29 | 新增: if err := writePrivate(filepath.Join(s.instanceDir(), "cage-resources.json"), tc.status); err != nil { | |
| 30 | 新增: t.Fatal(err) | |
| 31 | 新增: } | |
| 32 | 新增: // Inspect actual job admission before allowing the queued worker to run. | |
| 33 | 新增: s.op.Lock() | |
| 34 | 新增: s.recoverNetwork() | |
| 35 | 新增: job := s.jobs.snapshot() | |
| 36 | 新增: s.jobs.cancelRunning() | |
| 37 | 新增: s.op.Unlock() | |
| 38 | 新增: s.jobs.close() | |
| 39 | 新增: if (job.Running && job.Kind == "network-recovery") != tc.wantJob || gate.Status().Mode != cage.GateClosed { | |
| 40 | 新增: t.Fatalf("job = %+v, want admitted = %v while gate remains closed", job, tc.wantJob) | |
| 41 | 新增: } | |
| 42 | 新增: }) | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 12 | 46 | func failedMonitoringServer(t *testing.T) (*Server, *cage.EgressGate) { |
| 13 | 47 | s, gate := grantedToolUpdateServer(t) |
| 14 | 48 | s.setJobForTest(Job{}) |
| @@ -0,0 +1,66 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http/httptest" | |
| 6 | 新增: "testing" | |
| 7 | 新增: "time" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func TestNetworkStatusImmediatelyAfterManualGrant(t *testing.T) { | |
| 13 | 新增: for _, independentError := range []string{"", "出口位置服务暂时不可用"} { | |
| 14 | 新增: t.Run("location-error="+independentError, func(t *testing.T) { | |
| 15 | 新增: s, gate := grantedToolUpdateServer(t) | |
| 16 | 新增: s.setJobForTest(Job{}) | |
| 17 | 新增: s.networkError = independentError | |
| 18 | 新增: openBeforeFailure := gate.Status() | |
| 19 | 新增: client, err := s.gateClient() | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: t.Fatal(err) | |
| 22 | 新增: } | |
| 23 | 新增: checkStatus := func(wantMode, wantError string) { | |
| 24 | 新增: t.Helper() | |
| 25 | 新增: response := httptest.NewRecorder() | |
| 26 | 新增: s.status(response, httptest.NewRequest("GET", "/api/status", nil)) | |
| 27 | 新增: var status struct { | |
| 28 | 新增: NetworkError string `json:"network_error"` | |
| 29 | 新增: Safety safetyState `json:"safety"` | |
| 30 | 新增: } | |
| 31 | 新增: if err := json.Unmarshal(response.Body.Bytes(), &status); err != nil { | |
| 32 | 新增: t.Fatal(err) | |
| 33 | 新增: } | |
| 34 | 新增: if status.Safety.Gate == nil || status.Safety.Gate.Mode != wantMode || status.NetworkError != wantError { | |
| 35 | 新增: t.Fatalf("expected %s and %q, got %+v", wantMode, wantError, status) | |
| 36 | 新增: } | |
| 37 | 新增: if wantMode == cage.GateOpen && status.Safety.Error != "" { | |
| 38 | 新增: t.Fatalf("open gate retained a safety error: %s", status.Safety.Error) | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: | |
| 42 | 新增: const issue = "代理出口探测超时" | |
| 43 | 新增: s.finishSafetyObservation(t.Context(), client, openBeforeFailure, "", issue, true) | |
| 44 | 新增: s.publishGate(openBeforeFailure) // A delayed poll must not clear the current failure. | |
| 45 | 新增: checkStatus(cage.GateClosed, issue) | |
| 46 | 新增: | |
| 47 | 新增: checking, err := client.BeginCheck(t.Context()) | |
| 48 | 新增: if err != nil { | |
| 49 | 新增: t.Fatal(err) | |
| 50 | 新增: } | |
| 51 | 新增: s.publishGate(checking) | |
| 52 | 新增: checkStatus(cage.GateChecking, issue) | |
| 53 | 新增: report := *checking.Report | |
| 54 | 新增: report.ID, report.CheckID, report.CreatedAt = "manual-recheck", checking.CheckID, time.Now() | |
| 55 | 新增: for i := range report.Checks { | |
| 56 | 新增: report.Checks[i].CheckedAt = report.CreatedAt | |
| 57 | 新增: } | |
| 58 | 新增: opened, err := client.Grant(t.Context(), report) | |
| 59 | 新增: if err != nil { | |
| 60 | 新增: t.Fatal(err) | |
| 61 | 新增: } | |
| 62 | 新增: s.publishGate(opened) | |
| 63 | 新增: checkStatus(cage.GateOpen, independentError) | |
| 64 | 新增: }) | |
| 65 | 新增: } | |
| 66 | 新增:} | |
| @@ -0,0 +1,80 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "io" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "os" | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "sort" | |
| 9 | 新增: "strings" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:// Directory browsing lists names without granting a share. The existing | |
| 16 | 新增:// projects/open operation remains the only authority to add a project. | |
| 17 | 新增:func (s *Server) projectDirectories(w http.ResponseWriter, r *http.Request) { | |
| 18 | 新增: path := r.URL.Query().Get("path") | |
| 19 | 新增: if path == "" { | |
| 20 | 新增: path, _ = os.UserHomeDir() | |
| 21 | 新增: } | |
| 22 | 新增: if !filepath.IsAbs(path) { | |
| 23 | 新增: http.Error(w, "请选择服务器上的绝对路径", 400) | |
| 24 | 新增: return | |
| 25 | 新增: } | |
| 26 | 新增: real, err := paths.Resolve(path) | |
| 27 | 新增: if err != nil { | |
| 28 | 新增: http.Error(w, "服务器目录不存在或无法访问", 400) | |
| 29 | 新增: return | |
| 30 | 新增: } | |
| 31 | 新增: reserved, err := privateProjectDirectories(s.profile) | |
| 32 | 新增: if err != nil { | |
| 33 | 新增: http.Error(w, "无法验证环境存储目录", 500) | |
| 34 | 新增: return | |
| 35 | 新增: } | |
| 36 | 新增: private := func(path string) bool { | |
| 37 | 新增: for _, dir := range reserved { | |
| 38 | 新增: if cage.StorageContains(dir, path) { | |
| 39 | 新增: return true | |
| 40 | 新增: } | |
| 41 | 新增: } | |
| 42 | 新增: return false | |
| 43 | 新增: } | |
| 44 | 新增: if private(real) { | |
| 45 | 新增: http.Error(w, "Cage 配置目录不能作为项目浏览", 403) | |
| 46 | 新增: return | |
| 47 | 新增: } | |
| 48 | 新增: directory, err := os.Open(real) | |
| 49 | 新增: if err != nil { | |
| 50 | 新增: http.Error(w, "无法读取服务器目录", 403) | |
| 51 | 新增: return | |
| 52 | 新增: } | |
| 53 | 新增: defer directory.Close() | |
| 54 | 新增: entries, err := directory.ReadDir(2001) | |
| 55 | 新增: if err != nil && err != io.EOF { | |
| 56 | 新增: http.Error(w, "无法读取服务器目录", 403) | |
| 57 | 新增: return | |
| 58 | 新增: } | |
| 59 | 新增: if len(entries) > 2000 { | |
| 60 | 新增: http.Error(w, "此目录项目过多,请直接输入更具体的路径", 413) | |
| 61 | 新增: return | |
| 62 | 新增: } | |
| 63 | 新增: type child struct { | |
| 64 | 新增: Name string `json:"name"` | |
| 65 | 新增: Path string `json:"path"` | |
| 66 | 新增: } | |
| 67 | 新增: children := []child{} | |
| 68 | 新增: for _, entry := range entries { | |
| 69 | 新增: if !entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { | |
| 70 | 新增: continue | |
| 71 | 新增: } | |
| 72 | 新增: path := filepath.Join(real, entry.Name()) | |
| 73 | 新增: if physical, err := paths.Resolve(path); err == nil && !private(physical) { | |
| 74 | 新增: children = append(children, child{Name: entry.Name(), Path: physical}) | |
| 75 | 新增: } | |
| 76 | 新增: } | |
| 77 | 新增: sort.Slice(children, func(i, j int) bool { return children[i].Name < children[j].Name }) | |
| 78 | 新增: _, selectableError := validateWorkspace(real, s.profile) | |
| 79 | 新增: jsonReply(w, map[string]any{"path": real, "parent": filepath.Dir(real), "directories": children, "selectable": selectableError == nil}) | |
| 80 | 新增:} | |
| @@ -16,7 +16,6 @@ import ( | ||
| 16 | 16 | "al.essio.dev/pkg/shellescape" |
| 17 | 17 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 18 | 18 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 19 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 20 | 19 | ) |
| 21 | 20 | |
| 22 | 21 | // connectProject is the shared project entry point. Callers hold the lifecycle |
| @@ -175,7 +174,7 @@ func (s *Server) ensureProjectShare(path string) (returned error) { | ||
| 175 | 174 | return err |
| 176 | 175 | } |
| 177 | 176 | script := "exec sshfs " + shellescape.Quote(":"+filepath.ToSlash(path)) + " " + quoted + " -o slave,allow_other,cache=no,nodev,nosuid" |
| 178 | 删除: cmd := s.sshCommand(s.lifetimeContext(), "-T", "lima-"+vmname.Name(s.environmentDir()), "--", script) | |
| 177 | 新增: cmd := s.sshCommand(s.lifetimeContext(), "-T", s.sshTarget(), "--", script) | |
| 179 | 178 | output, err := cmd.StdoutPipe() |
| 180 | 179 | if err != nil { |
| 181 | 180 | return err |
| @@ -2,6 +2,7 @@ package workbench | ||
| 2 | 2 | |
| 3 | 3 | import ( |
| 4 | 4 | "encoding/json" |
| 5 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 5 | 6 | "io" |
| 6 | 7 | "net" |
| 7 | 8 | "net/http" |
| @@ -16,7 +17,6 @@ import ( | ||
| 16 | 17 | "github.com/lima-vm/sshocker/pkg/reversesshfs" |
| 17 | 18 | "github.com/pkg/sftp" |
| 18 | 19 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 19 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 20 | 20 | ) |
| 21 | 21 | |
| 22 | 22 | func TestProjectSelectionKeepsOneVMAndExistingSessionsOffline(t *testing.T) { |
| @@ -24,11 +24,11 @@ func TestProjectSelectionKeepsOneVMAndExistingSessionsOffline(t *testing.T) { | ||
| 24 | 24 | cfg, _ := loadConfig(s.configPath) |
| 25 | 25 | s.preferences.Workspace = s.environmentDir() |
| 26 | 26 | s.ready, s.networkPaused = true, true |
| 27 | 删除: marker := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json") | |
| 27 | 新增: marker := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json") | |
| 28 | 28 | if err := writePrivate(marker, map[string]int{"pid": os.Getpid()}); err != nil { |
| 29 | 29 | t.Fatal(err) |
| 30 | 30 | } |
| 31 | 删除: originalVM := vmname.Name(s.environmentDir()) | |
| 31 | 新增: originalVM := cage.InstanceName(s.profile, s.environmentDir()) | |
| 32 | 32 | terminal := &terminalSession{id: "keep", title: "existing terminal"} |
| 33 | 33 | s.terminals.sessions = map[string]*terminalSession{terminal.id: terminal} |
| 34 | 34 | a, _ := filepath.EvalSymlinks(t.TempDir()) |
| @@ -41,7 +41,7 @@ func TestProjectSelectionKeepsOneVMAndExistingSessionsOffline(t *testing.T) { | ||
| 41 | 41 | if err := s.apply(savedProfile{cfg, next}, true); err != nil { |
| 42 | 42 | t.Fatal(err) |
| 43 | 43 | } |
| 44 | 删除: if !s.ready || !s.vmRunning() || !s.networkPaused || vmname.Name(s.environmentDir()) != originalVM { | |
| 44 | 新增: if !s.ready || !s.vmRunning() || !s.networkPaused || cage.InstanceName(s.profile, s.environmentDir()) != originalVM { | |
| 45 | 45 | t.Fatal("project selection changed environment lifecycle or networking") |
| 46 | 46 | } |
| 47 | 47 | if s.terminals.get(terminal.id) != terminal || terminal.closed { |
| @@ -220,7 +220,7 @@ func TestProjectActionsUseExplicitDirectoryWithoutSwitchingProject(t *testing.T) | ||
| 220 | 220 | t.Fatal(err) |
| 221 | 221 | } |
| 222 | 222 | s.projectShares = map[string]*projectShare{a: {done: make(chan struct{})}} |
| 223 | 删除: marker := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json") | |
| 223 | 新增: marker := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json") | |
| 224 | 224 | if err := writePrivate(marker, map[string]int{"pid": os.Getpid()}); err != nil { |
| 225 | 225 | t.Fatal(err) |
| 226 | 226 | } |
| @@ -474,8 +474,8 @@ func (s *Server) proxyLogs(w http.ResponseWriter, r *http.Request) { | ||
| 474 | 474 | lines = append(lines, src.Updated.Format("2006-01-02 15:04")+" · "+src.Name+" · "+src.Error) |
| 475 | 475 | } |
| 476 | 476 | s.mu.Lock() |
| 477 | 删除: if s.networkError != "" { | |
| 478 | 删除: lines = append(lines, s.networkError) | |
| 477 | 新增: if issue := s.currentNetworkErrorLocked(); issue != "" { | |
| 478 | 新增: lines = append(lines, issue) | |
| 479 | 479 | } |
| 480 | 480 | s.mu.Unlock() |
| 481 | 481 | jsonReply(w, map[string]any{"lines": lines}) |
| @@ -14,7 +14,6 @@ import ( | ||
| 14 | 14 | |
| 15 | 15 | "github.com/sylvinus/agent-vm/internal/cage" |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 17 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 18 | 17 | ) |
| 19 | 18 | |
| 20 | 19 | func interfaceMonitorServer(t *testing.T) (*Server, *cage.EgressGate) { |
| @@ -43,7 +42,7 @@ func interfaceMonitorServer(t *testing.T) (*Server, *cage.EgressGate) { | ||
| 43 | 42 | if err := os.WriteFile(filepath.Join(s.profile, "proxy", "config.yaml"), data, 0600); err != nil { |
| 44 | 43 | t.Fatal(err) |
| 45 | 44 | } |
| 46 | 删除: dir := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 45 | 新增: dir := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) | |
| 47 | 46 | if err := writePrivate(filepath.Join(dir, "cage-running.json"), map[string]int{"pid": os.Getpid()}); err != nil { |
| 48 | 47 | t.Fatal(err) |
| 49 | 48 | } |
| @@ -11,7 +11,6 @@ import ( | ||
| 11 | 11 | |
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 13 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 14 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 15 | 14 | ) |
| 16 | 15 | |
| 17 | 16 | // Keep the real request, job, source persistence and gate-control paths. Only |
| @@ -144,7 +143,7 @@ func TestManualProxySelectionMayResumeExistingPause(t *testing.T) { | ||
| 144 | 143 | pauseProxyNetwork(t, s) |
| 145 | 144 | // No VM is running in this case, so selecting a node may prepare networking |
| 146 | 145 | // without trying to start a real guest as part of this unit test. |
| 147 | 删除: path := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "cage-running.json") | |
| 146 | 新增: path := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir()), "cage-running.json") | |
| 148 | 147 | if err := os.Remove(path); err != nil { |
| 149 | 148 | t.Fatal(err) |
| 150 | 149 | } |
| @@ -0,0 +1,103 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: "net/url" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "regexp" | |
| 11 | 新增: "runtime" | |
| 12 | 新增: | |
| 13 | 新增: "github.com/sylvinus/agent-vm/internal/host" | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/version" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:const remoteAPIProtocol = 1 | |
| 18 | 新增: | |
| 19 | 新增:var remoteInstanceID = regexp.MustCompile(`^[a-f0-9]{64}$`) | |
| 20 | 新增: | |
| 21 | 新增:type remoteInstance struct { | |
| 22 | 新增: ID string `json:"id"` | |
| 23 | 新增:} | |
| 24 | 新增: | |
| 25 | 新增:// The instance identity belongs to persistent server data, not its address, | |
| 26 | 新增:// filesystem spelling, current process or the client's operating system. | |
| 27 | 新增:func ensureRemoteInstance(profile string) (string, error) { | |
| 28 | 新增: path := filepath.Join(profile, "remote-instance.json") | |
| 29 | 新增: if err := host.CheckPrivateFile(path); err == nil { | |
| 30 | 新增: data, err := os.ReadFile(path) | |
| 31 | 新增: var instance remoteInstance | |
| 32 | 新增: if err != nil || json.Unmarshal(data, &instance) != nil || !remoteInstanceID.MatchString(instance.ID) { | |
| 33 | 新增: return "", errors.New("远程实例身份记录无效,请保留数据并检查配置") | |
| 34 | 新增: } | |
| 35 | 新增: return instance.ID, nil | |
| 36 | 新增: } else if !os.IsNotExist(err) { | |
| 37 | 新增: return "", err | |
| 38 | 新增: } | |
| 39 | 新增: instance := remoteInstance{ID: randomToken()} | |
| 40 | 新增: if err := writePrivate(path, instance); err != nil { | |
| 41 | 新增: return "", err | |
| 42 | 新增: } | |
| 43 | 新增: return instance.ID, nil | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:type RemoteEntry struct { | |
| 47 | 新增: APIProtocol int `json:"api_protocol"` | |
| 48 | 新增: InstanceID string `json:"instance_id"` | |
| 49 | 新增: Version string `json:"version"` | |
| 50 | 新增: Platform string `json:"platform"` | |
| 51 | 新增: Runtime string `json:"runtime"` | |
| 52 | 新增: Origin string `json:"origin"` | |
| 53 | 新增: Ticket string `json:"ticket,omitempty"` | |
| 54 | 新增: Capabilities map[string]bool `json:"capabilities"` | |
| 55 | 新增:} | |
| 56 | 新增: | |
| 57 | 新增:func (s *Server) remoteManifest(w http.ResponseWriter, r *http.Request) { | |
| 58 | 新增: kind := "lima" | |
| 59 | 新增: if _, err := os.Stat(filepath.Join(s.profile, "container.json")); err == nil { | |
| 60 | 新增: kind = "container" | |
| 61 | 新增: } | |
| 62 | 新增: jsonReply(w, RemoteEntry{APIProtocol: remoteAPIProtocol, InstanceID: s.instanceID, | |
| 63 | 新增: Version: version.Version, Platform: runtime.GOOS, Runtime: kind, Origin: s.origin, | |
| 64 | 新增: Capabilities: map[string]bool{"projects_browse": true, "terminal": true, | |
| 65 | 新增: "browser": true, "desktop": true, "audio": true}}) | |
| 66 | 新增:} | |
| 67 | 新增: | |
| 68 | 新增:// ServerEntry is used only over an authenticated SSH command channel. It | |
| 69 | 新增:// attaches to the existing server without triggering desktop build takeover. | |
| 70 | 新增:// The returned ticket must travel on that private pipe, never a shared log. | |
| 71 | 新增:func ServerEntry(configPath string) (RemoteEntry, error) { | |
| 72 | 新增: var result RemoteEntry | |
| 73 | 新增: c, err := connectController(filepath.Dir(configPath)) | |
| 74 | 新增: if err != nil { | |
| 75 | 新增: return result, errors.New("云端 Cage 服务尚未运行或无法认证,请检查服务状态") | |
| 76 | 新增: } | |
| 77 | 新增: defer c.close() | |
| 78 | 新增: entry, err := url.Parse(c.launch.URL) | |
| 79 | 新增: if err != nil { | |
| 80 | 新增: return result, err | |
| 81 | 新增: } | |
| 82 | 新增: status, err := c.call("POST", "/api/session", map[string]string{"token": entry.Fragment}, nil) | |
| 83 | 新增: if err != nil || status != http.StatusOK { | |
| 84 | 新增: return result, errors.New("无法建立云端入口会话") | |
| 85 | 新增: } | |
| 86 | 新增: status, err = c.call("GET", "/api/remote/manifest", nil, &result) | |
| 87 | 新增: if err != nil || status != http.StatusOK || !remoteInstanceID.MatchString(result.InstanceID) { | |
| 88 | 新增: return RemoteEntry{}, errors.New("云端服务不支持当前远程连接协议") | |
| 89 | 新增: } | |
| 90 | 新增: // The manifest lookup consumed the first ticket; issue another for the | |
| 91 | 新增: // connecting client's private transport. | |
| 92 | 新增: var launch launchResponse | |
| 93 | 新增: status, err = c.call("POST", "/api/launch", map[string]string{"token": c.record.Token}, &launch) | |
| 94 | 新增: if err != nil || status != http.StatusOK { | |
| 95 | 新增: return RemoteEntry{}, errors.New("无法取得云端一次性入口") | |
| 96 | 新增: } | |
| 97 | 新增: u, err := url.Parse(launch.URL) | |
| 98 | 新增: if err != nil || u.Scheme+"://"+u.Host != c.origin || u.Fragment == "" { | |
| 99 | 新增: return RemoteEntry{}, errors.New("云端入口无效") | |
| 100 | 新增: } | |
| 101 | 新增: result.Ticket = u.Fragment | |
| 102 | 新增: return result, nil | |
| 103 | 新增:} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增:) | |
| 8 | 新增: | |
| 9 | 新增:type connectionTransport struct { | |
| 10 | 新增: base http.RoundTripper | |
| 11 | 新增: id string | |
| 12 | 新增:} | |
| 13 | 新增: | |
| 14 | 新增:func (t connectionTransport) RoundTrip(r *http.Request) (*http.Response, error) { | |
| 15 | 新增: copy := r.Clone(r.Context()) | |
| 16 | 新增: copy.Header.Set(connectionHeader, t.id) | |
| 17 | 新增: return t.base.RoundTrip(copy) | |
| 18 | 新增:} | |
| 19 | 新增: | |
| 20 | 新增:func (t connectionTransport) CloseIdleConnections() { | |
| 21 | 新增: if closer, ok := t.base.(interface{ CloseIdleConnections() }); ok { | |
| 22 | 新增: closer.CloseIdleConnections() | |
| 23 | 新增: } | |
| 24 | 新增:} | |
| 25 | 新增: | |
| 26 | 新增:// A native picker captures the connection before the user selects a file. | |
| 27 | 新增:// Matching it here prevents a slow picker from sending that file to a newly | |
| 28 | 新增:// selected server. Native calls from old local builds may omit it only locally. | |
| 29 | 新增:func (c *controllerClient) bindConnection(expected string) (ClientContext, error) { | |
| 30 | 新增: var current ClientContext | |
| 31 | 新增: status, err := c.call("GET", "/api/client/context", nil, ¤t) | |
| 32 | 新增: if err == nil && status == http.StatusNotFound && expected == "" { | |
| 33 | 新增: return ClientContext{Mode: "local", ConnectionID: "local"}, nil | |
| 34 | 新增: } | |
| 35 | 新增: if err != nil || status != http.StatusOK { | |
| 36 | 新增: return current, errors.New("无法核对当前文件传递连接") | |
| 37 | 新增: } | |
| 38 | 新增: if current.DesktopGateway && (expected == "" || current.Mode == "none") { | |
| 39 | 新增: return current, errors.New("请先选择工作环境,再重新进行文件操作") | |
| 40 | 新增: } | |
| 41 | 新增: if current.Mode == "remote" && (expected == "" || current.State.State != "connected") { | |
| 42 | 新增: return current, errors.New("远程连接不可用,请重新连接后选择文件") | |
| 43 | 新增: } | |
| 44 | 新增: if expected != "" && expected != current.ConnectionID { | |
| 45 | 新增: return current, errors.New("连接已经切换,请在当前主机重新选择文件") | |
| 46 | 新增: } | |
| 47 | 新增: c.connectionID = current.ConnectionID | |
| 48 | 新增: c.client.Transport = connectionTransport{base: c.client.Transport, id: current.ConnectionID} | |
| 49 | 新增: return current, nil | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:func clientDownloadProfile(profile string, current ClientContext) (string, error) { | |
| 53 | 新增: if current.Mode != "remote" { | |
| 54 | 新增: return profile, nil | |
| 55 | 新增: } | |
| 56 | 新增: if !remoteInstanceID.MatchString(current.InstanceID) { | |
| 57 | 新增: return "", errors.New("远程实例身份无效") | |
| 58 | 新增: } | |
| 59 | 新增: return filepath.Join(profile, "remote-downloads", current.InstanceID), nil | |
| 60 | 新增:} | |
| @@ -0,0 +1,331 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "errors" | |
| 6 | 新增: "mime" | |
| 7 | 新增: "net/http" | |
| 8 | 新增: "net/http/httputil" | |
| 9 | 新增: "net/url" | |
| 10 | 新增: "runtime" | |
| 11 | 新增: "strings" | |
| 12 | 新增: "sync" | |
| 13 | 新增: | |
| 14 | 新增: "github.com/sylvinus/agent-vm/internal/remotehost" | |
| 15 | 新增:) | |
| 16 | 新增: | |
| 17 | 新增:const connectionHeader = "X-Cage-Connection" | |
| 18 | 新增: | |
| 19 | 新增:type remoteGateway struct { | |
| 20 | 新增: mu sync.Mutex | |
| 21 | 新增: remote bool | |
| 22 | 新增: clientOnly bool | |
| 23 | 新增: store *remotehost.Store | |
| 24 | 新增: manager *remotehost.Manager | |
| 25 | 新增: desktop *desktopGateway | |
| 26 | 新增:} | |
| 27 | 新增: | |
| 28 | 新增:func newRemoteGateway(profile string) *remoteGateway { | |
| 29 | 新增: store := remotehost.NewStore(profile) | |
| 30 | 新增: return &remoteGateway{store: store, manager: remotehost.NewManager(store)} | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:func (g *remoteGateway) close() { | |
| 34 | 新增: if g.desktop != nil { | |
| 35 | 新增: g.desktop.close() | |
| 36 | 新增: } | |
| 37 | 新增: _ = g.manager.Close() | |
| 38 | 新增:} | |
| 39 | 新增: | |
| 40 | 新增:func (g *remoteGateway) isRemote() bool { | |
| 41 | 新增: g.mu.Lock() | |
| 42 | 新增: defer g.mu.Unlock() | |
| 43 | 新增: return g.remote | |
| 44 | 新增:} | |
| 45 | 新增: | |
| 46 | 新增:func (g *remoteGateway) setRemote(remote bool) { | |
| 47 | 新增: g.mu.Lock() | |
| 48 | 新增: g.remote = remote | |
| 49 | 新增: g.mu.Unlock() | |
| 50 | 新增:} | |
| 51 | 新增: | |
| 52 | 新增:type ClientContext struct { | |
| 53 | 新增: DesktopGateway bool `json:"desktop_gateway,omitempty"` | |
| 54 | 新增: Candidate *desktopCandidate `json:"candidate,omitempty"` | |
| 55 | 新增: ClientOnly bool `json:"client_only"` | |
| 56 | 新增: Mode string `json:"mode"` | |
| 57 | 新增: ClientPlatform string `json:"client_platform"` | |
| 58 | 新增: ConnectionID string `json:"connection_id"` | |
| 59 | 新增: State remotehost.ConnectionState `json:"connection"` | |
| 60 | 新增: InstanceID string `json:"instance_id,omitempty"` | |
| 61 | 新增: HostID string `json:"host_id,omitempty"` | |
| 62 | 新增: HostFingerprint string `json:"host_fingerprint,omitempty"` | |
| 63 | 新增: ServerPlatform string `json:"server_platform"` | |
| 64 | 新增: Name string `json:"name,omitempty"` | |
| 65 | 新增:} | |
| 66 | 新增: | |
| 67 | 新增:func (g *remoteGateway) context() ClientContext { | |
| 68 | 新增: if g.desktop != nil { | |
| 69 | 新增: return g.desktop.context() | |
| 70 | 新增: } | |
| 71 | 新增: result := ClientContext{Mode: "local", ConnectionID: "local", ClientPlatform: runtime.GOOS, ServerPlatform: runtime.GOOS} | |
| 72 | 新增: result.ClientOnly = g.clientOnly | |
| 73 | 新增: result.State = g.manager.Snapshot() | |
| 74 | 新增: if !g.isRemote() { | |
| 75 | 新增: return result | |
| 76 | 新增: } | |
| 77 | 新增: result.Mode, result.ConnectionID = "remote", result.State.ConnectionID | |
| 78 | 新增: result.HostID, result.InstanceID = result.State.HostID, result.State.InstanceID | |
| 79 | 新增: result.ServerPlatform = "linux" | |
| 80 | 新增: if hosts, err := g.store.List(); err == nil { | |
| 81 | 新增: for _, host := range hosts { | |
| 82 | 新增: if host.ID == result.HostID { | |
| 83 | 新增: result.Name = host.Name | |
| 84 | 新增: if host.HostKey != nil { | |
| 85 | 新增: result.HostFingerprint = host.HostKey.Fingerprint | |
| 86 | 新增: } | |
| 87 | 新增: break | |
| 88 | 新增: } | |
| 89 | 新增: } | |
| 90 | 新增: } | |
| 91 | 新增: return result | |
| 92 | 新增:} | |
| 93 | 新增: | |
| 94 | 新增:func (s *Server) clientRequest(w http.ResponseWriter, r *http.Request) { | |
| 95 | 新增: g := s.remote | |
| 96 | 新增: if g == nil { | |
| 97 | 新增: http.Error(w, "远程连接服务不可用", 503) | |
| 98 | 新增: return | |
| 99 | 新增: } | |
| 100 | 新增: path := strings.TrimPrefix(r.URL.Path, "/api/client/") | |
| 101 | 新增: if g.desktop != nil && g.desktop.handle(path, w, r) { | |
| 102 | 新增: return | |
| 103 | 新增: } | |
| 104 | 新增: switch { | |
| 105 | 新增: case r.Method == "GET" && path == "context": | |
| 106 | 新增: jsonReply(w, g.context()) | |
| 107 | 新增: case r.Method == "GET" && path == "connection": | |
| 108 | 新增: jsonReply(w, g.context().State) | |
| 109 | 新增: case r.Method == "GET" && path == "hosts": | |
| 110 | 新增: hosts, err := g.store.List() | |
| 111 | 新增: if err != nil { | |
| 112 | 新增: requestError(w, err) | |
| 113 | 新增: return | |
| 114 | 新增: } | |
| 115 | 新增: jsonReply(w, map[string]any{"hosts": hosts}) | |
| 116 | 新增: case (r.Method == "POST" && path == "hosts") || (r.Method == "PUT" && strings.HasPrefix(path, "hosts/")): | |
| 117 | 新增: var host remotehost.HostProfile | |
| 118 | 新增: if !readJSON(w, r, &host) { | |
| 119 | 新增: return | |
| 120 | 新增: } | |
| 121 | 新增: if r.Method == "PUT" { | |
| 122 | 新增: host.ID = strings.TrimPrefix(path, "hosts/") | |
| 123 | 新增: } else { | |
| 124 | 新增: host.ID = "" | |
| 125 | 新增: } | |
| 126 | 新增: if g.desktop != nil { | |
| 127 | 新增: g.desktop.change.Lock() | |
| 128 | 新增: defer g.desktop.change.Unlock() | |
| 129 | 新增: } | |
| 130 | 新增: if host.ID != "" && g.hostInUse(host.ID) { | |
| 131 | 新增: http.Error(w, "请先断开这台主机,再修改连接配置", 409) | |
| 132 | 新增: return | |
| 133 | 新增: } | |
| 134 | 新增: saved, err := g.store.Upsert(host) | |
| 135 | 新增: if err != nil { | |
| 136 | 新增: requestError(w, err) | |
| 137 | 新增: return | |
| 138 | 新增: } | |
| 139 | 新增: jsonReply(w, saved) | |
| 140 | 新增: case r.Method == "DELETE" && strings.HasPrefix(path, "hosts/"): | |
| 141 | 新增: id := strings.TrimPrefix(path, "hosts/") | |
| 142 | 新增: if g.desktop != nil { | |
| 143 | 新增: g.desktop.change.Lock() | |
| 144 | 新增: defer g.desktop.change.Unlock() | |
| 145 | 新增: } | |
| 146 | 新增: if g.hostInUse(id) { | |
| 147 | 新增: http.Error(w, "请先断开这台主机,再删除本机连接配置", 409) | |
| 148 | 新增: return | |
| 149 | 新增: } | |
| 150 | 新增: if err := g.store.Delete(id); err != nil { | |
| 151 | 新增: requestError(w, err) | |
| 152 | 新增: return | |
| 153 | 新增: } | |
| 154 | 新增: jsonReply(w, map[string]bool{"ok": true}) | |
| 155 | 新增: case r.Method == "POST" && path == "connect": | |
| 156 | 新增: var input struct { | |
| 157 | 新增: HostID string `json:"host_id"` | |
| 158 | 新增: Deploy bool `json:"deploy,omitempty"` | |
| 159 | 新增: Passphrase string `json:"passphrase"` | |
| 160 | 新增: } | |
| 161 | 新增: if !readJSON(w, r, &input) { | |
| 162 | 新增: return | |
| 163 | 新增: } | |
| 164 | 新增: secret := []byte(input.Passphrase) | |
| 165 | 新增: input.Passphrase = "" | |
| 166 | 新增: state, err := g.manager.Connect(input.HostID, remotehost.ConnectSecrets{Passphrase: secret, Deploy: input.Deploy}) | |
| 167 | 新增: clear(secret) | |
| 168 | 新增: if err != nil { | |
| 169 | 新增: clear(secret) | |
| 170 | 新增: requestError(w, err) | |
| 171 | 新增: return | |
| 172 | 新增: } | |
| 173 | 新增: g.setRemote(true) | |
| 174 | 新增: w.WriteHeader(http.StatusAccepted) | |
| 175 | 新增: jsonReply(w, state) | |
| 176 | 新增: case r.Method == "POST" && (path == "disconnect" || path == "local"): | |
| 177 | 新增: if path == "local" && g.clientOnly { | |
| 178 | 新增: http.Error(w, "轻量客户端仅连接远程环境", 409) | |
| 179 | 新增: return | |
| 180 | 新增: } | |
| 181 | 新增: var input struct { | |
| 182 | 新增: ConnectionID string `json:"connection_id"` | |
| 183 | 新增: } | |
| 184 | 新增: if !readJSON(w, r, &input) { | |
| 185 | 新增: return | |
| 186 | 新增: } | |
| 187 | 新增: if err := g.manager.Disconnect(input.ConnectionID); err != nil { | |
| 188 | 新增: requestError(w, err) | |
| 189 | 新增: return | |
| 190 | 新增: } | |
| 191 | 新增: if path == "local" { | |
| 192 | 新增: g.setRemote(false) | |
| 193 | 新增: } | |
| 194 | 新增: jsonReply(w, g.context()) | |
| 195 | 新增: default: | |
| 196 | 新增: http.NotFound(w, r) | |
| 197 | 新增: } | |
| 198 | 新增:} | |
| 199 | 新增: | |
| 200 | 新增:func (g *remoteGateway) hostInUse(id string) bool { | |
| 201 | 新增: c := g.context() | |
| 202 | 新增: inUse := func(state remotehost.ConnectionState) bool { | |
| 203 | 新增: return state.HostID == id && (state.State == "connecting" || state.State == "connected") | |
| 204 | 新增: } | |
| 205 | 新增: return inUse(c.State) || (c.Candidate != nil && inUse(c.Candidate.Connection)) | |
| 206 | 新增:} | |
| 207 | 新增: | |
| 208 | 新增:func requestConnection(r *http.Request) string { | |
| 209 | 新增: if value := r.Header.Get(connectionHeader); value != "" { | |
| 210 | 新增: return value | |
| 211 | 新增: } | |
| 212 | 新增: return r.URL.Query().Get("connection") | |
| 213 | 新增:} | |
| 214 | 新增: | |
| 215 | 新增:// routeRemote runs after local Host/Origin/session authentication and before | |
| 216 | 新增:// the local account gate. Only business API requests cross SSH: neither the | |
| 217 | 新增:// remote server's scripts nor its bootstrap/update routes enter the client. | |
| 218 | 新增:func (s *Server) routeRemote(w http.ResponseWriter, r *http.Request) bool { | |
| 219 | 新增: if s.remote == nil || !strings.HasPrefix(r.URL.Path, "/api/") { | |
| 220 | 新增: return false | |
| 221 | 新增: } | |
| 222 | 新增: if strings.HasPrefix(r.URL.Path, "/api/client/") { | |
| 223 | 新增: s.clientRequest(w, r) | |
| 224 | 新增: return true | |
| 225 | 新增: } | |
| 226 | 新增: switch r.URL.Path { | |
| 227 | 新增: case "/api/session", "/api/launch", "/api/handoff": | |
| 228 | 新增: return false | |
| 229 | 新增: case "/api/remote/manifest": | |
| 230 | 新增: if s.remote.desktop != nil { | |
| 231 | 新增: http.NotFound(w, r) | |
| 232 | 新增: return true | |
| 233 | 新增: } | |
| 234 | 新增: return false | |
| 235 | 新增: } | |
| 236 | 新增: if r.URL.Path == "/api/diagnostics/events" { | |
| 237 | 新增: return false | |
| 238 | 新增: } | |
| 239 | 新增: var session *remotehost.Session | |
| 240 | 新增: remote := true | |
| 241 | 新增: var err error | |
| 242 | 新增: if desktop := s.remote.desktop; desktop != nil { | |
| 243 | 新增: session, remote, err = desktop.acquire(requestConnection(r)) | |
| 244 | 新增: } else if !s.remote.isRemote() { | |
| 245 | 新增: if s.clientOnly && r.URL.Path != "/api/diagnostics/events" { | |
| 246 | 新增: http.Error(w, "请先连接远程主机", 409) | |
| 247 | 新增: return true | |
| 248 | 新增: } | |
| 249 | 新增: if id := requestConnection(r); id != "" && id != "local" { | |
| 250 | 新增: http.Error(w, "连接已经切换,请重新打开当前工作台", 409) | |
| 251 | 新增: return true | |
| 252 | 新增: } | |
| 253 | 新增: return false | |
| 254 | 新增: } else { | |
| 255 | 新增: session, err = s.remote.manager.Acquire(requestConnection(r)) | |
| 256 | 新增: } | |
| 257 | 新增: if remote && r.URL.Path == "/api/environment/storage" { | |
| 258 | 新增: http.Error(w, "请在虚拟机所在电脑上调整环境存储", http.StatusForbidden) | |
| 259 | 新增: return true | |
| 260 | 新增: } | |
| 261 | 新增: if err != nil { | |
| 262 | 新增: http.Error(w, "连接不可用或已切换,请重新选择工作环境", 409) | |
| 263 | 新增: return true | |
| 264 | 新增: } | |
| 265 | 新增: | |
| 266 | 新增: if remote && r.Method == "GET" && r.URL.Path == "/api/browser/files/saved" { | |
| 267 | 新增: profile, err := clientDownloadProfile(s.profile, ClientContext{Mode: "remote", InstanceID: session.Ref.InstanceID}) | |
| 268 | 新增: if err != nil { | |
| 269 | 新增: requestError(w, err) | |
| 270 | 新增: return true | |
| 271 | 新增: } | |
| 272 | 新增: serveSavedDownloads(w, profile) | |
| 273 | 新增: return true | |
| 274 | 新增: } | |
| 275 | 新增: target, err := url.Parse(session.Origin) | |
| 276 | 新增: if err != nil { | |
| 277 | 新增: http.Error(w, "远程入口无效", 502) | |
| 278 | 新增: return true | |
| 279 | 新增: } | |
| 280 | 新增: ctx, cancel := context.WithCancel(r.Context()) | |
| 281 | 新增: stop := context.AfterFunc(session.Context, cancel) | |
| 282 | 新增: defer func() { stop(); cancel() }() | |
| 283 | 新增: proxy := &httputil.ReverseProxy{ | |
| 284 | 新增: Transport: session.Transport, | |
| 285 | 新增: FlushInterval: -1, | |
| 286 | 新增: Rewrite: func(p *httputil.ProxyRequest) { | |
| 287 | 新增: p.SetURL(target) | |
| 288 | 新增: p.Out.Host = target.Host | |
| 289 | 新增: p.Out.Header.Del(connectionHeader) | |
| 290 | 新增: query := p.Out.URL.Query() | |
| 291 | 新增: query.Del("connection") | |
| 292 | 新增: p.Out.URL.RawQuery = query.Encode() | |
| 293 | 新增: }, | |
| 294 | 新增: ModifyResponse: func(response *http.Response) error { | |
| 295 | 新增: response.Header.Del("Set-Cookie") | |
| 296 | 新增: response.Header.Del("Content-Security-Policy") | |
| 297 | 新增: response.Header.Del("Access-Control-Allow-Origin") | |
| 298 | 新增: response.Header.Set("X-Content-Type-Options", "nosniff") | |
| 299 | 新增: if response.StatusCode >= 300 && response.StatusCode < 400 { | |
| 300 | 新增: return errors.New("remote redirects are refused") | |
| 301 | 新增: } | |
| 302 | 新增: if downloadID := strings.TrimSuffix(strings.TrimPrefix(response.Request.URL.Path, "/api/browser/files/downloads/"), "/content"); strings.HasSuffix(response.Request.URL.Path, "/content") && browserFileID.MatchString(downloadID) { | |
| 303 | 新增: name := "download" | |
| 304 | 新增: _, parameters, err := mime.ParseMediaType(response.Header.Get("Content-Disposition")) | |
| 305 | 新增: if err == nil && browserDownloadName(parameters["filename"]) { | |
| 306 | 新增: name = parameters["filename"] | |
| 307 | 新增: } | |
| 308 | 新增: response.Header.Set("Content-Type", "application/octet-stream") | |
| 309 | 新增: response.Header.Set("Content-Disposition", mime.FormatMediaType("attachment", map[string]string{"filename": name})) | |
| 310 | 新增: return nil | |
| 311 | 新增: } | |
| 312 | 新增: if response.StatusCode != http.StatusSwitchingProtocols && response.StatusCode != http.StatusNoContent { | |
| 313 | 新增: contentType, _, err := mime.ParseMediaType(response.Header.Get("Content-Type")) | |
| 314 | 新增: if err != nil { | |
| 315 | 新增: return errors.New("remote response has no supported content type") | |
| 316 | 新增: } | |
| 317 | 新增: switch contentType { | |
| 318 | 新增: case "application/json", "text/plain", "text/event-stream", "application/octet-stream", "application/zip", "image/png", "image/jpeg", "image/webp": | |
| 319 | 新增: default: | |
| 320 | 新增: return errors.New("remote active content is refused") | |
| 321 | 新增: } | |
| 322 | 新增: } | |
| 323 | 新增: return nil | |
| 324 | 新增: }, | |
| 325 | 新增: ErrorHandler: func(w http.ResponseWriter, _ *http.Request, _ error) { | |
| 326 | 新增: http.Error(w, "远程连接已中断;已提交的操作请重连后核对", http.StatusBadGateway) | |
| 327 | 新增: }, | |
| 328 | 新增: } | |
| 329 | 新增: proxy.ServeHTTP(w, r.WithContext(ctx)) | |
| 330 | 新增: return true | |
| 331 | 新增:} | |
| @@ -0,0 +1,125 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "encoding/json" | |
| 5 | 新增: "net/http" | |
| 6 | 新增: "net/http/httptest" | |
| 7 | 新增: "net/url" | |
| 8 | 新增: "os" | |
| 9 | 新增: "path/filepath" | |
| 10 | 新增: "strings" | |
| 11 | 新增: "testing" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestRemoteHostManagementKeepsLocalSessionAndOriginBoundary(t *testing.T) { | |
| 15 | 新增: s := testServer(t) | |
| 16 | 新增: s.remote = newRemoteGateway(s.profile) | |
| 17 | 新增: defer s.remote.manager.Close() | |
| 18 | 新增: s.account.lock() | |
| 19 | 新增: if got := request(s, "GET", "/api/client/hosts", "", "", false).Code; got != 401 { | |
| 20 | 新增: t.Fatalf("unauthenticated host list: %d", got) | |
| 21 | 新增: } | |
| 22 | 新增: if got := request(s, "GET", "/api/client/context", "", "", true).Code; got != 200 { | |
| 23 | 新增: t.Fatalf("locked local account prevents connection management: %d", got) | |
| 24 | 新增: } | |
| 25 | 新增: if got := request(s, "POST", "/api/client/disconnect", "https://untrusted.example", "{}", true).Code; got != 403 { | |
| 26 | 新增: t.Fatalf("cross-origin connection mutation: %d", got) | |
| 27 | 新增: } | |
| 28 | 新增: s.remote.setRemote(true) | |
| 29 | 新增: if got := request(s, "POST", "/api/start", s.origin, "{}", true).Code; got != 409 { | |
| 30 | 新增: t.Fatalf("disconnected remote fell back to local start: %d", got) | |
| 31 | 新增: } | |
| 32 | 新增: if job := s.jobs.snapshot(); job.ID != "" { | |
| 33 | 新增: t.Fatal("disconnected remote created a local job") | |
| 34 | 新增: } | |
| 35 | 新增: s.remote.setRemote(false) | |
| 36 | 新增: r := httptest.NewRequest("POST", s.origin+"/api/stop", strings.NewReader("{}")) | |
| 37 | 新增: r.Header.Set("Origin", s.origin) | |
| 38 | 新增: r.Header.Set("Content-Type", "application/json") | |
| 39 | 新增: r.Header.Set(connectionHeader, "previous-remote-connection") | |
| 40 | 新增: r.AddCookie(&http.Cookie{Name: s.cookieName(), Value: s.session}) | |
| 41 | 新增: w := httptest.NewRecorder() | |
| 42 | 新增: s.handler().ServeHTTP(w, r) | |
| 43 | 新增: if w.Code != 409 { | |
| 44 | 新增: t.Fatalf("old remote request reached local runtime: %d", w.Code) | |
| 45 | 新增: } | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:func TestRemoteIdentityPersistsAndCorruptionDoesNotReplaceIt(t *testing.T) { | |
| 49 | 新增: profile := t.TempDir() | |
| 50 | 新增: first, err := ensureRemoteInstance(profile) | |
| 51 | 新增: if err != nil { | |
| 52 | 新增: t.Fatal(err) | |
| 53 | 新增: } | |
| 54 | 新增: again, err := ensureRemoteInstance(profile) | |
| 55 | 新增: if err != nil || first != again { | |
| 56 | 新增: t.Fatal("identity changed on reconnect", err) | |
| 57 | 新增: } | |
| 58 | 新增: other, err := ensureRemoteInstance(t.TempDir()) | |
| 59 | 新增: if err != nil || first == other { | |
| 60 | 新增: t.Fatal("different instances share an identity", err) | |
| 61 | 新增: } | |
| 62 | 新增: path := filepath.Join(profile, "remote-instance.json") | |
| 63 | 新增: corrupt := []byte(`{"id":"invalid"}`) | |
| 64 | 新增: if err := os.WriteFile(path, corrupt, 0600); err != nil { | |
| 65 | 新增: t.Fatal(err) | |
| 66 | 新增: } | |
| 67 | 新增: if _, err := ensureRemoteInstance(profile); err == nil { | |
| 68 | 新增: t.Fatal("corrupt identity was accepted") | |
| 69 | 新增: } | |
| 70 | 新增: retained, _ := os.ReadFile(path) | |
| 71 | 新增: if string(retained) != string(corrupt) { | |
| 72 | 新增: t.Fatal("corrupt identity was silently replaced") | |
| 73 | 新增: } | |
| 74 | 新增:} | |
| 75 | 新增: | |
| 76 | 新增:func TestRemoteDirectoryPickerHandlesEmptyProjectsAndBlocksPrivateSymlinks(t *testing.T) { | |
| 77 | 新增: s := testServer(t) | |
| 78 | 新增: empty := t.TempDir() | |
| 79 | 新增: w := request(s, "GET", "/api/projects/directories?path="+url.QueryEscape(empty), "", "", true) | |
| 80 | 新增: if w.Code != 200 { | |
| 81 | 新增: t.Fatal(w.Code, w.Body.String()) | |
| 82 | 新增: } | |
| 83 | 新增: var result struct { | |
| 84 | 新增: Directories []any `json:"directories"` | |
| 85 | 新增: Selectable bool `json:"selectable"` | |
| 86 | 新增: } | |
| 87 | 新增: if json.Unmarshal(w.Body.Bytes(), &result) != nil || len(result.Directories) != 0 || !result.Selectable { | |
| 88 | 新增: t.Fatal("empty project unavailable", w.Body.String()) | |
| 89 | 新增: } | |
| 90 | 新增: link := filepath.Join(t.TempDir(), "private-link") | |
| 91 | 新增: paths := []string{s.profile} | |
| 92 | 新增: if err := os.Symlink(s.profile, link); err == nil { | |
| 93 | 新增: paths = append(paths, link) | |
| 94 | 新增: } | |
| 95 | 新增: for _, path := range paths { | |
| 96 | 新增: w := request(s, "GET", "/api/projects/directories?path="+url.QueryEscape(path), "", "", true) | |
| 97 | 新增: if w.Code != 403 { | |
| 98 | 新增: t.Fatalf("private directory was listed: %d", w.Code) | |
| 99 | 新增: } | |
| 100 | 新增: } | |
| 101 | 新增:} | |
| 102 | 新增: | |
| 103 | 新增:func TestRemoteDownloadsAreScopedToPersistentInstance(t *testing.T) { | |
| 104 | 新增: profile := t.TempDir() | |
| 105 | 新增: first := ClientContext{Mode: "remote", InstanceID: strings.Repeat("a", 64)} | |
| 106 | 新增: second := ClientContext{Mode: "remote", InstanceID: strings.Repeat("b", 64)} | |
| 107 | 新增: one, err := clientDownloadProfile(profile, first) | |
| 108 | 新增: if err != nil { | |
| 109 | 新增: t.Fatal(err) | |
| 110 | 新增: } | |
| 111 | 新增: two, err := clientDownloadProfile(profile, second) | |
| 112 | 新增: if err != nil { | |
| 113 | 新增: t.Fatal(err) | |
| 114 | 新增: } | |
| 115 | 新增: saved := SavedDownload{ID: testBrowserFileID, InstanceID: first.InstanceID, Name: "project.zip", Path: filepath.Join(t.TempDir(), "project.zip")} | |
| 116 | 新增: if err := rememberDownload(one, saved, false); err != nil { | |
| 117 | 新增: t.Fatal(err) | |
| 118 | 新增: } | |
| 119 | 新增: if _, err := readSavedDownload(two, saved.ID); !os.IsNotExist(err) { | |
| 120 | 新增: t.Fatal("another host inherited the local file", err) | |
| 121 | 新增: } | |
| 122 | 新增: if _, err := clientDownloadProfile(profile, ClientContext{Mode: "remote", InstanceID: "../../private"}); err == nil { | |
| 123 | 新增: t.Fatal("invalid instance path accepted") | |
| 124 | 新增: } | |
| 125 | 新增:} | |
| @@ -7,15 +7,37 @@ import ( | ||
| 7 | 7 | |
| 8 | 8 | "github.com/docker/go-units" |
| 9 | 9 | "github.com/sylvinus/agent-vm/internal/cage" |
| 10 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 10 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 11 | 11 | "go.yaml.in/yaml/v3" |
| 12 | 12 | ) |
| 13 | 13 | |
| 14 | 14 | func (s *Server) instanceDir() string { |
| 15 | 删除: return filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 15 | 新增: if containerenv.Configured(s.profile) { | |
| 16 | 新增: return filepath.Join(s.profile, "state", "container", "environment") | |
| 17 | 新增: } | |
| 18 | 新增: return filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) | |
| 16 | 19 | } |
| 17 | 20 | |
| 18 | 21 | func (s *Server) resourceStatus(w http.ResponseWriter, r *http.Request) { |
| 22 | 新增: if containerenv.Configured(s.profile) { | |
| 23 | 新增: environment, err := containerenv.Load(s.profile) | |
| 24 | 新增: if err != nil { | |
| 25 | 新增: requestError(w, err) | |
| 26 | 新增: return | |
| 27 | 新增: } | |
| 28 | 新增: state, err := environment.State(r.Context()) | |
| 29 | 新增: if err != nil { | |
| 30 | 新增: requestError(w, err) | |
| 31 | 新增: return | |
| 32 | 新增: } | |
| 33 | 新增: config := environment.Config() | |
| 34 | 新增: jsonReply(w, map[string]any{"running": state.Running, "automatic": false, "runtime": "container", | |
| 35 | 新增: "recommended_memory_bytes": config.MemoryBytes, "recommended_cpus": config.CPUs, | |
| 36 | 新增: "configured_memory_bytes": state.MemoryBytes, "configured_cpus": state.CPUs, | |
| 37 | 新增: "resources_verified": state.ResourcesVerified, "resource_error": state.ResourceError, "pids_limit": state.PIDs, | |
| 38 | 新增: "restart_required": false, "observation": nil}) | |
| 39 | 新增: return | |
| 40 | 新增: } | |
| 19 | 41 | memory, cpus := cage.ResourceLimits() |
| 20 | 42 | running := s.vmRunning() |
| 21 | 43 | var configured struct { |
| @@ -14,8 +14,8 @@ import ( | ||
| 14 | 14 | "al.essio.dev/pkg/shellescape" |
| 15 | 15 | |
| 16 | 16 | "github.com/sylvinus/agent-vm/internal/cage" |
| 17 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 17 | 18 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 18 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 19 | 19 | ) |
| 20 | 20 | |
| 21 | 21 | var loadConfig = cage.Load |
| @@ -28,6 +28,27 @@ type guestCredentials struct { | ||
| 28 | 28 | |
| 29 | 29 | func (s *Server) workspace() string { s.mu.Lock(); defer s.mu.Unlock(); return s.preferences.Workspace } |
| 30 | 30 | func (s *Server) environmentDir() string { return environmentWorkspace(s.profile) } |
| 31 | 新增:func (s *Server) sshTarget() string { | |
| 32 | 新增: if containerenv.Configured(s.profile) { | |
| 33 | 新增: return "cage-container" | |
| 34 | 新增: } | |
| 35 | 新增: return "lima-" + cage.InstanceName(s.profile, s.environmentDir()) | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func (s *Server) environmentPrepared() bool { | |
| 39 | 新增: if containerenv.Configured(s.profile) { | |
| 40 | 新增: environment, err := containerenv.Load(s.profile) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: return false | |
| 43 | 新增: } | |
| 44 | 新增: ctx, cancel := context.WithTimeout(s.lifetimeContext(), 3*time.Second) | |
| 45 | 新增: defer cancel() | |
| 46 | 新增: state, err := environment.State(ctx) | |
| 47 | 新增: return err == nil && state.Exists | |
| 48 | 新增: } | |
| 49 | 新增: _, err := os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")) | |
| 50 | 新增: return err == nil | |
| 51 | 新增:} | |
| 31 | 52 | func (s *Server) sshCommand(ctx context.Context, args ...string) *exec.Cmd { |
| 32 | 53 | return s.sshCommandOptions(ctx, false, args...) |
| 33 | 54 | } |
| @@ -35,8 +56,7 @@ func (s *Server) sshCommandWithForwarding(ctx context.Context, args ...string) * | ||
| 35 | 56 | return s.sshCommandOptions(ctx, true, args...) |
| 36 | 57 | } |
| 37 | 58 | func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args ...string) *exec.Cmd { |
| 38 | 删除: name := vmname.Name(s.environmentDir()) | |
| 39 | 删除: cfg := filepath.Join(s.profile, "state", "lima", name, "ssh.config") | |
| 59 | 新增: cfg := filepath.Join(s.instanceDir(), "ssh.config") | |
| 40 | 60 | base := []string{"-q", "-e", "none", "-F", cfg, "-o", "BatchMode=yes", "-o", "IdentitiesOnly=yes", "-o", "PermitLocalCommand=no", "-o", "PasswordAuthentication=no", "-o", "KbdInteractiveAuthentication=no", "-o", "ProxyCommand=none", "-o", "ProxyJump=none", "-o", "ConnectTimeout=3", "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=2", "-o", "ForwardAgent=no", "-o", "IdentityAgent=none", "-o", "ForwardX11=no", "-o", "ClearAllForwardings=yes", "-o", "ControlPath=none"} |
| 41 | 61 | if maintenance { |
| 42 | 62 | for index, value := range base { |
| @@ -52,11 +72,10 @@ func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args . | ||
| 52 | 72 | return cmd |
| 53 | 73 | } |
| 54 | 74 | func (s *Server) guest(ctx context.Context, script string) ([]byte, error) { |
| 55 | 删除: name := vmname.Name(s.environmentDir()) | |
| 56 | 75 | // SSH enters the user's default shell. Run control scripts in Bash so |
| 57 | 76 | // zsh initialization cannot change their redirection or error behavior. |
| 58 | 77 | command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script) |
| 59 | 删除: cmd := s.sshCommand(ctx, "-T", "lima-"+name, "--", command) | |
| 78 | 新增: cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command) | |
| 60 | 79 | pipe, err := cmd.StdoutPipe() |
| 61 | 80 | if err != nil { |
| 62 | 81 | return nil, err |
| @@ -76,12 +95,35 @@ func (s *Server) guest(ctx context.Context, script string) ([]byte, error) { | ||
| 76 | 95 | return data, nil |
| 77 | 96 | } |
| 78 | 97 | func (s *Server) attach() error { |
| 79 | 删除: | |
| 80 | 删除: if !s.vmRunning() { | |
| 81 | 删除: return errors.New("环境尚未启动") | |
| 82 | 删除: } | |
| 83 | 98 | ctx, cancel := s.controlContext() |
| 84 | 99 | defer cancel() |
| 100 | 新增: if containerenv.Configured(s.profile) { | |
| 101 | 新增: environment, err := containerenv.Load(s.profile) | |
| 102 | 新增: if err != nil { | |
| 103 | 新增: return err | |
| 104 | 新增: } | |
| 105 | 新增: state, err := environment.State(ctx) | |
| 106 | 新增: if err != nil { | |
| 107 | 新增: return err | |
| 108 | 新增: } | |
| 109 | 新增: if !state.Running { | |
| 110 | 新增: return errors.New("环境尚未启动") | |
| 111 | 新增: } | |
| 112 | 新增: if !state.Ready { | |
| 113 | 新增: s.mu.Lock() | |
| 114 | 新增: s.ready = false | |
| 115 | 新增: s.mu.Unlock() | |
| 116 | 新增: if !state.MountsReady { | |
| 117 | 新增: return errors.New("容器项目共享需要初始化,请保存工作后完整停止并重新启动环境") | |
| 118 | 新增: } | |
| 119 | 新增: if !state.ResourcesVerified { | |
| 120 | 新增: return errors.New("容器资源限制尚未通过核验,请检查服务器资源配置") | |
| 121 | 新增: } | |
| 122 | 新增: return errors.New("容器网络与文件连接尚未就绪,请重试启动") | |
| 123 | 新增: } | |
| 124 | 新增: } else if !s.vmRunning() { | |
| 125 | 新增: return errors.New("环境尚未启动") | |
| 126 | 新增: } | |
| 85 | 127 | b, err := s.guest(ctx, guestConnectionSnapshot) |
| 86 | 128 | if err != nil { |
| 87 | 129 | return errors.New("环境尚未准备好") |
| @@ -152,8 +194,14 @@ func (s *Server) monitor(ctx context.Context) { | ||
| 152 | 194 | } |
| 153 | 195 | |
| 154 | 196 | func (s *Server) runCage(args ...string) error { |
| 155 | 删除: ctx, cancel := context.WithTimeout(s.operationContext(), 30*time.Minute) | |
| 156 | 删除: defer cancel() | |
| 197 | 新增: ctx := s.operationContext() | |
| 198 | 新增: // Setup and startup can both install dependencies. Downloads own their | |
| 199 | 新增: // inactivity timeouts; the operation context still permits an explicit stop. | |
| 200 | 新增: if len(args) != 1 || (args[0] != "setup" && args[0] != "up") { | |
| 201 | 新增: var cancel context.CancelFunc | |
| 202 | 新增: ctx, cancel = context.WithTimeout(ctx, 30*time.Minute) | |
| 203 | 新增: defer cancel() | |
| 204 | 新增: } | |
| 157 | 205 | cmd := exec.CommandContext(ctx, s.exe, args...) |
| 158 | 206 | hideCommand(cmd) |
| 159 | 207 | cmd.Dir = s.environmentDir() |
| @@ -162,6 +210,9 @@ func (s *Server) runCage(args ...string) error { | ||
| 162 | 210 | } |
| 163 | 211 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath) |
| 164 | 212 | execution := s.jobs.execution() |
| 213 | 新增: if len(args) == 1 && args[0] == "setup" { | |
| 214 | 新增: cmd.Env = append(cmd.Env, "CAGE_SETUP_PROGRESS=1") | |
| 215 | 新增: } | |
| 165 | 216 | cmd.Env = append(cmd.Env, cage.JobEnv+"="+execution.id) |
| 166 | 217 | cmd.Stdout, cmd.Stderr = execution, execution |
| 167 | 218 | if err := cmd.Run(); err != nil { |
| @@ -178,6 +229,22 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 178 | 229 | if _, err := validateWorkspace(s.environmentDir(), s.profile); err != nil { |
| 179 | 230 | return err |
| 180 | 231 | } |
| 232 | 新增: if containerenv.Configured(s.profile) { | |
| 233 | 新增: environment, err := containerenv.Load(s.profile) | |
| 234 | 新增: if err != nil { | |
| 235 | 新增: return err | |
| 236 | 新增: } | |
| 237 | 新增: state, err := environment.State(s.operationContext()) | |
| 238 | 新增: if err != nil { | |
| 239 | 新增: return err | |
| 240 | 新增: } | |
| 241 | 新增: if state.Running && !state.MountsReady { | |
| 242 | 新增: s.mu.Lock() | |
| 243 | 新增: s.ready = false | |
| 244 | 新增: s.mu.Unlock() | |
| 245 | 新增: return errors.New("容器项目共享需要初始化,请保存工作后先停止环境,再重新启动;项目和登录数据会保留") | |
| 246 | 新增: } | |
| 247 | 新增: } | |
| 181 | 248 | cfg, err := loadConfig(s.configPath) |
| 182 | 249 | if err != nil { |
| 183 | 250 | return err |
| @@ -261,7 +328,7 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 261 | 328 | } |
| 262 | 329 | if auto && syncTimezone && !s.vmRunning() { |
| 263 | 330 | if probeErr != nil { |
| 264 | 删除: if _, e := os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")); e != nil { | |
| 331 | 新增: if !s.environmentPrepared() { | |
| 265 | 332 | return probeErr |
| 266 | 333 | } |
| 267 | 334 | } |
| @@ -286,17 +353,21 @@ func (s *Server) startEnvironment(syncTimezone bool) error { | ||
| 286 | 353 | } |
| 287 | 354 | } else if probeErr != nil { |
| 288 | 355 | s.setMessage("正在检查代理连通性…") |
| 289 | 删除: if _, e := os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")); e != nil { | |
| 356 | 新增: if !s.environmentPrepared() { | |
| 290 | 357 | if err = s.runCage("check"); err != nil { |
| 291 | 358 | return err |
| 292 | 359 | } |
| 293 | 360 | } |
| 294 | 361 | } |
| 295 | 删除: if _, err = os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")); os.IsNotExist(err) { | |
| 362 | 新增: if _, err = os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")); !containerenv.Configured(s.profile) && os.IsNotExist(err) { | |
| 296 | 363 | s.setMessage("首次准备 Linux 环境与开发工具,可能需要数分钟…") |
| 364 | 新增: job := s.jobs.execution() | |
| 365 | 新增: job.setSetupProgress(&SetupProgress{Phase: "image", Label: "正在准备 Debian 13 镜像"}) | |
| 297 | 366 | if err = s.runCage("setup"); err != nil { |
| 298 | 367 | return err |
| 299 | 368 | } |
| 369 | 新增: job.setSetupProgress(&SetupProgress{Phase: "services", Label: "正在启动浏览器和编辑器"}) | |
| 370 | 新增: defer job.setSetupProgress(nil) | |
| 300 | 371 | } |
| 301 | 372 | s.setMessage("正在启动浏览器、编辑器与共享文件…") |
| 302 | 373 | if err = s.runCage("up"); err != nil { |
| @@ -321,7 +392,7 @@ func (s *Server) stopEnvironment() (returned error) { | ||
| 321 | 392 | returned = managedproxy.Stop(s.profile) |
| 322 | 393 | } |
| 323 | 394 | }() |
| 324 | 删除: if explicitStop && cage.InstanceJobID(filepath.Join(s.profile, "state"), "base-building") != "" { | |
| 395 | 新增: if (explicitStop || s.jobs.snapshot().Kind == "storage") && cage.InstanceJobID(filepath.Join(s.profile, "state"), "base-building") != "" { | |
| 325 | 396 | if err := s.runCage("stop", "base-building"); err != nil { |
| 326 | 397 | return err |
| 327 | 398 | } |
| @@ -344,7 +415,7 @@ func (s *Server) stopEnvironment() (returned error) { | ||
| 344 | 415 | if s.workspace() == "" { |
| 345 | 416 | return nil |
| 346 | 417 | } |
| 347 | 删除: if _, err := os.Stat(filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()), "lima.yaml")); os.IsNotExist(err) { | |
| 418 | 新增: if _, err := os.Stat(filepath.Join(s.instanceDir(), "lima.yaml")); !containerenv.Configured(s.profile) && os.IsNotExist(err) { | |
| 348 | 419 | return nil |
| 349 | 420 | } |
| 350 | 421 | if err := s.runCage("stop"); err != nil { |
| @@ -464,10 +535,20 @@ func (s *Server) monitorNetwork(ctx context.Context) { | ||
| 464 | 535 | } |
| 465 | 536 | |
| 466 | 537 | func vmAlive(profile, workspace string) bool { |
| 538 | 新增: if containerenv.Configured(profile) { | |
| 539 | 新增: environment, err := containerenv.Load(profile) | |
| 540 | 新增: if err != nil { | |
| 541 | 新增: return false | |
| 542 | 新增: } | |
| 543 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 544 | 新增: defer cancel() | |
| 545 | 新增: state, err := environment.State(ctx) | |
| 546 | 新增: return err == nil && state.Running | |
| 547 | 新增: } | |
| 467 | 548 | if workspace == "" { |
| 468 | 549 | return false |
| 469 | 550 | } |
| 470 | 删除: b, e := os.ReadFile(filepath.Join(profile, "state", "lima", vmname.Name(workspace), "cage-running.json")) | |
| 551 | 新增: b, e := os.ReadFile(filepath.Join(profile, "state", "lima", cage.InstanceName(profile, workspace), "cage-running.json")) | |
| 471 | 552 | if e != nil { |
| 472 | 553 | return false |
| 473 | 554 | } |
| @@ -0,0 +1,23 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "context" | |
| 5 | 新增: "io" | |
| 6 | 新增: "path/filepath" | |
| 7 | 新增: | |
| 8 | 新增: "al.essio.dev/pkg/shellescape" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// RunEnvironmentCommand shares the real SSH transport used by the workbench. | |
| 12 | 新增:// Arguments are explicitly supplied by a local CLI user, never by a web page. | |
| 13 | 新增:func RunEnvironmentCommand(ctx context.Context, configPath string, args []string, stdin io.Reader, stdout, stderr io.Writer, interactive bool) error { | |
| 14 | 新增: s := &Server{profile: filepath.Dir(configPath), configPath: configPath} | |
| 15 | 新增: command := "cd -- " + shellescape.Quote(guestPath(s.environmentDir())) + " && exec " + shellescape.QuoteCommand(args) | |
| 16 | 新增: terminal := "-T" | |
| 17 | 新增: if interactive { | |
| 18 | 新增: terminal = "-tt" | |
| 19 | 新增: } | |
| 20 | 新增: cmd := s.sshCommand(ctx, terminal, s.sshTarget(), "--", "exec /bin/bash -lc "+shellescape.Quote(command)) | |
| 21 | 新增: cmd.Stdin, cmd.Stdout, cmd.Stderr = stdin, stdout, stderr | |
| 22 | 新增: return cmd.Run() | |
| 23 | 新增:} | |
| @@ -6,6 +6,7 @@ import ( | ||
| 6 | 6 | "crypto/rand" |
| 7 | 7 | "errors" |
| 8 | 8 | "fmt" |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 10 | "net" |
| 10 | 11 | "os" |
| 11 | 12 | "os/exec" |
| @@ -13,7 +14,6 @@ import ( | ||
| 13 | 14 | "testing" |
| 14 | 15 | "time" |
| 15 | 16 | |
| 16 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 17 | 17 | "golang.org/x/crypto/ssh" |
| 18 | 18 | ) |
| 19 | 19 | |
| @@ -109,7 +109,7 @@ command_not_found_handler() { return 127; } | ||
| 109 | 109 | } |
| 110 | 110 | }() |
| 111 | 111 | s := testServer(t) |
| 112 | 删除: dir := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 112 | 新增: dir := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) | |
| 113 | 113 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 114 | 114 | t.Fatal(err) |
| 115 | 115 | } |
| @@ -17,8 +17,8 @@ import ( | ||
| 17 | 17 | |
| 18 | 18 | "al.essio.dev/pkg/shellescape" |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/cage" |
| 20 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 20 | 21 | "github.com/sylvinus/agent-vm/internal/paths" |
| 21 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 22 | 22 | "go.yaml.in/yaml/v3" |
| 23 | 23 | ) |
| 24 | 24 | |
| @@ -27,6 +27,7 @@ var guestSafetyProbe string | ||
| 27 | 27 | |
| 28 | 28 | type safetyState struct { |
| 29 | 29 | pauseVersion uint64 |
| 30 | 新增: monitorError string | |
| 30 | 31 | Gate *cage.GateStatus `json:"gate,omitempty"` |
| 31 | 32 | Report *cage.SafetyReport `json:"report,omitempty"` |
| 32 | 33 | Error string `json:"error,omitempty"` |
| @@ -64,19 +65,34 @@ type browserObservation struct { | ||
| 64 | 65 | } |
| 65 | 66 | |
| 66 | 67 | func (s *Server) gateClient() (*cage.GateClient, error) { |
| 67 | 删除: return cage.OpenGateClient(filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir()))) | |
| 68 | 新增: return cage.OpenGateClient(s.instanceDir()) | |
| 68 | 69 | } |
| 69 | 70 | |
| 70 | 71 | func (s *Server) publishGate(state cage.GateStatus) { |
| 71 | 72 | s.mu.Lock() |
| 72 | 73 | defer s.mu.Unlock() |
| 73 | 删除: if old := s.safety.Gate; old != nil && old.RunID == state.RunID && old.Epoch > state.Epoch { | |
| 74 | 新增: old := s.safety.Gate | |
| 75 | 新增: if old != nil && old.RunID == state.RunID && old.Epoch > state.Epoch { | |
| 74 | 76 | return |
| 75 | 77 | } |
| 76 | 78 | s.safety.Gate = &state |
| 77 | 79 | if state.Mode == cage.GateOpen && state.Report != nil { |
| 78 | 80 | s.safety.Report = state.Report |
| 81 | 新增: // A repeated status poll of the old grant is not a new authorization. | |
| 82 | 新增: if old == nil || old.RunID != state.RunID || old.Epoch != state.Epoch { | |
| 83 | 新增: s.safety.Error = "" | |
| 84 | 新增: s.safety.monitorError = "" | |
| 85 | 新增: } | |
| 86 | 新增: } | |
| 87 | 新增:} | |
| 88 | 新增: | |
| 89 | 新增:// A gate grant resolves a monitoring failure. Independent diagnostics, such | |
| 90 | 新增:// as a location lookup failure, are cleared by the operation that owns them. | |
| 91 | 新增:func (s *Server) currentNetworkErrorLocked() string { | |
| 92 | 新增: if s.safety.monitorError != "" { | |
| 93 | 新增: return s.safety.monitorError | |
| 79 | 94 | } |
| 95 | 新增: return s.networkError | |
| 80 | 96 | } |
| 81 | 97 | |
| 82 | 98 | func (s *Server) publishReport(report cage.SafetyReport) { |
| @@ -142,14 +158,15 @@ func (s *Server) safetyExport(w http.ResponseWriter, r *http.Request) { | ||
| 142 | 158 | } |
| 143 | 159 | // Exports cannot authorize networking and contain no proxy hash, address, |
| 144 | 160 | // credentials, launch ticket or host filesystem paths. |
| 145 | 删除: jsonReply(w, map[string]any{"policy": report.Policy, "created_at": report.CreatedAt, "checks": report.Checks, "scope": "采样与运行时策略检查;不代表平台账号资格或完整虚拟化审计"}) | |
| 161 | 新增: jsonReply(w, map[string]any{"policy": report.Policy, "created_at": report.CreatedAt, "checks": report.Checks, "scope": "采样与运行时策略检查;不代表平台账号资格或完整隔离审计"}) | |
| 146 | 162 | } |
| 147 | 163 | |
| 148 | 164 | // The probe runs in Linux, while its files are created on the host. Use the |
| 149 | 165 | // same guest path mapping as the VM's mounts for both sides of the boundary. |
| 150 | 166 | func boundaryProbeInput(port int, nonce, privateFile, sharedFile, challenge string) map[string]any { |
| 151 | 167 | return map[string]any{"stage": "boundary", "control_port": port, "nonce": nonce, |
| 152 | 删除: "private_file": guestPath(privateFile), "shared_file": guestPath(sharedFile), "challenge": challenge} | |
| 168 | 新增: "management_host": "192.168.5.2", | |
| 169 | 新增: "private_file": guestPath(privateFile), "shared_file": guestPath(sharedFile), "challenge": challenge} | |
| 153 | 170 | } |
| 154 | 171 | |
| 155 | 172 | func (s *Server) guestObservation(ctx context.Context, input map[string]any) (guestObservation, error) { |
| @@ -187,11 +204,24 @@ func browserSettingsMatch(v browserObservation, cfg cage.Config) bool { | ||
| 187 | 204 | } |
| 188 | 205 | |
| 189 | 206 | func (s *Server) inspectVMLayout() (bool, bool) { |
| 207 | 新增: if containerenv.Configured(s.profile) { | |
| 208 | 新增: environment, err := containerenv.Load(s.profile) | |
| 209 | 新增: if err != nil { | |
| 210 | 新增: return false, false | |
| 211 | 新增: } | |
| 212 | 新增: ctx, cancel := s.controlContext() | |
| 213 | 新增: defer cancel() | |
| 214 | 新增: inspection, err := environment.Inspect(ctx) | |
| 215 | 新增: if err != nil { | |
| 216 | 新增: return false, false | |
| 217 | 新增: } | |
| 218 | 新增: return inspection.FilesystemConfined, inspection.NetworkConfined | |
| 219 | 新增: } | |
| 190 | 220 | workspace, err := validateWorkspace(s.environmentDir(), s.profile) |
| 191 | 221 | if err != nil { |
| 192 | 222 | return false, false |
| 193 | 223 | } |
| 194 | 删除: data, err := os.ReadFile(filepath.Join(s.profile, "state", "lima", vmname.Name(workspace), "lima.yaml")) | |
| 224 | 新增: data, err := os.ReadFile(filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, workspace), "lima.yaml")) | |
| 195 | 225 | if err != nil { |
| 196 | 226 | return false, false |
| 197 | 227 | } |
| @@ -365,7 +395,7 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 365 | 395 | s.mu.Unlock() |
| 366 | 396 | }() |
| 367 | 397 | report := cage.SafetyReport{Policy: cage.SafetyPolicyVersion, ID: randomToken()[:32], RunID: state.RunID, CheckID: state.CheckID, Configuration: cfg.Fingerprint(), CreatedAt: time.Now()} |
| 368 | 删除: for _, item := range [][2]string{{"egress_policy", "VM 外出站约束"}, {"proxy_transport", "终端检测通道"}, {"dns_transport", "DNS 与解析约束"}, {"guest_settings", "系统时区与语言"}, {"browser_settings", "浏览器时区与语言"}, {"filesystem_boundary", "共享文件与宿主私有目录"}, {"management_boundary", "宿主管理接口"}, {"fail_closed", "代理故障关闭"}, {"udp_policy", "UDP 出站约束"}, {"ipv6_policy", "IPv6 出站约束"}, {"exit_consistency", "出口符合已保存规则"}} { | |
| 398 | 新增: for _, item := range [][2]string{{"egress_policy", "环境外出站约束"}, {"proxy_transport", "终端检测通道"}, {"dns_transport", "DNS 与解析约束"}, {"guest_settings", "系统时区与语言"}, {"browser_settings", "浏览器时区与语言"}, {"filesystem_boundary", "共享文件与宿主私有目录"}, {"management_boundary", "宿主管理接口"}, {"fail_closed", "代理故障关闭"}, {"udp_policy", "UDP 出站约束"}, {"ipv6_policy", "IPv6 出站约束"}, {"exit_consistency", "出口符合已保存规则"}} { | |
| 369 | 399 | report.Checks = append(report.Checks, cage.SafetyCheck{ID: item[0], Title: item[1], Critical: true, State: cage.CheckUnknown, Evidence: "尚未取得证据", Remedy: "完成检测后查看结果;未知项目不会自动通过", CheckedAt: report.CreatedAt}) |
| 370 | 400 | } |
| 371 | 401 | set := func(id string, result cage.CheckState, evidence, remedy string) { |
| @@ -403,7 +433,11 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 403 | 433 | control, _ := url.Parse(s.origin) |
| 404 | 434 | port, _ := strconv.Atoi(control.Port()) |
| 405 | 435 | s.setMessage("正在验证离线约束、共享文件与系统配置…") |
| 406 | 删除: boundary, boundaryErr := s.guestObservation(ctx, boundaryProbeInput(port, report.ID, private.Name(), shared.Name(), challenge)) | |
| 436 | 新增: boundaryInput := boundaryProbeInput(port, report.ID, private.Name(), shared.Name(), challenge) | |
| 437 | 新增: if containerenv.Configured(s.profile) { | |
| 438 | 新增: boundaryInput["management_host"] = containerenv.GatewayIP | |
| 439 | 新增: } | |
| 440 | 新增: boundary, boundaryErr := s.guestObservation(ctx, boundaryInput) | |
| 407 | 441 | after, err := client.Status(ctx) |
| 408 | 442 | if err != nil { |
| 409 | 443 | return err |
| @@ -422,7 +456,7 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 422 | 456 | set("filesystem_boundary", cage.CheckFailed, "共享读写、私有目录探针或挂载范围未符合预期", "检查共享目录;不要共享主目录或 Cage 配置目录") |
| 423 | 457 | } |
| 424 | 458 | if after.PolicyVerified && networkLayout && after.Configuration == cfg.Fingerprint() && !boundary.PublicConnected && after.Counters.TCPDenied > state.Counters.TCPDenied { |
| 425 | 删除: set("egress_policy", cage.CheckPassed, "运行中策略检查符合预期;未配置额外网卡;检查期间的公网 TCP 请求被 VM 外网络层拒绝", "") | |
| 459 | 新增: set("egress_policy", cage.CheckPassed, "运行中策略检查符合预期;未配置额外网卡;检查期间的公网 TCP 请求被 环境外网络层拒绝", "") | |
| 426 | 460 | } |
| 427 | 461 | if !boundary.ManagementConnected && after.Counters.PrivateDenied > state.Counters.PrivateDenied && s.managementRequiresSession(ctx) { |
| 428 | 462 | set("management_boundary", cage.CheckPassed, "guest 到宿主管理端口的连接被拒绝;本机接口无会话访问被拒绝", "") |
| @@ -434,7 +468,7 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 434 | 468 | set("management_boundary", result, "管理接口拒绝访问的证据不完整", "停止环境并重新启动;不要开放宿主控制端口") |
| 435 | 469 | } |
| 436 | 470 | if boundary.UDPAttempted && after.Counters.UDPDenied > state.Counters.UDPDenied && after.PolicyVerified { |
| 437 | 删除: set("udp_policy", cage.CheckPassed, "客机 UDP 探针已发起,VM 外网络层记录了拒绝;无响应本身不作为通过依据", "") | |
| 471 | 新增: set("udp_policy", cage.CheckPassed, "客机 UDP 探针已发起,环境外网络层记录了拒绝;无响应本身不作为通过依据", "") | |
| 438 | 472 | } |
| 439 | 473 | if !boundary.IPv6Connected && after.PolicyVerified && (boundary.IPv6DefaultRoutes == 0 || after.Counters.IPv6Denied > state.Counters.IPv6Denied) { |
| 440 | 474 | set("ipv6_policy", cage.CheckPassed, "客机公网 IPv6 策略为拒绝;连接采样未建立,路由或拒绝记录与策略一致。当前版本验证 IPv4 出口", "") |
| @@ -447,9 +481,9 @@ func (s *Server) runSafetyCheck() (returned error) { | ||
| 447 | 481 | return err |
| 448 | 482 | } |
| 449 | 483 | if networkErr == nil && network.Egress.Status == 200 && network.Egress.IP != "" && normalState.Counters.ProbeTCP > after.Counters.ProbeTCP { |
| 450 | 删除: set("proxy_transport", cage.CheckPassed, "终端请求经过 VM 网络层的固定检测通道,并由指定代理完成 HTTPS 出口查询;未放开任意网站", "") | |
| 484 | 新增: set("proxy_transport", cage.CheckPassed, "终端请求经过 环境网络层的固定检测通道,并由指定代理完成 HTTPS 出口查询;未放开任意网站", "") | |
| 451 | 485 | } else { |
| 452 | 删除: set("proxy_transport", cage.CheckUnknown, "终端未能完成固定检测请求,或缺少 VM 外通道记录", "检查指定代理和环境组件,然后重新检测") | |
| 486 | 新增: set("proxy_transport", cage.CheckUnknown, "终端未能完成固定检测请求,或缺少 环境外通道记录", "检查指定代理和环境组件,然后重新检测") | |
| 453 | 487 | } |
| 454 | 488 | if networkErr == nil && boundaryErr == nil && !boundary.PublicDNSAnswered && after.Counters.DNSDenied > state.Counters.DNSDenied && network.DNS.Status == 200 && normalState.Counters.ProbeDNS > after.Counters.ProbeDNS { |
| 455 | 489 | set("dns_transport", cage.CheckPassed, "检查期间公共解析被拒绝;固定 DNS 查询经指定 DoH 与代理完成", "") |
| @@ -657,7 +691,7 @@ func (s *Server) finishSafetyObservation(ctx context.Context, client *cage.GateC | ||
| 657 | 691 | s.mu.Lock() |
| 658 | 692 | s.safety.Error = issue |
| 659 | 693 | s.safety.ExitIP = ip |
| 660 | 删除: s.networkError = issue | |
| 694 | 新增: s.safety.monitorError = issue | |
| 661 | 695 | s.mu.Unlock() |
| 662 | 696 | return |
| 663 | 697 | } |
| @@ -677,7 +711,7 @@ func (s *Server) finishSafetyObservation(ctx context.Context, client *cage.GateC | ||
| 677 | 711 | s.mu.Lock() |
| 678 | 712 | s.safety.VerifiedAt = time.Now() |
| 679 | 713 | s.safety.Error = "" |
| 714 | 新增: s.safety.monitorError = "" | |
| 680 | 715 | s.safety.ExitIP = ip |
| 681 | 删除: s.networkError = "" | |
| 682 | 716 | s.mu.Unlock() |
| 683 | 717 | } |
| @@ -53,7 +53,7 @@ if args["stage"] in ("boundary", "environment"): | ||
| 53 | 53 | |
| 54 | 54 | if args["stage"] == "boundary": |
| 55 | 55 | result["public_connected"] = connected(("1.1.1.1", 443)) |
| 56 | 删除: result["management_connected"] = connected(("192.168.5.2", args["control_port"])) | |
| 56 | 新增: result["management_connected"] = connected((args["management_host"], args["control_port"])) | |
| 57 | 57 | result["ipv6_connected"] = connected(("2606:4700:4700::1111", 443), socket.AF_INET6) |
| 58 | 58 | try: |
| 59 | 59 | routes = subprocess.run(["ip", "-j", "-6", "route", "show", "default"], capture_output=True, text=True, timeout=3, check=True) |
| @@ -12,7 +12,6 @@ import ( | ||
| 12 | 12 | "github.com/sylvinus/agent-vm/internal/cage" |
| 13 | 13 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 14 | 14 | "github.com/sylvinus/agent-vm/internal/host" |
| 15 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 16 | 15 | "io" |
| 17 | 16 | "io/fs" |
| 18 | 17 | "log" |
| @@ -20,10 +19,12 @@ import ( | ||
| 20 | 19 | "net/http" |
| 21 | 20 | "net/url" |
| 22 | 21 | "os" |
| 22 | 新增: "os/signal" | |
| 23 | 23 | "path/filepath" |
| 24 | 24 | "runtime/debug" |
| 25 | 25 | "strings" |
| 26 | 26 | "sync" |
| 27 | 新增: "syscall" | |
| 27 | 28 | "time" |
| 28 | 29 | ) |
| 29 | 30 | |
| @@ -39,6 +40,11 @@ type controlFile struct { | ||
| 39 | 40 | Controller ControllerIdentity `json:"controller"` |
| 40 | 41 | } |
| 41 | 42 | type Server struct { |
| 43 | 新增: instanceID string | |
| 44 | 新增: clientOnly bool | |
| 45 | 新增: desktopEntry bool | |
| 46 | 新增: windowOwners map[int]bool | |
| 47 | 新增: remote *remoteGateway | |
| 42 | 48 | account *localAccount |
| 43 | 49 | identity ControllerIdentity |
| 44 | 50 | guestManifest *cage.GuestManifest |
| @@ -94,7 +100,17 @@ func randomToken() string { | ||
| 94 | 100 | func equalSecret(a, b string) bool { |
| 95 | 101 | return len(a) > 0 && subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 |
| 96 | 102 | } |
| 97 | 删除:func Serve(configPath string) (returned error) { | |
| 103 | 新增:func Serve(configPath string) error { return serve(configPath, false, "") } | |
| 104 | 新增: | |
| 105 | 新增:func ServeClient(configPath string) error { return serve(configPath, true, "") } | |
| 106 | 新增: | |
| 107 | 新增:// ServeDesktop is the desktop window's connection gateway. Its control lock and | |
| 108 | 新增:// logs live separately from the workload it may later attach to. | |
| 109 | 新增:func ServeDesktop(fullConfigPath string) error { | |
| 110 | 新增: return serve(desktopConfigPath(fullConfigPath), false, fullConfigPath) | |
| 111 | 新增:} | |
| 112 | 新增: | |
| 113 | 新增:func serve(configPath string, clientOnly bool, fullConfigPath string) (returned error) { | |
| 98 | 114 | store := diagnostics.New(filepath.Dir(configPath)) |
| 99 | 115 | diagnostics.SetDefault(store) |
| 100 | 116 | if err := store.Clean(); err != nil { |
| @@ -115,6 +131,9 @@ func Serve(configPath string) (returned error) { | ||
| 115 | 131 | if err = lockController(lock); err != nil { |
| 116 | 132 | return errors.New("此配置已有工作台服务正在运行") |
| 117 | 133 | } |
| 134 | 新增: if err := host.ProtectFile(lock.Name()); err != nil { | |
| 135 | 新增: return err | |
| 136 | 新增: } | |
| 118 | 137 | if err := store.ImportLegacy(filepath.Dir(configPath)); err != nil { |
| 119 | 138 | diagnostics.Log("warn", "diagnostics", "legacy log import failed: "+err.Error()) |
| 120 | 139 | } |
| @@ -134,59 +153,97 @@ func Serve(configPath string) (returned error) { | ||
| 134 | 153 | return err |
| 135 | 154 | } |
| 136 | 155 | defer listener.Close() |
| 137 | 删除: s := &Server{profile: profile, configPath: configPath, exe: exe, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: defaultKeyboard()}} | |
| 138 | 删除: s.account, err = loadLocalAccount(profile) | |
| 139 | 删除: if err != nil { | |
| 140 | 删除: return err | |
| 156 | 新增: s := &Server{profile: profile, configPath: configPath, exe: exe, clientOnly: clientOnly, origin: fmt.Sprintf("http://localhost:%d", port), token: randomToken(), session: randomToken(), preferences: Preferences{Keyboard: defaultKeyboard()}} | |
| 157 | 新增: s.desktopEntry = fullConfigPath != "" | |
| 158 | 新增: workload := !s.desktopEntry && !clientOnly | |
| 159 | 新增: if s.desktopEntry { | |
| 160 | 新增: if err = importDesktopConnections(filepath.Dir(fullConfigPath), profile); err != nil { | |
| 161 | 新增: return err | |
| 162 | 新增: } | |
| 163 | 新增: s.remote = newDesktopGateway(profile, NewDesktopLocalController(fullConfigPath, exe)) | |
| 164 | 新增: } else { | |
| 165 | 新增: s.remote = newRemoteGateway(profile) | |
| 166 | 新增: s.remote.clientOnly = clientOnly | |
| 167 | 新增: } | |
| 168 | 新增: defer s.remote.close() | |
| 169 | 新增: if workload { | |
| 170 | 新增: s.instanceID, err = ensureRemoteInstance(profile) | |
| 171 | 新增: if err != nil { | |
| 172 | 新增: return err | |
| 173 | 新增: } | |
| 174 | 新增: s.account, err = loadLocalAccount(profile) | |
| 175 | 新增: if err != nil { | |
| 176 | 新增: return err | |
| 177 | 新增: } | |
| 178 | 新增: defer s.account.lock() | |
| 179 | 新增: defer func() { returned = errors.Join(returned, s.closeService()) }() | |
| 180 | 新增: if b, e := os.ReadFile(filepath.Join(profile, "workbench.json")); e == nil { | |
| 181 | 新增: _ = json.Unmarshal(b, &s.preferences) | |
| 182 | 新增: } | |
| 183 | 新增: if err = s.prepareEnvironment(); err != nil { | |
| 184 | 新增: return err | |
| 185 | 新增: } | |
| 186 | 新增: if intentErr := s.restoreNetworkIntent(); intentErr != nil { | |
| 187 | 新增: s.networkError = intentErr.Error() | |
| 188 | 新增: } | |
| 189 | 新增: if s.preferences.Keyboard == "" { | |
| 190 | 新增: s.preferences.Keyboard = defaultKeyboard() | |
| 191 | 新增: } | |
| 192 | 新增: if _, e := os.Stat(configPath); os.IsNotExist(e) { | |
| 193 | 新增: if err = writePrivate(configPath, defaultConfig()); err != nil { | |
| 194 | 新增: return err | |
| 195 | 新增: } | |
| 196 | 新增: } | |
| 197 | 新增: // A previously running VM cannot keep an unmanaged endpoint online. | |
| 198 | 新增: if cfg, e := loadConfig(configPath); e != nil || cfg.RequireManagedProxy(profile) != nil { | |
| 199 | 新增: _ = s.closeProxyGate("尚未配置有效节点,外网保持关闭") | |
| 200 | 新增: } | |
| 201 | 新增: if s.networkPaused { | |
| 202 | 新增: _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网") | |
| 203 | 新增: } | |
| 204 | 新增: s.startMonitors() | |
| 141 | 205 | } |
| 142 | 删除: defer s.account.lock() | |
| 143 | 删除: defer func() { returned = errors.Join(returned, s.closeService()) }() | |
| 144 | 206 | s.identity, err = currentController() |
| 145 | 207 | if err != nil { |
| 146 | 208 | return err |
| 147 | 209 | } |
| 148 | 删除: if b, e := os.ReadFile(filepath.Join(profile, "workbench.json")); e == nil { | |
| 149 | 删除: _ = json.Unmarshal(b, &s.preferences) | |
| 150 | 删除: } | |
| 151 | 删除: if err = s.prepareEnvironment(); err != nil { | |
| 152 | 删除: return err | |
| 153 | 删除: } | |
| 154 | 删除: if intentErr := s.restoreNetworkIntent(); intentErr != nil { | |
| 155 | 删除: s.networkError = intentErr.Error() | |
| 156 | 删除: } | |
| 157 | 删除: if s.preferences.Keyboard == "" { | |
| 158 | 删除: s.preferences.Keyboard = defaultKeyboard() | |
| 159 | 删除: } | |
| 160 | 删除: if _, e := os.Stat(configPath); os.IsNotExist(e) { | |
| 161 | 删除: if e = writePrivate(configPath, defaultConfig()); e != nil { | |
| 162 | 删除: return e | |
| 163 | 删除: } | |
| 164 | 删除: } | |
| 165 | 210 | if err = writePrivate(filepath.Join(profile, "control.json"), controlFile{Port: port, Token: s.token, PID: os.Getpid(), Controller: s.identity}); err != nil { |
| 166 | 211 | return err |
| 167 | 212 | } |
| 168 | 213 | s.controlPublished = true |
| 169 | 删除: // A previously running VM cannot keep an unmanaged endpoint online. | |
| 170 | 删除: if cfg, e := loadConfig(configPath); e != nil || cfg.RequireManagedProxy(profile) != nil { | |
| 171 | 删除: _ = s.closeProxyGate("尚未配置有效节点,外网保持关闭") | |
| 214 | 新增: if !workload { | |
| 215 | 新增: defer os.Remove(filepath.Join(profile, "control.json")) | |
| 172 | 216 | } |
| 173 | 删除: if s.networkPaused { | |
| 174 | 删除: _ = s.closeProxyGate("网络保持暂停,请手动恢复后再联网") | |
| 175 | 删除: } | |
| 176 | 删除: s.startMonitors() | |
| 177 | 217 | serverErrors := store.Stream("http", "error") |
| 178 | 218 | defer serverErrors.Close() |
| 179 | 219 | server := &http.Server{ErrorLog: log.New(serverErrors, "", 0), Handler: s.handler(), ReadHeaderTimeout: 5 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 << 10} |
| 180 | 220 | defer server.Close() |
| 181 | 221 | shutdownDone := make(chan struct{}) |
| 222 | 新增: var shutdownOnce sync.Once | |
| 182 | 223 | s.shutdown = func() { |
| 183 | 删除: defer close(shutdownDone) | |
| 184 | 删除: s.beginClose() | |
| 185 | 删除: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 186 | 删除: defer cancel() | |
| 187 | 删除: _ = server.Shutdown(ctx) | |
| 188 | 删除: _ = server.Close() | |
| 189 | 删除: } | |
| 224 | 新增: shutdownOnce.Do(func() { | |
| 225 | 新增: defer close(shutdownDone) | |
| 226 | 新增: s.beginClose() | |
| 227 | 新增: ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) | |
| 228 | 新增: defer cancel() | |
| 229 | 新增: _ = server.Shutdown(ctx) | |
| 230 | 新增: _ = server.Close() | |
| 231 | 新增: }) | |
| 232 | 新增: } | |
| 233 | 新增: signals, stopSignals := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) | |
| 234 | 新增: defer stopSignals() | |
| 235 | 新增: serveDone := make(chan struct{}) | |
| 236 | 新增: defer close(serveDone) | |
| 237 | 新增: if s.desktopEntry { | |
| 238 | 新增: go s.watchDesktopOwners(serveDone) | |
| 239 | 新增: } | |
| 240 | 新增: go func() { | |
| 241 | 新增: select { | |
| 242 | 新增: case <-signals.Done(): | |
| 243 | 新增: s.shutdown() | |
| 244 | 新增: case <-serveDone: | |
| 245 | 新增: } | |
| 246 | 新增: }() | |
| 190 | 247 | err = server.Serve(listener) |
| 191 | 248 | if errors.Is(err, http.ErrServerClosed) { |
| 192 | 249 | <-shutdownDone |
| @@ -201,9 +258,17 @@ func (s *Server) handler() http.Handler { | ||
| 201 | 258 | if !s.launcherAuthenticated(w, r) { |
| 202 | 259 | return |
| 203 | 260 | } |
| 204 | 删除: jsonReply(w, launchResponse{URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity}) | |
| 261 | 新增: jsonReply(w, launchResponse{DesktopGateway: s.desktopEntry, URL: s.origin + "/?launch=" + randomToken()[:8] + "#" + s.issueTicket(), Controller: s.identity}) | |
| 205 | 262 | }) |
| 206 | 删除: mux.HandleFunc("POST /api/handoff", s.handoff) | |
| 263 | 新增: if s.desktopEntry || s.clientOnly { | |
| 264 | 新增: mux.HandleFunc("POST /api/handoff", s.handoffEntry) | |
| 265 | 新增: } else { | |
| 266 | 新增: mux.HandleFunc("POST /api/handoff", s.handoff) | |
| 267 | 新增: mux.HandleFunc("POST /api/desktop-local/{action}", s.desktopLocalControl) | |
| 268 | 新增: } | |
| 269 | 新增: if s.desktopEntry { | |
| 270 | 新增: mux.HandleFunc("POST /api/desktop-owner", s.registerDesktopOwner) | |
| 271 | 新增: } | |
| 207 | 272 | mux.HandleFunc("POST /api/session", func(w http.ResponseWriter, r *http.Request) { |
| 208 | 273 | var v struct { |
| 209 | 274 | Token string `json:"token"` |
| @@ -219,6 +284,8 @@ func (s *Server) handler() http.Handler { | ||
| 219 | 284 | jsonReply(w, map[string]bool{"ok": true}) |
| 220 | 285 | }) |
| 221 | 286 | mux.HandleFunc("GET /api/status", s.status) |
| 287 | 新增: mux.HandleFunc("GET /api/remote/manifest", s.remoteManifest) | |
| 288 | 新增: mux.HandleFunc("GET /api/projects/directories", s.projectDirectories) | |
| 222 | 289 | mux.HandleFunc("POST /api/input", s.remoteInput) |
| 223 | 290 | mux.HandleFunc("GET /api/diagnostics", s.diagnosticStatus) |
| 224 | 291 | mux.HandleFunc("POST /api/diagnostics/events", s.diagnosticEvent) |
| @@ -233,6 +300,8 @@ func (s *Server) handler() http.Handler { | ||
| 233 | 300 | mux.HandleFunc("GET /api/settings", s.getSettings) |
| 234 | 301 | mux.HandleFunc("POST /api/projects/open", s.openProject) |
| 235 | 302 | mux.HandleFunc("GET /api/environment/versions", s.environmentVersions) |
| 303 | 新增: mux.HandleFunc("GET /api/environment/storage", s.environmentStorage) | |
| 304 | 新增: mux.HandleFunc("POST /api/environment/storage", s.environmentStorage) | |
| 236 | 305 | mux.HandleFunc("GET /api/environment/resources", s.resourceStatus) |
| 237 | 306 | mux.HandleFunc("POST /api/environment/resources", s.applyResources) |
| 238 | 307 | mux.HandleFunc("POST /api/environment/update", s.updateEnvironment) |
| @@ -307,6 +376,20 @@ func (s *Server) handler() http.Handler { | ||
| 307 | 376 | return |
| 308 | 377 | } |
| 309 | 378 | } |
| 379 | 新增: // Launcher-token routes are handled only by this listener, never by a | |
| 380 | 新增: // selected workload. They perform their own authentication. | |
| 381 | 新增: if strings.HasPrefix(r.URL.Path, "/api/desktop-local/") || r.URL.Path == "/api/desktop-owner" { | |
| 382 | 新增: if (strings.HasPrefix(r.URL.Path, "/api/desktop-local/") && (s.desktopEntry || s.clientOnly)) || (r.URL.Path == "/api/desktop-owner" && !s.desktopEntry) { | |
| 383 | 新增: http.NotFound(w, r) | |
| 384 | 新增: return | |
| 385 | 新增: } | |
| 386 | 新增: mux.ServeHTTP(w, r) | |
| 387 | 新增: return | |
| 388 | 新增: } | |
| 389 | 新增: if r.URL.Path == "/api/remote/manifest" && (s.desktopEntry || s.clientOnly) { | |
| 390 | 新增: http.NotFound(w, r) | |
| 391 | 新增: return | |
| 392 | 新增: } | |
| 310 | 393 | if strings.HasPrefix(r.URL.Path, "/api/") && r.URL.Path != "/api/session" && r.URL.Path != "/api/launch" && r.URL.Path != "/api/handoff" { |
| 311 | 394 | c, e := r.Cookie(s.cookieName()) |
| 312 | 395 | if e != nil || !equalSecret(c.Value, s.session) { |
| @@ -314,6 +397,9 @@ func (s *Server) handler() http.Handler { | ||
| 314 | 397 | return |
| 315 | 398 | } |
| 316 | 399 | } |
| 400 | 新增: if s.routeRemote(w, r) { | |
| 401 | 新增: return | |
| 402 | 新增: } | |
| 317 | 403 | ctx, finish, err := s.beginActivity(r.Context()) |
| 318 | 404 | if err != nil { |
| 319 | 405 | http.Error(w, "后台正在更新,请重新打开 Cage。", http.StatusServiceUnavailable) |
| @@ -322,7 +408,7 @@ func (s *Server) handler() http.Handler { | ||
| 322 | 408 | defer finish() |
| 323 | 409 | r = r.WithContext(ctx) |
| 324 | 410 | accountRoute := r.URL.Path == "/api/account" || strings.HasPrefix(r.URL.Path, "/api/account/") |
| 325 | 删除: bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" | |
| 411 | 新增: bootstrapRoute := r.URL.Path == "/api/session" || r.URL.Path == "/api/launch" || r.URL.Path == "/api/handoff" || r.URL.Path == "/api/remote/manifest" | |
| 326 | 412 | if strings.HasPrefix(r.URL.Path, "/api/") && !accountRoute && !bootstrapRoute && !strings.HasPrefix(r.URL.Path, "/api/diagnostics") && !(r.Method == "GET" && r.URL.Path == "/api/appearance") { |
| 327 | 413 | epoch, unlocked := s.account.access() |
| 328 | 414 | if !unlocked { |
| @@ -330,6 +416,7 @@ func (s *Server) handler() http.Handler { | ||
| 330 | 416 | return |
| 331 | 417 | } |
| 332 | 418 | ctx, cancel := context.WithCancel(r.Context()) |
| 419 | 新增: | |
| 333 | 420 | stop := context.AfterFunc(epoch, cancel) |
| 334 | 421 | defer func() { stop(); cancel() }() |
| 335 | 422 | r = r.WithContext(ctx) |
| @@ -387,6 +474,7 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) { | ||
| 387 | 474 | requestError(w, errors.New("无法读取项目列表,请检查项目配置")) |
| 388 | 475 | return |
| 389 | 476 | } |
| 477 | 新增: running := vmAlive(s.profile, s.environmentDir()) | |
| 390 | 478 | s.mu.Lock() |
| 391 | 479 | defer s.mu.Unlock() |
| 392 | 480 | _, e := os.Stat(filepath.Join(s.profile, "previous-profile.json")) |
| @@ -394,7 +482,7 @@ func (s *Server) status(w http.ResponseWriter, r *http.Request) { | ||
| 394 | 482 | if len(s.projectErrors) > 0 { |
| 395 | 483 | projectError = "部分项目文件夹尚未连接,环境和浏览器可继续使用。" |
| 396 | 484 | } |
| 397 | 删除: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": vmAlive(s.profile, s.environmentDir()), "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "project_error": projectError, "project_errors": s.projectErrors, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(), "location": s.location, "network_error": s.networkError, "can_restore": e == nil, "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError}) | |
| 485 | 新增: jsonReply(w, map[string]any{"projects": projects, "ready": s.ready, "vm_running": running, "workspace": s.preferences.Workspace, "environment_workspace": s.preferences.Workspace == s.environmentDir(), "environment_directory": s.environmentDir(), "local_vm_storage": s.localVMStorage(), "project_error": projectError, "project_errors": s.projectErrors, "keyboard": s.preferences.Keyboard, "auto_timezone": s.preferences.AutoTimezone, "job": s.jobs.snapshot(), "location": s.location, "network_error": s.currentNetworkErrorLocked(), "can_restore": e == nil, "safety": s.safety, "environment_update_required": s.guestUpdateRequired, "environment_update_error": s.guestUpdateError}) | |
| 398 | 486 | } |
| 399 | 487 | func (s *Server) getSettings(w http.ResponseWriter, r *http.Request) { |
| 400 | 488 | c, err := loadConfig(s.configPath) |
| @@ -489,7 +577,7 @@ func (s *Server) stop(w http.ResponseWriter, r *http.Request) { | ||
| 489 | 577 | } |
| 490 | 578 | |
| 491 | 579 | func (s *Server) requestStop(w http.ResponseWriter, logout bool) { |
| 492 | 删除: for _, name := range []string{vmname.Name(s.environmentDir()), "base-building"} { | |
| 580 | 新增: for _, name := range []string{cage.InstanceName(s.profile, s.environmentDir()), "base-building"} { | |
| 493 | 581 | if owner := cage.InstanceJobID(filepath.Join(s.profile, "state"), name); owner != "" { |
| 494 | 582 | _ = cage.RequestJobStop(s.profile, owner) |
| 495 | 583 | } |
| @@ -13,7 +13,6 @@ import ( | ||
| 13 | 13 | |
| 14 | 14 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | 15 | "github.com/sylvinus/agent-vm/internal/managedproxy" |
| 16 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 17 | 16 | ) |
| 18 | 17 | |
| 19 | 18 | func testServer(t *testing.T) *Server { |
| @@ -242,7 +241,7 @@ func TestSSHIsolationOverridesLocalClientSettings(t *testing.T) { | ||
| 242 | 241 | } |
| 243 | 242 | s := testServer(t) |
| 244 | 243 | s.preferences.Workspace = t.TempDir() |
| 245 | 删除: dir := filepath.Join(s.profile, "state", "lima", vmname.Name(s.environmentDir())) | |
| 244 | 新增: dir := filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, s.environmentDir())) | |
| 246 | 245 | if err := os.MkdirAll(dir, 0700); err != nil { |
| 247 | 246 | t.Fatal(err) |
| 248 | 247 | } |
| @@ -17,7 +17,6 @@ import ( | ||
| 17 | 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | 18 | "github.com/sylvinus/agent-vm/internal/mounts" |
| 19 | 19 | "github.com/sylvinus/agent-vm/internal/paths" |
| 20 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 21 | 20 | ) |
| 22 | 21 | |
| 23 | 22 | type Preferences struct { |
| @@ -56,7 +55,7 @@ func (s *Server) prepareEnvironment() error { | ||
| 56 | 55 | if _, err := os.Stat(filepath.Join(s.profile, "environment.json")); os.IsNotExist(err) { |
| 57 | 56 | previous := s.workspace() |
| 58 | 57 | if previous != "" { |
| 59 | 删除: if _, err := os.Stat(filepath.Join(s.profile, "state", "lima", vmname.Name(previous), "lima.yaml")); err == nil { | |
| 58 | 新增: if _, err := os.Stat(filepath.Join(s.profile, "state", "lima", cage.InstanceName(s.profile, previous), "lima.yaml")); err == nil { | |
| 60 | 59 | path = previous |
| 61 | 60 | } |
| 62 | 61 | } |
| @@ -183,7 +182,7 @@ func validateWorkspace(path, profile string) (string, error) { | ||
| 183 | 182 | if err != nil { |
| 184 | 183 | return "", errors.New("项目路径无效") |
| 185 | 184 | } |
| 186 | 删除: abs, err = filepath.EvalSymlinks(abs) | |
| 185 | 新增: abs, err = paths.Resolve(abs) | |
| 187 | 186 | if err != nil { |
| 188 | 187 | return "", errors.New("项目目录不存在或无法访问") |
| 189 | 188 | } |
| @@ -191,25 +190,29 @@ func validateWorkspace(path, profile string) (string, error) { | ||
| 191 | 190 | if err != nil || !st.IsDir() { |
| 192 | 191 | return "", errors.New("请选择一个项目文件夹") |
| 193 | 192 | } |
| 194 | 删除: realProfile, err := filepath.EvalSymlinks(profile) | |
| 195 | 删除: if err != nil { | |
| 196 | 删除: realProfile = profile | |
| 197 | 删除: } | |
| 198 | 删除: contains := func(parent, child string) bool { | |
| 199 | 删除: rel, e := filepath.Rel(parent, child) | |
| 200 | 删除: return e == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) | |
| 193 | 新增: if realHome, err := paths.Resolve(home); err == nil { | |
| 194 | 新增: home = realHome | |
| 201 | 195 | } |
| 202 | 196 | if executable, e := os.Executable(); e == nil { |
| 203 | 删除: if real, e := filepath.EvalSymlinks(executable); e == nil && contains(abs, real) { | |
| 197 | 新增: if real, e := paths.Resolve(executable); e == nil && cage.StorageContains(abs, real) { | |
| 204 | 198 | return "", errors.New("不能共享正在运行的工作台程序所在目录。请将安装版 Cage 放在项目外,并重启控制服务后选择此项目。") |
| 205 | 199 | } |
| 206 | 200 | } |
| 207 | 201 | if mounts.UnderName(filepath.ToSlash(abs), nil) { |
| 208 | 202 | return "", errors.New("请选择项目根目录,不要共享 Git 等版本控制元数据目录") |
| 209 | 203 | } |
| 210 | 删除: if contains(abs, realProfile) || contains(realProfile, abs) || abs == home || abs == "/" { | |
| 204 | 新增: if paths.Equal(abs, home) || filepath.Dir(abs) == abs { | |
| 211 | 205 | return "", errors.New("请选择具体项目,不要共享主目录、Cage 配置或包含配置的上级目录") |
| 212 | 206 | } |
| 207 | 新增: private, err := privateProjectDirectories(profile) | |
| 208 | 新增: if err != nil { | |
| 209 | 新增: return "", err | |
| 210 | 新增: } | |
| 211 | 新增: for _, dir := range private { | |
| 212 | 新增: if cage.StoragePathsOverlap(abs, dir) { | |
| 213 | 新增: return "", errors.New("Cage 配置、环境存储、迁移备份及其上级目录不能共享给虚拟机") | |
| 214 | 新增: } | |
| 215 | 新增: } | |
| 213 | 216 | return abs, nil |
| 214 | 217 | } |
| 215 | 218 | |
| @@ -0,0 +1,96 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "strconv" | |
| 5 | 新增: "strings" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:type SetupProgress struct { | |
| 9 | 新增: Phase string `json:"phase"` | |
| 10 | 新增: Label string `json:"label"` | |
| 11 | 新增: Received *int64 `json:"received,omitempty"` | |
| 12 | 新增: Total int64 `json:"total,omitempty"` | |
| 13 | 新增:} | |
| 14 | 新增: | |
| 15 | 新增:// Only fixed component names from the installer are displayed. Other output | |
| 16 | 新增:// continues through the existing redacted operation log. | |
| 17 | 新增:func parseSetupProgress(line string) *SetupProgress { | |
| 18 | 新增: line = strings.TrimSpace(line) | |
| 19 | 新增: if strings.HasPrefix(line, "CAGE_IMAGE_BYTES ") { | |
| 20 | 新增: fields := strings.Fields(line) | |
| 21 | 新增: if len(fields) != 3 { | |
| 22 | 新增: return nil | |
| 23 | 新增: } | |
| 24 | 新增: received, err := strconv.ParseInt(fields[1], 10, 64) | |
| 25 | 新增: total, te := strconv.ParseInt(fields[2], 10, 64) | |
| 26 | 新增: if err != nil || te != nil || received < 0 || total < -1 || (total > 0 && received > total) { | |
| 27 | 新增: return nil | |
| 28 | 新增: } | |
| 29 | 新增: return &SetupProgress{"image", "正在下载 Debian 13 镜像", &received, max(total, 0)} | |
| 30 | 新增: } | |
| 31 | 新增: if strings.HasPrefix(line, "CAGE_TOOL_BYTES ") { | |
| 32 | 新增: fields := strings.Fields(line) | |
| 33 | 新增: if len(fields) != 3 && len(fields) != 4 { | |
| 34 | 新增: return nil | |
| 35 | 新增: } | |
| 36 | 新增: received, err := strconv.ParseInt(fields[2], 10, 64) | |
| 37 | 新增: if err != nil || received < 0 { | |
| 38 | 新增: return nil | |
| 39 | 新增: } | |
| 40 | 新增: p := &SetupProgress{Phase: "tools", Received: &received} | |
| 41 | 新增: if len(fields) == 4 { | |
| 42 | 新增: total, err := strconv.ParseInt(fields[3], 10, 64) | |
| 43 | 新增: if err != nil || total <= 0 || received > total { | |
| 44 | 新增: return nil | |
| 45 | 新增: } | |
| 46 | 新增: p.Total = total | |
| 47 | 新增: } | |
| 48 | 新增: switch fields[1] { | |
| 49 | 新增: case "mise.tar.gz": | |
| 50 | 新增: p.Phase, p.Label = "packages", "正在下载 mise" | |
| 51 | 新增: case "code-server.deb": | |
| 52 | 新增: p.Label = "正在下载网页编辑器 code-server" | |
| 53 | 新增: case "chromium.deb": | |
| 54 | 新增: p.Phase, p.Label = "packages", "正在下载 Chromium 浏览器" | |
| 55 | 新增: case "chromium-common.deb": | |
| 56 | 新增: p.Phase, p.Label = "packages", "正在下载 Chromium 公共资源" | |
| 57 | 新增: case "claude-code-linux-x64.tgz", "claude-code-linux-arm64.tgz": | |
| 58 | 新增: p.Label = "正在下载 Claude Code" | |
| 59 | 新增: default: | |
| 60 | 新增: return nil | |
| 61 | 新增: } | |
| 62 | 新增: return p | |
| 63 | 新增: } | |
| 64 | 新增: switch line { | |
| 65 | 新增: case "CAGE_IMAGE_READY": | |
| 66 | 新增: return &SetupProgress{Phase: "image", Label: "正在启动 Linux 基础环境"} | |
| 67 | 新增: case "CAGE_IMAGE_VERIFY": | |
| 68 | 新增: return &SetupProgress{Phase: "image", Label: "正在校验 Debian 镜像"} | |
| 69 | 新增: case "Installing packages inside VM...", "Installing base packages...": | |
| 70 | 新增: return &SetupProgress{Phase: "packages", Label: "正在安装 Linux 基础软件包"} | |
| 71 | 新增: case "Installing Python 3...": | |
| 72 | 新增: return &SetupProgress{Phase: "packages", Label: "正在安装 Python"} | |
| 73 | 新增: case "Installing Chromium...": | |
| 74 | 新增: return &SetupProgress{Phase: "packages", Label: "正在安装 Chromium 浏览器"} | |
| 75 | 新增: case "Installing Node.js 24...": | |
| 76 | 新增: return &SetupProgress{Phase: "packages", Label: "正在安装 Node.js 24"} | |
| 77 | 新增: case "Installing mise...": | |
| 78 | 新增: return &SetupProgress{Phase: "packages", Label: "正在安装 mise"} | |
| 79 | 新增: case "Installing Claude Code...": | |
| 80 | 新增: return &SetupProgress{Phase: "tools", Label: "正在安装 Claude Code"} | |
| 81 | 新增: case "Installing code-server...": | |
| 82 | 新增: return &SetupProgress{Phase: "tools", Label: "正在安装网页编辑器 code-server"} | |
| 83 | 新增: } | |
| 84 | 新增: if strings.HasPrefix(line, "Running custom setup from ") { | |
| 85 | 新增: return &SetupProgress{Phase: "services", Label: "正在配置桌面服务"} | |
| 86 | 新增: } | |
| 87 | 新增: return nil | |
| 88 | 新增:} | |
| 89 | 新增: | |
| 90 | 新增:func (e *jobExecution) setSetupProgress(p *SetupProgress) { | |
| 91 | 新增: e.owner.mu.Lock() | |
| 92 | 新增: defer e.owner.mu.Unlock() | |
| 93 | 新增: if e.id != "" && e.id == e.owner.state.ID && e.owner.state.Running { | |
| 94 | 新增: e.owner.state.SetupProgress = p | |
| 95 | 新增: } | |
| 96 | 新增:} | |
| @@ -0,0 +1,46 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "sync" | |
| 5 | 新增: "testing" | |
| 6 | 新增:) | |
| 7 | 新增: | |
| 8 | 新增:// Child pipes may split a progress line across writes. A fallback mirror may | |
| 9 | 新增:// restart from zero, and an absent Content-Length must stay indeterminate. | |
| 10 | 新增:func TestSetupProgressFromChildOutput(t *testing.T) { | |
| 11 | 新增: var m jobManager | |
| 12 | 新增: var op sync.Mutex | |
| 13 | 新增: var points []*SetupProgress | |
| 14 | 新增: _, err := m.submit(&op, "start", 0, nil, nil, func() error { | |
| 15 | 新增: e := m.execution() | |
| 16 | 新增: e.setSetupProgress(&SetupProgress{Phase: "image"}) | |
| 17 | 新增: for _, part := range []string{"CAGE_IMAGE_BYTES 25", " 100\n", "CAGE_IMAGE_BYTES 0 -1\n", "CAGE_IMAGE_BYTES 123 5\n", "CAGE_IMAGE_READY\n", "Installing Claude Code...\n"} { | |
| 18 | 新增: _, _ = e.Write([]byte(part)) | |
| 19 | 新增: points = append(points, m.snapshot().SetupProgress) | |
| 20 | 新增: } | |
| 21 | 新增: return nil | |
| 22 | 新增: }) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: t.Fatal(err) | |
| 25 | 新增: } | |
| 26 | 新增: awaitJobIdle(t, &m) | |
| 27 | 新增: if len(points) != 6 || points[0].Received != nil || points[1].Received == nil || *points[1].Received != 25 || points[1].Total != 100 || points[2].Received == nil || *points[2].Received != 0 || points[2].Total != 0 || points[3] != points[2] || points[4].Received != nil || points[5].Phase != "tools" { | |
| 28 | 新增: t.Fatalf("bad setup progress sequence: %+v", points) | |
| 29 | 新增: } | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:func TestToolProgressUsesOnlyKnownPackageNames(t *testing.T) { | |
| 33 | 新增: p := parseSetupProgress("CAGE_TOOL_BYTES claude-code-linux-x64.tgz 4980736") | |
| 34 | 新增: if p == nil || p.Phase != "tools" || p.Received == nil || *p.Received != 4980736 || p.Total != 0 { | |
| 35 | 新增: t.Fatalf("expected current bytes without a guessed total, got %+v", p) | |
| 36 | 新增: } | |
| 37 | 新增: if p := parseSetupProgress("CAGE_TOOL_BYTES untrusted 12"); p != nil { | |
| 38 | 新增: t.Fatalf("unexpected package name entered UI: %+v", p) | |
| 39 | 新增: } | |
| 40 | 新增: if p := parseSetupProgress("CAGE_TOOL_BYTES chromium-common.deb 5 10"); p == nil || p.Total != 10 || *p.Received != 5 { | |
| 41 | 新增: t.Fatalf("missing Chromium progress from signed index: %+v", p) | |
| 42 | 新增: } | |
| 43 | 新增: if p := parseSetupProgress("CAGE_TOOL_BYTES chromium.deb 12 10"); p != nil { | |
| 44 | 新增: t.Fatalf("excess bytes entered UI: %+v", p) | |
| 45 | 新增: } | |
| 46 | 新增:} | |
| @@ -0,0 +1,64 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "fmt" | |
| 6 | 新增: "net/http" | |
| 7 | 新增: | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 9 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 10 | 新增:) | |
| 11 | 新增: | |
| 12 | 新增:func (s *Server) localVMStorage() bool { | |
| 13 | 新增: return !s.clientOnly && !containerenv.Configured(s.profile) | |
| 14 | 新增:} | |
| 15 | 新增: | |
| 16 | 新增:func (s *Server) environmentStorage(w http.ResponseWriter, r *http.Request) { | |
| 17 | 新增: if !s.localVMStorage() { | |
| 18 | 新增: http.Error(w, "仅本机虚拟机支持调整存储位置", http.StatusConflict) | |
| 19 | 新增: return | |
| 20 | 新增: } | |
| 21 | 新增: if r.Method == http.MethodGet { | |
| 22 | 新增: location, err := cage.GetStorageLocation(s.profile) | |
| 23 | 新增: if err != nil { | |
| 24 | 新增: requestError(w, err) | |
| 25 | 新增: return | |
| 26 | 新增: } | |
| 27 | 新增: jsonReply(w, location) | |
| 28 | 新增: return | |
| 29 | 新增: } | |
| 30 | 新增: | |
| 31 | 新增: var input struct { | |
| 32 | 新增: Directory string `json:"directory"` | |
| 33 | 新增: Previous string `json:"previous"` | |
| 34 | 新增: Migrate bool `json:"migrate"` | |
| 35 | 新增: } | |
| 36 | 新增: if !readJSON(w, r, &input) { | |
| 37 | 新增: return | |
| 38 | 新增: } | |
| 39 | 新增: s.launch(w, "storage", func() error { | |
| 40 | 新增: current, err := cage.GetStorageLocation(s.profile) | |
| 41 | 新增: if err != nil { | |
| 42 | 新增: return err | |
| 43 | 新增: } | |
| 44 | 新增: if current.Directory != input.Previous || current.HasEnvironment != input.Migrate { | |
| 45 | 新增: return errors.New("环境或存储位置已改变,请重新打开设置后再选择") | |
| 46 | 新增: } | |
| 47 | 新增: if err = cage.ValidateStorageTarget(s.profile, input.Directory); err != nil { | |
| 48 | 新增: return err | |
| 49 | 新增: } | |
| 50 | 新增: if err = s.validateStoragePlacement(input.Directory); err != nil { | |
| 51 | 新增: return err | |
| 52 | 新增: } | |
| 53 | 新增: if current.HasEnvironment { | |
| 54 | 新增: if err = s.stopEnvironment(); err != nil { | |
| 55 | 新增: return err | |
| 56 | 新增: } | |
| 57 | 新增: } | |
| 58 | 新增: s.setMessage("正在检查环境存储…") | |
| 59 | 新增: _, err = cage.MoveStorage(s.operationContext(), s.profile, input.Directory, current, func(copied, total int64) { | |
| 60 | 新增: s.setMessage(fmt.Sprintf("正在迁移环境数据 · %.1f / %.1f GiB", float64(copied)/(1<<30), float64(total)/(1<<30))) | |
| 61 | 新增: }) | |
| 62 | 新增: return err | |
| 63 | 新增: }) | |
| 64 | 新增:} | |
| @@ -0,0 +1,55 @@ | ||
| 1 | 新增:package workbench | |
| 2 | 新增: | |
| 3 | 新增:import ( | |
| 4 | 新增: "errors" | |
| 5 | 新增: "os" | |
| 6 | 新增: | |
| 7 | 新增: "github.com/sylvinus/agent-vm/internal/cage" | |
| 8 | 新增: "github.com/sylvinus/agent-vm/internal/paths" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:func (s *Server) validateStoragePlacement(directory string) error { | |
| 12 | 新增: target, err := cage.StoragePhysicalPath(directory) | |
| 13 | 新增: if err != nil { | |
| 14 | 新增: return err | |
| 15 | 新增: } | |
| 16 | 新增: projects, err := s.projectPaths() | |
| 17 | 新增: if err != nil { | |
| 18 | 新增: return err | |
| 19 | 新增: } | |
| 20 | 新增: for _, project := range projects { | |
| 21 | 新增: physical, err := cage.StoragePhysicalPath(project) | |
| 22 | 新增: if err != nil { | |
| 23 | 新增: return err | |
| 24 | 新增: } | |
| 25 | 新增: if cage.StoragePathsOverlap(physical, target) { | |
| 26 | 新增: return errors.New("环境存储目录与已共享的项目重叠,请选择项目以外的专用文件夹") | |
| 27 | 新增: } | |
| 28 | 新增: } | |
| 29 | 新增: return nil | |
| 30 | 新增:} | |
| 31 | 新增: | |
| 32 | 新增:// Resolve both sides of the sharing boundary. A profile or retained backup | |
| 33 | 新增:// can be reached through a Windows junction even if its saved path looks | |
| 34 | 新增:// unrelated to the requested project. | |
| 35 | 新增:func privateProjectDirectories(profile string) ([]string, error) { | |
| 36 | 新增: directories, err := cage.StoragePrivatePaths(profile) | |
| 37 | 新增: if err != nil { | |
| 38 | 新增: return nil, err | |
| 39 | 新增: } | |
| 40 | 新增: directories = append(directories, profile) | |
| 41 | 新增: for _, directory := range directories { | |
| 42 | 新增: physical, err := cage.StoragePhysicalPath(directory) | |
| 43 | 新增: if os.IsNotExist(err) { | |
| 44 | 新增: // A detached backup drive still reserves its recorded location. | |
| 45 | 新增: continue | |
| 46 | 新增: } | |
| 47 | 新增: if err != nil { | |
| 48 | 新增: return nil, err | |
| 49 | 新增: } | |
| 50 | 新增: if !paths.Equal(physical, directory) { | |
| 51 | 新增: directories = append(directories, physical) | |
| 52 | 新增: } | |
| 53 | 新增: } | |
| 54 | 新增: return directories, nil | |
| 55 | 新增:} | |
| @@ -11,7 +11,6 @@ import ( | ||
| 11 | 11 | "time" |
| 12 | 12 | |
| 13 | 13 | "al.essio.dev/pkg/shellescape" |
| 14 | 删除: "github.com/sylvinus/agent-vm/internal/vmname" | |
| 15 | 14 | ) |
| 16 | 15 | |
| 17 | 16 | var ( |
| @@ -233,7 +232,6 @@ func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) | ||
| 233 | 232 | return nil, err |
| 234 | 233 | } |
| 235 | 234 | } |
| 236 | 删除: name := vmname.Name(s.environmentDir()) | |
| 237 | 235 | script := terminalScript(guestPath(workspace), input.Kind, command) |
| 238 | 236 | var selection claudeSelection |
| 239 | 237 | var finished func() |
| @@ -250,6 +248,7 @@ func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) | ||
| 250 | 248 | if !validClaudeID(selection.ID) || !validClaudeGuestID(selection.GuestID) || (login && selection.GuestID == "default") { |
| 251 | 249 | return nil, errors.New("Claude 账号 ID 无效") |
| 252 | 250 | } |
| 251 | 新增: | |
| 253 | 252 | if existing, conflict := s.terminals.existingClaudeLogin(selection.ID, login); existing != nil || conflict != nil { |
| 254 | 253 | return existing, conflict |
| 255 | 254 | } |
| @@ -266,7 +265,7 @@ func (s *Server) createTerminal(input terminalRequest) (*terminalSession, error) | ||
| 266 | 265 | } |
| 267 | 266 | } |
| 268 | 267 | } |
| 269 | 删除: cmd := s.sshCommand(s.lifetimeContext(), "-tt", "lima-"+name, "--", script) | |
| 268 | 新增: cmd := s.sshCommand(s.lifetimeContext(), "-tt", s.sshTarget(), "--", script) | |
| 270 | 269 | session, err := s.terminals.startSession(cmd, workspace, input.Kind, selection, finished) |
| 271 | 270 | if err == nil && input.Kind == "claude" && selection.ID != "" { |
| 272 | 271 | s.noteClaudeSelection(selection.ID, workspace) |
| @@ -8,6 +8,8 @@ import ( | ||
| 8 | 8 | "net/http" |
| 9 | 9 | "sync" |
| 10 | 10 | "time" |
| 11 | 新增: | |
| 12 | 新增: "github.com/sylvinus/agent-vm/internal/containerenv" | |
| 11 | 13 | ) |
| 12 | 14 | |
| 13 | 15 | func (s *Server) vnc(w http.ResponseWriter, r *http.Request) { |
| @@ -18,7 +20,21 @@ func (s *Server) vnc(w http.ResponseWriter, r *http.Request) { | ||
| 18 | 20 | http.Error(w, "环境尚未就绪", 409) |
| 19 | 21 | return |
| 20 | 22 | } |
| 21 | 删除: remote, e := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(r.Context(), "tcp", "127.0.0.1:15900") | |
| 23 | 新增: address := "127.0.0.1:15900" | |
| 24 | 新增: if containerenv.Configured(s.profile) { | |
| 25 | 新增: environment, err := containerenv.Load(s.profile) | |
| 26 | 新增: if err != nil { | |
| 27 | 新增: requestError(w, err) | |
| 28 | 新增: return | |
| 29 | 新增: } | |
| 30 | 新增: state, err := environment.State(r.Context()) | |
| 31 | 新增: if err != nil || !state.Ready { | |
| 32 | 新增: http.Error(w, "容器画面连接尚未就绪", 409) | |
| 33 | 新增: return | |
| 34 | 新增: } | |
| 35 | 新增: address = state.VNCAddress | |
| 36 | 新增: } | |
| 37 | 新增: remote, e := (&net.Dialer{Timeout: 3 * time.Second}).DialContext(r.Context(), "tcp", address) | |
| 22 | 38 | if e != nil { |
| 23 | 39 | http.Error(w, "画面连接暂时不可用", 502) |
| 24 | 40 | return |
| @@ -50,6 +50,7 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors" | ||
| 50 | 50 | !define MUI_FINISHPAGE_TEXT "Cage is installed.$\r$\n$\r$\nIf virtualization is unavailable, enable Windows Hypervisor Platform in Windows Features and restart Windows. Your projects and Cage data are preserved during upgrades and uninstall." |
| 51 | 51 | !insertmacro MUI_PAGE_WELCOME |
| 52 | 52 | !insertmacro MUI_PAGE_LICENSE "${APP_DIR}/LICENSE.txt" |
| 53 | 新增:!define MUI_DIRECTORYPAGE_TEXT_TOP "$(CageDirectoryHelp)" | |
| 53 | 54 | !insertmacro MUI_PAGE_DIRECTORY |
| 54 | 55 | !insertmacro MUI_PAGE_INSTFILES |
| 55 | 56 | !insertmacro MUI_PAGE_FINISH |
| @@ -58,6 +59,9 @@ VIAddVersionKey /LANG=1033 "LegalCopyright" "Cage contributors" | ||
| 58 | 59 | !insertmacro MUI_LANGUAGE "English" |
| 59 | 60 | !insertmacro MUI_LANGUAGE "SimpChinese" |
| 60 | 61 | |
| 62 | 新增:LangString CageDirectoryHelp ${LANG_ENGLISH} "Choose where to install the Cage application. On first launch, you can choose a separate drive for the Linux image, download cache, and virtual disks before starting the environment." | |
| 63 | 新增:LangString CageDirectoryHelp ${LANG_SIMPCHINESE} "请选择 Cage 程序的安装目录。首次打开 Cage 后,可以在启动环境前单独选择存放 Linux 镜像、下载缓存和虚拟磁盘的磁盘。" | |
| 64 | 新增: | |
| 61 | 65 | Var UpdateMode |
| 62 | 66 | Var StageDir |
| 63 | 67 | Var BackupDir |
| @@ -10,9 +10,11 @@ Enable Windows Hypervisor Platform in "Turn Windows features on or off", then | ||
| 10 | 10 | restart Windows if Cage reports that the hypervisor is unavailable. |
| 11 | 11 | Windows on ARM and 32-bit Windows are not supported by this package. |
| 12 | 12 | |
| 13 | 删除:In Cage, configure your own proxy and start the environment. Initial setup | |
| 14 | 删除:downloads the Linux image and development tools. Proxy service and Claude | |
| 15 | 删除:account are not included. Changes to shared projects affect the original files. | |
| 13 | 新增:In Cage, choose an environment data folder before starting the environment if | |
| 14 | 新增:you want the Linux image, cache and virtual disks on another drive. Configure | |
| 15 | 新增:your own proxy and start the environment to download the Linux image and tools. | |
| 16 | 新增:Proxy service and Claude account are not included. Changes to shared projects | |
| 17 | 新增:affect the original files. | |
| 16 | 18 | |
| 17 | 19 | Updates preserve the Cage configuration, virtual disk and project files. |
| 18 | 20 | Stop the environment and quit Cage before running an installer manually. |
| @@ -53,6 +53,8 @@ It runs inside the Lima hostagent, which with vz also runs the VM: a panic there | ||
| 53 | 53 | | `lima/0011-windows-native-usernet-socket` | lima-vm/lima | not sent | Opens the per-instance network control endpoint with its native filesystem path. Constructing `unix://C:\\...` fails URL parsing on Windows. `TestNetstackWindowsNativeSocketPaths` connects to both control and QEMU AF_UNIX listeners on Windows. | |
| 54 | 54 | | `lima/0012-dynamic-memory` | lima-vm/lima | not sent | Adds an optional hostagent resource controller with bounded private SSH observations, VZ memory targets and deadline-bound QEMU balloon commands. Stops the controller before the VM and suppresses probe consoles on Windows. VZ borrowed device wrappers retain VM ownership instead of releasing it from a temporary Go finalizer. Protocol, cancellation and capacity checks are covered in `TestMemoryTargetQMPProtocolAndCancellation`; Cage owns the adaptive policy and live acceptance. | |
| 55 | 55 | | `lima/0013-resumable-image-downloads` | lima-vm/lima | not sent | Resumes digest-pinned cached image downloads under the existing cache lock. Validates byte ranges and the complete digest before publication; retains partial data on interruption, handles servers that ignore or reject Range, and discards corrupted data. Local HTTP tests cover retries, cancellation and cache reuse. | |
| 56 | 新增:| `lima/0018-windows-bundled-firmware-path` | lima-vm/lima | not sent | On Windows, prefer the firmware shipped with QEMU. For a non-ASCII directory, start QEMU there and pass the firmware basename to the pflash drive. | | |
| 57 | 新增:| `lima/0019-whpx-qemu64-cpu-features` | lima-vm/lima | not sent | When the Windows x64 default is `qemu64`, add the SSSE3, SSE4.1, SSE4.2 and POPCNT features that Windows Hypervisor Platform reports. Preserve explicit CPU choices. | | |
| 56 | 58 | | `sshocker/0001-rooted-server-readonly-names` | lima-vm/sshocker | fork branch `readonly-names` | The builtin server serves only the mounted directory, and `ReadonlyNames`. | |
| 57 | 59 | | `sshocker/0002-expect-remove` | lima-vm/sshocker | fork branch `expect-remove` | `ExpectRemove`, for 0002 of Lima. | |
| 58 | 60 | | `sshocker/0003-append-fix` | lima-vm/sshocker | not sent | Bug 1. Tests `TestRootedOpenAppend`, `TestRootedOpenMode`. No pkg/sftp dependency: send first. | |
| @@ -0,0 +1,41 @@ | ||
| 1 | 新增:diff --git a/pkg/downloader/downloader.go b/pkg/downloader/downloader.go | |
| 2 | 新增:index c5977d8..3dfa402 100644 | |
| 3 | 新增:--- a/pkg/downloader/downloader.go | |
| 4 | 新增:+++ b/pkg/downloader/downloader.go | |
| 5 | 新增:@@ -80,9 +80,15 @@ func (o *options) apply(opts []Opt) error { | |
| 6 | 新增: | |
| 7 | 新增: type Opt func(*options) error | |
| 8 | 新增: | |
| 9 | 新增:-// WithCache enables caching using filepath.Join(os.UserCacheDir(), "lima") as the cache dir. | |
| 10 | 新增:+// WithCache uses Cage's environment volume when configured, or the user's Lima cache. | |
| 11 | 新增: func WithCache() Opt { | |
| 12 | 新增: return func(o *options) error { | |
| 13 | 新增:+ if dir := os.Getenv("CAGE_LIMA_CACHE_DIR"); dir != "" { | |
| 14 | 新增:+ if !filepath.IsAbs(dir) { | |
| 15 | 新增:+ return fmt.Errorf("CAGE_LIMA_CACHE_DIR must be absolute") | |
| 16 | 新增:+ } | |
| 17 | 新增:+ return WithCacheDir(dir)(o) | |
| 18 | 新增:+ } | |
| 19 | 新增: ucd, err := os.UserCacheDir() | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: return err | |
| 22 | 新增:diff --git a/pkg/downloader/resume_test.go b/pkg/downloader/resume_test.go | |
| 23 | 新增:index 896242c..5a76bdd 100644 | |
| 24 | 新增:--- a/pkg/downloader/resume_test.go | |
| 25 | 新增:+++ b/pkg/downloader/resume_test.go | |
| 26 | 新增:@@ -37,10 +37,14 @@ func TestPinnedDownloadResumesInterruptedBody(t *testing.T) { | |
| 27 | 新增: })) | |
| 28 | 新增: defer s.Close() | |
| 29 | 新增: cache := t.TempDir() | |
| 30 | 新增:- r, err := Download(t.Context(), "", s.URL, WithCacheDir(cache), WithExpectedDigest(digest.FromString(data))) | |
| 31 | 新增:+ t.Setenv("CAGE_LIMA_CACHE_DIR", cache) | |
| 32 | 新增:+ r, err := Download(t.Context(), "", s.URL, WithCache(), WithExpectedDigest(digest.FromString(data))) | |
| 33 | 新增: if err != nil { | |
| 34 | 新增: t.Fatal(err) | |
| 35 | 新增: } | |
| 36 | 新增:+ if rel, err := filepath.Rel(cache, r.CachePath); err != nil || !filepath.IsLocal(rel) { | |
| 37 | 新增:+ t.Fatalf("download landed outside chosen cache: %q", r.CachePath) | |
| 38 | 新增:+ } | |
| 39 | 新增: got, err := os.ReadFile(r.CachePath) | |
| 40 | 新增: if err != nil || string(got) != data || calls.Load() != 2 { | |
| 41 | 新增: t.Fatalf("result %q, calls %d, error %v", got, calls.Load(), err) | |
| @@ -0,0 +1,16 @@ | ||
| 1 | 新增:diff --git a/pkg/limatype/dirnames/dirnames.go b/pkg/limatype/dirnames/dirnames.go | |
| 2 | 新增:index 136c766..71ec9c2 100644 | |
| 3 | 新增:--- a/pkg/limatype/dirnames/dirnames.go | |
| 4 | 新增:+++ b/pkg/limatype/dirnames/dirnames.go | |
| 5 | 新增:@@ -31,6 +31,11 @@ func LimaDir() (string, error) { | |
| 6 | 新增: } | |
| 7 | 新增: dir = filepath.Join(homeDir, DotLima) | |
| 8 | 新增: } | |
| 9 | 新增:+ // Cage keeps a stable logical path for QEMU backing files, SSH and sockets | |
| 10 | 新增:+ // when the profile's private VM storage is moved to another volume. | |
| 11 | 新增:+ if stable := os.Getenv("CAGE_LOGICAL_LIMA_HOME"); stable != "" && filepath.Clean(dir) == filepath.Clean(stable) { | |
| 12 | 新增:+ return filepath.Clean(dir), nil | |
| 13 | 新增:+ } | |
| 14 | 新增: if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) { | |
| 15 | 新增: return dir, nil | |
| 16 | 新增: } | |
| @@ -0,0 +1,73 @@ | ||
| 1 | 新增:diff --git a/pkg/downloader/resume.go b/pkg/downloader/resume.go | |
| 2 | 新增:--- a/pkg/downloader/resume.go | |
| 3 | 新增:+++ b/pkg/downloader/resume.go | |
| 4 | 新增:@@ -157,6 +157,17 @@ | |
| 5 | 新增: bar.Start() | |
| 6 | 新增: defer bar.Finish() | |
| 7 | 新增: reader := &downloadActivityReader{reader: resp.Body, timer: idle} | |
| 8 | 新增:+ // The desktop workbench consumes complete lines when stderr is a pipe. | |
| 9 | 新增:+ // Range responses count the bytes already present in the partial file. | |
| 10 | 新增:+ if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 11 | 新增:+ reader.received = offset | |
| 12 | 新增:+ reader.total = total | |
| 13 | 新增:+ reader.report = func(received, total int64) { | |
| 14 | 新增:+ fmt.Fprintf(os.Stderr, "CAGE_IMAGE_BYTES %d %d\n", received, total) | |
| 15 | 新增:+ } | |
| 16 | 新增:+ reader.report(offset, total) | |
| 17 | 新增:+ reader.lastReport = time.Now() | |
| 18 | 新增:+ } | |
| 19 | 新增: n, err := io.Copy(out, bar.NewProxyReader(reader)) | |
| 20 | 新增: if err != nil { | |
| 21 | 新增: return true, err | |
| 22 | 新增:@@ -172,6 +183,10 @@ | |
| 23 | 新增: if total >= 0 && n+offset != total { | |
| 24 | 新增: return true, io.ErrUnexpectedEOF | |
| 25 | 新增: } | |
| 26 | 新增:+ if reader.report != nil { | |
| 27 | 新增:+ reader.report(reader.received, total) | |
| 28 | 新增:+ fmt.Fprintln(os.Stderr, "CAGE_IMAGE_VERIFY") | |
| 29 | 新增:+ } | |
| 30 | 新增: if err := out.Sync(); err != nil { | |
| 31 | 新增: return false, err | |
| 32 | 新增: } | |
| 33 | 新增:@@ -186,14 +201,24 @@ | |
| 34 | 新增: } | |
| 35 | 新增: | |
| 36 | 新增: type downloadActivityReader struct { | |
| 37 | 新增:- reader io.Reader | |
| 38 | 新增:- timer *time.Timer | |
| 39 | 新增:+ reader io.Reader | |
| 40 | 新增:+ timer *time.Timer | |
| 41 | 新增:+ received, total int64 | |
| 42 | 新增:+ report func(int64, int64) | |
| 43 | 新增:+ lastReport time.Time | |
| 44 | 新增: } | |
| 45 | 新增: | |
| 46 | 新增: func (r *downloadActivityReader) Read(p []byte) (int, error) { | |
| 47 | 新增: n, err := r.reader.Read(p) | |
| 48 | 新增: if n > 0 { | |
| 49 | 新增: r.timer.Reset(time.Minute) | |
| 50 | 新增:+ if r.report != nil { | |
| 51 | 新增:+ r.received += int64(n) | |
| 52 | 新增:+ if time.Since(r.lastReport) >= time.Second { | |
| 53 | 新增:+ r.report(r.received, r.total) | |
| 54 | 新增:+ r.lastReport = time.Now() | |
| 55 | 新增:+ } | |
| 56 | 新增:+ } | |
| 57 | 新增: } | |
| 58 | 新增: return n, err | |
| 59 | 新增: } | |
| 60 | 新增:diff --git a/pkg/instance/start.go b/pkg/instance/start.go | |
| 61 | 新增:index 489df5f..10b4d2f 100644 | |
| 62 | 新增:--- a/pkg/instance/start.go | |
| 63 | 新增:+++ b/pkg/instance/start.go | |
| 64 | 新增:@@ -183,6 +183,9 @@ func Prepare(ctx context.Context, inst *limatype.Instance, guestAgent string) (* | |
| 65 | 新增: } | |
| 66 | 新增: } | |
| 67 | 新增: | |
| 68 | 新增:+ if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 69 | 新增:+ fmt.Fprintln(os.Stderr, "CAGE_IMAGE_READY") | |
| 70 | 新增:+ } | |
| 71 | 新增: if err := limaDriver.CreateDisk(ctx); err != nil { | |
| 72 | 新增: return nil, err | |
| 73 | 新增: } | |
| @@ -0,0 +1,197 @@ | ||
| 1 | 新增:Subject: [PATCH] Use last received image data for download timeouts | |
| 2 | 新增: | |
| 3 | 新增:Remove the total attempt deadline, renew the inactivity deadline only for body | |
| 4 | 新增:data, and retain partial downloads for automatic and manual continuation. | |
| 5 | 新增: | |
| 6 | 新增:--- | |
| 7 | 新增:diff --git a/pkg/downloader/resume.go b/pkg/downloader/resume.go | |
| 8 | 新增:--- a/pkg/downloader/resume.go | |
| 9 | 新增:+++ b/pkg/downloader/resume.go | |
| 10 | 新增:@@ -12,6 +12,7 @@ | |
| 11 | 新增: "os" | |
| 12 | 新增: "strconv" | |
| 13 | 新增: "strings" | |
| 14 | 新增:+ "sync" | |
| 15 | 新增: "time" | |
| 16 | 新增: | |
| 17 | 新增: "github.com/lima-vm/lima/v2/pkg/progressbar" | |
| 18 | 新增:@@ -44,10 +45,8 @@ | |
| 19 | 新增: if ctx.Err() != nil { | |
| 20 | 新增: return ctx.Err() | |
| 21 | 新增: } | |
| 22 | 新增:- attemptCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) | |
| 23 | 新增: var retry bool | |
| 24 | 新增:- retry, err = resumeHTTPOnce(attemptCtx, local, modified, contentType, remote, description, expected) | |
| 25 | 新增:- cancel() | |
| 26 | 新增:+ retry, err = resumeHTTPOnce(ctx, local, modified, contentType, remote, description, expected, time.Minute) | |
| 27 | 新增: if err == nil { | |
| 28 | 新增: return publishPartial(part, local, identity) | |
| 29 | 新增: } | |
| 30 | 新增:@@ -73,7 +72,7 @@ | |
| 31 | 新增: return os.Remove(identity) | |
| 32 | 新增: } | |
| 33 | 新增: | |
| 34 | 新增:-func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest) (bool, error) { | |
| 35 | 新增:+func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest, idleTimeout time.Duration) (bool, error) { | |
| 36 | 新增: part := local + ".part" | |
| 37 | 新增: var offset int64 | |
| 38 | 新增: if st, err := os.Stat(part); err == nil { | |
| 39 | 新增:@@ -83,10 +82,10 @@ | |
| 40 | 新增: } | |
| 41 | 新增: ctx, cancel := context.WithCancel(ctx) | |
| 42 | 新增: defer cancel() | |
| 43 | 新增:- // A slow but progressing transfer may run for 30 minutes. A stalled | |
| 44 | 新增:- // connection is interrupted after one minute so a fresh attempt can resume. | |
| 45 | 新增:- idle := time.AfterFunc(time.Minute, cancel) | |
| 46 | 新增:- defer idle.Stop() | |
| 47 | 新增:+ // Only received body bytes renew the timeout. Headers and progress messages | |
| 48 | 新增:+ // cannot keep a stalled transfer alive; a progressing transfer has no cap. | |
| 49 | 新增:+ idle := newDownloadIdleWatchdog(idleTimeout, cancel) | |
| 50 | 新增:+ defer idle.stop() | |
| 51 | 新增: req, err := http.NewRequestWithContext(ctx, http.MethodGet, remote, nil) | |
| 52 | 新增: if err != nil { | |
| 53 | 新增: return false, err | |
| 54 | 新增:@@ -156,7 +155,7 @@ | |
| 55 | 新增: logrus.Infof("Downloading %s; continuing at %d bytes", description, offset) | |
| 56 | 新增: bar.Start() | |
| 57 | 新增: defer bar.Finish() | |
| 58 | 新增:- reader := &downloadActivityReader{reader: resp.Body, timer: idle} | |
| 59 | 新增:+ reader := &downloadActivityReader{reader: resp.Body, activity: idle.touch} | |
| 60 | 新增: // The desktop workbench consumes complete lines when stderr is a pipe. | |
| 61 | 新增: // Range responses count the bytes already present in the partial file. | |
| 62 | 新增: if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 63 | 新增:@@ -169,6 +168,7 @@ | |
| 64 | 新增: reader.lastReport = time.Now() | |
| 65 | 新增: } | |
| 66 | 新增: n, err := io.Copy(out, bar.NewProxyReader(reader)) | |
| 67 | 新增:+ idle.stop() // Local syncing and checksum validation are not network waits. | |
| 68 | 新增: if err != nil { | |
| 69 | 新增: return true, err | |
| 70 | 新增: } | |
| 71 | 新增:@@ -202,7 +202,7 @@ | |
| 72 | 新增: | |
| 73 | 新增: type downloadActivityReader struct { | |
| 74 | 新增: reader io.Reader | |
| 75 | 新增:- timer *time.Timer | |
| 76 | 新增:+ activity func() | |
| 77 | 新增: received, total int64 | |
| 78 | 新增: report func(int64, int64) | |
| 79 | 新增: lastReport time.Time | |
| 80 | 新增:@@ -211,7 +211,7 @@ | |
| 81 | 新增: func (r *downloadActivityReader) Read(p []byte) (int, error) { | |
| 82 | 新增: n, err := r.reader.Read(p) | |
| 83 | 新增: if n > 0 { | |
| 84 | 新增:- r.timer.Reset(time.Minute) | |
| 85 | 新增:+ r.activity() | |
| 86 | 新增: if r.report != nil { | |
| 87 | 新增: r.received += int64(n) | |
| 88 | 新增: if time.Since(r.lastReport) >= time.Second { | |
| 89 | 新增:@@ -223,6 +223,48 @@ | |
| 90 | 新增: return n, err | |
| 91 | 新增: } | |
| 92 | 新增: | |
| 93 | 新增:+// Check the latest receive time under the same lock as touch. An expired | |
| 94 | 新增:+// callback that was already scheduled must not cancel a renewed download. | |
| 95 | 新增:+type downloadIdleWatchdog struct { | |
| 96 | 新增:+ mu sync.Mutex | |
| 97 | 新增:+ timer *time.Timer | |
| 98 | 新增:+ last time.Time | |
| 99 | 新增:+ timeout time.Duration | |
| 100 | 新增:+ cancel context.CancelFunc | |
| 101 | 新增:+ stopped bool | |
| 102 | 新增:+} | |
| 103 | 新增:+ | |
| 104 | 新增:+func newDownloadIdleWatchdog(timeout time.Duration, cancel context.CancelFunc) *downloadIdleWatchdog { | |
| 105 | 新增:+ w := &downloadIdleWatchdog{last: time.Now(), timeout: timeout, cancel: cancel} | |
| 106 | 新增:+ w.timer = time.AfterFunc(timeout, func() { | |
| 107 | 新增:+ w.mu.Lock() | |
| 108 | 新增:+ defer w.mu.Unlock() | |
| 109 | 新增:+ if w.stopped { | |
| 110 | 新增:+ return | |
| 111 | 新增:+ } | |
| 112 | 新增:+ if remaining := w.timeout - time.Since(w.last); remaining > 0 { | |
| 113 | 新增:+ w.timer.Reset(remaining) | |
| 114 | 新增:+ } else { | |
| 115 | 新增:+ w.stopped = true | |
| 116 | 新增:+ w.cancel() | |
| 117 | 新增:+ } | |
| 118 | 新增:+ }) | |
| 119 | 新增:+ return w | |
| 120 | 新增:+} | |
| 121 | 新增:+ | |
| 122 | 新增:+func (w *downloadIdleWatchdog) touch() { | |
| 123 | 新增:+ w.mu.Lock() | |
| 124 | 新增:+ defer w.mu.Unlock() | |
| 125 | 新增:+ w.last = time.Now() | |
| 126 | 新增:+} | |
| 127 | 新增:+ | |
| 128 | 新增:+func (w *downloadIdleWatchdog) stop() { | |
| 129 | 新增:+ w.mu.Lock() | |
| 130 | 新增:+ defer w.mu.Unlock() | |
| 131 | 新增:+ w.stopped = true | |
| 132 | 新增:+ w.timer.Stop() | |
| 133 | 新增:+} | |
| 134 | 新增:+ | |
| 135 | 新增: func parseDownloadRange(value string) (start, end, total int64, ok bool) { | |
| 136 | 新增: span, size, found := strings.Cut(strings.TrimPrefix(value, "bytes "), "/") | |
| 137 | 新增: first, last, dash := strings.Cut(span, "-") | |
| 138 | 新增:diff --git a/pkg/downloader/resume_test.go b/pkg/downloader/resume_test.go | |
| 139 | 新增:--- a/pkg/downloader/resume_test.go | |
| 140 | 新增:+++ b/pkg/downloader/resume_test.go | |
| 141 | 新增:@@ -182,3 +182,56 @@ | |
| 142 | 新增: t.Fatal("cancelled data published") | |
| 143 | 新增: } | |
| 144 | 新增: } | |
| 145 | 新增:+ | |
| 146 | 新增:+func TestPinnedDownloadUsesLatestBodyActivity(t *testing.T) { | |
| 147 | 新增:+ for _, mode := range []string{"slow", "stalled", "headers-only", "no-response"} { | |
| 148 | 新增:+ t.Run(mode, func(t *testing.T) { | |
| 149 | 新增:+ const data = "abcdef" | |
| 150 | 新增:+ const idle = 200 * time.Millisecond | |
| 151 | 新增:+ s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 152 | 新增:+ if mode != "no-response" { | |
| 153 | 新增:+ w.Header().Set("Content-Length", fmt.Sprint(len(data))) | |
| 154 | 新增:+ w.(http.Flusher).Flush() | |
| 155 | 新增:+ } | |
| 156 | 新增:+ if mode == "headers-only" || mode == "no-response" { | |
| 157 | 新增:+ <-r.Context().Done() | |
| 158 | 新增:+ return | |
| 159 | 新增:+ } | |
| 160 | 新增:+ for i := range len(data) { | |
| 161 | 新增:+ fmt.Fprint(w, data[i:i+1]) | |
| 162 | 新增:+ w.(http.Flusher).Flush() | |
| 163 | 新增:+ if mode == "stalled" { | |
| 164 | 新增:+ <-r.Context().Done() | |
| 165 | 新增:+ return | |
| 166 | 新增:+ } | |
| 167 | 新增:+ select { | |
| 168 | 新增:+ case <-r.Context().Done(): | |
| 169 | 新增:+ return | |
| 170 | 新增:+ case <-time.After(idle / 3): | |
| 171 | 新增:+ } | |
| 172 | 新增:+ } | |
| 173 | 新增:+ })) | |
| 174 | 新增:+ defer s.Close() | |
| 175 | 新增:+ local := filepath.Join(t.TempDir(), "data") | |
| 176 | 新增:+ start := time.Now() | |
| 177 | 新增:+ retry, err := resumeHTTPOnce(t.Context(), local, "", "", s.URL, "test", digest.FromString(data), idle) | |
| 178 | 新增:+ if mode == "slow" { | |
| 179 | 新增:+ if err != nil || retry || time.Since(start) <= idle { | |
| 180 | 新增:+ t.Fatalf("progressing transfer interrupted: retry=%v err=%v", retry, err) | |
| 181 | 新增:+ } | |
| 182 | 新增:+ got, err := os.ReadFile(local + ".part") | |
| 183 | 新增:+ if err != nil || string(got) != data { | |
| 184 | 新增:+ t.Fatalf("received %q: %v", got, err) | |
| 185 | 新增:+ } | |
| 186 | 新增:+ } else if !retry || err == nil { | |
| 187 | 新增:+ t.Fatalf("stalled transfer not retried: retry=%v err=%v", retry, err) | |
| 188 | 新增:+ } | |
| 189 | 新增:+ if mode == "stalled" { | |
| 190 | 新增:+ got, err := os.ReadFile(local + ".part") | |
| 191 | 新增:+ if err != nil || string(got) != data[:1] { | |
| 192 | 新增:+ t.Fatalf("partial data lost: %q %v", got, err) | |
| 193 | 新增:+ } | |
| 194 | 新增:+ } | |
| 195 | 新增:+ }) | |
| 196 | 新增:+ } | |
| 197 | 新增:+} | |
| @@ -0,0 +1,161 @@ | ||
| 1 | 新增:Subject: [PATCH] Open Windows pflash firmware through its Unicode working directory | |
| 2 | 新增: | |
| 3 | 新增:diff --git a/pkg/driver/qemu/firmware.go b/pkg/driver/qemu/firmware.go | |
| 4 | 新增:new file mode 100644 | |
| 5 | 新增:index 0000000..ad3dc48 | |
| 6 | 新增:--- /dev/null | |
| 7 | 新增:+++ b/pkg/driver/qemu/firmware.go | |
| 8 | 新增:@@ -0,0 +1,22 @@ | |
| 9 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 10 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 11 | 新增:+ | |
| 12 | 新增:+package qemu | |
| 13 | 新增:+ | |
| 14 | 新增:+import ( | |
| 15 | 新增:+ "path/filepath" | |
| 16 | 新增:+ "unicode/utf8" | |
| 17 | 新增:+) | |
| 18 | 新增:+ | |
| 19 | 新增:+// The Windows QEMU build cannot reliably open a non-ASCII pflash argument. | |
| 20 | 新增:+// CreateProcessW takes the working directory as UTF-16, so QEMU can open | |
| 21 | 新增:+// the original firmware with its ASCII basename without making a stale copy. | |
| 22 | 新增:+func windowsFirmwareArgument(path string) (argument, workingDir string) { | |
| 23 | 新增:+ dir := filepath.Dir(path) | |
| 24 | 新增:+ for _, r := range dir { | |
| 25 | 新增:+ if r >= utf8.RuneSelf && filepath.IsAbs(path) { | |
| 26 | 新增:+ return filepath.Base(path), dir | |
| 27 | 新增:+ } | |
| 28 | 新增:+ } | |
| 29 | 新增:+ return path, "" | |
| 30 | 新增:+} | |
| 31 | 新增:diff --git a/pkg/driver/qemu/firmware_test.go b/pkg/driver/qemu/firmware_test.go | |
| 32 | 新增:new file mode 100644 | |
| 33 | 新增:index 0000000..01da5fe | |
| 34 | 新增:--- /dev/null | |
| 35 | 新增:+++ b/pkg/driver/qemu/firmware_test.go | |
| 36 | 新增:@@ -0,0 +1,60 @@ | |
| 37 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 38 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 39 | 新增:+ | |
| 40 | 新增:+package qemu | |
| 41 | 新增:+ | |
| 42 | 新增:+import ( | |
| 43 | 新增:+ "os" | |
| 44 | 新增:+ "path/filepath" | |
| 45 | 新增:+ "runtime" | |
| 46 | 新增:+ "testing" | |
| 47 | 新增:+ | |
| 48 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 49 | 新增:+) | |
| 50 | 新增:+ | |
| 51 | 新增:+func TestWindowsFirmwareArgument(t *testing.T) { | |
| 52 | 新增:+ dir := filepath.Join(t.TempDir(), "测试安装, Cage", "share") | |
| 53 | 新增:+ if err := os.MkdirAll(dir, 0o700); err != nil { | |
| 54 | 新增:+ t.Fatal(err) | |
| 55 | 新增:+ } | |
| 56 | 新增:+ const name = "edk2-x86_64-code.fd" | |
| 57 | 新增:+ path := filepath.Join(dir, name) | |
| 58 | 新增:+ arg, cwd := windowsFirmwareArgument(path) | |
| 59 | 新增:+ if arg != name || cwd != dir { | |
| 60 | 新增:+ t.Fatalf("got argument %q and working directory %q", arg, cwd) | |
| 61 | 新增:+ } | |
| 62 | 新增:+ // Replacing the packaged firmware must also replace what QEMU reads. | |
| 63 | 新增:+ for _, revision := range []string{"first release", "updated release"} { | |
| 64 | 新增:+ if err := os.WriteFile(path, []byte(revision), 0o600); err != nil { | |
| 65 | 新增:+ t.Fatal(err) | |
| 66 | 新增:+ } | |
| 67 | 新增:+ data, err := os.ReadFile(filepath.Join(cwd, arg)) | |
| 68 | 新增:+ if err != nil || string(data) != revision { | |
| 69 | 新增:+ t.Fatalf("reading %q: got %q, %v", revision, data, err) | |
| 70 | 新增:+ } | |
| 71 | 新增:+ } | |
| 72 | 新增:+} | |
| 73 | 新增:+ | |
| 74 | 新增:+func TestWindowsPackagedFirmwareBeatsOldUserCopy(t *testing.T) { | |
| 75 | 新增:+ if runtime.GOOS != "windows" { | |
| 76 | 新增:+ t.Skip("Windows QEMU distribution layout") | |
| 77 | 新增:+ } | |
| 78 | 新增:+ root := t.TempDir() | |
| 79 | 新增:+ home := filepath.Join(root, "用户") | |
| 80 | 新增:+ t.Setenv("USERPROFILE", home) | |
| 81 | 新增:+ binDir := filepath.Join(root, "安装目录", "qemu") | |
| 82 | 新增:+ const name = "edk2-x86_64-code.fd" | |
| 83 | 新增:+ bundled := filepath.Join(binDir, "share", name) | |
| 84 | 新增:+ for _, path := range []string{filepath.Join(home, ".local", "share", "qemu", name), bundled} { | |
| 85 | 新增:+ if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { | |
| 86 | 新增:+ t.Fatal(err) | |
| 87 | 新增:+ } | |
| 88 | 新增:+ if err := os.WriteFile(path, []byte(path), 0o600); err != nil { | |
| 89 | 新增:+ t.Fatal(err) | |
| 90 | 新增:+ } | |
| 91 | 新增:+ } | |
| 92 | 新增:+ got, err := getFirmware(filepath.Join(binDir, "qemu-system-x86_64.exe"), limatype.X8664) | |
| 93 | 新增:+ if err != nil || got != bundled { | |
| 94 | 新增:+ t.Fatalf("selected %q instead of the packaged %q: %v", got, bundled, err) | |
| 95 | 新增:+ } | |
| 96 | 新增:+} | |
| 97 | 新增:diff --git a/pkg/driver/qemu/qemu.go b/pkg/driver/qemu/qemu.go | |
| 98 | 新增:index 2dba8c5..7fd33ab 100644 | |
| 99 | 新增:--- a/pkg/driver/qemu/qemu.go | |
| 100 | 新增:+++ b/pkg/driver/qemu/qemu.go | |
| 101 | 新增:@@ -480,6 +480,10 @@ func resolveCPUType(y *limatype.LimaYAML, qemuVersion *semver.Version) string { | |
| 102 | 新增: } | |
| 103 | 新增: | |
| 104 | 新增: func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err error) { | |
| 105 | 新增:+ return cmdline(ctx, cfg, nil) | |
| 106 | 新增:+} | |
| 107 | 新增:+ | |
| 108 | 新增:+func cmdline(ctx context.Context, cfg Config, workingDir *string) (exe string, args []string, err error) { | |
| 109 | 新增: y := cfg.LimaYAML | |
| 110 | 新增: exe, args, err = Exe(*y.Arch) | |
| 111 | 新增: if err != nil { | |
| 112 | 新增:@@ -647,7 +651,11 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er | |
| 113 | 新增: logrus.Infof("Using system firmware (%#q)", firmware) | |
| 114 | 新增: } | |
| 115 | 新增: if firmware != "" { | |
| 116 | 新增:- args = append(args, "-drive", fmt.Sprintf("if=pflash,format=raw,readonly=on,file=%s", firmware)) | |
| 117 | 新增:+ if runtime.GOOS == "windows" && workingDir != nil { | |
| 118 | 新增:+ firmware, *workingDir = windowsFirmwareArgument(firmware) | |
| 119 | 新增:+ } | |
| 120 | 新增:+ // Commas in -drive filenames are escaped by doubling them. | |
| 121 | 新增:+ args = append(args, "-drive", "if=pflash,format=raw,readonly=on,file="+strings.ReplaceAll(firmware, ",", ",,")) | |
| 122 | 新增: } | |
| 123 | 新增: } | |
| 124 | 新增: | |
| 125 | 新增:@@ -1315,6 +1323,14 @@ func getFirmware(qemuExe string, arch limatype.Arch) (string, error) { | |
| 126 | 新增: | |
| 127 | 新增: relativePath := fmt.Sprintf("share/qemu/edk2-%s-code.fd", qemuEdk2Arch(arch)) | |
| 128 | 新增: relativePathWin := fmt.Sprintf("share/edk2-%s-code.fd", qemuEdk2Arch(arch)) | |
| 129 | 新增:+ if runtime.GOOS == "windows" { | |
| 130 | 新增:+ // The firmware shipped beside QEMU belongs to that QEMU version. | |
| 131 | 新增:+ // Prefer it over an old manual copy in the user's .local directory. | |
| 132 | 新增:+ bundled := filepath.Join(binDir, relativePathWin) | |
| 133 | 新增:+ if _, err := os.Stat(bundled); err == nil || !errors.Is(err, os.ErrNotExist) { | |
| 134 | 新增:+ return bundled, err | |
| 135 | 新增:+ } | |
| 136 | 新增:+ } | |
| 137 | 新增: candidates := []string{ | |
| 138 | 新增: filepath.Join(userLocalDir, relativePath), // XDG-like | |
| 139 | 新增: filepath.Join(localDir, relativePath), // macOS (homebrew) | |
| 140 | 新增:diff --git a/pkg/driver/qemu/qemu_driver.go b/pkg/driver/qemu/qemu_driver.go | |
| 141 | 新增:index dba8221..6c982cc 100644 | |
| 142 | 新增:--- a/pkg/driver/qemu/qemu_driver.go | |
| 143 | 新增:+++ b/pkg/driver/qemu/qemu_driver.go | |
| 144 | 新增:@@ -422,7 +422,8 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { | |
| 145 | 新增: socks.dgramConn.Close() | |
| 146 | 新增: } | |
| 147 | 新增: }() | |
| 148 | 新增:- qExe, qArgs, err := Cmdline(ctx, qCfg) | |
| 149 | 新增:+ var workingDir string | |
| 150 | 新增:+ qExe, qArgs, err := cmdline(ctx, qCfg, &workingDir) | |
| 151 | 新增: if err != nil { | |
| 152 | 新增: return nil, err | |
| 153 | 新增: } | |
| 154 | 新增:@@ -468,6 +469,7 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { | |
| 155 | 新增: qArgsFinal = append(qArgsFinal, applied) | |
| 156 | 新增: } | |
| 157 | 新增: qCmd := exec.CommandContext(ctx, qExe, qArgsFinal...) | |
| 158 | 新增:+ qCmd.Dir = workingDir | |
| 159 | 新增: qCmd.ExtraFiles = append(qCmd.ExtraFiles, applier.files...) | |
| 160 | 新增: qCmd.SysProcAttr = executil.BackgroundSysProcAttr | |
| 161 | 新增: qStdout, err := qCmd.StdoutPipe() | |
| @@ -0,0 +1,151 @@ | ||
| 1 | 新增:Subject: [PATCH] Expose WHPX-supported SSE features in the Windows qemu64 fallback | |
| 2 | 新增: | |
| 3 | 新增:Keep the explicit CPU model and newer QEMU host passthrough. On Windows | |
| 4 | 新增:x64, use WHvGetCapability to select additional qemu64 features. | |
| 5 | 新增: | |
| 6 | 新增:diff --git a/pkg/driver/qemu/cpu_other.go b/pkg/driver/qemu/cpu_other.go | |
| 7 | 新增:new file mode 100644 | |
| 8 | 新增:index 0000000..99a48c3 | |
| 9 | 新增:--- /dev/null | |
| 10 | 新增:+++ b/pkg/driver/qemu/cpu_other.go | |
| 11 | 新增:@@ -0,0 +1,9 @@ | |
| 12 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 13 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 14 | 新增:+ | |
| 15 | 新增:+//go:build !windows || !amd64 | |
| 16 | 新增:+ | |
| 17 | 新增:+package qemu | |
| 18 | 新增:+ | |
| 19 | 新增:+// Only the Windows amd64 driver defaults to qemu64. | |
| 20 | 新增:+func whpxQEMU64() string { return "qemu64" } | |
| 21 | 新增:diff --git a/pkg/driver/qemu/cpu_windows_amd64.go b/pkg/driver/qemu/cpu_windows_amd64.go | |
| 22 | 新增:new file mode 100644 | |
| 23 | 新增:index 0000000..77bdb8c | |
| 24 | 新增:--- /dev/null | |
| 25 | 新增:+++ b/pkg/driver/qemu/cpu_windows_amd64.go | |
| 26 | 新增:@@ -0,0 +1,50 @@ | |
| 27 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 28 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 29 | 新增:+ | |
| 30 | 新增:+package qemu | |
| 31 | 新增:+ | |
| 32 | 新增:+import ( | |
| 33 | 新增:+ "unsafe" | |
| 34 | 新增:+ | |
| 35 | 新增:+ "github.com/sirupsen/logrus" | |
| 36 | 新增:+ "golang.org/x/sys/windows" | |
| 37 | 新增:+) | |
| 38 | 新增:+ | |
| 39 | 新增:+func whpxQEMU64() string { | |
| 40 | 新增:+ // Query the processor features available to Windows Hypervisor Platform | |
| 41 | 新增:+ // guests. A nested hypervisor may expose a subset of the host's CPUID. | |
| 42 | 新增:+ query := windows.NewLazySystemDLL("WinHvPlatform.dll").NewProc("WHvGetCapability") | |
| 43 | 新增:+ if err := query.Find(); err != nil { | |
| 44 | 新增:+ logrus.WithError(err).Warn("Cannot query WHPX processor features; using qemu64 defaults") | |
| 45 | 新增:+ return "qemu64" | |
| 46 | 新增:+ } | |
| 47 | 新增:+ const processorFeatures = 0x1001 // WHvCapabilityCodeProcessorFeatures | |
| 48 | 新增:+ var bits uint64 | |
| 49 | 新增:+ var written uint32 | |
| 50 | 新增:+ status, _, _ := query.Call(processorFeatures, uintptr(unsafe.Pointer(&bits)), | |
| 51 | 新增:+ unsafe.Sizeof(bits), uintptr(unsafe.Pointer(&written))) | |
| 52 | 新增:+ if int32(status) < 0 || uintptr(written) != unsafe.Sizeof(bits) { | |
| 53 | 新增:+ logrus.Warnf("Cannot query WHPX processor features (HRESULT %#x, %d bytes); using qemu64 defaults", uint32(status), written) | |
| 54 | 新增:+ return "qemu64" | |
| 55 | 新增:+ } | |
| 56 | 新增:+ return whpxQEMU64Model(bits) | |
| 57 | 新增:+} | |
| 58 | 新增:+ | |
| 59 | 新增:+// Bit positions are from the Windows SDK's WHV_X64_PROCESSOR_FEATURES. | |
| 60 | 新增:+func whpxQEMU64Model(bits uint64) string { | |
| 61 | 新增:+ model := "qemu64" | |
| 62 | 新增:+ for _, feature := range []struct { | |
| 63 | 新增:+ mask uint64 | |
| 64 | 新增:+ flag string | |
| 65 | 新增:+ }{ | |
| 66 | 新增:+ {1 << 2, "+ssse3"}, | |
| 67 | 新增:+ {1 << 3, "+sse4.1"}, | |
| 68 | 新增:+ {1 << 4, "+sse4.2"}, | |
| 69 | 新增:+ {1 << 7, "+popcnt"}, | |
| 70 | 新增:+ } { | |
| 71 | 新增:+ if bits&feature.mask != 0 { | |
| 72 | 新增:+ model += "," + feature.flag | |
| 73 | 新增:+ } | |
| 74 | 新增:+ } | |
| 75 | 新增:+ return model | |
| 76 | 新增:+} | |
| 77 | 新增:diff --git a/pkg/driver/qemu/cpu_windows_amd64_test.go b/pkg/driver/qemu/cpu_windows_amd64_test.go | |
| 78 | 新增:new file mode 100644 | |
| 79 | 新增:index 0000000..d4e0f08 | |
| 80 | 新增:--- /dev/null | |
| 81 | 新增:+++ b/pkg/driver/qemu/cpu_windows_amd64_test.go | |
| 82 | 新增:@@ -0,0 +1,44 @@ | |
| 83 | 新增:+// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 84 | 新增:+// SPDX-License-Identifier: Apache-2.0 | |
| 85 | 新增:+ | |
| 86 | 新增:+package qemu | |
| 87 | 新增:+ | |
| 88 | 新增:+import ( | |
| 89 | 新增:+ "testing" | |
| 90 | 新增:+ | |
| 91 | 新增:+ "github.com/coreos/go-semver/semver" | |
| 92 | 新增:+ | |
| 93 | 新增:+ "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 94 | 新增:+) | |
| 95 | 新增:+ | |
| 96 | 新增:+func TestWHPXQEMU64Features(t *testing.T) { | |
| 97 | 新增:+ for bits, want := range map[uint64]string{ | |
| 98 | 新增:+ 0: "qemu64", | |
| 99 | 新增:+ 0x60: "qemu64", // AMD SSE4a and XOP do not imply SSE4.2. | |
| 100 | 新增:+ 0x0c: "qemu64,+ssse3,+sse4.1", | |
| 101 | 新增:+ 0x9c: "qemu64,+ssse3,+sse4.1,+sse4.2,+popcnt", | |
| 102 | 新增:+ } { | |
| 103 | 新增:+ if got := whpxQEMU64Model(bits); got != want { | |
| 104 | 新增:+ t.Errorf("WHPX feature mask %#x: got %q, want %q", bits, got, want) | |
| 105 | 新增:+ } | |
| 106 | 新增:+ } | |
| 107 | 新增:+} | |
| 108 | 新增:+ | |
| 109 | 新增:+func TestWindowsCPUResolution(t *testing.T) { | |
| 110 | 新增:+ arch := limatype.X8664 | |
| 111 | 新增:+ y := limatype.LimaYAML{Arch: &arch} | |
| 112 | 新增:+ // New and existing instances with no explicit CPU override both resolve | |
| 113 | 新增:+ // against the current host each time their QEMU command is generated. | |
| 114 | 新增:+ if got, want := resolveCPUType(&y, semver.New("11.1.0")), whpxQEMU64(); got != want { | |
| 115 | 新增:+ t.Fatalf("default for QEMU 11.1.0: got %q, want %q", got, want) | |
| 116 | 新增:+ } | |
| 117 | 新增:+ if got := resolveCPUType(&y, semver.New("11.1.1")); got != "host" { | |
| 118 | 新增:+ t.Fatalf("default for QEMU 11.1.1: got %q", got) | |
| 119 | 新增:+ } | |
| 120 | 新增:+ for _, override := range []string{"qemu64", "qemu64,+sse4.2", "Nehalem"} { | |
| 121 | 新增:+ y.VMOpts = limatype.VMOpts{limatype.QEMU: limatype.QEMUOpts{CPUType: limatype.CPUType{arch: override}}} | |
| 122 | 新增:+ if got := resolveCPUType(&y, semver.New("11.1.0")); got != override { | |
| 123 | 新增:+ t.Fatalf("explicit CPU type %q changed to %q", override, got) | |
| 124 | 新增:+ } | |
| 125 | 新增:+ } | |
| 126 | 新增:+} | |
| 127 | 新增:diff --git a/pkg/driver/qemu/qemu.go b/pkg/driver/qemu/qemu.go | |
| 128 | 新增:index 2dba8c5..e70322a 100644 | |
| 129 | 新增:--- a/pkg/driver/qemu/qemu.go | |
| 130 | 新增:+++ b/pkg/driver/qemu/qemu.go | |
| 131 | 新增:@@ -458,6 +458,11 @@ func resolveCPUType(y *limatype.LimaYAML, qemuVersion *semver.Version) string { | |
| 132 | 新增: if err := limayaml.Convert(y.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil { | |
| 133 | 新增: logrus.WithError(err).Warnf("Couldn't convert %#q", y.VMOpts[limatype.QEMU]) | |
| 134 | 新增: } | |
| 135 | 新增:+ // WHPX uses qemu64 when host passthrough is unavailable. Preserve an | |
| 136 | 新增:+ // explicit CPU model, including an explicitly requested bare qemu64. | |
| 137 | 新增:+ if cpuType[*y.Arch] == "qemu64" && qemuOpts.CPUType[*y.Arch] == "" { | |
| 138 | 新增:+ cpuType[*y.Arch] = whpxQEMU64() | |
| 139 | 新增:+ } | |
| 140 | 新增: for k, v := range qemuOpts.CPUType { | |
| 141 | 新增: if !slices.Contains(limatype.ArchTypes, *y.Arch) { | |
| 142 | 新增: logrus.Warnf("field `vmOpts.qemu.cpuType` uses unsupported arch %#q", k) | |
| 143 | 新增:@@ -1407,7 +1412,7 @@ func hasHostCPU(qemuVersion *semver.Version) bool { | |
| 144 | 新增: return true | |
| 145 | 新增: case "windows": | |
| 146 | 新增: // Should have been 11.1.0, but it contained a regression when running in nested virt | |
| 147 | 新增:- if qemuVersion.LessThan(*semver.New("11.1.1")) { | |
| 148 | 新增:+ if qemuVersion == nil || qemuVersion.LessThan(*semver.New("11.1.1")) { | |
| 149 | 新增: return false | |
| 150 | 新增: } | |
| 151 | 新增: return true | |
| @@ -0,0 +1,97 @@ | ||
| 1 | 新增:// Headed Chromium check; on Linux, run on an isolated DISPLAY. Browser data and | |
| 2 | 新增:// the controller listener use a temporary directory, never the user's profile. | |
| 3 | 新增:// CAGE_TEST_BROWSER_PATH can select a local Chromium on macOS or Windows. | |
| 4 | 新增:import assert from "node:assert/strict"; | |
| 5 | 新增:import { spawn } from "node:child_process"; | |
| 6 | 新增:import { once } from "node:events"; | |
| 7 | 新增:import { randomBytes } from "node:crypto"; | |
| 8 | 新增:import { cp, mkdtemp, readFile, readdir, realpath, rm, writeFile } from "node:fs/promises"; | |
| 9 | 新增:import { tmpdir } from "node:os"; | |
| 10 | 新增:import { join } from "node:path"; | |
| 11 | 新增:import { setTimeout as delay } from "node:timers/promises"; | |
| 12 | 新增: | |
| 13 | 新增:if (process.platform === "linux") assert.ok(process.env.DISPLAY, "Provide an isolated X display"); | |
| 14 | 新增:const executable = process.env.CAGE_TEST_BROWSER_PATH || "/usr/bin/chromium"; | |
| 15 | 新增:const directory = await realpath(await mkdtemp(join(tmpdir(), "cage-devtools-smoke-"))); | |
| 16 | 新增:const token = randomBytes(32).toString("hex"); | |
| 17 | 新增:let agent, control, stderr = ""; | |
| 18 | 新增:async function waitFor(fn, label) { | |
| 19 | 新增: const deadline = Date.now() + 20000; | |
| 20 | 新增: while (Date.now() < deadline) { | |
| 21 | 新增: if (agent && agent.exitCode !== null) throw new Error("Controller exited: " + stderr); | |
| 22 | 新增: const result = await fn(); | |
| 23 | 新增: if (result) return result; | |
| 24 | 新增: await delay(100); | |
| 25 | 新增: } | |
| 26 | 新增: throw new Error("Timed out: " + label + ". " + stderr); | |
| 27 | 新增:} | |
| 28 | 新增:async function api(path, input) { | |
| 29 | 新增: const response = await fetch(control + path, { | |
| 30 | 新增: method: input === undefined ? "GET" : "POST", | |
| 31 | 新增: headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" }, | |
| 32 | 新增: ...(input === undefined ? {} : { body: JSON.stringify(input) }), | |
| 33 | 新增: }); | |
| 34 | 新增: const result = await response.json(); | |
| 35 | 新增: assert.equal(response.status, 200, JSON.stringify(result)); | |
| 36 | 新增: return result; | |
| 37 | 新增:} | |
| 38 | 新增:const cdp = (method, params = {}, sessionId) => api("/__devtools-test", { method, params, sessionId }); | |
| 39 | 新增:try { | |
| 40 | 新增: const sourceDirectory = new URL("../internal/cage/", import.meta.url); | |
| 41 | 新增: for (const name of await readdir(sourceDirectory)) | |
| 42 | 新增: if ((name.startsWith("browser-") && name.endsWith(".mjs")) || name === "native-input.mjs") | |
| 43 | 新增: await cp(new URL(name, sourceDirectory), join(directory, name)); | |
| 44 | 新增: await cp(new URL("split-extension", sourceDirectory), join(directory, "extension"), { recursive: true }); | |
| 45 | 新增: const source = await readFile(new URL("browser-agent.mjs", sourceDirectory), "utf8"); | |
| 46 | 新增: const listen = 'server.listen(18500, "127.0.0.1");'; | |
| 47 | 新增: const input = 'const input = JSON.parse(text || "{}");'; | |
| 48 | 新增: assert.ok(source.includes(listen) && source.includes(input), "Update the isolated controller adapter"); | |
| 49 | 新增: // Auto-open exercises Chromium's real DevTools availability check without | |
| 50 | 新增: // relying on OS-specific shortcut synthesis. Keep the production mode flag. | |
| 51 | 新增: const adapted = source | |
| 52 | 新增: .replaceAll("/home/cage-browser", directory) | |
| 53 | 新增: .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) | |
| 54 | 新增: .replace("/usr/local/lib/cage-split", join(directory, "extension")) | |
| 55 | 新增: .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(executable)}, [...flags, "--auto-open-devtools-for-tabs"]`) | |
| 56 | 新增: .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("PORT=" + server.address().port));') | |
| 57 | 新增: .replace(input, `${input} | |
| 58 | 新增: if (req.url === "/__devtools-test") { | |
| 59 | 新增: res.end(JSON.stringify(await cdp(input.method, input.params || {}, input.sessionId))); | |
| 60 | 新增: return; | |
| 61 | 新增: }`); | |
| 62 | 新增: await writeFile(join(directory, "browser-agent.mjs"), adapted); | |
| 63 | 新增: await writeFile(join(directory, "control.json"), JSON.stringify({ token, workspace: directory })); | |
| 64 | 新增: await writeFile(join(directory, "homepage.json"), JSON.stringify({ url: "about:blank" })); | |
| 65 | 新增: agent = spawn(process.execPath, [join(directory, "browser-agent.mjs")], { stdio: ["ignore", "pipe", "pipe"] }); | |
| 66 | 新增: let output = ""; | |
| 67 | 新增: agent.stdout.on("data", chunk => { | |
| 68 | 新增: output += chunk; | |
| 69 | 新增: const match = output.match(/PORT=(\d+)/); | |
| 70 | 新增: if (match) control = `http://127.0.0.1:${match[1]}`; | |
| 71 | 新增: }); | |
| 72 | 新增: agent.stderr.on("data", chunk => { stderr = (stderr + chunk).slice(-4000); }); | |
| 73 | 新增: await waitFor(() => control, "control listener"); | |
| 74 | 新增: await waitFor(async () => (await fetch(control + "/health", { headers: { Authorization: `Bearer ${token}` } })).ok, "browser ready"); | |
| 75 | 新增: const devtools = await waitFor(async () => (await cdp("Target.getTargets")).targetInfos.find(t => t.url.startsWith("devtools://")), "real DevTools page"); | |
| 76 | 新增: const { sessionId } = await cdp("Target.attachToTarget", { targetId: devtools.targetId, flatten: true }); | |
| 77 | 新增: await waitFor(async () => { | |
| 78 | 新增: const result = await cdp("Runtime.evaluate", { expression: "document.readyState === 'complete' && document.title.includes('DevTools')", returnByValue: true }, sessionId); | |
| 79 | 新增: return result.result.value; | |
| 80 | 新增: }, "DevTools UI loaded"); | |
| 81 | 新增: const state = await api("/tabs"); | |
| 82 | 新增: assert.equal(state.tabs.length, 1, "DevTools must not appear as a Cage tab"); | |
| 83 | 新增: assert.equal(state.tabs[0].url, "about:blank"); | |
| 84 | 新增: assert.equal(state.active, state.tabs[0].id, "DevTools must not become the active Cage tab"); | |
| 85 | 新增: await cdp("Target.closeTarget", { targetId: devtools.targetId }); | |
| 86 | 新增: assert.equal((await api("/tabs")).active, state.active); | |
| 87 | 新增: console.log("PASS: production fullscreen controller opens real DevTools, keeps its page out of Cage tabs, and preserves the active website when DevTools closes"); | |
| 88 | 新增:} finally { | |
| 89 | 新增: if (agent?.exitCode === null) { | |
| 90 | 新增: const exited = once(agent, "exit"); | |
| 91 | 新增: agent.kill("SIGTERM"); | |
| 92 | 新增: const timer = setTimeout(() => agent.kill("SIGKILL"), 5000); | |
| 93 | 新增: await exited; | |
| 94 | 新增: clearTimeout(timer); | |
| 95 | 新增: } | |
| 96 | 新增: await rm(directory, { recursive: true, force: true }); | |
| 97 | 新增:} | |
| @@ -154,7 +154,7 @@ try { | ||
| 154 | 154 | .replace("/etc/claude-cage/browser-control.json", join(directory, "control.json")) |
| 155 | 155 | .replace("/usr/local/lib/cage-split", join(directory, "extension")) |
| 156 | 156 | .replace('spawn("/usr/bin/chromium", flags', `spawn(${JSON.stringify(executable)}, flags`) |
| 157 | 删除: .replace('"--kiosk",', '"--headless=new",') | |
| 157 | 新增: .replace('"--start-fullscreen",', '"--headless=new",') | |
| 158 | 158 | .replace(listen, 'server.listen(0, "127.0.0.1", () => console.log("CONTROL_PORT=" + server.address().port));') |
| 159 | 159 | .replace(input, testRoute); |
| 160 | 160 | await writeFile(join(directory, "browser-agent.mjs"), isolated); |
| @@ -40,6 +40,7 @@ mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" | ||
| 40 | 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" |
| 41 | 41 | 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 | 42 | cp _output/bin/cage "$bundle/Contents/Resources/cage" |
| 43 | 新增:node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources" | |
| 43 | 44 | cp _output/proxy-core/mihomo "$bundle/Contents/Resources/mihomo" |
| 44 | 45 | for executable in "$bundle/Contents/MacOS/Cage" "$bundle/Contents/Resources/CageUpdateInstaller" "$bundle/Contents/Resources/cage" "$bundle/Contents/Resources/mihomo"; do |
| 45 | 46 | minimum="$(otool -l "$executable" | awk '$1 == "minos" {print $2}')" |
| @@ -0,0 +1,85 @@ | ||
| 1 | 新增:#requires -Version 7.0 | |
| 2 | 新增:[CmdletBinding()] | |
| 3 | 新增:param( | |
| 4 | 新增: [switch]$SkipUI, | |
| 5 | 新增: [switch]$IncludeWebViewRuntime, | |
| 6 | 新增: [string]$DependencyCache | |
| 7 | 新增:) | |
| 8 | 新增:. (Join-Path $PSScriptRoot 'windows-common.ps1') | |
| 9 | 新增:$repository = Split-Path $PSScriptRoot -Parent | |
| 10 | 新增:$version = Get-CageVersion $repository | |
| 11 | 新增:$go = Get-BuildCommand @('go') | |
| 12 | 新增:$dotnet = Get-BuildCommand @('dotnet') | |
| 13 | 新增:$node = Get-BuildCommand @('node') | |
| 14 | 新增:$npm = Get-BuildCommand @('npm.cmd', 'npm') | |
| 15 | 新增:$dependencies = Get-Content -LiteralPath (Join-Path $repository 'packaging/windows/dependencies.json') -Raw | ConvertFrom-Json | |
| 16 | 新增:if (-not $DependencyCache) { $DependencyCache = Join-Path $repository '_output/windows-deps' } | |
| 17 | 新增:$outputRoot = Join-Path $repository '_output/client-windows-amd64' | |
| 18 | 新增:New-Item -ItemType Directory -Path $outputRoot -Force | Out-Null | |
| 19 | 新增:$id = [guid]::NewGuid().ToString('N') | |
| 20 | 新增:$stage = Join-Path $outputRoot ('.stage-' + $id) | |
| 21 | 新增:$destination = Join-Path $outputRoot ('build-' + (Get-Date -Format 'yyyyMMdd-HHmmss') + '-' + $id.Substring(0, 8)) | |
| 22 | 新增:$savedGoOS, $savedGoArch, $savedCGO = $env:GOOS, $env:GOARCH, $env:CGO_ENABLED | |
| 23 | 新增:New-Item -ItemType Directory -Path $stage | Out-Null | |
| 24 | 新增:Push-Location $repository | |
| 25 | 新增:try { | |
| 26 | 新增: if (-not $SkipUI) { | |
| 27 | 新增: if (-not (Test-Path -LiteralPath 'ui/node_modules')) { Invoke-BuildTool $npm @('--prefix', 'ui', 'ci', '--no-audit', '--no-fund') } | |
| 28 | 新增: Invoke-BuildTool $npm @('--prefix', 'ui', 'run', 'build') | |
| 29 | 新增: } | |
| 30 | 新增: if (-not (Test-Path -LiteralPath 'internal/workbench/web/index.html')) { throw 'Build the UI before using -SkipUI.' } | |
| 31 | 新增: $env:GOOS = 'windows'; $env:GOARCH = 'amd64'; $env:CGO_ENABLED = '0' | |
| 32 | 新增: $goDependencies = & $go 'list' '-deps' './cmd/cage-client' | |
| 33 | 新增: 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.' } | |
| 34 | 新增: $result = Join-Path $stage 'result' | |
| 35 | 新增: $app = Join-Path $result 'app' | |
| 36 | 新增: $resources = Join-Path $app 'resources' | |
| 37 | 新增: New-Item -ItemType Directory -Path $resources -Force | Out-Null | |
| 38 | 新增: Invoke-BuildTool $go @('build', '-trimpath', '-ldflags', "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=$version", '-o', (Join-Path $resources 'cage.exe'), './cmd/cage-client') | |
| 39 | 新增: Invoke-BuildTool $dotnet @('publish', 'desktop/windows/Cage.Windows.csproj', '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true', | |
| 40 | 新增: '-p:EnableWindowsTargeting=true', '-p:PublishSingleFile=true', '-p:RestoreLockedMode=true', "-p:Version=$version", "-p:InformationalVersion=$version", '-o', $app) | |
| 41 | 新增: Get-ChildItem -LiteralPath $app -File | Where-Object { $_.Extension -in @('.pdb', '.xml') } | Remove-Item -Force | |
| 42 | 新增: [IO.File]::WriteAllText((Join-Path $resources 'client-only'), '') | |
| 43 | 新增: [IO.File]::WriteAllText((Join-Path $app 'Cage.client-id'), 'io.github.lee-xeo.claude-cage-client') | |
| 44 | 新增: [IO.File]::WriteAllText((Join-Path $app 'version.txt'), $version) | |
| 45 | 新增: Invoke-BuildTool $node @('scripts/bundle-cloud-kit.mjs', $resources) | |
| 46 | 新增: Invoke-BuildTool $node @('scripts/collect-app-licenses.mjs', (Join-Path $resources 'licenses')) | |
| 47 | 新增: $assets = Get-Content -LiteralPath 'desktop/windows/obj/project.assets.json' -Raw | ConvertFrom-Json | |
| 48 | 新增: $nuget = @($assets.packageFolders.PSObject.Properties.Name)[0] | |
| 49 | 新增: $runtimeVersion = $dependencies.dotnet.runtimeVersion | |
| 50 | 新增: $packs = @($assets.project.frameworks.PSObject.Properties.Value.downloadDependencies | Where-Object { $_.name -in @('Microsoft.NETCore.App.Runtime.win-x64', 'Microsoft.WindowsDesktop.App.Runtime.win-x64') }) | |
| 51 | 新增: if ($packs.Count -ne 2 -or @($packs | Where-Object { $_.version -ne "[$runtimeVersion, $runtimeVersion]" }).Count -ne 0) { throw 'Resolved .NET runtime differs from the repository pin.' } | |
| 52 | 新增: $webviewVersion = ((Get-Content -LiteralPath 'desktop/windows/packages.lock.json' -Raw | ConvertFrom-Json).dependencies.PSObject.Properties.Value | ForEach-Object { $_.PSObject.Properties } | Where-Object { $_.Name -eq 'Microsoft.Web.WebView2' } | Select-Object -First 1).Value.resolved | |
| 53 | 新增: foreach ($package in @("microsoft.netcore.app.runtime.win-x64/$runtimeVersion", "microsoft.windowsdesktop.app.runtime.win-x64/$runtimeVersion", "microsoft.web.webview2/$webviewVersion")) { | |
| 54 | 新增: $source = Join-Path $nuget $package | |
| 55 | 新增: $target = Join-Path $resources "licenses/nuget/$package" | |
| 56 | 新增: New-Item -ItemType Directory -Path $target -Force | Out-Null | |
| 57 | 新增: $notices = @(Get-ChildItem -LiteralPath $source -File | Where-Object { $_.Name -match '^(LICENSE|NOTICE|THIRD.?PARTY)' }) | |
| 58 | 新增: if ($notices.Count -eq 0) { throw "Missing runtime license: $package" } | |
| 59 | 新增: $notices | Copy-Item -Destination $target | |
| 60 | 新增: } | |
| 61 | 新增: if ($IncludeWebViewRuntime) { | |
| 62 | 新增: $runtime = Get-VerifiedDependency $dependencies.webview2 $DependencyCache | |
| 63 | 新增: New-Item -ItemType Directory -Path (Join-Path $resources 'runtime') -Force | Out-Null | |
| 64 | 新增: Copy-Item -LiteralPath $runtime -Destination (Join-Path $resources 'runtime/MicrosoftEdgeWebView2RuntimeInstallerX64.exe') | |
| 65 | 新增: } | |
| 66 | 新增: Copy-Item -LiteralPath 'LICENSE' -Destination (Join-Path $app 'LICENSE.txt') | |
| 67 | 新增: [IO.File]::WriteAllText((Join-Path $app 'README.txt'), @' | |
| 68 | 新增:Cage 轻量远程客户端(未签名开发构建) | |
| 69 | 新增: | |
| 70 | 新增:运行 Cage.exe。需要 Windows 10/11 x64 与 Microsoft Edge WebView2 Runtime。 | |
| 71 | 新增:.NET 运行时已随应用提供。没有 WebView2 时,可使用 -IncludeWebViewRuntime 构建包含已校验安装程序的包;构建不会安装该程序。 | |
| 72 | 新增:本机只提供窗口、SSH 连接、输入和文件传递;项目、浏览器、终端与网络在云端 Cage 运行。 | |
| 73 | 新增:默认连接配置目录为用户目录下的 .claude-cage/client;显式 CLAUDE_CAGE_CONFIG 配置保持有效。 | |
| 74 | 新增:此目录为独立构建产物,不会安装、替换完整 Cage 或自动下载完整 Cage 更新。 | |
| 75 | 新增:本构建未签名或发布。Windows 原生运行验收范围以项目测试报告为准。 | |
| 76 | 新增:'@) | |
| 77 | 新增: Compress-Archive -Path $app -DestinationPath (Join-Path $result 'Cage-Client-windows-amd64.zip') -CompressionLevel Optimal | |
| 78 | 新增: if (Test-Path -LiteralPath $destination) { throw 'Client output already exists; no files were replaced.' } | |
| 79 | 新增: Move-Item -LiteralPath $result -Destination $destination | |
| 80 | 新增: Write-Host "Built standalone client: $destination" | |
| 81 | 新增:} finally { | |
| 82 | 新增: Pop-Location | |
| 83 | 新增: $env:GOOS = $savedGoOS; $env:GOARCH = $savedGoArch; $env:CGO_ENABLED = $savedCGO | |
| 84 | 新增: if (Test-Path -LiteralPath $stage) { Remove-Item -LiteralPath $stage -Recurse -Force } | |
| 85 | 新增:} | |
| @@ -0,0 +1,110 @@ | ||
| 1 | 新增:#!/usr/bin/env bash | |
| 2 | 新增:set -euo pipefail | |
| 3 | 新增:cd "$(dirname "$0")/.." | |
| 4 | 新增: | |
| 5 | 新增:skip_ui=false | |
| 6 | 新增:case "${1:-}" in | |
| 7 | 新增: '') ;; | |
| 8 | 新增: --skip-ui) skip_ui=true ;; | |
| 9 | 新增: *) echo 'Usage: scripts/build-client.sh [--skip-ui]' >&2; exit 2 ;; | |
| 10 | 新增:esac | |
| 11 | 新增:case "$(uname -s)" in Darwin) platform=macos ;; Linux) platform=linux ;; *) echo 'Use build-client-windows.ps1 for Windows.' >&2; exit 1 ;; esac | |
| 12 | 新增:case "$(uname -m)" in arm64|aarch64) arch=arm64 ;; x86_64) arch=amd64 ;; *) echo 'Unsupported client build architecture.' >&2; exit 1 ;; esac | |
| 13 | 新增:version="$(tr -d '\r\n' < VERSION)" | |
| 14 | 新增:[[ "$version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[A-Za-z0-9.-]+)?$ ]] || { echo 'Invalid VERSION.' >&2; exit 1; } | |
| 15 | 新增:short_version="${version%%-*}" | |
| 16 | 新增:output_root="$PWD/_output/client-$platform-$arch" | |
| 17 | 新增:mkdir -p "$output_root" | |
| 18 | 新增:stage="$(mktemp -d "$output_root/.stage.XXXXXX")" | |
| 19 | 新增:trap 'rm -rf "$stage"' EXIT | |
| 20 | 新增:suffix="${stage##*.stage.}" | |
| 21 | 新增:destination="$output_root/build-$(date +%Y%m%d-%H%M%S)-$suffix" | |
| 22 | 新增:[[ ! -e "$destination" ]] || { echo 'Client output already exists; no files were replaced.' >&2; exit 1; } | |
| 23 | 新增: | |
| 24 | 新增:if [[ "$skip_ui" == false ]]; then | |
| 25 | 新增: [[ -d ui/node_modules ]] || npm --prefix ui ci --no-audit --no-fund | |
| 26 | 新增: npm --prefix ui run build | |
| 27 | 新增:fi | |
| 28 | 新增:[[ -f internal/workbench/web/index.html ]] || { echo 'Build the UI before using --skip-ui.' >&2; exit 1; } | |
| 29 | 新增:go list -deps ./cmd/cage-client > "$stage/dependencies.txt" | |
| 30 | 新增:if grep -Eq 'internal/limaembed|github.com/lima-vm/lima/v2|github.com/Code-Hex/vz' "$stage/dependencies.txt"; then | |
| 31 | 新增: echo 'The client unexpectedly depends on a virtual machine runtime; build stopped.' >&2; exit 1 | |
| 32 | 新增:fi | |
| 33 | 新增: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 | |
| 34 | 新增:mkdir -p "$stage/result" | |
| 35 | 新增: | |
| 36 | 新增:if [[ "$platform" == macos ]]; then | |
| 37 | 新增: bundle="$stage/result/Cage Client.app" | |
| 38 | 新增: mkdir -p "$bundle/Contents/MacOS" "$bundle/Contents/Resources" | |
| 39 | 新增: swiftc -O -target "$(uname -m)-apple-macosx14.0" -parse-as-library \ | |
| 40 | 新增: -framework Cocoa -framework WebKit -framework Security -framework LocalAuthentication \ | |
| 41 | 新增: desktop/Cage.swift desktop/NativeInput.swift desktop/Updates.swift desktop/AccountDevice.swift \ | |
| 42 | 新增: -o "$bundle/Contents/MacOS/Cage" | |
| 43 | 新增: node scripts/bundle-cloud-kit.mjs "$bundle/Contents/Resources" | |
| 44 | 新增: cp "$stage/cage" "$bundle/Contents/Resources/cage" | |
| 45 | 新增: node scripts/collect-app-licenses.mjs "$bundle/Contents/Resources/licenses" | |
| 46 | 新增: swift desktop/Icon.swift logo.png "$stage/Cage.iconset" | |
| 47 | 新增: iconutil -c icns "$stage/Cage.iconset" -o "$bundle/Contents/Resources/Cage.icns" | |
| 48 | 新增: cat > "$bundle/Contents/Info.plist" <<PLIST | |
| 49 | 新增:<?xml version="1.0" encoding="UTF-8"?> | |
| 50 | 新增:<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> | |
| 51 | 新增:<plist version="1.0"><dict> | |
| 52 | 新增:<key>CFBundleName</key><string>Cage Client</string> | |
| 53 | 新增:<key>CFBundleDisplayName</key><string>Cage Client</string> | |
| 54 | 新增:<key>CFBundleIdentifier</key><string>io.github.lee-xeo.claude-cage-client</string> | |
| 55 | 新增:<key>CFBundleVersion</key><string>1</string> | |
| 56 | 新增:<key>CFBundleShortVersionString</key><string>$short_version</string> | |
| 57 | 新增:<key>CageVersion</key><string>$version</string> | |
| 58 | 新增:<key>CageClientOnly</key><true/> | |
| 59 | 新增:<key>CFBundleExecutable</key><string>Cage</string> | |
| 60 | 新增:<key>CFBundleIconFile</key><string>Cage</string> | |
| 61 | 新增:<key>CFBundlePackageType</key><string>APPL</string> | |
| 62 | 新增:<key>LSMinimumSystemVersion</key><string>14.0</string> | |
| 63 | 新增:<key>NSHighResolutionCapable</key><true/> | |
| 64 | 新增:<key>NSAppTransportSecurity</key><dict><key>NSAllowsLocalNetworking</key><true/></dict> | |
| 65 | 新增:</dict></plist> | |
| 66 | 新增:PLIST | |
| 67 | 新增: # An ad-hoc development signature makes the local build runnable. No release | |
| 68 | 新增: # certificate, notarization, installer, or installed app is touched. | |
| 69 | 新增: codesign --force --sign - "$bundle/Contents/Resources/cage" | |
| 70 | 新增: codesign --force --sign - "$bundle/Contents/MacOS/Cage" | |
| 71 | 新增: codesign --force --sign - "$bundle" | |
| 72 | 新增: codesign --verify --deep --strict "$bundle" | |
| 73 | 新增: ditto -c -k --keepParent "$bundle" "$stage/result/Cage-Client-macos-$arch.zip" | |
| 74 | 新增:else | |
| 75 | 新增: pkg-config --atleast-version=2.40 webkit2gtk-4.1 | |
| 76 | 新增: pkg-config --exists gtk+-3.0 json-glib-1.0 | |
| 77 | 新增: app="$stage/result/app" | |
| 78 | 新增: mkdir -p "$app" | |
| 79 | 新增: cc -std=c11 -O2 -Wall -Wextra -Werror -Wno-deprecated-declarations \ | |
| 80 | 新增: "-DCAGE_VERSION=\"$version\"" -DCAGE_CLIENT_ONLY=1 desktop/linux/cage-desktop.c \ | |
| 81 | 新增: $(pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.1 json-glib-1.0) -o "$app/cage-desktop" | |
| 82 | 新增: install -m 755 "$stage/cage" "$app/cage" | |
| 83 | 新增: node scripts/bundle-cloud-kit.mjs "$app" | |
| 84 | 新增: touch "$app/client-only" | |
| 85 | 新增: node scripts/collect-app-licenses.mjs "$app/licenses" | |
| 86 | 新增: printf '%s\n' 'libwebkit2gtk-4.1-0 (>= 2.40), libgtk-3-0, libjson-glib-1.0-0, libglib2.0-bin, ca-certificates' > "$app/dependencies.txt" | |
| 87 | 新增: cp /etc/os-release "$app/BUILD-PLATFORM.txt" | |
| 88 | 新增: pkg-config --modversion gtk+-3.0 webkit2gtk-4.1 json-glib-1.0 >> "$app/BUILD-PLATFORM.txt" | |
| 89 | 新增: cat > "$app/README.txt" <<'LINUX_README' | |
| 90 | 新增:Cage 轻量远程客户端(Linux 开发构建) | |
| 91 | 新增:在兼容 BUILD-PLATFORM.txt 所列发行版的图形桌面中,以普通用户运行 cage-desktop。 | |
| 92 | 新增:系统依赖见 dependencies.txt。项目、应用与网络在云端运行;本机连接配置默认位于 ~/.claude-cage/client。 | |
| 93 | 新增:构建不安装或覆盖现有应用,不包含虚拟机、Mihomo 或 OpenSSH 程序。验收范围以项目测试报告为准。 | |
| 94 | 新增:LINUX_README | |
| 95 | 新增: "$app/cage-desktop" --self-test | |
| 96 | 新增: tar -C "$stage/result" -czf "$stage/result/Cage-Client-linux-$arch.tar.gz" app | |
| 97 | 新增:fi | |
| 98 | 新增:cp LICENSE "$stage/result/LICENSE" | |
| 99 | 新增:printf '%s\n' "$version" > "$stage/result/VERSION" | |
| 100 | 新增:cat > "$stage/result/README.txt" <<'README' | |
| 101 | 新增:Cage 轻量远程客户端(开发构建) | |
| 102 | 新增: | |
| 103 | 新增:本机只提供窗口、SSH 连接、输入和文件传递;项目、浏览器、终端与网络在云端 Cage 运行。 | |
| 104 | 新增:默认连接配置目录为 ~/.claude-cage/client;显式设置 CLAUDE_CAGE_CONFIG 时沿用指定路径。 | |
| 105 | 新增:此目录为独立构建产物,不会安装或替换已安装的 Cage。当前构建使用手动更新。 | |
| 106 | 新增:macOS 运行 Cage Client.app。Linux 安装 app/dependencies.txt 中的系统依赖后运行 app/cage-desktop。 | |
| 107 | 新增:本构建未公证或发布;原生运行验收范围以项目测试报告为准。 | |
| 108 | 新增:README | |
| 109 | 新增:mv "$stage/result" "$destination" | |
| 110 | 新增:printf 'Built standalone client: %s\n' "$destination" | |
| @@ -26,6 +26,7 @@ cc -std=c11 -O2 -Wall -Wextra -Werror -Wno-deprecated-declarations \ | ||
| 26 | 26 | $(pkg-config --cflags --libs gtk+-3.0 webkit2gtk-4.1 json-glib-1.0) \ |
| 27 | 27 | -o "$app/cage-desktop" |
| 28 | 28 | install -m 755 _output/bin/cage "$app/cage" |
| 29 | 新增:node scripts/bundle-cloud-kit.mjs "$app" | |
| 29 | 30 | install -m 755 _output/linux-deps/mihomo "$app/mihomo" |
| 30 | 31 | cp _output/linux-deps/{LICENSE,NOTICE} "$app/licenses/mihomo/" |
| 31 | 32 | if [[ "${1:-}" == --prebuilt-backend && -d _output/linux-amd64/prebuilt-licenses ]]; then |
| @@ -56,6 +56,8 @@ try { | ||
| 56 | 56 | Invoke-BuildTool $dotnet @('publish', 'desktop/windows/Cage.Windows.csproj', '-c', 'Release', '-r', 'win-x64', '--self-contained', 'true', |
| 57 | 57 | '-p:EnableWindowsTargeting=true', '-p:PublishSingleFile=true', '-p:RestoreLockedMode=true', "-p:Version=$version", "-p:InformationalVersion=$version", '-o', $app) |
| 58 | 58 | Get-ChildItem -LiteralPath $app -File | Where-Object { $_.Extension -in @('.pdb', '.xml') } | Remove-Item -Force |
| 59 | 新增: node scripts/bundle-cloud-kit.mjs $resources | |
| 60 | 新增: if ($LASTEXITCODE -ne 0) { throw "Cloud deployment kit verification failed." } | |
| 59 | 61 | $coreArchive = Get-VerifiedDependency $dependencies.mihomo $DependencyCache |
| 60 | 62 | $core = Join-Path $stage 'mihomo' |
| 61 | 63 | Expand-BuildArchive $coreArchive $core $sevenZip |
| @@ -0,0 +1,49 @@ | ||
| 1 | 新增:// Prepare the Linux server and installation recipe for SSH deployment. | |
| 2 | 新增:// An explicitly selected offline kit can also be supplied for private builds. | |
| 3 | 新增:import fs from "node:fs"; | |
| 4 | 新增:import os from "node:os"; | |
| 5 | 新增:import path from "node:path"; | |
| 6 | 新增:import { createHash } from "node:crypto"; | |
| 7 | 新增:import { execFileSync } from "node:child_process"; | |
| 8 | 新增:import { createGzip } from "node:zlib"; | |
| 9 | 新增:import { pipeline } from "node:stream/promises"; | |
| 10 | 新增: | |
| 11 | 新增:const target = path.resolve(process.argv[2], "cloud-linux-amd64.tar"); | |
| 12 | 新增:const digest = async file => { | |
| 13 | 新增: const hash = createHash("sha256"); | |
| 14 | 新增: for await (const chunk of fs.createReadStream(file)) hash.update(chunk); | |
| 15 | 新增: return hash.digest("hex"); | |
| 16 | 新增:}; | |
| 17 | 新增:const offline = process.env.CAGE_CLOUD_KIT; | |
| 18 | 新增:if (offline) { | |
| 19 | 新增: if (await digest(offline) !== fs.readFileSync(offline + ".sha256", "utf8").trim()) | |
| 20 | 新增: throw Error("Cloud deployment kit checksum mismatch"); | |
| 21 | 新增: fs.copyFileSync(offline, target); | |
| 22 | 新增:} else { | |
| 23 | 新增: const stage = fs.mkdtempSync(path.join(os.tmpdir(), "cage-bootstrap-")); | |
| 24 | 新增: try { | |
| 25 | 新增: const version = fs.readFileSync("VERSION", "utf8").trim(); | |
| 26 | 新增: const binary = path.join(stage, "cage"); | |
| 27 | 新增: execFileSync("go", ["build", "-trimpath", "-ldflags", "-s -w -X github.com/sylvinus/agent-vm/internal/version.Version=" + version, "-o", binary, "./cmd/cage"], { | |
| 28 | 新增: env: {...process.env, CGO_ENABLED:"0", GOOS:"linux", GOARCH:"amd64"}, stdio:"inherit" | |
| 29 | 新增: }); | |
| 30 | 新增: await pipeline(fs.createReadStream(binary), createGzip(), fs.createWriteStream(binary + ".gz")); | |
| 31 | 新增: fs.unlinkSync(binary); | |
| 32 | 新增: const {mihomo} = JSON.parse(fs.readFileSync("packaging/linux/dependencies.json")); | |
| 33 | 新增: const cache = path.resolve("_output/linux-deps", mihomo.file); | |
| 34 | 新增: const core = path.join(stage, "mihomo.gz"); | |
| 35 | 新增: if (fs.existsSync(cache)) fs.copyFileSync(cache, core); | |
| 36 | 新增: else execFileSync("curl", ["--fail","--location","--retry","3","--max-time","300","--output",core,mihomo.url],{stdio:"inherit"}); | |
| 37 | 新增: if (await digest(core) !== mihomo.sha256) throw Error("Linux Mihomo checksum mismatch"); | |
| 38 | 新增: const recipe = path.join(stage, "deploy/cloud"); | |
| 39 | 新增: fs.mkdirSync(recipe, {recursive:true}); | |
| 40 | 新增: for (const name of ["Dockerfile.guest","restore-apt-sources.sh","build-guest.sh"]) | |
| 41 | 新增: fs.copyFileSync(path.join("deploy/cloud",name),path.join(recipe,name)); | |
| 42 | 新增: for (const name of ["cage-server.service","cage-container-engine.service"]) | |
| 43 | 新增: fs.copyFileSync(path.join("deploy/cloud",name),path.join(stage,name)); | |
| 44 | 新增: const runtime = JSON.parse(fs.readFileSync("deploy/cloud/runtime-artifacts.json")); | |
| 45 | 新增: fs.writeFileSync(path.join(stage,"engine-downloads"),runtime.artifacts.map(a=>[a.sha256,a.file,a.url].join(" ")).join("\n")+"\n"); | |
| 46 | 新增: execFileSync("tar", ["-cf",target,"-C",stage,"."],{env:{...process.env,COPYFILE_DISABLE:"1"},stdio:"inherit"}); | |
| 47 | 新增: } finally { fs.rmSync(stage,{recursive:true,force:true}); } | |
| 48 | 新增:} | |
| 49 | 新增:fs.writeFileSync(target+".sha256",await digest(target)+"\n"); | |
| @@ -57,8 +57,14 @@ try { | ||
| 57 | 57 | & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release |
| 58 | 58 | Invoke-BuildTool 'dotnet' @('run', '--project', 'desktop/windows.tests/Cage.Windows.Tests.csproj') |
| 59 | 59 | Invoke-BuildTool 'go' @('test', './internal/workbench', './internal/appupdate', './internal/host', './internal/managedproxy', './internal/env', './internal/paths', './internal/mounts') |
| 60 | 删除: Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)') | |
| 60 | 新增: # Exercise a second volume when the runner keeps its workspace and temp on different drives. | |
| 61 | 新增: if ($env:GITHUB_WORKSPACE -and -not $env:CAGE_TEST_STORAGE_VOLUME -and | |
| 62 | 新增: [IO.Path]::GetPathRoot($env:GITHUB_WORKSPACE) -ne [IO.Path]::GetPathRoot([IO.Path]::GetTempPath())) { | |
| 63 | 新增: $env:CAGE_TEST_STORAGE_VOLUME = $env:GITHUB_WORKSPACE | |
| 64 | 新增: } | |
| 65 | 新增: Invoke-BuildTool 'go' @('test', './internal/cage', '-run', 'Test(Storage|Gate|ProxyRevision|ConfigChange|JobStop|CONNECT|SOCKS|DNS|RejectHostLAN|Credentials|ProxyHostname|SafetyReport|Renew)') | |
| 61 | 66 | Invoke-BuildTool 'go' @('test', './internal/vm', '-run', 'Test(NetworkConfined|WindowsQEMUIdentity)') |
| 67 | 新增: Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/driver/qemu', '-run', 'Test(WindowsFirmwareArgument|WindowsPackagedFirmwareBeatsOldUserCopy|WHPXQEMU64Features|WindowsCPUResolution)$') | |
| 62 | 68 | Invoke-BuildTool 'go' @('test', 'github.com/lima-vm/lima/v2/pkg/networks/usernet', '-run', 'TestNetstackWindowsNativeSocketPaths') |
| 63 | 69 | Invoke-BuildTool 'go' @('vet', './cmd/cage', './internal/cage', './internal/workbench', './internal/appupdate', './internal/host') |
| 64 | 70 | $packageArguments = @{ Release = $Release; SkipBuild = $true } |
| @@ -16,7 +16,7 @@ const call = async (binary, ...args) => { | ||
| 16 | 16 | const { stdout } = await runFile(binary, [...args, "--json"], { env, timeout: 150_000, maxBuffer: 512 * 1024 }); |
| 17 | 17 | return JSON.parse(stdout); |
| 18 | 18 | }; |
| 19 | 删除:const record = async () => JSON.parse(await readFile(path.join(profile, "control.json"), "utf8")); | |
| 19 | 新增:const record = async (entry = false) => JSON.parse(await readFile(path.join(profile, entry ? "desktop-entry" : ".", "control.json"), "utf8")); | |
| 20 | 20 | const wait = async (test) => { |
| 21 | 21 | for (let i = 0; i < 100; i++) { |
| 22 | 22 | try { if (await test()) return; } catch {} |
| @@ -27,17 +27,18 @@ const wait = async (test) => { | ||
| 27 | 27 | const old = spawn(legacy, ["serve"], { cwd: profile, env, stdio: "ignore" }); |
| 28 | 28 | try { |
| 29 | 29 | await wait(async () => (await record()).pid === old.pid); |
| 30 | 删除: assert.equal((await call(current, "desktop")).status, "upgrade_pending"); | |
| 30 | 新增: assert.equal((await call(current, "desktop")).status, "ready", "Chooser can open without taking over the older workload"); | |
| 31 | 新增: assert.equal((await record()).pid, old.pid); | |
| 31 | 32 | assert.equal((await call(current, "desktop", "--existing")).status, "existing"); |
| 32 | 33 | assert.equal((await call(current, "prepare-update")).status, "stop_required"); |
| 33 | 34 | assert.equal((await call(current, "prepare-update", "--stop")).status, "prepared"); |
| 34 | 35 | await wait(() => old.exitCode !== null || old.signalCode !== null); |
| 35 | 36 | assert.equal((await call(current, "desktop")).status, "ready"); |
| 36 | 删除: const first = await record(); | |
| 37 | 新增: const first = await record(true); | |
| 37 | 38 | assert.equal((await call(current, "desktop")).status, "ready"); |
| 38 | 删除: assert.equal((await record()).pid, first.pid, "Same build must reuse its controller"); | |
| 39 | 新增: assert.equal((await record(true)).pid, first.pid, "Same build must reuse its controller"); | |
| 39 | 40 | assert.equal((await call(next, "desktop")).status, "ready"); |
| 40 | 删除: const replacement = await record(); | |
| 41 | 新增: const replacement = await record(true); | |
| 41 | 42 | assert.notEqual(replacement.pid, first.pid, "Different build must replace an idle controller"); |
| 42 | 43 | assert.notEqual(replacement.controller.build, first.controller.build); |
| 43 | 44 | assert.equal(replacement.controller.version, first.controller.version, "Exercise same-version distinct builds"); |
| @@ -36,12 +36,13 @@ 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, qemu-system-x86, qemu-utils, ovmf, openssh-client, iproute2, ca-certificates, git | |
| 39 | 新增:Depends: $dependencies, libwebkit2gtk-4.1-0 (>= 2.40), libglib2.0-bin, ca-certificates | |
| 40 | 新增:Suggests: qemu-system-x86, qemu-utils, ovmf, openssh-client, iproute2, git | |
| 40 | 41 | Recommends: dbus-user-session, fonts-noto-cjk, libnotify-bin, zenity | kdialog |
| 41 | 42 | Homepage: https://github.com/Lee-xeo/Claude-Cage |
| 42 | 43 | Description: Isolated coding workspace with a persistent Linux VM |
| 43 | 44 | Cage combines projects, terminals, a browser and an editor in a native |
| 44 | 删除: desktop window. Hardware virtualization and a user-supplied proxy are required. | |
| 45 | 新增: desktop window. Select a local virtual machine or connect to a Cage server over SSH. | |
| 45 | 46 | EOF |
| 46 | 47 | deb="$output/Cage-$version-linux-amd64.deb" |
| 47 | 48 | dpkg-deb --root-owner-group --build "$stage" "$deb" |
| @@ -10,7 +10,7 @@ test_home=$(getent passwd "$test_user" | cut -d: -f6) | ||
| 10 | 10 | report_dir="$test_home/reports" |
| 11 | 11 | profile="$test_home/upgrade-guard/config.json" |
| 12 | 12 | cleanup() { |
| 13 | 删除: if [[ -x /usr/bin/claude-cage && -f "${profile%/*}/control.json" ]]; then | |
| 13 | 新增: if [[ -x /usr/bin/claude-cage && ( -f "${profile%/*}/control.json" || -f "${profile%/*}/desktop-entry/control.json" ) ]]; then | |
| 14 | 14 | runuser -u "$test_user" -- env CLAUDE_CAGE_CONFIG="$profile" /usr/bin/claude-cage prepare-update --json >/dev/null || true |
| 15 | 15 | fi |
| 16 | 16 | } |
| @@ -44,7 +44,7 @@ try { | ||
| 44 | 44 | const adapted=original.replaceAll("/home/cage-browser",dir).replace("/etc/claude-cage/browser-control.json",join(dir,"control.json")) |
| 45 | 45 | .replace("/usr/local/lib/cage-split",join(dir,"extension")) |
| 46 | 46 | .replace('spawn("/usr/bin/chromium", flags',`spawn(${JSON.stringify(process.env.CAGE_TEST_BROWSER_PATH)}, flags`) |
| 47 | 删除: .replace('"--kiosk",','"--headless=new", "--ignore-certificate-errors", "--disable-background-networking",') | |
| 47 | 新增: .replace('"--start-fullscreen",','"--headless=new", "--ignore-certificate-errors", "--disable-background-networking",') | |
| 48 | 48 | .replace('server.listen(18500, "127.0.0.1");','server.listen(0,"127.0.0.1",()=>console.log("PORT="+server.address().port));') |
| 49 | 49 | .replace(marker,`${marker}\nif (req.url === "/__vault-test") { res.end(JSON.stringify(await cdp(input.method,input.params||{},await session(input.id)))); return; }`); |
| 50 | 50 | assert.notEqual(adapted, original); |
| @@ -80,9 +80,15 @@ func (o *options) apply(opts []Opt) error { | ||
| 80 | 80 | |
| 81 | 81 | type Opt func(*options) error |
| 82 | 82 | |
| 83 | 删除:// WithCache enables caching using filepath.Join(os.UserCacheDir(), "lima") as the cache dir. | |
| 83 | 新增:// WithCache uses Cage's environment volume when configured, or the user's Lima cache. | |
| 84 | 84 | func WithCache() Opt { |
| 85 | 85 | return func(o *options) error { |
| 86 | 新增: if dir := os.Getenv("CAGE_LIMA_CACHE_DIR"); dir != "" { | |
| 87 | 新增: if !filepath.IsAbs(dir) { | |
| 88 | 新增: return fmt.Errorf("CAGE_LIMA_CACHE_DIR must be absolute") | |
| 89 | 新增: } | |
| 90 | 新增: return WithCacheDir(dir)(o) | |
| 91 | 新增: } | |
| 86 | 92 | ucd, err := os.UserCacheDir() |
| 87 | 93 | if err != nil { |
| 88 | 94 | return err |
| @@ -12,6 +12,7 @@ import ( | ||
| 12 | 12 | "os" |
| 13 | 13 | "strconv" |
| 14 | 14 | "strings" |
| 15 | 新增: "sync" | |
| 15 | 16 | "time" |
| 16 | 17 | |
| 17 | 18 | "github.com/lima-vm/lima/v2/pkg/progressbar" |
| @@ -44,10 +45,8 @@ func downloadHTTPResumable(ctx context.Context, local, modified, contentType, re | ||
| 44 | 45 | if ctx.Err() != nil { |
| 45 | 46 | return ctx.Err() |
| 46 | 47 | } |
| 47 | 删除: attemptCtx, cancel := context.WithTimeout(ctx, 30*time.Minute) | |
| 48 | 48 | var retry bool |
| 49 | 删除: retry, err = resumeHTTPOnce(attemptCtx, local, modified, contentType, remote, description, expected) | |
| 50 | 删除: cancel() | |
| 49 | 新增: retry, err = resumeHTTPOnce(ctx, local, modified, contentType, remote, description, expected, time.Minute) | |
| 51 | 50 | if err == nil { |
| 52 | 51 | return publishPartial(part, local, identity) |
| 53 | 52 | } |
| @@ -73,7 +72,7 @@ func publishPartial(part, local, identity string) error { | ||
| 73 | 72 | return os.Remove(identity) |
| 74 | 73 | } |
| 75 | 74 | |
| 76 | 删除:func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest) (bool, error) { | |
| 75 | 新增:func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, description string, expected digest.Digest, idleTimeout time.Duration) (bool, error) { | |
| 77 | 76 | part := local + ".part" |
| 78 | 77 | var offset int64 |
| 79 | 78 | if st, err := os.Stat(part); err == nil { |
| @@ -83,10 +82,10 @@ func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, d | ||
| 83 | 82 | } |
| 84 | 83 | ctx, cancel := context.WithCancel(ctx) |
| 85 | 84 | defer cancel() |
| 86 | 删除: // A slow but progressing transfer may run for 30 minutes. A stalled | |
| 87 | 删除: // connection is interrupted after one minute so a fresh attempt can resume. | |
| 88 | 删除: idle := time.AfterFunc(time.Minute, cancel) | |
| 89 | 删除: defer idle.Stop() | |
| 85 | 新增: // Only received body bytes renew the timeout. Headers and progress messages | |
| 86 | 新增: // cannot keep a stalled transfer alive; a progressing transfer has no cap. | |
| 87 | 新增: idle := newDownloadIdleWatchdog(idleTimeout, cancel) | |
| 88 | 新增: defer idle.stop() | |
| 90 | 89 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, remote, nil) |
| 91 | 90 | if err != nil { |
| 92 | 91 | return false, err |
| @@ -156,8 +155,20 @@ func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, d | ||
| 156 | 155 | logrus.Infof("Downloading %s; continuing at %d bytes", description, offset) |
| 157 | 156 | bar.Start() |
| 158 | 157 | defer bar.Finish() |
| 159 | 删除: reader := &downloadActivityReader{reader: resp.Body, timer: idle} | |
| 158 | 新增: reader := &downloadActivityReader{reader: resp.Body, activity: idle.touch} | |
| 159 | 新增: // The desktop workbench consumes complete lines when stderr is a pipe. | |
| 160 | 新增: // Range responses count the bytes already present in the partial file. | |
| 161 | 新增: if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 162 | 新增: reader.received = offset | |
| 163 | 新增: reader.total = total | |
| 164 | 新增: reader.report = func(received, total int64) { | |
| 165 | 新增: fmt.Fprintf(os.Stderr, "CAGE_IMAGE_BYTES %d %d\n", received, total) | |
| 166 | 新增: } | |
| 167 | 新增: reader.report(offset, total) | |
| 168 | 新增: reader.lastReport = time.Now() | |
| 169 | 新增: } | |
| 160 | 170 | n, err := io.Copy(out, bar.NewProxyReader(reader)) |
| 171 | 新增: idle.stop() // Local syncing and checksum validation are not network waits. | |
| 161 | 172 | if err != nil { |
| 162 | 173 | return true, err |
| 163 | 174 | } |
| @@ -172,6 +183,10 @@ func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, d | ||
| 172 | 183 | if total >= 0 && n+offset != total { |
| 173 | 184 | return true, io.ErrUnexpectedEOF |
| 174 | 185 | } |
| 186 | 新增: if reader.report != nil { | |
| 187 | 新增: reader.report(reader.received, total) | |
| 188 | 新增: fmt.Fprintln(os.Stderr, "CAGE_IMAGE_VERIFY") | |
| 189 | 新增: } | |
| 175 | 190 | if err := out.Sync(); err != nil { |
| 176 | 191 | return false, err |
| 177 | 192 | } |
| @@ -186,18 +201,70 @@ func resumeHTTPOnce(ctx context.Context, local, modified, contentType, remote, d | ||
| 186 | 201 | } |
| 187 | 202 | |
| 188 | 203 | type downloadActivityReader struct { |
| 189 | 删除: reader io.Reader | |
| 190 | 删除: timer *time.Timer | |
| 204 | 新增: reader io.Reader | |
| 205 | 新增: activity func() | |
| 206 | 新增: received, total int64 | |
| 207 | 新增: report func(int64, int64) | |
| 208 | 新增: lastReport time.Time | |
| 191 | 209 | } |
| 192 | 210 | |
| 193 | 211 | func (r *downloadActivityReader) Read(p []byte) (int, error) { |
| 194 | 212 | n, err := r.reader.Read(p) |
| 195 | 213 | if n > 0 { |
| 196 | 删除: r.timer.Reset(time.Minute) | |
| 214 | 新增: r.activity() | |
| 215 | 新增: if r.report != nil { | |
| 216 | 新增: r.received += int64(n) | |
| 217 | 新增: if time.Since(r.lastReport) >= time.Second { | |
| 218 | 新增: r.report(r.received, r.total) | |
| 219 | 新增: r.lastReport = time.Now() | |
| 220 | 新增: } | |
| 221 | 新增: } | |
| 197 | 222 | } |
| 198 | 223 | return n, err |
| 199 | 224 | } |
| 200 | 225 | |
| 226 | 新增:// Check the latest receive time under the same lock as touch. An expired | |
| 227 | 新增:// callback that was already scheduled must not cancel a renewed download. | |
| 228 | 新增:type downloadIdleWatchdog struct { | |
| 229 | 新增: mu sync.Mutex | |
| 230 | 新增: timer *time.Timer | |
| 231 | 新增: last time.Time | |
| 232 | 新增: timeout time.Duration | |
| 233 | 新增: cancel context.CancelFunc | |
| 234 | 新增: stopped bool | |
| 235 | 新增:} | |
| 236 | 新增: | |
| 237 | 新增:func newDownloadIdleWatchdog(timeout time.Duration, cancel context.CancelFunc) *downloadIdleWatchdog { | |
| 238 | 新增: w := &downloadIdleWatchdog{last: time.Now(), timeout: timeout, cancel: cancel} | |
| 239 | 新增: w.timer = time.AfterFunc(timeout, func() { | |
| 240 | 新增: w.mu.Lock() | |
| 241 | 新增: defer w.mu.Unlock() | |
| 242 | 新增: if w.stopped { | |
| 243 | 新增: return | |
| 244 | 新增: } | |
| 245 | 新增: if remaining := w.timeout - time.Since(w.last); remaining > 0 { | |
| 246 | 新增: w.timer.Reset(remaining) | |
| 247 | 新增: } else { | |
| 248 | 新增: w.stopped = true | |
| 249 | 新增: w.cancel() | |
| 250 | 新增: } | |
| 251 | 新增: }) | |
| 252 | 新增: return w | |
| 253 | 新增:} | |
| 254 | 新增: | |
| 255 | 新增:func (w *downloadIdleWatchdog) touch() { | |
| 256 | 新增: w.mu.Lock() | |
| 257 | 新增: defer w.mu.Unlock() | |
| 258 | 新增: w.last = time.Now() | |
| 259 | 新增:} | |
| 260 | 新增: | |
| 261 | 新增:func (w *downloadIdleWatchdog) stop() { | |
| 262 | 新增: w.mu.Lock() | |
| 263 | 新增: defer w.mu.Unlock() | |
| 264 | 新增: w.stopped = true | |
| 265 | 新增: w.timer.Stop() | |
| 266 | 新增:} | |
| 267 | 新增: | |
| 201 | 268 | func parseDownloadRange(value string) (start, end, total int64, ok bool) { |
| 202 | 269 | span, size, found := strings.Cut(strings.TrimPrefix(value, "bytes "), "/") |
| 203 | 270 | first, last, dash := strings.Cut(span, "-") |
| @@ -37,10 +37,14 @@ func TestPinnedDownloadResumesInterruptedBody(t *testing.T) { | ||
| 37 | 37 | })) |
| 38 | 38 | defer s.Close() |
| 39 | 39 | cache := t.TempDir() |
| 40 | 删除: r, err := Download(t.Context(), "", s.URL, WithCacheDir(cache), WithExpectedDigest(digest.FromString(data))) | |
| 40 | 新增: t.Setenv("CAGE_LIMA_CACHE_DIR", cache) | |
| 41 | 新增: r, err := Download(t.Context(), "", s.URL, WithCache(), WithExpectedDigest(digest.FromString(data))) | |
| 41 | 42 | if err != nil { |
| 42 | 43 | t.Fatal(err) |
| 43 | 44 | } |
| 45 | 新增: if rel, err := filepath.Rel(cache, r.CachePath); err != nil || !filepath.IsLocal(rel) { | |
| 46 | 新增: t.Fatalf("download landed outside chosen cache: %q", r.CachePath) | |
| 47 | 新增: } | |
| 44 | 48 | got, err := os.ReadFile(r.CachePath) |
| 45 | 49 | if err != nil || string(got) != data || calls.Load() != 2 { |
| 46 | 50 | t.Fatalf("result %q, calls %d, error %v", got, calls.Load(), err) |
| @@ -178,3 +182,56 @@ func TestPinnedDownloadCancellationRetainsPartial(t *testing.T) { | ||
| 178 | 182 | t.Fatal("cancelled data published") |
| 179 | 183 | } |
| 180 | 184 | } |
| 185 | 新增: | |
| 186 | 新增:func TestPinnedDownloadUsesLatestBodyActivity(t *testing.T) { | |
| 187 | 新增: for _, mode := range []string{"slow", "stalled", "headers-only", "no-response"} { | |
| 188 | 新增: t.Run(mode, func(t *testing.T) { | |
| 189 | 新增: const data = "abcdef" | |
| 190 | 新增: const idle = 200 * time.Millisecond | |
| 191 | 新增: s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | |
| 192 | 新增: if mode != "no-response" { | |
| 193 | 新增: w.Header().Set("Content-Length", fmt.Sprint(len(data))) | |
| 194 | 新增: w.(http.Flusher).Flush() | |
| 195 | 新增: } | |
| 196 | 新增: if mode == "headers-only" || mode == "no-response" { | |
| 197 | 新增: <-r.Context().Done() | |
| 198 | 新增: return | |
| 199 | 新增: } | |
| 200 | 新增: for i := range len(data) { | |
| 201 | 新增: fmt.Fprint(w, data[i:i+1]) | |
| 202 | 新增: w.(http.Flusher).Flush() | |
| 203 | 新增: if mode == "stalled" { | |
| 204 | 新增: <-r.Context().Done() | |
| 205 | 新增: return | |
| 206 | 新增: } | |
| 207 | 新增: select { | |
| 208 | 新增: case <-r.Context().Done(): | |
| 209 | 新增: return | |
| 210 | 新增: case <-time.After(idle / 3): | |
| 211 | 新增: } | |
| 212 | 新增: } | |
| 213 | 新增: })) | |
| 214 | 新增: defer s.Close() | |
| 215 | 新增: local := filepath.Join(t.TempDir(), "data") | |
| 216 | 新增: start := time.Now() | |
| 217 | 新增: retry, err := resumeHTTPOnce(t.Context(), local, "", "", s.URL, "test", digest.FromString(data), idle) | |
| 218 | 新增: if mode == "slow" { | |
| 219 | 新增: if err != nil || retry || time.Since(start) <= idle { | |
| 220 | 新增: t.Fatalf("progressing transfer interrupted: retry=%v err=%v", retry, err) | |
| 221 | 新增: } | |
| 222 | 新增: got, err := os.ReadFile(local + ".part") | |
| 223 | 新增: if err != nil || string(got) != data { | |
| 224 | 新增: t.Fatalf("received %q: %v", got, err) | |
| 225 | 新增: } | |
| 226 | 新增: } else if !retry || err == nil { | |
| 227 | 新增: t.Fatalf("stalled transfer not retried: retry=%v err=%v", retry, err) | |
| 228 | 新增: } | |
| 229 | 新增: if mode == "stalled" { | |
| 230 | 新增: got, err := os.ReadFile(local + ".part") | |
| 231 | 新增: if err != nil || string(got) != data[:1] { | |
| 232 | 新增: t.Fatalf("partial data lost: %q %v", got, err) | |
| 233 | 新增: } | |
| 234 | 新增: } | |
| 235 | 新增: }) | |
| 236 | 新增: } | |
| 237 | 新增:} | |
| @@ -0,0 +1,9 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增://go:build !windows || !amd64 | |
| 5 | 新增: | |
| 6 | 新增:package qemu | |
| 7 | 新增: | |
| 8 | 新增:// Only the Windows amd64 driver defaults to qemu64. | |
| 9 | 新增:func whpxQEMU64() string { return "qemu64" } | |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "unsafe" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/sirupsen/logrus" | |
| 10 | 新增: "golang.org/x/sys/windows" | |
| 11 | 新增:) | |
| 12 | 新增: | |
| 13 | 新增:func whpxQEMU64() string { | |
| 14 | 新增: // Query the processor features available to Windows Hypervisor Platform | |
| 15 | 新增: // guests. A nested hypervisor may expose a subset of the host's CPUID. | |
| 16 | 新增: query := windows.NewLazySystemDLL("WinHvPlatform.dll").NewProc("WHvGetCapability") | |
| 17 | 新增: if err := query.Find(); err != nil { | |
| 18 | 新增: logrus.WithError(err).Warn("Cannot query WHPX processor features; using qemu64 defaults") | |
| 19 | 新增: return "qemu64" | |
| 20 | 新增: } | |
| 21 | 新增: const processorFeatures = 0x1001 // WHvCapabilityCodeProcessorFeatures | |
| 22 | 新增: var bits uint64 | |
| 23 | 新增: var written uint32 | |
| 24 | 新增: status, _, _ := query.Call(processorFeatures, uintptr(unsafe.Pointer(&bits)), | |
| 25 | 新增: unsafe.Sizeof(bits), uintptr(unsafe.Pointer(&written))) | |
| 26 | 新增: if int32(status) < 0 || uintptr(written) != unsafe.Sizeof(bits) { | |
| 27 | 新增: logrus.Warnf("Cannot query WHPX processor features (HRESULT %#x, %d bytes); using qemu64 defaults", uint32(status), written) | |
| 28 | 新增: return "qemu64" | |
| 29 | 新增: } | |
| 30 | 新增: return whpxQEMU64Model(bits) | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:// Bit positions are from the Windows SDK's WHV_X64_PROCESSOR_FEATURES. | |
| 34 | 新增:func whpxQEMU64Model(bits uint64) string { | |
| 35 | 新增: model := "qemu64" | |
| 36 | 新增: for _, feature := range []struct { | |
| 37 | 新增: mask uint64 | |
| 38 | 新增: flag string | |
| 39 | 新增: }{ | |
| 40 | 新增: {1 << 2, "+ssse3"}, | |
| 41 | 新增: {1 << 3, "+sse4.1"}, | |
| 42 | 新增: {1 << 4, "+sse4.2"}, | |
| 43 | 新增: {1 << 7, "+popcnt"}, | |
| 44 | 新增: } { | |
| 45 | 新增: if bits&feature.mask != 0 { | |
| 46 | 新增: model += "," + feature.flag | |
| 47 | 新增: } | |
| 48 | 新增: } | |
| 49 | 新增: return model | |
| 50 | 新增:} | |
| @@ -0,0 +1,44 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "testing" | |
| 8 | 新增: | |
| 9 | 新增: "github.com/coreos/go-semver/semver" | |
| 10 | 新增: | |
| 11 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 12 | 新增:) | |
| 13 | 新增: | |
| 14 | 新增:func TestWHPXQEMU64Features(t *testing.T) { | |
| 15 | 新增: for bits, want := range map[uint64]string{ | |
| 16 | 新增: 0: "qemu64", | |
| 17 | 新增: 0x60: "qemu64", // AMD SSE4a and XOP do not imply SSE4.2. | |
| 18 | 新增: 0x0c: "qemu64,+ssse3,+sse4.1", | |
| 19 | 新增: 0x9c: "qemu64,+ssse3,+sse4.1,+sse4.2,+popcnt", | |
| 20 | 新增: } { | |
| 21 | 新增: if got := whpxQEMU64Model(bits); got != want { | |
| 22 | 新增: t.Errorf("WHPX feature mask %#x: got %q, want %q", bits, got, want) | |
| 23 | 新增: } | |
| 24 | 新增: } | |
| 25 | 新增:} | |
| 26 | 新增: | |
| 27 | 新增:func TestWindowsCPUResolution(t *testing.T) { | |
| 28 | 新增: arch := limatype.X8664 | |
| 29 | 新增: y := limatype.LimaYAML{Arch: &arch} | |
| 30 | 新增: // New and existing instances with no explicit CPU override both resolve | |
| 31 | 新增: // against the current host each time their QEMU command is generated. | |
| 32 | 新增: if got, want := resolveCPUType(&y, semver.New("11.1.0")), whpxQEMU64(); got != want { | |
| 33 | 新增: t.Fatalf("default for QEMU 11.1.0: got %q, want %q", got, want) | |
| 34 | 新增: } | |
| 35 | 新增: if got := resolveCPUType(&y, semver.New("11.1.1")); got != "host" { | |
| 36 | 新增: t.Fatalf("default for QEMU 11.1.1: got %q", got) | |
| 37 | 新增: } | |
| 38 | 新增: for _, override := range []string{"qemu64", "qemu64,+sse4.2", "Nehalem"} { | |
| 39 | 新增: y.VMOpts = limatype.VMOpts{limatype.QEMU: limatype.QEMUOpts{CPUType: limatype.CPUType{arch: override}}} | |
| 40 | 新增: if got := resolveCPUType(&y, semver.New("11.1.0")); got != override { | |
| 41 | 新增: t.Fatalf("explicit CPU type %q changed to %q", override, got) | |
| 42 | 新增: } | |
| 43 | 新增: } | |
| 44 | 新增:} | |
| @@ -0,0 +1,22 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "path/filepath" | |
| 8 | 新增: "unicode/utf8" | |
| 9 | 新增:) | |
| 10 | 新增: | |
| 11 | 新增:// The Windows QEMU build cannot reliably open a non-ASCII pflash argument. | |
| 12 | 新增:// CreateProcessW takes the working directory as UTF-16, so QEMU can open | |
| 13 | 新增:// the original firmware with its ASCII basename without making a stale copy. | |
| 14 | 新增:func windowsFirmwareArgument(path string) (argument, workingDir string) { | |
| 15 | 新增: dir := filepath.Dir(path) | |
| 16 | 新增: for _, r := range dir { | |
| 17 | 新增: if r >= utf8.RuneSelf && filepath.IsAbs(path) { | |
| 18 | 新增: return filepath.Base(path), dir | |
| 19 | 新增: } | |
| 20 | 新增: } | |
| 21 | 新增: return path, "" | |
| 22 | 新增:} | |
| @@ -0,0 +1,60 @@ | ||
| 1 | 新增:// SPDX-FileCopyrightText: Copyright The Lima Authors | |
| 2 | 新增:// SPDX-License-Identifier: Apache-2.0 | |
| 3 | 新增: | |
| 4 | 新增:package qemu | |
| 5 | 新增: | |
| 6 | 新增:import ( | |
| 7 | 新增: "os" | |
| 8 | 新增: "path/filepath" | |
| 9 | 新增: "runtime" | |
| 10 | 新增: "testing" | |
| 11 | 新增: | |
| 12 | 新增: "github.com/lima-vm/lima/v2/pkg/limatype" | |
| 13 | 新增:) | |
| 14 | 新增: | |
| 15 | 新增:func TestWindowsFirmwareArgument(t *testing.T) { | |
| 16 | 新增: dir := filepath.Join(t.TempDir(), "测试安装, Cage", "share") | |
| 17 | 新增: if err := os.MkdirAll(dir, 0o700); err != nil { | |
| 18 | 新增: t.Fatal(err) | |
| 19 | 新增: } | |
| 20 | 新增: const name = "edk2-x86_64-code.fd" | |
| 21 | 新增: path := filepath.Join(dir, name) | |
| 22 | 新增: arg, cwd := windowsFirmwareArgument(path) | |
| 23 | 新增: if arg != name || cwd != dir { | |
| 24 | 新增: t.Fatalf("got argument %q and working directory %q", arg, cwd) | |
| 25 | 新增: } | |
| 26 | 新增: // Replacing the packaged firmware must also replace what QEMU reads. | |
| 27 | 新增: for _, revision := range []string{"first release", "updated release"} { | |
| 28 | 新增: if err := os.WriteFile(path, []byte(revision), 0o600); err != nil { | |
| 29 | 新增: t.Fatal(err) | |
| 30 | 新增: } | |
| 31 | 新增: data, err := os.ReadFile(filepath.Join(cwd, arg)) | |
| 32 | 新增: if err != nil || string(data) != revision { | |
| 33 | 新增: t.Fatalf("reading %q: got %q, %v", revision, data, err) | |
| 34 | 新增: } | |
| 35 | 新增: } | |
| 36 | 新增:} | |
| 37 | 新增: | |
| 38 | 新增:func TestWindowsPackagedFirmwareBeatsOldUserCopy(t *testing.T) { | |
| 39 | 新增: if runtime.GOOS != "windows" { | |
| 40 | 新增: t.Skip("Windows QEMU distribution layout") | |
| 41 | 新增: } | |
| 42 | 新增: root := t.TempDir() | |
| 43 | 新增: home := filepath.Join(root, "用户") | |
| 44 | 新增: t.Setenv("USERPROFILE", home) | |
| 45 | 新增: binDir := filepath.Join(root, "安装目录", "qemu") | |
| 46 | 新增: const name = "edk2-x86_64-code.fd" | |
| 47 | 新增: bundled := filepath.Join(binDir, "share", name) | |
| 48 | 新增: for _, path := range []string{filepath.Join(home, ".local", "share", "qemu", name), bundled} { | |
| 49 | 新增: if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { | |
| 50 | 新增: t.Fatal(err) | |
| 51 | 新增: } | |
| 52 | 新增: if err := os.WriteFile(path, []byte(path), 0o600); err != nil { | |
| 53 | 新增: t.Fatal(err) | |
| 54 | 新增: } | |
| 55 | 新增: } | |
| 56 | 新增: got, err := getFirmware(filepath.Join(binDir, "qemu-system-x86_64.exe"), limatype.X8664) | |
| 57 | 新增: if err != nil || got != bundled { | |
| 58 | 新增: t.Fatalf("selected %q instead of the packaged %q: %v", got, bundled, err) | |
| 59 | 新增: } | |
| 60 | 新增:} | |
| @@ -458,6 +458,11 @@ func resolveCPUType(y *limatype.LimaYAML, qemuVersion *semver.Version) string { | ||
| 458 | 458 | if err := limayaml.Convert(y.VMOpts[limatype.QEMU], &qemuOpts, "vmOpts.qemu"); err != nil { |
| 459 | 459 | logrus.WithError(err).Warnf("Couldn't convert %#q", y.VMOpts[limatype.QEMU]) |
| 460 | 460 | } |
| 461 | 新增: // WHPX uses qemu64 when host passthrough is unavailable. Preserve an | |
| 462 | 新增: // explicit CPU model, including an explicitly requested bare qemu64. | |
| 463 | 新增: if cpuType[*y.Arch] == "qemu64" && qemuOpts.CPUType[*y.Arch] == "" { | |
| 464 | 新增: cpuType[*y.Arch] = whpxQEMU64() | |
| 465 | 新增: } | |
| 461 | 466 | for k, v := range qemuOpts.CPUType { |
| 462 | 467 | if !slices.Contains(limatype.ArchTypes, *y.Arch) { |
| 463 | 468 | logrus.Warnf("field `vmOpts.qemu.cpuType` uses unsupported arch %#q", k) |
| @@ -480,6 +485,10 @@ func resolveCPUType(y *limatype.LimaYAML, qemuVersion *semver.Version) string { | ||
| 480 | 485 | } |
| 481 | 486 | |
| 482 | 487 | func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err error) { |
| 488 | 新增: return cmdline(ctx, cfg, nil) | |
| 489 | 新增:} | |
| 490 | 新增: | |
| 491 | 新增:func cmdline(ctx context.Context, cfg Config, workingDir *string) (exe string, args []string, err error) { | |
| 483 | 492 | y := cfg.LimaYAML |
| 484 | 493 | exe, args, err = Exe(*y.Arch) |
| 485 | 494 | if err != nil { |
| @@ -647,7 +656,11 @@ func Cmdline(ctx context.Context, cfg Config) (exe string, args []string, err er | ||
| 647 | 656 | logrus.Infof("Using system firmware (%#q)", firmware) |
| 648 | 657 | } |
| 649 | 658 | if firmware != "" { |
| 650 | 删除: args = append(args, "-drive", fmt.Sprintf("if=pflash,format=raw,readonly=on,file=%s", firmware)) | |
| 659 | 新增: if runtime.GOOS == "windows" && workingDir != nil { | |
| 660 | 新增: firmware, *workingDir = windowsFirmwareArgument(firmware) | |
| 661 | 新增: } | |
| 662 | 新增: // Commas in -drive filenames are escaped by doubling them. | |
| 663 | 新增: args = append(args, "-drive", "if=pflash,format=raw,readonly=on,file="+strings.ReplaceAll(firmware, ",", ",,")) | |
| 651 | 664 | } |
| 652 | 665 | } |
| 653 | 666 | |
| @@ -1315,6 +1328,14 @@ func getFirmware(qemuExe string, arch limatype.Arch) (string, error) { | ||
| 1315 | 1328 | |
| 1316 | 1329 | relativePath := fmt.Sprintf("share/qemu/edk2-%s-code.fd", qemuEdk2Arch(arch)) |
| 1317 | 1330 | relativePathWin := fmt.Sprintf("share/edk2-%s-code.fd", qemuEdk2Arch(arch)) |
| 1331 | 新增: if runtime.GOOS == "windows" { | |
| 1332 | 新增: // The firmware shipped beside QEMU belongs to that QEMU version. | |
| 1333 | 新增: // Prefer it over an old manual copy in the user's .local directory. | |
| 1334 | 新增: bundled := filepath.Join(binDir, relativePathWin) | |
| 1335 | 新增: if _, err := os.Stat(bundled); err == nil || !errors.Is(err, os.ErrNotExist) { | |
| 1336 | 新增: return bundled, err | |
| 1337 | 新增: } | |
| 1338 | 新增: } | |
| 1318 | 1339 | candidates := []string{ |
| 1319 | 1340 | filepath.Join(userLocalDir, relativePath), // XDG-like |
| 1320 | 1341 | filepath.Join(localDir, relativePath), // macOS (homebrew) |
| @@ -1407,7 +1428,7 @@ func hasHostCPU(qemuVersion *semver.Version) bool { | ||
| 1407 | 1428 | return true |
| 1408 | 1429 | case "windows": |
| 1409 | 1430 | // Should have been 11.1.0, but it contained a regression when running in nested virt |
| 1410 | 删除: if qemuVersion.LessThan(*semver.New("11.1.1")) { | |
| 1431 | 新增: if qemuVersion == nil || qemuVersion.LessThan(*semver.New("11.1.1")) { | |
| 1411 | 1432 | return false |
| 1412 | 1433 | } |
| 1413 | 1434 | return true |
| @@ -422,7 +422,8 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { | ||
| 422 | 422 | socks.dgramConn.Close() |
| 423 | 423 | } |
| 424 | 424 | }() |
| 425 | 删除: qExe, qArgs, err := Cmdline(ctx, qCfg) | |
| 425 | 新增: var workingDir string | |
| 426 | 新增: qExe, qArgs, err := cmdline(ctx, qCfg, &workingDir) | |
| 426 | 427 | if err != nil { |
| 427 | 428 | return nil, err |
| 428 | 429 | } |
| @@ -468,6 +469,7 @@ func (l *LimaQemuDriver) Start(ctx context.Context) (chan error, error) { | ||
| 468 | 469 | qArgsFinal = append(qArgsFinal, applied) |
| 469 | 470 | } |
| 470 | 471 | qCmd := exec.CommandContext(ctx, qExe, qArgsFinal...) |
| 472 | 新增: qCmd.Dir = workingDir | |
| 471 | 473 | qCmd.ExtraFiles = append(qCmd.ExtraFiles, applier.files...) |
| 472 | 474 | qCmd.SysProcAttr = executil.BackgroundSysProcAttr |
| 473 | 475 | qStdout, err := qCmd.StdoutPipe() |
| @@ -183,6 +183,9 @@ func Prepare(ctx context.Context, inst *limatype.Instance, guestAgent string) (* | ||
| 183 | 183 | } |
| 184 | 184 | } |
| 185 | 185 | |
| 186 | 新增: if os.Getenv("CAGE_SETUP_PROGRESS") == "1" { | |
| 187 | 新增: fmt.Fprintln(os.Stderr, "CAGE_IMAGE_READY") | |
| 188 | 新增: } | |
| 186 | 189 | if err := limaDriver.CreateDisk(ctx); err != nil { |
| 187 | 190 | return nil, err |
| 188 | 191 | } |
| @@ -31,6 +31,11 @@ func LimaDir() (string, error) { | ||
| 31 | 31 | } |
| 32 | 32 | dir = filepath.Join(homeDir, DotLima) |
| 33 | 33 | } |
| 34 | 新增: // Cage keeps a stable logical path for QEMU backing files, SSH and sockets | |
| 35 | 新增: // when the profile's private VM storage is moved to another volume. | |
| 36 | 新增: if stable := os.Getenv("CAGE_LOGICAL_LIMA_HOME"); stable != "" && filepath.Clean(dir) == filepath.Clean(stable) { | |
| 37 | 新增: return filepath.Clean(dir), nil | |
| 38 | 新增: } | |
| 34 | 39 | if _, err := os.Stat(dir); errors.Is(err, os.ErrNotExist) { |
| 35 | 40 | return dir, nil |
| 36 | 41 | } |
| @@ -1 +1 @@ | ||
| 1 | 删除:<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><meta name="color-scheme" content="light dark"><link rel="icon" type="image/png" href="/cage.png"><title>Cage</title></head><body><div id="root"></div><script type="module" src="/src/main.jsx"></script></body></html> | |
| 1 | 新增:<!doctype html><html lang="zh-CN"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"><meta name="color-scheme" content="light dark"><link rel="icon" type="image/png" href="/cage.png"><title>Cage</title></head><body><div id="root"></div><script type="module" src="/src/desktop-entry.jsx"></script></body></html> | |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 删除: "version": "0.1.5-alpha.2", | |
| 3 | 新增: "version": "0.1.6-alpha-preview", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "cage-workbench", |
| 9 | 删除: "version": "0.1.5-alpha.2", | |
| 9 | 新增: "version": "0.1.6-alpha-preview", | |
| 10 | 10 | "dependencies": { |
| 11 | 11 | "@xterm/addon-fit": "0.11.0", |
| 12 | 12 | "@xterm/xterm": "6.0.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "cage-workbench", |
| 3 | 3 | "private": true, |
| 4 | 删除: "version": "0.1.5-alpha.2", | |
| 4 | 新增: "version": "0.1.6-alpha-preview", | |
| 5 | 5 | "type": "module", |
| 6 | 6 | "scripts": { |
| 7 | 7 | "prepare-vnc": "node scripts/prepare-vnc.mjs", |
| @@ -0,0 +1,254 @@ | ||
| 1 | 新增:// Real workbench UI with isolated, controllable SSH and local lifecycle responses. | |
| 2 | 新增:// Use CAGE_UI_URL for a built workbench served on loopback. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { mkdir } from "node:fs/promises"; | |
| 5 | 新增:import { join, resolve } from "node:path"; | |
| 6 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 7 | 新增: | |
| 8 | 新增:const reports = resolve( | |
| 9 | 新增: process.env.CAGE_REMOTE_QA_DIR || "ui/_output/desktop-environments", | |
| 10 | 新增:); | |
| 11 | 新增:await mkdir(reports, { recursive: true }); | |
| 12 | 新增:const host = { | |
| 13 | 新增: id: "fixture-host", | |
| 14 | 新增: name: "开发云服务器", | |
| 15 | 新增: host: "dev.example", | |
| 16 | 新增: user: "cage", | |
| 17 | 新增: port: 22, | |
| 18 | 新增: auth: { kind: "agent" }, | |
| 19 | 新增:}; | |
| 20 | 新增:const second = { | |
| 21 | 新增: ...host, | |
| 22 | 新增: id: "fixture-second", | |
| 23 | 新增: name: "第二台开发机", | |
| 24 | 新增: host: "test.example", | |
| 25 | 新增:}; | |
| 26 | 新增:let generation = 0; | |
| 27 | 新增:const view = { | |
| 28 | 新增: desktop_gateway: true, | |
| 29 | 新增: mode: "none", | |
| 30 | 新增: connection_id: "view-0", | |
| 31 | 新增: client_platform: "darwin", | |
| 32 | 新增: server_platform: "darwin", | |
| 33 | 新增: connection: { state: "disconnected" }, | |
| 34 | 新增:}; | |
| 35 | 新增:const local = { | |
| 36 | 新增: available: true, | |
| 37 | 新增: known: true, | |
| 38 | 新增: service_running: false, | |
| 39 | 新增: running: false, | |
| 40 | 新增: busy: false, | |
| 41 | 新增: live_terminals: 0, | |
| 42 | 新增: controller_id: "", | |
| 43 | 新增:}; | |
| 44 | 新增:let failSSH = true, | |
| 45 | 新增: holdSSH = true, | |
| 46 | 新增: staleStop = false; | |
| 47 | 新增:const actions = []; | |
| 48 | 新增:function switchTo(mode, hostID) { | |
| 49 | 新增: const target = hostID === second.id ? second : host; | |
| 50 | 新增: Object.assign(view, { | |
| 51 | 新增: mode, | |
| 52 | 新增: connection_id: "view-" + ++generation, | |
| 53 | 新增: candidate: null, | |
| 54 | 新增: host_id: mode === "remote" ? target.id : "", | |
| 55 | 新增: name: mode === "remote" ? target.name : "", | |
| 56 | 新增: server_platform: mode === "remote" ? "linux" : "darwin", | |
| 57 | 新增: instance_id: mode === "remote" ? "1".repeat(64) : "", | |
| 58 | 新增: connection: { state: mode === "none" ? "disconnected" : "connected" }, | |
| 59 | 新增: }); | |
| 60 | 新增:} | |
| 61 | 新增:function stopLocal() { | |
| 62 | 新增: Object.assign(local, { | |
| 63 | 新增: service_running: false, | |
| 64 | 新增: running: false, | |
| 65 | 新增: live_terminals: 0, | |
| 66 | 新增: controller_id: "", | |
| 67 | 新增: }); | |
| 68 | 新增:} | |
| 69 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 70 | 新增: clientContext: view, | |
| 71 | 新增: clientRequest: async (route, path, body) => { | |
| 72 | 新增: const reply = (value) => route.fulfill({ json: value }); | |
| 73 | 新增: if (path === "/client/hosts") return reply({ hosts: [host, second] }); | |
| 74 | 新增: if (path === "/client/local-status") return reply(local); | |
| 75 | 新增: if (path === "/client/context") { | |
| 76 | 新增: if (!holdSSH && view.candidate?.connection.state === "connecting") { | |
| 77 | 新增: Object.assign( | |
| 78 | 新增: view.candidate.connection, | |
| 79 | 新增: failSSH | |
| 80 | 新增: ? { state: "failed", message: "无法连接云端服务" } | |
| 81 | 新增: : { state: "connected" }, | |
| 82 | 新增: ); | |
| 83 | 新增: } | |
| 84 | 新增: return reply(view); | |
| 85 | 新增: } | |
| 86 | 新增: assert.equal(body.connection_id, view.connection_id, "stale client intent"); | |
| 87 | 新增: actions.push([path, body]); | |
| 88 | 新增: if (path === "/client/candidate") { | |
| 89 | 新增: view.candidate = { | |
| 90 | 新增: id: "candidate-" + ++generation, | |
| 91 | 新增: mode: body.mode, | |
| 92 | 新增: connection: { | |
| 93 | 新增: host_id: body.host_id, | |
| 94 | 新增: state: body.mode === "local" ? "connected" : "connecting", | |
| 95 | 新增: }, | |
| 96 | 新增: }; | |
| 97 | 新增: return reply(view.candidate); | |
| 98 | 新增: } | |
| 99 | 新增: if (path === "/client/cancel") { | |
| 100 | 新增: assert.equal(body.candidate_id, view.candidate.id); | |
| 101 | 新增: view.candidate = null; | |
| 102 | 新增: return reply(view); | |
| 103 | 新增: } | |
| 104 | 新增: if (path === "/client/commit") { | |
| 105 | 新增: assert.equal(body.candidate_id, view.candidate.id); | |
| 106 | 新增: assert.equal(view.candidate.connection.state, "connected"); | |
| 107 | 新增: if (body.local_action === "stop") { | |
| 108 | 新增: assert.equal(body.local_controller_id, local.controller_id); | |
| 109 | 新增: if (staleStop) | |
| 110 | 新增: return route.fulfill({ status: 423, body: "请切回本机解锁" }); | |
| 111 | 新增: stopLocal(); | |
| 112 | 新增: } | |
| 113 | 新增: switchTo(view.candidate.mode, view.candidate.connection.host_id); | |
| 114 | 新增: return reply(view); | |
| 115 | 新增: } | |
| 116 | 新增: if (path === "/client/local-stop") { | |
| 117 | 新增: assert.equal(body.local_controller_id, local.controller_id); | |
| 118 | 新增: if (staleStop) | |
| 119 | 新增: return route.fulfill({ status: 423, body: "请切回本机解锁" }); | |
| 120 | 新增: stopLocal(); | |
| 121 | 新增: return reply(view); | |
| 122 | 新增: } | |
| 123 | 新增: if (path === "/client/disconnect") { | |
| 124 | 新增: switchTo("none"); | |
| 125 | 新增: return reply(view); | |
| 126 | 新增: } | |
| 127 | 新增: throw new Error("Unexpected client API " + path); | |
| 128 | 新增: }, | |
| 129 | 新增:}); | |
| 130 | 新增:page.setDefaultTimeout(7000); | |
| 131 | 新增:const click = (name) => page.getByRole("button", { name, exact: true }).click(); | |
| 132 | 新增:const visible = (name) => | |
| 133 | 新增: page.getByText(name, { exact: true }).first().waitFor(); | |
| 134 | 新增:try { | |
| 135 | 新增: await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 136 | 新增: assert.equal(view.mode, "local"); | |
| 137 | 新增: assert.equal(state.requests.some(r => r.path === "/start"), false); | |
| 138 | 新增: await click("SSH 主机"); | |
| 139 | 新增: // The working surface survives opening the sidebar and a failed candidate. | |
| 140 | 新增: await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 141 | 新增: await click("返回工作台侧栏"); | |
| 142 | 新增: await page.getByRole("navigation", { name: "主导航" }).waitFor(); | |
| 143 | 新增: await click("SSH 主机"); | |
| 144 | 新增: await click("连接此主机"); | |
| 145 | 新增: await page.getByText("正在验证…", { exact: true }).waitFor(); | |
| 146 | 新增: assert.equal(await page.getByRole("dialog").count(), 0); | |
| 147 | 新增: holdSSH = false; | |
| 148 | 新增: await visible("无法连接云端服务"); | |
| 149 | 新增: assert.equal(view.mode, "local"); | |
| 150 | 新增: failSSH = false; | |
| 151 | 新增: Object.assign(local, { | |
| 152 | 新增: service_running: true, | |
| 153 | 新增: running: true, | |
| 154 | 新增: live_terminals: 2, | |
| 155 | 新增: controller_id: "local-identity", | |
| 156 | 新增: }); | |
| 157 | 新增: await click("连接此主机"); | |
| 158 | 新增: const decision = page.getByRole("dialog", { name: "切换到 SSH 主机" }); | |
| 159 | 新增: await decision.waitFor(); | |
| 160 | 新增: await page.keyboard.press("Escape"); | |
| 161 | 新增: await decision.waitFor({ state: "hidden" }); | |
| 162 | 新增: assert.equal(view.mode, "local"); | |
| 163 | 新增: assert.equal(local.running, true); | |
| 164 | 新增: await click("连接此主机"); | |
| 165 | 新增: await decision.waitFor(); | |
| 166 | 新增: await page.screenshot({ path: join(reports, "ssh-switch-confirmation.png") }); | |
| 167 | 新增: await click("保留本机运行"); | |
| 168 | 新增: await visible("本机也在运行"); | |
| 169 | 新增: await visible("SSH · 云端运行"); | |
| 170 | 新增: assert.equal(view.mode, "remote"); | |
| 171 | 新增: assert.equal(local.running, true); | |
| 172 | 新增: await click("停止本机环境"); | |
| 173 | 新增: staleStop = true; | |
| 174 | 新增: await click("确认停止本机"); | |
| 175 | 新增: await visible("本机环境已锁定。请先返回本机解锁,再停止本机环境。"); | |
| 176 | 新增: assert.equal(view.mode, "remote"); | |
| 177 | 新增: assert.equal(state.account.unlocked, true); | |
| 178 | 新增: await click("返回本机解锁"); | |
| 179 | 新增: await page.locator(".client-toolbar").waitFor({state: "hidden"}); | |
| 180 | 新增: await page.getByRole("navigation", {name: "主导航"}).waitFor(); | |
| 181 | 新增: assert.equal(view.mode, "local"); | |
| 182 | 新增: staleStop = false; | |
| 183 | 新增: await click("SSH 主机"); | |
| 184 | 新增: await click("连接此主机"); | |
| 185 | 新增: await decision.waitFor(); | |
| 186 | 新增: await click("保留本机运行"); | |
| 187 | 新增: await visible("SSH · 云端运行"); | |
| 188 | 新增: await click("SSH 主机"); | |
| 189 | 新增: await page.screenshot({ path: join(reports, "ssh-sidebar-background.png") }); | |
| 190 | 新增: await page.getByRole("button", { name: /第二台开发机/ }).click(); | |
| 191 | 新增: await click("连接此主机"); | |
| 192 | 新增: await decision.waitFor(); | |
| 193 | 新增: assert.equal(view.host_id, host.id, "A remains selected before B's commit"); | |
| 194 | 新增: staleStop = true; | |
| 195 | 新增: await click("停止本机并连接"); | |
| 196 | 新增: await decision.getByRole("button", { name: "返回本机解锁" }).waitFor(); | |
| 197 | 新增: assert.equal(view.host_id, host.id); | |
| 198 | 新增: const cancelled = view.candidate.id; | |
| 199 | 新增: await click("返回本机解锁"); | |
| 200 | 新增: await page.locator(".client-toolbar").waitFor({state: "hidden"}); | |
| 201 | 新增: await page.getByRole("navigation", {name: "主导航"}).waitFor(); | |
| 202 | 新增: assert.ok( | |
| 203 | 新增: actions.some( | |
| 204 | 新增: ([path, body]) => | |
| 205 | 新增: path === "/client/cancel" && body.candidate_id === cancelled, | |
| 206 | 新增: ), | |
| 207 | 新增: ); | |
| 208 | 新增: staleStop = false; | |
| 209 | 新增: await click("SSH 主机"); | |
| 210 | 新增: await click("连接此主机"); | |
| 211 | 新增: await decision.waitFor(); | |
| 212 | 新增: await click("保留本机运行"); | |
| 213 | 新增: await visible("SSH · 云端运行"); | |
| 214 | 新增: await click("SSH 主机"); | |
| 215 | 新增: await page.getByRole("button", { name: /第二台开发机/ }).click(); | |
| 216 | 新增: await click("连接此主机"); | |
| 217 | 新增: await decision.waitFor(); | |
| 218 | 新增: await click("停止本机并连接"); | |
| 219 | 新增: await visible("SSH · 云端运行"); | |
| 220 | 新增: assert.equal(view.host_id, second.id); | |
| 221 | 新增: assert.equal(local.running, false); | |
| 222 | 新增: Object.assign(local, { | |
| 223 | 新增: running: true, | |
| 224 | 新增: live_terminals: 1, | |
| 225 | 新增: controller_id: "new-local-identity", | |
| 226 | 新增: }); | |
| 227 | 新增: await click("停止本机环境"); | |
| 228 | 新增: await click("确认停止本机"); | |
| 229 | 新增: await visible("SSH · 云端运行"); | |
| 230 | 新增: assert.equal(view.mode, "remote"); | |
| 231 | 新增: assert.equal(local.running, false); | |
| 232 | 新增: await click("SSH 主机"); | |
| 233 | 新增: await click("断开连接"); | |
| 234 | 新增: await page.getByRole("complementary", { name: "SSH 主机" }).waitFor(); | |
| 235 | 新增: assert.equal(view.mode, "none"); | |
| 236 | 新增: assert.equal( | |
| 237 | 新增: actions.some( | |
| 238 | 新增: ([path, body]) => | |
| 239 | 新增: path === "/client/local-stop" && | |
| 240 | 新增: body.local_controller_id === "new-local-identity", | |
| 241 | 新增: ), | |
| 242 | 新增: true, | |
| 243 | 新增: ); | |
| 244 | 新增: assert.deepEqual(errors, []); | |
| 245 | 新增: console.log( | |
| 246 | 新增: "PASS: on-demand workbench, SSH sidebar round trip, candidate failure, cancel/keep/stop, locked local stop, confirmed background stop and disconnect.", | |
| 247 | 新增: reports, | |
| 248 | 新增: ); | |
| 249 | 新增:} catch (error) { | |
| 250 | 新增: await page.screenshot({ path: join(reports, "failure.png") }).catch(() => {}); | |
| 251 | 新增: throw error; | |
| 252 | 新增:} finally { | |
| 253 | 新增: await browser.close(); | |
| 254 | 新增:} | |
| @@ -0,0 +1,53 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 5 | 新增:try { | |
| 6 | 新增: state.status.local_vm_storage = true; | |
| 7 | 新增: let location = { directory: "C:\\Users\\demo\\.claude-cage\\state", has_environment: false }; | |
| 8 | 新增: const writes = []; | |
| 9 | 新增: const destination = "D:\\开发工具\\Cage 环境"; | |
| 10 | 新增: await page.route("**/api/environment/storage", (route) => { | |
| 11 | 新增: if (route.request().method() === "GET") return route.fulfill({ json: location }); | |
| 12 | 新增: const input = route.request().postDataJSON(); | |
| 13 | 新增: writes.push(input); | |
| 14 | 新增: const rejected = input.directory.endsWith("occupied"); | |
| 15 | 新增: const job = { kind: "storage", id: String(writes.length), running: false, error: rejected ? "目录必须为空" : "" }; | |
| 16 | 新增: state.status.job = job; | |
| 17 | 新增: if (!rejected) location = { ...location, directory: input.directory, backup: location.has_environment ? location.directory : "" }; | |
| 18 | 新增: return route.fulfill({ json: job }); | |
| 19 | 新增: }); | |
| 20 | 新增: await page.getByRole("button", { name: "选择环境存储位置" }).click(); | |
| 21 | 新增: const panel = page.getByRole("region", { name: "本机环境存储" }); | |
| 22 | 新增: const picker = panel.getByRole("button", { name: "选择文件夹" }); | |
| 23 | 新增: const target = panel.getByLabel("新存储位置"); | |
| 24 | 新增: state.chosenFolder = ""; | |
| 25 | 新增: await picker.click(); | |
| 26 | 新增: assert.equal(await target.inputValue(), ""); | |
| 27 | 新增: state.chosenFolder = destination; | |
| 28 | 新增: await picker.click(); | |
| 29 | 新增: await page.waitForFunction((path) => [...document.querySelectorAll("input")].some((input) => input.value === path), destination); | |
| 30 | 新增: await panel.getByRole("button", { name: "使用此位置" }).click(); | |
| 31 | 新增: await panel.getByText(destination, { exact: true }).waitFor(); | |
| 32 | 新增: assert.equal(writes[0].migrate, false); | |
| 33 | 新增: location.has_environment = true; | |
| 34 | 新增: await page.reload(); | |
| 35 | 新增: await page.getByRole("button", { name: "选择环境存储位置" }).click(); | |
| 36 | 新增: await panel.getByText(destination, { exact: true }).waitFor(); | |
| 37 | 新增: await target.fill("E:\\occupied"); | |
| 38 | 新增: await panel.getByRole("button", { name: "迁移到此位置" }).click(); | |
| 39 | 新增: await page.getByRole("dialog").getByRole("button", { name: "取消" }).click(); | |
| 40 | 新增: assert.equal(writes.length, 1); | |
| 41 | 新增: await panel.getByRole("button", { name: "迁移到此位置" }).click(); | |
| 42 | 新增: await page.getByRole("dialog").getByRole("button", { name: "迁移环境" }).click(); | |
| 43 | 新增: await panel.getByText("目录必须为空", { exact: true }).waitFor(); | |
| 44 | 新增: await target.fill("E:\\Cage 环境"); | |
| 45 | 新增: await panel.getByRole("button", { name: "迁移到此位置" }).click(); | |
| 46 | 新增: await page.getByRole("dialog").getByRole("button", { name: "迁移环境" }).click(); | |
| 47 | 新增: await panel.getByText("E:\\Cage 环境", { exact: true }).waitFor(); | |
| 48 | 新增: assert.equal(writes.at(-1).migrate, true); | |
| 49 | 新增: assert.equal(writes.at(-1).previous, destination); | |
| 50 | 新增: assert.equal(await panel.locator("code").textContent(), destination); | |
| 51 | 新增: assert.deepEqual(errors, []); | |
| 52 | 新增: console.log("Storage selection, picker cancellation, migration confirmation, failure and backup location passed"); | |
| 53 | 新增:} finally { await browser.close(); } | |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import assert from "node:assert/strict"; |
| 2 | 新增:import { randomBytes } from "node:crypto"; | |
| 2 | 3 | import fs from "node:fs/promises"; |
| 3 | 4 | import os from "node:os"; |
| 4 | 5 | import path from "node:path"; |
| @@ -7,9 +8,12 @@ import { promisify } from "node:util"; | ||
| 7 | 8 | import { createRequire } from "node:module"; |
| 8 | 9 | |
| 9 | 10 | const run = promisify(execFile); |
| 10 | 删除:const bundle = process.argv[2]; | |
| 11 | 删除:assert.ok(bundle?.startsWith("/") && bundle.endsWith(".app"), "supply an absolute packaged App path"); | |
| 12 | 删除:const cage = path.join(bundle, "Contents/Resources/cage"); | |
| 11 | 新增:const target = process.argv[2]; | |
| 12 | 新增:assert.ok(path.isAbsolute(target || ""), "supply an absolute Cage.app or full Cage helper path"); | |
| 13 | 新增:const packaged = target.endsWith(".app"); | |
| 14 | 新增:const cage = packaged ? path.join(target, "Contents/Resources/cage") : target; | |
| 15 | 新增:const evidence = process.env.CAGE_REMOTE_QA_DIR; | |
| 16 | 新增:if (evidence) await fs.mkdir(evidence, { recursive: true }); | |
| 13 | 17 | const profile = await fs.mkdtemp(path.join(os.tmpdir(), "cage-packaged-")); |
| 14 | 18 | const env = { ...process.env, CLAUDE_CAGE_CONFIG: path.join(profile, "config.json") }; |
| 15 | 19 | const require = createRequire(import.meta.url); |
| @@ -20,20 +24,37 @@ try { | ||
| 20 | 24 | const entry = JSON.parse(stdout); |
| 21 | 25 | assert.equal(entry.status, "ready"); |
| 22 | 26 | assert.equal(entry.controller.version, (await fs.readFile(new URL("../../VERSION", import.meta.url), "utf8")).trim()); |
| 23 | 删除: browser = await chromium.launch({ headless: true }); | |
| 27 | 新增: browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); | |
| 24 | 28 | const page = await browser.newPage(); |
| 25 | 29 | const errors = []; |
| 26 | 30 | page.on("pageerror", (error) => errors.push(error.message)); |
| 27 | 31 | const statusResponse = page.waitForResponse((response) => response.url().endsWith("/api/status") && response.ok()); |
| 28 | 32 | await page.goto(entry.url); |
| 33 | 新增: await page.getByLabel("用户名",{exact:true}).waitFor(); | |
| 34 | 新增: const initial = await page.evaluate(async () => (await fetch("/api/client/local-status")).json()); | |
| 35 | 新增: assert.ok(initial.known && initial.service_running && !initial.running, "opening the local home must not boot the VM"); | |
| 36 | 新增: assert.equal(await page.getByRole("heading",{name:"选择工作环境"}).count(),0); | |
| 37 | 新增: if (evidence) await page.screenshot({ path:path.join(evidence,"desktop-first-open.png") }); | |
| 38 | 新增: const password = randomBytes(24).toString("base64url"); | |
| 39 | 新增: await page.getByLabel("用户名",{exact:true}).fill("Packaged Smoke"); | |
| 40 | 新增: await page.getByLabel("设置密码",{exact:true}).fill(password); | |
| 41 | 新增: await page.getByLabel("确认密码",{exact:true}).fill(password); | |
| 42 | 新增: await page.getByRole("button",{name:"创建本地账户",exact:true}).click(); | |
| 29 | 43 | const status = await (await statusResponse).json(); |
| 30 | 44 | assert.equal(status.vm_running, false); |
| 31 | 45 | await page.getByRole("button", { name: "配置网络与代理", exact: true }).waitFor(); |
| 46 | 新增: const nav = page.getByRole("navigation", {name:"主导航"}); | |
| 47 | 新增: assert.equal(await nav.getByRole("button", {name:/Claude(?: Code)? 会话/}).count(), 0); | |
| 48 | 新增: assert.equal(await nav.getByRole("button", {name:"Claude Desktop",exact:true}).count(), 1); | |
| 49 | 新增: await page.getByRole("button",{name:"SSH 主机",exact:true}).click(); | |
| 50 | 新增: await page.getByRole("complementary",{name:"SSH 主机"}).waitFor(); | |
| 51 | 新增: if (evidence) await page.screenshot({ path:path.join(evidence,"local-ssh-sidebar.png") }); | |
| 52 | 新增: await page.getByRole("button",{name:"返回工作台侧栏"}).click(); | |
| 32 | 53 | assert.equal(new URL(page.url()).hash, "", "launch ticket was not removed"); |
| 33 | 54 | await page.getByRole("button", { name: "配置网络与代理", exact: true }).click(); |
| 34 | 55 | await page.getByText("添加来源", { exact: true }).first().waitFor(); |
| 35 | 56 | assert.deepEqual(errors, []); |
| 36 | 删除: console.log(JSON.stringify({ checks: ["packaged helper bootstrap", "real session and APIs", "embedded production UI loaded", "private profile onboarding", "launch ticket removed"], version: entry.controller.version })); | |
| 57 | 新增: console.log(JSON.stringify({ checks: ["original local home by default", "VM stopped throughout", "isolated local account setup", packaged ? "packaged helper bootstrap" : "development helper bootstrap", "real session and APIs", "embedded production UI loaded", "private profile onboarding", "launch ticket removed"], version: entry.controller.version })); | |
| 37 | 58 | } finally { |
| 38 | 59 | await browser?.close(); |
| 39 | 60 | await run(cage, ["prepare-update", "--json"], { env }); |
| @@ -0,0 +1,106 @@ | ||
| 1 | 新增:// Real client service and browser interaction, using only a fresh temp profile. | |
| 2 | 新增:// No cloud host or personal Cage configuration is accessed. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { spawn } from "node:child_process"; | |
| 5 | 新增:import { createRequire } from "node:module"; | |
| 6 | 新增:import { mkdtemp, readFile, mkdir, writeFile } from "node:fs/promises"; | |
| 7 | 新增:import { tmpdir } from "node:os"; | |
| 8 | 新增:import { join, resolve } from "node:path"; | |
| 9 | 新增: | |
| 10 | 新增:const require = createRequire(import.meta.url); | |
| 11 | 新增:const { chromium } = require(process.env.CAGE_PLAYWRIGHT_MODULE || "playwright"); | |
| 12 | 新增:const executable = process.env.CAGE_CLIENT_BINARY; | |
| 13 | 新增:if (!executable) throw new Error("Set CAGE_CLIENT_BINARY to the newly built client binary"); | |
| 14 | 新增:const profile = await mkdtemp(join(tmpdir(), "cage-remote-host-ui-")); | |
| 15 | 新增:const artifacts = resolve(process.env.CAGE_REMOTE_QA_DIR || join(profile, "artifacts")); | |
| 16 | 新增:await mkdir(artifacts, { recursive: true }); | |
| 17 | 新增:const service = spawn(executable, ["serve"], { env: { ...process.env, CLAUDE_CAGE_CONFIG: join(profile, "config.json") }, stdio: "ignore" }); | |
| 18 | 新增:let browser; | |
| 19 | 新增:let page; | |
| 20 | 新增:try { | |
| 21 | 新增: let control; | |
| 22 | 新增: for (let i = 0; i < 200; i++) { | |
| 23 | 新增: try { control = JSON.parse(await readFile(join(profile, "control.json"), "utf8")); break; } | |
| 24 | 新增: catch { if (service.exitCode !== null) throw new Error("Client service exited before publishing its private control record"); await new Promise((r) => setTimeout(r, 50)); } | |
| 25 | 新增: } | |
| 26 | 新增: assert.ok(control, "client service did not start"); | |
| 27 | 新增: const origin = `http://localhost:${control.port}`; | |
| 28 | 新增: const launched = await fetch(`${origin}/api/launch`, { method: "POST", headers: { "Content-Type": "application/json", Origin: origin }, body: JSON.stringify({ token: control.token }) }); | |
| 29 | 新增: assert.equal(launched.status, 200); | |
| 30 | 新增: const entry = await launched.json(); | |
| 31 | 新增: browser = await chromium.launch({ headless: true, executablePath: process.env.CAGE_TEST_BROWSER_PATH }); | |
| 32 | 新增: page = await browser.newPage({ viewport: { width: 1280, height: 850 } }); | |
| 33 | 新增: const errors = []; | |
| 34 | 新增: page.on("pageerror", (error) => errors.push(error.message)); | |
| 35 | 新增: await page.goto(entry.url); | |
| 36 | 新增: await page.getByRole("complementary", { name: "SSH 主机", exact: true }).waitFor(); | |
| 37 | 新增: assert.equal(await page.getByRole("button", { name: "使用本机" }).count(), 0, "thin client must not offer local workloads"); | |
| 38 | 新增: assert.equal(await page.getByRole("button", { name: "创建本地账户" }).count(), 0, "local account must not block remote setup"); | |
| 39 | 新增: await page.getByRole("button", { name: "添加远程主机" }).click(); | |
| 40 | 新增: await page.getByLabel("主机名称", { exact: true }).fill("隔离 UI 测试主机"); | |
| 41 | 新增: await page.getByLabel("服务器地址", { exact: true }).fill("127.0.0.1"); | |
| 42 | 新增: await page.getByLabel("SSH 端口", { exact: true }).fill("9"); | |
| 43 | 新增: await page.getByLabel("SSH 用户名", { exact: true }).fill("cage-test"); | |
| 44 | 新增: const auth = page.getByRole("combobox", { name: "SSH 登录方式" }); | |
| 45 | 新增: const keyField = page.getByLabel("本机私钥文件", { exact: true }); | |
| 46 | 新增: // The centered dialog itself moves when its height changes. Compare gaps | |
| 47 | 新增: // inside the dialog to check whether the list takes up layout space. | |
| 48 | 新增: const gap = async () => (await keyField.boundingBox()).y - (await auth.boundingBox()).y; | |
| 49 | 新增: const before = await gap(); | |
| 50 | 新增: await auth.click(); | |
| 51 | 新增: await page.getByRole("option", { name: "本机 SSH agent" }).waitFor(); | |
| 52 | 新增: const expanded = await keyField.boundingBox(); | |
| 53 | 新增: assert.ok(await gap() > before + 30, "inline choices must push subsequent fields down"); | |
| 54 | 新增: const list = await page.getByRole("listbox").boundingBox(); | |
| 55 | 新增: assert.ok(list.y + list.height <= expanded.y, "choices must not cover the next field"); | |
| 56 | 新增: await auth.press("Escape"); | |
| 57 | 新增: assert.equal(await auth.getAttribute("aria-expanded"), "false"); | |
| 58 | 新增: await page.getByRole("listbox").waitFor({state:"hidden"}); | |
| 59 | 新增: assert.ok(Math.abs(await gap() - before) < 1, "closing choices restores layout"); | |
| 60 | 新增: await auth.press("ArrowDown"); | |
| 61 | 新增: await auth.press("ArrowDown"); | |
| 62 | 新增: await auth.press("Enter"); | |
| 63 | 新增: assert.equal(await auth.getAttribute("aria-expanded"), "false"); | |
| 64 | 新增: assert.equal(await keyField.count(), 0, "keyboard selection switches authentication method"); | |
| 65 | 新增: await auth.click(); | |
| 66 | 新增: await page.getByRole("option", { name: "本机密钥文件" }).click(); | |
| 67 | 新增: await page.screenshot({ path: join(artifacts, "remote-host-form-desktop.png"), fullPage: true }); | |
| 68 | 新增: await page.setViewportSize({ width: 375, height: 900 }); | |
| 69 | 新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false, "mobile form should not overflow horizontally"); | |
| 70 | 新增: await page.screenshot({ path: join(artifacts, "remote-host-form-mobile.png"), fullPage: true }); | |
| 71 | 新增: await page.setViewportSize({ width: 1280, height: 850 }); | |
| 72 | 新增: await page.getByLabel("本机私钥文件", { exact: true }).fill(join(profile, "missing-test-key")); | |
| 73 | 新增: await page.getByRole("button", { name: "保存主机", exact: true }).click(); | |
| 74 | 新增: await page.getByText("隔离 UI 测试主机", { exact: true }).waitFor(); | |
| 75 | 新增: await page.reload(); | |
| 76 | 新增: await page.getByText("隔离 UI 测试主机", { exact: true }).waitFor(); | |
| 77 | 新增: const saved = JSON.parse(await readFile(join(profile, "remote-hosts.json"), "utf8")); | |
| 78 | 新增: assert.equal(saved.hosts.length, 1); assert.equal(saved.hosts[0].port, 9); | |
| 79 | 新增: await page.getByRole("button", { name: "连接此主机" }).click(); | |
| 80 | 新增: await page.getByText("SSH 密钥不存在或文件权限不安全", { exact: true }).waitFor(); | |
| 81 | 新增: assert.equal(await page.getByRole("complementary", { name: "SSH 主机", exact: true }).count(), 1, "failed remote connection must retain host management"); | |
| 82 | 新增: assert.equal(await page.getByRole("button", { name: "创建本地账户" }).count(), 0, "failure must not fall back to a local account"); | |
| 83 | 新增: await page.screenshot({ path: join(artifacts, "remote-host-error.png"), fullPage: true }); | |
| 84 | 新增: await page.getByRole("button", { name: "编辑", exact: true }).click(); | |
| 85 | 新增: await page.getByLabel("主机名称", { exact: true }).fill("修改后的测试主机"); | |
| 86 | 新增: await page.getByRole("button", { name: "保存主机", exact: true }).click(); | |
| 87 | 新增: await page.getByText("修改后的测试主机", { exact: true }).waitFor(); | |
| 88 | 新增: await page.getByRole("button", { name: "移除连接", exact: true }).click(); | |
| 89 | 新增: await page.getByRole("button", { name: "取消", exact: true }).click(); | |
| 90 | 新增: assert.equal(await page.getByText("修改后的测试主机", { exact: true }).count(), 1); | |
| 91 | 新增: await page.getByRole("button", { name: "移除连接", exact: true }).click(); | |
| 92 | 新增: await page.getByRole("button", { name: "确认移除", exact: true }).click(); | |
| 93 | 新增: await page.getByText("还没有远程主机", { exact: true }).waitFor(); | |
| 94 | 新增: assert.deepEqual(JSON.parse(await readFile(join(profile, "remote-hosts.json"), "utf8")).hosts, []); | |
| 95 | 新增: assert.deepEqual(errors, []); | |
| 96 | 新增: const result = { ok: true, scope: "真实本地 cage-client 服务和 Chromium;独立临时配置;连接失败路径", checks: ["thin-client-no-local-account", "host-crud-and-persistence", "inline-dropdown-layout", "keyboard-choice", "mobile-layout", "connection-error-no-local-fallback", "remove-cancel-and-confirm"], notTested: ["真实云端服务器连接与容器工作负载", "macOS、Windows、Linux 原生窗口交互"], pageErrors: errors }; | |
| 97 | 新增: await writeFile(join(artifacts, "result.json"), JSON.stringify(result, null, 2)); | |
| 98 | 新增: console.log(JSON.stringify({ ...result, artifacts })); | |
| 99 | 新增:} catch (error) { | |
| 100 | 新增: if (page) await page.screenshot({ path: join(artifacts, "failure.png"), fullPage: true }).catch(() => {}); | |
| 101 | 新增: console.error(`UI evidence: ${artifacts}`); | |
| 102 | 新增: throw error; | |
| 103 | 新增:} finally { | |
| 104 | 新增: await browser?.close(); | |
| 105 | 新增: service.kill("SIGTERM"); | |
| 106 | 新增:} | |
| @@ -0,0 +1,99 @@ | ||
| 1 | 新增:// UI contract fixture: remote paths, generation binding and client-only quit. | |
| 2 | 新增:// SSH, cookies and streaming use the real protocol tests in internal/remotehost. | |
| 3 | 新增:import assert from "node:assert/strict"; | |
| 4 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:const connection = "test-remote-connection"; | |
| 7 | 新增:const instance = "a".repeat(64); | |
| 8 | 新增:const nativeCalls = []; | |
| 9 | 新增:const { browser, page, state, errors } = await createWorkbench({ | |
| 10 | 新增: clientContext: { mode: "remote", client_only: true, connection_id: connection, instance_id: instance, host_id: "test-host", name: "云端测试环境", client_platform: "darwin", server_platform: "linux", connection: { state: "connected", connection_id: connection, instance_id: instance } }, | |
| 11 | 新增: nativeRequest: async (body) => { nativeCalls.push(body); return body.action === "accountDevice" ? { supported: false } : true; }, | |
| 12 | 新增:}); | |
| 13 | 新增:const requests = []; | |
| 14 | 新增:page.on("request", (request) => { if (request.url().includes("/api/")) requests.push(request); }); | |
| 15 | 新增:let directoryRequests = 0; | |
| 16 | 新增:await page.route("**/api/projects/directories?*", async (route) => { | |
| 17 | 新增: const request = route.request(); | |
| 18 | 新增: assert.equal(request.headers()["x-cage-connection"], connection); | |
| 19 | 新增: directoryRequests++; | |
| 20 | 新增: const path = new URL(request.url()).searchParams.get("path"); | |
| 21 | 新增: await route.fulfill({ json: path === "/srv/projects/research" ? { path, parent: "/srv/projects", directories: [], selectable: true } : { path: "/srv/projects", parent: "/srv", directories: [{ name: "research", path: "/srv/projects/research" }], selectable: false } }); | |
| 22 | 新增:}); | |
| 23 | 新增:let resourceData = { | |
| 24 | 新增: runtime: "container", automatic: false, running: true, | |
| 25 | 新增: configured_memory_bytes: 8 * 1073741824, configured_cpus: 2, | |
| 26 | 新增: recommended_memory_bytes: 8 * 1073741824, recommended_cpus: 2, | |
| 27 | 新增: restart_required: false, observation: null, resources_verified: true, pids_limit: 512, resource_error: "", | |
| 28 | 新增:}; | |
| 29 | 新增:await page.route("**/api/environment/resources", (route) => route.fulfill({ json: resourceData })); | |
| 30 | 新增:try { | |
| 31 | 新增: state.settings.workspace = "/srv/cage/workspace"; | |
| 32 | 新增: state.settings.keyboard = "native"; | |
| 33 | 新增: Object.assign(state.status, { keyboard: "native", projects: [state.settings.workspace], environment_directory: state.settings.workspace }); | |
| 34 | 新增: await page.reload(); | |
| 35 | 新增: await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 36 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 37 | 新增: await page.getByRole("heading", { name: "Cage 环境已就绪", exact: true }).waitFor(); | |
| 38 | 新增: await page.getByRole("button", { name: "添加项目", exact: true }).click(); | |
| 39 | 新增: await page.getByRole("button", { name: "添加云端项目…", exact: true }).click(); | |
| 40 | 新增: const chooser = page.getByRole("region", { name: "云端文件夹" }); | |
| 41 | 新增: await chooser.getByRole("button", { name: "research", exact: true }).click(); | |
| 42 | 新增: await chooser.getByRole("button", { name: "选择此云端文件夹", exact: true }).click(); | |
| 43 | 新增: assert.equal(await page.getByLabel("新项目文件夹", { exact: true }).inputValue(), "/srv/projects/research"); | |
| 44 | 新增: await page.getByRole("dialog").getByRole("button", { name: "打开项目", exact: true }).click(); | |
| 45 | 新增: await page.getByRole("dialog").waitFor({ state: "hidden" }); | |
| 46 | 新增: assert.equal(state.settings.workspace, "/srv/projects/research"); | |
| 47 | 新增: assert.equal(directoryRequests, 2); | |
| 48 | 新增: await page.getByRole("button", { name: "设置", exact: true }).click(); | |
| 49 | 新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "通用", exact: true }).click(); | |
| 50 | 新增: const macKeyboard = page.getByRole("radio", { name: /Mac 快捷键/ }); | |
| 51 | 新增: assert.equal(await macKeyboard.isChecked(), true, "Mac client defaults must not follow Linux server keyboard mode"); | |
| 52 | 新增: const savesBefore = state.requests.filter((item) => item.path === "/settings" && item.method === "POST").length; | |
| 53 | 新增: await page.getByRole("radio", { name: /原生 Linux 快捷键/ }).check(); | |
| 54 | 新增: assert.equal(await page.evaluate((instance) => localStorage.getItem(`cage-keyboard:remote:${instance}`), instance), "native"); | |
| 55 | 新增: assert.equal(state.requests.filter((item) => item.path === "/settings" && item.method === "POST").length, savesBefore, "client keyboard changes must not write cloud settings"); | |
| 56 | 新增: await macKeyboard.check(); | |
| 57 | 新增: await page.getByRole("navigation", { name: "设置分组" }).getByRole("button", { name: "环境与恢复", exact: true }).click(); | |
| 58 | 新增: await page.getByRole("heading", { name: "服务器容器资源上限", exact: true }).waitFor(); | |
| 59 | 新增: const resources = page.getByRole("region", { name: "计算资源" }); | |
| 60 | 新增: await resources.getByText("8.0 GiB", { exact: true }).waitFor(); | |
| 61 | 新增: await resources.getByText("已核验", { exact: true }).waitFor(); | |
| 62 | 新增: await resources.getByText("512", { exact: true }).waitFor(); | |
| 63 | 新增: assert.equal(await resources.getByText("等待采样", { exact: true }).count(), 0); | |
| 64 | 新增: assert.equal(await resources.getByRole("button", { name: "重启并应用自动资源配置", exact: true }).count(), 0); | |
| 65 | 新增: resourceData = { ...resourceData, configured_memory_bytes: 0, configured_cpus: 0, pids_limit: 0, resources_verified: false, resource_error: "测试:无法核验服务器资源组限制" }; | |
| 66 | 新增: await resources.getByRole("alert").getByText("测试:无法核验服务器资源组限制", { exact: true }).waitFor(); | |
| 67 | 新增: assert.equal(await resources.getByText("0.0 GiB", { exact: true }).count(), 0, "failed verification must not render zero as a real resource limit"); | |
| 68 | 新增: assert.equal(await resources.getByText("8.0 GiB", { exact: true }).count(), 0, "failed verification must not retain a previously verified value"); | |
| 69 | 新增: assert.equal(await resources.getByText("未核验", { exact: true }).count(), 3); | |
| 70 | 新增: await page.locator("#settings-back").click(); | |
| 71 | 新增: assert.ok(nativeCalls.some((item) => item.action === "accountDevice"), "remote account must query native device capability"); | |
| 72 | 新增: assert.ok(nativeCalls.filter((item) => item.action === "accountDevice").every((item) => item.connection_id === connection), "device operations must bind to the remote generation"); | |
| 73 | 新增: assert.ok(requests.some((request) => request.url().includes("/api/browser/events?connection=" + connection)), "SSE must bind to the remote generation"); | |
| 74 | 新增: for (const request of requests.filter((request) => new URL(request.url()).pathname === "/api/projects/open")) assert.equal(request.headers()["x-cage-connection"], connection); | |
| 75 | 新增: await page.evaluate(() => window.cageNativeAction("quit")); | |
| 76 | 新增: assert.ok(nativeCalls.some((item) => item.action === "quitNow" && item.connection_id === connection)); | |
| 77 | 新增: assert.equal(state.requests.some((item) => item.path === "/account/suspend"), false); | |
| 78 | 新增: assert.equal(state.requests.some((item) => item.path === "/stop"), false); | |
| 79 | 新增: const downloadID = "de30b5c6-5460-4ebe-bdc6-343cd850ce47"; | |
| 80 | 新增: let saved = []; | |
| 81 | 新增: await page.route("**/api/input/files/desktop/requests", (route) => route.fulfill({ json: { uploads: [], downloads: [{ id: downloadID, name: "report.pdf", path: "/srv/cage/Downloads/report.pdf", state: "saved", target: "desktop" }] } })); | |
| 82 | 新增: await page.route("**/api/browser/files/saved", (route) => route.fulfill({ json: saved })); | |
| 83 | 新增: await page.reload(); | |
| 84 | 新增: await page.getByRole("button", { name: "下载文件", exact: true }).click(); | |
| 85 | 新增: const downloads = page.getByRole("dialog", { name: "下载文件" }); | |
| 86 | 新增: await downloads.getByText("已保存到云端", { exact: true }).waitFor(); | |
| 87 | 新增: assert.equal(await downloads.getByRole("button", { name: "打开文件", exact: true }).count(), 0, "cloud path must not offer a local open action"); | |
| 88 | 新增: saved = [{ id: downloadID, name: "report.pdf", path: "/tmp/cage-ui/report.pdf", instance_id: instance }]; | |
| 89 | 新增: await page.evaluate(() => window.dispatchEvent(new Event("cage-download-saved"))); | |
| 90 | 新增: await downloads.getByText("已保存到本机", { exact: true }).waitFor(); | |
| 91 | 新增: await downloads.getByRole("button", { name: "打开文件", exact: true }).click(); | |
| 92 | 新增: assert.ok(nativeCalls.some((item) => item.action === "browserDownloadAction" && item.connection_id === connection)); | |
| 93 | 新增: state.account.unlocked = false; | |
| 94 | 新增: await page.reload(); | |
| 95 | 新增: await page.getByText("账户资料保存在当前云端主机", { exact: true }).waitFor(); | |
| 96 | 新增: assert.ok(nativeCalls.filter((item) => item.action === "accountDevice").every((item) => item.connection_id === connection)); | |
| 97 | 新增: assert.deepEqual(errors, []); | |
| 98 | 新增: console.log("PASS: remote directories, client-scoped keyboard, container resource limits, HTTP/SSE/native-account generation binding, local/cloud download distinction, password fallback and quit preserving cloud tasks"); | |
| 99 | 新增:} finally { await browser.close(); } | |
| @@ -0,0 +1,54 @@ | ||
| 1 | 新增:import assert from "node:assert/strict"; | |
| 2 | 新增:import { createWorkbench } from "./workbench-fixture.mjs"; | |
| 3 | 新增: | |
| 4 | 新增:const { browser, page, state, errors } = await createWorkbench(); | |
| 5 | 新增:try { | |
| 6 | 新增: let starts = 0; | |
| 7 | 新增: await page.route("**/api/start", (route) => { | |
| 8 | 新增: starts++; | |
| 9 | 新增: state.status.job = { id: "setup-" + starts, kind: "start", running: true, message: "正在准备基础环境", | |
| 10 | 新增: setup_progress: { phase: "image", label: "下载 Debian 13 基础镜像", received: 25 * 1048576, total: 100 * 1048576 } }; | |
| 11 | 新增: return route.fulfill({ json: state.status.job }); | |
| 12 | 新增: }); | |
| 13 | 新增: await page.getByRole("button", { name: "启动 Cage 环境", exact: true }).click(); | |
| 14 | 新增: const panel = page.getByRole("region", { name: "环境安装进度" }); | |
| 15 | 新增: const bar = panel.getByRole("progressbar"); | |
| 16 | 新增: await panel.getByText("25 MiB / 100 MiB").waitFor(); | |
| 17 | 新增: assert.equal(await bar.getAttribute("aria-valuenow"), "25"); | |
| 18 | 新增: assert.equal(await panel.locator('[aria-current="step"]').textContent(), "系统镜像"); | |
| 19 | 新增: await panel.getByRole("button", { name: "操作详情" }).click(); | |
| 20 | 新增: await page.getByRole("dialog").waitFor(); | |
| 21 | 新增: await page.keyboard.press("Escape"); | |
| 22 | 新增: if (process.env.CAGE_SETUP_SCREENSHOT) await page.screenshot({ path: process.env.CAGE_SETUP_SCREENSHOT, animations: "disabled" }); | |
| 23 | 新增: state.status.job.setup_progress = { phase: "tools", label: "下载 code-server", received: 8 * 1048576 }; | |
| 24 | 新增: await panel.getByText("已接收 8 MiB").waitFor(); | |
| 25 | 新增: assert.equal(await bar.getAttribute("aria-valuenow"), null); | |
| 26 | 新增: state.status.job.setup_progress = { phase: "services", label: "正在配置浏览器与终端" }; | |
| 27 | 新增: await panel.getByRole("heading", { name: "正在配置浏览器与终端" }).waitFor(); | |
| 28 | 新增: assert.equal(await bar.getAttribute("aria-valuenow"), null); | |
| 29 | 新增: assert.equal(await panel.locator(".setup-transfer-bytes").count(), 0); | |
| 30 | 新增: await panel.getByRole("button", { name: "停止安装" }).click(); | |
| 31 | 新增: await page.getByRole("dialog").getByRole("button", { name: "取消" }).click(); | |
| 32 | 新增: assert.equal(state.requests.filter(r => r.path === "/stop").length, 0); | |
| 33 | 新增: await page.setViewportSize({ width: 600, height: 600 }); | |
| 34 | 新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false); | |
| 35 | 新增: state.status.job = { ...state.status.job, running: false, error: "下载重试次数已用尽,未完成文件已保存" }; | |
| 36 | 新增: await panel.getByRole("alert").waitFor(); | |
| 37 | 新增: assert.equal(await bar.count(), 0); | |
| 38 | 新增: await panel.getByText("可手动继续安装,已保存的下载会尝试续传。").waitFor(); | |
| 39 | 新增: assert.equal(starts, 1); | |
| 40 | 新增: await panel.getByRole("button", { name: "继续安装" }).click(); | |
| 41 | 新增: await panel.getByText("25 MiB / 100 MiB").waitFor(); | |
| 42 | 新增: assert.equal(starts, 2); | |
| 43 | 新增: state.status.job = { ...state.status.job, running: false, error: "下载再次中断,未完成文件已保存" }; | |
| 44 | 新增: await panel.getByRole("alert").waitFor(); | |
| 45 | 新增: await panel.getByRole("button", { name: "继续安装" }).click(); | |
| 46 | 新增: await panel.getByText("25 MiB / 100 MiB").waitFor(); | |
| 47 | 新增: assert.equal(starts, 3); | |
| 48 | 新增: await panel.getByRole("button", { name: "停止安装" }).click(); | |
| 49 | 新增: const stopped = page.waitForRequest("**/api/stop"); | |
| 50 | 新增: await page.getByRole("dialog").getByRole("button", { name: "停止安装" }).click(); | |
| 51 | 新增: await stopped; | |
| 52 | 新增: assert.deepEqual(errors, []); | |
| 53 | 新增: console.log("PASS: measured bytes and percent, unknown size, phase only, details, compact layout, cancel and retry."); | |
| 54 | 新增:} finally { await browser.close(); } | |
| @@ -9,7 +9,9 @@ export async function createWorkbench({ | ||
| 9 | 9 | mockWebSockets = true, |
| 10 | 10 | url, |
| 11 | 11 | nativeRequest, |
| 12 | 新增: clientRequest, | |
| 12 | 13 | startupFailure = false, |
| 14 | 新增: clientContext = { mode: "local", connection_id: "local", client_platform: "darwin", server_platform: "darwin", connection: { state: "disconnected" } }, | |
| 13 | 15 | } = {}) { |
| 14 | 16 | const engines = require( |
| 15 | 17 | process.env.CAGE_PLAYWRIGHT_MODULE || "playwright", |
| @@ -111,6 +113,8 @@ export async function createWorkbench({ | ||
| 111 | 113 | const path = new URL(request.url()).pathname.replace("/api", ""); |
| 112 | 114 | const body = request.postDataJSON(); |
| 113 | 115 | state.requests.push({ path, method: request.method(), body: path.startsWith("/account") ? undefined : body }); |
| 116 | 新增: if (clientRequest && path.startsWith("/client/")) return clientRequest(route, path, body); | |
| 117 | 新增: if (path === "/client/context") return route.fulfill({ json: clientContext }); | |
| 114 | 118 | const accountView = () => ({ ...state.account, background_running: state.status.vm_running }); |
| 115 | 119 | if (path === "/account") return route.fulfill({ json: accountView() }); |
| 116 | 120 | if (path.startsWith("/account/")) { |
| @@ -341,7 +345,7 @@ export async function createWorkbench({ | ||
| 341 | 345 | return route.fulfill({ json: result }); |
| 342 | 346 | }); |
| 343 | 347 | await page.goto(url || process.env.CAGE_UI_URL || "http://127.0.0.1:5198"); |
| 344 | 删除: if (!startupFailure) await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 348 | 新增: if (!startupFailure && clientContext.mode !== "none") await page.getByRole("heading", { name: "先启动 Cage 环境" }).waitFor(); | |
| 345 | 349 | return { browser, context, page, state, errors }; |
| 346 | 350 | } |
| 347 | 351 | |
| @@ -18,6 +18,7 @@ import { | ||
| 18 | 18 | Settings2, |
| 19 | 19 | } from "lucide-react"; |
| 20 | 20 | import { api, native, nativeAvailable } from "./api"; |
| 21 | 新增:import { isRemoteClient } from "./client-context.mjs"; | |
| 21 | 22 | import logo from "./logo.png"; |
| 22 | 23 | import "./account.css"; |
| 23 | 24 | |
| @@ -241,7 +242,7 @@ export function AccountGate({ children }) { | ||
| 241 | 242 | </div> |
| 242 | 243 | <section |
| 243 | 244 | className="account-entry" |
| 244 | 删除: aria-label={creating ? "创建本地账户" : "解锁 Cage"} | |
| 245 | 新增: aria-label={creating ? isRemoteClient() ? "创建云端账户" : "创建本地账户" : "解锁 Cage"} | |
| 245 | 246 | > |
| 246 | 247 | {creating ? ( |
| 247 | 248 | <img className="account-welcome-logo" src={logo} alt="" /> |
| @@ -257,10 +258,10 @@ export function AccountGate({ children }) { | ||
| 257 | 258 | </h1> |
| 258 | 259 | <p className="account-entry-intro"> |
| 259 | 260 | {creating |
| 260 | 删除: ? "创建一个本地账户,收好你的工作与登录状态。" | |
| 261 | 新增: ? isRemoteClient() ? "在云端创建账户,保护这台主机上的工作与登录状态。" : "创建一个本地账户,收好你的工作与登录状态。" | |
| 261 | 262 | : account |
| 262 | 263 | ? "输入密码,继续你的工作。" |
| 263 | 删除: : "正在读取本机账户…"} | |
| 264 | 新增: : isRemoteClient() ? "正在读取云端账户…" : "正在读取本机账户…"} | |
| 264 | 265 | </p> |
| 265 | 266 | {account?.background_running && ( |
| 266 | 267 | <div className="account-background"> |
| @@ -334,7 +335,7 @@ export function AccountGate({ children }) { | ||
| 334 | 335 | className="primary account-submit" |
| 335 | 336 | disabled={busy || !password || (creating && (!username.trim() || (nativeAvailable() && deviceSupport === null)))} |
| 336 | 337 | > |
| 337 | 删除: {busy ? "正在解锁…" : creating ? "创建本地账户" : "解锁 Cage"} | |
| 338 | 新增: {busy ? "正在解锁…" : creating ? isRemoteClient() ? "创建云端账户" : "创建本地账户" : "解锁 Cage"} | |
| 338 | 339 | </button> |
| 339 | 340 | </fieldset> |
| 340 | 341 | </form> |
| @@ -349,12 +350,12 @@ export function AccountGate({ children }) { | ||
| 349 | 350 | )} |
| 350 | 351 | <p className="account-local-note"> |
| 351 | 352 | <LockKeyhole size={14} /> |
| 352 | 删除: 账户资料仅保存在这台设备上 | |
| 353 | 新增: {isRemoteClient() ? "账户资料保存在当前云端主机" : "账户资料仅保存在这台设备上"} | |
| 353 | 354 | </p> |
| 354 | 355 | <p className="account-recovery-note"> |
| 355 | 356 | {creating |
| 356 | 357 | ? "密码至少 8 个字符,用于保护应用登录凭据。请妥善保存,当前不支持在线找回。" |
| 357 | 删除: : "请输入本地账户密码;当前不支持在线找回。"} | |
| 358 | 新增: : isRemoteClient() ? "请输入云端 Cage 账户密码;当前不支持在线找回。" : "请输入本地账户密码;当前不支持在线找回。"} | |
| 358 | 359 | </p> |
| 359 | 360 | </section> |
| 360 | 361 | {nativeAvailable() && ( |
| @@ -400,7 +401,7 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | ||
| 400 | 401 | if ( |
| 401 | 402 | action === "logout" && |
| 402 | 403 | !(await onConfirm({ |
| 403 | 删除: title: "退出本地账户?", | |
| 404 | 新增: title: isRemoteClient() ? "退出云端账户?" : "退出本地账户?", | |
| 404 | 405 | body: "这会停止 Cage 环境与后台任务,并锁定登录凭据。请先保存文件。", |
| 405 | 406 | confirm: "停止环境并退出账户", |
| 406 | 407 | })) |
| @@ -424,12 +425,12 @@ export function AccountMenu({ onSettings, onConfirm, onStatus, busy }) { | ||
| 424 | 425 | <AccountAvatar account={account} /> |
| 425 | 426 | <span className="account-trigger-name"> |
| 426 | 427 | <strong>{account.username}</strong> |
| 427 | 删除: <small>本地账户</small> | |
| 428 | 新增: <small>{isRemoteClient() ? "云端账户" : "本地账户"}</small> | |
| 428 | 429 | </span> |
| 429 | 430 | <ChevronDown size={15} /> |
| 430 | 431 | </button> |
| 431 | 432 | {open && ( |
| 432 | 删除: <div className="account-menu" role="menu" aria-label="本地账户菜单" | |
| 433 | 新增: <div className="account-menu" role="menu" aria-label={isRemoteClient() ? "云端账户菜单" : "本地账户菜单"} | |
| 433 | 434 | onKeyDown={(event) => { |
| 434 | 435 | if (event.key !== "ArrowDown" && event.key !== "ArrowUp") return; |
| 435 | 436 | event.preventDefault(); |
| @@ -625,8 +626,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 625 | 626 | <fieldset disabled={busy || environmentBusy}> |
| 626 | 627 | <h4>账户密码</h4> |
| 627 | 628 | <p className="field-help"> |
| 628 | 删除: 修改密码不会清除 Claude | |
| 629 | 删除: 的登录状态。密码仅用于本机解锁,没有在线找回。 | |
| 629 | 新增: 修改密码不会清除 Claude 的登录状态。{isRemoteClient() ? "密码用于解锁当前云端 Cage,没有在线找回。" : "密码仅用于本机解锁,没有在线找回。"} | |
| 630 | 630 | </p> |
| 631 | 631 | <PasswordField |
| 632 | 632 | label="当前密码" |
| @@ -658,7 +658,7 @@ export function AccountSettings({ busy: environmentBusy, onDirty }) { | ||
| 658 | 658 | <AccountDeviceSettings /> |
| 659 | 659 | <p className="account-settings-note"> |
| 660 | 660 | <LockKeyhole size={15} /> |
| 661 | 删除: 一个本地账户,一个持久工作环境。资料与凭据不上传到 Cage 服务器。 | |
| 661 | 新增: {isRemoteClient() ? "账户、应用资料与登录凭据保存在当前云端主机。" : "一个本地账户,一个持久工作环境。资料与凭据不上传到 Cage 服务器。"} | |
| 662 | 662 | </p> |
| 663 | 663 | </div> |
| 664 | 664 | ); |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { reportDiagnostic } from "./diagnostics.mjs"; |
| 2 | 新增:import { assertConnection, connectionHeaders, getClientContext } from "./client-context.mjs"; | |
| 2 | 3 | let sessionRenewal; |
| 3 | 4 | async function responseError(response) { |
| 4 | 5 | const error = new Error( |
| @@ -29,9 +30,10 @@ async function renewSession() { | ||
| 29 | 30 | return sessionRenewal; |
| 30 | 31 | } |
| 31 | 32 | export async function api(path, body, method) { |
| 33 | 新增: const connection = getClientContext().connection_id; | |
| 32 | 34 | const options = { |
| 33 | 35 | method: method || (body === undefined ? "GET" : "POST"), |
| 34 | 删除: headers: body === undefined ? {} : { "Content-Type": "application/json" }, | |
| 36 | 新增: headers: { ...connectionHeaders(path), ...(body === undefined ? {} : { "Content-Type": "application/json" }) }, | |
| 35 | 37 | body: body === undefined ? undefined : JSON.stringify(body), |
| 36 | 38 | }; |
| 37 | 39 | const send = async () => { |
| @@ -45,11 +47,15 @@ export async function api(path, body, method) { | ||
| 45 | 47 | await renewSession(); |
| 46 | 48 | response = await send(); |
| 47 | 49 | } |
| 48 | 删除: if (response.status === 423) window.dispatchEvent(new Event("cage-account-locked")); | |
| 50 | 新增: if (response.status === 423 && !path.startsWith("/client/")) window.dispatchEvent(new Event("cage-account-locked")); | |
| 49 | 51 | if (!response.ok) throw await responseError(response); |
| 50 | 删除: return response.json(); | |
| 52 | 新增: const value = await response.json(); | |
| 53 | 新增: if (path !== "/session" && !path.startsWith("/client/")) assertConnection(connection); | |
| 54 | 新增: return value; | |
| 51 | 55 | } |
| 52 | 56 | export async function uploadFile(path, file, { signal, onProgress } = {}) { |
| 57 | 新增: const headers = connectionHeaders(path); | |
| 58 | 新增: const connection = getClientContext().connection_id; | |
| 53 | 59 | const send = () => new Promise((resolve, reject) => { |
| 54 | 60 | if (signal?.aborted) { reject(new DOMException("上传已取消", "AbortError")); return; } |
| 55 | 61 | const request = new XMLHttpRequest(); |
| @@ -57,6 +63,7 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) { | ||
| 57 | 63 | const cleanup = () => signal?.removeEventListener("abort", abort); |
| 58 | 64 | request.open("POST", "/api" + path); |
| 59 | 65 | request.setRequestHeader("Content-Type", "application/octet-stream"); |
| 66 | 新增: for (const [name, value] of Object.entries(headers)) request.setRequestHeader(name, value); | |
| 60 | 67 | request.upload.onprogress = event => onProgress?.(event.loaded, event.total || file.size); |
| 61 | 68 | request.onerror = () => { cleanup(); reject(new Error("文件传递中断,请重试")); }; |
| 62 | 69 | request.onabort = () => { cleanup(); reject(new DOMException("上传已取消", "AbortError")); }; |
| @@ -67,7 +74,7 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) { | ||
| 67 | 74 | const error = new Error(request.responseText.trim() || "文件传递未完成"); |
| 68 | 75 | error.status = request.status; reject(error); return; |
| 69 | 76 | } |
| 70 | 删除: try { resolve(JSON.parse(request.responseText)); } | |
| 77 | 新增: try { assertConnection(connection); resolve(JSON.parse(request.responseText)); } | |
| 71 | 78 | catch { reject(new Error("文件传递响应无效")); } |
| 72 | 79 | }; |
| 73 | 80 | signal?.addEventListener("abort", abort, { once: true }); |
| @@ -83,11 +90,16 @@ export async function uploadFile(path, file, { signal, onProgress } = {}) { | ||
| 83 | 90 | export const nativeAvailable = () => |
| 84 | 91 | Boolean(window.webkit?.messageHandlers?.cage); |
| 85 | 92 | export async function native(action, extra = {}) { |
| 86 | 删除: if (action === "quitNow") { | |
| 93 | 新增: const connection = getClientContext().connection_id; | |
| 94 | 新增: if (action === "quitNow" && getClientContext().mode === "local" && !getClientContext().client_only) { | |
| 87 | 95 | try { await api("/account/suspend", {}); } |
| 88 | 96 | catch (error) { if (error.status !== 423) throw error; } |
| 89 | 97 | } |
| 90 | 删除: try { return await window.webkit.messageHandlers.cage.postMessage({ action, ...extra }); } | |
| 98 | 新增: try { | |
| 99 | 新增: const result = await window.webkit.messageHandlers.cage.postMessage({ action, ...extra, connection_id: connection }); | |
| 100 | 新增: assertConnection(connection); | |
| 101 | 新增: return result; | |
| 102 | 新增: } | |
| 91 | 103 | catch (error) { reportDiagnostic("frontend", error); throw error; } |
| 92 | 104 | } |
| 93 | 105 | export const readClipboard = () => |
| @@ -1,4 +1,5 @@ | ||
| 1 | 1 | import { api } from "./api"; |
| 2 | 新增:import { runtimeSocketURL } from "./client-context.mjs"; | |
| 2 | 3 | import workletURL from "./audio-worklet.js?url&no-inline"; |
| 3 | 4 | |
| 4 | 5 | export class AudioOutput { |
| @@ -83,7 +84,7 @@ export class AudioOutput { | ||
| 83 | 84 | const format = await api("/audio"); |
| 84 | 85 | if (!live()) return; |
| 85 | 86 | if (format.format !== "s16le" || format.sample_rate !== 48000 || format.channels !== 2) throw new Error("声音格式不兼容"); |
| 86 | 删除: const socket = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/audio`); | |
| 87 | 新增: const socket = new WebSocket(runtimeSocketURL("/audio")); | |
| 87 | 88 | socket.binaryType = "arraybuffer"; |
| 88 | 89 | this.socket = socket; |
| 89 | 90 | let confirmed = false; |
| @@ -2,6 +2,7 @@ import React, { useEffect, useRef, useState } from "react"; | ||
| 2 | 2 | import { createPortal } from "react-dom"; |
| 3 | 3 | import { ArrowDownToLine, CircleAlert } from "lucide-react"; |
| 4 | 4 | import { api, native, nativeAvailable } from "./api"; |
| 5 | 新增:import { isRemoteClient, runtimeURL } from "./client-context.mjs"; | |
| 5 | 6 | import { Modal } from "./views"; |
| 6 | 7 | |
| 7 | 8 | export function useDownloadNotifications( |
| @@ -68,7 +69,7 @@ export function useDesktopFiles(ready) { | ||
| 68 | 69 | async function saveDownload(item) { |
| 69 | 70 | if (!nativeAvailable()) { |
| 70 | 71 | const link = document.createElement("a"); |
| 71 | 删除: link.href = `/api/browser/files/downloads/${encodeURIComponent(item.id)}/content`; | |
| 72 | 新增: link.href = runtimeURL(`/browser/files/downloads/${encodeURIComponent(item.id)}/content`); | |
| 72 | 73 | link.download = item.name; |
| 73 | 74 | link.click(); |
| 74 | 75 | return; |
| @@ -90,6 +91,7 @@ export function BrowserDownloads({ | ||
| 90 | 91 | onStatus, |
| 91 | 92 | sidebar = false, |
| 92 | 93 | }) { |
| 94 | 新增: const remote = isRemoteClient(); | |
| 93 | 95 | const [open, setOpen] = useState(false), |
| 94 | 96 | [retrying, setRetrying] = useState(""); |
| 95 | 97 | const [saved, setSaved] = useState([]); |
| @@ -105,17 +107,17 @@ export function BrowserDownloads({ | ||
| 105 | 107 | const items = downloads.map((item) => { |
| 106 | 108 | const local = saved.find((entry) => entry.id === item.id); |
| 107 | 109 | return local |
| 108 | 删除: ? { ...item, ...local, state: "saved", retryable: false, error: "" } | |
| 110 | 新增: ? { ...item, ...local, localSaved: true, state: "saved", retryable: false, error: "" } | |
| 109 | 111 | : item; |
| 110 | 112 | }); |
| 111 | 113 | for (const item of saved) |
| 112 | 114 | if (!items.some((entry) => entry.id === item.id)) |
| 113 | 删除: items.push({ ...item, state: "saved" }); | |
| 115 | 新增: items.push({ ...item, localSaved: true, state: "saved" }); | |
| 114 | 116 | const failed = items.some((item) => item.state === "failed"); |
| 115 | 117 | const labels = { |
| 116 | 118 | downloading: "正在下载", |
| 117 | 删除: saving: "正在保存到本机", | |
| 118 | 删除: saved: "已保存到本机", | |
| 119 | 新增: saving: remote ? "正在保存到云端" : "正在保存到本机", | |
| 120 | 新增: saved: remote ? "已保存到云端" : "已保存到本机", | |
| 119 | 121 | failed: "保存失败", |
| 120 | 122 | canceled: "下载已取消", |
| 121 | 123 | }; |
| @@ -138,7 +140,7 @@ export function BrowserDownloads({ | ||
| 138 | 140 | <div className="browser-download-list"> |
| 139 | 141 | {!items.length && ( |
| 140 | 142 | <p> |
| 141 | 删除: 暂无下载。下载完成后可另存为到本机;取消时,原文件仍保留在默认工作区的 | |
| 143 | 新增: 暂无下载。下载完成后可另存为到本机;取消时,原文件仍保留在{remote ? "云端" : ""}默认工作区的 | |
| 142 | 144 | Downloads 文件夹。 |
| 143 | 145 | </p> |
| 144 | 146 | )} |
| @@ -146,12 +148,12 @@ export function BrowserDownloads({ | ||
| 146 | 148 | <article key={item.id} className="browser-download-item"> |
| 147 | 149 | <strong>{item.name}</strong> |
| 148 | 150 | <p> |
| 149 | 删除: {labels[item.state] || "状态待确认"} | |
| 151 | 新增: {item.localSaved ? "已保存到本机" : labels[item.state] || "状态待确认"} | |
| 150 | 152 | {item.state === "downloading" && |
| 151 | 153 | item.totalBytes > 0 && |
| 152 | 154 | ` · ${Math.min(100, Math.floor((item.receivedBytes / item.totalBytes) * 100))}%`} |
| 153 | 155 | </p> |
| 154 | 删除: {item.path && <p className="download-path">{item.path}</p>} | |
| 156 | 新增: {item.path && <p className="download-path">{remote ? item.localSaved ? "本机:" : "云端:" : ""}{item.path}</p>} | |
| 155 | 157 | {item.error && <p role="status">{item.error}</p>} |
| 156 | 158 | {(item.state === "saved" || (item.target !== "desktop" && item.retryable)) && ( |
| 157 | 159 | <div className="download-actions"> |
| @@ -172,6 +174,7 @@ export function BrowserDownloads({ | ||
| 172 | 174 | </button> |
| 173 | 175 | {nativeAvailable() && |
| 174 | 176 | item.state === "saved" && |
| 177 | 新增: (!remote || item.localSaved) && | |
| 175 | 178 | [ |
| 176 | 179 | ["open", "打开文件"], |
| 177 | 180 | ["reveal", "在文件夹中显示"], |
| @@ -0,0 +1,52 @@ | ||
| 1 | 新增:let current = Object.freeze({ mode: "local", connection_id: "local" }); | |
| 2 | 新增: | |
| 3 | 新增:export function setClientContext(value) { | |
| 4 | 新增: current = Object.freeze({ ...value }); | |
| 5 | 新增:} | |
| 6 | 新增: | |
| 7 | 新增:export const getClientContext = () => current; | |
| 8 | 新增:export const isRemoteClient = () => current.mode === "remote"; | |
| 9 | 新增: | |
| 10 | 新增:export function assertConnection(connectionID) { | |
| 11 | 新增: if (current.connection_id !== connectionID) { | |
| 12 | 新增: const error = new Error("工作环境已切换,请在当前环境重新操作。"); | |
| 13 | 新增: error.code = "connection_changed"; | |
| 14 | 新增: throw error; | |
| 15 | 新增: } | |
| 16 | 新增:} | |
| 17 | 新增: | |
| 18 | 新增:export function connectionHeaders(path, context = current) { | |
| 19 | 新增: if (path === "/session" || path.startsWith("/client/")) return {}; | |
| 20 | 新增: return { "X-Cage-Connection": context.connection_id || "disconnected" }; | |
| 21 | 新增:} | |
| 22 | 新增: | |
| 23 | 新增:export function runtimeURL(path, context = current) { | |
| 24 | 新增: const url = new URL("/api" + path, globalThis.location?.origin || "http://localhost"); | |
| 25 | 新增: url.searchParams.set("connection", context.connection_id || "disconnected"); | |
| 26 | 新增: return url.pathname + url.search; | |
| 27 | 新增:} | |
| 28 | 新增: | |
| 29 | 新增:export function runtimeSocketURL(path, context = current) { | |
| 30 | 新增: return `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}${runtimeURL(path, context)}`; | |
| 31 | 新增:} | |
| 32 | 新增: | |
| 33 | 新增:export function clientStorageKey(key, context = current) { | |
| 34 | 新增: return context.mode === "remote" | |
| 35 | 新增: ? `${key}:remote:${context.instance_id || context.host_id || "disconnected"}` | |
| 36 | 新增: : key; | |
| 37 | 新增:} | |
| 38 | 新增: | |
| 39 | 新增:export function clientKeyboard(serverKeyboard, context = current) { | |
| 40 | 新增: if (context.mode !== "remote") return serverKeyboard; | |
| 41 | 新增: try { | |
| 42 | 新增: const saved = localStorage.getItem(clientStorageKey("cage-keyboard", context)); | |
| 43 | 新增: if (["mac", "native"].includes(saved)) return saved; | |
| 44 | 新增: } catch { /* The client platform remains a usable default without storage. */ } | |
| 45 | 新增: return context.client_platform === "darwin" ? "mac" : "native"; | |
| 46 | 新增:} | |
| 47 | 新增: | |
| 48 | 新增:export function saveClientKeyboard(value) { | |
| 49 | 新增: if (!["mac", "native"].includes(value)) throw new Error("键盘习惯无效"); | |
| 50 | 新增: localStorage.setItem(clientStorageKey("cage-keyboard"), value); | |
| 51 | 新增: window.dispatchEvent(new Event("cage-client-preferences")); | |
| 52 | 新增:} | |
| @@ -0,0 +1,92 @@ | ||
| 1 | 新增:import test from "node:test"; | |
| 2 | 新增:import assert from "node:assert/strict"; | |
| 3 | 新增:import { api, native } from "./api.js"; | |
| 4 | 新增:import { clientKeyboard, clientStorageKey, runtimeURL, setClientContext } from "./client-context.mjs"; | |
| 5 | 新增: | |
| 6 | 新增:function environment(t) { | |
| 7 | 新增: const saved = { fetch: globalThis.fetch, window: globalThis.window, location: globalThis.location }; | |
| 8 | 新增: globalThis.location = new URL("http://localhost:17777/"); | |
| 9 | 新增: globalThis.window = { webkit: { messageHandlers: { cage: { postMessage: async () => true } } } }; | |
| 10 | 新增: setClientContext({ mode: "remote", connection_id: "first", instance_id: "instance-one" }); | |
| 11 | 新增: t.after(() => { | |
| 12 | 新增: setClientContext({ mode: "local", connection_id: "local" }); | |
| 13 | 新增: for (const [key, value] of Object.entries(saved)) { | |
| 14 | 新增: if (value === undefined) delete globalThis[key]; else globalThis[key] = value; | |
| 15 | 新增: } | |
| 16 | 新增: }); | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:test("an old API result cannot continue an action in a new remote environment", async (t) => { | |
| 20 | 新增: environment(t); | |
| 21 | 新增: let release; | |
| 22 | 新增: globalThis.fetch = (path, options) => { | |
| 23 | 新增: assert.equal(path, "/api/input/files/create"); | |
| 24 | 新增: assert.equal(options.headers["X-Cage-Connection"], "first"); | |
| 25 | 新增: return new Promise((resolve) => { release = resolve; }); | |
| 26 | 新增: }; | |
| 27 | 新增: const pending = api("/input/files/create", { target: "browser" }); | |
| 28 | 新增: setClientContext({ mode: "remote", connection_id: "second", instance_id: "instance-two" }); | |
| 29 | 新增: release(new Response(JSON.stringify({ id: "old-upload" }))); | |
| 30 | 新增: await assert.rejects(pending, (error) => error.code === "connection_changed"); | |
| 31 | 新增:}); | |
| 32 | 新增: | |
| 33 | 新增:test("a native picker finishing after a host switch cannot yield an upload handle", async (t) => { | |
| 34 | 新增: environment(t); | |
| 35 | 新增: let release; | |
| 36 | 新增: window.webkit.messageHandlers.cage.postMessage = (request) => { | |
| 37 | 新增: assert.equal(request.connection_id, "first"); | |
| 38 | 新增: return new Promise((resolve) => { release = resolve; }); | |
| 39 | 新增: }; | |
| 40 | 新增: const pending = native("chooseUploadFiles", { multiple: true }); | |
| 41 | 新增: setClientContext({ mode: "remote", connection_id: "second" }); | |
| 42 | 新增: release({ fileSelection: "old-file-handle", count: 1 }); | |
| 43 | 新增: await assert.rejects(pending, (error) => error.code === "connection_changed"); | |
| 44 | 新增:}); | |
| 45 | 新增: | |
| 46 | 新增:test("quitting a remote client never suspends the cloud account", async (t) => { | |
| 47 | 新增: environment(t); | |
| 48 | 新增: globalThis.fetch = () => { throw new Error("quit must not call a runtime API"); }; | |
| 49 | 新增: let request; | |
| 50 | 新增: window.webkit.messageHandlers.cage.postMessage = async (value) => { request = value; return true; }; | |
| 51 | 新增: await native("quitNow"); | |
| 52 | 新增: assert.deepEqual(request, { action: "quitNow", connection_id: "first" }); | |
| 53 | 新增:}); | |
| 54 | 新增: | |
| 55 | 新增:test("an account device operation retains its host generation and rejects a late result", async (t) => { | |
| 56 | 新增: environment(t); | |
| 57 | 新增: let release; | |
| 58 | 新增: window.webkit.messageHandlers.cage.postMessage = (request) => { | |
| 59 | 新增: assert.deepEqual(request, { action: "accountDevice", operation: "unlock", kind: "automatic", connection_id: "first" }); | |
| 60 | 新增: return new Promise((resolve) => { release = resolve; }); | |
| 61 | 新增: }; | |
| 62 | 新增: const pending = native("accountDevice", { operation: "unlock", kind: "automatic" }); | |
| 63 | 新增: setClientContext({ mode: "remote", connection_id: "second" }); | |
| 64 | 新增: release({ unlocked: true }); | |
| 65 | 新增: await assert.rejects(pending, (error) => error.code === "connection_changed"); | |
| 66 | 新增:}); | |
| 67 | 新增: | |
| 68 | 新增:test("stream URLs carry the generation while layout follows the persistent instance", (t) => { | |
| 69 | 新增: environment(t); | |
| 70 | 新增: assert.equal(runtimeURL("/browser/events?after=1"), "/api/browser/events?after=1&connection=first"); | |
| 71 | 新增: const key = clientStorageKey("cage-tab-layout"); | |
| 72 | 新增: setClientContext({ mode: "remote", connection_id: "reconnected", instance_id: "instance-one" }); | |
| 73 | 新增: assert.equal(clientStorageKey("cage-tab-layout"), key); | |
| 74 | 新增: setClientContext({ mode: "remote", connection_id: "other", instance_id: "instance-two" }); | |
| 75 | 新增: assert.notEqual(clientStorageKey("cage-tab-layout"), key); | |
| 76 | 新增:}); | |
| 77 | 新增: | |
| 78 | 新增:test("remote keyboard defaults follow the client and a saved choice does not alter server settings", (t) => { | |
| 79 | 新增: environment(t); | |
| 80 | 新增: const previous = globalThis.localStorage; | |
| 81 | 新增: const values = new Map(); | |
| 82 | 新增: globalThis.localStorage = { getItem: (key) => values.get(key) ?? null }; | |
| 83 | 新增: t.after(() => { if (previous === undefined) delete globalThis.localStorage; else globalThis.localStorage = previous; }); | |
| 84 | 新增: const mac = { mode: "remote", client_platform: "darwin", instance_id: "linux-server" }; | |
| 85 | 新增: const windows = { mode: "remote", client_platform: "windows", instance_id: "linux-server" }; | |
| 86 | 新增: assert.equal(clientKeyboard("native", mac), "mac"); | |
| 87 | 新增: assert.equal(clientKeyboard("mac", windows), "native"); | |
| 88 | 新增: values.set(clientStorageKey("cage-keyboard", mac), "native"); | |
| 89 | 新增: assert.equal(clientKeyboard("mac", mac), "native"); | |
| 90 | 新增: assert.equal(clientKeyboard("native", { ...mac, instance_id: "other-server" }), "mac"); | |
| 91 | 新增: assert.equal(clientKeyboard("native", { mode: "local", client_platform: "darwin" }), "native"); | |
| 92 | 新增:}); | |
| @@ -0,0 +1,29 @@ | ||
| 1 | 新增:import React, { lazy, Suspense } from "react"; | |
| 2 | 新增:import { createRoot } from "react-dom/client"; | |
| 3 | 新增:import { installDiagnostics } from "./diagnostics.mjs"; | |
| 4 | 新增:import { DiagnosticBoundary } from "./diagnostics.jsx"; | |
| 5 | 新增:import { ClientRoot } from "./remote-hosts"; | |
| 6 | 新增:import "./style.css"; | |
| 7 | 新增: | |
| 8 | 新增:const Workbench = lazy(() => import("./main.jsx")); | |
| 9 | 新增: | |
| 10 | 新增:installDiagnostics(); | |
| 11 | 新增:createRoot(document.getElementById("root")).render( | |
| 12 | 新增: <DiagnosticBoundary> | |
| 13 | 新增: <ClientRoot> | |
| 14 | 新增: <Suspense | |
| 15 | 新增: fallback={ | |
| 16 | 新增: <div className="client-loading" role="status"> | |
| 17 | 新增: 正在打开工作台… | |
| 18 | 新增: </div> | |
| 19 | 新增: } | |
| 20 | 新增: > | |
| 21 | 新增: <Workbench /> | |
| 22 | 新增: </Suspense> | |
| 23 | 新增: </ClientRoot> | |
| 24 | 新增: </DiagnosticBoundary>, | |
| 25 | 新增:); | |
| 26 | 新增: | |
| 27 | 新增:window.addEventListener("hashchange", () => { | |
| 28 | 新增: if (location.hash) location.reload(); | |
| 29 | 新增:}); | |
| @@ -2,8 +2,10 @@ import React, { useEffect, useState } from "react"; | ||
| 2 | 2 | import { ArrowDownToLine, LoaderCircle } from "lucide-react"; |
| 3 | 3 | import { api, native, nativeAvailable } from "./api"; |
| 4 | 4 | import { reportDiagnostic } from "./diagnostics.mjs"; |
| 5 | 新增:import { isRemoteClient, runtimeURL } from "./client-context.mjs"; | |
| 5 | 6 | |
| 6 | 7 | export function DiagnosticSettings() { |
| 8 | 新增: const remote = isRemoteClient(); | |
| 7 | 9 | const [info, setInfo] = useState(null); |
| 8 | 10 | const [busy, setBusy] = useState(false); |
| 9 | 11 | const [notice, setNotice] = useState(""); |
| @@ -22,7 +24,7 @@ export function DiagnosticSettings() { | ||
| 22 | 24 | if (!result?.canceled) setNotice("诊断包已保存。分享前请检查其中内容。"); |
| 23 | 25 | } else { |
| 24 | 26 | // Fetch before downloading so authentication or disk failures are shown. |
| 25 | 删除: const response = await fetch("/api/diagnostics/export"); | |
| 27 | 新增: const response = await fetch(runtimeURL("/diagnostics/export")); | |
| 26 | 28 | if (!response.ok) throw new Error((await response.text()).trim() || "诊断包导出失败"); |
| 27 | 29 | if (!response.headers.get("content-type")?.startsWith("application/zip")) throw new Error("当前后台不支持诊断导出,请重新打开 Cage"); |
| 28 | 30 | const url = URL.createObjectURL(await response.blob()); |
| @@ -35,13 +37,13 @@ export function DiagnosticSettings() { | ||
| 35 | 37 | }; |
| 36 | 38 | return <section className="settings-group" aria-label="日志与诊断"> |
| 37 | 39 | <h3>日志与诊断</h3> |
| 38 | 删除: <p className="footnote">自动记录应用故障并脱敏,保留 14 天,容量预算 50 MiB(本机上限 40 MiB、环境服务预算 10 MiB)。不收集终端内容、项目文件或完整配置。</p> | |
| 39 | 删除: {info && <p className="footnote">本机日志 {(info.bytes / 1024 / 1024).toFixed(1)} MiB · {info.files} 个文件</p>} | |
| 40 | 新增: <p className="footnote">自动记录应用故障并脱敏,保留 14 天,容量预算 50 MiB({remote ? "服务器" : "本机"}上限 40 MiB、环境服务预算 10 MiB)。不收集终端内容、项目文件或完整配置。</p> | |
| 41 | 新增: {info && <p className="footnote">{remote ? "服务器" : "本机"}日志 {(info.bytes / 1024 / 1024).toFixed(1)} MiB · {info.files} 个文件</p>} | |
| 40 | 42 | <button className="secondary-button" disabled={busy} onClick={save}> |
| 41 | 43 | {busy ? <LoaderCircle size={14} className="spin" /> : <ArrowDownToLine size={14} />} |
| 42 | 删除: {busy ? "正在导出…" : "导出诊断包"} | |
| 44 | 新增: {busy ? "正在导出…" : remote ? "导出服务器诊断包" : "导出诊断包"} | |
| 43 | 45 | </button> |
| 44 | 删除: <p className="footnote">诊断包包含脱敏日志、版本和收集状态;环境离线时仍可导出本机记录。只保存在你选择的位置。</p> | |
| 46 | 新增: <p className="footnote">{remote ? "诊断包包含当前云端主机的脱敏日志、版本和收集状态,需要保持远程连接。导出后保存在你选择的本机位置。" : "诊断包包含脱敏日志、版本和收集状态;环境离线时仍可导出本机记录。只保存在你选择的位置。"}</p> | |
| 45 | 47 | {notice && <p role="status">{notice}</p>} |
| 46 | 48 | {error && <p role="alert" className="error-message">{error}</p>} |
| 47 | 49 | </section>; |
| @@ -0,0 +1,75 @@ | ||
| 1 | 新增:import React, { useEffect, useState } from "react"; | |
| 2 | 新增:import { FolderOpen } from "lucide-react"; | |
| 3 | 新增:import { api, native, nativeAvailable } from "./api"; | |
| 4 | 新增: | |
| 5 | 新增:export function EnvironmentStorage({ status, onConfirm }) { | |
| 6 | 新增: const [location, setLocation] = useState(null); | |
| 7 | 新增: const [pending, setPending] = useState(null); | |
| 8 | 新增: const [directory, setDirectory] = useState(""); | |
| 9 | 新增: const [submitting, setSubmitting] = useState(false); | |
| 10 | 新增: const [error, setError] = useState(""); | |
| 11 | 新增: const job = status.job; | |
| 12 | 新增: const busy = submitting || Boolean(pending) || Boolean(job?.running); | |
| 13 | 新增: useEffect(() => { | |
| 14 | 新增: let live = true; | |
| 15 | 新增: if (pending && job?.id === pending.previousJob) return; | |
| 16 | 新增: if (job?.kind === "storage" && job.running) return; | |
| 17 | 新增: api("/environment/storage").then((next) => { | |
| 18 | 新增: if (!live) return; | |
| 19 | 新增: setLocation(next); | |
| 20 | 新增: if (pending) { | |
| 21 | 新增: setPending(null); | |
| 22 | 新增: if (job?.id === pending.id && job.error) setError(job.error); | |
| 23 | 新增: else if (job?.id === pending.id || next.directory === pending.path) { setDirectory(""); setError(""); } | |
| 24 | 新增: else setError("操作已结束,请核对当前环境目录后重试。"); | |
| 25 | 新增: } | |
| 26 | 新增: }).catch((e) => { | |
| 27 | 新增: if (live) { setError(e.message); setPending(null); } | |
| 28 | 新增: }); | |
| 29 | 新增: return () => { live = false; }; | |
| 30 | 新增: }, [pending, job?.id, job?.running]); | |
| 31 | 新增: | |
| 32 | 新增: const choose = async () => { | |
| 33 | 新增: setError(""); | |
| 34 | 新增: try { | |
| 35 | 新增: const selected = await native("chooseFolder", { purpose: "environmentStorage" }); | |
| 36 | 新增: if (selected) setDirectory(selected); | |
| 37 | 新增: } catch { setError("未能选择文件夹,请直接填写绝对路径。"); } | |
| 38 | 新增: }; | |
| 39 | 新增: const apply = async () => { | |
| 40 | 新增: if (!location || busy) return; | |
| 41 | 新增: const path = directory.trim(); | |
| 42 | 新增: if (location.has_environment && !(await onConfirm({ | |
| 43 | 新增: title: "迁移本机环境?", | |
| 44 | 新增: body: `请先保存文件。Cage 会停止环境和终端,将虚拟磁盘复制到 ${path},校验后再切换位置。原数据保留为备份,迁移完成后可手动启动环境。`, | |
| 45 | 新增: confirm: "迁移环境", | |
| 46 | 新增: }))) return; | |
| 47 | 新增: setSubmitting(true); | |
| 48 | 新增: setError(""); | |
| 49 | 新增: try { | |
| 50 | 新增: const accepted = await api("/environment/storage", { | |
| 51 | 新增: directory: path, previous: location.directory, migrate: location.has_environment, | |
| 52 | 新增: }); | |
| 53 | 新增: setPending({ id: accepted.id, previousJob: job?.id, path }); | |
| 54 | 新增: } catch (e) { setError(e.message); } | |
| 55 | 新增: finally { setSubmitting(false); } | |
| 56 | 新增: }; | |
| 57 | 新增: return <section className="environment-versions environment-storage" aria-label="本机环境存储"> | |
| 58 | 新增: <h4>本机环境存储</h4> | |
| 59 | 新增: <p className="field-help">Linux 镜像、下载缓存和虚拟磁盘可以放在另一块本地磁盘。项目文件保存在各自的项目文件夹。</p> | |
| 60 | 新增: <div className="setting-summary-row"><span>当前环境目录</span><strong>{location?.directory || "正在读取…"}</strong></div> | |
| 61 | 新增: {location?.backup && <p className="field-help">迁移前的备份保存在 <code>{location.backup}</code>。确认新环境能正常启动、文件和登录状态齐全后,可自行清理备份。</p>} | |
| 62 | 新增: <label>新存储位置 | |
| 63 | 新增: <input value={directory} onChange={(e) => { setDirectory(e.target.value); setError(""); }} spellCheck="false" | |
| 64 | 新增: disabled={busy || !location} placeholder="本地磁盘上专用空文件夹的完整路径" /> | |
| 65 | 新增: </label> | |
| 66 | 新增: <div className="storage-actions"> | |
| 67 | 新增: {nativeAvailable() && <button type="button" disabled={busy || !location} onClick={choose}><FolderOpen size={15} />选择文件夹</button>} | |
| 68 | 新增: <button type="button" disabled={busy || !location || !directory.trim() || directory.trim() === location.directory} onClick={apply}> | |
| 69 | 新增: {location?.has_environment ? "迁移到此位置" : "使用此位置"} | |
| 70 | 新增: </button> | |
| 71 | 新增: </div> | |
| 72 | 新增: {job?.kind === "storage" && job.running && <p role="status" className="field-help">{job.message}</p>} | |
| 73 | 新增: {error && <p role="alert" className="error-message">{error}</p>} | |
| 74 | 新增: </section>; | |
| 75 | 新增:} | |
| @@ -1,9 +1,11 @@ | ||
| 1 | 1 | import React, { useEffect, useRef, useState } from "react"; |
| 2 | 2 | import { LoaderCircle, ShieldCheck } from "lucide-react"; |
| 3 | 3 | import { api } from "./api"; |
| 4 | 新增:import { isRemoteClient } from "./client-context.mjs"; | |
| 4 | 5 | import { Modal } from "./views"; |
| 5 | 6 | |
| 6 | 7 | export function HostGitPreparation({ onClose, onReady }) { |
| 8 | 新增: const machine = isRemoteClient() ? "云端主机" : "本机"; | |
| 7 | 9 | const [state, setState] = useState(null); |
| 8 | 10 | const [busy, setBusy] = useState(true); |
| 9 | 11 | const [error, setError] = useState(""); |
| @@ -36,7 +38,7 @@ export function HostGitPreparation({ onClose, onReady }) { | ||
| 36 | 38 | if (!state && !error) return null; |
| 37 | 39 | return ( |
| 38 | 40 | <Modal |
| 39 | 删除: title="启动前,保护本机 Git" | |
| 41 | 新增: title={`启动前,保护${machine} Git`} | |
| 40 | 42 | onClose={busy ? undefined : onClose} |
| 41 | 43 | footer={ |
| 42 | 44 | <> |
| @@ -65,25 +67,25 @@ export function HostGitPreparation({ onClose, onReady }) { | ||
| 65 | 67 | > |
| 66 | 68 | <div className="modal-body host-git-preparation"> |
| 67 | 69 | {busy && !state ? ( |
| 68 | 删除: <p role="status">正在检查本机 Git,尚未修改任何设置…</p> | |
| 70 | 新增: <p role="status">正在检查{machine} Git,尚未修改任何设置…</p> | |
| 69 | 71 | ) : ( |
| 70 | 72 | <> |
| 71 | 73 | <p>{state?.message}</p> |
| 72 | 74 | {state?.can_enable && ( |
| 73 | 75 | <> |
| 74 | 76 | <p> |
| 75 | 删除: Claude 可以修改共享文件。启用这项保护后,本机 Git | |
| 76 | 删除: 会忽略未经你明确指定的裸仓库,避免共享目录里的配置在本机 | |
| 77 | 新增: Claude 可以修改共享文件。启用这项保护后,{machine} Git | |
| 78 | 新增: 会忽略未经你明确指定的裸仓库,避免共享目录里的配置在{machine} | |
| 77 | 79 | 上执行命令。 |
| 78 | 80 | </p> |
| 79 | 81 | <p> |
| 80 | 删除: 点击“启用保护并继续”将修改本机当前用户的一项全局 Git 设置: | |
| 82 | 新增: 点击“启用保护并继续”将修改{machine}当前用户的一项全局 Git 设置: | |
| 81 | 83 | </p> |
| 82 | 84 | <pre>git config --global safe.bareRepository explicit</pre> |
| 83 | 85 | <p> |
| 84 | 86 | 普通的 <code>.git</code>{" "} |
| 85 | 87 | 项目、提交记录和远程地址保持不变。使用裸仓库时,需要通过{" "} |
| 86 | 删除: <code>--git-dir</code> 明确指定。设置会影响本机其他使用 Git | |
| 88 | 新增: <code>--git-dir</code> 明确指定。设置会影响{machine}其他使用 Git | |
| 87 | 89 | 的工具。 |
| 88 | 90 | </p> |
| 89 | 91 | </> |
| @@ -1,9 +1,6 @@ | ||
| 1 | 删除:import { installDiagnostics } from "./diagnostics.mjs"; | |
| 2 | 删除:import { DiagnosticBoundary } from "./diagnostics.jsx"; | |
| 3 | 1 | import { shortcut, primaryModifier } from "./platform.mjs"; |
| 4 | 2 | import logo from "./logo.png"; |
| 5 | 3 | import React, { useEffect, useRef, useState } from "react"; |
| 6 | 删除:import { createRoot } from "react-dom/client"; | |
| 7 | 4 | import { |
| 8 | 5 | Clock3, |
| 9 | 6 | FileCode2, |
| @@ -19,9 +16,11 @@ import { | ||
| 19 | 16 | X, |
| 20 | 17 | } from "lucide-react"; |
| 21 | 18 | import { api, normalizeURL, native, nativeAvailable } from "./api"; |
| 19 | 新增:import { clientKeyboard, clientStorageKey, isRemoteClient, runtimeURL } from "./client-context.mjs"; | |
| 22 | 20 | import { RemoteView, TerminalView, Modal } from "./views"; |
| 23 | 21 | import { usePasswordVault } from "./password-vault"; |
| 24 | 22 | import { SettingsPanel } from "./settings"; |
| 23 | 新增:import { SetupProgress } from "./setup-progress"; | |
| 25 | 24 | import { AppearanceProvider } from "./appearance"; |
| 26 | 25 | import { EnvironmentShield } from "./environment-shield"; |
| 27 | 26 | import { WorkspaceSidebar } from "./workspace-sidebar"; |
| @@ -49,11 +48,16 @@ import { HostGitPreparation } from "./host-git"; | ||
| 49 | 48 | import { NetworkLatency } from "./network-latency"; |
| 50 | 49 | import { useWindowVisibility } from "./window-visibility"; |
| 51 | 50 | import { AppUpdateButton, useAppUpdates } from "./app-updates"; |
| 52 | 删除:import "./style.css"; | |
| 53 | 51 | import "./appearance.css"; |
| 54 | 52 | import { stopAndExit } from "./quit"; |
| 55 | 53 | |
| 56 | 54 | function App() { |
| 55 | 新增: const [, refreshClientPreferences] = useState(0); | |
| 56 | 新增: useEffect(() => { | |
| 57 | 新增: const refresh = () => refreshClientPreferences((value) => value + 1); | |
| 58 | 新增: window.addEventListener("cage-client-preferences", refresh); | |
| 59 | 新增: return () => window.removeEventListener("cage-client-preferences", refresh); | |
| 60 | 新增: }, []); | |
| 57 | 61 | const claudeProfiles = useClaudeAccounts(); |
| 58 | 62 | const [desktopOpen, setDesktopOpen] = useState(false); |
| 59 | 63 | const [terminalChoice, setTerminalChoice] = useState(null); |
| @@ -67,7 +71,7 @@ function App() { | ||
| 67 | 71 | [settings, setSettings] = useState(null), |
| 68 | 72 | [proxy, setProxy] = useState(null), |
| 69 | 73 | [tabs, setTabs] = useState([]), |
| 70 | 删除: [layout, setLayout] = useState(() => ({ active: localStorage.getItem("cage-active") || "" })), | |
| 74 | 新增: [layout, setLayout] = useState(() => ({ active: localStorage.getItem(clientStorageKey("cage-active")) || "" })), | |
| 71 | 75 | [browser, setBrowser] = useState({ tabs: [] }), |
| 72 | 76 | [settingsOpen, setSettingsOpen] = useState(false), |
| 73 | 77 | [hostGitOpen, setHostGitOpen] = useState(false), |
| @@ -75,10 +79,10 @@ function App() { | ||
| 75 | 79 | [settingsSection, setSettingsSection] = useState("keyboard"), |
| 76 | 80 | [home, setHome] = useState(true), |
| 77 | 81 | [sidebarCollapsed, setSidebarCollapsed] = useState( |
| 78 | 删除: readLocal("cage-sidebar-collapsed", false), | |
| 82 | 新增: readLocal(clientStorageKey("cage-sidebar-collapsed"), false), | |
| 79 | 83 | ), |
| 80 | 84 | [selectedProject, setSelectedProject] = useState(""), |
| 81 | 删除: [savedTabs, setSavedTabs] = useState(readLocal("cage-tab-layout", {})), | |
| 85 | 新增: [savedTabs, setSavedTabs] = useState(readLocal(clientStorageKey("cage-tab-layout"), {})), | |
| 82 | 86 | [projectDialog, setProjectDialog] = useState(null), |
| 83 | 87 | [rename, setRename] = useState(null), |
| 84 | 88 | [toast, setToast] = useState(""), |
| @@ -90,10 +94,11 @@ function App() { | ||
| 90 | 94 | [safetyOpen, setSafetyOpen] = useState(false), |
| 91 | 95 | [quitting, setQuitting] = useState(null); |
| 92 | 96 | // Keep feedback continuous until polling observes the accepted start job. |
| 93 | 删除: const status = serverStatus && (hostGitOpen || startRequest) | |
| 94 | 删除: ? { ...serverStatus, job: { running: true, kind: "start", message: hostGitOpen | |
| 95 | 删除: ? "正在检查本机 Git 安全保护…" : "正在启动 Cage 环境…" } } | |
| 96 | 删除: : serverStatus; | |
| 97 | 新增: const clientStatus = serverStatus && { ...serverStatus, keyboard: clientKeyboard(serverStatus.keyboard) }; | |
| 98 | 新增: const status = clientStatus && (hostGitOpen || startRequest) | |
| 99 | 新增: ? { ...clientStatus, job: { running: true, kind: "start", message: hostGitOpen | |
| 100 | 新增: ? isRemoteClient() ? "正在检查云端主机 Git 安全保护…" : "正在检查本机 Git 安全保护…" : "正在启动 Cage 环境…" } } | |
| 101 | 新增: : clientStatus; | |
| 97 | 102 | const { active } = layout; |
| 98 | 103 | const setActive = id => setLayout(previous => focusTab(previous, id)); |
| 99 | 104 | const workspaceBox = useRef(null); |
| @@ -117,6 +122,7 @@ function App() { | ||
| 117 | 122 | terminal = !desktopOpen && current?.kind === "terminal", |
| 118 | 123 | busy = Boolean(status?.job?.running), |
| 119 | 124 | showHome = !desktopOpen && (home || !status?.vm_running || !current); |
| 125 | 新增: const setupProgress = status?.job?.setup_progress && (busy || status.job.error); | |
| 120 | 126 | const other = tabs.find(tab => tab.id === layout.other); |
| 121 | 127 | const split = Boolean(other && current && !showHome && !desktopOpen); |
| 122 | 128 | const panes = !split ? [current].filter(Boolean) |
| @@ -231,7 +237,7 @@ function App() { | ||
| 231 | 237 | setDesktopOpen(false); |
| 232 | 238 | setHome(false); |
| 233 | 239 | setActive(id); |
| 234 | 删除: localStorage.setItem("cage-active", id); | |
| 240 | 新增: localStorage.setItem(clientStorageKey("cage-active"), id); | |
| 235 | 241 | const tab = tabs.find((t) => t.id === id); |
| 236 | 242 | if (tab?.kind === "terminal") setSelectedProject(tab.workspace); |
| 237 | 243 | if (tab && tab.kind !== "terminal") { |
| @@ -428,9 +434,9 @@ function App() { | ||
| 428 | 434 | const stop = async () => { |
| 429 | 435 | if ( |
| 430 | 436 | await confirm({ |
| 431 | 删除: title: "停止当前环境?", | |
| 432 | 删除: body: "请先保存文件。当前终端会话会结束,浏览器登录和项目文件会保留。", | |
| 433 | 删除: confirm: "停止环境", | |
| 437 | 新增: title: setupProgress ? "停止安装环境?" : "停止当前环境?", | |
| 438 | 新增: body: setupProgress ? "当前安装任务会停止。下次启动环境时可以继续安装。" : "请先保存文件。当前终端会话会结束,浏览器登录和项目文件会保留。", | |
| 439 | 新增: confirm: setupProgress ? "停止安装" : "停止环境", | |
| 434 | 440 | }) |
| 435 | 441 | ) |
| 436 | 442 | await action("/stop"); |
| @@ -586,7 +592,7 @@ function App() { | ||
| 586 | 592 | }, [settings, status, fatal, connectionError]); |
| 587 | 593 | useEffect(() => { |
| 588 | 594 | if (!status?.ready) return; |
| 589 | 删除: const stream = new EventSource("/api/browser/events"); | |
| 595 | 新增: const stream = new EventSource(runtimeURL("/browser/events")); | |
| 590 | 596 | stream.addEventListener("clipboard", (event) => { |
| 591 | 597 | remote.current?.receiveCopy(JSON.parse(event.data)); |
| 592 | 598 | }); |
| @@ -642,7 +648,7 @@ function App() { | ||
| 642 | 648 | (current?.title && current.title !== "新标签页" |
| 643 | 649 | ? current.title + " · " |
| 644 | 650 | : "") + "Cage"; |
| 645 | 删除: if (active) localStorage.setItem("cage-active", active); | |
| 651 | 新增: if (active) localStorage.setItem(clientStorageKey("cage-active"), active); | |
| 646 | 652 | }, [current?.url, current?.title, active]); |
| 647 | 653 | useEffect(() => { |
| 648 | 654 | if (!toast) return; |
| @@ -651,7 +657,7 @@ function App() { | ||
| 651 | 657 | }, [toast]); |
| 652 | 658 | useEffect(() => { |
| 653 | 659 | const key = (event) => { |
| 654 | 删除: if (!primaryModifier(event)) return; | |
| 660 | 新增: if (document.querySelector("[data-environment-dialog]") || !primaryModifier(event)) return; | |
| 655 | 661 | const k = event.key.toLowerCase(); |
| 656 | 662 | if (document.querySelector("[data-browser-dialog]")) { |
| 657 | 663 | if (k === "w") { |
| @@ -759,6 +765,10 @@ function App() { | ||
| 759 | 765 | return remote.current?.edit(command) || false; |
| 760 | 766 | }; |
| 761 | 767 | window.cageNativeAction = async (command) => { |
| 768 | 新增: if (document.querySelector("[data-environment-dialog]")) { | |
| 769 | 新增: if (command === "closeTab") document.dispatchEvent(new Event("cage-close-modal")); | |
| 770 | 新增: return; | |
| 771 | 新增: } | |
| 762 | 772 | if (hostGitOpen && command !== "quit") { |
| 763 | 773 | if (command === "closeTab") |
| 764 | 774 | document.dispatchEvent(new Event("cage-close-modal")); |
| @@ -812,6 +822,10 @@ function App() { | ||
| 812 | 822 | } |
| 813 | 823 | if (command === "quit") { |
| 814 | 824 | if (quitAfterStop.current) return; |
| 825 | 新增: if (isRemoteClient()) { | |
| 826 | 新增: await native("quitNow"); | |
| 827 | 新增: return; | |
| 828 | 新增: } | |
| 815 | 829 | if (status && !connectionError && !status.vm_running && !busy) { |
| 816 | 830 | await native("quitNow"); |
| 817 | 831 | return; |
| @@ -882,7 +896,7 @@ function App() { | ||
| 882 | 896 | }); |
| 883 | 897 | const persist = (key, value, setter) => { |
| 884 | 898 | try { |
| 885 | 删除: localStorage.setItem(key, JSON.stringify(value)); | |
| 899 | 新增: localStorage.setItem(clientStorageKey(key), JSON.stringify(value)); | |
| 886 | 900 | setter(value); |
| 887 | 901 | } catch { |
| 888 | 902 | notify("未能保存界面偏好,请检查本地存储空间。"); |
| @@ -1215,10 +1229,17 @@ function App() { | ||
| 1215 | 1229 | <div className="welcome"> |
| 1216 | 1230 | <div className="welcome-content"> |
| 1217 | 1231 | <img className="welcome-logo" src={logo} alt="Cage" /> |
| 1232 | 新增: {setupProgress ? <> | |
| 1233 | 新增: <h1>{status.job.error ? "环境安装未完成" : "正在安装 Cage 环境"}</h1> | |
| 1234 | 新增: <SetupProgress job={status.job} onDetails={() => setDetails(true)} | |
| 1235 | 新增: onStop={stop} onRetry={() => setHostGitOpen(true)} disconnected={Boolean(connectionError)} /> | |
| 1236 | 新增: </> : <> | |
| 1218 | 1237 | <h1> |
| 1219 | 1238 | {busy |
| 1220 | 1239 | ? status.job.kind === "stop" |
| 1221 | 1240 | ? "正在停止 Cage 环境" |
| 1241 | 新增: : status.job.kind === "storage" | |
| 1242 | 新增: ? "正在调整环境存储" | |
| 1222 | 1243 | : status.job.kind === "project" |
| 1223 | 1244 | ? "正在打开项目" |
| 1224 | 1245 | : "正在准备 Cage 环境" |
| @@ -1279,6 +1300,7 @@ function App() { | ||
| 1279 | 1300 | </small> |
| 1280 | 1301 | </span> |
| 1281 | 1302 | </div> |
| 1303 | 新增: {!running && status.local_vm_storage && !isRemoteClient() && <button className="storage-entry text-button" disabled={busy} onClick={() => openSettings("project")}>选择环境存储位置</button>} | |
| 1282 | 1304 | <div className="start-project-footer"> |
| 1283 | 1305 | <span> |
| 1284 | 1306 | <i className={`status-dot ${network.mode}`} /> |
| @@ -1359,9 +1381,10 @@ function App() { | ||
| 1359 | 1381 | 打开项目后,在终端输入 <code>claude</code> |
| 1360 | 1382 | ,按提示登录你的账户。 |
| 1361 | 1383 | <br /> |
| 1362 | 删除: 默认工作区和打开的项目与本机共享,编辑和删除文件会同步。 | |
| 1384 | 新增: {isRemoteClient() ? "默认工作区和打开的项目位于云端,编辑和删除会直接影响云端文件。" : "默认工作区和打开的项目与本机共享,编辑和删除文件会同步。"} | |
| 1363 | 1385 | </p> |
| 1364 | 1386 | )} |
| 1387 | 新增: </>} | |
| 1365 | 1388 | {status.project_error && ( |
| 1366 | 1389 | <div className="start-error" role="alert"> |
| 1367 | 1390 | <strong>部分项目文件夹尚未连接</strong> |
| @@ -1379,7 +1402,7 @@ function App() { | ||
| 1379 | 1402 | ) : <p>{status.project_error}</p>} |
| 1380 | 1403 | </div> |
| 1381 | 1404 | )} |
| 1382 | 删除: {status.job?.error && ( | |
| 1405 | 新增: {!setupProgress && status.job?.error && ( | |
| 1383 | 1406 | <div className="start-error" role="alert"> |
| 1384 | 1407 | <strong>本次操作未完成</strong> |
| 1385 | 1408 | <p>{status.job.error}</p> |
| @@ -1393,7 +1416,7 @@ function App() { | ||
| 1393 | 1416 | )} |
| 1394 | 1417 | </div> |
| 1395 | 1418 | )} |
| 1396 | 删除: {status.job?.log && ( | |
| 1419 | 新增: {!setupProgress && status.job?.log && ( | |
| 1397 | 1420 | <button |
| 1398 | 1421 | className="text-button details-link" |
| 1399 | 1422 | onClick={() => setDetails(true)} |
| @@ -1450,7 +1473,7 @@ function App() { | ||
| 1450 | 1473 | ? status.job.message |
| 1451 | 1474 | : running |
| 1452 | 1475 | ? status.ready |
| 1453 | 删除: ? "文件与本机同步" | |
| 1476 | 新增: ? isRemoteClient() ? "文件保存在云端" : "文件与本机同步" | |
| 1454 | 1477 | : "环境运行中 · 浏览器待恢复" |
| 1455 | 1478 | : "")} |
| 1456 | 1479 | </span> |
| @@ -1611,18 +1634,6 @@ function App() { | ||
| 1611 | 1634 | </div> |
| 1612 | 1635 | ); |
| 1613 | 1636 | } |
| 1614 | 删除:installDiagnostics(); | |
| 1615 | 删除:createRoot(document.getElementById("root")).render( | |
| 1616 | 删除: <DiagnosticBoundary> | |
| 1617 | 删除: <AccountProvider> | |
| 1618 | 删除: <AppearanceProvider> | |
| 1619 | 删除: <AccountGate><App /></AccountGate> | |
| 1620 | 删除: </AppearanceProvider> | |
| 1621 | 删除: </AccountProvider> | |
| 1622 | 删除: </DiagnosticBoundary>, | |
| 1623 | 删除:); | |
| 1624 | 删除: | |
| 1625 | 删除:// A launcher can reopen an existing window with a fresh one-use ticket. | |
| 1626 | 删除:window.addEventListener("hashchange", () => { | |
| 1627 | 删除: if (location.hash) location.reload(); | |
| 1628 | 删除:}); | |
| 1637 | 新增:export default function Workbench() { | |
| 1638 | 新增: return <AccountProvider><AppearanceProvider><AccountGate><App /></AccountGate></AppearanceProvider></AccountProvider>; | |
| 1639 | 新增:} | |
| @@ -0,0 +1,88 @@ | ||
| 1 | 新增:import React, { useEffect, useRef } from "react"; | |
| 2 | 新增: | |
| 3 | 新增:export function Modal({ title, children, onClose, wide = false, footer }) { | |
| 4 | 新增: const panel = useRef(), | |
| 5 | 新增: closeRef = useRef(onClose); | |
| 6 | 新增: closeRef.current = onClose; | |
| 7 | 新增: useEffect(() => { | |
| 8 | 新增: const previous = document.activeElement; | |
| 9 | 新增: const first = panel.current.querySelector( | |
| 10 | 新增: "input:not([disabled]),button:not([disabled]),select:not([disabled])", | |
| 11 | 新增: ); | |
| 12 | 新增: first?.focus(); | |
| 13 | 新增: const key = (e) => { | |
| 14 | 新增: if ( | |
| 15 | 新增: [...document.querySelectorAll('[role="dialog"]')].at(-1) !== | |
| 16 | 新增: panel.current | |
| 17 | 新增: ) | |
| 18 | 新增: return; | |
| 19 | 新增: if (e.key === "Escape") { | |
| 20 | 新增: if (e.target.closest('[role="combobox"][aria-expanded="true"]')) return; | |
| 21 | 新增: e.preventDefault(); | |
| 22 | 新增: e.stopPropagation(); | |
| 23 | 新增: closeRef.current?.(); | |
| 24 | 新增: } | |
| 25 | 新增: if (e.key === "Tab") { | |
| 26 | 新增: const nodes = [ | |
| 27 | 新增: ...panel.current.querySelectorAll( | |
| 28 | 新增: "input:not([disabled]),button:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href]", | |
| 29 | 新增: ), | |
| 30 | 新增: ].filter((n) => n.offsetParent !== null); | |
| 31 | 新增: if (!nodes.length) return; | |
| 32 | 新增: const index = nodes.indexOf(document.activeElement); | |
| 33 | 新增: if (e.shiftKey && index <= 0) { | |
| 34 | 新增: e.preventDefault(); | |
| 35 | 新增: nodes.at(-1).focus(); | |
| 36 | 新增: } else if (!e.shiftKey && (index === nodes.length - 1 || index < 0)) { | |
| 37 | 新增: e.preventDefault(); | |
| 38 | 新增: nodes[0].focus(); | |
| 39 | 新增: } | |
| 40 | 新增: } | |
| 41 | 新增: }; | |
| 42 | 新增: const closeEvent = () => { | |
| 43 | 新增: if ( | |
| 44 | 新增: [...document.querySelectorAll('[role="dialog"]')].at(-1) === | |
| 45 | 新增: panel.current | |
| 46 | 新增: ) | |
| 47 | 新增: closeRef.current?.(); | |
| 48 | 新增: }; | |
| 49 | 新增: document.addEventListener("cage-close-modal", closeEvent); | |
| 50 | 新增: document.addEventListener("keydown", key, true); | |
| 51 | 新增: return () => { | |
| 52 | 新增: document.removeEventListener("keydown", key, true); | |
| 53 | 新增: document.removeEventListener("cage-close-modal", closeEvent); | |
| 54 | 新增: previous?.focus?.(); | |
| 55 | 新增: }; | |
| 56 | 新增: }, []); | |
| 57 | 新增: return ( | |
| 58 | 新增: <div | |
| 59 | 新增: className="modal-scrim" | |
| 60 | 新增: onMouseDown={(e) => { | |
| 61 | 新增: if (e.target === e.currentTarget) onClose?.(); | |
| 62 | 新增: }} | |
| 63 | 新增: > | |
| 64 | 新增: <section | |
| 65 | 新增: ref={panel} | |
| 66 | 新增: className={`modal ${wide ? "wide" : ""}`} | |
| 67 | 新增: role="dialog" | |
| 68 | 新增: aria-modal="true" | |
| 69 | 新增: aria-label={title} | |
| 70 | 新增: > | |
| 71 | 新增: <header className="modal-head"> | |
| 72 | 新增: <h2>{title}</h2> | |
| 73 | 新增: {onClose && ( | |
| 74 | 新增: <button | |
| 75 | 新增: className="icon-button close-modal" | |
| 76 | 新增: aria-label="关闭面板" | |
| 77 | 新增: onClick={onClose} | |
| 78 | 新增: > | |
| 79 | 新增: × | |
| 80 | 新增: </button> | |
| 81 | 新增: )} | |
| 82 | 新增: </header> | |
| 83 | 新增: {children} | |
| 84 | 新增: {footer && <footer className="modal-footer">{footer}</footer>} | |
| 85 | 新增: </section> | |
| 86 | 新增: </div> | |
| 87 | 新增: ); | |
| 88 | 新增:} | |
| @@ -4,6 +4,7 @@ import { FolderOpen, LoaderCircle, Plus } from "lucide-react"; | ||
| 4 | 4 | import { api, native, nativeAvailable } from "./api"; |
| 5 | 5 | import { Modal } from "./views"; |
| 6 | 6 | import { projectName } from "./workspace-state.mjs"; |
| 7 | 新增:import { isRemoteClient } from "./client-context.mjs"; | |
| 7 | 8 | |
| 8 | 9 | export function ProjectDialog({ |
| 9 | 10 | status, |
| @@ -17,8 +18,18 @@ export function ProjectDialog({ | ||
| 17 | 18 | const [path, setPath] = useState(initialPath || status.workspace || projects[0] || ""); |
| 18 | 19 | const [error, setError] = useState(""); |
| 19 | 20 | const [submitting, setSubmitting] = useState(false); |
| 21 | 新增: const [directories, setDirectories] = useState(null); | |
| 22 | 新增: const [browsing, setBrowsing] = useState(false); | |
| 23 | 新增: const remote = isRemoteClient(); | |
| 20 | 24 | const busy = submitting || Boolean(status.job?.running); |
| 25 | 新增: const browse = async (directory = path.trim()) => { | |
| 26 | 新增: setBrowsing(true); setError(""); | |
| 27 | 新增: try { setDirectories(await api(`/projects/directories?${new URLSearchParams({ path: directory })}`)); } | |
| 28 | 新增: catch (e) { setError(e.message); } | |
| 29 | 新增: finally { setBrowsing(false); } | |
| 30 | 新增: }; | |
| 21 | 31 | const choose = async () => { |
| 32 | 新增: if (remote) { await browse(); return; } | |
| 22 | 33 | try { |
| 23 | 34 | const selected = await native("chooseFolder"); |
| 24 | 35 | if (selected) { |
| @@ -33,7 +44,8 @@ export function ProjectDialog({ | ||
| 33 | 44 | setAdding(true); |
| 34 | 45 | setPath(""); |
| 35 | 46 | setError(""); |
| 36 | 删除: if (nativeAvailable()) void choose(); | |
| 47 | 新增: if (remote) void browse(""); | |
| 48 | 新增: else if (nativeAvailable()) void choose(); | |
| 37 | 49 | }; |
| 38 | 50 | const open = async (event) => { |
| 39 | 51 | event.preventDefault(); |
| @@ -88,7 +100,7 @@ export function ProjectDialog({ | ||
| 88 | 100 | className="modal-body project-form" |
| 89 | 101 | onSubmit={open} |
| 90 | 102 | > |
| 91 | 删除: <p>{activate ? "选择已有项目,或添加一个本机项目文件夹。" : "从 Cage 项目列表选择工作目录。新项目由 Cage 授权并共享。"}</p> | |
| 103 | 新增: <p>{activate ? remote ? "选择已有项目,或添加一个云端项目文件夹。" : "选择已有项目,或添加一个本机项目文件夹。" : "从 Cage 项目列表选择工作目录。新项目由 Cage 授权并共享。"}</p> | |
| 92 | 104 | {!adding && <> |
| 93 | 105 | <fieldset className="project-picker-list" disabled={busy}> |
| 94 | 106 | <legend>Cage 项目</legend> |
| @@ -102,7 +114,7 @@ export function ProjectDialog({ | ||
| 102 | 114 | </span> |
| 103 | 115 | </label>)} |
| 104 | 116 | </fieldset> |
| 105 | 删除: <button type="button" className="quiet-button project-picker-add" onClick={add} disabled={busy}><Plus size={16} />添加本机项目…</button> | |
| 117 | 新增: <button type="button" className="quiet-button project-picker-add" onClick={add} disabled={busy}><Plus size={16} />{remote ? "添加云端项目…" : "添加本机项目…"}</button> | |
| 106 | 118 | </>} |
| 107 | 119 | {adding && <> |
| 108 | 120 | {projects.length > 0 && <button type="button" className="quiet-button project-picker-add" disabled={busy} onClick={() => { setAdding(false); setPath(status.workspace || projects[0]); setError(""); }}>返回已有项目</button>} |
| @@ -116,21 +128,29 @@ export function ProjectDialog({ | ||
| 116 | 128 | setPath(event.target.value); |
| 117 | 129 | setError(""); |
| 118 | 130 | }} |
| 119 | 删除: placeholder={isWindows ? "C:/Users/你的名字/Projects/my-project" : isMac ? "/Users/你的名字/Projects/my-project" : "/home/你的名字/Projects/my-project"} | |
| 131 | 新增: placeholder={remote ? "/home/cage/Projects/my-project" : isWindows ? "C:/Users/你的名字/Projects/my-project" : isMac ? "/Users/你的名字/Projects/my-project" : "/home/你的名字/Projects/my-project"} | |
| 120 | 132 | disabled={busy} |
| 121 | 133 | spellCheck="false" |
| 122 | 134 | autoComplete="off" |
| 123 | 135 | /> |
| 124 | 删除: {nativeAvailable() && ( | |
| 125 | 删除: <button type="button" onClick={choose} disabled={busy}> | |
| 126 | 删除: 选择文件夹… | |
| 136 | 新增: {(remote || nativeAvailable()) && ( | |
| 137 | 新增: <button type="button" onClick={choose} disabled={busy || browsing}> | |
| 138 | 新增: {browsing ? "正在读取…" : remote ? "浏览云端文件夹…" : "选择文件夹…"} | |
| 127 | 139 | </button> |
| 128 | 140 | )} |
| 129 | 141 | </div> |
| 142 | 新增: {remote && directories && <section className="remote-directory-picker" aria-label="云端文件夹"> | |
| 143 | 新增: <div className="remote-directory-heading"><strong>{directories.path}</strong><button type="button" disabled={browsing} onClick={() => setDirectories(null)}>收起</button></div> | |
| 144 | 新增: <div className="remote-directory-list"> | |
| 145 | 新增: {directories.parent && <button type="button" disabled={browsing} onClick={() => browse(directories.parent)}>返回上级文件夹</button>} | |
| 146 | 新增: {directories.directories?.map((directory) => <button type="button" key={directory.path} disabled={browsing} onClick={() => browse(directory.path)}><FolderOpen size={16} />{directory.name}</button>)} | |
| 147 | 新增: {directories.directories?.length === 0 && <p className="field-help">这个目录下没有可浏览的文件夹。</p>} | |
| 148 | 新增: </div> | |
| 149 | 新增: <button type="button" disabled={browsing || !directories.selectable} onClick={() => { setPath(directories.path); setDirectories(null); }}>选择此云端文件夹</button> | |
| 150 | 新增: </section>} | |
| 130 | 151 | </>} |
| 131 | 152 | <p className="field-help"> |
| 132 | 删除: 这个文件夹中的改动会同步到本机。所有项目共用 Cage | |
| 133 | 删除: 环境,已有终端和网页会保持运行。 | |
| 153 | 新增: {remote ? "项目文件保存在云端,修改会直接影响云端文件。本机文件需要通过上传传递。" : "这个文件夹中的改动会同步到本机。"}所有项目共用 Cage 环境,已有终端和网页会保持运行。 | |
| 134 | 154 | </p> |
| 135 | 155 | {error && ( |
| 136 | 156 | <div className="error-message" role="alert"> |
| @@ -0,0 +1,183 @@ | ||
| 1 | 新增:import React, { useState } from "react"; | |
| 2 | 新增:import { api } from "./api"; | |
| 3 | 新增:import { InlineSelect } from "./inline-select"; | |
| 4 | 新增:import { Modal } from "./modal"; | |
| 5 | 新增: | |
| 6 | 新增:const emptyHost = () => ({ | |
| 7 | 新增: name: "", | |
| 8 | 新增: host: "", | |
| 9 | 新增: port: 22, | |
| 10 | 新增: user: "", | |
| 11 | 新增: auth: { kind: "key_file", identity_file: "" }, | |
| 12 | 新增: executable: "cage", | |
| 13 | 新增: config_path: "", | |
| 14 | 新增:}); | |
| 15 | 新增: | |
| 16 | 新增:export function HostForm({ initial, platform, onSaved, onClose }) { | |
| 17 | 新增: const [form, setForm] = useState(() => | |
| 18 | 新增: initial ? structuredClone(initial) : emptyHost(), | |
| 19 | 新增: ); | |
| 20 | 新增: const [busy, setBusy] = useState(false); | |
| 21 | 新增: const [error, setError] = useState(""); | |
| 22 | 新增: const update = (field, value) => | |
| 23 | 新增: setForm((old) => ({ | |
| 24 | 新增: ...old, | |
| 25 | 新增: [field]: value, | |
| 26 | 新增: ...(["host", "port"].includes(field) ? { host_key: undefined } : {}), | |
| 27 | 新增: })); | |
| 28 | 新增: async function save(event) { | |
| 29 | 新增: event.preventDefault(); | |
| 30 | 新增: if (busy) return; | |
| 31 | 新增: setBusy(true); | |
| 32 | 新增: setError(""); | |
| 33 | 新增: try { | |
| 34 | 新增: const saved = await api( | |
| 35 | 新增: form.id ? `/client/hosts/${form.id}` : "/client/hosts", | |
| 36 | 新增: { ...form, port: Number(form.port) }, | |
| 37 | 新增: form.id ? "PUT" : "POST", | |
| 38 | 新增: ); | |
| 39 | 新增: await onSaved(saved); | |
| 40 | 新增: } catch (e) { | |
| 41 | 新增: setError(e.message); | |
| 42 | 新增: } finally { | |
| 43 | 新增: setBusy(false); | |
| 44 | 新增: } | |
| 45 | 新增: } | |
| 46 | 新增: return ( | |
| 47 | 新增: <Modal | |
| 48 | 新增: title={form.id ? "编辑远程主机" : "添加远程主机"} | |
| 49 | 新增: onClose={busy ? undefined : onClose} | |
| 50 | 新增: > | |
| 51 | 新增: <form className="remote-host-form" onSubmit={save}> | |
| 52 | 新增: {error && ( | |
| 53 | 新增: <p className="error-message" role="alert"> | |
| 54 | 新增: {error} | |
| 55 | 新增: </p> | |
| 56 | 新增: )} | |
| 57 | 新增: <fieldset disabled={busy}> | |
| 58 | 新增: <label> | |
| 59 | 新增: 主机名称 | |
| 60 | 新增: <input | |
| 61 | 新增: required | |
| 62 | 新增: value={form.name} | |
| 63 | 新增: onChange={(event) => update("name", event.target.value)} | |
| 64 | 新增: placeholder="例如:东京开发机" | |
| 65 | 新增: maxLength={200} | |
| 66 | 新增: /> | |
| 67 | 新增: </label> | |
| 68 | 新增: <div className="remote-form-row"> | |
| 69 | 新增: <label> | |
| 70 | 新增: 服务器地址 | |
| 71 | 新增: <input | |
| 72 | 新增: required | |
| 73 | 新增: value={form.host} | |
| 74 | 新增: onChange={(event) => update("host", event.target.value)} | |
| 75 | 新增: placeholder="IP 地址或域名" | |
| 76 | 新增: autoComplete="off" | |
| 77 | 新增: spellCheck="false" | |
| 78 | 新增: /> | |
| 79 | 新增: </label> | |
| 80 | 新增: <label className="remote-port"> | |
| 81 | 新增: SSH 端口 | |
| 82 | 新增: <input | |
| 83 | 新增: required | |
| 84 | 新增: type="number" | |
| 85 | 新增: min="1" | |
| 86 | 新增: max="65535" | |
| 87 | 新增: value={form.port} | |
| 88 | 新增: onChange={(event) => update("port", event.target.value)} | |
| 89 | 新增: /> | |
| 90 | 新增: </label> | |
| 91 | 新增: </div> | |
| 92 | 新增: <label> | |
| 93 | 新增: SSH 用户名 | |
| 94 | 新增: <input | |
| 95 | 新增: required | |
| 96 | 新增: value={form.user} | |
| 97 | 新增: onChange={(event) => update("user", event.target.value)} | |
| 98 | 新增: placeholder="cage" | |
| 99 | 新增: autoComplete="off" | |
| 100 | 新增: spellCheck="false" | |
| 101 | 新增: /> | |
| 102 | 新增: </label> | |
| 103 | 新增: <label> | |
| 104 | 新增: SSH 登录方式 | |
| 105 | 新增: <InlineSelect | |
| 106 | 新增: aria-label="SSH 登录方式" | |
| 107 | 新增: value={form.auth.kind} | |
| 108 | 新增: onValueChange={(kind) => | |
| 109 | 新增: update("auth", { | |
| 110 | 新增: kind, | |
| 111 | 新增: identity_file: | |
| 112 | 新增: kind === "key_file" ? form.auth.identity_file || "" : "", | |
| 113 | 新增: }) | |
| 114 | 新增: } | |
| 115 | 新增: > | |
| 116 | 新增: <option value="key_file">本机密钥文件</option> | |
| 117 | 新增: <option value="agent">本机 SSH agent</option> | |
| 118 | 新增: </InlineSelect> | |
| 119 | 新增: </label> | |
| 120 | 新增: {form.auth.kind === "key_file" && ( | |
| 121 | 新增: <label> | |
| 122 | 新增: 本机私钥文件 | |
| 123 | 新增: <input | |
| 124 | 新增: aria-label="本机私钥文件" | |
| 125 | 新增: required | |
| 126 | 新增: value={form.auth.identity_file} | |
| 127 | 新增: onChange={(event) => | |
| 128 | 新增: update("auth", { | |
| 129 | 新增: ...form.auth, | |
| 130 | 新增: identity_file: event.target.value, | |
| 131 | 新增: }) | |
| 132 | 新增: } | |
| 133 | 新增: placeholder={ | |
| 134 | 新增: platform === "windows" | |
| 135 | 新增: ? "C:\\Users\\你的名字\\.ssh\\id_ed25519" | |
| 136 | 新增: : "/Users/你的名字/.ssh/id_ed25519" | |
| 137 | 新增: } | |
| 138 | 新增: autoComplete="off" | |
| 139 | 新增: spellCheck="false" | |
| 140 | 新增: /> | |
| 141 | 新增: <small>填写绝对路径。密钥留在本机,不上传到云端。</small> | |
| 142 | 新增: </label> | |
| 143 | 新增: )} | |
| 144 | 新增: <details> | |
| 145 | 新增: <summary>云端安装路径</summary> | |
| 146 | 新增: <div className="remote-advanced"> | |
| 147 | 新增: <label> | |
| 148 | 新增: Cage 程序路径 | |
| 149 | 新增: <input | |
| 150 | 新增: value={form.executable || ""} | |
| 151 | 新增: onChange={(event) => update("executable", event.target.value)} | |
| 152 | 新增: placeholder="cage" | |
| 153 | 新增: spellCheck="false" | |
| 154 | 新增: /> | |
| 155 | 新增: <small>默认使用 cage,也可填写云端程序的绝对路径。</small> | |
| 156 | 新增: </label> | |
| 157 | 新增: <label> | |
| 158 | 新增: Cage 配置文件 | |
| 159 | 新增: <input | |
| 160 | 新增: value={form.config_path || ""} | |
| 161 | 新增: onChange={(event) => | |
| 162 | 新增: update("config_path", event.target.value) | |
| 163 | 新增: } | |
| 164 | 新增: placeholder="默认使用云端账户的 ~/.claude-cage/config.json" | |
| 165 | 新增: spellCheck="false" | |
| 166 | 新增: /> | |
| 167 | 新增: <small>自定义时填写云端绝对路径。</small> | |
| 168 | 新增: </label> | |
| 169 | 新增: </div> | |
| 170 | 新增: </details> | |
| 171 | 新增: <div className="remote-button-row"> | |
| 172 | 新增: <button className="primary" type="submit"> | |
| 173 | 新增: 保存主机 | |
| 174 | 新增: </button> | |
| 175 | 新增: <button type="button" onClick={onClose}> | |
| 176 | 新增: 取消 | |
| 177 | 新增: </button> | |
| 178 | 新增: </div> | |
| 179 | 新增: </fieldset> | |
| 180 | 新增: </form> | |
| 181 | 新增: </Modal> | |
| 182 | 新增: ); | |
| 183 | 新增:} | |
| @@ -0,0 +1,67 @@ | ||
| 1 | 新增:.client-shell { height:100vh; display:flex; flex-direction:column; min-width:0; } | |
| 2 | 新增:.client-toolbar, .local-background { flex:none; display:flex; align-items:center; gap:9px; padding:6px 16px; background:var(--chrome); border-bottom:1px solid var(--line); font-size:.86rem; } | |
| 3 | 新增:.client-toolbar { min-height:34px; } | |
| 4 | 新增:.client-toolbar strong { overflow:hidden; white-space:nowrap; text-overflow:ellipsis; } | |
| 5 | 新增:.client-toolbar .brand-logo { height:18px; width:18px; } | |
| 6 | 新增:.client-toolbar-hint, .local-background span { color:var(--muted); } | |
| 7 | 新增:.client-toolbar .ssh-fallback, .local-background button { margin-left:auto; } | |
| 8 | 新增:.client-shell:has(.ssh-navigation) .ssh-fallback { display:none; } | |
| 9 | 新增:.local-background { background:var(--selected); min-height:38px; } | |
| 10 | 新增:.local-background span { margin-left:8px; } | |
| 11 | 新增:.local-background button { flex:none; } | |
| 12 | 新增:.client-stage { flex:1; display:flex; min-height:0; min-width:0; } | |
| 13 | 新增:.client-workbench { flex:1; min-width:0; min-height:0; overflow:hidden; } | |
| 14 | 新增:.client-workbench > .app, .client-workbench .account-gate { height:100%; min-height:0; } | |
| 15 | 新增:.client-workbench .boot-screen { height:100%; } | |
| 16 | 新增:.client-loading { flex:1; display:flex; align-items:center; justify-content:center; gap:12px; color:var(--muted); } | |
| 17 | 新增:.client-error { display:flex; align-items:center; gap:12px; justify-content:space-between; margin:12px; } | |
| 18 | 新增:.ssh-sidebar { width:var(--sidebar-width); flex:0 0 var(--sidebar-width); min-width:0; } | |
| 19 | 新增:.ssh-sidebar-body { overflow:auto; min-height:0; padding-bottom:16px; } | |
| 20 | 新增:.ssh-list-heading { margin:12px 0 4px; padding-left:6px; display:flex; align-items:center; justify-content:space-between; color:var(--muted); font-size:.82rem; } | |
| 21 | 新增:.ssh-list-heading button { flex:none; } | |
| 22 | 新增:.ssh-host-row { display:flex; width:100%; align-items:center; gap:8px; text-align:left; padding:8px; border:0; border-radius:6px; background:transparent; color:var(--ink); } | |
| 23 | 新增:.ssh-host-row.selected { background:var(--selected); } | |
| 24 | 新增:.ssh-host-row > span { flex:1; min-width:0; } | |
| 25 | 新增:.ssh-host-row strong, .ssh-host-row small { display:block; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; } | |
| 26 | 新增:.ssh-host-row strong { font-weight:550; }.ssh-host-row small { margin-top:1px; color:var(--muted); font-size:.8rem; } | |
| 27 | 新增:.ssh-host-actions, .ssh-connection, .ssh-empty { display:grid; gap:10px; margin:14px 2px; } | |
| 28 | 新增:.ssh-empty p, .ssh-help, .ssh-connection p { margin:0; color:var(--muted); line-height:1.6; font-size:.86rem; } | |
| 29 | 新增:.ssh-connection code { font-size:.8rem; word-break:break-all; user-select:text; } | |
| 30 | 新增:.ssh-local-action, .ssh-help { border-top:1px solid var(--line); padding-top:13px; margin:18px 0 10px; } | |
| 31 | 新增:.ssh-sidebar-body button, .environment-picker button, .ssh-fallback { display:inline-flex; align-items:center; justify-content:center; gap:7px; } | |
| 32 | 新增:.ssh-sidebar-body .ssh-host-row { justify-content:flex-start; } | |
| 33 | 新增:.environment-picker { flex:1; min-width:0; overflow:auto; display:grid; align-items:start; justify-items:center; padding:clamp(40px,12vh,140px) 24px 32px; background:var(--paper); } | |
| 34 | 新增:.environment-picker > div { width:min(100%,492px); } | |
| 35 | 新增:.environment-logo { width:40px; height:40px; object-fit:contain; margin-bottom:12px; } | |
| 36 | 新增:.environment-picker h1 { font-size:1.7rem; margin:0 0 8px; color:var(--strong); } | |
| 37 | 新增:.environment-picker p { line-height:1.65; margin:0 0 18px; color:var(--muted); } | |
| 38 | 新增:.environment-actions, .remote-button-row { display:flex; align-items:center; flex-wrap:wrap; gap:8px; } | |
| 39 | 新增:.environment-recent { margin-top:24px; border-top:1px solid var(--line); } | |
| 40 | 新增:.environment-recent h2 { margin:16px 0 8px; color:var(--muted); font-size:.88rem; font-weight:500; } | |
| 41 | 新增:.environment-recent button { width:100%; justify-content:flex-start; gap:8px; border:none; background:var(--chrome); margin-bottom:4px; } | |
| 42 | 新增:.environment-recent small { margin-left:auto; color:var(--muted); } | |
| 43 | 新增:.ssh-dialog-body, .remote-host-form { padding:14px 22px 18px; overflow-y:auto; overscroll-behavior:contain; } | |
| 44 | 新增:.ssh-dialog-body p { margin:0 0 10px; color:var(--ink); line-height:1.65; } | |
| 45 | 新增:.ssh-dialog-body svg { vertical-align:middle; } | |
| 46 | 新增:.remote-host-form > fieldset { border:0; padding:0; min-width:0; margin:0; display:grid; gap:15px; } | |
| 47 | 新增:.remote-host-form label, .ssh-host-actions label { display:flex; flex-direction:column; gap:7px; font-weight:500; } | |
| 48 | 新增:.remote-host-form input, .ssh-host-actions input { width:100%; min-width:0; height:36px; border:1px solid var(--line); border-radius:6px; background:var(--input); color:var(--ink); padding:7px 10px; font:inherit; font-weight:400; } | |
| 49 | 新增:.remote-host-form .inline-select-trigger { justify-content:space-between; height:36px; border-radius:6px; background:var(--input); padding:7px 10px; } | |
| 50 | 新增:.remote-host-form small, .remote-host-form summary { color:var(--muted); font-weight:400; font-size:.85rem; } | |
| 51 | 新增:.remote-host-form summary { cursor:pointer; } | |
| 52 | 新增:.remote-form-row { display:flex; align-items:start; gap:12px; } | |
| 53 | 新增:.remote-form-row > label { flex:1; min-width:0; } | |
| 54 | 新增:.remote-form-row > .remote-port { flex:0 0 92px; } | |
| 55 | 新增:.remote-advanced { display:grid; gap:16px; margin-top:16px; } | |
| 56 | 新增:.remote-directory-picker { display: grid; gap: 12px; padding: 16px; border: 1px solid var(--line); border-radius: 8px; } | |
| 57 | 新增:.remote-directory-heading { display: flex; align-items: start; gap: 12px; } | |
| 58 | 新增:.remote-directory-heading strong { flex: 1; min-width: 0; overflow-wrap: anywhere; } | |
| 59 | 新增:.remote-directory-list { display: grid; gap: 8px; max-height: 240px; overflow: auto; } | |
| 60 | 新增:.remote-directory-list button { justify-content: flex-start; text-align: left; overflow-wrap: anywhere; } | |
| 61 | 新增: | |
| 62 | 新增:@media(max-width:640px) { | |
| 63 | 新增: .client-stage:has(.ssh-sidebar) > .client-workbench, .client-stage:has(.ssh-sidebar) > .environment-picker { display:none; } | |
| 64 | 新增: .ssh-sidebar { flex:1; width:100%; max-width:none; } | |
| 65 | 新增: .client-toolbar, .local-background { padding:6px 10px; } | |
| 66 | 新增: .local-background span { display:block; margin:0; } | |
| 67 | 新增:} | |
| @@ -0,0 +1,966 @@ | ||
| 1 | 新增:import React, { | |
| 2 | 新增: createContext, | |
| 3 | 新增: useCallback, | |
| 4 | 新增: useContext, | |
| 5 | 新增: useEffect, | |
| 6 | 新增: useRef, | |
| 7 | 新增: useState, | |
| 8 | 新增:} from "react"; | |
| 9 | 新增:import { | |
| 10 | 新增: ArrowLeft, | |
| 11 | 新增: Check, | |
| 12 | 新增: Computer, | |
| 13 | 新增: LoaderCircle, | |
| 14 | 新增: Plus, | |
| 15 | 新增: Server, | |
| 16 | 新增: ShieldCheck, | |
| 17 | 新增:} from "lucide-react"; | |
| 18 | 新增:import { api, native, nativeAvailable } from "./api"; | |
| 19 | 新增:import { setClientContext } from "./client-context.mjs"; | |
| 20 | 新增:import { Modal } from "./modal"; | |
| 21 | 新增:import { HostForm } from "./remote-host-form"; | |
| 22 | 新增:import logo from "./logo.png"; | |
| 23 | 新增:import "./remote-hosts.css"; | |
| 24 | 新增: | |
| 25 | 新增:const Navigation = createContext(null); | |
| 26 | 新增:export const useSSHNavigation = () => useContext(Navigation); | |
| 27 | 新增:const identity = (context) => | |
| 28 | 新增: `${context.mode}:${context.connection_id || "disconnected"}`; | |
| 29 | 新增:const occupied = (status) => | |
| 30 | 新增: Boolean(status?.running || status?.busy || status?.live_terminals); | |
| 31 | 新增:const unknown = () => ({ known: false, message: "本机状态待确认" }); | |
| 32 | 新增:const recentKey = "cage-recent-environment"; | |
| 33 | 新增:function recent() { | |
| 34 | 新增: try { | |
| 35 | 新增: return localStorage.getItem(recentKey) || ""; | |
| 36 | 新增: } catch { | |
| 37 | 新增: return ""; | |
| 38 | 新增: } | |
| 39 | 新增:} | |
| 40 | 新增:function remember(value) { | |
| 41 | 新增: try { | |
| 42 | 新增: localStorage.setItem(recentKey, value); | |
| 43 | 新增: } catch { | |
| 44 | 新增: /* Optional preference. */ | |
| 45 | 新增: } | |
| 46 | 新增:} | |
| 47 | 新增:function localSummary(status) { | |
| 48 | 新增: if (!status?.known) return "本机状态待确认"; | |
| 49 | 新增: if (status.busy) return "本机正在处理环境操作"; | |
| 50 | 新增: if (status.live_terminals) | |
| 51 | 新增: return `本机有 ${status.live_terminals} 个活动终端`; | |
| 52 | 新增: if (status.running) return "本机环境正在运行"; | |
| 53 | 新增: return status.service_running ? "本机控制服务已启动" : "本机环境已停止"; | |
| 54 | 新增:} | |
| 55 | 新增: | |
| 56 | 新增:export function ClientRoot({ children }) { | |
| 57 | 新增: const [context, setContext] = useState(null); | |
| 58 | 新增: const [error, setError] = useState(""); | |
| 59 | 新增: const currentIdentity = useRef(null); | |
| 60 | 新增: const mounted = useRef(false); | |
| 61 | 新增: const serial = useRef(0); | |
| 62 | 新增: const refresh = useCallback(async () => { | |
| 63 | 新增: const query = ++serial.current; | |
| 64 | 新增: const value = await api("/client/context"); | |
| 65 | 新增: if (!mounted.current || query !== serial.current) return value; | |
| 66 | 新增: if (!["none", "local", "remote"].includes(value.mode)) | |
| 67 | 新增: throw new Error("客户端未返回有效的工作环境,请更新 Cage。"); | |
| 68 | 新增: const next = identity(value); | |
| 69 | 新增: if (currentIdentity.current && currentIdentity.current !== next) { | |
| 70 | 新增: // Destroy callbacks, local files in flight and input handlers from the previous generation. | |
| 71 | 新增: location.reload(); | |
| 72 | 新增: return value; | |
| 73 | 新增: } | |
| 74 | 新增: currentIdentity.current = next; | |
| 75 | 新增: setClientContext(value); | |
| 76 | 新增: setContext(value); | |
| 77 | 新增: setError(""); | |
| 78 | 新增: return value; | |
| 79 | 新增: }, []); | |
| 80 | 新增: useEffect(() => { | |
| 81 | 新增: mounted.current = true; | |
| 82 | 新增: let timer; | |
| 83 | 新增: async function poll() { | |
| 84 | 新增: try { | |
| 85 | 新增: await refresh(); | |
| 86 | 新增: } catch (e) { | |
| 87 | 新增: if (mounted.current) setError(e.message); | |
| 88 | 新增: } | |
| 89 | 新增: if (mounted.current) timer = setTimeout(poll, 2000); | |
| 90 | 新增: } | |
| 91 | 新增: (async () => { | |
| 92 | 新增: if (location.hash) { | |
| 93 | 新增: await api("/session", { token: location.hash.slice(1) }); | |
| 94 | 新增: history.replaceState(null, "", location.pathname); | |
| 95 | 新增: } | |
| 96 | 新增: window.dispatchEvent(new Event("cage-session-ready")); | |
| 97 | 新增: await poll(); | |
| 98 | 新增: })().catch((e) => setError(e.message)); | |
| 99 | 新增: return () => { | |
| 100 | 新增: mounted.current = false; | |
| 101 | 新增: clearTimeout(timer); | |
| 102 | 新增: }; | |
| 103 | 新增: }, [refresh]); | |
| 104 | 新增: return ( | |
| 105 | 新增: <div className="client-shell"> | |
| 106 | 新增: {error && ( | |
| 107 | 新增: <div className="client-error error-message" role="alert"> | |
| 108 | 新增: {error} | |
| 109 | 新增: <button onClick={() => location.reload()}>重新连接</button> | |
| 110 | 新增: </div> | |
| 111 | 新增: )} | |
| 112 | 新增: {context ? ( | |
| 113 | 新增: <Environment context={context} refresh={refresh}> | |
| 114 | 新增: {children} | |
| 115 | 新增: </Environment> | |
| 116 | 新增: ) : ( | |
| 117 | 新增: !error && ( | |
| 118 | 新增: <div className="client-loading"> | |
| 119 | 新增: <LoaderCircle className="spin" size={18} /> | |
| 120 | 新增: 正在连接 Cage… | |
| 121 | 新增: </div> | |
| 122 | 新增: ) | |
| 123 | 新增: )} | |
| 124 | 新增: </div> | |
| 125 | 新增: ); | |
| 126 | 新增:} | |
| 127 | 新增: | |
| 128 | 新增:function Environment({ context, refresh, children }) { | |
| 129 | 新增: const gateway = Boolean(context.desktop_gateway); | |
| 130 | 新增: const local = context.mode === "local" && !context.client_only; | |
| 131 | 新增: const remote = context.mode === "remote"; | |
| 132 | 新增: const active = context.connection?.state === "connected" && remote; | |
| 133 | 新增: const localLost = | |
| 134 | 新增: gateway && local && context.connection?.state !== "connected"; | |
| 135 | 新增: const ready = (local && !localLost) || active; | |
| 136 | 新增: const [expanded, setExpanded] = useState(false); | |
| 137 | 新增: const [hosts, setHosts] = useState([]); | |
| 138 | 新增: const [selected, setSelected] = useState(context.host_id || recent()); | |
| 139 | 新增: const [form, setForm] = useState(null); | |
| 140 | 新增: const [remove, setRemove] = useState(null); | |
| 141 | 新增: const [stop, setStop] = useState(null); | |
| 142 | 新增: const [decision, setDecision] = useState(null); | |
| 143 | 新增: const [localLocked, setLocalLocked] = useState(false); | |
| 144 | 新增: const [localStatus, setLocalStatus] = useState(null); | |
| 145 | 新增: const [busy, setBusy] = useState(""); | |
| 146 | 新增: const [error, setError] = useState(""); | |
| 147 | 新增: const [password, setPassword] = useState(""); | |
| 148 | 新增: const runningAction = useRef(false); | |
| 149 | 新增: const serial = useRef(0); | |
| 150 | 新增: const secretForTrust = useRef(null); | |
| 151 | 新增: const shellPresent = useRef(true); | |
| 152 | 新增: const acknowledged = useRef(false); | |
| 153 | 新增: const awaitingTarget = | |
| 154 | 新增: !ready && gateway && !context.client_only && context.mode === "none"; | |
| 155 | 新增: const [stayInSSH, setStayInSSH] = useState(() => | |
| 156 | 新增: sessionStorage.getItem("cage-disconnected-generation") === context.connection_id | |
| 157 | 新增: ); | |
| 158 | 新增: const defaultLocal = awaitingTarget && !stayInSSH && context.candidate?.mode !== "remote"; | |
| 159 | 新增: const showHosts = expanded || (!ready && !defaultLocal); | |
| 160 | 新增: const candidate = gateway ? context.candidate : null; | |
| 161 | 新增: const verifying = candidate?.connection?.state === "connecting"; | |
| 162 | 新增: const connection = | |
| 163 | 新增: candidate?.connection || (!gateway ? context.connection : null); | |
| 164 | 新增: const host = hosts.find((item) => item.id === selected); | |
| 165 | 新增: const hostConnected = Boolean(active && host?.id === context.host_id); | |
| 166 | 新增: const connectionHostID = connection?.host_id || candidate?.host_id; | |
| 167 | 新增: const pinnedFailure = | |
| 168 | 新增: connectionHostID === selected && | |
| 169 | 新增: connection?.host_key && | |
| 170 | 新增: ["host_key_unknown", "host_key_changed"].includes(connection.error_code); | |
| 171 | 新增: const needsDeploy = connectionHostID === selected && connection?.error_code === "deployment_required"; | |
| 172 | 新增: const phase = connection?.phase || ""; | |
| 173 | 新增: const connectingLabel = phase.startsWith("cloud_upload_") | |
| 174 | 新增: ? `正在上传部署包 ${phase.slice("cloud_upload_".length)}%` | |
| 175 | 新增: : { cloud_install: "正在安装云端环境…", cloud_detect: "正在检测服务器…", cloud_start: "正在启动服务…" }[phase] || "正在验证…"; | |
| 176 | 新增: const hostName = remote | |
| 177 | 新增: ? context.name || "远程主机" | |
| 178 | 新增: : local | |
| 179 | 新增: ? "本机环境" | |
| 180 | 新增: : "选择工作环境"; | |
| 181 | 新增: const route = () => ({ connection_id: context.connection_id || "" }); | |
| 182 | 新增: const load = useCallback(async () => { | |
| 183 | 新增: const { hosts = [] } = await api("/client/hosts"); | |
| 184 | 新增: setHosts(hosts); | |
| 185 | 新增: setSelected((id) => | |
| 186 | 新增: hosts.some((item) => item.id === id) ? id : hosts[0]?.id || "", | |
| 187 | 新增: ); | |
| 188 | 新增: }, []); | |
| 189 | 新增: const statusSerial = useRef(0); | |
| 190 | 新增: const readLocal = useCallback(async () => { | |
| 191 | 新增: const id = ++statusSerial.current; | |
| 192 | 新增: let result; | |
| 193 | 新增: try { | |
| 194 | 新增: result = await api("/client/local-status"); | |
| 195 | 新增: } catch { | |
| 196 | 新增: result = unknown(); | |
| 197 | 新增: } | |
| 198 | 新增: if (shellPresent.current && id === statusSerial.current) | |
| 199 | 新增: setLocalStatus(result); | |
| 200 | 新增: return result; | |
| 201 | 新增: }, []); | |
| 202 | 新增: useEffect(() => { | |
| 203 | 新增: shellPresent.current = true; | |
| 204 | 新增: load().catch((e) => setError(e.message)); | |
| 205 | 新增: return () => { | |
| 206 | 新增: shellPresent.current = false; | |
| 207 | 新增: ++serial.current; | |
| 208 | 新增: }; | |
| 209 | 新增: }, [load]); | |
| 210 | 新增: useEffect(() => { | |
| 211 | 新增: if (!gateway || (local && !showHosts && !decision)) return; | |
| 212 | 新增: let live = true, | |
| 213 | 新增: timer; | |
| 214 | 新增: async function poll() { | |
| 215 | 新增: if (document.visibilityState !== "hidden") await readLocal(); | |
| 216 | 新增: if (live) timer = setTimeout(poll, 4500); | |
| 217 | 新增: } | |
| 218 | 新增: poll(); | |
| 219 | 新增: return () => { | |
| 220 | 新增: live = false; | |
| 221 | 新增: clearTimeout(timer); | |
| 222 | 新增: }; | |
| 223 | 新增: }, [gateway, local, showHosts, decision, readLocal]); | |
| 224 | 新增: useEffect(() => { | |
| 225 | 新增: if (!ready && !defaultLocal && !acknowledged.current && nativeAvailable()) { | |
| 226 | 新增: native("workbenchReady") | |
| 227 | 新增: .then((ok) => { | |
| 228 | 新增: if (ok === true) acknowledged.current = true; | |
| 229 | 新增: }) | |
| 230 | 新增: .catch(() => {}); | |
| 231 | 新增: } | |
| 232 | 新增: if (ready) return; | |
| 233 | 新增: const action = async (name) => { | |
| 234 | 新增: if (name === "quit") await native("quitNow"); | |
| 235 | 新增: }; | |
| 236 | 新增: window.cageNativeAction = action; | |
| 237 | 新增: return () => { | |
| 238 | 新增: if (window.cageNativeAction === action) delete window.cageNativeAction; | |
| 239 | 新增: }; | |
| 240 | 新增: }, [ready, defaultLocal]); | |
| 241 | 新增: const act = async (name, operation) => { | |
| 242 | 新增: if (runningAction.current) return; | |
| 243 | 新增: runningAction.current = true; | |
| 244 | 新增: setBusy(name); | |
| 245 | 新增: setError(""); | |
| 246 | 新增: setLocalLocked(false); | |
| 247 | 新增: try { | |
| 248 | 新增: await operation(); | |
| 249 | 新增: } catch (e) { | |
| 250 | 新增: setLocalLocked(e.status === 423); | |
| 251 | 新增: setError( | |
| 252 | 新增: e.status === 423 | |
| 253 | 新增: ? "本机环境已锁定。请先返回本机解锁,再停止本机环境。" | |
| 254 | 新增: : e.message, | |
| 255 | 新增: ); | |
| 256 | 新增: } finally { | |
| 257 | 新增: runningAction.current = false; | |
| 258 | 新增: setBusy(""); | |
| 259 | 新增: } | |
| 260 | 新增: }; | |
| 261 | 新增: const closeSidebar = () => { | |
| 262 | 新增: secretForTrust.current = null; | |
| 263 | 新增: setExpanded(false); | |
| 264 | 新增: setPassword(""); | |
| 265 | 新增: setError(""); | |
| 266 | 新增: }; | |
| 267 | 新增: const openSidebar = () => { | |
| 268 | 新增: setExpanded(true); | |
| 269 | 新增: setError(""); | |
| 270 | 新增: }; | |
| 271 | 新增: const cancel = async (pending = candidate) => { | |
| 272 | 新增: ++serial.current; | |
| 273 | 新增: if (pending) { | |
| 274 | 新增: try { | |
| 275 | 新增: await api("/client/cancel", { ...route(), candidate_id: pending.id }); | |
| 276 | 新增: } catch (e) { | |
| 277 | 新增: // Another window may already have cancelled this candidate. Never | |
| 278 | 新增: // dismiss a newer one, and keep retry available for a real failure. | |
| 279 | 新增: if (e.status !== 409 || (await refresh()).candidate?.id === pending.id) | |
| 280 | 新增: throw e; | |
| 281 | 新增: } | |
| 282 | 新增: } | |
| 283 | 新增: secretForTrust.current = null; | |
| 284 | 新增: setDecision(null); | |
| 285 | 新增: setPassword(""); | |
| 286 | 新增: await refresh(); | |
| 287 | 新增: }; | |
| 288 | 新增: async function commit(pending, action, status) { | |
| 289 | 新增: try { | |
| 290 | 新增: await api("/client/commit", { | |
| 291 | 新增: ...route(), | |
| 292 | 新增: candidate_id: pending.id, | |
| 293 | 新增: local_action: action, | |
| 294 | 新增: ...(action === "stop" | |
| 295 | 新增: ? { local_controller_id: status?.controller_id } | |
| 296 | 新增: : {}), | |
| 297 | 新增: }); | |
| 298 | 新增: } catch (e) { | |
| 299 | 新增: if (action === "auto" && e.status === 409 && pending.mode === "remote") { | |
| 300 | 新增: const result = await readLocal(); | |
| 301 | 新增: if (occupied(result) || !result.known) { | |
| 302 | 新增: setDecision({ pending, status: result }); | |
| 303 | 新增: return; | |
| 304 | 新增: } | |
| 305 | 新增: } | |
| 306 | 新增: if (action === "stop" && e.status !== 423) { | |
| 307 | 新增: const actual = await readLocal(); | |
| 308 | 新增: if (actual.known && !actual.service_running && !occupied(actual)) { | |
| 309 | 新增: setDecision(null); | |
| 310 | 新增: throw new Error( | |
| 311 | 新增: "本机环境已停止。目标连接未完成,请重新连接 SSH 主机。", | |
| 312 | 新增: ); | |
| 313 | 新增: } | |
| 314 | 新增: } | |
| 315 | 新增: throw e; | |
| 316 | 新增: } | |
| 317 | 新增: remember( | |
| 318 | 新增: pending.mode === "local" | |
| 319 | 新增: ? "local" | |
| 320 | 新增: : pending.connection?.host_id || pending.host_id || selected, | |
| 321 | 新增: ); | |
| 322 | 新增: setDecision(null); | |
| 323 | 新增: setPassword(""); | |
| 324 | 新增: await refresh(); | |
| 325 | 新增: } | |
| 326 | 新增: async function verified(pending) { | |
| 327 | 新增: if (pending.mode === "remote") { | |
| 328 | 新增: const status = await readLocal(); | |
| 329 | 新增: if (!status.known || occupied(status)) { | |
| 330 | 新增: setDecision({ pending, status }); | |
| 331 | 新增: return; | |
| 332 | 新增: } | |
| 333 | 新增: } | |
| 334 | 新增: await commit(pending, "auto"); | |
| 335 | 新增: } | |
| 336 | 新增: // Advance only the candidate this window requested. An interrupted window can | |
| 337 | 新增: // explicitly resume a verified candidate without applying another window's choice. | |
| 338 | 新增: async function requestTarget( | |
| 339 | 新增: mode, | |
| 340 | 新增: item = null, | |
| 341 | 新增: secret = "", | |
| 342 | 新增: cancelled = false, | |
| 343 | 新增: deploy = false, | |
| 344 | 新增: ) { | |
| 345 | 新增: setPassword(""); | |
| 346 | 新增: if (!gateway) { | |
| 347 | 新增: const old = context.connection; | |
| 348 | 新增: if (mode === "local") | |
| 349 | 新增: await api("/client/local", { connection_id: old?.connection_id || "" }); | |
| 350 | 新增: else { | |
| 351 | 新增: if (old?.connection_id) | |
| 352 | 新增: await api("/client/disconnect", { connection_id: old.connection_id }); | |
| 353 | 新增: await api("/client/connect", { host_id: item.id, passphrase: secret, deploy }); | |
| 354 | 新增: } | |
| 355 | 新增: await refresh(); | |
| 356 | 新增: return; | |
| 357 | 新增: } | |
| 358 | 新增: if (candidate && !cancelled) await cancel(candidate); | |
| 359 | 新增: secretForTrust.current = null; | |
| 360 | 新增: const pending = await api("/client/candidate", { | |
| 361 | 新增: ...route(), | |
| 362 | 新增: mode, | |
| 363 | 新增: ...(item ? { host_id: item.id, passphrase: secret, deploy } : {}), | |
| 364 | 新增: }); | |
| 365 | 新增: const request = ++serial.current; | |
| 366 | 新增: | |
| 367 | 新增: let progress = pending; | |
| 368 | 新增: while (shellPresent.current && serial.current === request) { | |
| 369 | 新增: if (progress.connection?.state === "connected") { | |
| 370 | 新增: await verified(progress); | |
| 371 | 新增: return; | |
| 372 | 新增: } | |
| 373 | 新增: if ( | |
| 374 | 新增: progress.connection?.state === "failed" || | |
| 375 | 新增: progress.connection?.state === "disconnected" | |
| 376 | 新增: ) { | |
| 377 | 新增: if (item && secret && (progress.connection?.host_key || progress.connection?.error_code === "deployment_required")) | |
| 378 | 新增: secretForTrust.current = { id: item.id, secret }; | |
| 379 | 新增: await refresh(); | |
| 380 | 新增: return; | |
| 381 | 新增: } | |
| 382 | 新增: await new Promise((resolve) => setTimeout(resolve, 350)); | |
| 383 | 新增: if (!shellPresent.current || request !== serial.current) return; | |
| 384 | 新增: const value = await refresh(); | |
| 385 | 新增: if ( | |
| 386 | 新增: value.connection_id !== context.connection_id || | |
| 387 | 新增: value.candidate?.id !== pending.id | |
| 388 | 新增: ) | |
| 389 | 新增: return; | |
| 390 | 新增: progress = value.candidate; | |
| 391 | 新增: } | |
| 392 | 新增: } | |
| 393 | 新增: const trust = async () => { | |
| 394 | 新增: const saved = hosts.find((h) => h.id === connectionHostID); | |
| 395 | 新增: if (!saved || !connection.host_key) | |
| 396 | 新增: throw new Error("主机配置已变化,请重新连接。"); | |
| 397 | 新增: const secret = | |
| 398 | 新增: password || | |
| 399 | 新增: (secretForTrust.current?.id === saved.id | |
| 400 | 新增: ? secretForTrust.current.secret | |
| 401 | 新增: : ""); | |
| 402 | 新增: if (candidate) await cancel(candidate); | |
| 403 | 新增: await api( | |
| 404 | 新增: `/client/hosts/${saved.id}`, | |
| 405 | 新增: { ...saved, host_key: connection.host_key }, | |
| 406 | 新增: "PUT", | |
| 407 | 新增: ); | |
| 408 | 新增: await load(); | |
| 409 | 新增: setSelected(saved.id); | |
| 410 | 新增: await requestTarget("remote", saved, secret, true); | |
| 411 | 新增: }; | |
| 412 | 新增: const disconnect = async () => { | |
| 413 | 新增: const next = await api( | |
| 414 | 新增: "/client/disconnect", | |
| 415 | 新增: gateway | |
| 416 | 新增: ? route() | |
| 417 | 新增: : { connection_id: context.connection?.connection_id || "" }, | |
| 418 | 新增: ); | |
| 419 | 新增: remember(context.host_id || selected); | |
| 420 | 新增: setPassword(""); | |
| 421 | 新增: setExpanded(true); | |
| 422 | 新增: if (gateway) { | |
| 423 | 新增: sessionStorage.setItem("cage-disconnected-generation", next.connection_id); | |
| 424 | 新增: setStayInSSH(true); | |
| 425 | 新增: } | |
| 426 | 新增: await refresh(); | |
| 427 | 新增: }; | |
| 428 | 新增: const choose = (item) => { | |
| 429 | 新增: secretForTrust.current = null; | |
| 430 | 新增: setSelected(item.id); | |
| 431 | 新增: setPassword(""); | |
| 432 | 新增: setError(""); | |
| 433 | 新增: openSidebar(); | |
| 434 | 新增: }; | |
| 435 | 新增: // Enter the ordinary local account/workbench on a fresh desktop launch. | |
| 436 | 新增: // Connecting this control service never invokes /start (the VM stays manual). | |
| 437 | 新增: const attemptedDefault = useRef(false); | |
| 438 | 新增: useEffect(() => { | |
| 439 | 新增: if (!defaultLocal || attemptedDefault.current) return; | |
| 440 | 新增: attemptedDefault.current = true; | |
| 441 | 新增: void act("local", () => requestTarget("local")); | |
| 442 | 新增: }, [defaultLocal]); | |
| 443 | 新增: const localButton = (label) => ( | |
| 444 | 新增: <button | |
| 445 | 新增: disabled={ | |
| 446 | 新增: Boolean(busy) || | |
| 447 | 新增: (localStatus?.available === false && | |
| 448 | 新增: localStatus?.known && | |
| 449 | 新增: !localStatus.service_running) | |
| 450 | 新增: } | |
| 451 | 新增: onClick={() => act("local", () => requestTarget("local"))} | |
| 452 | 新增: > | |
| 453 | 新增: <Computer size={16} /> | |
| 454 | 新增: {label} | |
| 455 | 新增: </button> | |
| 456 | 新增: ); | |
| 457 | 新增: const modalOpen = Boolean(form || remove || stop || decision); | |
| 458 | 新增: const decisionBusy = busy === "commit" || busy === "cancel"; | |
| 459 | 新增: const cancelDecision = () => act("cancel", () => cancel(decision.pending)); | |
| 460 | 新增: const unlockButton = localLocked && ( | |
| 461 | 新增: <button | |
| 462 | 新增: disabled={Boolean(busy)} | |
| 463 | 新增: onClick={() => | |
| 464 | 新增: act("unlock-local", async () => { | |
| 465 | 新增: const pending = decision?.pending || candidate; | |
| 466 | 新增: if (pending) await cancel(pending); | |
| 467 | 新增: setStop(null); | |
| 468 | 新增: setDecision(null); | |
| 469 | 新增: if (local && !localLost) { | |
| 470 | 新增: location.reload(); | |
| 471 | 新增: return; | |
| 472 | 新增: } | |
| 473 | 新增: setExpanded(true); | |
| 474 | 新增: await requestTarget("local", null, "", true); | |
| 475 | 新增: }) | |
| 476 | 新增: } | |
| 477 | 新增: > | |
| 478 | 新增: 返回本机解锁 | |
| 479 | 新增: </button> | |
| 480 | 新增: ); | |
| 481 | 新增: const access = { expanded: showHosts, open: openSidebar }; | |
| 482 | 新增: const showBackground = | |
| 483 | 新增: gateway && | |
| 484 | 新增: !local && | |
| 485 | 新增: localStatus && | |
| 486 | 新增: (!localStatus.known || | |
| 487 | 新增: occupied(localStatus) || | |
| 488 | 新增: localStatus.service_running); | |
| 489 | 新增: return ( | |
| 490 | 新增: <Navigation.Provider value={access}> | |
| 491 | 新增: {!local && !defaultLocal && <header className="client-toolbar"> | |
| 492 | 新增: {local ? ( | |
| 493 | 新增: <Computer size={16} /> | |
| 494 | 新增: ) : remote ? ( | |
| 495 | 新增: <Server size={16} /> | |
| 496 | 新增: ) : ( | |
| 497 | 新增: <img className="brand-logo" src={logo} alt="" /> | |
| 498 | 新增: )} | |
| 499 | 新增: <strong>{ready ? hostName : "Cage"}</strong> | |
| 500 | 新增: {ready && ( | |
| 501 | 新增: <span className="client-toolbar-hint"> | |
| 502 | 新增: {remote ? "SSH · 云端运行" : "当前工作环境"} | |
| 503 | 新增: </span> | |
| 504 | 新增: )} | |
| 505 | 新增: {ready && !showHosts && ( | |
| 506 | 新增: <button className="ssh-fallback" onClick={openSidebar}> | |
| 507 | 新增: <Server size={15} /> | |
| 508 | 新增: SSH 主机 | |
| 509 | 新增: </button> | |
| 510 | 新增: )} | |
| 511 | 新增: </header>} | |
| 512 | 新增: {showBackground && ( | |
| 513 | 新增: <div className="local-background" role="status"> | |
| 514 | 新增: <Computer size={16} /> | |
| 515 | 新增: <div> | |
| 516 | 新增: <strong> | |
| 517 | 新增: {occupied(localStatus) | |
| 518 | 新增: ? "本机也在运行" | |
| 519 | 新增: : localSummary(localStatus)} | |
| 520 | 新增: </strong> | |
| 521 | 新增: {occupied(localStatus) && ( | |
| 522 | 新增: <span> | |
| 523 | 新增: {localStatus.live_terminals | |
| 524 | 新增: ? `${localStatus.live_terminals} 个活动终端` | |
| 525 | 新增: : localStatus.busy | |
| 526 | 新增: ? "有操作正在进行" | |
| 527 | 新增: : "正在占用本机资源"} | |
| 528 | 新增: </span> | |
| 529 | 新增: )} | |
| 530 | 新增: </div> | |
| 531 | 新增: {localStatus.known && localStatus.controller_id && ( | |
| 532 | 新增: <button | |
| 533 | 新增: disabled={Boolean(busy)} | |
| 534 | 新增: onClick={() => { | |
| 535 | 新增: setError(""); | |
| 536 | 新增: setStop(localStatus); | |
| 537 | 新增: }} | |
| 538 | 新增: > | |
| 539 | 新增: 停止本机环境 | |
| 540 | 新增: </button> | |
| 541 | 新增: )} | |
| 542 | 新增: </div> | |
| 543 | 新增: )} | |
| 544 | 新增: <div | |
| 545 | 新增: className="client-stage" | |
| 546 | 新增: inert={modalOpen || undefined} | |
| 547 | 新增: data-environment-dialog={modalOpen || undefined} | |
| 548 | 新增: > | |
| 549 | 新增: {showHosts && ( | |
| 550 | 新增: <aside | |
| 551 | 新增: className="workspace-sidebar ssh-sidebar" | |
| 552 | 新增: aria-label="SSH 主机" | |
| 553 | 新增: > | |
| 554 | 新增: <div className="sidebar-top"> | |
| 555 | 新增: <span className="sidebar-brand"> | |
| 556 | 新增: <Server size={18} /> | |
| 557 | 新增: SSH 主机 | |
| 558 | 新增: </span> | |
| 559 | 新增: {ready && ( | |
| 560 | 新增: <button | |
| 561 | 新增: className="icon-button" | |
| 562 | 新增: disabled={Boolean(busy) || verifying} | |
| 563 | 新增: onClick={closeSidebar} | |
| 564 | 新增: aria-label="返回工作台侧栏" | |
| 565 | 新增: > | |
| 566 | 新增: <ArrowLeft size={16} /> | |
| 567 | 新增: </button> | |
| 568 | 新增: )} | |
| 569 | 新增: </div> | |
| 570 | 新增: <div className="ssh-sidebar-body"> | |
| 571 | 新增: <div className="ssh-list-heading"> | |
| 572 | 新增: <span>已保存的主机</span> | |
| 573 | 新增: <button | |
| 574 | 新增: className="icon-button" | |
| 575 | 新增: aria-label="添加远程主机" | |
| 576 | 新增: title="添加远程主机" | |
| 577 | 新增: disabled={Boolean(busy)} | |
| 578 | 新增: onClick={() => setForm({ host: null })} | |
| 579 | 新增: > | |
| 580 | 新增: <Plus size={16} /> | |
| 581 | 新增: </button> | |
| 582 | 新增: </div> | |
| 583 | 新增: {hosts.map((item) => ( | |
| 584 | 新增: <button | |
| 585 | 新增: className={`ssh-host-row ${selected === item.id ? "selected" : ""}`} | |
| 586 | 新增: key={item.id} | |
| 587 | 新增: aria-pressed={selected === item.id} | |
| 588 | 新增: disabled={Boolean(busy) || verifying} | |
| 589 | 新增: onClick={() => choose(item)} | |
| 590 | 新增: > | |
| 591 | 新增: <Server size={15} /> | |
| 592 | 新增: <span> | |
| 593 | 新增: <strong>{item.name}</strong> | |
| 594 | 新增: <small> | |
| 595 | 新增: {item.user}@{item.host}:{item.port} | |
| 596 | 新增: </small> | |
| 597 | 新增: </span> | |
| 598 | 新增: {context.host_id === item.id && active && ( | |
| 599 | 新增: <Check size={15} aria-label="已连接" /> | |
| 600 | 新增: )} | |
| 601 | 新增: </button> | |
| 602 | 新增: ))} | |
| 603 | 新增: {!hosts.length && ( | |
| 604 | 新增: <div className="ssh-empty"> | |
| 605 | 新增: <p>还没有远程主机</p> | |
| 606 | 新增: <button onClick={() => setForm({ host: null })}> | |
| 607 | 新增: <Plus size={14} /> | |
| 608 | 新增: 添加主机 | |
| 609 | 新增: </button> | |
| 610 | 新增: </div> | |
| 611 | 新增: )} | |
| 612 | 新增: {host && ( | |
| 613 | 新增: <section className="ssh-host-actions" aria-label="所选主机操作"> | |
| 614 | 新增: {host.auth.kind === "key_file" && !hostConnected && ( | |
| 615 | 新增: <label> | |
| 616 | 新增: 密钥口令(如果已设置) | |
| 617 | 新增: <input | |
| 618 | 新增: type="password" | |
| 619 | 新增: autoComplete="off" | |
| 620 | 新增: disabled={Boolean(busy)} | |
| 621 | 新增: value={password} | |
| 622 | 新增: onChange={(e) => setPassword(e.target.value)} | |
| 623 | 新增: /> | |
| 624 | 新增: </label> | |
| 625 | 新增: )} | |
| 626 | 新增: {hostConnected ? ( | |
| 627 | 新增: <button | |
| 628 | 新增: disabled={Boolean(busy)} | |
| 629 | 新增: onClick={() => act("disconnect", disconnect)} | |
| 630 | 新增: > | |
| 631 | 新增: 断开连接 | |
| 632 | 新增: </button> | |
| 633 | 新增: ) : ( | |
| 634 | 新增: !pinnedFailure && ( | |
| 635 | 新增: <button | |
| 636 | 新增: className="primary" | |
| 637 | 新增: disabled={ | |
| 638 | 新增: Boolean(busy) || verifying || Boolean(decision) | |
| 639 | 新增: } | |
| 640 | 新增: onClick={() => | |
| 641 | 新增: act("verify", () => | |
| 642 | 新增: requestTarget("remote", host, password || (needsDeploy && secretForTrust.current?.id === host.id ? secretForTrust.current.secret : ""), false, needsDeploy), | |
| 643 | 新增: ) | |
| 644 | 新增: } | |
| 645 | 新增: > | |
| 646 | 新增: {busy === "verify" || verifying | |
| 647 | 新增: ? connectingLabel | |
| 648 | 新增: : needsDeploy ? "部署并连接" : "连接此主机"} | |
| 649 | 新增: </button> | |
| 650 | 新增: ) | |
| 651 | 新增: )} | |
| 652 | 新增: <div className="remote-button-row"> | |
| 653 | 新增: <button | |
| 654 | 新增: disabled={Boolean(busy) || hostConnected || verifying} | |
| 655 | 新增: onClick={() => | |
| 656 | 新增: act("edit", async () => { | |
| 657 | 新增: if (candidate?.connection.host_id === host.id) | |
| 658 | 新增: await cancel(candidate); | |
| 659 | 新增: setForm({ host }); | |
| 660 | 新增: }) | |
| 661 | 新增: } | |
| 662 | 新增: > | |
| 663 | 新增: 编辑 | |
| 664 | 新增: </button> | |
| 665 | 新增: <button | |
| 666 | 新增: disabled={Boolean(busy) || hostConnected || verifying} | |
| 667 | 新增: onClick={() => | |
| 668 | 新增: act("remove-prompt", async () => { | |
| 669 | 新增: if (candidate?.connection.host_id === host.id) | |
| 670 | 新增: await cancel(candidate); | |
| 671 | 新增: setRemove(host); | |
| 672 | 新增: }) | |
| 673 | 新增: } | |
| 674 | 新增: > | |
| 675 | 新增: 移除连接 | |
| 676 | 新增: </button> | |
| 677 | 新增: </div> | |
| 678 | 新增: </section> | |
| 679 | 新增: )} | |
| 680 | 新增: {!context.client_only && (!local || localLost) && ( | |
| 681 | 新增: <div className="ssh-local-action"> | |
| 682 | 新增: {localButton("进入本机工作台")} | |
| 683 | 新增: </div> | |
| 684 | 新增: )} | |
| 685 | 新增: {!context.client_only && local && ( | |
| 686 | 新增: <p className="ssh-help">云端连接就绪后再切换工作台。</p> | |
| 687 | 新增: )} | |
| 688 | 新增: {error && !decision && !stop && !remove && ( | |
| 689 | 新增: <p className="error-message" role="alert"> | |
| 690 | 新增: {error} | |
| 691 | 新增: </p> | |
| 692 | 新增: )} | |
| 693 | 新增: {connection?.state === "failed" && | |
| 694 | 新增: (!connectionHostID || connectionHostID === selected) && ( | |
| 695 | 新增: <div className="ssh-connection" role="alert"> | |
| 696 | 新增: <strong> | |
| 697 | 新增: {connection.message || "连接失败,请重试。"} | |
| 698 | 新增: </strong> | |
| 699 | 新增: {pinnedFailure && ( | |
| 700 | 新增: <> | |
| 701 | 新增: <p>请与服务器管理员核对“{host?.name}”的主机指纹。</p> | |
| 702 | 新增: <code> | |
| 703 | 新增: {connection.host_key.algorithm} | |
| 704 | 新增: <br /> | |
| 705 | 新增: {connection.host_key.fingerprint} | |
| 706 | 新增: </code> | |
| 707 | 新增: <button | |
| 708 | 新增: disabled={Boolean(busy)} | |
| 709 | 新增: className="primary" | |
| 710 | 新增: onClick={() => act("trust", trust)} | |
| 711 | 新增: > | |
| 712 | 新增: <ShieldCheck size={15} /> | |
| 713 | 新增: 我已核对指纹,信任此主机 | |
| 714 | 新增: </button> | |
| 715 | 新增: </> | |
| 716 | 新增: )} | |
| 717 | 新增: </div> | |
| 718 | 新增: )} | |
| 719 | 新增: {remote && !active && !connection?.message && ( | |
| 720 | 新增: <p className="ssh-help" role="status"> | |
| 721 | 新增: 连接已断开。请重新连接并核对云端任务。 | |
| 722 | 新增: </p> | |
| 723 | 新增: )} | |
| 724 | 新增: {gateway && candidate && !decision && ( | |
| 725 | 新增: <> | |
| 726 | 新增: {candidate.connection?.state === "connected" && !busy && ( | |
| 727 | 新增: <button | |
| 728 | 新增: onClick={() => act("verify", () => verified(candidate))} | |
| 729 | 新增: > | |
| 730 | 新增: 继续连接 | |
| 731 | 新增: </button> | |
| 732 | 新增: )} | |
| 733 | 新增: <button | |
| 734 | 新增: disabled={decisionBusy} | |
| 735 | 新增: onClick={() => cancel().catch((e) => setError(e.message))} | |
| 736 | 新增: > | |
| 737 | 新增: 取消此次连接 | |
| 738 | 新增: </button> | |
| 739 | 新增: </> | |
| 740 | 新增: )} | |
| 741 | 新增: </div> | |
| 742 | 新增: </aside> | |
| 743 | 新增: )} | |
| 744 | 新增: {ready ? ( | |
| 745 | 新增: <div className="client-workbench">{children}</div> | |
| 746 | 新增: ) : defaultLocal && !error && candidate?.connection?.state !== "failed" && !expanded ? ( | |
| 747 | 新增: <div className="client-loading" role="status">正在打开 Cage 工作台…</div> | |
| 748 | 新增: ) : ( | |
| 749 | 新增: <main className="environment-picker"> | |
| 750 | 新增: <div> | |
| 751 | 新增: <img className="environment-logo" src={logo} alt="" /> | |
| 752 | 新增: <h1> | |
| 753 | 新增: {localLost | |
| 754 | 新增: ? "重新连接本机工作台" | |
| 755 | 新增: : remote && !active | |
| 756 | 新增: ? "重新连接 SSH 主机" | |
| 757 | 新增: : defaultLocal ? "本机工作台连接未完成" : "连接 SSH 主机"} | |
| 758 | 新增: </h1> | |
| 759 | 新增: <p> | |
| 760 | 新增: {context.client_only | |
| 761 | 新增: ? "通过 SSH 连接服务器,首次连接可自动部署 Cage。项目、应用和网络由服务器管理。" | |
| 762 | 新增: : "本机和 SSH 主机使用同一个工作台。项目、应用和网络由选中的环境管理。"} | |
| 763 | 新增: </p> | |
| 764 | 新增: {!context.client_only && | |
| 765 | 新增: localStatus?.known && | |
| 766 | 新增: localStatus.available === false && | |
| 767 | 新增: !localStatus.service_running && ( | |
| 768 | 新增: <p>本机运行组件不可用,可通过 SSH 连接服务器。</p> | |
| 769 | 新增: )} | |
| 770 | 新增: {!showHosts && error && ( | |
| 771 | 新增: <p className="error-message" role="alert"> | |
| 772 | 新增: {error} | |
| 773 | 新增: </p> | |
| 774 | 新增: )} | |
| 775 | 新增: <div className="environment-actions"> | |
| 776 | 新增: {!context.client_only && | |
| 777 | 新增: (!showHosts || localLost) && | |
| 778 | 新增: localButton("重新连接本机")} | |
| 779 | 新增: {!showHosts && ( | |
| 780 | 新增: <button disabled={Boolean(busy)} onClick={openSidebar}> | |
| 781 | 新增: <Server size={16} /> | |
| 782 | 新增: 连接 SSH 主机 | |
| 783 | 新增: </button> | |
| 784 | 新增: )} | |
| 785 | 新增: </div> | |
| 786 | 新增: {!showHosts && hosts.length > 0 && ( | |
| 787 | 新增: <div className="environment-recent"> | |
| 788 | 新增: <h2>已保存的主机</h2> | |
| 789 | 新增: {hosts.map((item) => ( | |
| 790 | 新增: <button key={item.id} onClick={() => choose(item)}> | |
| 791 | 新增: <Server size={15} /> | |
| 792 | 新增: {item.name} | |
| 793 | 新增: {recent() === item.id && <small>上次使用</small>} | |
| 794 | 新增: </button> | |
| 795 | 新增: ))} | |
| 796 | 新增: </div> | |
| 797 | 新增: )} | |
| 798 | 新增: {busy === "local" && <p role="status">正在连接本机工作台…</p>} | |
| 799 | 新增: {!showHosts && candidate?.connection?.state === "failed" && ( | |
| 800 | 新增: <p role="alert" className="error-message"> | |
| 801 | 新增: {candidate.connection.message} | |
| 802 | 新增: </p> | |
| 803 | 新增: )} | |
| 804 | 新增: </div> | |
| 805 | 新增: </main> | |
| 806 | 新增: )} | |
| 807 | 新增: </div> | |
| 808 | 新增: {form && ( | |
| 809 | 新增: <HostForm | |
| 810 | 新增: initial={form.host} | |
| 811 | 新增: platform={context.client_platform} | |
| 812 | 新增: onClose={() => setForm(null)} | |
| 813 | 新增: onSaved={async (saved) => { | |
| 814 | 新增: await load(); | |
| 815 | 新增: setSelected(saved.id); | |
| 816 | 新增: setPassword(""); | |
| 817 | 新增: setForm(null); | |
| 818 | 新增: }} | |
| 819 | 新增: /> | |
| 820 | 新增: )} | |
| 821 | 新增: {remove && ( | |
| 822 | 新增: <Modal | |
| 823 | 新增: title="移除 SSH 主机" | |
| 824 | 新增: onClose={busy ? undefined : () => setRemove(null)} | |
| 825 | 新增: footer={ | |
| 826 | 新增: <> | |
| 827 | 新增: <button disabled={Boolean(busy)} onClick={() => setRemove(null)}> | |
| 828 | 新增: 取消 | |
| 829 | 新增: </button> | |
| 830 | 新增: <button | |
| 831 | 新增: className="primary" | |
| 832 | 新增: disabled={Boolean(busy)} | |
| 833 | 新增: onClick={() => | |
| 834 | 新增: act("remove", async () => { | |
| 835 | 新增: await api( | |
| 836 | 新增: `/client/hosts/${remove.id}`, | |
| 837 | 新增: undefined, | |
| 838 | 新增: "DELETE", | |
| 839 | 新增: ); | |
| 840 | 新增: setRemove(null); | |
| 841 | 新增: setPassword(""); | |
| 842 | 新增: await load(); | |
| 843 | 新增: }) | |
| 844 | 新增: } | |
| 845 | 新增: > | |
| 846 | 新增: 确认移除 | |
| 847 | 新增: </button> | |
| 848 | 新增: </> | |
| 849 | 新增: } | |
| 850 | 新增: > | |
| 851 | 新增: <div className="ssh-dialog-body"> | |
| 852 | 新增: <p>移除“{remove.name}”的本机连接配置?云端文件和任务会保留。</p> | |
| 853 | 新增: {error && <p role="alert">{error}</p>} | |
| 854 | 新增: </div> | |
| 855 | 新增: </Modal> | |
| 856 | 新增: )} | |
| 857 | 新增: {decision && ( | |
| 858 | 新增: <Modal | |
| 859 | 新增: title="切换到 SSH 主机" | |
| 860 | 新增: onClose={decisionBusy ? undefined : cancelDecision} | |
| 861 | 新增: footer={ | |
| 862 | 新增: <> | |
| 863 | 新增: <button disabled={decisionBusy} onClick={cancelDecision}> | |
| 864 | 新增: 取消 | |
| 865 | 新增: </button> | |
| 866 | 新增: <button | |
| 867 | 新增: disabled={decisionBusy} | |
| 868 | 新增: onClick={() => | |
| 869 | 新增: act("commit", () => | |
| 870 | 新增: commit(decision.pending, "keep", decision.status), | |
| 871 | 新增: ) | |
| 872 | 新增: } | |
| 873 | 新增: > | |
| 874 | 新增: 保留本机运行 | |
| 875 | 新增: </button> | |
| 876 | 新增: <button | |
| 877 | 新增: className="primary" | |
| 878 | 新增: disabled={ | |
| 879 | 新增: decisionBusy || | |
| 880 | 新增: !decision.status.known || | |
| 881 | 新增: !decision.status.controller_id | |
| 882 | 新增: } | |
| 883 | 新增: onClick={() => | |
| 884 | 新增: act("commit", () => | |
| 885 | 新增: commit(decision.pending, "stop", decision.status), | |
| 886 | 新增: ) | |
| 887 | 新增: } | |
| 888 | 新增: > | |
| 889 | 新增: 停止本机并连接 | |
| 890 | 新增: </button> | |
| 891 | 新增: </> | |
| 892 | 新增: } | |
| 893 | 新增: > | |
| 894 | 新增: <div className="ssh-dialog-body"> | |
| 895 | 新增: <p> | |
| 896 | 新增: <Check size={16} /> 已验证{" "} | |
| 897 | 新增: {hosts.find( | |
| 898 | 新增: (h) => | |
| 899 | 新增: h.id === | |
| 900 | 新增: (decision.pending.connection?.host_id || | |
| 901 | 新增: decision.pending.host_id), | |
| 902 | 新增: )?.name || "目标主机"}{" "} | |
| 903 | 新增: 的 SSH 与 Cage 服务。 | |
| 904 | 新增: </p> | |
| 905 | 新增: <p> | |
| 906 | 新增: <strong>{localSummary(decision.status)}。</strong>{" "} | |
| 907 | 新增: 停止本机会结束终端任务并释放资源,未保存的内容可能丢失。选择保留后可以在云端工作台稍后停止。 | |
| 908 | 新增: </p> | |
| 909 | 新增: {busy === "commit" && ( | |
| 910 | 新增: <p role="status">正在确认环境切换,请稍候…</p> | |
| 911 | 新增: )} | |
| 912 | 新增: {error && ( | |
| 913 | 新增: <p role="alert" className="error-message"> | |
| 914 | 新增: {error} | |
| 915 | 新增: </p> | |
| 916 | 新增: )} | |
| 917 | 新增: {unlockButton} | |
| 918 | 新增: </div> | |
| 919 | 新增: </Modal> | |
| 920 | 新增: )} | |
| 921 | 新增: {stop && ( | |
| 922 | 新增: <Modal | |
| 923 | 新增: title="停止本机环境?" | |
| 924 | 新增: onClose={busy ? undefined : () => setStop(null)} | |
| 925 | 新增: footer={ | |
| 926 | 新增: <> | |
| 927 | 新增: <button disabled={Boolean(busy)} onClick={() => setStop(null)}> | |
| 928 | 新增: 取消 | |
| 929 | 新增: </button> | |
| 930 | 新增: <button | |
| 931 | 新增: className="primary" | |
| 932 | 新增: disabled={Boolean(busy)} | |
| 933 | 新增: onClick={() => | |
| 934 | 新增: act("stop", async () => { | |
| 935 | 新增: await api("/client/local-stop", { | |
| 936 | 新增: ...route(), | |
| 937 | 新增: local_controller_id: stop.controller_id, | |
| 938 | 新增: }); | |
| 939 | 新增: await readLocal(); | |
| 940 | 新增: setStop(null); | |
| 941 | 新增: }) | |
| 942 | 新增: } | |
| 943 | 新增: > | |
| 944 | 新增: 确认停止本机 | |
| 945 | 新增: </button> | |
| 946 | 新增: </> | |
| 947 | 新增: } | |
| 948 | 新增: > | |
| 949 | 新增: <div className="ssh-dialog-body"> | |
| 950 | 新增: <p> | |
| 951 | 新增: {localSummary(stop)} | |
| 952 | 新增: 。停止将结束本机终端任务并释放资源,未保存的内容可能丢失。云端任务继续运行。 | |
| 953 | 新增: </p> | |
| 954 | 新增: {busy === "stop" && <p role="status">正在停止本机环境…</p>} | |
| 955 | 新增: {error && ( | |
| 956 | 新增: <p role="alert" className="error-message"> | |
| 957 | 新增: {error} | |
| 958 | 新增: </p> | |
| 959 | 新增: )} | |
| 960 | 新增: {unlockButton} | |
| 961 | 新增: </div> | |
| 962 | 新增: </Modal> | |
| 963 | 新增: )} | |
| 964 | 新增: </Navigation.Provider> | |
| 965 | 新增: ); | |
| 966 | 新增:} | |
| @@ -34,6 +34,18 @@ export function ResourceSettings({ status, onConfirm }) { | ||
| 34 | 34 | const observation = data?.observation; |
| 35 | 35 | const guest = observation?.guest; |
| 36 | 36 | const fresh = observation && Date.now() - Date.parse(observation.observed_at) < 10000; |
| 37 | 新增: const resourceError = error || data?.resource_error; | |
| 38 | 新增: const resourcesVerified = data?.resources_verified === true && !resourceError; | |
| 39 | 新增: if (data?.runtime === "container") return <section className="environment-versions" aria-label="计算资源"> | |
| 40 | 新增: <h4>服务器容器资源上限</h4> | |
| 41 | 新增: <p className="field-help">CPU、内存与进程数量由服务器上的容器资源组限制。</p> | |
| 42 | 新增: <div className="setting-summary-row"><span>资源限制核验</span><strong>{data.running ? resourcesVerified ? "已核验" : "未通过核验" : "环境未运行"}</strong></div> | |
| 43 | 新增: <div className="setting-summary-row"><span>容器内存上限</span><strong>{data.running ? resourcesVerified ? gib(data.configured_memory_bytes) : "未核验" : gib(data.recommended_memory_bytes)}</strong></div> | |
| 44 | 新增: <div className="setting-summary-row"><span>容器 CPU 上限</span><strong>{data.running ? resourcesVerified ? `${data.configured_cpus} 个逻辑核心` : "未核验" : `${data.recommended_cpus} 个逻辑核心`}</strong></div> | |
| 45 | 新增: <div className="setting-summary-row"><span>进程与线程总数上限</span><strong>{data.running ? resourcesVerified ? data.pids_limit : "未核验" : "运行后核验"}</strong></div> | |
| 46 | 新增: <p className="field-help">{data.running ? resourcesVerified ? "已从服务器核验容器所属资源组的实际限制。实时内存与 CPU 用量尚未提供。" : "无法确认运行中容器的实际资源限制,请查看下方错误或等待重新核验。" : "环境尚未运行,当前显示部署配置中的资源上限。"}</p> | |
| 47 | 新增: {resourceError && <p role="alert" className="error-message">{resourceError}</p>} | |
| 48 | 新增: </section>; | |
| 37 | 49 | return <section className="environment-versions" aria-label="计算资源"> |
| 38 | 50 | <h4>计算资源 · 自动管理</h4> |
| 39 | 51 | <p className="field-help">内存随程序需求增长,持续空闲后逐步归还主机。默认上限为主机资源的一半;CPU 按实际任务使用,上限表示可同时使用的逻辑核心数。</p> |
| @@ -1,6 +1,7 @@ | ||
| 1 | 1 | import { PasswordVaultSettings } from "./password-vault"; |
| 2 | 2 | import { KeyRound } from "lucide-react"; |
| 3 | 3 | import { InlineSelect } from "./inline-select"; |
| 4 | 新增:import { clientKeyboard, isRemoteClient, saveClientKeyboard } from "./client-context.mjs"; | |
| 4 | 5 | import { shortcut, usesControl } from "./platform.mjs"; |
| 5 | 6 | import React, { useEffect, useMemo, useRef, useState } from "react"; |
| 6 | 7 | import { |
| @@ -22,6 +23,7 @@ import { ProxySettings } from "./proxy-settings"; | ||
| 22 | 23 | import { ExitPolicyFields } from "./exit-policy"; |
| 23 | 24 | import { canonicalExitPolicy } from "./safety-state.mjs"; |
| 24 | 25 | import { EnvironmentVersions } from "./environment-versions"; |
| 26 | 新增:import { EnvironmentStorage } from "./environment-storage"; | |
| 25 | 27 | import { ResourceSettings } from "./resources"; |
| 26 | 28 | import { DiagnosticSettings } from "./diagnostics.jsx"; |
| 27 | 29 | import { AccountSettings } from "./account"; |
| @@ -47,6 +49,7 @@ export function SettingsPanel({ | ||
| 47 | 49 | onClaudeLogin, |
| 48 | 50 | initialSection = "keyboard", |
| 49 | 51 | }) { |
| 52 | 新增: const [localKeyboard, setLocalKeyboard] = useState(() => clientKeyboard(current.keyboard)); | |
| 50 | 53 | const [accountDirty, setAccountDirty] = useState(false); |
| 51 | 54 | const [proxyDirty, setProxyDirty] = useState(false); |
| 52 | 55 | const [draft, setDraft] = useState({ ...current }), |
| @@ -511,15 +514,19 @@ export function SettingsPanel({ | ||
| 511 | 514 | ], |
| 512 | 515 | ].map(([value, title, help]) => ( |
| 513 | 516 | <label |
| 514 | 删除: className={`choice ${draft.keyboard === value ? "checked" : ""}`} | |
| 517 | 新增: className={`choice ${(isRemoteClient() ? localKeyboard : draft.keyboard) === value ? "checked" : ""}`} | |
| 515 | 518 | key={value} |
| 516 | 519 | > |
| 517 | 520 | <input |
| 518 | 521 | type="radio" |
| 519 | 522 | name="keyboard" |
| 520 | 523 | value={value} |
| 521 | 删除: checked={draft.keyboard === value} | |
| 522 | 删除: onChange={() => update("keyboard", value)} | |
| 524 | 新增: checked={(isRemoteClient() ? localKeyboard : draft.keyboard) === value} | |
| 525 | 新增: onChange={() => { | |
| 526 | 新增: if (!isRemoteClient()) { update("keyboard", value); return; } | |
| 527 | 新增: try { saveClientKeyboard(value); setLocalKeyboard(value); setError(""); } | |
| 528 | 新增: catch { setError("未能保存本机键盘习惯,请检查本地存储空间。"); } | |
| 529 | 新增: }} | |
| 523 | 530 | /> |
| 524 | 531 | <span> |
| 525 | 532 | <strong>{title}</strong> |
| @@ -530,6 +537,7 @@ export function SettingsPanel({ | ||
| 530 | 537 | </div> |
| 531 | 538 | <p className="field-help"> |
| 532 | 539 | 终端使用 {usesControl ? "Ctrl+Shift+C / Ctrl+Shift+V" : "⌘C / ⌘V"} 复制粘贴;Ctrl+C 始终用于中断命令。 |
| 540 | 新增: {isRemoteClient() && "键盘习惯立即生效,仅保存在当前客户端,不修改云端设置。"} | |
| 533 | 541 | </p> |
| 534 | 542 | <h4>工作台快捷键</h4> |
| 535 | 543 | <div className="shortcut-list"> |
| @@ -554,8 +562,9 @@ export function SettingsPanel({ | ||
| 554 | 562 | <> |
| 555 | 563 | <div className="section-title"> |
| 556 | 564 | <h3>环境与恢复</h3> |
| 557 | 删除: <p>本机与 Cage 中的改动会双向同步。</p> | |
| 565 | 新增: <p>{isRemoteClient() ? "项目位于云端,Cage 中的改动会直接保存到云端文件。" : "本机与 Cage 中的改动会双向同步。"}</p> | |
| 558 | 566 | </div> |
| 567 | 新增: {status.local_vm_storage && !isRemoteClient() && <EnvironmentStorage status={status} onConfirm={onConfirm} />} | |
| 559 | 568 | <div className="setting-summary-row"> |
| 560 | 569 | <span>当前项目</span> |
| 561 | 570 | <strong title={current.workspace}> |
| @@ -565,7 +574,7 @@ export function SettingsPanel({ | ||
| 565 | 574 | </strong> |
| 566 | 575 | </div> |
| 567 | 576 | <p className="field-help"> |
| 568 | 删除: 点击侧栏“项目”标题旁的加号,可选择其他本地文件夹。 | |
| 577 | 新增: {isRemoteClient() ? "点击侧栏“项目”标题旁的加号,可浏览并选择云端文件夹。" : "点击侧栏“项目”标题旁的加号,可选择其他本地文件夹。"} | |
| 569 | 578 | </p> |
| 570 | 579 | <div className="project-explanation"> |
| 571 | 580 | <FolderOpen size={22} /> |
| @@ -0,0 +1,50 @@ | ||
| 1 | 新增:.setup-progress { | |
| 2 | 新增: margin: 24px auto 0; | |
| 3 | 新增: padding: 20px 24px 16px; | |
| 4 | 新增: background: var(--paper); | |
| 5 | 新增: border: 1px solid var(--line); | |
| 6 | 新增: border-radius: 16px; | |
| 7 | 新增: text-align: left; | |
| 8 | 新增: min-width: 0; | |
| 9 | 新增:} | |
| 10 | 新增:.setup-stages { | |
| 11 | 新增: display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 8px; | |
| 12 | 新增: margin: 0; padding: 0; list-style: none; | |
| 13 | 新增:} | |
| 14 | 新增:.setup-stages li { | |
| 15 | 新增: border-top: 3px solid var(--line); padding-top: 8px; | |
| 16 | 新增: font-size: .8571rem; line-height: 1.4; color: var(--muted); | |
| 17 | 新增:} | |
| 18 | 新增:.setup-stages li[aria-current="step"] { color: var(--strong); font-weight: 600; border-color: var(--accent); } | |
| 19 | 新增:.setup-transfer { margin: 28px 0 20px; } | |
| 20 | 新增:.setup-transfer-heading { display: flex; align-items: center; gap: 12px; } | |
| 21 | 新增:.setup-transfer-icon { | |
| 22 | 新增: width: 36px; height: 36px; display: grid; place-items: center; flex: none; | |
| 23 | 新增: border-radius: 10px; color: var(--accent); background: var(--chrome); | |
| 24 | 新增:} | |
| 25 | 新增:.setup-transfer-description { flex: 1; min-width: 0; } | |
| 26 | 新增:.setup-transfer-description h2 { | |
| 27 | 新增: font-size: 1.1429rem; font-weight: 600; line-height: 1.5; color: var(--strong); | |
| 28 | 新增: margin: 0; overflow-wrap: anywhere; | |
| 29 | 新增:} | |
| 30 | 新增:.setup-transfer-bytes { font-size: .8571rem; color: var(--muted); font-variant-numeric: tabular-nums; } | |
| 31 | 新增:.setup-transfer-number { font-size: 1.7143rem; font-weight: 600; color: var(--strong); font-variant-numeric: tabular-nums; } | |
| 32 | 新增:.setup-transfer-number small { font-size: .9286rem; padding-left: 2px; } | |
| 33 | 新增:.setup-meter { height: 6px; overflow: hidden; margin-top: 16px; border-radius: 8px; background: var(--chrome-dark); } | |
| 34 | 新增:.setup-meter span { display: block; height: 100%; border-radius: inherit; background: var(--accent); transition: width .25s ease-out; } | |
| 35 | 新增:.setup-meter-active span { width: 28%; animation: setup-meter-scan 1.8s ease-in-out infinite alternate; } | |
| 36 | 新增:@keyframes setup-meter-scan { from { transform: translateX(0); } to { transform: translateX(257%); } } | |
| 37 | 新增:.setup-transfer-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; } | |
| 38 | 新增:.setup-transfer-actions button { font-size: .8571rem; } | |
| 39 | 新增:.setup-transfer-error { color: var(--danger); font-size: .9286rem; line-height: 1.6; overflow-wrap: anywhere; margin: 12px 0 0; } | |
| 40 | 新增:.setup-transfer-hint { color: var(--muted); font-size: .8571rem; line-height: 1.6; margin: 8px 0 0; } | |
| 41 | 新增:@media (prefers-reduced-motion: reduce) { | |
| 42 | 新增: .setup-meter span { animation: none; transition: none; } | |
| 43 | 新增: .setup-meter-active { background: repeating-linear-gradient(110deg,var(--chrome-dark) 0 6px,var(--line) 6px 12px); } | |
| 44 | 新增: .setup-meter-active span { display: none; } | |
| 45 | 新增:} | |
| 46 | 新增:@media (max-width: 600px) { | |
| 47 | 新增: .setup-progress { padding: 16px; } | |
| 48 | 新增: .setup-transfer-heading { gap: 8px; } | |
| 49 | 新增: .setup-transfer-icon { width: 28px; height: 28px; } | |
| 50 | 新增:} | |
| @@ -0,0 +1,59 @@ | ||
| 1 | 新增:import React from "react"; | |
| 2 | 新增:import { ArrowDownToLine, Box, Layers3, PackageOpen, SlidersHorizontal } from "lucide-react"; | |
| 3 | 新增:import "./setup-progress.css"; | |
| 4 | 新增: | |
| 5 | 新增:const stages = [ | |
| 6 | 新增: ["image", "系统镜像", ArrowDownToLine], | |
| 7 | 新增: ["packages", "系统软件", Layers3], | |
| 8 | 新增: ["tools", "开发工具", PackageOpen], | |
| 9 | 新增: ["services", "环境服务", SlidersHorizontal], | |
| 10 | 新增:]; | |
| 11 | 新增: | |
| 12 | 新增:function bytes(value) { | |
| 13 | 新增: const units = ["B", "KiB", "MiB", "GiB", "TiB"]; | |
| 14 | 新增: let unit = 0; | |
| 15 | 新增: while (value >= 1024 && unit < units.length - 1) { value /= 1024; unit++; } | |
| 16 | 新增: return `${Number(value.toFixed(unit && value < 100 ? 1 : 0))} ${units[unit]}`; | |
| 17 | 新增:} | |
| 18 | 新增: | |
| 19 | 新增:export function SetupProgress({ job, onDetails, onStop, onRetry, disconnected }) { | |
| 20 | 新增: const { phase, label, received, total } = job.setup_progress; | |
| 21 | 新增: const stage = stages.find(([key]) => key === phase); | |
| 22 | 新增: const Icon = stage?.[2] || Box; | |
| 23 | 新增: const hasBytes = Number.isFinite(received) && received >= 0; | |
| 24 | 新增: const knownSize = hasBytes && Number.isFinite(total) && total > 0 && received <= total; | |
| 25 | 新增: const percent = knownSize ? Math.floor(received / total * 100) : null; | |
| 26 | 新增: const failed = Boolean(job.error); | |
| 27 | 新增: const meter = knownSize ? `${bytes(received)} / ${bytes(total)}` : hasBytes ? `已接收 ${bytes(received)}` : ""; | |
| 28 | 新增: return <section className={`setup-progress${failed ? " setup-progress-failed" : ""}`} aria-label="环境安装进度"> | |
| 29 | 新增: <ol className="setup-stages" aria-label="安装阶段"> | |
| 30 | 新增: {stages.map(([key, name]) => <li key={key} aria-current={key === phase ? "step" : undefined}>{name}</li>)} | |
| 31 | 新增: </ol> | |
| 32 | 新增: <div className="setup-transfer"> | |
| 33 | 新增: <div className="setup-transfer-heading"> | |
| 34 | 新增: <span className="setup-transfer-icon"><Icon size={19} aria-hidden="true" /></span> | |
| 35 | 新增: <div className="setup-transfer-description"> | |
| 36 | 新增: <h2>{label || stage?.[1] || "正在准备环境"}</h2> | |
| 37 | 新增: {meter && <span className="setup-transfer-bytes">{meter}</span>} | |
| 38 | 新增: </div> | |
| 39 | 新增: {knownSize && <strong className="setup-transfer-number">{percent}<small>%</small></strong>} | |
| 40 | 新增: </div> | |
| 41 | 新增: {!failed && <div role="progressbar" aria-label={label || stage?.[1] || "当前操作"} | |
| 42 | 新增: aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent ?? undefined} | |
| 43 | 新增: aria-valuetext={knownSize ? `${percent}%,${meter}` : meter || undefined} | |
| 44 | 新增: className={knownSize ? "setup-meter" : "setup-meter setup-meter-active"}> | |
| 45 | 新增: <span style={knownSize ? { width: `${received / total * 100}%` } : undefined} /> | |
| 46 | 新增: </div>} | |
| 47 | 新增: {failed && <> | |
| 48 | 新增: <p className="setup-transfer-error" role="alert">{job.error}</p> | |
| 49 | 新增: <p className="setup-transfer-hint">可手动继续安装,已保存的下载会尝试续传。</p> | |
| 50 | 新增: </>} | |
| 51 | 新增: </div> | |
| 52 | 新增: <div className="setup-transfer-actions"> | |
| 53 | 新增: <button className="text-button" type="button" onClick={onDetails}>操作详情</button> | |
| 54 | 新增: {failed | |
| 55 | 新增: ? <button type="button" className="primary" onClick={onRetry} disabled={disconnected}>继续安装</button> | |
| 56 | 新增: : <button type="button" onClick={onStop} disabled={disconnected}>停止安装</button>} | |
| 57 | 新增: </div> | |
| 58 | 新增: </section>; | |
| 59 | 新增:} | |
| @@ -2324,3 +2324,8 @@ svg { | ||
| 2324 | 2324 | background: color-mix(in srgb, var(--accent) 15%, transparent); |
| 2325 | 2325 | border: 2px solid var(--accent); color: var(--accent); pointer-events: none; |
| 2326 | 2326 | } |
| 2327 | 新增: | |
| 2328 | 新增:.environment-storage .setting-summary-row strong, | |
| 2329 | 新增:.environment-storage .field-help code { overflow-wrap: anywhere; } | |
| 2330 | 新增:.environment-storage .storage-actions { display: flex; flex-wrap: wrap; gap: 8px; } | |
| 2331 | 新增:.start-project-box .storage-entry { justify-self: start; margin: 0 16px 8px; } | |
| @@ -12,6 +12,7 @@ import { Terminal } from "@xterm/xterm"; | ||
| 12 | 12 | import { FitAddon } from "@xterm/addon-fit"; |
| 13 | 13 | import RFB from "../.generated/novnc/core/rfb.js"; |
| 14 | 14 | import { api, writeClipboard, nativeAvailable } from "./api"; |
| 15 | 新增:import { runtimeSocketURL } from "./client-context.mjs"; | |
| 15 | 16 | import { readClipboardContent, transferFiles, hasFiles, sendImage } from "./image-transfer"; |
| 16 | 17 | import { sendFiles, shellFilePaths } from "./file-transfer"; |
| 17 | 18 | import { installRemoteInput } from "./remote-input"; |
| @@ -75,7 +76,7 @@ export const RemoteView = forwardRef(function RemoteView( | ||
| 75 | 76 | if (disposed) return; |
| 76 | 77 | client = new RFB( |
| 77 | 78 | box.current, |
| 78 | 删除: `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api${desktopPrefix}/vnc`, | |
| 79 | 新增: runtimeSocketURL(`${desktopPrefix}/vnc`), | |
| 79 | 80 | { credentials: { password } }, |
| 80 | 81 | ); |
| 81 | 82 | rfb.current = client; |
| @@ -255,7 +256,7 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon | ||
| 255 | 256 | instance.current = terminal; |
| 256 | 257 | fit.current = fitter; |
| 257 | 258 | const ws = new WebSocket( |
| 258 | 删除: `${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/api/terminals/${session.id}/stream`, | |
| 259 | 新增: runtimeSocketURL(`/terminals/${session.id}/stream`), | |
| 259 | 260 | ); |
| 260 | 261 | ws.binaryType = "arraybuffer"; |
| 261 | 262 | socket.current = ws; |
| @@ -445,89 +446,4 @@ export function TerminalView({ session, visible, focused = true, onStatus, onCon | ||
| 445 | 446 | ); |
| 446 | 447 | } |
| 447 | 448 | |
| 448 | 删除:export function Modal({ title, children, onClose, wide = false, footer }) { | |
| 449 | 删除: const panel = useRef(), | |
| 450 | 删除: closeRef = useRef(onClose); | |
| 451 | 删除: closeRef.current = onClose; | |
| 452 | 删除: useEffect(() => { | |
| 453 | 删除: const previous = document.activeElement; | |
| 454 | 删除: const first = panel.current.querySelector( | |
| 455 | 删除: "input:not([disabled]),button:not([disabled]),select:not([disabled])", | |
| 456 | 删除: ); | |
| 457 | 删除: first?.focus(); | |
| 458 | 删除: const key = (e) => { | |
| 459 | 删除: if ( | |
| 460 | 删除: [...document.querySelectorAll('[role="dialog"]')].at(-1) !== | |
| 461 | 删除: panel.current | |
| 462 | 删除: ) | |
| 463 | 删除: return; | |
| 464 | 删除: if (e.key === "Escape") { | |
| 465 | 删除: if (e.target.closest('[role="combobox"][aria-expanded="true"]')) return; | |
| 466 | 删除: e.preventDefault(); | |
| 467 | 删除: e.stopPropagation(); | |
| 468 | 删除: closeRef.current?.(); | |
| 469 | 删除: } | |
| 470 | 删除: if (e.key === "Tab") { | |
| 471 | 删除: const nodes = [ | |
| 472 | 删除: ...panel.current.querySelectorAll( | |
| 473 | 删除: "input:not([disabled]),button:not([disabled]),select:not([disabled]),textarea:not([disabled]),a[href]", | |
| 474 | 删除: ), | |
| 475 | 删除: ].filter((n) => n.offsetParent !== null); | |
| 476 | 删除: if (!nodes.length) return; | |
| 477 | 删除: const index = nodes.indexOf(document.activeElement); | |
| 478 | 删除: if (e.shiftKey && index <= 0) { | |
| 479 | 删除: e.preventDefault(); | |
| 480 | 删除: nodes.at(-1).focus(); | |
| 481 | 删除: } else if (!e.shiftKey && (index === nodes.length - 1 || index < 0)) { | |
| 482 | 删除: e.preventDefault(); | |
| 483 | 删除: nodes[0].focus(); | |
| 484 | 删除: } | |
| 485 | 删除: } | |
| 486 | 删除: }; | |
| 487 | 删除: const closeEvent = () => { | |
| 488 | 删除: if ( | |
| 489 | 删除: [...document.querySelectorAll('[role="dialog"]')].at(-1) === | |
| 490 | 删除: panel.current | |
| 491 | 删除: ) | |
| 492 | 删除: closeRef.current?.(); | |
| 493 | 删除: }; | |
| 494 | 删除: document.addEventListener("cage-close-modal", closeEvent); | |
| 495 | 删除: document.addEventListener("keydown", key, true); | |
| 496 | 删除: return () => { | |
| 497 | 删除: document.removeEventListener("keydown", key, true); | |
| 498 | 删除: document.removeEventListener("cage-close-modal", closeEvent); | |
| 499 | 删除: previous?.focus?.(); | |
| 500 | 删除: }; | |
| 501 | 删除: }, []); | |
| 502 | 删除: return ( | |
| 503 | 删除: <div | |
| 504 | 删除: className="modal-scrim" | |
| 505 | 删除: onMouseDown={(e) => { | |
| 506 | 删除: if (e.target === e.currentTarget) onClose?.(); | |
| 507 | 删除: }} | |
| 508 | 删除: > | |
| 509 | 删除: <section | |
| 510 | 删除: ref={panel} | |
| 511 | 删除: className={`modal ${wide ? "wide" : ""}`} | |
| 512 | 删除: role="dialog" | |
| 513 | 删除: aria-modal="true" | |
| 514 | 删除: aria-label={title} | |
| 515 | 删除: > | |
| 516 | 删除: <header className="modal-head"> | |
| 517 | 删除: <h2>{title}</h2> | |
| 518 | 删除: {onClose && ( | |
| 519 | 删除: <button | |
| 520 | 删除: className="icon-button close-modal" | |
| 521 | 删除: aria-label="关闭面板" | |
| 522 | 删除: onClick={onClose} | |
| 523 | 删除: > | |
| 524 | 删除: × | |
| 525 | 删除: </button> | |
| 526 | 删除: )} | |
| 527 | 删除: </header> | |
| 528 | 删除: {children} | |
| 529 | 删除: {footer && <footer className="modal-footer">{footer}</footer>} | |
| 530 | 删除: </section> | |
| 531 | 删除: </div> | |
| 532 | 删除: ); | |
| 533 | 删除:} | |
| 449 | 新增:export { Modal } from "./modal"; | |
| @@ -11,6 +11,7 @@ import { | ||
| 11 | 11 | PanelLeftClose, |
| 12 | 12 | Plus, |
| 13 | 13 | Settings2, |
| 14 | 新增: Server, | |
| 14 | 15 | SquareTerminal, |
| 15 | 16 | } from "lucide-react"; |
| 16 | 17 | import { EnvironmentShield } from "./environment-shield"; |
| @@ -18,6 +19,7 @@ import logo from "./logo.png"; | ||
| 18 | 19 | import { projectName } from "./workspace-state.mjs"; |
| 19 | 20 | import { WorkspaceTabs } from "./workspace-tabs"; |
| 20 | 21 | import { AccountMenu } from "./account"; |
| 22 | 新增:import { useSSHNavigation } from "./remote-hosts"; | |
| 21 | 23 | |
| 22 | 24 | export function WorkspaceSidebar({ |
| 23 | 25 | workspace, |
| @@ -56,12 +58,14 @@ export function WorkspaceSidebar({ | ||
| 56 | 58 | onCollapse, |
| 57 | 59 | updateAction, |
| 58 | 60 | }) { |
| 61 | 新增: const ssh = useSSHNavigation(); | |
| 59 | 62 | const [collapsed, setCollapsed] = useState({}); |
| 60 | 63 | const activeWorkspace = tabs.find((tab) => tab.id === active)?.workspace; |
| 61 | 64 | useEffect(() => { |
| 62 | 65 | if (activeWorkspace) |
| 63 | 66 | setCollapsed((previous) => ({ ...previous, [activeWorkspace]: false })); |
| 64 | 67 | }, [active, activeWorkspace]); |
| 68 | 新增: if (ssh?.expanded) return null; | |
| 65 | 69 | const healthy = ready && network.mode === "open"; |
| 66 | 70 | return ( |
| 67 | 71 | <aside className="workspace-sidebar" aria-label="项目与终端"> |
| @@ -97,6 +101,7 @@ export function WorkspaceSidebar({ | ||
| 97 | 101 | <Globe2 size={17} /> |
| 98 | 102 | 浏览器 |
| 99 | 103 | </button> |
| 104 | 新增: {ssh && <button className="sidebar-link ssh-navigation" onClick={ssh.open} aria-label="SSH 主机"><Server size={17} />SSH</button>} | |
| 100 | 105 | <div className="claude-shortcuts"> |
| 101 | 106 | <button className="sidebar-link" onClick={onClaudeWeb} disabled={!ready || busy} title="在 Cage 浏览器打开 claude.ai"><MessageCircle size={17} />claude.ai</button> |
| 102 | 107 | <button className={`sidebar-link ${desktopOpen ? "selected" : ""}`} onClick={onClaudeDesktop} disabled={!running || busy} title="安装或打开 Claude Desktop"><Monitor size={17} />Claude Desktop</button> |
| @@ -1,12 +1,12 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 删除: "version": "0.1.5-alpha.2", | |
| 3 | 新增: "version": "0.1.6-alpha-preview", | |
| 4 | 4 | "lockfileVersion": 3, |
| 5 | 5 | "requires": true, |
| 6 | 6 | "packages": { |
| 7 | 7 | "": { |
| 8 | 8 | "name": "claude-cage-website", |
| 9 | 删除: "version": "0.1.5-alpha.2", | |
| 9 | 新增: "version": "0.1.6-alpha-preview", | |
| 10 | 10 | "license": "MIT", |
| 11 | 11 | "dependencies": { |
| 12 | 12 | "@fontsource-variable/inter": "^5.3.0", |
| @@ -1,7 +1,7 @@ | ||
| 1 | 1 | { |
| 2 | 2 | "name": "claude-cage-website", |
| 3 | 3 | "type": "module", |
| 4 | 删除: "version": "0.1.5-alpha.2", | |
| 4 | 新增: "version": "0.1.6-alpha-preview", | |
| 5 | 5 | "private": true, |
| 6 | 6 | "description": "Claude Cage project website and macOS, Windows and Linux downloads", |
| 7 | 7 | "license": "MIT", |