codexmate 0.1.32 → 0.1.33

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 (70) hide show
  1. package/README.md +5 -0
  2. package/README.vi.md +5 -0
  3. package/README.zh.md +5 -0
  4. package/cli/claude-proxy.js +2 -2
  5. package/cli/prompt-history.js +2 -0
  6. package/cli.js +165 -213
  7. package/lib/cli-config-engine.js +6 -1
  8. package/lib/cli-file-utils.js +6 -1
  9. package/lib/config-change-fs.js +132 -0
  10. package/lib/config-changes.js +293 -0
  11. package/lib/handoff-mcp.js +18 -2
  12. package/lib/local-feature-store.js +39 -0
  13. package/lib/session-bookmarks.js +72 -0
  14. package/lib/session-context-health.js +23 -3
  15. package/lib/session-diagnostics.js +75 -0
  16. package/lib/session-feature-settings.js +21 -0
  17. package/lib/session-features.js +63 -0
  18. package/lib/session-handoff-draft.js +43 -0
  19. package/lib/session-projects.js +76 -0
  20. package/lib/session-search-index.js +188 -0
  21. package/lib/thread-handoff.js +8 -0
  22. package/lib/web-server.js +216 -0
  23. package/package.json +1 -1
  24. package/web-ui/app.js +7 -1
  25. package/web-ui/index.html +1 -0
  26. package/web-ui/logic.context-window.mjs +15 -0
  27. package/web-ui/modules/api.mjs +72 -39
  28. package/web-ui/modules/app.methods.agents.mjs +5 -0
  29. package/web-ui/modules/app.methods.claude-config.mjs +2 -0
  30. package/web-ui/modules/app.methods.codex-config.mjs +9 -0
  31. package/web-ui/modules/app.methods.config-changes.mjs +124 -0
  32. package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
  33. package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
  34. package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
  35. package/web-ui/modules/app.methods.pi-config.mjs +12 -3
  36. package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
  37. package/web-ui/modules/app.methods.providers.mjs +6 -0
  38. package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
  39. package/web-ui/modules/config-change-actions.mjs +9 -0
  40. package/web-ui/modules/i18n/locales/en.mjs +131 -4
  41. package/web-ui/modules/i18n/locales/ja.mjs +131 -4
  42. package/web-ui/modules/i18n/locales/vi.mjs +131 -4
  43. package/web-ui/modules/i18n/locales/zh-tw.mjs +131 -4
  44. package/web-ui/modules/i18n/locales/zh.mjs +131 -4
  45. package/web-ui/modules/request-deadline.mjs +33 -0
  46. package/web-ui/modules/session-features.mjs +279 -0
  47. package/web-ui/modules/thread-handoff.mjs +1 -1
  48. package/web-ui/partials/index/config-changes.html +25 -0
  49. package/web-ui/partials/index/context-window-reference.html +17 -0
  50. package/web-ui/partials/index/layout-header.html +7 -30
  51. package/web-ui/partials/index/modal-openclaw-config.html +0 -2
  52. package/web-ui/partials/index/modal-skills.html +0 -1
  53. package/web-ui/partials/index/modals-basic.html +0 -8
  54. package/web-ui/partials/index/modals-pi-provider.html +0 -1
  55. package/web-ui/partials/index/panel-config-codex.html +0 -3
  56. package/web-ui/partials/index/panel-config-openclaw.html +16 -13
  57. package/web-ui/partials/index/panel-dashboard.html +0 -2
  58. package/web-ui/partials/index/panel-plugins.html +0 -1
  59. package/web-ui/partials/index/panel-prompts.html +0 -1
  60. package/web-ui/partials/index/panel-sessions.html +9 -0
  61. package/web-ui/partials/index/panel-settings.html +1 -12
  62. package/web-ui/partials/index/panel-trash.html +0 -1
  63. package/web-ui/partials/index/session-diagnostics.html +29 -0
  64. package/web-ui/partials/index/session-features.html +107 -0
  65. package/web-ui/partials/index/thread-handoff.html +6 -3
  66. package/web-ui/res/web-ui-render.precompiled.js +1077 -135
  67. package/web-ui/styles/config-changes.css +30 -0
  68. package/web-ui/styles/openclaw-structured.css +205 -189
  69. package/web-ui/styles/session-features.css +148 -0
  70. package/web-ui/styles.css +3 -1
