codexmate 0.1.7 → 0.1.8

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.
@@ -0,0 +1,177 @@
1
+ 'use strict';
2
+
3
+ function createSystemPromptFileController(deps = {}) {
4
+ const {
5
+ fs,
6
+ path,
7
+ os,
8
+ crypto,
9
+ buildLineDiff,
10
+ CONFIG_DIR,
11
+ PI_AGENT_DIR
12
+ } = deps;
13
+
14
+ if (!fs) throw new Error('createSystemPromptFileController 缺少 fs');
15
+ if (!path) throw new Error('createSystemPromptFileController 缺少 path');
16
+ if (!os) throw new Error('createSystemPromptFileController 缺少 os');
17
+ if (!crypto) throw new Error('createSystemPromptFileController 缺少 crypto');
18
+ if (typeof buildLineDiff !== 'function') throw new Error('createSystemPromptFileController 缺少 buildLineDiff');
19
+ if (typeof CONFIG_DIR !== 'string' || !CONFIG_DIR) throw new Error('createSystemPromptFileController 缺少 CONFIG_DIR');
20
+ if (typeof PI_AGENT_DIR !== 'string' || !PI_AGENT_DIR) throw new Error('createSystemPromptFileController 缺少 PI_AGENT_DIR');
21
+
22
+ const MODES = {
23
+ system: 'SYSTEM.md',
24
+ append: 'APPEND_SYSTEM.md'
25
+ };
26
+
27
+ const SCOPES = ['global', 'project'];
28
+
29
+ function normalizeMode(mode) {
30
+ const key = typeof mode === 'string' ? mode.trim() : '';
31
+ if (!Object.prototype.hasOwnProperty.call(MODES, key)) {
32
+ throw new Error("Invalid system prompt mode: expected 'system' or 'append'");
33
+ }
34
+ return key;
35
+ }
36
+
37
+ function normalizeScope(scope) {
38
+ const key = typeof scope === 'string' ? scope.trim() : '';
39
+ if (!SCOPES.includes(key)) {
40
+ throw new Error("Invalid system prompt scope: expected 'global' or 'project'");
41
+ }
42
+ return key;
43
+ }
44
+
45
+ function hashContent(content) {
46
+ return crypto.createHash('sha256').update(String(content || '')).digest('hex');
47
+ }
48
+
49
+ function resolveSystemPromptFilePath(params = {}) {
50
+ const scope = normalizeScope(params.scope);
51
+ const mode = normalizeMode(params.mode);
52
+ const filename = MODES[mode];
53
+ let base;
54
+ if (scope === 'global') {
55
+ base = PI_AGENT_DIR;
56
+ } else {
57
+ const cwd = typeof params.cwd === 'string' && params.cwd.trim()
58
+ ? params.cwd.trim()
59
+ : process.cwd();
60
+ base = path.join(path.resolve(cwd), '.pi');
61
+ }
62
+ return {
63
+ scope,
64
+ mode,
65
+ filename,
66
+ path: path.join(base, filename),
67
+ replaceDefault: mode === 'system'
68
+ };
69
+ }
70
+
71
+ function readSystemPromptFile(params = {}) {
72
+ const target = resolveSystemPromptFilePath(params);
73
+ const exists = fs.existsSync(target.path);
74
+ let content = '';
75
+ if (exists) {
76
+ try {
77
+ content = fs.readFileSync(target.path, 'utf8');
78
+ } catch (e) {
79
+ return { ...target, exists: false, content: '', hash: hashContent(''), error: '读取 system prompt 失败: ' + e.message };
80
+ }
81
+ }
82
+ return {
83
+ ...target,
84
+ exists,
85
+ content,
86
+ hash: hashContent(content)
87
+ };
88
+ }
89
+
90
+ function saveSystemPromptFile(params = {}) {
91
+ const content = typeof params.content === 'string' ? params.content : '';
92
+ if (!content.trim()) {
93
+ return { error: 'System prompt 不能为空' };
94
+ }
95
+ if (content.length > 2 * 1024 * 1024) {
96
+ return { error: '内容过大(最大 2MB)' };
97
+ }
98
+ const target = resolveSystemPromptFilePath(params);
99
+ const current = readSystemPromptFilePath(target);
100
+ if (current.error) {
101
+ return { error: current.error };
102
+ }
103
+ const baseHash = typeof params.baseHash === 'string' ? params.baseHash.trim() : '';
104
+ if (baseHash && baseHash !== current.hash) {
105
+ return { error: '文件已被外部修改,请重新加载后再保存' };
106
+ }
107
+ try {
108
+ const dir = path.dirname(target.path);
109
+ fs.mkdirSync(dir, { recursive: true });
110
+ const finalContent = content.endsWith('\n') ? content : content + '\n';
111
+ fs.writeFileSync(target.path, finalContent, { encoding: 'utf8', mode: 0o600 });
112
+ try { fs.chmodSync(target.path, 0o600); } catch (_) {}
113
+ } catch (e) {
114
+ return { error: '写入 system prompt 失败: ' + e.message };
115
+ }
116
+ return readSystemPromptFilePath(target);
117
+ }
118
+
119
+ function readSystemPromptFilePath(resolved) {
120
+ const exists = fs.existsSync(resolved.path);
121
+ let content = '';
122
+ if (exists) {
123
+ try {
124
+ content = fs.readFileSync(resolved.path, 'utf8');
125
+ } catch (e) {
126
+ return { ...resolved, exists: false, content: '', hash: hashContent(''), error: '读取 system prompt 失败: ' + e.message };
127
+ }
128
+ }
129
+ return {
130
+ ...resolved,
131
+ exists,
132
+ content,
133
+ hash: hashContent(content)
134
+ };
135
+ }
136
+
137
+ function buildSystemPromptDiff(params = {}) {
138
+ const hasBaseContent = typeof params.baseContent === 'string';
139
+ const target = resolveSystemPromptFilePath(params);
140
+ const current = readSystemPromptFilePath(target);
141
+ if (current.error) {
142
+ return { error: current.error };
143
+ }
144
+ const beforeText = hasBaseContent
145
+ ? (typeof params.baseContent === 'string' ? params.baseContent : '')
146
+ : (current.content || '');
147
+ const afterText = typeof params.content === 'string' ? params.content : '';
148
+ const normalizedBefore = beforeText.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
149
+ const normalizedAfter = afterText.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
150
+ const diff = buildLineDiff(normalizedBefore, normalizedAfter);
151
+ const hasChanges = diff.truncated
152
+ ? normalizedBefore !== normalizedAfter
153
+ : (diff.stats.added > 0 || diff.stats.removed > 0);
154
+ return {
155
+ diff: {
156
+ ...diff,
157
+ hasChanges
158
+ },
159
+ path: target.path,
160
+ exists: current.exists,
161
+ scope: target.scope,
162
+ mode: target.mode
163
+ };
164
+ }
165
+
166
+ return {
167
+ readSystemPromptFile,
168
+ saveSystemPromptFile,
169
+ buildSystemPromptDiff,
170
+ normalizeMode,
171
+ normalizeScope
172
+ };
173
+ }
174
+
175
+ module.exports = {
176
+ createSystemPromptFileController
177
+ };
package/cli.js CHANGED
@@ -126,6 +126,9 @@ const {
126
126
  const {
127
127
  createAgentsFileController
128
128
  } = require('./cli/agents-files');
129
+ const {
130
+ createSystemPromptFileController
131
+ } = require('./cli/system-prompt-files');
129
132
  const {
130
133
  createArchiveHelperController
131
134
  } = require('./cli/archive-helpers');
@@ -308,6 +311,7 @@ const FAST_SESSION_DETAIL_PREVIEW_FILE_BYTES = 256 * 1024;
308
311
  const FAST_SESSION_DETAIL_PREVIEW_CHUNK_BYTES = 64 * 1024;
309
312
  const FAST_SESSION_DETAIL_PREVIEW_MAX_BYTES = 1024 * 1024;
310
313
  const AGENTS_FILE_NAME = 'AGENTS.md';
314
+ const PI_AGENT_DIR = path.join(os.homedir(), '.pi', 'agent');
311
315
  const MODELS_CACHE_TTL_MS = 60 * 1000;
312
316
  const MODELS_NEGATIVE_CACHE_TTL_MS = 5 * 1000;
313
317
  const MODELS_CACHE_MAX_ENTRIES = 50;
@@ -2102,6 +2106,20 @@ const {
2102
2106
  }
2103
2107
  });
