| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 8 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 9 | "runtime/debug" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "time" |
| 13 | ) |
| 14 | |
| 15 | type Job struct { |
| 16 | Canceled bool `json:"canceled,omitempty"` |
| 17 | SettingsSaved bool `json:"settings_saved,omitempty"` |
| 18 | SetupProgress *SetupProgress `json:"setup_progress,omitempty"` |
| 19 | ID string `json:"id"` |
| 20 | Kind string `json:"kind"` |
| 21 | Running bool `json:"running"` |
| 22 | Message string `json:"message"` |
| 23 | Error string `json:"error,omitempty"` |
| 24 | Recovery string `json:"recovery,omitempty"` |
| 25 | Workspace string `json:"workspace,omitempty"` |
| 26 | Log string `json:"log,omitempty"` |
| 27 | } |
| 28 | |
| 29 | var ( |
| 30 | errJobBusy = errors.New("另一个操作仍在进行,请稍候") |
| 31 | errJobsClosed = errors.New("后台正在更新,请重新打开 Cage。") |
| 32 | ) |
| 33 | |
| 34 | |
| 35 | |
| 36 | type jobManager struct { |
| 37 | mu sync.Mutex |
| 38 | state Job |
| 39 | cancel context.CancelFunc |
| 40 | active *jobExecution |
| 41 | afterSuccess func() error |
| 42 | closed bool |
| 43 | workers sync.WaitGroup |
| 44 | } |
| 45 | |
| 46 | |
| 47 | |
| 48 | |
| 49 | func (m *jobManager) submit(operation sync.Locker, kind string, pauseVersion uint64, prepare func() error, afterSuccess func() error, run func() error) (Job, error) { |
| 50 | m.mu.Lock() |
| 51 | defer m.mu.Unlock() |
| 52 | if m.closed { |
| 53 | return Job{}, errJobsClosed |
| 54 | } |
| 55 | if m.state.Running { |
| 56 | if kind == "stop" && m.state.Kind == "stop" { |
| 57 | |
| 58 | |
| 59 | if afterSuccess != nil { |
| 60 | m.afterSuccess = afterSuccess |
| 61 | } |
| 62 | return m.state, nil |
| 63 | } |
| 64 | if kind != "stop" { |
| 65 | return Job{}, fmt.Errorf("%w:当前正在%s。请等待完成,或先停止当前操作。", errJobBusy, jobName(m.state.Kind)) |
| 66 | } |
| 67 | } |
| 68 | if prepare != nil { |
| 69 | if err := prepare(); err != nil { |
| 70 | return Job{}, err |
| 71 | } |
| 72 | } |
| 73 | if m.cancel != nil { |
| 74 | m.cancel() |
| 75 | } |
| 76 | ctx, cancel := context.WithCancel(context.Background()) |
| 77 | m.cancel = cancel |
| 78 | m.afterSuccess = afterSuccess |
| 79 | m.state = Job{ID: randomToken()[:12], Kind: kind, Running: true, Message: "正在准备…"} |
| 80 | execution := &jobExecution{owner: m, id: m.state.ID, ctx: ctx, pauseVersion: pauseVersion} |
| 81 | execution.log = diagnostics.NewStream(diagnostics.Default(), "task/"+kind, "info", func(line string) { |
| 82 | if m.state.ID == execution.id { |
| 83 | if m.state.SetupProgress != nil { |
| 84 | if p := parseSetupProgress(line); p != nil { |
| 85 | previous := m.state.SetupProgress |
| 86 | if p.System == "" { |
| 87 | p.System = previous.System |
| 88 | } |
| 89 | now := time.Now() |
| 90 | if p.Operation != "verify" && p.Label == previous.Label && p.Total == previous.Total && p.Received != nil && previous.Received != nil && *p.Received >= *previous.Received && !execution.progressUpdated.IsZero() { |
| 91 | p.BytesPerSecond = float64(*p.Received-*previous.Received) / now.Sub(execution.progressUpdated).Seconds() |
| 92 | } |
| 93 | execution.progressUpdated = now |
| 94 | m.state.SetupProgress = p |
| 95 | if strings.HasPrefix(line, "CAGE_") { |
| 96 | return |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | m.state.Log += line |
| 101 | if len(m.state.Log) > 24000 { |
| 102 | m.state.Log = m.state.Log[len(m.state.Log)-24000:] |
| 103 | } |
| 104 | } |
| 105 | }) |
| 106 | diagnostics.Log("info", "task", kind+" started") |
| 107 | m.workers.Add(1) |
| 108 | go func() { |
| 109 | defer m.workers.Done() |
| 110 | defer cancel() |
| 111 | operation.Lock() |
| 112 | defer operation.Unlock() |
| 113 | m.mu.Lock() |
| 114 | if m.state.ID != execution.id { |
| 115 | m.mu.Unlock() |
| 116 | return |
| 117 | } |
| 118 | if ctx.Err() != nil { |
| 119 | m.finishLocked(execution, ctx.Err()) |
| 120 | m.mu.Unlock() |
| 121 | return |
| 122 | } |
| 123 | m.active = execution |
| 124 | m.mu.Unlock() |
| 125 | err := func() (err error) { |
| 126 | defer func() { |
| 127 | if failure := recover(); failure != nil { |
| 128 | diagnostics.Log("error", "task", fmt.Sprintf("panic: %v\n%s", failure, debug.Stack())) |
| 129 | panic(failure) |
| 130 | } |
| 131 | }() |
| 132 | return run() |
| 133 | }() |
| 134 | m.mu.Lock() |
| 135 | defer m.mu.Unlock() |
| 136 | m.finishLocked(execution, err) |
| 137 | }() |
| 138 | return m.state, nil |
| 139 | } |
| 140 | |
| 141 | func (m *jobManager) finishLocked(execution *jobExecution, err error) { |
| 142 | if execution.log != nil { |
| 143 | _ = execution.log.Close() |
| 144 | } |
| 145 | if m.active == execution { |
| 146 | m.active = nil |
| 147 | } |
| 148 | if m.state.ID != execution.id { |
| 149 | return |
| 150 | } |
| 151 | if err == nil { |
| 152 | err = execution.ctx.Err() |
| 153 | } |
| 154 | if err == nil && m.afterSuccess != nil { |
| 155 | err = m.afterSuccess() |
| 156 | } |
| 157 | m.cancel, m.afterSuccess = nil, nil |
| 158 | m.state.Running = false |
| 159 | switch { |
| 160 | case errors.Is(err, context.Canceled): |
| 161 | m.state.Canceled = true |
| 162 | m.state.Message = "已取消" |
| 163 | if m.state.SettingsSaved { |
| 164 | m.state.Message = "设置已保存,后续操作已取消" |
| 165 | } |
| 166 | diagnostics.Log("info", "task", m.state.Kind+" canceled") |
| 167 | case err != nil: |
| 168 | m.state.Error = usererror.Display(jobName(m.state.Kind), err, "打开“操作详情”查看失败记录;仍无法处理时,"+failureHelp).Error() |
| 169 | var projectFailure *projectShareError |
| 170 | if errors.As(err, &projectFailure) { |
| 171 | m.state.Recovery = projectFailure.Recovery |
| 172 | m.state.Workspace = projectFailure.Path |
| 173 | } |
| 174 | m.state.Message = jobName(m.state.Kind) + "失败" |
| 175 | var networkFailure networkCheckError |
| 176 | if m.state.Kind == "start" && errors.As(err, &networkFailure) { |
| 177 | m.state.Message = "环境已启动,联网检查未通过" |
| 178 | } else if m.state.SettingsSaved { |
| 179 | m.state.Message = "设置已保存,等待环境恢复" |
| 180 | if errors.As(err, &networkFailure) { |
| 181 | m.state.Message = "设置已保存,环境已启动,联网检查未通过" |
| 182 | } |
| 183 | } |
| 184 | diagnostics.Log("error", "task", fmt.Sprintf("%s: %v; cause=%v", m.state.Kind, err, errors.Unwrap(err))) |
| 185 | default: |
| 186 | m.state.Message = "已完成" |
| 187 | diagnostics.Log("info", "task", m.state.Kind+" completed") |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | func jobName(kind string) string { |
| 192 | names := map[string]string{ |
| 193 | "start": "启动环境", "stop": "停止环境", "setup": "准备环境", "settings": "应用设置", "project": "连接项目目录", "storage": "迁移环境目录", "restore": "恢复配置", "resources": "应用资源配置", "safety": "检查联网条件", "network-recovery": "恢复联网", "proxy": "应用代理节点", "proxy-network": "恢复代理连接", "environment-update": "更新环境组件", "environment-tools": "更新环境工具", "claude-desktop-install": "安装 Claude Desktop", "claude-desktop-start": "打开 Claude Desktop", "claude-desktop-stop": "关闭 Claude Desktop", |
| 194 | } |
| 195 | if name := names[kind]; name != "" { |
| 196 | return name |
| 197 | } |
| 198 | return "本次操作" |
| 199 | } |
| 200 | |
| 201 | func (m *jobManager) snapshot() Job { |
| 202 | m.mu.Lock() |
| 203 | defer m.mu.Unlock() |
| 204 | return m.state |
| 205 | } |
| 206 | |
| 207 | |
| 208 | |
| 209 | func (m *jobManager) execution() *jobExecution { |
| 210 | m.mu.Lock() |
| 211 | defer m.mu.Unlock() |
| 212 | if m.active != nil { |
| 213 | return m.active |
| 214 | } |
| 215 | return &jobExecution{owner: m, ctx: context.Background()} |
| 216 | } |
| 217 | |
| 218 | func (m *jobManager) cancelRunning() string { |
| 219 | m.mu.Lock() |
| 220 | defer m.mu.Unlock() |
| 221 | if m.state.Kind != "stop" && m.cancel != nil { |
| 222 | m.cancel() |
| 223 | } |
| 224 | if m.active != nil { |
| 225 | return m.active.id |
| 226 | } |
| 227 | return "" |
| 228 | } |
| 229 | |
| 230 | |
| 231 | |
| 232 | func (m *jobManager) close() { |
| 233 | m.mu.Lock() |
| 234 | m.closed = true |
| 235 | if m.cancel != nil { |
| 236 | m.cancel() |
| 237 | } |
| 238 | m.mu.Unlock() |
| 239 | m.workers.Wait() |
| 240 | } |
| 241 | |
| 242 | type jobExecution struct { |
| 243 | owner *jobManager |
| 244 | id string |
| 245 | ctx context.Context |
| 246 | pauseVersion uint64 |
| 247 | log *diagnostics.Stream |
| 248 | progressUpdated time.Time |
| 249 | } |
| 250 | |
| 251 | func (e *jobExecution) message(message string) { |
| 252 | e.owner.mu.Lock() |
| 253 | defer e.owner.mu.Unlock() |
| 254 | if e.id != "" && e.owner.state.ID == e.id && e.owner.state.Running { |
| 255 | if e.owner.state.SettingsSaved { |
| 256 | message = "设置已保存," + message |
| 257 | } |
| 258 | e.owner.state.Message = message |
| 259 | } |
| 260 | } |
| 261 | |
| 262 | func (e *jobExecution) settingsSaved() { |
| 263 | e.owner.mu.Lock() |
| 264 | defer e.owner.mu.Unlock() |
| 265 | if e.id != "" && e.owner.state.ID == e.id && e.owner.state.Running { |
| 266 | e.owner.state.SettingsSaved = true |
| 267 | } |
| 268 | } |
| 269 | |
| 270 | func (e *jobExecution) Write(data []byte) (int, error) { |
| 271 | e.owner.mu.Lock() |
| 272 | defer e.owner.mu.Unlock() |
| 273 | if e.id != "" && e.owner.state.ID == e.id && e.owner.state.Running { |
| 274 | if e.log != nil { |
| 275 | _, _ = e.log.Write(data) |
| 276 | } |
| 277 | } |
| 278 | return len(data), nil |
| 279 | } |