@@ -0,0 +1,216 @@
1
+ function createWebServerLifecycle(options, dependencies) {
2
+ const { server, host, port, httpToken, openBrowser } = options;
3
+ const { http, spawn, process, console, setTimeout, formatHostForUrl, DEFAULT_WEB_OPEN_HOST, isAnyAddressHost, getUnattendedWorkflowRunner } = dependencies;
4
+ const connections = new Set();
5
+
6
+ const probeWebUiReadiness = (callback) => {
7
+ const payload = JSON.stringify({ action: 'health-check', params: {} });
8
+ const requestOptions = {
9
+ hostname: openHost,
10
+ port,
11
+ path: '/api',
12
+ method: 'POST',
13
+ headers: {
14
+ 'Content-Type': 'application/json; charset=utf-8',
15
+ 'Content-Length': Buffer.byteLength(payload, 'utf-8'),
16
+ ...(httpToken ? { Authorization: `Bearer ${httpToken}` } : {})
17
+ }
18
+ };
19
+ let settled = false;
20
+ const finish = (ready) => {
21
+ if (settled) return;
22
+ settled = true;
23
+ callback(ready);
24
+ };
25
+ const req = http.request(requestOptions, (probeRes) => {
26
+ if (typeof probeRes.resume === 'function') {
27
+ probeRes.resume();
28
+ }
29
+ probeRes.on('end', () => {
30
+ finish(probeRes.statusCode === 200);
31
+ });
32
+ });
33
+ req.on('error', () => finish(false));
34
+ req.setTimeout(1000, () => {
35
+ try { req.destroy(); } catch (_) { }
36
+ finish(false);
37
+ });
38
+ req.end(payload, 'utf-8');
39
+ };
40
+
41
+ const probeWebUiAssetReadiness = (callback) => {
42
+ const requestOptions = {
43
+ hostname: openHost,
44
+ port,
45
+ path: '/web-ui/app.js',
46
+ method: 'GET',
47
+ headers: httpToken ? { Authorization: `Bearer ${httpToken}` } : {}
48
+ };
49
+ let settled = false;
50
+ const finish = (ready) => {
51
+ if (settled) return;
52
+ settled = true;
53
+ callback(ready);
54
+ };
55
+ const req = http.request(requestOptions, (probeRes) => {
56
+ if (typeof probeRes.resume === 'function') {
57
+ probeRes.resume();
58
+ }
59
+ probeRes.on('end', () => {
60
+ finish(probeRes.statusCode === 200);
61
+ });
62
+ });
63
+ req.on('error', () => finish(false));
64
+ req.setTimeout(1000, () => {
65
+ try { req.destroy(); } catch (_) { }
66
+ finish(false);
67
+ });
68
+ req.end();
69
+ };
70
+
71
+ const openBrowserAfterReady = (url) => {
72
+ // Some environments may start the listener before the bundled web-ui assets
73
+ // are ready for the first browser hit; wait until both API and assets respond.
74
+ const maxAttempts = 120;
75
+ const retryDelayMs = 200;
76
+ let finished = false;
77
+
78
+ const finish = (ready) => {
79
+ if (finished) return;
80
+ finished = true;
81
+ if (!ready) {
82
+ console.warn('! Web UI 就绪探测超时,未自动打开浏览器,请手动访问:', url);
83
+ return;
84
+ }
85
+
86
+ const platform = process.platform;
87
+ const commandSpec = platform === 'win32'
88
+ ? { command: 'cmd', args: ['/c', 'start', '', url] }
89
+ : (platform === 'darwin'
90
+ ? { command: 'open', args: [url] }
91
+ : { command: 'xdg-open', args: [url] });
92
+
93
+ try {
94
+ const child = spawn(commandSpec.command, commandSpec.args, {
95
+ stdio: 'ignore',
96
+ detached: true,
97
+ windowsHide: true
98
+ });
99
+ child.on('error', () => {
100
+ console.warn('无法自动打开浏览器,请手动访问:', url);
101
+ });
102
+ if (typeof child.unref === 'function') {
103
+ child.unref();
104
+ }
105
+ } catch (_) {
106
+ console.warn('无法自动打开浏览器,请手动访问:', url);
107
+ }
108
+ };
109
+ const scheduleProbe = (attempt) => {
110
+ probeWebUiReadiness((apiReady) => {
111
+ if (!apiReady) {
112
+ if (attempt >= maxAttempts) {
113
+ finish(false);
114
+ return;
115
+ }
116
+ setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
117
+ return;
118
+ }
119
+ probeWebUiAssetReadiness((assetReady) => {
120
+ if (assetReady) {
121
+ finish(true);
122
+ return;
123
+ }
124
+ if (attempt >= maxAttempts) {
125
+ finish(false);
126
+ return;
127
+ }
128
+ setTimeout(() => scheduleProbe(attempt + 1), retryDelayMs);
129
+ });
130
+ });
131
+ };
132
+
133
+ scheduleProbe(1);
134
+ };
135
+
136
+ server.on('connection', (socket) => {
137
+ connections.add(socket);
138
+ socket.on('close', () => connections.delete(socket));
139
+ });
140
+
141
+ const printPortOverrideHint = () => {
142
+ const examplePort = port === 8080 ? 8081 : 8080;
143
+ console.error(` 临时换端口(macOS/Linux): CODEXMATE_PORT=${examplePort} codexmate run`);
144
+ console.error(` 临时换端口(Windows PowerShell): $env:CODEXMATE_PORT=${examplePort}; codexmate run`);
145
+ console.error(` 临时换端口(Windows CMD): set CODEXMATE_PORT=${examplePort} && codexmate run`);
146
+ };
147
+
148
+ server.once('error', (err) => {
149
+ if (err && err.code === 'EADDRINUSE') {
150
+ console.error(`! 启动失败: 端口 ${port} 已被占用,可能有残留的 codexmate run 实例。`);
151
+ console.error(' 请先停止旧实例或更换端口后重试。');
152
+ printPortOverrideHint();
153
+ } else if (err && err.code === 'EACCES') {
154
+ console.error(`! 启动失败: 没有权限监听 ${host}:${port}。`);
155
+ console.error(' 请检查系统/安全软件限制,或更换端口后重试。');
156
+ printPortOverrideHint();
157
+ } else {
158
+ console.error('! 启动 Web UI 失败:', err && err.message ? err.message : err);
159
+ }
160
+ process.exit(1);
161
+ });
162
+
163
+ const openHost = host === '::'
164
+ ? '::1'
165
+ : (host === '0.0.0.0' ? DEFAULT_WEB_OPEN_HOST : host);
166
+
167
+ const openUrl = `http://${formatHostForUrl(openHost)}:${port}/?token=${encodeURIComponent(httpToken)}`;
168
+
169
+ server.listen(port, host, () => {
170
+ getUnattendedWorkflowRunner().recover();
171
+ console.log('\n✓ Web UI 已启动');
172
+ const willOpenBrowser = !!openBrowser && !process.env.CODEXMATE_NO_BROWSER;
173
+ console.log(` ${willOpenBrowser ? '已打开' : '待访问'}: ${openUrl}`);
174
+ if (host && host !== openHost) {
175
+ console.log(' 监听地址:', host);
176
+ }
177
+ console.log(' 退出: Ctrl+C\n');
178
+ if (isAnyAddressHost(host)) {
179
+ console.warn('! 安全提示: 当前监听所有网卡,局域网访问需要访问令牌。');
180
+ console.warn(' 远程 /bridge/ 请求需携带 Authorization: Bearer <访问令牌>。');
181
+ const allowedIps = (process.env.CODEXMATE_ALLOWED_IPS || '').trim();
182
+ if (allowedIps) {
183
+ console.warn(` 已启用的来源 IP 白名单: ${allowedIps}`);
184
+ }
185
+ }
186
+
187
+ if (willOpenBrowser) {
188
+ openBrowserAfterReady(openUrl);
189
+ }
190
+ });
191
+
192
+ const stop = () => new Promise((resolve) => {
193
+ let done = false;
194
+ const finish = () => {
195
+ if (done) return;
196
+ done = true;
197
+ for (const socket of connections) {
198
+ try { socket.destroy(); } catch (_) { }
199
+ }
200
+ connections.clear();
201
+ resolve();
202
+ };
203
+
204
+ if (!server.listening) {
205
+ finish();
206
+ return;
207
+ }
208
+
209
+ server.close(() => finish());
210
+ setTimeout(() => finish(), 800);
211
+ });
212
+
213
+ return { server, stop };
214
+ }
215
+
216
+ module.exports = { createWebServerLifecycle };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codexmate",
3
- "version": "0.1.32",
3
+ "version": "0.1.33",
4
4
  "description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
