openprototype 0.1.0 → 0.2.1

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 (57) hide show
  1. package/AGENTS.md +58 -0
  2. package/CONVENTIONS.md +54 -0
  3. package/LICENSE +21 -0
  4. package/README.md +234 -3
  5. package/bin/cli.js +297 -0
  6. package/lib/config.js +162 -0
  7. package/package.json +32 -10
  8. package/product/demo/pc/customer/customer_form.html +137 -0
  9. package/product/demo/pc/customer/customer_form.md +33 -0
  10. package/product/demo/pc/customer/customer_list.html +132 -0
  11. package/product/demo/pc/customer/customer_list.md +35 -0
  12. package/product/demo/pc/demo-data.js +23 -0
  13. package/product/demo/pc/index.html +1082 -0
  14. package/product/demo/pc/nav-tree.json +15 -0
  15. package/proto-kit.config.json +13 -0
  16. package/runtime/server.js +664 -0
  17. package/runtime/shared/ai-polish.js +159 -0
  18. package/runtime/shared/base-manager.js +168 -0
  19. package/runtime/shared/common/component-renderer.js +917 -0
  20. package/runtime/shared/common/copy-manager.js +134 -0
  21. package/runtime/shared/common/data-bridge.js +45 -0
  22. package/runtime/shared/common/form-renderer.js +211 -0
  23. package/runtime/shared/common/form.js +357 -0
  24. package/runtime/shared/common/formatter.js +78 -0
  25. package/runtime/shared/common/index.js +37 -0
  26. package/runtime/shared/common/line-chart.js +357 -0
  27. package/runtime/shared/common/modal-manager.js +82 -0
  28. package/runtime/shared/common/prd-panel.css +395 -0
  29. package/runtime/shared/common/prd-panel.js +1280 -0
  30. package/runtime/shared/common/prd-popup.js +168 -0
  31. package/runtime/shared/common/search-renderer.js +95 -0
  32. package/runtime/shared/common/table-renderer.js +177 -0
  33. package/runtime/shared/common/table.js +160 -0
  34. package/runtime/shared/common/toast.js +99 -0
  35. package/runtime/shared/common/ui-preference-manager.js +74 -0
  36. package/runtime/shared/common/view-mode.js +30 -0
  37. package/runtime/shared/common.js +43 -0
  38. package/runtime/shared/constants/icons.js +28 -0
  39. package/runtime/shared/constants/status.js +67 -0
  40. package/runtime/shared/libs/marked.min.js +69 -0
  41. package/runtime/shared/prd-content.js +9 -0
  42. package/runtime/shared/styles.css +7673 -0
  43. package/runtime/shared/utils.js +110 -0
  44. package/runtime/shared/view-controls.js +148 -0
  45. package/runtime/shell/agent-panel.css +429 -0
  46. package/runtime/shell/agent-panel.js +629 -0
  47. package/scripts/check/run-checks.js +58 -0
  48. package/scripts/check/smoke-test.js +244 -0
  49. package/scripts/check/static-check.js +248 -0
  50. package/scripts/check/sync-nav-tree.js +139 -0
  51. package/templates/AGENTS.md +58 -0
  52. package/templates/CONVENTIONS.md +54 -0
  53. package/templates/gitignore +12 -0
  54. package/templates/product-shell/index.html +1082 -0
  55. package/templates/skills/auto-test/SKILL.md +62 -0
  56. package/templates/skills/xiaojia/SKILL.md +299 -0
  57. package/cli.js +0 -4
