feat(sidebar): add a terminal text-size picker to the toolbar

The sidebar terminal toolbar gets an XS-XL text-size picker beside
Restart. SM (13px) stays the default, so nothing changes until a user
picks a size; the choice persists in chrome.storage.local and applies
to the live terminal, re-fitting xterm and re-sending the PTY size two
frames later so the new character cell is measured first.

A VM test runs the real sidepanel-terminal.js through one auto-connect
and checks the creation size, the stored-size fallback, persistence and
the live resize.

Co-authored-by: Yotam <yotsurfing@gmail.com>
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
committed 2026-10-08 14:55:21 +00:00
1 parent b150736602
commit 6b9d1e6927
4 files changed
+225 -2

No files matched your search

+147
View File
@@ -0,0 +1,147 @@
import { describe, test, expect } from 'bun:test';
import * as fs from 'fs';
import * as path from 'path';
import * as vm from 'vm';
// Sidebar terminal text-size picker. Runs the real sidepanel-terminal.js in a
// VM with a fake DOM, xterm, WebSocket and chrome.storage, drives one
// auto-connect to a live terminal, and checks the size the terminal is created
// with, what persists, and that a live change re-fits and resizes the PTY.
const TERMINAL_JS = path.resolve(
import.meta.path, '..', '..', '..', 'extension', 'sidepanel-terminal.js',
);
const SIDEPANEL_HTML = path.resolve(
import.meta.path, '..', '..', '..', 'extension', 'sidepanel.html',
);
function fakeElement() {
const listeners: Record<string, Array<(e: unknown) => void>> = {};
const el: any = {
style: {},
textContent: '',
value: '',
classList: { add() {}, remove() {}, contains: () => false },
addEventListener(type: string, fn: (e: unknown) => void) { (listeners[type] ||= []).push(fn); },
dispatch(type: string) { for (const fn of listeners[type] || []) fn({ target: el }); },
};
return el;
}
async function bootSidebar(stored: Record<string, unknown>) {
const elements = new Map<string, any>();
const terminals: any[] = [];
const sent: string[] = [];
const frames: Array<() => void> = [];
const store = { ...stored };
class FakeTerminal {
options: Record<string, unknown>;
cols = 80;
rows = 24;
constructor(opts: Record<string, unknown>) {
this.options = { ...opts };
terminals.push(this);
}
loadAddon() {}
open() {}
onData() {}
refresh() {}
}
class FakeWebSocket {
static OPEN = 1;
readyState = 1;
binaryType = '';
send(msg: unknown) { if (typeof msg === 'string') sent.push(msg); }
addEventListener() {}
close() {}
}
const json = (body: unknown) => new Response(JSON.stringify(body), { status: 200 });
const ctx: any = {
console,
TextEncoder,
Response,
document: {
readyState: 'complete',
addEventListener() {},
getElementById(id: string) {
if (!elements.has(id)) elements.set(id, fakeElement());
return elements.get(id);
},
},
Terminal: FakeTerminal,
FitAddon: { FitAddon: class { fit() {} } },
WebSocket: FakeWebSocket,
ResizeObserver: class { observe() {} },
MutationObserver: class { observe() {} },
requestAnimationFrame: (fn: () => void) => { frames.push(fn); return frames.length; },
setTimeout: () => 0,
setInterval: () => 0,
clearInterval() {},
clearTimeout() {},
fetch: async (url: string) =>
url.endsWith('/pty-session')
? json({ terminalPort: 4000, sessionId: 'sess', attachToken: 'tok' })
: json({ available: true }),
chrome: {
storage: {
local: {
get(_keys: string[], cb: (r: Record<string, unknown>) => void) { cb({ ...store }); },
set(items: Record<string, unknown>) { Object.assign(store, items); },
},
},
runtime: { sendMessage() {} },
},
gstackServerPort: 34567,
gstackAuthToken: 'auth',
};
ctx.window = ctx;
vm.runInNewContext(fs.readFileSync(TERMINAL_JS, 'utf-8'), ctx);
for (let i = 0; i < 50 && terminals.length === 0; i++) await new Promise((r) => setImmediate(r));
expect(terminals).toHaveLength(1);
const flushFrames = () => { for (const fn of frames.splice(0)) fn(); };
return { term: terminals[0], picker: elements.get('terminal-fontsize'), store, sent, flushFrames };
}
describe('sidebar terminal text size', () => {
test('defaults to 13px (sm) when nothing is stored', async () => {
const { term, picker } = await bootSidebar({});
expect(term.options.fontSize).toBe(13);
expect(picker.value).toBe('sm');
});
test('creates the terminal at the stored size; an unknown stored value falls back to sm', async () => {
const large = await bootSidebar({ terminalFontSize: 'lg' });
expect(large.term.options.fontSize).toBe(17);
expect(large.picker.value).toBe('lg');
const bogus = await bootSidebar({ terminalFontSize: 'huge' });
expect(bogus.term.options.fontSize).toBe(13);
expect(bogus.picker.value).toBe('sm');
});
test('a live change persists, resizes xterm, and re-sends PTY size after the font re-measures', async () => {
const { term, picker, store, sent, flushFrames } = await bootSidebar({});
flushFrames();
sent.length = 0;
picker.value = 'xl';
picker.dispatch('change');
expect(store.terminalFontSize).toBe('xl');
expect(term.options.fontSize).toBe(20);
expect(sent).toEqual([]);
flushFrames();
flushFrames();
expect(sent.map((m) => JSON.parse(m))).toContainEqual({ type: 'resize', cols: 80, rows: 24 });
});
test('the toolbar picker offers every size with sm preselected', () => {
const html = fs.readFileSync(SIDEPANEL_HTML, 'utf-8');
const select = html.match(/<select id="terminal-fontsize"[\s\S]*?<\/select>/)?.[0] ?? '';
expect([...select.matchAll(/value="(\w+)"/g)].map((m) => m[1])).toEqual(['xs', 'sm', 'md', 'lg', 'xl']);
expect(select).toContain('<option value="sm" selected>');
});
});
+32 -1
View File
@@ -39,8 +39,15 @@
ended: document.getElementById('terminal-ended'),
restart: document.getElementById('terminal-restart'),
restartNow: document.getElementById('terminal-restart-now'),
fontSize: document.getElementById('terminal-fontsize'),
};
// Toolbar text-size picker. 'sm' (13px) stays the default; a picked size
// persists in chrome.storage.local.
const FONT_SIZES = { xs: 11, sm: 13, md: 15, lg: 17, xl: 20 };
const FONT_SIZE_KEY = 'terminalFontSize';
let fontSize = 'sm';
/** State machine. */
const STATE = {
IDLE: 'idle',
@@ -392,7 +399,7 @@
if (term) return;
term = new Terminal({
fontFamily: '"JetBrains Mono", "SF Mono", Menlo, "Noto Sans Mono CJK KR", "Malgun Gothic", monospace',
fontSize: 13,
fontSize: FONT_SIZES[fontSize],
theme: { background: '#0a0a0a', foreground: '#e5e5e5' },
cursorBlink: true,
scrollback: 5000,
@@ -914,6 +921,30 @@
els.restart?.addEventListener('click', forceRestart);
els.restartNow?.addEventListener('click', forceRestart);
// xterm re-measures its character cell on the next render frame, so a
// live size change fits and tells the PTY its new cols/rows two frames
// later; fitting in the same tick reads the old cell size.
const applyFontSize = (size, persist) => {
fontSize = FONT_SIZES[size] ? size : 'sm';
if (els.fontSize) els.fontSize.value = fontSize;
if (persist) {
try { chrome.storage.local.set({ [FONT_SIZE_KEY]: fontSize }); } catch {}
}
if (!term) return;
term.options.fontSize = FONT_SIZES[fontSize];
requestAnimationFrame(() => requestAnimationFrame(() => {
try {
fitAddon && fitAddon.fit();
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }));
}
} catch {}
}));
};
els.fontSize?.addEventListener('change', (e) => applyFontSize(e.target.value, true));
try {
chrome.storage.local.get([FONT_SIZE_KEY], (r) => applyFontSize(r && r[FONT_SIZE_KEY], false));
} catch {}
// Live browser-tab state. background.js → sidepanel.js → us. We
// forward over the live PTY WebSocket; terminal-agent.ts writes
+33
View File
@@ -457,6 +457,39 @@ body::after {
color: #f59e0b;
border-color: #f59e0b;
}
.terminal-toolbar-right {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
}
.terminal-fontsize {
display: flex;
align-items: center;
gap: 3px;
color: #a1a1aa;
font-family: 'JetBrains Mono', monospace;
font-size: 13px;
}
.terminal-fontsize select {
background: #0a0a0a;
color: #a1a1aa;
border: 1px solid #27272a;
border-radius: 3px;
padding: 3px 4px;
font-size: 11px;
font-family: 'JetBrains Mono', monospace;
cursor: pointer;
color-scheme: dark;
}
.terminal-fontsize select:hover {
color: #f59e0b;
border-color: #f59e0b;
}
.terminal-fontsize select:focus-visible {
outline: 2px solid #f59e0b;
outline-offset: 1px;
}
.terminal-bootstrap {
flex: 1;
display: flex;
+13 -1
View File
@@ -30,7 +30,19 @@
<button id="chat-screenshot-btn" class="terminal-toolbar-btn" title="Take a screenshot">📸 Screenshot</button>
<button id="chat-cookies-btn" class="terminal-toolbar-btn" title="Import cookies from your browser">🍪 Cookies</button>
</div>
<button class="terminal-toolbar-btn" id="terminal-restart-now" title="Restart Claude Code session">↻ Restart</button>
<div class="terminal-toolbar-right">
<label class="terminal-fontsize" title="Sidebar text size">
<span aria-hidden="true">A</span>
<select id="terminal-fontsize" aria-label="Sidebar text size">
<option value="xs">XS</option>
<option value="sm" selected>SM</option>
<option value="md">MD</option>
<option value="lg">LG</option>
<option value="xl">XL</option>
</select>
</label>
<button class="terminal-toolbar-btn" id="terminal-restart-now" title="Restart Claude Code session">↻ Restart</button>
</div>
</div>
<div class="terminal-bootstrap" id="terminal-bootstrap">
<div class="terminal-bootstrap-icon">▸</div>