| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "image/png" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "strings" |
| 13 | "time" |
| 14 | ) |
| 15 | |
| 16 | const maxImageBytes = 20 << 20 |
| 17 | |
| 18 | type imageInputRequest struct { |
| 19 | PNG string `json:"png"` |
| 20 | Text *string `json:"text,omitempty"` |
| 21 | Target string `json:"target"` |
| 22 | ID string `json:"id"` |
| 23 | Transfer string `json:"transfer,omitempty"` |
| 24 | Context string `json:"context,omitempty"` |
| 25 | Window uint32 `json:"window,omitempty"` |
| 26 | PID int32 `json:"pid,omitempty"` |
| 27 | } |
| 28 | |
| 29 | func (s *Server) pasteInputStart(w http.ResponseWriter, r *http.Request) { |
| 30 | var input imageInputRequest |
| 31 | if !readJSON(w, r, &input) { |
| 32 | return |
| 33 | } |
| 34 | if input.Target == "browser" && (input.ID == "" || len(input.ID) > 256) { |
| 35 | http.Error(w, "请选择粘贴的网页", http.StatusBadRequest) |
| 36 | return |
| 37 | } |
| 38 | if !s.fileTargetReady(input.Target, input.ID) { |
| 39 | http.Error(w, "粘贴接收位置已关闭,请重新点击输入框", http.StatusConflict) |
| 40 | return |
| 41 | } |
| 42 | ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second) |
| 43 | defer cancel() |
| 44 | if input.Target == "terminal" { |
| 45 | jsonReply(w, map[string]any{"available": true, "context": input.ID}) |
| 46 | return |
| 47 | } |
| 48 | if input.Target == "desktop" { |
| 49 | body, _ := json.Marshal(map[string]any{"kind": "image", "window": input.Window, "pid": input.PID}) |
| 50 | result, err := s.guestFiles(ctx, "desktop", "POST", "/start", bytes.NewReader(body), "") |
| 51 | id, _ := result["id"].(string) |
| 52 | if err != nil || !browserFileID.MatchString(id) { |
| 53 | http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict) |
| 54 | return |
| 55 | } |
| 56 | jsonReply(w, map[string]any{"available": true, "transfer": id}) |
| 57 | return |
| 58 | } |
| 59 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 60 | data, err := s.nativeBrowserClient().request(ctx, "POST", "/paste-start", map[string]any{"id": input.ID, "length": 0}) |
| 61 | var result struct { |
| 62 | Transfer string `json:"transfer"` |
| 63 | } |
| 64 | if err != nil || json.Unmarshal(data, &result) != nil || !validInputToken(result.Transfer) { |
| 65 | http.Error(w, "粘贴目标未能绑定,请重新点击输入框。旧客机需要先同步环境组件", http.StatusConflict) |
| 66 | return |
| 67 | } |
| 68 | jsonReply(w, map[string]any{"available": true, "transfer": result.Transfer}) |
| 69 | return |
| 70 | } |
| 71 | data, err := s.browserAction(ctx, "ime", &browserInput{Target: "browser", ID: input.ID, Mode: "status"}) |
| 72 | var state struct { |
| 73 | Available bool `json:"available"` |
| 74 | Context string `json:"context"` |
| 75 | } |
| 76 | if err != nil || json.Unmarshal(data, &state) != nil || !state.Available || !validInputToken(state.Context) { |
| 77 | http.Error(w, "图片接收位置尚未聚焦,请点击输入框后重试", http.StatusConflict) |
| 78 | return |
| 79 | } |
| 80 | jsonReply(w, map[string]any{"available": true, "context": state.Context}) |
| 81 | } |
| 82 | |
| 83 | func (s *Server) pasteInputCancel(w http.ResponseWriter, r *http.Request) { |
| 84 | var input imageInputRequest |
| 85 | if !readJSON(w, r, &input) { |
| 86 | return |
| 87 | } |
| 88 | ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) |
| 89 | defer cancel() |
| 90 | if input.Target == "desktop" && browserFileID.MatchString(input.Transfer) { |
| 91 | body, _ := json.Marshal(map[string]string{"id": input.Transfer}) |
| 92 | _, _ = s.guestFiles(ctx, "desktop", "POST", "/cancel", bytes.NewReader(body), "") |
| 93 | } else if input.Target == "browser" && validInputToken(input.Transfer) && (s.macosGuest != nil || s.windowsGuest != nil) { |
| 94 | _, _ = s.nativeBrowserClient().request(ctx, "POST", "/paste-cancel", map[string]string{"transfer": input.Transfer}) |
| 95 | } |
| 96 | jsonReply(w, map[string]bool{"ok": true}) |
| 97 | } |
| 98 | |
| 99 | func (s *Server) textInput(w http.ResponseWriter, r *http.Request) { |
| 100 | var input imageInputRequest |
| 101 | if !readJSON(w, r, &input, 6*(2<<20)+4096) { |
| 102 | return |
| 103 | } |
| 104 | if input.Target != "browser" || input.ID == "" || len(input.ID) > 256 || input.Text == nil || len(*input.Text) > 2<<20 { |
| 105 | http.Error(w, "粘贴文字或目标无效,文本最多 2 MiB", http.StatusBadRequest) |
| 106 | return |
| 107 | } |
| 108 | if !s.fileTargetReady("browser", input.ID) { |
| 109 | http.Error(w, "网页已关闭或环境尚未就绪", http.StatusConflict) |
| 110 | return |
| 111 | } |
| 112 | ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) |
| 113 | defer cancel() |
| 114 | if *input.Text == "" { |
| 115 | jsonReply(w, map[string]bool{"ok": true}) |
| 116 | return |
| 117 | } |
| 118 | var err error |
| 119 | if s.macosGuest != nil || s.windowsGuest != nil { |
| 120 | if !validInputToken(input.Transfer) { |
| 121 | http.Error(w, "粘贴目标尚未绑定,请重新点击输入框", http.StatusConflict) |
| 122 | return |
| 123 | } |
| 124 | _, err = s.nativeBrowserClient().pasteData(ctx, input.ID, []byte(*input.Text), input.Transfer, "text/plain") |
| 125 | } else { |
| 126 | if !validInputToken(input.Context) { |
| 127 | http.Error(w, "粘贴目标尚未绑定,请重新点击输入框", http.StatusConflict) |
| 128 | return |
| 129 | } |
| 130 | body, _ := json.Marshal(map[string]string{"id": input.ID, "text": *input.Text, "context": input.Context}) |
| 131 | s.mu.Lock() |
| 132 | token := s.credentials.Token |
| 133 | s.mu.Unlock() |
| 134 | _, err = s.guestAPI(ctx, token, "POST", "/paste-text", body) |
| 135 | } |
| 136 | if err != nil { |
| 137 | http.Error(w, "文字未能交给原输入位置,请核对页面与客机组件后重试", http.StatusConflict) |
| 138 | return |
| 139 | } |
| 140 | jsonReply(w, map[string]bool{"ok": true}) |
| 141 | } |
| 142 | |
| 143 | func decodeInputImage(encoded string) ([]byte, error) { |
| 144 | if len(encoded) > base64.StdEncoding.EncodedLen(maxImageBytes) { |
| 145 | return nil, errors.New("图片不能超过 20 MB") |
| 146 | } |
| 147 | data, err := base64.StdEncoding.Strict().DecodeString(encoded) |
| 148 | if err != nil || len(data) == 0 || len(data) > maxImageBytes { |
| 149 | return nil, errors.New("图片数据无效") |
| 150 | } |
| 151 | return validateInputImage(data) |
| 152 | } |
| 153 | |
| 154 | func validateInputImage(data []byte) ([]byte, error) { |
| 155 | if len(data) == 0 || len(data) > maxImageBytes { |
| 156 | return nil, errors.New("图片数据无效") |
| 157 | } |
| 158 | config, err := png.DecodeConfig(bytes.NewReader(data)) |
| 159 | if err != nil || config.Width <= 0 || config.Height <= 0 || int64(config.Width)*int64(config.Height) > 40_000_000 { |
| 160 | return nil, errors.New("需要有效的 PNG 图片,且不能超过 4000 万像素") |
| 161 | } |
| 162 | if _, err := png.Decode(bytes.NewReader(data)); err != nil { |
| 163 | return nil, errors.New("图片已损坏,请重新复制或选择图片") |
| 164 | } |
| 165 | return data, nil |
| 166 | } |
| 167 | |
| 168 | func (s *Server) imageInput(w http.ResponseWriter, r *http.Request) { |
| 169 | var input imageInputRequest |
| 170 | if !readJSON(w, r, &input, int64(base64.StdEncoding.EncodedLen(maxImageBytes)+4096)) { |
| 171 | return |
| 172 | } |
| 173 | if (input.Target != "browser" && input.Target != "desktop" && input.Target != "terminal") || (input.Target != "desktop" && input.ID == "") || len(input.ID) > 256 { |
| 174 | http.Error(w, "图片目标无效", 400) |
| 175 | return |
| 176 | } |
| 177 | s.mu.Lock() |
| 178 | ready, token, terminal := s.ready, s.credentials.Token, s.terminals.get(input.ID) |
| 179 | s.mu.Unlock() |
| 180 | if !ready { |
| 181 | http.Error(w, "环境尚未就绪", 409) |
| 182 | return |
| 183 | } |
| 184 | if input.Target == "terminal" { |
| 185 | if terminal == nil { |
| 186 | http.Error(w, "终端已关闭", 409) |
| 187 | return |
| 188 | } |
| 189 | terminal.mu.Lock() |
| 190 | closed := terminal.closed |
| 191 | terminal.mu.Unlock() |
| 192 | if closed { |
| 193 | http.Error(w, "终端已关闭", 409) |
| 194 | return |
| 195 | } |
| 196 | } |
| 197 | data, err := decodeInputImage(input.PNG) |
| 198 | if err != nil { |
| 199 | requestError(w, err) |
| 200 | return |
| 201 | } |
| 202 | ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) |
| 203 | defer cancel() |
| 204 | if input.Target == "browser" { |
| 205 | if input.Context != "" && s.macosGuest == nil && s.windowsGuest == nil { |
| 206 | state, checkErr := s.browserAction(ctx, "ime", &browserInput{Target: "browser", ID: input.ID, Mode: "status"}) |
| 207 | var current struct { |
| 208 | Available bool `json:"available"` |
| 209 | Context string `json:"context"` |
| 210 | } |
| 211 | if checkErr != nil || json.Unmarshal(state, ¤t) != nil || !current.Available || current.Context != input.Context { |
| 212 | http.Error(w, "图片接收位置已变化,请重新粘贴", http.StatusConflict) |
| 213 | return |
| 214 | } |
| 215 | } |
| 216 | body, _ := json.Marshal(map[string]string{"id": input.ID, "png": input.PNG, "transfer": input.Transfer}) |
| 217 | if _, err = s.guestAPI(ctx, token, "POST", "/paste-image", body); err != nil { |
| 218 | http.Error(w, "图片未能粘贴,请点击支持图片的输入框后重试;环境组件过旧时请先更新环境", 502) |
| 219 | return |
| 220 | } |
| 221 | jsonReply(w, map[string]bool{"ok": true}) |
| 222 | return |
| 223 | } |
| 224 | if input.Target == "desktop" { |
| 225 | if !browserFileID.MatchString(input.Transfer) { |
| 226 | http.Error(w, "图片目标尚未绑定,请重新点击输入框后粘贴", http.StatusConflict) |
| 227 | return |
| 228 | } |
| 229 | if _, err = s.guestFiles(ctx, "desktop", "POST", "/upload?id="+input.Transfer, bytes.NewReader(data), "image.png"); err == nil { |
| 230 | body, _ := json.Marshal(map[string]string{"id": input.Transfer}) |
| 231 | var result map[string]any |
| 232 | result, err = s.guestFiles(ctx, "desktop", "POST", "/finish-image", bytes.NewReader(body), "") |
| 233 | if err == nil { |
| 234 | jsonReply(w, result) |
| 235 | return |
| 236 | } |
| 237 | } |
| 238 | http.Error(w, "图片未能交给原输入位置,请核对窗口和客机组件后重新粘贴", http.StatusConflict) |
| 239 | return |
| 240 | } |
| 241 | result, err := s.guestImage(ctx, input.Target, data, macOSWindowRequest{Window: input.Window, PID: input.PID}) |
| 242 | if err != nil { |
| 243 | http.Error(w, err.Error(), 502) |
| 244 | return |
| 245 | } |
| 246 | jsonReply(w, result) |
| 247 | } |
| 248 | |
| 249 | func (s *Server) guestImage(ctx context.Context, target string, data []byte, window macOSWindowRequest) (map[string]any, error) { |
| 250 | if s.macosGuest != nil && target == "desktop" { |
| 251 | return s.macOSPasteDesktopImage(ctx, data, window) |
| 252 | } |
| 253 | if s.macosGuest != nil && target == "terminal" { |
| 254 | result, err := s.guestFiles(ctx, target, "POST", "/upload", bytes.NewReader(data), "image.png") |
| 255 | if err != nil { |
| 256 | return nil, err |
| 257 | } |
| 258 | path, _ := result["path"].(string) |
| 259 | if !s.validMacOSAttachmentPath(path, "image.png") { |
| 260 | return nil, errors.New("图片保存路径无效") |
| 261 | } |
| 262 | return result, nil |
| 263 | } |
| 264 | if s.windowsGuest != nil { |
| 265 | if target == "terminal" { |
| 266 | return s.windowsSaveAttachment(ctx, "image.png", bytes.NewReader(data)) |
| 267 | } |
| 268 | var result map[string]any |
| 269 | err := s.windowsDesktopRequest(ctx, "paste-image", map[string]any{"png": base64.StdEncoding.EncodeToString(data)}, &result) |
| 270 | return result, err |
| 271 | } |
| 272 | script := "sudo -H -u cage /usr/local/bin/cage-image-input save" |
| 273 | if target == "desktop" { |
| 274 | 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" |
| 275 | } |
| 276 | cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", script) |
| 277 | cmd.Stdin = bytes.NewReader(data) |
| 278 | pipe, err := cmd.StdoutPipe() |
| 279 | if err != nil { |
| 280 | return nil, err |
| 281 | } |
| 282 | if err = cmd.Start(); err != nil { |
| 283 | return nil, errors.New("无法连接 Cage 环境") |
| 284 | } |
| 285 | output, readErr := io.ReadAll(io.LimitReader(pipe, 4097)) |
| 286 | if readErr != nil || len(output) > 4096 { |
| 287 | _ = cmd.Process.Kill() |
| 288 | _ = cmd.Wait() |
| 289 | return nil, errors.New("图片传递响应无效") |
| 290 | } |
| 291 | if err = cmd.Wait(); err != nil { |
| 292 | return nil, errors.New("图片未能传入 Cage,请确认目标已打开并支持图片;环境组件过旧时请先更新环境") |
| 293 | } |
| 294 | var result map[string]any |
| 295 | if json.Unmarshal(output, &result) != nil { |
| 296 | return nil, errors.New("图片传递响应无效") |
| 297 | } |
| 298 | if target == "terminal" { |
| 299 | path, ok := result["path"].(string) |
| 300 | if !ok || !strings.HasPrefix(path, "/home/cage/.local/share/cage/attachments/image-") || strings.ContainsAny(path, "'\r\n\x00") { |
| 301 | return nil, errors.New("图片保存路径无效") |
| 302 | } |
| 303 | } |
| 304 | return result, nil |
| 305 | } |