跳到主要内容

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

浏览文件

jobs.go

279 行 · 8.5 KB历史下载
1package workbench
2
3import (
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
15type 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
29var (
30 errJobBusy = errors.New("另一个操作仍在进行,请稍候")
31 errJobsClosed = errors.New("后台正在更新,请重新打开 Cage。")
32)
33
34// jobManager owns accepted work independently of HTTP requests. The operation
35// lock is shared with synchronous workbench operations and monitoring.
36type 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// prepare runs synchronously only for a new admission. Neither prepare nor
47// afterSuccess may call this manager. afterSuccess must not acquire Server.mu:
48// submission can hold Server.mu while waiting for the manager's lock.
49func (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 // Logout can join a pending stop and request account locking once
58 // that same stop succeeds. A plain repeated stop cannot undo it.
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
141func (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
191func 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
201func (m *jobManager) snapshot() Job {
202 m.mu.Lock()
203 defer m.mu.Unlock()
204 return m.state
205}
206
207// execution returns the operation that is actually running, including an old
208// operation that has been cancelled by a stop but has not returned yet.
209func (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
218func (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// close seals admission before waiting, so no worker can be added concurrently
231// with Wait. Superseded workers are included even while waiting for operation.
232func (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
242type 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
251func (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
262func (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
270func (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}