File size: 42,155 Bytes
4b138b2
9ceefcc
 
4b138b2
 
 
520c7b3
4b138b2
 
 
 
 
 
0181506
4b138b2
 
cb8b80f
4b138b2
 
f8253b7
4b138b2
cb8b80f
4b138b2
 
 
 
0181506
4b138b2
 
f8253b7
 
 
4b138b2
0181506
 
 
 
 
4b138b2
 
 
 
 
f8253b7
4b138b2
f8253b7
4b138b2
 
 
 
 
36de25c
4b138b2
 
 
 
 
 
 
36de25c
 
 
 
 
 
 
 
f8253b7
 
 
 
 
 
 
4b138b2
f8253b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b138b2
 
 
 
 
 
 
450c3f0
36de25c
4b138b2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb8b80f
 
 
 
 
 
 
4b138b2
cb8b80f
 
 
 
 
 
 
d00d60c
 
 
 
8da270f
d00d60c
 
 
 
 
61657d1
d61000f
 
d00d60c
 
 
 
 
 
cb8b80f
 
 
d00d60c
cb8b80f
d00d60c
cb8b80f
 
 
d00d60c
 
cb8b80f
d00d60c
cb8b80f
 
 
 
 
 
 
 
4b138b2
 
cb8b80f
e73dcb3
cb8b80f
 
 
 
 
 
 
 
 
450c3f0
cb8b80f
 
450c3f0
1c96c02
0785b5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
450c3f0
cb8b80f
 
 
 
 
 
 
 
 
450c3f0
cb8b80f
450c3f0
 
cb8b80f
 
 
 
450c3f0
 
 
 
cb8b80f
450c3f0
cb8b80f
 
 
 
 
 
