| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "errors" |
| 7 | "os" |
| 8 | "path/filepath" |
| 9 | "sort" |
| 10 | "strings" |
| 11 | "sync" |
| 12 | "time" |
| 13 | "unicode/utf8" |
| 14 | |
| 15 | "github.com/google/uuid" |
| 16 | "github.com/sylvinus/agent-vm/internal/cliconversation" |
| 17 | "github.com/sylvinus/agent-vm/internal/host" |
| 18 | ) |
| 19 | |
| 20 | const ( |
| 21 | mobilePromptLimit = 32 << 10 |
| 22 | mobileReplyLimit = 128 << 10 |
| 23 | mobileHistoryLimit = 448 << 10 |
| 24 | ) |
| 25 | |
| 26 | type mobileSummary struct { |
| 27 | AccountID string `json:"account_id,omitempty"` |
| 28 | AccountLabel string `json:"account_label,omitempty"` |
| 29 | Generation string `json:"generation"` |
| 30 | ID string `json:"id"` |
| 31 | Workspace string `json:"workspace"` |
| 32 | Title string `json:"title"` |
| 33 | CustomTitle string `json:"custom_title,omitempty"` |
| 34 | Pinned bool `json:"pinned"` |
| 35 | Active bool `json:"active"` |
| 36 | Running bool `json:"running"` |
| 37 | MetadataSet bool `json:"metadata_set"` |
| 38 | Deleted bool `json:"deleted,omitempty"` |
| 39 | Archived bool `json:"archived,omitempty"` |
| 40 | Purged bool `json:"purged,omitempty"` |
| 41 | Deleting bool `json:"deleting,omitempty"` |
| 42 | Revision uint64 `json:"revision"` |
| 43 | UpdatedAt time.Time `json:"updated_at"` |
| 44 | } |
| 45 | type mobileTurn struct { |
| 46 | Tools []cliconversation.ToolActivity `json:"tools,omitempty"` |
| 47 | ID string `json:"id"` |
| 48 | Prompt string `json:"prompt"` |
| 49 | Text string `json:"text"` |
| 50 | Status string `json:"status"` |
| 51 | Error string `json:"error,omitempty"` |
| 52 | DeniedTools []string `json:"denied_tools,omitempty"` |
| 53 | Truncated bool `json:"truncated,omitempty"` |
| 54 | Approval *mobileApproval `json:"approval,omitempty"` |
| 55 | } |
| 56 | type mobileApproval struct { |
| 57 | ID string `json:"id"` |
| 58 | Tool string `json:"tool"` |
| 59 | Input json.RawMessage `json:"input"` |
| 60 | Preview bool `json:"preview,omitempty"` |
| 61 | } |
| 62 | type mobileDecision struct { |
| 63 | ctx context.Context |
| 64 | reply chan bool |
| 65 | } |
| 66 | type mobileSession struct { |
| 67 | SwitchPolicy string `json:"switch_policy,omitempty"` |
| 68 | AccountFailure string `json:"account_failure,omitempty"` |
| 69 | AccountSwitch *claudeSwitchView `json:"account_switch,omitempty"` |
| 70 | mediaWorkingDir string |
| 71 | mobileSummary |
| 72 | Turns []mobileTurn `json:"turns"` |
| 73 | SingleTurn bool `json:"single_turn,omitempty"` |
| 74 | CanSend *bool `json:"can_send,omitempty"` |
| 75 | ConnectionNotice string `json:"connection_notice,omitempty"` |
| 76 | ConnectionWaiting bool `json:"connection_waiting,omitempty"` |
| 77 | HistoryTruncated bool `json:"history_truncated,omitempty"` |
| 78 | AcknowledgedRequestID string `json:"acknowledged_request_id,omitempty"` |
| 79 | TerminalAvailable bool `json:"terminal_available,omitempty"` |
| 80 | DesktopTerminalID string `json:"desktop_terminal_id,omitempty"` |
| 81 | } |
| 82 | type mobileRecord struct { |
| 83 | mobileSession |
| 84 | |
| 85 | |
| 86 | CLIID string `json:"cli_id"` |
| 87 | Launcher string `json:"launcher,omitempty"` |
| 88 | Account claudeSelection `json:"account"` |
| 89 | Resume bool `json:"resume"` |
| 90 | Terminal bool `json:"terminal,omitempty"` |
| 91 | GuestConfig string `json:"guest_config,omitempty"` |
| 92 | GuestWorkspace string `json:"guest_workspace,omitempty"` |
| 93 | Connection string `json:"connection,omitempty"` |
| 94 | TerminalID string `json:"terminal_id,omitempty"` |
| 95 | TerminalRunning bool `json:"terminal_running,omitempty"` |
| 96 | LegacyTurns []mobileTurn `json:"legacy_turns,omitempty"` |
| 97 | Switch *claudeAccountSwitch `json:"switch,omitempty"` |
| 98 | Executions []claudeExecution `json:"executions,omitempty"` |
| 99 | ResumeTranscript string `json:"resume_transcript,omitempty"` |
| 100 | } |
| 101 | |
| 102 | type claudeExecution struct { |
| 103 | CLIID string `json:"cli_id"` |
| 104 | Account claudeSelection `json:"account"` |
| 105 | Config string `json:"config"` |
| 106 | } |
| 107 | |
| 108 | type claudeAccountSwitch struct { |
| 109 | ID string `json:"id"` |
| 110 | Phase string `json:"phase"` |
| 111 | Source claudeExecution `json:"source"` |
| 112 | Target claudeSelection `json:"target"` |
| 113 | TargetID string `json:"target_cli_id"` |
| 114 | TargetLabel string `json:"target_label"` |
| 115 | Connection string `json:"connection"` |
| 116 | Error string `json:"error,omitempty"` |
| 117 | Continue bool `json:"continue"` |
| 118 | } |
| 119 | |
| 120 | type claudeSwitchView struct { |
| 121 | ID string `json:"id"` |
| 122 | Phase string `json:"phase"` |
| 123 | TargetLabel string `json:"target_label"` |
| 124 | Error string `json:"error,omitempty"` |
| 125 | } |
| 126 | type mobileRun struct { |
| 127 | record *mobileRecord |
| 128 | cancel context.CancelFunc |
| 129 | done chan struct{} |
| 130 | approvalGate chan struct{} |
| 131 | pending *mobileDecision |
| 132 | } |
| 133 | type mobileCLIStore struct { |
| 134 | mu sync.Mutex |
| 135 | active map[string]*mobileRun |
| 136 | catalog map[string]mobileSummary |
| 137 | running map[string]bool |
| 138 | generation string |
| 139 | } |
| 140 | |
| 141 | func (m *mobileCLIStore) epochLocked() string { |
| 142 | if m.generation == "" { |
| 143 | m.generation = uuid.NewString() |
| 144 | } |
| 145 | return m.generation |
| 146 | } |
| 147 | |
| 148 | func mobileID(id string) bool { |
| 149 | v, err := uuid.Parse(id) |
| 150 | return err == nil && v.Version() == 4 && v.Variant() == uuid.RFC4122 && v.String() == id |
| 151 | } |
| 152 | func validCLIUUID(id string) bool { |
| 153 | v, err := uuid.Parse(id) |
| 154 | return err == nil && v.String() == id |
| 155 | } |
| 156 | func mobileRecordPath(profile, id string) string { |
| 157 | return filepath.Join(profile, "mobile-cli-sessions", id+".json") |
| 158 | } |
| 159 | func (record *mobileRecord) changed() { |
| 160 | record.Revision++ |
| 161 | record.UpdatedAt = time.Now().UTC() |
| 162 | } |
| 163 | func (record *mobileRecord) summary() mobileSummary { |
| 164 | view := record.mobileSummary |
| 165 | view.AccountID = record.Account.ID |
| 166 | return view |
| 167 | } |
| 168 | func (record *mobileRecord) snapshot() mobileSession { |
| 169 | view := record.mobileSession |
| 170 | view.AccountID = record.Account.ID |
| 171 | if sw := record.Switch; sw != nil { |
| 172 | view.AccountSwitch = &claudeSwitchView{ID: sw.ID, Phase: sw.Phase, TargetLabel: sw.TargetLabel, Error: sw.Error} |
| 173 | } |
| 174 | if !record.Terminal { |
| 175 | view.Active = record.turnActive() |
| 176 | } |
| 177 | view.mediaWorkingDir = record.GuestWorkspace |
| 178 | view.TerminalAvailable = record.Terminal |
| 179 | view.DesktopTerminalID = record.TerminalID |
| 180 | if record.CustomTitle != "" { |
| 181 | view.Title = record.CustomTitle |
| 182 | } |
| 183 | view.Turns = append([]mobileTurn{}, record.Turns...) |
| 184 | return view |
| 185 | } |
| 186 | |
| 187 | func (record *mobileRecord) turnActive() bool { |
| 188 | if len(record.Turns) == 0 { |
| 189 | return false |
| 190 | } |
| 191 | status := record.Turns[len(record.Turns)-1].Status |
| 192 | return status == "running" || status == "stopping" || status == "queued" |
| 193 | } |
| 194 | |
| 195 | |
| 196 | |
| 197 | func (m *mobileCLIStore) record(profile, id string) (*mobileRecord, error) { |
| 198 | if !mobileID(id) { |
| 199 | return nil, os.ErrNotExist |
| 200 | } |
| 201 | if run := m.active[id]; run != nil { |
| 202 | if run.cancel == nil && writePrivate(mobileRecordPath(profile, id), run.record) == nil { |
| 203 | delete(m.active, id) |
| 204 | } |
| 205 | return run.record, nil |
| 206 | } |
| 207 | path := mobileRecordPath(profile, id) |
| 208 | if err := host.CheckPrivateFile(path); err != nil { |
| 209 | return nil, err |
| 210 | } |
| 211 | info, err := os.Stat(path) |
| 212 | if err != nil { |
| 213 | return nil, err |
| 214 | } |
| 215 | if info.Size() > 4<<20 { |
| 216 | return nil, errors.New("CLI 会话记录过大") |
| 217 | } |
| 218 | b, err := os.ReadFile(path) |
| 219 | if err != nil { |
| 220 | return nil, err |
| 221 | } |
| 222 | var record mobileRecord |
| 223 | if json.Unmarshal(b, &record) != nil || record.ID != id || !validCLIUUID(record.CLIID) || record.Workspace == "" || record.Turns == nil { |
| 224 | return nil, errors.New("CLI 会话记录无效,请从备份恢复") |
| 225 | } |
| 226 | |
| 227 | if record.Deleted && !record.Purged { |
| 228 | record.Deleted, record.Archived = false, true |
| 229 | if err := writePrivate(path, &record); err != nil { |
| 230 | return nil, err |
| 231 | } |
| 232 | } |
| 233 | record.Generation = m.epochLocked() |
| 234 | if n := len(record.Turns); n > 0 && !record.Terminal { |
| 235 | turn := &record.Turns[n-1] |
| 236 | if turn.Status == "running" || turn.Status == "stopping" { |
| 237 | turn.Status, turn.Error = "interrupted", "主机服务重新启动。请检查本轮结果后再发送消息。" |
| 238 | record.changed() |
| 239 | if err := writePrivate(path, &record); err != nil { |
| 240 | return nil, err |
| 241 | } |
| 242 | } |
| 243 | } |
| 244 | return &record, nil |
| 245 | } |
| 246 | func (m *mobileCLIStore) summaries(profile string, granted map[string]bool, archived bool) ([]mobileSummary, error) { |
| 247 | m.mu.Lock() |
| 248 | defer m.mu.Unlock() |
| 249 | list := []mobileSummary{} |
| 250 | if m.catalog == nil { |
| 251 | entries, err := os.ReadDir(filepath.Join(profile, "mobile-cli-sessions")) |
| 252 | if err != nil && !errors.Is(err, os.ErrNotExist) { |
| 253 | return nil, err |
| 254 | } |
| 255 | catalog := make(map[string]mobileSummary, len(entries)) |
| 256 | for _, entry := range entries { |
| 257 | id, ok := strings.CutSuffix(entry.Name(), ".json") |
| 258 | if !ok || !mobileID(id) { |
| 259 | continue |
| 260 | } |
| 261 | record, err := m.record(profile, id) |
| 262 | if err != nil { |
| 263 | return nil, err |
| 264 | } |
| 265 | catalog[id] = record.summary() |
| 266 | } |
| 267 | m.catalog = catalog |
| 268 | } |
| 269 | for id, summary := range m.catalog { |
| 270 | if run := m.active[id]; run != nil { |
| 271 | summary = run.record.summary() |
| 272 | summary.Active = run.record.turnActive() |
| 273 | } |
| 274 | summary.Running = m.running[id] |
| 275 | if granted[summary.Workspace] && !summary.Deleted && summary.Archived == archived { |
| 276 | if summary.CustomTitle != "" { |
| 277 | summary.Title = summary.CustomTitle |
| 278 | } |
| 279 | list = append(list, summary) |
| 280 | } |
| 281 | } |
| 282 | sort.Slice(list, func(i, j int) bool { |
| 283 | if list[i].Pinned != list[j].Pinned { |
| 284 | return list[i].Pinned |
| 285 | } |
| 286 | return list[i].UpdatedAt.After(list[j].UpdatedAt) |
| 287 | }) |
| 288 | return list, nil |
| 289 | } |
| 290 | func (m *mobileCLIStore) create(profile, workspace, id string) (mobileSession, error) { |
| 291 | m.mu.Lock() |
| 292 | defer m.mu.Unlock() |
| 293 | record, err := m.record(profile, id) |
| 294 | if err == nil { |
| 295 | if record.Deleted || record.Archived { |
| 296 | return mobileSession{}, errors.New("此会话已归档或删除,请从已归档会话恢复或新建会话") |
| 297 | } |
| 298 | if record.Workspace != workspace { |
| 299 | return mobileSession{}, errors.New("创建请求已用于其他项目") |
| 300 | } |
| 301 | return record.snapshot(), nil |
| 302 | } |
| 303 | if !errors.Is(err, os.ErrNotExist) { |
| 304 | return mobileSession{}, err |
| 305 | } |
| 306 | record = &mobileRecord{mobileSession: mobileSession{mobileSummary: mobileSummary{ID: id, Workspace: workspace, Title: "新会话"}, Turns: []mobileTurn{}}, CLIID: uuid.NewString()} |
| 307 | record.Generation = m.epochLocked() |
| 308 | record.changed() |
| 309 | err = writePrivate(mobileRecordPath(profile, id), record) |
| 310 | if err == nil && m.catalog != nil { |
| 311 | m.catalog[id] = record.summary() |
| 312 | } |
| 313 | return record.snapshot(), err |
| 314 | } |
| 315 | func mobileTrim(text string, limit int) string { |
| 316 | if len(text) <= limit { |
| 317 | return text |
| 318 | } |
| 319 | for limit > 0 && !utf8.RuneStart(text[limit]) { |
| 320 | limit-- |
| 321 | } |
| 322 | return text[:limit] |
| 323 | } |
| 324 | func (m *mobileCLIStore) activeAccounts() map[string]int { |
| 325 | m.mu.Lock() |
| 326 | defer m.mu.Unlock() |
| 327 | count := map[string]int{} |
| 328 | for _, run := range m.active { |
| 329 | if run.cancel != nil { |
| 330 | count[run.record.Account.ID]++ |
| 331 | } |
| 332 | } |
| 333 | return count |
| 334 | } |
| 335 | func (m *mobileCLIStore) stopAll() { |
| 336 | m.mu.Lock() |
| 337 | done := make([]chan struct{}, 0, len(m.active)) |
| 338 | for _, run := range m.active { |
| 339 | if run.cancel != nil { |
| 340 | run.cancel() |
| 341 | done = append(done, run.done) |
| 342 | } |
| 343 | } |
| 344 | m.mu.Unlock() |
| 345 | for _, ch := range done { |
| 346 | <-ch |
| 347 | } |
| 348 | } |