| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "net/http" |
| 10 | "strconv" |
| 11 | "strings" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/cage" |
| 15 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 16 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 17 | ) |
| 18 | |
| 19 | type claudeDesktopState struct { |
| 20 | Installed bool `json:"installed"` |
| 21 | Version string `json:"version"` |
| 22 | Running bool `json:"running"` |
| 23 | Failed bool `json:"failed"` |
| 24 | Managed bool `json:"managed"` |
| 25 | NativeUserSession bool `json:"native_user_session,omitempty"` |
| 26 | DisplayScale float64 `json:"display_scale,omitempty"` |
| 27 | FailureReason string `json:"failure_reason,omitempty"` |
| 28 | } |
| 29 | |
| 30 | const claudeDesktopSnapshot = `python3 - <<'CAGE_DESKTOP_STATE' |
| 31 | import json, subprocess |
| 32 | from pathlib import Path |
| 33 | def run(*args): |
| 34 | return subprocess.run(args, capture_output=True, text=True).stdout.strip() |
| 35 | package=run('dpkg-query','-W','-f=${Status}\n${Version}','claude-desktop').splitlines() |
| 36 | installed=bool(package and package[0]=='install ok installed') |
| 37 | state=run('systemctl','is-active','cage-claude-desktop.service') |
| 38 | result=run('systemctl','show','--property=Result','--value','cage-claude-desktop.service') if state=='failed' else '' |
| 39 | print(json.dumps({'installed':installed,'version':package[1] if installed else '', 'running':state=='active','failed':state=='failed','managed':Path('/run/cage-desktop/keyring-ready').exists(),'failure_reason':'oom-kill' if result=='oom-kill' else ''})) |
| 40 | CAGE_DESKTOP_STATE` |
| 41 | |
| 42 | func (s *Server) claudeDesktopStatus(w http.ResponseWriter, r *http.Request) { |
| 43 | if !s.vmRunning() { |
| 44 | http.Error(w, "请先启动 Cage 环境", 409) |
| 45 | return |
| 46 | } |
| 47 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 48 | defer cancel() |
| 49 | b, err := s.desktopStatus.read(ctx, s.lifetimeContext(), func(ctx context.Context) ([]byte, error) { |
| 50 | ctx, cancel := context.WithTimeout(ctx, 8*time.Second) |
| 51 | defer cancel() |
| 52 | if s.windowsGuest != nil { |
| 53 | var result claudeDesktopState |
| 54 | if err := s.windowsDesktopRequest(ctx, "status", nil, &result); err != nil { |
| 55 | return nil, err |
| 56 | } |
| 57 | return json.Marshal(result) |
| 58 | } |
| 59 | return s.guestQuick(ctx, claudeDesktopSnapshot) |
| 60 | }) |
| 61 | var state claudeDesktopState |
| 62 | if err != nil { |
| 63 | _ = diagnostics.New(s.profile).Record("warn", "claude-desktop", fmt.Sprintf("read state: %v", err)) |
| 64 | http.Error(w, usererror.Wrap("读取 Claude Desktop 状态", err, "请确认环境仍在运行;重新连接后再打开应用。持续失败时导出诊断包。").Error(), 502) |
| 65 | return |
| 66 | } |
| 67 | if json.Unmarshal(b, &state) != nil { |
| 68 | http.Error(w, "读取 Claude Desktop 状态失败:环境返回的应用状态格式无效。请更新环境组件;仍失败时导出诊断包。", 502) |
| 69 | return |
| 70 | } |
| 71 | jsonReply(w, state) |
| 72 | } |
| 73 | |
| 74 | func (s *Server) claudeDesktopAction(w http.ResponseWriter, r *http.Request) { |
| 75 | action := r.PathValue("action") |
| 76 | if action != "install" && action != "start" && action != "stop" { |
| 77 | http.NotFound(w, r) |
| 78 | return |
| 79 | } |
| 80 | var input struct{} |
| 81 | if !readJSON(w, r, &input) { |
| 82 | return |
| 83 | } |
| 84 | if !s.vmRunning() { |
| 85 | http.Error(w, "请先启动 Cage 环境", 409) |
| 86 | return |
| 87 | } |
| 88 | s.launch(w, "claude-desktop-"+action, func() error { |
| 89 | s.desktopStatus.invalidate() |
| 90 | defer s.desktopStatus.invalidate() |
| 91 | if s.windowsGuest != nil { |
| 92 | if action == "install" { |
| 93 | return errors.New("Windows 客机的自动安装尚未接通,请保留已有官方应用") |
| 94 | } |
| 95 | return s.windowsDesktopRequest(s.operationContext(), action, nil, nil) |
| 96 | } |
| 97 | switch action { |
| 98 | case "install": |
| 99 | s.mu.Lock() |
| 100 | allowed := s.toolsNetworkAllowedLocked() |
| 101 | s.mu.Unlock() |
| 102 | if !allowed { |
| 103 | return errors.New("工作台正在退出,请稍后重试安装") |
| 104 | } |
| 105 | monitorContext, stopMonitor := context.WithCancel(s.operationContext()) |
| 106 | done := make(chan struct{}) |
| 107 | go func() { |
| 108 | defer close(done) |
| 109 | ticker := time.NewTicker(10 * time.Second) |
| 110 | defer ticker.Stop() |
| 111 | for { |
| 112 | select { |
| 113 | case <-monitorContext.Done(): |
| 114 | return |
| 115 | case <-ticker.C: |
| 116 | s.monitorSafety() |
| 117 | } |
| 118 | } |
| 119 | }() |
| 120 | defer func() { |
| 121 | stopMonitor() |
| 122 | s.mu.Lock() |
| 123 | if s.monitorCancel != nil { |
| 124 | s.monitorCancel() |
| 125 | } |
| 126 | s.mu.Unlock() |
| 127 | <-done |
| 128 | }() |
| 129 | s.setMessage("正在下载并安装 Claude Desktop,可在操作详情查看进度…") |
| 130 | return RunMaintenanceScript(s.operationContext(), s.configPath, cage.ClaudeDesktopInstallScript(), s.jobs.execution(), s.jobs.execution()) |
| 131 | case "start": |
| 132 | return s.startClaudeDesktop() |
| 133 | default: |
| 134 | s.setMessage("正在关闭 Claude Desktop…") |
| 135 | return s.runDesktopScript("sudo systemctl stop cage-claude-desktop.service", 30*time.Second) |
| 136 | } |
| 137 | }) |
| 138 | } |
| 139 | |
| 140 | func (s *Server) startClaudeDesktop() error { |
| 141 | defer func() { s.desktopViews.reset(); s.desktopViews.background(s.changeDesktopVisibility) }() |
| 142 | s.desktopStatus.invalidate() |
| 143 | defer s.desktopStatus.invalidate() |
| 144 | s.setMessage("正在打开 Claude Desktop…") |
| 145 | key, err := s.account.desktopKey() |
| 146 | if err != nil { |
| 147 | return err |
| 148 | } |
| 149 | defer clear(key) |
| 150 | script := `test "$(dpkg-query -W -f='${Status}' claude-desktop 2>/dev/null)" = 'install ok installed' || { echo '请先安装 Claude Desktop。'; exit 1; } |
| 151 | ` + cage.ClaudeDesktopProvisionScript() |
| 152 | if err = s.runDesktopScript(script, 20*time.Second); err != nil { |
| 153 | return err |
| 154 | } |
| 155 | ctx, cancel := context.WithTimeout(s.operationContext(), 55*time.Second) |
| 156 | defer cancel() |
| 157 | cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "/usr/local/bin/cage-claude-start") |
| 158 | cmd.Stdin = bytes.NewReader(key) |
| 159 | cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution() |
| 160 | if err = cmd.Run(); err != nil { |
| 161 | return executionFailure("打开 Claude Desktop", errors.Join(ctx.Err(), err), s.jobs.snapshot().Log) |
| 162 | } |
| 163 | return nil |
| 164 | } |
| 165 | |
| 166 | func (s *Server) runDesktopScript(script string, timeout time.Duration) error { |
| 167 | ctx, cancel := context.WithTimeout(s.operationContext(), timeout) |
| 168 | defer cancel() |
| 169 | |
| 170 | |
| 171 | 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())) |
| 172 | cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command) |
| 173 | cmd.Stdin = strings.NewReader(script) |
| 174 | cmd.Stdout, cmd.Stderr = s.jobs.execution(), s.jobs.execution() |
| 175 | if err := cmd.Run(); err != nil { |
| 176 | if ctx.Err() != nil { |
| 177 | cleanup, finish := context.WithTimeout(context.Background(), 5*time.Second) |
| 178 | defer finish() |
| 179 | _, _ = s.guest(cleanup, "sudo systemctl stop cage-desktop-operation.service") |
| 180 | return ctx.Err() |
| 181 | } |
| 182 | return executionFailure("准备或关闭 Claude Desktop", err, s.jobs.snapshot().Log) |
| 183 | } |
| 184 | return nil |
| 185 | } |
| 186 | |
| 187 | func (s *Server) claudeDesktopCredentials(w http.ResponseWriter, r *http.Request) { |
| 188 | if s.windowsGuest != nil { |
| 189 | s.windowsDesktopCredentials(w, r) |
| 190 | return |
| 191 | } |
| 192 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 193 | defer cancel() |
| 194 | b, err := s.guestQuick(ctx, `set -eu |
| 195 | systemctl is-active --quiet cage-claude-desktop.service |
| 196 | password=$(cat /home/cage/.config/claude-cage/desktop-password) |
| 197 | printf '%s\n' "$password" |
| 198 | if test -f /run/cage-desktop/base-display-scale; then cat /run/cage-desktop/base-display-scale |
| 199 | elif test -f /run/cage-desktop/display-scale; then cat /run/cage-desktop/display-scale |
| 200 | else echo; fi |
| 201 | if test -f /run/cage-desktop/xsettings.pid; then echo dynamic; fi`) |
| 202 | password, scale, _ := strings.Cut(strings.TrimSpace(string(b)), "\n") |
| 203 | if err != nil || len(password) != 8 { |
| 204 | http.Error(w, "Claude Desktop 尚未启动", 409) |
| 205 | return |
| 206 | } |
| 207 | |
| 208 | scale, dynamic, _ := strings.Cut(scale, "\n") |
| 209 | density := 2.0 |
| 210 | if scale == "1.5" { |
| 211 | density = 1.5 |
| 212 | } |
| 213 | jsonReply(w, map[string]any{"password": password, "display_scale": density, "dynamic_scale": dynamic == "dynamic"}) |
| 214 | } |
| 215 | |
| 216 | |
| 217 | func validDisplayDensity(scale float64) bool { |
| 218 | return scale == 0 || scale >= 0.75 && scale <= 4 |
| 219 | } |
| 220 | |
| 221 | func (s *Server) claudeDesktopResize(w http.ResponseWriter, r *http.Request) { |
| 222 | var input struct { |
| 223 | Width int `json:"width"` |
| 224 | Height int `json:"height"` |
| 225 | Scale float64 `json:"scale"` |
| 226 | } |
| 227 | if !readJSON(w, r, &input) { |
| 228 | return |
| 229 | } |
| 230 | if input.Width < 320 || input.Height < 240 || input.Width > 8192 || input.Height > 8192 || !validDisplayDensity(input.Scale) { |
| 231 | http.Error(w, "画面尺寸无效", 400) |
| 232 | return |
| 233 | } |
| 234 | if s.windowsGuest != nil { |
| 235 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 236 | defer cancel() |
| 237 | if err := s.windowsDesktopRequest(ctx, "resize", map[string]any{"width": input.Width, "height": input.Height}, nil); err != nil { |
| 238 | http.Error(w, err.Error(), 502) |
| 239 | return |
| 240 | } |
| 241 | jsonReply(w, map[string]bool{"ok": true}) |
| 242 | return |
| 243 | } |
| 244 | scale := "" |
| 245 | if input.Scale != 0 { |
| 246 | scale = strconv.FormatFloat(input.Scale, 'f', -1, 64) |
| 247 | } |
| 248 | script := desktopResizeScript(input.Width, input.Height, scale) |
| 249 | ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second) |
| 250 | defer cancel() |
| 251 | output, err := s.guestQuick(ctx, script) |
| 252 | if err != nil { |
| 253 | http.Error(w, "Claude Desktop 画面尺寸未能调整", 502) |
| 254 | return |
| 255 | } |
| 256 | reply := map[string]any{"ok": true} |
| 257 | if applied, _, _ := strings.Cut(string(output), "\n"); scale != "" && strings.TrimSpace(applied) == "scale "+scale { |
| 258 | reply["scale"] = input.Scale |
| 259 | } |
| 260 | jsonReply(w, reply) |
| 261 | } |
| 262 | |
| 263 | |
| 264 | |
| 265 | func desktopResizeScript(wid, hei int, scale string) string { |
| 266 | return fmt.Sprintf(`set -eu |
| 267 | export DISPLAY=:78 XAUTHORITY=/run/cage-desktop/Xauthority |
| 268 | exec 9>/run/cage-desktop/resize.lock |
| 269 | flock 9 |
| 270 | requested=%s |
| 271 | manager= |
| 272 | if test -r /run/cage-desktop/xsettings.pid; then |
| 273 | manager=$(cat /run/cage-desktop/xsettings.pid) |
| 274 | if test "$(cat "/proc/$manager/comm" 2>/dev/null)" != xsettingsd; then manager=; fi |
| 275 | fi |
| 276 | # A fixed-density session ignores the request, and its viewer sizes for that |
| 277 | # density. A viewer that names none sized its display for the configured one. |
| 278 | scale= |
| 279 | if test -n "$manager"; then |
| 280 | scale=${requested:-$(cat /run/cage-desktop/base-display-scale 2>/dev/null || echo 2)} |
| 281 | if test -n "$requested"; then echo "scale $scale"; fi |
| 282 | fi |
| 283 | printf '%%s %%s %%s\n' %d %d "$scale" > /run/cage-desktop/desktop-size |
| 284 | # A phone holds the display. Its release applies this size and density. |
| 285 | if test -f /run/cage-phone-desktop/layout.json; then exit 0; fi |
| 286 | if test -n "$manager" && test "$(cat /run/cage-desktop/display-scale 2>/dev/null)" != "$scale"; then |
| 287 | dpi=$(awk -v scale="$scale" 'BEGIN {printf "%%.0f", scale * 96 * 1024}') |
| 288 | printf 'Xft/DPI %%s\nGdk/WindowScalingFactor 1\nGdk/UnscaledDPI %%s\nGtk/DecorationLayout ":"\n' "$dpi" "$dpi" > /run/cage-desktop/xsettings.conf.new |
| 289 | mv /run/cage-desktop/xsettings.conf.new /run/cage-desktop/xsettings.conf |
| 290 | kill -HUP "$manager" |
| 291 | printf '%%s\n' "$scale" > /run/cage-desktop/display-scale |
| 292 | fi |
| 293 | name=cage-%dx%d |
| 294 | if ! xrandr --query | grep -q " $name "; then |
| 295 | xrandr --newmode "$name" %.3f %d %d %d %d %d %d %d %d +HSync -VSync |
| 296 | xrandr --addmode VNC-0 "$name" |
| 297 | fi |
| 298 | xrandr --output VNC-0 --mode "$name" |
| 299 | for old in $(xrandr --query | awk '/^ +cage-/ {print $1}'); do |
| 300 | if [ "$old" != "$name" ]; then xrandr --delmode VNC-0 "$old"; xrandr --rmmode "$old"; fi |
| 301 | done`, scale, wid, hei, wid, hei, float64((wid+32)*(hei+8)*60)/1000000, wid, wid+8, wid+16, wid+32, hei, hei+1, hei+2, hei+8) |
| 302 | } |
| 303 | |
| 304 | func (s *Server) claudeDesktopVNC(w http.ResponseWriter, r *http.Request) { |
| 305 | if s.windowsGuest != nil { |
| 306 | s.windowsDesktopVNC(w, r) |
| 307 | return |
| 308 | } |
| 309 | if !s.vmRunning() { |
| 310 | http.Error(w, "环境尚未启动", 409) |
| 311 | return |
| 312 | } |
| 313 | release, err := s.acquireDesktopView() |
| 314 | if err != nil { |
| 315 | http.Error(w, "无法恢复 Claude Desktop 画面,请重新连接", http.StatusBadGateway) |
| 316 | return |
| 317 | } |
| 318 | defer release() |
| 319 | ctx, cancel := context.WithCancel(r.Context()) |
| 320 | defer cancel() |
| 321 | |
| 322 | |
| 323 | cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", "exec socat STDIO UNIX-CONNECT:/run/cage-desktop/vnc.sock") |
| 324 | reader, err := cmd.StdoutPipe() |
| 325 | if err != nil { |
| 326 | http.Error(w, "无法连接应用画面", 502) |
| 327 | return |
| 328 | } |
| 329 | writer, err := cmd.StdinPipe() |
| 330 | if err != nil { |
| 331 | _ = reader.Close() |
| 332 | http.Error(w, "无法连接应用画面", 502) |
| 333 | return |
| 334 | } |
| 335 | if err = cmd.Start(); err != nil { |
| 336 | _ = reader.Close() |
| 337 | _ = writer.Close() |
| 338 | http.Error(w, "无法连接应用画面", 502) |
| 339 | return |
| 340 | } |
| 341 | defer func() { cancel(); writer.Close(); reader.Close(); _ = cmd.Wait() }() |
| 342 | s.streamVNC(w, r, reader, writer, func() { cancel(); _ = writer.Close(); _ = reader.Close() }) |
| 343 | } |