openprototype 1.8.2 → 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.2",
3
+ "version": "1.8.3",
4
4
  "description": "本地原型工作台:左侧树形导航 + 中间原型预览 + 右侧 AI Agent(OpenCode)。PRD 与 HTML/JS 原型协作,含自动化检查。",
5
5
  "keywords": [
6
6
  "prototype",
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();
@@ -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
  }