cc-switch-tui 0.1.3

All-in-One Assistant for Claude Code, Codex, Gemini, OpenCode, OpenClaw & Hermes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::HashMap;

use crate::app_config::AppType;
use crate::config::write_text_file;
use crate::error::AppError;
use crate::prompt::Prompt;
use crate::prompt_files::prompt_file_path;
use crate::store::AppState;

pub struct PromptService;

impl PromptService {
    pub fn generate_prompt_id(name: &str, existing_ids: &[String]) -> String {
        let mut base_id = name
            .trim()
            .to_lowercase()
            .chars()
            .map(|c| {
                if c.is_alphanumeric() || c == '-' || c == '_' {
                    c
                } else {
                    '-'
                }
            })
            .collect::<String>()
            .trim_matches('-')
            .to_string();

        if base_id.is_empty() {
            base_id = "prompt".to_string();
        }

        if !existing_ids.contains(&base_id) {
            return base_id;
        }

        let mut counter = 1;
        loop {
            let candidate = format!("{base_id}-{counter}");
            if !existing_ids.contains(&candidate) {
                return candidate;
            }
            counter += 1;
        }
    }

    pub fn get_prompts(
        state: &AppState,
        app: AppType,
    ) -> Result<HashMap<String, Prompt>, AppError> {
        let cfg = state.config.read()?;
        let prompts = match app {
            AppType::Claude => &cfg.prompts.claude.prompts,
            AppType::Codex => &cfg.prompts.codex.prompts,
            AppType::Gemini => &cfg.prompts.gemini.prompts,
            AppType::OpenCode => &cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &cfg.prompts.openclaw.prompts,
            AppType::Hermes => &cfg.prompts.hermes.prompts,
        };
        Ok(prompts.clone())
    }

    pub fn upsert_prompt(
        state: &AppState,
        app: AppType,
        id: &str,
        prompt: Prompt,
    ) -> Result<(), AppError> {
        // 检查是否为已启用的提示词
        let is_enabled = prompt.enabled;

        let mut cfg = state.config.write()?;
        let prompts = match app {
            AppType::Claude => &mut cfg.prompts.claude.prompts,
            AppType::Codex => &mut cfg.prompts.codex.prompts,
            AppType::Gemini => &mut cfg.prompts.gemini.prompts,
            AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
            AppType::Hermes => &mut cfg.prompts.hermes.prompts,
        };
        prompts.insert(id.to_string(), prompt.clone());
        drop(cfg);
        state.save()?;

        // 如果是已启用的提示词,同步更新到对应的文件
        if is_enabled {
            let target_path = prompt_file_path(&app)?;
            write_text_file(&target_path, &prompt.content)?;
        }

        Ok(())
    }

    pub fn delete_prompt(state: &AppState, app: AppType, id: &str) -> Result<(), AppError> {
        let mut cfg = state.config.write()?;
        let prompts = match app {
            AppType::Claude => &mut cfg.prompts.claude.prompts,
            AppType::Codex => &mut cfg.prompts.codex.prompts,
            AppType::Gemini => &mut cfg.prompts.gemini.prompts,
            AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
            AppType::Hermes => &mut cfg.prompts.hermes.prompts,
        };

        if let Some(prompt) = prompts.get(id) {
            if prompt.enabled {
                return Err(AppError::InvalidInput("无法删除已启用的提示词".to_string()));
            }
        }

        prompts.remove(id);
        drop(cfg);
        state.save()?;
        Ok(())
    }

    pub fn rename_prompt(
        state: &AppState,
        app: AppType,
        id: &str,
        name: &str,
    ) -> Result<(), AppError> {
        let trimmed = name.trim();
        if trimmed.is_empty() {
            return Err(AppError::InvalidInput("提示词名称不能为空".to_string()));
        }

        let mut cfg = state.config.write()?;
        let prompts = match app {
            AppType::Claude => &mut cfg.prompts.claude.prompts,
            AppType::Codex => &mut cfg.prompts.codex.prompts,
            AppType::Gemini => &mut cfg.prompts.gemini.prompts,
            AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
            AppType::Hermes => &mut cfg.prompts.hermes.prompts,
        };

        let Some(prompt) = prompts.get_mut(id) else {
            return Err(AppError::InvalidInput(format!("提示词 {id} 不存在")));
        };

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;
        prompt.name = trimmed.to_string();
        prompt.updated_at = Some(timestamp);

        drop(cfg);
        state.save()?;
        Ok(())
    }

