codexmate 0.0.41 → 0.0.42

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 (155) hide show
  1. package/README.md +168 -168
  2. package/README.zh.md +168 -168
  3. package/cli/agents-files.js +230 -230
  4. package/cli/analytics-export-args.js +68 -68
  5. package/cli/archive-helpers.js +453 -453
  6. package/cli/auth-profiles.js +375 -375
  7. package/cli/builtin-proxy.js +2144 -2144
  8. package/cli/claude-proxy.js +1022 -1022
  9. package/cli/config-bootstrap.js +407 -407
  10. package/cli/config-health.js +454 -454
  11. package/cli/doctor-core.js +903 -903
  12. package/cli/import-skills-url.js +356 -356
  13. package/cli/local-bridge.js +556 -556
  14. package/cli/openai-bridge.js +1984 -1984
  15. package/cli/openclaw-config.js +629 -629
  16. package/cli/session-convert-args.js +69 -69
  17. package/cli/session-convert-io.js +82 -82
  18. package/cli/session-convert.js +150 -150
  19. package/cli/session-usage.concurrent.js +28 -28
  20. package/cli/session-usage.js +304 -304
  21. package/cli/session-usage.models.js +176 -176
  22. package/cli/skills.js +1141 -1141
  23. package/cli/update.js +171 -171
  24. package/cli/zip-commands.js +510 -510
  25. package/cli.js +16494 -16458
  26. package/lib/automation.js +404 -404
  27. package/lib/cli-file-utils.js +151 -151
  28. package/lib/cli-models-utils.js +440 -440
  29. package/lib/cli-network-utils.js +190 -190
  30. package/lib/cli-path-utils.js +85 -85
  31. package/lib/cli-session-utils.js +121 -121
  32. package/lib/cli-sessions.js +427 -427
  33. package/lib/cli-utils.js +155 -155
  34. package/lib/cli-webhook.js +154 -154
  35. package/lib/download-artifacts.js +92 -92
  36. package/lib/mcp-stdio.js +453 -453
  37. package/lib/task-orchestrator.js +869 -869
  38. package/lib/text-diff.js +303 -303
  39. package/lib/win-tray.js +119 -119
  40. package/lib/workflow-engine.js +340 -340
  41. package/package.json +77 -77
  42. package/plugins/README.md +20 -20
  43. package/plugins/README.zh-CN.md +20 -20
  44. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  45. package/plugins/prompt-templates/computed.mjs +311 -311
  46. package/plugins/prompt-templates/index.mjs +8 -8
  47. package/plugins/prompt-templates/manifest.mjs +18 -18
  48. package/plugins/prompt-templates/methods.mjs +553 -553
  49. package/plugins/prompt-templates/overview.mjs +91 -91
  50. package/plugins/prompt-templates/ownership.mjs +19 -19
  51. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  52. package/plugins/prompt-templates/storage.mjs +64 -64
  53. package/plugins/registry.mjs +16 -16
  54. package/web-ui/app.js +695 -695
  55. package/web-ui/index.html +37 -37
  56. package/web-ui/logic.agents-diff.mjs +386 -386
  57. package/web-ui/logic.claude.mjs +172 -172
  58. package/web-ui/logic.codex.mjs +69 -69
  59. package/web-ui/logic.mjs +5 -5
  60. package/web-ui/logic.runtime.mjs +128 -128
  61. package/web-ui/logic.session-convert.mjs +70 -70
  62. package/web-ui/logic.sessions.mjs +782 -782
  63. package/web-ui/modules/api.mjs +90 -90
  64. package/web-ui/modules/app.computed.dashboard.mjs +252 -252
  65. package/web-ui/modules/app.computed.index.mjs +17 -17
  66. package/web-ui/modules/app.computed.main-tabs.mjs +214 -214
  67. package/web-ui/modules/app.computed.session.mjs +876 -876
  68. package/web-ui/modules/app.constants.mjs +15 -15
  69. package/web-ui/modules/app.methods.agents.mjs +651 -651
  70. package/web-ui/modules/app.methods.claude-config.mjs +412 -412
  71. package/web-ui/modules/app.methods.codex-config.mjs +869 -869
  72. package/web-ui/modules/app.methods.index.mjs +96 -96
  73. package/web-ui/modules/app.methods.install.mjs +205 -205
  74. package/web-ui/modules/app.methods.navigation.mjs +804 -804
  75. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  76. package/web-ui/modules/app.methods.openclaw-editing.mjs +420 -420
  77. package/web-ui/modules/app.methods.openclaw-persist.mjs +375 -375
  78. package/web-ui/modules/app.methods.providers.mjs +601 -601
  79. package/web-ui/modules/app.methods.runtime.mjs +420 -420
  80. package/web-ui/modules/app.methods.session-actions.mjs +617 -591
  81. package/web-ui/modules/app.methods.session-browser.mjs +1018 -1018
  82. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  83. package/web-ui/modules/app.methods.session-trash.mjs +468 -468
  84. package/web-ui/modules/app.methods.startup-claude.mjs +554 -554
  85. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  86. package/web-ui/modules/app.methods.tool-config-permissions.mjs +87 -87
  87. package/web-ui/modules/app.methods.webhook.mjs +87 -87
  88. package/web-ui/modules/config-mode.computed.mjs +124 -124
  89. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  90. package/web-ui/modules/i18n/locales/en.mjs +1141 -1140
  91. package/web-ui/modules/i18n/locales/ja.mjs +1132 -1130
  92. package/web-ui/modules/i18n/locales/vi.mjs +239 -239
  93. package/web-ui/modules/i18n/locales/zh.mjs +1144 -1143
  94. package/web-ui/modules/i18n.dict.mjs +14 -14
  95. package/web-ui/modules/i18n.mjs +111 -111
  96. package/web-ui/modules/plugins.computed.mjs +3 -3
  97. package/web-ui/modules/plugins.methods.mjs +3 -3
  98. package/web-ui/modules/plugins.storage.mjs +11 -11
  99. package/web-ui/modules/provider-url-display.mjs +17 -17
  100. package/web-ui/modules/sessions-filters-url.mjs +138 -138
  101. package/web-ui/modules/skills.computed.mjs +107 -107
  102. package/web-ui/modules/skills.methods.mjs +513 -513
  103. package/web-ui/partials/index/layout-footer.html +13 -13
  104. package/web-ui/partials/index/layout-header.html +478 -478
  105. package/web-ui/partials/index/modal-config-template-agents.html +185 -185
  106. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  107. package/web-ui/partials/index/modal-health-check.html +45 -45
  108. package/web-ui/partials/index/modal-openclaw-config.html +344 -344
  109. package/web-ui/partials/index/modal-skills.html +200 -200
  110. package/web-ui/partials/index/modal-webhook.html +42 -42
  111. package/web-ui/partials/index/modals-basic.html +263 -263
  112. package/web-ui/partials/index/panel-config-claude.html +187 -187
  113. package/web-ui/partials/index/panel-config-codex.html +205 -205
  114. package/web-ui/partials/index/panel-config-openclaw.html +89 -89
  115. package/web-ui/partials/index/panel-dashboard.html +171 -171
  116. package/web-ui/partials/index/panel-docs.html +114 -114
  117. package/web-ui/partials/index/panel-market.html +104 -104
  118. package/web-ui/partials/index/panel-orchestration.html +391 -391
  119. package/web-ui/partials/index/panel-plugins.html +253 -253
  120. package/web-ui/partials/index/panel-sessions.html +325 -319
  121. package/web-ui/partials/index/panel-settings.html +181 -181
  122. package/web-ui/partials/index/panel-trash.html +82 -82
  123. package/web-ui/partials/index/panel-usage.html +181 -181
  124. package/web-ui/res/json5.min.js +1 -1
  125. package/web-ui/res/vue.global.prod.js +13 -13
  126. package/web-ui/res/vue.runtime.global.prod.js +7 -7
  127. package/web-ui/res/web-ui-render.precompiled.js +7671 -7666
  128. package/web-ui/session-helpers.mjs +602 -602
  129. package/web-ui/source-bundle.cjs +305 -305
  130. package/web-ui/styles/base-theme.css +291 -291
  131. package/web-ui/styles/bridge-pool.css +266 -266
  132. package/web-ui/styles/controls-forms.css +532 -532
  133. package/web-ui/styles/dashboard.css +438 -438
  134. package/web-ui/styles/docs-panel.css +245 -245
  135. package/web-ui/styles/feedback.css +108 -108
  136. package/web-ui/styles/health-check-dialog.css +144 -144
  137. package/web-ui/styles/layout-shell.css +711 -711
  138. package/web-ui/styles/modals-core.css +499 -499
  139. package/web-ui/styles/navigation-panels.css +399 -399
  140. package/web-ui/styles/openclaw-structured.css +616 -616
  141. package/web-ui/styles/plugins-panel.css +564 -564
  142. package/web-ui/styles/responsive.css +501 -501
  143. package/web-ui/styles/sessions-list.css +683 -683
  144. package/web-ui/styles/sessions-preview.css +407 -407
  145. package/web-ui/styles/sessions-toolbar-trash.css +518 -518
  146. package/web-ui/styles/sessions-usage.css +849 -849
  147. package/web-ui/styles/settings-panel.css +419 -419
  148. package/web-ui/styles/skills-list.css +305 -305
  149. package/web-ui/styles/skills-market.css +723 -723
  150. package/web-ui/styles/task-orchestration.css +822 -822
  151. package/web-ui/styles/titles-cards.css +486 -486
  152. package/web-ui/styles/trash-panel.css +90 -90
  153. package/web-ui/styles/webhook.css +115 -115
  154. package/web-ui/styles.css +24 -24
  155. package/web-ui.html +17 -17
