rob-revisited/ide/ui/js/claude.js

1598 lines
92 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// The Claude tool window (desktop): conversations with the Claude Code of this computer, in the project's folder, a tab
// each (a new one never stops the others; Open in a Window moves one into a window of its own, closing it brings it
// back). Every conversation is kept in the project (.jumphp/history/claude/, not in git): the History tab reopens them.
// One `claude -p` per conversation (JumPHP\Ide\Claude\ClaudeCode), kept open: a message typed while Claude works goes
// into the turn in progress (more information, "not that way"), as in Claude Code's own terminal. Its answer, the files it reads and changes, the
// commands it runs, appear as they come (claude.event); the conversation goes on (--resume). What it changes on disk
// comes back into the editors by themselves (the IDE watches the files). Follow (the eye): the IDE shows what Claude does
// as it does it (ClaudeWatch); Claude also drives the IDE with its own tools (AgentTools, MCP server jumphp-ide).
import { backend } from './backend.js';
import { openShareDialog } from './remote-share.js';
import { el, clear, icon, menu, selectAbove, notify, prefs, prompt, confirm, copyText, debounce, timeAgo, t } from './ui.js';
import { AgentTools, ClaudeWatch, IDE_TOOL, ideToolLabel } from './agent.js';
import { hasPending, redrawStep, stepCard } from './steps.js';
import { nearBottom, isProgrammatic, releasesOnWheel, releasesOnKey, releasesOnTouchMove, pickAnchor, anchorDelta, nextUnread } from './follow.js';
const tr = t; // t() is a local name (the Terminal tab) in some methods
const MODES = {
step: ['Step by step', 'Claude proposes each change as a diff in the editor (red removed, green added): accept or decline each block, tell it why, roll back any step'],
auto: ['Auto mode', 'Claude works on its own: a safety check approves the safe actions and refuses the risky ones'],
acceptEdits: ['Edit files', 'Claude changes files without asking; commands it may not run are refused'],
plan: ['Plan only', 'Claude reads and proposes, changes nothing'],
default: ['Ask (refuse what needs a yes)', 'Claude can only do what needs no permission'],
bypassPermissions: ['Full auto', 'Claude edits and runs any command without asking: only in a project you trust'],
};
// claude --model: '' = Claude Code's own setting; aliases follow the newest model of each family; "Other…" any full name
const MODELS = [
['', 'Model: default'],
['Newest', [['fable', 'Fable (newest)'], ['opus', 'Opus (newest)'], ['sonnet', 'Sonnet (newest)'], ['haiku', 'Haiku (newest)']]],
['Versions', [['claude-fable-5-1', 'Fable 5.1'], ['claude-opus-5-5', 'Opus 5.5'], ['claude-sonnet-5-5', 'Sonnet 5.5'], ['claude-haiku-5-5', 'Haiku 5.5'],
['opusplan', 'Opus plans, Sonnet codes']]],
];
// claude --effort: how hard it thinks
const EFFORTS = [['', 'Thinking: default'], ['low', 'Thinking: low'], ['medium', 'Thinking: medium'], ['high', 'Thinking: high'],
['xhigh', 'Thinking: extra high'], ['max', 'Thinking: max']];
const newKey = () => 'c-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
export class ClaudePanel {
/**
* @param detached a conversation key: this page is a window of its own showing only that conversation (Open in a
* Window); the main window leaves it alone until the window closes (ui.broadcast claude.dock)
*/
constructor(app, { detached = null } = {}) {
this.app = app;
this.detached = detached;
this.key = 'claude:' + app.projectKey;
this.mode = prefs.get('claudeMode', 'acceptEdits');
this.model = prefs.get('claudeModel', '');
this.effort = prefs.get('claudeEffort', '');
// the assistant: Claude Code, or OpenCode (https://opencode.ai: any model it has, a local one included), same window
this.agent = backend.kind === 'native' ? prefs.get('claudeAgent', 'claude') : 'claude';
this.opencodeModel = prefs.get('opencodeModel', '');
this.opencodeModels = [];
this.localModels = [];
this.status = el('span.claude-status');
if (!MODES[this.mode]) this.mode = 'acceptEdits';
this.modeSelect = el('select.input.small.claude-select', { title: 'What Claude may do (Shift+Tab in the box: next mode)', onchange: () => this.setMode(this.modeSelect.value) },
...Object.entries(MODES).map(([id, [label]]) => el('option', { value: id }, label)));
this.modeSelect.value = this.mode;
// Follow (the editors show what Claude does) and the IDE's tools for Claude: the main window's (a conversation in a
// window of its own has no editors)
this.watch = detached ? { on: false, use() {}, result() {}, done() {}, toggle() {}, marks: { clearAll() {} } } : new ClaudeWatch(app, this);
if (backend.kind === 'native' && !detached) this.tools = new AgentTools(app, this.watch);
this.agentSelect = el('select.input.small.claude-select', { title: 'Who answers: Claude Code, or OpenCode (any model it is set up for, local ones too)', onchange: () => this.setAgent(this.agentSelect.value) },
el('option', { value: 'claude' }, 'Claude'), el('option', { value: 'opencode' }, 'OpenCode'));
this.agentSelect.value = this.agent;
this.modelSelect = el('select.input.small.claude-select', { title: 'The model (claude --model, or opencode --model)', onchange: () => this.pickModel() });
this.effortSelect = el('select.input.small.claude-select', { title: 'How hard Claude thinks (claude --effort)',
onchange: () => { this.effort = this.effortSelect.value; prefs.set('claudeEffort', this.effort); } },
...EFFORTS.map(([v, label]) => el('option', { value: v, selected: v === this.effort }, label)));
// at the bottom of the window: their lists open upwards (the native ones went off the screen)
[this.agentSelect, this.modeSelect, this.modelSelect, this.effortSelect].forEach(selectAbove);
this.fillModels();
if (this.agent === 'opencode') this.loadOpencodeModels();
this.mcpBanner = el('div.claude-mcp', { hidden: true });
this.tabsNode = el('div.claude-tabs');
this.body = el('div.claude-body');
this.usage = new UsageGauges();
this.node = el('div.claude-panel', {}, this.tabsNode, this.mcpBanner, this.body, this.usage.node,
el('div.claude-bar.claude-settings', {}, ...(backend.kind === 'native' ? [this.agentSelect] : []), this.modeSelect, this.modelSelect, this.effortSelect, this.status));
this.remote = !!app.project.capabilities?.claudeRemote; // the web IDE: the Claude of the user's computer
this.historyLocal = backend.kind === 'native' && !this.remote;
this.convs = [];
this.active = null; // a Conversation, or 'history'
this.saveSoon = debounce(() => this.saveTabs(), 400);
this.detachedKeys = new Set(); // conversations in a window of their own (the window layout, layout.js)
this.restore();
backend.on('claude.event', (p) => {
if (p.event?.type === 'rate_limit_event') this.usage.limits(p.event.rate_limit_info);
this.route(p)?.event(p);
});
backend.on('claude.log', (p) => this.route(p)?.logLine(p));
backend.on('claude.speed', (p) => this.route(p)?.speed(p));
backend.on('claude.exit', (p) => this.route(p)?.exit(p));
// the lease of a session (ide/src/Claude/SessionArbiter.php): who works on it now, a queued message delivered, an external Terminal opened
backend.on('claude.lease', (p) => this.route({ conv: p.conv })?.leaseEvent(p));
backend.on('claude.queue.sent', (p) => this.route({ conv: p.conv, id: p.id })?.queueSent(p));
backend.on('claude.lease.opened', (p) => notify(`Claude ${tr('opened in')} ${p.terminal}`, 'info'));
backend.on('ui.broadcast', (m) => this.broadcast(m));
this.checkStatus();
}
/** The open tabs come back (an older IDE kept one conversation: it becomes the first tab). */
restore() {
if (this.detached) {
const url = new URLSearchParams(location.search);
backend.invoke('claude.history.read', { id: this.detached }).catch(() => null).then((data) => {
const c = this.openConversation({ key: this.detached, session: data?.session || null, items: data?.items || [], title: data?.title || '' });
const live = Number(url.get('live')) || null;
if (live) c.live = live;
if (url.get('running')) c.startTurn(live);
});
return;
}
const saved = prefs.get(this.key, {});
const tabs = Array.isArray(saved.tabs) ? saved.tabs
: (saved.session || saved.history?.length ? [{ key: newKey(), session: saved.session || null, items: saved.history || [] }] : []);
for (const t of tabs) if (!t.detached) this.openConversation(t, false);
if (!this.convs.length) this.openConversation({}, false);
this.show(this.convs.find((c) => c.key === saved.active) || this.convs[this.convs.length - 1]);
}
/** The conversation an event belongs to: by its key (claude.send's conv), else by its process (the web IDE). */
route({ id, conv }) {
return (conv && this.convs.find((c) => c.key === conv)) || this.convs.find((c) => c.run?.id === id || c.live === id) || null;
}
/** A new tab (a new conversation, or one from the history). */
openConversation(data = {}, show = true) {
const c = new Conversation(this, { key: data.key || newKey(), session: data.session || null, items: data.items || [], title: data.title || '', context: data.context || null });
this.convs.push(c);
if (show || !this.active) this.show(c);
else this.renderTabs();
this.saveSoon();
return c;
}
show(target) {
this.active = target;
clear(this.body);
if (target === 'history') this.body.append(this.historyNode());
else if (target) { this.body.append(target.node); target.scroll(); requestAnimationFrame(() => target.input.focus()); }
this.usage.context(target && target !== 'history' ? target.context : null);
this.renderTabs();
this.saveSoon();
}
current() { return this.active instanceof Conversation ? this.active : null; }
renderTabs() {
clear(this.tabsNode);
for (const c of this.convs) {
this.tabsNode.append(el(`button.tw-tab${c === this.active ? '.on' : ''}`, {
title: c.title() + (c.run ? ' (working…)' : '') + ' — right click: more',
onclick: () => this.show(c),
oncontextmenu: (e) => { e.preventDefault(); this.tabMenu(c, e); },
}, c.run ? el('span.spinner') : icon('claude'), el('span.claude-tab-title', {}, c.title()),
this.detached ? null : el('span.x', { title: 'Close (it stays in History)', onclick: (e) => { e.stopPropagation(); this.close(c); } }, '×')));
}
if (this.historyLocal && !this.detached) {
this.tabsNode.append(el(`button.tw-tab${this.active === 'history' ? '.on' : ''}`, { title: 'Every conversation of this project', onclick: () => this.show('history') },
icon('history'), 'History'));
}
this.app.refreshToolHeader?.('claude');
}
tabMenu(c, e) {
menu([
this.detached || backend.kind !== 'native' ? null : { label: 'Open in a Window', icon: 'split', action: () => this.undock(c) },
backend.kind !== 'native' || this.remote ? null : { label: 'Open in a Terminal', icon: 'terminal', action: () => this.undockTerminal(c) },
{ label: 'Rename…', action: async () => { const t = await prompt('Rename the conversation', { value: c.title() }); if (t != null) { c.name = t.trim(); c.save(); this.renderTabs(); } } },
this.historyLocal ? { label: 'Copy as Markdown', action: () => c.markdown().then((md) => { copyText(md); notify('Copied', 'info'); }) } : null,
this.detached ? null : '-',
this.detached ? null : { label: 'Close', action: () => this.close(c) },
].filter(Boolean), e);
}
/** Closes a tab: its process ends (the conversation stays in History). */
async close(c) {
if (c.run && !(await confirm('Close this conversation?', 'Claude is working in it: closing stops it. It stays in History.', { ok: 'Close', danger: true }))) return;
await c.saveNow();
if (!this.remote) backend.invoke('claude.close', { conv: c.key }).catch(() => null);
else if (c.run) backend.invoke('claude.stop', { id: c.run.id }).catch(() => null);
this.drop(c);
}
drop(c) {
c.dispose();
clearInterval(c.watchScroll);
this.convs = this.convs.filter((x) => x !== c);
if (this.active === c) this.show(this.convs[this.convs.length - 1] || null);
if (!this.convs.length) this.openConversation();
this.renderTabs();
this.saveSoon();
}
/** Open in a Window: the conversation goes on in a window of its own (its process too: nothing stops). */
async undock(c) {
await c.saveNow();
try {
await backend.invoke('claude.window', { conv: c.key, title: c.title(), live: c.live ?? c.run?.id ?? null, running: !!c.run });
} catch (e) { notify(e.message, 'error'); return; }
this.detachedKeys.add(c.key);
this.drop(c);
this.saveTabs([c]);
}
/** Open in a Terminal: the standard claude / opencode program in the desktop's terminal, resuming this conversation. */
async undockTerminal(c) {
if (!c) return;
await c.saveNow?.();
const agent = this.agent;
try {
const { terminal, pending } = await backend.invoke('claude.terminal', { agent, session: c.session || '', conv: c.key, mode: this.mode, model: agent === 'opencode' ? this.opencodeModel : this.model });
if (pending) { notify(tr('Switching…'), 'info', { title: 'Claude' }); return; } // the Terminal opens when the panel's Claude has left (claude.lease.opened)
notify(`${agent === 'opencode' ? 'OpenCode' : 'Claude'} opened in ${terminal}` + (c.session ? ' (this conversation resumed)' : ''), 'info');
} catch (e) { notify(e.message, 'error'); }
}
/** Messages between the IDE's windows (the PHP side sends ui.broadcast to every window). */
broadcast(m) {
if (!m || typeof m !== 'object') return;
if (m.type === 'claude.dock' && !this.detached) this.detachedKeys.delete(m.conv);
if (m.type === 'claude.dock' && !this.detached && !this.convs.some((c) => c.key === m.conv)) {
// the window of a conversation closed: it comes back as a tab, as it was (its process went on meanwhile)
backend.invoke('claude.history.read', { id: m.conv }).catch(() => null).then((data) => {
const c = this.openConversation({ key: m.conv, session: data?.session, items: data?.items || [], title: data?.title || '' });
if (m.live) c.live = m.live;
if (m.running && m.live) c.startTurn(m.live);
this.saveSoon();
});
} else if (m.type === 'claude.open' && !this.detached) {
this.app.editors?.open(m.path, m.line ? { line: m.line } : {});
}
}
/** What the window layout keeps of the panel (layout.js): the active conversation, per conversation its unsent text, scroll and log view. */
layoutState() {
if (this.detached) return null;
const convs = {};
for (const c of this.convs) convs[c.key] = { draft: c.input?.value || '', scroll: c.savedTop || 0, stick: c.stick !== false, log: !!c.logView && !c.logView.hidden };
return { active: this.current()?.key || null, convs, detached: [...this.detachedKeys] };
}
/** The Terminal tab a conversation in Remote Control lives in: {conv, mark}, saved so that a reload finds it again. */
rcOf(tab) {
const c = this.convs.find((x) => x.rcTab === tab);
return c ? { conv: c.key, mark: c.rcMark || null } : null;
}
/**
* The panel as it was (layout.js restore): unsent text, scroll, log view, the active conversation, the lease of each session
* (the arbiter may still hold it: the page asks claude.lease.get instead of stalling) and, after an IDE restart, the windows.
* @param rcTabs Map of saved Terminal id -> the tab re-attached, rc the saved {conv, mark} per id
*/
async restoreLayout(rec, { restarted = false, rcTabs = new Map(), rcSaved = [] } = {}) {
if (this.detached) return;
for (const c of this.convs) {
const r = rec.convs[c.key];
if (!r) continue;
if (r.draft && !c.input.value) c.input.value = r.draft;
if (r.log && c.logView.hidden) c.toggleLog();
c.stick = r.stick;
c.savedTop = r.scroll;
}
const active = this.convs.find((c) => c.key === rec.active);
if (active) this.show(active);
const cur = this.current();
if (cur && rec.convs[cur.key] && !rec.convs[cur.key].stick) requestAnimationFrame(() => { cur.log.scrollTop = rec.convs[cur.key].scroll; });
for (const c of this.convs) {
const saved = rcSaved.find((x) => x.rc?.conv === c.key);
await c.resync(saved ? rcTabs.get(saved.id) || null : null, saved?.rc || null);
}
this.detachedKeys = new Set(restarted ? [] : rec.detached);
if (restarted && backend.kind === 'native' && !this.remote) {
for (const key of rec.detached) {
if (this.convs.some((c) => c.key === key)) continue;
try { await backend.invoke('claude.window', { conv: key, title: '', live: null, running: false }); this.detachedKeys.add(key); } catch { /* skipped */ }
}
}
}
/** The open tabs, kept for the next start (the whole conversations are in the project's history). */
saveTabs(detachedNow = []) {
if (this.detached) return;
const tabs = this.convs.map((c) => ({ key: c.key, session: c.session, title: c.name || '', items: c.items.slice(-200), context: c.context || null }));
prefs.set(this.key, { tabs, active: this.current()?.key || null });
void detachedNow; // a conversation in a window is not reopened as a tab at the next start: History has it
}
/** History: every conversation of the project, newest first: open one again (a tab; it goes on), or delete it. */
historyNode() {
const node = el('div.claude-history', {}, el('div.placeholder', {}, 'Loading…'));
backend.invoke('claude.history.list').then((list) => {
clear(node);
if (!list.length) { node.append(el('div.placeholder.claude-empty', {}, 'No conversation yet.')); return; }
node.append(el('div.claude-history-head', {}, `${list.length} conversation(s), kept in .jumphp/history/claude/ (not in git)`));
for (const h of list) {
const open = this.convs.find((c) => c.key === h.id);
node.append(el('div.claude-history-row', { title: 'Open it in a tab (it goes on where it was)', onclick: () => this.reopen(h.id) },
icon('claude'), el('div.claude-history-text', {}, el('div.claude-history-title', {}, h.title),
el('div.claude-history-meta', {}, `${timeAgo(h.updated)} · ${h.messages} message(s)${open ? ' · open' : ''}`)),
el('button.btn.small', { title: 'Copy as Markdown', onclick: (e) => { e.stopPropagation(); backend.invoke('claude.history.markdown', { id: h.id }).then((md) => { copyText(md); notify('Copied', 'info'); }); } }, icon('file')),
el('button.btn.small', { title: open ? 'Close its tab first' : 'Delete', disabled: !!open, onclick: async (e) => {
e.stopPropagation();
if (await confirm('Delete this conversation?', h.title, { ok: 'Delete', danger: true })) { await backend.invoke('claude.history.delete', { id: h.id }); this.show('history'); }
} }, icon('close'))));
}
}).catch((e) => { clear(node); node.append(el('div.placeholder', {}, e.message)); });
return node;
}
async reopen(id) {
const open = this.convs.find((c) => c.key === id);
if (open) { this.show(open); return; }
const data = await backend.invoke('claude.history.read', { id }).catch((e) => { notify(e.message, 'error'); return null; });
if (data) this.openConversation({ key: data.id, session: data.session, items: data.items || [], title: data.title });
}
/** The plan (TodoWrite) goes to the conversation whose event is being read (ClaudeWatch calls it). */
showPlan(todos) { (this.planTarget || this.current())?.showPlan(todos); }
/** OpenCode's hosted models, and those running on this computer (asked to their own servers). */
async loadOpencodeModels() {
const [hosted, local] = await Promise.all([backend.invoke('ai.models', { provider: 'opencode' }).catch(() => []), backend.invoke('ai.localModels').catch(() => [])]);
this.opencodeModels = hosted;
this.localModels = local;
this.fillModels();
const chosen = local.flatMap((p) => p.models.map((m) => ({ ...m, key: `${p.provider}/${m.id}` }))).find((m) => m.key === this.opencodeModel);
if (chosen && !chosen.running) this.current?.()?.add({ role: 'note', text: `The local model “${chosen.name}” is not loaded (its server does not answer). Start it first, e.g. “llm-switch” in a terminal, then Restart.` });
}
/** The model list, with the one typed in "Other…" when it is not a known one. */
fillModels() {
clear(this.modelSelect);
if (this.agent === 'opencode') {
this.effortSelect.hidden = true;
this.modelSelect.append(el('option', { value: '' }, 'Model: OpenCode\'s default'));
// the models of THIS computer (llama.cpp, Ollama, LM Studio...) apart from the hosted ones; ● = its server answers now, ○ = stopped (not loaded)
const local = new Set();
const localGroups = (this.localModels || []).map((p) => el('optgroup', { label: `On this computer · ${p.name}${p.running ? '' : ' (server stopped)'}` },
...p.models.map((m) => { local.add(`${p.provider}/${m.id}`); return el('option', { value: `${p.provider}/${m.id}`, title: m.running ? 'Loaded and running' : 'Not loaded: start its server' }, `${m.running ? '●' : '○'} ${m.name}`); })));
const hosted = [...new Set([...(this.opencodeModel ? [this.opencodeModel] : []), ...this.opencodeModels])].filter((n) => !local.has(n) && !(this.localModels || []).some((p) => n.startsWith(p.provider + '/')));
this.modelSelect.append(...localGroups);
if (hosted.length) this.modelSelect.append(el('optgroup', { label: 'Hosted (online)' }, ...hosted.map((n) => el('option', { value: n }, n))));
this.modelSelect.append(el('option', { value: '?' }, 'Other…'));
this.modelSelect.value = this.opencodeModel;
return;
}
this.effortSelect.hidden = false;
const known = MODELS.flatMap(([v, g]) => (Array.isArray(g) ? g.map(([id]) => id) : [v]));
for (const [v, group] of MODELS) {
if (!Array.isArray(group)) { this.modelSelect.append(el('option', { value: v }, group)); continue; }
this.modelSelect.append(el('optgroup', { label: v }, ...group.map(([id, label]) => el('option', { value: id }, label))));
}
if (this.model && !known.includes(this.model)) this.modelSelect.append(el('option', { value: this.model }, this.model));
this.modelSelect.append(el('option', { value: '?' }, 'Other…'));
this.modelSelect.value = this.model;
}
/** Claude or OpenCode answers from now on: the model list changes, and the conversation starts a session of its own with it. */
async setAgent(agent) {
this.agent = agent === 'opencode' ? 'opencode' : 'claude';
prefs.set('claudeAgent', this.agent);
if (this.agent === 'opencode') {
const s = await backend.invoke('claude.status').catch(() => null);
if (s && s.opencode && !s.opencode.available) notify('OpenCode was not found on this computer. Install it: https://opencode.ai', 'error', { title: 'OpenCode' });
await this.loadOpencodeModels();
}
this.fillModels();
const c = this.current?.();
if (c) {
c.session = null; // a session of one assistant does not exist for the other
c.add({ role: 'note', text: this.agent === 'opencode' ? 'OpenCode answers now (it edits files directly, review the changes with Git).' : 'Claude answers now.' });
}
}
async pickModel() {
let value = this.modelSelect.value;
if (this.agent === 'opencode') {
if (value === '?') value = ((await prompt('Another model', { value: this.opencodeModel, label: 'As opencode --model wants it: provider/model, e.g. ollama/qwen2.5-coder', placeholder: 'provider/model' })) || '').trim();
if (!/^[A-Za-z0-9._:/@-]{0,100}$/.test(value)) value = this.opencodeModel;
this.opencodeModel = value;
prefs.set('opencodeModel', value);
this.fillModels();
return;
}
if (value === '?') {
value = ((await prompt('Another model', { value: this.model, label: 'Its name for claude --model, e.g. claude-opus-4-1 or claude-sonnet-5-5[1m]:', placeholder: 'claude-…' })) || '').trim();
if (!/^[A-Za-z0-9._[\]-]{1,60}$/.test(value)) value = this.model;
}
this.model = value;
prefs.set('claudeModel', value);
this.fillModels();
}
async checkStatus() {
const s = await backend.invoke('claude.status').catch(() => null);
if (!s) return;
const was = this.available;
this.available = s.available;
this.say(s.available ? (s.version || 'Claude Code') : (this.remote ? 'not connected' : 'not installed'));
if (!s.available) for (const c of this.convs) c.notInstalled();
else if (was === false) for (const c of this.convs) c.rerender();
if (s.available && !this.remote && backend.kind === 'native' && !this.detached) this.checkMcp({ quiet: true });
// the web IDE: keep looking for the computer while it is not connected
clearTimeout(this.statusTimer);
if (this.remote && !s.available) this.statusTimer = setTimeout(() => this.checkStatus(), 5000);
}
/**
* jumphp.net's MCP server in Claude Code: without it, Claude can not see the user's projects there, publish, run the
* tests on jumphp.net, keep notes. When it is missing, a banner offers to set it up (signing in first if needed).
*/
async checkMcp({ quiet = false } = {}) {
const m = await backend.invoke('claude.mcp.status').catch(() => null);
this.showMcp(m, quiet);
return m;
}
showMcp(m, quiet = false) {
this.mcp = m;
clear(this.mcpBanner);
if (!m || m.installed || !m.claude || (prefs.get('claudeMcpLater') && quiet)) { this.mcpBanner.hidden = true; return; }
this.mcpBanner.hidden = false;
const why = m.url ? `Claude Code has a jumphp server, but for another address (${m.url}).` : `Claude Code is not connected to ${m.server || 'jumphp.net'} yet.`;
this.mcpBanner.append(
el('div.claude-mcp-text', {}, el('b', {}, 'Connect Claude to jumphp.net'), el('br'),
`${why} Connected, Claude sees your projects there, publishes them, runs their tests on jumphp.net, reads the players' feedback and keeps notes for each project.`
+ (m.signedIn ? '' : ' You sign in with jumphp.net first (in your browser).')),
el('div.claude-mcp-actions', {},
el('button.btn.primary.small', { onclick: (e) => this.installMcp(e.currentTarget) }, m.signedIn ? 'Connect' : 'Sign in and connect'),
el('button.btn.small', { title: 'Hide this (Find Action: Connect Claude to jumphp.net)', onclick: () => { prefs.set('claudeMcpLater', true); this.mcpBanner.hidden = true; } }, 'Later')));
}
async installMcp(button = null) {
if (button) { button.disabled = true; button.textContent = 'Connecting…'; }
const task = this.app.task?.('Connecting Claude to jumphp.net…');
try {
await backend.invoke('claude.mcp.install');
notify('Claude Code now has jumphp.net\'s tools (the "jumphp" MCP server, for every project of this computer). A new conversation uses them.', 'success', { title: 'Claude connected to jumphp.net' });
prefs.set('claudeMcpLater', false);
} catch (e) {
notify(e.message, 'error', { title: 'Claude was not connected to jumphp.net' });
} finally {
task?.();
await this.checkMcp();
}
}
title() { return 'Claude'; }
headerExtra() { return this.detached ? el('span.tw-title', {}, 'Claude') : null; }
actions() {
return [
this.detached ? null : el(`button${this.watch.on ? '.on' : ''}`, { title: this.watch.on ? 'Following Claude: the IDE shows what it reads, edits and runs (click to stop)' : 'Follow Claude: show in the IDE what it reads, edits and runs',
onclick: () => { this.watch.toggle(); this.app.refreshToolHeader?.('claude'); } }, icon('eye')),
this.detached ? null : el('button', { title: 'New conversation (the others go on)', onclick: () => this.openConversation() }, icon('plus')),
this.detached || backend.kind !== 'native' || this.remote ? null
: el('button', { title: 'Open this conversation in a window', onclick: () => this.current() && this.undock(this.current()) }, icon('split')),
backend.kind !== 'native' || this.remote ? null
: el('button', { title: 'Open this conversation in a terminal (the standard claude / opencode program)', onclick: () => this.undockTerminal(this.current()) }, icon('terminal')),
el('button', { title: 'What Claude may do: ' + MODES[this.mode][0], onclick: (e) => menu([
{ head: 'What Claude may do' },
...Object.entries(MODES).map(([id, [label, hint]]) => ({ label, hint, checked: this.mode === id, action: () => this.setMode(id) })),
'-',
{ label: 'Forget the permissions given', hint: 'the session\'s, the timed ones and the always ones', action: () => { this.tools?.revokePermissions(); notify('Permissions forgotten', 'info', { title: 'Claude' }); } },
], e.currentTarget) }, icon('settings')),
].filter(Boolean);
}
say(text) { this.status.textContent = text; }
/** What Claude may do (claude --permission-mode): kept, applies from the next message. */
setMode(id) {
if (!MODES[id]) return;
this.mode = id;
this.modeSelect.value = id;
prefs.set('claudeMode', id);
this.app.refreshToolHeader?.('claude');
}
/** Shift+Tab: the next mode, as in Claude Code's terminal. */
cycleMode() {
const ids = Object.keys(MODES);
this.setMode(ids[(ids.indexOf(this.mode) + 1) % ids.length]);
}
/** The editor's "Ask Claude": the window, the current conversation, text in its box. */
ask(text = '') {
this.app.showTool('claude');
const c = this.current() || this.convs[0] || this.openConversation();
if (this.active !== c) this.show(c);
if (text) c.insert(text);
c.input.focus();
}
}
/** One conversation: its log, its plan, its box, its Claude Code process (a tab of the Claude window). */
class Conversation {
constructor(panel, { key, session, items, title, context = null }) {
this.context = context;
this.panel = panel;
this.app = panel.app;
this.key = key;
this.session = session;
this.items = items;
this.name = title || '';
this.run = null; // the turn in progress: {id, started, tools}
this.live = null; // the open conversation's process (its id), between turns too
this.log = el('div.claude-log');
// FOLLOW THE END (algorithm; pure decisions in follow.js):
// 1. `stick` = the reader is at the end (within 32 px): new content then scrolls the log to its end; otherwise NOTHING moves it down.
// 2. Only a reader releases `stick`: wheel up / PageUp / ArrowUp / Home / a finger going down / a press on the scroll bar act at once
// (before the next mutation is processed); any scroll event that is not the echo of our own assignment re-measures the distance
// (scrolling back down to the end re-enables the follow). Our own scrolls go through setTop(), which remembers the value it set.
// 3. Away from the end, the reader's place is kept by manual anchoring (WebKitGTK has no CSS scroll anchoring): the first visible
// child and its offset are recorded on every scroll; after each DOM change / image load / <details> toggle the offset is restored.
// 4. Away from the end, new items count as unread on the floating "Jump to latest" button; a click, or sending a message, follows again.
// 5. Put back in the page / re-layout (the browser resets the scroll to the top): the end, or the reader's own place, is restored.
this.stick = true;
this.unread = 0;
this.userAt = 0;
this.savedTop = 0; // where the reader themselves left it (their own scrolling only)
this.expectTop = null; // what our own last scroll assignment gave, and when
this.expectAt = 0;
this.anchor = null; // {node, top}: what the reader is looking at
this.dragging = false;
let touchY = 0;
const release = () => { this.stick = false; this.userAt = Date.now(); };
this.log.addEventListener('wheel', (e) => { this.userAt = Date.now(); if (releasesOnWheel(e.deltaY)) release(); }, { passive: true });
this.log.addEventListener('touchstart', (e) => { this.userAt = Date.now(); touchY = e.touches?.[0]?.clientY ?? 0; }, { passive: true });
this.log.addEventListener('touchmove', (e) => { this.userAt = Date.now(); if (releasesOnTouchMove(touchY, e.touches?.[0]?.clientY ?? touchY)) release(); }, { passive: true });
this.log.addEventListener('keydown', (e) => { this.userAt = Date.now(); if (releasesOnKey(e.key)) release(); }, { passive: true });
for (const ev of ['mousedown', 'pointerdown']) {
this.log.addEventListener(ev, (e) => {
this.userAt = Date.now();
if (e.clientX !== undefined && e.clientX > this.log.getBoundingClientRect().left + this.log.clientWidth) { this.dragging = true; release(); } // the scroll bar
}, { passive: true });
}
addEventListener('pointerup', () => { if (this.dragging) { this.dragging = false; this.measure(); } }, { passive: true });
this.log.addEventListener('scroll', () => {
if (this.log.clientHeight <= 0) return;
const top = this.log.scrollTop;
if (isProgrammatic(top, this.expectTop, Date.now() - this.expectAt)) { this.recordAnchor(); return; }
const byReader = Date.now() - this.userAt < 600;
if (!byReader && top < 4 && this.log.scrollHeight > this.log.clientHeight + 80 && (this.stick || this.savedTop > 80)) {
// thrown back to the top by itself: back to where the reader was (the end, or where they had scrolled to)
this.setTop(this.stick ? this.log.scrollHeight : this.savedTop);
return;
}
this.measure();
if (byReader) this.savedTop = top;
this.recordAnchor();
});
// the content changes by itself (a tool's result, markdown, an image, a details opened, the spinner moving): at the end, follow it;
// elsewhere, keep what the reader looks at where it is
if (typeof MutationObserver !== 'undefined') {
let pending = false;
new MutationObserver(() => {
if (this.stick && !this.dragging) {
if (pending) return;
pending = true;
requestAnimationFrame(() => { pending = false; if (this.stick && !this.dragging && this.log.clientHeight > 0) this.setTop(this.log.scrollHeight); });
} else this.keepAnchor();
}).observe(this.log, { childList: true, subtree: true, characterData: true, attributes: true });
}
for (const ev of ['load', 'toggle', 'error']) this.log.addEventListener(ev, () => { if (this.stick) this.setTop(this.log.scrollHeight); else this.keepAnchor(); }, true);
this.jump = el('button.btn.small.claude-jump', { hidden: true, title: tr('Jump to latest'), onclick: () => { this.scrollToEnd(); this.input?.focus(); } });
// put back in the page (or shown again), the browser may set the position back to the top after this callback: pin the end now, next
// frame and shortly after (only while the reader is at the end, or was before it happened)
const pin = () => {
if (this.log.clientHeight <= 0) return;
if (this.stick) this.setTop(this.log.scrollHeight);
else if (this.savedTop > 80 && this.log.scrollTop < 4 && Date.now() - this.userAt > 600) this.setTop(this.savedTop); // where they had scrolled to
else this.keepAnchor();
};
if (typeof ResizeObserver !== 'undefined') {
new ResizeObserver(() => { pin(); requestAnimationFrame(() => { pin(); setTimeout(pin, 150); }); }).observe(this.log);
}
// and a light watch while the window is open: whatever sets it back to the top (a dialog, a re-layout, a re-render), the reader's place is put back
this.watchScroll = setInterval(() => {
if (!this.log.isConnected) return;
const lost = this.log.clientHeight > 0 && this.log.scrollTop < 4 && this.log.scrollHeight > this.log.clientHeight + 80 && Date.now() - this.userAt > 600;
if (lost && (this.stick || this.savedTop > 80)) pin();
}, 300);
this.plan = el('div.claude-plan', { hidden: true });
this.input = el('textarea.input.claude-input', { rows: 3, placeholder: 'Ask Claude… (Enter to send, Shift+Enter: new line, @path: a file)',
onkeydown: (e) => { if (e.key === 'Tab' && e.shiftKey) { e.preventDefault(); this.panel.cycleMode(); return; } if (e.key === 'Enter' && !e.shiftKey && !e.isComposing) { e.preventDefault(); this.send(); } } });
this.sendBtn = el('button.btn.primary.small', { title: 'Send (Enter): while Claude works, it reads it at once', onclick: () => this.send() }, 'Send');
this.stopBtn = el('button.btn.small', { title: 'Stop Claude', hidden: true, onclick: () => this.stop() }, icon('stop'), 'Stop');
this.retryBtn = el('button.btn.small', { title: 'Restart the assistant: stops the turn in progress (stuck, no answer) and sends the last request again', onclick: () => this.retry() }, icon('refresh'), 'Restart');
// the live log: what the assistant (a local model above all) is doing, line by line, with the time since the turn started
this.logLines = [];
this.logView = el('pre.claude-livelog', { hidden: true });
this.logBtn = el('button.btn.small', { title: 'Live log: what the model is doing right now (steps, tools, answers, errors, its process output)', onclick: () => this.toggleLog() }, icon('terminal'), 'Log');
// the phone: the same as typing /rc (this conversation goes on in the Terminal with Remote Control)
this.rcBtn = el('button.btn.small', { title: tr('Remote Control: continue this conversation from your phone (the same as /rc)'), hidden: !!this.panel.remote || backend.kind !== 'native', onclick: () => this.remoteControl() }, icon('mobile'));
// share the IDE (Claude / Terminal / all) with a phone or another computer: end-to-end encrypted, allowed here first (ide/ui/js/remote-host.js)
this.screenBtn = el('button.btn.small', { title: t('Share this IDE with a phone or another computer'), hidden: !!this.panel.remote || backend.kind !== 'native', onclick: () => openShareDialog(this.app) }, icon('screen'));
this.node = el('div.claude-conv', {}, this.plan, this.log, this.jump, this.logView, el('div.claude-compose', {}, this.input,
el('div.claude-bar', {},
el('button.btn.small', { title: 'Mention the file open in the editor', onclick: () => this.mentionFile() }, icon('file'), 'File'),
el('button.btn.small', { title: 'Paste the selected code with its place', onclick: () => this.addSelection() }, icon('code'), 'Selection'),
this.leaseBadge = el('span.claude-lease', { hidden: true }),
el('span.tw-spacer'), this.screenBtn, this.rcBtn, this.logBtn, this.retryBtn, this.stopBtn, this.sendBtn)));
this.saveHistory = debounce(() => this.saveNow(), 1500);
this.rerender();
}
title() {
if (this.name) return this.name;
const first = this.items.find((i) => i.role === 'user');
return first ? first.text.replace(/\s+/g, ' ').slice(0, 40) : 'New conversation';
}
rerender() {
const top = this.log.scrollTop;
const stick = this.stick;
clear(this.log);
for (const item of this.items) this.renderItem(item);
if (!this.items.length) this.placeholder();
if (this.run && this.thinking) this.log.append(this.thinking);
this.anchor = null;
this.setTop(stick ? this.log.scrollHeight : top);
}
placeholder() {
this.log.append(el('div.placeholder.claude-empty', {}, el('p', {}, 'Claude Code, on this computer, in this project.'),
el('p', { style: { fontSize: '12px' } }, 'It reads AGENTS.md, writes the game, runs bin/jumphp test… The files it changes open here as it goes.')));
}
/** No Claude Code (or, on the web IDE, no computer connected): how to get it, above what the conversation holds. */
notInstalled() {
clear(this.log);
if (this.panel.remote) {
const command = 'bin/jumphp claude:connect';
this.log.append(el('div.placeholder.claude-empty', {}, el('p', {}, 'Use the Claude Code of your computer here.'),
el('p', { style: { fontSize: '12px' } }, 'In your JumPHP project, on your computer, run:'),
el('pre.claude-code', { title: 'Click to copy', style: { cursor: 'copy' }, onclick: () => { copyText(command); notify('Copied', 'info'); } }, command),
el('p', { style: { fontSize: '12px' } }, 'It opens the JumPHP IDE and asks you, in your browser, to allow it (or in the JumPHP IDE: your account menu › Claude for jumphp.net). Claude then works on a copy of this project on your computer; what it changes comes back here as drafts.'),
el('p', { style: { fontSize: '12px', color: 'var(--text-3)' } }, 'Waiting for your computer…')));
} else {
this.log.append(el('div.placeholder.claude-empty', {}, el('p', {}, 'Claude Code is not installed on this computer.'),
el('button.btn.primary', { onclick: () => this.app.openUrl('https://claude.com/claude-code') }, 'Install Claude Code'),
el('p', { style: { fontSize: '12px' } }, 'Then sign in once in a terminal (claude), and come back.')));
}
for (const item of this.items) this.renderItem(item); // an old conversation can still be read
}
/** The open tabs (prefs) and the project's history (the whole conversation, a moment later). */
save() {
this.panel.saveSoon();
if (this.panel.historyLocal && this.items.length) this.saveHistory();
}
saveNow() {
if (!this.panel.historyLocal || !this.items.length) return Promise.resolve();
return backend.invoke('claude.history.save', { conversation: { id: this.key, title: this.name, session: this.session, items: this.items } })
.catch(() => null);
}
markdown() {
return this.saveNow().then(() => backend.invoke('claude.history.markdown', { id: this.key }));
}
dispose() {
this.task?.();
this.task = null;
}
mentionFile() {
const path = this.app.editors?.activePath();
if (!path) return;
this.insert(`@${path} `);
}
addSelection() {
const ed = this.app.editors?.editor();
const path = this.app.editors?.activePath();
const sel = ed?.getSelection();
if (!ed || !path || !sel || sel.isEmpty()) { notify('Select some code first.', 'info'); return; }
const code = ed.getModel().getValueInRange(sel);
this.insert(`In ${path} (lines ${sel.startLineNumber}-${sel.endLineNumber}):\n\`\`\`\n${code}\n\`\`\`\n`);
}
insert(text) {
const at = this.input.selectionStart ?? this.input.value.length;
this.input.value = this.input.value.slice(0, at) + text + this.input.value.slice(at);
this.input.focus();
}
/** A line of the live log (claude.log): kept (the last 400), shown when the log is open, and it tells the spinner what happened last. */
logLine(p) {
const t = this.run ? ((p.at * 1000 - this.run.started) / 1000) : 0;
const line = `${t >= 0 ? '+' + t.toFixed(1).padStart(6) + ' s' : ' '} ${p.level === 'error' ? '✗ ' : p.level === 'stderr' ? '! ' : ' '}${p.text}`;
this.logLines.push(line);
if (this.logLines.length > 400) this.logLines.shift();
if (this.run) { this.run.lastAt = Date.now(); this.run.last = p.text; }
if (!this.logView.hidden) {
const stick = this.logView.scrollTop + this.logView.clientHeight >= this.logView.scrollHeight - 30;
this.logView.append(document.createTextNode(line + '\n'));
if (stick) this.logView.scrollTop = this.logView.scrollHeight;
}
}
toggleLog() {
this.logView.hidden = !this.logView.hidden;
this.logBtn.classList.toggle('active', !this.logView.hidden);
if (!this.logView.hidden) {
this.logView.textContent = this.logLines.length ? this.logLines.join('\n') + '\n' : '(nothing yet: the log fills while the assistant works)\n';
this.logView.scrollTop = this.logView.scrollHeight;
}
}
/** Live speed of the model (claude.speed from a local llama.cpp server, or computed from a message's usage): shown in the spinner line. */
speed(p) {
if (!this.run) return;
this.run.speed = { ...p, at: Date.now() };
this.tickThinking();
}
speedText() {
const s = this.run?.speed;
if (!s || Date.now() - s.at > 6000) return '';
if (s.phase === 'prompt') return ` · reading the prompt ${s.total ? Math.round(100 * s.done / s.total) + ' %' : ''}`;
if (s.phase === 'gen') return ` · ⚡ ${s.tps > 0 ? s.tps.toFixed(1) : '…'} tok/s (${s.n} tokens)`;
return s.tps ? ` · ${s.phase === 'avg' ? '~' : ''}${s.tps.toFixed(1)} tok/s` : '';
}
/** The spinner line says how long the turn lasts and how long since the last sign of life, so that a slow model does not look dead. */
tickThinking() {
if (!this.run || !this.thinkText?.isConnected) return;
const now = Date.now();
const total = Math.round((now - this.run.started) / 1000);
const quiet = Math.round((now - (this.run.lastAt || this.run.started)) / 1000);
const who = this.panel.agent === 'opencode' ? 'OpenCode' : 'Claude';
this.thinkText.textContent = `${who} is working… ${total} s` + this.speedText() + (this.run.last ? ` · last: ${this.run.last.slice(0, 90)}` : ' · waiting for the first answer (a local model loads/reads the prompt first)') + (quiet >= 20 ? ` · quiet for ${quiet} s (Log shows the details)` : '');
}
/** Restart: the turn in progress (stuck, or ended on an error) is stopped, and the last request is sent again on the same session. */
async retry() {
const prompt = this.lastPrompt || 'continue';
if (this.run) {
await backend.invoke('claude.stop', { id: this.run.id }).catch(() => null);
this.endTurn();
await new Promise((r) => setTimeout(r, 600)); // the process leaves: OpenCode answers one message at a time
}
this.add({ role: 'note', text: 'Restarting: ' + (this.lastPrompt ? 'the last request is sent again.' : '“continue” is sent.') });
this.input.value = prompt;
await this.send();
}
async send() {
const prompt = this.input.value.trim();
const p = this.panel;
// the web IDE's Claude (through jumphp.net) takes one message per run
if (!prompt || (this.run && p.remote)) return;
if (p.available === false) { this.notInstalled(); return; }
if (/^\/(rc|remote-control)$/.test(prompt)) { this.remoteControl(); return; }
// the conversation lives in the Terminal now (Remote Control): a second claude process on the same session is what made the phone say
// "another session is working on it" and showed a fork of the work. Write there (or from the phone); closing that tab gives it back here.
if (this.rcTab && !this.rcTab.ended && !p.remote) {
// the text goes into the arbiter's ordered queue and is typed into the Terminal's claude, in order, once it is there (drainTerminal):
// the panel shows it when claude writes it in its session file (followed live), so it is not added twice
const line = prompt.replace(/\s+/g, ' ').trim();
this.input.value = '';
this.add({ role: 'user', text: prompt });
this.app.showTool('terminal', true); // the Terminal is shown again and has the focus
this.rcTab.term.focus();
try {
await backend.invoke('claude.lease.submit', { conv: this.key, session: this.session || '', text: line });
await this.drainTerminal();
} catch (e) { this.add({ role: 'error', text: tr(e.message) }); }
return;
}
this.rcTab = null;
await this.app.editors?.saveAll(true);
this.log.querySelector('.claude-empty')?.remove();
// once per project: where what the AI does is kept
if (!p.remote && backend.kind === 'native' && !prefs.get('iaNote:' + p.app.projectKey, false)) {
prefs.set('iaNote:' + p.app.projectKey, true);
this.add({ role: 'note', text: 'Each turn of Claude / OpenCode is saved in the project\'s IA/HISTORY folder (IA/HISTORY/<assistant>/<model>/<date>/<request>.md). It is NOT sent to git (IA/ is in .gitignore): it stays on this computer only, so it is lost if you delete the project folder or change computer.' });
}
const during = !!this.run;
this.lastPrompt = prompt;
this.scrollToEnd(); // you want to see your answer
// a checkpoint before each message: the ↶ of its bubble brings the files and the conversation back to just before it
const cp = p.remote || backend.kind !== 'native' ? undefined : 'cp' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
this.add({ role: 'user', text: prompt, during, cp });
this.input.value = '';
p.renderTabs();
try {
const r = await backend.invoke('claude.send', { prompt, session: this.session, mode: p.mode, model: p.agent === 'opencode' ? p.opencodeModel : p.model, effort: p.effort, conv: this.key, agent: p.agent, checkpoint: cp });
if (r?.queued) { this.showQueued(r, prompt); return; } // somebody else has the session: it waits, in order (never dropped)
const { id } = r;
if (!p.remote) this.live = id;
if (this.run && this.run.id === id) return; // read by Claude in the turn in progress
this.startTurn(id);
if (p.remote) this.pollRemote(id, 0);
} catch (e) {
this.add({ role: 'error', text: tr(e.message) });
}
}
/** ↶ on a bubble of the user: the files as they were before it, the conversation cut there, the message back in the box to edit. */
async rewindTo(item) {
const at = this.items.indexOf(item);
if (at < 0) return;
const later = this.items.slice(at).filter((i) => i.role === 'user').length;
if (!(await confirm(tr('Go back to before this message?'), tr('The files are put back as they were before it (what Claude / OpenCode changed since is undone), and this message and the {n} after it are removed from the conversation. The message comes back in the box.', { n: later - 1 }), { ok: tr('Go back'), danger: true }))) return;
if (this.run) { await backend.invoke('claude.stop', { id: this.run.id }).catch(() => null); this.endTurn(); }
this.live = null;
let r;
try {
r = await backend.invoke('claude.rewind', { conv: this.key, checkpoint: item.cp, session: this.session || '' });
} catch (e) {
notify(tr(e.message), 'error', { title: tr('Go back') });
return;
}
this.items.splice(at);
this.session = r.session || null;
this.rerender();
this.save();
if (!this.items.length && this.panel.historyLocal) {
backend.invoke('claude.history.save', { conversation: { id: this.key, title: this.name, session: this.session, items: [] } }).catch(() => null);
}
if (r.note) this.add({ role: 'note', text: r.note });
this.input.value = item.text;
this.input.focus();
this.panel.renderTabs();
notify(r.files > 0 ? tr('Back to before the message: {n} file(s) restored.', { n: r.files }) : r.files === 0 ? tr('Back to before the message: no file had changed.') : tr('Back to before the message (Git was not found: the files were not restored).'), 'info', { title: 'Claude' });
}
/** /rc: `claude -p` has no Remote Control, so this conversation goes on in an interactive claude in the Terminal. */
async remoteControl() {
try { await this.startRemoteControl(); } finally { this.rcBusy = false; this.drainTerminal(); }
}
async startRemoteControl() {
if (this.rcTab && !this.rcTab.ended && !this.panel.remote) { // already there: a second claude on the session would fork it
this.input.value = '';
this.app.showTool('terminal', true);
this.rcTab.term.focus();
notify(tr('Remote Control is already open in the Terminal.'), 'info', { title: 'Claude' });
return;
}
if (this.panel.remote) { notify(tr('Remote Control needs Claude Code on this computer (the desktop IDE).'), 'info'); return; }
this.input.value = '';
// the same thing you type by hand: an interactive claude on this session, then its own /remote-control command (given as the first
// prompt). `claude --remote-control` on a session that `claude -p` made did not show on the phone, while /remote-control typed in claude did
const session = /^[\w-]+$/.test(this.session || '') ? ` --resume ${this.session}` : '';
this.add({ role: 'note', text: tr('Remote Control: this conversation goes on in the Terminal (the own Claude of the panel stops, so that only one works on it), where /remote-control is typed for you. Write there or from your phone; close that Terminal tab to use the panel again. Open it from claude.ai/code or the Claude app; if the Terminal shows no "Remote Control active" line, type /remote-control there.') });
const terminal = this.app.terminal;
// ONE claude on the session: the panel's own process (claude -p, kept open between turns) stops first. Two processes on the same session made
// the phone's Remote Control a fork that did not follow the panel, and refuse to take part ("another session is working on it")
if (this.run) { await backend.invoke('claude.stop', { id: this.run.id }).catch(() => null); this.endTurn(); }
await backend.invoke('claude.close', { conv: this.key }).catch(() => null);
this.live = null;
// the arbiter hands the session over: the panel's process must be GONE (confirmed exit, hard kill after a timeout) and no other claude may
// work on it; messages typed meanwhile are queued. Only then does the Terminal's claude start.
const lease = await this.requestLease();
if (!lease.ok) {
this.add({ role: 'error', text: tr('The session could not be handed to the Terminal: {message}', { message: this.leaseText(lease.lease) }) });
return;
}
// where the session's file is now: what the Terminal's claude adds after it comes back here (panel + IA/HISTORY) when its tab closes
const mark = await backend.invoke('claude.session.mark', { session: this.session || '' }).catch(() => ({ lines: 0, at: Date.now() / 1000 }));
// followed live from here on: every second what claude added to its session file comes into the panel, and into IA/HISTORY as turns end
await backend.invoke('claude.session.start', { conv: this.key, session: this.session || '', since: mark.lines || 0, at: mark.at || 0 }).catch(() => null);
this.rcMark = mark;
this.rcBusy = true; // nothing is typed by the queue while this function types the start-up commands
await terminal.run(`claude${session}`, 'Claude Remote Control');
const t = terminal.current();
if (!t) { this.rcBusy = false; backend.invoke('claude.session.stop', { conv: this.key }).catch(() => null); return; }
this.rcTab = t;
backend.invoke('claude.lease.attach', { conv: this.key, session: this.session || '', terminal: t.id }).catch(() => null);
this.rcFollow();
this.app.showTool('terminal', true); // the Terminal is shown and has the focus: the reader sees what happens
t.term.focus();
t.onEnd = () => { t.onEnd = null; this.rcBack(mark); };
// what claude's screen says (the xterm buffer, spaces squeezed so that a wrapped or re-drawn line still matches)
const screen = () => {
const buf = t.term.buffer.active;
const rows = [];
for (let i = Math.max(0, buf.length - 60); i < buf.length; i++) rows.push(buf.getLine(i)?.translateToString(true) ?? '');
return rows.join('\n');
};
const flat = () => screen().replace(/\s+/g, '').toLowerCase();
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
// 1. typed only once claude's own prompt is on the screen: it prints nothing for a few seconds while it starts (node, the session being
// loaded), and a quiet screen then is not a ready one. Then a short quiet, for the last things it draws.
const begun = Date.now();
let quietSince = 0;
let last = '';
while (!t.ended && Date.now() - begun < 45000) {
const now = flat();
// claude's prompt glyph changes between versions: its banner, or a quiet screen with something on it, is enough
const trust = now.includes('trustthisfolder') || now.includes('trustthefiles');
const ready = !trust && now.length > 40 && (now.includes('claudecode') || now.includes('❯') || now.includes('?forshortcuts') || Date.now() - begun > 6000);
if (now !== last) { last = now; quietSince = Date.now(); }
if (ready && Date.now() - quietSince >= 1200) break;
await pause(150);
}
if (t.ended) return;
if (/trustthisfolder|trustthefiles/.test(flat())) { notify(tr('Claude asks whether you trust this folder: answer it in the Terminal, then type /remote-control there.'), 'info', { title: tr('Remote Control') }); return; }
// 2. the text, then Enter apart (a TUI takes text and Enter together for a paste), then we look for claude's answer
t.term.focus();
terminal.input(t, '/remote-control');
await pause(700);
if (!t.ended && !flat().includes('/remote-control')) { terminal.input(t, '/remote-control'); await pause(700); } // lost while claude was drawing
terminal.input(t, '\r');
const answered = async (ms) => {
const until = Date.now() + ms;
while (!t.ended && Date.now() < until) {
// claude's own Remote Control menu ("This session is available in the Claude mobile app... ❯ Continue"): it means it is on; Continue is accepted
const f = flat();
if (f.includes('remote-controlisactive')) return true;
if (f.includes('thissessionisavailable') || f.includes('disconnectthissession')) {
if (/❯\s*continue/i.test(screen())) terminal.input(t, '\r');
await pause(400);
return true;
}
await pause(250);
}
return false;
};
let ok = await answered(12000);
if (!ok && !t.ended && flat().includes('/remote-control')) {
// the command is typed but not run (the command list was open and took the first Enter): once more
terminal.input(t, '\r');
ok = await answered(12000);
}
if (ok) {
notify(tr('Remote Control is active: continue from your phone or claude.ai/code.'), 'success', { title: 'Claude' });
// the menu is closed (Continue accepted): "continue" is typed in claude so that it goes on with the conversation
const gone = Date.now() + 6000;
while (!t.ended && Date.now() < gone && flat().includes('disconnectthissession')) await pause(250);
if (!t.ended) {
await pause(800);
// "continue: <the last request>": claude reads it as one line (a new line would send it half way)
const lastUser = [...this.items].reverse().find((i) => i.role === 'user');
const last = (lastUser?.text || this.lastPrompt || '').replace(/\s+/g, ' ').trim().slice(0, 600);
terminal.input(t, last ? `continue : ${last}` : 'continue');
await pause(500);
terminal.input(t, '\r');
}
}
else if (!t.ended) this.add({ role: 'error', text: tr('Remote Control did not answer “/remote-control is active” in the Terminal. What the screen shows:') + '\n' + screen().split('\n').filter((l) => l.trim()).slice(-8).join('\n') });
}
/** The Terminal's claude ended (its tab closed, /exit): the conversation is the panel's again, with what was typed there. */
/** While the Terminal's claude is open: its session file is read every second (what is typed there or from the phone shows here). */
rcFollow() {
clearInterval(this.rcTimer);
this.stopBtn.hidden = false; // Stop works on the Terminal's claude too
let busy = false;
this.rcTimer = setInterval(async () => {
if (busy || !this.rcTab) return;
busy = true;
try {
const r = await backend.invoke('claude.session.poll', { conv: this.key });
if (r.session) this.session = r.session;
let added = false;
for (const item of r.items || []) {
if (item.role === 'user' && this.rcPending?.length) { // typed in the panel: its bubble is already there
const k = this.rcPending.indexOf(item.text.replace(/\s+/g, ' ').trim());
if (k >= 0) { this.rcPending.splice(k, 1); continue; }
}
this.add(item); added = true;
}
if (added) this.save?.();
this.drainTerminal();
} catch { /* the next second */ } finally { busy = false; }
}, 1000);
}
async rcBack(mark) {
if (!this.rcTab) return;
this.rcTab = null;
this.rcBusy = false;
clearInterval(this.rcTimer);
if (!this.run) this.stopBtn.hidden = true;
try {
const r = await backend.invoke('claude.session.stop', { conv: this.key });
if (r.session) this.session = r.session;
for (const item of r.items || []) this.add(item);
this.add({ role: 'note', text: r.turns ? tr('Back in the panel: {n} request(s) of the Terminal were followed live here and kept in IA/HISTORY.', { n: r.turns }) : tr('Back in the panel (nothing new found in the session file {file}, {lines} lines, since {time}).', { file: r.file || 'none', lines: r.lines || 0, time: new Date((mark?.at || 0) * 1000).toLocaleTimeString() }) });
this.save?.();
this.panel.renderTabs();
this.app.showTool?.('claude', true);
} catch (e) { this.add({ role: 'error', text: tr('Back from the Terminal: {error}', { error: tr(e.message) }) }); }
}
// ---- the lease: who works on this session (ide/src/Claude/SessionArbiter.php, docs/claude-session-arbiter.md) ----------------------
/**
* The page reloaded: ask the arbiter who has the session now (claude.lease.get) instead of waiting for an event that already went by.
* A conversation that was in Remote Control finds its Terminal tab again (reload); without the tab (the IDE restarted: its shell is
* gone) the session is handed back to the panel.
*/
async resync(rcTab, rc) {
if (this.panel.remote || this.panel.agent === 'opencode') return;
const args = { conv: this.key, session: this.session || '' };
const l = await backend.invoke('claude.lease.get', args).catch(() => null);
if (!l || !l.state) return;
if (rcTab && !rcTab.ended && (l.state === 'terminal' || l.state === 'handoff')) {
this.rcTab = rcTab;
this.rcMark = rc?.mark || null;
rcTab.onEnd = () => { rcTab.onEnd = null; this.rcBack(this.rcMark); };
this.rcFollow();
this.leaseEvent(l);
return;
}
if (l.state === 'terminal') {
this.rcTab = { ended: true, term: { focus() {} } };
await backend.invoke('claude.lease.ended', { ...args, reason: 'terminal-gone' }).catch(() => null);
await this.rcBack(rc?.mark || null);
return;
}
this.leaseEvent(l);
}
/** Asks for the session for the Terminal and waits (polling, the frame is never blocked) until it is granted, refused, or too slow. */
async requestLease() {
const args = { conv: this.key, session: this.session || '' };
let l = await backend.invoke('claude.lease.request', args).catch((e) => ({ state: 'conflict', conflict: { message: e.message } }));
const end = Date.now() + 20000;
while (l.state !== 'terminal' && l.state !== 'conflict' && Date.now() < end) {
await new Promise((r) => setTimeout(r, 150));
l = await backend.invoke('claude.lease.get', args).catch(() => l);
}
if (l.state !== 'terminal') await backend.invoke('claude.lease.ended', { ...args, reason: 'request-withdrawn' }).catch(() => null);
return { ok: l.state === 'terminal', lease: l };
}
/** What the person reads about a conflict: which process, which terminal (the foreign claude is never guessed at). */
leaseText(l) {
const c = l?.conflict;
const f = c?.foreign?.[0];
if (c?.reason === 'will-not-exit') return tr('A Claude process does not stop (pid {pid}): stop it yourself.', { pid: f?.pid ?? '?' });
if (!f) return tr('Something writes into this session\'s file while no Claude of the IDE works on it. Close the other Claude that uses this session, then check again.')
+ (c?.file ? ' ' + tr('File: {file}', { file: c.file }) : '');
return tr('Another Claude works on this session (pid {pid}, {where}). Only one may work on a session: stop it, or close its terminal.',
{ pid: f.pid, where: f.tty ? tr('in terminal {tty}', { tty: f.tty }) : tr('without a terminal') });
}
leaseEvent(p) {
this.lease = p;
const was = this.leaseState;
this.leaseState = p.state;
this.renderLease();
this.conflictNode?.remove();
this.conflictNode = null;
// a conversation OpenCode answers does not use Claude's session: a conflict on it is not this conversation's business
if (p.state === 'conflict' && this.panel.agent !== 'opencode') this.showConflict(p); // every event of a conflict redraws the card (it used to vanish at the second one)
// the Terminal's claude is gone (/exit, Ctrl+C, its tab closed) while the shell stays: the panel has the conversation back and takes up its queue
if (this.rcTab && !this.rcBusy && (p.state === 'idle' || p.state === 'panel') && (p.reason || '').startsWith('terminal')) {
this.add({ role: 'note', text: tr('The Terminal\'s Claude is gone: the conversation is the panel\'s again.') });
this.rcBack(this.rcMark);
}
}
renderLease() {
const l = this.lease;
const names = { panel: tr('Panel'), terminal: tr('Terminal'), handoff: tr('Switching…'), conflict: tr('Conflict') };
const tips = {
panel: tr('The Claude of the panel works on this session'),
terminal: tr('The Claude of the Terminal works on this session'),
handoff: tr('The session is changing hands: messages typed now are queued and delivered in order'),
conflict: tr('Two Claude agents on one session: only one may work on it'),
};
const show = !!l && !!names[l.state] && !this.panel.remote && this.panel.agent !== 'opencode';
this.leaseBadge.hidden = !show;
if (show) {
this.leaseBadge.textContent = names[l.state];
this.leaseBadge.title = tips[l.state];
this.leaseBadge.className = 'claude-lease ' + l.state;
}
if (!this.run) this.input.placeholder = this.idlePlaceholder();
}
idlePlaceholder() {
const s = this.lease?.state;
if (s === 'handoff') return tr('Switching to the Terminal… a message typed now is queued and sent there, in order.');
if (s === 'terminal' && this.rcTab && !this.rcTab.ended) return tr('The Terminal\'s Claude has this session: what you type here is sent there.');
return 'Ask Claude… (Enter to send, Shift+Enter: new line, @path: a file)';
}
showConflict(p) {
const text = this.leaseText(p);
notify(text, 'warning', { title: 'Claude' });
const pids = (p.conflict?.foreign || []).filter((f) => f.kind === 'strong' || f.kind === 'weak').map((f) => f.pid);
// the lease is named by what its event says (conv / session of the arbiter), not by what this page believes: they can differ
const conv = p.conv || this.key;
const session = p.session && !String(p.session).startsWith('conv:') ? p.session : (this.session || '');
const status = el('span.claude-conflict-status', {});
const buttons = [];
const act = async (action, pid = 0) => {
buttons.forEach((b) => { b.disabled = true; });
status.textContent = tr('Checking…');
try {
const r = await backend.invoke('claude.lease.resolve', { conv, session, action, pid });
// solved: the claude.lease event removes the card; else it says so (and the buttons come back)
if (r && r.state === 'conflict') status.textContent = tr('Still in conflict.') + (r.message ? ' ' + r.message : '');
else status.textContent = '';
} catch (e) { status.textContent = ''; notify(e.message, 'error'); }
buttons.forEach((b) => { b.disabled = false; });
};
for (const pid of pids.slice(0, 3)) buttons.push(el('button.btn.small', { onclick: () => act('kill', pid) }, tr('Stop it') + ` (${pid})`));
buttons.push(el('button.btn.small', { onclick: () => act('recheck') }, tr('Check again')));
this.conflictNode = el('div.claude-conflict', {}, el('span', {}, text), ...buttons, status);
this.log.append(this.conflictNode);
this.scroll(true);
}
/** A message the arbiter keeps for whoever owns the session next: shown as waiting (the bubble is already there), delivered in order. */
showQueued(r, text) {
this.queuedNode?.remove();
const toTerminal = r.to === 'terminal' && this.rcTab && !this.rcTab.ended;
const what = r.state === 'conflict' || r.conflict ? tr('Queued: it waits until the conflict is solved.')
: toTerminal ? tr('Queued: it will go to the Terminal as soon as it is ready.') : tr('Queued: it will go to the panel as soon as it is ready.');
this.queuedNode = el('div.claude-thinking', {}, el('span.spinner'), el('span', {}, what));
this.log.append(this.queuedNode);
this.scroll(true);
}
/** The arbiter handed a queued message to the panel's claude: its turn starts. */
queueSent(p) {
this.queuedNode?.remove();
this.queuedNode = null;
if (p.id && !this.run) this.startTurn(p.id);
if (p.id) this.live = p.id;
}
/** What waits for the Terminal's claude is typed there, one message after the other (the text, then Enter apart: a TUI takes both together for a paste). */
async drainTerminal() {
if (!this.rcTab || this.rcTab.ended || this.rcBusy || this.draining || this.panel.remote) return;
this.draining = true;
const pause = (ms) => new Promise((r) => setTimeout(r, ms));
try {
const items = await backend.invoke('claude.lease.drain', { conv: this.key, session: this.session || '' });
for (const it of items || []) {
const tab = this.rcTab;
if (!tab || tab.ended) break;
if (it.conv === this.key) (this.rcPending ||= []).push(it.text.replace(/\s+/g, ' ').trim()); // its bubble is already there
this.app.terminal.input(tab, it.text);
await pause(400);
if (!tab.ended) this.app.terminal.input(tab, '\r');
await pause(600);
}
this.queuedNode?.remove();
this.queuedNode = null;
} catch { /* the next second */ } finally { this.draining = false; }
}
/** Claude works: the spinner, Stop, the box for more. */
startTurn(id) {
this.run = { id, started: Date.now(), tools: 0 };
this.stopBtn.hidden = false;
const who = this.panel.agent === 'opencode' ? 'OpenCode' : 'Claude';
this.input.placeholder = this.panel.remote ? `${who} is working…` : this.panel.agent === 'opencode' ? 'OpenCode is working… (one message at a time)' : 'Tell Claude more while it works: it reads it at once (Enter)';
this.thinking?.remove();
this.thinkText = el('span', {}, `${who} is working…`);
this.thinking = el('div.claude-thinking', {}, el('span.spinner'), this.thinkText);
clearInterval(this.thinkTimer);
this.thinkTimer = setInterval(() => this.tickThinking(), 1000);
this.logLines.push(`--- new turn ${new Date().toLocaleTimeString()} ---`);
if (!this.logView.hidden) this.logView.append(document.createTextNode(`--- new turn ${new Date().toLocaleTimeString()} ---\n`));
this.log.append(this.thinking);
this.scroll();
this.panel.say('working…');
this.panel.renderTabs();
this.task?.();
this.task = this.app.task?.(`${who} is working… (${this.title()})`, { open: () => { this.app.showTool('claude'); this.panel.show(this); } }) || null;
}
/** The turn is over (its result, or the process ended): what it changed comes in. */
endTurn() {
clearInterval(this.thinkTimer);
this.task?.();
this.task = null;
this.dropLive();
if (!this.run) return;
this.run = null;
this.panel.watch.done();
this.thinking?.remove();
this.stopBtn.hidden = true;
this.input.placeholder = this.idlePlaceholder();
this.panel.say('ready');
this.panel.renderTabs();
this.saveNow();
this.panel.saveSoon();
// what it changed: the tree, Git, the open files
this.app.tree?.refresh();
this.app.git?.refresh();
this.app.editors?.reloadFromDisk();
}
/** The web IDE: the events of the computer's Claude, through jumphp.net (they arrive as claude.event / claude.exit). */
async pollRemote(id, after) {
if (!this.run || this.run.id !== id) return;
const r = await backend.invoke('claude.poll', { id, after }).catch(() => null);
if (!this.run || this.run.id !== id) return;
setTimeout(() => this.pollRemote(id, r ? r.next : after), r ? 700 : 3000);
}
/** Stop: every agent of this conversation: the panel's claude / OpenCode, and the Terminal's claude (Remote Control) gets Escape, its own interrupt. */
stop() {
if (!this.panel.remote) backend.invoke('claude.stopAll', { conv: this.key, session: this.session || '' }).catch(() => null);
if (this.run) backend.invoke('claude.stop', { id: this.run.id }).catch(() => null);
if (this.rcTab && !this.rcTab.ended) { this.app.terminal.input(this.rcTab, '\x1b'); this.add({ role: 'note', text: tr('Stop sent to the Terminal\'s Claude (Escape).') }); }
}
/** Removes what was drawn live (the whole message of the same block follows). */
dropLive() {
this.live_?.node?.remove();
this.live_ = null;
if (this.run) this.run.streamChars = 0;
}
/** A partial event of the API stream: the thinking and the answer grow on screen, the spinner counts tokens. */
streamEvent({ event: e }) {
if (!this.run || !e) return;
const run = this.run;
const place = (node) => { if (this.thinking?.isConnected) this.log.insertBefore(node, this.thinking); else this.log.append(node); this.scroll(true); };
if (e.type === 'message_start') { run.turnStart = Date.now(); run.streamChars = 0; run.msgTokens = 0; }
else if (e.type === 'content_block_start') {
this.dropLive();
const t = e.content_block?.type;
run.blockStart = Date.now();
if (t === 'thinking') { const node = el('div.claude-msg.claude-live-think', {}, el('b', {}, 'Thinking… '), el('span')); this.live_ = { kind: 'thinking', node, body: node.lastChild, buf: '' }; place(node); }
else if (t === 'text') { const node = el('div.claude-msg.assistant'); this.live_ = { kind: 'text', node, buf: '' }; place(node); }
else if (t === 'tool_use') { const node = el('div.claude-tool', {}, icon('settings'), el('b', {}, e.content_block.name || 'tool'), el('span', {}, '…')); this.live_ = { kind: 'tool', node, buf: '' }; place(node); }
} else if (e.type === 'content_block_delta' && this.live_) {
const d = e.delta || {};
const piece = d.thinking ?? d.text ?? d.partial_json ?? '';
this.live_.buf += piece;
run.streamChars = (run.streamChars || 0) + piece.length;
if (!this.live_.raf) {
this.live_.raf = requestAnimationFrame(() => {
const l = this.live_; if (!l) return;
l.raf = 0;
if (l.kind === 'thinking') l.body.textContent = l.buf.slice(-1500);
else if (l.kind === 'text') { clear(l.node); l.node.append(...markdown(l.buf)); }
else l.node.lastChild.textContent = l.buf.slice(-200);
this.scroll();
});
}
const secs = Math.max(0.3, (Date.now() - (run.blockStart || run.started)) / 1000);
const n = Math.round(run.streamChars / 3.5);
this.speed({ phase: 'gen', tps: n / secs, n });
} else if (e.type === 'message_delta' && e.usage?.output_tokens) {
run.msgTokens = e.usage.output_tokens;
}
run.lastAt = Date.now();
if (this.live_?.kind === 'thinking') run.last = 'thinking…'; else if (this.live_?.kind === 'text') run.last = 'writing…'; else if (this.live_?.kind === 'tool') run.last = 'preparing an action…';
}
event({ id, event }) {
// the open conversation goes on by itself (a message that came just as a turn ended): a turn again
if (!this.run && id === this.live && event.type !== 'result' && event.type !== 'system') this.startTurn(id);
if (this.run && this.run.id === null) this.run.id = id; // a window that opened in the middle of a turn
if (!this.run || id !== this.run.id) return;
if (event.session_id) this.session = event.session_id;
if (event.type === 'stream_event') { this.streamEvent(event); return; } // thinking, text and tokens as they come (--include-partial-messages)
// no live feed from the server (Claude, cloud models): the speed of a message = its output tokens over the time since the last event
const outTokens = event.type === 'assistant' ? event.message?.usage?.output_tokens : 0;
const sinceLast = (Date.now() - (this.run.evAt || this.run.started)) / 1000;
this.run.evAt = Date.now();
if (outTokens > 20 && sinceLast > 0.3 && (!this.run.speed || this.run.speed.phase === 'avg')) this.speed({ phase: 'avg', tps: outTokens / sinceLast });
const panel = this.panel;
if (event.type === 'system' && event.subtype === 'init') {
panel.say(event.model ? `${event.model}` : 'working…');
// the context window is only reported with the turn's result: until then, the model's usual one, so the bar moves from the first answer
if (!this.context?.window) this.context = { ...this.context, window: /\[1m\]|1m$/i.test(event.model || '') ? 1000000 : 200000 };
if (panel.active === this) panel.usage.context(this.context);
} else if (event.type === 'assistant') {
const u = event.message?.usage;
if (u && !event.parent_tool_use_id) {
this.context = { ...this.context, used: (u.input_tokens || 0) + (u.cache_read_input_tokens || 0) + (u.cache_creation_input_tokens || 0) + (u.output_tokens || 0) };
if (panel.active === this) panel.usage.context(this.context);
panel.saveSoon();
}
this.dropLive();
for (const part of event.message?.content || []) {
if (part.type === 'thinking' && part.thinking?.trim()) this.add({ role: 'thinking', text: part.thinking });
else if (part.type === 'text' && part.text?.trim()) this.add({ role: 'assistant', text: part.text });
else if (part.type === 'tool_use') {
this.run.tools++;
this.add({ role: 'tool', name: part.name, input: part.input || {} });
if (part.name === 'TodoWrite') this.showPlan(part.input?.todos || []);
panel.planTarget = this;
panel.watch.use(part);
panel.planTarget = null;
this.task?.update(`${who}: ${toolText(part.name, part.input || {}, this.app.project?.root || '')}`);
}
}
} else if (event.type === 'user') {
for (const part of event.message?.content || []) {
if (part.type === 'tool_result' && part.is_error) this.add({ role: 'tool-error', text: toText(part.content).slice(0, 600) });
if (part.type === 'tool_result') panel.watch.result(part);
}
} else if (event.type === 'result') {
const windows = Object.values(event.modelUsage || {}).map((m) => m.contextWindow).filter(Boolean);
if (windows.length) {
this.context = { ...this.context, window: Math.max(...windows) };
if (panel.active === this) panel.usage.context(this.context);
}
const seconds = Math.round((event.duration_ms || (Date.now() - this.run.started)) / 1000);
if (event.is_error && event.result) this.add({ role: 'error', text: event.result });
if (event.permission_denials?.length) {
this.add({ role: 'note', text: `Refused (mode “${MODES[panel.mode][0]}”): ${event.permission_denials.map((d) => d.tool_name).join(', ')}. Change what Claude may do (⚙) and ask again.` });
}
this.add({ role: 'done', text: `${event.is_error ? 'Stopped' : 'Done'} · ${seconds} s · ${this.run.tools} action(s)` });
if (!panel.remote) { this.endTurn(); this.autoCompact(); return; }
}
this.save();
}
/**
* Claude Code's own automatic compaction does not always run in this window (claude -p): when the context is 80 % full at the
* end of a turn, /compact is sent, as one would type it. The gauge restarts from the summary.
*/
autoCompact() {
const p = this.panel;
if (this.compacting) { // the /compact turn just ended: the old size no longer counts
this.compacting = false;
this.context = { ...this.context, used: 0 };
if (p.active === this) p.usage.context(this.context);
return;
}
const c = this.context;
if (p.agent !== 'claude' || p.remote || prefs.get('claudeAutoCompact', true) === false || !c?.used || !c?.window || c.used / c.window < 0.8) return;
this.compacting = true;
this.add({ role: 'note', text: `The context is ${Math.round(100 * c.used / c.window)} % full: compacting it now (/compact) so the conversation goes on.` });
setTimeout(() => { this.input.value = '/compact'; this.send(); }, 300);
}
exit({ id, code, error, changed }) {
if (id === this.live) this.live = null;
if (!this.run || id !== this.run.id) return;
if (code !== 0 && error) this.add({ role: 'error', text: error });
if (changed?.length) this.add({ role: 'note', text: `Saved as drafts here: ${changed.join(', ')}` });
this.endTurn();
}
add(item) {
this.items.push(item);
this.renderItem(item);
this.scroll(true);
this.save();
}
/** A step of the "Step by step" mode asks for the user: its card joins the conversation (the item is already in `items` for the next ones). */
addStep(item) {
this.add(item);
this.panel.say('waiting for you');
}
/** A step's status changed: the card is drawn again, the conversation saved. */
refreshStep(item) {
redrawStep(item);
this.save();
this.panel.say('working…');
}
renderItem(item) {
let node;
if (item.role === 'user') {
node = el(`div.claude-msg.user${item.during ? '.during' : ''}`, { title: item.during ? tr('Sent while Claude was working') : '' }, item.text);
if (item.cp) node.append(el('button.claude-rewind', { title: tr('Go back to before this message: the files it changed are restored, this message and the ones after it are removed'), onclick: (e) => { e.stopPropagation(); this.rewindTo(item); } }, '↶'));
}
else if (item.role === 'assistant') node = el('div.claude-msg.assistant', {}, ...markdown(item.text));
else if (item.role === 'thinking') node = el('details.claude-think', {}, el('summary', {}, 'Thinking'), el('div.claude-think-text', {}, item.text));
else if (item.role === 'tool') node = this.toolRow(item);
else if (item.role === 'done') node = el('div.claude-done', {}, item.text);
else if (item.role === 'step') { if (item.status === 'pending' && !hasPending(item.id)) item.status = 'ended'; node = stepCard(this.app, item, this); }
else node = el(`div.claude-msg.${item.role === 'note' ? 'note' : item.role === 'tool-error' ? 'toolfail' : 'error'}`, {}, item.text);
if (this.thinking?.isConnected) this.log.insertBefore(node, this.thinking);
else this.log.append(node);
}
/** Claude's plan (TodoWrite), kept above the conversation while it works through it. */
showPlan(todos) {
clear(this.plan);
this.plan.hidden = !todos.length || todos.every((t) => t.status === 'completed');
if (this.plan.hidden) return;
const done = todos.filter((t) => t.status === 'completed').length;
this.plan.append(el('div.claude-plan-head', {}, icon('check'), `Plan · ${done}/${todos.length}`),
...todos.map((t) => el(`div.claude-plan-item.${t.status || 'pending'}`, {}, el('span.mark', {}, t.status === 'completed' ? '✓' : t.status === 'in_progress' ? '▸' : '○'),
t.status === 'in_progress' && t.activeForm ? t.activeForm : t.content)));
}
/** A file to show: here, or in the main window when this conversation is in a window of its own. */
openFile(path, opts = {}) {
if (this.panel.detached) backend.invoke('ui.broadcast', { type: 'claude.open', path, line: opts.line || null }).catch(() => null);
else this.app.editors.open(path, opts);
}
toolRow({ name, input }) {
if (name.startsWith(IDE_TOOL)) {
const { tool, what, label } = ideToolLabel(name, input);
const path = input.path && !String(input.path).startsWith('/') ? String(input.path) : null;
return el(`div.claude-tool.ide${path ? '.link' : ''}`, { title: `IDE tool: ${tool}`, onclick: () => path && this.openFile(path, input.start_line || input.line ? { line: input.start_line || input.line } : {}) },
icon('claude'), el('b', {}, label), el('span', {}, what.slice(0, 300)));
}
const root = this.app.project?.root || '';
const rel = (p) => (p && root && p.startsWith(root + '/') ? p.slice(root.length + 1) : p);
const file = rel(input.file_path || input.notebook_path || input.path);
const what = {
Read: ['eye', 'Read', file], Write: ['file', 'Wrote', file], Edit: ['code', 'Edited', file], MultiEdit: ['code', 'Edited', file],
Bash: ['terminal', '$', input.command], Glob: ['find', 'Looked for', input.pattern], Grep: ['find', 'Searched', input.pattern],
WebFetch: ['globe', 'Fetched', input.url], WebSearch: ['globe', 'Searched the web', input.query], TodoWrite: ['check', 'Planned', `${(input.todos || []).length} step(s)`],
}[name] || ['settings', name, input.description || ''];
const opens = file && !file.startsWith('/') && ['Read', 'Write', 'Edit', 'MultiEdit'].includes(name);
return el(`div.claude-tool${opens ? '.link' : ''}`, { title: opens ? 'Open ' + file : '', onclick: () => opens && this.openFile(file) },
icon(what[0]), el('b', {}, what[1]), el('span', {}, String(what[2] || '').slice(0, 300)));
}
/** New content: follow it only while the reader is at the end; away from it, count it as unread (`counts`: a new item, not a text delta). */
scroll(counts = false) {
if (this.stick) {
this.setTop(this.log.scrollHeight);
requestAnimationFrame(() => { if (this.stick && !this.dragging) this.setTop(this.log.scrollHeight); });
} else {
this.unread = nextUnread(this.unread, false, counts);
this.keepAnchor();
}
this.showJump();
}
/** The reader asks for the end (the button) or sends a message: follow again. */
scrollToEnd() {
this.stick = true;
this.unread = 0;
this.setTop(this.log.scrollHeight);
requestAnimationFrame(() => { if (this.stick) this.setTop(this.log.scrollHeight); });
this.showJump();
}
/** Our own scroll: remembered, so that its scroll event is never taken for the reader's. */
setTop(v) {
this.log.scrollTop = v;
this.expectTop = this.log.scrollTop;
this.expectAt = Date.now();
this.anchor = null;
this.recordAnchor();
}
/** Follow or not, from where the log is now (the reader's scrolling). */
measure() {
this.stick = nearBottom(this.log.scrollTop, this.log.clientHeight, this.log.scrollHeight);
if (this.stick) this.unread = 0;
this.showJump();
}
showJump() {
const show = !this.stick && this.unread > 0 && this.log.clientHeight > 0;
this.jump.hidden = !show;
if (show) this.jump.textContent = '↓ ' + tr('Jump to latest') + ' · ' + tr('{n} new', { n: this.unread });
}
recordAnchor() {
if (this.stick || this.log.clientHeight <= 0) { this.anchor = null; return; }
const kids = [...this.log.children];
const base = this.log.getBoundingClientRect().top;
const i = pickAnchor(kids.map((k) => { const r = k.getBoundingClientRect(); return { top: r.top - base, bottom: r.bottom - base }; }));
this.anchor = i < 0 ? null : { node: kids[i], top: kids[i].getBoundingClientRect().top - base };
}
/** Something changed height (above the view too): put what the reader looks at back where it was on the screen. */
keepAnchor() {
const a = this.anchor;
if (!a || this.stick || !a.node.isConnected || a.node.parentNode !== this.log || this.log.clientHeight <= 0) { this.recordAnchor(); return; }
const d = anchorDelta(a.top, a.node.getBoundingClientRect().top - this.log.getBoundingClientRect().top);
if (d) {
this.log.scrollTop += d;
this.expectTop = this.log.scrollTop;
this.expectAt = Date.now();
}
this.recordAnchor();
}
}
function toText(content) {
if (typeof content === 'string') return content;
if (Array.isArray(content)) return content.map((c) => (typeof c === 'string' ? c : c.text || '')).join('\n');
return '';
}
/** Enough Markdown for Claude's answers: code blocks, `code`, **bold**, paragraphs and lists as lines. */
function markdown(text) {
const out = [];
const parts = text.split(/```(\w*)\n?([\s\S]*?)```/g);
for (let i = 0; i < parts.length; i += 3) {
for (const para of parts[i].split(/\n{2,}/)) {
if (!para.trim()) continue;
const p = el('p');
for (const [n, chunk] of para.split(/(`[^`]+`|\*\*[^*]+\*\*)/g).entries()) {
if (n % 2 === 0) p.append(chunk);
else if (chunk.startsWith('`')) p.append(el('code', {}, chunk.slice(1, -1)));
else p.append(el('b', {}, chunk.slice(2, -2)));
}
out.push(p);
}
if (parts[i + 2] !== undefined) out.push(el('pre.claude-code', {}, parts[i + 2].replace(/\n$/, '')));
}
return out;
}
/** One line for the status bar: what Claude is doing now. */
function toolText(name, input, root) {
const rel = (p) => String(p || '').replace(root + '/', '');
return ({
Read: () => `reading ${rel(input.file_path)}`, Write: () => `writing ${rel(input.file_path)}`, Edit: () => `editing ${rel(input.file_path)}`,
MultiEdit: () => `editing ${rel(input.file_path)}`, Bash: () => `$ ${String(input.description || input.command || '').slice(0, 80)}`,
Grep: () => `searching ${input.pattern}`, Glob: () => `looking for ${input.pattern}`, WebFetch: () => `fetching ${input.url}`,
WebSearch: () => `searching the web: ${input.query}`, TodoWrite: () => 'planning',
}[name] || (() => name.replace(/^mcp__[^_]+__/, '')))();
}
/**
* Claude's usage under the conversations: the open conversation's context window, and the account's 5-hour and weekly
* limits (what `claude` reports in its rate_limit_event), each with when it starts again. The limits are kept between
* starts of the IDE (they belong to the account, not to a conversation).
*/
export class UsageGauges {
constructor() {
this.bars = {};
const gauge = (key, label, title) => {
const fill = el('span.claude-gauge-fill');
const text = el('span.claude-gauge-text');
this.bars[key] = { node: el('div.claude-gauge', { title, dataset: { title } }, el('span.claude-gauge-label', {}, label), el('span.claude-gauge-bar', {}, fill), text), fill, text };
return this.bars[key].node;
};
this.node = el('div.claude-usage', {},
gauge('context', 'Context', 'The open conversation: how much of the model\'s context window it fills (Claude compacts it when it is full)'),
gauge('five_hour', '5 h', 'Your Claude plan: what is used of the 5-hour limit'),
gauge('seven_day', 'Week', 'Your Claude plan: what is used of the weekly limit'));
this.saved = prefs.get('claudeLimits', {}) || {};
this.context(null);
this.paint();
setInterval(() => this.paint(), 15000);
}
/** rate_limit_info of a rate_limit_event: {unifiedWindows: {five_hour: {utilization, resetsAt}, seven_day: ...}} */
limits(info) {
const windows = info?.unifiedWindows || (info?.rateLimitType ? { [info.rateLimitType]: info } : {});
for (const key of ['five_hour', 'seven_day']) {
const w = windows[key];
if (w && typeof w.utilization === 'number') this.saved[key] = { ratio: w.utilization, resets: w.resetsAt || null };
}
prefs.set('claudeLimits', this.saved);
this.paint();
}
context(ctx) {
const known = ctx?.used && ctx?.window;
this.set('context', known ? ctx.used / ctx.window : null,
known ? `${Math.round(100 * ctx.used / ctx.window)} % · ${tokens(ctx.used)} / ${tokens(ctx.window)}` : '—');
}
paint() {
for (const key of ['five_hour', 'seven_day']) {
const w = this.saved[key];
const over = w?.resets && w.resets * 1000 <= Date.now(); // that window started again since
if (!w) { this.set(key, null, '—'); continue; }
const ratio = over ? 0 : w.ratio;
this.set(key, ratio, `${Math.round(100 * ratio)} %` + (w.resets && !over ? ` · ↻ ${resetText(w.resets * 1000, key === 'seven_day')}` : ''));
this.bars[key].node.title = `${this.bars[key].node.dataset.title}: ${Math.round(100 * ratio)} % used` + (w.resets && !over ? `, starts again ${new Date(w.resets * 1000).toLocaleString()}` : '');
}
}
set(key, ratio, text) {
const b = this.bars[key];
const r = ratio === null ? 0 : Math.max(0, Math.min(1, ratio));
b.fill.style.width = `${(100 * r).toFixed(1)}%`;
b.node.dataset.level = ratio === null ? 'none' : r >= 0.9 ? 'high' : r >= 0.7 ? 'mid' : 'low';
b.text.textContent = text;
}
}
function tokens(n) {
return n >= 1e6 ? `${(n / 1e6).toFixed(n % 1e6 ? 1 : 0)}M` : n >= 1000 ? `${Math.round(n / 1000)}k` : String(n);
}
/** When a limit starts again: "14:30", or with the day for the weekly one ("Thu 09:00"). */
function resetText(ms, withDay) {
const d = new Date(ms);
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
return (withDay || d.toDateString() !== new Date().toDateString() ? d.toLocaleDateString([], { weekday: 'short' }) + ' ' : '') + time;
}