codexmate 0.1.31 → 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 (92) hide show
  1. package/README.md +8 -3
  2. package/README.vi.md +8 -3
  3. package/README.zh.md +8 -3
  4. package/cli/agents-files.js +18 -4
  5. package/cli/claude-proxy.js +2 -2
  6. package/cli/plugin-config.js +64 -0
  7. package/cli/prompt-history.js +19 -4
  8. package/cli/system-prompt-files.js +7 -2
  9. package/cli.js +200 -214
  10. package/lib/cli-config-engine.js +15 -4
  11. package/lib/cli-file-utils.js +6 -1
  12. package/lib/config-change-fs.js +132 -0
  13. package/lib/config-changes.js +293 -0
  14. package/lib/handoff-mcp.js +18 -2
  15. package/lib/local-feature-store.js +39 -0
  16. package/lib/session-bookmarks.js +72 -0
  17. package/lib/session-context-health.js +102 -0
  18. package/lib/session-context-records.js +153 -0
  19. package/lib/session-diagnostics.js +75 -0
  20. package/lib/session-feature-settings.js +21 -0
  21. package/lib/session-features.js +63 -0
  22. package/lib/session-handoff-draft.js +43 -0
  23. package/lib/session-projects.js +76 -0
  24. package/lib/session-search-index.js +188 -0
  25. package/lib/thread-handoff.js +8 -0
  26. package/lib/web-server.js +216 -0
  27. package/lib/web-startup-auth.js +5 -1
  28. package/package.json +1 -1
  29. package/plugins/prompt-templates/computed.mjs +3 -3
  30. package/plugins/prompt-templates/invocation.mjs +73 -0
  31. package/plugins/prompt-templates/methods.mjs +48 -3
  32. package/plugins/prompt-templates/overview.mjs +2 -0
  33. package/web-ui/app.js +32 -1
  34. package/web-ui/index.html +2 -0
  35. package/web-ui/logic.context-health.mjs +144 -0
  36. package/web-ui/logic.context-window.mjs +15 -0
  37. package/web-ui/modules/api.mjs +72 -39
  38. package/web-ui/modules/app.computed.prompts.mjs +11 -0
  39. package/web-ui/modules/app.methods.agents.mjs +25 -3
  40. package/web-ui/modules/app.methods.claude-config.mjs +2 -0
  41. package/web-ui/modules/app.methods.codex-config.mjs +9 -0
  42. package/web-ui/modules/app.methods.config-changes.mjs +124 -0
  43. package/web-ui/modules/app.methods.index.mjs +4 -0
  44. package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
  45. package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
  46. package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
  47. package/web-ui/modules/app.methods.pi-config.mjs +12 -3
  48. package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
  49. package/web-ui/modules/app.methods.providers.mjs +6 -0
  50. package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
  51. package/web-ui/modules/app.methods.system-prompt.mjs +17 -2
  52. package/web-ui/modules/config-change-actions.mjs +9 -0
  53. package/web-ui/modules/context-health.methods.mjs +70 -0
  54. package/web-ui/modules/i18n/locales/en.mjs +164 -4
  55. package/web-ui/modules/i18n/locales/ja.mjs +164 -4
  56. package/web-ui/modules/i18n/locales/vi.mjs +164 -4
  57. package/web-ui/modules/i18n/locales/zh-tw.mjs +164 -4
  58. package/web-ui/modules/i18n/locales/zh.mjs +164 -4
  59. package/web-ui/modules/plugins.methods.mjs +2 -0
  60. package/web-ui/modules/prompt-ecosystem.methods.mjs +136 -0
  61. package/web-ui/modules/request-deadline.mjs +33 -0
  62. package/web-ui/modules/session-features.mjs +279 -0
  63. package/web-ui/modules/thread-handoff.mjs +1 -1
  64. package/web-ui/partials/index/config-changes.html +25 -0
  65. package/web-ui/partials/index/context-health.html +45 -0
  66. package/web-ui/partials/index/context-window-reference.html +17 -0
  67. package/web-ui/partials/index/layout-header.html +7 -30
  68. package/web-ui/partials/index/modal-openclaw-config.html +0 -2
  69. package/web-ui/partials/index/modal-prompt-invocation.html +17 -0
  70. package/web-ui/partials/index/modal-skills.html +0 -1
  71. package/web-ui/partials/index/modals-basic.html +0 -8
  72. package/web-ui/partials/index/modals-pi-provider.html +0 -1
  73. package/web-ui/partials/index/panel-config-codex.html +0 -3
  74. package/web-ui/partials/index/panel-config-openclaw.html +16 -13
  75. package/web-ui/partials/index/panel-dashboard.html +0 -2
  76. package/web-ui/partials/index/panel-plugins.html +37 -10
  77. package/web-ui/partials/index/panel-prompts.html +18 -3
  78. package/web-ui/partials/index/panel-sessions.html +23 -11
  79. package/web-ui/partials/index/panel-settings.html +1 -12
  80. package/web-ui/partials/index/panel-trash.html +0 -1
  81. package/web-ui/partials/index/session-diagnostics.html +29 -0
  82. package/web-ui/partials/index/session-features.html +107 -0
  83. package/web-ui/partials/index/thread-handoff.html +6 -3
  84. package/web-ui/res/web-ui-render.precompiled.js +1863 -271
  85. package/web-ui/styles/config-changes.css +30 -0
  86. package/web-ui/styles/context-health.css +107 -0
  87. package/web-ui/styles/openclaw-structured.css +205 -189
  88. package/web-ui/styles/prompts-editor.css +23 -0
  89. package/web-ui/styles/session-features.css +148 -0
  90. package/web-ui/styles/sessions-preview.css +21 -0
  91. package/web-ui/styles/sub-tabs.css +181 -0
  92. package/web-ui/styles.css +5 -1
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',
@@ -191,6 +193,23 @@ document.addEventListener('DOMContentLoaded', () => {
191
193
  promptComposerPickerKeyword: '',
192
194
  promptComposerSelectedTemplateId: '',
193
195
  promptComposerVarValuesRaw: {},
196
+ promptInvocationVisible: false,
197
+ promptInvocationTemplate: '',
198
+ promptInvocationNames: [],
199
+ promptInvocationValues: {},
200
+ promptInvocationResolve: null,
201
+ promptInvocationReturnFocus: null,
202
+ promptInvocationError: '',
203
+ pluginConfigHash: '',
204
+ pluginHistoryBucket: '',
205
+ pluginConfigLoaded: false,
206
+ pluginConfigSaving: false,
207
+ pluginHistoryVisible: false,
208
+ pluginHistoryLoading: false,
209
+ pluginHistoryItems: [],
210
+ pluginHistorySelectedId: '',
211
+ pluginHistoryContent: '',
212
+ pluginHistoryError: '',
194
213
  showConfirmDialog: false,
195
214
  confirmDialogTitle: '',
196
215
  confirmDialogMessage: '',
@@ -357,6 +376,14 @@ document.addEventListener('DOMContentLoaded', () => {
357
376
  activeSessionDetailClipped: false,
358
377
  sessionDetailLoading: false,
359
378
  sessionDetailRequestSeq: 0,
379
+ sessionContextHealth: null,
380
+ sessionContextHealthStamp: '',
381
+ sessionContextHealthLoading: false,
382
+ sessionContextHealthError: '',
383
+ sessionContextHealthExpanded: false,
384
+ sessionContextHealthPinned: false,
385
+ sessionContextHealthFocusedNode: null,
386
+ sessionContextHealthNodeLoading: false,
360
387
  sessionDetailInitialMessageLimit: 300,
361
388
  sessionDetailFetchStep: 300,
362
389
  sessionDetailMessageLimit: 80,
@@ -598,6 +625,7 @@ document.addEventListener('DOMContentLoaded', () => {
598
625
  },
599
626
 
600
627
  mounted() {
628
+ if (typeof this.installConfigChangePreview === 'function') this.installConfigChangePreview();
601
629
  this.refreshWorkflowRuns();
602
630
  this.workflowTimer = setInterval(() => this.refreshWorkflowRuns(), 3000);
603
631
  // URL 规范化:将 /web-ui/* 重定向到根路径 /
@@ -810,6 +838,7 @@ document.addEventListener('DOMContentLoaded', () => {
810
838
  },
811
839
 
812
840
  beforeUnmount() {
841
+ if (typeof this.uninstallConfigChangePreview === 'function') this.uninstallConfigChangePreview();
813
842
  clearInterval(this.workflowTimer);
814
843
  this.teardownSessionTabRender();
815
844
  this.cancelScheduledSessionTabDeferredTeardown();
@@ -911,6 +940,7 @@ document.addEventListener('DOMContentLoaded', () => {
911
940
  }
912
941
  },
913
942
  configMode(newMode) {
943
+ if (typeof this.refreshLastConfigChange === 'function') this.refreshLastConfigChange();
914
944
  if (newMode === 'pi' && typeof this.loadPiSources === 'function') {
915
945
  this.loadPiSources();
916
946
  }
@@ -928,6 +958,7 @@ document.addEventListener('DOMContentLoaded', () => {
928
958
  appOptions.render = window.__CODEXMATE_WEB_UI_RENDER__;
929
959
  }
930
960
 
961
+ appOptions.mixins.push(sessionFeaturesMixin);
931
962
  const app = createApp(appOptions);
932
963
  app.config.errorHandler = (err, vm, info) => {
933
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 -->
@@ -44,6 +45,7 @@
44
45
  <!-- @include ./partials/index/panel-prompts.html -->
45
46
  <!-- @include ./partials/index/layout-footer.html -->
46
47
  <!-- @include ./partials/index/modals-basic.html -->
48
+ <!-- @include ./partials/index/modal-prompt-invocation.html -->
47
49
  <!-- @include ./partials/index/modal-webhook.html -->
48
50
  <!-- @include ./partials/index/modal-openclaw-config.html -->
49
51
  <!-- @include ./partials/index/modal-config-template-agents.html -->
@@ -0,0 +1,144 @@
1
+ import { estimatePromptTokenCount } from './logic.prompts-token-count.mjs';
2
+
3
+ export const CONTEXT_CATEGORIES = ['system', 'user', 'assistant', 'tools', 'code'];
4
+ const HEALTHY_LIMIT = 32000;
5
+ const HEAVY_LIMIT = 64000;
6
+ const DOMINANT_SHARE = 0.15;
7
+ const TOP_CANDIDATES = 7;
8
+ const PREVIEW_LENGTH = 120;
9
+ const LONG_ERROR_TOKENS = 1024;
10
+ const LONG_ERROR_LINES = 100;
11
+ const ERROR_PATTERN = /Traceback|(?:Error|Exception)(?::|\b)|^\s+at .+\(.+:\d+/m;
12
+ const RULE_PATTERN = /<(system-reminder|instructions|user_instructions|developer_instructions|environment_context|project_rules|skills_instructions)>[\s\S]*?<\/\1>/gi;
13
+
14
+ export function contextHealthLevel(tokens) {
15
+ return tokens < HEALTHY_LIMIT ? 'healthy' : (tokens <= HEAVY_LIMIT ? 'heavy' : 'bloated');
16
+ }
17
+
18
+ function splitRules(text, category) {
19
+ if (category === 'system' || /^#\s*AGENTS\.md instructions\b/i.test(text.trimStart())) {
20
+ return [{ category: 'system', text }];
21
+ }
22
+ const parts = [];
23
+ let start = 0;
24
+ for (const match of text.matchAll(RULE_PATTERN)) {
25
+ if (match.index > start) parts.push({ category, text: text.slice(start, match.index) });
26
+ parts.push({ category: 'system', text: match[0] });
27
+ start = match.index + match[0].length;
28
+ }
29
+ if (start < text.length) parts.push({ category, text: text.slice(start) });
30
+ return parts;
31
+ }
32
+
33
+ export function splitContextText(text, category) {
34
+ if (!text) return [];
35
+ if (category === 'code') return [{ category, text }];
36
+ const lines = text.match(/[^\n]*\n|[^\n]+$/g) || [];
37
+ const parts = [];
38
+ let prose = '';
39
+ let code = '';
40
+ let fence = '';
41
+ let diff = false;
42
+ let patch = false;
43
+ for (let index = 0; index < lines.length; index++) {
44
+ const line = lines[index];
45
+ const marker = line.match(/^\s*(`{3,}|~{3,})/);
46
+ if (diff && !patch && !/^(?:[ +\-]|@@ |diff --git |index |new file|deleted file|rename |similarity |\\ No newline)/.test(line)) {
47
+ parts.push({ category: 'code', text: code });
48
+ code = ''; diff = false;
49
+ }
50
+ if (fence) {
51
+ code += line;
52
+ if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && /^\s*(`{3,}|~{3,})\s*$/.test(line)) {
53
+ parts.push({ category: 'code', text: code }); code = ''; fence = '';
54
+ }
55
+ } else if (diff) {
56
+ code += line;
57
+ if (patch && /^\*\*\* End Patch/.test(line)) {
58
+ parts.push({ category: 'code', text: code }); code = ''; diff = false; patch = false;
59
+ }
60
+ } else if (/^(?:diff --git |@@ -|\*\*\* Begin Patch)/.test(line) || (/^--- /.test(line) && /^\+\+\+ /.test(lines[index + 1] || ''))) {
61
+ parts.push(...splitRules(prose, category)); prose = '';
62
+ code = line; diff = true; patch = /^\*\*\* Begin Patch/.test(line);
63
+ } else if (marker) {
64
+ parts.push(...splitRules(prose, category)); prose = '';
65
+ fence = marker[1]; code = line;
66
+ } else prose += line;
67
+ }
68
+ if (code) parts.push({ category: 'code', text: code });
69
+ parts.push(...splitRules(prose, category));
70
+ return parts;
71
+ }
72
+
73
+ function preview(text) {
74
+ return text.replace(/Bearer\s+[^\s,]+/gi, 'Bearer [redacted]')
75
+ .replace(/((?:api[_-]?key|token|authorization)['"]?\s*[:=]\s*['"]?)[^\s,]+/gi, '$1[redacted]')
76
+ .replace(/\s+/g, ' ').slice(0, PREVIEW_LENGTH);
77
+ }
78
+
79
+ export function createContextAnalyzer() {
80
+ const totals = Object.fromEntries(CONTEXT_CATEGORIES.map((id) => [id, { estimatedTokens: 0, characters: 0 }]));
81
+ const top = [];
82
+ const hotspots = new Map();
83
+ const files = new Map();
84
+ let messageCount = 0;
85
+ let totalEstimatedTokens = 0;
86
+ function mark(node, reason) {
87
+ const entry = hotspots.get(node.id) || { ...node, reasons: [] };
88
+ if (!entry.reasons.includes(reason)) entry.reasons.push(reason);
89
+ hotspots.set(node.id, entry);
90
+ }
91
+ return {
92
+ add(node) {
93
+ const counts = Object.fromEntries(CONTEXT_CATEGORIES.map((id) => [id, 0]));
94
+ const texts = [];
95
+ for (const part of node.parts) {
96
+ for (const segment of splitContextText(part.text, part.category)) {
97
+ const tokens = estimatePromptTokenCount(segment.text);
98
+ counts[segment.category] += tokens;
99
+ totals[segment.category].estimatedTokens += tokens;
100
+ totals[segment.category].characters += segment.text.length;
101
+ texts.push(segment.text);
102
+ }
103
+ }
104
+ const estimatedTokens = Object.values(counts).reduce((sum, value) => sum + value, 0);
105
+ totalEstimatedTokens += estimatedTokens;
106
+ messageCount++;
107
+ const text = texts.join('');
108
+ const summary = { id: node.id, recordLineIndex: node.recordLineIndex,
109
+ messageIndex: node.messageIndex, role: node.role, estimatedTokens,
110
+ categories: counts, preview: preview(text) };
111
+ top.push(summary);
112
+ top.sort((a, b) => b.estimatedTokens - a.estimatedTokens || a.id.localeCompare(b.id));
113
+ if (top.length > TOP_CANDIDATES) top.pop();
114
+ if (ERROR_PATTERN.test(text) && (estimatedTokens >= LONG_ERROR_TOKENS || text.split('\n').length >= LONG_ERROR_LINES)) {
115
+ mark(summary, 'long_error_log');
116
+ }
117
+ for (const file of node.readPaths || []) {
118
+ const previous = files.get(file);
119
+ if (previous) {
120
+ previous.count++;
121
+ mark(previous.first, 'repeated_file_read');
122
+ mark(summary, 'repeated_file_read');
123
+ } else files.set(file, { count: 1, first: summary });
124
+ }
125
+ },
126
+ finish() {
127
+ for (const node of top) {
128
+ if (node.estimatedTokens > totalEstimatedTokens * DOMINANT_SHARE) mark(node, 'dominant_message');
129
+ }
130
+ const percentage = (tokens) => totalEstimatedTokens ? tokens * 100 / totalEstimatedTokens : 0;
131
+ const describe = (node) => ({ ...node, percentage: percentage(node.estimatedTokens),
132
+ reasons: hotspots.get(node.id)?.reasons || [] });
133
+ return {
134
+ estimator: 'cjk-1-non-cjk-4-v1', estimated: true, messageCount, totalEstimatedTokens,
135
+ health: contextHealthLevel(totalEstimatedTokens),
136
+ categories: CONTEXT_CATEGORIES.map((id) => ({ id, ...totals[id], percentage: percentage(totals[id].estimatedTokens) })),
137
+ topMessages: top.slice(0, 5).map(describe),
138
+ hotspots: [...hotspots.values()].map(describe),
139
+ duplicateFiles: [...files].filter(([, value]) => value.count > 1)
140
+ .map(([path, value]) => ({ path, reads: value.count }))
141
+ };
142
+ }
143
+ };
144
+ }
@@ -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
  }
@@ -1,7 +1,18 @@
1
+ import { buildLineDiff } from '../logic.agents-diff.mjs';
1
2
  import { estimatePromptTokenCount, buildPromptTokenDiffStats } from '../logic.prompts-token-count.mjs';
2
3
 
3
4
  export function createPromptsComputed() {
4
5
  return {
6
+ promptHistoryComparison() {
7
+ return buildLineDiff(this.promptHistoryPreviewContent, this.agentsContent);
8
+ },
9
+ sysHistoryComparison() {
10
+ return buildLineDiff(this.sysHistoryPreviewContent, this.sysPromptContent);
11
+ },
12
+ pluginHistoryComparison() {
13
+ const templates = this.promptTemplatesListRaw.filter((item) => item.isBuiltin !== true);
14
+ return buildLineDiff(this.pluginHistoryContent, JSON.stringify({ version: 1, templates }, null, 2) + '\n');
15
+ },
5
16
  agentsTokenCount() {
6
17
  return estimatePromptTokenCount(this.agentsContent);
7
18
  },
@@ -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
  }
@@ -908,7 +913,10 @@ export function createAgentsMethods(options = {}) {
908
913
  },
909
914
  async applyPromptPresetToEditor(preset) {
910
915
  if (!preset || typeof preset.content !== 'string' || !preset.content) return;
911
- this.agentsContent = preset.content;
916
+ const content = typeof this.resolvePromptTemplateInvocation === 'function'
917
+ ? await this.resolvePromptTemplateInvocation({ template: preset.content }) : preset.content;
918
+ if (content === null) return;
919
+ this.agentsContent = content;
912
920
  this.onAgentsContentInput();
913
921
  this.selectedPromptPresetId = preset.id;
914
922
  this.showMessage(this.t('prompts.presets.toast.pasted'), 'success');
@@ -981,6 +989,8 @@ export function createAgentsMethods(options = {}) {
981
989
  ? bucketArg.trim()
982
990
  : (this.promptHistoryBucket || resolveAgentsHistoryBucket(this));
983
991
  this.promptHistoryBucket = bucket;
992
+ const requestToken = Symbol('history-list');
993
+ this._promptHistoryRequestToken = requestToken;
984
994
  this.promptHistoryLoading = true;
985
995
  this.promptHistoryError = '';
986
996
  this.promptHistoryItems = [];
@@ -988,20 +998,24 @@ export function createAgentsMethods(options = {}) {
988
998
  this.promptHistoryPreviewContent = '';
989
999
  try {
990
1000
  const res = await api('list-prompt-history', { bucket });
1001
+ if (this._promptHistoryRequestToken !== requestToken || !this.promptHistoryVisible || this.promptHistoryBucket !== bucket) return;
991
1002
  if (res && res.error) {
992
1003
  this.promptHistoryError = res.error;
993
1004
  return;
994
1005
  }
995
1006
  this.promptHistoryItems = Array.isArray(res) ? res : [];
996
1007
  } catch (e) {
1008
+ if (this._promptHistoryRequestToken !== requestToken) return;
997
1009
  this.promptHistoryError = this.t('toast.load.fail');
998
1010
  } finally {
999
- this.promptHistoryLoading = false;
1011
+ if (this._promptHistoryRequestToken === requestToken) this.promptHistoryLoading = false;
1000
1012
  }
1001
1013
  },
1002
1014
 
1003
1015
  closePromptHistory() {
1004
1016
  this.promptHistoryVisible = false;
1017
+ this._promptHistoryRequestToken = null;
1018
+ this.promptHistoryLoading = false;
1005
1019
  this.promptHistoryPreviewId = '';
1006
1020
  this.promptHistoryPreviewContent = '';
1007
1021
  this.promptHistoryError = '';
@@ -1011,10 +1025,15 @@ export function createAgentsMethods(options = {}) {
1011
1025
  if (!item || !item.id) return;
1012
1026
  if (this.promptHistoryLoading) return;
1013
1027
  if (this.promptHistoryPreviewId === item.id && this.promptHistoryPreviewContent) return;
1028
+ const bucket = this.promptHistoryBucket;
1029
+ const requestToken = Symbol('history-preview');
1030
+ this._promptHistoryRequestToken = requestToken;
1031
+ this.promptHistoryLoading = true;
1014
1032
  this.promptHistoryPreviewId = item.id;
1015
1033
  this.promptHistoryPreviewContent = '';
1016
1034
  try {
1017
- const res = await api('get-prompt-history', { bucket: this.promptHistoryBucket, id: item.id });
1035
+ const res = await api('get-prompt-history', { bucket, id: item.id });
1036
+ if (this._promptHistoryRequestToken !== requestToken || !this.promptHistoryVisible || this.promptHistoryBucket !== bucket) return;
1018
1037
  if (res && res.error) {
1019
1038
  this.promptHistoryError = res.error;
1020
1039
  this.promptHistoryPreviewId = '';
@@ -1022,8 +1041,11 @@ export function createAgentsMethods(options = {}) {
1022
1041
  }
1023
1042
  this.promptHistoryPreviewContent = typeof res.content === 'string' ? res.content : '';
1024
1043
  } catch (e) {
1044
+ if (this._promptHistoryRequestToken !== requestToken) return;
1025
1045
  this.promptHistoryError = this.t('toast.load.fail');
1026
1046
  this.promptHistoryPreviewId = '';
1047
+ } finally {
1048
+ if (this._promptHistoryRequestToken === requestToken) this.promptHistoryLoading = false;
1027
1049
  }
1028
1050
  },
1029
1051
 
@@ -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();