codexmate 0.0.18 → 0.0.20

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 (73) hide show
  1. package/README.en.md +34 -17
  2. package/README.md +34 -25
  3. package/cli/config-health.js +338 -0
  4. package/cli.js +1570 -839
  5. package/lib/cli-models-utils.js +186 -27
  6. package/lib/cli-network-utils.js +117 -101
  7. package/package.json +8 -1
  8. package/web-ui/app.js +379 -5754
  9. package/web-ui/index.html +15 -2079
  10. package/web-ui/logic.agents-diff.mjs +386 -0
  11. package/web-ui/logic.claude.mjs +108 -0
  12. package/web-ui/logic.mjs +5 -793
  13. package/web-ui/logic.runtime.mjs +124 -0
  14. package/web-ui/logic.sessions.mjs +263 -0
  15. package/web-ui/modules/api.mjs +69 -0
  16. package/web-ui/modules/app.computed.dashboard.mjs +113 -0
  17. package/web-ui/modules/app.computed.index.mjs +13 -0
  18. package/web-ui/modules/app.computed.session.mjs +141 -0
  19. package/web-ui/modules/app.constants.mjs +15 -0
  20. package/web-ui/modules/app.methods.agents.mjs +493 -0
  21. package/web-ui/modules/app.methods.claude-config.mjs +174 -0
  22. package/web-ui/modules/app.methods.codex-config.mjs +640 -0
  23. package/web-ui/modules/app.methods.index.mjs +86 -0
  24. package/web-ui/modules/app.methods.install.mjs +157 -0
  25. package/web-ui/modules/app.methods.navigation.mjs +478 -0
  26. package/web-ui/modules/app.methods.openclaw-core.mjs +514 -0
  27. package/web-ui/modules/app.methods.openclaw-editing.mjs +337 -0
  28. package/web-ui/modules/app.methods.openclaw-persist.mjs +251 -0
  29. package/web-ui/modules/app.methods.providers.mjs +265 -0
  30. package/web-ui/modules/app.methods.runtime.mjs +323 -0
  31. package/web-ui/modules/app.methods.session-actions.mjs +457 -0
  32. package/web-ui/modules/app.methods.session-browser.mjs +435 -0
  33. package/web-ui/modules/app.methods.session-timeline.mjs +441 -0
  34. package/web-ui/modules/app.methods.session-trash.mjs +419 -0
  35. package/web-ui/modules/app.methods.startup-claude.mjs +406 -0
  36. package/web-ui/modules/config-mode.computed.mjs +1 -0
  37. package/web-ui/modules/skills.computed.mjs +26 -1
  38. package/web-ui/modules/skills.methods.mjs +154 -23
  39. package/web-ui/partials/index/layout-footer.html +69 -0
  40. package/web-ui/partials/index/layout-header.html +337 -0
  41. package/web-ui/partials/index/modal-config-template-agents.html +125 -0
  42. package/web-ui/partials/index/modal-confirm-toast.html +32 -0
  43. package/web-ui/partials/index/modal-health-check.html +72 -0
  44. package/web-ui/partials/index/modal-openclaw-config.html +275 -0
  45. package/web-ui/partials/index/modal-skills.html +184 -0
  46. package/web-ui/partials/index/modals-basic.html +196 -0
  47. package/web-ui/partials/index/panel-config-claude.html +100 -0
  48. package/web-ui/partials/index/panel-config-codex.html +237 -0
  49. package/web-ui/partials/index/panel-config-openclaw.html +84 -0
  50. package/web-ui/partials/index/panel-market.html +174 -0
  51. package/web-ui/partials/index/panel-sessions.html +387 -0
  52. package/web-ui/partials/index/panel-settings.html +166 -0
  53. package/web-ui/session-helpers.mjs +12 -0
  54. package/web-ui/source-bundle.cjs +233 -0
  55. package/web-ui/styles/base-theme.css +373 -0
  56. package/web-ui/styles/controls-forms.css +354 -0
  57. package/web-ui/styles/feedback.css +108 -0
  58. package/web-ui/styles/health-check-dialog.css +144 -0
  59. package/web-ui/styles/layout-shell.css +330 -0
  60. package/web-ui/styles/modals-core.css +449 -0
  61. package/web-ui/styles/navigation-panels.css +381 -0
  62. package/web-ui/styles/openclaw-structured.css +266 -0
  63. package/web-ui/styles/responsive.css +416 -0
  64. package/web-ui/styles/sessions-list.css +414 -0
  65. package/web-ui/styles/sessions-preview.css +405 -0
  66. package/web-ui/styles/sessions-toolbar-trash.css +243 -0
  67. package/web-ui/styles/sessions-usage.css +276 -0
  68. package/web-ui/styles/skills-list.css +298 -0
  69. package/web-ui/styles/skills-market.css +335 -0
  70. package/web-ui/styles/titles-cards.css +407 -0
  71. package/web-ui/styles.css +16 -4499
  72. package/doc/CHANGELOG.md +0 -32
  73. package/doc/CHANGELOG.zh-CN.md +0 -34
@@ -0,0 +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
+ }