agent-chat.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. /* AI 设计师 Agent 聊天窗(首页)——参考 opencode Session/Tool 架构的后端驱动 */
  2. (function () {
  3. if (!window.PL || !PL.api) return;
  4. const SID_KEY = 'pouchlab.agent.sid';
  5. const HANDOFF_KEY = 'pouchlab.agent.handoff';
  6. const st = {
  7. open: false, busy: false, sid: null, left: null,
  8. messages: [], state: null
  9. };
  10. function ensure() {
  11. if (document.getElementById('plAgentFab')) return;
  12. const fab = document.createElement('button');
  13. fab.id = 'plAgentFab';
  14. fab.type = 'button';
  15. fab.innerHTML = '<svg viewBox="0 0 24 24" aria-hidden="true"><defs><linearGradient id="plAISpark" x1="0" y1="0" x2="1" y2="1"><stop offset="0" style="stop-color:rgba(var(--accent-rgb),0.55)"/><stop offset="1" style="stop-color:var(--accent)"/></linearGradient></defs><path fill="url(#plAISpark)" d="M12 1.6c.7 5.6 4.8 9.7 10.4 10.4-5.6.7-9.7 4.8-10.4 10.4C11.3 16.8 7.2 12.7 1.6 12 7.2 11.3 11.3 7.2 12 1.6Z"/><path fill="url(#plAISpark)" d="M19.4 2.2c.25 1.75 1.55 3.05 3.3 3.3-1.75.25-3.05 1.55-3.3 3.3-.25-1.75-1.55-3.05-3.3-3.3 1.75-.25 3.05-1.55 3.3-3.3Z"/></svg><span>AI 设计师</span>';
  16. document.body.appendChild(fab);
  17. fab.addEventListener('click', toggle);
  18. const panel = document.createElement('div');
  19. panel.id = 'plAgentPanel';
  20. panel.className = 'pl-agent-panel';
  21. panel.hidden = true;
  22. panel.innerHTML =
  23. '<div class="pl-agent-head">' +
  24. '<div><b><svg viewBox="0 0 24 24" aria-hidden="true"><defs><linearGradient id="plAISpark" x1="0" y1="0" x2="1" y2="1"><stop offset="0" style="stop-color:rgba(var(--accent-rgb),0.55)"/><stop offset="1" style="stop-color:var(--accent)"/></linearGradient></defs><path fill="url(#plAISpark)" d="M12 1.6c.7 5.6 4.8 9.7 10.4 10.4-5.6.7-9.7 4.8-10.4 10.4C11.3 16.8 7.2 12.7 1.6 12 7.2 11.3 11.3 7.2 12 1.6Z"/><path fill="url(#plAISpark)" d="M19.4 2.2c.25 1.75 1.55 3.05 3.3 3.3-1.75.25-3.05 1.55-3.3 3.3-.25-1.75-1.55-3.05-3.3-3.3 1.75-.25 3.05-1.55 3.3-3.3Z"/></svg>AI 设计师</b><small>说出需求,一步步帮你设计包装</small></div>' +
  25. '<span class="pl-agent-quota" id="plAgentQuota"></span>' +
  26. '<button type="button" class="pl-agent-close" id="plAgentClose">✕</button>' +
  27. '</div>' +
  28. '<div class="pl-agent-body" id="plAgentBody">' +
  29. '<div class="pl-agent-msg ai">你好!我是 AI 设计师 👋 告诉我你要做什么包装,比如:<br>' +
  30. '「做一个 140×210 的咖啡袋,牛皮纸加烫金,极简风格,300 个」<br>' +
  31. '「给两支 8oz 蜡烛设计一个高端简约的邮寄礼盒」<br>' +
  32. '我会逐步选型、定尺寸、配材质并生成图案,右侧实时预览,满意后点「去微调」。</div>' +
  33. '</div>' +
  34. '<div class="pl-agent-preview" id="plAgentPreview" hidden></div>' +
  35. '<div class="pl-agent-state" id="plAgentState" hidden></div>' +
  36. '<div class="pl-agent-input">' +
  37. '<textarea id="plAgentInput" rows="2" placeholder="描述你的包装需求,或继续调整…"></textarea>' +
  38. '<button type="button" class="pl-agent-send" id="plAgentSend">发送</button>' +
  39. '</div>';
  40. document.body.appendChild(panel);
  41. panel.querySelector('#plAgentClose').addEventListener('click', function () { toggle(false); });
  42. panel.querySelector('#plAgentSend').addEventListener('click', send);
  43. if (!localStorage.getItem(SID_KEY)) {
  44. localStorage.setItem(SID_KEY, 'ag' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8));
  45. }
  46. st.sid = localStorage.getItem(SID_KEY);
  47. }
  48. function toggle(open) {
  49. ensure();
  50. st.open = open === undefined ? !st.open : open;
  51. document.getElementById('plAgentPanel').hidden = !st.open;
  52. if (st.open) {
  53. if (window.PL.auth && !PL.auth.user()) {
  54. PL.auth.require(function () { refreshQuota(); });
  55. } else {
  56. refreshQuota();
  57. }
  58. setTimeout(function () { document.getElementById('plAgentInput').focus(); }, 60);
  59. }
  60. }
  61. function refreshQuota() {
  62. if (!PL.api.token()) return;
  63. PL.api.get('/ai/quota').then(function (q) {
  64. st.left = q.left;
  65. const el = document.getElementById('plAgentQuota');
  66. if (el) el.textContent = q.configured ? ('剩余 ' + q.left + ' 次') : 'AI 未配置';
  67. }, function () {});
  68. // 恢复上次会话的方案(预览/状态卡)
  69. PL.api.get('/agent/session/' + currentSid() + '/status').then(function (r) {
  70. if (st.busy) return; // 正在跑任务时不覆盖
  71. if (r && r.state && r.state.kind) {
  72. st.state = r.state;
  73. renderState();
  74. }
  75. }, function () {});
  76. }
  77. function appendMsg(role, html) {
  78. const body = document.getElementById('plAgentBody');
  79. const div = document.createElement('div');
  80. div.className = 'pl-agent-msg ' + (role === 'user' ? 'user' : 'ai');
  81. div.innerHTML = html;
  82. body.appendChild(div);
  83. body.scrollTop = body.scrollHeight;
  84. return div;
  85. }
  86. const esc = function (s) {
  87. return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
  88. return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
  89. });
  90. };
  91. /* ------- 状态卡 + 预览小窗 ------- */
  92. function labelBag(pid) {
  93. const m = { standup: '站立袋', flatbottom: '平底袋', coffee: '咖啡袋', kraft: '牛皮纸袋', mailer: '邮寄袋', garment: '服装袋' };
  94. return m[pid] || pid || '-';
  95. }
  96. function labelMaterial(id) {
  97. const m = { matte: '哑光膜', gloss: '亮光膜', kraft: '再生牛皮', compost: '可降解膜',
  98. card: '350g白卡', grey: '灰板2mm', corrugated: 'E楞瓦楞' };
  99. return m[id] || id || '-';
  100. }
  101. function labelBox(s) {
  102. const m = { carton: '卡纸折叠盒', mailer: '飞机盒', mailbox: '磁吸书型盒', drawer: '抽屉盒', tuck: '插盖盒', rsc: '平口箱' };
  103. return m[s] || s || '-';
  104. }
  105. function renderState() {
  106. const box = document.getElementById('plAgentState');
  107. const prev = document.getElementById('plAgentPreview');
  108. const s = st.state;
  109. if (!s || !s.kind) { box.hidden = true; prev.hidden = true; return; }
  110. let chips = [];
  111. if (s.kind === 'bag') {
  112. const b = s.bag;
  113. chips = ['袋子 · ' + labelBag(b.productId)];
  114. if (b.customSize) chips.push(b.customSize.w + '×' + b.customSize.h + ' mm');
  115. if (b.material) chips.push(labelMaterial(b.material));
  116. if (b.finish && b.finish !== 'none') chips.push({ uv: '局部UV', foil: '烫金', soft: '触感膜' }[b.finish] || b.finish);
  117. if (b.qty) chips.push(b.qty + ' 个');
  118. } else {
  119. const b = s.box;
  120. chips = ['盒子 · ' + labelBox(b.structure)];
  121. if (b.w) chips.push(b.w + '×' + b.d + '×' + b.h + ' mm');
  122. if (b.material) chips.push(labelMaterial(b.material));
  123. if (b.qty) chips.push(b.qty + ' 个');
  124. }
  125. box.innerHTML = '<div class="pl-agent-chips">' + chips.map(function (c) {
  126. return '<span>' + esc(c) + '</span>';
  127. }).join('') + '</div>' +
  128. '<a class="pl-agent-go" id="plAgentGo" href="#">✏️ 去微调 →</a>';
  129. box.hidden = false;
  130. box.querySelector('#plAgentGo').addEventListener('click', function (e) {
  131. e.preventDefault();
  132. goEdit();
  133. });
  134. renderPreview();
  135. }
  136. function renderPreview() {
  137. const prev = document.getElementById('plAgentPreview');
  138. const s = st.state;
  139. if (!s || !s.kind) { prev.hidden = true; return; }
  140. if (s.kind === 'bag' && s.bag.design && window.PL.render && PL.data) {
  141. const D = PL.data, R = PL.render;
  142. const p = D.productById(s.bag.productId || 'standup') || D.products[0];
  143. const size = s.bag.customSize || { w: 140, h: 210 };
  144. const sides = ['front', 'back'].map(function (k) {
  145. const d = s.bag.design[k] || { elements: [] };
  146. return '<div class="pl-agent-face">' +
  147. R.bagSVG(p, k, d, { size: size, tight: true, material: s.bag.material || 'matte', finish: s.bag.finish || 'none' }) +
  148. '<i>' + (k === 'front' ? '正面' : '背面') + '</i></div>';
  149. }).join('');
  150. prev.innerHTML = '<div class="pl-agent-faces">' + sides + '</div>';
  151. prev.hidden = false;
  152. return;
  153. }
  154. if (s.kind === 'box' && s.box.w) {
  155. prev.innerHTML = buildBox3D(s.box);
  156. prev.hidden = false;
  157. initBox3D(prev, function () { goEdit(); });
  158. return;
  159. }
  160. prev.hidden = true;
  161. }
  162. /* ------- 盒 CSS 3D 立方体预览(可拖拽旋转,点击进微调) ------- */
  163. function buildBox3D(box) {
  164. box.faces = box.faces || {}; // 设计未生成时 faces 可能为 null(素色盒)
  165. const W = Math.max(40, Math.min(box.w, 400));
  166. const D = Math.max(40, Math.min(box.d, 400));
  167. const H = Math.max(40, Math.min(box.h, 400));
  168. const scale = 150 / Math.max(W, D, H); // 预览基准边 ~150px
  169. const w = Math.round(W * scale), d = Math.round(D * scale), h = Math.round(H * scale);
  170. const faces = {
  171. front: { w: w, h: h, t: 'translate(-50%,-50%) translateZ(' + (d / 2) + 'px)' },
  172. back: { w: w, h: h, t: 'translate(-50%,-50%) rotateY(180deg) translateZ(' + (d / 2) + 'px)' },
  173. left: { w: d, h: h, t: 'translate(-50%,-50%) rotateY(-90deg) translateZ(' + (w / 2) + 'px)' },
  174. right: { w: d, h: h, t: 'translate(-50%,-50%) rotateY(90deg) translateZ(' + (w / 2) + 'px)' },
  175. top: { w: w, h: d, t: 'translate(-50%,-50%) rotateX(90deg) translateZ(' + (h / 2) + 'px)' },
  176. bottom: { w: w, h: d, t: 'translate(-50%,-50%) rotateX(-90deg) translateZ(' + (h / 2) + 'px)' }
  177. };
  178. let html = '<div class="pl-agent-3d" tabindex="0"><div class="pl-agent-3d-inner" id="plAgent3dInner" style="--bw:' + w + 'px;--bh:' + h + 'px">';
  179. Object.keys(faces).forEach(function (k) {
  180. const geo = faces[k];
  181. const f = box.faces[k] || {};
  182. html += '<div class="pl-agent-3d-face" style="width:' + geo.w + 'px;height:' + geo.h + 'px;transform:' + geo.t + ';background:' + (f.color || '#efe9dc') + '">' +
  183. faceInner(f, geo) + '</div>';
  184. });
  185. html += '</div><span class="pl-agent-3d-hint">拖拽旋转 · 点击进入微调</span></div>';
  186. return html;
  187. }
  188. function faceInner(f, geo) {
  189. let html = '';
  190. (f.items || []).forEach(function (it) {
  191. if (it.name === 'logo' && it.src) {
  192. const w = Math.max(14, (it.w || 16) / 100 * geo.w);
  193. html += '<img class="pv-logo" src="' + it.src + '" style="width:' + w + 'px;left:' + ((it.x || 50) - (w / geo.w) * 50) + '%;top:' + (it.y || 50) + '%">';
  194. } else if ((it.name || '').indexOf('bg-') === 0 && it.src) {
  195. html += '<img class="pv-bg" src="' + it.src + '">';
  196. } else if (it.type === 'text') {
  197. const fs = Math.max(6, (it.size || 12) / 260 * geo.h);
  198. html += '<div class="pv-text" style="font-size:' + fs + 'px;color:' + (it.color || '#2b2620') + ';font-weight:' + (it.weight || 400) +
  199. ';left:' + (it.x || 50) + '%;top:' + (it.y || 50) + '%">' + esc(it.text || '') + '</div>';
  200. }
  201. });
  202. return html;
  203. }
  204. function initBox3D(container, onClick) {
  205. const stage = container.querySelector('.pl-agent-3d');
  206. const inner = container.querySelector('.pl-agent-3d-inner');
  207. if (!stage || !inner) return;
  208. let rx = -18, ry = -30, dragging = false, moved = 0, lx = 0, ly = 0;
  209. function apply() {
  210. inner.style.transform = 'rotateX(' + rx + 'deg) rotateY(' + ry + 'deg)';
  211. }
  212. apply();
  213. const auto = setInterval(function () {
  214. if (!dragging && document.contains(inner)) { ry += 0.4; apply(); }
  215. if (!document.contains(inner)) clearInterval(auto);
  216. }, 50);
  217. stage.addEventListener('pointerdown', function (e) {
  218. dragging = true; moved = 0; lx = e.clientX; ly = e.clientY;
  219. stage.setPointerCapture(e.pointerId);
  220. });
  221. stage.addEventListener('pointermove', function (e) {
  222. if (!dragging) return;
  223. const dx = e.clientX - lx, dy = e.clientY - ly;
  224. moved += Math.abs(dx) + Math.abs(dy);
  225. ry += dx * 0.5; rx = Math.max(-80, Math.min(80, rx - dy * 0.4));
  226. lx = e.clientX; ly = e.clientY;
  227. apply();
  228. });
  229. stage.addEventListener('pointerup', function () {
  230. dragging = false;
  231. if (moved < 6) onClick(); // 几乎没动 = 点击
  232. });
  233. }
  234. function goEdit() {
  235. localStorage.setItem(HANDOFF_KEY, JSON.stringify({ state: st.state, at: Date.now() }));
  236. location.href = st.state.kind === 'bag' ? 'studio.html' : 'box.html';
  237. }
  238. /* ------- 发送 ------- */
  239. function currentSid() {
  240. let sid = localStorage.getItem(SID_KEY);
  241. if (!sid) {
  242. sid = 'ag' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
  243. localStorage.setItem(SID_KEY, sid);
  244. }
  245. st.sid = sid;
  246. return sid;
  247. }
  248. function send() {
  249. currentSid();
  250. if (window.PL.auth && !PL.auth.user()) {
  251. PL.auth.require(function () { send(); });
  252. return;
  253. }
  254. const ta = document.getElementById('plAgentInput');
  255. const text = (ta.value || '').trim();
  256. if (!text || st.busy) return;
  257. ta.value = '';
  258. appendMsg('user', esc(text));
  259. st.busy = true;
  260. const btn = document.getElementById('plAgentSend');
  261. btn.disabled = true; btn.textContent = '…';
  262. const stepBox = appendMsg('ai', '<span class="pl-agent-dot"></span> 正在理解需求…');
  263. let shownSteps = 0;
  264. function renderSteps(task) {
  265. let html = '';
  266. (task.steps || []).slice(0, shownSteps + 8).forEach(function (s, i) {
  267. if (i < shownSteps) return;
  268. html += '<div class="pl-agent-step">✓ ' + esc(s.text) + '</div>';
  269. });
  270. shownSteps = (task.steps || []).length;
  271. stepBox.innerHTML = (task.status === 'running' ? '<span class="pl-agent-dot"></span>' : '') +
  272. (html || '正在理解需求…') +
  273. (task.status === 'running' ? '<div class="pl-agent-step pending">继续执行中…</div>' : '');
  274. const body = document.getElementById('plAgentBody');
  275. body.scrollTop = body.scrollHeight;
  276. }
  277. PL.api.post('/agent/chat', { session_id: st.sid, message: text }, { timeout: 20000 }).then(function () {
  278. poll();
  279. }, function (err) {
  280. if (err.status === 401) { st.busy = false; btn.disabled = false; btn.textContent = '发送'; PL.auth.require(function () { send(); }); return; }
  281. st.busy = false; btn.disabled = false; btn.textContent = '发送';
  282. stepBox.innerHTML = '⚠️ ' + esc(err.message || '任务启动失败');
  283. });
  284. function poll() {
  285. if (!st.busy) return;
  286. PL.api.get('/agent/session/' + currentSid() + '/status', { timeout: 15000 }).then(function (task) {
  287. if (task.status === 'idle') { setTimeout(poll, 2000); return; }
  288. renderSteps(task);
  289. if (task.state && task.state.kind) { st.state = task.state; renderState(); }
  290. if (task.status === 'running') { setTimeout(poll, 3000); return; }
  291. // done / error
  292. st.busy = false;
  293. btn.disabled = false; btn.textContent = '发送';
  294. if (task.status === 'done') {
  295. stepBox.remove();
  296. appendMsg('ai', esc(task.reply).replace(/\n/g, '<br>'));
  297. st.state = task.state;
  298. if (task.left != null) {
  299. const q = document.getElementById('plAgentQuota');
  300. if (q) q.textContent = '剩余 ' + task.left + ' 次';
  301. }
  302. renderState();
  303. } else {
  304. stepBox.innerHTML = '⚠️ ' + esc(task.error || '执行出错了,请重试');
  305. }
  306. }, function () { setTimeout(poll, 4000); });
  307. }
  308. }
  309. ensure(); // 悬浮按钮随脚本加载即创建(不等首次 toggle)
  310. window.PL = window.PL || {};
  311. window.PL.agentChat = { open: toggle };
  312. })();