codexmate 0.0.20 → 0.0.21

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 (102) hide show
  1. package/README.en.md +349 -259
  2. package/README.md +284 -252
  3. package/cli/agents-files.js +162 -0
  4. package/cli/archive-helpers.js +446 -0
  5. package/cli/auth-profiles.js +359 -0
  6. package/cli/builtin-proxy.js +580 -0
  7. package/cli/claude-proxy.js +998 -0
  8. package/cli/config-bootstrap.js +384 -0
  9. package/cli/config-health.js +338 -338
  10. package/cli/openclaw-config.js +629 -0
  11. package/cli/skills.js +1141 -0
  12. package/cli/zip-commands.js +510 -0
  13. package/cli.js +13101 -13497
  14. package/lib/cli-file-utils.js +151 -151
  15. package/lib/cli-models-utils.js +419 -311
  16. package/lib/cli-network-utils.js +164 -164
  17. package/lib/cli-path-utils.js +69 -0
  18. package/lib/cli-session-utils.js +121 -121
  19. package/lib/cli-sessions.js +386 -0
  20. package/lib/cli-utils.js +155 -155
  21. package/lib/download-artifacts.js +77 -0
  22. package/lib/mcp-stdio.js +440 -440
  23. package/lib/task-orchestrator.js +869 -0
  24. package/lib/text-diff.js +303 -303
  25. package/lib/workflow-engine.js +340 -340
  26. package/package.json +74 -70
  27. package/res/json5.min.js +1 -1
  28. package/res/vue.global.prod.js +13 -0
  29. package/web-ui/app.js +530 -397
  30. package/web-ui/index.html +33 -30
  31. package/web-ui/logic.agents-diff.mjs +386 -386
  32. package/web-ui/logic.claude.mjs +168 -108
  33. package/web-ui/logic.mjs +5 -5
  34. package/web-ui/logic.runtime.mjs +124 -124
  35. package/web-ui/logic.sessions.mjs +581 -263
  36. package/web-ui/modules/api.mjs +90 -69
  37. package/web-ui/modules/app.computed.dashboard.mjs +113 -113
  38. package/web-ui/modules/app.computed.index.mjs +15 -13
  39. package/web-ui/modules/app.computed.main-tabs.mjs +195 -0
  40. package/web-ui/modules/app.computed.session.mjs +507 -141
  41. package/web-ui/modules/app.constants.mjs +15 -15
  42. package/web-ui/modules/app.methods.agents.mjs +493 -493
  43. package/web-ui/modules/app.methods.claude-config.mjs +174 -174
  44. package/web-ui/modules/app.methods.codex-config.mjs +640 -640
  45. package/web-ui/modules/app.methods.index.mjs +88 -86
  46. package/web-ui/modules/app.methods.install.mjs +149 -157
  47. package/web-ui/modules/app.methods.navigation.mjs +619 -478
  48. package/web-ui/modules/app.methods.openclaw-core.mjs +814 -514
  49. package/web-ui/modules/app.methods.openclaw-editing.mjs +372 -337
  50. package/web-ui/modules/app.methods.openclaw-persist.mjs +369 -251
  51. package/web-ui/modules/app.methods.providers.mjs +363 -265
  52. package/web-ui/modules/app.methods.runtime.mjs +323 -323
  53. package/web-ui/modules/app.methods.session-actions.mjs +520 -457
  54. package/web-ui/modules/app.methods.session-browser.mjs +626 -435
  55. package/web-ui/modules/app.methods.session-timeline.mjs +448 -441
  56. package/web-ui/modules/app.methods.session-trash.mjs +422 -419
  57. package/web-ui/modules/app.methods.startup-claude.mjs +412 -406
  58. package/web-ui/modules/app.methods.task-orchestration.mjs +471 -0
  59. package/web-ui/modules/config-mode.computed.mjs +126 -124
  60. package/web-ui/modules/skills.computed.mjs +107 -107
  61. package/web-ui/modules/skills.methods.mjs +481 -481
  62. package/web-ui/partials/index/layout-footer.html +13 -69
  63. package/web-ui/partials/index/layout-header.html +402 -337
  64. package/web-ui/partials/index/modal-config-template-agents.html +125 -125
  65. package/web-ui/partials/index/modal-confirm-toast.html +32 -32
  66. package/web-ui/partials/index/modal-health-check.html +72 -72
  67. package/web-ui/partials/index/modal-openclaw-config.html +280 -275
  68. package/web-ui/partials/index/modal-skills.html +184 -184
  69. package/web-ui/partials/index/modals-basic.html +156 -196
  70. package/web-ui/partials/index/panel-config-claude.html +126 -100
  71. package/web-ui/partials/index/panel-config-codex.html +237 -237
  72. package/web-ui/partials/index/panel-config-openclaw.html +78 -84
  73. package/web-ui/partials/index/panel-docs.html +130 -0
  74. package/web-ui/partials/index/panel-market.html +174 -174
  75. package/web-ui/partials/index/panel-orchestration.html +397 -0
  76. package/web-ui/partials/index/panel-sessions.html +292 -387
  77. package/web-ui/partials/index/panel-settings.html +190 -166
  78. package/web-ui/partials/index/panel-usage.html +213 -0
  79. package/web-ui/session-helpers.mjs +559 -362
  80. package/web-ui/source-bundle.cjs +233 -233
  81. package/web-ui/styles/base-theme.css +271 -373
  82. package/web-ui/styles/controls-forms.css +360 -354
  83. package/web-ui/styles/docs-panel.css +182 -0
  84. package/web-ui/styles/feedback.css +108 -108
  85. package/web-ui/styles/health-check-dialog.css +144 -144
  86. package/web-ui/styles/layout-shell.css +376 -330
  87. package/web-ui/styles/modals-core.css +464 -449
  88. package/web-ui/styles/navigation-panels.css +348 -381
  89. package/web-ui/styles/openclaw-structured.css +266 -266
  90. package/web-ui/styles/responsive.css +450 -416
  91. package/web-ui/styles/sessions-list.css +400 -414
  92. package/web-ui/styles/sessions-preview.css +411 -405
  93. package/web-ui/styles/sessions-toolbar-trash.css +243 -243
  94. package/web-ui/styles/sessions-usage.css +628 -276
  95. package/web-ui/styles/skills-list.css +296 -298
  96. package/web-ui/styles/skills-market.css +335 -335
  97. package/web-ui/styles/task-orchestration.css +776 -0
  98. package/web-ui/styles/titles-cards.css +408 -407
  99. package/web-ui/styles.css +18 -16
  100. package/web-ui.html +17 -17
  101. package/res/screenshot.png +0 -0
  102. package/res/vue.global.js +0 -18552