450c3f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e73dcb3
01a57e0
450c3f0
4b138b2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
// STUDIUS empire backbone (frontend): HF sign-in, Workspace (user's HF Bucket), asset bus hand-off, bee agent dock.
import { MODULES, refreshQuota } from './real.js?v=136';
import { Avatars } from './avatar.js?v=136';
const $ = (s, r = document) => r.querySelector(s);
const esc = (t) => String(t ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const ST = () => window.__studius.STUDIOS;
const kindOf = (mime = '', name = '') => /(^|\/|\.)avatar\.json$/i.test(name) ? 'avatar' : /^image\//.test(mime) || /\.(png|jpe?g|webp|gif)$/i.test(name) ? 'image' : /^audio\//.test(mime) || /\.(wav|mp3|ogg|flac)$/i.test(name) ? 'audio' : /^video\//.test(mime) || /\.(mp4|webm|mov)$/i.test(name) ? 'video' : /^text\/|json/.test(mime) || /\.(txt|md|json|js|html|css)$/i.test(name) ? 'text' : 'file';
const W = { backend: false, me: null, bucket: localStorage.getItem('studius-bucket') || '' };
window.__ws = W;
async function api(path, opt = {}) { const r = await fetch(path, { credentials: 'include', ...opt }); const j = r.headers.get('content-type')?.includes('json') ? await r.json() : null; if (!r.ok) throw new Error(j?.detail || j?.error || r.status + ' ' + r.statusText); return j; }
const form = (o) => { const f = new FormData(); Object.entries(o).forEach(([k, v]) => f.append(k, v)); return f; };

/* HUD buttons */
$('#hud .hudr').insertAdjacentHTML('afterbegin', `<a id="signin" class="hbtn" href="/login" target="_blank" rel="noopener" hidden>🤗<span class="t"> Sign in with Hugging Face</span><span class="s"> Login</span></a><span id="quota" class="hbtn q" hidden title="Deine ZeroGPU-Quota"></span><button id="bkchip" class="hbtn" aria-label="Workspace-Bucket wechseln" hidden></button><button id="wsbtn" class="hbtn" aria-label="Workspace öffnen" hidden>▤<span class="t"> Workspace</span></button><span id="who" hidden></span>`);
document.body.insertAdjacentHTML('beforeend', `<aside id="wsp" hidden role="dialog" aria-label="Workspace"><div class="wh"><b>WORKSPACE</b><small id="wsb"></small><button class="x" aria-label="Workspace schließen">✕</button></div><div class="wbody"></div></aside>
<button id="beebtn" aria-label="Bee-Agenten öffnen" title="Bee-Agenten">🐝<span>Agents</span></button>
<aside id="bees" hidden role="dialog" aria-label="Bee-Agenten"><div class="wh"><b>BEE AGENTS</b><select id="agsel" aria-label="Agent wählen"></select><button class="x" aria-label="Agenten schließen">✕</button></div><div class="agcfg"></div><div class="blog" aria-live="polite"></div><details class="jw"><summary>Jobs (Server)</summary><div class="jobs"></div></details><div class="brow"><input id="bin" aria-label="Auftrag an Agent" placeholder="Auftrag… z.B. 'Male eine goldene Biene'"><button class="btn" id="bsend" aria-label="Senden">➤</button></div></aside>`);
['#wsp', '#bees'].forEach(s => $(s).addEventListener('keydown', e => { e.stopPropagation(); if (e.key === 'Escape') $(s).hidden = true; }));
$('#wsp .x').onclick = () => $('#wsp').hidden = true; $('#bees .x').onclick = () => $('#bees').hidden = true;
$('#bkchip').onclick = () => { $('#wsp').hidden = false; W.pick = true; renderWS(); };
$('#wsbtn').onclick = () => { $('#wsp').hidden = !$('#wsp').hidden; if (!$('#wsp').hidden) renderWS(); };
$('#beebtn').onclick = () => { $('#bees').hidden = !$('#bees').hidden; if (!$('#bees').hidden) { renderAgents(true).then(renderJobs); $('#bin').focus(); } };

async function refreshMe() {
  try { W.me = await api('/api/me'); W.backend = true; } catch (e) { W.backend = false; W.me = null; }
  $('#signin').hidden = !W.backend || !!W.me?.signedIn || !W.me?.oauth; $('#wsbtn').hidden = !W.backend;
  hudBucket(); if (W.me?.signedIn) { loadBuckets().catch(() => {}); refreshQuota(); } else $('#quota').hidden = true;
  const who = $('#who'); who.hidden = !W.me?.signedIn; if (W.me?.signedIn) who.innerHTML = `${W.me.user.avatar ? `<img src="${esc(W.me.user.avatar)}" alt="">` : ''}${esc(W.me.user.name)}`;
}
const fresh = /signedin=1/.test(location.search); if (fresh) history.replaceState(null, '', '/');
let wasIn = null; const onMe = () => { const now = !!W.me?.signedIn; if (now && (fresh || wasIn === false) && !W.bucket) { $('#wsp').hidden = false; renderWS(); } wasIn = now; };
window.__wsReady = refreshMe().then(onMe); addEventListener('focus', () => refreshMe().then(onMe));

addEventListener('studius-quota', (e) => { const q = e.detail, el = $('#quota'); if (!q?.ok) { el.hidden = true; return; } el.hidden = false;
  const r = Math.max(0, q.remaining), p = q.base ? r / q.base : 0; el.className = 'hbtn q' + (r < 60 ? ' low' : p < .25 ? ' mid' : '');
  el.innerHTML = `⚡<span class="t"> ${Math.floor(r / 60)}:${String(Math.round(r % 60)).padStart(2, '0')} min GPU</span><span class="s"> ${Math.round(r / 60)}m</span>`;
  el.title = `ZeroGPU-Quota: ${Math.round(r)} von ${q.base} s übrig` + (q.resetsAt ? ' · Reset ' + new Date(q.resetsAt).toLocaleString('de-DE') : ' · voll'); });

/* Workspace panel */
async function renderWS() {
  const b = $('#wsp .wbody'); $('#wsb').textContent = W.bucket || '';
  if (!W.backend) { b.innerHTML = '<p>Workspace braucht das STUDIUS-Backend.</p>'; return; }
  if (!W.me?.signedIn) { b.innerHTML = `<p>Melde dich mit deinem Hugging-Face-Konto an. Dein eigener <b>HF Storage Bucket</b> wird dann zum Workspace aller Studios.</p><a class="btn" href="/login" target="_blank" rel="noopener">🤗 Sign in with Hugging Face</a><p class="mut">Login öffnet einen neuen Tab (nötig im HF-iframe). Danach hierher zurückkehren.</p>`; return; }
  if (!W.bucket || W.pick) { W.pick = false; return connectUI(b); }
  b.innerHTML = `<div class="row"><label class="btn alt">⬆ Hochladen<input type="file" multiple hidden id="wsup"></label><button class="btn alt" id="wsre">↻</button><button class="btn alt" id="wsch">Bucket wechseln</button></div><div class="stat" id="wsst">Lade…</div><ul class="files"></ul><div class="pv"></div>`;
  $('#wsre').onclick = renderWS; $('#wsch').onclick = () => { W.pick = true; renderWS(); };
  $('#wsup').onchange = async (e) => { for (const f of e.target.files) { $('#wsst').textContent = 'Lade hoch: ' + f.name; try { await api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path: 'uploads/' + f.name, file: f }) }); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; return; } } renderWS(); };
  try { const { files } = await api('/api/ws/list?bucket=' + encodeURIComponent(W.bucket)); W.files = files; $('#wsst').textContent = files.length + ' Dateien · ' + W.bucket;
    $('#wsp .files').innerHTML = files.map((f, i) => { const k = kindOf(f.mime, f.path); const pins = f.meta?.pins || [];
      return `<li><button class="fn" data-i="${i}" title="Vorschau">${{ image: '🖼', audio: '🎵', video: '🎬', text: '📄' }[k] || '📦'} ${esc(f.path)}</button><small>${(f.size / 1024).toFixed(0)} KB${f.meta?.studio ? ' · ' + esc(f.meta.studio) : ''}${f.meta?.v > 1 ? ' · v' + f.meta.v : ''}${pins.length ? ' · 📌' + esc(pins.join(',')) : ''}</small><span><select data-send="${i}" aria-label="An Studio senden"><option value="">→ Studio…</option>${targets(k).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><a class="ib" href="/api/ws/file?dl=1&bucket=${encodeURIComponent(W.bucket)}&path=${encodeURIComponent(f.path)}" aria-label="Download">⬇</a><button class="ib" data-del="${i}" aria-label="Löschen">🗑</button></span></li>`; }).join('') || '<li class="mut">Leer – speichere Ergebnisse mit „In Workspace“.</li>';
    $('#wsp .files').onclick = async (e) => { const t = e.target.closest('button'); if (!t) return; const f = files[t.dataset.i ?? t.dataset.del];
      if (t.dataset.del != null) { if (!confirm(`„${f.path}“ aus ${W.bucket} löschen? (Letzte Version bleibt unter .studius/versions archiviert.)`)) return; try { await api('/api/ws/delete', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, confirm: f.path }) }); renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } return; }
      preview(f); };
    $('#wsp .files').onchange = (e) => { const s = e.target.closest('select[data-send]'); if (!s?.value) return; const f = files[s.dataset.send]; sendTo(s.value, wsAsset(f)); api('/api/ws/pin', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, studio: s.value }) }).catch(() => {}); s.value = ''; };
  } catch (e) { $('#wsst').textContent = '⚠ ' + e.message; }
}
const fileUrl = (p) => '/api/ws/file?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(p);
const wsAsset = (f) => ({ kind: kindOf(f.mime, f.path), mime: f.mime, url: fileUrl(f.path), name: f.path.split('/').pop(), studio: f.meta?.studio || 'workspace' });
async function preview(f) { const k = kindOf(f.mime, f.path), u = fileUrl(f.path), pv = $('#wsp .pv');
  pv.innerHTML = k === 'image' ? `<img alt="${esc(f.path)}" src="${u}">` : k === 'audio' ? `<audio controls src="${u}"></audio>` : k === 'video' ? `<video controls src="${u}"></video>` : k === 'text' ? `<pre>${esc((await (await fetch(u)).text()).slice(0, 4000))}</pre>` : '<p class="mut">Keine Vorschau</p>';
  const m = f.meta || {}; const box = document.createElement('div'); box.className = 'vers'; pv.append(box);
  box.innerHTML = `<small class="mut">${m.v ? 'v' + m.v : ''}${m.studio ? ' · ' + esc(m.studio) : ''}${m.model ? ' · ' + esc(m.model) : m.source ? ' · ' + esc(m.source) : ''}${m.prompt ? ' · „' + esc(m.prompt.slice(0, 80)) + '“' : ''}</small><div class="vl mut">Versionen laden…</div>`;
  try { const { versions } = await api('/api/ws/versions?bucket=' + encodeURIComponent(W.bucket) + '&path=' + encodeURIComponent(f.path)); window.__versions = versions;
    box.querySelector('.vl').innerHTML = versions.length ? '<b>Frühere Versionen</b>' + versions.map(v => `<div class="vr">v${v.v} · ${(v.size / 1024).toFixed(0)} KB · ${new Date(v.mtime).toLocaleString('de-DE')} <a class="ib" href="${fileUrl(v.vpath)}&dl=1" aria-label="v${v.v} herunterladen">⬇</a><button class="ib" data-rv="${v.v}" aria-label="v${v.v} wiederherstellen">↺</button></div>`).join('') : 'Keine früheren Versionen.';
    box.onclick = async (e) => { const b = e.target.closest('[data-rv]'); if (!b) return; if (!confirm(`v${b.dataset.rv} als neue aktuelle Version von „${f.path}“ wiederherstellen? (Die jetzige bleibt als Version erhalten.)`)) return;
      try { const r = await api('/api/ws/restore', { method: 'POST', body: form({ bucket: W.bucket, path: f.path, v: b.dataset.rv }) }); window.__restored = r; $('#wsst').textContent = `✔ v${b.dataset.rv} wiederhergestellt → v${r.meta.v}`; renderWS(); } catch (er) { $('#wsst').textContent = '⚠ ' + er.message; } };
  } catch (e) { box.querySelector('.vl').textContent = ''; } }
