| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | _ "embed" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "os/exec" |
| 11 | "path/filepath" |
| 12 | "strings" |
| 13 | "time" |
| 14 | |
| 15 | "al.essio.dev/pkg/shellescape" |
| 16 | |
| 17 | "github.com/sylvinus/agent-vm/internal/cage" |
| 18 | "github.com/sylvinus/agent-vm/internal/guestos" |
| 19 | "github.com/sylvinus/agent-vm/internal/host" |
| 20 | ) |
| 21 | |
| 22 | |
| 23 | |
| 24 | func macOSWorkbenchRoute(path string) bool { |
| 25 | if nativeWorkbenchRoute(path) { |
| 26 | return true |
| 27 | } |
| 28 | if id, ok := strings.CutPrefix(path, "/api/input/files/desktop/"); ok { |
| 29 | return id == "requests" || id == "open" || browserFileID.MatchString(id) |
| 30 | } |
| 31 | switch path { |
| 32 | case "/api/macos/first-setup", "/api/appearance/codex", "/api/macos/project-approval", "/api/macos/exit-policy", "/api/macos/login", "/api/macos/maintenance": |
| 33 | return true |
| 34 | } |
| 35 | return strings.HasPrefix(path, "/api/macos/claude/") || strings.HasPrefix(path, "/api/macos-browser/") |
| 36 | } |
| 37 | |
| 38 | func macOSInstanceRunning(instanceDir string) bool { |
| 39 | data, err := os.ReadFile(filepath.Join(instanceDir, "cage-running.json")) |
| 40 | var record struct { |
| 41 | PID int `json:"pid"` |
| 42 | Started string `json:"started"` |
| 43 | } |
| 44 | if err != nil || json.Unmarshal(data, &record) != nil || record.PID < 1 { |
| 45 | return false |
| 46 | } |
| 47 | return processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started) |
| 48 | } |
| 49 | |
| 50 | func (s *Server) macOSSSHCommand(ctx context.Context, args ...string) *exec.Cmd { |
| 51 | base, err := guestos.MacOSSSHArgs(s.profile, s.macosGuest.User) |
| 52 | if err != nil { |
| 53 | return &exec.Cmd{Err: err} |
| 54 | } |
| 55 | cmd := exec.CommandContext(ctx, sshExecutable(), append(base, args...)...) |
| 56 | cmd.Env = sshEnvironment() |
| 57 | host.HideCommandWindow(cmd) |
| 58 | return cmd |
| 59 | } |
| 60 | |
| 61 | func (s *Server) checkMacOSGuest(ctx context.Context) error { |
| 62 | if !s.vmRunning() { |
| 63 | return errors.New("macOS 客机尚未启动") |
| 64 | } |
| 65 | client, err := s.gateClient() |
| 66 | if err != nil { |
| 67 | return errors.New("无法验证 macOS 客机的网络隔离状态") |
| 68 | } |
| 69 | state, err := client.Status(ctx) |
| 70 | if err != nil { |
| 71 | return errors.New("无法验证 macOS 客机的网络门槛") |
| 72 | } |
| 73 | if state.Mode != cage.GateClosed { |
| 74 | s.mu.Lock() |
| 75 | ready, paused := s.ready, s.networkPaused |
| 76 | s.mu.Unlock() |
| 77 | reason := "" |
| 78 | switch { |
| 79 | case s.macSetupPending(): |
| 80 | reason = "首次系统设置期间外网关闭" |
| 81 | case paused: |
| 82 | reason = "网络保持暂停,请手动恢复后再联网" |
| 83 | case !ready: |
| 84 | reason = "客机重新连接,外网等待重新检查" |
| 85 | default: |
| 86 | cfg, cfgErr := loadConfig(s.configPath) |
| 87 | if state.Mode != cage.GateOpen || cfgErr != nil || state.Report == nil || !time.Now().Before(state.Until) || state.Report.Authorizes(state.RunID, cfg.Fingerprint(), time.Now()) != nil { |
| 88 | reason = "网络授权未通过当前配置的完整检查" |
| 89 | } |
| 90 | } |
| 91 | if reason != "" { |
| 92 | state, err = client.Close(ctx, reason) |
| 93 | if err != nil || state.Mode != cage.GateClosed { |
| 94 | return errors.New("macOS 客机网络状态不能确认") |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | s.publishGate(state) |
| 99 | probe := `test "$(uname -s)" = Darwin && [[ $(sysctl -n hw.model) == VirtualMac* ]] && test "$(id -un)" = ` + |
| 100 | shellescape.Quote(s.macosGuest.User) + ` && [[ " $(id -Gn) " != *" admin "* ]]` |
| 101 | if _, err := s.guest(ctx, probe); err != nil { |
| 102 | return errors.New("无法以已绑定的普通用户连接到这台虚拟 Mac,请检查客机身份和 SSH 登录") |
| 103 | } |
| 104 | return nil |
| 105 | } |
| 106 | |
| 107 | func (s *Server) attachMacOSGuest() error { |
| 108 | ctx, cancel := s.controlContext() |
| 109 | defer cancel() |
| 110 | err := s.checkMacOSGuest(ctx) |
| 111 | s.mu.Lock() |
| 112 | newlyReady := !s.ready && err == nil |
| 113 | checkAfterReconnect := newlyReady && !s.closing && !s.networkPaused && !s.jobs.snapshot().Running |
| 114 | s.ready = err == nil |
| 115 | s.guestUpdateError = "" |
| 116 | if err != nil { |
| 117 | s.guestUpdateError = err.Error() |
| 118 | } |
| 119 | s.mu.Unlock() |
| 120 | if newlyReady && !s.macSetupPending() { |
| 121 | s.restoreProjectShares() |
| 122 | if checkAfterReconnect { |
| 123 | _, _ = s.submitJob("network-recovery", s.checkNetworkIfWanted) |
| 124 | } |
| 125 | } else if err == nil && !s.macSetupPending() { |
| 126 | s.retryMacOSProjectShares(ctx) |
| 127 | } |
| 128 | return err |
| 129 | } |
| 130 | |
| 131 | func (s *Server) macOSLifecycleCommand(action string) error { |
| 132 | ctx, cancel := context.WithTimeout(s.operationContext(), 5*time.Minute) |
| 133 | defer cancel() |
| 134 | cmd := exec.CommandContext(ctx, s.exe, "guest-os", "macos", action) |
| 135 | cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath) |
| 136 | job := s.jobs.execution() |
| 137 | cmd.Stdout, cmd.Stderr = job, job |
| 138 | if err := cmd.Run(); err != nil { |
| 139 | return fmt.Errorf("macOS 客机操作失败(%s):%w", action, err) |
| 140 | } |
| 141 | return nil |
| 142 | } |
| 143 | |
| 144 | func (s *Server) startMacOSGuest() error { |
| 145 | if !s.vmRunning() { |
| 146 | if err := s.macOSLifecycleCommand("start"); err != nil { |
| 147 | return err |
| 148 | } |
| 149 | } |
| 150 | if err := s.syncMacGuestPassword(s.operationContext()); err != nil { |
| 151 | return err |
| 152 | } |
| 153 | if err := s.attachMacOSGuest(); err != nil { |
| 154 | return err |
| 155 | } |
| 156 | return s.checkNetworkIfWanted() |
| 157 | } |
| 158 | |
| 159 | |
| 160 | var macOSLocaleScript string |
| 161 | |
| 162 | func (s *Server) syncMacOSRegion(ctx context.Context, cfg cage.Config) error { |
| 163 | ctx, cancel := context.WithTimeout(ctx, 30*time.Second) |
| 164 | defer cancel() |
| 165 | s.setMessage("正在应用 macOS 客机账户的地区与语言…") |
| 166 | locale := strings.TrimSuffix(cfg.Locale, ".UTF-8") |
| 167 | cmd := shellescape.QuoteCommand([]string{"/bin/bash", "-c", macOSLocaleScript, "cage-locale", "NSGlobalDomain", locale}) |
| 168 | if _, err := s.guest(ctx, "exec "+cmd); err != nil { |
| 169 | return fmt.Errorf("macOS 客机已启动,未能写入客机账户的地区与语言:%w", err) |
| 170 | } |
| 171 | s.setMessage("正在等候 macOS 客机读回已保存的时区与语言…") |
| 172 | var last guestObservation |
| 173 | for { |
| 174 | got, err := s.macOSGuestObservation(ctx, map[string]any{"stage": "environment"}) |
| 175 | if err == nil { |
| 176 | last = got |
| 177 | if s.guestSettingsOK(got, cfg) { |
| 178 | return nil |
| 179 | } |
| 180 | } |
| 181 | select { |
| 182 | case <-ctx.Done(): |
| 183 | if errors.Is(ctx.Err(), context.Canceled) { |
| 184 | return ctx.Err() |
| 185 | } |
| 186 | return fmt.Errorf("macOS 客机的时区和语言尚未全部生效。期望 %s、%s,系统读回时区 %q、地区 %q、首选语言 %q,进程读回 %q、%q。外网保持关闭。可稍后重检,时区持续不符时请停止并重新启动客机。", cfg.Timezone, cfg.Locale, last.SystemTimezone, last.SystemLocale, last.SystemLanguage, last.TZ, last.ProcessLocale) |
| 187 | case <-time.After(time.Second): |
| 188 | } |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | func (s *Server) stopMacOSGuest() error { |
| 193 | s.mu.Lock() |
| 194 | s.macSetupProjectsChecked = time.Time{} |
| 195 | s.mu.Unlock() |
| 196 | s.closeWindowsBrowser() |
| 197 | s.mu.Lock() |
| 198 | s.ready = false |
| 199 | s.mu.Unlock() |
| 200 | s.terminals.closeAll() |
| 201 | s.closeProjectShares() |
| 202 | return s.macOSLifecycleCommand("stop") |
| 203 | } |