openprototype 1.8.1 → 1.8.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "openprototype",
3
- "version": "1.8.1",
3
+ "version": "1.8.3",
4
4
  "description": "本地原型工作台:左侧树形导航 + 中间原型预览 + 右侧 AI Agent(OpenCode)。PRD 与 HTML/JS 原型协作,含自动化检查。",
5
5
  "keywords": [
6
6
  "prototype",
@@ -756,29 +756,31 @@ function loadVersionCache() { try { return JSON.parse(navStorage.getItem(VER_CAC
756
756
  function saveVersionCache() { navStorage.setItem(VER_CACHE_KEY, JSON.stringify(versionCache)); }
757
757
  versionCache = loadVersionCache();
758
758
 
759
- function comparePrdVersions(left, right) {
760
- const leftParts = String(left || '').replace(/^v/i, '').split('.');
761
- const rightParts = String(right || '').replace(/^v/i, '').split('.');
762
- const length = Math.max(leftParts.length, rightParts.length);
763
- for (let index = 0; index < length; index += 1) {
764
- const leftPart = leftParts[index] || '0';
765
- const rightPart = rightParts[index] || '0';
766
- const leftNumber = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
767
- const rightNumber = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
768
- const comparison = leftNumber !== null && rightNumber !== null
769
- ? leftNumber - rightNumber
770
- : leftPart.localeCompare(rightPart, undefined, { numeric: true, sensitivity: 'base' });
771
- if (comparison !== 0) return comparison;
759
+ function extractPrdHistoryLatestVersion(text) {
760
+ const lines = String(text || '').replace(/<[^>]+>/g, '').split(/\r?\n/);
761
+ let latestVersion = null;
762
+
763
+ for (let index = 0; index < lines.length; index += 1) {
764
+ if (!/^\s*\|.*\|\s*$/.test(lines[index])) continue;
765
+
766
+ const tableLines = [];
767
+ while (index < lines.length && /^\s*\|.*\|\s*$/.test(lines[index])) {
768
+ tableLines.push(lines[index]);
769
+ index += 1;
770
+ }
771
+ index -= 1;
772
+
773
+ if (tableLines.length < 3 || !/^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(tableLines[1])) continue;
774
+ const headerCell = tableLines[0].split('|')[1] || '';
775
+ if (!headerCell.includes('版本')) continue;
776
+
777
+ tableLines.slice(2).forEach(row => {
778
+ const version = (row.split('|')[1] || '').trim();
779
+ if (version) latestVersion = version;
780
+ });
772
781
  }
773
- return 0;
774
- }
775
782
 
776
- function extractPrdHistoryMaxVersion(text) {
777
- const plainText = String(text || '').replace(/<[^>]+>/g, '');
778
- const versions = [...plainText.matchAll(/^\|\s*(v\d+(?:\.[0-9a-z]+)+)\s*\|/gim)].map(match => match[1]);
779
- return versions.length
780
- ? versions.reduce((maxVersion, version) => comparePrdVersions(version, maxVersion) > 0 ? version : maxVersion)
781
- : null;
783
+ return latestVersion;
782
784
  }
783
785
 
784
786
  async function fetchPageVersion(htmlPath) {
@@ -787,7 +789,7 @@ async function fetchPageVersion(htmlPath) {
787
789
  const res = await fetch(mdPath, { cache: 'no-cache' });
788
790
  if (!res.ok) return null;
789
791
  const text = await res.text();
790
- return extractPrdHistoryMaxVersion(text);
792
+ return extractPrdHistoryLatestVersion(text);
791
793
  } catch { return null; }
792
794
  }
793
795
 
package/runtime/server.js CHANGED
@@ -61,6 +61,7 @@ let openCodeProcess = null;
61
61
  let openCodeReadyPromise = null;
62
62
  let openCodeOwned = false;
63
63
  let openCodeStartError = '';
64
+ const agentTaskSnapshots = new Map();
64
65
 
65
66
  const MIME_TYPES = {
66
67
  '.html': 'text/html; charset=utf-8',
@@ -124,6 +125,73 @@ function resolveAgentWritablePath(inputPath, expectedExt) {
124
125
  return resolved;
125
126
  }
126
127
 
128
+ function findAgentWriteRoot(filePath) {
129
+ return AGENT_WRITE_ROOTS.find((root) => filePath === root || filePath.startsWith(root + path.sep)) || '';
130
+ }
131
+
132
+ function captureProductFiles(rootDir) {
133
+ const files = new Map();
134
+
135
+ function walk(dir) {
136
+ fs.readdirSync(dir, { withFileTypes: true }).forEach((entry) => {
137
+ if (entry.name.startsWith('.')) return;
138
+ const file = path.join(dir, entry.name);
139
+ if (entry.isDirectory()) {
140
+ walk(file);
141
+ return;
142
+ }
143
+ if (!entry.isFile()) return;
144
+ const stat = fs.statSync(file);
145
+ const rel = path.relative(rootDir, file).split(path.sep).join('/');
146
+ files.set(rel, `${stat.size}:${stat.mtimeMs}`);
147
+ });
148
+ }
149
+
150
+ walk(rootDir);
151
+ return files;
152
+ }
153
+
154
+ function startAgentTaskSnapshot(sessionID, htmlFile, htmlPath, prdPath) {
155
+ const rootDir = findAgentWriteRoot(htmlFile);
156
+ if (!rootDir) throw new Error('无法确定 Agent 任务所属产品目录');
157
+ agentTaskSnapshots.set(sessionID, {
158
+ rootDir,
159
+ files: captureProductFiles(rootDir),
160
+ context: {
161
+ htmlPath: String(htmlPath || ''),
162
+ prdPath: String(prdPath || '')
163
+ },
164
+ startedAt: Date.now()
165
+ });
166
+
167
+ if (agentTaskSnapshots.size > 50) {
168
+ const oldest = [...agentTaskSnapshots.entries()]
169
+ .sort((a, b) => a[1].startedAt - b[1].startedAt)
170
+ .slice(0, agentTaskSnapshots.size - 50);
171
+ oldest.forEach(([id]) => agentTaskSnapshots.delete(id));
172
+ }
173
+ }
174
+
175
+ function consumeAgentTaskChanges(sessionID) {
176
+ const snapshot = agentTaskSnapshots.get(sessionID);
177
+ if (!snapshot) return { context: null, changes: [] };
178
+
179
+ const current = captureProductFiles(snapshot.rootDir);
180
+ const names = new Set([...snapshot.files.keys(), ...current.keys()]);
181
+ const changes = [];
182
+ names.forEach((name) => {
183
+ const before = snapshot.files.get(name);
184
+ const after = current.get(name);
185
+ if (before === after) return;
186
+ changes.push({
187
+ file: path.relative(ROOT_DIR, path.join(snapshot.rootDir, name)).split(path.sep).join('/'),
188
+ change: before === undefined ? 'created' : after === undefined ? 'deleted' : 'modified'
189
+ });
190
+ });
191
+ agentTaskSnapshots.delete(sessionID);
192
+ return { context: snapshot.context, changes };
193
+ }
194
+
127
195
  function isLoopbackRequest(req) {
128
196
  const remoteAddress = String(req.socket.remoteAddress || '');
129
197
  return remoteAddress === '127.0.0.1' || remoteAddress === '::1' || remoteAddress === '::ffff:127.0.0.1';
@@ -834,8 +902,14 @@ async function handleAgentApi(req, res, urlPath) {
834
902
  if (!message) throw new Error('消息不能为空');
835
903
  const htmlFile = resolveAgentWritablePath(data.htmlPath, '.html');
836
904
  const prdFile = data.prdPath ? resolveAgentWritablePath(data.prdPath, '.md') : '';
837
- await ensureOpenCode();
838
- await sendOpenCodeMessage(match[1], message, buildAgentSystemPrompt(htmlFile, prdFile));
905
+ startAgentTaskSnapshot(match[1], htmlFile, data.htmlPath, data.prdPath);
906
+ try {
907
+ await ensureOpenCode();
908
+ await sendOpenCodeMessage(match[1], message, buildAgentSystemPrompt(htmlFile, prdFile));
909
+ } catch (err) {
910
+ agentTaskSnapshots.delete(match[1]);
911
+ throw err;
912
+ }
839
913
  sendJson(res, 202, { ok: true });
840
914
  return true;
841
915
  }
@@ -863,6 +937,12 @@ async function handleAgentApi(req, res, urlPath) {
863
937
  return true;
864
938
  }
865
939
 
940
+ match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/task-changes$/);
941
+ if (req.method === 'GET' && match) {
942
+ sendJson(res, 200, { ok: true, ...consumeAgentTaskChanges(match[1]) });
943
+ return true;
944
+ }
945
+
866
946
  match = urlPath.match(/^\/api\/agent\/sessions\/(ses_[A-Za-z0-9]+)\/pending$/);
867
947
  if (req.method === 'GET' && match) {
868
948
  await ensureOpenCode();
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  // 页面可在引入本模块前声明这些全局以覆盖默认行为;未声明时使用默认值。
7
- // “当前版本”优先读取主 PRD 历史记录中的最大版本;PRD_OVERVIEW_VERSION 仅作兼容兜底。
7
+ // “当前版本”优先读取主 PRD 版本记录表的最后一条;PRD_OVERVIEW_VERSION 仅作兼容兜底。
8
8
  // PRD_WORKSPACE_MAP 配置多文档工作区。
9
9
  var PRD_BASE_PATH = typeof PRD_BASE_PATH !== 'undefined' ? PRD_BASE_PATH : './';
10
10
  var PRD_FILE_MAP = typeof PRD_FILE_MAP !== 'undefined' ? PRD_FILE_MAP : {};
@@ -434,41 +434,36 @@ function getPrdDisplayName(filePath) {
434
434
  return (filePath || '').split('/').pop().replace(/\.md(?:#.*)?$/i, '').replace(/_/g, ' ');
435
435
  }
436
436
 
437
- function comparePrdVersions(left, right) {
438
- var leftParts = String(left || '').replace(/^v/i, '').split('.');
439
- var rightParts = String(right || '').replace(/^v/i, '').split('.');
440
- var length = Math.max(leftParts.length, rightParts.length);
441
-
442
- for (var index = 0; index < length; index += 1) {
443
- var leftPart = leftParts[index] || '0';
444
- var rightPart = rightParts[index] || '0';
445
- var leftNumber = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
446
- var rightNumber = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
447
- var comparison = leftNumber !== null && rightNumber !== null
448
- ? leftNumber - rightNumber
449
- : leftPart.localeCompare(rightPart, undefined, { numeric: true, sensitivity: 'base' });
450
- if (comparison !== 0) return comparison;
451
- }
452
- return 0;
453
- }
437
+ function getPrdHistoryLatestVersion(content) {
438
+ var lines = String(content || '').replace(/<[^>]+>/g, '').split(/\r?\n/);
439
+ var latestVersion = '';
454
440
 
455
- function getPrdHistoryMaxVersion(content) {
456
- var plainText = String(content || '').replace(/<[^>]+>/g, '');
457
- var pattern = /^\|\s*(v\d+(?:\.[0-9a-z]+)+)\s*\|/gim;
458
- var versions = [];
459
- var match;
460
- while ((match = pattern.exec(plainText)) !== null) {
461
- versions.push(match[1]);
441
+ for (var index = 0; index < lines.length; index += 1) {
442
+ if (!/^\s*\|.*\|\s*$/.test(lines[index])) continue;
443
+
444
+ var tableLines = [];
445
+ while (index < lines.length && /^\s*\|.*\|\s*$/.test(lines[index])) {
446
+ tableLines.push(lines[index]);
447
+ index += 1;
448
+ }
449
+ index -= 1;
450
+
451
+ if (tableLines.length < 3 || !/^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(tableLines[1])) continue;
452
+ var headerCell = tableLines[0].split('|')[1] || '';
453
+ if (headerCell.indexOf('版本') === -1) continue;
454
+
455
+ tableLines.slice(2).forEach(function(row) {
456
+ var version = (row.split('|')[1] || '').trim();
457
+ if (version) latestVersion = version;
458
+ });
462
459
  }
463
- if (!versions.length) return '';
464
- return versions.reduce(function(maxVersion, version) {
465
- return comparePrdVersions(version, maxVersion) > 0 ? version : maxVersion;
466
- });
460
+
461
+ return latestVersion;
467
462
  }
468
463
 
469
464
  function getPrdOverviewVersion(rootContent) {
470
- var historyMaxVersion = getPrdHistoryMaxVersion(rootContent);
471
- if (historyMaxVersion) return historyMaxVersion;
465
+ var historyLatestVersion = getPrdHistoryLatestVersion(rootContent);
466
+ if (historyLatestVersion) return historyLatestVersion;
472
467
  if (prdOverviewVersion) return prdOverviewVersion;
473
468
  if (typeof PRD_OVERVIEW_VERSION === 'undefined') return '';
474
469
  return String(PRD_OVERVIEW_VERSION || '').trim();
@@ -23,7 +23,7 @@
23
23
  createdAt: Number(item.createdAt || Date.now()),
24
24
  running: false,
25
25
  unread: false,
26
- taskContext: null
26
+ taskContext: item.taskContext && typeof item.taskContext === 'object' ? item.taskContext : null
27
27
  }));
28
28
  }
29
29
  } catch (err) {
@@ -85,6 +85,82 @@
85
85
  return decodeURIComponent(cleanPath.split('/').pop() || '');
86
86
  }
87
87
 
88
+ function normalizedPath(filePath) {
89
+ return decodeURIComponent(String(filePath || ''))
90
+ .split('?')[0]
91
+ .split('#')[0]
92
+ .replace(/\\/g, '/')
93
+ .replace(/^\/+/, '');
94
+ }
95
+
96
+ function findPageRow(filePath) {
97
+ const file = normalizedPath(filePath);
98
+ return Array.from(document.querySelectorAll('.file-row[data-path]')).find(row => {
99
+ const rowPath = normalizedPath(row.dataset.path);
100
+ return file === rowPath || file.endsWith('/' + rowPath);
101
+ }) || null;
102
+ }
103
+
104
+ function markReviewPending(row, type) {
105
+ if (!row) return false;
106
+ const button = row.querySelector(`.review-btn[data-review-target="${type}"]`);
107
+ if (!button || button.getAttribute('aria-pressed') !== 'true') return false;
108
+ button.click();
109
+ return true;
110
+ }
111
+
112
+ function resetReviewsForChanges(changes, context) {
113
+ const changed = Array.isArray(changes) ? changes : [];
114
+ if (!changed.length) return 0;
115
+ const resetButtons = new Set();
116
+ const taskRow = findPageRow(context && context.htmlPath);
117
+
118
+ changed.forEach(item => {
119
+ const file = normalizedPath(item && (item.file || item.path));
120
+ if (!file || file.endsWith('/nav-tree.json') || file === 'nav-tree.json') return;
121
+
122
+ if (/\.md$/i.test(file)) {
123
+ const row = findPageRow(file.replace(/\.md$/i, '.html'));
124
+ if (row) resetButtons.add(`${row.dataset.path}|md`);
125
+ return;
126
+ }
127
+
128
+ if (/\.html$/i.test(file)) {
129
+ const row = findPageRow(file);
130
+ if (row) resetButtons.add(`${row.dataset.path}|html`);
131
+ return;
132
+ }
133
+
134
+ if (/\.js$/i.test(file)) {
135
+ const siblingRow = findPageRow(file.replace(/\.js$/i, '.html'));
136
+ if (siblingRow) {
137
+ resetButtons.add(`${siblingRow.dataset.path}|html`);
138
+ return;
139
+ }
140
+ }
141
+
142
+ if (taskRow) resetButtons.add(`${taskRow.dataset.path}|html`);
143
+ });
144
+
145
+ let resetCount = 0;
146
+ resetButtons.forEach(key => {
147
+ const separator = key.lastIndexOf('|');
148
+ const row = findPageRow(key.slice(0, separator));
149
+ if (markReviewPending(row, key.slice(separator + 1))) resetCount += 1;
150
+ });
151
+ return resetCount;
152
+ }
153
+
154
+ async function consumeTaskChanges(sessionId, context) {
155
+ if (!sessionId) return 0;
156
+ try {
157
+ const data = await api(`/api/agent/sessions/${sessionId}/task-changes`);
158
+ return resetReviewsForChanges(data.changes, data.context || context || {});
159
+ } catch (err) {
160
+ return 0;
161
+ }
162
+ }
163
+
88
164
  function buildPanel() {
89
165
  const panel = document.getElementById('agentPanel');
90
166
  panel.innerHTML = [
@@ -154,7 +230,8 @@
154
230
  const stored = state.threads.map(item => ({
155
231
  id: item.id,
156
232
  title: item.title,
157
- createdAt: item.createdAt
233
+ createdAt: item.createdAt,
234
+ taskContext: item.taskContext || null
158
235
  }));
159
236
  agentStorage.setItem(THREADS_KEY, JSON.stringify(stored));
160
237
  if (state.sessionId) agentStorage.setItem(SESSION_KEY, state.sessionId);
@@ -220,6 +297,7 @@
220
297
  if (thread.id !== state.sessionId && data.status && data.status.type === 'idle') {
221
298
  thread.running = false;
222
299
  thread.unread = true;
300
+ await consumeTaskChanges(thread.id, thread.taskContext);
223
301
  reloadTaskPreview(thread.taskContext);
224
302
  }
225
303
  } catch (err) {
@@ -238,6 +316,7 @@
238
316
  try {
239
317
  const data = await api(`/api/agent/sessions/${thread.id}/status`);
240
318
  thread.running = Boolean(data.status && data.status.type !== 'idle');
319
+ if (!thread.running) await consumeTaskChanges(thread.id, thread.taskContext);
241
320
  } catch (err) {
242
321
  thread.running = false;
243
322
  }
@@ -677,9 +756,14 @@
677
756
  clearTimeout(state.statusPollTimer);
678
757
  state.statusPollTimer = null;
679
758
  setRunning(false);
680
- await Promise.all([refreshHistory(), refreshPending(), refreshDiff()]);
759
+ const results = await Promise.all([
760
+ refreshHistory(),
761
+ refreshPending(),
762
+ refreshDiff(),
763
+ consumeTaskChanges(state.sessionId, state.taskContext)
764
+ ]);
681
765
  reloadTaskPreview();
682
- setStatus('ready', '已完成,预览已刷新');
766
+ setStatus('ready', results[3] ? '已完成,预览已刷新;评审标记已重置' : '已完成,预览已刷新');
683
767
  }
684
768
 
685
769
  function handleEvent(event) {
@@ -693,6 +777,7 @@
693
777
  return;
694
778
  }
695
779
  if (type === 'session.error' || type === 'proxy.error') {
780
+ consumeTaskChanges(state.sessionId, state.taskContext);
696
781
  setRunning(false);
697
782
  setStatus('error', properties.message || 'OpenCode 执行失败');
698
783
  return;
@@ -758,7 +843,9 @@
758
843
  }
759
844
  connectEvents();
760
845
  const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
761
- setRunning(data.status && data.status.type !== 'idle');
846
+ const running = Boolean(data.status && data.status.type !== 'idle');
847
+ setRunning(running);
848
+ if (!running) await consumeTaskChanges(state.sessionId, state.taskContext);
762
849
  await Promise.all([refreshPending(), refreshDiff()]);
763
850
  } catch (err) {
764
851
  setStatus('error', `切换对话失败:${err.message}`);
@@ -783,7 +870,9 @@
783
870
  }
784
871
  connectEvents();
785
872
  const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
786
- setRunning(data.status && data.status.type !== 'idle');
873
+ const running = Boolean(data.status && data.status.type !== 'idle');
874
+ setRunning(running);
875
+ if (!running) await consumeTaskChanges(state.sessionId, state.taskContext);
787
876
  scheduleBackgroundStatusPoll();
788
877
  }
789
878
 
@@ -836,8 +925,11 @@
836
925
  try {
837
926
  await api(`/api/agent/sessions/${state.sessionId}/abort`, { method: 'POST' });
838
927
  setRunning(false);
839
- setStatus('ready', '任务已停止');
840
- await refreshHistory();
928
+ const results = await Promise.all([
929
+ refreshHistory(),
930
+ consumeTaskChanges(state.sessionId, state.taskContext)
931
+ ]);
932
+ setStatus('ready', results[1] ? '任务已停止;已修改内容的评审标记已重置' : '任务已停止');
841
933
  } catch (err) {
842
934
  setStatus('error', `停止失败:${err.message}`);
843
935
  }
@@ -756,29 +756,31 @@ function loadVersionCache() { try { return JSON.parse(navStorage.getItem(VER_CAC
756
756
  function saveVersionCache() { navStorage.setItem(VER_CACHE_KEY, JSON.stringify(versionCache)); }
757
757
  versionCache = loadVersionCache();
758
758
 
759
- function comparePrdVersions(left, right) {
760
- const leftParts = String(left || '').replace(/^v/i, '').split('.');
761
- const rightParts = String(right || '').replace(/^v/i, '').split('.');
762
- const length = Math.max(leftParts.length, rightParts.length);
763
- for (let index = 0; index < length; index += 1) {
764
- const leftPart = leftParts[index] || '0';
765
- const rightPart = rightParts[index] || '0';
766
- const leftNumber = /^\d+$/.test(leftPart) ? Number(leftPart) : null;
767
- const rightNumber = /^\d+$/.test(rightPart) ? Number(rightPart) : null;
768
- const comparison = leftNumber !== null && rightNumber !== null
769
- ? leftNumber - rightNumber
770
- : leftPart.localeCompare(rightPart, undefined, { numeric: true, sensitivity: 'base' });
771
- if (comparison !== 0) return comparison;
759
+ function extractPrdHistoryLatestVersion(text) {
760
+ const lines = String(text || '').replace(/<[^>]+>/g, '').split(/\r?\n/);
761
+ let latestVersion = null;
762
+
763
+ for (let index = 0; index < lines.length; index += 1) {
764
+ if (!/^\s*\|.*\|\s*$/.test(lines[index])) continue;
765
+
766
+ const tableLines = [];
767
+ while (index < lines.length && /^\s*\|.*\|\s*$/.test(lines[index])) {
768
+ tableLines.push(lines[index]);
769
+ index += 1;
770
+ }
771
+ index -= 1;
772
+
773
+ if (tableLines.length < 3 || !/^\s*\|(?:\s*:?-{3,}:?\s*\|)+\s*$/.test(tableLines[1])) continue;
774
+ const headerCell = tableLines[0].split('|')[1] || '';
775
+ if (!headerCell.includes('版本')) continue;
776
+
777
+ tableLines.slice(2).forEach(row => {
778
+ const version = (row.split('|')[1] || '').trim();
779
+ if (version) latestVersion = version;
780
+ });
772
781
  }
773
- return 0;
774
- }
775
782
 
776
- function extractPrdHistoryMaxVersion(text) {
777
- const plainText = String(text || '').replace(/<[^>]+>/g, '');
778
- const versions = [...plainText.matchAll(/^\|\s*(v\d+(?:\.[0-9a-z]+)+)\s*\|/gim)].map(match => match[1]);
779
- return versions.length
780
- ? versions.reduce((maxVersion, version) => comparePrdVersions(version, maxVersion) > 0 ? version : maxVersion)
781
- : null;
783
+ return latestVersion;
782
784
  }
783
785
 
784
786
  async function fetchPageVersion(htmlPath) {
@@ -787,7 +789,7 @@ async function fetchPageVersion(htmlPath) {
787
789
  const res = await fetch(mdPath, { cache: 'no-cache' });
788
790
  if (!res.ok) return null;
789
791
  const text = await res.text();
790
- return extractPrdHistoryMaxVersion(text);
792
+ return extractPrdHistoryLatestVersion(text);
791
793
  } catch { return null; }
792
794
  }
793
795