跳到主要内容

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

浏览文件

windows_display.go

849 行 · 24.4 KB历史下载
1package workbench
2
3import (
4 "bufio"
5 "bytes"
6 "compress/zlib"
7 "context"
8 "encoding/base64"
9 "encoding/binary"
10 "encoding/json"
11 "errors"
12 "image"
13 "image/color"
14 "image/draw"
15 _ "image/jpeg"
16 _ "image/png"
17 "io"
18 "net"
19 "net/http"
20 "os/exec"
21 "sync"
22 "time"
23
24 "github.com/sylvinus/agent-vm/internal/guestos"
25)
26
27type windowsWindowFrame struct {
28 Sequence string `json:"sequence,omitempty"`
29 Unchanged bool `json:"unchanged,omitempty"`
30 ID string `json:"id"`
31 Document string `json:"document"`
32 PNG string `json:"png"`
33 JPEG string `json:"jpeg"`
34 Width int `json:"width"`
35 Height int `json:"height"`
36 Target string `json:"target"`
37 Density float64 `json:"density"`
38 Panes []windowsWindowPane `json:"panes,omitempty"`
39 Overlays []windowsWindowPane `json:"overlays,omitempty"`
40 Wheel bool `json:"pixelWheel,omitempty"` // the guest scrolls by a pointer event's distance
41}
42
43type windowsWindowPane struct {
44 windowsWindowFrame
45 X int `json:"x"`
46 Y int `json:"y"`
47}
48
49type windowsWindowFailure struct{ code string }
50
51func (e windowsWindowFailure) Error() string {
52 return "Windows 应用操作未完成,请确认客机已解锁且 Claude 窗口仍在运行"
53}
54
55// Retry only validated frame reads during short window/popup transitions.
56// Session, identity, permission and transport failures are never suppressed.
57func transientWindowFrame(code string) bool {
58 switch code {
59 case "browser_target_changed", "target_changed", "desktop_target_changed", "desktop_capture_busy", "desktop_empty_frame":
60 return true
61 }
62 return false
63}
64
65func requestDesktopFrame(ctx context.Context, request func(any, any) error, input map[string]any, output any) error {
66 for attempt := 0; ; attempt++ {
67 err := request(input, output)
68 var failure windowsWindowFailure
69 if attempt >= 5 || !errors.As(err, &failure) || !transientWindowFrame(failure.code) {
70 return err
71 }
72 timer := time.NewTimer(80 * time.Millisecond)
73 select {
74 case <-ctx.Done():
75 timer.Stop()
76 return ctx.Err()
77 case <-timer.C:
78 }
79 }
80}
81
82// release ends the guest connection that owns this viewer's held keys and
83// buttons and opens another.
84func desktopViewerRequest(ctx context.Context, request func(any, any) error, release func() error) func(map[string]any, any) error {
85 inputSuspended := false
86 return func(input map[string]any, output any) error {
87 if input["action"] == "frame" {
88 if inputSuspended {
89 delete(input, "after")
90 }
91 err := requestDesktopFrame(ctx, request, input, output)
92 if err == nil && !output.(*windowsWindowFrame).Unchanged {
93 inputSuspended = false
94 }
95 return err
96 }
97 isInput := input["action"] == "pointer" || input["action"] == "key" || input["action"] == "text"
98 if isInput && inputSuspended {
99 return nil
100 }
101 err := request(input, output)
102 var failure windowsWindowFailure
103 if isInput && errors.As(err, &failure) && failure.code == "desktop_target_changed" {
104 // The guest keeps keys and buttons held when it rejects an event:
105 // a dropped key-up would leave its key down. Release them, then
106 // drop the old event and queued input; never replay it on a popup.
107 if err := release(); err != nil {
108 return err
109 }
110 inputSuspended = true
111 return nil
112 }
113 return err
114 }
115}
116
117// A viewer's guest connection owns the keys and buttons it holds down, and
118// the guest releases them when that connection ends.
119type desktopViewerConnection struct {
120 mu sync.Mutex
121 current *nativeWindowConnection
122 closed bool
123}
124
125func (c *desktopViewerConnection) request(input, output any) error {
126 c.mu.Lock()
127 current := c.current
128 c.mu.Unlock()
129 return current.request(input, output)
130}
131
132func (c *desktopViewerConnection) replace(open func() (*nativeWindowConnection, error)) error {
133 next, err := open()
134 if err != nil {
135 return err
136 }
137 c.mu.Lock()
138 if c.closed {
139 c.mu.Unlock()
140 next.Close()
141 return net.ErrClosed
142 }
143 previous := c.current
144 c.current = next
145 c.mu.Unlock()
146 previous.Close()
147 return nil
148}
149
150func (c *desktopViewerConnection) Close() {
151 c.mu.Lock()
152 c.closed = true
153 current := c.current
154 c.mu.Unlock()
155 current.Close()
156}
157
158type nativeWindowConnection struct {
159 cmd *exec.Cmd
160 input io.WriteCloser
161 output io.ReadCloser
162 scanner *bufio.Scanner
163 cancel context.CancelFunc
164 once sync.Once
165}
166
167func (s *Server) windowsWindowConnection(ctx context.Context) (*nativeWindowConnection, error) {
168 ctx, cancel := context.WithCancel(ctx)
169 cmd, err := guestos.WindowsRelayCommand(ctx, s.profile, "desktop")
170 if err != nil {
171 cancel()
172 return nil, err
173 }
174 return startWindowConnection(cmd, cancel)
175}
176
177func startWindowConnection(cmd *exec.Cmd, cancel context.CancelFunc) (*nativeWindowConnection, error) {
178 input, err := cmd.StdinPipe()
179 if err != nil {
180 cancel()
181 return nil, err
182 }
183 output, err := cmd.StdoutPipe()
184 if err != nil {
185 input.Close()
186 cancel()
187 return nil, err
188 }
189 if err = cmd.Start(); err != nil {
190 input.Close()
191 output.Close()
192 cancel()
193 return nil, err
194 }
195 scanner := bufio.NewScanner(output)
196 scanner.Buffer(make([]byte, 64<<10), clipboardWireLimit)
197 return &nativeWindowConnection{cmd: cmd, input: input, output: output, scanner: scanner, cancel: cancel}, nil
198}
199
200func (c *nativeWindowConnection) Close() {
201 c.once.Do(func() { c.cancel(); c.input.Close(); c.output.Close(); _ = c.cmd.Wait() })
202}
203
204func (c *nativeWindowConnection) request(input any, output any) error {
205 if err := json.NewEncoder(c.input).Encode(input); err != nil {
206 return err
207 }
208 if !c.scanner.Scan() {
209 return errors.New("客机应用连接中断")
210 }
211 var status struct {
212 Error string `json:"error"`
213 }
214 if json.Unmarshal(c.scanner.Bytes(), &status) != nil {
215 return errors.New("客机应用返回了无效响应")
216 }
217 if status.Error != "" {
218 return windowsWindowFailure{code: status.Error}
219 }
220 if output == nil {
221 return nil
222 }
223 return json.Unmarshal(c.scanner.Bytes(), output)
224}
225
226func (s *Server) windowsDesktopRequest(ctx context.Context, action string, input map[string]any, output any) error {
227 connection, err := s.windowsWindowConnection(ctx)
228 if err != nil {
229 return err
230 }
231 defer connection.Close()
232 if input == nil {
233 input = map[string]any{}
234 }
235 input["action"] = action
236 return connection.request(input, output)
237}
238
239// Windows renders the same RFB view used by Linux. The guest publishes only its
240// application client area; the controller never requests a desktop screenshot.
241func (s *Server) windowsDesktopVNC(w http.ResponseWriter, r *http.Request) {
242 ctx, cancel := context.WithCancel(r.Context())
243 defer cancel()
244 first, err := s.windowsWindowConnection(ctx)
245 if err != nil {
246 http.Error(w, "Windows 应用画面尚未连接", 502)
247 return
248 }
249 connection := &desktopViewerConnection{current: first}
250 defer connection.Close()
251 var frame windowsWindowFrame
252 if err = requestDesktopFrame(ctx, connection.request, map[string]any{"action": "frame"}, &frame); err != nil {
253 http.Error(w, err.Error(), 409)
254 return
255 }
256 local, remote := net.Pipe()
257 defer local.Close()
258 done := make(chan struct{})
259 go func() {
260 defer close(done)
261 defer remote.Close()
262 request := desktopViewerRequest(ctx, connection.request, func() error {
263 return connection.replace(func() (*nativeWindowConnection, error) { return s.windowsWindowConnection(ctx) })
264 })
265 _ = serveWindowsWindowRFB(remote, frame, func(input map[string]any, output any) error {
266 s.mu.Lock()
267 keyboard := s.preferences.Keyboard
268 s.mu.Unlock()
269 if input["action"] == "key" {
270 if key, ok := input["keysym"].(uint32); ok {
271 input["keysym"] = windowsGuestKeysym(key, keyboard)
272 }
273 }
274 return request(input, output)
275 })
276 }()
277 s.streamVNC(w, r, local, local, func() { cancel(); local.Close(); remote.Close(); connection.Close() })
278 <-done
279}
280
281func windowsGuestKeysym(key uint32, keyboard string) uint32 {
282 if keyboard == "mac" && (key == 0xffe7 || key == 0xffe8 || key == 0xffeb || key == 0xffec) {
283 return 0xffe3
284 }
285 return key
286}
287
288func nativeFrameImage(frame windowsWindowFrame) (image.Image, error) {
289 if frame.Width < 1 || frame.Height < 1 || frame.Width > 8192 || frame.Height > 8192 || int64(frame.Width)*int64(frame.Height) > 40_000_000 || len(frame.Target) == 0 || len(frame.Target) > 256 {
290 return nil, errors.New("应用画面无效")
291 }
292 if len(frame.Overlays) > 0 {
293 if len(frame.Overlays) > 16 {
294 return nil, errors.New("应用覆盖画面无效")
295 }
296 overlays := frame.Overlays
297 frame.Overlays = nil
298 base, err := nativeFrameImage(frame)
299 if err != nil {
300 return nil, err
301 }
302 canvas := image.NewRGBA(base.Bounds())
303 draw.Draw(canvas, canvas.Bounds(), base, base.Bounds().Min, draw.Src)
304 for _, overlay := range overlays {
305 if len(overlay.Panes) != 0 || len(overlay.Overlays) != 0 || overlay.Width > frame.Width || overlay.Height > frame.Height || overlay.X < -frame.Width || overlay.Y < -frame.Height || overlay.X > frame.Width || overlay.Y > frame.Height {
306 return nil, errors.New("应用覆盖位置无效")
307 }
308 overlay.Target = frame.Target
309 img, err := nativeFrameImage(overlay.windowsWindowFrame)
310 if err != nil {
311 return nil, err
312 }
313 area := image.Rect(overlay.X, overlay.Y, overlay.X+overlay.Width, overlay.Y+overlay.Height)
314 draw.Draw(canvas, area, img, img.Bounds().Min, draw.Over)
315 }
316 return canvas, nil
317 }
318 if len(frame.Panes) > 0 {
319 if len(frame.Panes) != 2 || frame.PNG != "" || frame.JPEG != "" {
320 return nil, errors.New("分屏画面无效")
321 }
322 img := image.NewRGBA(image.Rect(0, 0, frame.Width, frame.Height))
323 draw.Draw(img, img.Bounds(), image.NewUniform(color.White), image.Point{}, draw.Src)
324 var previous image.Rectangle
325 for index, pane := range frame.Panes {
326 bounds := image.Rect(pane.X, pane.Y, pane.X+pane.Width, pane.Y+pane.Height)
327 if pane.X < 0 || pane.Y < 0 || len(pane.Panes) != 0 || !bounds.In(img.Bounds()) || index > 0 && !previous.Intersect(bounds).Empty() {
328 return nil, errors.New("分屏画面位置无效")
329 }
330 pane.Target = frame.Target
331 part, err := nativeFrameImage(pane.windowsWindowFrame)
332 if err != nil {
333 return nil, err
334 }
335 draw.Draw(img, bounds, part, part.Bounds().Min, draw.Src)
336 previous = bounds
337 }
338 return img, nil
339 }
340 encoded := frame.PNG
341 if encoded == "" {
342 encoded = frame.JPEG
343 }
344 if len(encoded) > (20<<20)*4/3+4 {
345 return nil, errors.New("应用画面无效")
346 }
347 data, err := base64.StdEncoding.DecodeString(encoded)
348 if err != nil {
349 return nil, err
350 }
351 config, _, err := image.DecodeConfig(bytes.NewReader(data))
352 if err != nil || config.Width != frame.Width || config.Height != frame.Height {
353 return nil, errors.New("应用画面尺寸无效")
354 }
355 decoded, _, err := image.Decode(bytes.NewReader(data))
356 if err != nil {
357 return nil, err
358 }
359 return decoded, nil
360}
361
362func nativeFramePixels(frame windowsWindowFrame) ([]byte, error) {
363 decoded, err := nativeFrameImage(frame)
364 if err != nil {
365 return nil, err
366 }
367 rgba, ok := decoded.(*image.RGBA)
368 if !ok {
369 rgba = image.NewRGBA(image.Rect(0, 0, frame.Width, frame.Height))
370 draw.Draw(rgba, rgba.Bounds(), decoded, decoded.Bounds().Min, draw.Src)
371 }
372 pixels := make([]byte, frame.Width*frame.Height*4)
373 for y := 0; y < frame.Height; y++ {
374 row := rgba.Pix[y*rgba.Stride : y*rgba.Stride+frame.Width*4]
375 for x := 0; x < frame.Width; x++ {
376 i := (y*frame.Width + x) * 4
377 pixels[i] = row[x*4+2]
378 pixels[i+1] = row[x*4+1]
379 pixels[i+2] = row[x*4]
380 }
381 }
382 return pixels, nil
383}
384
385func serveWindowsWindowRFB(stream io.ReadWriter, initial windowsWindowFrame, request func(map[string]any, any) error) error {
386 if _, err := nativeFrameImage(initial); err != nil {
387 return err
388 }
389 write := func(data []byte) error { _, err := stream.Write(data); return err }
390 read := func(n int) ([]byte, error) {
391 data := make([]byte, n)
392 _, err := io.ReadFull(stream, data)
393 return data, err
394 }
395 if err := write([]byte("RFB 003.008\n")); err != nil {
396 return err
397 }
398 version, err := read(12)
399 if err != nil || string(version) != "RFB 003.008\n" {
400 return errors.New("画面协议版本无效")
401 }
402 // HTTP/WS origin, account and controller authentication precede this stream.
403 if err = write([]byte{1, 1}); err != nil {
404 return err
405 }
406 security, err := read(1)
407 if err != nil || security[0] != 1 {
408 return errors.New("画面认证协议无效")
409 }
410 if err = write([]byte{0, 0, 0, 0}); err != nil {
411 return err
412 }
413 if _, err = read(1); err != nil {
414 return err
415 }
416 init := make([]byte, 24)
417 binary.BigEndian.PutUint16(init, uint16(initial.Width))
418 binary.BigEndian.PutUint16(init[2:], uint16(initial.Height))
419 copy(init[4:], []byte{32, 24, 0, 1, 0, 255, 0, 255, 0, 255, 16, 8, 0, 0, 0, 0})
420 name := []byte("Cage application")
421 binary.BigEndian.PutUint32(init[20:], uint32(len(name)))
422 init = append(init, name...)
423 if err = write(init); err != nil {
424 return err
425 }
426 frame := initial
427 sized := false
428 supportsResize := false
429 supportsFence := false
430 pixelWheel := false
431 rgbOrder := false
432 useZlib := false
433 useTight := false
434 useTightPNG := false
435 var compressed bytes.Buffer
436 var compressor *zlib.Writer
437 defer func() {
438 if compressor != nil {
439 _ = compressor.Close()
440 }
441 }()
442 // Reading ahead of the guest keeps input moving while a frame request
443 // waits for its turn. Messages are still handled one at a time, in order.
444 messages := make(chan []byte)
445 stopped := make(chan struct{})
446 defer close(stopped)
447 var readErr error
448 go func() {
449 defer close(messages)
450 for {
451 message, err := readRFBClientMessage(stream)
452 if err != nil {
453 readErr = err
454 return
455 }
456 select {
457 case messages <- message:
458 case <-stopped:
459 return
460 }
461 }
462 }()
463 var pace nativeFramePace
464 // The pending update request, and whether it accepts an unchanged frame.
465 pending, incremental := false, true
466 timer := time.NewTimer(time.Hour)
467 defer timer.Stop()
468 schedule := func() {
469 timer.Stop()
470 select {
471 case <-timer.C:
472 default:
473 }
474 timer.Reset(time.Until(pace.next()))
475 }
476 sendFrame := func() error {
477 pending = false
478 pace.requested(time.Now())
479 input := map[string]any{"action": "frame"}
480 if incremental {
481 input["after"] = frame.Sequence
482 }
483 wasIncremental := incremental
484 incremental = true
485 var next windowsWindowFrame
486 if err := request(input, &next); err != nil {
487 return err
488 }
489 pace.answered(!next.Unchanged)
490 if next.Unchanged {
491 if !wasIncremental || frame.Sequence == "" || next.Sequence != frame.Sequence {
492 return errors.New("应用画面更新标识无效")
493 }
494 return write([]byte{0, 0, 0, 0})
495 }
496 if useTight || useTightPNG {
497 encoding := int32(7)
498 if useTightPNG {
499 encoding = -260
500 }
501 rectangles, count, supported, err := nativeTightRectangles(next, encoding)
502 if err != nil {
503 return err
504 }
505 if supported {
506 changed := next.Width != frame.Width || next.Height != frame.Height
507 if changed && !supportsResize {
508 return errors.New("画面尺寸已变化,请重新连接")
509 }
510 if changed {
511 count++
512 }
513 header := []byte{0, 0, byte(count >> 8), byte(count)}
514 if changed {
515 header = append(header, windowRFBRect(next.Width, next.Height, -223)...)
516 }
517 if err = write(append(header, rectangles...)); err != nil {
518 return err
519 }
520 frame = next
521 sized = true
522 return nil
523 }
524 }
525 pixels, err := nativeFramePixels(next)
526 if err != nil {
527 return err
528 }
529 if rgbOrder {
530 for i := 0; i < len(pixels); i += 4 {
531 pixels[i], pixels[i+2] = pixels[i+2], pixels[i]
532 }
533 }
534 encoding := int32(0)
535 payload := pixels
536 if useZlib {
537 if compressor == nil {
538 compressor, err = zlib.NewWriterLevel(&compressed, zlib.BestSpeed)
539 if err != nil {
540 return err
541 }
542 }
543 compressed.Reset()
544 if _, err = compressor.Write(pixels); err != nil {
545 return err
546 }
547 if err = compressor.Flush(); err != nil {
548 return err
549 }
550 payload = make([]byte, 4+compressed.Len())
551 binary.BigEndian.PutUint32(payload, uint32(compressed.Len()))
552 copy(payload[4:], compressed.Bytes())
553 encoding = 6
554 }
555 changed := next.Width != frame.Width || next.Height != frame.Height
556 if changed && !supportsResize {
557 return errors.New("画面尺寸已变化,请重新连接")
558 }
559 count := uint16(1)
560 if changed {
561 count++
562 }
563 header := make([]byte, 4)
564 binary.BigEndian.PutUint16(header[2:], count)
565 if changed {
566 header = append(header, windowRFBRect(next.Width, next.Height, -223)...)
567 }
568 header = append(header, windowRFBRect(next.Width, next.Height, encoding)...)
569 if err = write(header); err != nil {
570 return err
571 }
572 if err = write(payload); err != nil {
573 return err
574 }
575 frame = next
576 sized = true
577 return nil
578 }
579 for {
580 var due <-chan time.Time
581 if pending {
582 due = timer.C
583 }
584 var message []byte
585 select {
586 case <-due:
587 if err := sendFrame(); err != nil {
588 return err
589 }
590 continue
591 case received, open := <-messages:
592 if !open {
593 return readErr
594 }
595 message = received
596 }
597 body := message[1:]
598 switch message[0] {
599 case 0:
600 base := []byte{32, 24, 0, 1, 0, 255, 0, 255, 0, 255}
601 if !bytes.Equal(body[3:13], base) || (!bytes.Equal(body[13:16], []byte{16, 8, 0}) && !bytes.Equal(body[13:16], []byte{0, 8, 16})) {
602 return errors.New("画面像素格式无效")
603 }
604 rgbOrder = body[13] == 0
605 case 2:
606 encodings := body[3:]
607 useZlib = false
608 useTight = false
609 useTightPNG = false
610 fenceRequested, wheelRequested := false, false
611 for i := 0; i < len(encodings); i += 4 {
612 switch int32(binary.BigEndian.Uint32(encodings[i:])) {
613 case cageWheelEncoding:
614 wheelRequested = true
615 case -312:
616 fenceRequested = true
617 case -223:
618 supportsResize = true
619 case 6:
620 useZlib = true
621 case 7:
622 useTight = true
623 case -260:
624 useTightPNG = true
625 }
626 }
627 if fenceRequested && !supportsFence {
628 // noVNC enables ordered input after the server's first Fence request.
629 if err := write([]byte{248, 0, 0, 0, 0x80, 0, 0, 0, 0}); err != nil {
630 return err
631 }
632 }
633 supportsFence = fenceRequested
634 // An older guest would scroll one fixed step for every distance.
635 wheelRequested = wheelRequested && initial.Wheel
636 if fenceRequested && wheelRequested && !pixelWheel {
637 // The viewer sends distances only after this confirmation.
638 confirmation := append([]byte{248, 0, 0, 0, 0x80, 0, 0, 0, byte(len(cageWheelCapability))}, cageWheelCapability...)
639 if err := write(confirmation); err != nil {
640 return err
641 }
642 }
643 pixelWheel = fenceRequested && wheelRequested
644 // Only the browser display offers the wheel. Its guest streams
645 // frames as it composes them, so scrolling can be shown at 60 Hz.
646 pace.smooth = pixelWheel
647 case 3:
648 if body[0] == 0 {
649 incremental = false
650 }
651 if !pending {
652 pending = true
653 schedule()
654 }
655 case 4:
656 if !sized {
657 continue
658 }
659 if err := request(map[string]any{"action": "key", "target": frame.Target, "keysym": binary.BigEndian.Uint32(body[3:]), "down": body[0] != 0}, nil); err != nil {
660 return err
661 }
662 case 5:
663 if !sized {
664 continue
665 }
666 if err := request(map[string]any{"action": "pointer", "target": frame.Target, "mask": body[0], "x": binary.BigEndian.Uint16(body[1:]), "y": binary.BigEndian.Uint16(body[3:])}, nil); err != nil {
667 return err
668 }
669 case cageWheelMessage:
670 dx, dy := int32(binary.BigEndian.Uint32(body[5:])), int32(binary.BigEndian.Uint32(body[9:]))
671 if !pixelWheel || body[0] != 0 || dx < -cageWheelLimit || dx > cageWheelLimit || dy < -cageWheelLimit || dy > cageWheelLimit {
672 return errors.New("画面滚动消息无效")
673 }
674 if !sized || dx == 0 && dy == 0 {
675 continue
676 }
677 // The direction bits let a guest without distances scroll one step.
678 mask := 0
679 if dx < 0 {
680 mask |= 32
681 } else if dx > 0 {
682 mask |= 64
683 }
684 if dy < 0 {
685 mask |= 8
686 } else if dy > 0 {
687 mask |= 16
688 }
689 if err := request(map[string]any{"action": "pointer", "target": frame.Target, "mask": mask,
690 "x": binary.BigEndian.Uint16(body[1:]), "y": binary.BigEndian.Uint16(body[3:]), "deltaX": dx, "deltaY": dy}, nil); err != nil {
691 return err
692 }
693 case 6:
694 // Native shared clipboard owns clipboard data; committed text takes the
695 // fixed Unicode input path without changing the OS clipboard.
696 if err := request(map[string]any{"action": "text", "target": frame.Target, "text": string(body[7:])}, nil); err != nil {
697 return err
698 }
699 case 248:
700 if !supportsFence {
701 return errors.New("画面输入同步消息无效")
702 }
703 flags := binary.BigEndian.Uint32(body[3:7])
704 if flags&(1<<31) != 0 {
705 // Guest input and stream writes finish in order on this goroutine,
706 // satisfying BlockBefore and BlockAfter. SyncNext is unsupported.
707 reply := append([]byte{248}, body...)
708 binary.BigEndian.PutUint32(reply[4:8], flags&3)
709 if err := write(reply); err != nil {
710 return err
711 }
712 }
713 }
714 if message[0] == 4 || message[0] == 5 || message[0] == 6 || message[0] == cageWheelMessage {
715 // The window answers input at once: the next frame is not delayed
716 // by the pauses of an unchanged screen.
717 pace.input(time.Now())
718 if pending {
719 schedule()
720 }
721 }
722 }
723}
724
725// nativeFrameInterval is the shortest time between two frame requests, and
726// nativeOperatingInterval the one a browser display has while it is operated.
727const (
728 nativeFrameInterval = time.Second / 30
729 nativeOperatingInterval = time.Second / 60
730 nativeOperatingHold = time.Second
731)
732
733// The Cage browser display sends the scrolled distance in one message. It
734// offers the encoding, and uses the message once a fence names the capability.
735const (
736 cageWheelEncoding = -57345
737 cageWheelMessage = 180
738 cageWheelCapability = "cage-wheel-v1"
739 cageWheelLimit = 2048
740)
741
742// nativeFramePace spaces frame requests to a native guest. Each one is a
743// round trip into the guest, also when its window has not changed, so the
744// pause doubles with every unchanged answer, up to about a quarter second.
745// A changed frame or the viewer's input restores the shortest pause. Every
746// frame is a complete image: a smooth display has the shorter pause only for
747// a moment after input, and plays unattended animation at the usual one.
748type nativeFramePace struct {
749 last, acted time.Time
750 unchanged int
751 smooth bool
752}
753
754func (p *nativeFramePace) next() time.Time {
755 interval := nativeFrameInterval
756 if p.smooth && !p.acted.IsZero() && p.last.Sub(p.acted) < nativeOperatingHold {
757 interval = nativeOperatingInterval
758 }
759 return p.last.Add(interval << min(p.unchanged, 3))
760}
761
762func (p *nativeFramePace) requested(now time.Time) { p.last = now }
763
764func (p *nativeFramePace) answered(changed bool) {
765 if changed {
766 p.unchanged = 0
767 } else {
768 p.unchanged++
769 }
770}
771
772func (p *nativeFramePace) input(now time.Time) { p.unchanged, p.acted = 0, now }
773
774// readRFBClientMessage reads one complete client message, type byte first.
775func readRFBClientMessage(stream io.Reader) ([]byte, error) {
776 message := make([]byte, 1, 32)
777 if _, err := io.ReadFull(stream, message); err != nil {
778 return nil, err
779 }
780 extend := func(n int) error {
781 size := len(message)
782 message = append(message, make([]byte, n)...)
783 _, err := io.ReadFull(stream, message[size:])
784 return err
785 }
786 var err error
787 switch message[0] {
788 case 0:
789 err = extend(19)
790 case 2:
791 if err = extend(3); err == nil {
792 count := int(binary.BigEndian.Uint16(message[2:]))
793 if count > 256 {
794 return nil, errors.New("画面编码列表无效")
795 }
796 err = extend(count * 4)
797 }
798 case 3:
799 err = extend(9)
800 case 4:
801 err = extend(7)
802 case 5:
803 err = extend(5)
804 case 6:
805 if err = extend(7); err == nil {
806 size := binary.BigEndian.Uint32(message[4:])
807 if size > 2<<20 {
808 return nil, errors.New("粘贴文字超过限制")
809 }
810 err = extend(int(size))
811 }
812 case cageWheelMessage:
813 err = extend(13)
814 case 248:
815 if err = extend(8); err == nil {
816 if message[8] > 64 {
817 return nil, errors.New("画面输入同步消息无效")
818 }
819 err = extend(int(message[8]))
820 }
821 default:
822 return nil, errors.New("画面输入协议无效")
823 }
824 return message, err
825}
826
827func windowRFBRect(width, height int, encoding int32) []byte {
828 header := make([]byte, 12)
829 binary.BigEndian.PutUint16(header[4:], uint16(width))
830 binary.BigEndian.PutUint16(header[6:], uint16(height))
831 binary.BigEndian.PutUint32(header[8:], uint32(encoding))
832 return header
833}
834
835func (s *Server) windowsDesktopCredentials(w http.ResponseWriter, r *http.Request) {
836 ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
837 defer cancel()
838 var state claudeDesktopState
839 if err := s.windowsDesktopRequest(ctx, "status", nil, &state); err != nil || !state.Running {
840 http.Error(w, "Claude Desktop 尚未启动", 409)
841 return
842 }
843 density := state.DisplayScale
844 if density < 1 || density > 8 {
845 http.Error(w, "Claude Desktop 返回了无效的显示比例", 502)
846 return
847 }
848 jsonReply(w, map[string]any{"password": "", "display_scale": density})
849}