5
5
  "main": "cli.js",
6
6
  "bin": {
package/web-ui/app.js CHANGED
@@ -1,4 +1,6 @@
1
+ import { configChangeMixin } from './modules/app.methods.config-changes.mjs';
1
2
  import { threadHandoffMixin } from './modules/thread-handoff.mjs';
3
+ import { sessionFeaturesMixin } from './modules/session-features.mjs';
2
4
  import {
3
5
  DEFAULT_MODEL_AUTO_COMPACT_TOKEN_LIMIT,
4
6
  DEFAULT_MODEL_CONTEXT_WINDOW,
@@ -58,7 +60,7 @@ document.addEventListener('DOMContentLoaded', () => {
58
60
  });
59
61
 
60
62
  const appOptions = {
61
- mixins: [threadHandoffMixin],
63
+ mixins: [threadHandoffMixin, configChangeMixin],
62
64
  data() {
63
65
  return {
64
66
  workflowDefinitions: [], workflowRuns: [], workflowId: 'diagnose-config',
@@ -623,6 +625,7 @@ document.addEventListener('DOMContentLoaded', () => {
623
625
  },
624
626
 
625
627
  mounted() {
628
+ if (typeof this.installConfigChangePreview === 'function') this.installConfigChangePreview();
626
629
  this.refreshWorkflowRuns();
627
630
  this.workflowTimer = setInterval(() => this.refreshWorkflowRuns(), 3000);
628
631
  // URL 规范化:将 /web-ui/* 重定向到根路径 /
@@ -835,6 +838,7 @@ document.addEventListener('DOMContentLoaded', () => {
835
838
  },
836
839
 
837
840
  beforeUnmount() {
841
+ if (typeof this.uninstallConfigChangePreview === 'function') this.uninstallConfigChangePreview();
838
842
  clearInterval(this.workflowTimer);
839
843
  this.teardownSessionTabRender();
840
844
  this.cancelScheduledSessionTabDeferredTeardown();
@@ -936,6 +940,7 @@ document.addEventListener('DOMContentLoaded', () => {
936
940
  }
937
941
  },
938
942
  configMode(newMode) {
943
+ if (typeof this.refreshLastConfigChange === 'function') this.refreshLastConfigChange();
939
944
  if (newMode === 'pi' && typeof this.loadPiSources === 'function') {
940
945
  this.loadPiSources();
941
946
  }
@@ -953,6 +958,7 @@ document.addEventListener('DOMContentLoaded', () => {
953
958
  appOptions.render = window.__CODEXMATE_WEB_UI_RENDER__;
954
959
  }
955
960
 
961
+ appOptions.mixins.push(sessionFeaturesMixin);
956
962
  const app = createApp(appOptions);
957
963
  app.config.errorHandler = (err, vm, info) => {
958
964
  console.error('[Vue error handler]', err, info);
package/web-ui/index.html CHANGED
@@ -27,6 +27,7 @@
27
27
  <body>
28
28
  <!-- @include ./partials/index/layout-header.html -->
29
29
  <!-- @include ./partials/index/panel-dashboard.html -->
30
+ <!-- @include ./partials/index/config-changes.html -->
30
31
  <!-- @include ./partials/index/panel-config-codex.html -->
31
32
  <!-- @include ./partials/index/panel-config-claude.html -->
32
33
  <!-- @include ./partials/index/panel-config-openclaw.html -->
@@ -0,0 +1,15 @@
1
+ const WARNING_RATIO = 0.8;
2
+ const HIGH_RATIO = 0.95;
3
+ export function contextWindowReference(report, { model = '', window = '' } = {}) {
4
+ if (!report) return null;
5
+ const models = report.models || [];
6
+ const selected = model || (models.length === 1 ? models[0] : '');
7
+ if (models.length > 1 && !selected) return { status: 'unknown', model: '', source: 'unknown' };
8
+ const manual = window !== '' && window !== null && window !== undefined;
9
+ const size = manual ? Number(window) : Number((report.modelWindows || {})[selected]);
10
+ if (manual && (!Number.isSafeInteger(size) || size <= 0)) throw new Error('context-window-invalid');
11
+ if (!Number.isSafeInteger(size) || size <= 0) return { status: 'unknown', model: selected, source: 'unknown' };
12
+ const ratio = report.totalEstimatedTokens / size;
13
+ return { status: ratio >= HIGH_RATIO ? 'high' : ratio >= WARNING_RATIO ? 'warning' : 'normal',
14
+ model: selected, window: size, ratio, percentage: ratio * 100, source: manual ? 'manual' : 'record', estimated: true };
15
+ }
@@ -1,15 +1,30 @@
1
+ import { withRequestDeadline } from './request-deadline.mjs';
2
+ import { CONFIG_CHANGE_ACTIONS } from './config-change-actions.mjs';
1
3
  import { authorizationHeaders } from './access-token.mjs';
4
+ let configChangeHandler = null;
5
+ const configChangeBaselines = new Map();
6
+
7
+ export function getConfigChangeBaseline(target) {
8
+ return configChangeBaselines.get(target) || [];
9
+ }
10
+
11
+ export function setConfigChangeHandler(handler, expectedHandler) {
12
+ if (expectedHandler && configChangeHandler !== expectedHandler) return;
13
+ configChangeHandler = handler;
14
+ }
15
+
2
16
  const browserLocation = typeof location !== 'undefined' ? location : null;
3
17
 
4
18
  export const API_BASE = (browserLocation && browserLocation.origin && browserLocation.origin !== 'null')
5
19
  ? browserLocation.origin
6
20
  : 'http://localhost:3737';
7
21
 
8
- async function postApi(action, params = {}) {
22
+ async function postApi(action, params = {}, signal) {
9
23
  return await fetch(`${API_BASE}/api`, {
10
24
  method: 'POST',
11
25
  headers: authorizationHeaders({ 'Content-Type': 'application/json' }),
12
- body: JSON.stringify({ action, params })
26
+ body: JSON.stringify({ action, params }),
27
+ ...(signal ? { signal } : {})
13
28
  });
14
29
  }
15
30
 
@@ -44,48 +59,66 @@ function withPayloadTooLargeErrorCode(res, payload) {
44
59
  return { ...payload, errorCode: 'payload-too-large' };
45
60
  }
46
61
 
47
- export async function api(action, params = {}) {
48
- const res = await postApi(action, params);
49
- const contentType = String(res.headers.get('content-type') || '').toLowerCase();
50
- if (contentType && !contentType.includes('application/json')) {
51
- const body = await res.text();
52
- const errorDetails = buildApiResponseContext(action, res, contentType);
53
- const bodySnippet = formatUnexpectedApiBodySnippet(body, contentType);
54
- const bodyDetails = bodySnippet ? `: ${bodySnippet}` : '';
55
- throw new Error(`Unexpected non-JSON API response for ${errorDetails}${bodyDetails}`);
56
- }
57
- try {
58
- return await res.json();
59
- } catch (error) {
60
- const errorDetails = buildApiResponseContext(action, res, contentType);
61
- throw new Error(`Failed to parse API response for ${errorDetails}: ${error.message}`);
62
- }
63
- }
62
+ export async function api(action, params = {}, options = {}) {
64
63
 
65
- export async function apiWithMeta(action, params = {}) {
66
- const res = await postApi(action, params);
67
- const contentType = String(res.headers.get('content-type') || '').toLowerCase();
68
- if (contentType.includes('application/json')) {
64
+ if (configChangeHandler && Object.prototype.hasOwnProperty.call(CONFIG_CHANGE_ACTIONS, action)) return await configChangeHandler(action, params);
65
+ if (configChangeHandler && action === 'start-kilocode' && params.configure === true) {
66
+ const saved = await configChangeHandler('apply-kilocode-config', params);
67
+ if (saved.error || saved.canceled || saved.success === false) return saved;
68
+ return await api(action, { ...params, configure: false }, options);
69
+ }
70
+ return await withRequestDeadline(async (signal) => {
71
+ const res = await postApi(action, params, signal);
72
+ const contentType = String(res.headers.get('content-type') || '').toLowerCase();
73
+ if (contentType && !contentType.includes('application/json')) {
74
+ const body = await res.text();
75
+ const errorDetails = buildApiResponseContext(action, res, contentType);
76
+ const bodySnippet = formatUnexpectedApiBodySnippet(body, contentType);
77
+ const bodyDetails = bodySnippet ? `: ${bodySnippet}` : '';
78
+ throw new Error(`Unexpected non-JSON API response for ${errorDetails}${bodyDetails}`);
79
+ }
69
80
  try {
70
81
  const payload = await res.json();
71
- if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
72
- return { ...withPayloadTooLargeErrorCode(res, payload), ok: res.ok, status: res.status };
82
+ if (payload && payload.configChangeTarget && Array.isArray(payload.configChangeBaseline)) {
83
+ const entries = new Map(getConfigChangeBaseline(payload.configChangeTarget).map(item => [item.path, item]));
84
+ for (const item of payload.configChangeBaseline) entries.set(item.path, item);
85
+ configChangeBaselines.set(payload.configChangeTarget, [...entries.values()]);
73
86
  }
74
- return res.status === 413
75
- ? { ok: res.ok, status: res.status, data: payload, errorCode: 'payload-too-large' }
76
- : { ok: res.ok, status: res.status, data: payload };
87
+ return payload;
77
88
  } catch (error) {
78
- if (res.status === 413) {
79
- return { ok: false, status: 413, errorCode: 'payload-too-large' };
89
+ const errorDetails = buildApiResponseContext(action, res, contentType);
90
+ throw new Error(`Failed to parse API response for ${errorDetails}: ${error.message}`);
91
+ }
92
+ }, options);
93
+ }
94
+
95
+ export async function apiWithMeta(action, params = {}, options = {}) {
96
+
97
+ return await withRequestDeadline(async (signal) => {
98
+ const res = await postApi(action, params, signal);
99
+ const contentType = String(res.headers.get('content-type') || '').toLowerCase();
100
+ if (contentType.includes('application/json')) {
101
+ try {
102
+ const payload = await res.json();
103
+ if (payload && typeof payload === 'object' && !Array.isArray(payload)) {
104
+ return { ...withPayloadTooLargeErrorCode(res, payload), ok: res.ok, status: res.status };
105
+ }
106
+ return res.status === 413
107
+ ? { ok: res.ok, status: res.status, data: payload, errorCode: 'payload-too-large' }
108
+ : { ok: res.ok, status: res.status, data: payload };
109
+ } catch (error) {
110
+ if (res.status === 413) {
111
+ return { ok: false, status: 413, errorCode: 'payload-too-large' };
112
+ }
113
+ throw error;
80
114
  }
81
- throw error;
82
115
  }
83
- }
84
- const error = await res.text();
85
- return {
86
- ok: res.ok,
87
- status: res.status,
88
- error,
89
- errorCode: res.status === 413 ? 'payload-too-large' : ''
90
- };
116
+ const error = await res.text();
117
+ return {
118
+ ok: res.ok,
119
+ status: res.status,
120
+ error,
121
+ errorCode: res.status === 413 ? 'payload-too-large' : ''
122
+ };
123
+ }, options);
91
124
  }
@@ -285,6 +285,11 @@ export function createAgentsMethods(options = {}) {
285
285
  }
286
286
  },
287
287
  handleGlobalKeydown(event) {
288
+ if (this.configChangePreview) {
289
+ if (event.key === 'Escape') { event.preventDefault(); this.closeConfigChangePreview(); }
290
+ else if (event.key === 'Tab') this.trapModalFocus(event);
291
+ return;
292
+ }
288
293
  if (!event) {
289
294
  return;
290
295
  }
@@ -391,6 +391,7 @@ export function createClaudeConfigMethods(options = {}) {
391
391
  const _claudeKey = `${name}|${config.apiKey || ""}|${config.providerCacheRef || ""}|${config.baseUrl || ""}|${config.model || ""}|${config.targetApi || "responses"}`;
392
392
  try {
393
393
  const res = await api('apply-claude-config', { config: { ...config, name } });
394
+ if (res && res.canceled) return;
394
395
  if (res.error || res.success === false) {
395
396
  this.showMessage(res.error || this.t('toast.apply.fail'), 'error');
396
397
  } else {
@@ -512,6 +513,7 @@ export function createClaudeConfigMethods(options = {}) {
512
513
  const _claudeKey2 = `${name}|${config.apiKey || ""}|${config.providerCacheRef || ""}|${config.baseUrl || ""}|${config.model || ""}|${config.targetApi || "responses"}`;
513
514
  try {
514
515
  const res = await api('apply-claude-config', { config: { ...config, name } });
516
+ if (res && res.canceled) return;
515
517
  if (res.error || res.success === false) {
516
518
  if (!silentError) this.showMessage(res.error || this.t('toast.apply.fail'), 'error');
517
519
  return false;
@@ -636,6 +636,7 @@ export function createCodexConfigMethods(options = {}) {
636
636
 
637
637
  for (const item of codexItems) {
638
638
  const res = await api('delete-provider', { name: item.name });
639
+ if (res && res.canceled) return;
639
640
  if (res && res.error) {
640
641
  throw new Error(res.error);
641
642
  }
@@ -861,6 +862,7 @@ export function createCodexConfigMethods(options = {}) {
861
862
  const applyRes = await api('apply-config-template', {
862
863
  template: tplRes.template
863
864
  });
865
+ if (applyRes && applyRes.canceled) return;
864
866
  if (applyRes.error) {
865
867
  this.showMessage(
866
868
  (typeof applyRes.error === 'string' && applyRes.error.trim())
@@ -1048,10 +1050,12 @@ export function createCodexConfigMethods(options = {}) {
1048
1050
  res = await api('apply-claude-settings-raw', {
1049
1051
  content: this.configTemplateContent
1050
1052
  });
1053
+ if (res && res.canceled) return;
1051
1054
  } else {
1052
1055
  res = await api('apply-config-template', {
1053
1056
  template: this.configTemplateContent
1054
1057
  });
1058
+ if (res && res.canceled) return;
1055
1059
  }
1056
1060
  if (res.error) {
1057
1061
  this.showMessage(res.error, 'error');
@@ -1071,6 +1075,11 @@ export function createCodexConfigMethods(options = {}) {
1071
1075
  }
1072
1076
  };
1073
1077
 
1078
+ if (this._configChangeApiHandler) {
1079
+ await performApply();
1080
+ return;
1081
+ }
1082
+
1074
1083
  // One-step mode: apply immediately unless user explicitly entered the diff preview state.
1075
1084
  if (!shouldUseTwoStepConfirm && !this.configTemplateDiffVisible) {
1076
1085
  await performApply();
@@ -0,0 +1,124 @@
1
+ import { CONFIG_CHANGE_ACTIONS } from './config-change-actions.mjs';
2
+ import { api, setConfigChangeHandler, getConfigChangeBaseline } from './api.mjs';
3
+
4
+ export const configChangeMixin = {
5
+ methods: createConfigChangeMethods(),
6
+ data() {
7
+ return { configChangePreview: null, configChangeBusy: false, configChangeApplying: false, configChangeError: '', lastConfigChange: null };
8
+ }
9
+ };
10
+
11
+ export function createConfigChangeMethods() {
12
+ return {
13
+ installConfigChangePreview() {
14
+ this._configChangeApiHandler = (action, params) => this.requestConfigChange(action, params);
15
+ setConfigChangeHandler(this._configChangeApiHandler);
16
+ this.refreshLastConfigChange();
17
+ },
18
+ uninstallConfigChangePreview() {
19
+ setConfigChangeHandler(null, this._configChangeApiHandler);
20
+ this.closeConfigChangePreview({ force: true });
21
+ },
22
+ async requestConfigChange(action, params) {
23
+ if (this.configChangePreview || this.configChangeBusy) return { error: this.t('changes.busy'), success: false };
24
+ this.configChangeBusy = true;
25
+ try {
26
+ const preview = await api('preview-config-change', { action, params, baseline: getConfigChangeBaseline(CONFIG_CHANGE_ACTIONS[action]) });
27
+ if (preview.error) return { ...preview, error: this.configChangeErrorText(preview) };
28
+ if (!preview.hasChanges || this.configTemplateDiffConfirmEnabled === false) {
29
+ const result = await api('apply-config-change', { previewId: preview.previewId });
30
+ if (!result.error) await this.refreshLastConfigChange();
31
+ return result.error ? { ...result, error: this.configChangeErrorText(result) } : result;
32
+ }
33
+ this._configChangeReturnFocus = typeof document !== 'undefined' ? document.activeElement : null;
34
+ this.configChangePreview = preview;
35
+ this.configChangeError = '';
36
+ const pending = new Promise(resolve => { this._configChangeResolve = resolve; });
37
+ if (typeof this.$nextTick === 'function') this.$nextTick(() => this.$refs.configChangeCancel && this.$refs.configChangeCancel.focus());
38
+ return await pending;
39
+ } finally { this.configChangeBusy = false; }
40
+ },
41
+ configChangeErrorText(result) {
42
+ const key = `changes.error.${result.errorCode || ''}`;
43
+ const translated = this.t(key);
44
+ return translated === key ? this.t('changes.failed') : translated;
45
+ },
46
+ closeConfigChangePreview({ force = false } = {}) {
47
+ if (this.configChangeApplying && !force) return;
48
+ const resolve = this._configChangeResolve;
49
+ this._configChangeResolve = null;
50
+ this.configChangePreview = null;
51
+ this.configChangeError = '';
52
+ if (resolve) resolve({ canceled: true, success: false, error: this.t('changes.cancelled') });
53
+ const focus = this._configChangeReturnFocus;
54
+ this._configChangeReturnFocus = null;
55
+ if (focus && typeof focus.focus === 'function') focus.focus();
56
+ },
57
+ async confirmConfigChange() {
58
+ if (!this.configChangePreview || this.configChangeApplying) return;
59
+ this.configChangeApplying = true;
60
+ try {
61
+ const result = await api('apply-config-change', { previewId: this.configChangePreview.previewId });
62
+ if (result.error) {
63
+ this.configChangeError = this.configChangeErrorText(result);
64
+ if (result.rollbackFailed && result.rollbackFailed.length) this.configChangeError += ' ' + this.t('changes.restoreFailed', { paths: result.rollbackFailed.join(', ') });
65
+ return;
66
+ }
67
+ const resolve = this._configChangeResolve;
68
+ this._configChangeResolve = null;
69
+ this.closeConfigChangePreview({ force: true });
70
+ if (resolve) resolve(result);
71
+ await this.refreshLastConfigChange();
72
+ } catch (_) {
73
+ this.configChangeError = this.t('changes.failed');
74
+ } finally { this.configChangeApplying = false; }
75
+ },
76
+ async refreshLastConfigChange() {
77
+ const target = this.configMode;
78
+ try {
79
+ const result = await api('get-last-config-change', { target });
80
+ if (this.configMode === target) this.lastConfigChange = result.change || null;
81
+ } catch (_) {
82
+ if (this.configMode === target) this.lastConfigChange = null;
83
+ }
84
+ },
85
+ async undoLastConfigChange() {
86
+ const change = this.lastConfigChange;
87
+ if (!change || this.configChangeBusy || this.configChangeApplying || !this.isToolConfigWriteAllowed(change.target)) return;
88
+ const confirmed = await this.requestConfirmDialog({
89
+ title: this.t('changes.undo'), message: this.t('changes.undoConfirm', { paths: change.files.map(file => file.path).join('\n') }),
90
+ confirmText: this.t('changes.undo'), cancelText: this.t('common.cancel'), danger: true
91
+ });
92
+ if (!confirmed) return;
93
+ this.configChangeBusy = true;
94
+ try {
95
+ const result = await api('undo-config-change', { target: change.target, changeId: change.id });
96
+ if (result.error) {
97
+ let message = this.configChangeErrorText(result);
98
+ if (result.rollbackFailed && result.rollbackFailed.length) message += ' ' + this.t('changes.restoreFailed', { paths: result.rollbackFailed.join(', ') });
99
+ this.showMessage(message, 'error');
100
+ return;
101
+ }
102
+ this.showMessage(this.t('changes.undone'), 'success');
103
+ await this.refreshLastConfigChange();
104
+ if (change.target === 'codex' || change.target === 'claude') await this.loadAll();
105
+ if (change.target === 'claude') this._lastAppliedClaudeKey = '';
106
+ if (change.target === 'openclaw') await this.syncDefaultOpenclawConfigEntry();
107
+ if (change.target === 'opencode') await this.loadOpencodeConfig();
108
+ if (change.target === 'kilocode') await this.loadKilocodeConfig();
109
+ if (change.target === 'pi') await this.loadPiSources();
110
+ } catch (_) { this.showMessage(this.t('changes.refreshFailed'), 'error'); }
111
+ finally { this.configChangeBusy = false; }
112
+ },
113
+ handleConfigChangeKeydown(event) {
114
+ if (event.key === 'Escape') { event.stopPropagation(); this.closeConfigChangePreview(); return; }
115
+ if (event.key !== 'Tab') return;
116
+ event.stopPropagation();
117
+ const items = [...event.currentTarget.querySelectorAll('button:not(:disabled), [tabindex="0"]')];
118
+ const first = items[0];
119
+ const last = items[items.length - 1];
120
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
121
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
122
+ }
123
+ };
124
+ }
@@ -109,6 +109,7 @@ export function createKilocodeConfigMethods(options = {}) {
109
109
  this.kilocodeError = '';
110
110
  try {
111
111
  const res = await api('apply-kilocode-config', { provider, url, model, apiKey });
112
+ if (res && res.canceled) return;
112
113
  if (res && res.error) {
113
114
  this.kilocodeError = res.error;
114
115
  this.showMessage(res.error, 'error');
@@ -145,6 +146,7 @@ export function createKilocodeConfigMethods(options = {}) {
145
146
  apiKey: this.kilocodeApiKey
146
147
  } : {};
147
148
  const res = await api('start-kilocode', payload);
149
+ if (res && res.canceled) return;
148
150
  if (res && res.error) {
149
151
  this.kilocodeError = res.error;
150
152
  this.showMessage(res.error, 'error');
@@ -294,6 +294,7 @@ export function createOpenclawPersistMethods(options = {}) {
294
294
  lineEnding: this.openclawLineEnding,
295
295
  authProfileUpdates: Object.values(this.openclawPendingAuthProfileUpdates || {})
296
296
  });
297
+ if (res && res.canceled) return;
297
298
  if (res.error || res.success === false) {
298
299
  this.showMessage(res.error || '应用配置失败', 'error');
299
300
  return;
@@ -352,6 +353,7 @@ export function createOpenclawPersistMethods(options = {}) {
352
353
  lineEnding: this.openclawLineEnding,
353
354
  authProfileUpdates: Object.values(this.openclawPendingAuthProfileUpdates || {})
354
355
  });
356
+ if (res && res.canceled) return;
355
357
  if (res.error || res.success === false) {
356
358
  this.showMessage(res.error || '应用配置失败', 'error');
357
359
  } else {