2104
2108
 
2109
+ const {
2110
+ readSystemPromptFile,
2111
+ saveSystemPromptFile,
2112
+ buildSystemPromptDiff
2113
+ } = createSystemPromptFileController({
2114
+ fs,
2115
+ path,
2116
+ os,
2117
+ crypto,
2118
+ buildLineDiff,
2119
+ CONFIG_DIR,
2120
+ PI_AGENT_DIR
2121
+ });
2122
+
2105
2123
  const {
2106
2124
  readOpenclawConfigFile,
2107
2125
  applyOpenclawConfig,
@@ -13479,6 +13497,15 @@ function createWebServer({ htmlPath, assetsDir, webDir, host, port, openBrowser
13479
13497
  case 'apply-openclaw-workspace-file':
13480
13498
  result = applyOpenclawWorkspaceFile(params || {});
13481
13499
  break;
13500
+ case 'get-system-prompt':
13501
+ result = readSystemPromptFile(params || {});
13502
+ break;
13503
+ case 'apply-system-prompt':
13504
+ result = saveSystemPromptFile(params || {});
13505
+ break;
13506
+ case 'preview-system-prompt-diff':
13507
+ result = buildSystemPromptDiff(params || {});
13508
+ break;
13482
13509
  case 'switch':
13483
13510
  case 'use':
13484
13511
  case 'add':
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codexmate",
3
- "version": "0.1.7",
3
+ "version": "0.1.8",
4
4
  "description": "Codex/Claude Code/OpenClaw 配置、会话与任务编排 CLI + Web 工具",
5
5
  "main": "cli.js",
6
6
  "bin": {
package/web-ui/app.js CHANGED
@@ -154,6 +154,25 @@ document.addEventListener('DOMContentLoaded', () => {
154
154
  agentsContext: 'codex',
155
155
  agentsModalTitle: 'AGENTS.md 编辑器',
156
156
  agentsModalHint: '保存后会写入目标 AGENTS.md(与 config.toml 同级)。',
157
+ sysPromptScope: 'global',
158
+ sysPromptMode: 'append',
159
+ sysPromptContent: '',
160
+ sysPromptOriginalContent: '',
161
+ sysPromptPath: '',
162
+ sysPromptExists: false,
163
+ sysPromptHash: '',
164
+ sysPromptLoading: false,
165
+ sysPromptSaving: false,
166
+ sysPromptDiffVisible: false,
167
+ sysPromptDiffLoading: false,
168
+ sysPromptDiffError: '',
169
+ sysPromptDiffLines: [],
170
+ sysPromptDiffStats: { added: 0, removed: 0, unchanged: 0 },
171
+ sysPromptDiffTruncated: false,
172
+ sysPromptDiffHasChangesValue: false,
173
+ sysPromptDiffFingerprint: '',
174
+ _sysPromptDiffPreviewRequestToken: null,
175
+ _sysPromptOpenRequestToken: null,
157
176
  skillsTargetApp: 'codex',
158
177
  skillsRootPath: '',
159
178
  skillsList: [],
@@ -773,7 +773,7 @@ export function createSessionComputed() {
773
773
  const rows = currentKeys
774
774
  .map((key) => byDay.get(key))
775
775
  .filter(Boolean)
776
- .sort((a, b) => b.key.localeCompare(a.key, 'en-US'));
776
+ .sort((a, b) => a.key.localeCompare(b.key, 'en-US'));
777
777
  const rowsWithCompare = rows.map((row) => {
778
778
  if (!compareEnabled) {
779
779
  return { ...row, compareEnabled: false, prevKey: '', prevTokenTotal: 0 };
@@ -4,6 +4,7 @@ import {
4
4
  isAgentsDiffPreviewPayloadTooLarge,
5
5
  shouldApplyAgentsDiffPreviewResponse
6
6
  } from '../logic.mjs';
7
+ import { issueLatestRequestToken, isLatestRequestToken } from './request-token.mjs';
7
8
 
8
9
  function isValidOpenclawWorkspaceFileName(fileName) {
9
10
  if (typeof fileName !== 'string') {
@@ -19,16 +20,6 @@ function isValidOpenclawWorkspaceFileName(fileName) {
19
20
  return true;
20
21
  }
21
22
 
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
23
  export function createAgentsMethods(options = {}) {
33
24
  const {
34
25
  api,
@@ -894,15 +885,17 @@ export function createAgentsMethods(options = {}) {
894
885
  this.showMessage(this.t('prompts.presets.toast.deleted'), 'success');
895
886
  },
896
887
  switchPromptsSubTab(subTab) {
897
- const normalized = subTab === 'claude-project' ? subTab : 'codex';
888
+ const normalized = subTab === 'claude-project' || subTab === 'system' ? subTab : 'codex';
898
889
  if (normalized === 'claude-project' && !this.projectPathOptions.length && !this.projectPathOptionsLoading) {
899
890
  this.loadProjectPathOptions();
900
891
  }
901
892
  if (this.promptsSubTab === normalized) {
902
- this.loadPromptsContent();
893
+ if (normalized === 'system') this.loadSystemPrompt();
894
+ else this.loadPromptsContent();
903
895
  return;
904
896
  }
905
897
  this.promptsSubTab = normalized;
898
+ if (normalized === 'system') this.loadSystemPrompt();
906
899
  this.$nextTick(() => {
907
900
  document.querySelector('.main-panel')?.scrollTo({ top: 0, left: 0, behavior: 'auto' });
908
901
  });
@@ -12,6 +12,7 @@ import {
12
12
  SESSION_TRASH_PAGE_SIZE
13
13
  } from './app.constants.mjs';
14
14
  import { createAgentsMethods } from './app.methods.agents.mjs';
15
+ import { createSystemPromptMethods } from './app.methods.system-prompt.mjs';
15
16
  import { createClaudeConfigMethods } from './app.methods.claude-config.mjs';
16
17
  import { createCodexConfigMethods } from './app.methods.codex-config.mjs';
17
18
  import { createInstallMethods } from './app.methods.install.mjs';
@@ -85,6 +86,7 @@ export function createAppMethods() {
85
86
  ...createSkillsMethods({ api }),
86
87
  ...createPluginsMethods(),
87
88
  ...createAgentsMethods({ api, apiWithMeta }),
89
+ ...createSystemPromptMethods({ api, apiWithMeta }),
88
90
  ...createProvidersMethods({ api }),
89
91
  ...createProviderCacheMethods({ api }),
90
92
  ...createWebUiPreferencesMethods({ api }),
@@ -783,6 +783,7 @@ export function createSessionBrowserMethods(options = {}) {
783
783
  this.sessionsUsageCompareEnabled = false;
784
784
  }
785
785
  void this.loadSessionsUsage({ range });
786
+ this.scrollSessionsUsageDayIntoView({ behavior: 'auto' });
786
787
  },
787
788
 
788
789
  toggleSessionsUsageCompare() {
@@ -801,12 +802,29 @@ export function createSessionBrowserMethods(options = {}) {
801
802
  selectSessionsUsageDay(dayKey) {
802
803
  const normalized = typeof dayKey === 'string' ? dayKey.trim() : '';
803
804
  this.sessionsUsageSelectedDayKey = normalized;
805
+ this.scrollSessionsUsageDayIntoView({ behavior: 'smooth', align: 'nearest' });
804
806
  },
805
807
 
806
808
  clearSessionsUsageDay() {
807
809
  this.sessionsUsageSelectedDayKey = '';
808
810
  },
809
811
 
812
+ scrollSessionsUsageDayIntoView(options = {}) {
813
+ if (typeof document === 'undefined' || !document) return;
814
+ const behavior = options.behavior === 'smooth' ? 'smooth' : 'auto';
815
+ const inline = options.align === 'nearest' ? 'nearest' : 'end';
816
+ const scrollFn = () => {
817
+ const node = document.querySelector('.usage-wave-label.active');
818
+ if (!node || typeof node.scrollIntoView !== 'function') return;
819
+ node.scrollIntoView({ inline, block: 'nearest', behavior });
820
+ };
821
+ if (typeof this.$nextTick === 'function') {
822
+ this.$nextTick(scrollFn);
823
+ } else {
824
+ scrollFn();
825
+ }
826
+ },
827
+
810
828
  async loadSessionsUsage(options = {}) {
811
829
  if (this.sessionsUsageLoading) return;
812
830
  const normalizedRange = typeof options.range === 'string'
@@ -855,7 +873,9 @@ export function createSessionBrowserMethods(options = {}) {
855
873
  this.sessionsUsageLoadedLimit = limit;
856
874
  this.sessionsUsageLastLoadedRange = range;
857
875
  if (!this.sessionsUsageSelectedDayKey && Array.isArray(this.sessionUsageDailyTableRows) && this.sessionUsageDailyTableRows.length > 0) {
858
- this.sessionsUsageSelectedDayKey = this.sessionUsageDailyTableRows[0].key;
876
+ const dayKeys = this.sessionUsageDailyTableRows.map((row) => row.key).filter(Boolean).sort((a, b) => b.localeCompare(a, 'en-US'));
877
+ this.sessionsUsageSelectedDayKey = dayKeys[0] || this.sessionUsageDailyTableRows[this.sessionUsageDailyTableRows.length - 1].key;
878
+ this.scrollSessionsUsageDayIntoView({ behavior: 'auto' });
859
879
  }
860
880
  }
861
881
  }
@@ -0,0 +1,294 @@
1
+ import {
2
+ buildAgentsDiffPreview,
3
+ buildAgentsDiffPreviewRequest,
4
+ isAgentsDiffPreviewPayloadTooLarge,
5
+ shouldApplyAgentsDiffPreviewResponse
6
+ } from '../logic.mjs';
7
+ import { issueLatestRequestToken, isLatestRequestToken } from './request-token.mjs';
8
+
9
+ export function createSystemPromptMethods(options = {}) {
10
+ const {
11
+ api,
12
+ apiWithMeta
13
+ } = options;
14
+
15
+ return {
16
+
17
+ switchSysPromptScope(scope) {
18
+ if (this.sysPromptLoading || this.sysPromptSaving) return;
19
+ const normalized = scope === 'project' ? scope : 'global';
20
+ if (normalized === this.sysPromptScope) return;
21
+ this.sysPromptScope = normalized;
22
+ this.loadSystemPrompt();
23
+ },
24
+
25
+ switchSysPromptMode(mode) {
26
+ if (this.sysPromptLoading || this.sysPromptSaving) return;
27
+ const normalized = mode === 'system' ? mode : 'append';
28
+ if (normalized === this.sysPromptMode) return;
29
+ this.sysPromptMode = normalized;
30
+ this.loadSystemPrompt();
31
+ },
32
+
33
+ resetSysPromptDiffState() {
34
+ this.sysPromptDiffVisible = false;
35
+ this.sysPromptDiffLoading = false;
36
+ this.sysPromptDiffError = '';
37
+ this.sysPromptDiffLines = [];
38
+ this.sysPromptDiffStats = { added: 0, removed: 0, unchanged: 0 };
39
+ this.sysPromptDiffTruncated = false;
40
+ this.sysPromptDiffHasChangesValue = false;
41
+ this.sysPromptDiffFingerprint = '';
42
+ this._sysPromptDiffPreviewRequestToken = null;
43
+ },
44
+
45
+ hasSysPromptContentChanged() {
46
+ const original = typeof this.sysPromptOriginalContent === 'string' ? this.sysPromptOriginalContent : '';
47
+ const current = typeof this.sysPromptContent === 'string' ? this.sysPromptContent : '';
48
+ return original !== current;
49
+ },
50
+
51
+ buildSysPromptDiffFingerprint() {
52
+ const scope = this.sysPromptScope || 'global';
53
+ const mode = this.sysPromptMode || 'append';
54
+ const content = typeof this.sysPromptContent === 'string' ? this.sysPromptContent : '';
55
+ const original = typeof this.sysPromptOriginalContent === 'string' ? this.sysPromptOriginalContent : '';
56
+ return `${scope}::${mode}::${content.length}::${content}::${original.length}::${original}`;
57
+ },
58
+
59
+ async loadSystemPrompt() {
60
+ const requestToken = issueLatestRequestToken(this, '_sysPromptOpenRequestToken');
61
+ this.sysPromptLoading = true;
62
+ this.resetSysPromptDiffState();
63
+ try {
64
+ const params = {
65
+ scope: this.sysPromptScope || 'global',
66
+ mode: this.sysPromptMode || 'append'
67
+ };
68
+ const res = await api('get-system-prompt', params);
69
+ if (!isLatestRequestToken(this, '_sysPromptOpenRequestToken', requestToken)) return;
70
+ if (res.error) {
71
+ this.showMessage(res.error, 'error');
72
+ return;
73
+ }
74
+ this.sysPromptContent = res.content || '';
75
+ this.sysPromptOriginalContent = this.sysPromptContent;
76
+ this.sysPromptPath = res.path || '';
77
+ this.sysPromptExists = !!res.exists;
78
+ this.sysPromptHash = res.hash || '';
79
+ } catch (e) {
80
+ if (!isLatestRequestToken(this, '_sysPromptOpenRequestToken', requestToken)) return;
81
+ this.showMessage(this.t('toast.load.fail'), 'error');
82
+ } finally {
83
+ if (isLatestRequestToken(this, '_sysPromptOpenRequestToken', requestToken)) {
84
+ this.sysPromptLoading = false;
85
+ }
86
+ }
87
+ },
88
+
89
+ async prepareSysPromptDiff() {
90
+ const requestFingerprint = this.buildSysPromptDiffFingerprint();
91
+ const requestToken = Symbol('sys-prompt-diff-preview');
92
+ this._sysPromptDiffPreviewRequestToken = requestToken;
93
+ this.sysPromptDiffVisible = true;
94
+ this.sysPromptDiffLoading = true;
95
+ this.sysPromptDiffError = '';
96
+ this.sysPromptDiffLines = [];
97
+ this.sysPromptDiffStats = { added: 0, removed: 0, unchanged: 0 };
98
+ this.sysPromptDiffTruncated = false;
99
+ this.sysPromptDiffHasChangesValue = false;
100
+ try {
101
+ const shouldApplyPreviewState = () => shouldApplyAgentsDiffPreviewResponse({
102
+ isVisible: this.sysPromptDiffVisible,
103
+ requestToken,
104
+ activeRequestToken: this._sysPromptDiffPreviewRequestToken,
105
+ requestFingerprint,
106
+ currentFingerprint: this.buildSysPromptDiffFingerprint()
107
+ });
108
+ const applyPreviewState = (diff) => {
109
+ if (!shouldApplyPreviewState()) return false;
110
+ const normalizedDiff = diff && typeof diff === 'object' ? diff : {};
111
+ const rawLines = Array.isArray(normalizedDiff.lines) ? normalizedDiff.lines : [];
112
+ this.sysPromptDiffLines = rawLines.filter(line => line && line.type);
113
+ this.sysPromptDiffTruncated = !!normalizedDiff.truncated;
114
+ this.sysPromptDiffHasChangesValue = !!normalizedDiff.hasChanges;
115
+ if (normalizedDiff.stats && typeof normalizedDiff.stats === 'object') {
116
+ this.sysPromptDiffStats = {
117
+ added: Number(normalizedDiff.stats.added || 0),
118
+ removed: Number(normalizedDiff.stats.removed || 0),
119
+ unchanged: Number(normalizedDiff.stats.unchanged || 0)
120
+ };
121
+ } else {
122
+ const stats = { added: 0, removed: 0, unchanged: 0 };
123
+ for (const line of this.sysPromptDiffLines) {
124
+ if (line && line.type === 'add') stats.added += 1;
125
+ else if (line && line.type === 'del') stats.removed += 1;
126
+ else stats.unchanged += 1;
127
+ }
128
+ this.sysPromptDiffStats = stats;
129
+ }
130
+ this.sysPromptDiffFingerprint = requestFingerprint;
131
+ return true;
132
+ };
133
+ const previewRequest = buildAgentsDiffPreviewRequest({
134
+ baseContent: this.sysPromptOriginalContent,
135
+ content: this.sysPromptContent,
136
+ lineEnding: '\n',
137
+ context: 'sys-prompt',
138
+ baseDir: undefined
139
+ });
140
+ if (previewRequest.exceedsBodyLimit) {
141
+ applyPreviewState(buildAgentsDiffPreview({
142
+ baseContent: this.sysPromptOriginalContent,
143
+ content: this.sysPromptContent
144
+ }));
145
+ return;
146
+ }
147
+ const rpcParams = {
148
+ ...previewRequest.params,
149
+ scope: this.sysPromptScope || 'global',
150
+ mode: this.sysPromptMode || 'append'
151
+ };
152
+ const res = await apiWithMeta('preview-system-prompt-diff', rpcParams);
153
+ if (!shouldApplyPreviewState()) return;
154
+ if (res.error) {
155
+ if (isAgentsDiffPreviewPayloadTooLarge(res)) {
156
+ applyPreviewState(buildAgentsDiffPreview({
157
+ baseContent: this.sysPromptOriginalContent,
158
+ content: this.sysPromptContent
159
+ }));
160
+ return;
161
+ }
162
+ this.sysPromptDiffError = res.error;
163
+ return;
164
+ }
165
+ applyPreviewState(res.diff);
166
+ } catch (e) {
167
+ if (shouldApplyAgentsDiffPreviewResponse({
168
+ isVisible: this.sysPromptDiffVisible,
169
+ requestToken,
170
+ activeRequestToken: this._sysPromptDiffPreviewRequestToken,
171
+ requestFingerprint,
172
+ currentFingerprint: this.buildSysPromptDiffFingerprint()
173
+ })) {
174
+ this.sysPromptDiffError = '生成差异失败';
175
+ }
176
+ } finally {
177
+ if (this._sysPromptDiffPreviewRequestToken === requestToken) {
178
+ this.sysPromptDiffLoading = false;
179
+ }
180
+ }
181
+ },
182
+
183
+ cancelSysPromptEdit() {
184
+ if (this.sysPromptSaving || this.sysPromptDiffLoading) return;
185
+ this.resetSysPromptDiffState();
186
+ this.loadSystemPrompt();
187
+ },
188
+
189
+ async applySystemPrompt() {
190
+ if (this.sysPromptSaving) return;
191
+ if (!this.sysPromptDiffVisible) {
192
+ if (!this.hasSysPromptContentChanged()) {
193
+ this.showMessage(this.t('toast.noChanges'), 'info');
194
+ return;
195
+ }
196
+ await this.prepareSysPromptDiff();
197
+ return;
198
+ }
199
+ if (this.sysPromptDiffLoading) return;
200
+ if (this.sysPromptDiffError) {
201
+ this.showMessage(this.sysPromptDiffError, 'error');
202
+ return;
203
+ }
204
+ const fingerprint = this.buildSysPromptDiffFingerprint();
205
+ if (this.sysPromptDiffFingerprint !== fingerprint) {
206
+ await this.prepareSysPromptDiff();
207
+ return;
208
+ }
209
+ if (!this.sysPromptDiffHasChangesValue) {
210
+ this.showMessage(this.t('toast.noChanges'), 'info');
211
+ return;
212
+ }
213
+ this.sysPromptSaving = true;
214
+ try {
215
+ const params = {
216
+ scope: this.sysPromptScope || 'global',
217
+ mode: this.sysPromptMode || 'append',
218
+ content: this.sysPromptContent,
219
+ baseHash: this.sysPromptHash
220
+ };
221
+ const res = await api('apply-system-prompt', params);
222
+ if (res.error) {
223
+ this.showMessage(res.error, 'error');
224
+ return;
225
+ }
226
+ this.showMessage(this.t('sysPrompt.toast.saved'), 'success');
227
+ await this.loadSystemPrompt();
228
+ } catch (e) {
229
+ this.showMessage(this.t('toast.save.fail'), 'error');
230
+ } finally {
231
+ this.sysPromptSaving = false;
232
+ }
233
+ },
234
+
235
+ copySysPromptContent() {
236
+ const content = typeof this.sysPromptContent === 'string' ? this.sysPromptContent : '';
237
+ if (!content) return;
238
+ try {
239
+ navigator.clipboard?.writeText(content);
240
+ this.showMessage(this.t('common.copy'), 'success');
241
+ } catch (_) {}
242
+ },
243
+
244
+ exportSysPromptContent() {
245
+ const content = typeof this.sysPromptContent === 'string' ? this.sysPromptContent : '';
246
+ if (!content) return;
247
+ const filename = (this.sysPromptMode === 'system' ? 'SYSTEM.md' : 'APPEND_SYSTEM.md');
248
+ const blob = new Blob([content], { type: 'text/markdown' });
249
+ const a = document.createElement('a');
250
+ a.href = URL.createObjectURL(blob);
251
+ a.download = filename;
252
+ document.body.appendChild(a);
253
+ a.click();
254
+ a.remove();
255
+ URL.revokeObjectURL(a.href);
256
+ },
257
+
258
+ async pasteSysPromptContent() {
259
+ if (this.sysPromptLoading || this.sysPromptSaving || this.sysPromptDiffVisible) return;
260
+ try {
261
+ const text = await navigator.clipboard.readText();
262
+ if (text) {
263
+ this.sysPromptContent = text;
264
+ this.showMessage(this.t('common.paste'), 'success');
265
+ }
266
+ } catch (_) {}
267
+ },
268
+
269
+ sysPromptContextHint() {
270
+ if (!this.sysPromptLoading && !this.sysPromptDiffVisible && this.hasSysPromptContentChanged()) {
271
+ return { text: this.t('sysPrompt.hint.unsaved'), warn: true };
272
+ }
273
+ if (this.sysPromptDiffVisible && (this.sysPromptDiffLoading || this.sysPromptSaving)) {
274
+ return { text: this.t('diff.hint.busy'), warn: false };
275
+ }
276
+ if (this.sysPromptDiffVisible && this.sysPromptDiffError) {
277
+ return { text: this.t('diff.hint.failedBack'), warn: false };
278
+ }
279
+ if (this.sysPromptDiffVisible && !this.sysPromptDiffHasChangesValue) {
280
+ return { text: this.t('diff.hint.noChangesBack'), warn: false };
281
+ }
282
+ if (this.sysPromptDiffVisible && this.sysPromptDiffTruncated) {
283
+ return { text: this.t('diff.viewHint.truncated'), warn: false };
284
+ }
285
+ if (this.sysPromptDiffVisible) {
286
+ return { text: this.t('diff.viewHint.preview'), warn: false };
287
+ }
288
+ if (!this.sysPromptLoading) {
289
+ return { text: this.t('sysPrompt.hint.twoStepSave'), warn: false };
290
+ }
291
+ return null;
292
+ }
293
+ };
294
+ }