    pub fn create_prompt(
        state: &AppState,
        app: AppType,
        name: &str,
        content: &str,
    ) -> Result<Prompt, AppError> {
        let trimmed_name = name.trim();
        if trimmed_name.is_empty() {
            return Err(AppError::InvalidInput("提示词名称不能为空".to_string()));
        }

        let existing_ids = Self::get_prompts(state, app.clone())?
            .into_keys()
            .collect::<Vec<_>>();
        let id = Self::generate_prompt_id(trimmed_name, &existing_ids);
        if id.trim().is_empty() {
            return Err(AppError::InvalidInput(
                "无法根据提示词名称生成有效 ID".to_string(),
            ));
        }

        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or_default()
            .as_secs() as i64;
        let prompt = Prompt {
            id: id.clone(),
            name: trimmed_name.to_string(),
            content: content.trim_end().to_string(),
            description: None,
            enabled: false,
            created_at: Some(timestamp),
            updated_at: Some(timestamp),
        };

        Self::upsert_prompt(state, app, &id, prompt.clone())?;
        Ok(prompt)
    }

    pub fn enable_prompt(state: &AppState, app: AppType, id: &str) -> Result<(), AppError> {
        // 回填当前 live 文件内容到已启用的提示词,或创建备份
        let target_path = prompt_file_path(&app)?;
        if target_path.exists() {
            if let Ok(live_content) = std::fs::read_to_string(&target_path) {
                if !live_content.trim().is_empty() {
                    let mut cfg = state.config.write()?;
                    let prompts = match app {
                        AppType::Claude => &mut cfg.prompts.claude.prompts,
                        AppType::Codex => &mut cfg.prompts.codex.prompts,
                        AppType::Gemini => &mut cfg.prompts.gemini.prompts,
                        AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
                        AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
                        AppType::Hermes => &mut cfg.prompts.hermes.prompts,
                    };

                    // 尝试回填到当前已启用的提示词
                    if let Some((enabled_id, enabled_prompt)) = prompts
                        .iter_mut()
                        .find(|(_, p)| p.enabled)
                        .map(|(id, p)| (id.clone(), p))
                    {
                        let timestamp = std::time::SystemTime::now()
                            .duration_since(std::time::UNIX_EPOCH)
                            .unwrap()
                            .as_secs() as i64;
                        enabled_prompt.content = live_content.clone();
                        enabled_prompt.updated_at = Some(timestamp);
                        log::info!("回填 live 提示词内容到已启用项: {enabled_id}");
                        drop(cfg); // 释放锁后保存,避免死锁
                        state.save()?; // 第一次保存:回填后立即持久化
                    } else {
                        // 没有已启用的提示词,则创建一次备份(避免重复备份)
                        let content_exists = prompts
                            .values()
                            .any(|p| p.content.trim() == live_content.trim());
                        if !content_exists {
                            let timestamp = std::time::SystemTime::now()
                                .duration_since(std::time::UNIX_EPOCH)
                                .unwrap()
                                .as_secs() as i64;
                            let backup_id = format!("backup-{timestamp}");
                            let backup_prompt = Prompt {
                                id: backup_id.clone(),
                                name: format!(
                                    "原始提示词 {}",
                                    chrono::Local::now().format("%Y-%m-%d %H:%M")
                                ),
                                content: live_content,
                                description: Some("自动备份的原始提示词".to_string()),
                                enabled: false,
                                created_at: Some(timestamp),
                                updated_at: Some(timestamp),
                            };
                            prompts.insert(backup_id.clone(), backup_prompt);
                            log::info!("回填 live 提示词内容,创建备份: {backup_id}");
                            drop(cfg); // 释放锁后保存
                            state.save()?; // 第一次保存:回填后立即持久化
                        } else {
                            // 即使内容已存在,也无需重复备份;但不需要保存任何更改
                            drop(cfg);
                        }
                    }
                }
            }
        }

        // 启用目标提示词并写入文件
        let mut cfg = state.config.write()?;
        let prompts = match app {
            AppType::Claude => &mut cfg.prompts.claude.prompts,
            AppType::Codex => &mut cfg.prompts.codex.prompts,
            AppType::Gemini => &mut cfg.prompts.gemini.prompts,
            AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
            AppType::Hermes => &mut cfg.prompts.hermes.prompts,
        };

        for prompt in prompts.values_mut() {
            prompt.enabled = false;
        }

        if let Some(prompt) = prompts.get_mut(id) {
            prompt.enabled = true;
            write_text_file(&target_path, &prompt.content)?; // 原子写入
        } else {
            return Err(AppError::InvalidInput(format!("提示词 {id} 不存在")));
        }

        drop(cfg);
        state.save()?; // 第二次保存:启用目标提示词并写入文件后
        Ok(())
    }