@@ -0,0 +1,629 @@
1
+ (function() {
2
+ const KIT = window.PROTO_KIT || {};
3
+ const NS = (KIT.productId || 'proto') + '-navigator';
4
+ const SESSION_KEY = NS + '-agent-session';
5
+ const WIDTH_KEY = NS + '-agent-width';
6
+ const COLLAPSED_KEY = NS + '-agent-collapsed';
7
+ const DEFAULT_WIDTH = 380;
8
+ const MIN_WIDTH = 320;
9
+ const MAX_WIDTH = 600;
10
+ const HISTORY_REFRESH_DELAY = 180;
11
+ const agentStorage = window['localStorage'];
12
+
13
+ const state = {
14
+ sessionId: agentStorage.getItem(SESSION_KEY) || '',
15
+ currentContext: { htmlPath: '', prdPath: '', title: '' },
16
+ taskContext: null,
17
+ eventSource: null,
18
+ messages: [],
19
+ pending: { permissions: [], questions: [] },
20
+ diff: [],
21
+ running: false,
22
+ connected: false,
23
+ statusText: '正在连接 OpenCode…',
24
+ refreshTimer: null,
25
+ statusPollTimer: null,
26
+ taskStartedAt: 0,
27
+ optimisticMessage: ''
28
+ };
29
+
30
+ let refs = {};
31
+
32
+ function api(path, options) {
33
+ return fetch(path, options).then(async response => {
34
+ const data = await response.json().catch(() => ({}));
35
+ if (!response.ok || data.ok === false) {
36
+ throw new Error(data.error || `请求失败: ${response.status}`);
37
+ }
38
+ return data;
39
+ });
40
+ }
41
+
42
+ function basename(filePath) {
43
+ const cleanPath = String(filePath || '').split('?')[0].split('#')[0];
44
+ return decodeURIComponent(cleanPath.split('/').pop() || '');
45
+ }
46
+
47
+ function buildPanel() {
48
+ const panel = document.getElementById('agentPanel');
49
+ panel.innerHTML = [
50
+ '<button class="agent-resizer" id="agentResizer" type="button" aria-label="拖动调整 Agent 栏宽度"></button>',
51
+ '<div class="agent-header">',
52
+ ' <div class="agent-header-main">',
53
+ ' <div class="agent-title-row"><span class="agent-status-dot" id="agentStatusDot"></span><span>Agent · OpenCode</span></div>',
54
+ ' <div class="agent-subtitle" id="agentStatusText">正在连接 OpenCode…</div>',
55
+ ' </div>',
56
+ ' <button class="agent-header-btn agent-new-chat" id="agentNewChatBtn" type="button">新对话</button>',
57
+ ' <button class="agent-header-btn agent-toggle" id="agentToggleBtn" type="button">收起</button>',
58
+ '</div>',
59
+ '<div class="agent-context">',
60
+ ' <div class="agent-context-label">本条消息将携带</div>',
61
+ ' <div class="agent-context-chip"><span class="agent-context-kind">页面</span><span class="agent-context-value" id="agentHtmlContext">请先从左侧选择页面</span></div>',
62
+ ' <div class="agent-context-chip"><span class="agent-context-kind">PRD</span><span class="agent-context-value" id="agentPrdContext">未选择</span></div>',
63
+ ' <button class="agent-quick-action" id="agentPrdUpdateBtn" type="button" disabled>按当前 PRD 标红内容更新页面</button>',
64
+ '</div>',
65
+ '<div class="agent-messages" id="agentMessages"></div>',
66
+ '<div class="agent-composer">',
67
+ ' <div class="agent-input-wrap">',
68
+ ' <textarea class="agent-input" id="agentInput" placeholder="选择页面后,描述要修改的内容…" disabled></textarea>',
69
+ ' <div class="agent-composer-actions">',
70
+ ' <span class="agent-composer-hint">Enter 发送 · Shift+Enter 换行</span>',
71
+ ' <button class="agent-send-btn" id="agentSendBtn" type="button" disabled>发送</button>',
72
+ ' <button class="agent-stop-btn" id="agentStopBtn" type="button" hidden>停止</button>',
73
+ ' </div>',
74
+ ' </div>',
75
+ '</div>'
76
+ ].join('');
77
+
78
+ refs = {
79
+ panel,
80
+ resizer: document.getElementById('agentResizer'),
81
+ statusDot: document.getElementById('agentStatusDot'),
82
+ statusText: document.getElementById('agentStatusText'),
83
+ newChat: document.getElementById('agentNewChatBtn'),
84
+ toggle: document.getElementById('agentToggleBtn'),
85
+ htmlContext: document.getElementById('agentHtmlContext'),
86
+ prdContext: document.getElementById('agentPrdContext'),
87
+ quickAction: document.getElementById('agentPrdUpdateBtn'),
88
+ messages: document.getElementById('agentMessages'),
89
+ input: document.getElementById('agentInput'),
90
+ send: document.getElementById('agentSendBtn'),
91
+ stop: document.getElementById('agentStopBtn')
92
+ };
93
+ }
94
+
95
+ function setStatus(kind, text) {
96
+ state.statusText = text;
97
+ refs.statusDot.className = 'agent-status-dot' + (kind ? ` is-${kind}` : '');
98
+ refs.statusText.textContent = text;
99
+ }
100
+
101
+ function applyPanelWidth(width, persist) {
102
+ const viewportLimit = Math.max(MIN_WIDTH, window.innerWidth - 290 - 560);
103
+ const nextWidth = Math.max(MIN_WIDTH, Math.min(MAX_WIDTH, viewportLimit, Number(width) || DEFAULT_WIDTH));
104
+ refs.panel.style.width = `${nextWidth}px`;
105
+ if (persist) agentStorage.setItem(WIDTH_KEY, String(nextWidth));
106
+ }
107
+
108
+ function setCollapsed(collapsed, persist) {
109
+ refs.panel.classList.toggle('is-collapsed', collapsed);
110
+ refs.toggle.textContent = collapsed ? 'Agent' : '收起';
111
+ refs.toggle.setAttribute('aria-label', collapsed ? '展开 Agent' : '收起 Agent');
112
+ if (!collapsed) applyPanelWidth(agentStorage.getItem(WIDTH_KEY) || DEFAULT_WIDTH, false);
113
+ if (persist) agentStorage.setItem(COLLAPSED_KEY, collapsed ? '1' : '0');
114
+ }
115
+
116
+ function bindResize() {
117
+ let resizing = false;
118
+ refs.resizer.addEventListener('mousedown', event => {
119
+ if (refs.panel.classList.contains('is-collapsed')) return;
120
+ resizing = true;
121
+ refs.resizer.classList.add('is-resizing');
122
+ document.body.classList.add('is-resizing-agent');
123
+ event.preventDefault();
124
+ });
125
+ document.addEventListener('mousemove', event => {
126
+ if (!resizing) return;
127
+ applyPanelWidth(window.innerWidth - event.clientX, false);
128
+ });
129
+ document.addEventListener('mouseup', () => {
130
+ if (!resizing) return;
131
+ resizing = false;
132
+ refs.resizer.classList.remove('is-resizing');
133
+ document.body.classList.remove('is-resizing-agent');
134
+ applyPanelWidth(parseInt(refs.panel.style.width, 10), true);
135
+ });
136
+ window.addEventListener('resize', () => {
137
+ if (!refs.panel.classList.contains('is-collapsed')) {
138
+ applyPanelWidth(parseInt(refs.panel.style.width, 10), false);
139
+ }
140
+ });
141
+ }
142
+
143
+ function updateContextDisplay() {
144
+ const context = state.currentContext;
145
+ refs.htmlContext.textContent = context.htmlPath ? basename(context.htmlPath) : '请先从左侧选择页面';
146
+ refs.htmlContext.title = context.htmlPath || '';
147
+ refs.prdContext.textContent = context.prdPath ? basename(context.prdPath) : '未识别当前 PRD';
148
+ refs.prdContext.title = context.prdPath || '';
149
+ refs.input.disabled = !context.htmlPath || !state.connected || state.running;
150
+ refs.send.disabled = refs.input.disabled || !refs.input.value.trim();
151
+ refs.quickAction.disabled = !context.htmlPath || !context.prdPath || !state.connected || state.running;
152
+ }
153
+
154
+ function parseContextualText(text) {
155
+ const value = String(text || '');
156
+ const match = value.match(/^\[导航器上下文\]\n页面:([^\n]*)\nPRD:([^\n]*)\n\n([\s\S]*)$/);
157
+ if (!match) return { text: value, htmlPath: '', prdPath: '' };
158
+ return {
159
+ htmlPath: match[1],
160
+ prdPath: match[2] === '未识别' ? '' : match[2],
161
+ text: match[3]
162
+ };
163
+ }
164
+
165
+ function appendText(parent, className, text) {
166
+ const element = document.createElement('div');
167
+ element.className = className;
168
+ element.textContent = text;
169
+ parent.appendChild(element);
170
+ return element;
171
+ }
172
+
173
+ function renderMessage(item) {
174
+ const info = item.info || item;
175
+ const role = info.role || 'assistant';
176
+ const parts = Array.isArray(item.parts) ? item.parts : [];
177
+ const text = parts.filter(part => part.type === 'text').map(part => part.text || '').join('');
178
+ const toolParts = parts.filter(part => part.type === 'tool');
179
+ if (!text && !toolParts.length) return null;
180
+
181
+ const wrapper = document.createElement('div');
182
+ wrapper.className = `agent-message is-${role}`;
183
+ appendText(wrapper, 'agent-message-role', role === 'user' ? '你' : 'OpenCode');
184
+
185
+ const parsed = role === 'user' ? parseContextualText(text) : { text };
186
+ if (role === 'user' && (parsed.htmlPath || parsed.prdPath)) {
187
+ const context = document.createElement('div');
188
+ context.className = 'agent-message-context';
189
+ if (parsed.htmlPath) appendText(context, '', `页面 · ${basename(parsed.htmlPath)}`);
190
+ if (parsed.prdPath) appendText(context, '', `PRD · ${basename(parsed.prdPath)}`);
191
+ wrapper.appendChild(context);
192
+ }
193
+ if (parsed.text) appendText(wrapper, 'agent-message-body', parsed.text);
194
+
195
+ toolParts.forEach(part => {
196
+ const status = part.state && part.state.status ? part.state.status : 'pending';
197
+ const tool = document.createElement('div');
198
+ const statusClass = status === 'completed' ? 'complete' : status === 'error' ? 'error' : 'running';
199
+ tool.className = `agent-tool is-${statusClass}`;
200
+ const dot = document.createElement('span');
201
+ dot.className = 'agent-tool-status';
202
+ tool.appendChild(dot);
203
+ appendText(tool, '', (part.state && part.state.title) || part.tool || '执行工具');
204
+ wrapper.appendChild(tool);
205
+ });
206
+ return wrapper;
207
+ }
208
+
209
+ function renderPermission(item) {
210
+ const card = document.createElement('div');
211
+ card.className = 'agent-request-card';
212
+ appendText(card, 'agent-request-title', 'OpenCode 请求权限');
213
+ const detail = item.permission || item.action || item.title || '执行受保护操作';
214
+ appendText(card, 'agent-request-desc', detail);
215
+ const actions = document.createElement('div');
216
+ actions.className = 'agent-request-actions';
217
+ [['once', '允许一次', true], ['always', '始终允许', false], ['reject', '拒绝', false]].forEach(([reply, label, primary]) => {
218
+ const button = document.createElement('button');
219
+ button.type = 'button';
220
+ button.className = 'agent-request-btn' + (primary ? ' is-primary' : '');
221
+ button.textContent = label;
222
+ button.addEventListener('click', () => replyPermission(item.id, reply));
223
+ actions.appendChild(button);
224
+ });
225
+ card.appendChild(actions);
226
+ return card;
227
+ }
228
+
229
+ function renderQuestion(item) {
230
+ const card = document.createElement('div');
231
+ card.className = 'agent-request-card';
232
+ appendText(card, 'agent-request-title', 'OpenCode 需要你的选择');
233
+ const questions = Array.isArray(item.questions) ? item.questions : [];
234
+ questions.forEach((question, index) => {
235
+ appendText(card, 'agent-request-desc', question.question || question.header || `问题 ${index + 1}`);
236
+ const field = document.createElement(question.options && question.options.length ? 'select' : 'input');
237
+ field.className = 'agent-question-field';
238
+ field.dataset.questionIndex = String(index);
239
+ if (field.tagName === 'SELECT') {
240
+ question.options.forEach(option => {
241
+ const optionElement = document.createElement('option');
242
+ optionElement.value = option.label || option.value || String(option);
243
+ optionElement.textContent = option.label || option.value || String(option);
244
+ field.appendChild(optionElement);
245
+ });
246
+ } else {
247
+ field.type = 'text';
248
+ field.placeholder = '输入回答';
249
+ }
250
+ card.appendChild(field);
251
+ });
252
+ const actions = document.createElement('div');
253
+ actions.className = 'agent-request-actions';
254
+ const submit = document.createElement('button');
255
+ submit.type = 'button';
256
+ submit.className = 'agent-request-btn is-primary';
257
+ submit.textContent = '提交回答';
258
+ submit.addEventListener('click', () => {
259
+ const answers = Array.from(card.querySelectorAll('.agent-question-field')).map(field => [field.value]);
260
+ replyQuestion(item.id, answers);
261
+ });
262
+ actions.appendChild(submit);
263
+ card.appendChild(actions);
264
+ return card;
265
+ }
266
+
267
+ function renderDiff() {
268
+ if (!state.diff.length) return null;
269
+ const card = document.createElement('div');
270
+ card.className = 'agent-diff-card';
271
+ appendText(card, 'agent-diff-title', `本次会话涉及 ${state.diff.length} 个文件`);
272
+ state.diff.slice(0, 8).forEach(item => {
273
+ const fileName = item.file || item.path || item.filename || '';
274
+ const additions = Number(item.additions || 0);
275
+ const deletions = Number(item.deletions || 0);
276
+ appendText(card, 'agent-diff-file', `${fileName}${additions || deletions ? ` +${additions} / -${deletions}` : ''}`);
277
+ });
278
+ return card;
279
+ }
280
+
281
+ function renderMessages() {
282
+ refs.messages.replaceChildren();
283
+ state.pending.permissions.forEach(item => refs.messages.appendChild(renderPermission(item)));
284
+ state.pending.questions.forEach(item => refs.messages.appendChild(renderQuestion(item)));
285
+
286
+ const diffCard = renderDiff();
287
+ if (diffCard) refs.messages.appendChild(diffCard);
288
+
289
+ state.messages.forEach(item => {
290
+ const message = renderMessage(item);
291
+ if (message) refs.messages.appendChild(message);
292
+ });
293
+
294
+ if (state.optimisticMessage) {
295
+ const message = renderMessage({
296
+ info: { role: 'user' },
297
+ parts: [{ type: 'text', text: state.optimisticMessage }]
298
+ });
299
+ if (message) refs.messages.appendChild(message);
300
+ }
301
+
302
+ if (!refs.messages.children.length) {
303
+ const empty = document.createElement('div');
304
+ empty.className = 'agent-empty';
305
+ appendText(empty, 'agent-empty-title', '直接修改当前原型');
306
+ appendText(empty, '', '从左侧选择页面,然后描述需要调整的字段、交互或 PRD。OpenCode 会在这里持续显示过程和结果。');
307
+ refs.messages.appendChild(empty);
308
+ }
309
+ refs.messages.scrollTop = refs.messages.scrollHeight;
310
+ }
311
+
312
+ function setRunning(running) {
313
+ if (running && !state.running) state.taskStartedAt = Date.now();
314
+ state.running = running;
315
+ refs.stop.hidden = !running;
316
+ refs.send.hidden = running;
317
+ refs.newChat.disabled = running;
318
+ if (running) {
319
+ setStatus('running', 'OpenCode 正在处理…');
320
+ scheduleStatusPoll();
321
+ }
322
+ else if (state.connected) setStatus('ready', state.statusText.includes('失败') ? state.statusText : 'OpenCode 已连接');
323
+ updateContextDisplay();
324
+ }
325
+
326
+ function scheduleStatusPoll() {
327
+ if (state.statusPollTimer || !state.running || !state.sessionId) return;
328
+ state.statusPollTimer = setTimeout(async () => {
329
+ state.statusPollTimer = null;
330
+ if (!state.running) return;
331
+ try {
332
+ const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
333
+ const elapsed = Date.now() - state.taskStartedAt;
334
+ if (data.status && data.status.type === 'idle' && elapsed > 750) {
335
+ await finishTask();
336
+ return;
337
+ }
338
+ } catch (err) {
339
+ // SSE remains the primary signal when polling is temporarily unavailable.
340
+ }
341
+ scheduleStatusPoll();
342
+ }, 800);
343
+ }
344
+
345
+ function scheduleHistoryRefresh() {
346
+ clearTimeout(state.refreshTimer);
347
+ state.refreshTimer = setTimeout(() => {
348
+ refreshHistory();
349
+ refreshPending();
350
+ }, HISTORY_REFRESH_DELAY);
351
+ }
352
+
353
+ async function refreshHistory() {
354
+ if (!state.sessionId) return;
355
+ try {
356
+ const data = await api(`/api/agent/sessions/${state.sessionId}/messages`);
357
+ state.messages = data.messages || [];
358
+ if (state.optimisticMessage && state.messages.some(item => {
359
+ const info = item.info || item;
360
+ const text = (item.parts || []).filter(part => part.type === 'text').map(part => part.text || '').join('');
361
+ return info.role === 'user' && text === state.optimisticMessage;
362
+ })) {
363
+ state.optimisticMessage = '';
364
+ }
365
+ renderMessages();
366
+ return true;
367
+ } catch (err) {
368
+ if (!state.running) setStatus('error', `历史加载失败:${err.message}`);
369
+ return false;
370
+ }
371
+ }
372
+
373
+ async function refreshPending() {
374
+ if (!state.sessionId) return;
375
+ try {
376
+ const data = await api(`/api/agent/sessions/${state.sessionId}/pending`);
377
+ state.pending = {
378
+ permissions: data.permissions || [],
379
+ questions: data.questions || []
380
+ };
381
+ renderMessages();
382
+ } catch (err) {
383
+ // Pending prompts are best-effort; message streaming remains usable.
384
+ }
385
+ }
386
+
387
+ async function refreshDiff() {
388
+ if (!state.sessionId) return;
389
+ try {
390
+ const data = await api(`/api/agent/sessions/${state.sessionId}/diff`);
391
+ state.diff = Array.isArray(data.diff) ? data.diff : [];
392
+ renderMessages();
393
+ } catch (err) {
394
+ state.diff = [];
395
+ }
396
+ }
397
+
398
+ function reloadTaskPreview() {
399
+ if (!state.taskContext || state.currentContext.htmlPath !== state.taskContext.htmlPath) return;
400
+ const frame = document.getElementById('previewFrame');
401
+ if (!frame) return;
402
+ const baseUrl = state.taskContext.htmlPath;
403
+ frame.src = baseUrl + (baseUrl.includes('?') ? '&' : '?') + `_agentReload=${Date.now()}`;
404
+ }
405
+
406
+ async function finishTask() {
407
+ if (!state.running) return;
408
+ clearTimeout(state.statusPollTimer);
409
+ state.statusPollTimer = null;
410
+ setRunning(false);
411
+ await Promise.all([refreshHistory(), refreshPending(), refreshDiff()]);
412
+ reloadTaskPreview();
413
+ setStatus('ready', '已完成,预览已刷新');
414
+ }
415
+
416
+ function handleEvent(event) {
417
+ const type = event.type || '';
418
+ const properties = event.properties || {};
419
+ if (type === 'proxy.ready') return;
420
+ scheduleHistoryRefresh();
421
+ if (type.includes('permission') || type.includes('question')) refreshPending();
422
+ if (type === 'session.idle' || (type === 'session.status' && properties.status && properties.status.type === 'idle')) {
423
+ finishTask();
424
+ return;
425
+ }
426
+ if (type === 'session.error' || type === 'proxy.error') {
427
+ setRunning(false);
428
+ setStatus('error', properties.message || 'OpenCode 执行失败');
429
+ return;
430
+ }
431
+ if (state.running || type.includes('message') || type.includes('tool')) setRunning(true);
432
+ }
433
+
434
+ function connectEvents() {
435
+ if (state.eventSource) state.eventSource.close();
436
+ if (!state.sessionId) return;
437
+ state.eventSource = new EventSource(`/api/agent/sessions/${state.sessionId}/events`);
438
+ state.eventSource.onmessage = message => {
439
+ try {
440
+ handleEvent(JSON.parse(message.data));
441
+ } catch (err) {
442
+ // Ignore malformed proxy messages; EventSource will continue.
443
+ }
444
+ };
445
+ state.eventSource.onerror = () => {
446
+ if (!state.connected) setStatus('error', 'OpenCode 事件流连接失败');
447
+ };
448
+ }
449
+
450
+ async function createSession() {
451
+ const data = await api('/api/agent/sessions', {
452
+ method: 'POST',
453
+ headers: { 'Content-Type': 'application/json' },
454
+ body: JSON.stringify({ title: (KIT.productTitle || '原型') + ' Agent' })
455
+ });
456
+ state.sessionId = data.session.id;
457
+ agentStorage.setItem(SESSION_KEY, state.sessionId);
458
+ state.messages = [];
459
+ state.pending = { permissions: [], questions: [] };
460
+ state.diff = [];
461
+ state.optimisticMessage = '';
462
+ connectEvents();
463
+ renderMessages();
464
+ }
465
+
466
+ async function ensureSession() {
467
+ if (!state.sessionId) {
468
+ await createSession();
469
+ return;
470
+ }
471
+ const restored = await refreshHistory();
472
+ if (!restored) {
473
+ await createSession();
474
+ return;
475
+ }
476
+ connectEvents();
477
+ const data = await api(`/api/agent/sessions/${state.sessionId}/status`);
478
+ setRunning(data.status && data.status.type !== 'idle');
479
+ }
480
+
481
+ async function sendMessage(message) {
482
+ const text = String(message || '').trim();
483
+ if (!text || !state.currentContext.htmlPath || state.running) return;
484
+ try {
485
+ if (!state.sessionId) await createSession();
486
+ state.taskContext = { ...state.currentContext };
487
+ state.optimisticMessage = [
488
+ '[导航器上下文]',
489
+ `页面:${state.taskContext.htmlPath}`,
490
+ `PRD:${state.taskContext.prdPath || '未识别'}`,
491
+ '',
492
+ text
493
+ ].join('\n');
494
+ refs.input.value = '';
495
+ renderMessages();
496
+ setRunning(true);
497
+ await api(`/api/agent/sessions/${state.sessionId}/messages`, {
498
+ method: 'POST',
499
+ headers: { 'Content-Type': 'application/json' },
500
+ body: JSON.stringify({
501
+ message: state.optimisticMessage,
502
+ htmlPath: state.taskContext.htmlPath,
503
+ prdPath: state.taskContext.prdPath
504
+ })
505
+ });
506
+ scheduleHistoryRefresh();
507
+ } catch (err) {
508
+ state.optimisticMessage = '';
509
+ setRunning(false);
510
+ setStatus('error', `发送失败:${err.message}`);
511
+ renderMessages();
512
+ }
513
+ }
514
+
515
+ async function abortTask() {
516
+ if (!state.sessionId || !state.running) return;
517
+ try {
518
+ await api(`/api/agent/sessions/${state.sessionId}/abort`, { method: 'POST' });
519
+ setRunning(false);
520
+ setStatus('ready', '任务已停止');
521
+ await refreshHistory();
522
+ } catch (err) {
523
+ setStatus('error', `停止失败:${err.message}`);
524
+ }
525
+ }
526
+
527
+ async function replyPermission(requestId, reply) {
528
+ try {
529
+ await api(`/api/agent/sessions/${state.sessionId}/permissions/${requestId}`, {
530
+ method: 'POST',
531
+ headers: { 'Content-Type': 'application/json' },
532
+ body: JSON.stringify({ reply })
533
+ });
534
+ await refreshPending();
535
+ } catch (err) {
536
+ setStatus('error', `权限回复失败:${err.message}`);
537
+ }
538
+ }
539
+
540
+ async function replyQuestion(requestId, answers) {
541
+ try {
542
+ await api(`/api/agent/sessions/${state.sessionId}/questions/${requestId}`, {
543
+ method: 'POST',
544
+ headers: { 'Content-Type': 'application/json' },
545
+ body: JSON.stringify({ answers })
546
+ });
547
+ await refreshPending();
548
+ } catch (err) {
549
+ setStatus('error', `回答失败:${err.message}`);
550
+ }
551
+ }
552
+
553
+ function bindEvents() {
554
+ refs.toggle.addEventListener('click', () => {
555
+ setCollapsed(!refs.panel.classList.contains('is-collapsed'), true);
556
+ });
557
+ refs.newChat.addEventListener('click', async () => {
558
+ try {
559
+ await createSession();
560
+ setStatus('ready', '已开始新对话');
561
+ } catch (err) {
562
+ setStatus('error', `新建对话失败:${err.message}`);
563
+ }
564
+ });
565
+ refs.send.addEventListener('click', () => sendMessage(refs.input.value));
566
+ refs.stop.addEventListener('click', abortTask);
567
+ refs.quickAction.addEventListener('click', () => sendMessage('请只根据当前 PRD 中所有红色标记的内容更新当前 HTML/JS 原型及必要的 mock/constants;不要修改 PRD 本身,也不要处理未标红的历史内容。'));
568
+ refs.input.addEventListener('input', () => {
569
+ refs.send.disabled = refs.input.disabled || !refs.input.value.trim();
570
+ refs.input.style.height = 'auto';
571
+ refs.input.style.height = `${Math.min(refs.input.scrollHeight, 160)}px`;
572
+ });
573
+ refs.input.addEventListener('keydown', event => {
574
+ if (event.key === 'Enter' && !event.shiftKey) {
575
+ event.preventDefault();
576
+ sendMessage(refs.input.value);
577
+ }
578
+ });
579
+
580
+ window.addEventListener('pak-page-change', event => {
581
+ const detail = event.detail || {};
582
+ const htmlPath = detail.htmlPath || '';
583
+ state.currentContext = {
584
+ htmlPath,
585
+ prdPath: htmlPath ? htmlPath.replace(/\.html(?:\?.*)?$/i, '.md') : '',
586
+ title: detail.title || basename(htmlPath)
587
+ };
588
+ updateContextDisplay();
589
+ });
590
+
591
+ window.addEventListener('message', event => {
592
+ const frame = document.getElementById('previewFrame');
593
+ if (!frame || event.source !== frame.contentWindow) return;
594
+ if (!event.data || event.data.type !== 'pak-prd-context') return;
595
+ if (event.data.htmlPath && event.data.htmlPath !== state.currentContext.htmlPath) return;
596
+ state.currentContext.prdPath = event.data.prdPath || '';
597
+ updateContextDisplay();
598
+ });
599
+ }
600
+
601
+ async function init() {
602
+ buildPanel();
603
+ bindResize();
604
+ bindEvents();
605
+ applyPanelWidth(agentStorage.getItem(WIDTH_KEY) || DEFAULT_WIDTH, false);
606
+ setCollapsed(agentStorage.getItem(COLLAPSED_KEY) === '1', false);
607
+ renderMessages();
608
+ updateContextDisplay();
609
+
610
+ try {
611
+ const status = await api('/api/agent/status');
612
+ state.connected = true;
613
+ setStatus('ready', `OpenCode ${status.version} · ${status.model}`);
614
+ updateContextDisplay();
615
+ await ensureSession();
616
+ await refreshPending();
617
+ } catch (err) {
618
+ state.connected = false;
619
+ setStatus('error', `OpenCode 不可用:${err.message}`);
620
+ updateContextDisplay();
621
+ }
622
+ }
623
+
624
+ if (document.readyState === 'loading') {
625
+ document.addEventListener('DOMContentLoaded', init);
626
+ } else {
627
+ init();
628
+ }
629
+ })();
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 编排入口 — 先跑静态规则检查,再跑运行时冒烟测试,汇总成一份报告。
4
+ *
5
+ * 用法:
6
+ * node scripts/check/run-checks.js # 全量
7
+ * node scripts/check/run-checks.js --changed # 只查 git 改动(AI 生成后默认用这个)
8
+ * node scripts/check/run-checks.js product/demo/pc # 指定范围
9
+ * node scripts/check/run-checks.js --static-only # 跳过浏览器层
10
+ */
11
+
12
+ const { execFileSync } = require('child_process');
13
+ const path = require('path');
14
+
15
+ const DIR = __dirname;
16
+ const passthrough = process.argv.slice(2).filter((a) => a !== '--static-only');
17
+ const staticOnly = process.argv.includes('--static-only');
18
+
19
+ function run(script) {
20
+ try {
21
+ const out = execFileSync('node', [path.join(DIR, script), '--json', ...passthrough], { encoding: 'utf8' });
22
+ return JSON.parse(out);
23
+ } catch (e) {
24
+ // 脚本以非零退出码结束时,stdout 仍是 JSON
25
+ try { return JSON.parse(e.stdout); } catch { return { scanned: 0, errors: [{ file: script, rule: '运行', msg: String(e.message).slice(0, 200) }], warns: [] }; }
26
+ }
27
+ }
28
+
29
+ const nav = run('sync-nav-tree.js');
30
+ const stat = run('static-check.js');
31
+ const smoke = staticOnly ? { scanned: 0, errors: [], warns: [] } : run('smoke-test.js');
32
+
33
+ const allErr = [...stat.errors, ...smoke.errors];
34
+ const allWarn = [...nav.warns, ...stat.warns, ...smoke.warns];
35
+ if (nav.added && nav.added.length) {
36
+ console.log(`📌 导航树已自动同步新增页面(${nav.added.length} 个):${nav.added.join('、')}`);
37
+ }
38
+
39
+ console.log('\n════════════════════════════════════════');
40
+ console.log(' 原型自动化检查报告');
41
+ console.log('════════════════════════════════════════');
42
+ console.log(`静态规则:扫描 ${stat.scanned} 文件,${stat.errors.length} ERROR / ${stat.warns.length} WARN`);
43
+ console.log(`运行时 :打开 ${smoke.scanned} 页面,${smoke.errors.length} ERROR / ${smoke.warns.length} WARN`);
44
+ console.log('────────────────────────────────────────');
45
+
46
+ const fmt = (r) => ` ${r.file}${r.line ? ':' + r.line : ''} [${r.rule}] ${r.msg}`;
47
+ if (allErr.length) {
48
+ console.log(`\n❌ 必须修复(${allErr.length}):`);
49
+ allErr.forEach((r) => console.log(fmt(r)));
50
+ }
51
+ if (allWarn.length) {
52
+ console.log(`\n⚠️ 建议修复(${allWarn.length}):`);
53
+ allWarn.forEach((r) => console.log(fmt(r)));
54
+ }
55
+ if (!allErr.length && !allWarn.length) console.log('\n✅ 全部通过。');
56
+ console.log('');
57
+
58
+ process.exit(allErr.length ? 1 : 0);