@hit-sudomaker/ccw 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/terminal.js CHANGED
@@ -1,488 +1,228 @@
1
- import { isDeepStrictEqual } from 'node:util';
2
- import { ACTION_NAMES, contentEntries, contentName, contentOrder, contentRows, describeChange, describeDiagnostic, describeItem, describeInspectionProblem, describePreparation, effectiveConnection, entryRows, entrySelected, failureLabel, HOME_TITLE, inspectedItems, MODEL_FIELDS, planVerb, preparationTitle, reason, SETTINGS_FIELDS, SETTINGS_LANGUAGES, SETTINGS_STYLES, } from './render.js';
3
- import { createRunPresentation } from './run-presentation.js';
4
- import { apiConfigurationProblem, kindOf } from './model.js';
5
- import { knownTitle } from './titles.js';
6
- async function chooseWithDetails(terminal, title, choices, details, defaultIndex = choices.length - 1) {
7
- let focus = defaultIndex;
8
- while (true) {
9
- const choice = await terminal.choose(title, [...choices, '查看详情'], focus, choices.length - 1);
10
- if (choice !== choices.length)
11
- return choice;
12
- await terminal.choose(details, ['返回']);
13
- focus = choice;
14
- }
15
- }
16
- async function editSettings(item, editor, terminal, prior) {
17
- const values = { ...item.values, ...prior?.fields };
18
- const fields = { ...prior?.fields };
19
- if (editor !== 'connection') {
20
- const choices = editor === 'language' ? SETTINGS_LANGUAGES : SETTINGS_STYLES;
21
- const current = values[editor] ?? (editor === 'language' ? 'Simplified Chinese' : 'Explanatory');
22
- const index = await terminal.choose(editor === 'language' ? '默认输出语言' : '输出风格', [...choices.map(choice => choice.label), '返回'], Math.max(0, choices.findIndex(choice => choice.value === current)));
23
- const choice = choices[index];
24
- if (choice === undefined)
25
- return null;
26
- fields[editor] = choice.value;
27
- return { id: item.id, fields };
28
- }
29
- const mode = await terminal.choose('模型配置', ['官方登录', '第三方 API', '返回'], effectiveConnection(values, item.facts) === 'api' ? 1 : 0);
30
- if (mode === 2)
31
- return null;
32
- for (const field of SETTINGS_FIELDS.connection)
33
- delete fields[field];
34
- if (mode === 0) {
35
- fields.mode = 'official';
36
- fields.login = 'yes';
37
- }
38
- else {
39
- const api = { mode: 'api', auth: values.auth ?? 'key' };
40
- for (const { key } of MODEL_FIELDS)
41
- if (values[key] !== undefined)
42
- api[key] = values[key];
43
- for (const key of ['baseUrl', 'secret'])
44
- if (prior?.fields?.[key] !== undefined)
45
- api[key] = prior.fields[key];
46
- const edited = await terminal.form('第三方 API', [
47
- { key: 'baseUrl', label: 'Base URL', value: api.baseUrl ?? '', placeholder: '必填' },
48
- { key: 'secret', label: 'API Key', value: api.secret ?? '', secret: true, placeholder: '必填' },
49
- ...MODEL_FIELDS.map(model => ({
50
- key: model.key,
51
- label: model.label,
52
- value: api[model.key] ?? '',
53
- placeholder: '选填,可添加 [1m]',
54
- })),
55
- ], form => {
56
- const problem = apiConfigurationProblem(form.baseUrl, Boolean(form.secret?.trim()));
57
- return problem
58
- ? {
59
- message: reason(problem),
60
- field: problem === 'credential-required' ? 'secret' : 'baseUrl',
61
- detail: describeDiagnostic({ code: problem }),
62
- }
63
- : null;
64
- });
65
- if (edited === null)
66
- return null;
67
- for (const [key, value] of Object.entries(edited)) {
68
- if (key === 'secret') {
69
- if (value.trim()) {
70
- api.secret = value.trim();
71
- api.auth = 'key';
72
- }
73
- }
74
- else if (value.trim() || Object.hasOwn(api, key))
75
- api[key] = value.trim();
76
- }
77
- Object.assign(fields, api);
78
- }
79
- if (values.language === undefined)
80
- fields.language = 'Simplified Chinese';
81
- if (values.outputStyle === undefined)
82
- fields.outputStyle = 'Explanatory';
83
- return { id: item.id, fields };
84
- }
85
- const TASK_ORDER = ['install', 'inspect', 'uninstall', 'clean'];
86
- const TASKS = {
87
- install: { name: '安装套件', actions: ['install', 'connect', 'configure'] },
88
- inspect: { name: '检查套件', actions: [] },
89
- uninstall: { name: '卸载套件', actions: ['uninstall', 'detach'] },
90
- clean: { name: '清理数据', actions: ['clean'] },
1
+ import { errorCode } from './machine.js';
2
+ import { apiConfigurationProblem } from './settings.js';
3
+ import { HOME_TITLE, BACK_TO_HOME, contentRow, contentOrder, describeInspection, describeChange, describePreparation, describeRun, describePlan, MODEL_FIELDS, DEFAULT_PREFERENCES, effectiveConnection, SETTINGS_EDITORS, SETTINGS_LANGUAGES, SETTINGS_STYLES, settingsRow, reason, createRunPresentation, } from './render.js';
4
+ const HOME_ACTIONS = [
5
+ { label: '安装配置', id: 'install' },
6
+ { label: '检查状态', id: 'inspect' },
7
+ { label: '移除程序', id: 'uninstall' },
8
+ { label: '清理数据', id: 'clean' },
9
+ { label: '退出程序', id: 'exit' },
10
+ ];
11
+ const TASK_TEXT = {
12
+ install: { title: '安装配置', empty: '没有可配置项目', confirm: '确认安装' },
13
+ uninstall: {
14
+ title: '移除程序\n保留会话记录和个人文件,移除所选接入配置',
15
+ empty: '没有可移除项目',
16
+ confirm: '确认移除',
17
+ },
18
+ clean: {
19
+ title: '清理数据\n删除所选数据,保留程序、配置与凭据',
20
+ empty: '没有可清理数据',
21
+ confirm: '确认清理',
22
+ },
91
23
  };
92
- function availableActions(item, task) {
93
- if (task === 'install' && item.skillSet)
94
- return [];
95
- if (task === 'install')
96
- return item.canInstall ? [item.kind === 'settings' ? 'configure' : 'install'] : [];
97
- return item.actions
98
- .filter(action => TASKS[task].actions.includes(action))
99
- .sort((a, b) => Number(b === 'uninstall') - Number(a === 'uninstall'));
100
- }
101
- export async function runTerminal(ccw, terminal, signal) {
102
- const focus = { install: 0, inspect: 0, uninstall: 0, clean: 0 };
103
- const knownItems = new Map();
104
- const drafts = {
105
- install: new Map(),
106
- inspect: new Map(),
107
- uninstall: new Map(),
108
- clean: new Map(),
109
- };
110
- const problems = new Map();
111
- let task = 'inspect';
112
- let pending;
113
- let removeClaudeData = false;
114
- const selected = () => drafts[task];
115
- const dataPending = () => task === 'uninstall' && pending?.task === task && pending.removeData === true;
116
- const dataVisible = () => task === 'uninstall' &&
117
- ([...selected().keys()].some(id => knownItems.get(id)?.kind === 'claude' || kindOf(id) === 'claude') ||
118
- dataPending());
119
- const hasSelection = () => selected().size > 0 || dataPending();
120
- const reconcile = () => {
121
- if (task === 'uninstall' && !dataVisible())
122
- removeClaudeData = false;
123
- };
124
- const changeSelection = (edit) => {
125
- const before = [...selected()];
126
- const dataBefore = removeClaudeData;
127
- edit();
128
- if (!isDeepStrictEqual(before, [...selected()]) || dataBefore !== removeClaudeData) {
129
- pending = undefined;
130
- problems.delete('data:claude');
131
- }
132
- reconcile();
133
- };
134
- const select = (id, pick) => {
135
- changeSelection(() => {
136
- if (pick)
137
- selected().set(id, pick);
138
- else
139
- selected().delete(id);
140
- problems.delete(id);
141
- });
142
- };
24
+ /**
25
+ * 驱动主菜单、配置草稿、变更预览和确认后的执行
26
+ *
27
+ * @param signal - 传递给检查、计划准备与执行;取消不会唤醒正在等待输入的菜单或表单
28
+ * @param details - 在检查、预览、执行结果和操作失败说明中附带原因码
29
+ * @remarks 只有用户确认预览后才调用 apply;取消不回滚已执行变更,终端由调用方关闭
30
+ * @throws Error - 未在操作页处理的终端或检查失败会拒绝 Promise
31
+ */
32
+ export async function runTerminal(ccw, terminal, signal, details = false) {
143
33
  while (!signal?.aborted) {
144
- const selectedTask = TASK_ORDER[await terminal.choose(HOME_TITLE, [...TASK_ORDER.map(task => TASKS[task].name), '退出'])];
145
- if (selectedTask === undefined || signal?.aborted)
34
+ const choice = await terminal.choose(HOME_TITLE, HOME_ACTIONS.map(action => action.label), 0, {
35
+ home: true,
36
+ });
37
+ const action = HOME_ACTIONS[choice]?.id;
38
+ if (action === undefined || action === 'exit' || signal?.aborted)
146
39
  return;
147
- task = selectedTask;
148
- reconcile();
149
- let returnToMenu = false;
150
- let view = null;
151
- problems.clear();
152
- while (!returnToMenu && !signal?.aborted) {
153
- if (view === null) {
154
- view = await terminal.wait(`${TASKS[task].name} · 检查环境`, reading => ccw.inspect(task === 'clean' ? 'data' : 'contents', reading), signal);
155
- if (view === null || signal?.aborted)
156
- break;
157
- for (const item of view.items)
158
- knownItems.set(item.id, item);
159
- }
160
- const ordered = contentOrder(task === 'inspect' ? inspectedItems(view.items) : view.items);
161
- if (task === 'inspect') {
162
- const choices = [...contentRows(ordered), '刷新检查', '返回主菜单'];
163
- const index = await terminal.choose(`检查套件 · 当前用户${view.problems.length ? '\n! 待确认' : ''}`, view.problems.length ? [...choices, '查看详情'] : choices, focus.inspect, ordered.length + 1);
164
- focus.inspect = index;
165
- if (view.problems.length && index === choices.length) {
166
- await terminal.choose(`检查详情\n${view.problems.map(describeInspectionProblem).join('\n')}`, ['返回']);
167
- continue;
168
- }
169
- if (index === ordered.length) {
170
- view = null;
171
- continue;
172
- }
173
- const item = ordered[index];
174
- if (item === undefined)
175
- break;
176
- const installTarget = item.kind === 'skill' || item.kind === 'command' ? undefined : item;
177
- const routes = [
178
- ...(installTarget && availableActions(installTarget, 'install').length
179
- ? [{ label: '进入安装', task: 'install', item: installTarget }]
180
- : []),
181
- ...(availableActions(item, 'uninstall').length
182
- ? [{ label: '进入卸载', task: 'uninstall', item }]
183
- : []),
184
- ];
185
- const route = routes[await chooseWithDetails(terminal, describeItem(item), [...routes.map(route => route.label), '返回'], describeItem(item, true), routes.length)];
186
- if (!route)
187
- continue;
188
- task = route.task;
189
- reconcile();
190
- const target = route.item;
191
- const selection = target.kind === 'settings' && task === 'install'
192
- ? await editSettings(target, 'connection', terminal, selected().get(target.id))
193
- : {
194
- id: target.id,
195
- ...(task === 'uninstall' && !target.actions.includes('uninstall')
196
- ? { removal: 'detach' }
197
- : {}),
198
- };
199
- if (selection && (target.kind === 'settings' || !selected().has(target.id)))
200
- select(target.id, selection);
201
- continue;
202
- }
203
- const taskAction = task;
204
- const items = ordered.filter(item => availableActions(item, task).length > 0);
205
- const remaining = pending?.task === task ? pending : undefined;
206
- const missing = new Set([...selected().keys()].filter(id => !remaining && !items.some(item => item.id === id)));
207
- if (remaining)
208
- for (const id of selected().keys()) {
209
- const item = knownItems.get(id);
210
- if (item && !items.some(value => value.id === id))
211
- items.push(item);
212
- }
213
- for (const id of missing) {
214
- const item = knownItems.get(id);
215
- if (item)
216
- items.push(item);
217
- problems.set(id, 'selected-item-unavailable');
218
- }
219
- const entries = contentEntries(items, task === 'install');
220
- const notices = [];
221
- if (task === 'uninstall') {
222
- notices.push('默认保留用户配置与数据');
223
- if (!items.length && !hasSelection())
224
- notices.push('无可卸载项');
225
- }
226
- if (task === 'clean') {
227
- notices.push('保留程序、配置与凭据');
228
- if (!items.length)
229
- notices.push('无可清理数据');
230
- }
231
- if (problems.size)
232
- notices.push('! ' + failureLabel(task));
233
- if (view.problems.length)
234
- notices.push('! 待确认');
235
- const title = [TASKS[task].name + ' · 当前用户', ...notices].join('\n');
236
- const page = () => {
237
- const labels = entryRows(entries, selected());
238
- const showData = dataVisible();
239
- const dataProblem = problems.get('data:claude');
240
- const rows = entries.map((entry, index) => {
241
- const problem = problems.get(entry.item.id);
242
- const editable = task === 'install' && entry.editor !== undefined;
243
- const removal = task === 'uninstall' && entry.item.actions.includes('uninstall')
244
- ? selected().get(entry.item.id)?.removal === 'detach'
245
- ? '仅解除接入'
246
- : '卸载程序'
247
- : '';
40
+ const inspection = await terminal.wait('检查状态', reading => ccw.inspect(reading, action === 'clean' ? 'data' : 'contents'), signal);
41
+ if (!inspection || signal?.aborted)
42
+ continue;
43
+ if (action === 'inspect') {
44
+ await terminal.choose('检查状态\n' + describeInspection(inspection, details), [BACK_TO_HOME]);
45
+ continue;
46
+ }
47
+ const task = action;
48
+ const text = TASK_TEXT[task];
49
+ const items = contentOrder(inspection.items).filter(item => task === 'install'
50
+ ? item.canInstall === true
51
+ : task === 'clean'
52
+ ? item.canClean === true
53
+ : !item.skillSet && item.canUninstall === true);
54
+ const unavailable = {
55
+ items: inspection.items.filter(item => item.problem && !items.includes(item)),
56
+ problems: inspection.problems,
57
+ };
58
+ const inspectionNotice = unavailable.items.length || unavailable.problems.length
59
+ ? '\n以下项目检查未完成或暂不可操作\n' + describeInspection(unavailable, details)
60
+ : '';
61
+ if (!items.length) {
62
+ await terminal.choose(inspectionNotice || text.empty, [BACK_TO_HOME]);
63
+ continue;
64
+ }
65
+ const entries = items.flatMap(item => task === 'install' && item.kind === 'settings'
66
+ ? SETTINGS_EDITORS.map(editor => ({ item, editor, key: item.id + '/' + editor }))
67
+ : [{ item, key: item.id }]);
68
+ const selected = new Map();
69
+ const drafts = new Map();
70
+ const remember = (key, pick) => {
71
+ drafts.set(key, pick);
72
+ selected.set(key, pick);
73
+ };
74
+ let focus = 0;
75
+ let finished = false;
76
+ while (!finished && !signal?.aborted) {
77
+ const page = () => ({
78
+ title: text.title + inspectionNotice,
79
+ submitLabel: '查看变更 · ' + selected.size + ' 项',
80
+ focus,
81
+ rows: entries.map(entry => {
82
+ const draft = drafts.get(entry.key);
83
+ const row = entry.editor ? settingsRow(entry.item, entry.editor, draft?.fields) : contentRow(entry.item);
248
84
  return {
249
- ...labels[index],
250
- label: labels[index]?.label ?? '',
251
- detail: [problem ? failureLabel(taskAction) : labels[index]?.detail, removal].filter(Boolean).join(' · '),
252
- checked: entrySelected(entry, selected()),
253
- enter: problem
254
- ? 'open'
255
- : editable
256
- ? 'edit'
257
- : task === 'install' || availableActions(entry.item, task).length === 1
258
- ? 'toggle'
259
- : 'open',
85
+ ...row,
86
+ checked: selected.has(entry.key),
87
+ editable: entry.editor !== undefined,
260
88
  };
261
- });
262
- if (showData) {
263
- rows.push({
264
- label: `删除 ${knownTitle('data:claude')}(不可恢复)`,
265
- ...(dataProblem ? { detail: failureLabel(taskAction) } : {}),
266
- group: '运行数据',
267
- checked: removeClaudeData,
268
- enter: dataProblem ? 'open' : 'toggle',
269
- });
270
- }
271
- const selectedCount = selected().size + Number(showData && removeClaudeData);
272
- const dataDescription = showData
273
- ? '\n删除范围:配置、登录状态、会话、Skills 和目录内工具\n删除位置:.claude / .claude.json(以预览路径为准)'
274
- : '';
275
- return {
276
- title: title + dataDescription,
277
- submitLabel: task === 'install' ? `开始安装(${selectedCount} 项)` : `预览 ${selectedCount} 项变更`,
278
- rows,
279
- };
280
- };
89
+ }),
90
+ });
281
91
  const response = await terminal.select(page(), event => {
282
- changeSelection(() => {
283
- if (event.kind === 'toggle' && event.index === entries.length && dataVisible()) {
284
- removeClaudeData = !removeClaudeData;
285
- return;
286
- }
287
- const targets = event.kind === 'all'
288
- ? entries.filter(entry => entry.editor === undefined && !missing.has(entry.item.id))
289
- : entries.filter((_entry, index) => index === event.index);
290
- const shouldSelect = event.kind === 'all' && targets.some(entry => !entrySelected(entry, selected()));
291
- for (const entry of targets) {
292
- const prior = selected().get(entry.item.id);
293
- if (event.kind === 'all' ? !shouldSelect : entrySelected(entry, selected())) {
294
- const fields = { ...prior?.fields };
295
- if (entry.editor)
296
- for (const field of SETTINGS_FIELDS[entry.editor])
297
- delete fields[field];
298
- if (entry.editor && Object.keys(fields).length)
299
- selected().set(entry.item.id, { ...prior, id: entry.item.id, fields });
300
- else
301
- selected().delete(entry.item.id);
302
- }
303
- else if (!prior && entry.editor === undefined && !missing.has(entry.item.id)) {
304
- selected().set(entry.item.id, {
305
- id: entry.item.id,
306
- ...(task === 'uninstall' && !entry.item.actions.includes('uninstall')
307
- ? { removal: 'detach' }
308
- : {}),
309
- });
310
- }
311
- if (!missing.has(entry.item.id) || !selected().has(entry.item.id))
312
- problems.delete(entry.item.id);
313
- }
314
- });
92
+ const targets = (event.kind === 'all' ? entries : [entries[event.index]]).filter(entry => entry !== undefined);
93
+ const selectAll = event.kind === 'all' && targets.some(entry => !selected.has(entry.key));
94
+ for (const entry of targets) {
95
+ if (event.kind === 'all' ? selectAll : !selected.has(entry.key))
96
+ selected.set(entry.key, drafts.get(entry.key) ?? { id: entry.item.id });
97
+ else
98
+ selected.delete(entry.key);
99
+ }
315
100
  return page();
316
- }, focus[task]);
317
- focus[task] = response.index;
318
- if (response.kind === 'cancel') {
319
- returnToMenu = true;
101
+ });
102
+ if (response === 'cancel')
103
+ break;
104
+ if (typeof response === 'object') {
105
+ focus = response.index;
106
+ const entry = entries[response.index];
107
+ if (entry?.editor) {
108
+ const pick = await configure(entry.item, entry.editor, terminal, drafts.get(entry.key));
109
+ if (pick)
110
+ remember(entry.key, pick);
111
+ }
320
112
  continue;
321
113
  }
322
- if (response.kind === 'refresh') {
323
- view = null;
324
- problems.clear();
114
+ if (!selected.size)
325
115
  continue;
326
- }
327
- if (response.kind === 'open') {
328
- const entry = entries[response.index];
329
- if (entry === undefined) {
330
- const dataProblem = problems.get('data:claude');
331
- if (response.index === entries.length && dataVisible() && dataProblem) {
332
- const choice = await chooseWithDetails(terminal, `${knownTitle('data:claude')}\n${failureLabel(task)}`, ['取消选择', '返回'], `${knownTitle('data:claude')}\n${describeDiagnostic({ code: dataProblem })}`);
333
- if (choice === 0)
334
- changeSelection(() => {
335
- removeClaudeData = false;
336
- problems.delete('data:claude');
337
- });
116
+ if (task === 'install') {
117
+ let cancelled = false;
118
+ for (const entry of entries.filter(entry => selected.has(entry.key))) {
119
+ const { item, key, editor } = entry;
120
+ if (editor && !selected.get(key)?.fields) {
121
+ const pick = savedSelection(item, editor) ?? (await configure(item, editor, terminal, drafts.get(key)));
122
+ if (!pick) {
123
+ cancelled = true;
124
+ break;
125
+ }
126
+ remember(key, pick);
338
127
  }
339
- continue;
340
128
  }
341
- const item = entry.item;
342
- const problem = problems.get(item.id);
343
- const brief = problem ? `${contentName(item)}\n${failureLabel(task)}` : describeItem(item);
344
- const details = [
345
- describeItem(item, true),
346
- ...(problem && problem !== item.problem ? [describeDiagnostic({ code: problem })] : []),
347
- ...view.problems.map(describeInspectionProblem),
348
- ].join('\n');
349
- if (task === 'install' && problems.get(item.id) === 'local-edits-preserved') {
350
- const choice = await chooseWithDetails(terminal, brief, ['备份并替换', '取消选择', '返回'], details, 2);
351
- const prior = selected().get(item.id);
352
- if (choice === 0 && prior)
353
- select(item.id, { ...prior, fields: { ...prior.fields, replace: 'yes' } });
354
- if (choice === 1)
355
- select(item.id);
356
- continue;
357
- }
358
- if (entry.editor !== undefined) {
359
- if (problem) {
360
- const choice = await chooseWithDetails(terminal, brief, ['编辑配置', '取消选择', '返回'], details);
361
- if (choice === 1)
362
- select(item.id);
363
- if (choice !== 0)
364
- continue;
365
- }
366
- const selection = await editSettings(item, entry.editor, terminal, selected().get(item.id));
367
- if (selection) {
368
- select(item.id, selection);
369
- }
129
+ if (cancelled)
370
130
  continue;
371
- }
372
- const actions = task === 'install' ? [] : availableActions(item, task);
373
- const choice = await chooseWithDetails(terminal, brief, [...actions.map(action => ACTION_NAMES[action]), '取消选择', '返回'], details, actions.length + 1);
374
- if (choice === actions.length) {
375
- select(item.id);
376
- }
377
- const action = actions[choice];
378
- if (action !== undefined) {
379
- select(item.id, {
380
- id: item.id,
381
- ...(action === 'detach' ? { removal: 'detach' } : {}),
382
- });
383
- }
384
- continue;
385
131
  }
386
- if (!hasSelection())
387
- continue;
388
- if ([...missing].some(id => selected().has(id))) {
389
- focus[task] = Math.max(0, entries.findIndex(entry => missing.has(entry.item.id) && selected().has(entry.item.id)));
390
- continue;
391
- }
392
- const saved = pending?.task === task ? pending : undefined;
393
- const picks = [...selected().values()];
394
- const request = saved?.remaining
395
- ? { resume: saved.remaining }
396
- : task === 'uninstall'
397
- ? { task, selected: picks, ...(removeClaudeData ? { removeData: true } : {}) }
398
- : { task, selected: picks };
399
- const preparationTask = task;
400
- const preparation = preparationTitle(task);
401
- let preparing;
402
- const plan = saved?.plan ??
403
- (saved?.remaining
404
- ? await ccw.plan(request, signal)
405
- : await terminal.wait(preparation, (reading, update) => {
406
- preparing = ccw.plan(request, reading, event => update?.(describePreparation(event, preparationTask)));
407
- return preparing;
408
- }, signal, preparation));
409
- if (plan === null) {
410
- await preparing?.catch(() => undefined);
411
- pending = undefined;
412
- continue;
413
- }
414
- if (signal?.aborted)
415
- return;
416
- pending = undefined;
417
- problems.clear();
418
- for (const item of plan.items)
419
- if (item.problem !== null)
420
- problems.set(item.id, item.problem);
421
- if (plan.problem === null && problems.size === 0)
422
- pending = { task, plan, ...(task === 'uninstall' && removeClaudeData ? { removeData: true } : {}) };
423
- if (plan.problem !== null) {
424
- await chooseWithDetails(terminal, failureLabel(task), ['返回'], describeDiagnostic({ code: plan.problem }));
425
- continue;
426
- }
427
- if (problems.size) {
428
- const problemIndex = entries.findIndex(entry => problems.has(entry.item.id));
429
- focus[task] = Math.max(0, problemIndex >= 0 ? problemIndex : removeClaudeData && problems.has('data:claude') ? entries.length : 0);
430
- continue;
431
- }
432
- if (task !== 'install') {
433
- const preview = plan.items
434
- .map(item => `${planVerb(item)} ${contentName(item)}\n${item.problem ? ` ! ${reason(item.problem)}` : item.changes.map(change => ` · ${describeChange(change)}`).join('\n')}`)
435
- .join('\n');
436
- const confirm = await terminal.choose(`变更预览\n${preview}`, [task === 'clean' ? '确认清理' : '确认卸载', '返回修改'], 1);
437
- if (confirm !== 0)
132
+ try {
133
+ const plan = await terminal.wait('准备变更', (reading, update) => ccw.plan({ task, selected: mergeSelections(selected.values()) }, reading, event => update?.(describePreparation(event))), signal);
134
+ if (!plan)
438
135
  continue;
439
- }
440
- const presentation = createRunPresentation(plan, taskAction);
441
- terminal.show(presentation.progress());
442
- const result = await ccw.apply(plan.id, signal, event => {
443
- terminal.show(presentation.progress(event));
444
- });
445
- view = null;
446
- for (const item of result.items) {
447
- if (item.state !== 'done' && item.isPending !== false)
136
+ const blocked = !!plan.problem || plan.items.every(item => item.problem !== null);
137
+ const confirm = await terminal.choose('变更预览\n' + describePlan(plan, details), blocked ? ['返回修改'] : [text.confirm, '返回修改'], blocked ? 0 : 1);
138
+ if (blocked || confirm !== 0)
448
139
  continue;
449
- if (item.id === 'data:claude')
450
- removeClaudeData = false;
451
- else
452
- selected().delete(item.id);
140
+ const presentation = createRunPresentation(plan, task, details);
141
+ terminal.show(presentation.progress());
142
+ const result = await ccw.apply(plan.id, signal, event => terminal.show(presentation.progress(event)));
143
+ await terminal.choose(describeRun(presentation.result(result)), [BACK_TO_HOME]);
144
+ finished = true;
453
145
  }
454
- const dataRemaining = removeClaudeData && result.items.some(item => item.id === 'data:claude' && item.isPending === true);
455
- pending = result.remaining
456
- ? { task, remaining: result.remaining, ...(dataRemaining ? { removeData: true } : {}) }
457
- : undefined;
458
- reconcile();
459
- const resultView = presentation.result(result);
460
- let resultFocus = 1;
461
- let detailFocus = 0;
462
- while (!signal?.aborted) {
463
- const next = await terminal.choose(resultView, [hasSelection() && result.remaining ? '重试未完成项' : '返回列表', '返回主菜单', '查看详情'], resultFocus, 1);
464
- if (next !== 2) {
465
- if (next === 1)
466
- returnToMenu = true;
467
- break;
468
- }
469
- resultFocus = next;
470
- let item = result.items[0];
471
- if (result.items.length > 1) {
472
- detailFocus = await terminal.choose('选择结果', [
473
- ...result.items.map(item => ({
474
- label: resultView.rows.find(row => row.id === item.id)?.title ?? contentName(item),
475
- detail: resultView.rows.find(row => row.id === item.id)?.status ?? '',
476
- })),
477
- '返回',
478
- ], Math.min(detailFocus, result.items.length - 1));
479
- item = result.items[detailFocus];
480
- }
481
- if (item)
482
- await terminal.choose(presentation.details(result, item.id), ['返回']);
483
- else if (!result.items.length)
484
- await terminal.choose('结果详情\n本次没有条目记录', ['返回']);
146
+ catch (error) {
147
+ if (signal?.aborted)
148
+ return;
149
+ await terminal.choose('操作失败:' + describeChange({ code: errorCode(error) }, details), ['返回修改']);
485
150
  }
486
151
  }
487
152
  }
488
153
  }
154
+ function savedSelection(item, editor) {
155
+ const values = item.values ?? {};
156
+ if (item.problem)
157
+ return;
158
+ if (editor !== 'connection')
159
+ return { id: item.id, fields: { [editor]: values[editor] ?? DEFAULT_PREFERENCES[editor] } };
160
+ if (values.mode === 'official' ||
161
+ (effectiveConnection(values, item.facts) === 'api' &&
162
+ apiConfigurationProblem(values.baseUrl, item.hasCredential === true) === null))
163
+ return { id: item.id, fields: {} };
164
+ }
165
+ async function configure(item, editor, terminal, prior) {
166
+ const values = { ...item.values, ...prior?.fields };
167
+ if (editor !== 'connection') {
168
+ const choices = editor === 'language' ? SETTINGS_LANGUAGES : SETTINGS_STYLES;
169
+ const current = values[editor] ?? DEFAULT_PREFERENCES[editor];
170
+ const index = await terminal.choose(editor === 'language' ? '默认语言' : '输出风格', [...choices.map(choice => choice.label), '返回'], Math.max(0, choices.findIndex(choice => choice.value === current)));
171
+ const choice = choices[index];
172
+ return choice ? { id: item.id, fields: { [editor]: choice.value } } : null;
173
+ }
174
+ const mode = await terminal.choose('模型配置', ['官方登录', '第三方 API', '返回'], effectiveConnection(values, item.facts) === 'api' ? 1 : 0);
175
+ if (mode === 2)
176
+ return null;
177
+ if (mode === 0)
178
+ return {
179
+ id: item.id,
180
+ fields: {
181
+ mode: 'official',
182
+ login: 'yes',
183
+ },
184
+ };
185
+ const kept = item.hasCredential === true;
186
+ const fields = await terminal.form('第三方 API', [
187
+ { key: 'baseUrl', label: 'Base URL', value: values.baseUrl ?? '' },
188
+ {
189
+ key: 'secret',
190
+ label: 'API Key',
191
+ value: prior?.fields?.secret ?? '',
192
+ secret: true,
193
+ placeholder: kept ? '留空保留现有凭据' : '必填',
194
+ },
195
+ ...MODEL_FIELDS.map(field => ({
196
+ key: field.key,
197
+ label: field.label,
198
+ value: values[field.key] ?? '',
199
+ placeholder: '选填',
200
+ })),
201
+ ], value => {
202
+ const problem = apiConfigurationProblem(value.baseUrl, !!value.secret?.trim() || kept);
203
+ return problem
204
+ ? { message: reason(problem), field: problem === 'credential-required' ? 'secret' : 'baseUrl' }
205
+ : null;
206
+ });
207
+ return fields
208
+ ? {
209
+ id: item.id,
210
+ fields: {
211
+ ...fields,
212
+ mode: 'api',
213
+ auth: fields.secret?.trim() ? 'key' : (values.auth ?? 'key'),
214
+ },
215
+ }
216
+ : null;
217
+ }
218
+ function mergeSelections(selections) {
219
+ const merged = new Map();
220
+ for (const selection of selections) {
221
+ const prior = merged.get(selection.id);
222
+ merged.set(selection.id, {
223
+ id: selection.id,
224
+ ...(prior?.fields || selection.fields ? { fields: { ...prior?.fields, ...selection.fields } } : {}),
225
+ });
226
+ }
227
+ return [...merged.values()];
228
+ }