codexmate 0.0.30 → 0.0.32

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.
Files changed (144) hide show
  1. package/README.md +363 -421
  2. package/README.zh.md +371 -354
  3. package/cli/agents-files.js +224 -224
  4. package/cli/archive-helpers.js +446 -446
  5. package/cli/auth-profiles.js +375 -375
  6. package/cli/builtin-proxy.js +1725 -1725
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +402 -402
  9. package/cli/config-health.js +454 -454
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/local-bridge.js +324 -324
  13. package/cli/openai-bridge.js +1653 -1653
  14. package/cli/openclaw-config.js +629 -629
  15. package/cli/session-convert-args.js +69 -65
  16. package/cli/session-convert-io.js +82 -82
  17. package/cli/session-convert.js +150 -43
  18. package/cli/session-usage.concurrent.js +28 -28
  19. package/cli/session-usage.js +118 -118
  20. package/cli/session-usage.models.js +176 -176
  21. package/cli/skills.js +1141 -1141
  22. package/cli/zip-commands.js +510 -510
  23. package/cli.js +15829 -15481
  24. package/lib/automation.js +404 -404
  25. package/lib/cli-file-utils.js +151 -151
  26. package/lib/cli-models-utils.js +440 -440
  27. package/lib/cli-network-utils.js +190 -190
  28. package/lib/cli-path-utils.js +85 -85
  29. package/lib/cli-session-utils.js +121 -121
  30. package/lib/cli-sessions.js +426 -417
  31. package/lib/cli-utils.js +155 -155
  32. package/lib/cli-webhook.js +126 -126
  33. package/lib/download-artifacts.js +92 -92
  34. package/lib/mcp-stdio.js +453 -453
  35. package/lib/task-orchestrator.js +869 -869
  36. package/lib/text-diff.js +303 -303
  37. package/lib/workflow-engine.js +340 -340
  38. package/package.json +76 -76
  39. package/plugins/README.md +20 -20
  40. package/plugins/README.zh-CN.md +20 -20
  41. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  42. package/plugins/prompt-templates/computed.mjs +253 -253
  43. package/plugins/prompt-templates/index.mjs +8 -8
  44. package/plugins/prompt-templates/manifest.mjs +15 -15
  45. package/plugins/prompt-templates/methods.mjs +553 -553
  46. package/plugins/prompt-templates/overview.mjs +91 -91
  47. package/plugins/prompt-templates/ownership.mjs +19 -19
  48. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  49. package/plugins/prompt-templates/storage.mjs +64 -64
  50. package/plugins/registry.mjs +16 -16
  51. package/web-ui/app.js +647 -645
  52. package/web-ui/index.html +36 -36
  53. package/web-ui/logic.agents-diff.mjs +386 -386
  54. package/web-ui/logic.claude.mjs +168 -168
  55. package/web-ui/logic.codex.mjs +69 -69
  56. package/web-ui/logic.mjs +5 -5
  57. package/web-ui/logic.runtime.mjs +128 -128
  58. package/web-ui/logic.session-convert.mjs +70 -70
  59. package/web-ui/logic.sessions.mjs +781 -765
  60. package/web-ui/modules/api.mjs +90 -90
  61. package/web-ui/modules/app.computed.dashboard.mjs +248 -248
  62. package/web-ui/modules/app.computed.index.mjs +17 -17
  63. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  64. package/web-ui/modules/app.computed.session.mjs +693 -999
  65. package/web-ui/modules/app.constants.mjs +15 -15
  66. package/web-ui/modules/app.methods.agents.mjs +651 -632
  67. package/web-ui/modules/app.methods.claude-config.mjs +200 -200
  68. package/web-ui/modules/app.methods.codex-config.mjs +861 -917
  69. package/web-ui/modules/app.methods.index.mjs +94 -94
  70. package/web-ui/modules/app.methods.install.mjs +205 -205
  71. package/web-ui/modules/app.methods.navigation.mjs +774 -774
  72. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  73. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  74. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  75. package/web-ui/modules/app.methods.providers.mjs +529 -529
  76. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  77. package/web-ui/modules/app.methods.session-actions.mjs +591 -593
  78. package/web-ui/modules/app.methods.session-browser.mjs +1012 -984
  79. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  80. package/web-ui/modules/app.methods.session-trash.mjs +438 -438
  81. package/web-ui/modules/app.methods.startup-claude.mjs +537 -534
  82. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  83. package/web-ui/modules/app.methods.webhook.mjs +79 -79
  84. package/web-ui/modules/config-mode.computed.mjs +124 -124
  85. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  86. package/web-ui/modules/i18n.dict.mjs +3177 -3146
  87. package/web-ui/modules/i18n.mjs +62 -62
  88. package/web-ui/modules/plugins.computed.mjs +3 -3
  89. package/web-ui/modules/plugins.methods.mjs +3 -3
  90. package/web-ui/modules/plugins.storage.mjs +11 -11
  91. package/web-ui/modules/provider-url-display.mjs +17 -17
  92. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  93. package/web-ui/modules/skills.computed.mjs +107 -107
  94. package/web-ui/modules/skills.methods.mjs +482 -482
  95. package/web-ui/partials/index/layout-footer.html +13 -13
  96. package/web-ui/partials/index/layout-header.html +503 -500
  97. package/web-ui/partials/index/modal-config-template-agents.html +185 -174
  98. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  99. package/web-ui/partials/index/modal-health-check.html +45 -45
  100. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  101. package/web-ui/partials/index/modal-skills.html +200 -200
  102. package/web-ui/partials/index/modals-basic.html +162 -162
  103. package/web-ui/partials/index/panel-config-claude.html +136 -194
  104. package/web-ui/partials/index/panel-config-codex.html +197 -337
  105. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  106. package/web-ui/partials/index/panel-dashboard.html +219 -219
  107. package/web-ui/partials/index/panel-docs.html +115 -147
  108. package/web-ui/partials/index/panel-market.html +177 -177
  109. package/web-ui/partials/index/panel-orchestration.html +391 -391
  110. package/web-ui/partials/index/panel-plugins.html +253 -253
  111. package/web-ui/partials/index/panel-sessions.html +313 -308
  112. package/web-ui/partials/index/panel-settings.html +190 -190
  113. package/web-ui/partials/index/panel-trash.html +83 -88
  114. package/web-ui/partials/index/panel-usage.html +138 -371
  115. package/web-ui/res/json5.min.js +1 -1
  116. package/web-ui/res/vue.global.prod.js +13 -13
  117. package/web-ui/session-helpers.mjs +591 -594
  118. package/web-ui/source-bundle.cjs +233 -233
  119. package/web-ui/styles/base-theme.css +281 -281
  120. package/web-ui/styles/bridge-pool.css +197 -0
  121. package/web-ui/styles/controls-forms.css +433 -422
  122. package/web-ui/styles/dashboard.css +406 -406
  123. package/web-ui/styles/docs-panel.css +245 -271
  124. package/web-ui/styles/feedback.css +108 -108
  125. package/web-ui/styles/health-check-dialog.css +144 -144
  126. package/web-ui/styles/layout-shell.css +638 -626
  127. package/web-ui/styles/modals-core.css +466 -466
  128. package/web-ui/styles/navigation-panels.css +391 -391
  129. package/web-ui/styles/openclaw-structured.css +266 -266
  130. package/web-ui/styles/plugins-panel.css +564 -564
  131. package/web-ui/styles/responsive.css +392 -454
  132. package/web-ui/styles/sessions-list.css +647 -417
  133. package/web-ui/styles/sessions-preview.css +407 -407
  134. package/web-ui/styles/sessions-toolbar-trash.css +518 -334
  135. package/web-ui/styles/sessions-usage.css +588 -1040
  136. package/web-ui/styles/settings-panel.css +349 -349
  137. package/web-ui/styles/skills-list.css +305 -305
  138. package/web-ui/styles/skills-market.css +429 -429
  139. package/web-ui/styles/task-orchestration.css +822 -822
  140. package/web-ui/styles/titles-cards.css +472 -472
  141. package/web-ui/styles/trash-panel.css +90 -90
  142. package/web-ui/styles/webhook.css +81 -81
  143. package/web-ui/styles.css +24 -23
  144. package/web-ui.html +17 -17
