/* AI 设计师 Agent 聊天窗(首页)——参考 opencode Session/Tool 架构的后端驱动 */ (function () { if (!window.PL || !PL.api) return; const SID_KEY = 'pouchlab.agent.sid'; const HANDOFF_KEY = 'pouchlab.agent.handoff'; const st = { open: false, busy: false, sid: null, left: null, messages: [], state: null }; function ensure() { if (document.getElementById('plAgentFab')) return; const fab = document.createElement('button'); fab.id = 'plAgentFab'; fab.type = 'button'; fab.innerHTML = 'AI 设计师'; document.body.appendChild(fab); fab.addEventListener('click', toggle); const panel = document.createElement('div'); panel.id = 'plAgentPanel'; panel.className = 'pl-agent-panel'; panel.hidden = true; panel.innerHTML = '
' + '
AI 设计师说出需求,一步步帮你设计包装
' + '' + '' + '
' + '
' + '
你好!我是 AI 设计师 👋 告诉我你要做什么包装,比如:
' + '「做一个 140×210 的咖啡袋,牛皮纸加烫金,极简风格,300 个」
' + '「给两支 8oz 蜡烛设计一个高端简约的邮寄礼盒」
' + '我会逐步选型、定尺寸、配材质并生成图案,右侧实时预览,满意后点「去微调」。
' + '
' + '' + '' + '
' + '' + '' + '
'; document.body.appendChild(panel); panel.querySelector('#plAgentClose').addEventListener('click', function () { toggle(false); }); panel.querySelector('#plAgentSend').addEventListener('click', send); if (!localStorage.getItem(SID_KEY)) { localStorage.setItem(SID_KEY, 'ag' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8)); } st.sid = localStorage.getItem(SID_KEY); } function toggle(open) { ensure(); st.open = open === undefined ? !st.open : open; document.getElementById('plAgentPanel').hidden = !st.open; if (st.open) { if (window.PL.auth && !PL.auth.user()) { PL.auth.require(function () { refreshQuota(); }); } else { refreshQuota(); } setTimeout(function () { document.getElementById('plAgentInput').focus(); }, 60); } } function refreshQuota() { if (!PL.api.token()) return; PL.api.get('/ai/quota').then(function (q) { st.left = q.left; const el = document.getElementById('plAgentQuota'); if (el) el.textContent = q.configured ? ('剩余 ' + q.left + ' 次') : 'AI 未配置'; }, function () {}); // 恢复上次会话的方案(预览/状态卡) PL.api.get('/agent/session/' + currentSid() + '/status').then(function (r) { if (st.busy) return; // 正在跑任务时不覆盖 if (r && r.state && r.state.kind) { st.state = r.state; renderState(); } }, function () {}); } function appendMsg(role, html) { const body = document.getElementById('plAgentBody'); const div = document.createElement('div'); div.className = 'pl-agent-msg ' + (role === 'user' ? 'user' : 'ai'); div.innerHTML = html; body.appendChild(div); body.scrollTop = body.scrollHeight; return div; } const esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }; /* ------- 状态卡 + 预览小窗 ------- */ function labelBag(pid) { const m = { standup: '站立袋', flatbottom: '平底袋', coffee: '咖啡袋', kraft: '牛皮纸袋', mailer: '邮寄袋', garment: '服装袋' }; return m[pid] || pid || '-'; } function labelMaterial(id) { const m = { matte: '哑光膜', gloss: '亮光膜', kraft: '再生牛皮', compost: '可降解膜', card: '350g白卡', grey: '灰板2mm', corrugated: 'E楞瓦楞' }; return m[id] || id || '-'; } function labelBox(s) { const m = { carton: '卡纸折叠盒', mailer: '飞机盒', mailbox: '磁吸书型盒', drawer: '抽屉盒', tuck: '插盖盒', rsc: '平口箱' }; return m[s] || s || '-'; } function renderState() { const box = document.getElementById('plAgentState'); const prev = document.getElementById('plAgentPreview'); const s = st.state; if (!s || !s.kind) { box.hidden = true; prev.hidden = true; return; } let chips = []; if (s.kind === 'bag') { const b = s.bag; chips = ['袋子 · ' + labelBag(b.productId)]; if (b.customSize) chips.push(b.customSize.w + '×' + b.customSize.h + ' mm'); if (b.material) chips.push(labelMaterial(b.material)); if (b.finish && b.finish !== 'none') chips.push({ uv: '局部UV', foil: '烫金', soft: '触感膜' }[b.finish] || b.finish); if (b.qty) chips.push(b.qty + ' 个'); } else { const b = s.box; chips = ['盒子 · ' + labelBox(b.structure)]; if (b.w) chips.push(b.w + '×' + b.d + '×' + b.h + ' mm'); if (b.material) chips.push(labelMaterial(b.material)); if (b.qty) chips.push(b.qty + ' 个'); } box.innerHTML = '
' + chips.map(function (c) { return '' + esc(c) + ''; }).join('') + '
' + '✏️ 去微调 →'; box.hidden = false; box.querySelector('#plAgentGo').addEventListener('click', function (e) { e.preventDefault(); goEdit(); }); renderPreview(); } function renderPreview() { const prev = document.getElementById('plAgentPreview'); const s = st.state; if (!s || !s.kind) { prev.hidden = true; return; } if (s.kind === 'bag' && s.bag.design && window.PL.render && PL.data) { const D = PL.data, R = PL.render; const p = D.productById(s.bag.productId || 'standup') || D.products[0]; const size = s.bag.customSize || { w: 140, h: 210 }; const sides = ['front', 'back'].map(function (k) { const d = s.bag.design[k] || { elements: [] }; return '
' + R.bagSVG(p, k, d, { size: size, tight: true, material: s.bag.material || 'matte', finish: s.bag.finish || 'none' }) + '' + (k === 'front' ? '正面' : '背面') + '
'; }).join(''); prev.innerHTML = '
' + sides + '
'; prev.hidden = false; return; } if (s.kind === 'box' && s.box.w) { prev.innerHTML = buildBox3D(s.box); prev.hidden = false; initBox3D(prev, function () { goEdit(); }); return; } prev.hidden = true; } /* ------- 盒 CSS 3D 立方体预览(可拖拽旋转,点击进微调) ------- */ function buildBox3D(box) { box.faces = box.faces || {}; // 设计未生成时 faces 可能为 null(素色盒) const W = Math.max(40, Math.min(box.w, 400)); const D = Math.max(40, Math.min(box.d, 400)); const H = Math.max(40, Math.min(box.h, 400)); const scale = 150 / Math.max(W, D, H); // 预览基准边 ~150px const w = Math.round(W * scale), d = Math.round(D * scale), h = Math.round(H * scale); const faces = { front: { w: w, h: h, t: 'translate(-50%,-50%) translateZ(' + (d / 2) + 'px)' }, back: { w: w, h: h, t: 'translate(-50%,-50%) rotateY(180deg) translateZ(' + (d / 2) + 'px)' }, left: { w: d, h: h, t: 'translate(-50%,-50%) rotateY(-90deg) translateZ(' + (w / 2) + 'px)' }, right: { w: d, h: h, t: 'translate(-50%,-50%) rotateY(90deg) translateZ(' + (w / 2) + 'px)' }, top: { w: w, h: d, t: 'translate(-50%,-50%) rotateX(90deg) translateZ(' + (h / 2) + 'px)' }, bottom: { w: w, h: d, t: 'translate(-50%,-50%) rotateX(-90deg) translateZ(' + (h / 2) + 'px)' } }; let html = '
'; Object.keys(faces).forEach(function (k) { const geo = faces[k]; const f = box.faces[k] || {}; html += '
' + faceInner(f, geo) + '
'; }); html += '
拖拽旋转 · 点击进入微调
'; return html; } function faceInner(f, geo) { let html = ''; (f.items || []).forEach(function (it) { if (it.name === 'logo' && it.src) { const w = Math.max(14, (it.w || 16) / 100 * geo.w); html += ''; } else if ((it.name || '').indexOf('bg-') === 0 && it.src) { html += ''; } else if (it.type === 'text') { const fs = Math.max(6, (it.size || 12) / 260 * geo.h); html += '
' + esc(it.text || '') + '
'; } }); return html; } function initBox3D(container, onClick) { const stage = container.querySelector('.pl-agent-3d'); const inner = container.querySelector('.pl-agent-3d-inner'); if (!stage || !inner) return; let rx = -18, ry = -30, dragging = false, moved = 0, lx = 0, ly = 0; function apply() { inner.style.transform = 'rotateX(' + rx + 'deg) rotateY(' + ry + 'deg)'; } apply(); const auto = setInterval(function () { if (!dragging && document.contains(inner)) { ry += 0.4; apply(); } if (!document.contains(inner)) clearInterval(auto); }, 50); stage.addEventListener('pointerdown', function (e) { dragging = true; moved = 0; lx = e.clientX; ly = e.clientY; stage.setPointerCapture(e.pointerId); }); stage.addEventListener('pointermove', function (e) { if (!dragging) return; const dx = e.clientX - lx, dy = e.clientY - ly; moved += Math.abs(dx) + Math.abs(dy); ry += dx * 0.5; rx = Math.max(-80, Math.min(80, rx - dy * 0.4)); lx = e.clientX; ly = e.clientY; apply(); }); stage.addEventListener('pointerup', function () { dragging = false; if (moved < 6) onClick(); // 几乎没动 = 点击 }); } function goEdit() { localStorage.setItem(HANDOFF_KEY, JSON.stringify({ state: st.state, at: Date.now() })); location.href = st.state.kind === 'bag' ? 'studio.html' : 'box.html'; } /* ------- 发送 ------- */ function currentSid() { let sid = localStorage.getItem(SID_KEY); if (!sid) { sid = 'ag' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8); localStorage.setItem(SID_KEY, sid); } st.sid = sid; return sid; } function send() { currentSid(); if (window.PL.auth && !PL.auth.user()) { PL.auth.require(function () { send(); }); return; } const ta = document.getElementById('plAgentInput'); const text = (ta.value || '').trim(); if (!text || st.busy) return; ta.value = ''; appendMsg('user', esc(text)); st.busy = true; const btn = document.getElementById('plAgentSend'); btn.disabled = true; btn.textContent = '…'; const stepBox = appendMsg('ai', ' 正在理解需求…'); let shownSteps = 0; function renderSteps(task) { let html = ''; (task.steps || []).slice(0, shownSteps + 8).forEach(function (s, i) { if (i < shownSteps) return; html += '
✓ ' + esc(s.text) + '
'; }); shownSteps = (task.steps || []).length; stepBox.innerHTML = (task.status === 'running' ? '' : '') + (html || '正在理解需求…') + (task.status === 'running' ? '
继续执行中…
' : ''); const body = document.getElementById('plAgentBody'); body.scrollTop = body.scrollHeight; } PL.api.post('/agent/chat', { session_id: st.sid, message: text }, { timeout: 20000 }).then(function () { poll(); }, function (err) { if (err.status === 401) { st.busy = false; btn.disabled = false; btn.textContent = '发送'; PL.auth.require(function () { send(); }); return; } st.busy = false; btn.disabled = false; btn.textContent = '发送'; stepBox.innerHTML = '⚠️ ' + esc(err.message || '任务启动失败'); }); function poll() { if (!st.busy) return; PL.api.get('/agent/session/' + currentSid() + '/status', { timeout: 15000 }).then(function (task) { if (task.status === 'idle') { setTimeout(poll, 2000); return; } renderSteps(task); if (task.state && task.state.kind) { st.state = task.state; renderState(); } if (task.status === 'running') { setTimeout(poll, 3000); return; } // done / error st.busy = false; btn.disabled = false; btn.textContent = '发送'; if (task.status === 'done') { stepBox.remove(); appendMsg('ai', esc(task.reply).replace(/\n/g, '
')); st.state = task.state; if (task.left != null) { const q = document.getElementById('plAgentQuota'); if (q) q.textContent = '剩余 ' + task.left + ' 次'; } renderState(); } else { stepBox.innerHTML = '⚠️ ' + esc(task.error || '执行出错了,请重试'); } }, function () { setTimeout(poll, 4000); }); } } ensure(); // 悬浮按钮随脚本加载即创建(不等首次 toggle) window.PL = window.PL || {}; window.PL.agentChat = { open: toggle }; })();