codexmate 0.0.28 → 0.0.29

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 (142) hide show
  1. package/README.md +421 -421
  2. package/README.zh.md +354 -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 -1620
  7. package/cli/claude-proxy.js +1022 -1022
  8. package/cli/config-bootstrap.js +384 -384
  9. package/cli/config-health.js +338 -338
  10. package/cli/doctor-core.js +903 -903
  11. package/cli/import-skills-url.js +356 -356
  12. package/cli/openai-bridge.js +1576 -1489
  13. package/cli/openclaw-config.js +629 -629
  14. package/cli/session-convert-args.js +65 -65
  15. package/cli/session-convert-io.js +82 -82
  16. package/cli/session-convert.js +43 -43
  17. package/cli/session-usage.concurrent.js +28 -28
  18. package/cli/session-usage.js +118 -118
  19. package/cli/session-usage.models.js +176 -176
  20. package/cli/skills.js +1141 -1141
  21. package/cli/zip-commands.js +510 -510
  22. package/cli.js +15340 -15264
  23. package/lib/automation.js +404 -404
  24. package/lib/cli-file-utils.js +151 -151
  25. package/lib/cli-models-utils.js +440 -440
  26. package/lib/cli-network-utils.js +190 -190
  27. package/lib/cli-path-utils.js +85 -85
  28. package/lib/cli-session-utils.js +121 -121
  29. package/lib/cli-sessions.js +417 -417
  30. package/lib/cli-utils.js +155 -155
  31. package/lib/cli-webhook.js +126 -0
  32. package/lib/download-artifacts.js +92 -92
  33. package/lib/mcp-stdio.js +453 -453
  34. package/lib/task-orchestrator.js +869 -869
  35. package/lib/text-diff.js +303 -303
  36. package/lib/workflow-engine.js +340 -340
  37. package/package.json +76 -76
  38. package/plugins/README.md +20 -20
  39. package/plugins/README.zh-CN.md +20 -20
  40. package/plugins/prompt-templates/comment-polish/index.mjs +25 -25
  41. package/plugins/prompt-templates/computed.mjs +253 -253
  42. package/plugins/prompt-templates/index.mjs +8 -8
  43. package/plugins/prompt-templates/manifest.mjs +15 -15
  44. package/plugins/prompt-templates/methods.mjs +553 -553
  45. package/plugins/prompt-templates/overview.mjs +91 -91
  46. package/plugins/prompt-templates/ownership.mjs +19 -19
  47. package/plugins/prompt-templates/rule-ack/index.mjs +21 -21
  48. package/plugins/prompt-templates/storage.mjs +64 -64
  49. package/plugins/registry.mjs +16 -16
  50. package/web-ui/app.js +639 -625
  51. package/web-ui/index.html +36 -35
  52. package/web-ui/logic.agents-diff.mjs +386 -386
  53. package/web-ui/logic.claude.mjs +168 -168
  54. package/web-ui/logic.codex.mjs +69 -56
  55. package/web-ui/logic.mjs +5 -5
  56. package/web-ui/logic.runtime.mjs +128 -128
  57. package/web-ui/logic.session-convert.mjs +70 -70
  58. package/web-ui/logic.sessions.mjs +765 -765
  59. package/web-ui/modules/api.mjs +90 -90
  60. package/web-ui/modules/app.computed.dashboard.mjs +225 -225
  61. package/web-ui/modules/app.computed.index.mjs +17 -17
  62. package/web-ui/modules/app.computed.main-tabs.mjs +205 -205
  63. package/web-ui/modules/app.computed.session.mjs +999 -994
  64. package/web-ui/modules/app.constants.mjs +15 -15
  65. package/web-ui/modules/app.methods.agents.mjs +632 -632
  66. package/web-ui/modules/app.methods.claude-config.mjs +200 -190
  67. package/web-ui/modules/app.methods.codex-config.mjs +892 -892
  68. package/web-ui/modules/app.methods.index.mjs +94 -92
  69. package/web-ui/modules/app.methods.install.mjs +205 -205
  70. package/web-ui/modules/app.methods.navigation.mjs +761 -743
  71. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -814
  72. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -372
  73. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -369
  74. package/web-ui/modules/app.methods.providers.mjs +493 -412
  75. package/web-ui/modules/app.methods.runtime.mjs +345 -345
  76. package/web-ui/modules/app.methods.session-actions.mjs +593 -593
  77. package/web-ui/modules/app.methods.session-browser.mjs +984 -984
  78. package/web-ui/modules/app.methods.session-timeline.mjs +479 -479
  79. package/web-ui/modules/app.methods.session-trash.mjs +438 -439
  80. package/web-ui/modules/app.methods.startup-claude.mjs +533 -533
  81. package/web-ui/modules/app.methods.task-orchestration.mjs +556 -556
  82. package/web-ui/modules/app.methods.webhook.mjs +79 -0
  83. package/web-ui/modules/config-mode.computed.mjs +124 -124
  84. package/web-ui/modules/config-template-confirm-pref.mjs +33 -33
  85. package/web-ui/modules/i18n.dict.mjs +3131 -2109
  86. package/web-ui/modules/i18n.mjs +62 -56
  87. package/web-ui/modules/plugins.computed.mjs +3 -3
  88. package/web-ui/modules/plugins.methods.mjs +3 -3
  89. package/web-ui/modules/plugins.storage.mjs +11 -11
  90. package/web-ui/modules/provider-url-display.mjs +17 -17
  91. package/web-ui/modules/sessions-filters-url.mjs +85 -85
  92. package/web-ui/modules/skills.computed.mjs +107 -107
  93. package/web-ui/modules/skills.methods.mjs +481 -481
  94. package/web-ui/partials/index/layout-footer.html +13 -13
  95. package/web-ui/partials/index/layout-header.html +500 -475
  96. package/web-ui/partials/index/modal-config-template-agents.html +174 -174
  97. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  98. package/web-ui/partials/index/modal-health-check.html +45 -45
  99. package/web-ui/partials/index/modal-openclaw-config.html +280 -280
  100. package/web-ui/partials/index/modal-skills.html +200 -200
  101. package/web-ui/partials/index/modals-basic.html +162 -165
  102. package/web-ui/partials/index/panel-config-claude.html +194 -188
  103. package/web-ui/partials/index/panel-config-codex.html +323 -312
  104. package/web-ui/partials/index/panel-config-openclaw.html +83 -83
  105. package/web-ui/partials/index/panel-dashboard.html +186 -186
  106. package/web-ui/partials/index/panel-docs.html +147 -147
  107. package/web-ui/partials/index/panel-market.html +177 -177
  108. package/web-ui/partials/index/panel-orchestration.html +391 -391
  109. package/web-ui/partials/index/panel-plugins.html +253 -253
  110. package/web-ui/partials/index/panel-sessions.html +316 -316
  111. package/web-ui/partials/index/panel-settings.html +190 -253
  112. package/web-ui/partials/index/panel-trash.html +88 -0
  113. package/web-ui/partials/index/panel-usage.html +371 -371
  114. package/web-ui/res/json5.min.js +1 -1
  115. package/web-ui/res/vue.global.prod.js +13 -13
  116. package/web-ui/session-helpers.mjs +576 -576
  117. package/web-ui/source-bundle.cjs +233 -233
  118. package/web-ui/styles/base-theme.css +281 -281
  119. package/web-ui/styles/controls-forms.css +422 -422
  120. package/web-ui/styles/dashboard.css +274 -274
  121. package/web-ui/styles/docs-panel.css +271 -247
  122. package/web-ui/styles/feedback.css +108 -108
  123. package/web-ui/styles/health-check-dialog.css +144 -144
  124. package/web-ui/styles/layout-shell.css +626 -606
  125. package/web-ui/styles/modals-core.css +466 -466
  126. package/web-ui/styles/navigation-panels.css +391 -391
  127. package/web-ui/styles/openclaw-structured.css +266 -266
  128. package/web-ui/styles/plugins-panel.css +523 -523
  129. package/web-ui/styles/responsive.css +454 -454
  130. package/web-ui/styles/sessions-list.css +419 -419
  131. package/web-ui/styles/sessions-preview.css +411 -411
  132. package/web-ui/styles/sessions-toolbar-trash.css +330 -330
  133. package/web-ui/styles/sessions-usage.css +1040 -1040
  134. package/web-ui/styles/settings-panel.css +349 -185
  135. package/web-ui/styles/skills-list.css +303 -303
  136. package/web-ui/styles/skills-market.css +406 -406
  137. package/web-ui/styles/task-orchestration.css +822 -822
  138. package/web-ui/styles/titles-cards.css +472 -472
  139. package/web-ui/styles/trash-panel.css +90 -0
  140. package/web-ui/styles/webhook.css +81 -0
  141. package/web-ui/styles.css +23 -21
  142. package/web-ui.html +17 -17