    pub fn disable_prompt(state: &AppState, app: AppType, id: &str) -> Result<(), AppError> {
        let mut cfg = state.config.write()?;
        let prompts = match app {
            AppType::Claude => &mut cfg.prompts.claude.prompts,
            AppType::Codex => &mut cfg.prompts.codex.prompts,
            AppType::Gemini => &mut cfg.prompts.gemini.prompts,
            AppType::OpenCode => &mut cfg.prompts.opencode.prompts,
            AppType::OpenClaw => &mut cfg.prompts.openclaw.prompts,
            AppType::Hermes => &mut cfg.prompts.hermes.prompts,
        };

        // 验证提示词是否存在且已启用
        if let Some(prompt) = prompts.get_mut(id) {
            if !prompt.enabled {
                return Err(AppError::InvalidInput(format!("提示词 {} 未激活", id)));
            }
            prompt.enabled = false;
        } else {
            return Err(AppError::InvalidInput(format!("提示词 {} 不存在", id)));
        }

        drop(cfg);
        state.save()?;

        // 清空对应的实时文件
        let target_path = prompt_file_path(&app)?;
        write_text_file(&target_path, "")?;

        Ok(())
    }

    pub fn import_from_file(state: &AppState, app: AppType) -> Result<String, AppError> {
        let file_path = prompt_file_path(&app)?;

        if !file_path.exists() {
            return Err(AppError::Message("提示词文件不存在".to_string()));
        }

        let content =
            std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
        let timestamp = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        let id = format!("imported-{timestamp}");
        let prompt = Prompt {
            id: id.clone(),
            name: format!(
                "导入的提示词 {}",
                chrono::Local::now().format("%Y-%m-%d %H:%M")
            ),
            content,
            description: Some("从现有配置文件导入".to_string()),
            enabled: false,
            created_at: Some(timestamp),
            updated_at: Some(timestamp),
        };

        Self::upsert_prompt(state, app, &id, prompt)?;
        Ok(id)
    }

    pub fn get_current_file_content(app: AppType) -> Result<Option<String>, AppError> {
        let file_path = prompt_file_path(&app)?;
        if !file_path.exists() {
            return Ok(None);
        }
        let content =
            std::fs::read_to_string(&file_path).map_err(|e| AppError::io(&file_path, e))?;
        Ok(Some(content))
    }

    pub fn sync_all_active_to_live_best_effort(state: &AppState) -> Result<(), AppError> {
        let active_prompts = {
            let cfg = state.config.read()?;
            let mut result = Vec::new();

            for app in AppType::all() {
                let prompts = match app {
                    AppType::Claude => &cfg.prompts.claude.prompts,
                    AppType::Codex => &cfg.prompts.codex.prompts,
                    AppType::Gemini => &cfg.prompts.gemini.prompts,
                    AppType::OpenCode => &cfg.prompts.opencode.prompts,
                    AppType::OpenClaw => &cfg.prompts.openclaw.prompts,
                    AppType::Hermes => &cfg.prompts.hermes.prompts,
                };

                if let Some(prompt) = select_active_prompt(prompts) {
                    result.push((app, prompt.content));
                }
            }

            result
        };

        for (app, content) in active_prompts {
            if !crate::sync_policy::should_sync_live(&app) {
                continue;
            }

            let target_path = match prompt_file_path(&app) {
                Ok(path) => path,
                Err(err) => {
                    log::warn!("同步 {app} 提示词 live 文件时解析路径失败: {err}");
                    continue;
                }
            };

            if let Err(err) = write_text_file(&target_path, &content) {
                log::warn!("同步 {app} 提示词到 live 文件失败: {err}");
            }
        }

        Ok(())
    }
}

fn select_active_prompt(prompts: &HashMap<String, Prompt>) -> Option<Prompt> {
    prompts
        .values()
        .filter(|prompt| prompt.enabled)
        .max_by_key(|prompt| {
            (
                prompt.updated_at.unwrap_or(prompt.created_at.unwrap_or(0)),
                prompt.created_at.unwrap_or(0),
                prompt.id.clone(),
            )
        })
        .cloned()
}