SPB Git

spb/admin-ka

Public
50.4 KB · 1,058 lines javascript
1/* Admin-Ka v2 — client : chat Claude Code + sessions détachées + écosystème */2(() => {3  const $ = (id) => document.getElementById(id);4  const messagesEl = $('messages');5  const inputEl = $('input');6  const sendBtn = $('sendBtn');7  const stopBtn = $('stopBtn');8  const projectSel = $('projectSel');910  marked.setOptions({ breaks: true, mangle: false, headerIds: false });1112  // ---------- état ----------13  const store = JSON.parse(localStorage.getItem('adminka') || '{}');14  const settings = {15    model: store.model || 'fable',16    permMode: store.permMode || 'default',17    projectId: store.projectId || null,18  };19  function saveStore() { localStorage.setItem('adminka', JSON.stringify(settings)); }2021  let ws = null, wsRetry = 1000, wsWanted = true;22  let currentChat = null;      // publicChat du serveur23  let isRunning = false;24  let live = null, liveThink = null;25  let curView = 'chat';26  let ecoData = null;27  const toolCards = new Map();28  const permCards = new Map();2930  const MODEL_LABEL = { fable: 'Fable 5', opus: 'Opus 5', sonnet: 'Sonnet 5', haiku: 'Haiku' };31  const PERM_LABEL = { default: 'normal', acceptEdits: 'acceptEdits', plan: 'plan', bypass: '⚠ bypass' };3233  // ---------- utilitaires ----------34  function esc(s) { return String(s).replace(/[&<>"]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c])); }35  function el(tag, cls, html) {36    const e = document.createElement(tag);37    if (cls) e.className = cls;38    if (html !== undefined) e.innerHTML = html;39    return e;40  }41  function fmt$(v) { return (v || 0) < 0.005 ? '<0,01 $' : (v).toFixed(2).replace('.', ',') + ' $'; }42  function fmtTok(v) { return v > 1000 ? Math.round(v / 1000) + 'k' : String(v || 0); }43  function timeAgo(ts) {44    if (!ts) return '—';45    const s = (Date.now() - ts) / 1000;46    if (s < 90) return 'à l’instant';47    if (s < 3600) return Math.round(s / 60) + ' min';48    if (s < 86400) return Math.round(s / 3600) + ' h';49    return Math.round(s / 86400) + ' j';50  }51  function fmtMB(b) { return b ? Math.round(b / 1048576) + ' Mo' : '—'; }5253  // ---------- navigation ----------54  const views = ['chat', 'sessions', 'eco', 'settings'];55  function switchView(name) {56    curView = name;57    for (const v of views) $('view-' + v).classList.toggle('hidden', v !== name);58    document.querySelectorAll('.nav-btn').forEach((b) => {59      b.classList.toggle('active', b.dataset.view === name);60      if (b.dataset.view === name) b.querySelector('.badge').classList.add('hidden');61    });62    if (name === 'sessions') loadSessions();63    if (name === 'eco') { loadEco(); send({ type: 'eco_sub' }); } else { send({ type: 'eco_unsub' }); }64    if (name === 'settings') refreshSettingsView();65  }66  document.querySelectorAll('.nav-btn').forEach((b) => { b.onclick = () => switchView(b.dataset.view); });67  function navBadge(view) {68    if (curView === view) return;69    const b = document.querySelector(`.nav-btn[data-view="${view}"] .badge`);70    if (b) b.classList.remove('hidden');71  }7273  // ---------- bannières ----------74  function banner(kind, html, onclick, ttl = 6000) {75    const b = el('div', 'banner ' + kind, html);76    if (onclick) b.onclick = () => { onclick(); b.remove(); };77    $('banners').appendChild(b);78    if (navigator.vibrate) navigator.vibrate(60);79    setTimeout(() => b.remove(), ttl);80  }8182  // ---------- scroll / messages ----------83  function nearBottom() { return messagesEl.scrollHeight - messagesEl.scrollTop - messagesEl.clientHeight < 130; }84  function scrollBottom(force) { if (force || nearBottom()) messagesEl.scrollTop = messagesEl.scrollHeight; }85  function addMsg(node) {86    $('welcome').classList.add('hidden');87    const wasNear = nearBottom();88    const w = workingEl(); if (w) messagesEl.insertBefore(node, w); else messagesEl.appendChild(node);89    scrollBottom(wasNear);90  }91  function renderMd(container, text) {92    container.innerHTML = marked.parse(text || '');93    container.querySelectorAll('pre code').forEach((b) => { try { hljs.highlightElement(b); } catch {} });94  }95  // bouton copier sur tous les blocs de code (délégué, marche pour tout <pre>)96  messagesEl.addEventListener('click', (e) => {97    const pre = e.target.closest('pre');98    if (!pre || e.target.closest('button') || pre.dataset.copying) return;99    if (window.getSelection().toString()) return;100    navigator.clipboard.writeText(pre.textContent).then(() => {101      pre.dataset.copying = '1';102      const tag = el('span', 'copied-tag', 'copié ✓');103      pre.appendChild(tag);104      setTimeout(() => { tag.remove(); delete pre.dataset.copying; }, 1200);105    }).catch(() => {});106  });107  function truncPre(text, limit = 3000) {108    const pre = el('pre');109    const full = String(text ?? '');110    if (full.length <= limit) { pre.textContent = full; return pre; }111    pre.textContent = full.slice(0, limit);112    const wrap = el('div');113    const btn = el('button', 'see-more', 'voir plus (' + Math.round((full.length - limit) / 1000) + ' k de plus)');114    btn.onclick = () => { pre.textContent = full; btn.remove(); };115    wrap.append(pre, btn);116    return wrap;117  }118119  function workingEl() { return messagesEl.querySelector('.working'); }120  let workTimer = null, workStart = 0;121  function setRunning(r) {122    isRunning = r;123    sendBtn.classList.toggle('hidden', r);124    stopBtn.classList.toggle('hidden', !r);125    let w = workingEl();126    if (r && !w) {127      $('welcome').classList.add('hidden');128      w = el('div', 'working', '<div class="dots"><i></i><i></i><i></i></div><span>Claude Code travaille…</span><b class="work-time"></b>');129      messagesEl.appendChild(w);130      scrollBottom(true);131      workStart = Date.now();132      clearInterval(workTimer);133      workTimer = setInterval(() => {134        const t = w.querySelector('.work-time');135        if (!t) { clearInterval(workTimer); return; }136        const s = Math.floor((Date.now() - workStart) / 1000);137        t.textContent = s >= 60 ? Math.floor(s / 60) + ' min ' + (s % 60) + ' s' : s + ' s';138      }, 1000);139    } else if (!r && w) { w.remove(); clearInterval(workTimer); }140    if (!r) {141      finalizeLive(); finalizeThink();142      flushQueued();143    }144  }145  const WORK_VERB = { Bash: 'exécute', Read: 'lit', Edit: 'modifie', MultiEdit: 'modifie', Write: 'écrit', Glob: 'cherche', Grep: 'cherche dans', LS: 'liste', Task: 'délègue', WebFetch: 'récupère', WebSearch: 'recherche', TodoWrite: 'planifie', ExitPlanMode: 'propose un plan' };146  function setWorkingLabel(name, sub) {147    const w = workingEl(); if (!w) return;148    const span = w.querySelector('span'); if (!span) return;149    const verb = WORK_VERB[name] || 'utilise ' + name;150    const detail = sub ? ' ' + sub.slice(0, 46) : '';151    span.textContent = `Claude ${verb}${detail}…`;152  }153  // file d'attente : un message tapé pendant l'exécution part dès que Claude a fini154  let queuedPrompt = null;155  function flushQueued() {156    if (!queuedPrompt) return;157    const q = queuedPrompt; queuedPrompt = null;158    const n = messagesEl.querySelector('.queued-notice'); if (n) n.remove();159    doSend(q);160  }161162  // ---------- streaming live ----------163  function ensureLive() {164    if (live) return live;165    const w = workingEl(); if (w) { const s = w.querySelector('span'); if (s) s.textContent = 'Claude rédige…'; }166    const wrap = el('div', 'msg-claude');167    const md = el('div', 'md');168    wrap.appendChild(md);169    addMsg(wrap);170    live = { el: wrap, textEl: md, text: '' };171    return live;172  }173  function finalizeLive() { if (live) { live.el.remove(); live = null; } }174  function ensureThink() {175    if (liveThink) return liveThink;176    const box = el('div', 'thinking');177    addMsg(box);178    liveThink = { el: box, text: '' };179    return liveThink;180  }181  function finalizeThink() {182    if (!liveThink) return;183    const d = el('details', 'thinking-box', '<summary>réflexion</summary>');184    const inner = el('div', 'thinking'); inner.textContent = liveThink.text;185    d.appendChild(inner);186    liveThink.el.replaceWith(d);187    liveThink = null;188  }189190  // ---------- cartes outils ----------191  const TOOL_ICONS = { Bash: '❯', Read: '📄', Edit: '✏️', MultiEdit: '✏️', Write: '📝', Glob: '🔍', Grep: '🔍', LS: '📁', Task: '🤖', WebFetch: '🌐', WebSearch: '🌐', TodoWrite: '☑️', NotebookRead: '📓', NotebookEdit: '📓', ExitPlanMode: '📋' };192  const TOOL_TINT = { Bash: 'bash', Edit: 'edit', MultiEdit: 'edit', Write: 'edit', NotebookEdit: 'edit', Read: 'read', Glob: 'read', Grep: 'read', LS: 'read', NotebookRead: 'read', WebFetch: 'web', WebSearch: 'web' };193  function toolSubtitle(name, input) {194    input = input || {};195    if (name === 'Bash') return input.command || '';196    if (input.file_path) return input.file_path.replace(/^\/Users\/[^/]+\//, '~/');197    if (input.pattern) return input.pattern;198    if (input.url) return input.url;199    if (name === 'Task') return input.description || '';200    if (name === 'TodoWrite') return 'liste de tâches';201    return '';202  }203  function diffBlock(oldStr, newStr) {204    const d = el('div', 'diff');205    for (const l of String(oldStr || '').split('\n')) d.appendChild(el('div', 'dl del', esc('- ' + l)));206    for (const l of String(newStr || '').split('\n')) d.appendChild(el('div', 'dl add', esc('+ ' + l)));207    return d;208  }209  function toolBody(name, input) {210    const body = el('div', 'tool-body');211    input = input || {};212    if (name === 'Bash') {213      body.appendChild(el('div', 'label', 'commande'));214      body.appendChild(truncPre(input.command));215      if (input.description) body.appendChild(el('div', 'meta-line', esc(input.description)));216    } else if (name === 'Edit') {217      body.appendChild(diffBlock(input.old_string, input.new_string));218    } else if (name === 'MultiEdit') {219      for (const e of input.edits || []) body.appendChild(diffBlock(e.old_string, e.new_string));220    } else if (name === 'Write') {221      body.appendChild(el('div', 'label', 'contenu'));222      const d = el('div', 'diff');223      const lines = String(input.content || '').split('\n');224      for (const l of lines.slice(0, 40)) d.appendChild(el('div', 'dl add', esc('+ ' + l)));225      if (lines.length > 40) d.appendChild(el('div', 'dl', '… ' + (lines.length - 40) + ' lignes de plus'));226      body.appendChild(d);227    } else if (name === 'TodoWrite') {228      const ul = el('ul', 'todos');229      for (const t of input.todos || []) {230        const icon = t.status === 'completed' ? '☑' : t.status === 'in_progress' ? '◐' : '☐';231        ul.appendChild(el('li', t.status === 'completed' ? 'done' : t.status === 'in_progress' ? 'doing' : '', esc(icon + ' ' + t.content)));232      }233      body.appendChild(ul);234    } else if (name === 'Task') {235      body.appendChild(truncPre(input.prompt || JSON.stringify(input, null, 2)));236    } else if (name === 'ExitPlanMode') {237      const md = el('div', 'md'); renderMd(md, input.plan || ''); body.appendChild(md);238    } else {239      body.appendChild(truncPre(JSON.stringify(input, null, 2), 1500));240    }241    return body;242  }243  // outils dont on ouvre la carte par défaut (on veut VOIR ce qui est fait)244  const OPEN_BY_DEFAULT = new Set(['Bash', 'Edit', 'MultiEdit', 'Write', 'NotebookEdit', 'ExitPlanMode']);245  function addToolCard(block) {246    finalizeLive(); finalizeThink();247    const name = block.name || '?';248    const shortName = name.startsWith('mcp__') ? name.split('__').slice(1).join(':') : name;249    const card = el('details', 'tool');250    if (OPEN_BY_DEFAULT.has(name)) card.open = true;251    const sum = el('summary');252    sum.innerHTML = `<span class="t-icon ${TOOL_TINT[name] || ''}">${TOOL_ICONS[name] || '⚙️'}</span><span class="t-name">${esc(shortName)}</span><span class="t-sub">${esc(toolSubtitle(name, block.input))}</span><span class="t-state pending">●&nbsp;en cours</span>`;253    card.appendChild(sum);254    card.appendChild(toolBody(name, block.input));255    addMsg(card);256    toolCards.set(block.id, { card, name, stateEl: sum.querySelector('.t-state'), subEl: sum.querySelector('.t-sub'), bodyEl: card.querySelector('.tool-body') });257    // met à jour l'indicateur « en cours » avec l'action réelle258    setWorkingLabel(name, toolSubtitle(name, block.input));259  }260  function attachToolResult(block) {261    const t = toolCards.get(block.tool_use_id);262    if (!t) return;263    t.stateEl.className = 't-state ' + (block.is_error ? 'err' : 'ok');264    t.stateEl.textContent = block.is_error ? '✗ erreur' : '✓';265    let text = '';266    if (typeof block.content === 'string') text = block.content;267    else if (Array.isArray(block.content)) text = block.content.map((c) => c.type === 'text' ? c.text : '[' + c.type + ']').join('\n');268    text = text.trim();269    if (text) {270      // les cartes repliées (Read/Grep/…) montrent un aperçu du résultat dans l'en-tête271      if (!t.card.open && t.subEl) {272        const firstLine = text.split('\n').find(l => l.trim()) || '';273        t.subEl.textContent = firstLine.slice(0, 80);274      }275      t.bodyEl.appendChild(el('div', 'label', block.is_error ? 'erreur' : 'résultat'));276      t.bodyEl.appendChild(truncPre(text));277    } else {278      t.bodyEl.appendChild(el('div', 'meta-line', block.is_error ? 'erreur (vide)' : 'terminé sans sortie'));279    }280  }281282  // ---------- permissions ----------283  function addPermCard(ev) {284    finalizeLive(); finalizeThink();285    const card = el('div', 'perm');286    const isPlan = ev.tool === 'ExitPlanMode';287    card.innerHTML = `<div class="perm-title">${isPlan ? '📋 Plan proposé' : '🔐 Permission — ' + esc(ev.tool)}</div>`;288    if (isPlan && ev.input?.plan) {289      const md = el('div', 'md'); renderMd(md, ev.input.plan); card.appendChild(md);290    } else {291      const pre = el('pre'); pre.textContent = JSON.stringify(ev.input, null, 2); card.appendChild(pre);292    }293    const actions = el('div', 'perm-actions');294    const deny = el('button', 'perm-deny', 'Refuser');295    const allow = el('button', 'perm-allow', isPlan ? 'Approuver' : 'Autoriser');296    actions.append(deny, allow);297    if (!isPlan) {298      const always = el('button', 'perm-always', 'Toujours<br><small>cet outil</small>');299      always.onclick = () => send({ type: 'perm', requestId: ev.requestId, allow: true, always: true });300      actions.insertBefore(always, allow);301      // « Tout autoriser » : le serveur approuve TOUTES les permissions de la302      // session — la tâche va au bout même téléphone rangé303      const all = el('button', 'perm-allall', '🔓 Tout autoriser — finir la tâche sans redemander');304      all.onclick = () => send({ type: 'perm', requestId: ev.requestId, allow: true, allowAll: true });305      card.appendChild(actions);306      card.appendChild(all);307    } else {308      card.appendChild(actions);309    }310    deny.onclick = () => send({ type: 'perm', requestId: ev.requestId, allow: false });311    allow.onclick = () => send({ type: 'perm', requestId: ev.requestId, allow: true });312    addMsg(card);313    permCards.set(ev.requestId, card);314    scrollBottom(true);315    if (navigator.vibrate) navigator.vibrate([60, 60, 60]);316  }317  function resolvePermCard(ev) {318    const card = permCards.get(ev.requestId);319    if (!card) return;320    const actions = card.querySelector('.perm-actions');321    if (actions) actions.remove();322    const allBtn = card.querySelector('.perm-allall');323    if (allBtn) allBtn.remove();324    card.appendChild(el('div', 'perm-resolved',325      ev.allow ? ('✓ Autorisé' + (ev.always ? ' (toujours)' : '')) : ('✗ Refusé' + (ev.reason === 'timeout' ? ' (délai dépassé)' : ''))));326  }327328  // ---------- rendu des événements ----------329  function renderEvent(ev) {330    if (ev.type === 'user_prompt') {331      finalizeLive(); finalizeThink();332      const b = el('div', 'msg-user'); b.textContent = ev.text; addMsg(b);333      return;334    }335    if (ev.type === 'status') { setRunning(ev.state === 'running'); return; }336    if (ev.type === 'error') { addMsg(el('div', 'error-box', esc(ev.message))); return; }337    if (ev.type === 'notice') { addMsg(el('div', 'notice-line', esc(ev.text))); return; }338    if (ev.type === 'permission_request') { addPermCard(ev); return; }339    if (ev.type === 'permission_resolved') { resolvePermCard(ev); return; }340    if (ev.type === 'permission_auto') { addMsg(el('div', 'meta-line', esc('🔓 auto-autorisé : ' + ev.key))); return; }341    if (ev.type === 'claude') { renderClaude(ev.event); return; }342  }343344  function renderClaude(ev) {345    if (ev.type === 'system') {346      if (ev.subtype === 'init') {347        addMsg(el('div', 'meta-line', esc(`⌁ ${ev.model || ''} · session ${String(ev.session_id || '').slice(0, 8)} · ${(ev.cwd || '').replace(/^\/Users\/[^/]+\//, '~/')}`)));348      } else if (ev.subtype === 'compact_boundary') {349        addMsg(el('div', 'meta-line', '⇣ contexte compacté'));350      } else if (ev.subtype && ev.subtype !== 'hook') {351        addMsg(el('div', 'meta-line', esc('⌁ ' + ev.subtype)));352      }353      return;354    }355    if (ev.type === 'stream_event' && ev.event) {356      const se = ev.event;357      if (se.type === 'content_block_delta' && se.delta) {358        if (se.delta.type === 'text_delta') {359          const l = ensureLive();360          l.text += se.delta.text;361          renderMd(l.textEl, l.text);362          scrollBottom();363        } else if (se.delta.type === 'thinking_delta') {364          const t = ensureThink();365          t.text += se.delta.thinking;366          t.el.textContent = t.text.slice(-600);367          scrollBottom();368        }369      }370      return;371    }372    if (ev.type === 'assistant' && ev.message && Array.isArray(ev.message.content)) {373      for (const block of ev.message.content) {374        if (block.type === 'text' && block.text && block.text.trim()) {375          finalizeLive(); finalizeThink();376          const wrap = el('div', 'msg-claude');377          const md = el('div', 'md');378          renderMd(md, block.text);379          wrap.appendChild(md);380          addMsg(wrap);381        } else if (block.type === 'tool_use') {382          addToolCard(block);383        } else if (block.type === 'thinking' && block.thinking) {384          if (liveThink) { liveThink.el.remove(); liveThink = null; }385          const d = el('details', 'thinking-box', '<summary>réflexion</summary>');386          const inner = el('div', 'thinking'); inner.textContent = block.thinking;387          d.appendChild(inner);388          addMsg(d);389        }390      }391      return;392    }393    if (ev.type === 'user' && ev.message && Array.isArray(ev.message.content)) {394      for (const block of ev.message.content) if (block.type === 'tool_result') attachToolResult(block);395      return;396    }397    if (ev.type === 'result') {398      finalizeLive(); finalizeThink();399      const dur = ev.duration_ms ? (ev.duration_ms / 1000).toFixed(1) + ' s' : '';400      const cost = ev.total_cost_usd ? ' · ' + ev.total_cost_usd.toFixed(3) + ' $' : '';401      const turns = ev.num_turns ? ' · ' + ev.num_turns + ' tours' : '';402      addMsg(el('div', 'meta-line', esc('— fin ' + dur + cost + turns)));403      if (ev.is_error && ev.result) addMsg(el('div', 'error-box', esc(String(ev.result))));404      return;405    }406  }407408  // ---------- méta de session (chips + bandeau) ----------409  function refreshChips() {410    const model = currentChat ? currentChat.model : settings.model;411    const perm = currentChat ? currentChat.permMode : settings.permMode;412    $('chipModel').textContent = MODEL_LABEL[model] || model;413    $('chipPerm').textContent = PERM_LABEL[perm] || perm;414    $('chipPerm').classList.toggle('warn', perm === 'bypass');415    $('chipModel').classList.add('orange');416    const meta = $('sessMeta');417    if (currentChat && (currentChat.claudeSessionId || currentChat.totalCost)) {418      meta.classList.remove('hidden');419      $('metaModel').textContent = (currentChat.autoAllowAll ? '🔓 ' : '') + (currentChat.lastModel || MODEL_LABEL[model]);420      $('metaSid').textContent = currentChat.claudeSessionId ? 'sess ' + currentChat.claudeSessionId.slice(0, 8) : '';421      $('metaCost').textContent = fmt$(currentChat.totalCost);422      $('metaCtx').textContent = currentChat.contextTokens ? 'ctx ' + fmtTok(currentChat.contextTokens) + ' tok (' + Math.min(99, Math.round(currentChat.contextTokens / 2000)) + '%)' : '';423    } else meta.classList.add('hidden');424  }425426  // ---------- WebSocket ----------427  function send(obj) { if (ws && ws.readyState === 1) ws.send(JSON.stringify(obj)); }428  function setConn(state) {429    const pill = $('connPill');430    pill.className = 'conn-pill ' + state;431    $('connText').textContent = state === 'on' ? 'connecté' : state === 'mid' ? 'reconnexion…' : 'hors ligne';432  }433  function connect() {434    if (!wsWanted) return;435    setConn('mid');436    const proto = location.protocol === 'https:' ? 'wss' : 'ws';437    ws = new WebSocket(`${proto}://${location.host}/ws`);438    ws.onopen = () => {439      setConn('on');440      wsRetry = 1000;441      if (currentChat) send({ type: 'open', chatId: currentChat.id });442      if (curView === 'eco') send({ type: 'eco_sub' });443    };444    ws.onclose = () => {445      setConn('off');446      setTimeout(connect, wsRetry);447      wsRetry = Math.min(wsRetry * 1.6, 20000);448    };449    ws.onmessage = (e) => {450      let msg;451      try { msg = JSON.parse(e.data); } catch { return; }452      handleServer(msg);453    };454  }455  function rememberChat(id) { settings.lastChatId = id; saveStore(); }456  function handleServer(msg) {457    if (msg.type === 'chat_created') { currentChat = msg.chat; rememberChat(msg.chat.id); refreshChips(); return; }458    if (msg.type === 'chat_meta') {459      if (currentChat && msg.chat.id === currentChat.id) { currentChat = msg.chat; refreshChips(); }460      return;461    }462    if (msg.type === 'history') {463      currentChat = msg.chat;464      rememberChat(msg.chat.id);465      clearConversation(true);466      for (const ev of msg.events) { try { renderEvent(ev); } catch {} }467      setRunning(msg.running);468      for (const o of projectSel.options) if (o.value === msg.chat.projectId) projectSel.value = o.value;469      refreshChips();470      scrollBottom(true);471      return;472    }473    if (msg.type === 'notify') {474      if (msg.kind === 'done') {475        if (!(curView === 'chat' && currentChat && currentChat.id === msg.chatId && !document.hidden)) {476          banner('good', `✓ Tâche terminée — ${esc(msg.title || '')}`, () => openChat(msg.chatId));477          navBadge('chat'); navBadge('sessions');478        }479      } else if (msg.kind === 'perm') {480        if (!(curView === 'chat' && currentChat && currentChat.id === msg.chatId && !document.hidden)) {481          banner('warn', `🔐 Permission attendue (${esc(msg.tool || '')}) — ${esc(msg.title || '')}`, () => openChat(msg.chatId), 12000);482          navBadge('chat');483        }484      }485      return;486    }487    if (msg.type === 'eco_alert') {488      if (msg.kind === 'down') banner('bad', `🔴 ${esc(msg.site)} est HORS LIGNE — ${esc(msg.reason || '')}`, () => switchView('eco'), 12000);489      else banner('good', `🟢 ${esc(msg.site)} est de retour en ligne`, () => switchView('eco'));490      navBadge('eco');491      if (curView === 'eco') loadEco();492      return;493    }494    if (msg.type === 'eco') {495      if (msg.kind === 'checks' && ecoData && curView === 'eco') applyChecks(msg.items);496      return;497    }498    renderEvent(msg);499  }500501  function clearConversation(keepChat) {502    messagesEl.innerHTML = '';503    toolCards.clear(); permCards.clear();504    live = null; liveThink = null;505    if (!keepChat && !currentChat) $('welcome').classList.remove('hidden');506  }507  function openChat(chatId) {508    switchView('chat');509    currentChat = { id: chatId };510    clearConversation(true);511    send({ type: 'open', chatId });512  }513514  // ---------- composer ----------515  function doSend(text) {516    send({517      type: 'start',518      chatId: currentChat ? currentChat.id : null,519      project: projectSel.value,520      model: currentChat ? currentChat.model : settings.model,521      permMode: currentChat ? currentChat.permMode : settings.permMode,522      prompt: text,523    });524  }525  function sendPrompt() {526    const text = inputEl.value.trim();527    if (!text) return;528    // commandes slash locales529    if (text === '/clear') { if (currentChat) send({ type: 'clear', chatId: currentChat.id }); inputEl.value = ''; autoGrow(); return; }530    if (text === '/cost') {531      if (currentChat) addMsg(el('div', 'meta-line', esc(`coût cumulé ${fmt$(currentChat.totalCost)} · ${currentChat.turns || 0} tours · ctx ${fmtTok(currentChat.contextTokens)} tok`)));532      inputEl.value = ''; autoGrow(); return;533    }534    if (text === '/resume') { switchView('sessions'); inputEl.value = ''; autoGrow(); return; }535    inputEl.value = '';536    autoGrow();537    hideSlash();538    if (isRunning) {539      // Claude travaille : le message part automatiquement dès la fin du tour540      queuedPrompt = queuedPrompt ? queuedPrompt + '\n' + text : text;541      let n = messagesEl.querySelector('.queued-notice');542      if (!n) { n = el('div', 'notice-line queued-notice'); messagesEl.appendChild(n); }543      n.textContent = '⏳ en attente de la fin du tour : « ' + queuedPrompt.slice(0, 80) + ' »';544      scrollBottom(true);545      return;546    }547    doSend(text);548  }549  sendBtn.onclick = sendPrompt;550  stopBtn.onclick = () => { if (currentChat) send({ type: 'interrupt', chatId: currentChat.id }); };551  inputEl.addEventListener('keydown', (e) => {552    if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendPrompt(); }553  });554  function autoGrow() {555    inputEl.style.height = 'auto';556    inputEl.style.height = Math.min(inputEl.scrollHeight, 140) + 'px';557  }558  inputEl.addEventListener('input', () => {559    autoGrow();560    if (inputEl.value.startsWith('/')) showSlash(); else hideSlash();561  });562  inputEl.addEventListener('focus', () => setTimeout(() => scrollBottom(true), 300));563564  function showSlash() {565    const h = $('slashHint');566    h.classList.remove('hidden');567    if (!h.childElementCount) {568      for (const [cmd, tip] of [['/clear', 'effacer le contexte'], ['/compact', 'compacter la session'], ['/cost', 'coût de la session'], ['/resume', 'liste des sessions']]) {569        const b = el('button', '', `${cmd} <span style="color:var(--muted);font-weight:600">${tip}</span>`);570        b.onclick = () => { inputEl.value = cmd; hideSlash(); sendPrompt(); };571        h.appendChild(b);572      }573    }574  }575  function hideSlash() { $('slashHint').classList.add('hidden'); }576577  document.querySelectorAll('.hint').forEach((h) => {578    h.onclick = () => { inputEl.value = h.textContent; autoGrow(); inputEl.focus(); };579  });580581  // ---------- chips ----------582  $('chipModel').onclick = () => {583    const order = ['fable', 'opus', 'sonnet', 'haiku'];584    const cur = currentChat ? currentChat.model : settings.model;585    const next = order[(order.indexOf(cur) + 1) % order.length];586    applyOpts({ model: next });587  };588  $('chipPerm').onclick = () => {589    const order = ['default', 'acceptEdits', 'plan', 'bypass'];590    const cur = currentChat ? currentChat.permMode : settings.permMode;591    const next = order[(order.indexOf(cur) + 1) % 4];592    if (next === 'bypass' && !confirm('Mode BYPASS : Claude Code exécutera TOUTES les actions sans demander. Continuer ?')) return;593    applyOpts({ permMode: next });594  };595  function applyOpts(opts) {596    if (currentChat) {597      Object.assign(currentChat, opts);598      send({ type: 'set_opts', chatId: currentChat.id, model: currentChat.model, permMode: currentChat.permMode });599    }600    if (opts.model) settings.model = opts.model;601    if (opts.permMode) settings.permMode = opts.permMode;602    saveStore();603    refreshChips();604    refreshSettingsView();605  }606  $('chipMore').onclick = () => {607    const c = currentChat;608    openSheet(`609      <div class="sheet-h"><h3>Session</h3></div>610      <div class="sheet-sec">611        <div class="kv"><span>Projet</span><b>${esc(c ? c.projectName : projectSel.selectedOptions[0]?.textContent || '—')}</b></div>612        <div class="kv"><span>Session Claude Code</span><b>${c?.claudeSessionId ? c.claudeSessionId.slice(0, 12) + '…' : '—'}</b></div>613        <div class="kv"><span>Modèle du dernier tour</span><b>${esc(c?.lastModel || '—')}</b></div>614        <div class="kv"><span>Coût cumulé</span><b>${fmt$(c?.totalCost)}</b></div>615        <div class="kv"><span>Contexte</span><b>${c?.contextTokens ? fmtTok(c.contextTokens) + ' tokens' : '—'}</b></div>616      </div>617      <div class="sheet-sec">618        <div class="set-actions">619          <button class="btn-ghost" id="shClear">/clear — nouveau contexte</button>620          <button class="btn-ghost" id="shCompact">/compact</button>621          <button class="btn-ghost" id="shNew">+ Nouvelle conversation</button>622        </div>623      </div>`);624    $('shClear').onclick = () => { if (c) send({ type: 'clear', chatId: c.id }); closeSheet(); };625    $('shCompact').onclick = () => { closeSheet(); inputEl.value = '/compact'; sendPrompt(); };626    $('shNew').onclick = () => { closeSheet(); newChat(); };627  };628  function newChat() {629    currentChat = null;630    queuedPrompt = null;631    settings.lastChatId = null; saveStore();632    clearConversation();633    setRunning(false);634    refreshChips();635    switchView('chat');636  }637638  // ---------- sessions ----------639  async function loadSessions() {640    const r = await fetch('/api/chats');641    if (!r.ok) return;642    const { chats } = await r.json();643    const list = $('sessList');644    list.innerHTML = '';645    if (!chats.length) { list.appendChild(el('div', 'sess-empty', 'Aucune session. Lance une conversation dans l’onglet Chat.')); return; }646    const stLabel = { running: '● en cours', waiting_perm: '🔐 permission', idle: '✓ terminée' };647    for (const c of chats) {648      const card = el('div', 'sess-card');649      card.innerHTML = `650        <div class="sess-top">651          <span class="sess-title">${esc(c.title)}</span>652          <span class="sess-badge ${c.state}">${stLabel[c.state] || c.state}</span>653        </div>654        <div class="sess-info">655          <span>${esc(c.projectName || '')}</span>656          <span>${MODEL_LABEL[c.model] || c.model}</span>657          <span>${fmt$(c.totalCost)}</span>658          <span>${timeAgo(c.updated)}</span>659        </div>`;660      const actions = el('div', 'sess-actions');661      const open = el('button', '', c.state === 'idle' ? 'Reprendre' : 'Ouvrir');662      open.onclick = (e) => { e.stopPropagation(); openChat(c.id); };663      actions.appendChild(open);664      if (c.state === 'idle') {665        const del = el('button', 'del', 'Supprimer');666        del.onclick = async (e) => {667          e.stopPropagation();668          if (!confirm('Supprimer cette session ?')) return;669          await fetch('/api/chats/' + c.id, { method: 'DELETE' });670          card.remove();671          if (currentChat && currentChat.id === c.id) { currentChat = null; clearConversation(); }672        };673        actions.appendChild(del);674      }675      card.appendChild(actions);676      card.onclick = () => openChat(c.id);677      list.appendChild(card);678    }679  }680  $('newSessBtn').onclick = newChat;681682  // incidents globaux (bouton en tête de l'onglet Écosystème)683  $('incBtn').onclick = async () => {684    const r = await fetch('/api/eco/incidents');685    if (!r.ok) return;686    const { incidents } = await r.json();687    const label = (app) => (ecoData?.sites.find(s => s.app === app)?.label) || app;688    openSheet(`689      <div class="sheet-h"><h3>Incidents</h3></div>690      <div class="sheet-sec">691        <h4>Historique — 50 derniers</h4>692        ${incidents.length ? incidents.map(i => `693          <div class="inc-item"><span class="${i.ended ? 'inc-ok' : 'inc-dot'}">${i.ended ? '✓' : '■'}</span>694          <span><b>${esc(label(i.site))}</b> · ${new Date(i.started).toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}695          ${i.ended ? ' → rétabli en ' + Math.round((i.ended - i.started) / 60000) + ' min' : ' — <b style="color:var(--bad)">EN COURS</b>'} · ${esc(i.reason || '')}</span></div>`).join('')696          : '<div style="color:var(--muted)">Aucun incident enregistré 🎉</div>'}697      </div>`);698  };699700  // ---------- écosystème ----------701  function siteStatus(s) {702    if (s.incident || (s.last && !s.last.ok)) return 'down';703    if (s.last && s.last.ms > 4000) return 'slow';704    return s.last ? 'up' : 'unknown';705  }706  const ST = {707    up: { cls: 'up', ico: '●', lbl: 'EN LIGNE' },708    slow: { cls: 'slow', ico: '▲', lbl: 'LENT' },709    down: { cls: 'down', ico: '■', lbl: 'HORS LIGNE' },710    unknown: { cls: 'slow', ico: '▲', lbl: '…' },711  };712  function sparkline(spark, w = 120, h = 30) {713    if (!spark || spark.length < 2) return '<svg class="spark"></svg>';714    const ms = spark.map(p => p.ok ? p.ms : null);715    const max = Math.max(...ms.filter(v => v !== null), 100) * 1.15;716    const step = w / (spark.length - 1);717    let d = '', pen = false;718    spark.forEach((p, i) => {719      if (!p.ok) { pen = false; return; }720      const x = i * step, y = h - 3 - (p.ms / max) * (h - 8);721      d += (pen ? 'L' : 'M') + x.toFixed(1) + ' ' + y.toFixed(1);722      pen = true;723    });724    const fails = spark.map((p, i) => !p.ok ? `<rect x="${(i * step - 1.5).toFixed(1)}" y="${h - 7}" width="3" height="5" fill="var(--bad)"/>` : '').join('');725    return `<svg class="spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none"><path d="${d}" fill="none" stroke="var(--orange-deep)" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>${fails}</svg>`;726  }727  async function loadEco() {728    const [r, rn] = await Promise.all([fetch('/api/eco/summary'), fetch('/api/eco/nodes')]);729    if (!r.ok) return;730    ecoData = await r.json();731    renderEco();732    if (rn.ok) renderNodes(await rn.json());733  }734  function nbar(label, val, pct) {735    const c = pct > 88 ? 'var(--bad)' : pct > 70 ? 'var(--warn)' : 'var(--good)';736    return `<div class="nbar"><div class="nbar-l"><span>${label}</span><b>${val}</b></div>737      <div class="nbar-track"><div class="nbar-fill" style="width:${Math.max(2, Math.min(100, pct))}%;background:${c}"></div></div></div>`;738  }739  function renderNodes(data) {740    const grid = $('ecoNodes');741    if (!grid) return;742    grid.innerHTML = '';743    for (const n of data.nodes) {744      const L = n.last;745      const memPct = L && L.mem_total ? Math.round(L.mem_used / L.mem_total * 100) : null;746      const upApps = n.apps.filter(a => a.status === 'online').length;747      const badApp = n.apps.some(a => a.status && a.status !== 'online');748      const card = el('div', 'node-card' + (badApp ? ' warn' : ''));749      card.innerHTML = `750        <div class="node-top"><span class="node-name">${esc(n.node)}</span>751          <span class="node-apps${badApp ? ' bad' : ''}">${upApps}/${n.apps.length} apps</span></div>752        ${nbar('charge', L ? L.load1.toFixed(1) : '—', L ? Math.min(100, L.load1 / 32 * 100) : 0)}753        ${nbar('RAM', memPct !== null ? memPct + '%' : '—', memPct || 0)}754        ${nbar('disque', L ? L.disk_pct + '%' : '—', L ? L.disk_pct : 0)}`;755      grid.appendChild(card);756    }757  }758  function applyChecks(items) {759    if (!ecoData) return;760    for (const it of items) {761      const s = ecoData.sites.find(x => x.app === it.site);762      if (!s) continue;763      s.last = { ts: it.ts, ms: it.ms, code: it.code, ok: it.ok, err: it.err };764      s.spark.push({ ts: it.ts, ms: it.ms, ok: it.ok });765      if (s.spark.length > 40) s.spark.shift();766    }767    renderEco();768  }769  function renderEco() {770    const sites = ecoData.sites;771    const up = sites.filter(s => siteStatus(s) === 'up').length;772    const down = sites.filter(s => siteStatus(s) === 'down').length;773    const lat = sites.filter(s => s.last?.ok).map(s => s.last.ms);774    const avg = lat.length ? Math.round(lat.reduce((a, b) => a + b, 0) / lat.length) : 0;775    $('ecoStamp').textContent = 'maj ' + new Date().toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit', second: '2-digit' });776    $('ecoOverview').innerHTML = `777      <div class="eco-stat ok"><div class="v">${up}/${sites.length}</div><div class="l">en ligne</div></div>778      <div class="eco-stat ${down ? 'bad' : ''}"><div class="v">${down}</div><div class="l">hors ligne</div></div>779      <div class="eco-stat"><div class="v">${avg}<small style="font-size:12px"> ms</small></div><div class="l">latence moy.</div></div>`;780    const grid = $('ecoGrid');781    grid.innerHTML = '';782    const order = { down: 0, slow: 1, unknown: 2, up: 3 };783    for (const s of [...sites].sort((a, b) => order[siteStatus(a)] - order[siteStatus(b)])) {784      const st = ST[siteStatus(s)];785      const card = el('div', 'site-card' + (siteStatus(s) === 'down' ? ' down' : ''));786      card.innerHTML = `787        <div class="site-top">788          <span class="site-name">${esc(s.label)}</span>789          <span class="st-pill ${st.cls}">${st.ico} ${st.lbl}</span>790        </div>791        <div class="site-mid">792          <div class="site-ms">${s.last?.ok ? s.last.ms : '—'}<small> ms</small></div>793          ${sparkline(s.spark)}794        </div>795        <div class="site-foot">796          <span>up 24h <b>${s.uptime24 ?? '—'}%</b></span>797          <span>p95 <b>${s.p95_24 ?? '—'} ms</b></span>798          <span>${esc(s.node)}</span>799          ${s.proc?.status ? `<span class="${s.proc.status === 'online' ? '' : 'foot-bad'}">pm2 <b>${esc(s.proc.status)}</b></span>` : ''}800          ${s.certExpires ? `<span>SSL <b>${Math.max(0, Math.round((s.certExpires - Date.now()) / 86400000))} j</b></span>` : ''}801        </div>`;802      card.onclick = () => openSiteSheet(s.app);803      grid.appendChild(card);804    }805  }806807  async function openSiteSheet(app) {808    const r = await fetch('/api/eco/site/' + app);809    if (!r.ok) return;810    const d = await r.json();811    const s = ecoData.sites.find(x => x.app === app) || {};812    const st = ST[siteStatus(s)];813    const certDays = s.certExpires ? Math.max(0, Math.round((s.certExpires - Date.now()) / 86400000)) : null;814    openSheet(`815      <div class="sheet-h">816        <h3>${esc(d.label)}</h3>817        <span class="st-pill ${st.cls}">${st.ico} ${st.lbl}</span>818      </div>819      <div class="sheet-sec">820        <h4>Disponibilité</h4>821        <div class="tile-row">822          <div class="tile"><div class="v">${s.uptime24 ?? '—'}%</div><div class="l">24 h</div></div>823          <div class="tile"><div class="v">${s.uptime7 ?? '—'}%</div><div class="l">7 j</div></div>824          <div class="tile"><div class="v">${s.uptime30 ?? '—'}%</div><div class="l">30 j</div></div>825        </div>826        <div style="margin-top:10px">${uptimeDays(d.days)}</div>827      </div>828      <div class="sheet-sec">829        <h4>Latence — 24 h</h4>830        ${latencyChart(d.series)}831        <div class="tile-row" style="margin-top:10px">832          <div class="tile"><div class="v">${s.avg24 ?? '—'}</div><div class="l">moy ms</div></div>833          <div class="tile"><div class="v">${s.p95_24 ?? '—'}</div><div class="l">p95 ms</div></div>834          <div class="tile"><div class="v">${s.last?.code || '—'}</div><div class="l">HTTP</div></div>835        </div>836      </div>837      <div class="sheet-sec">838        <h4>Service</h4>839        <div class="kv"><span>Domaine</span><b>${esc(d.domain)}</b></div>840        <div class="kv"><span>Nœud</span><b>${esc(d.node)}</b></div>841        <div class="kv"><span>PM2</span><b>${esc(s.proc?.status || '—')}${s.proc?.restarts ? ' · ' + s.proc.restarts + ' restarts' : ''}</b></div>842        <div class="kv"><span>CPU / RAM process</span><b>${s.proc ? s.proc.cpu + '% / ' + fmtMB(s.proc.mem) : '—'}</b></div>843        <div class="kv"><span>Charge nœud</span><b>${s.nodeStat ? s.nodeStat.load1 + ' · RAM ' + Math.round(s.nodeStat.mem_used / s.nodeStat.mem_total * 100) + '% · disque ' + s.nodeStat.disk_pct + '%' : '—'}</b></div>844        <div class="kv"><span>Dernier commit</span><b>${s.proc?.last_commit ? timeAgo(s.proc.last_commit) : '—'}</b></div>845        <div class="kv"><span>Certificat SSL</span><b>${certDays !== null ? 'expire dans ' + certDays + ' j' : '—'}</b></div>846      </div>847      ${d.incidents.length ? `<div class="sheet-sec"><h4>Incidents — 30 j</h4>${d.incidents.map(i => `848        <div class="inc-item"><span class="${i.ended ? 'inc-ok' : 'inc-dot'}">${i.ended ? '✓' : '■'}</span>849        <span>${new Date(i.started).toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}850        ${i.ended ? ' → ' + Math.round((i.ended - i.started) / 60000) + ' min' : ' — EN COURS'} · ${esc(i.reason || '')}</span></div>`).join('')}</div>` : ''}851      ${d.errors.length ? `<div class="sheet-sec"><h4>Erreurs récentes</h4>${d.errors.slice(0, 8).map(e => `852        <div class="inc-item"><span class="inc-dot">✗</span><span>${new Date(e.ts).toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })} · ${e.code ? 'HTTP ' + e.code : esc(e.err || '')}</span></div>`).join('')}</div>` : ''}853      <div class="sheet-sec">854        <h4>Actions d'administration</h4>855        <div class="admin-actions">856          <button class="btn-ghost" id="aRestart">↻ Redémarrer PM2</button>857          <button class="btn-ghost" id="aLogs">📜 Logs récents</button>858          <button class="btn-ghost" id="aCommits">⌥ Git & commits</button>859          <a class="btn-ghost" href="https://${esc(d.domain)}" target="_blank" rel="noopener">↗ Ouvrir le site</a>860        </div>861        <div id="aOut" class="admin-out hidden"></div>862      </div>863      <button class="btn-cta" style="width:100%" id="shChat">💬 Demander à Claude Code →</button>864    `);865    $('shChat').onclick = () => {866      closeSheet();867      newChat();868      for (const o of projectSel.options) if (o.value.startsWith(d.app + '@')) projectSel.value = o.value;869    };870    const out = () => $('aOut');871    const showOut = (html) => { out().classList.remove('hidden'); out().innerHTML = html; };872    $('aRestart').onclick = async () => {873      if (!confirm(`Redémarrer ${d.label} (pm2 restart) sur ${d.node} ?`)) return;874      showOut('<div class="admin-load">redémarrage…</div>');875      const r = await fetch('/api/admin/action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ app: d.app, action: 'restart' }) });876      const j = await r.json();877      showOut(`<div class="${j.ok ? 'admin-ok' : 'admin-err'}">${j.ok ? '✓ redémarré' : '✗ échec'} — statut : ${esc(j.output || '')}</div>`);878      if (navigator.vibrate) navigator.vibrate(60);879    };880    $('aLogs').onclick = async () => {881      showOut('<div class="admin-load">chargement des logs…</div>');882      const r = await fetch('/api/admin/logs/' + d.app);883      const j = await r.json();884      showOut(`<pre>${esc((j.logs || '').slice(-4000))}</pre>`);885    };886    $('aCommits').onclick = async () => {887      showOut('<div class="admin-load">…</div>');888      const r = await fetch('/api/admin/commits/' + d.app);889      const j = await r.json();890      showOut(`<pre>${esc(j.text || '')}</pre>`);891    };892    attachChartTips();893  }894895  function uptimeDays(days) {896    if (!days) return '';897    const cells = days.map(dd => {898      const u = dd.uptime;899      const c = u === null ? 'var(--line)' : u >= 99.5 ? 'var(--good)' : u >= 95 ? 'var(--warn)' : 'var(--bad)';900      return `<div title="${new Date(dd.day).toLocaleDateString('fr-CA')} — ${u === null ? 'aucune donnée' : u + '%'}" style="flex:1;height:22px;border-radius:5px;background:${c};border:1.5px solid var(--line)"></div>`;901    }).join('');902    return `<div style="display:flex;gap:4px">${cells}</div><div style="display:flex;justify-content:space-between;font-size:10px;color:var(--muted);font-family:var(--mono);margin-top:3px"><span>il y a 14 j</span><span>aujourd'hui</span></div>`;903  }904905  function latencyChart(series) {906    const W = 340, H = 130, PL = 38, PB = 18, PT = 8;907    if (!series || series.length < 2) return '<div style="color:var(--muted);font-size:13px">Pas encore assez de données.</div>';908    const ok = series.filter(p => p.ok);909    const max = Math.max(...ok.map(p => p.ms), 100) * 1.15;910    const x = (t) => PL + ((t - series[0].t) / (series[series.length - 1].t - series[0].t)) * (W - PL - 6);911    const y = (ms) => PT + (1 - ms / max) * (H - PT - PB);912    let d = '', pen = false;913    const pts = [];914    for (const p of series) {915      if (!p.ok) { pen = false; continue; }916      const px = x(p.t), py = y(p.ms);917      d += (pen ? 'L' : 'M') + px.toFixed(1) + ' ' + py.toFixed(1);918      pts.push({ x: px, y: py, ms: Math.round(p.ms), t: p.t });919      pen = true;920    }921    const failMarks = series.filter(p => !p.ok).map(p =>922      `<rect x="${(x(p.t) - 2).toFixed(1)}" y="${H - PB - 6}" width="4" height="6" fill="var(--bad)"/>`).join('');923    const gridLines = [0.25, 0.5, 0.75, 1].map(f => {924      const gy = y(max * f / 1.15);925      return `<line x1="${PL}" y1="${gy}" x2="${W - 6}" y2="${gy}" stroke="var(--grid)" stroke-width="1"/>926        <text x="${PL - 5}" y="${gy + 3.5}" text-anchor="end" font-size="9" fill="var(--muted)" font-family="var(--mono)">${Math.round(max * f / 1.15)}</text>`;927    }).join('');928    const lastPt = pts[pts.length - 1];929    const lastLbl = lastPt ? `<circle cx="${lastPt.x}" cy="${lastPt.y}" r="3.5" fill="var(--orange-deep)" stroke="var(--card)" stroke-width="2"/>930      <text x="${Math.min(lastPt.x, W - 40)}" y="${Math.max(lastPt.y - 8, 10)}" font-size="10" font-weight="800" fill="var(--ink)" font-family="var(--mono)">${lastPt.ms} ms</text>` : '';931    const t0 = new Date(series[0].t), t1 = new Date(series[series.length - 1].t);932    const fmtH = (dt) => dt.getHours().toString().padStart(2, '0') + 'h';933    return `<div style="position:relative">934      <svg class="chart lat-chart" viewBox="0 0 ${W} ${H}" data-pts='${JSON.stringify(pts.map(p => ({ x: +p.x.toFixed(1), y: +p.y.toFixed(1), ms: p.ms, t: p.t })))}'>935        ${gridLines}936        <path d="${d}" fill="none" stroke="var(--orange-deep)" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>937        ${failMarks}${lastLbl}938        <text x="${PL}" y="${H - 4}" font-size="9" fill="var(--muted)" font-family="var(--mono)">${fmtH(t0)}</text>939        <text x="${W - 6}" y="${H - 4}" text-anchor="end" font-size="9" fill="var(--muted)" font-family="var(--mono)">${fmtH(t1)}</text>940      </svg></div>`;941  }942  function attachChartTips() {943    document.querySelectorAll('.lat-chart').forEach((svg) => {944      const pts = JSON.parse(svg.dataset.pts || '[]');945      if (!pts.length) return;946      const wrap = svg.parentElement;947      let tip = null;948      const show = (clientX) => {949        const rect = svg.getBoundingClientRect();950        const vx = (clientX - rect.left) / rect.width * 340;951        let best = pts[0];952        for (const p of pts) if (Math.abs(p.x - vx) < Math.abs(best.x - vx)) best = p;953        if (!tip) { tip = el('div', 'chart-tip'); wrap.appendChild(tip); }954        tip.textContent = `${new Date(best.t).toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit' })} · ${best.ms} ms`;955        tip.style.left = (best.x / 340 * rect.width) + 'px';956        tip.style.top = (best.y / 130 * rect.height) + 'px';957      };958      svg.addEventListener('pointerdown', (e) => show(e.clientX));959      svg.addEventListener('pointermove', (e) => { if (e.buttons || e.pointerType === 'mouse') show(e.clientX); });960      svg.addEventListener('pointerleave', () => { if (tip) { tip.remove(); tip = null; } });961    });962  }963964  // rafraîchissement périodique de l'onglet éco (en plus du push)965  setInterval(() => { if (curView === 'eco' && !document.hidden) loadEco(); }, 60000);966  // retour au premier plan (iOS coupe le WS quand l'écran se verrouille) :967  // reconnexion IMMÉDIATE + resynchronisation de la conversation en cours968  document.addEventListener('visibilitychange', () => {969    if (document.hidden) return;970    if (!ws || ws.readyState !== 1) {971      wsRetry = 500;972      try { ws && ws.close(); } catch {}973      connect();974    } else if (currentChat) {975      send({ type: 'open', chatId: currentChat.id });976    }977    if (curView === 'eco') loadEco();978  });979  window.addEventListener('online', () => { wsRetry = 500; if (!ws || ws.readyState !== 1) connect(); });980981  // ---------- feuille ----------982  function openSheet(html) {983    $('sheetBody').innerHTML = html;984    $('sheet').classList.remove('hidden');985  }986  function closeSheet() { $('sheet').classList.add('hidden'); }987  $('sheetBack').onclick = closeSheet;988989  // ---------- réglages ----------990  function refreshSettingsView() {991    document.querySelectorAll('#segModel button').forEach(b => b.classList.toggle('on', b.dataset.v === settings.model));992    document.querySelectorAll('#segPerm button').forEach(b => b.classList.toggle('on', b.dataset.v === settings.permMode));993    $('setSid').textContent = currentChat?.claudeSessionId ? currentChat.claudeSessionId.slice(0, 12) + '…' : '—';994    $('setCost').textContent = currentChat ? fmt$(currentChat.totalCost) : '—';995    $('setCtx').textContent = currentChat?.contextTokens ? fmtTok(currentChat.contextTokens) + ' tokens' : '—';996  }997  document.querySelectorAll('#segModel button').forEach(b => { b.onclick = () => applyOpts({ model: b.dataset.v }); });998  document.querySelectorAll('#segPerm button').forEach(b => {999    b.onclick = () => {1000      if (b.dataset.v === 'bypass' && !confirm('Mode BYPASS : Claude Code exécutera TOUTES les actions sans demander. Continuer ?')) return;1001      applyOpts({ permMode: b.dataset.v });1002    };1003  });1004  $('btnClear').onclick = () => { if (currentChat) { send({ type: 'clear', chatId: currentChat.id }); switchView('chat'); } };1005  $('btnCompact').onclick = () => { switchView('chat'); inputEl.value = '/compact'; sendPrompt(); };1006  $('logoutBtn').onclick = async () => {1007    wsWanted = false;1008    await fetch('/api/logout', { method: 'POST' });1009    location.reload();1010  };10111012  // ---------- login / init ----------1013  async function init() {1014    const me = await fetch('/api/me');1015    if (!me.ok) {1016      $('login').classList.remove('hidden');1017      $('app').classList.add('hidden');1018      return;1019    }1020    const info = await me.json();1021    $('setHost').textContent = (info.node || 'M3U96a') + ':3300';1022    $('login').classList.add('hidden');1023    $('app').classList.remove('hidden');1024    const pr = await fetch('/api/projects');1025    const { projects } = await pr.json();1026    projectSel.innerHTML = '';1027    for (const p of projects) {1028      const o = document.createElement('option');1029      o.value = p.id; o.textContent = p.name + ' · ' + p.node;1030      projectSel.appendChild(o);1031    }1032    if (settings.projectId) projectSel.value = settings.projectId;1033    projectSel.onchange = () => { settings.projectId = projectSel.value; saveStore(); };1034    refreshChips();1035    refreshSettingsView();1036    // reprise automatique : on rouvre la dernière conversation (historique +1037    // live si une tâche tourne encore) même après fermeture complète de l'app1038    if (settings.lastChatId) currentChat = { id: settings.lastChatId };1039    connect();1040  }1041  $('loginBtn').onclick = doLogin;1042  $('password').addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });1043  async function doLogin() {1044    const r = await fetch('/api/login', {1045      method: 'POST',1046      headers: { 'Content-Type': 'application/json' },1047      body: JSON.stringify({ password: $('password').value }),1048    });1049    if (r.ok) { $('password').value = ''; init(); }1050    else {1051      const d = await r.json().catch(() => ({}));1052      $('loginError').textContent = d.error || 'Erreur';1053    }1054  }10551056  init();1057})();1058
Files · 5c1b0038b12924b272dd41edf2b6f331b4942f70
Menu

Theme