@@ -1,917 +1,861 @@
1
- import { runLatestOnlyQueue } from '../logic.mjs';
2
- import { normalizeConfigTemplateDiffConfirmEnabled } from './config-template-confirm-pref.mjs';
3
- import {
4
- getConvertTargetSource,
5
- normalizeSessionConvertSource
6
- } from '../logic.session-convert.mjs';
7
- import { syncSessionsFilterUrl } from './sessions-filters-url.mjs';
8
-
9
- function hasResponseError(response) {
10
- if (!response || typeof response !== 'object') {
11
- return false;
12
- }
13
- if (typeof response.error === 'string') {
14
- return response.error.trim().length > 0;
15
- }
16
- return response.error !== undefined && response.error !== null && response.error !== false;
17
- }
18
-
19
- function getResponseMessage(response, fallback) {
20
- if (!response || typeof response !== 'object') {
21
- return fallback;
22
- }
23
- for (const key of ['error', 'message', 'detail']) {
24
- const value = response[key];
25
- if (typeof value === 'string' && value.trim()) {
26
- return value.trim();
27
- }
28
- }
29
- return fallback;
30
- }
31
-
32
- export function createCodexConfigMethods(options = {}) {
33
- const {
34
- api,
35
- defaultModelContextWindow = 190000,
36
- defaultModelAutoCompactTokenLimit = 185000,
37
- getProviderConfigModeMeta
38
- } = options;
39
-
40
- return {
41
- downloadTextFile(fileName, content, mimeType = 'text/markdown;charset=utf-8') {
42
- const BOM = '\uFEFF';
43
- const blob = new Blob([BOM + content], { type: mimeType });
44
- const url = URL.createObjectURL(blob);
45
- const link = document.createElement('a');
46
- link.href = url;
47
- link.download = fileName;
48
- link.click();
49
- URL.revokeObjectURL(url);
50
- },
51
-
52
- async exportSession(session) {
53
- const key = this.getSessionExportKey(session);
54
- if (this.sessionExporting[key]) return;
55
-
56
- this.sessionExporting[key] = true;
57
- try {
58
- const res = await api('export-session', {
59
- source: session.source,
60
- sessionId: session.sessionId,
61
- filePath: session.filePath
62
- });
63
- if (res.error) {
64
- this.showMessage(res.error, 'error');
65
- return;
66
- }
67
-
68
- const fileName = res.fileName || `${session.source || 'session'}-${session.sessionId || Date.now()}.md`;
69
- this.downloadTextFile(fileName, res.content || '');
70
- if (res.truncated) {
71
- const maxLabel = res.maxMessages === 'all' ? 'all' : res.maxMessages;
72
- this.showMessage(`会话导出完成(已截断:最多 ${maxLabel} 条消息)`, 'info');
73
- } else {
74
- this.showMessage('操作成功', 'success');
75
- }
76
- } catch (e) {
77
- this.showMessage('导出失败', 'error');
78
- } finally {
79
- this.sessionExporting[key] = false;
80
- }
81
- },
82
-
83
- async convertSession(session) {
84
- const source = normalizeSessionConvertSource(session && session.source ? session.source : '');
85
- const target = getConvertTargetSource(source);
86
- if (!source || !target) {
87
- this.showMessage('不支持此操作', 'error');
88
- return;
89
- }
90
- const key = this.getSessionExportKey(session);
91
- if (this.sessionConverting[key]) return;
92
- this.sessionConverting[key] = true;
93
- try {
94
- const res = await api('convert-session', {
95
- source,
96
- target,
97
- sessionId: session.sessionId,
98
- filePath: session.filePath,
99
- maxMessages: 'all'
100
- });
101
- if (res && res.error) {
102
- this.showMessage(res.error, 'error');
103
- return;
104
- }
105
- const converted = res && res.session ? res.session : null;
106
- if (!converted) {
107
- this.showMessage('转换失败', 'error');
108
- return;
109
- }
110
- if (res && res.truncated) {
111
- const maxLabel = res.maxMessages === 'all' ? 'all' : res.maxMessages;
112
- const targetLabel = converted && converted.sourceLabel ? String(converted.sourceLabel).trim() : '';
113
- if (targetLabel && typeof this.sessionFilterSource === 'string' && this.sessionFilterSource !== converted.source) {
114
- this.showMessage(`已生成派生会话(来源:${targetLabel},已截断:最多 ${maxLabel} 条消息)`, 'info');
115
- } else {
116
- this.showMessage(`已生成派生会话(已截断:最多 ${maxLabel} 条消息)`, 'info');
117
- }
118
- } else {
119
- const targetLabel = converted && converted.sourceLabel ? String(converted.sourceLabel).trim() : '';
120
- if (targetLabel && typeof this.sessionFilterSource === 'string' && this.sessionFilterSource !== converted.source) {
121
- this.showMessage(`已生成派生会话(来源:${targetLabel})`, 'success');
122
- } else {
123
- this.showMessage('已生成派生会话', 'success');
124
- }
125
- }
126
-
127
- if (converted && converted.source && typeof this.sessionFilterSource === 'string') {
128
- if (this.sessionFilterSource !== converted.source) {
129
- this.sessionFilterSource = converted.source;
130
- if (typeof this.refreshSessionPathOptions === 'function') {
131
- this.refreshSessionPathOptions(this.sessionFilterSource);
132
- }
133
- if (typeof this.persistSessionFilterCache === 'function') {
134
- this.persistSessionFilterCache();
135
- }
136
- syncSessionsFilterUrl(this);
137
- this.sessionsList = [converted];
138
- } else {
139
- const list = Array.isArray(this.sessionsList) ? this.sessionsList : [];
140
- const next = [converted, ...list.filter(item => !(item && item.filePath === converted.filePath && item.source === converted.source))];
141
- this.sessionsList = next;
142
- }
143
- }
144
- if (typeof this.selectSession === 'function') {
145
- await this.selectSession(converted);
146
- }
147
- } catch (e) {
148
- this.showMessage('转换失败', 'error');
149
- } finally {
150
- this.sessionConverting[key] = false;
151
- }
152
- },
153
-
154
- async quickSwitchProvider(name) {
155
- const target = String(name || '').trim();
156
- const visualTarget = String(this.providerSwitchDisplayTarget || '').trim();
157
- if (!target || target === visualTarget || target === this.pendingProviderSwitch) {
158
- return;
159
- }
160
- if (!this.providerSwitchInProgress && target === this.currentProvider) {
161
- return;
162
- }
163
- await this.switchProvider(target);
164
- },
165
-
166
- async waitForCodexApplyIdle(maxWaitMs = 20000) {
167
- const startedAt = Date.now();
168
- while (this.codexApplying) {
169
- if ((Date.now() - startedAt) > maxWaitMs) {
170
- throw new Error('等待配置应用完成超时');
171
- }
172
- await new Promise((resolve) => setTimeout(resolve, 50));
173
- }
174
- },
175
-
176
- async performProviderSwitch(name) {
177
- await this.waitForCodexApplyIdle();
178
- const previousProvider = this.currentProvider;
179
- const previousModel = this.currentModel;
180
- const previousModels = Array.isArray(this.models) ? [...this.models] : [];
181
- const previousModelsSource = this.modelsSource;
182
- const previousModelsHasCurrent = this.modelsHasCurrent;
183
- // 切走前把上一个 provider 的 model 落到内存字典,避免切回时显示抖动。
184
- if (previousProvider && typeof previousModel === 'string' && previousModel.trim() && previousModel !== '未设置') {
185
- if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
186
- this.currentModels[previousProvider] = previousModel.trim();
187
- }
188
- this.currentProvider = name;
189
- // 立即按字典预填,让 UI 不出现空白;远端 /models 后台异步补齐。
190
- const dictModel = typeof this.activeProviderModel === 'function'
191
- ? this.activeProviderModel(name)
192
- : '';
193
- if (dictModel) {
194
- this.currentModel = dictModel;
195
- }
196
- const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
197
-
198
- // 不要把“切换提供商”强绑定到 /models 成功与否:
199
- // 部分 OpenAI 兼容服务 /models 不可用或很慢,但用户仍希望一次点击即可完成切换。
200
- // 这里做“短等待 + 后台补齐”:
201
- // 1) 先启动 models 拉取(静默)
202
- // 2) 给一个很短的窗口等待它完成,以便能立即选到第一个模型
203
- // 3) 无论 models 是否成功,先应用 provider 切换
204
- // 4) models 后续若补齐并发现当前 model 不在列表,则自动切到首个 model 并再应用一次
205
- const modelsTask = this.loadModelsForProvider(name, { silentError: true })
206
- .catch(() => {});
207
-
208
- await Promise.race([modelsTask, delay(250)]);
209
-
210
- // 只在“字典中没有该 provider 记录”时才允许 remote 首项覆盖,否则尊重用户上次选择。
211
- if (!dictModel
212
- && this.modelsSource === 'remote'
213
- && this.models.length > 0
214
- && !this.models.includes(this.currentModel)) {
215
- this.currentModel = this.models[0];
216
- this.modelsHasCurrent = true;
217
- }
218
-
219
- if (getProviderConfigModeMeta(this.configMode)) {
220
- await this.waitForCodexApplyIdle();
221
- await this.applyCodexConfigDirect({ silent: true });
222
- }
223
-
224
- await modelsTask;
225
-
226
- if (this.currentProvider === name) {
227
- if (!dictModel
228
- && this.modelsSource === 'remote'
229
- && this.models.length > 0
230
- && !this.models.includes(this.currentModel)) {
231
- this.currentModel = this.models[0];
232
- this.modelsHasCurrent = true;
233
- if (getProviderConfigModeMeta(this.configMode)) {
234
- await this.waitForCodexApplyIdle();
235
- await this.applyCodexConfigDirect({ silent: true });
236
- }
237
- }
238
- }
239
-
240
- if (typeof this.loadLocalBridgeExcluded === 'function') {
241
- this.loadLocalBridgeExcluded();
242
- }
243
- },
244
-
245
- async switchProvider(name) {
246
- const target = String(name || '').trim();
247
- if (!target) {
248
- return;
249
- }
250
- if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
251
- return;
252
- }
253
- this.providerSwitchDisplayTarget = target;
254
- if (this.providerSwitchInProgress) {
255
- this.pendingProviderSwitch = target;
256
- return;
257
- }
258
- this.providerSwitchInProgress = true;
259
- let lastError = '';
260
- try {
261
- this.pendingProviderSwitch = '';
262
- const result = await runLatestOnlyQueue(target, {
263
- perform: async (queuedTarget) => {
264
- this.providerSwitchDisplayTarget = queuedTarget;
265
- await this.performProviderSwitch(queuedTarget);
266
- },
267
- consumePending: () => {
268
- const queued = this.pendingProviderSwitch;
269
- this.pendingProviderSwitch = '';
270
- return queued;
271
- }
272
- });
273
- if (result && typeof result.lastError === 'string') {
274
- lastError = result.lastError;
275
- }
276
- } finally {
277
- this.providerSwitchInProgress = false;
278
- this.pendingProviderSwitch = '';
279
- this.providerSwitchDisplayTarget = '';
280
- }
281
- if (lastError) {
282
- this.showMessage(lastError, 'error');
283
- }
284
- },
285
-
286
- async onModelChange() {
287
- const name = String(this.currentProvider || '').trim();
288
- const model = typeof this.currentModel === 'string' ? this.currentModel.trim() : '';
289
- if (name && model) {
290
- if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
291
- this.currentModels[name] = model;
292
- }
293
- await this.applyCodexConfigDirect();
294
- },
295
-
296
- async onServiceTierChange() {
297
- await this.applyCodexConfigDirect({ silent: true });
298
- },
299
-
300
- async onReasoningEffortChange() {
301
- await this.applyCodexConfigDirect({ silent: true });
302
- },
303
-
304
- sanitizePositiveIntegerDraft(field) {
305
- if (!field || typeof this[field] === 'undefined') return;
306
- const current = typeof this[field] === 'string'
307
- ? this[field]
308
- : String(this[field] || '');
309
- const sanitized = current.replace(/[^\d]/g, '');
310
- if (sanitized !== current) {
311
- this[field] = sanitized;
312
- }
313
- },
314
-
315
- normalizePositiveIntegerInput(value, label, fallback = '') {
316
- const fallbackText = fallback === '' ? '' : String(fallback).trim();
317
- const raw = typeof value === 'string'
318
- ? value.trim()
319
- : String(value == null ? '' : value).trim();
320
- const text = raw || fallbackText;
321
- if (!text) {
322
- return { ok: true, value: null, text: '' };
323
- }
324
- if (!/^\d+$/.test(text)) {
325
- return { ok: false, error: `${label} 请输入正整数` };
326
- }
327
- const num = Number.parseInt(text, 10);
328
- if (!Number.isSafeInteger(num) || num <= 0) {
329
- return { ok: false, error: `${label} 请输入正整数` };
330
- }
331
- return { ok: true, value: num, text: String(num) };
332
- },
333
-
334
- async onModelContextWindowBlur() {
335
- this.editingCodexBudgetField = '';
336
- const normalized = this.normalizePositiveIntegerInput(
337
- this.modelContextWindowInput,
338
- 'model_context_window',
339
- defaultModelContextWindow
340
- );
341
- if (!normalized.ok) {
342
- this.showMessage(normalized.error, 'error');
343
- return;
344
- }
345
- this.modelContextWindowInput = normalized.text;
346
- await this.applyCodexConfigDirect({
347
- silent: true,
348
- modelContextWindow: normalized.value
349
- });
350
- },
351
-
352
- async onModelAutoCompactTokenLimitBlur() {
353
- this.editingCodexBudgetField = '';
354
- const normalized = this.normalizePositiveIntegerInput(
355
- this.modelAutoCompactTokenLimitInput,
356
- 'model_auto_compact_token_limit',
357
- defaultModelAutoCompactTokenLimit
358
- );
359
- if (!normalized.ok) {
360
- this.showMessage(normalized.error, 'error');
361
- return;
362
- }
363
- this.modelAutoCompactTokenLimitInput = normalized.text;
364
- await this.applyCodexConfigDirect({
365
- silent: true,
366
- modelAutoCompactTokenLimit: normalized.value
367
- });
368
- },
369
-
370
- async resetCodexContextBudgetDefaults() {
371
- this.modelContextWindowInput = String(defaultModelContextWindow);
372
- this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
373
- await this.applyCodexConfigDirect({
374
- modelContextWindow: defaultModelContextWindow,
375
- modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
376
- });
377
- },
378
-
379
- async runHealthCheck(options = {}) {
380
- this.healthCheckLoading = true;
381
- this.healthCheckResult = null;
382
- this.healthCheckBatchTotal = 0;
383
- this.healthCheckBatchDone = 0;
384
- this.healthCheckBatchFailed = 0;
385
- try {
386
- const silent = !!(options && options.silent);
387
- const forceRefresh = !!(options && options.forceRefresh);
388
- const useDoctor = !!(options && options.doctor);
389
- if (useDoctor) {
390
- const res = await api('doctor', {
391
- lang: this.lang,
392
- remote: true,
393
- range: this.sessionsUsageTimeRange,
394
- targetApp: this.skillsTargetApp,
395
- includeUsage: true,
396
- includeTasks: true,
397
- includeSkills: true,
398
- includeInstall: true,
399
- forceRefresh
400
- });
401
- if (hasResponseError(res)) {
402
- this.healthCheckResult = null;
403
- if (!silent) {
404
- this.showMessage(getResponseMessage(res, '检查失败'), 'error');
405
- }
406
- return;
407
- }
408
- if (res && typeof res === 'object') {
409
- this.healthCheckResult = res;
410
- const report = res.report && typeof res.report === 'object' ? res.report : null;
411
- const summary = report && report.summary && typeof report.summary === 'object' ? report.summary : null;
412
- const total = summary && Number.isFinite(Number(summary.total))
413
- ? Math.max(0, Math.floor(Number(summary.total)))
414
- : (Array.isArray(res.issues) ? res.issues.length : 0);
415
- const errors = summary && Number.isFinite(Number(summary.error)) ? Math.max(0, Math.floor(Number(summary.error))) : 0;
416
- const warns = summary && Number.isFinite(Number(summary.warn)) ? Math.max(0, Math.floor(Number(summary.warn))) : 0;
417
- this.healthCheckBatchTotal = total;
418
- this.healthCheckBatchDone = total;
419
- this.healthCheckBatchFailed = errors + warns;
420
- if (!silent && res.ok) {
421
- this.showMessage('检查通过', 'success');
422
- }
423
- return;
424
- }
425
- this.healthCheckResult = null;
426
- if (!silent) {
427
- this.showMessage('检查失败', 'error');
428
- }
429
- return;
430
- }
431
-
432
- if (this.configMode === 'claude') {
433
- const entries = Object.entries(this.claudeConfigs || {});
434
- this.healthCheckBatchTotal = entries.length;
435
-
436
- const speedTasks = entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)
437
- .then((result) => {
438
- if (!result || result.ok !== true) {
439
- this.healthCheckBatchFailed += 1;
440
- }
441
- return { name, result };
442
- })
443
- .catch((err) => {
444
- this.healthCheckBatchFailed += 1;
445
- return {
446
- name,
447
- result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
448
- };
449
- })
450
- .finally(() => {
451
- this.healthCheckBatchDone += 1;
452
- })
453
- );
454
-
455
- const pairs = await Promise.all(speedTasks);
456
- const results = {};
457
- const issues = [];
458
- for (const pair of pairs) {
459
- results[pair.name] = pair.result || null;
460
- if (typeof this.buildSpeedTestIssue === 'function') {
461
- const issue = this.buildSpeedTestIssue(pair.name, pair.result);
462
- if (issue) issues.push(issue);
463
- }
464
- }
465
- const ok = issues.length === 0 && this.healthCheckBatchFailed === 0;
466
- this.healthCheckResult = {
467
- ok,
468
- issues,
469
- remote: {
470
- type: 'speed-test',
471
- speedTests: results
472
- }
473
- };
474
- if (ok && !silent) {
475
- this.showMessage('检查通过', 'success');
476
- }
477
- return;
478
- }
479
-
480
- const shouldRunSpeedTests = this.configMode === 'codex';
481
- const speedTimeoutMs = shouldRunSpeedTests ? 3500 : 0;
482
- const providers = shouldRunSpeedTests
483
- ? (this.providersList || [])
484
- .map((provider) => typeof provider === 'string'
485
- ? provider.trim()
486
- : String((provider && provider.name) || '').trim())
487
- .filter(Boolean)
488
- : [];
489
- const currentProvider = String(this.currentProvider || '').trim();
490
- const orderedProviders = currentProvider && providers.includes(currentProvider)
491
- ? [currentProvider, ...providers.filter((name) => name !== currentProvider)]
492
- : providers;
493
- this.healthCheckBatchTotal = orderedProviders.length;
494
-
495
- const speedTasks = orderedProviders.map((provider) => this.runSpeedTest(provider, { silent: true, timeoutMs: speedTimeoutMs })
496
- .then((result) => {
497
- if (!result || result.ok !== true) {
498
- this.healthCheckBatchFailed += 1;
499
- }
500
- return { name: provider, result };
501
- })
502
- .catch((err) => {
503
- this.healthCheckBatchFailed += 1;
504
- return {
505
- name: provider,
506
- result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
507
- };
508
- })
509
- .finally(() => {
510
- this.healthCheckBatchDone += 1;
511
- })
512
- );
513
-
514
- const configTask = api('config-health-check', { remote: this.configMode === 'codex' });
515
- const [res, pairs] = await Promise.all([
516
- configTask,
517
- Promise.all(speedTasks)
518
- ]);
519
- if (hasResponseError(res)) {
520
- this.healthCheckResult = null;
521
- if (!silent) {
522
- this.showMessage(getResponseMessage(res, '检查失败'), 'error');
523
- }
524
- } else if (res && typeof res === 'object') {
525
- const issues = Array.isArray(res.issues) ? [...res.issues] : [];
526
- let remote = res.remote || null;
527
- if (shouldRunSpeedTests) {
528
- const results = {};
529
- for (const pair of pairs) {
530
- results[pair.name] = pair.result || null;
531
- const issue = this.buildSpeedTestIssue(pair.name, pair.result);
532
- if (issue) issues.push(issue);
533
- }
534
- remote = remote && typeof remote === 'object'
535
- ? { ...remote, speedTests: results }
536
- : { type: 'speed-test', speedTests: results };
537
- }
538
-
539
- const ok = issues.length === 0;
540
- this.healthCheckResult = {
541
- ...res,
542
- ok,
543
- issues,
544
- remote
545
- };
546
- if (ok && !silent) {
547
- this.showMessage('检查通过', 'success');
548
- }
549
- } else {
550
- this.healthCheckResult = null;
551
- if (!silent) {
552
- this.showMessage('检查失败', 'error');
553
- }
554
- }
555
- } catch (e) {
556
- this.healthCheckResult = null;
557
- if (!(options && options.silent)) {
558
- this.showMessage('检查失败', 'error');
559
- }
560
- } finally {
561
- this.healthCheckBatchTotal = this.healthCheckBatchTotal || 0;
562
- this.healthCheckBatchDone = Math.min(this.healthCheckBatchDone || 0, this.healthCheckBatchTotal || 0);
563
- this.healthCheckLoading = false;
564
- if (typeof this.runProvidersHealthCheck === 'function' && this.configMode === 'codex') {
565
- void this.runProvidersHealthCheck({ remote: true });
566
- }
567
- }
568
- },
569
-
570
- async runProvidersHealthCheck(options = {}) {
571
- this.providersHealthLoading = true;
572
- try {
573
- const res = await api('providers-health', {
574
- remote: options.remote !== false
575
- });
576
- if (res && typeof res === 'object' && !res.error) {
577
- this.providersHealthResult = res;
578
- } else {
579
- this.providersHealthResult = null;
580
- }
581
- } catch (e) {
582
- this.providersHealthResult = null;
583
- } finally {
584
- this.providersHealthLoading = false;
585
- }
586
- },
587
-
588
- escapeTomlString(value) {
589
- return String(value || '')
590
- .replace(/\\/g, '\\\\')
591
- .replace(/"/g, '\\"');
592
- },
593
-
594
- async openConfigTemplateEditor(options = {}) {
595
- this.resetConfigTemplateDiffState();
596
- const modelContextWindow = this.normalizePositiveIntegerInput(
597
- this.modelContextWindowInput,
598
- 'model_context_window',
599
- defaultModelContextWindow
600
- );
601
- if (!modelContextWindow.ok) {
602
- this.showMessage(modelContextWindow.error, 'error');
603
- return;
604
- }
605
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
606
- this.modelAutoCompactTokenLimitInput,
607
- 'model_auto_compact_token_limit',
608
- defaultModelAutoCompactTokenLimit
609
- );
610
- if (!modelAutoCompactTokenLimit.ok) {
611
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
612
- return;
613
- }
614
- try {
615
- const res = await api('get-config-template', {
616
- provider: this.currentProvider,
617
- model: this.currentModel,
618
- serviceTier: this.serviceTier,
619
- reasoningEffort: this.modelReasoningEffort,
620
- modelContextWindow: modelContextWindow.value,
621
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
622
- });
623
- if (res.error) {
624
- this.showMessage(res.error, 'error');
625
- return;
626
- }
627
- let template = res.template || '';
628
- const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
629
- const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
630
- if (appendHint) {
631
- template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
632
- }
633
- if (appendBlock) {
634
- template = `${template.trimEnd()}\n\n${appendBlock}\n`;
635
- }
636
- this.configTemplateContent = template;
637
- this.showConfigTemplateModal = true;
638
- } catch (e) {
639
- this.showMessage('加载模板失败', 'error');
640
- }
641
- },
642
-
643
- async applyCodexConfigDirect(options = {}) {
644
- if (this.codexApplying) {
645
- this._pendingCodexApplyOptions = {
646
- ...(this._pendingCodexApplyOptions || {}),
647
- ...options
648
- };
649
- return;
650
- }
651
-
652
- const provider = (this.currentProvider || '').trim();
653
- const model = (this.currentModel || '').trim();
654
- if (!provider || !model) {
655
- this.showMessage('请选择提供商和模型', 'error');
656
- return;
657
- }
658
-
659
- const modelContextWindow = this.normalizePositiveIntegerInput(
660
- options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
661
- 'model_context_window',
662
- defaultModelContextWindow
663
- );
664
- if (!modelContextWindow.ok) {
665
- this.showMessage(modelContextWindow.error, 'error');
666
- return;
667
- }
668
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
669
- options.modelAutoCompactTokenLimit !== undefined
670
- ? options.modelAutoCompactTokenLimit
671
- : this.modelAutoCompactTokenLimitInput,
672
- 'model_auto_compact_token_limit',
673
- defaultModelAutoCompactTokenLimit
674
- );
675
- if (!modelAutoCompactTokenLimit.ok) {
676
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
677
- return;
678
- }
679
- this.modelContextWindowInput = modelContextWindow.text;
680
- this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
681
-
682
- const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
683
-
684
- this.codexApplying = true;
685
- try {
686
- const tplRes = await api('get-config-template', {
687
- provider,
688
- model,
689
- serviceTier: this.serviceTier,
690
- reasoningEffort: this.modelReasoningEffort,
691
- modelContextWindow: modelContextWindow.value,
692
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
693
- });
694
- if (tplRes.error) {
695
- this.showMessage(
696
- (typeof tplRes.error === 'string' && tplRes.error.trim())
697
- || (typeof tplRes.message === 'string' && tplRes.message.trim())
698
- || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
699
- || '获取模板失败',
700
- 'error'
701
- );
702
- return;
703
- }
704
-
705
- const applyRes = await api('apply-config-template', {
706
- template: tplRes.template
707
- });
708
- if (applyRes.error) {
709
- this.showMessage(
710
- (typeof applyRes.error === 'string' && applyRes.error.trim())
711
- || (typeof applyRes.message === 'string' && applyRes.message.trim())
712
- || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
713
- || '应用模板失败',
714
- 'error'
715
- );
716
- return;
717
- }
718
-
719
- if (options.silent !== true) {
720
- if (this._lastAppliedCodexKey !== _codexKey) {
721
- this.showMessage('配置已应用', 'success');
722
- this._lastAppliedCodexKey = _codexKey;
723
- }
724
- } else {
725
- this._lastAppliedCodexKey = _codexKey;
726
- }
727
-
728
- const refreshOptions = options.silent === true
729
- ? { preserveLoading: true }
730
- : {};
731
- try {
732
- await this.loadAll(refreshOptions);
733
- } catch (_) {
734
- this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
735
- }
736
- } catch (e) {
737
- this.showMessage('应用失败', 'error');
738
- } finally {
739
- this.codexApplying = false;
740
- const pendingOptions = this._pendingCodexApplyOptions;
741
- this._pendingCodexApplyOptions = null;
742
- if (pendingOptions) {
743
- await this.applyCodexConfigDirect(pendingOptions);
744
- }
745
- }
746
- },
747
-
748
- closeConfigTemplateModal(options = {}) {
749
- const force = !!options.force;
750
- if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
751
- return;
752
- }
753
- this.showConfigTemplateModal = false;
754
- this.configTemplateContent = '';
755
- this.resetConfigTemplateDiffState();
756
- },
757
-
758
- resetConfigTemplateDiffState() {
759
- this.configTemplateDiffVisible = false;
760
- this.configTemplateDiffLoading = false;
761
- this.configTemplateDiffError = '';
762
- this.configTemplateDiffLines = [];
763
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
764
- this.configTemplateDiffHasChangesValue = false;
765
- this.configTemplateDiffFingerprint = '';
766
- this._configTemplateDiffPreviewRequestToken = null;
767
- },
768
-
769
- onConfigTemplateContentInput() {
770
- if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
771
- this.resetConfigTemplateDiffState();
772
- }
773
- },
774
-
775
- buildConfigTemplateDiffFingerprint() {
776
- const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
777
- return `${content.length}::${content}`;
778
- },
779
-
780
- hasConfigTemplateDiffChanges() {
781
- if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
782
- return !!this.configTemplateDiffHasChangesValue;
783
- }
784
- const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
785
- ? this.configTemplateDiffStats
786
- : {};
787
- const added = Number(stats.added || 0);
788
- const removed = Number(stats.removed || 0);
789
- return added > 0 || removed > 0;
790
- },
791
-
792
- async prepareConfigTemplateDiff() {
793
- const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
794
- const requestToken = Symbol('config-template-diff-preview');
795
- this._configTemplateDiffPreviewRequestToken = requestToken;
796
- this.configTemplateDiffVisible = true;
797
- this.configTemplateDiffLoading = true;
798
- this.configTemplateDiffError = '';
799
- this.configTemplateDiffLines = [];
800
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
801
- this.configTemplateDiffHasChangesValue = false;
802
- try {
803
- const shouldApply = () => (
804
- this.configTemplateDiffVisible
805
- && this._configTemplateDiffPreviewRequestToken === requestToken
806
- && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
807
- );
808
- const res = await api('preview-config-template-diff', {
809
- template: this.configTemplateContent
810
- });
811
- if (!shouldApply()) {
812
- return;
813
- }
814
- if (res.error) {
815
- this.configTemplateDiffError = res.error;
816
- return;
817
- }
818
- const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
819
- const lines = Array.isArray(diff.lines) ? diff.lines : [];
820
- this.configTemplateDiffLines = lines.filter(line => line && line.type);
821
- const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
822
- if (stats) {
823
- this.configTemplateDiffStats = {
824
- added: Number(stats.added || 0),
825
- removed: Number(stats.removed || 0),
826
- unchanged: Number(stats.unchanged || 0)
827
- };
828
- } else {
829
- const nextStats = { added: 0, removed: 0, unchanged: 0 };
830
- for (const line of this.configTemplateDiffLines) {
831
- if (line && line.type === 'add') nextStats.added += 1;
832
- else if (line && line.type === 'del') nextStats.removed += 1;
833
- else nextStats.unchanged += 1;
834
- }
835
- this.configTemplateDiffStats = nextStats;
836
- }
837
- this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
838
- this.configTemplateDiffFingerprint = requestFingerprint;
839
- } catch (_) {
840
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
841
- this.configTemplateDiffError = '生成差异失败';
842
- }
843
- } finally {
844
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
845
- this.configTemplateDiffLoading = false;
846
- }
847
- }
848
- },
849
-
850
- async applyConfigTemplate() {
851
- if (this.configTemplateApplying) {
852
- return;
853
- }
854
- if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
855
- this.showMessage('模板不能为空', 'error');
856
- return;
857
- }
858
-
859
- // Default to two-step confirmation when the setting is unset.
860
- // (The normalize helper lives in session-actions; keep a safe fallback here.)
861
- const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
862
-
863
- const performApply = async () => {
864
- this.configTemplateApplying = true;
865
- try {
866
- const res = await api('apply-config-template', {
867
- template: this.configTemplateContent
868
- });
869
- if (res.error) {
870
- this.showMessage(res.error, 'error');
871
- return;
872
- }
873
- this.showMessage('模板已应用', 'success');
874
- this.closeConfigTemplateModal({ force: true });
875
- try {
876
- await this.loadAll();
877
- } catch (_) {
878
- this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
879
- }
880
- } catch (e) {
881
- this.showMessage('应用模板失败', 'error');
882
- } finally {
883
- this.configTemplateApplying = false;
884
- }
885
- };
886
-
887
- // One-step mode: apply immediately unless user explicitly entered the diff preview state.
888
- if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
889
- await performApply();
890
- return;
891
- }
892
-
893
- if (!this.configTemplateDiffVisible) {
894
- await this.prepareConfigTemplateDiff();
895
- return;
896
- }
897
- if (this.configTemplateDiffLoading) {
898
- return;
899
- }
900
- if (this.configTemplateDiffError) {
901
- this.showMessage(this.configTemplateDiffError, 'error');
902
- return;
903
- }
904
- const fingerprint = this.buildConfigTemplateDiffFingerprint();
905
- if (this.configTemplateDiffFingerprint !== fingerprint) {
906
- await this.prepareConfigTemplateDiff();
907
- return;
908
- }
909
- if (!this.hasConfigTemplateDiffChanges()) {
910
- this.showMessage('未检测到改动', 'info');
911
- return;
912
- }
913
-
914
- await performApply();
915
- }
916
- };
917
- }
1
+ import { runLatestOnlyQueue } from '../logic.mjs';
2
+ import { normalizeConfigTemplateDiffConfirmEnabled } from './config-template-confirm-pref.mjs';
3
+
4
+ function hasResponseError(response) {
5
+ if (!response || typeof response !== 'object') {
6
+ return false;
7
+ }
8
+ if (typeof response.error === 'string') {
9
+ return response.error.trim().length > 0;
10
+ }
11
+ return response.error !== undefined && response.error !== null && response.error !== false;
12
+ }
13
+
14
+ function getResponseMessage(response, fallback) {
15
+ if (!response || typeof response !== 'object') {
16
+ return fallback;
17
+ }
18
+ for (const key of ['error', 'message', 'detail']) {
19
+ const value = response[key];
20
+ if (typeof value === 'string' && value.trim()) {
21
+ return value.trim();
22
+ }
23
+ }
24
+ return fallback;
25
+ }
26
+
27
+ export function createCodexConfigMethods(options = {}) {
28
+ const {
29
+ api,
30
+ defaultModelContextWindow = 190000,
31
+ defaultModelAutoCompactTokenLimit = 185000,
32
+ getProviderConfigModeMeta
33
+ } = options;
34
+
35
+ return {
36
+ downloadTextFile(fileName, content, mimeType = 'text/markdown;charset=utf-8') {
37
+ const BOM = '\uFEFF';
38
+ const blob = new Blob([BOM + content], { type: mimeType });
39
+ const url = URL.createObjectURL(blob);
40
+ const link = document.createElement('a');
41
+ link.href = url;
42
+ link.download = fileName;
43
+ link.click();
44
+ URL.revokeObjectURL(url);
45
+ },
46
+
47
+ async exportSession(session) {
48
+ const key = this.getSessionExportKey(session);
49
+ if (this.sessionExporting[key]) return;
50
+
51
+ this.sessionExporting[key] = true;
52
+ try {
53
+ const res = await api('export-session', {
54
+ source: session.source,
55
+ sessionId: session.sessionId,
56
+ filePath: session.filePath
57
+ });
58
+ if (res.error) {
59
+ this.showMessage(res.error, 'error');
60
+ return;
61
+ }
62
+
63
+ const fileName = res.fileName || `${session.source || 'session'}-${session.sessionId || Date.now()}.md`;
64
+ this.downloadTextFile(fileName, res.content || '');
65
+ if (res.truncated) {
66
+ const maxLabel = res.maxMessages === 'all' ? 'all' : res.maxMessages;
67
+ this.showMessage(`会话导出完成(已截断:最多 ${maxLabel} 条消息)`, 'info');
68
+ } else {
69
+ this.showMessage('操作成功', 'success');
70
+ }
71
+ } catch (e) {
72
+ this.showMessage('导出失败', 'error');
73
+ } finally {
74
+ this.sessionExporting[key] = false;
75
+ }
76
+ },
77
+
78
+ async quickSwitchProvider(name) {
79
+ const target = String(name || '').trim();
80
+ const visualTarget = String(this.providerSwitchDisplayTarget || '').trim();
81
+ if (!target || target === visualTarget || target === this.pendingProviderSwitch) {
82
+ return;
83
+ }
84
+ if (!this.providerSwitchInProgress && target === this.currentProvider) {
85
+ return;
86
+ }
87
+ await this.switchProvider(target);
88
+ },
89
+
90
+ async waitForCodexApplyIdle(maxWaitMs = 20000) {
91
+ const startedAt = Date.now();
92
+ while (this.codexApplying) {
93
+ if ((Date.now() - startedAt) > maxWaitMs) {
94
+ throw new Error('等待配置应用完成超时');
95
+ }
96
+ await new Promise((resolve) => setTimeout(resolve, 50));
97
+ }
98
+ },
99
+
100
+ async performProviderSwitch(name) {
101
+ await this.waitForCodexApplyIdle();
102
+ const previousProvider = this.currentProvider;
103
+ const previousModel = this.currentModel;
104
+ const previousModels = Array.isArray(this.models) ? [...this.models] : [];
105
+ const previousModelsSource = this.modelsSource;
106
+ const previousModelsHasCurrent = this.modelsHasCurrent;
107
+ // 切走前把上一个 provider 的 model 落到内存字典,避免切回时显示抖动。
108
+ if (previousProvider && typeof previousModel === 'string' && previousModel.trim() && previousModel !== '未设置') {
109
+ if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
110
+ this.currentModels[previousProvider] = previousModel.trim();
111
+ }
112
+ this.currentProvider = name;
113
+ // 立即按字典预填,让 UI 不出现空白;远端 /models 后台异步补齐。
114
+ const dictModel = typeof this.activeProviderModel === 'function'
115
+ ? this.activeProviderModel(name)
116
+ : '';
117
+ if (dictModel) {
118
+ this.currentModel = dictModel;
119
+ }
120
+ const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
121
+
122
+ // 不要把“切换提供商”强绑定到 /models 成功与否:
123
+ // 部分 OpenAI 兼容服务 /models 不可用或很慢,但用户仍希望一次点击即可完成切换。
124
+ // 这里做“短等待 + 后台补齐”:
125
+ // 1) 先启动 models 拉取(静默)
126
+ // 2) 给一个很短的窗口等待它完成,以便能立即选到第一个模型
127
+ // 3) 无论 models 是否成功,先应用 provider 切换
128
+ // 4) models 后续若补齐并发现当前 model 不在列表,则自动切到首个 model 并再应用一次
129
+ const modelsTask = this.loadModelsForProvider(name, { silentError: true })
130
+ .catch(() => {});
131
+
132
+ await Promise.race([modelsTask, delay(250)]);
133
+
134
+ // 只在“字典中没有该 provider 记录”时才允许 remote 首项覆盖,否则尊重用户上次选择。
135
+ if (!dictModel
136
+ && this.modelsSource === 'remote'
137
+ && this.models.length > 0
138
+ && !this.models.includes(this.currentModel)) {
139
+ this.currentModel = this.models[0];
140
+ this.modelsHasCurrent = true;
141
+ }
142
+
143
+ if (getProviderConfigModeMeta(this.configMode)) {
144
+ await this.waitForCodexApplyIdle();
145
+ await this.applyCodexConfigDirect({ silent: true });
146
+ }
147
+
148
+ await modelsTask;
149
+
150
+ if (this.currentProvider === name) {
151
+ if (!dictModel
152
+ && this.modelsSource === 'remote'
153
+ && this.models.length > 0
154
+ && !this.models.includes(this.currentModel)) {
155
+ this.currentModel = this.models[0];
156
+ this.modelsHasCurrent = true;
157
+ if (getProviderConfigModeMeta(this.configMode)) {
158
+ await this.waitForCodexApplyIdle();
159
+ await this.applyCodexConfigDirect({ silent: true });
160
+ }
161
+ }
162
+ }
163
+
164
+ if (typeof this.loadLocalBridgeExcluded === 'function') {
165
+ this.loadLocalBridgeExcluded();
166
+ }
167
+ },
168
+
169
+ async switchProvider(name) {
170
+ const target = String(name || '').trim();
171
+ if (!target) {
172
+ return;
173
+ }
174
+ if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
175
+ return;
176
+ }
177
+ this.providerSwitchDisplayTarget = target;
178
+ if (this.providerSwitchInProgress) {
179
+ this.pendingProviderSwitch = target;
180
+ return;
181
+ }
182
+ this.providerSwitchInProgress = true;
183
+ let lastError = '';
184
+ try {
185
+ this.pendingProviderSwitch = '';
186
+ const result = await runLatestOnlyQueue(target, {
187
+ perform: async (queuedTarget) => {
188
+ this.providerSwitchDisplayTarget = queuedTarget;
189
+ await this.performProviderSwitch(queuedTarget);
190
+ },
191
+ consumePending: () => {
192
+ const queued = this.pendingProviderSwitch;
193
+ this.pendingProviderSwitch = '';
194
+ return queued;
195
+ }
196
+ });
197
+ if (result && typeof result.lastError === 'string') {
198
+ lastError = result.lastError;
199
+ }
200
+ } finally {
201
+ this.providerSwitchInProgress = false;
202
+ this.pendingProviderSwitch = '';
203
+ this.providerSwitchDisplayTarget = '';
204
+ }
205
+ if (lastError) {
206
+ this.showMessage(lastError, 'error');
207
+ }
208
+ },
209
+
210
+ async onModelChange() {
211
+ const name = String(this.currentProvider || '').trim();
212
+ const model = typeof this.currentModel === 'string' ? this.currentModel.trim() : '';
213
+ if (name && model) {
214
+ if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
215
+ this.currentModels[name] = model;
216
+ }
217
+ await this.applyCodexConfigDirect();
218
+ },
219
+
220
+ async onServiceTierChange() {
221
+ await this.applyCodexConfigDirect({ silent: true });
222
+ },
223
+
224
+ async onReasoningEffortChange() {
225
+ await this.applyCodexConfigDirect({ silent: true });
226
+ },
227
+
228
+ sanitizePositiveIntegerDraft(field) {
229
+ if (!field || typeof this[field] === 'undefined') return;
230
+ const current = typeof this[field] === 'string'
231
+ ? this[field]
232
+ : String(this[field] || '');
233
+ const sanitized = current.replace(/[^\d]/g, '');
234
+ if (sanitized !== current) {
235
+ this[field] = sanitized;
236
+ }
237
+ },
238
+
239
+ normalizePositiveIntegerInput(value, label, fallback = '') {
240
+ const fallbackText = fallback === '' ? '' : String(fallback).trim();
241
+ const raw = typeof value === 'string'
242
+ ? value.trim()
243
+ : String(value == null ? '' : value).trim();
244
+ const text = raw || fallbackText;
245
+ if (!text) {
246
+ return { ok: true, value: null, text: '' };
247
+ }
248
+ if (!/^\d+$/.test(text)) {
249
+ return { ok: false, error: `${label} 请输入正整数` };
250
+ }
251
+ const num = Number.parseInt(text, 10);
252
+ if (!Number.isSafeInteger(num) || num <= 0) {
253
+ return { ok: false, error: `${label} 请输入正整数` };
254
+ }
255
+ return { ok: true, value: num, text: String(num) };
256
+ },
257
+
258
+ async onModelContextWindowBlur() {
259
+ this.editingCodexBudgetField = '';
260
+ const normalized = this.normalizePositiveIntegerInput(
261
+ this.modelContextWindowInput,
262
+ 'model_context_window',
263
+ defaultModelContextWindow
264
+ );
265
+ if (!normalized.ok) {
266
+ this.showMessage(normalized.error, 'error');
267
+ return;
268
+ }
269
+ this.modelContextWindowInput = normalized.text;
270
+ await this.applyCodexConfigDirect({
271
+ silent: true,
272
+ modelContextWindow: normalized.value
273
+ });
274
+ },
275
+
276
+ async onModelAutoCompactTokenLimitBlur() {
277
+ this.editingCodexBudgetField = '';
278
+ const normalized = this.normalizePositiveIntegerInput(
279
+ this.modelAutoCompactTokenLimitInput,
280
+ 'model_auto_compact_token_limit',
281
+ defaultModelAutoCompactTokenLimit
282
+ );
283
+ if (!normalized.ok) {
284
+ this.showMessage(normalized.error, 'error');
285
+ return;
286
+ }
287
+ this.modelAutoCompactTokenLimitInput = normalized.text;
288
+ await this.applyCodexConfigDirect({
289
+ silent: true,
290
+ modelAutoCompactTokenLimit: normalized.value
291
+ });
292
+ },
293
+
294
+ async resetCodexContextBudgetDefaults() {
295
+ this.modelContextWindowInput = String(defaultModelContextWindow);
296
+ this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
297
+ await this.applyCodexConfigDirect({
298
+ modelContextWindow: defaultModelContextWindow,
299
+ modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
300
+ });
301
+ },
302
+
303
+ async runHealthCheck(options = {}) {
304
+ this.healthCheckLoading = true;
305
+ this.healthCheckResult = null;
306
+ this.healthCheckBatchTotal = 0;
307
+ this.healthCheckBatchDone = 0;
308
+ this.healthCheckBatchFailed = 0;
309
+ try {
310
+ const silent = !!(options && options.silent);
311
+ const forceRefresh = !!(options && options.forceRefresh);
312
+ const useDoctor = !!(options && options.doctor);
313
+ if (useDoctor) {
314
+ const res = await api('doctor', {
315
+ lang: this.lang,
316
+ remote: true,
317
+ range: this.sessionsUsageTimeRange,
318
+ targetApp: this.skillsTargetApp,
319
+ includeUsage: true,
320
+ includeTasks: true,
321
+ includeSkills: true,
322
+ includeInstall: true,
323
+ forceRefresh
324
+ });
325
+ if (hasResponseError(res)) {
326
+ this.healthCheckResult = null;
327
+ if (!silent) {
328
+ this.showMessage(getResponseMessage(res, '检查失败'), 'error');
329
+ }
330
+ return;
331
+ }
332
+ if (res && typeof res === 'object') {
333
+ this.healthCheckResult = res;
334
+ const report = res.report && typeof res.report === 'object' ? res.report : null;
335
+ const summary = report && report.summary && typeof report.summary === 'object' ? report.summary : null;
336
+ const total = summary && Number.isFinite(Number(summary.total))
337
+ ? Math.max(0, Math.floor(Number(summary.total)))
338
+ : (Array.isArray(res.issues) ? res.issues.length : 0);
339
+ const errors = summary && Number.isFinite(Number(summary.error)) ? Math.max(0, Math.floor(Number(summary.error))) : 0;
340
+ const warns = summary && Number.isFinite(Number(summary.warn)) ? Math.max(0, Math.floor(Number(summary.warn))) : 0;
341
+ this.healthCheckBatchTotal = total;
342
+ this.healthCheckBatchDone = total;
343
+ this.healthCheckBatchFailed = errors + warns;
344
+ if (!silent && res.ok) {
345
+ this.showMessage('检查通过', 'success');
346
+ }
347
+ return;
348
+ }
349
+ this.healthCheckResult = null;
350
+ if (!silent) {
351
+ this.showMessage('检查失败', 'error');
352
+ }
353
+ return;
354
+ }
355
+
356
+ if (this.configMode === 'claude') {
357
+ const entries = Object.entries(this.claudeConfigs || {});
358
+ this.healthCheckBatchTotal = entries.length;
359
+
360
+ const speedTasks = entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)
361
+ .then((result) => {
362
+ if (!result || result.ok !== true) {
363
+ this.healthCheckBatchFailed += 1;
364
+ }
365
+ return { name, result };
366
+ })
367
+ .catch((err) => {
368
+ this.healthCheckBatchFailed += 1;
369
+ return {
370
+ name,
371
+ result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
372
+ };
373
+ })
374
+ .finally(() => {
375
+ this.healthCheckBatchDone += 1;
376
+ })
377
+ );
378
+
379
+ const pairs = await Promise.all(speedTasks);
380
+ const results = {};
381
+ const issues = [];
382
+ for (const pair of pairs) {
383
+ results[pair.name] = pair.result || null;
384
+ if (typeof this.buildSpeedTestIssue === 'function') {
385
+ const issue = this.buildSpeedTestIssue(pair.name, pair.result);
386
+ if (issue) issues.push(issue);
387
+ }
388
+ }
389
+ const ok = issues.length === 0 && this.healthCheckBatchFailed === 0;
390
+ this.healthCheckResult = {
391
+ ok,
392
+ issues,
393
+ remote: {
394
+ type: 'speed-test',
395
+ speedTests: results
396
+ }
397
+ };
398
+ if (ok && !silent) {
399
+ this.showMessage('检查通过', 'success');
400
+ }
401
+ return;
402
+ }
403
+
404
+ const shouldRunSpeedTests = this.configMode === 'codex';
405
+ const speedTimeoutMs = shouldRunSpeedTests ? 3500 : 0;
406
+ const providers = shouldRunSpeedTests
407
+ ? (this.providersList || [])
408
+ .map((provider) => typeof provider === 'string'
409
+ ? provider.trim()
410
+ : String((provider && provider.name) || '').trim())
411
+ .filter(Boolean)
412
+ : [];
413
+ const currentProvider = String(this.currentProvider || '').trim();
414
+ const orderedProviders = currentProvider && providers.includes(currentProvider)
415
+ ? [currentProvider, ...providers.filter((name) => name !== currentProvider)]
416
+ : providers;
417
+ this.healthCheckBatchTotal = orderedProviders.length;
418
+
419
+ const speedTasks = orderedProviders.map((provider) => this.runSpeedTest(provider, { silent: true, timeoutMs: speedTimeoutMs })
420
+ .then((result) => {
421
+ if (!result || result.ok !== true) {
422
+ this.healthCheckBatchFailed += 1;
423
+ }
424
+ return { name: provider, result };
425
+ })
426
+ .catch((err) => {
427
+ this.healthCheckBatchFailed += 1;
428
+ return {
429
+ name: provider,
430
+ result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
431
+ };
432
+ })
433
+ .finally(() => {
434
+ this.healthCheckBatchDone += 1;
435
+ })
436
+ );
437
+
438
+ const configTask = api('config-health-check', { remote: this.configMode === 'codex' });
439
+ const [res, pairs] = await Promise.all([
440
+ configTask,
441
+ Promise.all(speedTasks)
442
+ ]);
443
+ if (hasResponseError(res)) {
444
+ this.healthCheckResult = null;
445
+ if (!silent) {
446
+ this.showMessage(getResponseMessage(res, '检查失败'), 'error');
447
+ }
448
+ } else if (res && typeof res === 'object') {
449
+ const issues = Array.isArray(res.issues) ? [...res.issues] : [];
450
+ let remote = res.remote || null;
451
+ if (shouldRunSpeedTests) {
452
+ const results = {};
453
+ for (const pair of pairs) {
454
+ results[pair.name] = pair.result || null;
455
+ const issue = this.buildSpeedTestIssue(pair.name, pair.result);
456
+ if (issue) issues.push(issue);
457
+ }
458
+ remote = remote && typeof remote === 'object'
459
+ ? { ...remote, speedTests: results }
460
+ : { type: 'speed-test', speedTests: results };
461
+ }
462
+
463
+ const ok = issues.length === 0;
464
+ this.healthCheckResult = {
465
+ ...res,
466
+ ok,
467
+ issues,
468
+ remote
469
+ };
470
+ if (ok && !silent) {
471
+ this.showMessage('检查通过', 'success');
472
+ }
473
+ } else {
474
+ this.healthCheckResult = null;
475
+ if (!silent) {
476
+ this.showMessage('检查失败', 'error');
477
+ }
478
+ }
479
+ } catch (e) {
480
+ this.healthCheckResult = null;
481
+ if (!(options && options.silent)) {
482
+ this.showMessage('检查失败', 'error');
483
+ }
484
+ } finally {
485
+ this.healthCheckBatchTotal = this.healthCheckBatchTotal || 0;
486
+ this.healthCheckBatchDone = Math.min(this.healthCheckBatchDone || 0, this.healthCheckBatchTotal || 0);
487
+ this.healthCheckLoading = false;
488
+ if (typeof this.runProvidersHealthCheck === 'function' && this.configMode === 'codex') {
489
+ void this.runProvidersHealthCheck({ remote: true });
490
+ }
491
+ }
492
+ },
493
+
494
+ async runProvidersHealthCheck(options = {}) {
495
+ this.providersHealthLoading = true;
496
+ try {
497
+ const res = await api('providers-health', {
498
+ remote: options.remote !== false
499
+ });
500
+ if (res && typeof res === 'object' && !res.error) {
501
+ this.providersHealthResult = res;
502
+ } else {
503
+ this.providersHealthResult = null;
504
+ }
505
+ } catch (e) {
506
+ this.providersHealthResult = null;
507
+ } finally {
508
+ this.providersHealthLoading = false;
509
+ }
510
+ },
511
+
512
+ escapeTomlString(value) {
513
+ return String(value || '')
514
+ .replace(/\\/g, '\\\\')
515
+ .replace(/"/g, '\\"');
516
+ },
517
+
518
+ async openConfigTemplateEditor(options = {}) {
519
+ this.resetConfigTemplateDiffState();
520
+ const modelContextWindow = this.normalizePositiveIntegerInput(
521
+ this.modelContextWindowInput,
522
+ 'model_context_window',
523
+ defaultModelContextWindow
524
+ );
525
+ if (!modelContextWindow.ok) {
526
+ this.showMessage(modelContextWindow.error, 'error');
527
+ return;
528
+ }
529
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
530
+ this.modelAutoCompactTokenLimitInput,
531
+ 'model_auto_compact_token_limit',
532
+ defaultModelAutoCompactTokenLimit
533
+ );
534
+ if (!modelAutoCompactTokenLimit.ok) {
535
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
536
+ return;
537
+ }
538
+ try {
539
+ const res = await api('get-config-template', {
540
+ provider: this.currentProvider,
541
+ model: this.currentModel,
542
+ serviceTier: this.serviceTier,
543
+ reasoningEffort: this.modelReasoningEffort,
544
+ modelContextWindow: modelContextWindow.value,
545
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
546
+ });
547
+ if (res.error) {
548
+ this.showMessage(res.error, 'error');
549
+ return;
550
+ }
551
+ let template = res.template || '';
552
+ const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
553
+ const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
554
+ if (appendHint) {
555
+ template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
556
+ }
557
+ if (appendBlock) {
558
+ template = `${template.trimEnd()}\n\n${appendBlock}\n`;
559
+ }
560
+ this.configTemplateContent = template;
561
+ this.showConfigTemplateModal = true;
562
+ } catch (e) {
563
+ this.showMessage('加载模板失败', 'error');
564
+ }
565
+ },
566
+
567
+ async applyCodexConfigDirect(options = {}) {
568
+ if (this.codexApplying) {
569
+ this._pendingCodexApplyOptions = {
570
+ ...(this._pendingCodexApplyOptions || {}),
571
+ ...options
572
+ };
573
+ return;
574
+ }
575
+
576
+ const provider = (this.currentProvider || '').trim();
577
+ const model = (this.currentModel || '').trim();
578
+ if (!provider || !model) {
579
+ this.showMessage('请选择提供商和模型', 'error');
580
+ return;
581
+ }
582
+
583
+ const modelContextWindow = this.normalizePositiveIntegerInput(
584
+ options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
585
+ 'model_context_window',
586
+ defaultModelContextWindow
587
+ );
588
+ if (!modelContextWindow.ok) {
589
+ this.showMessage(modelContextWindow.error, 'error');
590
+ return;
591
+ }
592
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
593
+ options.modelAutoCompactTokenLimit !== undefined
594
+ ? options.modelAutoCompactTokenLimit
595
+ : this.modelAutoCompactTokenLimitInput,
596
+ 'model_auto_compact_token_limit',
597
+ defaultModelAutoCompactTokenLimit
598
+ );
599
+ if (!modelAutoCompactTokenLimit.ok) {
600
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
601
+ return;
602
+ }
603
+ this.modelContextWindowInput = modelContextWindow.text;
604
+ this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
605
+
606
+ const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
607
+
608
+ this.codexApplying = true;
609
+ try {
610
+ const tplRes = await api('get-config-template', {
611
+ provider,
612
+ model,
613
+ serviceTier: this.serviceTier,
614
+ reasoningEffort: this.modelReasoningEffort,
615
+ modelContextWindow: modelContextWindow.value,
616
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
617
+ });
618
+ if (tplRes.error) {
619
+ this.showMessage(
620
+ (typeof tplRes.error === 'string' && tplRes.error.trim())
621
+ || (typeof tplRes.message === 'string' && tplRes.message.trim())
622
+ || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
623
+ || '获取模板失败',
624
+ 'error'
625
+ );
626
+ return;
627
+ }
628
+
629
+ const applyRes = await api('apply-config-template', {
630
+ template: tplRes.template
631
+ });
632
+ if (applyRes.error) {
633
+ this.showMessage(
634
+ (typeof applyRes.error === 'string' && applyRes.error.trim())
635
+ || (typeof applyRes.message === 'string' && applyRes.message.trim())
636
+ || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
637
+ || '应用模板失败',
638
+ 'error'
639
+ );
640
+ return;
641
+ }
642
+
643
+ if (options.silent !== true) {
644
+ if (this._lastAppliedCodexKey !== _codexKey) {
645
+ this.showMessage('配置已应用', 'success');
646
+ this._lastAppliedCodexKey = _codexKey;
647
+ }
648
+ } else {
649
+ this._lastAppliedCodexKey = _codexKey;
650
+ }
651
+
652
+ const refreshOptions = options.silent === true
653
+ ? { preserveLoading: true }
654
+ : {};
655
+ try {
656
+ await this.loadAll(refreshOptions);
657
+ } catch (_) {
658
+ this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
659
+ }
660
+ } catch (e) {
661
+ this.showMessage('应用失败', 'error');
662
+ } finally {
663
+ this.codexApplying = false;
664
+ const pendingOptions = this._pendingCodexApplyOptions;
665
+ this._pendingCodexApplyOptions = null;
666
+ if (pendingOptions) {
667
+ await this.applyCodexConfigDirect(pendingOptions);
668
+ }
669
+ }
670
+ },
671
+
672
+ closeConfigTemplateModal(options = {}) {
673
+ const force = !!options.force;
674
+ if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
675
+ return;
676
+ }
677
+ this.showConfigTemplateModal = false;
678
+ this.configTemplateContent = '';
679
+ this.resetConfigTemplateDiffState();
680
+ },
681
+
682
+ resetConfigTemplateDiffState() {
683
+ this.configTemplateDiffVisible = false;
684
+ this.configTemplateDiffLoading = false;
685
+ this.configTemplateDiffError = '';
686
+ this.configTemplateDiffLines = [];
687
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
688
+ this.configTemplateDiffHasChangesValue = false;
689
+ this.configTemplateDiffFingerprint = '';
690
+ this._configTemplateDiffPreviewRequestToken = null;
691
+ },
692
+
693
+ onConfigTemplateContentInput() {
694
+ if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
695
+ this.resetConfigTemplateDiffState();
696
+ }
697
+ },
698
+
699
+ async pasteConfigTemplateContent() {
700
+ if (this.configTemplateApplying || this.configTemplateDiffLoading || this.configTemplateDiffVisible) {
701
+ return;
702
+ }
703
+ let text = '';
704
+ try {
705
+ text = await navigator.clipboard.readText();
706
+ } catch (_) {
707
+ this.showMessage('无法读取剪贴板', 'error');
708
+ return;
709
+ }
710
+ if (typeof text !== 'string' || !text) {
711
+ this.showMessage('剪贴板为空', 'info');
712
+ return;
713
+ }
714
+ this.configTemplateContent = text;
715
+ this.onConfigTemplateContentInput();
716
+ this.showMessage('已粘贴', 'success');
717
+ },
718
+
719
+ buildConfigTemplateDiffFingerprint() {
720
+ const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
721
+ return `${content.length}::${content}`;
722
+ },
723
+
724
+ hasConfigTemplateDiffChanges() {
725
+ if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
726
+ return !!this.configTemplateDiffHasChangesValue;
727
+ }
728
+ const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
729
+ ? this.configTemplateDiffStats
730
+ : {};
731
+ const added = Number(stats.added || 0);
732
+ const removed = Number(stats.removed || 0);
733
+ return added > 0 || removed > 0;
734
+ },
735
+
736
+ async prepareConfigTemplateDiff() {
737
+ const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
738
+ const requestToken = Symbol('config-template-diff-preview');
739
+ this._configTemplateDiffPreviewRequestToken = requestToken;
740
+ this.configTemplateDiffVisible = true;
741
+ this.configTemplateDiffLoading = true;
742
+ this.configTemplateDiffError = '';
743
+ this.configTemplateDiffLines = [];
744
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
745
+ this.configTemplateDiffHasChangesValue = false;
746
+ try {
747
+ const shouldApply = () => (
748
+ this.configTemplateDiffVisible
749
+ && this._configTemplateDiffPreviewRequestToken === requestToken
750
+ && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
751
+ );
752
+ const res = await api('preview-config-template-diff', {
753
+ template: this.configTemplateContent
754
+ });
755
+ if (!shouldApply()) {
756
+ return;
757
+ }
758
+ if (res.error) {
759
+ this.configTemplateDiffError = res.error;
760
+ return;
761
+ }
762
+ const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
763
+ const lines = Array.isArray(diff.lines) ? diff.lines : [];
764
+ this.configTemplateDiffLines = lines.filter(line => line && line.type);
765
+ const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
766
+ if (stats) {
767
+ this.configTemplateDiffStats = {
768
+ added: Number(stats.added || 0),
769
+ removed: Number(stats.removed || 0),
770
+ unchanged: Number(stats.unchanged || 0)
771
+ };
772
+ } else {
773
+ const nextStats = { added: 0, removed: 0, unchanged: 0 };
774
+ for (const line of this.configTemplateDiffLines) {
775
+ if (line && line.type === 'add') nextStats.added += 1;
776
+ else if (line && line.type === 'del') nextStats.removed += 1;
777
+ else nextStats.unchanged += 1;
778
+ }
779
+ this.configTemplateDiffStats = nextStats;
780
+ }
781
+ this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
782
+ this.configTemplateDiffFingerprint = requestFingerprint;
783
+ } catch (_) {
784
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
785
+ this.configTemplateDiffError = '生成差异失败';
786
+ }
787
+ } finally {
788
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
789
+ this.configTemplateDiffLoading = false;
790
+ }
791
+ }
792
+ },
793
+
794
+ async applyConfigTemplate() {
795
+ if (this.configTemplateApplying) {
796
+ return;
797
+ }
798
+ if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
799
+ this.showMessage('模板不能为空', 'error');
800
+ return;
801
+ }
802
+
803
+ // Default to two-step confirmation when the setting is unset.
804
+ // (The normalize helper lives in session-actions; keep a safe fallback here.)
805
+ const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
806
+
807
+ const performApply = async () => {
808
+ this.configTemplateApplying = true;
809
+ try {
810
+ const res = await api('apply-config-template', {
811
+ template: this.configTemplateContent
812
+ });
813
+ if (res.error) {
814
+ this.showMessage(res.error, 'error');
815
+ return;
816
+ }
817
+ this.showMessage('模板已应用', 'success');
818
+ this.closeConfigTemplateModal({ force: true });
819
+ try {
820
+ await this.loadAll();
821
+ } catch (_) {
822
+ this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
823
+ }
824
+ } catch (e) {
825
+ this.showMessage('应用模板失败', 'error');
826
+ } finally {
827
+ this.configTemplateApplying = false;
828
+ }
829
+ };
830
+
831
+ // One-step mode: apply immediately unless user explicitly entered the diff preview state.
832
+ if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
833
+ await performApply();
834
+ return;
835
+ }
836
+
837
+ if (!this.configTemplateDiffVisible) {
838
+ await this.prepareConfigTemplateDiff();
839
+ return;
840
+ }
841
+ if (this.configTemplateDiffLoading) {
842
+ return;
843
+ }
844
+ if (this.configTemplateDiffError) {
845
+ this.showMessage(this.configTemplateDiffError, 'error');
846
+ return;
847
+ }
848
+ const fingerprint = this.buildConfigTemplateDiffFingerprint();
849
+ if (this.configTemplateDiffFingerprint !== fingerprint) {
850
+ await this.prepareConfigTemplateDiff();
851
+ return;
852
+ }
853
+ if (!this.hasConfigTemplateDiffChanges()) {
854
+ this.showMessage('未检测到改动', 'info');
855
+ return;
856
+ }
857
+
858
+ await performApply();
859
+ }
860
+ };
861
+ }