| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333 |
- /* 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 = '<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>';
- 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 =
- '<div class="pl-agent-head">' +
- '<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>' +
- '<span class="pl-agent-quota" id="plAgentQuota"></span>' +
- '<button type="button" class="pl-agent-close" id="plAgentClose">✕</button>' +
- '</div>' +
- '<div class="pl-agent-body" id="plAgentBody">' +
- '<div class="pl-agent-msg ai">你好!我是 AI 设计师 👋 告诉我你要做什么包装,比如:<br>' +
- '「做一个 140×210 的咖啡袋,牛皮纸加烫金,极简风格,300 个」<br>' +
- '「给两支 8oz 蜡烛设计一个高端简约的邮寄礼盒」<br>' +
- '我会逐步选型、定尺寸、配材质并生成图案,右侧实时预览,满意后点「去微调」。</div>' +
- '</div>' +
- '<div class="pl-agent-preview" id="plAgentPreview" hidden></div>' +
- '<div class="pl-agent-state" id="plAgentState" hidden></div>' +
- '<div class="pl-agent-input">' +
- '<textarea id="plAgentInput" rows="2" placeholder="描述你的包装需求,或继续调整…"></textarea>' +
- '<button type="button" class="pl-agent-send" id="plAgentSend">发送</button>' +
- '</div>';
- 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 = '<div class="pl-agent-chips">' + chips.map(function (c) {
- return '<span>' + esc(c) + '</span>';
- }).join('') + '</div>' +
- '<a class="pl-agent-go" id="plAgentGo" href="#">✏️ 去微调 →</a>';
- 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 '<div class="pl-agent-face">' +
- R.bagSVG(p, k, d, { size: size, tight: true, material: s.bag.material || 'matte', finish: s.bag.finish || 'none' }) +
- '<i>' + (k === 'front' ? '正面' : '背面') + '</i></div>';
- }).join('');
- prev.innerHTML = '<div class="pl-agent-faces">' + sides + '</div>';
- 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 = '<div class="pl-agent-3d" tabindex="0"><div class="pl-agent-3d-inner" id="plAgent3dInner" style="--bw:' + w + 'px;--bh:' + h + 'px">';
- Object.keys(faces).forEach(function (k) {
- const geo = faces[k];
- const f = box.faces[k] || {};
- html += '<div class="pl-agent-3d-face" style="width:' + geo.w + 'px;height:' + geo.h + 'px;transform:' + geo.t + ';background:' + (f.color || '#efe9dc') + '">' +
- faceInner(f, geo) + '</div>';
- });
- html += '</div><span class="pl-agent-3d-hint">拖拽旋转 · 点击进入微调</span></div>';
- 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 += '<img class="pv-logo" src="' + it.src + '" style="width:' + w + 'px;left:' + ((it.x || 50) - (w / geo.w) * 50) + '%;top:' + (it.y || 50) + '%">';
- } else if ((it.name || '').indexOf('bg-') === 0 && it.src) {
- html += '<img class="pv-bg" src="' + it.src + '">';
- } else if (it.type === 'text') {
- const fs = Math.max(6, (it.size || 12) / 260 * geo.h);
- html += '<div class="pv-text" style="font-size:' + fs + 'px;color:' + (it.color || '#2b2620') + ';font-weight:' + (it.weight || 400) +
- ';left:' + (it.x || 50) + '%;top:' + (it.y || 50) + '%">' + esc(it.text || '') + '</div>';
- }
- });
- 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', '<span class="pl-agent-dot"></span> 正在理解需求…');
- let shownSteps = 0;
- function renderSteps(task) {
- let html = '';
- (task.steps || []).slice(0, shownSteps + 8).forEach(function (s, i) {
- if (i < shownSteps) return;
- html += '<div class="pl-agent-step">✓ ' + esc(s.text) + '</div>';
- });
- shownSteps = (task.steps || []).length;
- stepBox.innerHTML = (task.status === 'running' ? '<span class="pl-agent-dot"></span>' : '') +
- (html || '正在理解需求…') +
- (task.status === 'running' ? '<div class="pl-agent-step pending">继续执行中…</div>' : '');
- 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, '<br>'));
- 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 };
- })();
|