/* bucket picker: user + org buckets, search, recent, one-click connect, inline create */
const REC = 'studius-buckets-recent'; const recent = () => { try { return JSON.parse(localStorage.getItem(REC)) || []; } catch (e) { return []; } };
const remember = (id) => localStorage.setItem(REC, JSON.stringify([id, ...recent().filter(x => x !== id)].slice(0, 5)));
let BK = null, BKp = null; // cache of bucket list
const loadBuckets = (force) => { if (force) BK = BKp = null; return BKp ||= api('/api/ws/buckets').then(r => (BK = r)).catch(e => { BKp = null; throw e; }); };
function setBucket(id) { W.bucket = id; if (id) { localStorage.setItem('studius-bucket', id); remember(id); } else localStorage.removeItem('studius-bucket'); hudBucket(); }
function hudBucket() { const c = $('#bkchip'); if (!c) return; c.hidden = !W.me?.signedIn; c.innerHTML = W.bucket ? `🪣<span class="t"> ${esc(W.bucket)}</span><span class="s"> ${esc(W.bucket.split('/')[1])}</span> ▾` : '🪣<span class="t"> Bucket wählen</span><span class="s"> Bucket</span> ▾'; c.title = W.bucket ? 'Aktiver Workspace: ' + W.bucket + ' – klicken zum Wechseln' : 'Workspace-Bucket wählen'; c.classList.toggle('none', !W.bucket); }
async function connectUI(b) {
  const me = W.me.user.name, cur = W.bucket;
  b.innerHTML = `<div class="bp"><p class="bph"><b>Workspace-Bucket wählen</b>${cur ? ` · aktiv: <code>${esc(cur)}</code>` : ''}</p>
    <input id="bkq" type="search" placeholder="Buckets durchsuchen…" aria-label="Buckets durchsuchen" autocomplete="off">
    <div class="stat" id="bst" role="status">Lade deine Buckets…</div><ul class="files bkl" id="blist" aria-label="Buckets"><li class="sk"></li><li class="sk"></li><li class="sk"></li></ul>
    <details class="bnew" ${cur ? '' : 'open'}><summary>+ Neuen Bucket anlegen</summary><div class="row"><select id="bown" aria-label="Besitzer"><option>${esc(me)}</option></select><span>/</span><input id="bname" aria-label="Bucket-Name" value="studius-workspace"></div>
      <label class="chk"><input type="checkbox" id="bpriv" checked> privat (empfohlen)</label><div class="row"><button class="btn" id="bcreate">Erstellen & verbinden</button></div></details>
    ${cur ? '<div class="row"><button class="btn alt" id="bcancel">Abbrechen</button></div>' : ''}</div>`;
  if (cur) $('#bcancel').onclick = () => renderWS();
  let busy = false;
  const go = async (id, create, btn) => { if (busy) return; busy = true; b.querySelectorAll('button').forEach(x => x.disabled = true); if (btn) btn.classList.add('busy');
    $('#bst').textContent = create ? `Erstelle ${id}…` : `Verbinde ${id}…`; $('#bst').classList.remove('err');
    try { const r = await api('/api/ws/connect', { method: 'POST', body: form({ bucket: id, create }) }); setBucket(r.bucket); if (create) BK = BKp = null; window.__bucketConnected = r.bucket; renderWS(); }
    catch (e) { busy = false; b.querySelectorAll('button').forEach(x => x.disabled = false); btn?.classList.remove('busy'); $('#bst').textContent = '⚠ ' + e.message; $('#bst').classList.add('err'); } };
  $('#bcreate').onclick = (e) => { const n = $('#bname').value.trim(); if (!/^[A-Za-z0-9][\w.-]{0,95}$/.test(n)) { $('#bst').textContent = '⚠ Name: Buchstaben, Ziffern, . _ -'; $('#bst').classList.add('err'); return; } go($('#bown').value + '/' + n, true, e.target); };
  const draw = () => { const r = BK; if (!r) return; const q = $('#bkq').value.trim().toLowerCase(); const rec = recent();
    const list = r.buckets.filter(x => !q || x.id.toLowerCase().includes(q)).sort((x, y) => (rec.indexOf(x.id) + 1 || 99) - (rec.indexOf(y.id) + 1 || 99) || (x.owner === me ? 0 : 1) - (y.owner === me ? 0 : 1) || /studius/.test(y.id) - /studius/.test(x.id) || x.id.localeCompare(y.id));
    $('#blist').innerHTML = list.map(x => `<li><button class="fn bk${x.id === cur ? ' on' : ''}" data-b="${esc(x.id)}" title="Mit ${esc(x.id)} verbinden">🪣 ${esc(x.id)}</button><small>${x.private ? '🔒 privat' : '🌐 öffentlich'}${rec.includes(x.id) ? ' · zuletzt' : ''}${x.id === cur ? ' · aktiv' : ''}</small></li>`).join('')
      || `<li class="mut">${q ? 'Kein Bucket passt zu „' + esc(q) + '“.' : 'Noch keine Buckets – lege unten einen an.'}</li>`;
    const errs = Object.entries(r.errors || {}); $('#bst').textContent = `${list.length} von ${r.buckets.length} Buckets · ${r.owners.join(', ')}` + (errs.length ? ` · ⚠ kein Zugriff auf ${errs.map(e => e[0]).join(', ')} (beim Login Org-Zugriff erlauben)` : '');
    if (!r.buckets.length) $('#bnew')?.setAttribute('open', ''); window.__buckets = { n: r.buckets.length, owners: r.owners, shown: list.length, errors: r.errors }; };
  $('#bkq').oninput = draw; $('#bkq').onkeydown = (e) => { if (e.key === 'Enter') { const f = $('#blist [data-b]'); if (f) go(f.dataset.b, false, f); } };
  $('#blist').onclick = (e) => { const t = e.target.closest('[data-b]'); if (t) go(t.dataset.b, false, t); };
  try { await loadBuckets(); if (!b.isConnected) return; $('#bown').innerHTML = BK.owners.map(o => `<option>${esc(o)}</option>`).join(''); draw(); $('#bkq').focus(); }
  catch (e) { $('#blist').innerHTML = ''; $('#bst').innerHTML = `⚠ Buckets konnten nicht geladen werden: ${esc(e.message)} <button class="btn alt" id="bretry">Erneut</button>`; $('#bst').classList.add('err'); $('#bretry').onclick = () => { loadBuckets(true); connectUI(b); }; }
}

