, which stays the single
* source of truth for load/save (the same contract as the model cards).
*/
_buildSelectSegment(selectId, segId) {
const select = document.getElementById(selectId);
const seg = document.getElementById(segId);
if (!select || !seg || seg.dataset.built === '1' || !select.options) return;
seg.innerHTML = '';
[...select.options].forEach(opt => {
const btn = document.createElement('button');
btn.type = 'button';
btn.setAttribute('role', 'radio');
btn.dataset.value = opt.value;
btn.textContent = opt.textContent;
btn.addEventListener('click', () => {
select.value = opt.value;
this._syncSelectSegment(selectId, segId);
});
seg.appendChild(btn);
});
seg.dataset.built = '1';
},
_syncSelectSegment(selectId, segId) {
const select = document.getElementById(selectId);
const seg = document.getElementById(segId);
if (!select || !seg) return;
seg.querySelectorAll('button').forEach(btn => {
const on = btn.dataset.value === (select.value || '');
btn.classList.toggle('selected', on);
btn.setAttribute('aria-checked', on ? 'true' : 'false');
});
},
/**
* Live filter across every section. Everything stays mounted (that is the
* point of the single-document layout), so a search only hides units that do
* not match, then collapses groups and sections left with nothing visible.
*/
_filterSettings(query) {
const doc = document.getElementById('appSettingsDoc');
if (!doc) return;
const q = (query || '').trim().toLowerCase();
const UNIT = '.set-row, .set-chip, .set-modelgrid, .set-minigrid, .event-type-grid, #appSettingsShortcutsList';
const units = [...doc.querySelectorAll(UNIT)];
let anyVisible = false;
units.forEach(unit => {
if (!q) {
unit.classList.remove('set-hit-hidden');
return;
}
const hay = `${unit.dataset?.search || ''} ${unit.textContent || ''}`.toLowerCase();
const hit = hay.includes(q);
unit.classList.toggle('set-hit-hidden', !hit);
if (hit) anyVisible = true;
});
// A chip wrapper is only empty when every chip inside it is hidden.
doc.querySelectorAll('.set-chips').forEach(wrap => {
const hasVisible = [...wrap.querySelectorAll('.set-chip')].some(c => !c.classList.contains('set-hit-hidden'));
wrap.classList.toggle('set-hit-hidden', !!q && !hasVisible);
});
doc.querySelectorAll('.set-group').forEach(group => {
const hasVisible = [...group.querySelectorAll(UNIT)].some(u => !u.classList.contains('set-hit-hidden'));
group.classList.toggle('set-hit-hidden', !!q && !hasVisible);
// An Advanced group that matches must open, or the hit stays invisible.
if (q && hasVisible) group.classList.add('open');
});
doc.querySelectorAll('.set-section').forEach(section => {
const hasVisible = [...section.querySelectorAll('.set-group')].some(g => !g.classList.contains('set-hit-hidden'));
section.classList.toggle('set-hit-hidden', !!q && !hasVisible);
});
// The live preview sits outside any group, so it survives the sweep above;
// a search is asking for one row, not for the scale model around it.
doc.querySelectorAll('.set-preview').forEach(pv => pv.classList.toggle('set-hit-hidden', !!q));
const empty = document.getElementById('appSettingsSearchEmpty');
if (empty) empty.hidden = !q || anyVisible;
if (!q) doc.querySelectorAll('.set-group-advanced').forEach(g => g.classList.remove('open'));
},
closeAppSettings() {
this._toggleSettingsJump(false);
document.getElementById('appSettingsModal').classList.remove('active');
// Deactivate focus trap and restore focus
if (this.activeFocusTrap) {
this.activeFocusTrap.deactivate();
this.activeFocusTrap = null;
}
},
// ───────────────────────────────────────────────────────────────
// Self-Update (App Settings → Updates). Backend: src/web/self-update.ts.
// ───────────────────────────────────────────────────────────────
/** Friendly label for an in-flight update phase. */
_updatePhaseText(phase) {
return {
queued: 'Queued…',
preparing: 'Preparing…',
stashing: 'Stashing local changes…',
fetching: 'Fetching release…',
checkout: 'Checking out release…',
installing: 'Installing dependencies…',
building: 'Building…',
restarting: 'Restarting Codeman…',
}[phase] || phase;
},
/** Populate the version row and clear transient UI when the modal opens. */
_initUpdatesSection() {
const verEl = this.$('updateCurrentVersion');
if (verEl) verEl.textContent = (this.$('versionDisplay')?.textContent || '').trim() || '—';
for (const id of ['updateResult', 'updateActionRow', 'updateNotes', 'updateProgress']) {
const el = this.$(id);
if (el) el.style.display = 'none';
}
this._updateCheck = null;
},
/**
* Settings → Terminal & Input → Key tester: prints what the browser reports for each key event.
* Read-only and local; it never reaches a session. keypress is shown on purpose: that event is
* why a Shift-only Enter used to submit (xterm drops Ctrl/Alt keypresses, not Shift ones).
*/
keyTesterEvent(ev) {
const log = document.getElementById('keyTesterLog');
if (!log) return;
// Never preventDefault on keydown: that suppresses the keypress this panel exists to show.
// The field is readonly, so nothing is typed into it either way.
const mods = ['ctrlKey', 'shiftKey', 'altKey', 'metaKey'].filter((m) => ev[m]).map((m) => m.replace('Key', ''));
const line =
`${ev.type.padEnd(8)} key=${JSON.stringify(ev.key)} code=${ev.code || '-'} ` +
`mods=${mods.join('+') || 'none'}` +
(ev.type === 'keypress' ? ` charCode=${ev.charCode}` : '') +
(ev.repeat ? ' (repeat)' : '');
const lines = (log.textContent ? log.textContent.split('\n') : []).concat(line);
log.textContent = lines.slice(-14).join('\n');
log.style.display = 'block';
},
/**
* MCP sync is opt-in (`mcpSyncEnabled`): with the flag off the action row is hidden rather than
* shown disabled, because both endpoints would only answer 403. Called on open and from the
* checkbox's own onchange (assigning .checked fires no change event).
*/
applyMcpSyncVisibility() {
const on = document.getElementById('appSettingsMcpSync')?.checked ?? false;
const row = document.getElementById('mcpSyncActionRow');
if (row) row.style.display = on ? '' : 'none';
const out = this.$('mcpSyncResult');
if (!on && out) { out.style.display = 'none'; out.innerHTML = ''; }
this._applyMcpSyncAdminGate();
},
/**
* Both /api/mcp-sync verbs are admin-only in multi-user mode (they write files in the server
* user's home), so a non-admin gets no MCP group at all, switch included, the same way
* _applyCliManagementAdminGate hides the CLI list. Also wired to `codeman:me`, because
* `window.__codemanUser`'s real role can resolve after settings were opened once.
*/
_applyMcpSyncAdminGate() {
const group = document.getElementById('mcpSyncGroup');
if (!group) return;
const me = window.__codemanUser || {};
group.style.display = me.multiUser && me.role !== 'admin' ? 'none' : '';
},
/**
* GET /api/doctor is admin-only in multi-user mode (it names install paths on the host), so a
* non-admin gets no Diagnostics group instead of a button that can only answer 403. Also
* wired to `codeman:me` for the same late-resolving role as the groups above.
*/
_applyDoctorAdminGate() {
const me = window.__codemanUser || {};
for (const id of ['doctorGroup', 'configBackupGroup']) {
const group = document.getElementById(id);
if (group) group.style.display = me.multiUser && me.role !== 'admin' ? 'none' : '';
}
},
// ── Config backups ──────────────────────────────────────────────────────────
// Server-side files, so these read the SAVED settings: a folder or retention edit applies after Save.
/**
* The retention keys a Save sends: a value only once it was saved before or edited here. After a reset
* the form merely DISPLAYS what the passes use (the retention the backups recorded), and writing that back
* would replace it with whatever a different folder or an older default says.
*/
_configBackupRetentionPayload(prev) {
const count = document.getElementById('appSettingsConfigBackupKeepCount');
const days = document.getElementById('appSettingsConfigBackupKeepDays');
const out = {};
if (prev.configBackupKeepCount !== undefined || count.dataset.touched) {
out.configBackupKeepCount = Math.min(500, Math.max(2, parseInt(count.value, 10) || 20));
}
if (prev.configBackupKeepDays !== undefined || days.dataset.touched) {
const n = parseInt(days.value, 10);
out.configBackupKeepDays = Math.min(3650, Math.max(0, Number.isNaN(n) ? 30 : n));
}
return out;
},
/** Fill the backup list, and show the default folder as the input's placeholder. */
async loadConfigBackups() {
const out = this.$('configBackupList');
if (!out) return;
const res = await this._api('/api/config-backups');
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
out.textContent = body?.error || 'Backups are not available here (admin only in multi-user mode).';
return;
}
const data = body.data;
const dirInput = this.$('appSettingsConfigBackupDir') || document.getElementById('appSettingsConfigBackupDir');
if (dirInput && data.defaultDir) dirInput.placeholder = `default: ${data.defaultDir}`;
// A reset settings.json has none of the four keys, but the passes keep the retention the newest backup
// recorded: show that, or a Save would write 20 / 30 over it.
const saved = this.loadAppSettingsFromStorage();
const countInput = document.getElementById('appSettingsConfigBackupKeepCount');
const daysInput = document.getElementById('appSettingsConfigBackupKeepDays');
if (countInput && saved.configBackupKeepCount === undefined && data.settings) countInput.value = data.settings.keepCount;
if (daysInput && saved.configBackupKeepDays === undefined && data.settings) daysInput.value = data.settings.keepDays;
if (!data.backups.length) {
out.innerHTML = `No backups yet in ${escapeHtml(data.dir)}.`;
return;
}
const kb = (n) => (n < 1024 ? `${n} B` : `${(n / 1024).toFixed(1)} KB`);
this._configBackups = data.backups;
const rows = data.backups.map((b, i) => {
const when = new Date(b.createdAt).toLocaleString();
const names = b.files.map((f) => escapeHtml(f.name)).join(', ');
const id = escapeHtml(b.id);
// The list is newest first, so the next row is the backup this one followed.
const prev = data.backups[i + 1];
const vsPrev = prev ? `Changes in this backup ` : '';
return `${escapeHtml(when)} (${escapeHtml(b.reason)}, ${kb(b.bytes)})
Restore
Compare with current
${vsPrev}
${names}
`;
});
const options = (sel) => [`Current config `]
.concat(data.backups.map((b) => `${escapeHtml(new Date(b.createdAt).toLocaleString())} (${escapeHtml(b.reason)}) `))
.join('');
const picker = data.backups.length
? `Compare ${options(data.backups[0].id)} with ${options('current')}
Show changes
`
: '';
out.innerHTML = `${data.backups.length} backup${data.backups.length === 1 ? '' : 's'} in ${escapeHtml(data.dir)}
${picker}
`;
},
/** What differs between two states of the config files: a backup id or `current` (the running config). */
async showConfigDiff(from, to) {
const out = this.$('configBackupDiff');
if (!out) return;
out.textContent = 'Comparing…';
const res = await this._api(`/api/config-backups/diff?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`);
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
out.textContent = body?.error || 'Could not compare these';
return;
}
const label = (id) => {
if (id === 'current') return 'the current config';
const b = (this._configBackups || []).find((x) => x.id === id);
return b ? new Date(b.createdAt).toLocaleString() : id;
};
const d = body.data;
const verb = { added: 'added', removed: 'removed', changed: 'changed' };
const files = d.files.filter((f) => f.status !== 'unchanged').map((f) => {
let detail;
if (f.detail === 'bytes') {
detail = 'Differs (not a key/value file, so no detail).
';
} else {
const rows = f.changes.map((c) => {
const val = (v) => `${escapeHtml(v ?? '')}`;
const text = c.redacted ? `${verb[c.kind]} (value hidden: credential) `
: c.kind === 'added' ? `added ${val(c.after)}`
: c.kind === 'removed' ? `removed (was ${val(c.before)})`
: `${val(c.before)} → ${val(c.after)}`;
return `${escapeHtml(c.path)}: ${text} `;
});
const more = f.truncated ? 'More changes not shown. ' : '';
detail = f.changes.length ? `` : '';
}
const whole = f.status === 'added' ? ' (new file)' : f.status === 'removed' ? ' (file gone)' : '';
return `${escapeHtml(f.name)} ${whole}${detail}
`;
});
const same = d.files.filter((f) => f.status === 'unchanged').map((f) => escapeHtml(f.name));
out.innerHTML = `${escapeHtml(label(d.from))} → ${escapeHtml(label(d.to))} : ${
d.changed ? `${d.changed} file${d.changed === 1 ? '' : 's'} differ` : 'no differences'}
${files.join('')}${
same.length ? `Unchanged: ${same.join(', ')}
` : ''}`;
},
async backupConfigNow() {
const btn = this.$('configBackupNowBtn');
if (btn) btn.disabled = true;
try {
const res = await this._apiPost('/api/config-backups', {});
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
this.showToast(body?.error || 'Backup failed', 'error');
} else if (body.data.status === 'empty') {
this.showToast('Nothing to back up yet', 'warning');
} else {
this.showToast(`Backed up ${body.data.files} file${body.data.files === 1 ? '' : 's'}`, 'success');
}
} finally {
if (btn) btn.disabled = false;
this.loadConfigBackups();
}
},
async restoreConfigBackup(id) {
const names = ((this._configBackups || []).find((b) => b.id === id)?.files || []).map((f) => f.name);
const secret = names.filter((n) => ['.env', 'users.json', 'push-keys.json', 'custom-model-hosts.json', 'webhook.json'].includes(n));
const list = names.length ? `\n\nFiles replaced: ${names.join(', ')}` : '';
const warn = secret.length ? `\n\nThis rolls back credentials and accounts (${secret.join(', ')}): passwords, disabled accounts and keys return to how they were then.` : '';
if (!confirm(`Restore this backup? Its files replace the current ones (a copy of the current files is made first). Some files only take effect after a restart.${list}${warn}`)) return;
const res = await this._apiPost(`/api/config-backups/${encodeURIComponent(id)}/restore`, {});
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
const ok = res && res.ok && body && body.success !== false;
const d = body?.data;
// A restore that failed partway still answers with what it wrote (`restored`, `failed`, `safetySnapshot`):
// those files are the backup's now and need the same refill as a full restore.
if (!ok && !Array.isArray(d?.restored)) {
this.showToast(body?.error || 'Restore failed', 'error');
return;
}
const restart = d.restartRequired?.length ? ` Restart Codeman to apply: ${d.restartRequired.join(', ')}.` : '';
// The form still holds the pre-restore values, and Save would PUT them over the restored file.
if (d.restored.includes('settings.json')) {
await this.loadAppSettingsFromServer();
this.openAppSettings();
}
if (ok) {
this.showToast(`Restored ${d.restored.length} file${d.restored.length === 1 ? '' : 's'}.${restart}`, 'success');
} else {
this.showToast(`${body.error || 'Restore failed partway'}.${restart}`, 'error');
}
this.loadConfigBackups();
},
/** Preview (apply=false) or run (apply=true) the MCP server sync across enabled CLIs. */
async mcpSync(apply) {
const out = this.$('mcpSyncResult');
const show = (html, hint = '') => {
if (out) { out.style.display = 'block'; out.innerHTML = html; out.dataset.hint = hint; }
};
// Switched on in this modal but not saved yet: the routes would only answer "disabled".
if (!this._mcpSyncSavedOn) {
show('Apply or Save settings to turn MCP sync on first, then preview or sync.', 'save-first');
return;
}
if (apply && !confirm('Add missing MCP servers to every installed, enabled CLI\'s config file (and GitHub Copilot CLI\'s, when it is installed)? Env values and headers on those servers are copied too.')) return;
show('Working…');
const res = apply ? await this._apiPost('/api/mcp-sync', {}) : await this._api('/api/mcp-sync');
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
show(escapeHtml(body?.error || 'MCP sync failed.'));
return;
}
const data = body.data;
const rows = data.targets.map((t) => {
if (t.status === 'absent') return `${escapeHtml(t.label)} : not installed, skipped `;
if (t.status === 'skipped') return `${escapeHtml(t.label)} : not touched (${escapeHtml(t.error || 'config location unknown')}) `;
if (t.status === 'unreadable') return `${escapeHtml(t.label)} : not touched, file can't be read safely (${escapeHtml(t.error || 'unreadable')}) `;
if (t.status === 'failed') return `${escapeHtml(t.label)} : failed (${escapeHtml(t.error || 'error')}); the file may be unchanged `;
const verb = data.applied ? 'added' : 'would add';
const parts = [t.added.length ? `${verb} ${t.added.map(escapeHtml).join(', ')}` : 'up to date'];
if (t.skipped.length) parts.push(`can't express ${t.skipped.map(escapeHtml).join(', ')}`);
const count = `${t.servers.length} server${t.servers.length === 1 ? '' : 's'}`;
return `${escapeHtml(t.label)} (${count}): ${parts.join('; ')} `;
});
const conflicts = data.conflicts.length
? `Defined differently across CLIs (each existing definition is kept; the first CLI's is copied where the name is missing): ${data.conflicts.map(escapeHtml).join(', ')}
`
: '';
const disabled = data.disabled?.length
? `Switched off in their own CLI, so not copied: ${data.disabled.map(escapeHtml).join(', ')}
`
: '';
const unsupported = data.unsupported?.length
? `No MCP config support for: ${data.unsupported.map(escapeHtml).join(', ')}
`
: '';
show(`${conflicts}${disabled}${unsupported}`);
},
/**
* Webhook notifications (Settings → Notifications). Server-side config behind /api/webhook, not a
* settings-payload field: the URL is a secret, so it never round-trips through settings.json or
* this page. The URL box is write-only; the status line shows scheme + host only.
*
* Three ways to save, one PUT: the group's own Save, Send test (saves pending edits first, so it
* never tests the old URL while the box shows a new one), and the modal's main Save, which calls
* saveWebhook() beside the settings PUT the same way it saves the model config
* (saveModelConfigFromSettings). `_webhookLoaded` is what loadWebhook() put on screen, so
* `_webhookPending()` can tell an edited group from an untouched one.
*/
_webhookSay(text, bad = false) {
const out = document.getElementById('webhookResult');
if (!out) return;
out.textContent = text;
out.style.display = text ? 'block' : 'none';
out.style.color = bad ? 'var(--danger, #e5534b)' : '';
},
async loadWebhook() {
const group = document.getElementById('webhookGroup');
if (!group) return;
const res = await this._api('/api/webhook');
if (!res || !res.ok) {
this._webhookLoaded = null;
group.style.display = 'none'; // not an admin in multi-user mode, or the server predates the route
return;
}
let body = null;
try { body = await res.json(); } catch { /* leave hidden */ }
if (!body || body.success === false) { this._webhookLoaded = null; group.style.display = 'none'; return; }
const d = body.data;
group.style.display = '';
document.getElementById('webhookEnabled').checked = d.enabled === true;
document.getElementById('webhookKind').value = d.kind;
document.getElementById('webhookScope').value = d.scope;
const url = document.getElementById('webhookUrl');
url.value = '';
url.placeholder = d.hasUrl ? 'Saved. Paste a new URL to replace it' : 'https://ntfy.sh/your-topic';
document.getElementById('webhookUrlHint').textContent = d.hasUrl ? `Saved: ${d.urlMasked}` : 'Nothing saved yet.';
const clearBtn = document.getElementById('webhookClearBtn');
if (clearBtn) clearBtn.style.display = d.hasUrl ? '' : 'none';
// Read back from the controls, so a value the does not offer compares as what is shown.
this._webhookLoaded = {
enabled: document.getElementById('webhookEnabled').checked,
kind: document.getElementById('webhookKind').value,
scope: document.getElementById('webhookScope').value,
};
if (d.lastResult) {
const when = new Date(d.lastResult.at).toLocaleString();
this._webhookSay(
d.lastResult.ok ? `Last delivery succeeded (${when}).` : `Last delivery failed (${when}): ${d.lastResult.error}`,
!d.lastResult.ok
);
} else {
this._webhookSay('');
}
},
/** True when the visible webhook group differs from what loadWebhook() last showed. */
_webhookPending() {
const group = document.getElementById('webhookGroup');
const loaded = this._webhookLoaded;
if (!group || group.style.display === 'none' || !loaded) return false;
return (
document.getElementById('webhookUrl').value.trim() !== '' ||
document.getElementById('webhookEnabled').checked !== loaded.enabled ||
document.getElementById('webhookKind').value !== loaded.kind ||
document.getElementById('webhookScope').value !== loaded.scope
);
},
/** PUT the group's state. Resolves to '' on success, else the error (also shown in the group). */
async saveWebhook() {
const payload = {
enabled: document.getElementById('webhookEnabled').checked,
kind: document.getElementById('webhookKind').value,
scope: document.getElementById('webhookScope').value,
};
const url = document.getElementById('webhookUrl').value.trim();
if (url) payload.url = url; // blank = keep the saved one (Remove URL is the way to clear it)
const res = await this._api('/api/webhook', { method: 'PUT', body: payload });
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
const error = body?.error || 'Could not save the webhook.';
this._webhookSay(error, true);
return error;
}
await this.loadWebhook();
this._webhookSay('Saved.');
return '';
},
/** Delete the saved URL from the server (the API clears on `url: ""`), which also turns the channel off. */
async clearWebhook() {
if (!confirm('Remove the saved webhook URL from the server? Webhook alerts stop until you save a new one.')) return;
const res = await this._api('/api/webhook', { method: 'PUT', body: { url: '', enabled: false } });
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
this._webhookSay(body?.error || 'Could not remove the webhook URL.', true);
return;
}
await this.loadWebhook();
this._webhookSay('Webhook URL removed.');
},
async testWebhook() {
const btn = document.getElementById('webhookTestBtn');
if (btn) btn.disabled = true;
try {
if (this._webhookPending() && (await this.saveWebhook())) return; // the save's error is already shown
this._webhookSay('Sending…');
const res = await this._apiPost('/api/webhook/test', {});
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
this._webhookSay(body?.error || 'Could not send the test.', true);
return;
}
const r = body.data;
this._webhookSay(r.ok ? 'Test sent. Check your phone or channel.' : `Delivery failed: ${r.error}`, !r.ok);
} finally {
if (btn) btn.disabled = false;
}
},
/**
* Discord bridge (Settings → Notifications). Server-side config behind /api/discord, not a
* settings-payload field: the bot token is a secret, so it never round-trips through settings.json
* or this page. The token box is write-only. Unlike the webhook group it has its own Save button
* only (the modal's main Save does not touch it), so a half-typed token is never sent by accident.
*/
_discordSay(text, bad = false) {
const out = document.getElementById('discordResult');
if (!out) return;
out.textContent = text;
out.style.display = text ? 'block' : 'none';
out.style.color = bad ? 'var(--danger, #e5534b)' : '';
},
async loadDiscord() {
const group = document.getElementById('discordGroup');
if (!group) return;
const res = await this._api('/api/discord');
let body = null;
try { body = res && res.ok ? await res.json() : null; } catch { /* leave hidden */ }
if (!body || body.success === false) { group.style.display = 'none'; return; } // not an admin, or an older server
const d = body.data;
group.style.display = '';
document.getElementById('discordEnabled').checked = d.enabled === true;
const token = document.getElementById('discordToken');
token.value = '';
token.placeholder = d.hasToken ? 'Saved. Paste a new token to replace it' : 'Bot token from the Developer Portal';
document.getElementById('discordTokenHint').textContent = d.hasToken ? `Saved: ${d.tokenMasked}` : 'Nothing saved yet.';
document.getElementById('discordGuildId').value = d.guildId || '';
document.getElementById('discordParentChannelId').value = d.parentChannelId || '';
document.getElementById('discordAllowedUserIds').value = (d.allowedUserIds || []).join(', ');
document.getElementById('discordThreadCreation').value = d.threadCreation;
document.getElementById('discordOnSessionDelete').value = d.onSessionDelete;
document.getElementById('discordStaleThreads').value = d.staleThreads || 'keep';
document.getElementById('discordPingMode').value = d.pingMode;
document.getElementById('discordScope').value = d.scope;
document.getElementById('discordStartupHint').checked = d.startupHint !== false;
const clearBtn = document.getElementById('discordClearBtn');
if (clearBtn) clearBtn.style.display = d.hasToken ? '' : 'none';
const gw = { off: 'Not connected (disabled).', connecting: 'Connecting to Discord…', connected: 'Connected: replies are being read.', error: `Not connected: ${d.gatewayError || 'error'}` };
let line = gw[d.gateway] || '';
if (d.lastResult) {
const when = new Date(d.lastResult.at).toLocaleString();
line += d.lastResult.ok ? ` Last post succeeded (${when}).` : ` Last post failed (${when}): ${d.lastResult.error}`;
}
this._discordSay(line.trim(), d.gateway === 'error' || (d.lastResult && !d.lastResult.ok));
},
/** PUT the group's state. Resolves to '' on success, else the error (also shown in the group). */
async saveDiscord() {
const ids = document.getElementById('discordAllowedUserIds').value.split(/[\s,]+/).filter(Boolean);
const payload = {
enabled: document.getElementById('discordEnabled').checked,
guildId: document.getElementById('discordGuildId').value.trim(),
parentChannelId: document.getElementById('discordParentChannelId').value.trim(),
allowedUserIds: ids,
threadCreation: document.getElementById('discordThreadCreation').value,
onSessionDelete: document.getElementById('discordOnSessionDelete').value,
staleThreads: document.getElementById('discordStaleThreads').value,
pingMode: document.getElementById('discordPingMode').value,
scope: document.getElementById('discordScope').value,
startupHint: document.getElementById('discordStartupHint').checked,
};
const token = document.getElementById('discordToken').value.trim();
if (token) payload.token = token; // blank = keep the saved one (Remove token is the way to clear it)
const res = await this._api('/api/discord', { method: 'PUT', body: payload });
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
const error = body?.error || 'Could not save the Discord settings.';
this._discordSay(error, true);
return error;
}
await this.loadDiscord();
return '';
},
async clearDiscord() {
if (!confirm('Remove the saved bot token from the server? The Discord bridge stops until you save a new one.')) return;
const res = await this._api('/api/discord', { method: 'PUT', body: { token: '', enabled: false } });
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
this._discordSay(body?.error || 'Could not remove the token.', true);
return;
}
await this.loadDiscord();
},
async testDiscord() {
const btn = document.getElementById('discordTestBtn');
if (btn) btn.disabled = true;
try {
if (await this.saveDiscord()) return; // saves first, so it never tests the old values; the error is shown
this._discordSay('Sending…');
const res = await this._apiPost('/api/discord/test', {});
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
this._discordSay(body?.error || 'Could not send the test.', true);
return;
}
const r = body.data;
this._discordSay(r.ok ? 'Test sent. Check the channel.' : `Delivery failed: ${r.error}`, !r.ok);
} finally {
if (btn) btn.disabled = false;
}
},
/**
* Settings → System → Diagnostics: run `codeman doctor` on the server (GET /api/doctor) and list
* each tool. Built with DOM nodes and textContent: paths and versions come from the host.
*/
async runDoctor() {
const out = document.getElementById('doctorResult');
const btn = document.getElementById('doctorRunBtn');
if (!out) return;
const say = (text) => {
out.replaceChildren(document.createTextNode(text));
out.style.display = 'block';
};
if (btn) btn.disabled = true;
say('Checking…');
try {
const res = await this._api('/api/doctor');
let body = null;
try { body = res ? await res.json() : null; } catch { /* fall through */ }
if (!res || !res.ok || !body || body.success === false) {
say(body?.error || 'The check failed.');
return;
}
const { tools, summary, platform } = body.data;
const glyph = { ok: '✓', missing: '✗', outdated: '!', error: '!', skipped: '–' };
const list = document.createElement('ul');
list.style.margin = '0';
list.style.paddingLeft = '1.2em';
for (const t of tools) {
const li = document.createElement('li');
const strong = document.createElement('b');
// As the terminal doctor marks it: a missing OPTIONAL tool is ○, only a required one ✗.
const mark = t.status === 'missing' && !t.required ? '○' : glyph[t.status] || '?';
strong.textContent = `${mark} ${t.label}`;
li.append(strong);
const bits = [t.status];
if (t.version) bits.push(t.version);
if (t.status !== 'ok' && t.status !== 'skipped') bits.push(t.required ? 'required' : 'optional');
if (t.reason) bits.push(t.reason);
li.append(document.createTextNode(` ${bits.join(' · ')}`));
if (t.path) {
const p = document.createElement('div');
p.className = 'mono';
p.textContent = t.path;
li.append(p);
}
if (t.status === 'missing' && t.installHint) {
const h = document.createElement('div');
h.textContent = `Install: ${t.installHint}`;
li.append(h);
}
list.append(li);
}
const head = document.createElement('p');
head.textContent =
`${summary.ok} ok · ${summary.requiredMissing} required missing · ${summary.optionalMissing} optional missing` +
` (${platform.environment})`;
out.replaceChildren(head, list);
out.style.display = 'block';
} finally {
if (btn) btn.disabled = false;
}
},
_setUpdateResult(html) {
const el = this.$('updateResult');
if (el) { el.style.display = 'block'; el.innerHTML = html; }
},
_setUpdateProgress(html) {
const el = this.$('updateProgress');
if (el) { el.style.display = 'block'; el.innerHTML = html; }
},
/** Manual "Check for updates" — asks the server to query GitHub. */
async checkForUpdate() {
const btn = this.$('updateCheckBtn');
if (btn) { btn.disabled = true; btn.textContent = 'Checking…'; }
const data = await this._apiJson('/api/system/update/check');
if (btn) { btn.disabled = false; btn.textContent = 'Check now'; }
const actionRow = this.$('updateActionRow');
const notes = this.$('updateNotes');
if (actionRow) actionRow.style.display = 'none';
if (notes) notes.style.display = 'none';
if (!data) {
this._setUpdateResult('Could not check for updates. Try again later.');
return;
}
this._updateCheck = data;
const verEl = this.$('updateCurrentVersion');
if (verEl && data.currentVersion) verEl.textContent = `v${data.currentVersion}`;
// `docker-compose` self-updates in place like `git` does — the container
// restarts itself. Anything else cannot.
if (data.installKind && data.installKind !== 'git' && data.installKind !== 'docker-compose') {
// `archive` = installed by install.sh on a machine with no working git: the
// installer replaces it with a fresh build, so point there, not at npm.
const hint =
data.supervisor === 'docker-compose'
? 'Update from the Docker host with docker/Start-Codeman.sh.'
: data.installKind === 'archive'
? 'It was installed without git. Re-run the installer to update: curl -fsSL https://getcodeman.com/install | bash'
: 'Update with npm i -g aicodeman@latest.';
this._setUpdateResult(`This install can't update itself (${escapeHtml(data.installKind)}). ${hint}`);
return;
}
if (data.selfUpdateEnabled === false) {
this._setUpdateResult('In-app updates are disabled on this server (CODEMAN_DISABLE_SELF_UPDATE=1).');
return;
}
if (data.error && !data.updateAvailable) {
this._setUpdateResult(escapeHtml(data.error));
return;
}
// A container release that changes the ENVIRONMENT (Dockerfile, compose file
// or new .env keys) cannot be applied by the container restarting itself, so
// the update button is never offered — the host command is, instead. The
// server re-checks this on POST, so hiding the button is UX, not the gate.
const blockers = data.environment?.blockers || [];
if (data.updateAvailable && blockers.length > 0) {
const reasons = blockers
.map((b) => {
const details = b.details?.length ? `${escapeHtml(b.details.join(' '))}` : '';
return `${escapeHtml(b.message)}${details} `;
})
.join('');
this._setUpdateResult(
`v${escapeHtml(data.latestVersion || '')} needs a rebuild on the Docker host` +
` (current v${escapeHtml(data.currentVersion || '')}):` +
`Run ${escapeHtml(data.environment?.hostCommand || 'docker/Start-Codeman.sh')} there to apply it.`
);
if (notes && data.notes) {
notes.style.display = 'block';
notes.textContent = data.notes;
}
return;
}
if (data.updateAvailable && data.latestVersion) {
this._setUpdateResult(
`Update available: v${escapeHtml(data.latestVersion)} (current v${escapeHtml(data.currentVersion || '')})`
);
const label = this.$('updateActionLabel');
if (label) label.textContent = `Update to v${data.latestVersion}`;
if (actionRow) actionRow.style.display = 'flex';
const nowBtn = this.$('updateNowBtn');
if (nowBtn) { nowBtn.disabled = false; nowBtn.textContent = 'Update now'; }
if (notes && data.notes) {
notes.style.display = 'block';
notes.textContent = data.notes;
}
} else {
this._setUpdateResult(`You're up to date (v${escapeHtml(data.currentVersion || '')}).`);
}
},
/** Start the update, then poll status across the service restart. */
async startSelfUpdate() {
const target = this._updateCheck?.latestVersion ? `v${this._updateCheck.latestVersion}` : 'the latest release';
if (!confirm(`Update Codeman to ${target}? The server will restart and this page will reload.`)) return;
const btn = this.$('updateNowBtn');
if (btn) { btn.disabled = true; btn.textContent = 'Starting…'; }
const res = await this._apiPost('/api/system/update', {});
if (!res || !res.ok) {
let msg = 'Failed to start the update.';
try { const j = await res.json(); if (typeof j?.error === 'string' && j.error) msg = j.error; } catch {}
this._setUpdateProgress(`${escapeHtml(msg)} `);
if (btn) { btn.disabled = false; btn.textContent = 'Update now'; }
return;
}
const actionRow = this.$('updateActionRow');
if (actionRow) actionRow.style.display = 'none';
const notes = this.$('updateNotes');
if (notes) notes.style.display = 'none';
this._setUpdateProgress('Starting update…');
this._pollUpdateStatus();
},
_stopUpdatePolling() {
if (this._updatePollTimer) { clearInterval(this._updatePollTimer); this._updatePollTimer = null; }
},
/**
* Poll the status file every 1.5s. Survives the connection drop while the
* server restarts (fetch throws → "restarting"), then reads the reconciled
* terminal state from the freshly-booted server.
*/
_pollUpdateStatus() {
this._stopUpdatePolling();
const terminal = new Set(['completed', 'completed-needs-manual-restart', 'failed', 'idle']);
const poll = async () => {
let data = null;
try {
const res = await fetch('/api/system/update/status');
if (res.ok) {
const env = await res.json();
data = env && env.success === true ? env.data : env;
}
} catch { /* server restarting — keep polling */ }
if (!data) {
this._setUpdateProgress('↻ Restarting Codeman…');
return;
}
if (!terminal.has(data.phase)) {
// Prefer the live status message — the updater's heartbeat enriches it with
// the latest npm/build output line so a slow step doesn't look frozen — and
// fall back to the static phase label. Append total elapsed so the counter
// keeps ticking between heartbeats: a clear "still working" signal.
const label = (data.message && data.message.trim()) ? data.message.trim() : this._updatePhaseText(data.phase);
let elapsed = '';
if (data.startedAt) {
const secs = Math.max(0, Math.round((Date.now() - data.startedAt) / 1000));
elapsed = ` · ${secs}s `;
}
this._setUpdateProgress(` ${escapeHtml(label)}${elapsed}`);
return;
}
this._stopUpdatePolling();
if (data.phase === 'completed') {
let html = `✓ Updated to v${escapeHtml(data.toVersion || '')}. Reloading… `;
if (data.stashRef) {
html += `Local changes stashed as ${escapeHtml(data.stashRef)} — run git stash pop to restore. `;
}
this._setUpdateProgress(html);
setTimeout(() => location.reload(), 2500);
} else if (data.phase === 'completed-needs-manual-restart') {
this._setUpdateProgress(
`Update staged. Restart Codeman to apply:${escapeHtml(data.manualRestartCommand || 'restart codeman web')}`
);
} else if (data.phase === 'failed') {
let html = `✗ ${escapeHtml(data.message || 'Update failed')}. `;
if (data.error) html += `${escapeHtml(data.error)} `;
html += `The previous version is still running. `;
if (data.stashRef) {
html += `Local changes stashed as ${escapeHtml(data.stashRef)}. `;
}
this._setUpdateProgress(html);
const nowBtn = this.$('updateNowBtn');
const actionRow = this.$('updateActionRow');
if (nowBtn) { nowBtn.disabled = false; nowBtn.textContent = 'Try again'; }
if (actionRow) actionRow.style.display = 'flex';
}
};
poll();
this._updatePollTimer = setInterval(poll, 1500);
},
/**
* Is `tool` installed on the server? Reads `window.__codemanCliAvailable`,
* injected by renderIndexHtml (see the comment there for why this is injected
* rather than fetched per surface).
*
* Unknown reads as AVAILABLE. A missing flag means the page was rendered by a
* build that predates the injection, or by a solo popup: hiding every run
* button on a doubt would leave nothing to click, and the pre-existing failure
* mode for a genuinely missing CLI is just an error toast.
*/
isCliAvailable(tool) {
const flags = window.__codemanCliAvailable;
if (!flags || typeof flags !== 'object') return true;
return flags[tool] !== false;
},
/**
* Render the registry's enabled, available CLIs as welcome-screen actions:
* ONE primary button, then every other entry as a slim chip in a row under it.
*
* The primary is the first AGENT in catalog order (the first entry whose kind
* is not 'shell'), so on a stock install it is Claude Code, and with Claude
* disabled or missing it is simply the next agent; only a catalog with no agent
* at all promotes the shell. Chosen from the catalog's order and kind, never by
* an id: the registry decides what comes first. Everything else keeps catalog
* order inside the chip row, so the DOM order across both is the catalog's.
*
* The CLI id travels only as DATA: `data-mode` for the click, and the
* `run-mode-dot ` logo slot every Run menu shares (styles.css draws the
* brand mark, or a plain dot for an id it has no logo for). No per-id class on
* the buttons themselves, so no rule anywhere can give one CLI its own look.
*/
renderWelcomeCliActions() {
const container = document.getElementById('welcomeCliActions');
if (!container) return;
const catalog = Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : [];
const offered = catalog.filter((cli) => cli.enabled && this.isCliAvailable(cli.id));
const primary = offered.find((cli) => cli.kind !== 'shell') || offered[0];
// "Run ", the strings i18n.js translates ("Run Claude Code", "Run Shell");
// a custom CLI's label simply has no dictionary entry, so it renders as typed.
const runLabel = (cli) => `Run ${cli.kind === 'shell' ? 'Shell' : cli.label}`;
const logo = (cli) => {
const dot = document.createElement('span');
dot.className = `run-mode-dot ${cli.id}`;
dot.setAttribute('aria-hidden', 'true');
return dot;
};
const launch = (cli) => () => {
this.setRunMode(cli.id);
void this.run();
};
container.replaceChildren();
if (!primary) return;
const main = document.createElement('button');
main.type = 'button';
main.className = 'welcome-primary';
main.dataset.mode = primary.id;
// The mark sits on a small light disc: brand marks (Claude's is orange) turn
// muddy straight on the accent fill, and the disc reads on every skin.
const disc = document.createElement('span');
disc.className = 'welcome-primary-logo';
disc.appendChild(logo(primary));
main.appendChild(disc);
// One raw string, kept whole: i18n.js matches the exact text node. The span
// only lets a long custom label ellipsize (styles.css .welcome-label).
const mainLabel = document.createElement('span');
mainLabel.className = 'welcome-label';
mainLabel.textContent = runLabel(primary);
main.appendChild(mainLabel);
main.onclick = launch(primary);
container.appendChild(main);
const rest = offered.filter((cli) => cli !== primary);
if (!rest.length) return;
const chips = document.createElement('div');
chips.className = 'welcome-chips';
chips.setAttribute('role', 'group');
chips.setAttribute('aria-label', 'More tools');
for (const cli of rest) {
const chip = document.createElement('button');
chip.type = 'button';
chip.className = 'welcome-chip';
chip.dataset.mode = cli.id;
// The chip shows the bare name (the row under "Run …" already says what it
// does); the full "Run " is its accessible name and tooltip, both of
// which i18n.js translates.
chip.title = runLabel(cli);
chip.setAttribute('aria-label', runLabel(cli));
chip.appendChild(logo(cli));
const chipLabel = document.createElement('span');
chipLabel.className = 'welcome-label';
chipLabel.textContent = cli.kind === 'shell' ? 'Shell' : cli.label;
chip.appendChild(chipLabel);
chip.onclick = launch(cli);
chips.appendChild(chip);
}
container.appendChild(chips);
},
/**
* #200: show a welcome-screen action only where the thing it launches exists.
* The registry catalog is injected with the initial document and is updated in
* place after a Settings toggle, so the page never offers a disabled CLI.
*/
applyWelcomeCliVisibility() {
this.renderWelcomeCliActions();
// Not a run mode, same reasoning: offering a Cloudflare Tunnel on a box
// without cloudflared can only ever produce "cloudflared not found".
const tunnel = document.getElementById('welcomeTunnelBtn');
if (tunnel) tunnel.style.display = this.isCliAvailable('cloudflared') ? 'flex' : 'none';
},
async loadTunnelStatus() {
try {
const res = await fetch('/api/tunnel/status');
const env = await res.json();
const status = env?.success === true ? env.data : env;
const active = status.running && status.url;
this._tunnelUrl = active ? status.url : null;
this._updateTunnelUrlDisplay(this._tunnelUrl);
this._updateWelcomeTunnelBtn(!!active, this._tunnelUrl);
this._updateTunnelIndicator(!!active);
} catch {
this._tunnelUrl = null;
this._updateTunnelUrlDisplay(null);
this._updateWelcomeTunnelBtn(false);
this._updateTunnelIndicator(false);
}
},
_updateTunnelUrlDisplay(url) {
const row = document.getElementById('tunnelUrlRow');
const display = document.getElementById('tunnelUrlDisplay');
if (!row || !display) return;
if (url) {
row.style.display = '';
display.textContent = url;
display.onclick = () => {
navigator.clipboard.writeText(url).then(() => {
this.showToast('Tunnel URL copied', 'success');
});
};
} else {
row.style.display = 'none';
display.textContent = '';
display.onclick = null;
}
},
showTunnelQR() {
// Close existing popup if open
this.closeTunnelQR();
const overlay = document.createElement('div');
overlay.id = 'tunnelQrOverlay';
overlay.style.cssText = 'position:fixed;inset:0;background:rgba(0,0,0,0.7);z-index:5000;display:flex;align-items:center;justify-content:center;cursor:pointer';
overlay.onclick = (e) => { if (e.target === overlay) this.closeTunnelQR(); };
const card = document.createElement('div');
card.style.cssText = 'background:var(--bg-card);border:1px solid var(--border);border-radius:12px;padding:24px;text-align:center;max-width:340px;width:90vw;box-shadow:var(--shadow-lg);cursor:default';
card.innerHTML = `
Scan to connect
Close
`;
overlay.appendChild(card);
document.body.appendChild(overlay);
// Fetch QR SVG from server
fetch('/api/tunnel/qr')
.then(res => {
if (!res.ok) throw new Error('Tunnel not running');
return res.json();
})
.then(env => {
const data = env?.success === true ? env.data : env;
const container = document.getElementById('tunnelQrContainer');
if (container && data.svg) container.innerHTML = data.svg;
// Show auth badge, countdown, and regenerate button when auth is enabled
if (data.authEnabled) {
const badge = document.createElement('div');
badge.id = 'tunnelQrBadge';
badge.style.cssText = 'margin-top:8px;font-size:11px;color:var(--text-muted)';
badge.textContent = 'Single-use auth \u00b7 expires in 60s';
const regenBtn = document.createElement('button');
regenBtn.textContent = 'Regenerate QR';
regenBtn.style.cssText = 'margin-top:8px;padding:4px 12px;background:var(--bg-elevated);border:1px solid var(--border);border-radius:4px;color:var(--text-secondary);cursor:pointer;font-size:11px';
regenBtn.onclick = () => {
// A refusal is not a success: in multi-user mode this is admin-only (403).
fetch('/api/tunnel/qr/regenerate', { method: 'POST' })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
this.showToast('QR code regenerated', 'success');
})
.catch(() => this.showToast('Failed to regenerate QR', 'error'));
};
const card = container.parentElement;
if (card) {
card.appendChild(badge);
card.appendChild(regenBtn);
}
this._resetQrCountdown();
}
})
.catch(() => {
const container = document.getElementById('tunnelQrContainer');
if (container) container.innerHTML = 'Tunnel not active
';
});
// Fetch URL for display
fetch('/api/tunnel/status')
.then(r => r.json())
.then(env => {
const status = env?.success === true ? env.data : env;
const urlEl = document.getElementById('tunnelQrUrl');
if (urlEl && status.url) {
urlEl.textContent = status.url;
urlEl.onclick = () => {
navigator.clipboard.writeText(status.url).then(() => {
this.showToast('Tunnel URL copied', 'success');
});
};
}
})
.catch(() => {});
// Close on Escape
this._tunnelQrEscHandler = (e) => { if (e.key === 'Escape') this.closeTunnelQR(); };
document.addEventListener('keydown', this._tunnelQrEscHandler);
},
closeTunnelQR() {
const overlay = document.getElementById('tunnelQrOverlay');
if (overlay) overlay.remove();
if (this._tunnelQrEscHandler) {
document.removeEventListener('keydown', this._tunnelQrEscHandler);
this._tunnelQrEscHandler = null;
}
this._clearQrCountdown();
},
/** Fallback: fetch QR SVG from API when SSE payload lacks it */
_refreshTunnelQrFromApi() {
fetch('/api/tunnel/qr')
.then(res => res.ok ? res.json() : null)
.then(env => {
const data = env?.success === true ? env.data : env;
if (!data?.svg) return;
const container = document.getElementById('tunnelQrContainer');
if (container) container.innerHTML = data.svg;
const welcomeInner = document.getElementById('welcomeQrInner');
if (welcomeInner) welcomeInner.innerHTML = data.svg;
})
.catch(() => {});
},
/** Start or reset the 60s countdown on the QR badge */
_resetQrCountdown() {
this._clearQrCountdown();
this._qrCountdownSec = 60;
this._updateQrCountdownText();
this._qrCountdownTimer = setInterval(() => {
this._qrCountdownSec--;
if (this._qrCountdownSec <= 0) {
this._clearQrCountdown();
return;
}
this._updateQrCountdownText();
}, 1000);
},
_updateQrCountdownText() {
const badge = document.getElementById('tunnelQrBadge');
if (badge) {
badge.textContent = `Single-use auth \u00b7 expires in ${this._qrCountdownSec}s`;
}
},
_clearQrCountdown() {
if (this._qrCountdownTimer) {
clearInterval(this._qrCountdownTimer);
this._qrCountdownTimer = null;
}
},
async toggleTunnelFromWelcome() {
const btn = document.getElementById('welcomeTunnelBtn');
if (!btn) return;
// The tunnel is a server-wide setting (PUT /api/settings), admin-only in multi-user mode.
if (this._settingsReadOnly()) {
this.showToast('Server-wide settings can only be changed by an admin', 'warning');
return;
}
const isActive = btn.classList.contains('active');
btn.disabled = true;
try {
const newEnabled = !isActive;
const gate = newEnabled ? await this._confirmTunnelEnable() : { proceed: true, acknowledge: false };
if (!gate.proceed) {
this._updateWelcomeTunnelBtn(false);
btn.disabled = false;
return;
}
const res = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tunnelEnabled: newEnabled, ...(gate.acknowledge ? { acknowledgeUnauthTunnel: true } : {}) }),
});
// COD-55: server refuses an unauthenticated public tunnel (403). Surface it.
if (newEnabled && (await this._handleTunnelEnableRefusal(res))) {
this._dismissTunnelConnecting();
this._updateWelcomeTunnelBtn(false);
btn.disabled = false;
return;
}
// A stop the server did not store (a 409 for a settings.json that does not parse) left the
// tunnel running: say so, and leave the button showing it on.
const stopError = newEnabled ? '' : await this._settingsWriteError(res);
if (stopError) {
this.showToast(`Tunnel not stopped: ${stopError}`, 'error', { duration: 0 });
btn.disabled = false;
return;
}
if (newEnabled) {
this._showTunnelConnecting();
// Poll tunnel status as fallback in case SSE event is missed
this._pollTunnelStatus();
} else {
this._dismissTunnelConnecting();
this.showToast('Tunnel stopped', 'info');
this._updateWelcomeTunnelBtn(false);
btn.disabled = false;
}
} catch (err) {
this._dismissTunnelConnecting();
this.showToast('Failed to toggle tunnel', 'error');
btn.disabled = false;
}
},
_showTunnelConnecting() {
// Remove any existing connecting toast first (without resetting button state)
const oldToast = document.getElementById('tunnelConnectingToast');
if (oldToast) {
oldToast.remove();
}
const btn = document.getElementById('welcomeTunnelBtn');
if (btn) {
btn.classList.add('connecting');
btn.innerHTML = `
Connecting...`;
}
// Persistent toast with spinner
const toast = document.createElement('div');
toast.className = 'toast toast-info show';
toast.id = 'tunnelConnectingToast';
toast.innerHTML = ' Cloudflare Tunnel connecting...';
toast.style.pointerEvents = 'auto';
if (!this._toastContainer) {
this._toastContainer = document.querySelector('.toast-container');
if (!this._toastContainer) {
this._toastContainer = document.createElement('div');
this._toastContainer.className = 'toast-container';
document.body.appendChild(this._toastContainer);
}
}
this._toastContainer.appendChild(toast);
},
_dismissTunnelConnecting() {
clearTimeout(this._tunnelPollTimer);
this._tunnelPollTimer = null;
const toast = document.getElementById('tunnelConnectingToast');
if (toast) {
toast.classList.remove('show');
setTimeout(() => toast.remove(), 200);
}
const btn = document.getElementById('welcomeTunnelBtn');
if (btn) btn.classList.remove('connecting');
},
_pollTunnelStatus(attempt = 0) {
if (attempt > 15) return; // give up after ~30s
this._tunnelPollTimer = setTimeout(async () => {
try {
const res = await fetch('/api/tunnel/status');
const env = await res.json();
const status = env?.success === true ? env.data : env;
if (status.running && status.url) {
// Tunnel is up — update UI
this._dismissTunnelConnecting();
this._updateTunnelUrlDisplay(status.url);
const welcomeVisible = document.getElementById('welcomeOverlay')?.classList.contains('visible');
if (welcomeVisible) {
this._updateWelcomeTunnelBtn(true, status.url, true);
this.showToast('Tunnel active', 'success');
} else {
this._updateWelcomeTunnelBtn(true, status.url);
this.showToast(`Tunnel active: ${status.url}`, 'success');
this.showTunnelQR();
}
return;
}
} catch { /* ignore */ }
this._pollTunnelStatus(attempt + 1);
}, 2000);
},
_updateWelcomeTunnelBtn(active, url, firstAppear = false) {
const btn = document.getElementById('welcomeTunnelBtn');
if (btn) {
btn.disabled = false;
if (active) {
btn.classList.remove('connecting');
btn.classList.add('active');
btn.innerHTML = `
Tunnel Active`;
} else {
btn.classList.remove('active', 'connecting');
btn.innerHTML = `
Cloudflare Tunnel`;
}
}
// Update welcome QR code
const qrWrap = document.getElementById('welcomeQr');
const qrInner = document.getElementById('welcomeQrInner');
const qrUrl = document.getElementById('welcomeQrUrl');
if (!qrWrap || !qrInner) return;
if (active) {
qrWrap.classList.add('visible');
// First appear: start expanded, auto-shrink after 8s
if (firstAppear) {
qrWrap.classList.add('expanded');
clearTimeout(this._welcomeQrShrinkTimer);
this._welcomeQrShrinkTimer = setTimeout(() => {
qrWrap.classList.remove('expanded');
}, 8000);
}
if (url) {
qrUrl.textContent = url;
qrUrl.title = 'Click QR to enlarge';
}
fetch('/api/tunnel/qr')
.then(r => { if (!r.ok) throw new Error(); return r.json(); })
.then(env => { const data = env?.success === true ? env.data : env; if (data.svg) qrInner.innerHTML = data.svg; })
.catch(() => { qrInner.innerHTML = 'QR unavailable
'; });
} else {
clearTimeout(this._welcomeQrShrinkTimer);
qrWrap.classList.remove('visible', 'expanded');
qrInner.innerHTML = '';
if (qrUrl) qrUrl.textContent = '';
}
},
toggleWelcomeQrSize() {
const qrWrap = document.getElementById('welcomeQr');
if (qrWrap) {
clearTimeout(this._welcomeQrShrinkTimer);
qrWrap.classList.toggle('expanded');
}
},
// ═══════════════════════════════════════════════════════════════
// Tunnel Header Indicator & Panel (desktop only)
// ═══════════════════════════════════════════════════════════════
_updateTunnelIndicator(active) {
if (MobileDetection.getDeviceType() === 'mobile') return;
const indicator = document.getElementById('tunnelIndicator');
if (!indicator) return;
indicator.style.display = active ? 'flex' : 'none';
indicator.classList.remove('connecting');
},
toggleTunnelPanel() {
const existing = document.getElementById('tunnelPanel');
if (existing) {
this.closeTunnelPanel();
return;
}
this._openTunnelPanel();
},
async _openTunnelPanel() {
const panel = document.createElement('div');
panel.className = 'tunnel-panel';
panel.id = 'tunnelPanel';
panel.innerHTML = `
`;
document.body.appendChild(panel);
// Close on outside click
this._tunnelPanelClickHandler = (e) => {
if (!panel.contains(e.target) && e.target.id !== 'tunnelIndicator' && !e.target.closest('.tunnel-indicator')) {
this.closeTunnelPanel();
}
};
setTimeout(() => document.addEventListener('click', this._tunnelPanelClickHandler), 0);
// Close on Escape
this._tunnelPanelEscHandler = (e) => { if (e.key === 'Escape') this.closeTunnelPanel(); };
document.addEventListener('keydown', this._tunnelPanelEscHandler);
// Fetch tunnel info
try {
const res = await fetch('/api/tunnel/info');
const env = await res.json();
const info = env?.success === true ? env.data : env;
this._renderTunnelPanel(info);
} catch {
const body = document.getElementById('tunnelPanelBody');
if (body) body.innerHTML = 'Failed to load tunnel info
';
}
},
_renderTunnelPanel(info) {
const statusEl = document.getElementById('tunnelPanelStatus');
const body = document.getElementById('tunnelPanelBody');
if (!statusEl || !body) return;
statusEl.textContent = info.running ? 'Connected' : 'Offline';
statusEl.className = 'tunnel-panel-status' + (info.running ? '' : ' offline');
let html = '';
// URL section
if (info.url) {
html += `
URL
${escapeHtml(info.url)}
`;
}
// Clients section
html += `
Connections
Remote Clients
${info.sseClients}
`;
if (info.authEnabled) {
html += `
Auth Sessions
${info.authSessions.length}
`;
}
html += '
';
// Auth sessions detail
if (info.authEnabled && info.authSessions.length > 0) {
html += 'Authenticated Devices
';
for (const s of info.authSessions) {
const ua = s.ua || 'Unknown';
const browser = ua.match(/Chrome|Firefox|Safari|Edge|Mobile/)?.[0] || 'Browser';
const ago = this._formatTimeAgo(s.createdAt);
html += `
${escapeHtml(browser)} · ${escapeHtml(s.ip)} · ${ago}
${s.method}
`;
}
html += '
';
}
// Actions
html += '';
if (info.running) {
html += `
QR Code
Stop Tunnel `;
} else {
html += `Start Tunnel `;
}
html += '
';
// Revoke all sessions button
if (info.authEnabled && info.authSessions.length > 0) {
html += `
Revoke All Sessions
`;
}
body.innerHTML = html;
// Bind URL copy handler
const urlEl = document.getElementById('tunnelPanelUrl');
if (urlEl) {
urlEl.onclick = () => {
navigator.clipboard.writeText(info.url).then(() => this.showToast('Tunnel URL copied', 'success'));
};
}
},
_formatTimeAgo(timestamp) {
const diff = Date.now() - timestamp;
const mins = Math.floor(diff / 60000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
return `${Math.floor(hrs / 24)}d ago`;
},
/**
* End an App Settings save whose tunnel enable did not go through (confirm cancelled, or
* refused by the server): the WHOLE settings PUT is off, so turn the tunnel toggle back
* off in the UI and localStorage. Other settings persisted to localStorage still apply locally.
*/
_abandonTunnelEnable(settings, keepOpen) {
settings.tunnelEnabled = false;
this.saveAppSettingsToStorage(settings);
const cb = document.getElementById('appSettingsTunnelEnabled');
if (cb) cb.checked = false;
if (!keepOpen) this.closeAppSettings();
},
/** The one SECURITY WARNING prompt for an unauthenticated public tunnel. */
_askUnauthTunnel() {
return confirm(
'⚠️ SECURITY WARNING — no password set\n\n' +
'Enabling the Cloudflare tunnel will publish THIS machine to a public URL with ' +
'NO login. Anyone who gets the URL has full terminal control — effectively remote ' +
'code execution on your computer.\n\n' +
'Strongly recommended: set CODEMAN_PASSWORD instead.\n\n' +
'Enable the unauthenticated public tunnel anyway?'
);
},
/**
* #706: ask BEFORE a tunnel enable whenever the server has no login (no CODEMAN_PASSWORD,
* not multi-user), every time, whatever the server would accept. With
* CODEMAN_ALLOW_UNAUTHENTICATED_TUNNEL set the PUT is never refused, so the refusal
* handler below would never ask. The ONE gate for the welcome link, the tunnel panel and
* the App Settings save. A tunnel that is already running is not being turned on, and
* the server does not guard it either. When the status cannot be read, the PUT goes out
* without the acknowledgement and `_handleTunnelEnableRefusal` stays the fallback.
* @returns {Promise<{ proceed: boolean, acknowledge: boolean }>} proceed=false: cancelled,
* send nothing; acknowledge: send `acknowledgeUnauthTunnel: true` with the enable.
*/
async _confirmTunnelEnable() {
let status = null;
try {
const res = await fetch('/api/tunnel/status');
if (res.ok) {
const env = await res.json();
status = env?.success === true ? env.data : env;
}
} catch {
/* unknown: the 403 handler asks instead */
}
if (!status || status.running || status.loginConfigured !== false) return { proceed: true, acknowledge: false };
if (!this._askUnauthTunnel()) {
this.showToast('Tunnel not enabled', 'info');
return { proceed: false, acknowledge: false };
}
return { proceed: true, acknowledge: true };
},
/**
* COD-55: detect the server's refusal to start an unauthenticated public tunnel.
* The PUT /api/settings route returns a 4xx with { success:false, error } when no
* CODEMAN_PASSWORD is set and the unauthenticated-tunnel opt-in is not acknowledged.
* Shows the server's (actionable) message as an error toast. Since #706 this is the
* fallback for when `_confirmTunnelEnable` could not read the tunnel status.
* @param {Response|null} res - the fetch Response from the settings PUT
* @param {object} [sent] - what that PUT sent, resent with the acknowledgement: the refusal
* rejected all of it, so an App Settings save retried with the tunnel keys alone lost the rest
* @returns {Promise} true if the tunnel-enable was refused (caller should abort)
*/
async _handleTunnelEnableRefusal(res, sent = { tunnelEnabled: true }) {
if (!res || res.ok) return false;
let message = 'Tunnel refused: set CODEMAN_PASSWORD before exposing Codeman publicly.';
let errorCode = '';
try {
const body = await res.json();
if (body && body.error) message = body.error;
if (body && typeof body.errorCode === 'string') errorCode = body.errorCode;
} catch {
/* non-JSON body — use the default message */
}
// A non-admin in multi-user mode: PUT /api/settings is admin-only there (403 FORBIDDEN).
// That is not the no-password refusal below, so no security prompt and no retry. The
// callers skip the PUT for a known non-admin; this covers a role that had not resolved yet.
if (res.status === 403 && errorCode === 'FORBIDDEN') {
this._dismissTunnelConnecting?.();
this.showToast('Server-wide settings can only be changed by an admin', 'warning');
return true;
}
// 403 = the no-password safety refusal (COD-55). Warn loudly and let the
// operator acknowledge the risk; on confirm, retry with explicit acknowledgment.
if (res.status === 403) {
const confirmed = this._askUnauthTunnel();
if (!confirmed) {
this._dismissTunnelConnecting?.();
this.showToast('Tunnel not enabled', 'info');
return true;
}
try {
const retry = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ...sent, acknowledgeUnauthTunnel: true }),
});
if (retry.ok) {
this.showToast('Public tunnel enabling — no password set ⚠️', 'warning');
return false; // proceed with the caller's success/connecting path
}
let m = 'Failed to enable tunnel.';
try {
const b = await retry.json();
if (b && b.error) m = b.error;
} catch {
/* non-JSON */
}
this._dismissTunnelConnecting?.();
this.showToast(m, 'error');
return true;
} catch {
this._dismissTunnelConnecting?.();
this.showToast('Failed to enable tunnel', 'error');
return true;
}
}
this._dismissTunnelConnecting?.();
this.showToast(message, 'error');
return true;
},
async _tunnelPanelToggle(enable) {
// The tunnel is a server-wide setting (PUT /api/settings), admin-only in multi-user mode.
if (this._settingsReadOnly()) {
this.showToast('Server-wide settings can only be changed by an admin', 'warning');
this.closeTunnelPanel();
return;
}
try {
const gate = enable ? await this._confirmTunnelEnable() : { proceed: true, acknowledge: false };
if (!gate.proceed) {
this.closeTunnelPanel();
return;
}
const res = await fetch('/api/settings', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ tunnelEnabled: enable, ...(gate.acknowledge ? { acknowledgeUnauthTunnel: true } : {}) }),
});
// COD-55: server refuses an unauthenticated public tunnel (403). Surface it.
if (enable && (await this._handleTunnelEnableRefusal(res))) {
this.closeTunnelPanel();
return;
}
// A stop the server did not store left the tunnel running (see toggleTunnelFromWelcome).
const stopError = enable ? '' : await this._settingsWriteError(res);
if (stopError) {
this.showToast(`Tunnel not stopped: ${stopError}`, 'error', { duration: 0 });
this.closeTunnelPanel();
return;
}
if (enable) {
this._updateTunnelIndicator(false);
const indicator = document.getElementById('tunnelIndicator');
if (indicator) {
indicator.style.display = 'flex';
indicator.classList.add('connecting');
}
this.showToast('Tunnel starting...', 'info');
this._showTunnelConnecting();
this._pollTunnelStatus();
} else {
this.showToast('Tunnel stopped', 'info');
}
this.closeTunnelPanel();
} catch {
this.showToast('Failed to toggle tunnel', 'error');
}
},
async _tunnelPanelRevokeAll() {
try {
await fetch('/api/auth/revoke', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' });
this.showToast('All sessions revoked', 'success');
// Refresh panel
const res = await fetch('/api/tunnel/info');
const env = await res.json();
const info = env?.success === true ? env.data : env;
this._renderTunnelPanel(info);
} catch {
this.showToast('Failed to revoke sessions', 'error');
}
},
closeTunnelPanel() {
const panel = document.getElementById('tunnelPanel');
if (panel) panel.remove();
if (this._tunnelPanelClickHandler) {
document.removeEventListener('click', this._tunnelPanelClickHandler);
this._tunnelPanelClickHandler = null;
}
if (this._tunnelPanelEscHandler) {
document.removeEventListener('keydown', this._tunnelPanelEscHandler);
this._tunnelPanelEscHandler = null;
}
},
toggleDeepgramKeyVisibility() {
const input = document.getElementById('voiceDeepgramKey');
const btn = document.getElementById('voiceKeyToggleBtn');
if (input.type === 'password') {
input.type = 'text';
btn.textContent = 'Hide';
} else {
input.type = 'password';
btn.textContent = 'Show';
}
},
// ═══════════════════════════════════════════════════════════════
// Session Lifecycle Log
// ═══════════════════════════════════════════════════════════════
openLifecycleLog() {
const win = document.getElementById('lifecycleWindow');
win.style.display = 'block';
// Reset transform so it appears centered initially
if (!win._dragInitialized) {
win.style.left = '50%';
win.style.transform = 'translateX(-50%)';
this._initLifecycleDrag(win);
win._dragInitialized = true;
}
this.loadLifecycleLog();
},
closeLifecycleLog() {
document.getElementById('lifecycleWindow').style.display = 'none';
},
_initLifecycleDrag(win) {
const header = document.getElementById('lifecycleWindowHeader');
let isDragging = false;
let startX, startY, startLeft, startTop;
header.addEventListener('mousedown', (e) => {
if (e.target.tagName === 'SELECT' || e.target.tagName === 'INPUT' || e.target.tagName === 'BUTTON') return;
isDragging = true;
// Clear transform so left/top work in absolute pixels
const rect = win.getBoundingClientRect();
win.style.transform = 'none';
win.style.left = rect.left + 'px';
win.style.top = rect.top + 'px';
startX = e.clientX;
startY = e.clientY;
startLeft = rect.left;
startTop = rect.top;
e.preventDefault();
});
document.addEventListener('mousemove', (e) => {
if (!isDragging) return;
win.style.left = (startLeft + e.clientX - startX) + 'px';
win.style.top = (startTop + e.clientY - startY) + 'px';
});
document.addEventListener('mouseup', () => {
isDragging = false;
});
},
async loadLifecycleLog() {
const eventFilter = document.getElementById('lifecycleFilterEvent').value;
const sessionFilter = document.getElementById('lifecycleFilterSession').value.trim();
const params = new URLSearchParams();
if (eventFilter) params.set('event', eventFilter);
if (sessionFilter) params.set('sessionId', sessionFilter);
params.set('limit', '300');
try {
const res = await fetch(`/api/session-lifecycle?${params}`);
const env = await res.json();
const data = env?.success === true ? env.data : env;
const tbody = document.getElementById('lifecycleTableBody');
const empty = document.getElementById('lifecycleEmpty');
if (!data.entries || data.entries.length === 0) {
tbody.innerHTML = '';
empty.style.display = '';
return;
}
empty.style.display = 'none';
const eventColors = {
created: '#4ade80', started: '#4ade80', recovered: '#4ade80',
exit: '#fbbf24', mux_died: '#f87171', deleted: '#f87171', stale_cleaned: '#f87171',
server_started: '#666', server_stopped: '#666',
};
tbody.innerHTML = data.entries.map(e => {
const time = new Date(e.ts).toLocaleString();
const color = eventColors[e.event] || '#888';
const name = e.name || (e.sessionId === '*' ? '—' : this.getShortId(e.sessionId));
const extra = [];
if (e.exitCode !== undefined && e.exitCode !== null) extra.push(`code=${e.exitCode}`);
if (e.mode) extra.push(e.mode);
return `
${time}
${e.event}
${name}
${e.reason || ''}
${extra.join(', ')}
`;
}).join('');
} catch (err) {
console.error('Failed to load lifecycle log:', err);
}
},
/**
* Paint both Voice status rows: which provider a mic press would use, and what
* the server reports about its Claude login. Called on open and again once the
* /api/voice/status probe resolves.
*/
_renderVoiceProviderStatus() {
const providerEl = document.getElementById('voiceProviderStatus');
if (providerEl) {
const providerName = VoiceInput.getActiveProviderName();
providerEl.textContent = providerName;
const live = providerName.startsWith('Deepgram Nova') || providerName.startsWith('Claude (this');
providerEl.className = 'voice-provider-status' + (live ? ' active' : '');
}
const claudeEl = document.getElementById('voiceClaudeStatus');
if (!claudeEl) return;
const status = VoiceInput._claudeStatus;
const text = !status
? 'Checking...'
: status.available
? `Ready${status.subscriptionType ? ` (${status.subscriptionType})` : ''}`
: status.reason === 'expired'
? 'Login expired - run a Claude session to refresh'
: status.reason === 'no-credentials'
? 'No Claude Code login on the server'
: status.reason === 'malformed'
? 'Claude credentials unreadable'
: 'Off - enable it above';
claudeEl.textContent = text;
claudeEl.className = 'voice-provider-status' + (status?.available ? ' active' : '');
},
/**
* Apply button: the same save as Save, but the modal stays open and the MCP sync group (its
* Preview and Sync need the saved flag) and the CLI management writes are refreshed in place, so
* turning either on needs no close-and-reopen. It is a wrapper rather than an option on
* saveAppSettings() so that function's signature (which tests locate by text) stays as it was.
*
* `_keepSettingsOpenOnce` is the one-shot intent and `_applyInFlight` the double-click guard:
* saveAppSettings() consumes the intent before its first await, so a Save clicked while an Apply
* is still in flight is an ordinary Save and closes the modal.
*/
async applyAppSettings() {
if (this._applyInFlight) return;
this._applyInFlight = true;
this._keepSettingsOpenOnce = true;
try {
await this.saveAppSettings();
} finally {
this._applyInFlight = false;
this._keepSettingsOpenOnce = false;
}
},
async saveAppSettings() {
const keepOpen = this._keepSettingsOpenOnce === true;
this._keepSettingsOpenOnce = false;
// Gesture overlay is injected at page render (server-side), so a change to it
// only takes effect on reload — remember the prior value to decide below.
const _prev = this.loadAppSettingsFromStorage();
// After a save the server did not store, this device's blob is ahead of the server, so the
// two server-side changes judged against it (the gesture reload, the plan-usage collection
// flip) are judged against the blob that save started from until a save lands.
const _prevServer = this._unsavedSettingsBaseline ?? _prev;
const _prevGestureEnabled = (_prevServer.gestureControlEnabled ?? false) === true;
// WebGL toggle: default ON (desktop), so only an explicit stored false counts
// as "previously off" — used below to detect a real OFF→ON flip.
const _prevWebglEnabled = (_prev.webglRendererEnabled ?? true) === true;
const settings = {
displayName: window.CodemanI18n?.normalizeDisplayName(
document.getElementById('appSettingsDisplayName').value
) || 'Codeman',
language: window.CodemanI18n?.normalizeLanguage(
document.getElementById('appSettingsLanguage').value
) || 'en',
defaultClaudeMdPath: document.getElementById('appSettingsClaudeMdPath').value.trim(),
defaultWorkingDir: document.getElementById('appSettingsDefaultDir').value.trim(),
ralphTrackerEnabled: document.getElementById('appSettingsRalphEnabled').checked,
// Header visibility settings
showFontControls: document.getElementById('appSettingsShowFontControls').checked,
showSystemStats: document.getElementById('appSettingsShowSystemStats').checked,
showGpuStats: document.getElementById('appSettingsShowGpuStats').checked,
showCpuMhz: document.getElementById('appSettingsShowCpuMhz').checked,
headerStatsStyle: document.getElementById('appSettingsHeaderStatsStyle').value,
showLifecycleLog: document.getElementById('appSettingsShowLifecycleLog').checked,
showResponseViewer: document.getElementById('appSettingsShowResponseViewer').checked,
showFileViewerButton: document.getElementById('appSettingsShowFileViewerButton').checked,
showAttachmentsButton: document.getElementById('appSettingsShowAttachmentsButton').checked,
showMonitor: document.getElementById('appSettingsShowMonitor').checked,
showProjectInsights: document.getElementById('appSettingsShowProjectInsights').checked,
showFileBrowser: document.getElementById('appSettingsShowFileBrowser').checked,
showSubagents: document.getElementById('appSettingsShowSubagents').checked,
showUltracodeAgents: document.getElementById('appSettingsShowUltracodeAgents').checked,
approvalsInboxEnabled: document.getElementById('appSettingsApprovalsInbox').checked,
customModelEndpointsEnabled: document.getElementById('appSettingsCustomModelEndpoints').checked,
cliManagementEnabled: document.getElementById('appSettingsCliManagement').checked,
mcpSyncEnabled: document.getElementById('appSettingsMcpSync').checked,
configBackupEnabled: document.getElementById('appSettingsConfigBackup').checked,
configBackupDir: document.getElementById('appSettingsConfigBackupDir').value.trim(),
...this._configBackupRetentionPayload(_prev),
agentInboxPersistEnabled: document.getElementById('appSettingsAgentInboxPersist').checked,
agentCoordinationEnabled: document.getElementById('appSettingsAgentCoordination').checked,
readMyMindEnabled: document.getElementById('appSettingsReadMyMind').checked,
ultracodeFloatingWindows: document.getElementById('appSettingsUltracodeFloatingWindows').checked,
showMultiMonitorButton: document.getElementById('appSettingsShowMultiMonitorButton').checked,
showSplitButton: document.getElementById('appSettingsShowSplitButton').checked,
showTileGridButton: document.getElementById('appSettingsShowTileGridButton').checked,
showPlanUsageLimits: document.getElementById('appSettingsShowPlanUsageLimits').checked,
showRedrawButton: document.getElementById('appSettingsShowRedrawButton').checked,
mobileOverviewEnabled: document.getElementById('appSettingsMobileOverview').checked,
sessionLineageLines: document.getElementById('appSettingsLineageLines').checked,
autoNameSessions: document.getElementById('appSettingsAutoNameSessions').checked,
spawnedTabsFollowParent: document.getElementById('appSettingsSpawnedTabsFollowParent').checked,
showSessionButton: document.getElementById('appSettingsShowSessionButton').checked,
showAwayDigestButton: document.getElementById('appSettingsShowAwayDigestButton').checked,
showCronButton: document.getElementById('appSettingsShowCronButton').checked,
showGitStatus: document.getElementById('appSettingsShowGitStatus').checked,
gitStatusTree: document.getElementById('appSettingsGitStatusTree').checked,
// Clamped here and again on the server; an empty or odd value falls back to the default.
gitStatusMaxRepos: Math.min(50, Math.max(1, parseInt(document.getElementById('appSettingsGitStatusMaxRepos').value, 10) || 12)),
gitStatusTimeoutSeconds: Math.min(120, Math.max(5, parseInt(document.getElementById('appSettingsGitStatusTimeout').value, 10) || 30)),
// Clamped to the schema's bounds here too: a value outside them fails the whole save, and these keys
// must survive the strip below because the server's scheduler is what reads them.
gitFetchEnabled: document.getElementById('appSettingsGitFetchEnabled').checked,
gitFetchIntervalSeconds: Math.min(
3600,
Math.max(30, parseInt(document.getElementById('appSettingsGitFetchIntervalSeconds').value, 10) || 300)
),
showEditHistory: document.getElementById('appSettingsShowEditHistory').checked,
gestureControlEnabled: document.getElementById('appSettingsGestureControl').checked,
subagentTrackingEnabled: document.getElementById('appSettingsSubagentTracking').checked,
subagentActiveTabOnly: document.getElementById('appSettingsSubagentActiveTabOnly').checked,
imageWatcherEnabled: document.getElementById('appSettingsImageWatcherEnabled').checked,
promptCacheKeepWarm: document.getElementById('appSettingsPromptCacheKeepWarm').checked,
promptCacheKeepWarmMaxHours:
// Clamped to the schema's range: one value outside it fails the whole save.
Math.min(24, Math.max(0.5, parseFloat(document.getElementById('appSettingsPromptCacheKeepWarmMaxHours').value) || 2)),
tunnelEnabled: document.getElementById('appSettingsTunnelEnabled').checked,
localEchoEnabled: document.getElementById('appSettingsLocalEcho').checked,
keyboardHoldsRows: document.getElementById('appSettingsKeyboardHoldsRows').checked,
autoCopySelection: document.getElementById('appSettingsAutoCopySelection').checked,
copyStripMargin: document.getElementById('appSettingsCopyStripMargin').checked,
terminalFontFamily: document.getElementById('appSettingsTerminalFont').value.trim(),
terminalFontWeight: this.readTerminalFontWeight(document.getElementById('appSettingsTerminalFontWeight')),
terminalFontWeightBold: this.readTerminalFontWeight(
document.getElementById('appSettingsTerminalFontWeightBold')
),
terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked,
cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked,
webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked,
extendedKeyboardBar: document.getElementById('appSettingsExtendedKeyboardBar').checked,
tabTwoRows: document.getElementById('appSettingsTabTwoRows').checked,
showTabCliLogos: document.getElementById('appSettingsShowTabCliLogos').checked,
tabOrientation: document.getElementById('appSettingsTabOrientation').value,
tabRailWidth: this.readTabRailWidthSetting?.() ?? 256,
tabRailDetail: document.getElementById('appSettingsTabRailDetail').value,
tabRailSort: document.getElementById('appSettingsTabRailSort').value,
tabArrangement: document.getElementById('appSettingsTabArrangement').value,
tabStateOrder: document.getElementById('appSettingsTabStateOrder').value,
showTabDetachButton: document.getElementById('appSettingsShowTabDetachButton').checked,
showTabNewButton: document.getElementById('appSettingsShowTabNewButton').checked,
tileDetachEnabled: document.getElementById('appSettingsTileDetach').checked,
sessionListLayout: document.getElementById('appSettingsSessionListLayout').value,
sessionSidebarFontSize: this.resolveSessionSidebarFontSize(
document.getElementById('appSettingsSessionSidebarFontSize').value
),
skin: document.getElementById('appSettingsSkin').value,
// Claude CLI settings
claudeMode: document.getElementById('appSettingsClaudeMode').value,
allowedTools: document.getElementById('appSettingsAllowedTools').value.trim(),
// Codex CLI settings
codexModel: document.getElementById('appSettingsCodexModel').value.trim(),
codexReasoningEffort: document.getElementById('appSettingsCodexReasoningEffort').value,
codexDangerouslyBypassApprovals: document.getElementById('appSettingsCodexDangerouslyBypassApprovals').checked,
codexNetworkAccess: document.getElementById('appSettingsCodexNetworkAccess').checked,
codexAnimationsEnabled: document.getElementById('appSettingsCodexAnimations').checked,
// Claude Permissions settings
agentTeamsEnabled: document.getElementById('appSettingsAgentTeams').checked,
agentSkillEnabled: document.getElementById('appSettingsAgentSkill').checked,
workspaceHooksEnabled: document.getElementById('appSettingsWorkspaceHooks').checked,
pinCliSessionName: document.getElementById('appSettingsPinCliSessionName').checked,
claudeVoiceEnabled: document.getElementById('appSettingsClaudeVoice').checked,
claudeModel: document.getElementById('appSettingsClaudeModel').value,
opusContext1mEnabled: document.getElementById('appSettingsOpusContext1m').checked,
remoteAutoReconnect: document.getElementById('appSettingsRemoteAutoReconnect').checked,
thinkingEffort: document.getElementById('appSettingsThinkingEffort').value,
claudeAdvisorModel: document.getElementById('appSettingsClaudeAdvisor').value,
// CPU Priority settings
nice: {
enabled: document.getElementById('appSettingsNiceEnabled').checked,
niceValue: parseInt(document.getElementById('appSettingsNiceValue').value) || 10,
},
};
// One-shot form read for _captureSettingsFormBaseline(): hand back what the form
// shows, before anything below is checked, stored, applied or sent.
if (this._readSettingsFormOnce === true) {
this._readSettingsFormOnce = false;
return settings;
}
// SettingsUpdateSchema is .strict() and checks codexModel with this same
// pattern, so one bad character 400s the WHOLE settings PUT while the toast
// still says "Settings saved". Refuse it here, before anything is persisted.
if (!/^[A-Za-z0-9._\/-]*$/.test(settings.codexModel)) {
this.showToast('Default Codex model may only contain letters, digits, ".", "_", "-" and "/"', 'error');
document.getElementById('appSettingsCodexModel')?.focus();
return;
}
// The "Token Count" / "Show Cost ($)" header toggles were removed from the
// UI, but their features still read settings.showTokenCount / settings.showCost
// (applyHeaderVisibilitySettings, the header cost render). saveAppSettings
// rebuilds `settings` fresh from the DOM (a full replacement, not a merge), so
// without this these keys would be DROPPED on every save and fall back to their
// defaults — silently re-enabling the token chip for anyone who'd turned it off,
// with no UI left to turn it back off. Preserve the prior stored preference.
if (_prev.showTokenCount !== undefined) settings.showTokenCount = _prev.showTokenCount;
if (_prev.showCost !== undefined) settings.showCost = _prev.showCost;
// Shortcut overrides are edited from the Shortcuts tab (not rebuilt from the
// general-settings DOM), so the fresh rebuild would drop them on every save.
if (_prev.shortcutOverrides !== undefined) settings.shortcutOverrides = _prev.shortcutOverrides;
// Multi-user mode, signed in as a non-admin: settings.json is one file for the whole
// server and PUT /api/settings answers 403 (system-routes.ts), so nothing is sent
// below. The per-device keys still save here exactly as before; every SYNCED key
// keeps the server's value, which the next page load would put back anyway, so this
// device never shows a server-wide change that did not happen.
const settingsReadOnly = this._settingsReadOnly();
const syncedChangeRefused = settingsReadOnly && this._keepServerSyncedSettings(settings, _prev);
// Save to localStorage
this.saveAppSettingsToStorage(settings);
this._updateLocalEchoState();
// Turning Keep Size Under Keyboard off while it holds releases it now.
this._reconcileKeyboardHold?.();
this.applyTerminalFontFamily?.(settings.terminalFontFamily);
this.applyTerminalFontWeights?.(settings);
// A real OFF→ON flip of the WebGL toggle retires the GPU-stall auto-fallback
// marker so the next reload actually re-tries WebGL. Only the transition
// clears it — an incidental save with the checkbox default-checked must NOT
// defeat the sticky safety net (shouldSkipWebGL treats stored true like the
// untouched default at page load).
if (!_prevWebglEnabled && settings.webglRendererEnabled) {
try { localStorage.removeItem('codeman-webgl-disabled'); } catch {}
}
// Save voice settings to localStorage + include in server payload for cross-device sync
const voiceSettings = {
provider: document.getElementById('voiceProvider').value,
apiKey: document.getElementById('voiceDeepgramKey').value.trim(),
language: document.getElementById('voiceLanguage').value,
keyterms: document.getElementById('voiceKeyterms').value.trim(),
insertMode: document.getElementById('voiceInsertMode').value,
};
VoiceInput._saveDeepgramConfig(voiceSettings);
// Save notification preferences separately
const notifPrefsToSave = {
enabled: document.getElementById('appSettingsNotifEnabled').checked,
browserNotifications: document.getElementById('appSettingsNotifBrowser').checked,
audioAlerts: document.getElementById('appSettingsNotifAudio').checked,
stuckThresholdMs: (parseInt(document.getElementById('appSettingsNotifStuckMins').value) || 10) * 60000,
toastDurationMs: (parseInt(document.getElementById('appSettingsNotifToastSecs').value) || 3) * 1000,
browserAutoCloseMs: (parseInt(document.getElementById('appSettingsNotifBrowserSecs').value) || 8) * 1000,
muteCritical: !document.getElementById('appSettingsNotifCritical').checked,
muteWarning: !document.getElementById('appSettingsNotifWarning').checked,
muteInfo: !document.getElementById('appSettingsNotifInfo').checked,
// Per-event-type preferences
eventTypes: {
permission_prompt: {
enabled: document.getElementById('eventPermissionEnabled').checked,
browser: document.getElementById('eventPermissionBrowser').checked,
push: document.getElementById('eventPermissionPush').checked,
audio: document.getElementById('eventPermissionAudio').checked,
},
elicitation_dialog: {
enabled: document.getElementById('eventQuestionEnabled').checked,
browser: document.getElementById('eventQuestionBrowser').checked,
push: document.getElementById('eventQuestionPush').checked,
audio: document.getElementById('eventQuestionAudio').checked,
},
idle_prompt: {
enabled: document.getElementById('eventIdleEnabled').checked,
browser: document.getElementById('eventIdleBrowser').checked,
push: document.getElementById('eventIdlePush').checked,
audio: document.getElementById('eventIdleAudio').checked,
},
stop: {
enabled: document.getElementById('eventStopEnabled').checked,
browser: document.getElementById('eventStopBrowser').checked,
push: document.getElementById('eventStopPush').checked,
audio: document.getElementById('eventStopAudio').checked,
},
session_error: {
enabled: true,
browser: this.notificationManager?.preferences?.eventTypes?.session_error?.browser ?? true,
push: this.notificationManager?.preferences?.eventTypes?.session_error?.push ?? false,
audio: false,
},
respawn_cycle: {
enabled: document.getElementById('eventRespawnEnabled').checked,
browser: document.getElementById('eventRespawnBrowser').checked,
push: document.getElementById('eventRespawnPush').checked,
audio: document.getElementById('eventRespawnAudio').checked,
},
token_milestone: {
enabled: true,
browser: false,
push: false,
audio: false,
},
ralph_complete: {
enabled: document.getElementById('eventRalphEnabled').checked,
browser: document.getElementById('eventRalphBrowser').checked,
push: document.getElementById('eventRalphPush').checked,
audio: document.getElementById('eventRalphAudio').checked,
},
subagent_spawn: {
enabled: document.getElementById('eventSubagentEnabled').checked,
browser: document.getElementById('eventSubagentBrowser').checked,
push: document.getElementById('eventSubagentPush').checked,
audio: document.getElementById('eventSubagentAudio').checked,
},
subagent_complete: {
enabled: document.getElementById('eventSubagentEnabled').checked,
browser: document.getElementById('eventSubagentBrowser').checked,
push: document.getElementById('eventSubagentPush').checked,
audio: document.getElementById('eventSubagentAudio').checked,
},
},
_version: 5,
};
if (this.notificationManager) {
this.notificationManager.preferences = this.notificationManager.normalizePreferences(notifPrefsToSave);
this.notificationManager.savePreferences();
}
// Sync push preferences to server
this._syncPushPreferences();
// Apply header visibility immediately
this.applyHeaderVisibilitySettings();
this.applySkin();
this.applyLocalization();
// Re-parents #sessionTabs between header host and sidebar if the layout
// changed, then calls applyTabWrapSettings() itself — do not call both.
this.applySessionListLayout();
this.applyTabOrientation({ settleRailWidth: true });
this.applyLineageLineSettings?.();
this._updateTokensImmediate(); // Re-render token display (picks up showCost change)
this.applyMonitorVisibility();
this.renderApprovals?.(); // Approvals Inbox toggle (hide/show bell + drawer)
this.renderProjectInsightsPanel(); // Re-render to apply visibility setting
this.updateSubagentWindowVisibility(); // Apply subagent window visibility setting
// Apply CJK input visibility immediately
this._updateCjkInputState();
// The phone home surface (overview vs welcome) may have just been toggled.
// Only re-decide while a home screen is actually up.
if (!this.activeSessionId) this.showWelcome();
// Apply keyboard bar mode
KeyboardAccessoryBar.setMode(settings.extendedKeyboardBar ? 'extended' : 'simple');
// Save to server (includes notification prefs for cross-browser persistence).
// Strip device-specific DISPLAY keys so they never sync across devices —
// localEcho/cjk/extendedKeyboard/skin are per-platform.
// webglRendererEnabled is per-device as well (renderer choice is GPU-specific,
// and syncing would leak mobile's hidden-checkbox false onto desktop); it's
// also absent from SettingsUpdateSchema, which is .strict() — sending it
// would 400 the whole settings PUT.
// showPlanUsageLimits is per-device for DISPLAY (loadAppSettingsFromServer
// only seeds it into localStorage when a device has no value yet, like every
// other display key) but ALSO doubles as the server-side plan-usage telemetry
// COLLECTION switch (readPlanUsageTelemetryEnabled in hooks-config.ts, read
// fresh at every claude session create/respawn). So it is stripped here like
// the others and re-added below ONLY when this save FLIPS it on this device
// (planUsageCollectionFlip): the chip defaults OFF on handhelds, so sending
// it on every save let a phone saving its font size persist `false` and
// switch collection off for every desktop, whose chip then went stale with
// no error anywhere. An explicit toggle on any device still writes it, in
// either direction.
const _chipFlip = this.planUsageCollectionFlip(_prevServer, settings.showPlanUsageLimits);
const {
localEchoEnabled: _leo,
// Per-device (it is about this screen's keyboard) and absent from
// SettingsUpdateSchema (.strict()), so sending it would 400 the whole PUT.
keyboardHoldsRows: _khr,
cjkInputEnabled: _cjk,
extendedKeyboardBar: _ekb,
skin: _skin,
language: _language,
showPlanUsageLimits: _pul,
showAttachmentsButton: _ahb,
showFileViewerButton: _fvb,
// Desktop-only header button, per-device, and absent from
// SettingsUpdateSchema (.strict()) — sending it 400s the whole PUT
// (moving it into displayKeys alone is not the strip; this is).
showSplitButton: _ssp,
// Same as Split: a per-device header button (and the Tiles chord), absent
// from SettingsUpdateSchema (.strict()), so sending it 400s the whole PUT.
showTileGridButton: _stg,
webglRendererEnabled: _wgl,
terminalWheelLocalScrollback: _twls,
// Copy-on-select. Per-device (clipboard access differs by device and by
// origin: the plain-HTTP LAN install has no navigator.clipboard at all)
// and absent from SettingsUpdateSchema (.strict()), so sending it would
// 400 the whole settings PUT.
autoCopySelection: _acs,
// What the clipboard gets is a property of what this device is looking
// at, and the key is absent from SettingsUpdateSchema (.strict()), so
// sending it would 400 the whole settings PUT.
copyStripMargin: _csm,
// Per-device by nature (the font must exist on the device) and absent
// from SettingsUpdateSchema (.strict()) — sending it would 400 the PUT.
terminalFontFamily: _tff,
// Same two reasons: which weights a family can actually render is a
// property of the faces installed on THIS device, and neither key is
// declared in the .strict() schema.
terminalFontWeight: _tfw,
terminalFontWeightBold: _tfwb,
// Per-device header/toolbar button toggles — client-only, and absent from
// SettingsUpdateSchema (.strict()), so sending them would 400 the PUT.
showSessionButton: _ssb,
showAwayDigestButton: _adb,
showCronButton: _crb,
// Per-device bottom-bar indicator, absent from SettingsUpdateSchema (.strict()): it must not reach the PUT.
showGitStatus: _sgs,
// Opt-in header readings (GPU Stats, CPU MHz): per-device and absent from the .strict() schema.
showGpuStats: _sgp,
showCpuMhz: _scm,
gitStatusTree: _gst,
gitStatusMaxRepos: _gsm,
gitStatusTimeoutSeconds: _gst2,
// Per-device header button (edit-history-ui.js), likewise absent from the .strict() schema.
showEditHistory: _seh,
showTabDetachButton: _tdb,
showTabNewButton: _tnb,
// Detach Tiles: what a tile drag does is a property of this device's
// windows, and the key is absent from the .strict() SettingsUpdateSchema.
tileDetachEnabled: _tde,
// Phone-only home surface, and absent from SettingsUpdateSchema (.strict()).
mobileOverviewEnabled: _mov,
// Desktop-only tab decoration, per-device, and likewise absent from the
// .strict() schema — syncing it would push a desktop-shaped choice onto
// devices that cannot render it at all.
sessionLineageLines: _sll,
// Keyboard shortcut overrides are per-device (bindings follow the keyboard
// and the OS: Cmd on macOS, Ctrl elsewhere) and absent from the .strict()
// SettingsUpdateSchema. They used to ride along here, so the first
// Shortcuts change on a device (even a Reset, which leaves an empty {})
// made EVERY later App Settings save a 400, and every synced key stopped
// reaching the server while the toast still said "Settings saved".
shortcutOverrides: _sco,
...serverSettings
} = settings;
let webhookError = '';
let saveError = '';
let serverSaved = false;
try {
// #706: a save that turns the tunnel on asks first when the server has no login
// (one already running is not asked about, see _confirmTunnelEnable).
const tunnelGate = settings.tunnelEnabled && !settingsReadOnly
? await this._confirmTunnelEnable()
: { proceed: true, acknowledge: false };
if (!tunnelGate.proceed) {
this._unsavedSettingsBaseline = _prevServer;
this._abandonTunnelEnable(settings, keepOpen);
return;
}
// A non-admin's save is not sent at all (see settingsReadOnly above): the server
// would refuse it with a 403, the plan-usage collection flip included.
const body = {
...serverSettings,
...(_chipFlip !== undefined ? { showPlanUsageLimits: _chipFlip } : {}),
...(tunnelGate.acknowledge ? { acknowledgeUnauthTunnel: true } : {}),
notificationPreferences: notifPrefsToSave,
voiceSettings,
};
const res = settingsReadOnly ? null : await this._apiPut('/api/settings', body);
// Multi-user mode, a non-admin whose role was not known when this save started
// (/api/me had not answered, or failed and admin-ui.js fell back to a single-user
// admin): the server refused the PUT as admin-only. End it the way a known non-admin's save
// ends: every synced key back to the server's value on this device, and the one admin
// toast below instead of "Settings saved". The page is read-only from here on.
const refusedAsNonAdmin = !settingsReadOnly && (await this._noteSettingsWriteRefusal(res));
if (refusedAsNonAdmin) {
this._keepServerSyncedSettings(settings, _prev);
this.saveAppSettingsToStorage(settings);
}
// COD-55: the server refuses an unauthenticated public tunnel with a 403 — which
// rejects the WHOLE settings PUT. Surface the message and revert the tunnel toggle
// so it doesn't look enabled. Only a 403: any other failure with the switch on is
// not about the tunnel, and turning the switch off for it would be wrong too.
const tunnelRefused = !refusedAsNonAdmin && settings.tunnelEnabled && res?.status === 403;
if (tunnelRefused && (await this._handleTunnelEnableRefusal(res, body))) {
this._unsavedSettingsBaseline = _prevServer;
this._abandonTunnelEnable(settings, keepOpen);
return;
}
// `_apiPut` answers null or a non-ok response instead of throwing, so this is the only
// evidence the server kept the flags the Apply refresh below reads (a tunnel 403 still
// here was retried with the whole save and accepted).
serverSaved = !!res?.ok || tunnelRefused;
// Any other failure (a 409 for a settings.json that does not parse, a 400, a 500, a dropped
// connection) stored nothing on the server, so the save must not say it did. A known
// non-admin sent nothing (res is null).
saveError =
settingsReadOnly || refusedAsNonAdmin || tunnelRefused ? '' : await this._settingsWriteError(res);
this._unsavedSettingsBaseline = saveError ? _prevServer : null;
// Save model configuration separately. For a non-admin it is not sent either, and the
// answer says whether this save would have changed it.
const modelConfigRefused = (await this.saveModelConfigFromSettings()) === true;
// The webhook is server state in its own 0600 file (its URL is a secret, kept out of
// settings.json), so like the model config above it is saved beside the settings PUT, not in
// it. Only when the group was edited: an untouched group must not re-PUT. A refusal (bad URL,
// enabled with no URL) keeps the modal open below, with the pasted URL still in the box.
webhookError = this._webhookPending() ? await this.saveWebhook() : '';
if (saveError) {
this.showToast(`Saved on this device, not on the server: ${saveError}`, 'warning', { duration: 0 });
} else if (webhookError) {
this.showToast(`Settings saved, but not the webhook: ${webhookError}`, 'warning');
} else if (syncedChangeRefused || modelConfigRefused || refusedAsNonAdmin) {
// ONE toast for the whole save, and only when the user really changed a server-wide
// setting: a non-admin saving a font size hears "Settings saved" as everyone does.
// A refused PUT always gets it: the server said this user is not an admin.
this.showToast('Saved on this device. Server-wide settings can only be changed by an admin.', 'warning');
} else {
this.showToast(keepOpen ? 'Settings applied' : 'Settings saved', 'success');
}
// Show tunnel-specific feedback if toggled on (never for a non-admin, whose save
// starts nothing: the box only shows what the server already has)
if (settings.tunnelEnabled && !settingsReadOnly && !refusedAsNonAdmin && !saveError) {
this.showToast('Tunnel starting — QR code will appear when ready...', 'info');
}
} catch (err) {
// Server save failed but localStorage succeeded
this.showToast('Settings saved locally', 'warning');
}
// Only when the settings PUT landed: after a 400 or a dropped connection the server still has the
// old flags, and a webhook-only failure still saved the rest, so this runs ahead of that branch.
if (keepOpen && serverSaved) this._refreshSettingsAfterApply(settings);
// A failed settings PUT keeps the modal open too, with the form as the user left it.
if (webhookError) {
document.getElementById('webhookGroup')?.scrollIntoView({ block: 'center' });
} else if (!keepOpen && !saveError) {
this.closeAppSettings();
}
// Voice availability is a server-side answer, so re-probe after a save:
// otherwise the mic keeps using the pre-save provider until the next reload.
VoiceInput.refreshClaudeStatus();
// The gesture overlay is injected at page render (server reads
// gestureControlEnabled from settings.json), so a change only takes effect on
// reload. Reload when it actually changed — the server PUT above already
// persisted the new value (not after a failed PUT: the reload would render the old one).
// `?? false`: a non-admin's save puts a synced key the server never stored back to
// absent (_keepServerSyncedSettings), and absent means off, as in _prevGestureEnabled.
if (!saveError && (settings.gestureControlEnabled ?? false) !== _prevGestureEnabled) {
this.showToast(
settings.gestureControlEnabled ? 'Enabling gesture control — reloading…' : 'Disabling gesture control — reloading…',
'info'
);
setTimeout(() => location.reload(), 400);
}
},
/**
* True only for a signed-in NON-ADMIN in multi-user mode, where every server-wide settings
* write is refused with 403 FORBIDDEN (PUT /api/settings, PUT /api/execution/model-config and
* PUT /api/cases/order: settings.json is one file for the whole server). Single-user mode and
* admins answer false. Read at call time, because `window.__codemanUser` resolves after page
* load (admin-ui.js fetches /api/me). Also true once the server has refused one of these
* writes as admin-only on this page (_noteSettingsWriteRefusal): before /api/me answers, and
* after it failed (admin-ui.js then falls back to a single-user admin), the role alone reads
* as writable. Other modules call it as
* `this._settingsReadOnly?.()`, so a harness that loads one of them without this file reads
* it as writable, which is what an admin gets.
*/
_settingsReadOnly() {
if (this._settingsWriteForbidden === true) return true;
// typeof guard: the load path calls this, and some vm harnesses define no `window`.
const me = (typeof window !== 'undefined' && window.__codemanUser) || {};
return !!(me.multiUser && me.role !== 'admin');
},
/**
* Whether `res` (a settings write's response) is the multi-user admin-only refusal: 403 with
* errorCode FORBIDDEN. The tunnel's no-password refusal is a 403 too, with another code, and
* is not this. When it is, the page reads as read-only from now on (_settingsReadOnly), so a
* write sent before the role was known is the last one. Reads a clone, so the caller can
* still read the body.
* @returns {Promise}
*/
async _noteSettingsWriteRefusal(res) {
if (!res || res.status !== 403) return false;
let body = null;
try {
body = await (typeof res.clone === 'function' ? res.clone() : res).json();
} catch {
return false;
}
if (body?.errorCode !== 'FORBIDDEN') return false;
this._settingsWriteForbidden = true;
return true;
},
/**
* Why a settings write did not land, or '' when it did: the server's `error` (a 409 when
* settings.json does not parse, a 400, ...), else the HTTP status, else, for the null that
* `_apiPut` answers a dropped connection with, that the server could not be reached. Reads a
* clone, like _noteSettingsWriteRefusal.
* @returns {Promise}
*/
async _settingsWriteError(res) {
if (!res) return 'the server could not be reached';
if (res.ok) return '';
let body = null;
try {
body = await res.clone().json();
} catch {
/* not JSON: the status is all there is */
}
return body?.error || `HTTP ${res.status}`;
},
/**
* The end of a background settings write (run mode, respawn presets): the admin-only refusal is
* _noteSettingsWriteRefusal's, and any other failure says that `what` stayed on this device only.
*/
async _noteSettingsWriteResult(res, what) {
if (await this._noteSettingsWriteRefusal(res)) return;
const error = await this._settingsWriteError(res);
if (error) this.showToast(`${what} saved on this device, not on the server: ${error}`, 'warning', { duration: 0 });
},
/**
* Where a non-admin's OWN run mode and respawn presets live (multi-user mode). Both are keys of
* the server-wide settings.json, whose PUT is admin-only, so this user's picks are kept on this
* device under their name instead (_rememberOwnSetting) and put back over the server's on every
* page load (_applyOwnSettings): loadAppSettingsFromServer() writes the server's values into
* `codeman_runMode` and `codeman-respawn-presets` each time, which used to drop them on reload.
*/
_ownSettingsKey() {
const me = (typeof window !== 'undefined' && window.__codemanUser) || {};
return `codeman:own-settings:${me.username || ''}`;
},
_readOwnSettings() {
try {
const own = JSON.parse(localStorage.getItem(this._ownSettingsKey()) || '{}');
return own && typeof own === 'object' && !Array.isArray(own) ? own : {};
} catch {
return {};
}
},
/** Keep a non-admin's own pick of a server-wide `key` on this device (see _ownSettingsKey). */
_rememberOwnSetting(key, value) {
try {
const own = this._readOwnSettings();
own[key] = value;
localStorage.setItem(this._ownSettingsKey(), JSON.stringify(own));
} catch {
/* storage unavailable: the pick lasts until the next page load */
}
},
/**
* A non-admin's own run mode and respawn presets win over the server's (see _ownSettingsKey).
* Called after the server's values are applied at load, and again on `codeman:me`, because the
* role can resolve either side of that load. A no-op for admins and single-user mode.
*/
_applyOwnSettings() {
if (!this._settingsReadOnly()) return;
const own = this._readOwnSettings();
if (Array.isArray(own.respawnPresets)) {
this._serverRespawnPresets = own.respawnPresets;
try { localStorage.setItem('codeman-respawn-presets', JSON.stringify(own.respawnPresets)); } catch {}
}
if (typeof own.runMode === 'string' && own.runMode) {
this.runMode = own.runMode;
try { localStorage.setItem('codeman_runMode', own.runMode); } catch {}
this._applyRunMode?.();
}
},
/**
* What the App Settings form showed when it opened, read the way saveAppSettings() reads it
* (its one-shot `_readSettingsFormOnce` form read), so a non-admin's save can tell whether the
* user changed a SYNCED setting. The stored blob cannot answer that: a key no admin has ever
* saved is absent from it while the form shows the default, which would read as a change on
* every save. Taken only for a non-admin; nobody else's save asks for it.
*/
_captureSettingsFormBaseline() {
this._settingsFormBaseline = null;
if (!this._settingsReadOnly()) return;
this._readSettingsFormOnce = true;
let pending;
try {
pending = this.saveAppSettings();
} finally {
// Consumed by the read itself; cleared here too in case it threw before reaching it.
this._readSettingsFormOnce = false;
}
Promise.resolve(pending)
.then((form) => {
this._settingsFormBaseline = form && typeof form === 'object' ? form : null;
})
.catch(() => {});
},
/**
* A non-admin's save in multi-user mode (saveAppSettings): put every SYNCED key of `settings`
* back to the value this device last had from the server (`prev`; deleted when it had none),
* and answer whether the form changed one since it opened. Synced means outside the per-device
* `displayKeys` merge policy of loadAppSettingsFromServer() (_displaySettingKeySet(), the one
* list both read): those are the keys the server's settings.json overwrites on every page load.
* A per-device key is left exactly as the user set it.
* @returns {boolean} true when the user changed at least one synced setting
*/
_keepServerSyncedSettings(settings, prev) {
const displayKeys = this._displaySettingKeySet();
// Without a baseline (the form was read before the role was known) the stored blob stands
// in, and a key it lacks is not counted: no toast is better than one on every save.
const baseline = this._settingsFormBaseline || prev || {};
let changed = false;
for (const key of Object.keys(settings)) {
// shortcutOverrides is carried over from `prev` already and never comes from the form.
if (displayKeys.has(key) || key === 'shortcutOverrides') continue;
if (key in baseline && JSON.stringify(settings[key]) !== JSON.stringify(baseline[key])) changed = true;
if (prev && key in prev) settings[key] = prev[key];
else delete settings[key];
}
return changed;
},
/**
* After Apply: bring the groups whose contents depend on a SAVED value up to date without
* reopening the modal. openAppSettings does the same on open; this is the part of it that
* a save can change, without touching what the user is editing or the scroll position.
*/
_refreshSettingsAfterApply(settings) {
// The MCP routes read the saved flag, so switching it on is only usable from now.
this._mcpSyncSavedOn = settings.mcpSyncEnabled === true;
const out = this.$('mcpSyncResult');
if (this._mcpSyncSavedOn && out && out.dataset?.hint === 'save-first') {
out.style.display = 'none';
out.innerHTML = '';
}
this.applyMcpSyncVisibility();
this.applyCustomModelEndpointsVisibility();
this.applyCliManagementVisibility();
this._applyDoctorAdminGate();
},
// Load model configuration from server for the settings modal
async loadModelConfigForSettings() {
try {
const res = await fetch('/api/execution/model-config');
const data = await res.json();
if (data.success && data.data) {
const config = data.data;
// Default model
const defaultModelEl = document.getElementById('appSettingsDefaultModel');
if (defaultModelEl) {
defaultModelEl.value = config.defaultModel || '';
}
// Show recommendations
const showRecsEl = document.getElementById('appSettingsShowModelRecommendations');
if (showRecsEl) {
showRecsEl.checked = config.showRecommendations ?? true;
}
// Agent type overrides
const overrides = config.agentTypeOverrides || {};
const exploreEl = document.getElementById('appSettingsModelExplore');
const implementEl = document.getElementById('appSettingsModelImplement');
const testEl = document.getElementById('appSettingsModelTest');
const reviewEl = document.getElementById('appSettingsModelReview');
if (exploreEl) exploreEl.value = overrides.explore || '';
if (implementEl) implementEl.value = overrides.implement || '';
if (testEl) testEl.value = overrides.test || '';
if (reviewEl) reviewEl.value = overrides.review || '';
}
} catch (err) {
console.warn('Failed to load model config:', err);
}
// What the form shows now, so a non-admin's save can tell whether it was changed.
this._modelConfigBaseline = JSON.stringify(this._modelConfigFromSettingsForm());
},
/** The model configuration as the settings modal's form shows it (the PUT body). */
_modelConfigFromSettingsForm() {
const defaultModelEl = document.getElementById('appSettingsDefaultModel');
const showRecsEl = document.getElementById('appSettingsShowModelRecommendations');
const exploreEl = document.getElementById('appSettingsModelExplore');
const implementEl = document.getElementById('appSettingsModelImplement');
const testEl = document.getElementById('appSettingsModelTest');
const reviewEl = document.getElementById('appSettingsModelReview');
const agentTypeOverrides = {};
if (exploreEl?.value) agentTypeOverrides.explore = exploreEl.value;
if (implementEl?.value) agentTypeOverrides.implement = implementEl.value;
if (testEl?.value) agentTypeOverrides.test = testEl.value;
if (reviewEl?.value) agentTypeOverrides.review = reviewEl.value;
return {
defaultModel: defaultModelEl?.value || '',
showRecommendations: showRecsEl?.checked ?? true,
agentTypeOverrides,
};
},
/**
* Save model configuration from settings modal to server.
* @returns {Promise} true only when a non-admin in multi-user mode changed it:
* the config is a key of the server-wide settings.json and its PUT is admin-only (403), so it is
* not sent, and saveAppSettings() folds this into its one admin-only toast
*/
async saveModelConfigFromSettings() {
const config = this._modelConfigFromSettingsForm();
if (this._settingsReadOnly()) {
const baseline = this._modelConfigBaseline;
return typeof baseline === 'string' && JSON.stringify(config) !== baseline;
}
try {
await fetch('/api/execution/model-config', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(config)
});
} catch (err) {
console.warn('Failed to save model config:', err);
}
},
// ═══════════════════════════════════════════════════════════════
// Custom Model Endpoint Profiles (docs/custom-model-endpoints-plan.md)
//
// CRUD against /api/model-endpoints, rendered into the Models settings section.
// Deliberately its own load/save pair rather than folded into openAppSettings/
// saveAppSettings: these are server-side infra records (like remote/docker
// hosts), not a settings-payload field, so the app-settings-structure guard's
// by-id contract does not apply to them — only the `customModelEndpointsEnabled`
// toggle itself goes through that path.
// ═══════════════════════════════════════════════════════════════
/**
* Toggles the endpoint-management body's visibility to match the setting and,
* turning it on, lazily loads the endpoint list. Assigning `.checked` (as the
* settings load path does) fires no `change` event, so this must be called
* explicitly on open as well as wired to the checkbox's own onchange — a
* gate that only worked one of those two ways would show a stale "off"
* body right after opening, or a stale "on" one right after saving it off.
* With the feature off the body is a list of controls that do nothing, so it
* is hidden entirely rather than shown disabled.
*/
applyCustomModelEndpointsVisibility() {
const enabled = document.getElementById('appSettingsCustomModelEndpoints').checked;
const body = document.getElementById('customModelEndpointsBody');
if (body) body.style.display = enabled ? '' : 'none';
if (enabled) this.loadCustomModelEndpointsForSettings();
else this.closeCustomModelHostEditor();
this._applyCustomModelAdminGate();
},
/**
* Endpoint writes are admin-only in multi-user mode (custom-model-routes.ts),
* and GET already answers a non-admin with an empty list, which hides every
* per-row Edit/Discover/Delete button on its own. The "+ Add endpoint" button
* has no row to hide behind, so it needs its own gate — otherwise a non-admin
* can open the form, fill it in, and get a 403 toast on Save. Wired to the
* `codeman:me` event (admin-ui.js) as well as called from
* applyCustomModelEndpointsVisibility(), because `window.__codemanUser`'s
* real role can resolve AFTER settings have already been opened once.
*/
_applyCustomModelAdminGate() {
const addBtn = document.getElementById('customModelHostAddBtn');
if (!addBtn) return;
const me = window.__codemanUser || {};
const blocked = me.multiUser && me.role !== 'admin';
addBtn.style.display = blocked ? 'none' : '';
},
async loadCustomModelEndpointsForSettings() {
// GET /api/model-endpoints wraps its body in the { success, data } envelope
// like every other /api route (server.ts's preSerialization hook applies to
// arrays too) — _apiJson() unwraps it. A raw fetch().json() here would
// silently see the envelope object instead of the array and this panel
// would read as "No endpoints yet" forever, even with endpoints saved.
const hosts = await this._apiJson('/api/model-endpoints');
this._customModelHosts = Array.isArray(hosts) ? hosts : [];
this.renderCustomModelHostsList();
},
renderCustomModelHostsList() {
const list = document.getElementById('customModelHostsList');
if (!list) return;
const hosts = this._customModelHosts || [];
if (hosts.length === 0) {
list.innerHTML = 'No endpoints yet. Add one below to point a harness at a local or cloud OpenAI-compatible server.
';
return;
}
list.innerHTML = hosts
.map((h) => {
const modelCount = (h.models || []).length;
const modelSummary = modelCount === 0
? 'No models discovered yet'
: `${modelCount} model${modelCount === 1 ? '' : 's'}${h.defaultModelId ? ` · default: ${escapeHtml(h.defaultModelId)}` : ' · no default set'}`;
// escapeHtml(JSON.stringify(h.id)) — not JSON.stringify(h.id) alone —
// because JSON.stringify's own double quotes would otherwise terminate
// this double-quoted attribute at the first one, and everything after
// parses as raw tag content rather than the rest of the quoted string.
// Same idiom as deleteCase's onclick in session-ui.js. h.id is
// regex-constrained server-side (safe either way) but the pattern must
// match everywhere it is used, including where the argument is not.
const idArg = escapeHtml(JSON.stringify(h.id));
return `
${escapeHtml(h.label)}
${escapeHtml(h.baseUrl)} — ${modelSummary}
Discover
Edit
Delete
`;
})
.join('');
},
/** Opens the inline add/edit form. Pass no id to add a new endpoint. */
openCustomModelHostEditor(hostId) {
const host = hostId ? (this._customModelHosts || []).find((h) => h.id === hostId) : null;
this._editingCustomModelHostId = host ? host.id : null;
document.getElementById('customModelHostEditorTitle').textContent = host ? `Edit ${host.label}` : 'Add endpoint';
document.getElementById('customModelHostId').value = host?.id || '';
document.getElementById('customModelHostId').disabled = !!host; // id is immutable once created
document.getElementById('customModelHostLabel').value = host?.label || '';
document.getElementById('customModelHostBaseUrl').value = host?.baseUrl || '';
document.getElementById('customModelHostApiKey').value = ''; // the server never returns the real value (apiKeySet is a bool)
document.getElementById('customModelHostApiKey').placeholder = host?.apiKeySet ? '•••••••• (unchanged if left blank)' : '';
document.getElementById('customModelHostAuthStyle').value = host?.authStyle || 'bearer';
// User-set fallback, round-tripped verbatim (discovery never touches it, so the
// cached copy is authoritative); blank means "no default", cleared on save.
document.getElementById('customModelHostDefaultContextLength').value = host?.defaultContextLength ?? '';
this._populateCustomModelDefaultSelect(host);
document.getElementById('customModelHostEditor').style.display = '';
},
closeCustomModelHostEditor() {
document.getElementById('customModelHostEditor').style.display = 'none';
this._editingCustomModelHostId = null;
},
_populateCustomModelDefaultSelect(host) {
const select = document.getElementById('customModelHostDefaultModel');
const models = host?.models || [];
select.innerHTML =
'No default (picker uses the first discovered model) ' +
models.map((m) => `${escapeHtml(m)} `).join('');
select.value = host?.defaultModelId || '';
select.disabled = models.length === 0;
},
async saveCustomModelHostFromEditor() {
const id = document.getElementById('customModelHostId').value.trim();
const label = document.getElementById('customModelHostLabel').value.trim();
const baseUrl = document.getElementById('customModelHostBaseUrl').value.trim();
const apiKeyInput = document.getElementById('customModelHostApiKey').value;
const authStyle = document.getElementById('customModelHostAuthStyle').value;
// Blank means "no default" (key omitted, so PUT clears it); a value must satisfy
// the same bound the server schema enforces, caught here for a friendlier message.
const defaultContextLengthInput = document.getElementById('customModelHostDefaultContextLength').value.trim();
let defaultContextLength;
if (defaultContextLengthInput !== '') {
const parsed = Number(defaultContextLengthInput);
if (!Number.isInteger(parsed) || parsed < 1 || parsed > 100000000) {
this.showToast('Default context length must be a whole number of tokens between 1 and 100,000,000', 'warning');
return;
}
defaultContextLength = parsed;
}
const defaultModelId = document.getElementById('customModelHostDefaultModel').value || undefined;
if (!id || !label || !baseUrl) {
this.showToast('Id, label and base URL are all required', 'warning');
return;
}
const editing = this._editingCustomModelHostId;
// PUT (server-side) treats an absent apiKey as "keep the stored one" — the
// browser never holds the real value to resend deliberately unchanged (see
// openCustomModelHostEditor and custom-model-routes.ts's applyStoredApiKey),
// so a blank field here means omitting the key entirely, not resending
// something we do not have. models/lastDiscoveredAt DO still need
// re-sending: PUT replaces the whole record, and this cached copy still
// carries both (only apiKey is redacted from what GET hands back).
const existing = editing ? (this._customModelHosts || []).find((h) => h.id === editing) : null;
const body = {
id,
label,
baseUrl,
authStyle,
defaultModelId,
defaultContextLength,
apiKey: apiKeyInput || undefined,
models: existing?.models,
lastDiscoveredAt: existing?.lastDiscoveredAt,
};
try {
const res = await fetch(editing ? `/api/model-endpoints/${encodeURIComponent(editing)}` : '/api/model-endpoints', {
method: editing ? 'PUT' : 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
const data = await res.json();
if (!data.success) {
this.showToast(data.error || 'Failed to save endpoint', 'error');
return;
}
this.showToast(editing ? 'Endpoint updated' : 'Endpoint added', 'success');
this.closeCustomModelHostEditor();
await this.loadCustomModelEndpointsForSettings();
} catch (err) {
this.showToast(`Failed to save endpoint: ${err.message}`, 'error');
}
},
async discoverCustomModelHostModels(hostId) {
this.showToast('Discovering models…', 'info');
try {
const res = await fetch(`/api/model-endpoints/${encodeURIComponent(hostId)}/discover-models`, { method: 'POST' });
const data = await res.json();
if (!data.success) {
this.showToast(data.error || 'Discovery failed', 'error');
return;
}
this.showToast(`Found ${data.data.models.length} model${data.data.models.length === 1 ? '' : 's'}`, 'success');
await this.loadCustomModelEndpointsForSettings();
} catch (err) {
this.showToast(`Discovery failed: ${err.message}`, 'error');
}
},
async deleteCustomModelHost(hostId) {
const host = (this._customModelHosts || []).find((h) => h.id === hostId);
if (!confirm(`Delete endpoint "${host?.label || hostId}"? Any session currently pointed at it keeps running until cleared.`)) return;
try {
await fetch(`/api/model-endpoints/${encodeURIComponent(hostId)}`, { method: 'DELETE' });
await this.loadCustomModelEndpointsForSettings();
} catch (err) {
this.showToast(`Failed to delete endpoint: ${err.message}`, 'error');
}
},
// ═══════════════════════════════════════════════════════════════
// CLI management (docs/cli-enable-disable-plan.md)
//
// CRUD against /api/clis, rendered into the Agents & CLIs settings section.
// Same load/save-pair-outside-openAppSettings reasoning as the Custom Model
// Endpoints block above: these are server-side registry records, not a
// settings-payload field — only the `cliManagementEnabled` toggle itself
// goes through openAppSettings/saveAppSettings.
// ═══════════════════════════════════════════════════════════════
/**
* Same two-caller shape as applyCustomModelEndpointsVisibility (assigning
* .checked fires no change event, so this needs both an explicit call on
* open AND the checkbox's own onchange) and the same reasoning for hiding
* the whole list rather than showing it disabled: with the flag off the
* rows would be controls that only 403.
*/
applyCliManagementVisibility() {
const enabled = document.getElementById('appSettingsCliManagement').checked;
const group = document.getElementById('cliListGroup');
if (group) group.style.display = enabled ? '' : 'none';
if (enabled) this.loadCliListForSettings();
else this.closeCliCustomForm();
this._applyCliManagementAdminGate();
},
/**
* Decision 5 (docs/cli-enable-disable-plan.md): hidden entirely for a
* non-admin in multi-user mode, not shown-empty. GET /api/clis already
* answers a non-admin with [], which empties the row list on its own; the
* "Add a custom CLI" row has no list row to hide behind, so it needs its
* own gate the same way the Custom Model Endpoints "+ Add" button does.
*/
_applyCliManagementAdminGate() {
const group = document.getElementById('cliListGroup');
if (!group) return;
const me = window.__codemanUser || {};
const blocked = me.multiUser && me.role !== 'admin';
const featureOn = document.getElementById('appSettingsCliManagement')?.checked ?? false;
group.style.display = blocked || !featureOn ? 'none' : '';
const addRow = document.getElementById('cliCustomAddToggle');
if (addRow) addRow.style.display = blocked ? 'none' : '';
},
async loadCliListForSettings() {
// GET /api/clis wraps its body in the { success, data } envelope like every
// other /api route — _apiJson() unwraps it, same reasoning as the Custom
// Model Endpoints list load above.
const clis = await this._apiJson('/api/clis');
this._cliList = Array.isArray(clis) ? clis : [];
this._syncCliLaunchCatalog();
this.renderCliList();
},
/** Keep the launch surfaces in sync with Settings mutations without a reload. */
_syncCliLaunchCatalog() {
if (!Array.isArray(this._cliList) || this._cliList.length === 0) return;
// /api/clis rows carry no capabilities, so keep the served catalog's `external`
// (isExternalCliSession() reads it). A new custom CLI has none and falls back to `kind`.
const previous = new Map(
(Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : []).map((cli) => [cli.id, cli])
);
window.__codemanCliCatalog = this._cliList.map((cli) => ({
id: cli.id,
label: cli.label,
shortBadge: cli.shortBadge,
order: cli.order,
kind: cli.kind,
external: previous.get(cli.id)?.external,
enabled: cli.enabled,
available: cli.kind === 'shell' || (cli.enabled && cli.installed),
}));
window.__codemanCliAvailable = {
...(window.__codemanCliAvailable || {}),
...Object.fromEntries(this._cliList.map((cli) => [cli.id, cli.kind === 'shell' || (cli.enabled && cli.installed)])),
};
if (!window.__codemanCliCatalog.some((cli) => cli.id === this.runMode && cli.enabled)) {
this.setRunMode?.('claude');
}
this.applyWelcomeCliVisibility?.();
this.renderRegistryRunOptions?.();
this.renderMobileOverview?.();
const menu = document.getElementById('runModeMenu');
if (menu) this._refreshRunModeAvailability?.(menu);
},
renderCliList() {
const list = document.getElementById('cliListRows');
if (!list) return;
const clis = [...(this._cliList || [])].sort((a, b) => {
// Installed CLIs first, alphabetically; then not-installed, alphabetically.
if (a.installed !== b.installed) return a.installed ? -1 : 1;
return a.label.localeCompare(b.label);
});
if (clis.length === 0) {
list.innerHTML = 'No CLIs found.
';
return;
}
// Mirrors cli-registry-routes.ts's own isUndisableable(): a kind 'shell' entry
// is the one the backend refuses to ever disable (keyed on kind, never an id).
// Revised 2026-09-23: rather
// than render a permanently-greyed switch for it (which read as "broken"
// next to every other row's working toggle), shell gets NO switch at all —
// a plain "Always available" label, so there is nothing to click that
// could look like it should work but doesn't.
list.innerHTML = clis
.map((c) => {
const idArg = escapeHtml(JSON.stringify(c.id));
const untoggleable = c.kind === 'shell';
const installBtn =
c.stock && !c.installed
? `Install `
: '';
const customActions = c.stock
? ''
: `Edit
Delete `;
const toggle = untoggleable
? 'Always available '
: `
`;
return `
${escapeHtml(c.label)} ${escapeHtml(c.shortBadge)}
${c.installed ? 'Installed' : 'Not installed'}${c.stock ? '' : ' · custom'}
${installBtn}
${customActions}
${toggle}
`;
})
.join('');
},
/**
* ⚠️ A successful toggle must patch `window.__codemanCliAvailable` and refresh
* every surface that reads it, or the change is invisible everywhere except
* this settings row until the next full page reload — `window.__codemanCliAvailable`
* is injected ONCE at initial page render (server.ts) and nothing else refetches
* it. Same pattern `installDeepSeekProfile()` already uses for the same reason.
*/
async toggleCliEnabled(id, checkbox) {
const next = checkbox.checked;
const res = await this._api(`/api/clis/${encodeURIComponent(id)}`, { method: 'PUT', body: { enabled: next } });
if (!res || !res.ok) {
checkbox.checked = !next; // revert on failure — the row must not lie about server state
let detail = '';
try {
detail = (await res?.json())?.error || '';
} catch {
/* no body to read */
}
this.showToast(`Failed to ${next ? 'enable' : 'disable'} "${id}"${detail ? `: ${detail}` : ''}`, 'error');
return;
}
await this.loadCliListForSettings();
},
async installCliEntry(id) {
// Installing runs a command on the server, so it never happens on a single click:
// the confirm names the exact command POST /api/clis/:id/install would run (the
// #343 review's "auto-install may end up behind an explicit confirm").
const entry = (this._cliList || []).find((c) => c.id === id);
const label = entry?.label || id;
const command = entry?.installCommand;
const prompt = command
? `Install ${label}? This runs the following on the Codeman server:\n\n${command}`
: `Install ${label}? This runs its official install command on the Codeman server.`;
if (!confirm(prompt)) return;
const btn = document.getElementById(`cliInstallBtn-${id}`);
if (btn) {
btn.disabled = true;
btn.textContent = 'Installing…';
}
try {
const res = await this._api(`/api/clis/${encodeURIComponent(id)}/install`, { method: 'POST' });
if (!res || !res.ok) {
let detail = '';
try {
detail = (await res?.json())?.error || '';
} catch {
/* no body to read */
}
this.showToast(`Installing "${id}" failed${detail ? `: ${detail}` : ''}`, 'error');
return;
}
this.showToast(`Installed "${id}"`, 'success');
} finally {
await this.loadCliListForSettings();
}
},
/**
* Pass no id to create a new entry; pass an existing CUSTOM id to edit one.
* ⚠️ GET /api/clis deliberately excludes discovery/launch (Phase 2's own
* scope), so an edit cannot be pre-filled with the entry's existing binary
* or argv — those two fields start blank and must be re-entered, since the
* update endpoint (PUT /api/clis/custom/:id) replaces the whole launch
* spec rather than patching it. id/label/badge DO come from the list row.
*/
openCliCustomForm(editId) {
const form = document.getElementById('cliCustomForm');
const errorEl = document.getElementById('cliCustomFormError');
if (!form) return;
const existing = editId ? (this._cliList || []).find((c) => c.id === editId) : null;
this._editingCliCustomId = existing ? existing.id : null;
document.getElementById('cliCustomId').value = existing ? existing.id : '';
document.getElementById('cliCustomId').disabled = !!existing; // id is immutable once created
document.getElementById('cliCustomLabel').value = existing ? existing.label : '';
document.getElementById('cliCustomBadge').value = existing ? existing.shortBadge : '';
document.getElementById('cliCustomBinary').value = '';
document.getElementById('cliCustomArgv').value = '';
document.getElementById('cliCustomSubmit').textContent = existing ? 'Save' : 'Create';
if (errorEl) errorEl.style.display = 'none';
form.style.display = '';
},
closeCliCustomForm() {
const form = document.getElementById('cliCustomForm');
if (form) form.style.display = 'none';
this._editingCliCustomId = null;
},
/** Wired to #cliCustomForm's onsubmit; `event` is the submit event. */
async submitCliCustomForm(event) {
event.preventDefault();
const errorEl = document.getElementById('cliCustomFormError');
const showError = (msg) => {
if (errorEl) {
errorEl.textContent = msg;
errorEl.style.display = '';
}
};
const id = document.getElementById('cliCustomId').value.trim();
const label = document.getElementById('cliCustomLabel').value.trim();
const shortBadge = document.getElementById('cliCustomBadge').value.trim();
const binaries = document.getElementById('cliCustomBinary').value.trim().split(/\s+/).filter(Boolean);
const argv = document.getElementById('cliCustomArgv').value.trim().split(/\s+/).filter(Boolean);
if (!id || !label || !shortBadge || binaries.length === 0 || argv.length === 0) {
showError('All fields are required.');
return;
}
const editing = this._editingCliCustomId;
const path = editing ? `/api/clis/custom/${encodeURIComponent(editing)}` : '/api/clis';
const method = editing ? 'PUT' : 'POST';
const res = await this._api(path, { method, body: { id, label, shortBadge, binaries, argv } });
if (!res || !res.ok) {
let detail = 'Request failed';
try {
detail = (await res?.json())?.error || detail;
} catch {
/* no body to read */
}
showError(detail);
return;
}
this.closeCliCustomForm();
await this.loadCliListForSettings();
},
async deleteCliCustom(id) {
const entry = (this._cliList || []).find((c) => c.id === id);
if (!confirm(`Delete custom CLI "${entry?.label || id}"? This cannot be undone.`)) return;
const res = await this._api(`/api/clis/${encodeURIComponent(id)}`, { method: 'DELETE' });
if (!res || !res.ok) {
let detail = '';
try {
detail = (await res?.json())?.error || '';
} catch {
/* no body to read */
}
this.showToast(`Failed to delete "${id}"${detail ? `: ${detail}` : ''}`, 'error');
return;
}
await this.loadCliListForSettings();
},
// ═══════════════════════════════════════════════════════════════
// Visibility Settings & Device-Specific Defaults
// ═══════════════════════════════════════════════════════════════
// Get the global Ralph tracker enabled setting
isRalphTrackerEnabledByDefault() {
const settings = this.loadAppSettingsFromStorage();
return settings.ralphTrackerEnabled ?? false;
},
// Keep the settings namespace stable across foldable posture changes. Layout
// still follows viewport width, but an unfolded phone remains the same
// handheld device and must not silently switch to desktop preferences.
getSettingsStorageKey() {
const isHandheld =
MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType() === 'mobile';
return isHandheld ? 'codeman-app-settings-mobile' : 'codeman-app-settings';
},
// Get default settings based on device type
// Note: Notification prefs are handled separately by NotificationManager
getDefaultSettings() {
const isHandheld =
MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType() === 'mobile';
if (isHandheld) {
// Mobile defaults: minimal UI for small screens
return {
// Header visibility - hide everything on mobile
showFontControls: false,
showSystemStats: false,
showGpuStats: false,
showCpuMhz: false,
showTokenCount: false,
showCost: false,
// Panel visibility - hide panels on mobile (not enough space)
showMonitor: false,
showProjectInsights: false,
showFileBrowser: false,
showSubagents: false,
showUltracodeAgents: false,
ultracodeFloatingWindows: false,
showMultiMonitorButton: false,
showSplitButton: false,
showTileGridButton: false,
// Desktop defaults this ON (see planUsageChipEnabled); handhelds keep it
// OFF so the phone header stays minimal and the mobile-header-buttons
// policy guard keeps passing.
showPlanUsageLimits: false,
showAttachmentsButton: false,
showFileViewerButton: false,
showRedrawButton: false,
showSessionButton: false,
showAwayDigestButton: false,
showCronButton: false,
// Phone home screen: the C logo opens the session overview instead of the
// welcome screen. ON by default here, and the escape hatch if it ever
// misbehaves on a device (the gate treats only an explicit false as off).
mobileOverviewEnabled: true,
// Remote auto-reconnect (COD-108) — on by default
remoteAutoReconnect: true,
// Input
gestureControlEnabled: false,
// Feature toggles - keep tracking on even on mobile
subagentTrackingEnabled: true,
subagentActiveTabOnly: true, // Only show subagents for active tab
imageWatcherEnabled: false,
ralphTrackerEnabled: false,
tabTwoRows: false,
showTabCliLogos: true,
tabOrientation: 'horizontal',
tabRailWidth: 256,
tabRailDetail: 'rich',
tabRailSort: 'activity',
tabArrangement: 'classic',
tabStateOrder: 'urgent-first',
sessionListLayout: 'header',
sessionSidebarFontSize: 12,
cjkInputEnabled: false,
terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel
webglRendererEnabled: false, // mobile always uses the DOM renderer
skin: 'daylight-blue',
};
}
// Desktop defaults - rely on ?? operators in apply functions
// This allows desktop to have different defaults without duplication
// A touch-primary tablet (iPad, an Android tablet: not a handheld, so it
// lands here) keeps the Tiles button opt-in, as Split is: a tile has none of
// the main terminal's touch, IME and soft-keyboard handling. The PRIMARY
// pointer decides, never MobileDetection.isTouchDevice(), which is true on a
// touchscreen laptop too (fine primary pointer: the desktop default stays).
const coarsePrimaryPointer =
typeof window !== 'undefined' && window.matchMedia?.('(pointer: coarse)')?.matches === true;
return coarsePrimaryPointer ? { showTileGridButton: false } : {};
},
loadAppSettingsFromStorage() {
// Return cached settings if available (avoids synchronous localStorage + JSON.parse
// on every SSE event — critical for input responsiveness)
if (this._cachedAppSettings) return this._cachedAppSettings;
try {
const key = this.getSettingsStorageKey();
const saved = localStorage.getItem(key);
if (saved) {
this._cachedAppSettings = JSON.parse(saved);
return this._cachedAppSettings;
}
} catch (err) {
console.error('Failed to load app settings:', err);
}
// Return device-specific defaults, without showTileGridButton: its default
// on a non-handheld follows the LIVE primary pointer (getDefaultSettings),
// and this object is what a fresh device caches and the server-settings
// merge then persists, which would freeze a 2-in-1's first-load posture
// into a stored value. Every reader resolves the absent key through a
// fresh getDefaultSettings() (?? defaults.showTileGridButton ?? true).
const defaults = { ...this.getDefaultSettings() };
delete defaults.showTileGridButton;
this._cachedAppSettings = defaults;
return this._cachedAppSettings;
},
saveAppSettingsToStorage(settings) {
// Invalidate cache on save
this._cachedAppSettings = settings;
try {
const key = this.getSettingsStorageKey();
localStorage.setItem(key, JSON.stringify(settings));
} catch (err) {
console.error('Failed to save app settings:', err);
}
},
// Apply the chosen skin live: sets the html[data-skin] attribute, syncs BOTH
// localStorage locations (the standalone 'codeman:skin' key the pre-paint head
// script reads + the app-settings blob field written by saveAppSettingsToStorage),
// updates window.__codemanSkin, and re-themes any live terminals.
applySkin() {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
const skin = settings.skin ?? defaults.skin ?? 'daylight-blue';
document.documentElement.setAttribute('data-skin', skin);
window.__codemanSkin = skin;
const themeColor = getComputedStyle(document.documentElement).getPropertyValue('--bg-dark').trim();
if (themeColor) document.querySelector('meta[name="theme-color"]')?.setAttribute('content', themeColor);
try {
localStorage.setItem('codeman:skin', skin);
} catch (_e) {
/* private mode */
}
if (typeof this.applyTerminalSkin === 'function') this.applyTerminalSkin(skin);
},
// Apply the per-device language and the synced user-facing product name.
// The i18n layer updates both existing static nodes and future dynamic DOM.
applyLocalization() {
const settings = this.loadAppSettingsFromStorage();
const result = window.CodemanI18n?.configure({
language: settings.language,
displayName: settings.displayName,
});
if (result && this.notificationManager) {
this.notificationManager.originalTitle = document.title;
}
// The connection tile's value word (Header Stats Style Tiles) is written
// already translated into a data-i18n-skip span, so the translator above
// cannot revert it; its own language compare makes this one call repaint it.
this._updateConnectionIndicator?.();
},
// Resolved per-device state of the plan-usage chip. Desktop defaults ON,
// handhelds default OFF (the mobile block in getDefaultSettings() sets false,
// and the mobile-header-buttons-policy guard depends on that staying false).
// Single source of truth for the two call sites that must never disagree:
// the App Settings checkbox and the chip's visibility. Telemetry COLLECTION
// no longer has a THIRD client-side call site here at all — the server reads
// this same persisted setting directly (readPlanUsageTelemetryEnabled in
// hooks-config.ts), fresh, at every claude session create/respawn.
planUsageChipEnabled(settings = null) {
const s = settings ?? this.loadAppSettingsFromStorage();
return s.showPlanUsageLimits ?? this.getDefaultSettings().showPlanUsageLimits ?? true;
},
// What a settings save tells the server about plan-usage COLLECTION: the new
// chip value when this save FLIPS it relative to what this device resolved
// before (stored value, else the per-device default), otherwise undefined,
// meaning "say nothing". The server reads an absent key as ON, so a device
// that never touched the chip leaves collection alone, and a handheld (chip
// default OFF) cannot switch it off for every desktop by saving its font
// size. Pure so test/plan-usage-collection-flip.test.ts can drive it.
planUsageCollectionFlip(prevSettings, now) {
const before = this.planUsageChipEnabled(prevSettings ?? {});
return now === before ? undefined : now;
},
/**
* The stored tab layout, or the default. Anything but the four known values
* (an absent key, a value from a newer build) reads as 'classic', the default:
* the single strip as before, the owner's pick on the 1.36.0 beta. 'state'
* (Discussion #426, option C), 'case' and 'ledger' are opt-in.
*/
resolveTabArrangement(settings) {
const value = settings?.tabArrangement ?? this.getDefaultSettings().tabArrangement;
return value === 'state' || value === 'case' || value === 'ledger' ? value : 'classic';
},
/**
* CLI Logos on Tabs (`showTabCliLogos`, per-device, default ON on every
* device). Anything but an explicit false reads as on, the same test the
* pre-paint script in index.html applies, so a reload and a Save never
* disagree about an odd stored value.
*/
tabCliLogosEnabled(settings) {
return (settings?.showTabCliLogos ?? this.getDefaultSettings().showTabCliLogos) !== false;
},
/** The stored state-group order: 'urgent-last' only when chosen, else 'urgent-first'. */
resolveTabStateOrder(settings) {
const value = settings?.tabStateOrder ?? this.getDefaultSettings().tabStateOrder;
return value === 'urgent-last' ? 'urgent-last' : 'urgent-first';
},
/**
* The stored header-stats style, or the default. Anything but the three
* known values (an absent key, a value from a newer build) reads as
* 'compact', the default (the two-pill ring variant of Discussion #426's
* option G, picked by the owner on the 1.36.0 beta over 'tiles').
*/
resolveHeaderStatsStyle(settings) {
const value = settings?.headerStatsStyle ?? this.getDefaultSettings().headerStatsStyle;
return value === 'classic' || value === 'tiles' ? value : 'compact';
},
/**
* Apply a header-stats style: the `data-header-stats` attribute every rule in
* the "Header stats styles" block of styles.css keys on, plus the two DOM
* moves the clustered styles need.
*
* The template keeps the classic order, where the connection indicator sits
* before the font controls and the plan-usage chip near the end of the header.
* Compact and Tiles draw them as ONE cluster (WS · CPU · MEM, then the plan
* windows), so the indicator moves into #headerSystemStats as its first child
* and the chip moves right after it. Comment anchors left at the template
* positions are what 'classic' moves them back to, so switching back restores
* the header exactly.
*
* ⚠️ The indicator only joins the pill while System Stats is shown: the pill
* is hidden with `display: none`, and the WS readout must not disappear with
* it. Both elements keep their ids, so every writer (setConnectionStatus,
* updatePlanUsageChip) finds them wherever they sit.
*
* @param {{style: 'classic'|'compact'|'tiles', showSystemStats: boolean}} opts
*/
applyHeaderStatsStyle({ style, showSystemStats }) {
document.documentElement.dataset.headerStats = style;
const stats = document.getElementById('headerSystemStats');
const conn = document.getElementById('connectionIndicator');
const plan = document.getElementById('planUsageChip');
if (!stats || !conn || !plan) return;
if (!this._headerStatsAnchors) {
const connAnchor = document.createComment(' connection indicator (classic position) ');
const planAnchor = document.createComment(' plan usage chip (classic position) ');
conn.before(connAnchor);
plan.before(planAnchor);
this._headerStatsAnchors = { conn: connAnchor, plan: planAnchor };
}
const anchors = this._headerStatsAnchors;
const clustered = style !== 'classic';
if (clustered && showSystemStats) {
if (stats.firstElementChild !== conn) stats.prepend(conn);
} else if (anchors.conn.nextSibling !== conn) {
anchors.conn.after(conn);
}
if (clustered) {
if (stats.nextElementSibling !== plan) stats.after(plan);
} else if (anchors.plan.nextSibling !== plan) {
anchors.plan.after(plan);
}
},
applyHeaderVisibilitySettings() {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
// Tab pop-out (open-in-new-window) button: opt-in (App Settings → Tab Bar,
// default OFF, per-device). Mirrored as a class on : styles.css hides
// .tab-detach without it (a tab that is already detached keeps its icon as
// the re-focus affordance for the popped-out window).
// Under a host that opens windows (see hasHostWindows) popping out is the
// way to get two panes side by side, so the button defaults on there.
const showTabDetach =
this.tabDetachButtonEnabled?.(settings, defaults)
?? (settings.showTabDetachButton ?? defaults.showTabDetachButton ?? false);
document.documentElement.classList.toggle('tabs-show-detach', showTabDetach);
// The tab's "+" (new session beside it): per-device and opt-in everywhere,
// like the pop-out button. On a phone it also widens the active tab (mobile.css).
document.documentElement.classList.toggle('tabs-show-new', settings.showTabNewButton === true);
const compactHeader = MobileDetection.getDeviceType() !== 'desktop';
const showFontControls = compactHeader ? false : (settings.showFontControls ?? defaults.showFontControls ?? false);
const showSystemStats = compactHeader ? false : (settings.showSystemStats ?? defaults.showSystemStats ?? true);
// Default OFF: the header stays gear + usage chips + files button unless a
// stored preference explicitly re-enables the token chip (no UI toggle exists).
const showTokenCount = compactHeader ? false : (settings.showTokenCount ?? defaults.showTokenCount ?? false);
const fontControlsEl = document.querySelector('.header-font-controls');
const systemStatsEl = document.getElementById('headerSystemStats');
const tokenCountEl = document.getElementById('headerTokens');
if (fontControlsEl) {
fontControlsEl.style.display = showFontControls ? '' : 'none';
}
if (systemStatsEl) {
systemStatsEl.style.display = showSystemStats ? '' : 'none';
}
if (tokenCountEl) {
tokenCountEl.style.display = showTokenCount ? '' : 'none';
}
// After the System Stats visibility above: whether WS joins the stats pill
// depends on the pill being shown.
this.applyHeaderStatsStyle({
style: compactHeader || this.isSoloWindow ? 'classic' : this.resolveHeaderStatsStyle(settings),
showSystemStats,
});
// Hide lifecycle log button when setting is disabled
// Default OFF: the lifecycle-log document icon is opt-in; the default header
// keeps only WS/CPU/MEM, the file-viewer folder, usage chips, and the gear.
const showLifecycleLog = settings.showLifecycleLog ?? defaults.showLifecycleLog ?? false;
const lifecycleBtn = document.querySelector('.btn-lifecycle-log');
if (lifecycleBtn) {
lifecycleBtn.style.display = showLifecycleLog ? '' : 'none';
}
// Hide the response viewer (eye) button when setting is disabled.
// Marker class, not inline style — the base rule is display:inline-flex !important.
const showResponseViewer = settings.showResponseViewer ?? defaults.showResponseViewer ?? false;
const responseViewerBtn = document.querySelector('.btn-response-viewer-header');
if (responseViewerBtn) {
responseViewerBtn.classList.toggle('btn-response-viewer-header--hidden', !showResponseViewer);
}
// Hide the attachments (history) button when disabled. Opt-in, default OFF —
// marker class, base is display:inline-flex !important.
const showAttachmentsButton = settings.showAttachmentsButton ?? defaults.showAttachmentsButton ?? false;
const attachmentsBtn = document.getElementById('attachmentsHistoryBtn');
if (attachmentsBtn) {
attachmentsBtn.classList.toggle('btn-attachments-history--hidden', !showAttachmentsButton);
}
// File Viewer header button — opt-in, default OFF. Marker class (base is
// display:inline-flex !important); clicking it toggles the file browser panel.
// Default ON (desktop): the folder button is part of the standard header now;
// phones still hide it via mobile.css (btn-file-viewer in the phone-hidden set).
const showFileViewerButton = settings.showFileViewerButton ?? defaults.showFileViewerButton ?? true;
const fileViewerBtn = document.querySelector('.btn-file-viewer');
if (fileViewerBtn) {
fileViewerBtn.classList.toggle('btn-file-viewer--hidden', !showFileViewerButton);
}
// Multi-monitor button — hidden by default (App Settings → Display → "Header
// Displays"). The server renders the correct initial state on every reload;
// this handles a live toggle from a settings save (no reload). Toggle the
// marker class (matches the server-side reveal) rather than an inline style.
const showMultiMonitorButton = settings.showMultiMonitorButton ?? defaults.showMultiMonitorButton ?? false;
const multiMonitorBtn = document.querySelector('.btn-multimonitor');
if (multiMonitorBtn) {
multiMonitorBtn.classList.toggle('btn-multimonitor--hidden', !showMultiMonitorButton);
}
// Split button — hidden by default, and hard-gated to desktop widths
// regardless of the setting (window.CodemanSplitPane.SPLIT_PANE_MIN_WIDTH,
// matching HOME_SESSIONS_MIN_WIDTH's JS-check + media-query-backstop
// pattern — the CSS in styles.css is the backstop, this is the check).
const showSplitButton = settings.showSplitButton ?? defaults.showSplitButton ?? false;
this._applySplitButtonVisibility?.(showSplitButton);
// Tiles button: same gate and backstop as Split (tile-grid.js).
const showTileGridButton = settings.showTileGridButton ?? defaults.showTileGridButton ?? true;
this._applyTileGridButtonVisibility?.(showTileGridButton);
// Detach Tiles changes what a tile's header does (and says): repaint the handles.
this._renderTileChrome?.();
// Ultracode/Workflow agents launcher — hidden by default; reveal when enabled.
// Marker class only (base is display:inline-flex !important) so it's auto-excluded
// from the mobile-header-buttons-policy guard.
const showUltracodeAgents = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false;
const ultracodeBtn = document.querySelector('.btn-ultracode-agents');
if (ultracodeBtn) {
ultracodeBtn.classList.toggle('btn-ultracode-agents--hidden', !showUltracodeAgents);
}
// Read My Mind 🧠 — hidden unless the synced opt-in `readMyMindEnabled` is
// ON (only an explicit true enables, mirroring the Approvals bell). Marker
// class (base is display:inline-flex !important); phones hide it in
// mobile.css regardless (their surface is the keyboard-accessory 🧠 key,
// re-synced right below).
const readMyMindBtn = document.querySelector('.btn-readmymind');
if (readMyMindBtn) {
readMyMindBtn.classList.toggle('btn-readmymind--hidden', settings.readMyMindEnabled !== true);
}
// The accessory-bar 🧠 key shares the setting; its marker class lives on
// the bar element (keyboard-accessory.js), so a live toggle from a
// settings save reveals/hides it without a reload.
if (typeof KeyboardAccessoryBar !== 'undefined') KeyboardAccessoryBar.syncReadMyMind?.();
// Plan-usage chip — shown by default on desktop, OFF on handhelds (App
// Settings → Display → "Plan Usage Limits"). The template always ships it
// hidden because display is per-device and the server cannot know a
// localStorage value, so THIS is what reveals it on every load as well as
// on a live toggle. Marker class (base is display:inline-flex !important),
// matching the response-viewer/multimonitor pattern.
const showPlanUsageLimits = this.planUsageChipEnabled(settings);
const planUsageChip = document.getElementById('planUsageChip');
if (planUsageChip) {
planUsageChip.classList.toggle('header-plan-usage--hidden', !showPlanUsageLimits);
}
const showRedrawButton = settings.showRedrawButton ?? defaults.showRedrawButton ?? false;
const redrawBtn = document.querySelector('.btn-redraw-terminal');
if (redrawBtn) {
redrawBtn.classList.toggle('btn-redraw-terminal--hidden', !showRedrawButton);
}
// Session Manager button — opt-in, hidden by default (App Settings → Display).
// Marker class (base is display:inline-flex !important); phones keep it hidden
// via mobile.css regardless. Sessions stay reachable via the Ctrl+K palette.
const showSessionButton = settings.showSessionButton ?? defaults.showSessionButton ?? false;
const sessionBtn = document.querySelector('.btn-session-manager');
if (sessionBtn) {
sessionBtn.classList.toggle('btn-session-manager--hidden', !showSessionButton);
}
// Away Digest button — opt-in, hidden by default. Same marker pattern.
const showAwayDigestButton = settings.showAwayDigestButton ?? defaults.showAwayDigestButton ?? false;
const awayDigestBtn = document.querySelector('.btn-away-digest');
if (awayDigestBtn) {
awayDigestBtn.classList.toggle('btn-away-digest--hidden', !showAwayDigestButton);
}
// Cron button (footer toolbar) — opt-in, hidden by default. Same marker pattern.
const showCronButton = settings.showCronButton ?? defaults.showCronButton ?? false;
const cronBtn = document.querySelector('.btn-cron');
if (cronBtn) {
cronBtn.classList.toggle('btn-cron--hidden', !showCronButton);
}
// Bottom-bar Git indicator (git-status-ui.js): opt-in, per-device. Starts or stops its poll to
// match the setting, so a live toggle needs no reload.
this.applyGitStatusVisibility?.();
// Header Edit history button (edit-history-ui.js): opt-in, per-device, marker-class hidden.
this.applyEditHistoryVisibility?.();
// Notification bell is retired (notifications live in Settings → Notifications
// + the drawer); keep it hidden regardless of the notification-enabled state.
const notifBtn = document.querySelector('.btn-notifications');
if (notifBtn) {
notifBtn.style.display = 'none';
}
// Close the drawer if notifications got disabled while it's open
const notifEnabled = this.notificationManager?.preferences?.enabled ?? true;
if (!notifEnabled) {
const drawer = document.getElementById('notifDrawer');
if (drawer) drawer.classList.remove('open');
}
},
applyTabOrientation(options = {}) {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
const sidebarOwnsTabs = this.isSessionSidebarActive?.() === true;
const orientation =
!this.isSoloWindow && !sidebarOwnsTabs && window.CodemanTabOverflow?.resolveTabOrientation
? window.CodemanTabOverflow.resolveTabOrientation({
deviceType: MobileDetection.getDeviceType(),
setting: settings.tabOrientation ?? defaults.tabOrientation ?? 'horizontal',
})
: 'horizontal';
// The search box lives in the rail: a search left applied after the list
// moves out would hide tabs with no box to clear it from.
if (orientation !== 'vertical' && this._tabRailSearch) this._resetTabRailSearch?.();
const root = document.documentElement;
const previous = root.getAttribute('data-tab-orientation') || 'horizontal';
root.setAttribute('data-tab-orientation', orientation);
// Row detail rides on its OWN attribute, exactly like the sidebar's
// data-sidebar-detail: every html[data-tab-orientation='vertical'] rule in
// styles.css keeps matching both variants untouched, and the gate in app.js
// reads one attribute instead of re-parsing localStorage per tab.
const previousDetail = root.dataset.tabRailDetail || 'rich';
const detail = (settings.tabRailDetail ?? defaults.tabRailDetail ?? 'rich') === 'simple' ? 'simple' : 'rich';
root.dataset.tabRailDetail = detail;
// Row ORDER rides on a third attribute, for the same reason detail rides on
// its own: a sort flip leaves orientation on 'vertical' both times, and the
// order is applied as an inline `order` the render paths emit, not by CSS
// that could just re-match. `isTabRailSorted()` (app.js) reads this.
const previousSort = root.dataset.tabRailSort || 'activity';
const sort = (settings.tabRailSort ?? defaults.tabRailSort ?? 'activity') === 'manual' ? 'manual' : 'activity';
root.dataset.tabRailSort = sort;
// The tab layout rides on a fourth attribute, for the same reason: it is
// applied by the render paths (inline `order` plus headings, or cluster
// boxes), so a flip has to re-render, and the gates in app.js
// (`isTabTriage()`, `isTabClusters()`, `isTabLedger()`) read one attribute
// per pass instead of re-parsing localStorage.
const previousArrangement = root.dataset.tabArrangement || 'state';
const arrangement = this.resolveTabArrangement(settings);
root.dataset.tabArrangement = arrangement;
// Which end the state groups start from; read by _tabTriageLayout().
const previousStateOrder = root.dataset.tabStateOrder || 'urgent-first';
const stateOrder = this.resolveTabStateOrder(settings);
root.dataset.tabStateOrder = stateOrder;
// CLI Logos on Tabs. Unlike the attributes above this one is pure CSS
// (styles.css hides `.tab-harness` and `.home-sessions-harness` under
// html[data-tab-logos='off']), so a flip re-renders nothing and stays out
// of `changed` below: the logo spans are always in the markup. It still
// resizes every agent tab, which the tail of this function settles.
const previousLogos = root.dataset.tabLogos;
const logos = this.tabCliLogosEnabled(settings) ? 'on' : 'off';
root.dataset.tabLogos = logos;
const tabsEl = document.getElementById('sessionTabs');
const rail = document.getElementById('tabRail');
const headerHost = document.getElementById('sessionTabsHost');
if (!sidebarOwnsTabs && tabsEl && rail && headerHost) {
if (orientation === 'vertical') {
if (tabsEl.parentElement !== rail) rail.appendChild(tabsEl);
} else if (tabsEl.parentElement !== headerHost) {
headerHost.appendChild(tabsEl);
}
}
if (tabsEl) {
tabsEl.setAttribute('aria-orientation', sidebarOwnsTabs || orientation === 'vertical' ? 'vertical' : 'horizontal');
}
const settleRailWidth =
options.settleRailWidth === true && (orientation === 'vertical' || previous !== orientation);
this.applyTabRailWidth?.({ settle: settleRailWidth });
const orientationChanged = previous !== orientation;
// A detail flip counts as a change on its own: simple ⟷ detailed leaves the
// orientation on 'vertical' both times, and the stamps line is emitted by
// the row template, not toggled by CSS — same reasoning as the sidebar's
// detail half in applySessionListLayout(). Taller rows also move every
// connector anchored to a tab rect.
const changed = orientationChanged || previousDetail !== detail || previousSort !== sort || previousArrangement !== arrangement || previousStateOrder !== stateOrder;
if (orientationChanged) {
this.updateTabOverflowMode?.();
if (!settleRailWidth) this.syncTerminalGeometry?.();
}
// applyTabWrapSettings() is the ONE owner of tabs-show-folder and is
// rail-aware, so it has to run AFTER the two attributes above — the
// applySessionListLayout() call that precedes this one on the settings-save
// path ran while data-tab-rail-detail still held the old value. It
// re-renders by itself when the folder row appears or disappears, which is
// why the render below is skipped in that case rather than doubled.
const prevTall = this._tallTabsEnabled;
if (changed) this.applyTabWrapSettings?.();
if (changed) {
// Mirror of applyTabWrapSettings()'s OWN render condition, which is
// `prevTallTabs !== undefined && prevTallTabs !== showFolder`: its first
// call ever only establishes the baseline and deliberately renders
// nothing. Reading an undefined previous value as "it rendered" skips
// BOTH renders and leaves the rows stale — reachable whenever this is the
// first call, i.e. when the pre-paint script threw and left the
// attributes on their fallbacks for applyTabOrientation() to correct.
const wrapRendered = prevTall !== undefined && prevTall !== this._tallTabsEnabled;
if (!wrapRendered) this._fullRenderSessionTabs?.();
this._updateConnectionLinesImmediate?.();
this._refreshHomeSessionsIfVisible?.();
} else if (previousLogos !== logos) {
// A logo flip narrows or widens every agent tab with no render behind
// it, so re-take what a render would have: the strip's one-row wrap
// decision and the lines anchored to tab rects (lineage, subagent
// connectors). A header that gains or loses a row resizes the terminal
// container, whose ResizeObserver (terminal-ui.js) owns the PTY geometry.
this.updateTabOverflowMode?.();
this._updateConnectionLinesImmediate?.();
}
// Only detailed rows carry stamps that go stale with no event behind them.
// _fullRenderSessionTabs() settles this too, but applyTabOrientation() runs
// on paths where nothing re-rendered (boot with the layout already applied).
if (this.isRichTabRows?.()) this._startSidebarRichClock?.();
else this._stopSidebarRichClock?.();
},
applyTabWrapSettings() {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
const deviceType = MobileDetection.getDeviceType();
// The left sidebar is one vertical column with its own scroller: there is no
// row to wrap into, and its rows are always tall (name + folder) because that
// is the cheapest way to tell 25 sessions apart. Header strip keeps the old
// rules unchanged. Kept here rather than only in applySessionListLayout() so
// that a stray applyTabWrapSettings() call (this one is invoked from
// saveAppSettings and from the resize path) cannot leave the sidebar wrapped.
// Matches BOTH sidebar variants: isSessionSidebarActive() reads
// data-session-list, which applySessionListLayout() sets to 'sidebar' for
// 'sidebar' and 'sidebar-rich' alike. Row detail rides on a separate
// attribute and has no bearing on wrapping.
const sidebar = this.isSessionSidebarActive?.() === true;
// Two-row tabs disabled on mobile/tablet — not enough screen space
const twoRows = !sidebar && deviceType === 'desktop'
? (settings.tabTwoRows ?? defaults.tabTwoRows ?? false)
: false;
// The DETAILED vertical rail is the third tall-row surface, for the same
// reason as the sidebar: it is a docked column with a row per session, and
// the stamps line below the name says nothing about WHICH project the
// session is in. Read from the applied attribute, which applyTabOrientation()
// has already written (app.js calls it before this).
const railRich = this.isTabRailRich?.() === true;
const showFolder = sidebar || twoRows || railRich;
const prevTallTabs = this._tallTabsEnabled;
this._tallTabsEnabled = showFolder;
const tabsEl = document.getElementById('sessionTabs');
if (tabsEl) {
tabsEl.classList.toggle('tabs-two-rows', twoRows);
tabsEl.classList.toggle('tabs-show-folder', showFolder);
}
// Re-render tabs if folder visibility changed (folder spans are generated in JS)
if (prevTallTabs !== undefined && prevTallTabs !== showFolder) {
this._fullRenderSessionTabs();
}
},
applyMonitorVisibility() {
const settings = this.loadAppSettingsFromStorage();
const defaults = this.getDefaultSettings();
const showMonitor = settings.showMonitor ?? defaults.showMonitor ?? false;
const showSubagents = settings.showSubagents ?? defaults.showSubagents ?? false;
const showFileBrowser = settings.showFileBrowser ?? defaults.showFileBrowser ?? false;
const monitorPanel = document.getElementById('monitorPanel');
if (monitorPanel) {
monitorPanel.style.display = showMonitor ? '' : 'none';
if (showMonitor) {
monitorPanel.classList.add('open');
} else {
monitorPanel.classList.remove('open');
}
}
const subagentsPanel = document.getElementById('subagentsPanel');
if (subagentsPanel) {
if (showSubagents) {
subagentsPanel.classList.remove('hidden');
} else {
subagentsPanel.classList.add('hidden');
}
}
// Ultracode agents panel visibility (SYNCED setting — not in displayKeys)
const showUltracodeAgents = settings.showUltracodeAgents ?? defaults.showUltracodeAgents ?? false;
const ultracodePanel = document.getElementById('ultracodeAgentsPanel');
if (ultracodePanel) {
if (showUltracodeAgents) {
ultracodePanel.classList.remove('hidden');
} else {
ultracodePanel.classList.remove('open');
ultracodePanel.classList.add('hidden');
}
}
// Floating ultracode run windows have their OWN opt-in (default OFF), independent of the
// docked panel above: pop active runs when enabled, tear them all down when disabled
// (additional layer — ultracode-windows.js).
const ultracodeFloatingWindows = settings.ultracodeFloatingWindows ?? defaults.ultracodeFloatingWindows ?? false;
if (ultracodeFloatingWindows) {
if (typeof this.syncAllUltracodeFloatingWindows === 'function') this.syncAllUltracodeFloatingWindows();
} else if (typeof this.removeAllUltracodeWindows === 'function') {
this.removeAllUltracodeWindows();
}
// File browser panel visibility
const fileBrowserPanel = document.getElementById('fileBrowserPanel');
if (fileBrowserPanel) {
if (showFileBrowser && this.activeSessionId) {
fileBrowserPanel.classList.add('visible');
this.loadFileBrowser(this.activeSessionId);
// Attach drag listeners if not already attached
if (!this.fileBrowserDragListeners) {
const header = fileBrowserPanel.querySelector('.file-browser-header');
if (header) {
// Convert right-positioned to left/top before drag so makeWindowDraggable works
const onFirstDrag = () => {
if (!fileBrowserPanel.style.left) {
const rect = fileBrowserPanel.getBoundingClientRect();
fileBrowserPanel.style.left = `${rect.left}px`;
fileBrowserPanel.style.top = `${rect.top}px`;
fileBrowserPanel.style.right = 'auto';
}
};
header.addEventListener('mousedown', onFirstDrag);
header.addEventListener('touchstart', onFirstDrag, { passive: true });
this.fileBrowserDragListeners = this.makeWindowDraggable(fileBrowserPanel, header);
this.fileBrowserDragListeners._onFirstDrag = onFirstDrag;
}
}
} else if (fileBrowserPanel.classList.contains('visible')) {
this._resetFileBrowserForHide?.();
fileBrowserPanel.classList.remove('visible');
}
}
},
closeMonitor() {
// Hide the monitor panel
const monitorPanel = document.getElementById('monitorPanel');
if (monitorPanel) {
monitorPanel.classList.remove('open');
monitorPanel.style.display = 'none';
}
// Save the setting
const settings = this.loadAppSettingsFromStorage();
settings.showMonitor = false;
this.saveAppSettingsToStorage(settings);
},
closeSubagentsPanel() {
// Hide the subagents panel
const subagentsPanel = document.getElementById('subagentsPanel');
if (subagentsPanel) {
subagentsPanel.classList.remove('open');
subagentsPanel.classList.add('hidden');
}
this.subagentPanelVisible = false;
// Save the setting
const settings = this.loadAppSettingsFromStorage();
settings.showSubagents = false;
this.saveAppSettingsToStorage(settings);
},
async clearAllSubagents() {
const count = this.subagents.size;
if (count === 0) {
this.showToast('No subagents to clear', 'info');
return;
}
if (!confirm(`Clear all ${count} tracked subagent(s)? This removes them from the UI but does not affect running processes.`)) {
return;
}
try {
const res = await fetch('/api/subagents', { method: 'DELETE' });
const data = await res.json();
if (data.success) {
// Clear local state
this.subagents.clear();
this.subagentActivity.clear();
this.subagentToolResults.clear();
// Close any open subagent windows
this.cleanupAllFloatingWindows();
// Update UI
this.renderSubagentPanel();
this.renderMonitorSubagents();
this.updateSubagentBadge();
this.showToast(`Cleared ${data.data.cleared} subagent(s)`, 'success');
} else {
this.showToast('Failed to clear subagents: ' + data.error, 'error');
}
} catch (err) {
this.showToast('Failed to clear subagents', 'error');
}
},
toggleSubagentsPanel() {
const panel = document.getElementById('subagentsPanel');
const toggleBtn = document.getElementById('subagentsToggleBtn');
if (!panel) return;
// If hidden, show it first
if (panel.classList.contains('hidden')) {
panel.classList.remove('hidden');
// Save setting
const settings = this.loadAppSettingsFromStorage();
settings.showSubagents = true;
this.saveAppSettingsToStorage(settings);
}
// Toggle open/collapsed state
panel.classList.toggle('open');
this.subagentPanelVisible = panel.classList.contains('open');
// Update toggle button icon
if (toggleBtn) {
toggleBtn.innerHTML = this.subagentPanelVisible ? '▼' : '▲'; // Down when open, up when collapsed
}
if (this.subagentPanelVisible) {
this.renderSubagentPanel();
}
},
/**
* The per-device DISPLAY keys. They are device-specific (mobile vs desktop) and must not be
* synced from the server, to avoid overriding mobile defaults: loadAppSettingsFromServer()
* seeds one from the server only when this device has no value for it. A non-admin's save in
* multi-user mode reads the same split (_keepServerSyncedSettings()), so the list lives here,
* once, and is there even when GET /api/settings failed at load.
* NOTE: Feature toggles (subagentTrackingEnabled, imageWatcherEnabled, ralphTrackerEnabled)
* are NOT display keys: they control server-side behavior and must sync from server.
*/
_displaySettingKeySet() {
const displayKeys = new Set([
'showFontControls', 'showSystemStats', 'showGpuStats', 'showCpuMhz', 'headerStatsStyle', 'showTokenCount', 'showCost',
'showLifecycleLog', 'showResponseViewer', 'showRedrawButton',
'showMonitor', 'showProjectInsights', 'showFileBrowser', 'showSubagents',
'subagentActiveTabOnly', 'tabTwoRows', 'showTabCliLogos', 'tabOrientation', 'tabRailWidth', 'tabRailDetail', 'tabRailSort', 'tabArrangement', 'tabStateOrder', 'sessionListLayout', 'sessionSidebarFontSize', 'localEchoEnabled', 'keyboardHoldsRows', 'cjkInputEnabled', 'extendedKeyboardBar',
'skin', 'showPlanUsageLimits', 'showAttachmentsButton', 'showFileViewerButton', 'webglRendererEnabled',
'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold',
'language',
'terminalWheelLocalScrollback',
'autoCopySelection', 'copyStripMargin',
'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory',
'showTabDetachButton',
'showTabNewButton',
'mobileOverviewEnabled',
'sessionLineageLines',
'showSplitButton',
'showTileGridButton',
'tileDetachEnabled',
]);
return displayKeys;
},
async loadAppSettingsFromServer(settingsPromise = null) {
// One-time migration: showPlanUsageLimits became a per-device display setting.
// Before this, it synced from the server, so the (separate) mobile settings blob
// may carry a stale `true` the user never enabled on this device. Clear it once
// so mobile defaults to OFF; the desktop blob is untouched and keeps its value.
try {
if (
(MobileDetection.isHandheldDevice?.() ?? MobileDetection.getDeviceType() === 'mobile') &&
!localStorage.getItem('codeman:planUsagePerDeviceMigrated')
) {
const s = this.loadAppSettingsFromStorage();
if (s && s.showPlanUsageLimits) {
s.showPlanUsageLimits = false;
this.saveAppSettingsToStorage(s);
}
localStorage.setItem('codeman:planUsagePerDeviceMigrated', '1');
}
} catch {
/* best-effort migration */
}
try {
const settings = settingsPromise ? await settingsPromise : await fetch('/api/settings').then(r => r.ok ? r.json() : null).then(env => env?.success === true ? env.data : env);
if (settings) {
// Extract notification prefs before merging app settings
const { notificationPreferences, voiceSettings, respawnPresets, runMode, ...appSettings } = settings;
// Display settings are device-specific (mobile vs desktop) and must not be synced
// from the server: see _displaySettingKeySet().
const displayKeys = this._displaySettingKeySet();
// The plan-usage chip is a PER-DEVICE display setting (desktop default ON,
// handheld default OFF): desktop can show it while mobile stays hidden. Drop
// the server's stored value here so it is NEVER seeded into a device that
// didn't explicitly enable it — even though this SAME setting also drives
// server-side telemetry collection now (readPlanUsageTelemetryEnabled in
// hooks-config.ts), that's a read the server does directly from settings.json
// at spawn time; it has nothing to do with what gets merged into THIS
// device's local display preference.
delete appSettings.showPlanUsageLimits;
// Merge settings: non-display keys always sync from server,
// display keys only seed from server when localStorage has no value
// (prevents cross-device overwrite while fixing settings re-enabling on fresh loads)
const localSettings = this.loadAppSettingsFromStorage();
const merged = { ...localSettings };
for (const [key, value] of Object.entries(appSettings)) {
if (displayKeys.has(key)) {
// Display keys: only use server value as initial seed
if (!(key in localSettings)) {
merged[key] = value;
}
} else {
// Non-display keys: server always wins
merged[key] = value;
}
}
// The agent skill is a synced key that is ON when absent (since 1.50.0). A server
// without the key means that default, so this device's own copy goes rather than
// standing in for it: up to 1.49.0 the switch loaded an absent key as off, so a
// device whose save never reached the server still holds `false`, and its next
// Save would write it back. The server's one-time boot migration stores `true` for
// installs that had saved `false` (agent-skill-default-migration.ts).
if (!('agentSkillEnabled' in appSettings)) delete merged.agentSkillEnabled;
this.saveAppSettingsToStorage(merged);
// Apply notification prefs from server if present (only if localStorage has none)
if (notificationPreferences && this.notificationManager) {
const localNotifPrefs = localStorage.getItem(this.notificationManager.getStorageKey());
if (!localNotifPrefs) {
this.notificationManager.preferences =
this.notificationManager.normalizePreferences(notificationPreferences);
this.notificationManager.savePreferences();
}
}
// Sync voice settings from server (seed localStorage if no local API key)
if (voiceSettings) {
const localVoice = localStorage.getItem('codeman-voice-settings');
if (!localVoice || !JSON.parse(localVoice).apiKey) {
VoiceInput._saveDeepgramConfig(voiceSettings);
}
}
// Sync respawn presets from server (server is source of truth)
if (respawnPresets && Array.isArray(respawnPresets)) {
this._serverRespawnPresets = respawnPresets;
// Also update localStorage for offline access
localStorage.setItem('codeman-respawn-presets', JSON.stringify(respawnPresets));
} else if (!this._settingsReadOnly()) {
// Migration: push existing localStorage presets to server. Not for a non-admin in
// multi-user mode: the presets are a server-wide setting there (admin-only PUT).
const localPresets = localStorage.getItem('codeman-respawn-presets');
if (localPresets) {
const parsed = JSON.parse(localPresets);
if (parsed.length > 0) {
this._serverRespawnPresets = parsed;
this._apiPut('/api/settings', { respawnPresets: parsed })
.then((res) => this._noteSettingsWriteRefusal(res))
.catch(() => {});
}
}
}
// Sync run mode from server
if (runMode) {
this.runMode = runMode;
try { localStorage.setItem('codeman_runMode', runMode); } catch {}
this._applyRunMode();
}
// Multi-user non-admin: their own run mode and presets, kept on this device, win over
// the server's just applied (no-op otherwise; `codeman:me` below covers a late role).
this._applyOwnSettings();
return merged;
}
} catch (err) {
console.error('Failed to load settings from server:', err);
}
return this.loadAppSettingsFromStorage();
},
/**
* Load subagent window states from server (or localStorage fallback).
* Called on page load to restore minimized/open window states.
*/
async loadSubagentWindowStates() {
let states = null;
// Try server first for cross-browser sync
try {
const res = await fetch('/api/subagent-window-states');
if (res.ok) {
const env = await res.json();
states = env?.success === true ? env.data : env;
// Also update localStorage
localStorage.setItem('codeman-subagent-window-states', JSON.stringify(states));
}
} catch (err) {
console.error('Failed to load subagent window states from server:', err);
}
// Fallback to localStorage
if (!states) {
try {
const saved = localStorage.getItem('codeman-subagent-window-states');
if (saved) {
states = JSON.parse(saved);
}
} catch (err) {
console.error('Failed to load subagent window states from localStorage:', err);
}
}
return states || { minimized: {}, open: [] };
},
// ═══════════════════════════════════════════════════════════════
// Persistent Parent Associations
// ═══════════════════════════════════════════════════════════════
// This is the ROCK-SOLID system for tracking which tab an agent belongs to.
// Once an agent's parent is discovered, it's saved here PERMANENTLY.
/**
* Save the subagent parent map to localStorage and server.
* Called whenever a new parent association is discovered.
*/
async saveSubagentParentMap() {
const mapData = Object.fromEntries(this.subagentParentMap);
// Save to localStorage for instant recovery
try {
localStorage.setItem('codeman-subagent-parents', JSON.stringify(mapData));
} catch (err) {
console.error('Failed to save subagent parents to localStorage:', err);
}
// Save to server for cross-browser/session persistence
try {
await fetch('/api/subagent-parents', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(mapData)
});
} catch (err) {
console.error('Failed to save subagent parents to server:', err);
}
},
/**
* Load the subagent parent map from server (or localStorage fallback).
* Called once on page load, before any agents are discovered.
*/
async loadSubagentParentMap() {
let mapData = null;
// Try server first (most authoritative)
try {
const res = await fetch('/api/subagent-parents');
if (res.ok) {
const env = await res.json();
mapData = env?.success === true ? env.data : env;
// Update localStorage as cache
localStorage.setItem('codeman-subagent-parents', JSON.stringify(mapData));
}
} catch (err) {
console.error('Failed to load subagent parents from server:', err);
}
// Fallback to localStorage
if (!mapData) {
try {
const saved = localStorage.getItem('codeman-subagent-parents');
if (saved) {
mapData = JSON.parse(saved);
}
} catch (err) {
console.error('Failed to load subagent parents from localStorage:', err);
}
}
// Populate the map (prune stale entries: require both session and agent to exist)
if (mapData && typeof mapData === 'object') {
for (const [agentId, sessionId] of Object.entries(mapData)) {
if (this.sessions.has(sessionId) && this.subagents.has(agentId)) {
this.subagentParentMap.set(agentId, sessionId);
}
}
}
},
/**
* Get the parent session ID for an agent from the persistent map.
* This is the ONLY source of truth for connection lines.
*/
getAgentParentSessionId(agentId) {
return this.subagentParentMap.get(agentId) || null;
},
/**
* Set and persist the parent session ID for an agent.
* Once set, this association is PERMANENT and never recalculated.
*/
setAgentParentSessionId(agentId, sessionId) {
if (!agentId || !sessionId) return;
// Only set if not already set (first association wins)
if (this.subagentParentMap.has(agentId)) {
return; // Already has a parent, don't override
}
this.subagentParentMap.set(agentId, sessionId);
this.saveSubagentParentMap(); // Persist immediately
// Also update the agent object for consistency
const agent = this.subagents.get(agentId);
if (agent) {
agent.parentSessionId = sessionId;
const session = this.sessions.get(sessionId);
if (session) {
agent.parentSessionName = this.getSessionName(session);
}
this.subagents.set(agentId, agent);
}
},
// ═══════════════════════════════════════════════════════════════
// Help Modal
// ═══════════════════════════════════════════════════════════════
showHelp() {
const modal = document.getElementById('helpModal');
modal.classList.add('active');
// Activate focus trap
this.activeFocusTrap = new FocusTrap(modal);
this.activeFocusTrap.activate();
},
closeHelp() {
document.getElementById('helpModal').classList.remove('active');
// Deactivate focus trap and restore focus
if (this.activeFocusTrap) {
this.activeFocusTrap.deactivate();
this.activeFocusTrap = null;
}
},
// ─── Shortcut Settings (App Settings → Shortcuts tab) ────────────────────────
// Renders the list of shortcuts with capture buttons for key rebinding,
// and persists overrides under settings.shortcutOverrides (saved through
// saveAppSettingsToStorage so the device key + settings cache stay coherent).
renderShortcutSettingsList() {
const list = document.getElementById('appSettingsShortcutsList');
if (!list) return;
const registry = this.getShortcutRegistry
? this.getShortcutRegistry()
: typeof DEFAULT_SHORTCUTS !== 'undefined'
? DEFAULT_SHORTCUTS
: [];
const overrides = this.readShortcutOverridesFromSettings();
list.innerHTML = registry
.map((shortcut) => {
const bindingLabel = shortcut.displayBindings
? shortcut.displayBindings.join(' / ')
: (shortcut.bindings || []).map((b) => [...(b.modifiers || []), b.key || b.code || ''].join('+')).join(' / ');
// Only registry entries dispatched through matchesShortcutEvent() are
// configurable; fixed keys (Escape, tab arrows, …) render read-only.
const configurable = !!shortcut.action && Array.isArray(shortcut.bindings);
const overridden = !!overrides[shortcut.id];
const controls = configurable
? `Edit
Reset
`
: '';
return `
${escapeHtml(shortcut.label)}
${controls}
`;
})
.join('');
this._wireShortcutSettingsList(list);
},
// Delegated handlers (no inline onclick — registry ids never land inside a
// JS string context, and the listeners survive re-renders).
_wireShortcutSettingsList(list) {
if (list.dataset.shortcutListenersAdded) return;
list.dataset.shortcutListenersAdded = 'true';
list.addEventListener('click', (e) => {
const btn = e.target?.closest?.('[data-shortcut-action]');
if (!btn) return;
const id = btn.closest?.('[data-shortcut-id]')?.dataset?.shortcutId;
if (!id) return;
if (btn.dataset.shortcutAction === 'capture') this.startShortcutCapture(id);
else if (btn.dataset.shortcutAction === 'reset') this.resetShortcutOverride(id);
});
list.addEventListener('change', (e) => {
const box = e.target;
if (!box?.matches?.('[data-shortcut-action="toggle"]')) return;
const id = box.closest?.('[data-shortcut-id]')?.dataset?.shortcutId;
if (id) this.toggleShortcutEnabled(id, box.checked);
});
},
readShortcutOverridesFromSettings() {
const settings = this.loadAppSettingsFromStorage();
return settings.shortcutOverrides || {};
},
startShortcutCapture(shortcutId) {
const input = document.querySelector(`.shortcut-binding-input[data-id="${shortcutId}"]`);
if (!input) return;
input.value = 'Press keys…';
input.focus();
this._capturingShortcutId = shortcutId;
// Persistent listener (NOT {once}) — the first keydown of a combo like
// Ctrl+Shift+P is the modifier itself ('Control'), which must not end the
// capture. The first non-modifier key completes it.
const onCaptureKeydown = (e) => {
e.preventDefault();
e.stopPropagation();
if (e.key === 'Control' || e.key === 'Shift' || e.key === 'Alt' || e.key === 'Meta') return;
input.removeEventListener('keydown', onCaptureKeydown);
this.onShortcutCaptureKeydown(e, shortcutId);
};
input.addEventListener('keydown', onCaptureKeydown);
},
onShortcutCaptureKeydown(e, shortcutId) {
e.preventDefault();
e.stopPropagation();
this._capturingShortcutId = null;
if (e.key === 'Escape') {
this.renderShortcutSettingsList();
return;
}
// Require a real chord: the dispatcher has no focus-target guard, so a
// bare-key binding would fire while typing in any input.
if (!e.ctrlKey && !e.metaKey && !e.altKey) {
this.renderShortcutSettingsList();
this.showToast?.('Shortcut must include Ctrl, Cmd, or Alt', 'error');
return;
}
// Refuse a chord something else already owns: the registry dispatches the first match,
// so a duplicate would silently take over (or lose to) the other action.
const taken = this.findShortcutConflict(e, shortcutId);
if (taken) {
this.renderShortcutSettingsList();
this.showToast?.(`${this.describeShortcutEvent(e)} is already used by ${taken}`, 'error');
return;
}
const modifiers = [];
if (e.ctrlKey) modifiers.push('ctrl');
if (e.metaKey) modifiers.push('meta');
if (e.shiftKey) modifiers.push('shift');
if (e.altKey) modifiers.push('alt');
const settings = this.loadAppSettingsFromStorage();
const shortcutOverrides = { ...(settings.shortcutOverrides || {}) };
shortcutOverrides[shortcutId] = {
...(shortcutOverrides[shortcutId] || {}),
bindings: [{ modifiers, key: e.key, code: e.code }],
};
settings.shortcutOverrides = shortcutOverrides;
this.saveAppSettingsToStorage(settings);
this.renderShortcutSettingsList();
},
/** Label of the action that already owns the chord in `e`, or '' when it is free. */
findShortcutConflict(e, shortcutId) {
// Chords the keydown handlers claim before (or outside) the registry: they are fixed, so a
// rebind onto one of them would be dead or would hijack it. Alt+1-9 switch tabs by index
// (the document handler does not exclude Cmd); Ctrl/Shift+Enter insert a newline and
// Ctrl/Cmd+V pastes, and the user-bound gate sits above those branches in the xterm handler.
if (e.altKey && !e.ctrlKey && !e.shiftKey && /^Digit[1-9]$/.test(e.code || '')) {
return 'Switch to Tab N';
}
// (Alt+Shift+Enter is the tile grid's Zoom chord, a registry entry, so Alt stays free.)
if (e.key === 'Enter' && !e.altKey && (e.ctrlKey || e.shiftKey)) return 'Insert Newline';
if ((e.ctrlKey || e.metaKey) && !e.altKey && !e.shiftKey && String(e.key).toLowerCase() === 'v') return 'Paste';
if (typeof this.getShortcutRegistry !== 'function' || typeof this.matchesShortcutEvent !== 'function') return '';
const other = this.getShortcutRegistry().find(
(shortcut) =>
shortcut.id !== shortcutId && !shortcut.disabled && Array.isArray(shortcut.bindings) && this.matchesShortcutEvent(e, shortcut)
);
return other ? other.label : '';
},
/**
* Label of the action that already owns a chord in `shortcut`'s bindings, or ''. Used when a
* binding comes back without a capture (re-enable, Reset), where the chord may have been
* given to another action in the meantime.
*/
findShortcutBindingConflict(shortcut) {
for (const binding of shortcut?.bindings || []) {
const mods = binding.modifiers || [];
const taken = this.findShortcutConflict(
{
ctrlKey: mods.includes('ctrl'),
metaKey: mods.includes('meta'),
shiftKey: mods.includes('shift'),
altKey: mods.includes('alt'),
key: binding.key || '',
code: binding.code || '',
},
shortcut.id
);
if (taken) return taken;
}
return '';
},
describeShortcutEvent(e) {
const parts = [];
if (e.ctrlKey) parts.push('Ctrl');
if (e.metaKey) parts.push('Meta');
if (e.shiftKey) parts.push('Shift');
if (e.altKey) parts.push('Alt');
parts.push(e.key && e.key.length === 1 ? e.key.toUpperCase() : e.key || e.code);
return parts.join('+');
},
resetShortcutOverride(shortcutId) {
// Reset puts the default chord back (and re-enables the row): refuse when another action
// has taken that chord since, instead of leaving two actions on one key.
const fallback = typeof DEFAULT_SHORTCUTS !== 'undefined' ? DEFAULT_SHORTCUTS.find((d) => d.id === shortcutId) : null;
const taken = fallback ? this.findShortcutBindingConflict(fallback) : '';
if (taken) {
this.renderShortcutSettingsList();
this.showToast?.(`The default chord is already used by ${taken}`, 'error');
return;
}
const settings = this.loadAppSettingsFromStorage();
const shortcutOverrides = { ...(settings.shortcutOverrides || {}) };
delete shortcutOverrides[shortcutId];
settings.shortcutOverrides = shortcutOverrides;
this.saveAppSettingsToStorage(settings);
this.renderShortcutSettingsList();
},
toggleShortcutEnabled(shortcutId, enabled) {
if (enabled) {
// Re-enabling brings the row's chord back into play: leave it disabled when another action
// has been bound to that chord while it was off.
const shortcut = this.getShortcutRegistry?.().find((s) => s.id === shortcutId);
const taken = this.findShortcutBindingConflict(shortcut);
if (taken) {
this.renderShortcutSettingsList();
this.showToast?.(`Its chord is already used by ${taken}`, 'error');
return;
}
}
const settings = this.loadAppSettingsFromStorage();
const shortcutOverrides = { ...(settings.shortcutOverrides || {}) };
shortcutOverrides[shortcutId] = { ...(shortcutOverrides[shortcutId] || {}), disabled: !enabled };
settings.shortcutOverrides = shortcutOverrides;
this.saveAppSettingsToStorage(settings);
this.renderShortcutSettingsList();
},
closeAllPanels() {
this.closeSessionOptions();
this.closeAppSettings();
this.cancelCloseSession();
this.closeTokenStats();
document.getElementById('monitorPanel').classList.remove('open');
// Collapse subagents panel (don't hide it permanently)
const subagentsPanel = document.getElementById('subagentsPanel');
if (subagentsPanel) {
subagentsPanel.classList.remove('open');
}
this.subagentPanelVisible = false;
},
});
// window.__codemanUser's real role can resolve after settings have already been
// opened once (admin-ui.js fetches /api/me asynchronously and dispatches this on
// arrival), so the Custom Model Endpoints admin gate needs to be re-applied when
// it does, not just when the modal opens. Optional chaining on addEventListener
// itself: several frontend tests (run-mode-ui.test.ts) load this file into a vm
// context with a minimal fake `document` that has no event-target methods at
// all, and a module-level statement that throws there fails the whole file's
// evaluation, not just this feature.
document.addEventListener?.('codeman:me', () => {
// A non-admin's own run mode and respawn presets (multi-user mode) win over the server's,
// which the settings load may already have applied before the role was known.
window.app?._applyOwnSettings?.();
window.app?._applyCustomModelAdminGate?.();
window.app?._applyCliManagementAdminGate?.();
window.app?._applyMcpSyncAdminGate?.();
window.app?._applyDoctorAdminGate?.();
});