跳到主要内容

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

浏览文件

runtime.go

729 行 · 22.9 KB历史下载
1package workbench
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "io"
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/containerenv"
19 "github.com/sylvinus/agent-vm/internal/diagnostics"
20 "github.com/sylvinus/agent-vm/internal/guestos"
21 "github.com/sylvinus/agent-vm/internal/host"
22 "github.com/sylvinus/agent-vm/internal/hostimage"
23 "github.com/sylvinus/agent-vm/internal/managedproxy"
24)
25
26var loadConfig = cage.Load
27var defaultConfig = cage.DefaultConfig
28
29type guestCredentials struct {
30 Token string `json:"token"`
31 VNCPassword string `json:"-"`
32 DisplayScale float64 `json:"display_scale"`
33 DynamicScale bool `json:"dynamic_scale"`
34}
35
36func (s *Server) workspaceLocked() string {
37 if s.clientWorkspace != "" {
38 return s.clientWorkspace
39 }
40 return s.preferences.Workspace
41}
42func (s *Server) workspace() string { s.mu.Lock(); defer s.mu.Unlock(); return s.workspaceLocked() }
43func (s *Server) environmentDir() string { return environmentWorkspace(s.profile) }
44func (s *Server) sshTarget() string {
45 if s.macosGuest != nil {
46 return "cage-macos"
47 }
48 if containerenv.Configured(s.profile) {
49 return "cage-container"
50 }
51 return "lima-" + cage.InstanceName(s.profile, s.environmentDir())
52}
53
54func (s *Server) environmentPrepared() bool {
55 if s.windowsGuest != nil {
56 return true
57 }
58 if containerenv.Configured(s.profile) {
59 environment, err := containerenv.Load(s.profile)
60 if err != nil {
61 return false
62 }
63 ctx, cancel := context.WithTimeout(s.lifetimeContext(), 3*time.Second)
64 defer cancel()
65 state, err := environment.State(ctx)
66 return err == nil && state.Exists
67 }
68 _, err := os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version"))
69 return err == nil
70}
71func (s *Server) sshCommand(ctx context.Context, args ...string) *exec.Cmd {
72 return s.sshCommandOptions(ctx, false, args...)
73}
74func (s *Server) sshCommandWithForwarding(ctx context.Context, args ...string) *exec.Cmd {
75 return s.sshCommandOptions(ctx, true, args...)
76}
77func (s *Server) sshCommandOptions(ctx context.Context, maintenance bool, args ...string) *exec.Cmd {
78 if s.windowsGuest != nil {
79 return &exec.Cmd{Err: errors.New("Windows 客机不支持 Linux SSH 控制脚本")}
80 }
81 if s.macosGuest != nil {
82 return s.macOSSSHCommand(ctx, args...)
83 }
84 cfg := filepath.Join(s.instanceDir(), "ssh.config")
85 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"}
86 if maintenance {
87 for index, value := range base {
88 if value == "ClearAllForwardings=yes" {
89 base[index] = "ClearAllForwardings=no"
90 }
91 }
92 }
93 base = append(base, args...)
94 cmd := exec.CommandContext(ctx, sshExecutable(), base...)
95 cmd.Env = sshEnvironment()
96 host.HideCommandWindow(cmd)
97 return cmd
98}
99func (s *Server) guest(ctx context.Context, script string) ([]byte, error) {
100 return s.guestControl(ctx, script, "")
101}
102
103func (s *Server) guestControl(ctx context.Context, script, diagnosticSource string) ([]byte, error) {
104 if s.windowsGuest != nil {
105 return nil, errors.New("Windows 客机不支持 Linux 控制脚本")
106 }
107 // SSH enters the user's default shell. Run control scripts in Bash so
108 // zsh initialization cannot change their redirection or error behavior.
109 command := "exec /bin/bash --noprofile --norc -c " + shellescape.Quote(script)
110 cmd := s.sshCommand(ctx, "-T", s.sshTarget(), "--", command)
111 var stderr fileControlStderr
112 if diagnosticSource != "" {
113 cmd.Stderr = &stderr
114 defer func() {
115 if len(stderr.data) > 0 {
116 _ = diagnostics.New(s.profile).Record("warn", diagnosticSource, "guest control stderr: "+string(stderr.data))
117 }
118 }()
119 }
120 pipe, err := cmd.StdoutPipe()
121 if err != nil {
122 return nil, err
123 }
124 if err = cmd.Start(); err != nil {
125 return nil, err
126 }
127 data, readErr := io.ReadAll(io.LimitReader(pipe, (64<<10)+1))
128 if readErr != nil || len(data) > 64<<10 {
129 _ = cmd.Process.Kill()
130 _ = cmd.Wait()
131 return nil, errors.New("guest control response exceeded its limit")
132 }
133 if err = cmd.Wait(); err != nil {
134 return nil, err
135 }
136 return data, nil
137}
138func (s *Server) attach() error {
139 if err := s.requireStorageReady(); err != nil {
140 return err
141 }
142 if s.windowsGuest != nil {
143 return s.attachWindowsGuest()
144 }
145 if s.macosGuest != nil {
146 return s.attachMacOSGuest()
147 }
148 ctx, cancel := s.controlContext()
149 defer cancel()
150 if containerenv.Configured(s.profile) {
151 environment, err := containerenv.Load(s.profile)
152 if err != nil {
153 return err
154 }
155 state, err := environment.State(ctx)
156 if err != nil {
157 return err
158 }
159 if !state.Running {
160 return errors.New("环境尚未启动")
161 }
162 if !state.Ready {
163 s.mu.Lock()
164 s.ready = false
165 s.mu.Unlock()
166 if !state.MountsReady {
167 return errors.New("容器项目共享需要初始化,请保存工作后完整停止并重新启动环境")
168 }
169 if !state.ResourcesVerified {
170 return errors.New("容器资源限制尚未通过核验,请检查服务器资源配置")
171 }
172 return errors.New("容器网络与文件连接尚未就绪,请重试启动")
173 }
174 } else if !s.vmRunning() {
175 return errors.New("环境尚未启动")
176 }
177 b, err := s.guest(ctx, guestConnectionSnapshot)
178 if err != nil {
179 return errors.New("环境尚未准备好")
180 }
181 credentials, manifest, err := parseGuestConnection(b)
182 s.mu.Lock()
183 s.guestManifest = manifest
184 s.guestUpdateRequired = errors.Is(err, errGuestUpdateRequired)
185 s.guestUpdateError = ""
186 if err != nil {
187 s.ready = false
188 s.guestUpdateError = err.Error()
189 }
190 s.mu.Unlock()
191 if err != nil {
192 if errors.Is(err, errGuestUpdateRequired) {
193 _ = s.closeProxyGate("环境组件需要更新,外网保持关闭")
194 }
195 return err
196 }
197 if _, err = s.guestAPI(ctx, credentials.Token, "GET", "/health", nil); err != nil {
198 return err
199 }
200 s.mu.Lock()
201 home := browserHomeURL(s.preferences)
202 s.mu.Unlock()
203 if err = s.setBrowserHome(ctx, credentials.Token, home); err != nil {
204 return err
205 }
206 if containerenv.Configured(s.profile) {
207 if err := s.recoverClientMounts(ctx); err != nil {
208 return err
209 }
210 }
211 s.mu.Lock()
212 s.credentials = credentials
213 s.ready = true
214 s.mu.Unlock()
215 s.restoreProjectShares()
216 s.desktopViews.background(s.changeDesktopVisibility)
217 s.browserViews.background(s.changeBrowserVisibility)
218 return nil
219}
220func (s *Server) monitor(ctx context.Context) {
221 ticker := time.NewTicker(5 * time.Second)
222 defer ticker.Stop()
223 skipped := 0
224 for ctx.Err() == nil {
225 timing := s.startMonitorTiming()
226 if s.op.TryLock() {
227 skipped = 0
228 if !s.busy() {
229 s.mu.Lock()
230 ready := s.ready
231 token := s.credentials.Token
232 s.mu.Unlock()
233 if !ready || s.macosGuest != nil || s.windowsGuest != nil {
234 _ = s.attach()
235 } else {
236 ctx, cancel := s.controlContext()
237 _, err := s.guestAPI(ctx, token, "GET", "/health", nil)
238 cancel()
239 if err != nil {
240 s.mu.Lock()
241 s.ready = false
242 s.mu.Unlock()
243 }
244 }
245 timing.stage("environment_health")
246 if s.macosGuest != nil {
247 s.monitorNetworkTick()
248 timing.stage("network_tick")
249 }
250 } else {
251 timing.result = "job_running"
252 }
253 s.op.Unlock()
254 } else {
255 skipped++
256 timing.result = "operation_lock_busy"
257 }
258 timing.stages = append(timing.stages, fmt.Sprintf("consecutive_lock_skips=%d", skipped))
259 s.recordMonitorTiming("environment", timing)
260 select {
261 case <-ctx.Done():
262 return
263 case <-ticker.C:
264 }
265 }
266}
267
268func (s *Server) runCage(args ...string) error {
269 ctx := s.operationContext()
270 // Setup and startup can both install dependencies. Downloads own their
271 // inactivity timeouts; the operation context still permits an explicit stop.
272 if len(args) != 1 || (args[0] != "setup" && args[0] != "up") {
273 var cancel context.CancelFunc
274 ctx, cancel = context.WithTimeout(ctx, 30*time.Minute)
275 defer cancel()
276 }
277 cmd := exec.CommandContext(ctx, s.exe, args...)
278 host.HideCommandWindow(cmd)
279 cmd.Dir = s.environmentDir()
280 if cmd.Dir == "" {
281 cmd.Dir = s.profile
282 }
283 cmd.Env = append(os.Environ(), cage.ConfigEnv+"="+s.configPath)
284 execution := s.jobs.execution()
285 if len(args) == 1 && args[0] == "setup" {
286 cmd.Env = append(cmd.Env, "CAGE_SETUP_PROGRESS=1")
287 }
288 cmd.Env = append(cmd.Env, cage.JobEnv+"="+execution.id)
289 cmd.Stdout, cmd.Stderr = execution, execution
290 if err := cmd.Run(); err != nil {
291 if errors.Is(ctx.Err(), context.Canceled) {
292 return context.Canceled
293 }
294 action := map[string]string{"setup": "准备 Linux 环境", "up": "启动环境", "down": "停止环境", "stop": "停止环境"}[args[0]]
295 if action == "" {
296 action = "执行环境操作"
297 }
298 if p := s.jobs.snapshot().SetupProgress; p != nil && p.Label != "" {
299 action = strings.TrimPrefix(p.Label, "正在")
300 }
301 // CLI failures can include the original QEMU stderr before a generic
302 // "Failed to start base VM" footer. Surface that reason in job.error.
303 for _, line := range strings.Split(s.jobs.snapshot().Log, "\n") {
304 if _, reason, ok := strings.Cut(line, "Error: QEMU 启动失败:"); ok {
305 return fmt.Errorf("%s失败:虚拟机未能启动。QEMU 启动失败:%s。请查看操作详情;仍无法启动时,在设置中导出诊断包。", action, reason)
306 }
307 }
308 diagnostics.Log("error", "environment-operation", fmt.Sprintf("operation=%s error=%v context=%v", args[0], err, ctx.Err()))
309 return executionFailure(action, errors.Join(ctx.Err(), err), s.jobs.snapshot().Log)
310 }
311 return nil
312}
313func (s *Server) startEnvironment(syncTimezone bool) error {
314 s.desktopViews.reset()
315 s.browserViews.reset()
316 s.controlSession.close()
317 s.desktopStatus.invalidate()
318 defer s.desktopStatus.invalidate()
319 if err := s.requireStorageReady(); err != nil {
320 return err
321 }
322 if s.macosGuest != nil {
323 return s.startMacOSGuest()
324 }
325 if s.windowsGuest != nil {
326 return s.startWindowsGuest()
327 }
328 pending, err := guestos.LoadInstallation(s.profile)
329 if err != nil || (pending != nil && !hostimage.IsLinux(pending.System)) {
330 return errors.New("请从首次安装入口继续原生客户机安装")
331 }
332 linuxSystem, err := s.installedLinuxSystem()
333 if err != nil {
334 return err
335 }
336 if pending != nil {
337 prepared, err := hostimage.Load(filepath.Join(s.profile, "state", "guest-media"))
338 if err != nil || pending.Media == "" || prepared != pending.Source {
339 return errors.New("请从首次安装入口完成本机系统材料准备")
340 }
341 }
342 // Check before proxy activation or the first image download. The UI cannot
343 // bypass this gate by calling /start or applying settings directly.
344 if err := requireHostGit(s.operationContext()); err != nil {
345 return err
346 }
347 if _, err := validateWorkspace(s.environmentDir(), s.profile); err != nil {
348 return err
349 }
350 if containerenv.Configured(s.profile) {
351 environment, err := containerenv.Load(s.profile)
352 if err != nil {
353 return err
354 }
355 state, err := environment.State(s.operationContext())
356 if err != nil {
357 return err
358 }
359 if state.Running && !state.MountsReady {
360 s.mu.Lock()
361 s.ready = false
362 s.mu.Unlock()
363 return errors.New("容器项目共享需要初始化,请保存工作后先停止环境,再重新启动;项目和登录数据会保留")
364 }
365 }
366 cfg, err := loadConfig(s.configPath)
367 if err != nil {
368 return err
369 }
370 if err = cfg.RequireManagedProxy(s.profile); err != nil {
371 _ = s.closeProxyGate(err.Error())
372 return err
373 }
374 {
375 p, e := managedproxy.Load(s.profile)
376 if e != nil {
377 return e
378 }
379 if p.Selected == "" || p.Endpoint() != cfg.ProxyURL || p.Revision != cfg.ProxyRevision {
380 return errors.New("内置代理配置未应用,请重新选择节点")
381 }
382 name, e := physicalProxyInterface(s.operationContext())
383 if e != nil {
384 _ = s.closeProxyGate(e.Error())
385 return e
386 }
387 bound, _ := managedproxy.BoundInterface(filepath.Join(managedproxy.Dir(s.profile), "config.yaml"))
388 if bound != name || !managedproxy.Running(s.operationContext(), s.profile, p) {
389 // Every core start changes the report generation, including recovery.
390 if e = s.activateProxy(p, cfg); e != nil {
391 return e
392 }
393 cfg, e = loadConfig(s.configPath)
394 if e != nil {
395 return e
396 }
397 }
398 }
399
400 attachErr := s.attach()
401 if errors.Is(attachErr, errGuestUpdateRequired) {
402 return s.synchronizeEnvironment()
403 }
404 if attachErr == nil {
405 client, gateErr := s.gateClient()
406 if gateErr == nil {
407 state, e := client.Status(context.Background())
408 if e == nil {
409 if state.Mode == cage.GateOpen && state.Report != nil && state.Report.Authorizes(state.RunID, cfg.Fingerprint(), time.Now()) == nil {
410 s.publishGate(state)
411 return nil
412 }
413 return s.checkNetworkIfWanted()
414 }
415 }
416 s.setMessage("正在重启环境以加载 VM 外网络门槛…")
417 if err := s.stopEnvironment(); err != nil {
418 return err
419 }
420 }
421 s.mu.Lock()
422 preferences := s.preferences
423 auto := preferences.AutoTimezone || preferences.AutoLanguage
424 s.mu.Unlock()
425 s.setMessage("正在验证代理出口…")
426 loc, probeErr := probeEnvironmentLocation(s.operationContext(), cfg, preferences)
427 if s.operationContext().Err() != nil {
428 return s.operationContext().Err()
429 }
430 if err := s.finishLocationProbe(cfg, loc, probeErr); err != nil {
431 return err
432 }
433 if probeErr != nil && !s.environmentPrepared() {
434 return probeErr
435 }
436 if cfg.ExitPolicy.NeedsBinding() && loc.IP != "" && !s.vmRunning() {
437 bound := cfg.ExitPolicy.BindMissing(loc.exitLocation())
438 if bound != cfg.ExitPolicy {
439 cfg.ExitPolicy = bound
440 if err = writePrivate(s.configPath, cfg); err != nil {
441 return err
442 }
443 }
444 }
445 if auto && syncTimezone && !s.vmRunning() && probeErr == nil {
446 observed := loc.exitLocation()
447 within, _ := cfg.ExitPolicy.Evaluate(loc.IP, &observed)
448 updated := cfg
449 if within == cage.CheckPassed {
450 updated = autoRegionSettings(cfg, preferences, loc)
451 }
452 if updated != cfg {
453 // Changing a live hostagent's profile is forbidden. Stop before replacing it.
454 s.setMessage("正在应用出口所在地的时区与语言建议…")
455 if err = s.stopEnvironment(); err != nil {
456 return err
457 }
458 cfg = updated
459 if err = writePrivate(s.configPath, cfg); err != nil {
460 return err
461 }
462 }
463 } else if probeErr != nil {
464 s.setMessage("代理出口无法通过检查,正在启动离线环境…")
465 }
466 if _, err = os.Stat(filepath.Join(s.profile, "state", ".agent-vm-base-version")); !containerenv.Configured(s.profile) && os.IsNotExist(err) {
467 s.setMessage("首次准备 Linux 环境与开发工具,可能需要数分钟…")
468 job := s.jobs.execution()
469 job.setSetupProgress(&SetupProgress{Phase: "image", System: linuxSystem, Label: "正在准备 " + guestProgressName(linuxSystem) + " 镜像"})
470 if err = s.runCage("setup"); err != nil {
471 return err
472 }
473 job.setSetupProgress(&SetupProgress{Phase: "services", Label: "正在启动浏览器和编辑器"})
474 defer job.setSetupProgress(nil)
475 }
476 s.setMessage("正在启动浏览器、编辑器与共享文件…")
477 if err = s.runCage("up"); err != nil {
478 return err
479 }
480 for i := 0; i < 8; i++ {
481 if s.operationContext().Err() != nil {
482 return s.operationContext().Err()
483 }
484 if err = s.attach(); err == nil {
485 return s.checkNetworkIfWanted()
486 }
487 time.Sleep(time.Second)
488 }
489 return errors.New("环境已启动,但浏览器连接尚未就绪。请重试连接或查看操作详情。")
490}
491func (s *Server) stopEnvironment() (returned error) {
492 s.desktopStatus.invalidate()
493 defer s.desktopStatus.invalidate()
494 explicitStop := s.jobs.snapshot().Kind == "stop"
495 defer func() {
496 if explicitStop && returned == nil {
497 returned = managedproxy.Stop(s.profile)
498 }
499 }()
500 if s.windowsGuest != nil {
501 return s.stopWindowsGuest()
502 }
503 if s.macosGuest != nil {
504 return s.stopMacOSGuest()
505 }
506 s.setMessage("正在停止 Cage 环境…")
507 if (explicitStop || s.jobs.snapshot().Kind == "storage") && cage.InstanceJobID(filepath.Join(s.profile, "state"), "base-building") != "" {
508 if err := s.runCage("stop", "base-building"); err != nil {
509 return err
510 }
511 }
512 if client, err := s.gateClient(); err == nil {
513 if state, e := client.Close(context.Background(), "环境正在停止"); e == nil {
514 s.publishGate(state)
515 }
516 }
517 s.mu.Lock()
518 s.ready = false
519 s.credentials = guestCredentials{}
520 s.guestManifest = nil
521 s.guestUpdateRequired = false
522 s.guestUpdateError = ""
523 s.safety.Error = ""
524 s.mu.Unlock()
525 s.terminals.closeAll()
526 s.mobileCLI.stopAll()
527 s.closeProjectShares()
528 if s.workspace() == "" {
529 return nil
530 }
531 if _, err := os.Stat(filepath.Join(s.instanceDir(), "lima.yaml")); !containerenv.Configured(s.profile) && os.IsNotExist(err) {
532 return nil
533 }
534 if err := s.runCage("stop"); err != nil {
535 return err
536 }
537 return nil
538}
539func (s *Server) apply(v savedProfile, validate bool) error {
540 old, err := loadConfig(s.configPath)
541 if err != nil {
542 return err
543 }
544 // Network endpoints are generated by the node manager, including restore.
545 v.Config.ProxyURL, v.Config.ProxyRevision = old.ProxyURL, old.ProxyRevision
546 s.mu.Lock()
547 oldPrefs := s.preferences
548 resumeVersion := s.safety.pauseVersion
549 if execution := s.jobs.execution(); execution.id != "" {
550 resumeVersion = execution.pauseVersion
551 }
552 wasReady := vmAlive(s.profile, s.environmentDir())
553 if s.windowsGuest != nil {
554 wasReady = s.windowsState.Running
555 } else if s.macosGuest != nil {
556 wasReady = macOSInstanceRunning(s.instanceDir())
557 }
558 s.mu.Unlock()
559 changed := old != v.Config || oldPrefs.AutoTimezone != v.Preferences.AutoTimezone || oldPrefs.AutoLanguage != v.Preferences.AutoLanguage
560 if changed && validate && old.RequireManagedProxy(s.profile) == nil {
561 s.setMessage("正在验证新出口,现有环境保持运行…")
562 loc, e := probeEnvironmentLocation(s.operationContext(), v.Config, v.Preferences)
563 if err := s.finishLocationProbe(v.Config, loc, e); err != nil {
564 return err
565 }
566 if e != nil {
567 if v.Preferences.AutoTimezone || v.Preferences.AutoLanguage || loc.IP == "" {
568 return e
569 }
570 } else {
571 v.Config = autoRegionSettings(v.Config, v.Preferences, loc)
572 }
573 v.Config.ExitPolicy = v.Config.ExitPolicy.BindMissing(loc.exitLocation())
574 observed := loc.exitLocation()
575 if result, message := v.Config.ExitPolicy.Evaluate(loc.IP, &observed); result != cage.CheckPassed {
576 if result == cage.CheckUnknown && e != nil && !v.Preferences.AutoTimezone && !v.Preferences.AutoLanguage {
577 return errors.New("时区和语言已选择手动设置,但所有出口仍须确认国家或地区。请重试位置检测或切换节点;静态 IP 和不限地区不能跳过大陆出口检查,原配置保持不变")
578 }
579 return errors.New(message)
580 }
581 }
582 if changed {
583 if s.windowsGuest != nil && wasReady && (old.Timezone != v.Config.Timezone || old.Locale != v.Config.Locale) {
584 if err := s.closeProxyGate("正在应用 Windows 系统设置,外网等待重新检查"); err != nil {
585 return err
586 }
587 if err := s.applyWindowsGuestSettings(s.operationContext(), v.Config); err != nil {
588 return err
589 }
590 }
591 if err := s.resumeNetworkIntentAt(resumeVersion); err != nil {
592 return err
593 }
594 if s.operationContext().Err() != nil {
595 return s.operationContext().Err()
596 }
597 if err = writePrivate(filepath.Join(s.profile, "previous-profile.json"), savedProfile{old, oldPrefs}); err != nil {
598 return err
599 }
600 if err = s.stopEnvironment(); err != nil {
601 return err
602 }
603 }
604 // A project is a live directory grant in the same VM, never a lifecycle change.
605 if v.Preferences.Workspace != "" && s.vmRunning() {
606 s.setMessage("正在连接项目文件夹…")
607 if _, err = s.connectProject(v.Preferences.Workspace, true); err != nil {
608 return err
609 }
610 }
611 if err = writePrivate(s.configPath, v.Config); err != nil {
612 return err
613 }
614 if err = writePrivate(filepath.Join(s.profile, "workbench.json"), v.Preferences); err != nil {
615 _ = writePrivate(s.configPath, old)
616 return err
617 }
618 s.mu.Lock()
619 s.preferences = v.Preferences
620 token, ready := s.credentials.Token, s.ready
621 s.mu.Unlock()
622 s.jobs.execution().settingsSaved()
623 if !changed && ready && browserHomeURL(oldPrefs) != browserHomeURL(v.Preferences) {
624 ctx, cancel := s.controlContext()
625 defer cancel()
626 if err = s.setBrowserHome(ctx, token, browserHomeURL(v.Preferences)); err != nil {
627 return fmt.Errorf("设置已保存,但浏览器暂时未能应用默认网站,请恢复连接后重试:%w", err)
628 }
629 }
630 if changed && wasReady {
631 s.setMessage("正在重新连接客机…")
632 if err = s.startEnvironment(false); err != nil {
633 var network networkCheckError
634 if errors.As(err, &network) {
635 return fmt.Errorf("设置已保存,环境已启动。外网仍关闭,修复以下问题后可重新检测:%w", err)
636 }
637 return fmt.Errorf("设置已保存,环境尚未恢复就绪。请核对客机状态后重试启动:%w", err)
638 }
639 }
640 return nil
641}
642
643// Interface recovery uses the ordinary cancellable job queue. Location changes
644// remain governed by the saved exit policy and never replace its baseline.
645func (s *Server) monitorNetworkTick() {
646 timing := s.startMonitorTiming()
647 defer s.recordMonitorTiming("network", timing)
648 if s.storageRecoveryStatus().Required {
649 timing.result = "storage_recovery_pending"
650 return
651 }
652 if s.macSetupPending() {
653 timing.result = "setup_pending"
654 return
655 }
656 s.monitorProxyInterface()
657 timing.stage("physical_interface")
658 s.checkProxyHealth()
659 timing.stage("proxy_health")
660 s.monitorSafety()
661 timing.stage("safety")
662 s.recoverNetwork()
663 timing.stage("recovery")
664 s.refreshProxySubscriptions()
665 timing.stage("subscriptions")
666}
667
668func (s *Server) monitorNetwork(ctx context.Context) {
669 ticker := time.NewTicker(5 * time.Second)
670 defer ticker.Stop()
671 skipped := 0
672 for ctx.Err() == nil {
673 if s.op.TryLock() {
674 skipped = 0
675 s.monitorNetworkTick()
676 s.op.Unlock()
677 } else {
678 skipped++
679 timing := s.startMonitorTiming()
680 timing.result = "operation_lock_busy"
681 timing.stages = append(timing.stages, fmt.Sprintf("consecutive_lock_skips=%d", skipped))
682 s.recordMonitorTiming("network", timing)
683 }
684 select {
685 case <-ctx.Done():
686 return
687 case <-ticker.C:
688 }
689 }
690}
691
692func vmAlive(profile, workspace string) bool {
693 if containerenv.Configured(profile) {
694 environment, err := containerenv.Load(profile)
695 if err != nil {
696 return false
697 }
698 ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
699 defer cancel()
700 state, err := environment.State(ctx)
701 return err == nil && state.Running
702 }
703 if workspace == "" {
704 return false
705 }
706 b, e := os.ReadFile(filepath.Join(profile, "state", "lima", cage.InstanceName(profile, workspace), "cage-running.json"))
707 if e != nil {
708 return false
709 }
710 var record struct {
711 PID int `json:"pid"`
712 Started string `json:"started"`
713 }
714 if json.Unmarshal(b, &record) != nil || record.PID < 1 {
715 return false
716 }
717 return processExists(record.PID) && cage.ProcessStartMatches(record.PID, record.Started)
718}
719func (s *Server) vmRunning() bool {
720 if s.windowsGuest != nil {
721 s.mu.Lock()
722 defer s.mu.Unlock()
723 return s.windowsState.Running
724 }
725 if s.macosGuest != nil {
726 return macOSInstanceRunning(s.instanceDir())
727 }
728 return vmAlive(s.profile, s.environmentDir())
729}