/* asset bus */
const targets = (kind) => ST().filter(s => s.accepts?.includes(kind));
export async function saveAsset(a) {
  if (!W.backend || !W.me?.signedIn) throw new Error('Bitte anmelden (Sign in with Hugging Face)');
  if (!W.bucket) throw new Error('Kein Workspace-Bucket verbunden (▤ Workspace)');
  const path = a.path || `${a.studio || 'misc'}/${a.name}`;
  if (a.url && (/^https:\/\/[a-z0-9-]+\.hf\.space\//.test(a.url) || a.url.startsWith('/api/tmp/'))) return api('/api/ws/save-url', { method: 'POST', body: form({ bucket: W.bucket, url: a.url, path, studio: a.studio || '', prompt: a.prompt || '', model: a.model || '' }) });
  const blob = a.blob || (a.text != null ? new Blob([a.text], { type: 'text/plain' }) : await (await fetch(a.url)).blob());
  return api('/api/ws/upload', { method: 'POST', body: form({ bucket: W.bucket, path, studio: a.studio || '', file: new File([blob], a.name) }) });
}
let inbox = null;
export function sendTo(id, asset) { const i = ST().findIndex(s => s.id === id); if (i < 0) return; inbox = { id, asset }; window.__studius.open(i); }
window.addEventListener('studius-opened', (e) => { if (!inbox || inbox.id !== e.detail.id) return; const { asset } = inbox; inbox = null; const s = ST().find(x => x.id === e.detail.id);
  setTimeout(async () => { try { await s.accept(e.detail.el, asset); window.__handoff = { to: s.id, kind: asset.kind, ok: true }; } catch (er) { window.__handoff = { to: s.id, ok: false, err: er.message }; console.warn('hand-off', er); } }, 60); });
function actionRow(asset) {
  const d = document.createElement('div'); d.className = 'row assetbar';
  d.innerHTML = `<button class="btn alt sv">💾 In Workspace</button><select aria-label="Senden an Studio"><option value="">→ Öffnen in…</option>${targets(asset.kind).filter(s => s.id !== asset.studio).map(s => `<option value="${s.id}">${esc(s.name)}</option>`).join('')}</select><small class="st"></small>`;
  d.querySelector('.sv').onclick = async () => { const st = d.querySelector('.st'); st.textContent = 'speichere…'; try { const r = await saveAsset(asset); st.textContent = '✔ ' + r.path; window.__saved = r; } catch (e) { st.textContent = '⚠ ' + e.message; } };
  d.querySelector('select').onchange = (e) => e.target.value && sendTo(e.target.value, asset);
  return d;
}
window.addEventListener('studius-result', (e) => { const { el, asset } = e.detail; if (!el?.isConnected) return; if (el.nextElementSibling?.classList?.contains('assetbar')) el.nextElementSibling.remove(); el.after(actionRow(asset)); });
window.__bus = { sendTo, saveAsset };

/* bee agents: Mitarbeiter-Team (agents + teams in the bucket), real LLM function-calling (server), server job list with approval */
MODULES.workspace = { id: 'workspace', name: 'Workspace', backend: 'HF Storage Bucket', inputs: [{ name: 'url', type: 'asset-url' }], outputs: [{ kind: 'file' }],
  actions: {
    save: { desc: 'SPEICHERT ein Ergebnis (url aus der Übergabe) dauerhaft im Workspace. Benutze dies zum Speichern/Archivieren. Braucht Freigabe durch den Menschen', params: { url: 'string' }, external: true, run: async ({ url: u }, on = {}) => { const a = on.assetFor?.(u); if (!a) throw new Error('kein Ergebnis zu dieser url'); const r = await saveAsset(a); return { kind: 'text', text: 'Gespeichert: ' + r.path, saved: r.path, name: 'saved.txt', studio: 'workspace' }; } },
    list: { desc: 'Zeigt nur vorhandene Dateien an (prefix, sonst leer lassen). Speichert NICHTS', params: { prefix: 'string' }, run: async ({ prefix = '' } = {}) => { const r = await api('/api/ws/list?bucket=' + encodeURIComponent(W.bucket) + '&prefix=' + encodeURIComponent(prefix || '')); const t = r.files.slice(0, 20).map(f => f.path).join('\n'); return { kind: 'text', text: t || '(leer)', name: 'list.txt', studio: 'workspace' }; } },
  } };
const DEF = [{ id: 'demo', name: 'Demo-Biene', role: 'Allrounder', modules: ['chat', 'image'] }];
let agents; try { agents = JSON.parse(localStorage.getItem('studius-agents')) || DEF; } catch (e) { agents = DEF; }
let teams = []; try { teams = JSON.parse(localStorage.getItem('studius-teams')) || []; } catch (e) {}
let cur = agents[0].id; const cloud = () => !!(W.backend && W.me?.signedIn && W.bucket);
const saveAg = async (a) => { localStorage.setItem('studius-agents', JSON.stringify(agents)); if (a && cloud()) { try { await api('/api/crew/agents', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bucket: W.bucket, item: a }) }); window.__agSaved = a.id; } catch (e) { say('bee', '⚠ ' + esc(e.message)); } } };
const saveTeam = async (t) => { localStorage.setItem('studius-teams', JSON.stringify(teams)); if (cloud()) { try { await api('/api/crew/teams', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ bucket: W.bucket, item: t }) }); window.__teamSaved = t.id; } catch (e) { say('bee', '⚠ ' + esc(e.message)); } } };
async function loadCrew() { if (!cloud()) return; try { const [A, T] = await Promise.all([api('/api/crew/agents?bucket=' + encodeURIComponent(W.bucket)), api('/api/crew/teams?bucket=' + encodeURIComponent(W.bucket))]);
  if (A.agents.length) { const ids = new Set(A.agents.map(x => x.id)); agents = [...A.agents, ...agents.filter(x => !ids.has(x.id) && x.id !== 'demo')]; if (!agents.some(x => x.id === cur)) cur = agents[0].id; }
  if (T.teams.length) teams = T.teams; window.__crew = { agents: agents.map(a => a.id), teams: teams.map(t => t.id) }; } catch (e) {} }