@@ -1,640 +1,640 @@
1
- import { runLatestOnlyQueue } from '../logic.mjs';
2
-
3
- function hasResponseError(response) {
4
- if (!response || typeof response !== 'object') {
5
- return false;
6
- }
7
- if (typeof response.error === 'string') {
8
- return response.error.trim().length > 0;
9
- }
10
- return response.error !== undefined && response.error !== null && response.error !== false;
11
- }
12
-
13
- function getResponseMessage(response, fallback) {
14
- if (!response || typeof response !== 'object') {
15
- return fallback;
16
- }
17
- for (const key of ['error', 'message', 'detail']) {
18
- const value = response[key];
19
- if (typeof value === 'string' && value.trim()) {
20
- return value.trim();
21
- }
22
- }
23
- return fallback;
24
- }
25
-
26
- export function createCodexConfigMethods(options = {}) {
27
- const {
28
- api,
29
- defaultModelContextWindow = 190000,
30
- defaultModelAutoCompactTokenLimit = 185000,
31
- getProviderConfigModeMeta
32
- } = options;
33
-
34
- return {
35
- downloadTextFile(fileName, content, mimeType = 'text/markdown;charset=utf-8') {
36
- const BOM = '\uFEFF';
37
- const blob = new Blob([BOM + content], { type: mimeType });
38
- const url = URL.createObjectURL(blob);
39
- const link = document.createElement('a');
40
- link.href = url;
41
- link.download = fileName;
42
- link.click();
43
- URL.revokeObjectURL(url);
44
- },
45
-
46
- async exportSession(session) {
47
- const key = this.getSessionExportKey(session);
48
- if (this.sessionExporting[key]) return;
49
-
50
- this.sessionExporting[key] = true;
51
- try {
52
- const res = await api('export-session', {
53
- source: session.source,
54
- sessionId: session.sessionId,
55
- filePath: session.filePath
56
- });
57
- if (res.error) {
58
- this.showMessage(res.error, 'error');
59
- return;
60
- }
61
-
62
- const fileName = res.fileName || `${session.source || 'session'}-${session.sessionId || Date.now()}.md`;
63
- this.downloadTextFile(fileName, res.content || '');
64
- if (res.truncated) {
65
- const maxLabel = res.maxMessages === 'all' ? 'all' : res.maxMessages;
66
- this.showMessage(`会话导出完成(已截断:最多 ${maxLabel} 条消息)`, 'info');
67
- } else {
68
- this.showMessage('操作成功', 'success');
69
- }
70
- } catch (e) {
71
- this.showMessage('导出失败', 'error');
72
- } finally {
73
- this.sessionExporting[key] = false;
74
- }
75
- },
76
-
77
- async quickSwitchProvider(name) {
78
- const target = String(name || '').trim();
79
- const visualTarget = String(this.providerSwitchDisplayTarget || '').trim();
80
- if (!target || target === visualTarget || target === this.pendingProviderSwitch) {
81
- return;
82
- }
83
- if (!this.providerSwitchInProgress && target === this.currentProvider) {
84
- return;
85
- }
86
- await this.switchProvider(target);
87
- },
88
-
89
- async waitForCodexApplyIdle(maxWaitMs = 20000) {
90
- const startedAt = Date.now();
91
- while (this.codexApplying) {
92
- if ((Date.now() - startedAt) > maxWaitMs) {
93
- throw new Error('等待配置应用完成超时');
94
- }
95
- await new Promise((resolve) => setTimeout(resolve, 50));
96
- }
97
- },
98
-
99
- async performProviderSwitch(name) {
100
- await this.waitForCodexApplyIdle();
101
- const previousProvider = this.currentProvider;
102
- const previousModel = this.currentModel;
103
- const previousModels = Array.isArray(this.models) ? [...this.models] : [];
104
- const previousModelsSource = this.modelsSource;
105
- const previousModelsHasCurrent = this.modelsHasCurrent;
106
- this.currentProvider = name;
107
- await this.loadModelsForProvider(name);
108
- if (this.modelsSource === 'error') {
109
- this.currentProvider = previousProvider;
110
- this.currentModel = previousModel;
111
- this.models = previousModels;
112
- this.modelsSource = previousModelsSource;
113
- this.modelsHasCurrent = previousModelsHasCurrent;
114
- return;
115
- }
116
- if (this.modelsSource === 'remote' && this.models.length > 0 && !this.models.includes(this.currentModel)) {
117
- this.currentModel = this.models[0];
118
- this.modelsHasCurrent = true;
119
- }
120
- if (getProviderConfigModeMeta(this.configMode)) {
121
- await this.waitForCodexApplyIdle();
122
- await this.applyCodexConfigDirect({ silent: true });
123
- }
124
- },
125
-
126
- async switchProvider(name) {
127
- const target = String(name || '').trim();
128
- if (!target) {
129
- return;
130
- }
131
- if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
132
- return;
133
- }
134
- this.providerSwitchDisplayTarget = target;
135
- if (this.providerSwitchInProgress) {
136
- this.pendingProviderSwitch = target;
137
- return;
138
- }
139
- this.providerSwitchInProgress = true;
140
- let lastError = '';
141
- try {
142
- this.pendingProviderSwitch = '';
143
- const result = await runLatestOnlyQueue(target, {
144
- perform: async (queuedTarget) => {
145
- this.providerSwitchDisplayTarget = queuedTarget;
146
- await this.performProviderSwitch(queuedTarget);
147
- },
148
- consumePending: () => {
149
- const queued = this.pendingProviderSwitch;
150
- this.pendingProviderSwitch = '';
151
- return queued;
152
- }
153
- });
154
- if (result && typeof result.lastError === 'string') {
155
- lastError = result.lastError;
156
- }
157
- } finally {
158
- this.providerSwitchInProgress = false;
159
- this.pendingProviderSwitch = '';
160
- this.providerSwitchDisplayTarget = '';
161
- }
162
- if (lastError) {
163
- this.showMessage(lastError, 'error');
164
- }
165
- },
166
-
167
- async onModelChange() {
168
- await this.applyCodexConfigDirect();
169
- },
170
-
171
- async onServiceTierChange() {
172
- await this.applyCodexConfigDirect({ silent: true });
173
- },
174
-
175
- async onReasoningEffortChange() {
176
- await this.applyCodexConfigDirect({ silent: true });
177
- },
178
-
179
- sanitizePositiveIntegerDraft(field) {
180
- if (!field || typeof this[field] === 'undefined') return;
181
- const current = typeof this[field] === 'string'
182
- ? this[field]
183
- : String(this[field] || '');
184
- const sanitized = current.replace(/[^\d]/g, '');
185
- if (sanitized !== current) {
186
- this[field] = sanitized;
187
- }
188
- },
189
-
190
- normalizePositiveIntegerInput(value, label, fallback = '') {
191
- const fallbackText = fallback === '' ? '' : String(fallback).trim();
192
- const raw = typeof value === 'string'
193
- ? value.trim()
194
- : String(value ?? '').trim();
195
- const text = raw || fallbackText;
196
- if (!text) {
197
- return { ok: true, value: null, text: '' };
198
- }
199
- if (!/^\d+$/.test(text)) {
200
- return { ok: false, error: `${label} 请输入正整数` };
201
- }
202
- const num = Number.parseInt(text, 10);
203
- if (!Number.isSafeInteger(num) || num <= 0) {
204
- return { ok: false, error: `${label} 请输入正整数` };
205
- }
206
- return { ok: true, value: num, text: String(num) };
207
- },
208
-
209
- async onModelContextWindowBlur() {
210
- this.editingCodexBudgetField = '';
211
- const normalized = this.normalizePositiveIntegerInput(
212
- this.modelContextWindowInput,
213
- 'model_context_window',
214
- defaultModelContextWindow
215
- );
216
- if (!normalized.ok) {
217
- this.showMessage(normalized.error, 'error');
218
- return;
219
- }
220
- this.modelContextWindowInput = normalized.text;
221
- await this.applyCodexConfigDirect({
222
- silent: true,
223
- modelContextWindow: normalized.value
224
- });
225
- },
226
-
227
- async onModelAutoCompactTokenLimitBlur() {
228
- this.editingCodexBudgetField = '';
229
- const normalized = this.normalizePositiveIntegerInput(
230
- this.modelAutoCompactTokenLimitInput,
231
- 'model_auto_compact_token_limit',
232
- defaultModelAutoCompactTokenLimit
233
- );
234
- if (!normalized.ok) {
235
- this.showMessage(normalized.error, 'error');
236
- return;
237
- }
238
- this.modelAutoCompactTokenLimitInput = normalized.text;
239
- await this.applyCodexConfigDirect({
240
- silent: true,
241
- modelAutoCompactTokenLimit: normalized.value
242
- });
243
- },
244
-
245
- async resetCodexContextBudgetDefaults() {
246
- this.modelContextWindowInput = String(defaultModelContextWindow);
247
- this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
248
- await this.applyCodexConfigDirect({
249
- modelContextWindow: defaultModelContextWindow,
250
- modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
251
- });
252
- },
253
-
254
- async runHealthCheck() {
255
- this.healthCheckLoading = true;
256
- this.healthCheckResult = null;
257
- let shouldRunClaudeSpeedTests = false;
258
- try {
259
- const res = await api('config-health-check', {
260
- remote: this.configMode === 'codex'
261
- });
262
- if (hasResponseError(res)) {
263
- this.healthCheckResult = null;
264
- this.showMessage(getResponseMessage(res, '检查失败'), 'error');
265
- } else if (res && typeof res === 'object') {
266
- shouldRunClaudeSpeedTests = true;
267
- const issues = Array.isArray(res.issues) ? [...res.issues] : [];
268
- let remote = res.remote || null;
269
- {
270
- const providers = (this.providersList || [])
271
- .map((provider) => typeof provider === 'string'
272
- ? provider.trim()
273
- : String((provider && provider.name) || '').trim())
274
- .filter(Boolean);
275
- const tasks = providers.map(provider =>
276
- this.runSpeedTest(provider, { silent: true })
277
- .then(result => ({ name: provider, result }))
278
- .catch(err => ({
279
- name: provider,
280
- result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
281
- }))
282
- );
283
- const pairs = await Promise.all(tasks);
284
- const results = {};
285
- for (const pair of pairs) {
286
- results[pair.name] = pair.result || null;
287
- const issue = this.buildSpeedTestIssue(pair.name, pair.result);
288
- if (issue) issues.push(issue);
289
- }
290
- if (remote && typeof remote === 'object') {
291
- remote = {
292
- ...remote,
293
- speedTests: results
294
- };
295
- } else {
296
- remote = {
297
- type: 'speed-test',
298
- speedTests: results
299
- };
300
- }
301
- }
302
-
303
- const ok = issues.length === 0;
304
- this.healthCheckResult = {
305
- ...res,
306
- ok,
307
- issues,
308
- remote
309
- };
310
- if (ok) {
311
- this.showMessage('检查通过', 'success');
312
- }
313
- } else {
314
- this.healthCheckResult = null;
315
- this.showMessage('检查失败', 'error');
316
- }
317
- } catch (e) {
318
- this.healthCheckResult = null;
319
- this.showMessage('检查失败', 'error');
320
- } finally {
321
- if (shouldRunClaudeSpeedTests && this.configMode === 'claude') {
322
- try {
323
- const entries = Object.entries(this.claudeConfigs || {});
324
- await Promise.all(entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)));
325
- } catch (e) {}
326
- }
327
- this.healthCheckLoading = false;
328
- }
329
- },
330
-
331
- buildDefaultHealthCheckPrompt() {
332
- return '请简短回复:当前提供商连接正常。';
333
- },
334
-
335
- openHealthCheckDialog(options = {}) {
336
- const providerName = typeof options.providerName === 'string'
337
- ? options.providerName.trim()
338
- : '';
339
- const locked = !!options.locked && !!providerName;
340
- const nextProvider = providerName
341
- || String(this.healthCheckDialogSelectedProvider || '').trim()
342
- || String(this.currentProvider || '').trim()
343
- || String(((this.displayProvidersList || [])[0] || {}).name || '').trim();
344
-
345
- this.showHealthCheckDialog = true;
346
- this.healthCheckDialogLockedProvider = locked ? nextProvider : '';
347
- this.healthCheckDialogSelectedProvider = nextProvider;
348
- this.healthCheckDialogPrompt = this.buildDefaultHealthCheckPrompt();
349
- this.healthCheckDialogMessages = [];
350
- this.healthCheckDialogLastResult = null;
351
- },
352
-
353
- closeHealthCheckDialog(options = {}) {
354
- if (this.healthCheckDialogSending && !options.force) {
355
- return;
356
- }
357
- this.showHealthCheckDialog = false;
358
- this.healthCheckDialogLockedProvider = '';
359
- this.healthCheckDialogSelectedProvider = '';
360
- this.healthCheckDialogPrompt = this.buildDefaultHealthCheckPrompt();
361
- this.healthCheckDialogMessages = [];
362
- this.healthCheckDialogLastResult = null;
363
- },
364
-
365
- async sendHealthCheckDialogMessage() {
366
- if (this.healthCheckDialogSending) {
367
- return;
368
- }
369
-
370
- const provider = String(
371
- this.healthCheckDialogLockedProvider || this.healthCheckDialogSelectedProvider || ''
372
- ).trim();
373
- const prompt = String(this.healthCheckDialogPrompt || '').trim();
374
- if (!provider) {
375
- this.showMessage('请先选择提供商', 'error');
376
- return;
377
- }
378
- if (!prompt) {
379
- this.showMessage('请输入对话内容', 'error');
380
- return;
381
- }
382
-
383
- this.healthCheckDialogMessages.push({
384
- id: `user-${Date.now()}`,
385
- role: 'user',
386
- text: prompt
387
- });
388
- this.healthCheckDialogSending = true;
389
- this.healthCheckDialogLastResult = null;
390
-
391
- try {
392
- const res = await api('provider-chat-check', {
393
- name: provider,
394
- prompt
395
- });
396
- this.healthCheckDialogLastResult = res;
397
-
398
- if (hasResponseError(res) || res.ok === false) {
399
- const message = getResponseMessage(res, '健康检测失败');
400
- this.healthCheckDialogMessages.push({
401
- id: `assistant-${Date.now()}`,
402
- role: 'assistant',
403
- text: message,
404
- ok: false,
405
- status: Number.isFinite(res && res.status) ? res.status : 0,
406
- durationMs: Number.isFinite(res && res.durationMs) ? res.durationMs : 0,
407
- model: typeof (res && res.model) === 'string' ? res.model : '',
408
- rawPreview: typeof (res && res.rawPreview) === 'string' ? res.rawPreview : ''
409
- });
410
- this.showMessage(message, 'error');
411
- return;
412
- }
413
-
414
- const reply = typeof res.reply === 'string' && res.reply.trim()
415
- ? res.reply.trim()
416
- : '已收到响应,但未解析到可展示文本。';
417
- this.healthCheckDialogMessages.push({
418
- id: `assistant-${Date.now()}`,
419
- role: 'assistant',
420
- text: reply,
421
- ok: true,
422
- status: Number.isFinite(res.status) ? res.status : 0,
423
- durationMs: Number.isFinite(res.durationMs) ? res.durationMs : 0,
424
- model: typeof res.model === 'string' ? res.model : '',
425
- rawPreview: typeof res.rawPreview === 'string' ? res.rawPreview : ''
426
- });
427
- this.healthCheckDialogPrompt = '';
428
- } catch (e) {
429
- const message = e && e.message ? e.message : '健康检测失败';
430
- this.healthCheckDialogMessages.push({
431
- id: `assistant-${Date.now()}`,
432
- role: 'assistant',
433
- text: message,
434
- ok: false,
435
- status: 0,
436
- durationMs: 0,
437
- model: '',
438
- rawPreview: ''
439
- });
440
- this.healthCheckDialogLastResult = { ok: false, error: message };
441
- this.showMessage(message, 'error');
442
- } finally {
443
- this.healthCheckDialogSending = false;
444
- }
445
- },
446
-
447
- escapeTomlString(value) {
448
- return String(value || '')
449
- .replace(/\\/g, '\\\\')
450
- .replace(/"/g, '\\"');
451
- },
452
-
453
- async openConfigTemplateEditor(options = {}) {
454
- const modelContextWindow = this.normalizePositiveIntegerInput(
455
- this.modelContextWindowInput,
456
- 'model_context_window',
457
- defaultModelContextWindow
458
- );
459
- if (!modelContextWindow.ok) {
460
- this.showMessage(modelContextWindow.error, 'error');
461
- return;
462
- }
463
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
464
- this.modelAutoCompactTokenLimitInput,
465
- 'model_auto_compact_token_limit',
466
- defaultModelAutoCompactTokenLimit
467
- );
468
- if (!modelAutoCompactTokenLimit.ok) {
469
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
470
- return;
471
- }
472
- try {
473
- const res = await api('get-config-template', {
474
- provider: this.currentProvider,
475
- model: this.currentModel,
476
- serviceTier: this.serviceTier,
477
- reasoningEffort: this.modelReasoningEffort,
478
- modelContextWindow: modelContextWindow.value,
479
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
480
- });
481
- if (res.error) {
482
- this.showMessage(res.error, 'error');
483
- return;
484
- }
485
- let template = res.template || '';
486
- const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
487
- const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
488
- if (appendHint) {
489
- template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
490
- }
491
- if (appendBlock) {
492
- template = `${template.trimEnd()}\n\n${appendBlock}\n`;
493
- }
494
- this.configTemplateContent = template;
495
- this.showConfigTemplateModal = true;
496
- } catch (e) {
497
- this.showMessage('加载模板失败', 'error');
498
- }
499
- },
500
-
501
- async applyCodexConfigDirect(options = {}) {
502
- if (this.codexApplying) {
503
- this._pendingCodexApplyOptions = {
504
- ...(this._pendingCodexApplyOptions || {}),
505
- ...options
506
- };
507
- return;
508
- }
509
-
510
- const provider = (this.currentProvider || '').trim();
511
- const model = (this.currentModel || '').trim();
512
- if (!provider || !model) {
513
- this.showMessage('请选择提供商和模型', 'error');
514
- return;
515
- }
516
-
517
- const modelContextWindow = this.normalizePositiveIntegerInput(
518
- options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
519
- 'model_context_window',
520
- defaultModelContextWindow
521
- );
522
- if (!modelContextWindow.ok) {
523
- this.showMessage(modelContextWindow.error, 'error');
524
- return;
525
- }
526
- const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
527
- options.modelAutoCompactTokenLimit !== undefined
528
- ? options.modelAutoCompactTokenLimit
529
- : this.modelAutoCompactTokenLimitInput,
530
- 'model_auto_compact_token_limit',
531
- defaultModelAutoCompactTokenLimit
532
- );
533
- if (!modelAutoCompactTokenLimit.ok) {
534
- this.showMessage(modelAutoCompactTokenLimit.error, 'error');
535
- return;
536
- }
537
- this.modelContextWindowInput = modelContextWindow.text;
538
- this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
539
-
540
- this.codexApplying = true;
541
- try {
542
- const tplRes = await api('get-config-template', {
543
- provider,
544
- model,
545
- serviceTier: this.serviceTier,
546
- reasoningEffort: this.modelReasoningEffort,
547
- modelContextWindow: modelContextWindow.value,
548
- modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
549
- });
550
- if (tplRes.error) {
551
- this.showMessage(
552
- (typeof tplRes.error === 'string' && tplRes.error.trim())
553
- || (typeof tplRes.message === 'string' && tplRes.message.trim())
554
- || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
555
- || '获取模板失败',
556
- 'error'
557
- );
558
- return;
559
- }
560
-
561
- const applyRes = await api('apply-config-template', {
562
- template: tplRes.template
563
- });
564
- if (applyRes.error) {
565
- this.showMessage(
566
- (typeof applyRes.error === 'string' && applyRes.error.trim())
567
- || (typeof applyRes.message === 'string' && applyRes.message.trim())
568
- || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
569
- || '应用模板失败',
570
- 'error'
571
- );
572
- return;
573
- }
574
-
575
- if (options.silent !== true) {
576
- this.showMessage('配置已应用', 'success');
577
- }
578
-
579
- const refreshOptions = options.silent === true
580
- ? { preserveLoading: true }
581
- : {};
582
- try {
583
- await this.loadAll(refreshOptions);
584
- } catch (_) {
585
- this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
586
- }
587
- } catch (e) {
588
- this.showMessage('应用失败', 'error');
589
- } finally {
590
- this.codexApplying = false;
591
- const pendingOptions = this._pendingCodexApplyOptions;
592
- this._pendingCodexApplyOptions = null;
593
- if (pendingOptions) {
594
- await this.applyCodexConfigDirect(pendingOptions);
595
- }
596
- }
597
- },
598
-
599
- closeConfigTemplateModal(options = {}) {
600
- const force = !!options.force;
601
- if (!force && this.configTemplateApplying) {
602
- return;
603
- }
604
- this.showConfigTemplateModal = false;
605
- this.configTemplateContent = '';
606
- },
607
-
608
- async applyConfigTemplate() {
609
- if (this.configTemplateApplying) {
610
- return;
611
- }
612
- if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
613
- this.showMessage('模板不能为空', 'error');
614
- return;
615
- }
616
-
617
- this.configTemplateApplying = true;
618
- try {
619
- const res = await api('apply-config-template', {
620
- template: this.configTemplateContent
621
- });
622
- if (res.error) {
623
- this.showMessage(res.error, 'error');
624
- return;
625
- }
626
- this.showMessage('模板已应用', 'success');
627
- this.closeConfigTemplateModal({ force: true });
628
- try {
629
- await this.loadAll();
630
- } catch (_) {
631
- this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
632
- }
633
- } catch (e) {
634
- this.showMessage('应用模板失败', 'error');
635
- } finally {
636
- this.configTemplateApplying = false;
637
- }
638
- }
639
- };
640
- }
1
+ import { runLatestOnlyQueue } from '../logic.mjs';
2
+
3
+ function hasResponseError(response) {
4
+ if (!response || typeof response !== 'object') {
5
+ return false;
6
+ }
7
+ if (typeof response.error === 'string') {
8
+ return response.error.trim().length > 0;
9
+ }
10
+ return response.error !== undefined && response.error !== null && response.error !== false;
11
+ }
12
+
13
+ function getResponseMessage(response, fallback) {
14
+ if (!response || typeof response !== 'object') {
15
+ return fallback;
16
+ }
17
+ for (const key of ['error', 'message', 'detail']) {
18
+ const value = response[key];
19
+ if (typeof value === 'string' && value.trim()) {
20
+ return value.trim();
21
+ }
22
+ }
23
+ return fallback;
24
+ }
25
+
26
+ export function createCodexConfigMethods(options = {}) {
27
+ const {
28
+ api,
29
+ defaultModelContextWindow = 190000,
30
+ defaultModelAutoCompactTokenLimit = 185000,
31
+ getProviderConfigModeMeta
32
+ } = options;
33
+
34
+ return {
35
+ downloadTextFile(fileName, content, mimeType = 'text/markdown;charset=utf-8') {
36
+ const BOM = '\uFEFF';
37
+ const blob = new Blob([BOM + content], { type: mimeType });
38
+ const url = URL.createObjectURL(blob);
39
+ const link = document.createElement('a');
40
+ link.href = url;
41
+ link.download = fileName;
42
+ link.click();
43
+ URL.revokeObjectURL(url);
44
+ },
45
+
46
+ async exportSession(session) {
47
+ const key = this.getSessionExportKey(session);
48
+ if (this.sessionExporting[key]) return;
49
+
50
+ this.sessionExporting[key] = true;
51
+ try {
52
+ const res = await api('export-session', {
53
+ source: session.source,
54
+ sessionId: session.sessionId,
55
+ filePath: session.filePath
56
+ });
57
+ if (res.error) {
58
+ this.showMessage(res.error, 'error');
59
+ return;
60
+ }
61
+
62
+ const fileName = res.fileName || `${session.source || 'session'}-${session.sessionId || Date.now()}.md`;
63
+ this.downloadTextFile(fileName, res.content || '');
64
+ if (res.truncated) {
65
+ const maxLabel = res.maxMessages === 'all' ? 'all' : res.maxMessages;
66
+ this.showMessage(`会话导出完成(已截断:最多 ${maxLabel} 条消息)`, 'info');
67
+ } else {
68
+ this.showMessage('操作成功', 'success');
69
+ }
70
+ } catch (e) {
71
+ this.showMessage('导出失败', 'error');
72
+ } finally {
73
+ this.sessionExporting[key] = false;
74
+ }
75
+ },
76
+
77
+ async quickSwitchProvider(name) {
78
+ const target = String(name || '').trim();
79
+ const visualTarget = String(this.providerSwitchDisplayTarget || '').trim();
80
+ if (!target || target === visualTarget || target === this.pendingProviderSwitch) {
81
+ return;
82
+ }
83
+ if (!this.providerSwitchInProgress && target === this.currentProvider) {
84
+ return;
85
+ }
86
+ await this.switchProvider(target);
87
+ },
88
+
89
+ async waitForCodexApplyIdle(maxWaitMs = 20000) {
90
+ const startedAt = Date.now();
91
+ while (this.codexApplying) {
92
+ if ((Date.now() - startedAt) > maxWaitMs) {
93
+ throw new Error('等待配置应用完成超时');
94
+ }
95
+ await new Promise((resolve) => setTimeout(resolve, 50));
96
+ }
97
+ },
98
+
99
+ async performProviderSwitch(name) {
100
+ await this.waitForCodexApplyIdle();
101
+ const previousProvider = this.currentProvider;
102
+ const previousModel = this.currentModel;
103
+ const previousModels = Array.isArray(this.models) ? [...this.models] : [];
104
+ const previousModelsSource = this.modelsSource;
105
+ const previousModelsHasCurrent = this.modelsHasCurrent;
106
+ this.currentProvider = name;
107
+ await this.loadModelsForProvider(name);
108
+ if (this.modelsSource === 'error') {
109
+ this.currentProvider = previousProvider;
110
+ this.currentModel = previousModel;
111
+ this.models = previousModels;
112
+ this.modelsSource = previousModelsSource;
113
+ this.modelsHasCurrent = previousModelsHasCurrent;
114
+ return;
115
+ }
116
+ if (this.modelsSource === 'remote' && this.models.length > 0 && !this.models.includes(this.currentModel)) {
117
+ this.currentModel = this.models[0];
118
+ this.modelsHasCurrent = true;
119
+ }
120
+ if (getProviderConfigModeMeta(this.configMode)) {
121
+ await this.waitForCodexApplyIdle();
122
+ await this.applyCodexConfigDirect({ silent: true });
123
+ }
124
+ },
125
+
126
+ async switchProvider(name) {
127
+ const target = String(name || '').trim();
128
+ if (!target) {
129
+ return;
130
+ }
131
+ if (target === String(this.providerSwitchDisplayTarget || '').trim()) {
132
+ return;
133
+ }
134
+ this.providerSwitchDisplayTarget = target;
135
+ if (this.providerSwitchInProgress) {
136
+ this.pendingProviderSwitch = target;
137
+ return;
138
+ }
139
+ this.providerSwitchInProgress = true;
140
+ let lastError = '';
141
+ try {
142
+ this.pendingProviderSwitch = '';
143
+ const result = await runLatestOnlyQueue(target, {
144
+ perform: async (queuedTarget) => {
145
+ this.providerSwitchDisplayTarget = queuedTarget;
146
+ await this.performProviderSwitch(queuedTarget);
147
+ },
148
+ consumePending: () => {
149
+ const queued = this.pendingProviderSwitch;
150
+ this.pendingProviderSwitch = '';
151
+ return queued;
152
+ }
153
+ });
154
+ if (result && typeof result.lastError === 'string') {
155
+ lastError = result.lastError;
156
+ }
157
+ } finally {
158
+ this.providerSwitchInProgress = false;
159
+ this.pendingProviderSwitch = '';
160
+ this.providerSwitchDisplayTarget = '';
161
+ }
162
+ if (lastError) {
163
+ this.showMessage(lastError, 'error');
164
+ }
165
+ },
166
+
167
+ async onModelChange() {
168
+ await this.applyCodexConfigDirect();
169
+ },
170
+
171
+ async onServiceTierChange() {
172
+ await this.applyCodexConfigDirect({ silent: true });
173
+ },
174
+
175
+ async onReasoningEffortChange() {
176
+ await this.applyCodexConfigDirect({ silent: true });
177
+ },
178
+
179
+ sanitizePositiveIntegerDraft(field) {
180
+ if (!field || typeof this[field] === 'undefined') return;
181
+ const current = typeof this[field] === 'string'
182
+ ? this[field]
183
+ : String(this[field] || '');
184
+ const sanitized = current.replace(/[^\d]/g, '');
185
+ if (sanitized !== current) {
186
+ this[field] = sanitized;
187
+ }
188
+ },
189
+
190
+ normalizePositiveIntegerInput(value, label, fallback = '') {
191
+ const fallbackText = fallback === '' ? '' : String(fallback).trim();
192
+ const raw = typeof value === 'string'
193
+ ? value.trim()
194
+ : String(value ?? '').trim();
195
+ const text = raw || fallbackText;
196
+ if (!text) {
197
+ return { ok: true, value: null, text: '' };
198
+ }
199
+ if (!/^\d+$/.test(text)) {
200
+ return { ok: false, error: `${label} 请输入正整数` };
201
+ }
202
+ const num = Number.parseInt(text, 10);
203
+ if (!Number.isSafeInteger(num) || num <= 0) {
204
+ return { ok: false, error: `${label} 请输入正整数` };
205
+ }
206
+ return { ok: true, value: num, text: String(num) };
207
+ },
208
+
209
+ async onModelContextWindowBlur() {
210
+ this.editingCodexBudgetField = '';
211
+ const normalized = this.normalizePositiveIntegerInput(
212
+ this.modelContextWindowInput,
213
+ 'model_context_window',
214
+ defaultModelContextWindow
215
+ );
216
+ if (!normalized.ok) {
217
+ this.showMessage(normalized.error, 'error');
218
+ return;
219
+ }
220
+ this.modelContextWindowInput = normalized.text;
221
+ await this.applyCodexConfigDirect({
222
+ silent: true,
223
+ modelContextWindow: normalized.value
224
+ });
225
+ },
226
+
227
+ async onModelAutoCompactTokenLimitBlur() {
228
+ this.editingCodexBudgetField = '';
229
+ const normalized = this.normalizePositiveIntegerInput(
230
+ this.modelAutoCompactTokenLimitInput,
231
+ 'model_auto_compact_token_limit',
232
+ defaultModelAutoCompactTokenLimit
233
+ );
234
+ if (!normalized.ok) {
235
+ this.showMessage(normalized.error, 'error');
236
+ return;
237
+ }
238
+ this.modelAutoCompactTokenLimitInput = normalized.text;
239
+ await this.applyCodexConfigDirect({
240
+ silent: true,
241
+ modelAutoCompactTokenLimit: normalized.value
242
+ });
243
+ },
244
+
245
+ async resetCodexContextBudgetDefaults() {
246
+ this.modelContextWindowInput = String(defaultModelContextWindow);
247
+ this.modelAutoCompactTokenLimitInput = String(defaultModelAutoCompactTokenLimit);
248
+ await this.applyCodexConfigDirect({
249
+ modelContextWindow: defaultModelContextWindow,
250
+ modelAutoCompactTokenLimit: defaultModelAutoCompactTokenLimit
251
+ });
252
+ },
253
+
254
+ async runHealthCheck() {
255
+ this.healthCheckLoading = true;
256
+ this.healthCheckResult = null;
257
+ let shouldRunClaudeSpeedTests = false;
258
+ try {
259
+ const res = await api('config-health-check', {
260
+ remote: this.configMode === 'codex'
261
+ });
262
+ if (hasResponseError(res)) {
263
+ this.healthCheckResult = null;
264
+ this.showMessage(getResponseMessage(res, '检查失败'), 'error');
265
+ } else if (res && typeof res === 'object') {
266
+ shouldRunClaudeSpeedTests = true;
267
+ const issues = Array.isArray(res.issues) ? [...res.issues] : [];
268
+ let remote = res.remote || null;
269
+ {
270
+ const providers = (this.providersList || [])
271
+ .map((provider) => typeof provider === 'string'
272
+ ? provider.trim()
273
+ : String((provider && provider.name) || '').trim())
274
+ .filter(Boolean);
275
+ const tasks = providers.map(provider =>
276
+ this.runSpeedTest(provider, { silent: true })
277
+ .then(result => ({ name: provider, result }))
278
+ .catch(err => ({
279
+ name: provider,
280
+ result: { ok: false, error: err && err.message ? err.message : 'Speed test failed' }
281
+ }))
282
+ );
283
+ const pairs = await Promise.all(tasks);
284
+ const results = {};
285
+ for (const pair of pairs) {
286
+ results[pair.name] = pair.result || null;
287
+ const issue = this.buildSpeedTestIssue(pair.name, pair.result);
288
+ if (issue) issues.push(issue);
289
+ }
290
+ if (remote && typeof remote === 'object') {
291
+ remote = {
292
+ ...remote,
293
+ speedTests: results
294
+ };
295
+ } else {
296
+ remote = {
297
+ type: 'speed-test',
298
+ speedTests: results
299
+ };
300
+ }
301
+ }
302
+
303
+ const ok = issues.length === 0;
304
+ this.healthCheckResult = {
305
+ ...res,
306
+ ok,
307
+ issues,
308
+ remote
309
+ };
310
+ if (ok) {
311
+ this.showMessage('检查通过', 'success');
312
+ }
313
+ } else {
314
+ this.healthCheckResult = null;
315
+ this.showMessage('检查失败', 'error');
316
+ }
317
+ } catch (e) {
318
+ this.healthCheckResult = null;
319
+ this.showMessage('检查失败', 'error');
320
+ } finally {
321
+ if (shouldRunClaudeSpeedTests && this.configMode === 'claude') {
322
+ try {
323
+ const entries = Object.entries(this.claudeConfigs || {});
324
+ await Promise.all(entries.map(([name, config]) => this.runClaudeSpeedTest(name, config)));
325
+ } catch (e) {}
326
+ }
327
+ this.healthCheckLoading = false;
328
+ }
329
+ },
330
+
331
+ buildDefaultHealthCheckPrompt() {
332
+ return '请简短回复:当前提供商连接正常。';
333
+ },
334
+
335
+ openHealthCheckDialog(options = {}) {
336
+ const providerName = typeof options.providerName === 'string'
337
+ ? options.providerName.trim()
338
+ : '';
339
+ const locked = !!options.locked && !!providerName;
340
+ const nextProvider = providerName
341
+ || String(this.healthCheckDialogSelectedProvider || '').trim()
342
+ || String(this.currentProvider || '').trim()
343
+ || String(((this.displayProvidersList || [])[0] || {}).name || '').trim();
344
+
345
+ this.showHealthCheckDialog = true;
346
+ this.healthCheckDialogLockedProvider = locked ? nextProvider : '';
347
+ this.healthCheckDialogSelectedProvider = nextProvider;
348
+ this.healthCheckDialogPrompt = this.buildDefaultHealthCheckPrompt();
349
+ this.healthCheckDialogMessages = [];
350
+ this.healthCheckDialogLastResult = null;
351
+ },
352
+
353
+ closeHealthCheckDialog(options = {}) {
354
+ if (this.healthCheckDialogSending && !options.force) {
355
+ return;
356
+ }
357
+ this.showHealthCheckDialog = false;
358
+ this.healthCheckDialogLockedProvider = '';
359
+ this.healthCheckDialogSelectedProvider = '';
360
+ this.healthCheckDialogPrompt = this.buildDefaultHealthCheckPrompt();
361
+ this.healthCheckDialogMessages = [];
362
+ this.healthCheckDialogLastResult = null;
363
+ },
364
+
365
+ async sendHealthCheckDialogMessage() {
366
+ if (this.healthCheckDialogSending) {
367
+ return;
368
+ }
369
+
370
+ const provider = String(
371
+ this.healthCheckDialogLockedProvider || this.healthCheckDialogSelectedProvider || ''
372
+ ).trim();
373
+ const prompt = String(this.healthCheckDialogPrompt || '').trim();
374
+ if (!provider) {
375
+ this.showMessage('请先选择提供商', 'error');
376
+ return;
377
+ }
378
+ if (!prompt) {
379
+ this.showMessage('请输入对话内容', 'error');
380
+ return;
381
+ }
382
+
383
+ this.healthCheckDialogMessages.push({
384
+ id: `user-${Date.now()}`,
385
+ role: 'user',
386
+ text: prompt
387
+ });
388
+ this.healthCheckDialogSending = true;
389
+ this.healthCheckDialogLastResult = null;
390
+
391
+ try {
392
+ const res = await api('provider-chat-check', {
393
+ name: provider,
394
+ prompt
395
+ });
396
+ this.healthCheckDialogLastResult = res;
397
+
398
+ if (hasResponseError(res) || res.ok === false) {
399
+ const message = getResponseMessage(res, '健康检测失败');
400
+ this.healthCheckDialogMessages.push({
401
+ id: `assistant-${Date.now()}`,
402
+ role: 'assistant',
403
+ text: message,
404
+ ok: false,
405
+ status: Number.isFinite(res && res.status) ? res.status : 0,
406
+ durationMs: Number.isFinite(res && res.durationMs) ? res.durationMs : 0,
407
+ model: typeof (res && res.model) === 'string' ? res.model : '',
408
+ rawPreview: typeof (res && res.rawPreview) === 'string' ? res.rawPreview : ''
409
+ });
410
+ this.showMessage(message, 'error');
411
+ return;
412
+ }
413
+
414
+ const reply = typeof res.reply === 'string' && res.reply.trim()
415
+ ? res.reply.trim()
416
+ : '已收到响应,但未解析到可展示文本。';
417
+ this.healthCheckDialogMessages.push({
418
+ id: `assistant-${Date.now()}`,
419
+ role: 'assistant',
420
+ text: reply,
421
+ ok: true,
422
+ status: Number.isFinite(res.status) ? res.status : 0,
423
+ durationMs: Number.isFinite(res.durationMs) ? res.durationMs : 0,
424
+ model: typeof res.model === 'string' ? res.model : '',
425
+ rawPreview: typeof res.rawPreview === 'string' ? res.rawPreview : ''
426
+ });
427
+ this.healthCheckDialogPrompt = '';
428
+ } catch (e) {
429
+ const message = e && e.message ? e.message : '健康检测失败';
430
+ this.healthCheckDialogMessages.push({
431
+ id: `assistant-${Date.now()}`,
432
+ role: 'assistant',
433
+ text: message,
434
+ ok: false,
435
+ status: 0,
436
+ durationMs: 0,
437
+ model: '',
438
+ rawPreview: ''
439
+ });
440
+ this.healthCheckDialogLastResult = { ok: false, error: message };
441
+ this.showMessage(message, 'error');
442
+ } finally {
443
+ this.healthCheckDialogSending = false;
444
+ }
445
+ },
446
+
447
+ escapeTomlString(value) {
448
+ return String(value || '')
449
+ .replace(/\\/g, '\\\\')
450
+ .replace(/"/g, '\\"');
451
+ },
452
+
453
+ async openConfigTemplateEditor(options = {}) {
454
+ const modelContextWindow = this.normalizePositiveIntegerInput(
455
+ this.modelContextWindowInput,
456
+ 'model_context_window',
457
+ defaultModelContextWindow
458
+ );
459
+ if (!modelContextWindow.ok) {
460
+ this.showMessage(modelContextWindow.error, 'error');
461
+ return;
462
+ }
463
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
464
+ this.modelAutoCompactTokenLimitInput,
465
+ 'model_auto_compact_token_limit',
466
+ defaultModelAutoCompactTokenLimit
467
+ );
468
+ if (!modelAutoCompactTokenLimit.ok) {
469
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
470
+ return;
471
+ }
472
+ try {
473
+ const res = await api('get-config-template', {
474
+ provider: this.currentProvider,
475
+ model: this.currentModel,
476
+ serviceTier: this.serviceTier,
477
+ reasoningEffort: this.modelReasoningEffort,
478
+ modelContextWindow: modelContextWindow.value,
479
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
480
+ });
481
+ if (res.error) {
482
+ this.showMessage(res.error, 'error');
483
+ return;
484
+ }
485
+ let template = res.template || '';
486
+ const appendHint = typeof options.appendHint === 'string' ? options.appendHint.trim() : '';
487
+ const appendBlock = typeof options.appendBlock === 'string' ? options.appendBlock.trim() : '';
488
+ if (appendHint) {
489
+ template = `${template.trimEnd()}\n\n# -------------------------------\n# ${appendHint}\n# -------------------------------\n`;
490
+ }
491
+ if (appendBlock) {
492
+ template = `${template.trimEnd()}\n\n${appendBlock}\n`;
493
+ }
494
+ this.configTemplateContent = template;
495
+ this.showConfigTemplateModal = true;
496
+ } catch (e) {
497
+ this.showMessage('加载模板失败', 'error');
498
+ }
499
+ },
500
+
501
+ async applyCodexConfigDirect(options = {}) {
502
+ if (this.codexApplying) {
503
+ this._pendingCodexApplyOptions = {
504
+ ...(this._pendingCodexApplyOptions || {}),
505
+ ...options
506
+ };
507
+ return;
508
+ }
509
+
510
+ const provider = (this.currentProvider || '').trim();
511
+ const model = (this.currentModel || '').trim();
512
+ if (!provider || !model) {
513
+ this.showMessage('请选择提供商和模型', 'error');
514
+ return;
515
+ }
516
+
517
+ const modelContextWindow = this.normalizePositiveIntegerInput(
518
+ options.modelContextWindow !== undefined ? options.modelContextWindow : this.modelContextWindowInput,
519
+ 'model_context_window',
520
+ defaultModelContextWindow
521
+ );
522
+ if (!modelContextWindow.ok) {
523
+ this.showMessage(modelContextWindow.error, 'error');
524
+ return;
525
+ }
526
+ const modelAutoCompactTokenLimit = this.normalizePositiveIntegerInput(
527
+ options.modelAutoCompactTokenLimit !== undefined
528
+ ? options.modelAutoCompactTokenLimit
529
+ : this.modelAutoCompactTokenLimitInput,
530
+ 'model_auto_compact_token_limit',
531
+ defaultModelAutoCompactTokenLimit
532
+ );
533
+ if (!modelAutoCompactTokenLimit.ok) {
534
+ this.showMessage(modelAutoCompactTokenLimit.error, 'error');
535
+ return;
536
+ }
537
+ this.modelContextWindowInput = modelContextWindow.text;
538
+ this.modelAutoCompactTokenLimitInput = modelAutoCompactTokenLimit.text;
539
+
540
+ this.codexApplying = true;
541
+ try {
542
+ const tplRes = await api('get-config-template', {
543
+ provider,
544
+ model,
545
+ serviceTier: this.serviceTier,
546
+ reasoningEffort: this.modelReasoningEffort,
547
+ modelContextWindow: modelContextWindow.value,
548
+ modelAutoCompactTokenLimit: modelAutoCompactTokenLimit.value
549
+ });
550
+ if (tplRes.error) {
551
+ this.showMessage(
552
+ (typeof tplRes.error === 'string' && tplRes.error.trim())
553
+ || (typeof tplRes.message === 'string' && tplRes.message.trim())
554
+ || (typeof tplRes.detail === 'string' && tplRes.detail.trim())
555
+ || '获取模板失败',
556
+ 'error'
557
+ );
558
+ return;
559
+ }
560
+
561
+ const applyRes = await api('apply-config-template', {
562
+ template: tplRes.template
563
+ });
564
+ if (applyRes.error) {
565
+ this.showMessage(
566
+ (typeof applyRes.error === 'string' && applyRes.error.trim())
567
+ || (typeof applyRes.message === 'string' && applyRes.message.trim())
568
+ || (typeof applyRes.detail === 'string' && applyRes.detail.trim())
569
+ || '应用模板失败',
570
+ 'error'
571
+ );
572
+ return;
573
+ }
574
+
575
+ if (options.silent !== true) {
576
+ this.showMessage('配置已应用', 'success');
577
+ }
578
+
579
+ const refreshOptions = options.silent === true
580
+ ? { preserveLoading: true }
581
+ : {};
582
+ try {
583
+ await this.loadAll(refreshOptions);
584
+ } catch (_) {
585
+ this.showMessage('配置已应用,但界面刷新失败,请手动刷新', 'error');
586
+ }
587
+ } catch (e) {
588
+ this.showMessage('应用失败', 'error');
589
+ } finally {
590
+ this.codexApplying = false;
591
+ const pendingOptions = this._pendingCodexApplyOptions;
592
+ this._pendingCodexApplyOptions = null;
593
+ if (pendingOptions) {
594
+ await this.applyCodexConfigDirect(pendingOptions);
595
+ }
596
+ }
597
+ },
598
+
599
+ closeConfigTemplateModal(options = {}) {
600
+ const force = !!options.force;
601
+ if (!force && this.configTemplateApplying) {
602
+ return;
603
+ }
604
+ this.showConfigTemplateModal = false;
605
+ this.configTemplateContent = '';
606
+ },
607
+
608
+ async applyConfigTemplate() {
609
+ if (this.configTemplateApplying) {
610
+ return;
611
+ }
612
+ if (!this.configTemplateContent || !this.configTemplateContent.trim()) {
613
+ this.showMessage('模板不能为空', 'error');
614
+ return;
615
+ }
616
+
617
+ this.configTemplateApplying = true;
618
+ try {
619
+ const res = await api('apply-config-template', {
620
+ template: this.configTemplateContent
621
+ });
622
+ if (res.error) {
623
+ this.showMessage(res.error, 'error');
624
+ return;
625
+ }
626
+ this.showMessage('模板已应用', 'success');
627
+ this.closeConfigTemplateModal({ force: true });
628
+ try {
629
+ await this.loadAll();
630
+ } catch (_) {
631
+ this.showMessage('模板已应用,但界面刷新失败,请手动刷新', 'error');
632
+ }
633
+ } catch (e) {
634
+ this.showMessage('应用模板失败', 'error');
635
+ } finally {
636
+ this.configTemplateApplying = false;
637
+ }
638
+ }
639
+ };
640
+ }