@@ -1,869 +1,869 @@
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.configTemplateContext = 'codex';
562
- this.showConfigTemplateModal = true;
563
- } catch (e) {
564
- this.showMessage('加载模板失败', 'error');
565
- }
566
- },
567
-
568
- async applyCodexConfigDirect(options = {}) {
569
- if (this.codexApplying) {
570
- this._pendingCodexApplyOptions = {
571
- ...(this._pendingCodexApplyOptions || {}),
572
- ...options
573
- };
574
- return;
575
- }
576
-
577
- const provider = (this.currentProvider || '').trim();
578
- const model = (this.currentModel || '').trim();
579
- if (!provider || !model) {
580
- this.showMessage('请选择提供商和模型', 'error');
581
- return;
582
- }
583
-
584
- const modelContextWindow = this.normalizePositiveIntegerInput(
585
- options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
586
- 'model_context_window',
587
- defaultModelContextWindow
588
- );
589
- if (!modelContextWindow.ok) {
590
- this.showMessage(modelContextWindow.error, 'error');
591
- return;
592
- }
593
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
594
- options.modelAutoCompactTokenLimit !== undefined
595
- ? options.modelAutoCompactTokenLimit
596
- : this.modelAutoCompactTokenLimitInput,
597
- 'model_auto_compact_token_limit',
598
- defaultModelAutoCompactTokenLimit
599
- );
600
- if (!modelAutoCompactTokenLimit.ok) {
601
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
602
- return;
603
- }
604
- this.modelContextWindowInput = modelContextWindow.text;
605
- this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
606
-
607
- const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
608
-
609
- this.codexApplying = true;
610
- try {
611
- const tplRes = await api('get-config-template', {
612
- provider,
613
- model,
614
- serviceTier: this.serviceTier,
615
- reasoningEffort: this.modelReasoningEffort,
616
- modelContextWindow: modelContextWindow.value,
617
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
618
- });
619
- if (tplRes.error) {
620
- this.showMessage(
621
- (typeof tplRes.error === 'string' && tplRes.error.trim())
622
- || (typeof tplRes.message === 'string' && tplRes.message.trim())
623
- || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
624
- || '获取模板失败',
625
- 'error'
626
- );
627
- return;
628
- }
629
-
630
- const applyRes = await api('apply-config-template', {
631
- template: tplRes.template
632
- });
633
- if (applyRes.error) {
634
- this.showMessage(
635
- (typeof applyRes.error === 'string' && applyRes.error.trim())
636
- || (typeof applyRes.message === 'string' && applyRes.message.trim())
637
- || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
638
- || '应用模板失败',
639
- 'error'
640
- );
641
- return;
642
- }
643
-
644
- if (options.silent !== true) {
645
- if (this._lastAppliedCodexKey !== _codexKey) {
646
- this.showMessage('配置已应用', 'success');
647
- this._lastAppliedCodexKey = _codexKey;
648
- }
649
- } else {
650
- this._lastAppliedCodexKey = _codexKey;
651
- }
652
-
653
- const refreshOptions = options.silent === true
654
- ? { preserveLoading: true }
655
- : {};
656
- try {
657
- await this.loadAll(refreshOptions);
658
- } catch (_) {
659
- this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
660
- }
661
- } catch (e) {
662
- this.showMessage('应用失败', 'error');
663
- } finally {
664
- this.codexApplying = false;
665
- const pendingOptions = this._pendingCodexApplyOptions;
666
- this._pendingCodexApplyOptions = null;
667
- if (pendingOptions) {
668
- await this.applyCodexConfigDirect(pendingOptions);
669
- }
670
- }
671
- },
672
-
673
- closeConfigTemplateModal(options = {}) {
674
- const force = !!options.force;
675
- if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
676
- return;
677
- }
678
- this.showConfigTemplateModal = false;
679
- this.configTemplateContent = '';
680
- this.resetConfigTemplateDiffState();
681
- },
682
-
683
- resetConfigTemplateDiffState() {
684
- this.configTemplateDiffVisible = false;
685
- this.configTemplateDiffLoading = false;
686
- this.configTemplateDiffError = '';
687
- this.configTemplateDiffLines = [];
688
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
689
- this.configTemplateDiffHasChangesValue = false;
690
- this.configTemplateDiffFingerprint = '';
691
- this._configTemplateDiffPreviewRequestToken = null;
692
- },
693
-
694
- onConfigTemplateContentInput() {
695
- if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
696
- this.resetConfigTemplateDiffState();
697
- }
698
- },
699
-
700
- async pasteConfigTemplateContent() {
701
- if (this.configTemplateApplying || this.configTemplateDiffLoading || this.configTemplateDiffVisible) {
702
- return;
703
- }
704
- let text = '';
705
- try {
706
- text = await navigator.clipboard.readText();
707
- } catch (_) {
708
- this.showMessage('无法读取剪贴板', 'error');
709
- return;
710
- }
711
- if (typeof text !== 'string' || !text) {
712
- this.showMessage('剪贴板为空', 'info');
713
- return;
714
- }
715
- this.configTemplateContent = text;
716
- this.onConfigTemplateContentInput();
717
- this.showMessage('已粘贴', 'success');
718
- },
719
-
720
- buildConfigTemplateDiffFingerprint() {
721
- const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
722
- return `${content.length}::${content}`;
723
- },
724
-
725
- hasConfigTemplateDiffChanges() {
726
- if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
727
- return !!this.configTemplateDiffHasChangesValue;
728
- }
729
- const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
730
- ? this.configTemplateDiffStats
731
- : {};
732
- const added = Number(stats.added || 0);
733
- const removed = Number(stats.removed || 0);
734
- return added > 0 || removed > 0;
735
- },
736
-
737
- async prepareConfigTemplateDiff() {
738
- const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
739
- const requestToken = Symbol('config-template-diff-preview');
740
- this._configTemplateDiffPreviewRequestToken = requestToken;
741
- this.configTemplateDiffVisible = true;
742
- this.configTemplateDiffLoading = true;
743
- this.configTemplateDiffError = '';
744
- this.configTemplateDiffLines = [];
745
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
746
- this.configTemplateDiffHasChangesValue = false;
747
- try {
748
- const shouldApply = () => (
749
- this.configTemplateDiffVisible
750
- && this._configTemplateDiffPreviewRequestToken === requestToken
751
- && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
752
- );
753
- const res = await api('preview-config-template-diff', {
754
- template: this.configTemplateContent
755
- });
756
- if (!shouldApply()) {
757
- return;
758
- }
759
- if (res.error) {
760
- this.configTemplateDiffError = res.error;
761
- return;
762
- }
763
- const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
764
- const lines = Array.isArray(diff.lines) ? diff.lines : [];
765
- this.configTemplateDiffLines = lines.filter(line => line && line.type);
766
- const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
767
- if (stats) {
768
- this.configTemplateDiffStats = {
769
- added: Number(stats.added || 0),
770
- removed: Number(stats.removed || 0),
771
- unchanged: Number(stats.unchanged || 0)
772
- };
773
- } else {
774
- const nextStats = { added: 0, removed: 0, unchanged: 0 };
775
- for (const line of this.configTemplateDiffLines) {
776
- if (line && line.type === 'add') nextStats.added += 1;
777
- else if (line && line.type === 'del') nextStats.removed += 1;
778
- else nextStats.unchanged += 1;
779
- }
780
- this.configTemplateDiffStats = nextStats;
781
- }
782
- this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
783
- this.configTemplateDiffFingerprint = requestFingerprint;
784
- } catch (_) {
785
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
786
- this.configTemplateDiffError = '生成差异失败';
787
- }
788
- } finally {
789
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
790
- this.configTemplateDiffLoading = false;
791
- }
792
- }
793
- },
794
-
795
- async applyConfigTemplate() {
796
- if (this.configTemplateApplying) {
797
- return;
798
- }
799
- if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
800
- this.showMessage('模板不能为空', 'error');
801
- return;
802
- }
803
-
804
- // Default to two-step confirmation when the setting is unset.
805
- // (The normalize helper lives in session-actions; keep a safe fallback here.)
806
- const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
807
-
808
- const performApply = async () => {
809
- this.configTemplateApplying = true;
810
- try {
811
- let res;
812
- if (this.configTemplateContext === 'claude') {
813
- res = await api('apply-claude-settings-raw', {
814
- content: this.configTemplateContent
815
- });
816
- } else {
817
- res = await api('apply-config-template', {
818
- template: this.configTemplateContent
819
- });
820
- }
821
- if (res.error) {
822
- this.showMessage(res.error, 'error');
823
- return;
824
- }
825
- this.showMessage('模板已应用', 'success');
826
- this.closeConfigTemplateModal({ force: true });
827
- try {
828
- await this.loadAll();
829
- } catch (_) {
830
- this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
831
- }
832
- } catch (e) {
833
- this.showMessage('应用模板失败', 'error');
834
- } finally {
835
- this.configTemplateApplying = false;
836
- }
837
- };
838
-
839
- // One-step mode: apply immediately unless user explicitly entered the diff preview state.
840
- if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
841
- await performApply();
842
- return;
843
- }
844
-
845
- if (!this.configTemplateDiffVisible) {
846
- await this.prepareConfigTemplateDiff();
847
- return;
848
- }
849
- if (this.configTemplateDiffLoading) {
850
- return;
851
- }
852
- if (this.configTemplateDiffError) {
853
- this.showMessage(this.configTemplateDiffError, 'error');
854
- return;
855
- }
856
- const fingerprint = this.buildConfigTemplateDiffFingerprint();
857
- if (this.configTemplateDiffFingerprint !== fingerprint) {
858
- await this.prepareConfigTemplateDiff();
859
- return;
860
- }
861
- if (!this.hasConfigTemplateDiffChanges()) {
862
- this.showMessage('未检测到改动', 'info');
863
- return;
864
- }
865
-
866
- await performApply();
867
- }
868
- };
869
- }
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.configTemplateContext = 'codex';
562
+ this.showConfigTemplateModal = true;
563
+ } catch (e) {
564
+ this.showMessage('加载模板失败', 'error');
565
+ }
566
+ },
567
+
568
+ async applyCodexConfigDirect(options = {}) {
569
+ if (this.codexApplying) {
570
+ this._pendingCodexApplyOptions = {
571
+ ...(this._pendingCodexApplyOptions || {}),
572
+ ...options
573
+ };
574
+ return;
575
+ }
576
+
577
+ const provider = (this.currentProvider || '').trim();
578
+ const model = (this.currentModel || '').trim();
579
+ if (!provider || !model) {
580
+ this.showMessage('请选择提供商和模型', 'error');
581
+ return;
582
+ }
583
+
584
+ const modelContextWindow = this.normalizePositiveIntegerInput(
585
+ options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
586
+ 'model_context_window',
587
+ defaultModelContextWindow
588
+ );
589
+ if (!modelContextWindow.ok) {
590
+ this.showMessage(modelContextWindow.error, 'error');
591
+ return;
592
+ }
593
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
594
+ options.modelAutoCompactTokenLimit !== undefined
595
+ ? options.modelAutoCompactTokenLimit
596
+ : this.modelAutoCompactTokenLimitInput,
597
+ 'model_auto_compact_token_limit',
598
+ defaultModelAutoCompactTokenLimit
599
+ );
600
+ if (!modelAutoCompactTokenLimit.ok) {
601
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
602
+ return;
603
+ }
604
+ this.modelContextWindowInput = modelContextWindow.text;
605
+ this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
606
+
607
+ const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
608
+
609
+ this.codexApplying = true;
610
+ try {
611
+ const tplRes = await api('get-config-template', {
612
+ provider,
613
+ model,
614
+ serviceTier: this.serviceTier,
615
+ reasoningEffort: this.modelReasoningEffort,
616
+ modelContextWindow: modelContextWindow.value,
617
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
618
+ });
619
+ if (tplRes.error) {
620
+ this.showMessage(
621
+ (typeof tplRes.error === 'string' && tplRes.error.trim())
622
+ || (typeof tplRes.message === 'string' && tplRes.message.trim())
623
+ || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
624
+ || '获取模板失败',
625
+ 'error'
626
+ );
627
+ return;
628
+ }
629
+
630
+ const applyRes = await api('apply-config-template', {
631
+ template: tplRes.template
632
+ });
633
+ if (applyRes.error) {
634
+ this.showMessage(
635
+ (typeof applyRes.error === 'string' && applyRes.error.trim())
636
+ || (typeof applyRes.message === 'string' && applyRes.message.trim())
637
+ || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
638
+ || '应用模板失败',
639
+ 'error'
640
+ );
641
+ return;
642
+ }
643
+
644
+ if (options.silent !== true) {
645
+ if (this._lastAppliedCodexKey !== _codexKey) {
646
+ this.showMessage('配置已应用', 'success');
647
+ this._lastAppliedCodexKey = _codexKey;
648
+ }
649
+ } else {
650
+ this._lastAppliedCodexKey = _codexKey;
651
+ }
652
+
653
+ const refreshOptions = options.silent === true
654
+ ? { preserveLoading: true }
655
+ : {};
656
+ try {
657
+ await this.loadAll(refreshOptions);
658
+ } catch (_) {
659
+ this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
660
+ }
661
+ } catch (e) {
662
+ this.showMessage('应用失败', 'error');
663
+ } finally {
664
+ this.codexApplying = false;
665
+ const pendingOptions = this._pendingCodexApplyOptions;
666
+ this._pendingCodexApplyOptions = null;
667
+ if (pendingOptions) {
668
+ await this.applyCodexConfigDirect(pendingOptions);
669
+ }
670
+ }
671
+ },
672
+
673
+ closeConfigTemplateModal(options = {}) {
674
+ const force = !!options.force;
675
+ if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
676
+ return;
677
+ }
678
+ this.showConfigTemplateModal = false;
679
+ this.configTemplateContent = '';
680
+ this.resetConfigTemplateDiffState();
681
+ },
682
+
683
+ resetConfigTemplateDiffState() {
684
+ this.configTemplateDiffVisible = false;
685
+ this.configTemplateDiffLoading = false;
686
+ this.configTemplateDiffError = '';
687
+ this.configTemplateDiffLines = [];
688
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
689
+ this.configTemplateDiffHasChangesValue = false;
690
+ this.configTemplateDiffFingerprint = '';
691
+ this._configTemplateDiffPreviewRequestToken = null;
692
+ },
693
+
694
+ onConfigTemplateContentInput() {
695
+ if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
696
+ this.resetConfigTemplateDiffState();
697
+ }
698
+ },
699
+
700
+ async pasteConfigTemplateContent() {
701
+ if (this.configTemplateApplying || this.configTemplateDiffLoading || this.configTemplateDiffVisible) {
702
+ return;
703
+ }
704
+ let text = '';
705
+ try {
706
+ text = await navigator.clipboard.readText();
707
+ } catch (_) {
708
+ this.showMessage('无法读取剪贴板', 'error');
709
+ return;
710
+ }
711
+ if (typeof text !== 'string' || !text) {
712
+ this.showMessage('剪贴板为空', 'info');
713
+ return;
714
+ }
715
+ this.configTemplateContent = text;
716
+ this.onConfigTemplateContentInput();
717
+ this.showMessage('已粘贴', 'success');
718
+ },
719
+
720
+ buildConfigTemplateDiffFingerprint() {
721
+ const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
722
+ return `${content.length}::${content}`;
723
+ },
724
+
725
+ hasConfigTemplateDiffChanges() {
726
+ if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
727
+ return !!this.configTemplateDiffHasChangesValue;
728
+ }
729
+ const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
730
+ ? this.configTemplateDiffStats
731
+ : {};
732
+ const added = Number(stats.added || 0);
733
+ const removed = Number(stats.removed || 0);
734
+ return added > 0 || removed > 0;
735
+ },
736
+
737
+ async prepareConfigTemplateDiff() {
738
+ const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
739
+ const requestToken = Symbol('config-template-diff-preview');
740
+ this._configTemplateDiffPreviewRequestToken = requestToken;
741
+ this.configTemplateDiffVisible = true;
742
+ this.configTemplateDiffLoading = true;
743
+ this.configTemplateDiffError = '';
744
+ this.configTemplateDiffLines = [];
745
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
746
+ this.configTemplateDiffHasChangesValue = false;
747
+ try {
748
+ const shouldApply = () => (
749
+ this.configTemplateDiffVisible
750
+ && this._configTemplateDiffPreviewRequestToken === requestToken
751
+ && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
752
+ );
753
+ const res = await api('preview-config-template-diff', {
754
+ template: this.configTemplateContent
755
+ });
756
+ if (!shouldApply()) {
757
+ return;
758
+ }
759
+ if (res.error) {
760
+ this.configTemplateDiffError = res.error;
761
+ return;
762
+ }
763
+ const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
764
+ const lines = Array.isArray(diff.lines) ? diff.lines : [];
765
+ this.configTemplateDiffLines = lines.filter(line => line && line.type);
766
+ const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
767
+ if (stats) {
768
+ this.configTemplateDiffStats = {
769
+ added: Number(stats.added || 0),
770
+ removed: Number(stats.removed || 0),
771
+ unchanged: Number(stats.unchanged || 0)
772
+ };
773
+ } else {
774
+ const nextStats = { added: 0, removed: 0, unchanged: 0 };
775
+ for (const line of this.configTemplateDiffLines) {
776
+ if (line && line.type === 'add') nextStats.added += 1;
777
+ else if (line && line.type === 'del') nextStats.removed += 1;
778
+ else nextStats.unchanged += 1;
779
+ }
780
+ this.configTemplateDiffStats = nextStats;
781
+ }
782
+ this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
783
+ this.configTemplateDiffFingerprint = requestFingerprint;
784
+ } catch (_) {
785
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
786
+ this.configTemplateDiffError = '生成差异失败';
787
+ }
788
+ } finally {
789
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
790
+ this.configTemplateDiffLoading = false;
791
+ }
792
+ }
793
+ },
794
+
795
+ async applyConfigTemplate() {
796
+ if (this.configTemplateApplying) {
797
+ return;
798
+ }
799
+ if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
800
+ this.showMessage('模板不能为空', 'error');
801
+ return;
802
+ }
803
+
804
+ // Default to two-step confirmation when the setting is unset.
805
+ // (The normalize helper lives in session-actions; keep a safe fallback here.)
806
+ const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
807
+
808
+ const performApply = async () => {
809
+ this.configTemplateApplying = true;
810
+ try {
811
+ let res;
812
+ if (this.configTemplateContext === 'claude') {
813
+ res = await api('apply-claude-settings-raw', {
814
+ content: this.configTemplateContent
815
+ });
816
+ } else {
817
+ res = await api('apply-config-template', {
818
+ template: this.configTemplateContent
819
+ });
820
+ }
821
+ if (res.error) {
822
+ this.showMessage(res.error, 'error');
823
+ return;
824
+ }
825
+ this.showMessage('模板已应用', 'success');
826
+ this.closeConfigTemplateModal({ force: true });
827
+ try {
828
+ await this.loadAll();
829
+ } catch (_) {
830
+ this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
831
+ }
832
+ } catch (e) {
833
+ this.showMessage('应用模板失败', 'error');
834
+ } finally {
835
+ this.configTemplateApplying = false;
836
+ }
837
+ };
838
+
839
+ // One-step mode: apply immediately unless user explicitly entered the diff preview state.
840
+ if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
841
+ await performApply();
842
+ return;
843
+ }
844
+
845
+ if (!this.configTemplateDiffVisible) {
846
+ await this.prepareConfigTemplateDiff();
847
+ return;
848
+ }
849
+ if (this.configTemplateDiffLoading) {
850
+ return;
851
+ }
852
+ if (this.configTemplateDiffError) {
853
+ this.showMessage(this.configTemplateDiffError, 'error');
854
+ return;
855
+ }
856
+ const fingerprint = this.buildConfigTemplateDiffFingerprint();
857
+ if (this.configTemplateDiffFingerprint !== fingerprint) {
858
+ await this.prepareConfigTemplateDiff();
859
+ return;
860
+ }
861
+ if (!this.hasConfigTemplateDiffChanges()) {
862
+ this.showMessage('未检测到改动', 'info');
863
+ return;
864
+ }
865
+
866
+ await performApply();
867
+ }
868
+ };
869
+ }