const TEMPLATES = [
  { id: 'musik-team', name: 'Musik-Team', icon: '🎵', task: 'Mach einen kurzen Lofi-Beat mit warmem Piano, mastere ihn auf -14 LUFS und speichere ihn im Workspace',
    members: [['komponist', 'Komponist', 'Komponiert kurze Musikstücke nach Vorgabe', ['music']], ['stem-engineer', 'Stem-Engineer', 'Trennt Songs in Stems, wenn Vocals stören; sonst nichts tun', ['stems']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -14 LUFS (Streaming)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
  { id: 'social-team', name: 'Social-Media-Team', icon: '📱', task: 'Erstelle einen kurzen Social-Clip: goldene Biene über Honigwaben, mit Caption',
    members: [['texter', 'Social-Texter', 'Schreibt Captions mit Hashtags pro Plattform (social.captions)', ['social', 'chat']], ['art-director', 'Art-Director', 'Erzeugt das Key-Visual als Bild', ['image']], ['video-producer', 'Video-Producer', 'Erzeugt aus dem Prompt einen 2-3 s Clip', ['video']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
  { id: 'radio-team', name: 'Radio-Team', icon: '📻', task: 'Produziere eine 15-Sekunden-Radio-Ansage für die STUDIUS-Launch-Party mit Jingle',
    members: [['redakteur', 'Redakteur', 'Schreibt einen kurzen Moderationstext (max. 2 Sätze)', ['chat']], ['sprecher', 'Sprecher', 'Spricht den Moderationstext mit der Avatar-Stimme', ['avatar']], ['jingle', 'Jingle-Komponist', 'Komponiert einen kurzen Radio-Jingle', ['music']], ['mastering', 'Mastering-Engineer', 'Mastert Audio auf -16 LUFS (Podcast/Radio)', ['master']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
  { id: 'shop-team', name: 'Shop/Marketing-Team', icon: '🛍', task: 'Bewirb ein goldenes Bienen-T-Shirt: Produkttext, Produktfoto und kurzer Werbeclip',
    members: [['produkttexter', 'Produkttexter', 'Schreibt Produktbeschreibung (3 Sätze) und Slogan', ['chat']], ['produktfoto', 'Produktfotograf', 'Erzeugt ein Produktfoto im Studio-Look', ['image']], ['werbespot', 'Werbespot-Regie', 'Erzeugt aus dem Produktfoto-Prompt einen kurzen Clip', ['video']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
  { id: 'avatar-team', name: 'Avatar-Content-Team', icon: '👤', task: 'Der Avatar stellt sich in einem kurzen Clip vor',
    members: [['autor', 'Avatar-Autor', 'Schreibt in der Persona des Avatars einen Vorstellungstext (2 Sätze)', ['avatar']], ['fotograf', 'Avatar-Fotograf', 'Erzeugt ein Bild des Avatars in einer passenden Szene', ['avatar']], ['stimme', 'Avatar-Sprecher', 'Macht aus dem Text ein sprechendes Video des Avatars (avatar.talk, Lip-Sync)', ['avatar']], ['archivar', 'Archivar', 'Speichert fertige Ergebnisse im Workspace', ['workspace']]] },
  { id: 'empire-team', name: 'Empire-Flow', icon: '👑', task: 'Komponiere einen 10-Sekunden-Lofi-Track „Honey Lofi“ mit warmem Piano, schreibe Release-Captions für Social Media im Ton unserer Marke, und lege einen passenden T-Shirt-Merch-Entwurf an; speichere den Track im Workspace',
    members: [['markenwart', 'Markenwart', 'Liest das Branding-Kit (brand.get), damit alle Texte zur Marke passen', ['brand']], ['komponist', 'Komponist', 'Komponiert kurze Musikstücke nach Vorgabe', ['music']], ['texter', 'Social-Texter', 'Schreibt Release-Captions mit Hashtags im Markenton (social.captions). Postet nichts', ['social']], ['merch', 'Merch-Designer', 'Legt einen passenden T-Shirt-Entwurf für Jenniisdriptees an (shop.draft, nur Entwurf, Freigabe nötig)', ['shop']], ['archivar', 'Archivar', 'Speichert den Track im Workspace', ['workspace']]] },
];
async function fromTemplate(tid) { const T = TEMPLATES.find(t => t.id === tid); if (!T) return; const av = avList[0]?.id || '';
  const made = []; for (const [id, name, role, modules] of T.members) { const aid = (id === 'archivar' ? '' : T.id.split('-')[0] + '-') + id;
    let a = agents.find(x => x.id === aid); if (!a) { a = { id: aid, name, role, modules: modules.filter(m => MODULES[m]), avatar: modules.includes('avatar') ? av : '' }; agents.push(a); await saveAg(a); } made.push(a.id); }
  let t = teams.find(x => x.id === T.id); if (!t) { t = { id: T.id, name: T.name, members: made, task: T.task }; teams.push(t); } else t.members = made; await saveTeam(t);
  cur = 'team:' + t.id; $('#bin').value = T.task; window.__tpl = { id: T.id, members: made }; renderAgents(); }
const slugify = (s) => s.toLowerCase().normalize('NFKD').replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 40) || 'a' + Date.now();
let avList = []; const loadAv = async () => { try { avList = await Avatars.list(); } catch (e) { avList = []; } };
async function renderAgents(reload) { if (reload) { await loadCrew(); await loadAv(); }
  const sel = $('#agsel'); sel.innerHTML = agents.map(a => `<option value="${a.id}">🐝 ${esc(a.name)}</option>`).join('') + teams.map(t => `<option value="team:${t.id}">👥 ${esc(t.name)}</option>`).join('') + '<option value="+">+ Neuer Agent</option><option value="+t">+ Neues Team</option><option value="+v">✨ Team aus Vorlage…</option>'; sel.value = cur === '+v' ? '+v' : cur;
  sel.onchange = async () => { if (sel.value === '+') { const n = prompt('Name des Mitarbeiters?'); if (n) { const a = { id: slugify(n), name: n.slice(0, 40), role: '', modules: ['chat'], avatar: '' }; agents.push(a); cur = a.id; await saveAg(a); } }
    else if (sel.value === '+v') { cur = '+v'; }
    else if (sel.value === '+t') { const n = prompt('Name des Teams?'); if (n) { const t = { id: slugify(n), name: n.slice(0, 40), members: agents.slice(0, 2).map(a => a.id) }; teams.push(t); cur = 'team:' + t.id; await saveTeam(t); } }
    else cur = sel.value; renderAgents(); };
  const cfg = $('#bees .agcfg');
  if (cur === '+v') { cfg.innerHTML = `<small>Team-Vorlage wählen – ein Klick legt Mitarbeiter + Team an (danach frei editierbar):</small><div class="tpls">${TEMPLATES.map(t => `<button class="tpl" data-tpl="${t.id}"><b>${t.icon} ${esc(t.name)}</b><small>${t.members.map(m => esc(m[1])).join(' → ')}</small></button>`).join('')}</div>`;
    cfg.onclick = async (e) => { const b = e.target.closest('[data-tpl]'); if (!b) return; cfg.querySelectorAll('.tpl').forEach(x => x.disabled = true); b.classList.add('busy'); await fromTemplate(b.dataset.tpl); }; cfg.onchange = null; return; }
  if (cur.startsWith('team:')) { const t = teams.find(x => 'team:' + x.id === cur); if (!t) { cur = agents[0].id; return renderAgents(); }
    if (t.task) $('#bin').placeholder = 'z. B. ' + t.task;
    cfg.innerHTML = `<small>Team-Reihenfolge (Übergabe von oben nach unten):</small><div class="tm">${t.members.map((m, i) => `<div><select data-m="${i}" aria-label="Mitglied ${i + 1}">${agents.map(a => `<option value="${a.id}" ${a.id === m ? 'selected' : ''}>${esc(a.name)}</option>`).join('')}</select><button class="ib" data-rm="${i}" aria-label="Entfernen">✕</button></div>`).join('')}</div><button class="ib" data-add aria-label="Mitglied hinzufügen">+ Mitglied</button>`;
    cfg.onchange = (e) => { const s = e.target.closest('[data-m]'); if (s) { t.members[+s.dataset.m] = s.value; saveTeam(t); } };
    cfg.onclick = (e) => { if (e.target.closest('[data-add]')) { t.members.push(agents[0].id); saveTeam(t); renderAgents(); } const r = e.target.closest('[data-rm]'); if (r) { t.members.splice(+r.dataset.rm, 1); saveTeam(t); renderAgents(); } };
    return; }
  const a = agents.find(x => x.id === cur) || agents[0];
  cfg.innerHTML = `<div class="agrow"><input class="role" aria-label="Rolle" placeholder="Rolle, z. B. Mastering-Engineer" value="${esc(a.role || '')}"><select class="agav" aria-label="Avatar"><option value="">ohne Avatar</option>${avList.map(v => `<option value="${esc(v.id)}" ${v.id === a.avatar ? 'selected' : ''}>👤 ${esc(v.name)}</option>`).join('')}</select></div><small>Module:</small>` + Object.values(MODULES).map(m => `<label><input type="checkbox" value="${m.id}" ${a.modules.includes(m.id) ? 'checked' : ''}> ${esc(m.name)}</label>`).join('');
  cfg.onchange = (e) => { const t = e.target; if (t.classList.contains('role')) a.role = t.value.slice(0, 300); else if (t.classList.contains('agav')) a.avatar = t.value; else a.modules = t.checked ? [...new Set([...a.modules, t.value])] : a.modules.filter(m => m !== t.value); saveAg(a); };
  cfg.onclick = null; }
const blog = () => $('#bees .blog');
function say(who, html) { const p = document.createElement('div'); p.className = 'bm ' + who; p.innerHTML = (who === 'bee' ? '<i class="bee">🐝</i>' : '') + `<div>${html}</div>`; blog().append(p); blog().scrollTop = 1e6; return p.lastChild; }
const toolsOf = (a) => a.modules.flatMap(m => Object.entries(MODULES[m]?.actions || {}).map(([k, v]) => ({ name: m + '.' + k, desc: v.desc, params: v.params, run: v.run, external: !!v.external })));
const jpost = (u, b) => { const bk = W.bucket ? (u.includes('?') ? '&' : '?') + 'bucket=' + encodeURIComponent(W.bucket) : ''; return api(u + (u.startsWith('/api/jobs') ? bk : ''), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ...(b || {}), ...(u.startsWith('/api/jobs') && W.bucket ? { bucket: W.bucket } : {}) }) }); };
const show = (res) => res.kind === 'image' ? `<img alt="" src="${esc(res.url)}">` : res.kind === 'audio' ? `<audio controls src="${esc(res.url)}"></audio>` : `<p>${esc((res.text || '').slice(0, 600))}</p>`;
function approval(job, st, box) { return new Promise((ok) => {
  box.innerHTML = `<b>Freigabe nötig</b> · <code>${esc(st.tool)}</code><br><small>${esc(JSON.stringify(st.args).slice(0, 200))}</small><div class="row"><button class="btn ap">Freigeben</button><button class="btn alt rj">Ablehnen</button></div>`;
  window.__approval = { job: job.id, n: st.n, tool: st.tool };
  const go = async (d) => { box.querySelectorAll('button').forEach(b => b.disabled = true); try { const r = await jpost(`/api/jobs/${job.id}/steps/${st.n}/${d}`); ok(r.step.state === 'approved'); } catch (e) { ok(false); } };
  box.querySelector('.ap').onclick = () => go('approve'); box.querySelector('.rj').onclick = () => go('reject'); }); }
async function work(job, a, task, shared, maxSteps) { // one agent's function-calling loop; shared = {history, assets}
  const tools = toolsOf(a); if (!tools.length) { say('bee', `${esc(a.name)}: keine Module zugewiesen.`); return null; }
  let system = a.role ? `Deine Rolle: ${a.role}.` : ''; const av = a.avatar && avList.find(v => v.id === a.avatar); if (av) system = Avatars.persona(av) + ' ' + system;
  let final = null; const startLen = shared.history.length; const mine = new Set(tools.map(t => t.name)); const did = () => shared.history.some(h => mine.has(h.tool) && !h.result?.error && !h.result?.rejected); const mustTool = !(a.modules.length === 1 && a.modules[0] === 'chat') && !did();
  for (let i = 0; i < maxSteps; i++) {
    const box = say('bee', `<b>${esc(a.name)}</b> <span class="buzz"><i>🐝</i><i>🐝</i><i>🐝</i></span> plant…`);
    let p; try { p = await jpost('/api/agent/step', { task, system, tools: tools.map(({ name, desc, params }) => ({ name, desc, params })), history: shared.history, known_urls: shared.assets.filter(x => x.url).map(x => x.url), require_tool: mustTool && !did() }); } catch (e) { if (did()) { box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; final = 'fertig'; break; } throw e; }
    window.__agent = { ...window.__agent, via: p.via, state: 'plan', attempts: [...(window.__agent?.attempts || []), ...(p.attempts || [])] };
    if (!p.call) {
      // if this agent hasn't used a tool yet and has an external save available with a pending asset, force it
      if (shared.history.length === startLen && tools.some(t => t.name === 'workspace.save') && shared.assets.length) {
        p = { call: { tool: 'workspace.save', args: { url: shared.assets.at(-1).url } }, via: (p.via || '') + '+forced-save' };
      } else {
        final = p.final || 'fertig';
        if (shared.history.length === startLen && (a.modules.includes('chat') || a.modules.includes('avatar')) && final && final !== 'fertig') {
          const res = { kind: 'text', text: final, name: 'agent-' + Date.now() + '.txt', studio: 'chat' }; shared.assets.push(res);
          shared.history.push({ tool: 'chat.reply', args: { prompt: task }, result: { kind: 'text', text: final.slice(0, 300) } });
          box.innerHTML = `<b>${esc(a.name)}</b> · <code>chat.reply</code> ✔` + show(res) + ` <small>(${esc(p.via)})</small>`;
        } else box.innerHTML = `<b>${esc(a.name)}</b> ✔ ${esc(final)} <small>(${esc(p.via)})</small>`;
        break;
      }
    }

    if (shared.team && shared.history.some(h => h.tool === p.call.tool && !h.result?.error && !h.result?.rejected)) { final = 'fertig'; box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; break; }
    const t = tools.find(x => x.name === p.call.tool); const args = { ...p.call.args };
    const last = shared.assets.at(-1); // resolve bad/missing url args to the latest result (hand-off)
    for (const k of ['url', 'source']) if (k in (t.params || {}) && !shared.assets.some(x => x.url === args[k]) && last) args[k] = last.url;
    if (t.name === 'master.master' && !args.source && last) args.source = last.url;
    if (shared.history.some(h => h.tool === t.name && JSON.stringify(h.args) === JSON.stringify(args))) { final = 'fertig'; box.innerHTML = `<b>${esc(a.name)}</b> ✔ fertig`; break; }
    const { step } = await jpost(`/api/jobs/${job.id}/step`, { tool: t.name, args, agent: a.id });
    if (step.state === 'awaiting_approval') { const okd = await approval(job, step, box); if (!okd) { box.innerHTML = `<b>${esc(a.name)}</b> ✋ <code>${esc(t.name)}</code> abgelehnt – nichts ausgeführt.`; shared.history.push({ tool: t.name, args, result: { rejected: true } }); return 'abgelehnt'; } }
    box.innerHTML = `<b>${esc(a.name)}</b> → <code>${esc(t.name)}</code> <small>(${esc(p.via)})</small> <small class="s"></small>`; window.__agent = { ...window.__agent, state: 'run', tool: t.name };
    try { const res = await t.run(args, { status: m => { const s = box.querySelector('.s'); if (s) s.textContent = m.stage + (m.position != null ? ' #' + (m.position + 1) : ''); }, data: () => {}, assetFor: (u) => shared.assets.find(x => x.url === u) || shared.assets.at(-1) });
      let keep = null; if (res.url && cloud()) { try { const sv = await saveAsset({ ...res, path: `jobs/${job.id}/step${step.n}-${res.name || 'result'}` }); keep = sv.path; } catch (e) { console.warn('step result not persisted', e.message); } }
      if (res.url) shared.assets.push(res); shared.history.push({ tool: t.name, args, result: { kind: res.kind, url: res.url, text: (res.text || '').slice(0, 300) } });
      box.innerHTML = `<b>${esc(a.name)}</b> · <code>${esc(t.name)}</code> ✔` + show(res);
      await jpost(`/api/jobs/${job.id}/steps/${step.n}/done`, { result: { kind: res.kind, name: res.name, text: (res.text || '').slice(0, 300), ...(keep ? { path: keep, url: fileUrl(keep) } : res.url && !res.url.startsWith('blob:') ? { url: res.url } : {}) } });
      if (res.url) window.dispatchEvent(new CustomEvent('studius-result', { detail: { el: box.lastElementChild, asset: res } }));
    } catch (e) { box.innerHTML = `<b>${esc(a.name)}</b> ⚠ ${esc(t.name)}: ${esc(e.message)}`; await jpost(`/api/jobs/${job.id}/steps/${step.n}/error`).catch(() => {}); shared.history.push({ tool: t.name, args, result: { error: e.message } }); }
  }
  return final; }
async function runJob(job, crew, team, task, shared, from = 0) {
  let sum = '';
  try { for (const [i, a] of crew.entries()) { if (i < from) continue;
      jpost(`/api/jobs/${job.id}/cursor`, { member: i, agent: a.id, members: crew.map(c => c.id) }).catch(() => {});
      const sub = team ? `${task}\n\n(Du bist Mitglied ${i + 1}/${crew.length} im Team „${team.name}“. Dein Teil: ${a.role || 'siehe Werkzeuge'}. Erledige NUR deinen Teil mit deinen Werkzeugen${shared.assets.length ? '; Übergabe vom Vorgänger: ' + shared.assets.at(-1).url : ''}. Dann antworte ohne Werkzeug.)` : task;
      if (team && i > from) say('bee', `↪ Übergabe an <b>${esc(a.name)}</b>`);
      const r = await work(job, a, sub, shared, team ? 2 : 4); sum += `${a.name}: ${r || '-'}\n`; if (r === 'abgelehnt') break; }
    const st = shared.history.some(h => h.result?.rejected) ? 'rejected' : 'done';
    await jpost(`/api/jobs/${job.id}/finish`, { state: st, summary: sum });
    window.__agent = { ...window.__agent, state: 'done', steps: shared.history.map(h => h.tool), kinds: shared.history.map(h => h.result?.kind || (h.result?.rejected ? 'rejected' : h.result?.error ? 'error' : '')), url: shared.assets.at(-1)?.url, text: shared.history.at(-1)?.result?.text };
  } catch (e) { say('bee', '⚠ ' + esc(e.message)); window.__agent = { ...window.__agent, state: 'error', err: e.message }; jpost(`/api/jobs/${job.id}/finish`, { state: 'error', summary: e.message }).catch(() => {}); }
  renderJobs(); }
async function runAgent() { const inp = $('#bin'), task = inp.value.trim(); if (!task) return; inp.value = '';
  if (!W.me?.signedIn) { say('bee', 'Bitte zuerst mit Hugging Face anmelden – Agenten planen serverseitig mit deiner HF-Quota.'); return; }
  const team = cur.startsWith('team:') ? teams.find(t => 'team:' + t.id === cur) : null; const crew = team ? team.members.map(m => agents.find(a => a.id === m)).filter(Boolean) : [agents.find(x => x.id === cur)];
  say('me', esc(task)); window.__agent = { task, state: 'plan', team: team?.id };
  const job = await jpost('/api/jobs', { task, agent: team ? '' : crew[0].id, team: team?.id || '' }); window.__agent.job = job.id;
  await runJob(job, crew, team, task, { history: [], assets: [], team: !!team }); }
async function resumeJob(id) {
  const j0 = (window.__jobs || []).find(x => x.id === id); if (!j0) return;
  const job = await jpost(`/api/jobs/${id}/resume`); const team = job.team ? teams.find(t => t.id === job.team) : null;
  const ids = job.members || (team ? team.members : [job.agent]); const crew = ids.map(m => agents.find(a => a.id === m)).filter(Boolean);
  if (!crew.length) { say('bee', '⚠ Mitarbeiter dieses Jobs nicht mehr vorhanden.'); return; }
  const shared = { history: [], assets: [], team: !!team };
  for (const st of job.steps.filter(s => s.state === 'done')) { const r = st.result || {}; shared.history.push({ tool: st.tool, args: st.args, result: { kind: r.kind, url: r.url, text: r.text } });
    if (r.url) shared.assets.push({ kind: r.kind, url: r.url, name: r.name || (r.path || '').split('/').pop(), studio: 'job', path: r.path }); }
  const from = job.cursor?.member || 0; $('#bees').hidden = false;
  say('me', `↻ Fortsetzen: ${esc(job.task)}`); say('bee', `Fortsetzen ab <b>${esc(crew[from]?.name || '?')}</b> – ${shared.history.length} erledigte Schritt(e) übernommen${shared.assets.length ? ': ' + shared.assets.map(x => esc(x.name)).join(', ') : ''}.`);
  window.__agent = { task: job.task, state: 'plan', team: job.team, job: id, resumed: true, from, carried: shared.history.map(h => h.tool) };
  await runJob(job, crew, team, job.task, shared, from); }
window.__resumeJob = resumeJob;
async function renderJobs() { const el = $('#bees .jobs'); if (!el || !W.me?.signedIn) return; try { const { jobs } = await api('/api/jobs' + (W.bucket ? '?bucket=' + encodeURIComponent(W.bucket) : '')); window.__jobs = jobs;
  el.innerHTML = jobs.slice(0, 8).map(j => `<div class="job"><b>${{ done: '✔', running: '⏳', awaiting_approval: '✋', rejected: '⛔', error: '⚠', interrupted: '⏸' }[j.state] || '·'}</b> ${esc(j.task.slice(0, 50))} <small class="mut">${new Date(j.created * 1000).toLocaleString('de-DE', { dateStyle: 'short', timeStyle: 'short' })}${j.saved ? ' · 🪣' : ''}${j.restored ? ' · aus Bucket' : ''}</small> <small>${j.steps.map(s => esc(s.tool) + (s.external ? '🔒' : '') + ':' + s.state).join(' → ')}</small>${['interrupted', 'error', 'awaiting_approval'].includes(j.state) ? `<button class="btn alt rs" data-rs="${esc(j.id)}">↻ Fortsetzen</button>` : ''}</div>`).join('') || '<small class="mut">Noch keine Jobs.</small>'; } catch (e) {} }
$('#bees .jobs').onclick = (e) => { const b = e.target.closest('[data-rs]'); if (b) { b.disabled = true; resumeJob(b.dataset.rs); } };
$('#bsend').onclick = runAgent; $('#bin').addEventListener('keydown', e => { if (e.key === 'Enter') runAgent(); });