lampson 0.4.0 → 0.5.0
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/README.md +8 -2
- package/chat.syn +1 -1
- package/hub.tpl.syn +99 -7
- package/lib/api.syn +178 -7
- package/lib/diagnose.syn +142 -0
- package/lib/loop.syn +14 -0
- package/lib/plugins.syn +6 -4
- package/lib/provider.syn +16 -13
- package/lib/runtime.syn +56 -0
- package/lib/schedule.syn +40 -2
- package/lib/teamrun.syn +78 -4
- package/lib/teams.syn +397 -24
- package/lib/workspaces.syn +84 -1
- package/lib/worktree.syn +108 -0
- package/package.json +1 -1
- package/plugins/example-hello/plugin.json +1 -0
- package/public/css/chat.css +9 -8
- package/public/css/hub.css +73 -11
- package/public/css/layout.css +12 -4
- package/public/css/login.css +1 -1
- package/public/css/mobile.css +2 -2
- package/public/css/panel.css +16 -7
- package/public/css/sidebar.css +1 -1
- package/public/css/teams.css +722 -48
- package/public/css/tokens.css +36 -12
- package/public/css/views.css +124 -0
- package/public/hub.html +17 -8
- package/public/index.html +3 -2
- package/public/js/app.js +2 -2
- package/public/js/approvals.js +1 -1
- package/public/js/core.js +5 -2
- package/public/js/flow.js +187 -0
- package/public/js/hub.js +131 -22
- package/public/js/navtabs.js +23 -0
- package/public/js/objdiag.js +90 -0
- package/public/js/objlive.js +393 -0
- package/public/js/panel.js +2 -1
- package/public/js/plugins-home.js +59 -0
- package/public/js/plugins.js +40 -18
- package/public/js/schedules.js +5 -0
- package/public/js/sidebar.js +6 -4
- package/public/js/tasks-home.js +104 -0
- package/public/js/teams-home.js +144 -0
- package/public/js/teams.js +928 -195
- package/public/js/terminal.js +8 -2
- package/public/js/workspaces.js +6 -3
- package/public/plugins-home.html +32 -0
- package/public/tasks-home.html +31 -0
- package/public/teams-home.html +45 -0
- package/public/teams.html +33 -45
- package/public/vendor/xterm-addon-webgl.js +2 -0
- package/web.syn +61 -8
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
// objlive.js — la vista EN VIVO de un objetivo abierto (la usa js/teams.js → loadObj; cuando termina, la página pasa
|
|
2
|
+
// sola al informe). Tres partes, todas con datos reales — nada se mueve si no pasó algo:
|
|
3
|
+
// · el equipo vivo (js/flow.js, con las posiciones del editor): cada asiento tiene su color; quien trabaja lleva un
|
|
4
|
+
// anillo que gira y un ícono animado de lo que hace (piensa, lee, escribe, corre un comando, git, escribe a alguien,
|
|
5
|
+
// mueve el tablero); lo que dice aparece en un globo; cada mensaje viaja como un sobre por la línea, que se enciende
|
|
6
|
+
// · el tablero: las tarjetas se deslizan de columna (FLIP) y una ficha vuela desde quien la movió
|
|
7
|
+
// · lo último: los eventos del registro en una cinta; el registro completo, en el botón «Registro»
|
|
8
|
+
// En tiempo real: los pasos llegan por SSE (/api/events, temas team.step y team.ledger que publican lib/runtime.syn y
|
|
9
|
+
// lib/teams.syn) en el momento en que pasan. El sondeo de siempre (refresh cada 2,5 s y la traza) queda de respaldo.
|
|
10
|
+
// Se arma una vez por objetivo y después solo se tocan las partes que cambiaron: rearmar cortaría las animaciones.
|
|
11
|
+
const LIVE = { key: null, o: null, flow: null, flowSig: '', members: [], seenLedger: 0, flown: new Set(), steps: {}, stepsAt: 0, rects: null,
|
|
12
|
+
act: {}, busy: {}, pend: {}, lastSpent: null, tok: 0, tokAnim: 0, view: {}, kanban: '', head: '', ticker: '', extra: [], flights: [],
|
|
13
|
+
sent: {}, es: null, esOk: false, watch: 0, reload: 0 };
|
|
14
|
+
const avatarOf = (s) => String(s || '?').normalize('NFD').replace(/\p{M}/gu, '').slice(0, 2);
|
|
15
|
+
const reduced = () => matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
16
|
+
|
|
17
|
+
// ---- íconos (trazo propio, animados por CSS en teams.css → .ico.<nombre>) ----
|
|
18
|
+
const svg = (cls, inner) => `<svg class="ico ${cls}" viewBox="0 0 24 24" aria-hidden="true">${inner}</svg>`;
|
|
19
|
+
const ICONS = {
|
|
20
|
+
think: svg('think', '<path d="M9.5 4.5A3 3 0 0 0 6.6 7 3 3 0 0 0 4.5 10a3 3 0 0 0 .9 4.6 3.2 3.2 0 0 0 4.1 4.9h.5v-15z"/><path d="M14.5 4.5A3 3 0 0 1 17.4 7a3 3 0 0 1 2.1 3 3 3 0 0 1-.9 4.6 3.2 3.2 0 0 1-4.1 4.9H14v-15z"/><circle class="sp s1" cx="7.4" cy="10.4" r="1.15"/><circle class="sp s2" cx="16.6" cy="9" r="1.15"/><circle class="sp s3" cx="8.4" cy="15" r="1.15"/><circle class="sp s4" cx="15.6" cy="14.6" r="1.15"/>'),
|
|
21
|
+
look: svg('look', '<g class="lens"><circle cx="10.5" cy="10.5" r="5.5"/><path d="M14.6 14.6 20 20"/></g>'),
|
|
22
|
+
write: svg('write', '<path class="ink" d="M3.5 20.5h9"/><g class="pen"><path d="M15.5 3.5l4.8 4.8L10 18.6l-5.4.6.6-5.4z"/><path d="M13.6 5.4l4.8 4.8"/></g>'),
|
|
23
|
+
run: svg('run', '<rect x="2.5" y="4.5" width="19" height="15" rx="2.5"/><path d="M6.5 9.5l3 2.5-3 2.5"/><rect class="cur" x="11.5" y="13.6" width="5" height="1.8" rx=".6"/>'),
|
|
24
|
+
git: svg('git', '<circle cx="6" cy="5.5" r="2.2"/><circle cx="6" cy="18.5" r="2.2"/><circle cx="18" cy="7.5" r="2.2"/><path d="M6 7.7v8.6"/><path d="M18 9.7c0 4.3-7.5 3.3-11.2 6.9"/><circle class="bit" r="1.4"><animateMotion dur="1.4s" repeatCount="indefinite" path="M18 9.7c0 4.3-7.5 3.3-11.2 6.9"/></circle>'),
|
|
25
|
+
send: svg('send', '<g class="env"><rect x="3" y="6" width="18" height="12.5" rx="2"/><path d="M3.5 7l8.5 6.2L20.5 7"/></g>'),
|
|
26
|
+
board: svg('board', '<rect x="2.5" y="4" width="19" height="16" rx="2.5"/><path d="M9 4v16M15 4v16"/><rect class="card" x="3.9" y="7" width="3.7" height="3" rx=".8"/>'),
|
|
27
|
+
flag: svg('flag', '<path d="M5.5 21V4"/><path class="cloth" d="M5.5 4.5h11.5l-2.4 3.7 2.4 3.8H5.5"/>'),
|
|
28
|
+
web: svg('web', '<circle cx="12" cy="12" r="8.5"/><ellipse class="mer" cx="12" cy="12" rx="3.6" ry="8.5"/><path d="M3.5 12h17"/>'),
|
|
29
|
+
gear: svg('gear', '<g class="cog"><circle cx="12" cy="12" r="3"/><path d="M12 2.8v3M12 18.2v3M2.8 12h3M18.2 12h3M5.5 5.5l2.1 2.1M16.4 16.4l2.1 2.1M5.5 18.5l2.1-2.1M16.4 7.6l2.1-2.1"/></g>'),
|
|
30
|
+
say: svg('say', '<path d="M4 5.5h16a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H10l-4.5 3.5v-3.5H4a1 1 0 0 1-1-1v-9a1 1 0 0 1 1-1z"/><circle class="dot d1" cx="8.5" cy="11" r="1"/><circle class="dot d2" cx="12" cy="11" r="1"/><circle class="dot d3" cx="15.5" cy="11" r="1"/>'),
|
|
31
|
+
done: svg('done', '<circle cx="12" cy="12" r="9"/><path class="tick" d="M7.8 12.3l2.8 2.8 5.6-6"/>'),
|
|
32
|
+
wait: svg('wait', '<circle cx="12" cy="12" r="8.5"/><path d="M12 7.5V12l3 2"/>'),
|
|
33
|
+
warn: svg('warn', '<path d="M12 3.5 21.5 20h-19z"/><path d="M12 10v4.5"/><circle class="dt" cx="12" cy="17.3" r=".9"/>'),
|
|
34
|
+
block: svg('block', '<circle cx="12" cy="12" r="8.5"/><path d="M6.2 6.2l11.6 11.6"/>'),
|
|
35
|
+
};
|
|
36
|
+
// el sobre que viaja por la línea (centrado en 0,0, para animateMotion)
|
|
37
|
+
const ENVELOPE = '<g class="envg"><rect x="-10" y="-7" width="20" height="14" rx="3"/><path d="M-8.5 -5l8.5 6 8.5-6"/></g>';
|
|
38
|
+
// qué ícono va con cada herramienta
|
|
39
|
+
function actOf(name, a = {}) {
|
|
40
|
+
if (['read', 'ls', 'find', 'grep', 'glob', 'lsp'].includes(name)) return 'look';
|
|
41
|
+
if (name === 'write' || name === 'edit') return 'write';
|
|
42
|
+
if (name === 'bash') return /\bgit\b/.test(a.command || '') ? 'git' : 'run';
|
|
43
|
+
if (name === 'send') return 'send';
|
|
44
|
+
if (name === 'board') return 'board';
|
|
45
|
+
if (name === 'objective') return 'flag';
|
|
46
|
+
if (name === 'fetch' || name === 'web' || name === 'search') return 'web';
|
|
47
|
+
return 'gear';
|
|
48
|
+
}
|
|
49
|
+
// el color de cada asiento, en el orden del equipo (el líder primero); la paleta está en teams.css (--s0…--s6)
|
|
50
|
+
const colorOf = (a) => { const i = LIVE.members.findIndex((m) => m.agent === a); return `var(--s${(i < 0 ? 0 : i) % 7})`; };
|
|
51
|
+
|
|
52
|
+
// las últimas líneas de una traza (son recientes: la fecha sale de ahora, no del inicio de la sesión)
|
|
53
|
+
function parseTraceRecent(txt) {
|
|
54
|
+
const now = Date.now() / 1000, day0 = Math.floor(now / 86400) * 86400, out = [];
|
|
55
|
+
for (const line of String(txt || '').split('\n')) {
|
|
56
|
+
const m = line.match(/^(\d\d):(\d\d):(\d\d)\.(\d{3}) .{6}s {2}(\S+)\s+(.*)$/); if (!m) continue;
|
|
57
|
+
let at = day0 + +m[1] * 3600 + +m[2] * 60 + +m[3] + +m[4] / 1000;
|
|
58
|
+
if (at > now + 300) at -= 86400;
|
|
59
|
+
out.push({ at, kind: m[5], text: m[6] });
|
|
60
|
+
}
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
// el último paso de cada asiento según su traza: el arranque y el respaldo (lo de ahora llega por eventos)
|
|
64
|
+
async function liveSteps(o) {
|
|
65
|
+
if (LIVE.key === 'live:' + o.id && Date.now() - LIVE.stepsAt < (LIVE.esOk ? 10000 : 2400)) return LIVE.steps;
|
|
66
|
+
const res = {};
|
|
67
|
+
await Promise.all((o.seats || []).map(async (s) => {
|
|
68
|
+
if (!s.session) return;
|
|
69
|
+
const r = await api('trace?session=' + enc(s.session) + '&tail=120');
|
|
70
|
+
const items = stepsOf(parseTraceRecent(r.ok ? r.data.trace : '').filter((e) => e.at >= o.created_at - 2)).flatMap((t) => t.items);
|
|
71
|
+
res[s.agent] = { last: items[items.length - 1] || null };
|
|
72
|
+
}));
|
|
73
|
+
LIVE.steps = res; LIVE.stepsAt = Date.now();
|
|
74
|
+
return res;
|
|
75
|
+
}
|
|
76
|
+
// ¿trabaja ahora? Lo que dijeron los eventos manda por un rato; si no hay, lo que dice el sondeo
|
|
77
|
+
function busyOf(o, a) { const b = LIVE.busy[a]; return b && Date.now() - b.at < 90000 ? b.v : !!workingNow(o, a); }
|
|
78
|
+
// qué está haciendo un asiento: {cls, icon, html}
|
|
79
|
+
function seatView(o, s) {
|
|
80
|
+
const a = s.agent, mine = (o.tasks || []).filter((t) => t.owner === a);
|
|
81
|
+
if (busyOf(o, a)) {
|
|
82
|
+
const ev = LIVE.act[a], tr = (LIVE.steps[a] || {}).last;
|
|
83
|
+
if (ev && (!tr || ev.at >= tr.at - 1)) return { cls: 'busy', icon: ev.icon, html: ev.html };
|
|
84
|
+
if (tr) { const name = tr.raw ? tr.raw.split(' ')[0] : ''; return { cls: 'busy', icon: tr.cls.includes('say') ? 'say' : name ? actOf(name, salvageArgs(tr.raw.slice(name.length + 1))) : 'think', html: tr.html }; }
|
|
85
|
+
return { cls: 'busy', icon: 'think', html: 'pensando…' };
|
|
86
|
+
}
|
|
87
|
+
if (mine.length && mine.every((t) => t.status === 'done')) return { cls: 'done', icon: 'done', html: 'terminó lo suyo' };
|
|
88
|
+
if (mine.some((t) => t.status === 'blocked')) return { cls: 'blocked', icon: 'block', html: 'trabado: espera que se destrabe algo' };
|
|
89
|
+
if (mine.some((t) => t.status !== 'done')) return { cls: 'wait', icon: 'wait', html: 'esperando su próximo turno' };
|
|
90
|
+
return { cls: 'idle', icon: 'wait', html: s.lead ? 'coordinando' : 'sin tareas por ahora' };
|
|
91
|
+
}
|
|
92
|
+
// una línea del registro, como la contaría una persona
|
|
93
|
+
function tickerLine(r, roleOf) {
|
|
94
|
+
const who = `<b style="color:${colorOf(r.actor)}">${esc(roleOf(r.actor))}</b>`, x = r.text && r.text !== 'null' ? esc(short(String(r.text).replace(/\*\*|`/g, ''), 120)) : '';
|
|
95
|
+
if (r.kind === 'message') return `${who} → <b>${esc(roleOf(String(r.ref).replace('→', '').trim()))}</b>: «${x}»`;
|
|
96
|
+
if (r.kind === 'added') return `${who} creó ${esc(r.ref)} «${esc(short(String(r.text).split(' → ')[0], 80))}»`;
|
|
97
|
+
if (r.kind === 'claimed') return `${who} tomó ${esc(r.ref)}`;
|
|
98
|
+
if (r.kind === 'updated') return `${who} movió ${esc(r.ref)}${x ? ' · ' + x : ''}`;
|
|
99
|
+
if (r.kind === 'report') return `${who} informó: «${x}»`;
|
|
100
|
+
if (r.kind === 'over cap') return `${who} pasó su tope diario: ${esc(overText(r))}`;
|
|
101
|
+
if (r.kind === 'continued') return `${esc(roleOf(String(r.text).split(':')[0]))} llegó al límite de pasos de un turno: sigue donde quedó`;
|
|
102
|
+
if (r.kind === 'stuck') return `${esc(roleOf(String(r.text).split(':')[0]))} se cortó varias veces seguidas: le avisamos a su jefe`;
|
|
103
|
+
if (r.kind === 'tokens') return `le diste más tokens por hoy a ${esc(roleOf(String(r.text).split(':')[0]))}`;
|
|
104
|
+
if (r.kind === 'handed off') return `${who} le pasó el trabajo a <b>${esc(teamName(String(r.text).split(':')[0].trim()))}</b> (${esc(r.ref)})`;
|
|
105
|
+
return `${who} ${esc(KIND[r.kind] || r.kind)} ${esc(r.ref || '')}${x ? ': «' + x + '»' : ''}`;
|
|
106
|
+
}
|
|
107
|
+
function kanbanHtml(o, roleOf, seatsBusy) {
|
|
108
|
+
const cols = LANES.filter(([st]) => st !== 'blocked' || (o.tasks || []).some((t) => t.status === 'blocked'));
|
|
109
|
+
return cols.map(([st, label]) => {
|
|
110
|
+
const cs = (o.tasks || []).filter((t) => t.status === st);
|
|
111
|
+
return `<div class="kcol ${st}"><h6><span>${label}</span><span>${cs.length}</span></h6><div class="kcards">${cs.map((t) => {
|
|
112
|
+
const busy = t.owner && seatsBusy.has(t.owner) && (st === 'doing' || st === 'review');
|
|
113
|
+
return `<div class="kc${busy ? ' busy' : ''}" data-id="${t.id}" style="--seat:${colorOf(t.owner)}"><div class="kh"><span class="kid">#${t.id}</span>${busy ? '<span class="spin" aria-label="trabajando"></span>' : st === 'done' ? '<span class="ok">✓</span>' : ''}</div><p>${esc(short(t.title, 110))}</p>${t.owner ? `<div class="ko"><span class="av">${esc(avatarOf(roleOf(t.owner)))}</span>${esc(roleOf(t.owner))}</div>` : '<div class="ko none">sin dueño</div>'}</div>`;
|
|
114
|
+
}).join('') || '<p class="kempty">—</p>'}</div></div>`;
|
|
115
|
+
}).join('');
|
|
116
|
+
}
|
|
117
|
+
// FLIP: cada tarjeta recuerda dónde estaba y se desliza a su lugar nuevo; la nueva aparece; la que llega a hecho, salta
|
|
118
|
+
function flipKanban(box, html) {
|
|
119
|
+
const before = {}; box.querySelectorAll('.kc').forEach((c) => (before[c.dataset.id] = { r: c.getBoundingClientRect(), st: c.closest('.kcol').classList[1] }));
|
|
120
|
+
box.innerHTML = html;
|
|
121
|
+
if (reduced() || !LIVE.rects) { LIVE.rects = true; return; }
|
|
122
|
+
box.querySelectorAll('.kc').forEach((c) => {
|
|
123
|
+
const b = before[c.dataset.id], st = c.closest('.kcol').classList[1];
|
|
124
|
+
if (!b) { c.classList.add('appear'); return; }
|
|
125
|
+
const r = c.getBoundingClientRect(), dx = b.r.left - r.left, dy = b.r.top - r.top;
|
|
126
|
+
if (dx || dy) {
|
|
127
|
+
c.style.transform = `translate(${dx}px,${dy}px)`; c.style.transition = 'none'; c.classList.add('moving');
|
|
128
|
+
requestAnimationFrame(() => requestAnimationFrame(() => { c.style.transition = 'transform .7s cubic-bezier(.2,.8,.2,1)'; c.style.transform = ''; }));
|
|
129
|
+
setTimeout(() => c.classList.remove('moving'), 900);
|
|
130
|
+
if (b.st !== st && st === 'done') setTimeout(() => c.classList.add('pop'), 650);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
// una ficha «#N» vuela desde el asiento que movió la tarea hasta su tarjeta
|
|
135
|
+
function flyCards() {
|
|
136
|
+
const q = LIVE.flights.splice(0); if (!q.length || reduced()) return;
|
|
137
|
+
q.forEach(({ agent, id }, i) => {
|
|
138
|
+
const n = nodeEl(agent), c = document.querySelector(`#lvKanban .kc[data-id="${id}"]`); if (!n || !c) return;
|
|
139
|
+
const a = n.getBoundingClientRect(), b = c.getBoundingClientRect(); if (!a.width || !b.width) return;
|
|
140
|
+
const chip = document.createElement('div'); chip.className = 'lvfly'; chip.style.setProperty('--seat', colorOf(agent)); chip.textContent = '#' + id;
|
|
141
|
+
document.body.appendChild(chip);
|
|
142
|
+
const x0 = a.left + a.width / 2 - 16, y0 = a.top + a.height / 2 - 10, x1 = b.left + 10, y1 = b.top + 6, mx = (x0 + x1) / 2, my = Math.min(y0, y1) - 70;
|
|
143
|
+
const an = chip.animate([{ transform: `translate(${x0}px,${y0}px) scale(.5)`, opacity: 0 }, { transform: `translate(${mx}px,${my}px) scale(1.15)`, opacity: 1, offset: 0.45 }, { transform: `translate(${x1}px,${y1}px) scale(.9)`, opacity: 0.95 }],
|
|
144
|
+
{ duration: 950, delay: i * 160, easing: 'cubic-bezier(.3,.7,.25,1)', fill: 'forwards' });
|
|
145
|
+
an.onfinish = () => { chip.remove(); c.classList.remove('land'); void c.offsetWidth; c.classList.add('land'); };
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// ---- el equipo vivo: se toca solo lo que cambió ----
|
|
150
|
+
const nodeEl = (a) => document.querySelector(`#lvStage .fl-node[data-id="${CSS.escape(a)}"]`);
|
|
151
|
+
function hit(a, kind) {
|
|
152
|
+
const el = nodeEl(a); if (!el || reduced()) return;
|
|
153
|
+
el.classList.remove('hit-ok', 'hit-bad', 'hit-recv'); void el.offsetWidth; el.classList.add('hit-' + kind);
|
|
154
|
+
clearTimeout(el._hit); el._hit = setTimeout(() => el.classList.remove('hit-' + kind), 900);
|
|
155
|
+
}
|
|
156
|
+
// lo que dice un asiento, en un globo que se va solo
|
|
157
|
+
function bubble(a, html) {
|
|
158
|
+
const el = nodeEl(a); if (!el) return;
|
|
159
|
+
el.querySelectorAll('.lvbubble').forEach((b) => b.remove());
|
|
160
|
+
const b = document.createElement('div'); b.className = 'lvbubble'; b.innerHTML = html; el.appendChild(b); el.classList.add('talking');
|
|
161
|
+
setTimeout(() => b.classList.add('out'), 4200); setTimeout(() => { b.remove(); if (!el.querySelector('.lvbubble')) el.classList.remove('talking'); }, 4700);
|
|
162
|
+
}
|
|
163
|
+
function sendFly(from, to) {
|
|
164
|
+
if (!LIVE.flow || !nodeEl(from) || !nodeEl(to)) return;
|
|
165
|
+
LIVE.sent[from + '>' + to] = Date.now();
|
|
166
|
+
LIVE.flow.particle(from, to, { color: colorOf(from), glyph: ENVELOPE, dur: 1.5 });
|
|
167
|
+
setTimeout(() => hit(to, 'recv'), 1500);
|
|
168
|
+
}
|
|
169
|
+
// el trabajo sale a otro equipo: el sobre deja el lienzo por una puerta con su nombre, y un aviso lleva al objetivo
|
|
170
|
+
// nuevo en unos segundos (o enseguida, con «ver ahora»; «quedarme acá» o pasar el mouse por encima lo frena)
|
|
171
|
+
function handoffFly(o, r) {
|
|
172
|
+
const tid = String(r.text || '').split(':')[0].trim(), nid = +String(r.ref || '').replace('O-', ''); if (!tid || !nid) return;
|
|
173
|
+
const stage = $('#lvStage'), n = nodeEl(o.agent);
|
|
174
|
+
if (stage && n && !reduced()) {
|
|
175
|
+
const door = document.createElement('div'); door.className = 'lvdoor'; door.style.setProperty('--seat', colorOf(o.agent));
|
|
176
|
+
door.innerHTML = `${ICON_PASS}<span>${esc(teamName(tid))}</span>`; stage.appendChild(door);
|
|
177
|
+
const a = n.getBoundingClientRect(), b = door.getBoundingClientRect();
|
|
178
|
+
const env = document.createElement('div'); env.className = 'lvenv'; env.style.setProperty('--seat', colorOf(o.agent));
|
|
179
|
+
env.innerHTML = `<svg viewBox="-12 -9 24 18" aria-hidden="true">${ENVELOPE}</svg>`; document.body.appendChild(env);
|
|
180
|
+
const x0 = a.left + a.width / 2 - 14, y0 = a.top + a.height / 2 - 10, x1 = b.left + 10, y1 = b.top + b.height / 2 - 10, mx = (x0 + x1) / 2, my = Math.min(y0, y1) - 60;
|
|
181
|
+
const an = env.animate([{ transform: `translate(${x0}px,${y0}px) scale(.6)`, opacity: 0 }, { transform: `translate(${mx}px,${my}px) scale(1.2)`, opacity: 1, offset: 0.5 }, { transform: `translate(${x1}px,${y1}px) scale(.8)`, opacity: 0.2 }],
|
|
182
|
+
{ duration: 1400, easing: 'cubic-bezier(.3,.7,.25,1)', fill: 'forwards' });
|
|
183
|
+
an.onfinish = () => { env.remove(); door.classList.add('got'); };
|
|
184
|
+
setTimeout(() => door.remove(), 15000);
|
|
185
|
+
}
|
|
186
|
+
handoffToast(o.id, tid, nid);
|
|
187
|
+
}
|
|
188
|
+
function handoffToast(from, tid, nid) {
|
|
189
|
+
document.querySelectorAll('.lvhand').forEach((x) => x.remove());
|
|
190
|
+
const href = url.obj(tid, nid), t = document.createElement('div'); let left = 6;
|
|
191
|
+
t.className = 'lvhand'; t.setAttribute('role', 'status');
|
|
192
|
+
t.innerHTML = `${ICON_PASS}<div class="hb"><b>Pasado a ${esc(teamName(tid))}</b><span>Ahora es O-${nid}, un objetivo de ese equipo. <span class="cd">Te llevo en ${left} s.</span></span></div>
|
|
193
|
+
<a class="btn primary" href="${esc(href)}">ver ahora</a><button type="button" class="lnk" data-stay>quedarme acá</button>`;
|
|
194
|
+
document.body.appendChild(t);
|
|
195
|
+
const stop = () => { clearInterval(iv); const cd = t.querySelector('.cd'); if (cd) cd.textContent = ''; };
|
|
196
|
+
const iv = setInterval(() => {
|
|
197
|
+
left -= 1;
|
|
198
|
+
if (left > 0) { t.querySelector('.cd').textContent = `Te llevo en ${left} s.`; return; }
|
|
199
|
+
clearInterval(iv); t.remove();
|
|
200
|
+
if (state.route.obj === from) go(href); // solo si sigue mirando el objetivo de donde salió
|
|
201
|
+
}, 1000);
|
|
202
|
+
t.addEventListener('mouseenter', stop, { once: true });
|
|
203
|
+
t.querySelector('[data-stay]').onclick = () => { stop(); t.remove(); };
|
|
204
|
+
t.querySelector('a').onclick = (e) => { e.preventDefault(); e.stopPropagation(); stop(); t.remove(); go(href); };
|
|
205
|
+
}
|
|
206
|
+
function paintSeats(o) {
|
|
207
|
+
const seats = o.seats || [];
|
|
208
|
+
LIVE.members.forEach((m) => {
|
|
209
|
+
const el = nodeEl(m.agent); if (!el) return;
|
|
210
|
+
const s = seats.find((x) => x.agent === m.agent) || { agent: m.agent, role: m.role, lead: m.agent === o.agent };
|
|
211
|
+
const v = seatView(o, s), was = LIVE.view[m.agent] || {};
|
|
212
|
+
el.style.setProperty('--seat', colorOf(m.agent));
|
|
213
|
+
if (was.cls !== v.cls) ['busy', 'done', 'blocked', 'wait', 'idle'].forEach((c) => el.classList.toggle(c, c === v.cls));
|
|
214
|
+
const box = el.querySelector('.lvact');
|
|
215
|
+
if (box && was.icon !== v.icon) { const ic = box.querySelector('.ico'); if (ic) ic.outerHTML = ICONS[v.icon]; else box.insertAdjacentHTML('afterbegin', ICONS[v.icon]); }
|
|
216
|
+
if (box && was.html !== v.html) { const tx = box.querySelector('.tx'); tx.innerHTML = v.html; if (was.html !== undefined) { tx.classList.remove('enter'); void tx.offsetWidth; tx.classList.add('enter'); } }
|
|
217
|
+
const mine = (o.tasks || []).filter((t) => t.owner === m.agent), busy = v.cls === 'busy';
|
|
218
|
+
const th = mine.slice(0, 5).map((t) => `<span class="tchip ${t.status}" title="${esc(t.title)}">#${t.id}${t.status === 'done' ? ' ✓' : (t.status === 'doing' || t.status === 'review') && busy ? ' ⟳' : ''}</span>`).join('') + (mine.length > 5 ? `<span class="tchip">+${mine.length - 5}</span>` : '');
|
|
219
|
+
const tb = el.querySelector('.lvtasks'); if (tb && was.tasks !== th) tb.innerHTML = th;
|
|
220
|
+
const over = overCap(o, s), ob = el.querySelector('.lvover');
|
|
221
|
+
el.classList.toggle('over', over);
|
|
222
|
+
if (ob) { ob.hidden = !over; if (over) { ob.innerHTML = `${ICONS.warn}tope ${k(s.today)}/${k(s.cap)}`; ob.title = `Hoy lleva ${k(s.today)} tokens y su tope diario es ${k(s.cap)}: tocá para darle más`; ob.onpointerdown = (e) => e.stopPropagation(); ob.onclick = (e) => { e.stopPropagation(); capPop(ob, LIVE.o, [s]); }; } }
|
|
223
|
+
LIVE.view[m.agent] = { ...v, tasks: th };
|
|
224
|
+
});
|
|
225
|
+
// las líneas de quien trabaja corren despacio, del color de quien trabaja
|
|
226
|
+
const busyA = new Set(LIVE.members.filter((m) => (LIVE.view[m.agent] || {}).cls === 'busy').map((m) => m.agent));
|
|
227
|
+
document.querySelectorAll('#lvStage .fl-edge').forEach((g) => {
|
|
228
|
+
const [, from, to] = (g.dataset.k || '').match(/^[^:]+:(.*)>(.*)$/) || [];
|
|
229
|
+
const who = busyA.has(to) ? to : busyA.has(from) ? from : null;
|
|
230
|
+
g.classList.toggle('live', !!who); if (who) g.style.setProperty('--flow', colorOf(who));
|
|
231
|
+
});
|
|
232
|
+
}
|
|
233
|
+
// el contador de tokens sube de a poco: lo gastado + lo que van gastando los turnos en curso (llega en cada paso)
|
|
234
|
+
function tokTarget(o) {
|
|
235
|
+
if (LIVE.lastSpent !== o.spent) { Object.keys(LIVE.pend).forEach((a) => { if (LIVE.pend[a].ended) delete LIVE.pend[a]; }); LIVE.lastSpent = o.spent; }
|
|
236
|
+
return o.spent + Object.values(LIVE.pend).reduce((n, p) => n + p.cost, 0);
|
|
237
|
+
}
|
|
238
|
+
function tokTo(o) {
|
|
239
|
+
const el = $('#lvTok'), meter = $('#lvMeter'), target = tokTarget(o), from = LIVE.tok;
|
|
240
|
+
const show = (n) => { if (el) el.textContent = k(Math.round(n)); if (meter && o.budget_tokens) meter.style.width = Math.min(100, (100 * n) / o.budget_tokens) + '%'; };
|
|
241
|
+
cancelAnimationFrame(LIVE.tokAnim);
|
|
242
|
+
if (Math.round(from) === target || reduced() || !from) { LIVE.tok = target; show(target); return; }
|
|
243
|
+
if (el && target > from) { el.classList.remove('up'); void el.offsetWidth; el.classList.add('up'); }
|
|
244
|
+
const t0 = performance.now(), step = (t) => { const p = Math.min(1, (t - t0) / 700), n = from + (target - from) * (1 - Math.pow(1 - p, 3)); LIVE.tok = n; show(n); if (p < 1) LIVE.tokAnim = requestAnimationFrame(step); };
|
|
245
|
+
LIVE.tokAnim = requestAnimationFrame(step);
|
|
246
|
+
}
|
|
247
|
+
function paintHead(o) {
|
|
248
|
+
const busyN = LIVE.members.filter((m) => busyOf(o, m.agent)).length;
|
|
249
|
+
const rid = routineOf(o), rt = rid && state.routines.find((x) => x.id === rid);
|
|
250
|
+
const html = `<span class="ref">${esc(o.ref)}</span><span class="st ${o.status}">${STATUS[o.status] || o.status}</span>
|
|
251
|
+
<span class="crew">${busyN ? `<span class="pulse"></span>${busyN} trabajando` : 'nadie trabajando en este momento'}</span>
|
|
252
|
+
<span class="dmeta">${rt ? `⟳ <a data-nav href="${esc(url.routine(o.team, rid))}">${esc(rt.name)}</a> · ` : ''}${o.turns} ronda${o.turns === 1 ? '' : 's'} · <span id="lvTok" class="tok"></span>${o.budget_tokens ? ' de ' + k(o.budget_tokens) : ''} tokens</span>${passLinksHtml(o)}
|
|
253
|
+
${o.budget_tokens ? `<span class="meter ${o.spent > o.budget_tokens * 0.8 ? 'hot' : ''}"><i id="lvMeter"></i></span>` : ''}
|
|
254
|
+
${(() => { const ov = (o.seats || []).filter((s) => overCap(o, s)); return ov.length ? `<button type="button" class="lvwarn" data-capall title="Qué pasa y qué podés hacer">${ICONS.warn}${ov.map((s) => esc(s.role || s.agent)).join(', ')} ${ov.length === 1 ? 'pasó su' : 'pasaron su'} tope diario</button>` : ''; })()}
|
|
255
|
+
<span class="spacer"></span>${o.team ? '<button data-diag title="Qué está trabado y cómo destrabarlo">Revisar</button>' : ''}<button data-log>Registro</button>${o.status === 'paused' ? '<button data-resume>Seguir (más presupuesto)</button>' : ''}<button class="no" data-cancel>Cancelar</button>`;
|
|
256
|
+
if (LIVE.head !== html) { LIVE.head = html; $('#lvHead').innerHTML = html; bindObjButtons(o); const ca = $('#lvHead [data-capall]'); if (ca) ca.onclick = () => capPop(ca, LIVE.o, (LIVE.o.seats || []).filter((s) => overCap(LIVE.o, s))); const t = Math.round(LIVE.tok); if ($('#lvTok')) $('#lvTok').textContent = k(t); }
|
|
257
|
+
tokTo(o);
|
|
258
|
+
}
|
|
259
|
+
function paintTicker(o) {
|
|
260
|
+
const roleOf = (a) => ((o.seats || []).find((s) => s.agent === a) || {}).role || a;
|
|
261
|
+
const ids = new Set((o.ledger || []).map((r) => r.id));
|
|
262
|
+
LIVE.extra = LIVE.extra.filter((r) => !ids.has(r.id));
|
|
263
|
+
const rows = [...LIVE.extra, ...(o.ledger || [])].sort((a, b) => b.id - a.id).slice(0, 4);
|
|
264
|
+
const html = `<span class="lbl">lo último</span>${rows.map((r) => `<span class="ti" data-id="${r.id}"><span class="t">${hhmm(r.at)}</span>${tickerLine(r, roleOf)}</span>`).join('') || '<span class="ti">todavía nada</span>'}`;
|
|
265
|
+
if (LIVE.ticker === html) return;
|
|
266
|
+
const seen = new Set([...document.querySelectorAll('#lvTicker .ti[data-id]')].map((x) => x.dataset.id));
|
|
267
|
+
LIVE.ticker = html; $('#lvTicker').innerHTML = html;
|
|
268
|
+
if (seen.size) document.querySelectorAll('#lvTicker .ti[data-id]').forEach((x) => { if (!seen.has(x.dataset.id)) x.classList.add('new'); });
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// ---- los eventos en vivo (SSE) ----
|
|
272
|
+
const onLivePage = () => state.route.page === 'obj' && LIVE.o && state.liveKey === 'live:' + LIVE.o.id;
|
|
273
|
+
function liveConnect() {
|
|
274
|
+
if (LIVE.es || typeof EventSource === 'undefined') return;
|
|
275
|
+
try { LIVE.es = new EventSource(BASE + '/api/events'); } catch (e) { LIVE.es = null; return; }
|
|
276
|
+
LIVE.es.onopen = () => (LIVE.esOk = true);
|
|
277
|
+
LIVE.es.addEventListener('event', (e) => { let ev; try { ev = JSON.parse(e.data); } catch (x) { return; } if (ev.topic && ev.topic.startsWith('team.')) onLive(ev); });
|
|
278
|
+
LIVE.es.onerror = () => { liveDisconnect(); setTimeout(() => { if (onLivePage()) liveConnect(); }, 3000); };
|
|
279
|
+
clearInterval(LIVE.watch); LIVE.watch = setInterval(() => { if (!onLivePage()) liveDisconnect(); }, 4000);
|
|
280
|
+
}
|
|
281
|
+
function liveDisconnect() { if (LIVE.es) LIVE.es.close(); LIVE.es = null; LIVE.esOk = false; clearInterval(LIVE.watch); }
|
|
282
|
+
const soonReload = (ms = 120) => { clearTimeout(LIVE.reload); LIVE.reload = setTimeout(() => { if (onLivePage()) loadObj(); }, ms); };
|
|
283
|
+
function onLive(ev) {
|
|
284
|
+
if (!onLivePage()) { liveDisconnect(); return; }
|
|
285
|
+
const o = LIVE.o, d = ev.data || {}, scope = o.team ? 'team:' + o.team : 'objective:' + o.id;
|
|
286
|
+
if (d.scope !== scope || !LIVE.members.some((m) => m.agent === (d.agent || d.actor))) return;
|
|
287
|
+
if (ev.topic === 'team.step') onStep(d); else if (ev.topic === 'team.ledger') onLedger(o, d);
|
|
288
|
+
paintSeats(o); paintHead(o);
|
|
289
|
+
}
|
|
290
|
+
function onStep(d) {
|
|
291
|
+
const a = d.agent, x = d.data || {}, at = d.at || Date.now() / 1000;
|
|
292
|
+
const setAct = (icon, html) => (LIVE.act[a] = { icon, html, at });
|
|
293
|
+
if (d.kind === 'turn_start') { LIVE.busy[a] = { v: true, at: Date.now() }; setAct('think', 'arranca su turno…'); }
|
|
294
|
+
else if (d.kind === 'busy' && x.what === 'llm') setAct('think', 'pensando…');
|
|
295
|
+
else if (d.kind === 'tool_call') {
|
|
296
|
+
let args = {}; try { args = JSON.parse(x.args); } catch (e) { args = salvageArgs(x.args); }
|
|
297
|
+
setAct(actOf(x.name, args), sayCall(x.name, args));
|
|
298
|
+
if (x.name === 'send' && args.recipient) sendFly(a, args.recipient);
|
|
299
|
+
} else if (d.kind === 'tool_result') hit(a, x.ok ? 'ok' : 'bad');
|
|
300
|
+
else if (d.kind === 'tool_denied') { hit(a, 'bad'); setAct('block', 'no se le permitió: ' + esc(short(x.reason, 90))); }
|
|
301
|
+
else if (d.kind === 'assistant') { if (String(x.text || '').trim()) bubble(a, mdInline(short(x.text, 220))); }
|
|
302
|
+
else if (d.kind === 'usage') { const p = LIVE.pend[a] || (LIVE.pend[a] = { cost: 0, ended: false }); p.cost += x.cost || 0; p.ended = false; }
|
|
303
|
+
else if (d.kind === 'turn_end') { LIVE.busy[a] = { v: false, at: Date.now() }; delete LIVE.act[a]; if (LIVE.pend[a]) LIVE.pend[a].ended = true; soonReload(400); }
|
|
304
|
+
}
|
|
305
|
+
function onLedger(o, r) {
|
|
306
|
+
LIVE.extra.unshift(r); LIVE.extra = LIVE.extra.slice(0, 8); LIVE.flown.add(r.id);
|
|
307
|
+
if (r.kind === 'message') {
|
|
308
|
+
const to = String(r.ref).replace('→', '').trim();
|
|
309
|
+
if (Date.now() - (LIVE.sent[r.actor + '>' + to] || 0) > 15000) sendFly(r.actor, to);
|
|
310
|
+
} else if (r.kind === 'handed off') { handoffFly(o, r); soonReload(150);
|
|
311
|
+
} else if (['added', 'claimed', 'updated'].includes(r.kind)) {
|
|
312
|
+
const id = +String(r.ref || '').replace('#', ''); if (id) LIVE.flights.push({ agent: r.actor, id });
|
|
313
|
+
soonReload(80);
|
|
314
|
+
} else soonReload(150);
|
|
315
|
+
paintTicker(o);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
async function renderLive(o) {
|
|
319
|
+
const key = 'live:' + o.id, el = $('#objDetail');
|
|
320
|
+
const team = o.team ? teamOf(o.team) : null;
|
|
321
|
+
const roleOf = (a) => ((o.seats || []).find((s) => s.agent === a) || {}).role || a;
|
|
322
|
+
// el esqueleto, una vez por objetivo
|
|
323
|
+
if (state.liveKey !== key) {
|
|
324
|
+
state.liveKey = key; LIVE.key = null; LIVE.rects = null; LIVE.flowSig = ''; LIVE.view = {}; LIVE.kanban = ''; LIVE.head = ''; LIVE.ticker = '';
|
|
325
|
+
LIVE.act = {}; LIVE.busy = {}; LIVE.pend = {}; LIVE.extra = []; LIVE.flights = []; LIVE.tok = 0; LIVE.lastSpent = null; LIVE.flown = new Set();
|
|
326
|
+
LIVE.seenLedger = Math.max(0, ...(o.ledger || []).map((r) => r.id));
|
|
327
|
+
el.classList.add('lvmode');
|
|
328
|
+
el.innerHTML = `<div class="lvhead" id="lvHead"></div><div class="lvask" id="lvAsk"></div><div class="lvdiag" id="lvDiag" hidden></div>
|
|
329
|
+
<div class="lvgrid"><section class="lvstage"><div class="lvlabel">El equipo, ahora</div><div id="lvStage"></div></section>
|
|
330
|
+
<section class="lvboard"><div class="lvlabel">Tablero <span class="live2">● en vivo</span></div><div class="kanban" id="lvKanban"></div></section></div>
|
|
331
|
+
<div class="lvticker" id="lvTicker"></div>`;
|
|
332
|
+
LIVE.flow = Flow.create($('#lvStage'));
|
|
333
|
+
}
|
|
334
|
+
LIVE.o = o;
|
|
335
|
+
liveConnect();
|
|
336
|
+
await liveSteps(o);
|
|
337
|
+
if (state.route.obj !== o.id || state.liveKey !== key) return;
|
|
338
|
+
LIVE.key = key; LIVE.o = o;
|
|
339
|
+
const seats = o.seats || [];
|
|
340
|
+
const members = team ? team.members : seats.map((s) => ({ agent: s.agent, role: s.role, reports_to: '' }));
|
|
341
|
+
LIVE.members = [...members].sort((a, b) => (b.agent === o.agent) - (a.agent === o.agent));
|
|
342
|
+
$('#lvAsk').innerHTML = `<p class="${state.askOpen ? '' : 'clamp'}"><b>Qué se pidió:</b> ${esc(unescapeU(o.text))}</p>${o.text.length > 160 ? `<button class="lnk" data-ask>${state.askOpen ? 'ver menos' : 'ver todo'}</button>` : ''}
|
|
343
|
+
${o.status === 'waiting' ? `<div class="box q"><h5>${o.pass_pending ? 'quiere pasarle el trabajo a otro equipo' : o.question_kind === 'approval' ? 'te pide aprobación' : 'te pregunta'}</h5><p>${questionHtml(o)}</p><p class="ds">Respondé arriba, en la franja de lo que te espera.</p></div>` : ''}`;
|
|
344
|
+
// el equipo se dibuja solo si cambió quién está o cómo se une; lo demás se pinta encima
|
|
345
|
+
const edges = members.filter((m) => m.reports_to && members.some((x) => x.agent === m.reports_to)).map((m) => ({ kind: 'reports', from: m.reports_to, to: m.agent }))
|
|
346
|
+
.concat(((team && team.talks) || []).map(([x, y]) => ({ kind: 'talk', from: x, to: y })));
|
|
347
|
+
const sig = members.map((m) => m.agent + '/' + (m.role || '')).join(',') + '|' + edges.map((e) => e.kind + e.from + e.to).join(',') + '|' + o.agent;
|
|
348
|
+
if (LIVE.flowSig !== sig) {
|
|
349
|
+
LIVE.flowSig = sig; LIVE.view = {};
|
|
350
|
+
const nodes = members.map((m) => ({ id: m.agent, title: m.role || m.agent, avatar: avatarOf(m.role || m.agent), lead: m.agent === o.agent, cls: 'lv', html: '<button type="button" class="lvover" hidden></button><div class="lvact"><span class="tx"></span></div><div class="lvtasks"></div>' }));
|
|
351
|
+
LIVE.flow.render({ nodes, edges, editable: false, storeKey: 'lampson.flow:' + BASE + ':' + (o.team || 'solo-' + o.agent), onSelect: (a) => { if (a) openDrawer('seat', a); } });
|
|
352
|
+
}
|
|
353
|
+
paintSeats(o);
|
|
354
|
+
paintHead(o);
|
|
355
|
+
// respaldo sin eventos: los mensajes nuevos que trae el sondeo (y que no llegaron en vivo) igual viajan
|
|
356
|
+
const fresh = (o.ledger || []).filter((r) => r.id > LIVE.seenLedger && !LIVE.flown.has(r.id)).sort((a, b) => a.id - b.id);
|
|
357
|
+
fresh.filter((r) => r.kind === 'message').forEach((r, i) => setTimeout(() => sendFly(r.actor, String(r.ref).replace('→', '').trim()), i * 350));
|
|
358
|
+
fresh.filter((r) => r.kind === 'handed off').forEach((r) => { LIVE.flown.add(r.id); handoffFly(o, r); });
|
|
359
|
+
LIVE.seenLedger = Math.max(LIVE.seenLedger, ...(o.ledger || []).map((r) => r.id));
|
|
360
|
+
// el tablero, solo si cambió (rehacerlo en cada pulso reinicia las ruedas)
|
|
361
|
+
const busy = new Set(LIVE.members.filter((m) => busyOf(o, m.agent)).map((m) => m.agent)), kh = kanbanHtml(o, roleOf, busy);
|
|
362
|
+
if (LIVE.kanban !== kh) { LIVE.kanban = kh; flipKanban($('#lvKanban'), kh); }
|
|
363
|
+
flyCards();
|
|
364
|
+
paintTicker(o);
|
|
365
|
+
diagBanner(o);
|
|
366
|
+
if (state.drawer) renderDrawer(o);
|
|
367
|
+
}
|
|
368
|
+
// los botones del objetivo (en vivo y en el informe)
|
|
369
|
+
function bindObjButtons(o) {
|
|
370
|
+
const c = $('#objDetail [data-cancel]');
|
|
371
|
+
if (c) c.onclick = async () => { if (c.dataset.sure) { await api(`objectives/${o.id}/cancel`, {}); refresh(); } else { c.dataset.sure = '1'; c.textContent = '¿seguro? cancelar'; } };
|
|
372
|
+
const rs = $('#objDetail [data-resume]'); if (rs) rs.onclick = () => reply(o.id, 'Seguí: te doy más presupuesto.', false);
|
|
373
|
+
const ak = $('#objDetail [data-ask]'); if (ak) ak.onclick = () => { state.askOpen = !state.askOpen; loadObj(); };
|
|
374
|
+
const lg = $('#objDetail [data-log]'); if (lg) lg.onclick = () => openDrawer('log');
|
|
375
|
+
const dg = $('#objDetail [data-diag]'); if (dg) dg.onclick = () => openDrawer('diag');
|
|
376
|
+
state.objNow = o;
|
|
377
|
+
}
|
|
378
|
+
// el panel de la derecha: el registro completo, o los pasos de un asiento
|
|
379
|
+
function openDrawer(kind, agent) { state.drawer = state.drawer && state.drawer.kind === kind && state.drawer.agent === agent ? null : { kind, agent }; if (kind === 'diag') DIAG.drawn = null; if (state.objNow) renderDrawer(state.objNow); }
|
|
380
|
+
async function renderDrawer(o) {
|
|
381
|
+
const d = $('#objDrawer'); d.hidden = !state.drawer; if (!state.drawer) return;
|
|
382
|
+
$('#odClose').onclick = () => { state.drawer = null; d.hidden = true; };
|
|
383
|
+
if (state.drawer.kind === 'log') { $('#odTitle').textContent = 'Registro de ' + o.ref; $('#objLog').hidden = false; $('#odSeat').hidden = true; logHtml(o.ledger || [], $('#objLog')); return; }
|
|
384
|
+
if (state.drawer.kind === 'diag') { $('#odTitle').textContent = 'Revisar qué pasa · ' + o.ref; $('#objLog').hidden = true; $('#odSeat').hidden = false; renderDiag(o); return; }
|
|
385
|
+
DIAG.drawn = null;
|
|
386
|
+
const a = state.drawer.agent, s = (o.seats || []).find((x) => x.agent === a);
|
|
387
|
+
$('#odTitle').textContent = 'Pasos de ' + ((s && s.role) || a); $('#objLog').hidden = true; $('#odSeat').hidden = false;
|
|
388
|
+
const seats = await loadSeatWork(o), w = seats.find((x) => x.agent === a);
|
|
389
|
+
const box = $('#odSeat'), atBottom = box.scrollHeight - box.scrollTop - box.clientHeight < 40;
|
|
390
|
+
box.innerHTML = w ? seatTimelineHtml(w.turns, a) : '<p class="ihint">Sin pasos todavía.</p>';
|
|
391
|
+
box.querySelectorAll('details[data-k]').forEach((x) => (x.ontoggle = () => { if (x.open) state.openRaw.add(x.dataset.k); else state.openRaw.delete(x.dataset.k); }));
|
|
392
|
+
if (atBottom) box.scrollTop = box.scrollHeight; // mientras trabaja, la línea de tiempo crece y se sigue sola
|
|
393
|
+
}
|
package/public/js/panel.js
CHANGED
|
@@ -27,7 +27,8 @@ const Panel = (() => {
|
|
|
27
27
|
}
|
|
28
28
|
const box = () => ensure().querySelector('.panel');
|
|
29
29
|
function head(spec) {
|
|
30
|
-
|
|
30
|
+
// {href} = un enlace de texto (a otra pantalla o a la guía), no un botón cuadrado
|
|
31
|
+
const acts = (spec.headActions || []).map((a, i) => a.href ? `<a class="plink" href="${esc(a.href)}"${a.external ? ' target="_blank" rel="noopener"' : ''} title="${esc(a.title || '')}">${esc(a.label)}</a>` : `<button class="pghost" data-ha="${i}" title="${esc(a.title || '')}">${esc(a.label)}</button>`).join('');
|
|
31
32
|
return `<div class="phead"><span class="eyebrow">${esc(spec.eyebrow || '')}</span><h3>${esc(spec.title || '')}</h3><span class="sub">${esc(spec.sub || '')}</span><span class="spacer"></span>${acts}${spec.noClose ? '' : `<button class="pghost" data-close title="cerrar (Esc)">${ICON_X}</button>`}</div>`;
|
|
32
33
|
}
|
|
33
34
|
function open(spec) {
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// plugins-home.js — el escaparate de plugins (public/plugins-home.html, servido por el hub en /plugins).
|
|
2
|
+
// Lee GET /api/plugins-home: los de la instalación (valen para todos los proyectos), los de cada proyecto y cuáles
|
|
3
|
+
// tiene encendidos cada uno. Acá no se enciende nada: «usar en un proyecto» lleva al panel de plugins de ese
|
|
4
|
+
// proyecto (/w/<slug>#plugins=<nombre>), donde se revisa qué puede hacer y se decide.
|
|
5
|
+
const $ = (s) => document.querySelector(s);
|
|
6
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
7
|
+
let data = null, picking = null;
|
|
8
|
+
|
|
9
|
+
function setTheme(t) { document.documentElement.setAttribute('data-theme', t); try { localStorage.setItem('lampson.theme', t); } catch (e) {} $('#theme').textContent = t === 'dark' ? '☀' : '☾'; }
|
|
10
|
+
setTheme(document.documentElement.getAttribute('data-theme') || 'dark');
|
|
11
|
+
$('#theme').onclick = () => setTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark');
|
|
12
|
+
|
|
13
|
+
// lo que permite hacer cada plugin que viene con lampson, en palabras de quien lo usa (el manifiesto trae una
|
|
14
|
+
// descripción técnica en inglés: es la que se muestra para los demás)
|
|
15
|
+
const PITCH = {
|
|
16
|
+
telegram: 'Un bot de Telegram atendido por un agente. Gratis y sin intermediarios: creás el bot con @BotFather y le pasás el token.',
|
|
17
|
+
chatwoot: 'Tu bandeja de Chatwoot —WhatsApp, Instagram, Facebook, email, chat web— respondida por un agente.',
|
|
18
|
+
orders: 'Tomar pedidos por chat: catálogo, presupuestos con promos y envío, pedidos con cliente y dirección, y stock al día.',
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
function card(p, where) {
|
|
22
|
+
const on = data.workspaces.filter((w) => w.enabled.includes(p.name) && (p.scope === 'global' || w.slug === where.slug));
|
|
23
|
+
const tags = [p.channel ? 'canal' : '', p.tools.length ? `${p.tools.length} herramienta${p.tools.length === 1 ? '' : 's'}` : '', p.config.length ? 'necesita configurar' : '', p.scope === 'project' ? 'solo en ' + where.name : ''].filter(Boolean);
|
|
24
|
+
const key = p.scope + ':' + p.name + ':' + (where.slug || '');
|
|
25
|
+
const targets = p.scope === 'global' ? data.workspaces : data.workspaces.filter((w) => w.slug === where.slug);
|
|
26
|
+
return `<div class="pcard${on.length ? ' used' : ''}">
|
|
27
|
+
<p class="pn">${esc(p.name)}</p>
|
|
28
|
+
<p class="ptags">${tags.map((t) => `<span>${esc(t)}</span>`).join('')}</p>
|
|
29
|
+
<p class="pdesc">${esc(PITCH[p.name] || p.description || 'sin descripción')}</p>
|
|
30
|
+
${p.config.length ? `<p class="pcfg" title="van en el .env de lampson, con el prefijo LAMPSON_">pide: ${p.config.map((c) => `<code>${esc(c)}</code>`).join(' ')}</p>` : ''}
|
|
31
|
+
<p class="pwhere">${on.length ? 'encendido en ' + on.map((w) => `<a href="/w/${esc(w.slug)}#plugins=${encodeURIComponent(p.name)}">${esc(w.name)}</a>`).join(', ') : 'todavía no lo usás en ningún proyecto'}</p>
|
|
32
|
+
${picking === key
|
|
33
|
+
? `<div class="ppick"><span>¿en qué proyecto?</span>${targets.map((w) => `<a href="/w/${esc(w.slug)}#plugins=${encodeURIComponent(p.name)}">${esc(w.name)}${w.enabled.includes(p.name) ? ' ✓' : ''}</a>`).join('')}<span class="pcancel" data-cancel>cancelar</span></div>`
|
|
34
|
+
: `<button class="${on.length ? '' : 'primary'}" data-pick="${esc(key)}">${on.length ? 'usar en otro proyecto' : 'usar en un proyecto'} →</button>`}
|
|
35
|
+
</div>`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function render() {
|
|
39
|
+
if (!data) return;
|
|
40
|
+
const global = data.global.filter((p) => !p.example).sort((a, b) => a.name.localeCompare(b.name));
|
|
41
|
+
const local = data.workspaces.flatMap((w) => w.local.filter((p) => !p.example).map((p) => ({ p, w })));
|
|
42
|
+
$('#grid').innerHTML = (global.length || local.length)
|
|
43
|
+
? global.map((p) => card(p, {})).join('') + local.map(({ p, w }) => card(p, w)).join('')
|
|
44
|
+
: '<div class="vempty"><p><b>No hay plugins instalados.</b></p><p>Los que vienen con lampson viven en la carpeta <code>plugins/</code> de la instalación.</p></div>';
|
|
45
|
+
document.querySelectorAll('[data-pick]').forEach((b) => (b.onclick = () => { picking = b.dataset.pick; render(); }));
|
|
46
|
+
document.querySelectorAll('[data-cancel]').forEach((b) => (b.onclick = () => { picking = null; render(); }));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
async function refresh() {
|
|
50
|
+
try {
|
|
51
|
+
const r = await fetch('/api/plugins-home');
|
|
52
|
+
if (r.status === 401) { location.href = '/login'; return; }
|
|
53
|
+
data = await r.json();
|
|
54
|
+
render();
|
|
55
|
+
$('#live').classList.remove('off');
|
|
56
|
+
} catch (e) { $('#live').classList.add('off'); }
|
|
57
|
+
}
|
|
58
|
+
refresh();
|
|
59
|
+
setInterval(refresh, 15000);
|
package/public/js/plugins.js
CHANGED
|
@@ -3,11 +3,24 @@
|
|
|
3
3
|
let pluginsData = [], pluginsMeta = { global: 'plugins/', project: '.lampson/plugins/' };
|
|
4
4
|
async function fetchPlugins() {
|
|
5
5
|
let r; try { r = await (await fetch(BASE + '/api/plugins')).json(); } catch (e) { return pluginsData; }
|
|
6
|
-
pluginsData = r.plugins || []; pluginsMeta = { global: r.global || 'plugins/', project: r.project || '.lampson/plugins/' };
|
|
6
|
+
pluginsData = (r.plugins || []).filter(l => !l.example || l.enabled); pluginsMeta = { global: r.global || 'plugins/', project: r.project || '.lampson/plugins/' };
|
|
7
7
|
const on = pluginsData.filter(l => l.enabled).length;
|
|
8
8
|
const pill = $('#plugins'); pill.textContent = pluginsData.length ? `plugins ${on}/${pluginsData.length}` : 'plugins'; pill.classList.toggle('on', on > 0);
|
|
9
|
+
pill.title = pluginsData.length ? `${on} de ${pluginsData.length} plugins instalados encendidos en este proyecto · clic para ver qué hace cada uno y encender los que quieras` : 'plugins: tools propias que vos encendés · clic para ver y activar';
|
|
10
|
+
paintPlugHint();
|
|
9
11
|
return pluginsData;
|
|
10
12
|
}
|
|
13
|
+
// en la portada del proyecto: los plugins instalados que acá están apagados (sin los de ejemplo ni los rotos). Sin
|
|
14
|
+
// esto, quien no sabe que existen cree que el agente «no puede» mandar un Telegram o tomar un pedido. Encender
|
|
15
|
+
// sigue siendo decisión de la persona: la pista solo abre el panel.
|
|
16
|
+
function paintPlugHint() {
|
|
17
|
+
const el = $('#plugHint'); if (!el) return;
|
|
18
|
+
const off = pluginsData.filter(l => !l.enabled && !l.error);
|
|
19
|
+
el.hidden = !off.length; if (!off.length) return;
|
|
20
|
+
const names = off.slice(0, 3).map(l => `<b>${esc(l.name)}</b>`).join(', ') + (off.length > 3 ? ` y ${off.length - 3} más` : '');
|
|
21
|
+
el.innerHTML = `⧉ ${off.length === 1 ? 'Hay un plugin instalado que este proyecto no tiene encendido' : `Hay ${off.length} plugins instalados que este proyecto no tiene encendidos`}: ${names}. <span class="try">ver qué hacen →</span>`;
|
|
22
|
+
el.querySelector('.try').onclick = () => openPlugins(off[0].name);
|
|
23
|
+
}
|
|
11
24
|
async function loadPlugins() { await fetchPlugins(); if (Panel.is('plugins')) Panel.refresh(); }
|
|
12
25
|
function pluginMatches(l, q) {
|
|
13
26
|
if (!q) return true;
|
|
@@ -36,25 +49,32 @@ function pluginArgs(tdiv, props, required) {
|
|
|
36
49
|
}
|
|
37
50
|
return { args };
|
|
38
51
|
}
|
|
52
|
+
// la ayuda del «?» es corta y lleva a la acción (un pedido listo para el chat); lo largo vive en la guía del sitio
|
|
53
|
+
const PLUGINS_DOCS = 'https://lampson.org/es/docs/plugins';
|
|
54
|
+
const PLUGIN_PROMPT = 'Hacé un plugin para este proyecto que liste los endpoints del backend: método, path y handler. Validalo y pedime que lo encienda.';
|
|
39
55
|
const PLUGINS_HELP = `<h4>Herramientas hechas a medida para este proyecto</h4>
|
|
40
|
-
<p>Un plugin es una tool que el agente
|
|
41
|
-
<
|
|
42
|
-
<p><b>Encendido = existe
|
|
43
|
-
<p><b>
|
|
44
|
-
<
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
56
|
+
<p>Un plugin es una tool nueva que el agente ve en su catálogo, con parámetros tipados: una carpeta con <code>plugin.json</code> y el código, en Synsema (con un techo de capacidades que no puede superar) o en cualquier lenguaje. Queda en el repo para la próxima sesión y lo podés correr vos desde acá.</p>
|
|
57
|
+
<div class="pprompt"><b>Pedíselo al agente</b><p>${esc(PLUGIN_PROMPT)}</p><div class="pacts"><button class="primary" data-use>Escribirlo en el chat</button><button data-copy>Copiar</button><span class="ds" data-copied></span></div></div>
|
|
58
|
+
<p><b>Encendido = existe.</b> Apagado, el agente ni lo ve; encendido, sus tools entran al catálogo como <code>plugin_<plugin>_<tool></code> desde el próximo turno. Los de este proyecto viven en <code data-project></code>; los globales, en <code data-global></code>, y valen para todos los proyectos.</p>
|
|
59
|
+
<p><b>Otras ideas:</b> <code>check_i18n()</code> con las claves que faltan por idioma, <code>db_schema()</code> y <code>query(sql)</code> contra tu SQLite de desarrollo, <code>new_component(name)</code> con tu plantilla exacta, <code>deploy_status()</code> contra tu API.</p>
|
|
60
|
+
<p class="plinks"><a href="${PLUGINS_DOCS}" target="_blank" rel="noopener">Guía completa de plugins</a><span data-all-wrap> · <a data-all>Todos los plugins instalados</a></span> · <a href="https://lamps.sh" target="_blank" rel="noopener">lamps.sh</a>, para herramientas compartidas entre agentes</p>
|
|
61
|
+
<p><button data-back>← volver a los plugins</button></p>`;
|
|
62
|
+
// el «?» abre la ayuda y engancha sus botones (rutas reales, pedido al chat, enlace al hub)
|
|
63
|
+
function wirePluginsHelp(b) {
|
|
64
|
+
Panel.help(true);
|
|
65
|
+
const h = b.querySelector('.phelp');
|
|
66
|
+
h.querySelector('[data-project]').textContent = shortPath(pluginsMeta.project); h.querySelector('[data-global]').textContent = shortPath(pluginsMeta.global);
|
|
67
|
+
h.querySelector('[data-back]').onclick = () => Panel.help(false);
|
|
68
|
+
h.querySelector('[data-use]').onclick = () => { Panel.close(); const ta = $('#in'); if (!ta) return; ta.value = PLUGIN_PROMPT; ta.dispatchEvent(new Event('input')); ta.focus(); };
|
|
69
|
+
h.querySelector('[data-copy]').onclick = async () => { const ok = h.querySelector('[data-copied]'); try { await navigator.clipboard.writeText(PLUGIN_PROMPT); ok.textContent = 'copiado'; } catch (e) { ok.textContent = 'no se pudo copiar'; } };
|
|
70
|
+
if (BASE) h.querySelector('[data-all]').href = HUB_BASE + '/plugins'; else h.querySelector('[data-all-wrap]').remove();
|
|
71
|
+
}
|
|
53
72
|
function openPlugins(selectName) {
|
|
54
73
|
let first = selectName || null;
|
|
55
74
|
Panel.open({
|
|
56
75
|
id: 'plugins', eyebrow: 'plugins', title: 'Plugins', layout: 'browse',
|
|
57
|
-
|
|
76
|
+
// «todos los plugins» = la pantalla del hub (/plugins): qué hay instalado y en qué proyectos está encendido
|
|
77
|
+
headActions: [...(BASE ? [{ label: 'todos los plugins', href: HUB_BASE + '/plugins', title: 'los plugins de todos tus proyectos y dónde está encendido cada uno' }] : []), { label: '?', title: '¿qué es un plugin?', onClick: wirePluginsHelp }],
|
|
58
78
|
browse: {
|
|
59
79
|
placeholder: 'buscar plugin o tool…', listWidth: '260px', help: PLUGINS_HELP,
|
|
60
80
|
key: l => l.name,
|
|
@@ -62,7 +82,7 @@ function openPlugins(selectName) {
|
|
|
62
82
|
render: (l) => `<span class="dot">${l.error ? '!' : (l.enabled ? '●' : '○')}</span><div><div class="nm">${esc(l.name)}</div><div class="meta">${esc(l.scope)} · ${esc(l.kind)} · ${(l.tools || []).length} tool${(l.tools || []).length === 1 ? '' : 's'}${l.error ? ' · roto' : ''}${l.legacy ? ' · carpeta vieja' : ''}</div></div>`,
|
|
63
83
|
count: (rows, q) => q ? `${rows.length} de ${pluginsData.length}` : `${pluginsData.length} plugin${pluginsData.length === 1 ? '' : 's'}`,
|
|
64
84
|
emptyHtml: 'ninguno todavía',
|
|
65
|
-
emptyDetail: `Todavía no hay plugins.<br><br>Pedile uno al agente en el chat — <i>«hacé un plugin que liste los endpoints del backend»</i> — o creá una carpeta con <code>plugin.json</code> en <code>${esc(pluginsMeta.project)}</code> (proyecto) o <code>${esc(pluginsMeta.global)}</code> (global). El botón <b>?</b> de arriba explica qué son y para qué sirven.`,
|
|
85
|
+
emptyDetail: `Todavía no hay plugins.<br><br>Pedile uno al agente en el chat — <i>«hacé un plugin que liste los endpoints del backend»</i> — o creá una carpeta con <code>plugin.json</code> en <code>${esc(shortPath(pluginsMeta.project))}</code> (proyecto) o <code>${esc(shortPath(pluginsMeta.global))}</code> (global). El botón <b>?</b> de arriba explica qué son y para qué sirven.`,
|
|
66
86
|
detail: (l) => {
|
|
67
87
|
const specs = l.tool_specs || [];
|
|
68
88
|
const cap = l.error ? `<div class="dcap err">roto: ${esc(l.error)}</div>` : (l.kind === 'syn' ? `<div class="dcap">techo de capacidades: ${esc(l.caps)}</div>` : `<div class="dcap"><b>sin techo</b> (exec) · $ ${esc(l.command)}</div>`);
|
|
@@ -77,7 +97,7 @@ function openPlugins(selectName) {
|
|
|
77
97
|
+ (l.enabled ? `<div class="go"><button class="primary run">▶ correr</button><span class="st"></span></div><pre class="out" style="display:none"></pre>` : '')
|
|
78
98
|
+ `</div>`;
|
|
79
99
|
}).join('')
|
|
80
|
-
+ `<div class="dfoot"><span>${esc(l.dir
|
|
100
|
+
+ `<div class="dfoot"><span>${esc(shortPath(l.dir))}</span>${l.scope === 'project' ? '<span class="del">eliminar</span>' : '<span title="los globales se borran a mano">global · se borra a mano</span>'}</div><div class="err" data-err></div>`;
|
|
81
101
|
},
|
|
82
102
|
wire: (l, box) => {
|
|
83
103
|
const errEl = box.querySelector('[data-err]');
|
|
@@ -111,4 +131,6 @@ function openPlugins(selectName) {
|
|
|
111
131
|
});
|
|
112
132
|
}
|
|
113
133
|
$('#plugins').onclick = () => openPlugins();
|
|
114
|
-
|
|
134
|
+
// deep link: abre el panel al cargar; #plugins=<nombre> (desde /plugins del hub, «usar en este proyecto») con ese plugin elegido
|
|
135
|
+
if (location.hash === '#plugins' || location.hash === '#lamps') setTimeout(() => openPlugins(), 400);
|
|
136
|
+
else if (location.hash.startsWith('#plugins=')) setTimeout(() => openPlugins(decodeURIComponent(location.hash.slice(9))), 400);
|
package/public/js/schedules.js
CHANGED
|
@@ -116,3 +116,8 @@ function schedFormWire(box, err) {
|
|
|
116
116
|
};
|
|
117
117
|
}
|
|
118
118
|
$('#schedAddBtn').onclick = (ev) => { ev.stopPropagation(); openSched('__new'); };
|
|
119
|
+
// deep link desde /tareas del hub: #tareas (el panel), #tareas=<id> (esa tarea), #tareas=nueva (el formulario)
|
|
120
|
+
if (location.hash === '#tareas' || location.hash.startsWith('#tareas=')) {
|
|
121
|
+
const sel = decodeURIComponent(location.hash.slice(8));
|
|
122
|
+
setTimeout(() => openSched(sel === 'nueva' ? '__new' : sel || null), 400);
|
|
123
|
+
}
|