SPB Git

spb/admin-ka

Public
51.7 KB · 1,095 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  // ---------- upgradeur de prompt (Opus 4.8 + savoir Groupe KA) ----------582  const upgradeBtn = $('upgradeBtn');583  let upgrading = false;584  upgradeBtn.onclick = async () => {585    const raw = inputEl.value.trim();586    if (!raw || upgrading) return;587    upgrading = true;588    upgradeBtn.classList.add('busy');589    const original = inputEl.value;590    inputEl.disabled = true;591    inputEl.value = '✨ amélioration du prompt avec Opus 4.8…';592    try {593      const r = await fetch('/api/upgrade-prompt', {594        method: 'POST',595        headers: { 'Content-Type': 'application/json' },596        body: JSON.stringify({ prompt: raw, project: projectSel.value }),597      });598      const d = await r.json();599      if (r.ok && d.upgraded) {600        inputEl.value = d.upgraded;601        if (navigator.vibrate) navigator.vibrate(40);602      } else {603        inputEl.value = original;604        banner('bad', '✗ Upgrade impossible : ' + esc(d.error || 'erreur'), null, 5000);605      }606    } catch (e) {607      inputEl.value = original;608      banner('bad', '✗ Upgrade impossible (réseau)', null, 5000);609    } finally {610      inputEl.disabled = false;611      upgrading = false;612      upgradeBtn.classList.remove('busy');613      autoGrow();614      inputEl.focus();615    }616  };617618  // ---------- chips ----------619  $('chipModel').onclick = () => {620    const order = ['fable', 'opus', 'sonnet', 'haiku'];621    const cur = currentChat ? currentChat.model : settings.model;622    const next = order[(order.indexOf(cur) + 1) % order.length];623    applyOpts({ model: next });624  };625  $('chipPerm').onclick = () => {626    const order = ['default', 'acceptEdits', 'plan', 'bypass'];627    const cur = currentChat ? currentChat.permMode : settings.permMode;628    const next = order[(order.indexOf(cur) + 1) % 4];629    if (next === 'bypass' && !confirm('Mode BYPASS : Claude Code exécutera TOUTES les actions sans demander. Continuer ?')) return;630    applyOpts({ permMode: next });631  };632  function applyOpts(opts) {633    if (currentChat) {634      Object.assign(currentChat, opts);635      send({ type: 'set_opts', chatId: currentChat.id, model: currentChat.model, permMode: currentChat.permMode });636    }637    if (opts.model) settings.model = opts.model;638    if (opts.permMode) settings.permMode = opts.permMode;639    saveStore();640    refreshChips();641    refreshSettingsView();642  }643  $('chipMore').onclick = () => {644    const c = currentChat;645    openSheet(`646      <div class="sheet-h"><h3>Session</h3></div>647      <div class="sheet-sec">648        <div class="kv"><span>Projet</span><b>${esc(c ? c.projectName : projectSel.selectedOptions[0]?.textContent || '—')}</b></div>649        <div class="kv"><span>Session Claude Code</span><b>${c?.claudeSessionId ? c.claudeSessionId.slice(0, 12) + '…' : '—'}</b></div>650        <div class="kv"><span>Modèle du dernier tour</span><b>${esc(c?.lastModel || '—')}</b></div>651        <div class="kv"><span>Coût cumulé</span><b>${fmt$(c?.totalCost)}</b></div>652        <div class="kv"><span>Contexte</span><b>${c?.contextTokens ? fmtTok(c.contextTokens) + ' tokens' : '—'}</b></div>653      </div>654      <div class="sheet-sec">655        <div class="set-actions">656          <button class="btn-ghost" id="shClear">/clear — nouveau contexte</button>657          <button class="btn-ghost" id="shCompact">/compact</button>658          <button class="btn-ghost" id="shNew">+ Nouvelle conversation</button>659        </div>660      </div>`);661    $('shClear').onclick = () => { if (c) send({ type: 'clear', chatId: c.id }); closeSheet(); };662    $('shCompact').onclick = () => { closeSheet(); inputEl.value = '/compact'; sendPrompt(); };663    $('shNew').onclick = () => { closeSheet(); newChat(); };664  };665  function newChat() {666    currentChat = null;667    queuedPrompt = null;668    settings.lastChatId = null; saveStore();669    clearConversation();670    setRunning(false);671    refreshChips();672    switchView('chat');673  }674675  // ---------- sessions ----------676  async function loadSessions() {677    const r = await fetch('/api/chats');678    if (!r.ok) return;679    const { chats } = await r.json();680    const list = $('sessList');681    list.innerHTML = '';682    if (!chats.length) { list.appendChild(el('div', 'sess-empty', 'Aucune session. Lance une conversation dans l’onglet Chat.')); return; }683    const stLabel = { running: '● en cours', waiting_perm: '🔐 permission', idle: '✓ terminée' };684    for (const c of chats) {685      const card = el('div', 'sess-card');686      card.innerHTML = `687        <div class="sess-top">688          <span class="sess-title">${esc(c.title)}</span>689          <span class="sess-badge ${c.state}">${stLabel[c.state] || c.state}</span>690        </div>691        <div class="sess-info">692          <span>${esc(c.projectName || '')}</span>693          <span>${MODEL_LABEL[c.model] || c.model}</span>694          <span>${fmt$(c.totalCost)}</span>695          <span>${timeAgo(c.updated)}</span>696        </div>`;697      const actions = el('div', 'sess-actions');698      const open = el('button', '', c.state === 'idle' ? 'Reprendre' : 'Ouvrir');699      open.onclick = (e) => { e.stopPropagation(); openChat(c.id); };700      actions.appendChild(open);701      if (c.state === 'idle') {702        const del = el('button', 'del', 'Supprimer');703        del.onclick = async (e) => {704          e.stopPropagation();705          if (!confirm('Supprimer cette session ?')) return;706          await fetch('/api/chats/' + c.id, { method: 'DELETE' });707          card.remove();708          if (currentChat && currentChat.id === c.id) { currentChat = null; clearConversation(); }709        };710        actions.appendChild(del);711      }712      card.appendChild(actions);713      card.onclick = () => openChat(c.id);714      list.appendChild(card);715    }716  }717  $('newSessBtn').onclick = newChat;718719  // incidents globaux (bouton en tête de l'onglet Écosystème)720  $('incBtn').onclick = async () => {721    const r = await fetch('/api/eco/incidents');722    if (!r.ok) return;723    const { incidents } = await r.json();724    const label = (app) => (ecoData?.sites.find(s => s.app === app)?.label) || app;725    openSheet(`726      <div class="sheet-h"><h3>Incidents</h3></div>727      <div class="sheet-sec">728        <h4>Historique — 50 derniers</h4>729        ${incidents.length ? incidents.map(i => `730          <div class="inc-item"><span class="${i.ended ? 'inc-ok' : 'inc-dot'}">${i.ended ? '✓' : '■'}</span>731          <span><b>${esc(label(i.site))}</b> · ${new Date(i.started).toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}732          ${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('')733          : '<div style="color:var(--muted)">Aucun incident enregistré 🎉</div>'}734      </div>`);735  };736737  // ---------- écosystème ----------738  function siteStatus(s) {739    if (s.incident || (s.last && !s.last.ok)) return 'down';740    if (s.last && s.last.ms > 4000) return 'slow';741    return s.last ? 'up' : 'unknown';742  }743  const ST = {744    up: { cls: 'up', ico: '●', lbl: 'EN LIGNE' },745    slow: { cls: 'slow', ico: '▲', lbl: 'LENT' },746    down: { cls: 'down', ico: '■', lbl: 'HORS LIGNE' },747    unknown: { cls: 'slow', ico: '▲', lbl: '…' },748  };749  function sparkline(spark, w = 120, h = 30) {750    if (!spark || spark.length < 2) return '<svg class="spark"></svg>';751    const ms = spark.map(p => p.ok ? p.ms : null);752    const max = Math.max(...ms.filter(v => v !== null), 100) * 1.15;753    const step = w / (spark.length - 1);754    let d = '', pen = false;755    spark.forEach((p, i) => {756      if (!p.ok) { pen = false; return; }757      const x = i * step, y = h - 3 - (p.ms / max) * (h - 8);758      d += (pen ? 'L' : 'M') + x.toFixed(1) + ' ' + y.toFixed(1);759      pen = true;760    });761    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('');762    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>`;763  }764  async function loadEco() {765    const [r, rn] = await Promise.all([fetch('/api/eco/summary'), fetch('/api/eco/nodes')]);766    if (!r.ok) return;767    ecoData = await r.json();768    renderEco();769    if (rn.ok) renderNodes(await rn.json());770  }771  function nbar(label, val, pct) {772    const c = pct > 88 ? 'var(--bad)' : pct > 70 ? 'var(--warn)' : 'var(--good)';773    return `<div class="nbar"><div class="nbar-l"><span>${label}</span><b>${val}</b></div>774      <div class="nbar-track"><div class="nbar-fill" style="width:${Math.max(2, Math.min(100, pct))}%;background:${c}"></div></div></div>`;775  }776  function renderNodes(data) {777    const grid = $('ecoNodes');778    if (!grid) return;779    grid.innerHTML = '';780    for (const n of data.nodes) {781      const L = n.last;782      const memPct = L && L.mem_total ? Math.round(L.mem_used / L.mem_total * 100) : null;783      const upApps = n.apps.filter(a => a.status === 'online').length;784      const badApp = n.apps.some(a => a.status && a.status !== 'online');785      const card = el('div', 'node-card' + (badApp ? ' warn' : ''));786      card.innerHTML = `787        <div class="node-top"><span class="node-name">${esc(n.node)}</span>788          <span class="node-apps${badApp ? ' bad' : ''}">${upApps}/${n.apps.length} apps</span></div>789        ${nbar('charge', L ? L.load1.toFixed(1) : '—', L ? Math.min(100, L.load1 / 32 * 100) : 0)}790        ${nbar('RAM', memPct !== null ? memPct + '%' : '—', memPct || 0)}791        ${nbar('disque', L ? L.disk_pct + '%' : '—', L ? L.disk_pct : 0)}`;792      grid.appendChild(card);793    }794  }795  function applyChecks(items) {796    if (!ecoData) return;797    for (const it of items) {798      const s = ecoData.sites.find(x => x.app === it.site);799      if (!s) continue;800      s.last = { ts: it.ts, ms: it.ms, code: it.code, ok: it.ok, err: it.err };801      s.spark.push({ ts: it.ts, ms: it.ms, ok: it.ok });802      if (s.spark.length > 40) s.spark.shift();803    }804    renderEco();805  }806  function renderEco() {807    const sites = ecoData.sites;808    const up = sites.filter(s => siteStatus(s) === 'up').length;809    const down = sites.filter(s => siteStatus(s) === 'down').length;810    const lat = sites.filter(s => s.last?.ok).map(s => s.last.ms);811    const avg = lat.length ? Math.round(lat.reduce((a, b) => a + b, 0) / lat.length) : 0;812    $('ecoStamp').textContent = 'maj ' + new Date().toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit', second: '2-digit' });813    $('ecoOverview').innerHTML = `814      <div class="eco-stat ok"><div class="v">${up}/${sites.length}</div><div class="l">en ligne</div></div>815      <div class="eco-stat ${down ? 'bad' : ''}"><div class="v">${down}</div><div class="l">hors ligne</div></div>816      <div class="eco-stat"><div class="v">${avg}<small style="font-size:12px"> ms</small></div><div class="l">latence moy.</div></div>`;817    const grid = $('ecoGrid');818    grid.innerHTML = '';819    const order = { down: 0, slow: 1, unknown: 2, up: 3 };820    for (const s of [...sites].sort((a, b) => order[siteStatus(a)] - order[siteStatus(b)])) {821      const st = ST[siteStatus(s)];822      const card = el('div', 'site-card' + (siteStatus(s) === 'down' ? ' down' : ''));823      card.innerHTML = `824        <div class="site-top">825          <span class="site-name">${esc(s.label)}</span>826          <span class="st-pill ${st.cls}">${st.ico} ${st.lbl}</span>827        </div>828        <div class="site-mid">829          <div class="site-ms">${s.last?.ok ? s.last.ms : '—'}<small> ms</small></div>830          ${sparkline(s.spark)}831        </div>832        <div class="site-foot">833          <span>up 24h <b>${s.uptime24 ?? '—'}%</b></span>834          <span>p95 <b>${s.p95_24 ?? '—'} ms</b></span>835          <span>${esc(s.node)}</span>836          ${s.proc?.status ? `<span class="${s.proc.status === 'online' ? '' : 'foot-bad'}">pm2 <b>${esc(s.proc.status)}</b></span>` : ''}837          ${s.certExpires ? `<span>SSL <b>${Math.max(0, Math.round((s.certExpires - Date.now()) / 86400000))} j</b></span>` : ''}838        </div>`;839      card.onclick = () => openSiteSheet(s.app);840      grid.appendChild(card);841    }842  }843844  async function openSiteSheet(app) {845    const r = await fetch('/api/eco/site/' + app);846    if (!r.ok) return;847    const d = await r.json();848    const s = ecoData.sites.find(x => x.app === app) || {};849    const st = ST[siteStatus(s)];850    const certDays = s.certExpires ? Math.max(0, Math.round((s.certExpires - Date.now()) / 86400000)) : null;851    openSheet(`852      <div class="sheet-h">853        <h3>${esc(d.label)}</h3>854        <span class="st-pill ${st.cls}">${st.ico} ${st.lbl}</span>855      </div>856      <div class="sheet-sec">857        <h4>Disponibilité</h4>858        <div class="tile-row">859          <div class="tile"><div class="v">${s.uptime24 ?? '—'}%</div><div class="l">24 h</div></div>860          <div class="tile"><div class="v">${s.uptime7 ?? '—'}%</div><div class="l">7 j</div></div>861          <div class="tile"><div class="v">${s.uptime30 ?? '—'}%</div><div class="l">30 j</div></div>862        </div>863        <div style="margin-top:10px">${uptimeDays(d.days)}</div>864      </div>865      <div class="sheet-sec">866        <h4>Latence — 24 h</h4>867        ${latencyChart(d.series)}868        <div class="tile-row" style="margin-top:10px">869          <div class="tile"><div class="v">${s.avg24 ?? '—'}</div><div class="l">moy ms</div></div>870          <div class="tile"><div class="v">${s.p95_24 ?? '—'}</div><div class="l">p95 ms</div></div>871          <div class="tile"><div class="v">${s.last?.code || '—'}</div><div class="l">HTTP</div></div>872        </div>873      </div>874      <div class="sheet-sec">875        <h4>Service</h4>876        <div class="kv"><span>Domaine</span><b>${esc(d.domain)}</b></div>877        <div class="kv"><span>Nœud</span><b>${esc(d.node)}</b></div>878        <div class="kv"><span>PM2</span><b>${esc(s.proc?.status || '—')}${s.proc?.restarts ? ' · ' + s.proc.restarts + ' restarts' : ''}</b></div>879        <div class="kv"><span>CPU / RAM process</span><b>${s.proc ? s.proc.cpu + '% / ' + fmtMB(s.proc.mem) : '—'}</b></div>880        <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>881        <div class="kv"><span>Dernier commit</span><b>${s.proc?.last_commit ? timeAgo(s.proc.last_commit) : '—'}</b></div>882        <div class="kv"><span>Certificat SSL</span><b>${certDays !== null ? 'expire dans ' + certDays + ' j' : '—'}</b></div>883      </div>884      ${d.incidents.length ? `<div class="sheet-sec"><h4>Incidents — 30 j</h4>${d.incidents.map(i => `885        <div class="inc-item"><span class="${i.ended ? 'inc-ok' : 'inc-dot'}">${i.ended ? '✓' : '■'}</span>886        <span>${new Date(i.started).toLocaleString('fr-CA', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })}887        ${i.ended ? ' → ' + Math.round((i.ended - i.started) / 60000) + ' min' : ' — EN COURS'} · ${esc(i.reason || '')}</span></div>`).join('')}</div>` : ''}888      ${d.errors.length ? `<div class="sheet-sec"><h4>Erreurs récentes</h4>${d.errors.slice(0, 8).map(e => `889        <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>` : ''}890      <div class="sheet-sec">891        <h4>Actions d'administration</h4>892        <div class="admin-actions">893          <button class="btn-ghost" id="aRestart">↻ Redémarrer PM2</button>894          <button class="btn-ghost" id="aLogs">📜 Logs récents</button>895          <button class="btn-ghost" id="aCommits">⌥ Git & commits</button>896          <a class="btn-ghost" href="https://${esc(d.domain)}" target="_blank" rel="noopener">↗ Ouvrir le site</a>897        </div>898        <div id="aOut" class="admin-out hidden"></div>899      </div>900      <button class="btn-cta" style="width:100%" id="shChat">💬 Demander à Claude Code →</button>901    `);902    $('shChat').onclick = () => {903      closeSheet();904      newChat();905      for (const o of projectSel.options) if (o.value.startsWith(d.app + '@')) projectSel.value = o.value;906    };907    const out = () => $('aOut');908    const showOut = (html) => { out().classList.remove('hidden'); out().innerHTML = html; };909    $('aRestart').onclick = async () => {910      if (!confirm(`Redémarrer ${d.label} (pm2 restart) sur ${d.node} ?`)) return;911      showOut('<div class="admin-load">redémarrage…</div>');912      const r = await fetch('/api/admin/action', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ app: d.app, action: 'restart' }) });913      const j = await r.json();914      showOut(`<div class="${j.ok ? 'admin-ok' : 'admin-err'}">${j.ok ? '✓ redémarré' : '✗ échec'} — statut : ${esc(j.output || '')}</div>`);915      if (navigator.vibrate) navigator.vibrate(60);916    };917    $('aLogs').onclick = async () => {918      showOut('<div class="admin-load">chargement des logs…</div>');919      const r = await fetch('/api/admin/logs/' + d.app);920      const j = await r.json();921      showOut(`<pre>${esc((j.logs || '').slice(-4000))}</pre>`);922    };923    $('aCommits').onclick = async () => {924      showOut('<div class="admin-load">…</div>');925      const r = await fetch('/api/admin/commits/' + d.app);926      const j = await r.json();927      showOut(`<pre>${esc(j.text || '')}</pre>`);928    };929    attachChartTips();930  }931932  function uptimeDays(days) {933    if (!days) return '';934    const cells = days.map(dd => {935      const u = dd.uptime;936      const c = u === null ? 'var(--line)' : u >= 99.5 ? 'var(--good)' : u >= 95 ? 'var(--warn)' : 'var(--bad)';937      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>`;938    }).join('');939    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>`;940  }941942  function latencyChart(series) {943    const W = 340, H = 130, PL = 38, PB = 18, PT = 8;944    if (!series || series.length < 2) return '<div style="color:var(--muted);font-size:13px">Pas encore assez de données.</div>';945    const ok = series.filter(p => p.ok);946    const max = Math.max(...ok.map(p => p.ms), 100) * 1.15;947    const x = (t) => PL + ((t - series[0].t) / (series[series.length - 1].t - series[0].t)) * (W - PL - 6);948    const y = (ms) => PT + (1 - ms / max) * (H - PT - PB);949    let d = '', pen = false;950    const pts = [];951    for (const p of series) {952      if (!p.ok) { pen = false; continue; }953      const px = x(p.t), py = y(p.ms);954      d += (pen ? 'L' : 'M') + px.toFixed(1) + ' ' + py.toFixed(1);955      pts.push({ x: px, y: py, ms: Math.round(p.ms), t: p.t });956      pen = true;957    }958    const failMarks = series.filter(p => !p.ok).map(p =>959      `<rect x="${(x(p.t) - 2).toFixed(1)}" y="${H - PB - 6}" width="4" height="6" fill="var(--bad)"/>`).join('');960    const gridLines = [0.25, 0.5, 0.75, 1].map(f => {961      const gy = y(max * f / 1.15);962      return `<line x1="${PL}" y1="${gy}" x2="${W - 6}" y2="${gy}" stroke="var(--grid)" stroke-width="1"/>963        <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>`;964    }).join('');965    const lastPt = pts[pts.length - 1];966    const lastLbl = lastPt ? `<circle cx="${lastPt.x}" cy="${lastPt.y}" r="3.5" fill="var(--orange-deep)" stroke="var(--card)" stroke-width="2"/>967      <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>` : '';968    const t0 = new Date(series[0].t), t1 = new Date(series[series.length - 1].t);969    const fmtH = (dt) => dt.getHours().toString().padStart(2, '0') + 'h';970    return `<div style="position:relative">971      <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 })))}'>972        ${gridLines}973        <path d="${d}" fill="none" stroke="var(--orange-deep)" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>974        ${failMarks}${lastLbl}975        <text x="${PL}" y="${H - 4}" font-size="9" fill="var(--muted)" font-family="var(--mono)">${fmtH(t0)}</text>976        <text x="${W - 6}" y="${H - 4}" text-anchor="end" font-size="9" fill="var(--muted)" font-family="var(--mono)">${fmtH(t1)}</text>977      </svg></div>`;978  }979  function attachChartTips() {980    document.querySelectorAll('.lat-chart').forEach((svg) => {981      const pts = JSON.parse(svg.dataset.pts || '[]');982      if (!pts.length) return;983      const wrap = svg.parentElement;984      let tip = null;985      const show = (clientX) => {986        const rect = svg.getBoundingClientRect();987        const vx = (clientX - rect.left) / rect.width * 340;988        let best = pts[0];989        for (const p of pts) if (Math.abs(p.x - vx) < Math.abs(best.x - vx)) best = p;990        if (!tip) { tip = el('div', 'chart-tip'); wrap.appendChild(tip); }991        tip.textContent = `${new Date(best.t).toLocaleTimeString('fr-CA', { hour: '2-digit', minute: '2-digit' })} · ${best.ms} ms`;992        tip.style.left = (best.x / 340 * rect.width) + 'px';993        tip.style.top = (best.y / 130 * rect.height) + 'px';994      };995      svg.addEventListener('pointerdown', (e) => show(e.clientX));996      svg.addEventListener('pointermove', (e) => { if (e.buttons || e.pointerType === 'mouse') show(e.clientX); });997      svg.addEventListener('pointerleave', () => { if (tip) { tip.remove(); tip = null; } });998    });999  }10001001  // rafraîchissement périodique de l'onglet éco (en plus du push)1002  setInterval(() => { if (curView === 'eco' && !document.hidden) loadEco(); }, 60000);1003  // retour au premier plan (iOS coupe le WS quand l'écran se verrouille) :1004  // reconnexion IMMÉDIATE + resynchronisation de la conversation en cours1005  document.addEventListener('visibilitychange', () => {1006    if (document.hidden) return;1007    if (!ws || ws.readyState !== 1) {1008      wsRetry = 500;1009      try { ws && ws.close(); } catch {}1010      connect();1011    } else if (currentChat) {1012      send({ type: 'open', chatId: currentChat.id });1013    }1014    if (curView === 'eco') loadEco();1015  });1016  window.addEventListener('online', () => { wsRetry = 500; if (!ws || ws.readyState !== 1) connect(); });10171018  // ---------- feuille ----------1019  function openSheet(html) {1020    $('sheetBody').innerHTML = html;1021    $('sheet').classList.remove('hidden');1022  }1023  function closeSheet() { $('sheet').classList.add('hidden'); }1024  $('sheetBack').onclick = closeSheet;10251026  // ---------- réglages ----------1027  function refreshSettingsView() {1028    document.querySelectorAll('#segModel button').forEach(b => b.classList.toggle('on', b.dataset.v === settings.model));1029    document.querySelectorAll('#segPerm button').forEach(b => b.classList.toggle('on', b.dataset.v === settings.permMode));1030    $('setSid').textContent = currentChat?.claudeSessionId ? currentChat.claudeSessionId.slice(0, 12) + '…' : '—';1031    $('setCost').textContent = currentChat ? fmt$(currentChat.totalCost) : '—';1032    $('setCtx').textContent = currentChat?.contextTokens ? fmtTok(currentChat.contextTokens) + ' tokens' : '—';1033  }1034  document.querySelectorAll('#segModel button').forEach(b => { b.onclick = () => applyOpts({ model: b.dataset.v }); });1035  document.querySelectorAll('#segPerm button').forEach(b => {1036    b.onclick = () => {1037      if (b.dataset.v === 'bypass' && !confirm('Mode BYPASS : Claude Code exécutera TOUTES les actions sans demander. Continuer ?')) return;1038      applyOpts({ permMode: b.dataset.v });1039    };1040  });1041  $('btnClear').onclick = () => { if (currentChat) { send({ type: 'clear', chatId: currentChat.id }); switchView('chat'); } };1042  $('btnCompact').onclick = () => { switchView('chat'); inputEl.value = '/compact'; sendPrompt(); };1043  $('logoutBtn').onclick = async () => {1044    wsWanted = false;1045    await fetch('/api/logout', { method: 'POST' });1046    location.reload();1047  };10481049  // ---------- login / init ----------1050  async function init() {1051    const me = await fetch('/api/me');1052    if (!me.ok) {1053      $('login').classList.remove('hidden');1054      $('app').classList.add('hidden');1055      return;1056    }1057    const info = await me.json();1058    $('setHost').textContent = (info.node || 'M3U96a') + ':3300';1059    $('login').classList.add('hidden');1060    $('app').classList.remove('hidden');1061    const pr = await fetch('/api/projects');1062    const { projects } = await pr.json();1063    projectSel.innerHTML = '';1064    for (const p of projects) {1065      const o = document.createElement('option');1066      o.value = p.id; o.textContent = p.name + ' · ' + p.node;1067      projectSel.appendChild(o);1068    }1069    if (settings.projectId) projectSel.value = settings.projectId;1070    projectSel.onchange = () => { settings.projectId = projectSel.value; saveStore(); };1071    refreshChips();1072    refreshSettingsView();1073    // reprise automatique : on rouvre la dernière conversation (historique +1074    // live si une tâche tourne encore) même après fermeture complète de l'app1075    if (settings.lastChatId) currentChat = { id: settings.lastChatId };1076    connect();1077  }1078  $('loginBtn').onclick = doLogin;1079  $('password').addEventListener('keydown', (e) => { if (e.key === 'Enter') doLogin(); });1080  async function doLogin() {1081    const r = await fetch('/api/login', {1082      method: 'POST',1083      headers: { 'Content-Type': 'application/json' },1084      body: JSON.stringify({ password: $('password').value }),1085    });1086    if (r.ok) { $('password').value = ''; init(); }1087    else {1088      const d = await r.json().catch(() => ({}));1089      $('loginError').textContent = d.error || 'Erreur';1090    }1091  }10921093  init();1094})();1095
Files · 27fcf70e4d95f96917c03d667658fae374d7bec3
Menu

Theme