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,141 @@
1
+ import {
2
+ buildSessionTimelineNodes,
3
+ buildUsageChartGroups,
4
+ isSessionQueryEnabled
5
+ } from '../logic.mjs';
6
+ import { SESSION_TRASH_PAGE_SIZE } from './app.constants.mjs';
7
+
8
+ export function createSessionComputed() {
9
+ return {
10
+ isSessionQueryEnabled() {
11
+ return isSessionQueryEnabled(this.sessionFilterSource);
12
+ },
13
+ activeSessionExportKey() {
14
+ return this.activeSession ? this.getSessionExportKey(this.activeSession) : '';
15
+ },
16
+ sortedSessionsList() {
17
+ const list = Array.isArray(this.sessionsList) ? this.sessionsList : [];
18
+ if (list.length === 0) return [];
19
+ const pinnedMap = (this.sessionPinnedMap && typeof this.sessionPinnedMap === 'object')
20
+ ? this.sessionPinnedMap
21
+ : {};
22
+ let hasPinned = false;
23
+ const decorated = list.map((session, index) => {
24
+ const key = session ? this.getSessionExportKey(session) : '';
25
+ const rawPinnedAt = key ? pinnedMap[key] : 0;
26
+ const pinnedAt = Number.isFinite(Number(rawPinnedAt))
27
+ ? Math.floor(Number(rawPinnedAt))
28
+ : 0;
29
+ const isPinned = pinnedAt > 0;
30
+ if (isPinned) {
31
+ hasPinned = true;
32
+ }
33
+ return { session, index, pinnedAt, isPinned };
34
+ });
35
+ if (!hasPinned) return list;
36
+ decorated.sort((a, b) => {
37
+ if (a.isPinned !== b.isPinned) return a.isPinned ? -1 : 1;
38
+ if (a.isPinned && a.pinnedAt !== b.pinnedAt) return b.pinnedAt - a.pinnedAt;
39
+ return a.index - b.index;
40
+ });
41
+ return decorated.map(item => item.session);
42
+ },
43
+ activeSessionVisibleMessages() {
44
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
45
+ return [];
46
+ }
47
+ const list = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages : [];
48
+ const rawCount = Number(this.sessionPreviewVisibleCount);
49
+ const visibleCount = Number.isFinite(rawCount)
50
+ ? Math.max(0, Math.floor(rawCount))
51
+ : 0;
52
+ if (visibleCount <= 0) {
53
+ if (!list.length) return [];
54
+ return list.slice(0, Math.min(8, list.length));
55
+ }
56
+ if (visibleCount >= list.length) return list;
57
+ return list.slice(0, visibleCount);
58
+ },
59
+ canLoadMoreSessionMessages() {
60
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
61
+ return false;
62
+ }
63
+ const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
64
+ const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
65
+ return total > visible;
66
+ },
67
+ sessionPreviewRemainingCount() {
68
+ const total = Array.isArray(this.activeSessionMessages) ? this.activeSessionMessages.length : 0;
69
+ const visible = Array.isArray(this.activeSessionVisibleMessages) ? this.activeSessionVisibleMessages.length : 0;
70
+ return Math.max(0, total - visible);
71
+ },
72
+ sessionTimelineNodes() {
73
+ if (this.mainTab !== 'sessions' || !this.sessionPreviewRenderEnabled) {
74
+ return [];
75
+ }
76
+ return buildSessionTimelineNodes(this.activeSessionVisibleMessages, {
77
+ getKey: (message, index) => this.getRecordRenderKey(message, index)
78
+ });
79
+ },
80
+ sessionTimelineNodeKeyMap() {
81
+ const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
82
+ if (!nodes.length) {
83
+ return Object.create(null);
84
+ }
85
+ const map = Object.create(null);
86
+ for (const node of nodes) {
87
+ if (!node || !node.key) continue;
88
+ map[node.key] = true;
89
+ }
90
+ return map;
91
+ },
92
+ sessionTimelineActiveTitle() {
93
+ if (!this.sessionTimelineActiveKey) return '';
94
+ const nodes = Array.isArray(this.sessionTimelineNodes) ? this.sessionTimelineNodes : [];
95
+ const matched = nodes.find(node => node.key === this.sessionTimelineActiveKey);
96
+ return matched ? matched.title : '';
97
+ },
98
+ sessionQueryPlaceholder() {
99
+ if (this.isSessionQueryEnabled) {
100
+ return '关键词检索(支持 Codex/Claude,例:claude code)';
101
+ }
102
+ return '当前来源暂不支持关键词检索';
103
+ },
104
+ sessionUsageCharts() {
105
+ return buildUsageChartGroups(this.sessionsList, {
106
+ range: this.sessionsUsageTimeRange
107
+ });
108
+ },
109
+ sessionUsageSummaryCards() {
110
+ const summary = this.sessionUsageCharts && this.sessionUsageCharts.summary
111
+ ? this.sessionUsageCharts.summary
112
+ : { totalSessions: 0, totalMessages: 0, activeDays: 0 };
113
+ return [
114
+ { key: 'sessions', label: '总会话数', value: summary.totalSessions || 0 },
115
+ { key: 'messages', label: '总消息数', value: summary.totalMessages || 0 },
116
+ { key: 'days', label: '活跃天数', value: summary.activeDays || 0 }
117
+ ];
118
+ },
119
+ visibleSessionTrashItems() {
120
+ const items = Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems : [];
121
+ const visibleCount = Number(this.sessionTrashVisibleCount);
122
+ const safeVisibleCount = Number.isFinite(visibleCount) && visibleCount > 0
123
+ ? Math.floor(visibleCount)
124
+ : SESSION_TRASH_PAGE_SIZE;
125
+ return items.slice(0, safeVisibleCount);
126
+ },
127
+ sessionTrashHasMoreItems() {
128
+ return this.visibleSessionTrashItems.length < this.sessionTrashCount;
129
+ },
130
+ sessionTrashHiddenCount() {
131
+ return Math.max(0, this.sessionTrashCount - this.visibleSessionTrashItems.length);
132
+ },
133
+ sessionTrashCount() {
134
+ const totalCount = Number(this.sessionTrashTotalCount);
135
+ if (Number.isFinite(totalCount) && totalCount >= 0) {
136
+ return Math.max(0, Math.floor(totalCount));
137
+ }
138
+ return Array.isArray(this.sessionTrashItems) ? this.sessionTrashItems.length : 0;
139
+ }
140
+ };
141
+ }
@@ -0,0 +1,15 @@
1
+ export const SESSION_TRASH_LIST_LIMIT = 500;
2
+ export const SESSION_TRASH_PAGE_SIZE = 200;
3
+ export const DEFAULT_MODEL_CONTEXT_WINDOW = 190000;
4
+ export const DEFAULT_MODEL_AUTO_COMPACT_TOKEN_LIMIT = 185000;
5
+ export const DEFAULT_OPENCLAW_TEMPLATE = `{
6
+ // OpenClaw config (JSON5)
7
+ agent: {
8
+ model: "gpt-4.1"
9
+ },
10
+ agents: {
11
+ defaults: {
12
+ workspace: "~/.openclaw/workspace"
13
+ }
14
+ }
15
+ }`;
@@ -0,0 +1,493 @@
1
+ import {
2
+ buildAgentsDiffPreview,
3
+ buildAgentsDiffPreviewRequest,
4
+ isAgentsDiffPreviewPayloadTooLarge,
5
+ shouldApplyAgentsDiffPreviewResponse
6
+ } from '../logic.mjs';
7
+
8
+ function isValidOpenclawWorkspaceFileName(fileName) {
9
+ if (typeof fileName !== 'string') {
10
+ return false;
11
+ }
12
+ const normalized = fileName.trim();
13
+ if (!normalized || !normalized.endsWith('.md')) {
14
+ return false;
15
+ }
16
+ if (normalized.startsWith('/') || normalized.includes('\\') || normalized.includes('/') || normalized.includes('..')) {
17
+ return false;
18
+ }
19
+ return true;
20
+ }
21
+
22
+ function issueLatestRequestToken(context, key) {
23
+ const token = (Number(context[key]) || 0) + 1;
24
+ context[key] = token;
25
+ return token;
26
+ }
27
+
28
+ function isLatestRequestToken(context, key, token) {
29
+ return !!context && context[key] === token;
30
+ }
31
+
32
+ export function createAgentsMethods(options = {}) {
33
+ const {
34
+ api,
35
+ apiWithMeta
36
+ } = options;
37
+
38
+ return {
39
+ async openAgentsEditor() {
40
+ this.setAgentsModalContext('codex');
41
+ const requestToken = issueLatestRequestToken(this, '_agentsOpenRequestToken');
42
+ this.agentsLoading = true;
43
+ try {
44
+ const res = await api('get-agents-file');
45
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
46
+ return;
47
+ }
48
+ if (res.error) {
49
+ this.showMessage(res.error, 'error');
50
+ return;
51
+ }
52
+ this.agentsContent = res.content || '';
53
+ this.agentsOriginalContent = this.agentsContent;
54
+ this.agentsPath = res.path || '';
55
+ this.agentsExists = !!res.exists;
56
+ this.agentsLineEnding = res.lineEnding === '\r\n' ? '\r\n' : '\n';
57
+ this.resetAgentsDiffState();
58
+ this.showAgentsModal = true;
59
+ } catch (e) {
60
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
61
+ return;
62
+ }
63
+ this.showMessage('加载文件失败', 'error');
64
+ } finally {
65
+ if (isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
66
+ this.agentsLoading = false;
67
+ }
68
+ }
69
+ },
70
+
71
+ async openOpenclawAgentsEditor() {
72
+ this.setAgentsModalContext('openclaw');
73
+ const requestToken = issueLatestRequestToken(this, '_agentsOpenRequestToken');
74
+ this.agentsLoading = true;
75
+ try {
76
+ const res = await api('get-openclaw-agents-file');
77
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
78
+ return;
79
+ }
80
+ if (res.error) {
81
+ this.showMessage(res.error, 'error');
82
+ return;
83
+ }
84
+ if (res.configError) {
85
+ this.showMessage(`OpenClaw 配置解析失败,已使用默认 Workspace:${res.configError}`, 'error');
86
+ }
87
+ this.agentsContent = res.content || '';
88
+ this.agentsOriginalContent = this.agentsContent;
89
+ this.agentsPath = res.path || '';
90
+ this.agentsExists = !!res.exists;
91
+ this.agentsLineEnding = res.lineEnding === '\r\n' ? '\r\n' : '\n';
92
+ this.resetAgentsDiffState();
93
+ this.showAgentsModal = true;
94
+ } catch (e) {
95
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
96
+ return;
97
+ }
98
+ this.showMessage('加载文件失败', 'error');
99
+ } finally {
100
+ if (isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
101
+ this.agentsLoading = false;
102
+ }
103
+ }
104
+ },
105
+
106
+ async openOpenclawWorkspaceEditor() {
107
+ const fileName = (this.openclawWorkspaceFileName || '').trim();
108
+ if (!fileName) {
109
+ this.showMessage('请输入文件名', 'error');
110
+ return;
111
+ }
112
+ if (!isValidOpenclawWorkspaceFileName(fileName)) {
113
+ this.showMessage('仅支持 OpenClaw Workspace 内的 `.md` 文件', 'error');
114
+ return;
115
+ }
116
+ this.setAgentsModalContext('openclaw-workspace', { fileName });
117
+ const requestToken = issueLatestRequestToken(this, '_agentsOpenRequestToken');
118
+ this.agentsLoading = true;
119
+ try {
120
+ const res = await api('get-openclaw-workspace-file', { fileName });
121
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
122
+ return;
123
+ }
124
+ if (res.error) {
125
+ this.showMessage(res.error, 'error');
126
+ return;
127
+ }
128
+ if (res.configError) {
129
+ this.showMessage(`OpenClaw 配置解析失败,已使用默认 Workspace:${res.configError}`, 'error');
130
+ }
131
+ this.agentsContent = res.content || '';
132
+ this.agentsOriginalContent = this.agentsContent;
133
+ this.agentsPath = res.path || '';
134
+ this.agentsExists = !!res.exists;
135
+ this.agentsLineEnding = res.lineEnding === '\r\n' ? '\r\n' : '\n';
136
+ this.resetAgentsDiffState();
137
+ this.showAgentsModal = true;
138
+ } catch (e) {
139
+ if (!isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
140
+ return;
141
+ }
142
+ this.showMessage('加载文件失败', 'error');
143
+ } finally {
144
+ if (isLatestRequestToken(this, '_agentsOpenRequestToken', requestToken)) {
145
+ this.agentsLoading = false;
146
+ }
147
+ }
148
+ },
149
+
150
+ setAgentsModalContext(context, options = {}) {
151
+ if (context === 'openclaw-workspace') {
152
+ const fileName = (options.fileName || this.openclawWorkspaceFileName || 'AGENTS.md').trim();
153
+ this.agentsContext = 'openclaw-workspace';
154
+ this.agentsWorkspaceFileName = fileName;
155
+ this.agentsModalTitle = `OpenClaw 工作区文件: ${fileName}`;
156
+ this.agentsModalHint = `保存后会写入 OpenClaw Workspace 下的 ${fileName}。`;
157
+ return;
158
+ }
159
+ this.agentsContext = context === 'openclaw' ? 'openclaw' : 'codex';
160
+ if (this.agentsContext === 'openclaw') {
161
+ this.agentsModalTitle = 'OpenClaw AGENTS.md 编辑器';
162
+ this.agentsModalHint = '保存后会写入 OpenClaw Workspace 下的 AGENTS.md。';
163
+ } else {
164
+ this.agentsModalTitle = 'AGENTS.md 编辑器';
165
+ this.agentsModalHint = '保存后会写入目标 AGENTS.md(与 config.toml 同级)。';
166
+ }
167
+ this.agentsWorkspaceFileName = '';
168
+ },
169
+
170
+ resetAgentsDiffState() {
171
+ this.agentsDiffVisible = false;
172
+ this.agentsDiffLoading = false;
173
+ this.agentsDiffError = '';
174
+ this.agentsDiffLines = [];
175
+ this.agentsDiffStats = {
176
+ added: 0,
177
+ removed: 0,
178
+ unchanged: 0
179
+ };
180
+ this.agentsDiffTruncated = false;
181
+ this.agentsDiffHasChangesValue = false;
182
+ this.agentsDiffFingerprint = '';
183
+ this._agentsDiffPreviewRequestToken = null;
184
+ },
185
+ handleGlobalKeydown(event) {
186
+ if (!event || event.key !== 'Escape') {
187
+ return;
188
+ }
189
+ if (this.showConfirmDialog) {
190
+ event.preventDefault();
191
+ event.stopPropagation();
192
+ this.resolveConfirmDialog(false);
193
+ return;
194
+ }
195
+ if (!this.showAgentsModal) {
196
+ return;
197
+ }
198
+ event.preventDefault();
199
+ event.stopPropagation();
200
+ if (this.agentsSaving || this.agentsDiffLoading) {
201
+ return;
202
+ }
203
+ if (this.agentsDiffVisible) {
204
+ this.resetAgentsDiffState();
205
+ return;
206
+ }
207
+ this.closeAgentsModal();
208
+ },
209
+ hasPendingAgentsDraft() {
210
+ if (!this.showAgentsModal || this.agentsLoading) {
211
+ return false;
212
+ }
213
+ return !!this.agentsSaving || this.hasAgentsContentChanged() || this.agentsDiffVisible;
214
+ },
215
+ handleBeforeUnload(event) {
216
+ if (!this.hasPendingAgentsDraft()) {
217
+ return;
218
+ }
219
+ if (event && typeof event.preventDefault === 'function') {
220
+ event.preventDefault();
221
+ event.returnValue = '';
222
+ }
223
+ return '';
224
+ },
225
+ hasAgentsContentChanged() {
226
+ const original = typeof this.agentsOriginalContent === 'string' ? this.agentsOriginalContent : '';
227
+ const current = typeof this.agentsContent === 'string' ? this.agentsContent : '';
228
+ return original !== current;
229
+ },
230
+ requestConfirmDialog(options = {}) {
231
+ if (typeof this.confirmDialogResolver === 'function') {
232
+ this.confirmDialogResolver(false);
233
+ }
234
+ const confirmDisabled = options.confirmDisabled;
235
+ this.confirmDialogTitle = typeof options.title === 'string' && options.title.trim()
236
+ ? options.title.trim()
237
+ : '请确认操作';
238
+ this.confirmDialogMessage = typeof options.message === 'string' ? options.message : '';
239
+ this.confirmDialogConfirmText = typeof options.confirmText === 'string' && options.confirmText.trim()
240
+ ? options.confirmText.trim()
241
+ : '确认';
242
+ this.confirmDialogCancelText = typeof options.cancelText === 'string' && options.cancelText.trim()
243
+ ? options.cancelText.trim()
244
+ : '取消';
245
+ this.confirmDialogDanger = !!options.danger;
246
+ this.confirmDialogConfirmDisabled = typeof confirmDisabled === 'function' ? false : !!confirmDisabled;
247
+ this.confirmDialogDisableWhen = typeof confirmDisabled === 'function' ? confirmDisabled : null;
248
+ this.showConfirmDialog = true;
249
+ return new Promise((resolve) => {
250
+ this.confirmDialogResolver = resolve;
251
+ });
252
+ },
253
+ isConfirmDialogDisabled() {
254
+ if (typeof this.confirmDialogDisableWhen === 'function') {
255
+ try {
256
+ return !!this.confirmDialogDisableWhen.call(this);
257
+ } catch (_) {
258
+ return true;
259
+ }
260
+ }
261
+ return !!this.confirmDialogConfirmDisabled;
262
+ },
263
+ resolveConfirmDialog(confirmed) {
264
+ const resolver = typeof this.confirmDialogResolver === 'function'
265
+ ? this.confirmDialogResolver
266
+ : null;
267
+ this.showConfirmDialog = false;
268
+ this.confirmDialogTitle = '';
269
+ this.confirmDialogMessage = '';
270
+ this.confirmDialogConfirmText = '确认';
271
+ this.confirmDialogCancelText = '取消';
272
+ this.confirmDialogDanger = false;
273
+ this.confirmDialogConfirmDisabled = false;
274
+ this.confirmDialogDisableWhen = null;
275
+ this.confirmDialogResolver = null;
276
+ if (resolver) {
277
+ resolver(!!confirmed);
278
+ }
279
+ },
280
+ closeConfirmDialog() {
281
+ this.resolveConfirmDialog(false);
282
+ },
283
+ onAgentsContentInput() {
284
+ if (this.agentsDiffVisible || this.agentsDiffLines.length) {
285
+ this.resetAgentsDiffState();
286
+ }
287
+ },
288
+ buildAgentsDiffFingerprint() {
289
+ const context = this.agentsContext || 'codex';
290
+ const fileName = context === 'openclaw-workspace'
291
+ ? (this.agentsWorkspaceFileName || '')
292
+ : '';
293
+ const lineEnding = this.agentsLineEnding || '\n';
294
+ const content = typeof this.agentsContent === 'string' ? this.agentsContent : '';
295
+ const original = typeof this.agentsOriginalContent === 'string' ? this.agentsOriginalContent : '';
296
+ return `${context}::${fileName}::${lineEnding}::${content.length}::${content}::${original.length}::${original}`;
297
+ },
298
+ async prepareAgentsDiff() {
299
+ const requestFingerprint = this.buildAgentsDiffFingerprint();
300
+ const requestToken = Symbol('agents-diff-preview');
301
+ this._agentsDiffPreviewRequestToken = requestToken;
302
+ this.agentsDiffVisible = true;
303
+ this.agentsDiffLoading = true;
304
+ this.agentsDiffError = '';
305
+ this.agentsDiffLines = [];
306
+ this.agentsDiffStats = {
307
+ added: 0,
308
+ removed: 0,
309
+ unchanged: 0
310
+ };
311
+ this.agentsDiffTruncated = false;
312
+ this.agentsDiffHasChangesValue = false;
313
+ try {
314
+ const shouldApplyPreviewState = () => shouldApplyAgentsDiffPreviewResponse({
315
+ isVisible: this.agentsDiffVisible,
316
+ requestToken,
317
+ activeRequestToken: this._agentsDiffPreviewRequestToken,
318
+ requestFingerprint,
319
+ currentFingerprint: this.buildAgentsDiffFingerprint()
320
+ });
321
+ const applyPreviewState = (diff) => {
322
+ if (!shouldApplyPreviewState()) {
323
+ return false;
324
+ }
325
+ const normalizedDiff = diff && typeof diff === 'object' ? diff : {};
326
+ const rawLines = Array.isArray(normalizedDiff.lines) ? normalizedDiff.lines : [];
327
+ this.agentsDiffLines = rawLines.filter(line => line && line.type);
328
+ this.agentsDiffTruncated = !!normalizedDiff.truncated;
329
+ this.agentsDiffHasChangesValue = !!normalizedDiff.hasChanges;
330
+ if (normalizedDiff.stats && typeof normalizedDiff.stats === 'object') {
331
+ this.agentsDiffStats = {
332
+ added: Number(normalizedDiff.stats.added || 0),
333
+ removed: Number(normalizedDiff.stats.removed || 0),
334
+ unchanged: Number(normalizedDiff.stats.unchanged || 0)
335
+ };
336
+ } else {
337
+ const stats = { added: 0, removed: 0, unchanged: 0 };
338
+ for (const line of this.agentsDiffLines) {
339
+ if (line && line.type === 'add') stats.added += 1;
340
+ else if (line && line.type === 'del') stats.removed += 1;
341
+ else stats.unchanged += 1;
342
+ }
343
+ this.agentsDiffStats = stats;
344
+ }
345
+ this.agentsDiffFingerprint = requestFingerprint;
346
+ return true;
347
+ };
348
+ const previewRequest = buildAgentsDiffPreviewRequest({
349
+ baseContent: this.agentsOriginalContent,
350
+ content: this.agentsContent,
351
+ lineEnding: this.agentsLineEnding,
352
+ context: this.agentsContext,
353
+ fileName: this.agentsWorkspaceFileName
354
+ });
355
+ if (previewRequest.exceedsBodyLimit) {
356
+ applyPreviewState(buildAgentsDiffPreview({
357
+ baseContent: this.agentsOriginalContent,
358
+ content: this.agentsContent
359
+ }));
360
+ return;
361
+ }
362
+ const res = await apiWithMeta('preview-agents-diff', previewRequest.params);
363
+ if (!shouldApplyPreviewState()) {
364
+ return;
365
+ }
366
+ if (res.error) {
367
+ if (isAgentsDiffPreviewPayloadTooLarge(res)) {
368
+ applyPreviewState(buildAgentsDiffPreview({
369
+ baseContent: this.agentsOriginalContent,
370
+ content: this.agentsContent
371
+ }));
372
+ return;
373
+ }
374
+ this.agentsDiffError = res.error;
375
+ return;
376
+ }
377
+ applyPreviewState(res.diff);
378
+ } catch (e) {
379
+ if (shouldApplyAgentsDiffPreviewResponse({
380
+ isVisible: this.agentsDiffVisible,
381
+ requestToken,
382
+ activeRequestToken: this._agentsDiffPreviewRequestToken,
383
+ requestFingerprint,
384
+ currentFingerprint: this.buildAgentsDiffFingerprint()
385
+ })) {
386
+ this.agentsDiffError = '生成差异失败';
387
+ }
388
+ } finally {
389
+ if (this._agentsDiffPreviewRequestToken === requestToken) {
390
+ this.agentsDiffLoading = false;
391
+ }
392
+ }
393
+ },
394
+
395
+ async closeAgentsModal(options = {}) {
396
+ const force = !!(options && options.force);
397
+ if (!force && (this.agentsSaving || this.agentsDiffLoading)) {
398
+ return;
399
+ }
400
+ const shouldConfirmClose = !force
401
+ && this.hasPendingAgentsDraft();
402
+ if (shouldConfirmClose) {
403
+ const message = this.agentsDiffVisible
404
+ ? '当前处于差异预览模式,改动尚未保存。确认放弃改动并关闭吗?'
405
+ : '存在未保存改动,确认放弃改动并关闭吗?(关闭页面或应用也会丢失改动)';
406
+ const confirmed = await this.requestConfirmDialog({
407
+ title: '放弃未保存改动',
408
+ message,
409
+ confirmText: '放弃并关闭',
410
+ cancelText: '继续编辑',
411
+ danger: true
412
+ });
413
+ if (!confirmed) {
414
+ return;
415
+ }
416
+ }
417
+ issueLatestRequestToken(this, '_agentsOpenRequestToken');
418
+ this.agentsLoading = false;
419
+ this.showAgentsModal = false;
420
+ this.agentsContent = '';
421
+ this.agentsOriginalContent = '';
422
+ this.agentsPath = '';
423
+ this.agentsExists = false;
424
+ this.agentsLineEnding = '\n';
425
+ this.agentsSaving = false;
426
+ this.agentsWorkspaceFileName = '';
427
+ this.resetAgentsDiffState();
428
+ this.setAgentsModalContext('codex');
429
+ },
430
+
431
+ async applyAgentsContent() {
432
+ if (this.agentsSaving) {
433
+ return;
434
+ }
435
+ if (!this.agentsDiffVisible) {
436
+ if (!this.hasAgentsContentChanged()) {
437
+ this.showMessage('未检测到改动', 'info');
438
+ return;
439
+ }
440
+ await this.prepareAgentsDiff();
441
+ return;
442
+ }
443
+ if (this.agentsDiffLoading) {
444
+ return;
445
+ }
446
+ if (this.agentsDiffError) {
447
+ this.showMessage(this.agentsDiffError, 'error');
448
+ return;
449
+ }
450
+ const fingerprint = this.buildAgentsDiffFingerprint();
451
+ if (this.agentsDiffFingerprint !== fingerprint) {
452
+ await this.prepareAgentsDiff();
453
+ return;
454
+ }
455
+ if (!this.agentsDiffHasChanges) {
456
+ this.showMessage('未检测到改动', 'info');
457
+ return;
458
+ }
459
+ if (this.agentsContext === 'openclaw-workspace' && !isValidOpenclawWorkspaceFileName(this.agentsWorkspaceFileName)) {
460
+ this.showMessage('仅支持 OpenClaw Workspace 内的 `.md` 文件', 'error');
461
+ return;
462
+ }
463
+ this.agentsSaving = true;
464
+ try {
465
+ let action = 'apply-agents-file';
466
+ const params = {
467
+ content: this.agentsContent,
468
+ lineEnding: this.agentsLineEnding
469
+ };
470
+ if (this.agentsContext === 'openclaw') {
471
+ action = 'apply-openclaw-agents-file';
472
+ } else if (this.agentsContext === 'openclaw-workspace') {
473
+ action = 'apply-openclaw-workspace-file';
474
+ params.fileName = this.agentsWorkspaceFileName;
475
+ }
476
+ const res = await api(action, params);
477
+ if (res.error) {
478
+ this.showMessage(res.error, 'error');
479
+ return;
480
+ }
481
+ const successLabel = this.agentsContext === 'openclaw-workspace'
482
+ ? `工作区文件已保存${this.agentsWorkspaceFileName ? `: ${this.agentsWorkspaceFileName}` : ''}`
483
+ : (this.agentsContext === 'openclaw' ? 'OpenClaw AGENTS.md 已保存' : 'AGENTS.md 已保存');
484
+ this.showMessage(successLabel, 'success');
485
+ this.closeAgentsModal({ force: true });
486
+ } catch (e) {
487
+ this.showMessage('保存失败', 'error');
488
+ } finally {
489
+ this.agentsSaving = false;
490
+ }
491
+ }
492
+ };
493
+ }