@@ -1,892 +1,892 @@
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
-
241
- async switchProvider(name) {
242
- const target = String(name || '').trim();
243
- if (!target) {
244
- return;
245
- }
246
- if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
247
- return;
248
- }
249
- this.providerSwitchDisplayTarget = target;
250
- if (this.providerSwitchInProgress) {
251
- this.pendingProviderSwitch = target;
252
- return;
253
- }
254
- this.providerSwitchInProgress = true;
255
- let lastError = '';
256
- try {
257
- this.pendingProviderSwitch = '';
258
- const result = await runLatestOnlyQueue(target, {
259
- perform: async (queuedTarget) => {
260
- this.providerSwitchDisplayTarget = queuedTarget;
261
- await this.performProviderSwitch(queuedTarget);
262
- },
263
- consumePending: () => {
264
- const queued = this.pendingProviderSwitch;
265
- this.pendingProviderSwitch = '';
266
- return queued;
267
- }
268
- });
269
- if (result && typeof result.lastError === 'string') {
270
- lastError = result.lastError;
271
- }
272
- } finally {
273
- this.providerSwitchInProgress = false;
274
- this.pendingProviderSwitch = '';
275
- this.providerSwitchDisplayTarget = '';
276
- }
277
- if (lastError) {
278
- this.showMessage(lastError, 'error');
279
- }
280
- },
281
-
282
- async onModelChange() {
283
- const name = String(this.currentProvider || '').trim();
284
- const model = typeof this.currentModel === 'string' ? this.currentModel.trim() : '';
285
- if (name && model) {
286
- if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
287
- this.currentModels[name] = model;
288
- }
289
- await this.applyCodexConfigDirect();
290
- },
291
-
292
- async onServiceTierChange() {
293
- await this.applyCodexConfigDirect({ silent: true });
294
- },
295
-
296
- async onReasoningEffortChange() {
297
- await this.applyCodexConfigDirect({ silent: true });
298
- },
299
-
300
- sanitizePositiveIntegerDraft(field) {
301
- if (!field || typeof this[field] === 'undefined') return;
302
- const current = typeof this[field] === 'string'
303
- ? this[field]
304
- : String(this[field] || '');
305
- const sanitized = current.replace(/[^\d]/g, '');
306
- if (sanitized !== current) {
307
- this[field] = sanitized;
308
- }
309
- },
310
-
311
- normalizePositiveIntegerInput(value, label, fallback = '') {
312
- const fallbackText = fallback === '' ? '' : String(fallback).trim();
313
- const raw = typeof value === 'string'
314
- ? value.trim()
315
- : String(value == null ? '' : value).trim();
316
- const text = raw || fallbackText;
317
- if (!text) {
318
- return { ok: true, value: null, text: '' };
319
- }
320
- if (!/^\d+$/.test(text)) {
321
- return { ok: false, error: `${label} 请输入正整数` };
322
- }
323
- const num = Number.parseInt(text, 10);
324
- if (!Number.isSafeInteger(num) || num <= 0) {
325
- return { ok: false, error: `${label} 请输入正整数` };
326
- }
327
- return { ok: true, value: num, text: String(num) };
328
- },
329
-
330
- async onModelContextWindowBlur() {
331
- this.editingCodexBudgetField = '';
332
- const normalized = this.normalizePositiveIntegerInput(
333
- this.modelContextWindowInput,
334
- 'model_context_window',
335
- defaultModelContextWindow
336
- );
337
- if (!normalized.ok) {
338
- this.showMessage(normalized.error, 'error');
339
- return;
340
- }
341
- this.modelContextWindowInput = normalized.text;
342
- await this.applyCodexConfigDirect({
343
- silent: true,
344
- modelContextWindow: normalized.value
345
- });
346
- },
347
-
348
- async onModelAutoCompactTokenLimitBlur() {
349
- this.editingCodexBudgetField = '';
350
- const normalized = this.normalizePositiveIntegerInput(
351
- this.modelAutoCompactTokenLimitInput,
352
- 'model_auto_compact_token_limit',
353
- defaultModelAutoCompactTokenLimit
354
- );
355
- if (!normalized.ok) {
356
- this.showMessage(normalized.error, 'error');
357
- return;
358
- }
359
- this.modelAutoCompactTokenLimitInput = normalized.text;
360
- await this.applyCodexConfigDirect({
361
- silent: true,
362
- modelAutoCompactTokenLimit: normalized.value
363
- });
364
- },
365
-
366
- async resetCodexContextBudgetDefaults() {
367
- this.modelContextWindowInput = String(defaultModelContextWindow);
368
- this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
369
- await this.applyCodexConfigDirect({
370
- modelContextWindow: defaultModelContextWindow,
371
- modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
372
- });
373
- },
374
-
375
- async runHealthCheck(options = {}) {
376
- this.healthCheckLoading = true;
377
- this.healthCheckResult = null;
378
- this.healthCheckBatchTotal = 0;
379
- this.healthCheckBatchDone = 0;
380
- this.healthCheckBatchFailed = 0;
381
- try {
382
- const silent = !!(options && options.silent);
383
- const forceRefresh = !!(options && options.forceRefresh);
384
- const useDoctor = !!(options && options.doctor);
385
- if (useDoctor) {
386
- const res = await api('doctor', {
387
- lang: this.lang,
388
- remote: true,
389
- range: this.sessionsUsageTimeRange,
390
- targetApp: this.skillsTargetApp,
391
- includeUsage: true,
392
- includeTasks: true,
393
- includeSkills: true,
394
- includeInstall: true,
395
- forceRefresh
396
- });
397
- if (hasResponseError(res)) {
398
- this.healthCheckResult = null;
399
- if (!silent) {
400
- this.showMessage(getResponseMessage(res, '检查失败'), 'error');
401
- }
402
- return;
403
- }
404
- if (res && typeof res === 'object') {
405
- this.healthCheckResult = res;
406
- const report = res.report && typeof res.report === 'object' ? res.report : null;
407
- const summary = report && report.summary && typeof report.summary === 'object' ? report.summary : null;
408
- const total = summary && Number.isFinite(Number(summary.total))
409
- ? Math.max(0, Math.floor(Number(summary.total)))
410
- : (Array.isArray(res.issues) ? res.issues.length : 0);
411
- const errors = summary && Number.isFinite(Number(summary.error)) ? Math.max(0, Math.floor(Number(summary.error))) : 0;
412
- const warns = summary && Number.isFinite(Number(summary.warn)) ? Math.max(0, Math.floor(Number(summary.warn))) : 0;
413
- this.healthCheckBatchTotal = total;
414
- this.healthCheckBatchDone = total;
415
- this.healthCheckBatchFailed = errors + warns;
416
- if (!silent && res.ok) {
417
- this.showMessage('检查通过', 'success');
418
- }
419
- return;
420
- }
421
- this.healthCheckResult = null;
422
- if (!silent) {
423
- this.showMessage('检查失败', 'error');
424
- }
425
- return;
426
- }
427
-
428
- if (this.configMode === 'claude') {
429
- const entries = Object.entries(this.claudeConfigs || {});
430
- this.healthCheckBatchTotal = entries.length;
431
-
432
- const speedTasks = entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)
433
- .then((result) => {
434
- if (!result || result.ok !== true) {
435
- this.healthCheckBatchFailed += 1;
436
- }
437
- return { name, result };
438
- })
439
- .catch((err) => {
440
- this.healthCheckBatchFailed += 1;
441
- return {
442
- name,
443
- result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
444
- };
445
- })
446
- .finally(() => {
447
- this.healthCheckBatchDone += 1;
448
- })
449
- );
450
-
451
- const pairs = await Promise.all(speedTasks);
452
- const results = {};
453
- const issues = [];
454
- for (const pair of pairs) {
455
- results[pair.name] = pair.result || null;
456
- if (typeof this.buildSpeedTestIssue === 'function') {
457
- const issue = this.buildSpeedTestIssue(pair.name, pair.result);
458
- if (issue) issues.push(issue);
459
- }
460
- }
461
- const ok = issues.length === 0 && this.healthCheckBatchFailed === 0;
462
- this.healthCheckResult = {
463
- ok,
464
- issues,
465
- remote: {
466
- type: 'speed-test',
467
- speedTests: results
468
- }
469
- };
470
- if (ok && !silent) {
471
- this.showMessage('检查通过', 'success');
472
- }
473
- return;
474
- }
475
-
476
- const shouldRunSpeedTests = this.configMode === 'codex';
477
- const speedTimeoutMs = shouldRunSpeedTests ? 3500 : 0;
478
- const providers = shouldRunSpeedTests
479
- ? (this.providersList || [])
480
- .map((provider) => typeof provider === 'string'
481
- ? provider.trim()
482
- : String((provider && provider.name) || '').trim())
483
- .filter(Boolean)
484
- : [];
485
- const currentProvider = String(this.currentProvider || '').trim();
486
- const orderedProviders = currentProvider && providers.includes(currentProvider)
487
- ? [currentProvider, ...providers.filter((name) => name !== currentProvider)]
488
- : providers;
489
- this.healthCheckBatchTotal = orderedProviders.length;
490
-
491
- const speedTasks = orderedProviders.map((provider) => this.runSpeedTest(provider, { silent: true, timeoutMs: speedTimeoutMs })
492
- .then((result) => {
493
- if (!result || result.ok !== true) {
494
- this.healthCheckBatchFailed += 1;
495
- }
496
- return { name: provider, result };
497
- })
498
- .catch((err) => {
499
- this.healthCheckBatchFailed += 1;
500
- return {
501
- name: provider,
502
- result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
503
- };
504
- })
505
- .finally(() => {
506
- this.healthCheckBatchDone += 1;
507
- })
508
- );
509
-
510
- const configTask = api('config-health-check', { remote: this.configMode === 'codex' });
511
- const [res, pairs] = await Promise.all([
512
- configTask,
513
- Promise.all(speedTasks)
514
- ]);
515
- if (hasResponseError(res)) {
516
- this.healthCheckResult = null;
517
- if (!silent) {
518
- this.showMessage(getResponseMessage(res, '检查失败'), 'error');
519
- }
520
- } else if (res && typeof res === 'object') {
521
- const issues = Array.isArray(res.issues) ? [...res.issues] : [];
522
- let remote = res.remote || null;
523
- if (shouldRunSpeedTests) {
524
- const results = {};
525
- for (const pair of pairs) {
526
- results[pair.name] = pair.result || null;
527
- const issue = this.buildSpeedTestIssue(pair.name, pair.result);
528
- if (issue) issues.push(issue);
529
- }
530
- remote = remote && typeof remote === 'object'
531
- ? { ...remote, speedTests: results }
532
- : { type: 'speed-test', speedTests: results };
533
- }
534
-
535
- const ok = issues.length === 0;
536
- this.healthCheckResult = {
537
- ...res,
538
- ok,
539
- issues,
540
- remote
541
- };
542
- if (ok && !silent) {
543
- this.showMessage('检查通过', 'success');
544
- }
545
- } else {
546
- this.healthCheckResult = null;
547
- if (!silent) {
548
- this.showMessage('检查失败', 'error');
549
- }
550
- }
551
- } catch (e) {
552
- this.healthCheckResult = null;
553
- if (!(options && options.silent)) {
554
- this.showMessage('检查失败', 'error');
555
- }
556
- } finally {
557
- this.healthCheckBatchTotal = this.healthCheckBatchTotal || 0;
558
- this.healthCheckBatchDone = Math.min(this.healthCheckBatchDone || 0, this.healthCheckBatchTotal || 0);
559
- this.healthCheckLoading = false;
560
- }
561
- },
562
-
563
- escapeTomlString(value) {
564
- return String(value || '')
565
- .replace(/\\/g, '\\\\')
566
- .replace(/"/g, '\\"');
567
- },
568
-
569
- async openConfigTemplateEditor(options = {}) {
570
- this.resetConfigTemplateDiffState();
571
- const modelContextWindow = this.normalizePositiveIntegerInput(
572
- this.modelContextWindowInput,
573
- 'model_context_window',
574
- defaultModelContextWindow
575
- );
576
- if (!modelContextWindow.ok) {
577
- this.showMessage(modelContextWindow.error, 'error');
578
- return;
579
- }
580
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
581
- this.modelAutoCompactTokenLimitInput,
582
- 'model_auto_compact_token_limit',
583
- defaultModelAutoCompactTokenLimit
584
- );
585
- if (!modelAutoCompactTokenLimit.ok) {
586
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
587
- return;
588
- }
589
- try {
590
- const res = await api('get-config-template', {
591
- provider: this.currentProvider,
592
- model: this.currentModel,
593
- serviceTier: this.serviceTier,
594
- reasoningEffort: this.modelReasoningEffort,
595
- modelContextWindow: modelContextWindow.value,
596
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
597
- });
598
- if (res.error) {
599
- this.showMessage(res.error, 'error');
600
- return;
601
- }
602
- let template = res.template || '';
603
- const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
604
- const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
605
- if (appendHint) {
606
- template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
607
- }
608
- if (appendBlock) {
609
- template = `${template.trimEnd()}\n\n${appendBlock}\n`;
610
- }
611
- this.configTemplateContent = template;
612
- this.showConfigTemplateModal = true;
613
- } catch (e) {
614
- this.showMessage('加载模板失败', 'error');
615
- }
616
- },
617
-
618
- async applyCodexConfigDirect(options = {}) {
619
- if (this.codexApplying) {
620
- this._pendingCodexApplyOptions = {
621
- ...(this._pendingCodexApplyOptions || {}),
622
- ...options
623
- };
624
- return;
625
- }
626
-
627
- const provider = (this.currentProvider || '').trim();
628
- const model = (this.currentModel || '').trim();
629
- if (!provider || !model) {
630
- this.showMessage('请选择提供商和模型', 'error');
631
- return;
632
- }
633
-
634
- const modelContextWindow = this.normalizePositiveIntegerInput(
635
- options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
636
- 'model_context_window',
637
- defaultModelContextWindow
638
- );
639
- if (!modelContextWindow.ok) {
640
- this.showMessage(modelContextWindow.error, 'error');
641
- return;
642
- }
643
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
644
- options.modelAutoCompactTokenLimit !== undefined
645
- ? options.modelAutoCompactTokenLimit
646
- : this.modelAutoCompactTokenLimitInput,
647
- 'model_auto_compact_token_limit',
648
- defaultModelAutoCompactTokenLimit
649
- );
650
- if (!modelAutoCompactTokenLimit.ok) {
651
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
652
- return;
653
- }
654
- this.modelContextWindowInput = modelContextWindow.text;
655
- this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
656
-
657
- const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
658
-
659
- this.codexApplying = true;
660
- try {
661
- const tplRes = await api('get-config-template', {
662
- provider,
663
- model,
664
- serviceTier: this.serviceTier,
665
- reasoningEffort: this.modelReasoningEffort,
666
- modelContextWindow: modelContextWindow.value,
667
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
668
- });
669
- if (tplRes.error) {
670
- this.showMessage(
671
- (typeof tplRes.error === 'string' && tplRes.error.trim())
672
- || (typeof tplRes.message === 'string' && tplRes.message.trim())
673
- || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
674
- || '获取模板失败',
675
- 'error'
676
- );
677
- return;
678
- }
679
-
680
- const applyRes = await api('apply-config-template', {
681
- template: tplRes.template
682
- });
683
- if (applyRes.error) {
684
- this.showMessage(
685
- (typeof applyRes.error === 'string' && applyRes.error.trim())
686
- || (typeof applyRes.message === 'string' && applyRes.message.trim())
687
- || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
688
- || '应用模板失败',
689
- 'error'
690
- );
691
- return;
692
- }
693
-
694
- if (options.silent !== true) {
695
- if (this._lastAppliedCodexKey !== _codexKey) {
696
- this.showMessage('配置已应用', 'success');
697
- this._lastAppliedCodexKey = _codexKey;
698
- }
699
- } else {
700
- this._lastAppliedCodexKey = _codexKey;
701
- }
702
-
703
- const refreshOptions = options.silent === true
704
- ? { preserveLoading: true }
705
- : {};
706
- try {
707
- await this.loadAll(refreshOptions);
708
- } catch (_) {
709
- this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
710
- }
711
- } catch (e) {
712
- this.showMessage('应用失败', 'error');
713
- } finally {
714
- this.codexApplying = false;
715
- const pendingOptions = this._pendingCodexApplyOptions;
716
- this._pendingCodexApplyOptions = null;
717
- if (pendingOptions) {
718
- await this.applyCodexConfigDirect(pendingOptions);
719
- }
720
- }
721
- },
722
-
723
- closeConfigTemplateModal(options = {}) {
724
- const force = !!options.force;
725
- if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
726
- return;
727
- }
728
- this.showConfigTemplateModal = false;
729
- this.configTemplateContent = '';
730
- this.resetConfigTemplateDiffState();
731
- },
732
-
733
- resetConfigTemplateDiffState() {
734
- this.configTemplateDiffVisible = false;
735
- this.configTemplateDiffLoading = false;
736
- this.configTemplateDiffError = '';
737
- this.configTemplateDiffLines = [];
738
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
739
- this.configTemplateDiffHasChangesValue = false;
740
- this.configTemplateDiffFingerprint = '';
741
- this._configTemplateDiffPreviewRequestToken = null;
742
- },
743
-
744
- onConfigTemplateContentInput() {
745
- if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
746
- this.resetConfigTemplateDiffState();
747
- }
748
- },
749
-
750
- buildConfigTemplateDiffFingerprint() {
751
- const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
752
- return `${content.length}::${content}`;
753
- },
754
-
755
- hasConfigTemplateDiffChanges() {
756
- if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
757
- return !!this.configTemplateDiffHasChangesValue;
758
- }
759
- const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
760
- ? this.configTemplateDiffStats
761
- : {};
762
- const added = Number(stats.added || 0);
763
- const removed = Number(stats.removed || 0);
764
- return added > 0 || removed > 0;
765
- },
766
-
767
- async prepareConfigTemplateDiff() {
768
- const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
769
- const requestToken = Symbol('config-template-diff-preview');
770
- this._configTemplateDiffPreviewRequestToken = requestToken;
771
- this.configTemplateDiffVisible = true;
772
- this.configTemplateDiffLoading = true;
773
- this.configTemplateDiffError = '';
774
- this.configTemplateDiffLines = [];
775
- this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
776
- this.configTemplateDiffHasChangesValue = false;
777
- try {
778
- const shouldApply = () => (
779
- this.configTemplateDiffVisible
780
- && this._configTemplateDiffPreviewRequestToken === requestToken
781
- && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
782
- );
783
- const res = await api('preview-config-template-diff', {
784
- template: this.configTemplateContent
785
- });
786
- if (!shouldApply()) {
787
- return;
788
- }
789
- if (res.error) {
790
- this.configTemplateDiffError = res.error;
791
- return;
792
- }
793
- const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
794
- const lines = Array.isArray(diff.lines) ? diff.lines : [];
795
- this.configTemplateDiffLines = lines.filter(line => line && line.type);
796
- const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
797
- if (stats) {
798
- this.configTemplateDiffStats = {
799
- added: Number(stats.added || 0),
800
- removed: Number(stats.removed || 0),
801
- unchanged: Number(stats.unchanged || 0)
802
- };
803
- } else {
804
- const nextStats = { added: 0, removed: 0, unchanged: 0 };
805
- for (const line of this.configTemplateDiffLines) {
806
- if (line && line.type === 'add') nextStats.added += 1;
807
- else if (line && line.type === 'del') nextStats.removed += 1;
808
- else nextStats.unchanged += 1;
809
- }
810
- this.configTemplateDiffStats = nextStats;
811
- }
812
- this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
813
- this.configTemplateDiffFingerprint = requestFingerprint;
814
- } catch (_) {
815
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
816
- this.configTemplateDiffError = '生成差异失败';
817
- }
818
- } finally {
819
- if (this._configTemplateDiffPreviewRequestToken === requestToken) {
820
- this.configTemplateDiffLoading = false;
821
- }
822
- }
823
- },
824
-
825
- async applyConfigTemplate() {
826
- if (this.configTemplateApplying) {
827
- return;
828
- }
829
- if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
830
- this.showMessage('模板不能为空', 'error');
831
- return;
832
- }
833
-
834
- // Default to two-step confirmation when the setting is unset.
835
- // (The normalize helper lives in session-actions; keep a safe fallback here.)
836
- const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
837
-
838
- const performApply = async () => {
839
- this.configTemplateApplying = true;
840
- try {
841
- const res = await api('apply-config-template', {
842
- template: this.configTemplateContent
843
- });
844
- if (res.error) {
845
- this.showMessage(res.error, 'error');
846
- return;
847
- }
848
- this.showMessage('模板已应用', 'success');
849
- this.closeConfigTemplateModal({ force: true });
850
- try {
851
- await this.loadAll();
852
- } catch (_) {
853
- this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
854
- }
855
- } catch (e) {
856
- this.showMessage('应用模板失败', 'error');
857
- } finally {
858
- this.configTemplateApplying = false;
859
- }
860
- };
861
-
862
- // One-step mode: apply immediately unless user explicitly entered the diff preview state.
863
- if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
864
- await performApply();
865
- return;
866
- }
867
-
868
- if (!this.configTemplateDiffVisible) {
869
- await this.prepareConfigTemplateDiff();
870
- return;
871
- }
872
- if (this.configTemplateDiffLoading) {
873
- return;
874
- }
875
- if (this.configTemplateDiffError) {
876
- this.showMessage(this.configTemplateDiffError, 'error');
877
- return;
878
- }
879
- const fingerprint = this.buildConfigTemplateDiffFingerprint();
880
- if (this.configTemplateDiffFingerprint !== fingerprint) {
881
- await this.prepareConfigTemplateDiff();
882
- return;
883
- }
884
- if (!this.hasConfigTemplateDiffChanges()) {
885
- this.showMessage('未检测到改动', 'info');
886
- return;
887
- }
888
-
889
- await performApply();
890
- }
891
- };
892
- }
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
+
241
+ async switchProvider(name) {
242
+ const target = String(name || '').trim();
243
+ if (!target) {
244
+ return;
245
+ }
246
+ if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
247
+ return;
248
+ }
249
+ this.providerSwitchDisplayTarget = target;
250
+ if (this.providerSwitchInProgress) {
251
+ this.pendingProviderSwitch = target;
252
+ return;
253
+ }
254
+ this.providerSwitchInProgress = true;
255
+ let lastError = '';
256
+ try {
257
+ this.pendingProviderSwitch = '';
258
+ const result = await runLatestOnlyQueue(target, {
259
+ perform: async (queuedTarget) => {
260
+ this.providerSwitchDisplayTarget = queuedTarget;
261
+ await this.performProviderSwitch(queuedTarget);
262
+ },
263
+ consumePending: () => {
264
+ const queued = this.pendingProviderSwitch;
265
+ this.pendingProviderSwitch = '';
266
+ return queued;
267
+ }
268
+ });
269
+ if (result && typeof result.lastError === 'string') {
270
+ lastError = result.lastError;
271
+ }
272
+ } finally {
273
+ this.providerSwitchInProgress = false;
274
+ this.pendingProviderSwitch = '';
275
+ this.providerSwitchDisplayTarget = '';
276
+ }
277
+ if (lastError) {
278
+ this.showMessage(lastError, 'error');
279
+ }
280
+ },
281
+
282
+ async onModelChange() {
283
+ const name = String(this.currentProvider || '').trim();
284
+ const model = typeof this.currentModel === 'string' ? this.currentModel.trim() : '';
285
+ if (name && model) {
286
+ if (!this.currentModels || typeof this.currentModels !== 'object') this.currentModels = {};
287
+ this.currentModels[name] = model;
288
+ }
289
+ await this.applyCodexConfigDirect();
290
+ },
291
+
292
+ async onServiceTierChange() {
293
+ await this.applyCodexConfigDirect({ silent: true });
294
+ },
295
+
296
+ async onReasoningEffortChange() {
297
+ await this.applyCodexConfigDirect({ silent: true });
298
+ },
299
+
300
+ sanitizePositiveIntegerDraft(field) {
301
+ if (!field || typeof this[field] === 'undefined') return;
302
+ const current = typeof this[field] === 'string'
303
+ ? this[field]
304
+ : String(this[field] || '');
305
+ const sanitized = current.replace(/[^\d]/g, '');
306
+ if (sanitized !== current) {
307
+ this[field] = sanitized;
308
+ }
309
+ },
310
+
311
+ normalizePositiveIntegerInput(value, label, fallback = '') {
312
+ const fallbackText = fallback === '' ? '' : String(fallback).trim();
313
+ const raw = typeof value === 'string'
314
+ ? value.trim()
315
+ : String(value == null ? '' : value).trim();
316
+ const text = raw || fallbackText;
317
+ if (!text) {
318
+ return { ok: true, value: null, text: '' };
319
+ }
320
+ if (!/^\d+$/.test(text)) {
321
+ return { ok: false, error: `${label} 请输入正整数` };
322
+ }
323
+ const num = Number.parseInt(text, 10);
324
+ if (!Number.isSafeInteger(num) || num <= 0) {
325
+ return { ok: false, error: `${label} 请输入正整数` };
326
+ }
327
+ return { ok: true, value: num, text: String(num) };
328
+ },
329
+
330
+ async onModelContextWindowBlur() {
331
+ this.editingCodexBudgetField = '';
332
+ const normalized = this.normalizePositiveIntegerInput(
333
+ this.modelContextWindowInput,
334
+ 'model_context_window',
335
+ defaultModelContextWindow
336
+ );
337
+ if (!normalized.ok) {
338
+ this.showMessage(normalized.error, 'error');
339
+ return;
340
+ }
341
+ this.modelContextWindowInput = normalized.text;
342
+ await this.applyCodexConfigDirect({
343
+ silent: true,
344
+ modelContextWindow: normalized.value
345
+ });
346
+ },
347
+
348
+ async onModelAutoCompactTokenLimitBlur() {
349
+ this.editingCodexBudgetField = '';
350
+ const normalized = this.normalizePositiveIntegerInput(
351
+ this.modelAutoCompactTokenLimitInput,
352
+ 'model_auto_compact_token_limit',
353
+ defaultModelAutoCompactTokenLimit
354
+ );
355
+ if (!normalized.ok) {
356
+ this.showMessage(normalized.error, 'error');
357
+ return;
358
+ }
359
+ this.modelAutoCompactTokenLimitInput = normalized.text;
360
+ await this.applyCodexConfigDirect({
361
+ silent: true,
362
+ modelAutoCompactTokenLimit: normalized.value
363
+ });
364
+ },
365
+
366
+ async resetCodexContextBudgetDefaults() {
367
+ this.modelContextWindowInput = String(defaultModelContextWindow);
368
+ this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
369
+ await this.applyCodexConfigDirect({
370
+ modelContextWindow: defaultModelContextWindow,
371
+ modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
372
+ });
373
+ },
374
+
375
+ async runHealthCheck(options = {}) {
376
+ this.healthCheckLoading = true;
377
+ this.healthCheckResult = null;
378
+ this.healthCheckBatchTotal = 0;
379
+ this.healthCheckBatchDone = 0;
380
+ this.healthCheckBatchFailed = 0;
381
+ try {
382
+ const silent = !!(options && options.silent);
383
+ const forceRefresh = !!(options && options.forceRefresh);
384
+ const useDoctor = !!(options && options.doctor);
385
+ if (useDoctor) {
386
+ const res = await api('doctor', {
387
+ lang: this.lang,
388
+ remote: true,
389
+ range: this.sessionsUsageTimeRange,
390
+ targetApp: this.skillsTargetApp,
391
+ includeUsage: true,
392
+ includeTasks: true,
393
+ includeSkills: true,
394
+ includeInstall: true,
395
+ forceRefresh
396
+ });
397
+ if (hasResponseError(res)) {
398
+ this.healthCheckResult = null;
399
+ if (!silent) {
400
+ this.showMessage(getResponseMessage(res, '检查失败'), 'error');
401
+ }
402
+ return;
403
+ }
404
+ if (res && typeof res === 'object') {
405
+ this.healthCheckResult = res;
406
+ const report = res.report && typeof res.report === 'object' ? res.report : null;
407
+ const summary = report && report.summary && typeof report.summary === 'object' ? report.summary : null;
408
+ const total = summary && Number.isFinite(Number(summary.total))
409
+ ? Math.max(0, Math.floor(Number(summary.total)))
410
+ : (Array.isArray(res.issues) ? res.issues.length : 0);
411
+ const errors = summary && Number.isFinite(Number(summary.error)) ? Math.max(0, Math.floor(Number(summary.error))) : 0;
412
+ const warns = summary && Number.isFinite(Number(summary.warn)) ? Math.max(0, Math.floor(Number(summary.warn))) : 0;
413
+ this.healthCheckBatchTotal = total;
414
+ this.healthCheckBatchDone = total;
415
+ this.healthCheckBatchFailed = errors + warns;
416
+ if (!silent && res.ok) {
417
+ this.showMessage('检查通过', 'success');
418
+ }
419
+ return;
420
+ }
421
+ this.healthCheckResult = null;
422
+ if (!silent) {
423
+ this.showMessage('检查失败', 'error');
424
+ }
425
+ return;
426
+ }
427
+
428
+ if (this.configMode === 'claude') {
429
+ const entries = Object.entries(this.claudeConfigs || {});
430
+ this.healthCheckBatchTotal = entries.length;
431
+
432
+ const speedTasks = entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)
433
+ .then((result) => {
434
+ if (!result || result.ok !== true) {
435
+ this.healthCheckBatchFailed += 1;
436
+ }
437
+ return { name, result };
438
+ })
439
+ .catch((err) => {
440
+ this.healthCheckBatchFailed += 1;
441
+ return {
442
+ name,
443
+ result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
444
+ };
445
+ })
446
+ .finally(() => {
447
+ this.healthCheckBatchDone += 1;
448
+ })
449
+ );
450
+
451
+ const pairs = await Promise.all(speedTasks);
452
+ const results = {};
453
+ const issues = [];
454
+ for (const pair of pairs) {
455
+ results[pair.name] = pair.result || null;
456
+ if (typeof this.buildSpeedTestIssue === 'function') {
457
+ const issue = this.buildSpeedTestIssue(pair.name, pair.result);
458
+ if (issue) issues.push(issue);
459
+ }
460
+ }
461
+ const ok = issues.length === 0 && this.healthCheckBatchFailed === 0;
462
+ this.healthCheckResult = {
463
+ ok,
464
+ issues,
465
+ remote: {
466
+ type: 'speed-test',
467
+ speedTests: results
468
+ }
469
+ };
470
+ if (ok && !silent) {
471
+ this.showMessage('检查通过', 'success');
472
+ }
473
+ return;
474
+ }
475
+
476
+ const shouldRunSpeedTests = this.configMode === 'codex';
477
+ const speedTimeoutMs = shouldRunSpeedTests ? 3500 : 0;
478
+ const providers = shouldRunSpeedTests
479
+ ? (this.providersList || [])
480
+ .map((provider) => typeof provider === 'string'
481
+ ? provider.trim()
482
+ : String((provider && provider.name) || '').trim())
483
+ .filter(Boolean)
484
+ : [];
485
+ const currentProvider = String(this.currentProvider || '').trim();
486
+ const orderedProviders = currentProvider && providers.includes(currentProvider)
487
+ ? [currentProvider, ...providers.filter((name) => name !== currentProvider)]
488
+ : providers;
489
+ this.healthCheckBatchTotal = orderedProviders.length;
490
+
491
+ const speedTasks = orderedProviders.map((provider) => this.runSpeedTest(provider, { silent: true, timeoutMs: speedTimeoutMs })
492
+ .then((result) => {
493
+ if (!result || result.ok !== true) {
494
+ this.healthCheckBatchFailed += 1;
495
+ }
496
+ return { name: provider, result };
497
+ })
498
+ .catch((err) => {
499
+ this.healthCheckBatchFailed += 1;
500
+ return {
501
+ name: provider,
502
+ result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
503
+ };
504
+ })
505
+ .finally(() => {
506
+ this.healthCheckBatchDone += 1;
507
+ })
508
+ );
509
+
510
+ const configTask = api('config-health-check', { remote: this.configMode === 'codex' });
511
+ const [res, pairs] = await Promise.all([
512
+ configTask,
513
+ Promise.all(speedTasks)
514
+ ]);
515
+ if (hasResponseError(res)) {
516
+ this.healthCheckResult = null;
517
+ if (!silent) {
518
+ this.showMessage(getResponseMessage(res, '检查失败'), 'error');
519
+ }
520
+ } else if (res && typeof res === 'object') {
521
+ const issues = Array.isArray(res.issues) ? [...res.issues] : [];
522
+ let remote = res.remote || null;
523
+ if (shouldRunSpeedTests) {
524
+ const results = {};
525
+ for (const pair of pairs) {
526
+ results[pair.name] = pair.result || null;
527
+ const issue = this.buildSpeedTestIssue(pair.name, pair.result);
528
+ if (issue) issues.push(issue);
529
+ }
530
+ remote = remote && typeof remote === 'object'
531
+ ? { ...remote, speedTests: results }
532
+ : { type: 'speed-test', speedTests: results };
533
+ }
534
+
535
+ const ok = issues.length === 0;
536
+ this.healthCheckResult = {
537
+ ...res,
538
+ ok,
539
+ issues,
540
+ remote
541
+ };
542
+ if (ok && !silent) {
543
+ this.showMessage('检查通过', 'success');
544
+ }
545
+ } else {
546
+ this.healthCheckResult = null;
547
+ if (!silent) {
548
+ this.showMessage('检查失败', 'error');
549
+ }
550
+ }
551
+ } catch (e) {
552
+ this.healthCheckResult = null;
553
+ if (!(options && options.silent)) {
554
+ this.showMessage('检查失败', 'error');
555
+ }
556
+ } finally {
557
+ this.healthCheckBatchTotal = this.healthCheckBatchTotal || 0;
558
+ this.healthCheckBatchDone = Math.min(this.healthCheckBatchDone || 0, this.healthCheckBatchTotal || 0);
559
+ this.healthCheckLoading = false;
560
+ }
561
+ },
562
+
563
+ escapeTomlString(value) {
564
+ return String(value || '')
565
+ .replace(/\\/g, '\\\\')
566
+ .replace(/"/g, '\\"');
567
+ },
568
+
569
+ async openConfigTemplateEditor(options = {}) {
570
+ this.resetConfigTemplateDiffState();
571
+ const modelContextWindow = this.normalizePositiveIntegerInput(
572
+ this.modelContextWindowInput,
573
+ 'model_context_window',
574
+ defaultModelContextWindow
575
+ );
576
+ if (!modelContextWindow.ok) {
577
+ this.showMessage(modelContextWindow.error, 'error');
578
+ return;
579
+ }
580
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
581
+ this.modelAutoCompactTokenLimitInput,
582
+ 'model_auto_compact_token_limit',
583
+ defaultModelAutoCompactTokenLimit
584
+ );
585
+ if (!modelAutoCompactTokenLimit.ok) {
586
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
587
+ return;
588
+ }
589
+ try {
590
+ const res = await api('get-config-template', {
591
+ provider: this.currentProvider,
592
+ model: this.currentModel,
593
+ serviceTier: this.serviceTier,
594
+ reasoningEffort: this.modelReasoningEffort,
595
+ modelContextWindow: modelContextWindow.value,
596
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
597
+ });
598
+ if (res.error) {
599
+ this.showMessage(res.error, 'error');
600
+ return;
601
+ }
602
+ let template = res.template || '';
603
+ const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
604
+ const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
605
+ if (appendHint) {
606
+ template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
607
+ }
608
+ if (appendBlock) {
609
+ template = `${template.trimEnd()}\n\n${appendBlock}\n`;
610
+ }
611
+ this.configTemplateContent = template;
612
+ this.showConfigTemplateModal = true;
613
+ } catch (e) {
614
+ this.showMessage('加载模板失败', 'error');
615
+ }
616
+ },
617
+
618
+ async applyCodexConfigDirect(options = {}) {
619
+ if (this.codexApplying) {
620
+ this._pendingCodexApplyOptions = {
621
+ ...(this._pendingCodexApplyOptions || {}),
622
+ ...options
623
+ };
624
+ return;
625
+ }
626
+
627
+ const provider = (this.currentProvider || '').trim();
628
+ const model = (this.currentModel || '').trim();
629
+ if (!provider || !model) {
630
+ this.showMessage('请选择提供商和模型', 'error');
631
+ return;
632
+ }
633
+
634
+ const modelContextWindow = this.normalizePositiveIntegerInput(
635
+ options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
636
+ 'model_context_window',
637
+ defaultModelContextWindow
638
+ );
639
+ if (!modelContextWindow.ok) {
640
+ this.showMessage(modelContextWindow.error, 'error');
641
+ return;
642
+ }
643
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
644
+ options.modelAutoCompactTokenLimit !== undefined
645
+ ? options.modelAutoCompactTokenLimit
646
+ : this.modelAutoCompactTokenLimitInput,
647
+ 'model_auto_compact_token_limit',
648
+ defaultModelAutoCompactTokenLimit
649
+ );
650
+ if (!modelAutoCompactTokenLimit.ok) {
651
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
652
+ return;
653
+ }
654
+ this.modelContextWindowInput = modelContextWindow.text;
655
+ this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
656
+
657
+ const _codexKey = `${provider}|${model}|${this.serviceTier || ""}|${this.modelReasoningEffort || ""}|${modelContextWindow.value}|${modelAutoCompactTokenLimit.value}`;
658
+
659
+ this.codexApplying = true;
660
+ try {
661
+ const tplRes = await api('get-config-template', {
662
+ provider,
663
+ model,
664
+ serviceTier: this.serviceTier,
665
+ reasoningEffort: this.modelReasoningEffort,
666
+ modelContextWindow: modelContextWindow.value,
667
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
668
+ });
669
+ if (tplRes.error) {
670
+ this.showMessage(
671
+ (typeof tplRes.error === 'string' && tplRes.error.trim())
672
+ || (typeof tplRes.message === 'string' && tplRes.message.trim())
673
+ || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
674
+ || '获取模板失败',
675
+ 'error'
676
+ );
677
+ return;
678
+ }
679
+
680
+ const applyRes = await api('apply-config-template', {
681
+ template: tplRes.template
682
+ });
683
+ if (applyRes.error) {
684
+ this.showMessage(
685
+ (typeof applyRes.error === 'string' && applyRes.error.trim())
686
+ || (typeof applyRes.message === 'string' && applyRes.message.trim())
687
+ || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
688
+ || '应用模板失败',
689
+ 'error'
690
+ );
691
+ return;
692
+ }
693
+
694
+ if (options.silent !== true) {
695
+ if (this._lastAppliedCodexKey !== _codexKey) {
696
+ this.showMessage('配置已应用', 'success');
697
+ this._lastAppliedCodexKey = _codexKey;
698
+ }
699
+ } else {
700
+ this._lastAppliedCodexKey = _codexKey;
701
+ }
702
+
703
+ const refreshOptions = options.silent === true
704
+ ? { preserveLoading: true }
705
+ : {};
706
+ try {
707
+ await this.loadAll(refreshOptions);
708
+ } catch (_) {
709
+ this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
710
+ }
711
+ } catch (e) {
712
+ this.showMessage('应用失败', 'error');
713
+ } finally {
714
+ this.codexApplying = false;
715
+ const pendingOptions = this._pendingCodexApplyOptions;
716
+ this._pendingCodexApplyOptions = null;
717
+ if (pendingOptions) {
718
+ await this.applyCodexConfigDirect(pendingOptions);
719
+ }
720
+ }
721
+ },
722
+
723
+ closeConfigTemplateModal(options = {}) {
724
+ const force = !!options.force;
725
+ if (!force && (this.configTemplateApplying || this.configTemplateDiffLoading)) {
726
+ return;
727
+ }
728
+ this.showConfigTemplateModal = false;
729
+ this.configTemplateContent = '';
730
+ this.resetConfigTemplateDiffState();
731
+ },
732
+
733
+ resetConfigTemplateDiffState() {
734
+ this.configTemplateDiffVisible = false;
735
+ this.configTemplateDiffLoading = false;
736
+ this.configTemplateDiffError = '';
737
+ this.configTemplateDiffLines = [];
738
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
739
+ this.configTemplateDiffHasChangesValue = false;
740
+ this.configTemplateDiffFingerprint = '';
741
+ this._configTemplateDiffPreviewRequestToken = null;
742
+ },
743
+
744
+ onConfigTemplateContentInput() {
745
+ if (this.configTemplateDiffVisible || (this.configTemplateDiffLines && this.configTemplateDiffLines.length)) {
746
+ this.resetConfigTemplateDiffState();
747
+ }
748
+ },
749
+
750
+ buildConfigTemplateDiffFingerprint() {
751
+ const content = typeof this.configTemplateContent === 'string' ? this.configTemplateContent : '';
752
+ return `${content.length}::${content}`;
753
+ },
754
+
755
+ hasConfigTemplateDiffChanges() {
756
+ if (this.configTemplateDiffHasChangesValue !== undefined && this.configTemplateDiffHasChangesValue !== null) {
757
+ return !!this.configTemplateDiffHasChangesValue;
758
+ }
759
+ const stats = this.configTemplateDiffStats && typeof this.configTemplateDiffStats === 'object'
760
+ ? this.configTemplateDiffStats
761
+ : {};
762
+ const added = Number(stats.added || 0);
763
+ const removed = Number(stats.removed || 0);
764
+ return added > 0 || removed > 0;
765
+ },
766
+
767
+ async prepareConfigTemplateDiff() {
768
+ const requestFingerprint = this.buildConfigTemplateDiffFingerprint();
769
+ const requestToken = Symbol('config-template-diff-preview');
770
+ this._configTemplateDiffPreviewRequestToken = requestToken;
771
+ this.configTemplateDiffVisible = true;
772
+ this.configTemplateDiffLoading = true;
773
+ this.configTemplateDiffError = '';
774
+ this.configTemplateDiffLines = [];
775
+ this.configTemplateDiffStats = { added: 0, removed: 0, unchanged: 0 };
776
+ this.configTemplateDiffHasChangesValue = false;
777
+ try {
778
+ const shouldApply = () => (
779
+ this.configTemplateDiffVisible
780
+ && this._configTemplateDiffPreviewRequestToken === requestToken
781
+ && this.buildConfigTemplateDiffFingerprint() === requestFingerprint
782
+ );
783
+ const res = await api('preview-config-template-diff', {
784
+ template: this.configTemplateContent
785
+ });
786
+ if (!shouldApply()) {
787
+ return;
788
+ }
789
+ if (res.error) {
790
+ this.configTemplateDiffError = res.error;
791
+ return;
792
+ }
793
+ const diff = res.diff && typeof res.diff === 'object' ? res.diff : {};
794
+ const lines = Array.isArray(diff.lines) ? diff.lines : [];
795
+ this.configTemplateDiffLines = lines.filter(line => line && line.type);
796
+ const stats = diff.stats && typeof diff.stats === 'object' ? diff.stats : null;
797
+ if (stats) {
798
+ this.configTemplateDiffStats = {
799
+ added: Number(stats.added || 0),
800
+ removed: Number(stats.removed || 0),
801
+ unchanged: Number(stats.unchanged || 0)
802
+ };
803
+ } else {
804
+ const nextStats = { added: 0, removed: 0, unchanged: 0 };
805
+ for (const line of this.configTemplateDiffLines) {
806
+ if (line && line.type === 'add') nextStats.added += 1;
807
+ else if (line && line.type === 'del') nextStats.removed += 1;
808
+ else nextStats.unchanged += 1;
809
+ }
810
+ this.configTemplateDiffStats = nextStats;
811
+ }
812
+ this.configTemplateDiffHasChangesValue = !!diff.hasChanges;
813
+ this.configTemplateDiffFingerprint = requestFingerprint;
814
+ } catch (_) {
815
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
816
+ this.configTemplateDiffError = '生成差异失败';
817
+ }
818
+ } finally {
819
+ if (this._configTemplateDiffPreviewRequestToken === requestToken) {
820
+ this.configTemplateDiffLoading = false;
821
+ }
822
+ }
823
+ },
824
+
825
+ async applyConfigTemplate() {
826
+ if (this.configTemplateApplying) {
827
+ return;
828
+ }
829
+ if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
830
+ this.showMessage('模板不能为空', 'error');
831
+ return;
832
+ }
833
+
834
+ // Default to two-step confirmation when the setting is unset.
835
+ // (The normalize helper lives in session-actions; keep a safe fallback here.)
836
+ const shouldUseTwoStepConfirm = normalizeConfigTemplateDiffConfirmEnabled(this.configTemplateDiffConfirmEnabled);
837
+
838
+ const performApply = async () => {
839
+ this.configTemplateApplying = true;
840
+ try {
841
+ const res = await api('apply-config-template', {
842
+ template: this.configTemplateContent
843
+ });
844
+ if (res.error) {
845
+ this.showMessage(res.error, 'error');
846
+ return;
847
+ }
848
+ this.showMessage('模板已应用', 'success');
849
+ this.closeConfigTemplateModal({ force: true });
850
+ try {
851
+ await this.loadAll();
852
+ } catch (_) {
853
+ this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
854
+ }
855
+ } catch (e) {
856
+ this.showMessage('应用模板失败', 'error');
857
+ } finally {
858
+ this.configTemplateApplying = false;
859
+ }
860
+ };
861
+
862
+ // One-step mode: apply immediately unless user explicitly entered the diff preview state.
863
+ if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
864
+ await performApply();
865
+ return;
866
+ }
867
+
868
+ if (!this.configTemplateDiffVisible) {
869
+ await this.prepareConfigTemplateDiff();
870
+ return;
871
+ }
872
+ if (this.configTemplateDiffLoading) {
873
+ return;
874
+ }
875
+ if (this.configTemplateDiffError) {
876
+ this.showMessage(this.configTemplateDiffError, 'error');
877
+ return;
878
+ }
879
+ const fingerprint = this.buildConfigTemplateDiffFingerprint();
880
+ if (this.configTemplateDiffFingerprint !== fingerprint) {
881
+ await this.prepareConfigTemplateDiff();
882
+ return;
883
+ }
884
+ if (!this.hasConfigTemplateDiffChanges()) {
885
+ this.showMessage('未检测到改动', 'info');
886
+ return;
887
+ }
888
+
889
+ await performApply();
890
+ }
891
+ };
892
+ }