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
package/public/js/teams.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
|
-
// teams.js — la pantalla de equipos y
|
|
2
|
-
// agente de programación.
|
|
3
|
-
//
|
|
1
|
+
// teams.js — la pantalla de equipos, objetivos y rutinas de un proyecto (public/teams.html). Página propia: no depende
|
|
2
|
+
// de los módulos del agente de programación. Cada nivel tiene su URL (ver el comentario de teams.html) y «atrás» vuelve
|
|
3
|
+
// al anterior: el router lee location.pathname. Se actualiza sola (cada 2,5 s) desde la API privada del workspace:
|
|
4
|
+
// GET api/objectives · api/objectives/:id · api/teams · api/schedules (las rutinas son tareas con acción objective)
|
|
4
5
|
// POST api/objectives/add · api/objectives/:id/reply · api/objectives/:id/cancel · api/teams/save
|
|
6
|
+
// api/schedules/add · api/schedules/toggle · api/schedules/run · api/schedules/remove
|
|
5
7
|
// GET api/approvals + POST api/approve (las aprobaciones de la cola: p. ej. un merge a main desde la copia de un agente)
|
|
6
8
|
const $ = (s) => document.querySelector(s);
|
|
7
9
|
const BASE = (location.pathname.match(/^\/w\/[^/]+/) || [''])[0];
|
|
8
10
|
const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
|
9
11
|
const LANES = [['todo', 'por hacer'], ['doing', 'en curso'], ['review', 'en revisión'], ['done', 'hecho'], ['blocked', 'bloqueada']];
|
|
10
|
-
const STATUS = { active: '
|
|
11
|
-
const KIND = { added: 'agregó', claimed: 'tomó', updated: 'movió', message: 'escribió', report: 'informó', asked: 'preguntó', 'approval requested': 'pide aprobación', approved: 'aprobó', denied: 'denegó', answered: 'respondió', done: 'terminó', failed: 'falló', cancelled: 'canceló', paused: 'pausado', budget: 'presupuesto', objective: 'nuevo objetivo', error: 'error' };
|
|
12
|
-
|
|
12
|
+
const STATUS = { active: 'en curso', waiting: 'te espera', done: 'hecho', failed: 'falló', cancelled: 'cancelado', paused: 'sin presupuesto' };
|
|
13
|
+
const KIND = { added: 'agregó', claimed: 'tomó', updated: 'movió', message: 'escribió', report: 'informó', asked: 'preguntó', 'approval requested': 'pide aprobación', approved: 'aprobó', denied: 'denegó', answered: 'respondió', done: 'terminó', failed: 'falló', cancelled: 'canceló', paused: 'pausado', budget: 'presupuesto', 'over cap': 'pasó su tope diario', objective: 'nuevo objetivo', 'handed off': 'pasó el trabajo a', continued: 'sigue donde quedó', stuck: 'se trabó', tokens: 'tokens', error: 'error' };
|
|
13
14
|
const PRESETS = [['code', 'código (leer, editar, comandos)'], ['read', 'leer y correr comandos (no edita)'], ['none', 'ninguna (solo coordina)']];
|
|
14
|
-
const
|
|
15
|
+
const ROUTINE = 'rutina:'; // created_by de las ejecuciones de una rutina (lib/schedule.syn → run_routine)
|
|
16
|
+
const state = { approvals: [], teamsMeta: [], draft: null, sel: null, route: { page: 'list' }, team: null, objectives: [], agents: [], teams: [], routines: [], seen: new Set() };
|
|
15
17
|
|
|
16
18
|
async function api(path, body) {
|
|
17
19
|
const r = await fetch(BASE + '/api/' + path, body === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
|
@@ -20,25 +22,120 @@ async function api(path, body) {
|
|
|
20
22
|
if (r.status === 401) location.href = '/login';
|
|
21
23
|
return { ok: r.ok, status: r.status, data };
|
|
22
24
|
}
|
|
23
|
-
const ago = (t) => { const s = Math.max(0, Date.now() / 1000 - t); return s < 60 ? 'recién' : s < 3600 ? Math.floor(s / 60) + ' min' : s < 86400 ? Math.floor(s / 3600) + ' h' : Math.floor(s / 86400) + ' d'; };
|
|
25
|
+
const ago = (t) => { const s = Math.max(0, Date.now() / 1000 - t); return s < 60 ? 'recién' : s < 3600 ? 'hace ' + Math.floor(s / 60) + ' min' : s < 86400 ? 'hace ' + Math.floor(s / 3600) + ' h' : 'hace ' + Math.floor(s / 86400) + ' d'; };
|
|
24
26
|
const hhmm = (t) => new Date(t * 1000).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
25
27
|
const k = (n) => n >= 1000 ? (n / 1000).toFixed(n >= 100000 ? 0 : 1) + 'k' : String(n);
|
|
28
|
+
const proj = BASE ? BASE.slice(3).replace(/-[0-9a-f]{8}$/, '') : 'local';
|
|
29
|
+
const enc = encodeURIComponent;
|
|
30
|
+
|
|
31
|
+
// ---------- rutas: cada nivel con su URL; «atrás» del navegador vuelve al anterior ----------
|
|
32
|
+
const url = {
|
|
33
|
+
list: () => BASE + '/equipos', newTeam: () => BASE + '/equipos/nuevo',
|
|
34
|
+
team: (t) => BASE + '/equipos/' + enc(t), edit: (t) => BASE + '/equipos/' + enc(t) + '/editar',
|
|
35
|
+
obj: (t, n) => (t ? BASE + '/equipos/' + enc(t) + '/objetivos/' : BASE + '/objetivos/') + n,
|
|
36
|
+
newObj: (t) => BASE + '/equipos/' + enc(t) + '/objetivos/nuevo', newRoutine: (t) => BASE + '/equipos/' + enc(t) + '/rutinas/nueva',
|
|
37
|
+
routine: (t, id) => BASE + '/equipos/' + enc(t) + '/rutinas/' + enc(id),
|
|
38
|
+
};
|
|
39
|
+
function parseRoute() {
|
|
40
|
+
const seg = location.pathname.slice(BASE.length).split('/').filter(Boolean).map(decodeURIComponent);
|
|
41
|
+
if (seg[0] === 'objetivos' && seg[1]) return { page: 'obj', obj: +seg[1] };
|
|
42
|
+
if (!seg[1]) return { page: 'list' };
|
|
43
|
+
if (seg[1] === 'nuevo') return { page: 'newteam' };
|
|
44
|
+
const team = seg[1];
|
|
45
|
+
if (seg[2] === 'editar') return { page: 'edit', team };
|
|
46
|
+
if (seg[2] === 'objetivos' && seg[3] === 'nuevo') return { page: 'team', team, form: 'once' };
|
|
47
|
+
if (seg[2] === 'objetivos' && seg[3]) return { page: 'obj', team, obj: +seg[3] };
|
|
48
|
+
if (seg[2] === 'rutinas' && seg[3] === 'nueva') return { page: 'team', team, form: 'repeat' };
|
|
49
|
+
if (seg[2] === 'rutinas' && seg[3]) return { page: 'routine', team, routine: seg[3] };
|
|
50
|
+
return { page: 'team', team };
|
|
51
|
+
}
|
|
52
|
+
// las URLs de antes (?tab=…, ?o=…, ?new=1, ?edit=…, ?objetivo=…) llevan a las de ahora
|
|
53
|
+
function legacyRedirect() {
|
|
54
|
+
const q = new URLSearchParams(location.search); if (![...q.keys()].length) return;
|
|
55
|
+
let to = location.pathname;
|
|
56
|
+
if (q.get('new')) to = url.newTeam();
|
|
57
|
+
else if (q.get('edit')) to = url.edit(q.get('edit'));
|
|
58
|
+
else if (q.get('objetivo')) to = url.newObj(q.get('objetivo'));
|
|
59
|
+
else if (q.get('o')) to = url.obj('', +q.get('o'));
|
|
60
|
+
else if (q.get('tab')) to = url.list();
|
|
61
|
+
history.replaceState(null, '', to);
|
|
62
|
+
}
|
|
63
|
+
function go(href, replace) { history[replace ? 'replaceState' : 'pushState'](null, '', href); route(); }
|
|
64
|
+
window.addEventListener('popstate', route);
|
|
65
|
+
// los enlaces internos (data-nav) navegan sin recargar; con Ctrl/⌘ o rueda, en otra pestaña como siempre
|
|
66
|
+
document.addEventListener('click', (e) => {
|
|
67
|
+
const a = e.target.closest('a[data-nav]');
|
|
68
|
+
if (!a || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey) return;
|
|
69
|
+
e.preventDefault(); go(a.getAttribute('href'));
|
|
70
|
+
});
|
|
71
|
+
const teamOf = (id) => state.teams.find((t) => t.id === id);
|
|
72
|
+
const teamName = (id) => { const t = teamOf(id) || (state.teamsMeta || []).find((x) => x.id === id); return (t && t.name) || String(id).replace(/~.*$/, ''); };
|
|
26
73
|
|
|
27
|
-
//
|
|
28
|
-
|
|
29
|
-
|
|
74
|
+
// las migas: Proyectos › proyecto › Equipos › equipo › (O-n | rutina | editar | nuevo)
|
|
75
|
+
function renderCrumbs() {
|
|
76
|
+
const r = state.route, parts = [['/', 'Proyectos'], [BASE || '/', proj], [url.list(), 'Equipos']];
|
|
77
|
+
if (r.page === 'newteam') parts.push(['', 'Equipo nuevo']);
|
|
78
|
+
if (r.team) parts.push([url.team(r.team), teamName(r.team)]);
|
|
79
|
+
if (r.page === 'edit') parts.push(['', 'Editar']);
|
|
80
|
+
if (r.form) parts.push(['', r.form === 'repeat' ? 'Rutina nueva' : 'Objetivo nuevo']);
|
|
81
|
+
if (r.page === 'routine') { const rt = state.routines.find((x) => x.id === r.routine); parts.push(['', rt ? rt.name : 'Rutina']); }
|
|
82
|
+
if (r.page === 'obj') {
|
|
83
|
+
const o = state.objectives.find((x) => x.id === r.obj), rid = o && String(o.created_by || '').startsWith(ROUTINE) ? o.created_by.slice(ROUTINE.length) : '';
|
|
84
|
+
const rt = rid && state.routines.find((x) => x.id === rid);
|
|
85
|
+
if (rt && r.team) parts.push([url.routine(r.team, rid), rt.name]);
|
|
86
|
+
if (!r.team) parts.push(['', 'Un solo agente']);
|
|
87
|
+
parts.push(['', 'O-' + r.obj]);
|
|
88
|
+
}
|
|
89
|
+
$('#crumbs').innerHTML = parts.map(([h, t], i) => (i ? '<span class="sep">›</span>' : '') + (h && i < parts.length - 1 ? `<a href="${esc(h)}"${h.startsWith(BASE + '/') && BASE ? ' data-nav' : ''}>${esc(t)}</a>` : `<span class="here">${esc(t)}</span>`)).join('');
|
|
90
|
+
document.title = 'Lampson · ' + parts.slice(2).map((p) => p[1]).join(' › ');
|
|
91
|
+
}
|
|
30
92
|
function setTheme(t) { document.documentElement.setAttribute('data-theme', t); try { localStorage.setItem('lampson.theme', t); } catch (e) {} $('#theme').textContent = t === 'dark' ? '☀' : '☾'; }
|
|
31
93
|
setTheme(document.documentElement.getAttribute('data-theme') || 'dark');
|
|
32
94
|
$('#theme').onclick = () => setTheme(document.documentElement.getAttribute('data-theme') === 'dark' ? 'light' : 'dark');
|
|
33
|
-
function showTab(t) {
|
|
34
|
-
state.tab = t; try { localStorage.setItem('lampson.teams.tab', t); } catch (e) {}
|
|
35
|
-
document.querySelectorAll('#tabs button').forEach((b) => b.classList.toggle('on', b.dataset.tab === t));
|
|
36
|
-
$('#v-objectives').hidden = t !== 'objectives'; $('#v-teams').hidden = t !== 'teams';
|
|
37
|
-
refresh();
|
|
38
|
-
}
|
|
39
|
-
document.querySelectorAll('#tabs button').forEach((b) => (b.onclick = () => showTab(b.dataset.tab)));
|
|
40
95
|
|
|
41
96
|
// ---------- lo que espera a la persona ----------
|
|
97
|
+
// ---------- lo que te espera: preguntas, aprobaciones, pases a otro equipo y merges ----------
|
|
98
|
+
// Cada aviso dice quién (su rol y su equipo), qué quiere y, si es un merge, qué entra: la rama, sus commits, los
|
|
99
|
+
// archivos y si choca (lib/worktree.syn → preview), así se aprueba sabiendo qué y no leyendo el comando.
|
|
100
|
+
const ATTN_SVG = {
|
|
101
|
+
key: '<svg class="ico" viewBox="0 0 24 24" aria-hidden="true"><circle cx="8" cy="15" r="4.5"/><path d="M11.3 11.7 20 3M16.5 6.5l2.5 2.5M14 9l2 2"/></svg>',
|
|
102
|
+
arrow: '<svg class="arr" viewBox="0 0 24 12" aria-hidden="true"><path d="M1 6h20M16 1.5 21 6l-5 4.5"/></svg>',
|
|
103
|
+
};
|
|
104
|
+
function seatOf(a) {
|
|
105
|
+
for (const t of state.teams) { const m = t.members.find((x) => x.agent === a); if (m) return { role: m.role || a, team: t }; }
|
|
106
|
+
return { role: a, team: null };
|
|
107
|
+
}
|
|
108
|
+
// por qué pide permiso, en palabras
|
|
109
|
+
function whyText(why) {
|
|
110
|
+
const w = String(why || '').replace(/ · agent \S+$/, '');
|
|
111
|
+
let m;
|
|
112
|
+
if ((m = w.match(/dangerous pattern: (.+)$/))) return `Es un comando que puede borrar o cambiar cosas difíciles de recuperar (${m[1].trim()}).`;
|
|
113
|
+
if ((m = w.match(/asks before every (\S+) call/))) return `Este agente pide permiso antes de cada «${m[1]}».`;
|
|
114
|
+
if (/shared history/.test(w)) return 'Toca la historia compartida del proyecto: siempre lo aprobás vos.';
|
|
115
|
+
return w;
|
|
116
|
+
}
|
|
117
|
+
function mergeHtml(a) {
|
|
118
|
+
const p = a.preview;
|
|
119
|
+
if (!p) return `<pre class="av-cmd">${esc(a.message)}</pre>`;
|
|
120
|
+
if (p.missing) return `<p class="av-warn">La rama <code>${esc(p.branch)}</code> no existe: si lo aprobás, el comando va a fallar.</p><pre class="av-cmd">${esc(a.message)}</pre>`;
|
|
121
|
+
const add = p.files.reduce((n, f) => n + f.add, 0), del = p.files.reduce((n, f) => n + f.del, 0);
|
|
122
|
+
const badge = p.conflicts ? `<span class="av-badge bad">choca con ${esc(p.into)}</span>` : `<span class="av-badge ok">${p.ff ? 'avance directo' : 'sin conflictos'}</span>`;
|
|
123
|
+
const open = (state.attnOpen || new Set()).has(a.id);
|
|
124
|
+
return `<div class="av-merge">
|
|
125
|
+
<div class="av-flow"><code>${esc(p.branch)}</code>${ATTN_SVG.arrow}<code>${esc(p.into || 'remoto')}</code>${badge}</div>
|
|
126
|
+
${p.count ? `<p class="av-stat">${p.count} commit${p.count === 1 ? '' : 's'} · ${p.files.length} archivo${p.files.length === 1 ? '' : 's'} <span class="add">+${add}</span> <span class="del">−${del}</span></p>
|
|
127
|
+
<ul class="av-commits">${p.commits.slice(0, 4).map((c) => `<li><span class="sha">${esc(c.sha)}</span><span class="sj">${esc(c.subject)}</span><span class="by">${esc(String(c.author).split(" · ")[0])}</span></li>`).join('')}${p.count > 4 ? `<li class="more">y ${p.count - 4} más</li>` : ''}</ul>
|
|
128
|
+
<details class="av-files" data-k="${esc(a.id)}"${open ? ' open' : ''}><summary>ver archivos y comando</summary><ul>${p.files.map((f) => `<li><span class="fp">${esc(f.path)}</span><span class="add">+${f.add}</span><span class="del">−${f.del}</span></li>`).join('')}</ul><pre class="av-cmd">${esc(a.message)}</pre></details>` : `<p class="av-stat">No trae nada nuevo: ${esc(p.into)} ya tiene todo lo de esta rama.</p>`}
|
|
129
|
+
${p.conflicts ? '<p class="av-warn">Toca las mismas líneas que cambiaron en la rama principal: si lo aprobás, el merge se frena con conflictos y el agente tiene que resolverlos.</p>' : ''}
|
|
130
|
+
</div>`;
|
|
131
|
+
}
|
|
132
|
+
function avisoHtml(kind, { who, verb, meta, body, acts, id }) {
|
|
133
|
+
const icon = { ask: ICONS.say, ok: ATTN_SVG.key, pass: ICON_PASS, git: ICONS.git }[kind];
|
|
134
|
+
const fresh = !(state.attnSeen || (state.attnSeen = new Set())).has(id); state.attnSeen.add(id);
|
|
135
|
+
return `<article class="aviso k-${kind}${fresh ? ' fresh' : ''}"><span class="av-ico">${icon}</span><div class="av-body">
|
|
136
|
+
<header><span class="av-who"><b>${esc(who)}</b> ${verb}</span><span class="av-meta">${meta}</span></header>
|
|
137
|
+
${body}<div class="av-acts">${acts}</div></div></article>`;
|
|
138
|
+
}
|
|
42
139
|
function renderAttention() {
|
|
43
140
|
const waiting = state.objectives.filter((o) => o.status === 'waiting');
|
|
44
141
|
const pend = state.approvals.filter((a) => a.status === 'pending');
|
|
@@ -46,256 +143,892 @@ function renderAttention() {
|
|
|
46
143
|
box.hidden = waiting.length === 0 && pend.length === 0;
|
|
47
144
|
const keep = {};
|
|
48
145
|
box.querySelectorAll('input[data-id]').forEach((i) => (keep[i.dataset.id] = i.value));
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
146
|
+
const focused = document.activeElement && box.contains(document.activeElement) ? document.activeElement.dataset.id : null;
|
|
147
|
+
const metaOf = (team, ref, href, at) => `${team ? esc(team.name || team.id) + ' · ' : ''}${ref ? `<a data-nav href="${esc(href)}">${esc(ref)}</a> · ` : ''}${ago(at)}`;
|
|
148
|
+
const html = waiting.map((o) => {
|
|
149
|
+
const s = seatOf(o.agent), ap = o.question_kind === 'approval', meta = metaOf(s.team || teamOf(o.team), o.ref, url.obj(o.team, o.id), o.updated_at);
|
|
150
|
+
if (o.pass_pending) {
|
|
151
|
+
const m = String(o.question || '').match(/^hand over to team (\S+):\n?([\s\S]*)$/) || [];
|
|
152
|
+
return avisoHtml('pass', { id: 'o' + o.id, who: s.role, verb: `quiere pasarle el trabajo a <b>${esc(teamName(m[1] || ''))}</b>`, meta,
|
|
153
|
+
body: `<p class="av-lbl">Lo que le va a pedir:</p><blockquote class="av-q">${reportHtml(m[2] || '')}</blockquote>`,
|
|
154
|
+
acts: `<input data-id="${o.id}" placeholder="nota para ${esc(s.role)} (opcional)"><button class="ok" data-approve="${o.id}">Pasárselo</button><button class="no" data-deny="${o.id}">No pasarlo</button>` });
|
|
155
|
+
}
|
|
156
|
+
return avisoHtml(ap ? 'ok' : 'ask', { id: 'o' + o.id, who: s.role, verb: ap ? 'te pide aprobación' : 'te pregunta', meta,
|
|
157
|
+
body: `<div class="av-q">${reportHtml(o.question)}</div>`,
|
|
158
|
+
acts: ap ? `<input data-id="${o.id}" placeholder="nota (opcional)"><button class="ok" data-approve="${o.id}">Aprobar</button><button class="no" data-deny="${o.id}">Denegar</button>`
|
|
159
|
+
: `<input data-id="${o.id}" placeholder="tu respuesta"><button class="primary" data-answer="${o.id}">Responder</button>` });
|
|
56
160
|
}).join('') + pend.map((a) => {
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
161
|
+
const agent = (String(a.why || '').match(/agent (\S+)/) || [])[1], s = agent ? seatOf(agent) : { role: 'un agente', team: null };
|
|
162
|
+
const meta = metaOf(s.team, '', '', a.created), p = a.preview;
|
|
163
|
+
if (p) return avisoHtml('git', { id: a.id, who: s.role, verb: p.kind === 'push' ? `quiere subir <b>${esc(p.branch)}</b>` : `quiere llevar su trabajo a <b>${esc(p.into)}</b>`, meta,
|
|
164
|
+
body: mergeHtml(a), acts: `<button class="ok" data-qok="${esc(a.id)}">${p.kind === 'push' ? 'Aprobar push' : 'Aprobar merge'}</button><button class="no" data-qno="${esc(a.id)}">Denegar</button><span class="av-exp">vence ${esc(fmtWhen(a.expires_at))}</span>` });
|
|
165
|
+
return avisoHtml('ok', { id: a.id, who: s.role, verb: 'quiere correr un comando', meta,
|
|
166
|
+
body: `<pre class="av-cmd">${esc(a.message)}</pre><p class="av-why">${esc(whyText(a.why))}</p>`,
|
|
167
|
+
acts: `<button class="ok" data-qok="${esc(a.id)}">Aprobar</button><button class="no" data-qno="${esc(a.id)}">Denegar</button><span class="av-exp">vence ${esc(fmtWhen(a.expires_at))}</span>` });
|
|
60
168
|
}).join('');
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
169
|
+
// rehacerlo en cada pulso cortaría lo que estás escribiendo: solo si cambió
|
|
170
|
+
if (state.attnHtml === html) return;
|
|
171
|
+
state.attnHtml = html; box.innerHTML = html;
|
|
172
|
+
box.querySelectorAll('details[data-k]').forEach((d) => (d.ontoggle = () => { const s = state.attnOpen || (state.attnOpen = new Set()); if (d.open) s.add(d.dataset.k); else s.delete(d.dataset.k); }));
|
|
173
|
+
const act = (b, fn) => (b.onclick = async () => { b.closest('.aviso').classList.add('going'); b.closest('.av-acts').querySelectorAll('button').forEach((x) => (x.disabled = true)); await fn(); });
|
|
174
|
+
box.querySelectorAll('[data-qok]').forEach((b) => act(b, async () => { await api('approve', { id: b.dataset.qok, decision: true }); refresh(); }));
|
|
175
|
+
box.querySelectorAll('[data-qno]').forEach((b) => act(b, async () => { await api('approve', { id: b.dataset.qno, decision: false }); refresh(); }));
|
|
176
|
+
box.querySelectorAll('input[data-id]').forEach((i) => { if (keep[i.dataset.id]) i.value = keep[i.dataset.id]; if (focused === i.dataset.id) i.focus(); });
|
|
64
177
|
const note = (id) => (box.querySelector(`input[data-id="${id}"]`) || {}).value || '';
|
|
65
|
-
box.querySelectorAll('[data-
|
|
66
|
-
box.querySelectorAll('[data-
|
|
67
|
-
box.querySelectorAll('[data-
|
|
68
|
-
box.querySelectorAll('[data-
|
|
178
|
+
box.querySelectorAll('[data-approve]').forEach((b) => act(b, () => reply(+b.dataset.approve, note(b.dataset.approve), true)));
|
|
179
|
+
box.querySelectorAll('[data-deny]').forEach((b) => act(b, () => reply(+b.dataset.deny, note(b.dataset.deny), false)));
|
|
180
|
+
box.querySelectorAll('[data-answer]').forEach((b) => (b.onclick = () => { const t = note(b.dataset.answer); if (!t.trim()) { box.querySelector(`input[data-id="${b.dataset.answer}"]`).focus(); return; } b.closest('.aviso').classList.add('going'); reply(+b.dataset.answer, t, false); }));
|
|
181
|
+
box.querySelectorAll('input[data-id]').forEach((i) => (i.onkeydown = (e) => { if (e.key === 'Enter') { const b = i.parentElement.querySelector('[data-answer], [data-approve]'); if (b) b.click(); } }));
|
|
69
182
|
}
|
|
70
183
|
async function reply(id, text, approved) { await api(`objectives/${id}/reply`, { text, approved }); refresh(); }
|
|
71
184
|
|
|
72
|
-
// ---------- objetivos ----------
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
function
|
|
80
|
-
|
|
185
|
+
// ---------- tarjetas de objetivos y de rutinas ----------
|
|
186
|
+
const OPEN_OBJ = ['waiting', 'active', 'paused'];
|
|
187
|
+
function firstSentence(t, max = 140) {
|
|
188
|
+
const x = String(t || '').replace(/\s+/g, ' ').trim(), m = x.match(/^(.{20,}?[.:;!?])(\s|$)/), out = m ? m[1] : x;
|
|
189
|
+
return out.length > max ? out.slice(0, max - 3).replace(/\s+\S*$/, '') + '…' : out;
|
|
190
|
+
}
|
|
191
|
+
const routineOf = (o) => (String(o.created_by || '').startsWith(ROUTINE) ? o.created_by.slice(ROUTINE.length) : '');
|
|
192
|
+
function objCardHtml(o, opts = {}) {
|
|
193
|
+
const rid = routineOf(o), rt = rid && state.routines.find((x) => x.id === rid);
|
|
194
|
+
const now = o.status === 'waiting' ? `<p class="oq">«${esc(firstSentence(o.question, 160))}»</p>` : o.progress && o.status === 'active' ? `<p class="oprog">Ahora: ${esc(firstSentence(o.progress, 150))}</p>` : '';
|
|
195
|
+
return `<a class="ocard ${o.status}" data-nav href="${esc(url.obj(o.team, o.id))}">
|
|
196
|
+
<div class="oh"><span class="ref">${esc(o.ref)}</span><span class="st ${o.status}">${STATUS[o.status] || o.status}</span>${o.working ? '<span class="tw">● ahora</span>' : ''}${rt && !opts.inRoutine ? `<span class="from" title="una ejecución de esta rutina">⟳ ${esc(rt.name)}</span>` : ''}${String(o.created_by || '').startsWith('team:') ? `<span class="from" title="se lo pasó otro equipo">viene de ${esc(teamName(o.created_by.slice(5)))}</span>` : ''}</div>
|
|
197
|
+
<p class="otext">${esc(firstSentence(unescapeU(o.text)))}</p>${now}
|
|
198
|
+
<div class="ometa">${o.turns} ronda${o.turns === 1 ? '' : 's'} · ${k(o.spent)} tokens · ${ago(o.updated_at)}</div></a>`;
|
|
199
|
+
}
|
|
200
|
+
const MARK = { done: ['✓', 'hecho'], failed: ['✕', 'falló'], cancelled: ['–', 'cancelado'], active: ['●', 'trabajando'], waiting: ['⚑', 'te espera'], paused: ['‖', 'sin presupuesto'] };
|
|
201
|
+
const runsOf = (rid) => state.objectives.filter((o) => o.created_by === ROUTINE + rid);
|
|
202
|
+
function routineCardHtml(rt) {
|
|
203
|
+
const runs = runsOf(rt.id);
|
|
204
|
+
return `<a class="rcard${rt.enabled ? '' : ' off'}" data-nav href="${esc(url.routine(rt.action.team, rt.id))}">
|
|
205
|
+
<div class="oh"><span class="when">⟳ ${esc(rt.plan)}</span>${rt.enabled ? '' : '<span class="st paused">pausada</span>'}</div>
|
|
206
|
+
<p class="otext">${esc(firstSentence(rt.action.text))}</p>
|
|
207
|
+
<div class="ometa">${rt.enabled && rt.next_run ? 'próxima: ' + esc(fmtWhen(rt.next_run)) : rt.enabled ? 'sin próxima' : 'no va a correr hasta que la enciendas'}${runs.length ? ` · últimas: <span class="marks">${runs.slice(0, 6).map((o) => `<i class="${o.status}" title="${esc(o.ref)} · ${MARK[o.status][1]}">${MARK[o.status][0]}</i>`).join('')}</span>` : ''}</div></a>`;
|
|
208
|
+
}
|
|
209
|
+
function fmtWhen(ts) {
|
|
210
|
+
const d = new Date(ts * 1000), now = new Date(), hm = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
211
|
+
const day = (x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime(), diff = Math.round((day(d) - day(now)) / 86400000);
|
|
212
|
+
return diff === 0 ? 'hoy ' + hm : diff === 1 ? 'mañana ' + hm : diff === -1 ? 'ayer ' + hm : d.toLocaleDateString([], { weekday: 'short', day: 'numeric', month: 'short' }) + ' ' + hm;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---------- la página de un equipo: sus objetivos (en curso arriba, terminados plegados) y sus rutinas ----------
|
|
216
|
+
function teamPageHtml(t) {
|
|
217
|
+
const mine = state.objectives.filter((o) => o.team === t.id), open = mine.filter((o) => OPEN_OBJ.includes(o.status)).sort((a, b) => OPEN_OBJ.indexOf(a.status) - OPEN_OBJ.indexOf(b.status)), done = mine.filter((o) => !OPEN_OBJ.includes(o.status));
|
|
218
|
+
const lead = t.lead, roles = [...t.members].sort((a, b) => (b.agent === lead) - (a.agent === lead));
|
|
219
|
+
const rts = state.routines.filter((r) => r.action.team === t.id);
|
|
220
|
+
return `<div class="tphead"><div class="tpinfo"><h2>${esc(t.name || t.id)}</h2>${t.description ? `<p>${esc(t.description)}</p>` : ''}
|
|
221
|
+
<div class="roles">${roles.map((m) => `<span class="role${m.agent === lead ? ' lead' : ''}${m.working ? ' on' : ''}">${esc(m.role || m.agent)}</span>`).join('')}</div></div>
|
|
222
|
+
<div class="tpacts"><a class="btn" data-nav href="${esc(url.edit(t.id))}">Editar equipo</a><a class="btn primary" data-nav href="${esc(url.newObj(t.id))}">+ Nuevo objetivo</a></div></div>
|
|
223
|
+
<section class="osec"><h3>En curso</h3><div class="ogrid">${open.map((o) => objCardHtml(o)).join('') || `<p class="oempty">Nada en curso. <a data-nav href="${esc(url.newObj(t.id))}">Dale un objetivo</a> y el equipo se reparte el trabajo.</p>`}</div></section>
|
|
224
|
+
<section class="osec" id="rutinas"><h3>Rutinas <span class="hint2">objetivos que se repiten: cada vez que les toca, el equipo recibe uno nuevo</span></h3><div class="ogrid">${rts.map(routineCardHtml).join('')}
|
|
225
|
+
<a class="rnew" data-nav href="${esc(url.newRoutine(t.id))}"><span class="plus">+</span><b>Nueva rutina</b><span>«Todos los lunes a las 9, armá el resumen de la semana».</span></a></div></section>
|
|
226
|
+
${done.length ? `<details class="osec done"${state.doneOpen ? ' open' : ''}><summary><h3>Terminados <span class="n">${done.length}</span></h3></summary><div class="ogrid">${done.map((o) => objCardHtml(o)).join('')}</div></details>` : ''}`;
|
|
227
|
+
}
|
|
228
|
+
// ---------- la página de una rutina: cuándo, encendida o pausada, y sus ejecuciones ----------
|
|
229
|
+
function routinePageHtml(rt) {
|
|
230
|
+
const runs = runsOf(rt.id), t = rt.action.team;
|
|
231
|
+
return `<div class="tphead"><div class="tpinfo"><p class="rwhen">⟳ ${esc(rt.plan)}${rt.enabled && rt.next_run ? ' · próxima ' + esc(fmtWhen(rt.next_run)) : ''}</p><h2>${esc(rt.name)}</h2><p class="rtext">${esc(rt.action.text)}</p></div>
|
|
232
|
+
<div class="tpacts"><label class="sw2"><input type="checkbox" id="rtOn" ${rt.enabled ? 'checked' : ''}><span class="swt"></span><span>${rt.enabled ? 'encendida' : 'pausada'}</span></label><button id="rtRun">Correr ahora</button><button class="no" id="rtDel">Eliminar rutina</button></div></div>
|
|
233
|
+
<section class="osec"><h3>Ejecuciones <span class="n">${runs.length}</span></h3><div class="ogrid">${runs.map((o) => objCardHtml(o, { inRoutine: true })).join('') || `<p class="oempty">Todavía no corrió.${rt.enabled && rt.next_run ? ' La primera, ' + esc(fmtWhen(rt.next_run)) + '.' : ''} Cada ejecución es un objetivo para el equipo, con su propio resultado.</p>`}</div></section>
|
|
234
|
+
<p class="ferr" id="rtErr"></p>`;
|
|
235
|
+
}
|
|
236
|
+
function bindRoutinePage(rt) {
|
|
237
|
+
$('#rtOn').onchange = async (e) => { const r = await api('schedules/toggle', { id: rt.id, enabled: e.target.checked }); if (!r.ok) $('#rtErr').textContent = r.data.error || 'no se pudo'; await refreshRoutines(); render(); };
|
|
238
|
+
$('#rtRun').onclick = async () => { $('#rtRun').disabled = true; $('#rtRun').textContent = 'arrancando…'; await api('schedules/run', { id: rt.id }); setTimeout(refresh, 1500); };
|
|
239
|
+
const del = $('#rtDel');
|
|
240
|
+
del.onclick = async () => { if (!del.dataset.sure) { del.dataset.sure = '1'; del.textContent = '¿seguro? eliminar'; return; } await api('schedules/remove', { id: rt.id }); await refreshRoutines(); go(url.team(rt.action.team), true); };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
// ---------- objetivo o rutina nuevos (un formulario, «una vez» o «se repite») ----------
|
|
244
|
+
const DAYS = [['mon', 'lun'], ['tue', 'mar'], ['wed', 'mié'], ['thu', 'jue'], ['fri', 'vie'], ['sat', 'sáb'], ['sun', 'dom']];
|
|
245
|
+
function objFormHtml(t, mode) {
|
|
246
|
+
const f = state.form;
|
|
247
|
+
return `<div class="wcard oform"><h2>${mode === 'repeat' ? 'Rutina nueva' : 'Objetivo nuevo'} <span class="for">para ${esc(t.name || t.id)}</span></h2>
|
|
248
|
+
<div class="seg" role="tablist"><button type="button" data-mode="once" class="${mode === 'once' ? 'on' : ''}">Una vez</button><button type="button" data-mode="repeat" class="${mode === 'repeat' ? 'on' : ''}">Se repite</button></div>
|
|
249
|
+
<label class="big">¿Qué tiene que lograr?<span class="mwrap"><textarea id="nText" rows="6" placeholder="${mode === 'repeat' ? 'Revisá las ventas de la semana y armá un resumen corto con lo que cambió y qué conviene hacer.' : 'Agregá a la API filtrar las tareas por estado, con tests. Trabajá en tu rama y pedí aprobación antes de mezclar.'}">${esc(f.text)}</textarea><span class="mlist" id="nMention" role="listbox" hidden></span></span></label>
|
|
250
|
+
<div id="nPass">${passBoxHtml(t, f)}</div>
|
|
251
|
+
${mode === 'repeat' ? `<div class="whenbox"><label>Cuándo <select id="nFreq"><option value="daily" ${f.freq === 'daily' ? 'selected' : ''}>todos los días</option><option value="days" ${f.freq === 'days' ? 'selected' : ''}>ciertos días de la semana</option><option value="every" ${f.freq === 'every' ? 'selected' : ''}>cada tantas horas</option></select></label>
|
|
252
|
+
${f.freq === 'every' ? `<label>Cada <span class="unit"><input id="nEvery" type="number" min="1" max="168" value="${f.every}"> h</span></label>` : `<label>A las <input id="nAt" type="time" value="${esc(f.at)}"></label>`}
|
|
253
|
+
${f.freq === 'days' ? `<div class="days">${DAYS.map(([v, l]) => `<label class="chip"><input type="checkbox" data-day="${v}" ${f.days.includes(v) ? 'checked' : ''}>${l}</label>`).join('')}</div>` : ''}
|
|
254
|
+
<p class="ds">Cada vez que le toca, el equipo recibe un objetivo nuevo con este texto. Si el anterior sigue abierto, esa vez se saltea.</p></div>` : ''}
|
|
255
|
+
<details class="adv"><summary>Opciones</summary><div class="advgrid">
|
|
256
|
+
<div class="opt"><div class="oh"><label for="nBudget">Gasto máximo ${mode === 'repeat' ? 'por ejecución' : ''}</label>${help('El total de tokens que puede usar el equipo en este objetivo. Al llegar, se pausa y te avisa: podés darle más para que siga.')}</div><span class="unit"><input id="nBudget" type="number" min="0" step="50000" value="${f.budget}"> tokens</span></div>
|
|
257
|
+
</div></details>
|
|
258
|
+
<div class="wacts"><button type="button" id="nCancel">Cancelar</button><button type="button" class="primary" id="nGo">${mode === 'repeat' ? 'Crear rutina' : 'Empezar'}</button></div><p class="ferr" id="nErr"></p></div>`;
|
|
259
|
+
}
|
|
260
|
+
// ---------- pasarle el trabajo a otro equipo: «…y si encontrás algo, pasáselo a @desarrollo» ----------
|
|
261
|
+
// (lib/teams.syn → mentions: los mismos @id que reconoce el servidor)
|
|
262
|
+
function mentionsOf(txt, self) {
|
|
263
|
+
const ids = new Set(state.teams.map((x) => x.id)), out = [];
|
|
264
|
+
for (const m of String(txt || '').toLowerCase().matchAll(/@([a-z0-9][a-z0-9-]*)/g)) { const id = m[1].replace(/-+$/, ''); if (ids.has(id) && id !== self && !out.includes(id)) out.push(id); }
|
|
265
|
+
return out;
|
|
266
|
+
}
|
|
267
|
+
function passBoxHtml(t, f) {
|
|
268
|
+
const others = state.teams.filter((x) => x.id !== t.id);
|
|
269
|
+
if (!others.length) return '';
|
|
270
|
+
const to = mentionsOf(f.text, t.id);
|
|
271
|
+
if (!to.length) return `<p class="ds mhint">¿El resultado le sirve a otro equipo? Escribí <b>@</b> y su nombre (${others.slice(0, 3).map((x) => '@' + esc(x.id)).join(', ')}) y el líder se lo pasa, ya preparado para ese equipo.</p>`;
|
|
272
|
+
return `<div class="passbox">${ICON_PASS}<div><p>Si hace falta, ${esc(t.name || t.id)} se lo pasa a ${to.map((x) => `<b>${esc(teamName(x))}</b>`).join(' o ')}: les escribe un pedido para ese equipo, con lo que necesitan para hacerlo. Si no hay nada para ellos, solo te informa a vos.</p>
|
|
273
|
+
<label class="chk"><input type="checkbox" id="nPassAsk" ${f.passAsk ? 'checked' : ''}> Preguntarme antes de pasarlo</label></div></div>`;
|
|
274
|
+
}
|
|
275
|
+
const ICON_PASS = '<svg class="ico pass" viewBox="0 0 24 24" aria-hidden="true"><rect x="2.5" y="6" width="13" height="10" rx="1.8"/><path d="M3 7l6 4.4L15 7"/><path d="M15 17.5h6.5M18.5 14.5l3 3-3 3"/></svg>';
|
|
276
|
+
// el autocompletado de @: debajo del texto, con flechas, Enter o Tab
|
|
277
|
+
function bindMentions(t, onChange) {
|
|
278
|
+
const ta = $('#nText'), box = $('#nMention'); let items = [], at = 0;
|
|
279
|
+
const query = () => { const m = ta.value.slice(0, ta.selectionStart).match(/(^|\s)@([a-z0-9-]*)$/i); return m ? m[2].toLowerCase() : null; };
|
|
280
|
+
const paint = () => {
|
|
281
|
+
const q = query();
|
|
282
|
+
items = q === null ? [] : state.teams.filter((x) => x.id !== t.id && (x.id.startsWith(q) || String(x.name || '').toLowerCase().includes(q))).slice(0, 6);
|
|
283
|
+
box.hidden = !items.length; at = Math.min(at, Math.max(0, items.length - 1));
|
|
284
|
+
box.innerHTML = items.map((x, i) => `<span class="mi${i === at ? ' on' : ''}" role="option" data-i="${i}"><b>@${esc(x.id)}</b>${x.name && x.name !== x.id ? ' ' + esc(x.name) : ''}${x.description && x.description !== x.name ? `<i>${esc(short(x.description, 70))}</i>` : ''}</span>`).join('');
|
|
285
|
+
};
|
|
286
|
+
const pick = (i) => {
|
|
287
|
+
const x = items[i]; if (!x) return;
|
|
288
|
+
const pos = ta.selectionStart, before = ta.value.slice(0, pos).replace(/@([a-z0-9-]*)$/i, '@' + x.id + ' ');
|
|
289
|
+
ta.value = before + ta.value.slice(pos); ta.selectionStart = ta.selectionEnd = before.length; ta.focus();
|
|
290
|
+
box.hidden = true; items = []; onChange();
|
|
291
|
+
};
|
|
292
|
+
ta.addEventListener('input', () => { at = 0; paint(); onChange(); });
|
|
293
|
+
ta.addEventListener('click', paint);
|
|
294
|
+
ta.addEventListener('blur', () => setTimeout(() => (box.hidden = true), 150));
|
|
295
|
+
ta.addEventListener('keydown', (e) => {
|
|
296
|
+
if (box.hidden || !items.length) return;
|
|
297
|
+
if (e.key === 'ArrowDown' || e.key === 'ArrowUp') { e.preventDefault(); at = (at + (e.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length; paint(); }
|
|
298
|
+
else if (e.key === 'Enter' || e.key === 'Tab') { e.preventDefault(); pick(at); }
|
|
299
|
+
else if (e.key === 'Escape') { box.hidden = true; }
|
|
300
|
+
});
|
|
301
|
+
box.addEventListener('mousedown', (e) => { const el = e.target.closest('[data-i]'); if (el) { e.preventDefault(); pick(+el.dataset.i); } });
|
|
302
|
+
}
|
|
303
|
+
// la pregunta de un objetivo, en palabras: un pase pendiente dice a qué equipo y qué le va a pedir
|
|
304
|
+
function questionHtml(o) {
|
|
305
|
+
const m = String(o.question || '').match(/^hand over to team (\S+):\n?([\s\S]*)$/);
|
|
306
|
+
return m ? `pasarle a <b>${esc(teamName(m[1]))}</b>: ${esc(m[2])}` : esc(o.question);
|
|
307
|
+
}
|
|
308
|
+
// de dónde vino y a quién se lo pasó (en vivo y en el informe)
|
|
309
|
+
function passLinksHtml(o) {
|
|
310
|
+
const out = [];
|
|
311
|
+
if (o.from) out.push(`<a class="xlink from" data-nav href="${esc(url.obj(o.from.team, o.from.id))}">viene de <b>${esc(teamName(o.from.team))}</b> · ${esc(o.from.ref)}</a>`);
|
|
312
|
+
(o.passed || []).forEach((c) => out.push(`<a class="xlink to" data-nav href="${esc(url.obj(c.team, c.id))}">${ICON_PASS}pasado a <b>${esc(teamName(c.team))}</b> · ${esc(c.ref)} · ${esc(STATUS[c.status] || c.status)}</a>`));
|
|
313
|
+
const left = (o.pass_to || []).filter((x) => !(o.passed || []).some((c) => c.team === x));
|
|
314
|
+
if (left.length && OPEN_OBJ.includes(o.status)) out.push(`<span class="xlink maybe" title="lo nombraste en el pedido: el líder decide si hace falta">puede pasarlo a ${left.map((x) => esc(teamName(x))).join(' o ')}</span>`);
|
|
315
|
+
return out.join('');
|
|
316
|
+
}
|
|
317
|
+
function bindObjForm(t, mode) {
|
|
318
|
+
const f = state.form, keep = () => { f.text = $('#nText').value; if ($('#nPassAsk')) f.passAsk = $('#nPassAsk').checked; if ($('#nAt')) f.at = $('#nAt').value; if ($('#nEvery')) f.every = +$('#nEvery').value || 1; f.budget = +$('#nBudget').value || 0; f.days = [...document.querySelectorAll('[data-day]:checked')].map((c) => c.dataset.day); };
|
|
319
|
+
const redraw = () => { keep(); $('#objNew').innerHTML = objFormHtml(t, mode); bindObjForm(t, mode); };
|
|
320
|
+
document.querySelectorAll('#objNew [data-mode]').forEach((b) => (b.onclick = () => { keep(); if (b.dataset.mode !== mode) go(b.dataset.mode === 'repeat' ? url.newRoutine(t.id) : url.newObj(t.id), true); }));
|
|
321
|
+
if ($('#nFreq')) $('#nFreq').onchange = (e) => { keep(); f.freq = e.target.value; redraw(); };
|
|
322
|
+
$('#nCancel').onclick = () => { state.form = null; go(url.team(t.id)); };
|
|
323
|
+
$('#nGo').onclick = async () => {
|
|
324
|
+
keep();
|
|
325
|
+
if (!f.text.trim()) { $('#nErr').textContent = 'Escribí qué tiene que lograr el equipo.'; return; }
|
|
326
|
+
$('#nGo').disabled = true;
|
|
327
|
+
if (mode === 'once') {
|
|
328
|
+
const r = await api('objectives/add', { team: t.id, text: f.text.trim(), budget_tokens: f.budget, pass_ask: !!f.passAsk });
|
|
329
|
+
$('#nGo').disabled = false;
|
|
330
|
+
if (!r.ok) { $('#nErr').textContent = r.data.error || 'no se pudo crear'; return; }
|
|
331
|
+
state.form = null; await refreshObjectives(); go(url.obj(t.id, r.data.id), true); return;
|
|
332
|
+
}
|
|
333
|
+
// la rutina: una tarea programada (lib/schedule.syn) cuya acción le da este objetivo al equipo
|
|
334
|
+
if (f.freq === 'days' && !f.days.length) { $('#nGo').disabled = false; $('#nErr').textContent = 'Elegí al menos un día.'; return; }
|
|
335
|
+
const when = f.freq === 'every' ? 'every ' + Math.max(1, f.every) + 'h' : (f.freq === 'days' ? f.days.join(',') + ' ' : 'daily ') + (f.at || '09:00');
|
|
336
|
+
const r = await api('schedules/add', { name: firstSentence(f.text, 60), when, action: { type: 'objective', team: t.id, text: f.text.trim(), budget_tokens: f.budget, pass_ask: !!f.passAsk } });
|
|
337
|
+
$('#nGo').disabled = false;
|
|
338
|
+
if (!r.ok) { $('#nErr').textContent = r.data.error || 'no se pudo crear la rutina'; return; }
|
|
339
|
+
state.form = null; await refreshRoutines(); go(url.routine(t.id, r.data.task.id), true);
|
|
340
|
+
};
|
|
341
|
+
const passNow = () => { keep(); const h = passBoxHtml(t, f); if ($('#nPass').innerHTML !== h) $('#nPass').innerHTML = h; };
|
|
342
|
+
bindMentions(t, passNow);
|
|
343
|
+
setTimeout(() => $('#nText') && $('#nText').focus(), 0);
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
// ---------- un objetivo (o una ejecución de una rutina) ----------
|
|
347
|
+
// Arriba lo que importa: el resultado (o qué pasa ahora). Después qué hizo cada asiento, con sus pasos en palabras
|
|
348
|
+
// normales — salen de la traza de su sesión (.lampson/trace/<sid>.log vía api/trace), recortada a la ventana del
|
|
349
|
+
// objetivo — y el tablero de este objetivo, que se resalta cuando algo cambia.
|
|
350
|
+
function boardHtml(tasks, moved) {
|
|
81
351
|
return LANES.map(([st, label]) => {
|
|
82
352
|
const cs = tasks.filter((t) => t.status === st);
|
|
83
|
-
return `<div class="lane"><h6><span>${label}</span><span>${cs.length}</span></h6><div class="cards">${cs.map((t) => `<div class="card"><div class="cid">#${t.id}</div>${esc(t.title)}${t.depends && t.depends.length ? `<div class="dep">depende de ${t.depends.map((d) => '#' + d).join(', ')}</div>` : ''}${t.notes ? `<div class="notes">${esc(t.notes)}</div>` : ''}${t.owner ? `<div class="own">${esc(t.owner)}</div>` : ''}</div>`).join('')}</div></div>`;
|
|
353
|
+
return `<div class="lane"><h6><span>${label}</span><span>${cs.length}</span></h6><div class="cards">${cs.map((t) => `<div class="card${moved && moved.has(t.id) ? ' moved' : ''}"><div class="cid">#${t.id}</div>${esc(t.title)}${t.depends && t.depends.length ? `<div class="dep">depende de ${t.depends.map((d) => '#' + d).join(', ')}</div>` : ''}${t.notes ? `<div class="notes">${esc(t.notes)}</div>` : ''}${t.owner ? `<div class="own">${esc(t.owner)}</div>` : ''}</div>`).join('')}</div></div>`;
|
|
84
354
|
}).join('');
|
|
85
355
|
}
|
|
356
|
+
// «over cap» (lib/teams.syn → team_turn_end): «670000 of 600000 daily tokens — …», dicho para la persona
|
|
357
|
+
function overText(r) {
|
|
358
|
+
const m = String(r.text || '').match(/^(\d+) of (\d+)/); if (!m) return r.text;
|
|
359
|
+
return `hoy lleva ${k(+m[1])} de ${k(+m[2])}` + (/no more turns/.test(r.text) ? ': sin más turnos hoy' : ': sigue porque el objetivo tiene presupuesto');
|
|
360
|
+
}
|
|
361
|
+
// ¿un asiento pasó su tope diario? (solo cuenta para objetivos de hoy: el gasto es del día)
|
|
362
|
+
const overCap = (o, s) => s.cap > 0 && s.today >= s.cap && new Date(o.created_at * 1000).toDateString() === new Date().toDateString();
|
|
363
|
+
// lo que se puede hacer con un asiento que pasó su tope: darle más por hoy, reiniciarlo o cambiar su tope
|
|
364
|
+
// (lib/api.syn → seat_tokens; el tope propio del asiento se guarda con el equipo)
|
|
365
|
+
function capPop(anchor, o, seats) {
|
|
366
|
+
document.querySelectorAll('.cappop').forEach((x) => x.remove());
|
|
367
|
+
const live = OPEN_OBJ.includes(o.status), left = o.budget_tokens ? Math.max(0, o.budget_tokens - o.spent) : 0;
|
|
368
|
+
const pop = document.createElement('div'); pop.className = 'cappop'; pop.setAttribute('role', 'dialog');
|
|
369
|
+
pop.innerHTML = `<button type="button" class="iclose" data-x title="cerrar">✕</button>
|
|
370
|
+
${seats.map((s) => `<div class="cp-seat" data-agent="${esc(s.agent)}"><p class="cp-h"><b>${esc(s.role || s.agent)}</b> lleva <b>${k(s.today)}</b> de ${k(s.cap)} hoy</p>
|
|
371
|
+
<div class="cp-bar"><i style="width:${Math.min(100, (100 * s.cap) / Math.max(s.today, 1))}%"></i></div>
|
|
372
|
+
<div class="cp-acts"><button type="button" class="primary" data-grant>Darle ${k(s.cap)} más hoy</button><button type="button" data-reset>Reiniciar su cuenta de hoy</button><button type="button" class="lnk" data-edit>Cambiar su tope</button></div></div>`).join('')}
|
|
373
|
+
<p class="cp-note">${live && (!o.budget_tokens || left > 0) ? `Mientras este objetivo tenga presupuesto (le quedan ${o.budget_tokens ? k(left) : 'sin límite'}), sigue trabajando igual: el tope diario frena sus turnos sueltos, fuera de un objetivo.` : 'Sin más presupuesto en un objetivo, al pasar el tope no recibe turnos hasta mañana.'} Mirá sus pasos para ver en qué se le fue.</p>
|
|
374
|
+
<p class="ferr" data-err></p>`;
|
|
375
|
+
document.body.appendChild(pop);
|
|
376
|
+
const r = anchor.getBoundingClientRect(), w = pop.offsetWidth;
|
|
377
|
+
pop.style.left = Math.max(12, Math.min(innerWidth - w - 12, r.left + r.width / 2 - w / 2)) + 'px';
|
|
378
|
+
pop.style.top = Math.min(innerHeight - pop.offsetHeight - 12, r.bottom + 8) + 'px';
|
|
379
|
+
const close = () => { pop.remove(); document.removeEventListener('pointerdown', away, true); };
|
|
380
|
+
const away = (e) => { if (!pop.contains(e.target) && e.target !== anchor) close(); };
|
|
381
|
+
setTimeout(() => document.addEventListener('pointerdown', away, true), 0);
|
|
382
|
+
pop.querySelector('[data-x]').onclick = close;
|
|
383
|
+
pop.querySelectorAll('.cp-seat').forEach((box) => {
|
|
384
|
+
const agent = box.dataset.agent, s = seats.find((x) => x.agent === agent);
|
|
385
|
+
const send = async (body, btn) => {
|
|
386
|
+
box.querySelectorAll('button').forEach((b) => (b.disabled = true)); btn.textContent = 'listo…';
|
|
387
|
+
const res = await api('teams/seat-tokens', { agent, ...body });
|
|
388
|
+
if (!res.ok) { pop.querySelector('[data-err]').textContent = (res.data && res.data.error) || 'no se pudo'; box.querySelectorAll('button').forEach((b) => (b.disabled = false)); return; }
|
|
389
|
+
box.querySelector('.cp-h').innerHTML = `<b>${esc(s.role || s.agent)}</b> lleva <b>${k(res.data.today)}</b> de ${k(res.data.cap)} hoy <span class="cp-ok">✓</span>`;
|
|
390
|
+
box.querySelector('.cp-bar i').style.width = Math.min(100, (100 * res.data.today) / Math.max(res.data.cap, 1)) + '%';
|
|
391
|
+
box.querySelector('.cp-acts').remove(); if (state.route.page === 'obj') loadObj(); setTimeout(close, 1600);
|
|
392
|
+
};
|
|
393
|
+
box.querySelector('[data-grant]').onclick = (e) => send({ action: 'grant', tokens: s.cap }, e.target);
|
|
394
|
+
box.querySelector('[data-reset]').onclick = (e) => send({ action: 'reset' }, e.target);
|
|
395
|
+
box.querySelector('[data-edit]').onclick = () => { close(); state.selWanted = agent; go(url.edit(o.team)); };
|
|
396
|
+
});
|
|
397
|
+
}
|
|
86
398
|
function logHtml(rows, el) {
|
|
87
399
|
const fresh = [];
|
|
88
400
|
const html = rows.map((r) => {
|
|
89
401
|
const key = el.id + ':' + r.id;
|
|
90
402
|
const isNew = state.seen.size > 0 && !state.seen.has(key);
|
|
91
403
|
fresh.push(key);
|
|
92
|
-
return `<li class="${isNew ? 'fresh' : ''}"><span class="t">${hhmm(r.at)}</span><span class="a">${esc(r.actor)}</span><span class="k ${esc(r.kind.split(' ')[0])}">${esc(KIND[r.kind] || r.kind)} ${esc(r.ref)}</span>${r.text ? `<span class="x">${esc(r.text)}</span>` : ''}</li>`;
|
|
404
|
+
return `<li class="${isNew ? 'fresh' : ''}"><span class="t">${hhmm(r.at)}</span><span class="a">${esc(r.actor)}</span><span class="k ${esc(r.kind.split(' ')[0])}">${esc(KIND[r.kind] || r.kind)} ${esc(r.ref)}</span>${r.text && r.text !== 'null' ? `<span class="x">${esc(r.kind === 'over cap' ? overText(r) : r.text)}</span>` : ''}</li>`;
|
|
93
405
|
}).join('');
|
|
94
406
|
el.innerHTML = html || '<li class="hint">Nada todavía.</li>';
|
|
95
407
|
fresh.forEach((x) => state.seen.add(x));
|
|
96
408
|
}
|
|
409
|
+
// la traza de una sesión → pasos con fecha completa. Las líneas traen solo la hora (UTC); la fecha sale del id de la
|
|
410
|
+
// sesión (AAAAMMDD-…) y avanza un día cada vez que la hora vuelve para atrás
|
|
411
|
+
function parseTrace(sid, txt) {
|
|
412
|
+
const m0 = String(sid).match(/^(\d{4})(\d{2})(\d{2})/); if (!m0) return [];
|
|
413
|
+
let day = Date.UTC(+m0[1], +m0[2] - 1, +m0[3]) / 1000, prev = -1;
|
|
414
|
+
const out = [];
|
|
415
|
+
for (const line of String(txt || '').split('\n')) {
|
|
416
|
+
const m = line.match(/^(\d\d):(\d\d):(\d\d)\.(\d{3}) .{6}s {2}(\S+)\s+(.*)$/); if (!m) continue;
|
|
417
|
+
const secs = +m[1] * 3600 + +m[2] * 60 + +m[3] + +m[4] / 1000;
|
|
418
|
+
if (prev >= 0 && secs < prev - 60) day += 86400;
|
|
419
|
+
prev = secs;
|
|
420
|
+
out.push({ at: day + secs, kind: m[5], text: m[6] });
|
|
421
|
+
}
|
|
422
|
+
return out;
|
|
423
|
+
}
|
|
424
|
+
const TASK_ST = { todo: 'por hacer', doing: 'en curso', review: 'en revisión', done: 'hecha', blocked: 'bloqueada' };
|
|
425
|
+
const short = (s, n = 90) => { const t = String(s ?? '').replace(/\s*⏎\s*/g, ' ').trim(); return t.length > n ? t.slice(0, n - 1) + '…' : t; };
|
|
426
|
+
// una llamada a una herramienta, dicha como lo haría una persona
|
|
427
|
+
function sayCall(name, a) {
|
|
428
|
+
a = a || {};
|
|
429
|
+
const p = a.path || a.file || '';
|
|
430
|
+
switch (name) {
|
|
431
|
+
// si el corte de la traza se llevó la ruta, se dice en general (sin un hueco)
|
|
432
|
+
case 'read': return p ? `leyó <code>${esc(p)}</code>` : 'leyó un archivo';
|
|
433
|
+
case 'write': return p ? `escribió <code>${esc(p)}</code>` : 'escribió un archivo';
|
|
434
|
+
case 'edit': return p ? `editó <code>${esc(p)}</code>` : 'editó un archivo';
|
|
435
|
+
case 'ls': return `miró la carpeta <code>${esc(p || '.')}</code>`;
|
|
436
|
+
case 'find': case 'grep': return `buscó «${esc(short(a.pattern || a.query || a.name || '', 60))}»`;
|
|
437
|
+
case 'bash': return a.command ? `corrió <code>${esc(short(a.command, 80))}</code>` : 'corrió un comando';
|
|
438
|
+
case 'todo': return 'actualizó su lista de pendientes';
|
|
439
|
+
case 'fetch': return `consultó <code>${esc(short(a.url, 70))}</code>`;
|
|
440
|
+
case 'memory': return 'anotó algo en la memoria';
|
|
441
|
+
case 'send': return (a.recipient ? `le escribió a <b>${esc(a.recipient)}</b>` : 'mandó un mensaje') + (a.message ? `: «${esc(short(a.message, 140))}»` : '');
|
|
442
|
+
case 'board': {
|
|
443
|
+
const act = a.action;
|
|
444
|
+
if (act === 'list') return 'miró el tablero';
|
|
445
|
+
if (act === 'add') return `creó la tarea «${esc(short(a.title, 80))}»${a.owner ? ' para <b>' + esc(a.owner) + '</b>' : ''}`;
|
|
446
|
+
if (act === 'claim') return `tomó la tarea #${esc(a.id)}`;
|
|
447
|
+
if (act === 'update') return `movió la tarea #${esc(a.id)}${a.status ? ' a «' + esc(TASK_ST[a.status] || a.status) + '»' : ''}${a.notes ? ': ' + esc(short(a.notes, 100)) : ''}`;
|
|
448
|
+
return `revisó el tablero (${esc(act || '')})`;
|
|
449
|
+
}
|
|
450
|
+
case 'objective': {
|
|
451
|
+
const msg = esc(short(a.message, 160)), act = a.action;
|
|
452
|
+
if (act === 'report') return `informó: «${msg}»`;
|
|
453
|
+
if (act === 'ask') return `te preguntó: «${msg}»`;
|
|
454
|
+
if (act === 'request_approval') return `pidió tu aprobación: «${msg}»`;
|
|
455
|
+
if (act === 'done') return 'cerró el objetivo con su informe';
|
|
456
|
+
if (act === 'fail') return `lo dio por fallido: «${msg}»`;
|
|
457
|
+
return 'miró el objetivo';
|
|
458
|
+
}
|
|
459
|
+
default: return `usó <code>${esc(name)}</code>`;
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
// la traza corta cada línea a 600 caracteres: en un edit el texto nuevo va primero y la ruta queda después del corte.
|
|
463
|
+
// Si el JSON llegó cortado, se rescatan uno por uno los campos que se muestran (lo que sí alcanzó a quedar)
|
|
464
|
+
function salvageArgs(raw) {
|
|
465
|
+
const out = {};
|
|
466
|
+
for (const key of ['path', 'file', 'command', 'recipient', 'message', 'title', 'owner', 'id', 'status', 'action', 'notes', 'pattern', 'query', 'url']) {
|
|
467
|
+
const m = String(raw).match(new RegExp(String.raw`"${key}":\s*("(?:[^"\\]|\\.)*"|-?\d+)`));
|
|
468
|
+
if (m) { try { out[key] = JSON.parse(m[1]); } catch (x) {} continue; }
|
|
469
|
+
// un texto que el corte dejó sin cerrar: lo que alcanzó a quedar, con «…»
|
|
470
|
+
const c = String(raw).match(new RegExp(String.raw`"${key}":\s*"((?:[^"\\]|\\.)*?)\\?$`));
|
|
471
|
+
if (c) { try { out[key] = JSON.parse('"' + c[1] + '"') + '…'; } catch (x) {} }
|
|
472
|
+
}
|
|
473
|
+
return out;
|
|
474
|
+
}
|
|
475
|
+
// los pasos de un asiento, agrupados por turno: qué lo despertó, qué dijo, qué hizo (con el detalle técnico a un clic)
|
|
476
|
+
function stepsOf(evs) {
|
|
477
|
+
const turns = []; let cur = null, last = null;
|
|
478
|
+
for (const e of evs) {
|
|
479
|
+
if (e.kind === 'USER') {
|
|
480
|
+
const t = e.text.replace(/^\[[^\]]*\]\s*/, '');
|
|
481
|
+
const why = /^\[round\]/.test(t) ? 'ronda: revisó si tenía algo pendiente' : /^\[message from ([^\]]+)\]/.test(t) ? 'le llegó un mensaje de ' + t.match(/^\[message from ([^\]]+)\]/)[1] : /^\[objective O-/.test(t) ? 'recibió el objetivo' : 'empezó un turno';
|
|
482
|
+
cur = { at: e.at, why, items: [], tokens: 0 }; turns.push(cur); continue;
|
|
483
|
+
}
|
|
484
|
+
if (!cur) { cur = { at: e.at, why: 'turno', items: [], tokens: 0 }; turns.push(cur); }
|
|
485
|
+
if (e.kind === 'SAY') cur.items.push({ at: e.at, html: `«${mdInline(short(e.text, 400))}»`, cls: 'say' });
|
|
486
|
+
else if (e.kind === 'CALL') {
|
|
487
|
+
const sp = e.text.indexOf(' '), name = sp < 0 ? e.text : e.text.slice(0, sp); let args = {};
|
|
488
|
+
try { args = JSON.parse(e.text.slice(sp + 1)); } catch (x) { args = salvageArgs(e.text.slice(sp + 1)); }
|
|
489
|
+
last = { at: e.at, html: sayCall(name, args), raw: e.text, cls: 'call' }; cur.items.push(last);
|
|
490
|
+
} else if ((e.kind === 'OK' || e.kind === 'FAIL') && last) { last.out = e.text.replace(/^\S+ → /, ''); if (e.kind === 'FAIL') last.cls += ' bad'; }
|
|
491
|
+
else if (e.kind === 'DENY') cur.items.push({ at: e.at, html: 'no se le permitió: ' + esc(short(e.text, 200)), cls: 'bad' });
|
|
492
|
+
else if (e.kind === 'ERR') cur.items.push({ at: e.at, html: 'error: ' + esc(short(e.text, 200)), cls: 'bad' });
|
|
493
|
+
// gasto con la misma regla que el del objetivo (lib/runtime.syn): lo que ya estaba en caché cuenta un décimo
|
|
494
|
+
else if (e.kind === 'STEP') { const m = e.text.match(/in=(\d+)(?: \(cache (\d+)\))? out=(\d+)/); if (m) cur.tokens += +m[1] - (+m[2] || 0) + Math.floor((+m[2] || 0) / 10) + +m[3]; }
|
|
495
|
+
}
|
|
496
|
+
return turns;
|
|
497
|
+
}
|
|
498
|
+
function seatTimelineHtml(turns, agent) {
|
|
499
|
+
if (!turns.length) return '<p class="ihint">No trabajó en este objetivo.</p>';
|
|
500
|
+
const raw = state.openRaw || new Set();
|
|
501
|
+
return turns.map((t) => `<div class="turn"><div class="twhy"><span class="t">${hhmm(t.at)}</span>${esc(t.why)}${t.tokens ? `<span class="tk">${k(t.tokens)} tokens</span>` : ''}</div>
|
|
502
|
+
<ol>${t.items.map((i) => i.raw ? `<li class="${i.cls}"><details data-k="${esc(agent + ':' + i.at)}"${raw.has(agent + ':' + i.at) ? ' open' : ''}><summary><span class="t">${hhmm(i.at)}</span>${i.html}</summary><pre>${esc(i.raw)}${i.out ? '\n→ ' + esc(i.out) : ''}</pre></details></li>` : `<li class="${i.cls}"><span class="t">${hhmm(i.at)}</span>${i.html}</li>`).join('')}</ol></div>`).join('');
|
|
503
|
+
}
|
|
504
|
+
// ¿está trabajando ahora? (el buzón del agente en la conversación del objetivo: api/teams para un equipo, el objetivo si es solo)
|
|
505
|
+
const workingNow = (o, agent) => o.team ? ((teamOf(o.team) || { members: [] }).members.find((m) => m.agent === agent) || {}).working : o.working;
|
|
506
|
+
// la traza de cada asiento, recortada a la ventana del objetivo (mientras está abierto se relee: cada 3 s si alguien trabaja, si no cada 10)
|
|
507
|
+
async function loadSeatWork(o) {
|
|
508
|
+
const end = OPEN_OBJ.includes(o.status) ? Date.now() / 1000 + 60 : o.updated_at + 60;
|
|
509
|
+
const key = o.id + ':' + o.status;
|
|
510
|
+
const busy = (o.seats || []).some((x) => workingNow(o, x.agent)), every = busy ? 3000 : 10000;
|
|
511
|
+
if (state.work && state.work.key === key && OPEN_OBJ.includes(o.status) && Date.now() - state.work.at < every) return state.work.seats;
|
|
512
|
+
if (state.work && state.work.key === key && !OPEN_OBJ.includes(o.status)) return state.work.seats;
|
|
513
|
+
const seats = await Promise.all((o.seats || []).map(async (s) => {
|
|
514
|
+
if (!s.session) return { ...s, turns: [] };
|
|
515
|
+
const r = await api('trace?session=' + enc(s.session) + '&tail=100000');
|
|
516
|
+
const evs = parseTrace(s.session, r.ok ? r.data.trace : '').filter((e) => e.at >= o.created_at - 2 && e.at <= end);
|
|
517
|
+
return { ...s, turns: stepsOf(evs) };
|
|
518
|
+
}));
|
|
519
|
+
state.work = { key, at: Date.now(), seats };
|
|
520
|
+
return seats;
|
|
521
|
+
}
|
|
522
|
+
// el informe: cada línea en su párrafo, y las rutas de archivos como código
|
|
523
|
+
// markdown chico: lo que escriben los agentes (**negrita**, `código`, rutas) se ve con formato y no con los signos
|
|
524
|
+
// algunos modelos escriben los acentos escapados («é»): se muestran como letras
|
|
525
|
+
const unescapeU = (t) => String(t ?? '').replace(/\\u([0-9a-fA-F]{4})/g, (m, h) => String.fromCharCode(parseInt(h, 16)));
|
|
526
|
+
function mdInline(t) {
|
|
527
|
+
return esc(unescapeU(t)).replace(/`([^`]+)`/g, '<code>$1</code>').replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>')
|
|
528
|
+
.replace(/(^|[\s(«])((?:[\w.-]+\/)+[\w.-]+|[\w-]+\.(?:md|js|ts|tsx|jsx|json|py|syn|css|html|yml|yaml|txt|csv))(?=[\s),.;:»]|$)/g, (m, a, b) => a + '<code>' + b + '</code>');
|
|
529
|
+
}
|
|
530
|
+
// el informe: un párrafo por línea; «- …» como lista; las partes «**Algo:**» como títulos chicos
|
|
531
|
+
function reportHtml(txt) {
|
|
532
|
+
const lines = String(txt || '').replace(/\s+-\s+(?=\*\*)/g, '\n- ').split(/\n+|(?=\s✓\s)/).map((l) => l.trim()).filter(Boolean);
|
|
533
|
+
let html = '', list = false;
|
|
534
|
+
for (const l of lines) {
|
|
535
|
+
const li = l.match(/^[-•*]\s+(.*)$/);
|
|
536
|
+
if (li && !list) { html += '<ul>'; list = true; }
|
|
537
|
+
if (!li && list) { html += '</ul>'; list = false; }
|
|
538
|
+
html += li ? `<li>${mdInline(li[1])}</li>` : `<p>${mdInline(l)}</p>`;
|
|
539
|
+
}
|
|
540
|
+
return html + (list ? '</ul>' : '');
|
|
541
|
+
}
|
|
97
542
|
async function loadObj() {
|
|
98
|
-
if (!
|
|
99
|
-
const r = await api('objectives/' +
|
|
543
|
+
const id = state.route.obj; if (!id) return;
|
|
544
|
+
const r = await api('objectives/' + id);
|
|
100
545
|
if (!r.ok) { $('#objDetail').innerHTML = '<div class="empty">Ese objetivo no existe.</div>'; return; }
|
|
101
546
|
const o = r.data;
|
|
102
|
-
|
|
103
|
-
|
|
547
|
+
// la URL con el equipo (un enlace viejo o /objetivos/<n> de un objetivo que es de un equipo)
|
|
548
|
+
if (o.team && state.route.team !== o.team) { history.replaceState(null, '', url.obj(o.team, o.id)); state.route = parseRoute(); renderCrumbs(); }
|
|
549
|
+
if (state.route.obj !== id) return;
|
|
550
|
+
// lo desplegado (pasos de un asiento, el detalle de un paso, el pedido entero) sobrevive al pulso; otro objetivo, de cero
|
|
551
|
+
if (state.openFor !== id) { state.openFor = id; state.openSeats = new Set(); state.openRaw = new Set(); state.askOpen = false; }
|
|
552
|
+
if (OPEN_OBJ.includes(o.status)) { await renderLive(o); return; }
|
|
553
|
+
if (state.liveKey) { state.liveKey = null; $('#objDetail').classList.remove('lvmode'); }
|
|
554
|
+
const seats = await loadSeatWork(o);
|
|
555
|
+
if (state.route.obj !== id) return;
|
|
556
|
+
// qué cambió en el tablero desde el último pulso: se resalta un instante
|
|
557
|
+
const prev = state.boardSeen && state.boardSeen.id === id ? state.boardSeen.map : null, moved = new Set();
|
|
558
|
+
(o.tasks || []).forEach((t) => { if (prev && prev[t.id] !== t.status) moved.add(t.id); });
|
|
559
|
+
state.boardSeen = { id, map: Object.fromEntries((o.tasks || []).map((t) => [t.id, t.status])) };
|
|
560
|
+
const open = OPEN_OBJ.includes(o.status), pct = o.budget_tokens > 0 ? Math.min(100, Math.round((100 * o.spent) / o.budget_tokens)) : 0;
|
|
561
|
+
const rid = routineOf(o), rt = rid && state.routines.find((x) => x.id === rid);
|
|
562
|
+
const long = o.text.length > 280, openSeats = state.openSeats || (state.openSeats = new Set());
|
|
563
|
+
const ordered = [...seats].sort((a, b) => b.lead - a.lead);
|
|
564
|
+
const seatRow = (s) => {
|
|
565
|
+
const mine = (o.tasks || []).filter((t) => t.owner === s.agent), done = mine.filter((t) => t.status === 'done');
|
|
566
|
+
const tokens = s.turns.reduce((n, t) => n + t.tokens, 0), calls = s.turns.reduce((n, t) => n + t.items.filter((i) => i.raw).length, 0);
|
|
567
|
+
const lastSay = [...s.turns].reverse().flatMap((t) => [...t.items].reverse()).find((i) => i.cls === 'say');
|
|
568
|
+
const what = done.length ? 'hizo ' + done.map((t) => '«' + esc(short(t.title, 70)) + '»').join(', ') : mine.length ? 'trabaja en ' + mine.map((t) => '«' + esc(short(t.title, 70)) + '»').join(', ') : lastSay ? lastSay.html : s.turns.length ? 'participó sin tareas propias' : 'no trabajó en este objetivo';
|
|
569
|
+
const isOpen = openSeats.has(s.agent), live = open && workingNow(o, s.agent);
|
|
570
|
+
const lastStep = live ? [...s.turns].reverse().flatMap((t) => [...t.items].reverse())[0] : null;
|
|
571
|
+
// el «ahora» se ilumina solo cuando hay un paso nuevo, no en cada pulso
|
|
572
|
+
const seen = state.liveSeen || (state.liveSeen = {}), fresh = !!lastStep && seen[s.agent] !== lastStep.at; if (lastStep) seen[s.agent] = lastStep.at;
|
|
573
|
+
return `<div class="seat${s.turns.length ? '' : ' idle'}"><div class="shead"><span class="av">${esc((s.role || s.agent).normalize('NFD').replace(/\p{M}/gu, '').slice(0, 2))}</span>
|
|
574
|
+
<div class="sbody"><div class="sname"><b>${esc(s.role || s.agent)}</b>${s.lead ? '<span class="fl-lead">líder</span>' : ''}${live ? '<span class="tw">● trabajando</span>' : ''}</div>${live && lastStep ? `<p class="snow${fresh ? ' fresh' : ''}"><span class="t">${hhmm(lastStep.at)}</span>ahora: ${lastStep.html}</p>` : ''}<p class="swhat">${what}</p>
|
|
575
|
+
<p class="smeta">${mine.length ? `${done.length} de ${mine.length} tarea${mine.length === 1 ? '' : 's'} · ` : ''}${calls} paso${calls === 1 ? '' : 's'} · ${k(tokens)} tokens${overCap(o, s) ? ` · <span class="over">hoy lleva ${k(s.today)} de ${k(s.cap)}: pasó su tope diario</span>` : ''}</p></div>
|
|
576
|
+
${s.turns.length ? `<button class="lnk" data-seat="${esc(s.agent)}">${isOpen ? 'ocultar pasos' : 'ver sus pasos'}</button>` : ''}</div>
|
|
577
|
+
${isOpen ? `<div class="steps">${seatTimelineHtml(s.turns, s.agent)}</div>` : ''}</div>`;
|
|
578
|
+
};
|
|
579
|
+
const now = 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>`
|
|
580
|
+
: o.result ? `<div class="box res${o.status === 'failed' ? ' bad' : ''}"><h5>${o.status === 'failed' ? 'Por qué no se pudo' : 'Resultado'} <span class="who">informe de ${esc((seats.find((s) => s.lead) || {}).role || o.agent)}</span></h5>${reportHtml(o.result)}</div>`
|
|
581
|
+
: o.progress ? `<div class="box"><h5>Ahora</h5>${reportHtml(o.progress)}</div>` : open ? '<div class="box"><h5>Ahora</h5><p>Arrancando: el líder está repartiendo el trabajo.</p></div>' : '';
|
|
104
582
|
$('#objDetail').innerHTML = `
|
|
105
|
-
<div class="dhead"><span class="ref">${esc(o.ref)}</span><span class="st ${o.status}">${STATUS[o.status] || o.status}</span
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
${o.budget_tokens ? `<div class="meter ${pct > 80 ? 'hot' : ''}"><i style="width:${pct}%"></i></div>` : ''}
|
|
109
|
-
<div
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
if (
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const body = { text: $('#fText').value.trim(), round_seconds: +$('#fRound').value || 20, budget_tokens: +$('#fBudget').value || 0 };
|
|
128
|
-
if (target.startsWith('team:')) body.team = target.slice(5); else body.agent = target;
|
|
129
|
-
if (!target || !body.text) { $('#fErr').textContent = 'Elegí un agente o un equipo y escribí qué tiene que lograr.'; return; }
|
|
130
|
-
const r = await api('objectives/add', body);
|
|
131
|
-
if (!r.ok) { $('#fErr').textContent = r.data.error || 'no se pudo crear'; return; }
|
|
132
|
-
$('#fErr').textContent = ''; $('#fText').value = ''; $('#objForm').hidden = true;
|
|
133
|
-
await refreshObjectives(); openObj(r.data.id);
|
|
134
|
-
};
|
|
583
|
+
<div class="dhead"><span class="ref">${esc(o.ref)}</span><span class="st ${o.status}">${STATUS[o.status] || o.status}</span>${o.working ? '<span class="tw">● trabajando ahora</span>' : ''}
|
|
584
|
+
<span class="dmeta">${rt ? `⟳ ejecución de <a data-nav href="${esc(url.routine(o.team, rid))}">${esc(rt.name)}</a> · ` : ''}${fmtWhen(o.created_at)} · ${o.turns} ronda${o.turns === 1 ? '' : 's'} · ${k(o.spent)}${o.budget_tokens ? ' de ' + k(o.budget_tokens) : ''} tokens</span>${passLinksHtml(o)}
|
|
585
|
+
<span class="spacer"></span>${o.team ? '<button data-diag title="Qué está trabado y cómo destrabarlo">Revisar</button>' : ''}<button data-log>Registro</button>${open ? `${o.status === 'paused' ? '<button data-resume>Seguir (más presupuesto)</button>' : ''}<button class="no" data-cancel>Cancelar</button>` : ''}</div>
|
|
586
|
+
${o.budget_tokens && open ? `<div class="meter ${pct > 80 ? 'hot' : ''}"><i style="width:${pct}%"></i></div>` : ''}
|
|
587
|
+
<div class="rgrid"><div class="rmain">
|
|
588
|
+
<div class="ask0${long && !state.askOpen ? ' clamp' : ''}"><h5>Qué se pidió</h5><p>${esc(unescapeU(o.text))}</p>${long ? `<button class="lnk" data-ask>${state.askOpen ? 'ver menos' : 'ver todo'}</button>` : ''}</div>
|
|
589
|
+
${now}</div>
|
|
590
|
+
<div class="rside"><h4 class="secttl">Qué hizo cada asiento</h4>${overNote(o)}<div class="seats">${ordered.map(seatRow).join('')}</div></div></div>
|
|
591
|
+
<h4 class="secttl">Tablero de este objetivo ${open ? '<span class="live2">● en vivo</span>' : ''}</h4>
|
|
592
|
+
${(o.tasks || []).length ? `<div class="board">${boardHtml(o.tasks, moved)}</div>` : '<p class="ihint">Todavía no hay tareas: el líder las crea al repartir el trabajo.</p>'}`;
|
|
593
|
+
bindObjButtons(o);
|
|
594
|
+
const cb = $('#objDetail [data-cap]'); if (cb) cb.onclick = () => capPop(cb, o, (o.seats || []).filter((s) => overCap(o, s)));
|
|
595
|
+
if (state.drawer) renderDrawer(o);
|
|
596
|
+
document.querySelectorAll('#objDetail [data-seat]').forEach((b) => (b.onclick = () => { const a = b.dataset.seat; if (openSeats.has(a)) openSeats.delete(a); else openSeats.add(a); loadObj(); }));
|
|
597
|
+
document.querySelectorAll('#objDetail details[data-k]').forEach((d) => (d.ontoggle = () => { if (d.open) state.openRaw.add(d.dataset.k); else state.openRaw.delete(d.dataset.k); }));
|
|
598
|
+
}
|
|
599
|
+
// quién pasó su tope diario: una nota con a dónde ir a revisarlo (qué se le pide, sus herramientas, el tope)
|
|
600
|
+
function overNote(o) {
|
|
601
|
+
const over = (o.seats || []).filter((s) => overCap(o, s)); if (!over.length) return '';
|
|
602
|
+
const names = over.map((s) => `<b>${esc(s.role || s.agent)}</b>`).join(', ');
|
|
603
|
+
return `<p class="overnote">${names} ${over.length === 1 ? 'pasó su' : 'pasaron su'} tope diario de tokens. Mirá sus pasos para ver en qué se le fue${o.team ? ` y, si hace falta, <button type="button" class="lnk" data-cap>dale más o ajustá su tope</button>` : ''}.</p>`;
|
|
604
|
+
}
|
|
135
605
|
async function refreshObjectives() {
|
|
136
606
|
const r = await api('objectives');
|
|
137
607
|
if (!r.ok) return false;
|
|
138
608
|
state.objectives = r.data.objectives; state.agents = r.data.agents; state.teamsMeta = r.data.teams || [];
|
|
139
609
|
const ap = await api('approvals');
|
|
140
610
|
if (ap.ok) state.approvals = ap.data.approvals || [];
|
|
141
|
-
|
|
142
|
-
sel.innerHTML = (state.teamsMeta.length ? `<optgroup label="equipos">${state.teamsMeta.map((t) => `<option value="team:${esc(t.id)}">equipo ${esc(t.id)} (lo lidera ${esc(t.lead)})</option>`).join('')}</optgroup>` : '') +
|
|
143
|
-
`<optgroup label="agentes">${state.agents.map((a) => `<option value="${esc(a.id)}" title="${esc(a.description)}">${esc(a.id)}${a.description ? ' — ' + esc(a.description.slice(0, 50)) : ''}</option>`).join('')}</optgroup>`;
|
|
144
|
-
if (cur) sel.value = cur;
|
|
145
|
-
if (!state.obj && state.objectives.length) state.obj = state.objectives[0].id;
|
|
146
|
-
renderObjList(); renderAttention();
|
|
611
|
+
renderAttention();
|
|
147
612
|
return true;
|
|
148
613
|
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const lv = (a, seen = new Set()) => { if (level[a] !== undefined) return level[a]; const m = by[a]; if (!m || !m.reports_to || !by[m.reports_to] || seen.has(a)) return (level[a] = 0); seen.add(a); return (level[a] = lv(m.reports_to, seen) + 1); };
|
|
156
|
-
team.members.forEach((m) => lv(m.agent));
|
|
157
|
-
const rows = {};
|
|
158
|
-
team.members.forEach((m) => (rows[level[m.agent]] = rows[level[m.agent]] || []).push(m.agent));
|
|
159
|
-
// ancho según la fila más poblada: con pocos agentes el grafo no queda diminuto
|
|
160
|
-
const widest = Math.max(...Object.values(rows).map((r) => r.length));
|
|
161
|
-
const nodeW = 184, nodeH = 70, gap = 56, rowH = 130;
|
|
162
|
-
const W = Math.max(560, widest * (nodeW + gap) + 80);
|
|
163
|
-
const depth = Math.max(...Object.keys(rows).map(Number)) + 1;
|
|
164
|
-
const pos = {};
|
|
165
|
-
Object.entries(rows).forEach(([l, list]) => list.forEach((a, i) => (pos[a] = { x: W / 2 + (i - (list.length - 1) / 2) * (nodeW + gap), y: 60 + Number(l) * rowH })));
|
|
166
|
-
return { pos, W, H: 60 + depth * rowH, nodeW, nodeH };
|
|
614
|
+
// las rutinas son tareas programadas con acción «objective» (lib/schedule.syn)
|
|
615
|
+
async function refreshRoutines() {
|
|
616
|
+
const r = await api('schedules');
|
|
617
|
+
if (!r.ok) return false;
|
|
618
|
+
state.routines = (r.data.tasks || []).filter((t) => t.action && t.action.type === 'objective');
|
|
619
|
+
return true;
|
|
167
620
|
}
|
|
621
|
+
|
|
622
|
+
// ---------- equipos: la lista de tarjetas; el lienzo (js/flow.js), al crear o editar uno ----------
|
|
623
|
+
// Cada miembro es un ASIENTO: su tarjeta muestra rol, para qué está y qué puede hacer. Unir dos asientos (el punto de
|
|
624
|
+
// abajo de uno hasta el otro) es la jerarquía: el de abajo le reporta. Siempre hay un líder (d.lead): no se elimina.
|
|
625
|
+
// Un asiento puede quedar suelto mientras se arma el equipo; al guardar, le reporta al líder. Las punteadas («también
|
|
626
|
+
// hablan») son de verdad: el editor las propone al unir dos asientos bajo el mismo jefe, y se borran como cualquiera.
|
|
627
|
+
const flow = Flow.create($('#graph'));
|
|
628
|
+
state.newAt = {};
|
|
629
|
+
const TOOLS_LABEL = { code: 'edita y corre comandos', read: 'lee y corre comandos', none: 'solo coordina' };
|
|
168
630
|
function hotPairs(team) {
|
|
169
|
-
//
|
|
631
|
+
// conexiones que se encienden: mensajes de los últimos 25 s (registro: actor "message" ref "→ dest")
|
|
170
632
|
const now = Date.now() / 1000; const hot = new Set();
|
|
171
|
-
team.ledger.filter((r) => r.kind === 'message' && now - r.at < 25).forEach((r) => { const d = String(r.ref).replace('→', '').trim(); hot.add([r.actor, d].sort().join('|')); });
|
|
633
|
+
(team.ledger || []).filter((r) => r.kind === 'message' && now - r.at < 25).forEach((r) => { const d = String(r.ref).replace('→', '').trim(); hot.add([r.actor, d].sort().join('|')); });
|
|
172
634
|
return hot;
|
|
173
635
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
636
|
+
const has = (d, a) => d.members.some((x) => x.agent === a);
|
|
637
|
+
const slugify = (t) => String(t || '').normalize('NFD').replace(/\p{M}/gu, '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
|
|
638
|
+
const ID_OK = /^[a-z0-9][a-z0-9-]{0,39}$/;
|
|
639
|
+
// el líder del borrador existe y no le reporta a nadie; un jefe que ya no está deja suelto a su asiento
|
|
640
|
+
function normalize(d) {
|
|
641
|
+
if (!has(d, d.lead)) d.lead = (d.members.find((m) => !m.reports_to) || d.members[0]).agent;
|
|
642
|
+
d.members.forEach((m) => { if (m.agent === d.lead || !has(d, m.reports_to)) m.reports_to = ''; });
|
|
643
|
+
d.talks = d.talks.filter((p) => p.every((a) => has(d, a)) && p[0] !== p[1]);
|
|
644
|
+
return d.lead;
|
|
645
|
+
}
|
|
646
|
+
const loose = (d, m) => m.agent !== d.lead && !m.reports_to;
|
|
647
|
+
function renderGraph() {
|
|
648
|
+
const d = state.draft, team = d && !d.isNew ? state.teams.find((t) => t.id === d.id) : null;
|
|
649
|
+
if (!d) { state.lastMode = 'list'; return; }
|
|
650
|
+
const members = d.members, talks = d.talks;
|
|
651
|
+
const lead = normalize(d);
|
|
652
|
+
// los que están trabajando ahora (del equipo guardado): se ven en el lienzo mientras se edita
|
|
653
|
+
const live = Object.fromEntries((team ? team.members : []).map((m) => [m.agent, m]));
|
|
654
|
+
const hot = team ? hotPairs(team) : new Set();
|
|
655
|
+
const nodes = members.map((m) => ({ id: m.agent, title: m.role || m.agent, desc: m.description || (d ? 'Tocalo para darle nombre y decir para qué está.' : ''), lead: m.agent === lead, loose: d && loose(d, m),
|
|
656
|
+
meta: m.missing ? 'falta su archivo de agente' : m.working ? 'trabajando…' : d && loose(d, m) ? 'suelto · al guardar le reporta al líder' : d ? TOOLS_LABEL[m.preset] || '' : (TOOLS_LABEL[presetOf(m.tools)] || '') + (m.spent_today ? ' · hoy ' + k(m.spent_today) : ''),
|
|
657
|
+
avatar: (m.role || m.agent).normalize('NFD').replace(/\p{M}/gu, '').slice(0, 2), working: (live[m.agent] || {}).working, missing: (live[m.agent] || {}).missing, at: state.newAt[m.agent] }));
|
|
658
|
+
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, hot: hot.has([m.agent, m.reports_to].sort().join('|')) }))
|
|
659
|
+
.concat(talks.map(([x, y]) => ({ kind: 'talk', from: x, to: y, hot: hot.has([x, y].sort().join('|')) })));
|
|
660
|
+
// al abrir el lienzo (venía de la lista), encuadrar
|
|
661
|
+
if (state.lastMode !== 'edit') { state.lastMode = 'edit'; requestAnimationFrame(() => flow.fit()); }
|
|
662
|
+
flow.render({ nodes, edges, editable: true, selected: state.sel, storeKey: 'lampson.flow:' + BASE + ':' + (d.isNew ? '__nuevo' : d.id),
|
|
663
|
+
onSelect: (id) => { state.sel = id; renderTeams(); },
|
|
664
|
+
onConnect: (from, to) => connectDraft(from, to),
|
|
665
|
+
onConnectEmpty: (from, pos) => addSeat(from, pos),
|
|
666
|
+
onDeleteEdge: (e) => { const dd = state.draft; if (e.kind === 'reports') { const m = dd.members.find((x) => x.agent === e.to); if (m) m.reports_to = ''; } else dd.talks = dd.talks.filter((p) => !(p.includes(e.from) && p.includes(e.to))); renderTeams(); } });
|
|
667
|
+
state.newAt = {};
|
|
668
|
+
}
|
|
669
|
+
// al quedar bajo un jefe: propone hablar con los que ya le reportan a ese jefe (punteadas que se pueden borrar)
|
|
670
|
+
function proposeTalks(d, agent) {
|
|
671
|
+
const m = d.members.find((x) => x.agent === agent); if (!m || !m.reports_to) return;
|
|
672
|
+
d.members.filter((x) => x.agent !== agent && x.reports_to === m.reports_to).forEach((x) => { if (!d.talks.some((p) => p.includes(agent) && p.includes(x.agent))) d.talks.push([x.agent, agent]); });
|
|
673
|
+
}
|
|
674
|
+
// ¿`a` está por encima de `b` (su jefe, el jefe de su jefe…)?
|
|
675
|
+
function above(d, a, b) {
|
|
676
|
+
let up = (d.members.find((x) => x.agent === b) || {}).reports_to; const seen = new Set();
|
|
677
|
+
while (up && !seen.has(up)) { if (up === a) return true; seen.add(up); up = (d.members.find((x) => x.agent === up) || {}).reports_to; }
|
|
678
|
+
return false;
|
|
679
|
+
}
|
|
680
|
+
// unir dos asientos: el que recibe la línea le reporta al que la tiró. Pero arrastrar nunca cambia el liderazgo (para eso
|
|
681
|
+
// está «Hacer líder»): si se suelta sobre el líder, o sobre alguien que ya está por encima, se entiende al revés.
|
|
682
|
+
function connectDraft(from, to) {
|
|
683
|
+
const d = state.draft; if (!d) return;
|
|
684
|
+
if (to === d.lead || above(d, to, from)) [from, to] = [to, from];
|
|
685
|
+
if (to === d.lead || above(d, to, from)) return; // sin ciclos
|
|
686
|
+
d.members.find((x) => x.agent === to).reports_to = from;
|
|
687
|
+
d.talks = d.talks.filter((p) => !(p.includes(from) && p.includes(to)));
|
|
688
|
+
proposeTalks(d, to);
|
|
689
|
+
flow.placeUnder(to, from);
|
|
690
|
+
renderTeams();
|
|
691
|
+
}
|
|
692
|
+
// + asiento: debajo del elegido; sin nada elegido, suelto en el lienzo
|
|
693
|
+
function addSeat(boss, at) {
|
|
694
|
+
const d = state.draft; let n = 1; while (has(d, 'asiento-' + n)) n++;
|
|
695
|
+
const id = 'asiento-' + n, top = boss === undefined ? state.sel || '' : boss || '';
|
|
696
|
+
state.newAt[id] = at || flow.freeSpot(top || null);
|
|
697
|
+
// nombre provisorio distinto para cada uno («Asiento 3»); el rol queda elegido para escribir el de verdad
|
|
698
|
+
let r = d.members.length + 1; while (d.members.some((x) => x.role === 'Asiento ' + r)) r++;
|
|
699
|
+
d.members.push({ agent: id, role: 'Asiento ' + r, reports_to: top, description: '', system: '', preset: 'code', permission: 'ask', dirty: true });
|
|
700
|
+
proposeTalks(d, id);
|
|
701
|
+
state.sel = id; renderTeams();
|
|
702
|
+
if (top && flow.placeUnder(id, top)) renderGraph();
|
|
703
|
+
const ri = $('#mRole'); if (ri) { ri.focus(); ri.select(); }
|
|
704
|
+
}
|
|
705
|
+
function removeSeat(id) {
|
|
706
|
+
const d = state.draft; if (id === d.lead) return;
|
|
707
|
+
const m = d.members.find((x) => x.agent === id);
|
|
708
|
+
d.members = d.members.filter((x) => x !== m); d.members.forEach((x) => { if (x.reports_to === id) x.reports_to = m.reports_to; });
|
|
709
|
+
d.talks = d.talks.filter((p) => !p.includes(id)); state.sel = null; renderTeams();
|
|
710
|
+
}
|
|
711
|
+
// «Hacer líder»: el elegido pasa arriba y el líder anterior le reporta
|
|
712
|
+
function makeLeader(id) {
|
|
713
|
+
const d = state.draft; if (id === d.lead) return;
|
|
714
|
+
const old = d.lead; d.lead = id;
|
|
715
|
+
d.members.find((x) => x.agent === id).reports_to = '';
|
|
716
|
+
d.members.find((x) => x.agent === old).reports_to = id;
|
|
717
|
+
d.talks = d.talks.filter((p) => !(p.includes(id) && p.includes(old)));
|
|
718
|
+
proposeTalks(d, old); renderTeams();
|
|
719
|
+
}
|
|
720
|
+
// ---------- plantillas: un equipo armado para empezar (después se edita en el lienzo) ----------
|
|
721
|
+
// Plantillas de equipo. Cada asiento: [agente, rol, jefe, herramientas, qué hace (se ve en el editor), cómo trabaja (su
|
|
722
|
+
// instrucción)]. Pensadas como equipos reales: cada uno hace SU parte y no rehace la de otro (el que construye no se
|
|
723
|
+
// revisa solo; el que revisa no reconstruye; el líder reparte y controla, no ejecuta), con traspasos cortos. Así el
|
|
724
|
+
// trabajo no se duplica y gasta menos. Ante algo riesgoso, cada asiento le pregunta a su jefe; el líder, a la persona.
|
|
725
|
+
const WAYS = 'Cómo trabaja este equipo: hacé solo tu parte y no rehagas la de otro; si algo de otro está mal, decíselo con lo concreto (qué, dónde, cómo verlo). Mensajes cortos: qué hiciste, dónde quedó, qué falta. Leé solo lo que necesitás para tu tarea. Si algo te bloquea o es riesgoso, preguntale a quien te reporta.';
|
|
726
|
+
const TEMPLATES = [
|
|
727
|
+
{ id: 'startup', title: 'Startup', desc: 'Dirección, producto, tecnología y comunicación: cada uno en lo suyo, hacia un mismo objetivo.', members: [
|
|
728
|
+
['ceo', 'CEO', '', 'read', 'Reparte el objetivo, sigue el avance y decide cuándo está terminado. No ejecuta: delega y controla.',
|
|
729
|
+
'Dirigís. Convertí el objetivo en tareas del tablero, cada una con un dueño claro, y mandale a cada uno lo que necesitás de él. Después seguí el avance y destrabá lo que se frene. No implementás, no revisás código ni escribís documentos: eso lo hace cada responsable. Cerrás cuando cada responsable confirmó su parte; los merges a main los hacés vos cuando el CTO aprobó.'],
|
|
730
|
+
['cpo', 'CPO', 'ceo', 'code', 'Convierte el objetivo en requisitos cortos y criterios de aceptación verificables.',
|
|
731
|
+
'Escribís los requisitos: un documento corto con qué tiene que hacer y cómo se comprueba (criterios de aceptación verificables), y las decisiones de producto que hagan falta. No implementás ni revisás código. Cuando esté, avisales al CTO y al Dev dónde quedó.'],
|
|
732
|
+
['cto', 'CTO', 'ceo', 'code', 'Decide el enfoque técnico y verifica lo que entrega el Dev: revisa y prueba. No implementa.',
|
|
733
|
+
'Sos el responsable técnico. Si hace falta, decidí el enfoque y decíselo al Dev en pocas líneas. Cuando el Dev entrega, revisá el cambio contra los requisitos y escribí y corré las pruebas que lo verifican. No implementás la funcionalidad: si algo falla, devolvéselo al Dev con lo concreto. Cuando aprobás, avisale al CEO que está listo para main.'],
|
|
734
|
+
['dev', 'Dev', 'cto', 'code', 'Implementa en su rama y entrega algo que corre. Las pruebas de verificación las hace el CTO.',
|
|
735
|
+
'Implementás lo que pide tu tarea, en tu rama. Antes de entregar comprobá que funciona: que corre, sin errores ni advertencias, y que lo que ya andaba sigue andando. Las pruebas de verificación las escribe el CTO: no las dupliques. Entregá con un commit y un mensaje corto al CTO: qué cambiaste y dónde.'],
|
|
736
|
+
['cmo', 'CMO', 'ceo', 'code', 'Documenta y comunica lo que se hizo: guía para usuarios, notas de versión, anuncios.',
|
|
737
|
+
'Comunicás lo que se hizo: documentación para quien lo usa, notas de versión y anuncios. Escribí a partir de lo ya entregado y aprobado (leé el código y lo que informó el CTO), no de supuestos. No tocás el código ni lo verificás: eso ya lo hizo el CTO. No levantes servidores ni corras pruebas.']],
|
|
738
|
+
talks: [['cpo', 'cto'], ['cmo', 'cto']] },
|
|
739
|
+
{ id: 'software', title: 'Desarrollo de software', desc: 'Un líder técnico que reparte y aprueba, desarrollo que construye y QA que verifica.', members: [
|
|
740
|
+
['lider', 'Líder técnico', '', 'read', 'Reparte el trabajo, decide el enfoque y da el OK final. No implementa ni prueba.',
|
|
741
|
+
'Liderás. Repartí el trabajo en tareas con dueño, decidí el enfoque cuando haga falta (en pocas líneas) y seguí el avance. No implementás ni probás: delegás y controlás. Cuando QA aprueba, hacés el merge a main y cerrás.'],
|
|
742
|
+
['dev', 'Dev', 'lider', 'code', 'Implementa en su rama y entrega algo que corre. Las pruebas de verificación las hace QA.',
|
|
743
|
+
'Implementás lo que pide tu tarea, en tu rama. Antes de entregar comprobá que funciona: que corre, sin errores ni advertencias, y que lo que ya andaba sigue andando. Las pruebas de verificación las escribe QA: no las dupliques. Entregá con un commit y un mensaje corto a QA: qué cambiaste y dónde.'],
|
|
744
|
+
['qa', 'QA', 'lider', 'code', 'Verifica lo que entrega el Dev contra lo pedido: revisa, escribe y corre las pruebas.',
|
|
745
|
+
'Verificás lo que entrega el Dev contra lo pedido: revisá el cambio y escribí y corré las pruebas que lo comprueban. No arreglás el código: si algo falla, devolvéselo al Dev con qué falla y cómo reproducirlo. Cuando pasa, avisale al líder que está listo.']],
|
|
746
|
+
talks: [['dev', 'qa']] },
|
|
747
|
+
{ id: 'contenido', title: 'Contenido y marketing', desc: 'Un editor que planifica y aprueba, un redactor que escribe y un corrector que pule.', members: [
|
|
748
|
+
['editor', 'Editor', '', 'read', 'Planifica qué se publica, encarga cada pieza con un brief y aprueba. No redacta.',
|
|
749
|
+
'Editás. Decidí qué piezas hacen falta y encargalas con un brief corto: para quién es, qué tiene que lograr, tono y largo. Seguí el avance y aprobá cuando el corrector la dio por buena. No redactás ni corregís: delegás y controlás.'],
|
|
750
|
+
['redactor', 'Redactor', 'editor', 'code', 'Escribe las piezas según el brief: artículos, publicaciones, guiones, newsletters.',
|
|
751
|
+
'Escribís las piezas según el brief del editor, en archivos del proyecto. Basate en información real del proyecto, no inventes datos. Cuando terminás un borrador, pasáselo al corrector diciéndole dónde está.'],
|
|
752
|
+
['corrector', 'Corrector', 'editor', 'code', 'Revisa cada pieza: datos, claridad, tono, ortografía y SEO. Corrige lo puntual, no reescribe.',
|
|
753
|
+
'Revisás cada borrador: que los datos sean ciertos, que se entienda, el tono, la ortografía y lo básico de SEO. Corregí lo puntual vos mismo; si hace falta reescribir algo, devolvéselo al redactor con lo concreto. Cuando está bien, avisale al editor.']],
|
|
754
|
+
talks: [['redactor', 'corrector']] },
|
|
755
|
+
{ id: 'soporte', title: 'Base de conocimiento de soporte', desc: 'No atiende clientes: escribe lo que se usa para responderles (preguntas frecuentes, ayuda, respuestas modelo).', members: [
|
|
756
|
+
['coordinador', 'Coordinador', '', 'read', 'Decide qué falta documentar según las dudas frecuentes y el producto, reparte y aprueba.',
|
|
757
|
+
'Coordinás la base de conocimiento que usan las personas y los agentes que atienden clientes: preguntas frecuentes, artículos de ayuda y respuestas modelo. Decidí qué falta o qué quedó viejo (por las dudas frecuentes, los cambios del producto o lo que te pidan), encargalo con un brief corto y aprobá. No escribís los artículos.'],
|
|
758
|
+
['redactor', 'Redactor de ayuda', 'coordinador', 'code', 'Escribe preguntas frecuentes, artículos de ayuda y respuestas modelo, claros y paso a paso.',
|
|
759
|
+
'Escribís el material de ayuda: preguntas frecuentes, artículos paso a paso y respuestas modelo, en archivos del proyecto. Lenguaje simple, para alguien que no conoce el producto. Cuando terminás, pasáselo al verificador diciéndole dónde está.'],
|
|
760
|
+
['verificador', 'Verificador', 'coordinador', 'read', 'Comprueba contra el producto real que lo escrito sea cierto y esté al día.',
|
|
761
|
+
'Comprobás que lo que escribió el redactor sea cierto contra el producto real (su código, su configuración, su documentación) y que los pasos funcionen. No reescribís: si algo no coincide, devolvéselo al redactor con lo concreto. Cuando está bien, avisale al coordinador.']],
|
|
762
|
+
talks: [['redactor', 'verificador']] },
|
|
763
|
+
{ id: 'seguridad', title: 'Auditoría de seguridad', desc: 'Busca vulnerabilidades sin tocar el código y entrega un informe priorizado. Ideal como rutina semanal.', members: [
|
|
764
|
+
['jefe', 'Jefe de seguridad', '', 'code', 'Define qué se revisa, reparte y consolida un informe priorizado. No corrige el código.',
|
|
765
|
+
'Dirigís la auditoría. Definí el alcance (qué partes, qué cambió desde la última), repartilo y consolidá lo que encuentren en un informe priorizado por gravedad, con dónde está cada problema, por qué importa y cómo arreglarlo. Escribí el informe en un archivo con la fecha. No corregís el código ni lo hacen ellos: el informe es la entrega.'],
|
|
766
|
+
['codigo', 'Auditor de código', 'jefe', 'read', 'Revisa el código: entradas sin validar, inyecciones, autenticación, permisos, secretos.',
|
|
767
|
+
'Revisás el código buscando vulnerabilidades: entradas sin validar, inyecciones, autenticación y permisos, manejo de secretos, datos sensibles expuestos. Para cada hallazgo: dónde está (archivo y línea), qué tan grave, cómo se explota y cómo se arregla. Solo hallazgos reales, sin relleno. No tocás el código. Pasale los hallazgos al jefe.'],
|
|
768
|
+
['dependencias', 'Auditor de dependencias', 'jefe', 'read', 'Revisa dependencias, configuración y secretos en el repositorio.',
|
|
769
|
+
'Revisás las dependencias (versiones con vulnerabilidades conocidas, paquetes abandonados), la configuración (permisos, opciones inseguras, CI) y si hay secretos en el repositorio o en su historia. Usá las herramientas de auditoría que ya tenga el proyecto. Para cada hallazgo: dónde, qué tan grave y cómo se arregla. No tocás nada. Pasale los hallazgos al jefe.']],
|
|
770
|
+
talks: [['codigo', 'dependencias']] },
|
|
771
|
+
{ id: 'vacio', title: 'Un solo asiento', desc: 'Un líder que hace todo. Para probar, o para sumar asientos de a uno en el lienzo.', members: [['lider', 'Líder', '', 'code', 'Hace el trabajo y, si sumás asientos, coordina al resto.', 'Hacés el trabajo vos; si el equipo crece, repartilo y controlá.']], talks: [] },
|
|
772
|
+
];
|
|
773
|
+
function startNewTeam() { go(url.newTeam()); }
|
|
774
|
+
function draftFromTemplate(tpl, name, desc) {
|
|
775
|
+
// cada asiento, su propio agente: si el proyecto ya tiene uno con ese nombre (de otro equipo), este se llama
|
|
776
|
+
// <equipo>-<asiento>. Compartirlo arrastraba sus instrucciones viejas y su gasto del día (el tope es por agente):
|
|
777
|
+
// visto 2026-10-17, un equipo nuevo arrancó con todos «pasados de tope» y el CEO se asignó todo
|
|
778
|
+
const known = new Set([...(state.agents || []).map((a) => a.id), ...state.teams.flatMap((t) => t.members.map((m) => m.agent))]);
|
|
779
|
+
const ids = {}; tpl.members.forEach(([agent]) => { ids[agent] = known.has(agent) ? slugify(name).slice(0, 39 - agent.length).replace(/-+$/, '') + '-' + agent : agent; });
|
|
780
|
+
return { isNew: true, id: name, lead: ids[tpl.members[0][0]], description: desc || (tpl.id === 'vacio' ? '' : tpl.title), round_minutes: 0, budget_daily_tokens: 300000, worktrees: true, talks: tpl.talks.map(([x, y]) => [ids[x], ids[y]]),
|
|
781
|
+
members: tpl.members.map(([agent, role, boss, preset, d, how]) => ({ agent: ids[agent], role, reports_to: boss ? ids[boss] : '', description: d, system: `Sos ${role} del equipo. ${how || d}\n\n${WAYS}`, preset, permission: 'ask', dirty: true })) };
|
|
782
|
+
}
|
|
783
|
+
function wizardHtml() {
|
|
784
|
+
const w = state.wizard;
|
|
785
|
+
return `<div class="wcard"><h2>Un equipo nuevo</h2><p class="wlead">Elegí con qué empezar. Después sumás, quitás o reordenás asientos en el lienzo.</p>
|
|
786
|
+
<div class="tpls">${TEMPLATES.map((t) => `<label class="tpl${w.tpl === t.id ? ' on' : ''}"><input type="radio" name="tpl" value="${t.id}" ${w.tpl === t.id ? 'checked' : ''}><b>${esc(t.title)}</b><span class="tdesc2">${esc(t.desc)}</span><span class="troles">${t.members.map((m) => `<i>${esc(m[1])}</i>`).join('')}</span></label>`).join('')}</div>
|
|
787
|
+
<div class="wfoot"><label class="wname">Nombre del equipo <input id="wName" value="${esc(w.name)}" placeholder="por ejemplo: producto" autocomplete="off"><span id="wSlug">${w.name && slugify(w.name) !== w.name ? 'se guarda como ' + esc(slugify(w.name)) : 'como quieras: se guarda sin espacios ni acentos'}</span></label>
|
|
788
|
+
<label class="wname grow">Para qué es <input id="wDesc" value="${esc(w.desc)}" placeholder="una línea: qué hace este equipo" autocomplete="off"><span>opcional · lo podés cambiar después</span></label></div>
|
|
789
|
+
<div class="wacts"><button id="wCancel">Cancelar</button><button class="primary" id="wGo">Armar el equipo</button></div><p class="ferr" id="wErr"></p></div>`;
|
|
790
|
+
}
|
|
791
|
+
function bindWizard() {
|
|
792
|
+
const keep = () => { state.wizard.name = $('#wName').value; state.wizard.desc = $('#wDesc').value; };
|
|
793
|
+
document.querySelectorAll('input[name=tpl]').forEach((r) => (r.onchange = () => { keep(); state.wizard.tpl = r.value; $('#wizard').innerHTML = wizardHtml(); bindWizard(); }));
|
|
794
|
+
$('#wName').oninput = () => { keep(); const sl = slugify(state.wizard.name); $('#wSlug').textContent = state.wizard.name && sl !== state.wizard.name ? 'se guarda como ' + sl : 'como quieras: se guarda sin espacios ni acentos'; };
|
|
795
|
+
$('#wDesc').oninput = keep;
|
|
796
|
+
$('#wCancel').onclick = () => { state.wizard = null; go(url.list(), true); };
|
|
797
|
+
$('#wGo').onclick = () => {
|
|
798
|
+
const raw = $('#wName').value.trim(), name = slugify(raw);
|
|
799
|
+
if (!ID_OK.test(name)) { $('#wErr').textContent = 'Poné un nombre para el equipo (por ejemplo «producto»).'; return; }
|
|
800
|
+
if (state.teams.some((t) => t.id === name)) { $('#wErr').textContent = `Ya hay un equipo «${name}» en este proyecto.`; return; }
|
|
801
|
+
const tpl = TEMPLATES.find((t) => t.id === state.wizard.tpl);
|
|
802
|
+
try { localStorage.removeItem('lampson.flow:' + BASE + ':__nuevo'); } catch (e) {}
|
|
803
|
+
state.draft = draftFromTemplate(tpl, name, $('#wDesc').value.trim()); state.draft.name = raw; state.sel = null; state.wizard = null; renderTeams();
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
// ---------- borrador: el equipo (miembros + datos de sus agentes) que se guarda entero ----------
|
|
188
807
|
function draftFrom(team) {
|
|
189
|
-
return { isNew: false, id: team.id, description: team.description, round_minutes: team.round_minutes, budget_daily_tokens: team.budget_daily_tokens, worktrees: team.worktrees !== false, talks: (team.talks || []).map((p) => p.slice()),
|
|
190
|
-
members: team.members.map((m) => ({ agent: m.agent, role: m.role, reports_to: m.reports_to, description: m.description, system: m.system, preset: presetOf(m.tools), permission: m.permission || 'strict', dirty: false })) };
|
|
808
|
+
return { isNew: false, id: team.id, name: team.name || team.id, lead: team.lead || (team.members.find((m) => !m.reports_to) || team.members[0]).agent, description: team.description, round_minutes: team.round_minutes, budget_daily_tokens: team.budget_daily_tokens, worktrees: team.worktrees !== false, talks: (team.talks || []).map((p) => p.slice()),
|
|
809
|
+
members: team.members.map((m) => ({ agent: m.agent, role: m.role, reports_to: m.reports_to, daily_tokens: m.daily_tokens || 0, description: m.description, system: m.system, preset: presetOf(m.tools), permission: m.permission || 'strict', dirty: false })) };
|
|
191
810
|
}
|
|
192
811
|
function presetOf(tools) { const t = tools || []; if (!t.length) return 'none'; if (t.includes('write') || t.includes('edit')) return 'code'; return 'read'; }
|
|
193
|
-
function
|
|
194
|
-
|
|
195
|
-
|
|
812
|
+
function slugName() { return (BASE ? BASE.slice(3) : 'equipo').replace(/-[0-9a-f]{8}$/, '').replace(/[^a-z0-9-]/g, '').slice(0, 40) || 'equipo'; }
|
|
813
|
+
// «ante algo riesgoso»: a quién le pregunta depende del asiento — cadena de mando (lib/loop.syn): solo el líder te pregunta
|
|
814
|
+
// a vos; los demás se lo piden a su jefe, que lo hace o lo sube hasta el líder
|
|
815
|
+
const permsFor = (lead, bossRole) => [['strict', 'no lo hace'], ['ask', lead ? 'te pregunta a vos' : 'se lo pide a su jefe' + (bossRole ? ' (' + bossRole + ')' : '')], ['yolo', 'lo hace sin preguntar']];
|
|
816
|
+
// la barra del equipo (debajo de la cabecera). Viendo: cuál, para qué y qué hacer; editando: nombre, para qué y guardar
|
|
817
|
+
// debajo del nombre: cómo se guarda (nuevo) o la clave que no cambia (uno que ya existe)
|
|
818
|
+
const slugNote = (d) => d.isNew ? (d.name && slugify(d.name) !== d.name ? 'se guarda como ' + esc(slugify(d.name)) : '') : (d.name !== d.id ? 'clave interna: ' + esc(d.id) + ' (no cambia)' : '');
|
|
819
|
+
// un «?» que despliega una explicación corta (se cierra con otro clic, afuera o con Escape)
|
|
820
|
+
const help = (text) => `<details class="qhelp"><summary aria-label="¿qué es?">?</summary><p>${esc(text)}</p></details>`;
|
|
821
|
+
function subbarHtml() {
|
|
822
|
+
const d = state.draft, team = state.teams.find((t) => t.id === state.team);
|
|
823
|
+
if (d) return `<div class="tsub-l"><button type="button" class="back" id="eBack" title="volver sin guardar">← ${esc(d.isNew ? 'Equipos' : teamName(d.id))}</button><div class="namebox"><label class="inl">Nombre <input id="eId" value="${esc(d.name ?? d.id)}" placeholder="producto" size="18" autocomplete="off"></label><span class="slug" id="eSlug">${slugNote(d)}</span></div>
|
|
824
|
+
<label class="inl grow">Para qué es <input id="eDesc" value="${esc(d.description)}" placeholder="una línea: qué hace este equipo"></label>
|
|
825
|
+
<details class="advpop"><summary>Opciones</summary><div class="advgrid">
|
|
826
|
+
<div class="opt"><div class="oh"><label for="eRound">Rondas automáticas cada</label>${help('Cada cuánto un asiento retoma por su cuenta lo que tiene pendiente —sus tareas del tablero o novedades que lo involucran— aunque nadie le escriba. Los mensajes y los objetivos le llegan igual, al momento. Más seguido avanza más rápido, pero gasta más.')}</div>
|
|
827
|
+
<span class="unit"><input id="eRound" type="number" min="0" value="${d.round_minutes}"> min</span><span class="ds">0 = sin rondas: trabajan cuando les llega un objetivo o un mensaje</span></div>
|
|
828
|
+
<div class="opt"><div class="oh"><label for="eBudget">Gasto máximo por asiento, por día</label>${help('Cuántos tokens puede usar cada asiento en un día. Al llegar al tope no recibe más turnos hasta el día siguiente, y queda anotado en el registro. Sirve para que un equipo no gaste de más si algo se traba.')}</div>
|
|
829
|
+
<span class="unit"><input id="eBudget" type="number" min="0" step="10000" value="${d.budget_daily_tokens}"> tokens</span><span class="ds">0 = sin tope</span></div>
|
|
830
|
+
<div class="opt"><div class="oh"><label class="chk"><input id="eWt" type="checkbox" ${d.worktrees ? 'checked' : ''}> Cada asiento en su propia copia de git</label>${help('Si el proyecto usa git, cada asiento trabaja en su rama y en su propia copia de los archivos: nadie pisa el trabajo de otro. Llevar los cambios a la rama principal lo hace el líder, con tu aprobación.')}</div></div>
|
|
831
|
+
${d.isNew ? '' : deleteBoxHtml(d)}
|
|
832
|
+
</div></details></div>
|
|
833
|
+
<div class="tsub-r"><span class="ferr" id="eErr"></span><button id="eCancel">${d.isNew ? 'Descartar' : 'Cancelar'}</button><button class="primary" id="eSave">${d.isNew ? 'Crear equipo' : 'Guardar cambios'}</button></div>`;
|
|
834
|
+
return '';
|
|
196
835
|
}
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
836
|
+
// borrar el equipo: dos pasos, diciendo antes qué pasa con lo suyo (lib/api.syn → delete_team)
|
|
837
|
+
function deleteBoxHtml(d) {
|
|
838
|
+
const open = state.objectives.filter((o) => o.team === d.id && OPEN_OBJ.includes(o.status)).length, rts = state.routines.filter((r) => r.action.team === d.id).length;
|
|
839
|
+
// sus agentes se van con él (se crearon para este equipo); solo queda el que también está en otro equipo
|
|
840
|
+
const shared = d.members.map((m) => [m, state.teams.find((t) => t.id !== d.id && t.members.some((x) => x.agent === m.agent))]).filter(([, t]) => t);
|
|
841
|
+
const own = d.members.length - shared.length;
|
|
842
|
+
const what = [own ? `se borra${own === 1 ? '' : 'n'} ${own === 1 ? 'su agente' : 'sus ' + own + ' agentes'}` : '', open ? `se cancela${open === 1 ? '' : 'n'} ${open} objetivo${open === 1 ? '' : 's'} en curso` : '', rts ? `se borra${rts === 1 ? '' : 'n'} ${rts} rutina${rts === 1 ? '' : 's'}` : ''].filter(Boolean);
|
|
843
|
+
const said = what.length ? what.slice(0, -1).join(', ') + (what.length > 1 ? ' y ' : '') + what[what.length - 1] : '';
|
|
844
|
+
return `<div class="opt danger"><div class="oh"><b>Eliminar este equipo</b></div>
|
|
845
|
+
<p class="ds">${said ? said[0].toUpperCase() + said.slice(1) + '. ' : ''}${shared.length ? shared.map(([m, t]) => `${esc(m.role || m.agent)} queda porque también está en «${esc(t.name || t.id)}». `).join('') : ''}El historial de sus objetivos queda, y el trabajo que no llegó a la rama principal queda guardado en ramas <code>archive/</code>. Un equipo nuevo con el mismo nombre arranca de cero.</p>
|
|
846
|
+
<button type="button" class="no" id="eDelete">Eliminar equipo</button></div>`;
|
|
201
847
|
}
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
<
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
848
|
+
// ---------- la lista: una tarjeta por equipo del proyecto, y «+ nuevo equipo» ----------
|
|
849
|
+
// la tarjeta de un equipo: quién es y tres puertas (objetivos, rutinas, editar). Lo único que se ve sin entrar es si
|
|
850
|
+
// algo te espera; los números salen de lo que la pantalla ya tiene cargado (no suma pedidos)
|
|
851
|
+
function teamCardHtml(t) {
|
|
852
|
+
const lead = t.lead || (t.members.find((m) => !m.reports_to) || t.members[0] || {}).agent;
|
|
853
|
+
const roles = [...t.members].sort((a, b) => (b.agent === lead) - (a.agent === lead));
|
|
854
|
+
const mine = (state.objectives || []).filter((o) => o.team === t.id), waiting = mine.filter((o) => o.status === 'waiting').length;
|
|
855
|
+
const working = t.members.some((m) => m.working), rts = state.routines.filter((r) => r.action.team === t.id).length;
|
|
856
|
+
const cnt = (n) => (n ? ` <span class="cnt">${n}</span>` : '');
|
|
857
|
+
return `<article class="tcard3" data-team="${esc(t.id)}" tabindex="0" title="ver sus objetivos y rutinas">
|
|
858
|
+
<div class="thead"><h3>${esc(t.name || t.id)}</h3>${waiting ? `<span class="tw wait">⚑ te espera${waiting > 1 ? 'n ' + waiting : ''}</span>` : working ? '<span class="tw">● trabajando</span>' : ''}</div>
|
|
859
|
+
${t.description ? `<p class="tdesc">${esc(t.description)}</p>` : ''}
|
|
860
|
+
<div class="roles">${roles.map((m) => `<span class="role${m.agent === lead ? ' lead' : ''}${m.working ? ' on' : ''}" title="${esc(m.agent)}${m.agent === lead ? ' · líder' : ''}">${esc(m.role || m.agent)}</span>`).join('')}</div>
|
|
861
|
+
<div class="tacts"><a class="btn primary" data-nav href="${esc(url.team(t.id))}">Objetivos${cnt(mine.length)}</a><a class="btn" data-nav href="${esc(url.team(t.id))}#rutinas">Rutinas${cnt(rts)}</a><a class="btn" data-nav href="${esc(url.edit(t.id))}">Editar</a></div>
|
|
862
|
+
</article>`;
|
|
863
|
+
}
|
|
864
|
+
function listHtml() {
|
|
865
|
+
const proj = BASE ? BASE.slice(3).replace(/-[0-9a-f]{8}$/, '') : 'este proyecto';
|
|
866
|
+
return `<div class="tlhead"><h2>Equipos de ${esc(proj)}</h2><p>Cada equipo es un grupo de asientos con un líder. Un proyecto puede tener varios: uno que programa, otro que escribe, otro que atiende.</p></div>
|
|
867
|
+
<div class="tgrid3">${state.teams.map(teamCardHtml).join('')}
|
|
868
|
+
<button type="button" class="tnew" id="newTeamCard"><span class="plus">+</span><b>Nuevo equipo</b><span>Elegí una plantilla o empezá con un solo asiento.</span></button></div>
|
|
869
|
+
`;
|
|
870
|
+
}
|
|
871
|
+
function bindList() {
|
|
872
|
+
$('#newTeamCard').onclick = () => go(url.newTeam());
|
|
873
|
+
document.querySelectorAll('.tcard3').forEach((c) => {
|
|
874
|
+
const open = () => go(url.team(c.dataset.team));
|
|
875
|
+
c.onclick = (e) => { if (e.target.closest('button, a')) return; open(); };
|
|
876
|
+
c.onkeydown = (e) => { if (e.key === 'Enter' && e.target === c) open(); };
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
// al tocar un asiento, editando: su tarjeta de edición, dentro del lienzo
|
|
880
|
+
function inspectorHtml() {
|
|
881
|
+
const d = state.draft; const m = d && d.members.find((x) => x.agent === state.sel);
|
|
882
|
+
if (!m) return '';
|
|
883
|
+
const L = d.lead, others = d.members.filter((x) => x !== m);
|
|
884
|
+
const below = new Set(); const walk = (a) => d.members.filter((x) => x.reports_to === a).forEach((x) => { below.add(x.agent); walk(x.agent); }); walk(m.agent);
|
|
885
|
+
const talksWith = d.talks.filter((p) => p.includes(m.agent)).map((p) => (p[0] === m.agent ? p[1] : p[0]));
|
|
886
|
+
// con quién más puede hablar: todos menos su jefe y los que le reportan (con ellos ya habla); primero los de su nivel
|
|
887
|
+
const cand = others.filter((x) => x.agent !== m.reports_to && x.reports_to !== m.agent).sort((a, b) => (b.reports_to === m.reports_to && !!m.reports_to) - (a.reports_to === m.reports_to && !!m.reports_to));
|
|
888
|
+
return `<div class="ihead"><h3>${esc(m.role || m.agent)}</h3>${m.agent === L ? '<span class="fl-lead">líder</span>' : ''}<button type="button" class="iclose" id="mClose" title="cerrar">✕</button></div>
|
|
889
|
+
<label>Rol <input id="mRole" value="${esc(m.role)}" placeholder="CTO"></label>
|
|
890
|
+
<label>Para qué está <input id="mDesc" value="${esc(m.description)}" placeholder="una línea"></label>
|
|
891
|
+
${m.agent === L ? '<p class="ds">Es el líder: recibe los objetivos, reparte el trabajo y es el único que te pregunta a vos. Si está solo, lo hace todo.</p>' : `<label>Le reporta a <select id="mBoss"><option value="" ${m.reports_to ? '' : 'selected'}>nadie por ahora (al guardar, al líder)</option>${others.filter((x) => !below.has(x.agent)).map((x) => `<option value="${esc(x.agent)}" ${x.agent === m.reports_to ? 'selected' : ''}>${esc(x.role || x.agent)}${x.agent === L ? ' (líder)' : ''}</option>`).join('')}</select></label>`}
|
|
892
|
+
<label>Qué puede hacer <select id="mPreset">${PRESETS.map(([v, l]) => `<option value="${v}" ${v === m.preset ? 'selected' : ''}>${l}</option>`).join('')}</select></label>
|
|
893
|
+
<label>Ante algo riesgoso <select id="mPerm">${permsFor(m.agent === L, m.reports_to && (d.members.find((x) => x.agent === m.reports_to) || {}).role).map(([v, l]) => `<option value="${v}" ${v === m.permission ? 'selected' : ''}>${l}</option>`).join('')}</select>
|
|
894
|
+
<span class="ds">${m.agent === L ? 'Es el único del equipo que te consulta a vos.' : 'Nunca te pregunta a vos: si su jefe no puede decidirlo, sube hasta el líder, que es el único que te consulta.'}</span></label>
|
|
895
|
+
<label>Tope diario de tokens <span class="unit"><input id="mCap" type="number" min="0" step="50000" value="${m.daily_tokens || ''}" placeholder="el del equipo: ${esc(k(d.budget_daily_tokens || 0))}"> tokens</span>
|
|
896
|
+
<span class="ds">${(() => { const live = (teamOf(d.id) || { members: [] }).members.find((x) => x.agent === m.agent); return live ? `Hoy lleva ${k(live.spent_today || 0)}. ` : ''; })()}Vacío = el del equipo (en Opciones). Ponele más al que más trabaja.</span></label>
|
|
897
|
+
<label>Cómo trabaja <textarea id="mSys" rows="4" placeholder="Sos el CTO: decidís cómo se construye, revisás el código de los demás…">${esc(m.system)}</textarea></label>
|
|
898
|
+
${cand.length ? `<div class="talkbox"><div class="lbl">También habla con</div><div class="chips">${cand.map((x) => `<label class="chip"><input type="checkbox" data-talk="${esc(x.agent)}" ${talksWith.includes(x.agent) ? 'checked' : ''}>${esc(x.role || x.agent)}</label>`).join('')}</div><p class="ds">La línea punteada. Se propone sola al unir dos asientos bajo el mismo jefe; sacala si no hace falta.</p></div>` : ''}
|
|
899
|
+
<details class="adv"><summary>Nombre interno</summary><label><input id="mId" value="${esc(m.agent)}"><span class="ds">el id del agente (se guarda sin espacios ni acentos)</span></label></details>
|
|
900
|
+
<div class="acts">${m.agent === L ? '' : '<button id="mLead">Hacer líder</button><button class="no" id="mDel">Eliminar asiento</button>'}</div>`;
|
|
228
901
|
}
|
|
229
902
|
function bindEditor() {
|
|
230
903
|
const d = state.draft; const m = d.members.find((x) => x.agent === state.sel);
|
|
231
904
|
const on = (id, ev, fn) => { const e = $(id); if (e) e[ev] = fn; };
|
|
232
|
-
|
|
905
|
+
// un equipo nuevo toma su clave del nombre; uno que ya existe cambia solo el nombre visible (la clave no se toca)
|
|
906
|
+
on('#eId', 'oninput', (e) => { d.name = e.target.value; if (d.isNew) d.id = slugify(d.name); $('#eSlug').innerHTML = slugNote(d); });
|
|
233
907
|
on('#eDesc', 'oninput', (e) => (d.description = e.target.value));
|
|
234
908
|
on('#eRound', 'oninput', (e) => (d.round_minutes = +e.target.value || 0));
|
|
235
909
|
on('#eBudget', 'oninput', (e) => (d.budget_daily_tokens = +e.target.value || 0));
|
|
236
910
|
on('#eWt', 'onchange', (e) => (d.worktrees = e.target.checked));
|
|
237
|
-
|
|
238
|
-
|
|
911
|
+
const del = $('#eDelete');
|
|
912
|
+
if (del) del.onclick = async () => {
|
|
913
|
+
if (!del.dataset.sure) { del.dataset.sure = '1'; del.textContent = `¿Seguro? Eliminar «${d.name || d.id}»`; return; }
|
|
914
|
+
del.disabled = true; del.textContent = 'eliminando…';
|
|
915
|
+
const r = await api('teams/delete', { id: d.id, agents: true });
|
|
916
|
+
if (!r.ok) { del.disabled = false; del.textContent = 'Eliminar equipo'; delete del.dataset.sure; $('#eErr').textContent = 'No se pudo eliminar: ' + ((r.data && r.data.error) || r.error || ''); return; }
|
|
917
|
+
try { localStorage.removeItem('lampson.flow:' + BASE + ':' + d.id); } catch (e) {}
|
|
918
|
+
state.draft = null; await refresh(); go(url.list(), true);
|
|
919
|
+
};
|
|
920
|
+
const leave = () => { const back = d.isNew ? url.list() : url.team(d.id); state.draft = null; state.sel = null; go(back, true); };
|
|
921
|
+
on('#eCancel', 'onclick', leave);
|
|
922
|
+
on('#eBack', 'onclick', leave);
|
|
239
923
|
on('#eSave', 'onclick', saveDraft);
|
|
924
|
+
on('#addSeat', 'onclick', () => addSeat());
|
|
240
925
|
if (!m) return;
|
|
241
926
|
const touch = () => (m.dirty = true);
|
|
242
|
-
on('#
|
|
243
|
-
on('#
|
|
244
|
-
on('#
|
|
245
|
-
on('#
|
|
927
|
+
on('#mClose', 'onclick', () => { state.sel = null; renderTeams(); });
|
|
928
|
+
on('#mId', 'onchange', (e) => { const v = slugify(e.target.value); if (!ID_OK.test(v) || d.members.some((x) => x !== m && x.agent === v)) { e.target.value = m.agent; return; } d.members.forEach((x) => { if (x.reports_to === m.agent) x.reports_to = v; }); d.talks = d.talks.map((p) => p.map((a) => (a === m.agent ? v : a))); if (d.lead === m.agent) d.lead = v; m.agent = v; state.sel = v; touch(); renderTeams(); });
|
|
929
|
+
on('#mRole', 'oninput', (e) => { m.role = e.target.value; touch(); renderGraph(); });
|
|
930
|
+
on('#mRole', 'onchange', () => renderTeams());
|
|
931
|
+
on('#mDesc', 'oninput', (e) => { m.description = e.target.value; touch(); renderGraph(); });
|
|
932
|
+
on('#mBoss', 'onchange', (e) => { if (e.target.value) connectDraft(e.target.value, m.agent); else { m.reports_to = ''; renderTeams(); } });
|
|
246
933
|
on('#mSys', 'oninput', (e) => { m.system = e.target.value; touch(); });
|
|
247
|
-
on('#
|
|
934
|
+
on('#mCap', 'oninput', (e) => (m.daily_tokens = Math.max(0, +e.target.value || 0)));
|
|
935
|
+
on('#mPreset', 'onchange', (e) => { m.preset = e.target.value; touch(); renderGraph(); });
|
|
248
936
|
on('#mPerm', 'onchange', (e) => { m.permission = e.target.value; touch(); });
|
|
249
|
-
on('#
|
|
250
|
-
|
|
937
|
+
on('#mLead', 'onclick', () => makeLeader(m.agent));
|
|
938
|
+
on('#mDel', 'onclick', () => removeSeat(m.agent));
|
|
939
|
+
document.querySelectorAll('[data-talk]').forEach((c) => (c.onchange = () => { const o = c.dataset.talk; d.talks = d.talks.filter((p) => !(p.includes(o) && p.includes(m.agent))); if (c.checked) d.talks.push([m.agent, o]); renderTeams(); }));
|
|
251
940
|
}
|
|
252
941
|
async function saveDraft() {
|
|
253
|
-
const d = state.draft;
|
|
254
|
-
|
|
942
|
+
const d = state.draft; normalize(d);
|
|
943
|
+
if (!ID_OK.test(d.id || '') || !String(d.name ?? d.id).trim()) { $('#eErr').textContent = 'Poné un nombre para el equipo (por ejemplo «producto»).'; return; }
|
|
944
|
+
if (d.isNew && state.teams.some((t) => t.id === d.id)) { $('#eErr').textContent = `Ya hay un equipo «${d.id}» en este proyecto: elegí otro nombre.`; return; }
|
|
945
|
+
// los sueltos le reportan al líder; el líder va primero (lib/teams.syn → lead_of: el primero que no reporta a nadie)
|
|
946
|
+
d.members.forEach((m) => { if (loose(d, m)) m.reports_to = d.lead; });
|
|
947
|
+
const ordered = [d.members.find((m) => m.agent === d.lead), ...d.members.filter((m) => m.agent !== d.lead)];
|
|
948
|
+
const body = { team: { id: d.id, name: String(d.name ?? d.id).trim(), description: d.description, members: ordered.map((m) => ({ agent: m.agent, role: m.role || m.agent, reports_to: m.reports_to, daily_tokens: m.daily_tokens || 0 })), talks: d.talks, round_minutes: d.round_minutes, budget_daily_tokens: d.budget_daily_tokens, worktrees: d.worktrees },
|
|
255
949
|
agents: d.members.filter((m) => m.dirty || m.system).map((m) => ({ id: m.agent, description: m.description, system: m.system || `Sos ${m.role || m.agent} del equipo ${d.id}.`, preset: m.preset, permission: m.permission })) };
|
|
256
950
|
const r = await api('teams/save', body);
|
|
257
951
|
if (!r.ok) { $('#eErr').textContent = r.data.error || 'no se pudo guardar'; return; }
|
|
258
|
-
|
|
259
|
-
|
|
952
|
+
// las posiciones del borrador pasan a ser las del equipo
|
|
953
|
+
if (d.isNew) { try { const k0 = 'lampson.flow:' + BASE + ':__nuevo', v = localStorage.getItem(k0); if (v) localStorage.setItem('lampson.flow:' + BASE + ':' + d.id, v); localStorage.removeItem(k0); } catch (e) {} }
|
|
954
|
+
// guardado: de vuelta a la lista, con la tarjeta al día
|
|
955
|
+
state.draft = null; state.sel = null; state.teams = r.data.teams;
|
|
956
|
+
go(url.team(d.id), true);
|
|
260
957
|
}
|
|
261
958
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
if (
|
|
270
|
-
if (
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
959
|
+
document.addEventListener('pointerdown', (e) => document.querySelectorAll('details.advpop[open], details.qhelp[open]').forEach((d) => { if (!d.contains(e.target)) d.open = false; }));
|
|
960
|
+
document.addEventListener('keydown', (e) => { if (e.key === 'Escape') document.querySelectorAll('details.advpop[open], details.qhelp[open]').forEach((d) => (d.open = false)); });
|
|
961
|
+
// ---------- la página de la ruta ----------
|
|
962
|
+
function route() {
|
|
963
|
+
state.route = parseRoute(); const r = state.route;
|
|
964
|
+
if (r.page !== 'edit' && r.page !== 'newteam') { state.draft = null; state.sel = null; }
|
|
965
|
+
if (r.page === 'edit' && state.draft && state.draft.id !== r.team) state.draft = null;
|
|
966
|
+
if (r.page === 'newteam' && !state.draft && !state.wizard) state.wizard = { tpl: 'software', name: '', desc: '' };
|
|
967
|
+
if (r.page !== 'newteam') state.wizard = null;
|
|
968
|
+
const fkey = r.form ? r.team + ':' + r.form : '';
|
|
969
|
+
if (fkey && (!state.form || state.form.team !== r.team)) state.form = { team: r.team, text: '', freq: 'daily', at: '09:00', every: 6, days: ['mon'], budget: 600000 };
|
|
970
|
+
if (!fkey) state.form = null;
|
|
971
|
+
state.formKey = null; state.drawer = null; state.liveKey = null;
|
|
972
|
+
$('#objDetail').classList.remove('lvmode'); $('#objDrawer').hidden = true;
|
|
973
|
+
render();
|
|
974
|
+
if (r.page === 'obj') loadObj();
|
|
975
|
+
// …/equipos/<equipo>#rutinas: directo a esa sección; si no, arriba de todo
|
|
976
|
+
const anchor = location.hash && document.getElementById(location.hash.slice(1));
|
|
977
|
+
if (anchor) anchor.scrollIntoView({ block: 'start' }); else { window.scrollTo(0, 0); document.querySelectorAll('.tlist').forEach((x) => (x.scrollTop = 0)); }
|
|
978
|
+
}
|
|
979
|
+
// light: el pulso — repinta las páginas de lectura (lista, equipo, rutina) sin tocar formularios ni el lienzo
|
|
980
|
+
function render(light) {
|
|
981
|
+
const r = state.route;
|
|
982
|
+
renderCrumbs();
|
|
983
|
+
if (r.page === 'edit' && !state.draft) { const t = teamOf(r.team); if (t) state.draft = draftFrom(t); }
|
|
984
|
+
if (r.page === 'edit' && state.draft && state.selWanted) { if (state.draft.members.some((m) => m.agent === state.selWanted)) state.sel = state.selWanted; state.selWanted = null; }
|
|
985
|
+
const d = state.draft, editing = (r.page === 'edit' || r.page === 'newteam') && !!d, listing = r.page === 'list' || (r.page === 'newteam' && !d);
|
|
986
|
+
$('#tlist').hidden = !listing; $('#tpage').hidden = r.page !== 'team'; $('#rpage').hidden = r.page !== 'routine'; $('#opage').hidden = r.page !== 'obj'; $('#tedit').hidden = !editing;
|
|
987
|
+
const loaded = state.loaded;
|
|
988
|
+
if (listing) { $('#tlist').innerHTML = listHtml(); bindList(); }
|
|
989
|
+
if (r.page === 'team') {
|
|
990
|
+
const t = teamOf(r.team);
|
|
991
|
+
$('#tpage').innerHTML = t ? teamPageHtml(t) : loaded ? `<div class="oempty">No hay un equipo «${esc(r.team)}» en este proyecto. <a data-nav href="${esc(url.list())}">Ver los equipos</a></div>` : '';
|
|
992
|
+
const dn = $('#tpage details.done'); if (dn) dn.ontoggle = () => (state.doneOpen = dn.open);
|
|
275
993
|
}
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
994
|
+
if (r.page === 'routine') {
|
|
995
|
+
const rt = state.routines.find((x) => x.id === r.routine);
|
|
996
|
+
if (!(light && $('#rpage').contains(document.activeElement) && document.activeElement.id === 'rtDel')) {
|
|
997
|
+
$('#rpage').innerHTML = rt ? routinePageHtml(rt) : loaded ? `<div class="oempty">Esa rutina ya no existe. <a data-nav href="${esc(url.team(r.team))}">Volver al equipo</a></div>` : '';
|
|
998
|
+
if (rt) bindRoutinePage(rt);
|
|
999
|
+
}
|
|
1000
|
+
}
|
|
1001
|
+
if (light) return;
|
|
1002
|
+
// las plantillas (equipo nuevo) y el formulario de objetivo o rutina: encima de la página
|
|
1003
|
+
const wz = $('#wizard'); wz.hidden = !state.wizard;
|
|
1004
|
+
if (state.wizard) { wz.innerHTML = wizardHtml(); bindWizard(); }
|
|
1005
|
+
const fo = $('#objNew'), fkey = r.form ? r.team + ':' + r.form : '';
|
|
1006
|
+
fo.hidden = !fkey;
|
|
1007
|
+
if (fkey && state.formKey !== fkey) { const t = teamOf(r.team); if (t) { state.formKey = fkey; fo.innerHTML = objFormHtml(t, r.form); bindObjForm(t, r.form); } }
|
|
1008
|
+
// el lienzo
|
|
1009
|
+
$('#tsub').innerHTML = editing ? subbarHtml() : '';
|
|
1010
|
+
$('#ovAdd').innerHTML = editing ? `<button class="primary" id="addSeat">+ asiento</button><span class="ahint">Arrastrá el punto de abajo hasta otro asiento: ese le reporta.</span>` : '';
|
|
1011
|
+
const insp = $('#inspector'); insp.hidden = !(editing && state.sel); insp.innerHTML = insp.hidden ? '' : inspectorHtml();
|
|
1012
|
+
if (editing) { renderGraph(); bindEditor(); } else state.lastMode = 'list';
|
|
280
1013
|
}
|
|
1014
|
+
const renderTeams = () => render();
|
|
281
1015
|
async function refreshTeams() {
|
|
282
1016
|
const r = await api('teams');
|
|
283
1017
|
if (!r.ok) return false;
|
|
284
1018
|
state.teams = r.data.teams;
|
|
285
|
-
// ?edit=<equipo> abre el editor de ese equipo (enlaces directos, capturas)
|
|
286
|
-
const ed = new URLSearchParams(location.search).get('edit');
|
|
287
|
-
if (ed && !state.editOpened) { state.editOpened = true; const t = state.teams.find((x) => x.id === ed); if (t) { state.team = t.id; state.draft = draftFrom(t); state.sel = t.lead || t.members[0].agent; renderTeams(); return true; } }
|
|
288
|
-
if (state.draft) return true; // editando: el pulso no pisa el formulario
|
|
289
|
-
renderTeams();
|
|
290
1019
|
return true;
|
|
291
1020
|
}
|
|
292
1021
|
|
|
293
1022
|
// ---------- pulso ----------
|
|
294
1023
|
async function refresh() {
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
1024
|
+
const ok = (await Promise.all([refreshObjectives(), refreshTeams(), refreshRoutines()])).every(Boolean);
|
|
1025
|
+
state.loaded = true;
|
|
1026
|
+
render(true);
|
|
1027
|
+
if (state.route.page === 'obj') await loadObj();
|
|
298
1028
|
$('#live').classList.toggle('off', !ok);
|
|
299
1029
|
}
|
|
300
|
-
|
|
1030
|
+
legacyRedirect();
|
|
1031
|
+
state.route = parseRoute();
|
|
1032
|
+
renderCrumbs();
|
|
1033
|
+
refresh().then(route);
|
|
301
1034
|
setInterval(refresh, 2500);
|