Skip to content

Commit 177686f

Browse files
axisrowclaude
andauthored
perf: reduce per-repaint CPU under concurrent sessions (#2)
* perf: cut per-repaint subprocess and module-graph cost (sirmalloc#397) With several concurrent Claude Code sessions every statusline invocation is a fresh process, so per-render fixed costs multiply by session count. - terminal: probe each ancestor with a single `ps -o ppid=,tty=` call instead of two spawns per ancestor; the walk runs per render on macOS where numeric widths are deliberately not persisted - usage-fetch, claude-service-status: load https-proxy-agent (and its transitive graph) on demand, only when a proxy is actually configured Benchmark (13MB transcript, 4 parallel workers x 20 renders via stdin): 27.2 -> 20.6 CPU-seconds total, 0.34 -> 0.26 CPU-s per render (-24%), wall 7.5s -> 5.6s. node --cpu-prof shows the undici/proxy graph gone from startup (compileForInternalLoader 40.7ms -> 7.5ms per render). Co-Authored-By: Claude Code <[email protected]> * fix(review): clarify width-walk invariant and test status-page proxy wiring - terminal: check the ancestor TTY before reassigning pid so each loop iteration reads as "one ps answer, one pid"; no call-order change - claude-service-status: cover the lazy proxy-agent branch with tests (agent attached when HTTPS_PROXY is set, absent otherwise), matching the usage-fetch proxy coverage Co-Authored-By: Claude Code <[email protected]> * fix(terminal): restore walk parity and BSD-safe ps format per verification - ps: use two -o flags instead of the comma list; FreeBSD's parser treats everything after the first '=' as one header, which collapsed the combined form into a single bogus column and dropped the probe to the tput fallback. Still one spawn per ancestor. - walk: start at process.ppid and read each generation's TTY before terminating on its PPID, restoring the old two-spawn walk's generation coverage (1..8) and keeping a dead-end PPID from hiding a valid width on the same ps row. Known narrowing vs the old sequence: if the combined lookup fails entirely, the walk stops (the old two-call flow could still continue on the separately obtained PPID). Co-Authored-By: Claude Code <[email protected]> --------- Co-authored-by: axisrow <[email protected]> Co-authored-by: Claude Code <[email protected]>
1 parent 12ea9e8 commit 177686f

5 files changed

Lines changed: 210 additions & 149 deletions

File tree

‎src/utils/__tests__/claude-service-status.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { EventEmitter } from 'events';
22
import {
3+
afterEach,
34
describe,
45
expect,
56
it
@@ -182,6 +183,54 @@ describe('status page response handling', () => {
182183
});
183184
});
184185

186+
describe('proxy agent wiring', () => {
187+
const ORIGINAL_HTTPS_PROXY = process.env.HTTPS_PROXY;
188+
189+
afterEach(() => {
190+
if (ORIGINAL_HTTPS_PROXY === undefined) {
191+
delete process.env.HTTPS_PROXY;
192+
} else {
193+
process.env.HTTPS_PROXY = ORIGINAL_HTTPS_PROXY;
194+
}
195+
});
196+
197+
function captureRequest(captured: { agent: unknown }): StatusPageRequestFn {
198+
return (options, onResponse) => {
199+
captured.agent = (options as { agent?: unknown }).agent;
200+
const response = Object.assign(new EventEmitter(), {
201+
statusCode: 200,
202+
setEncoding: () => undefined
203+
});
204+
const request = Object.assign(new EventEmitter(), {
205+
destroy: () => undefined,
206+
end() {
207+
onResponse(response);
208+
response.emit('data', 'status body');
209+
response.emit('end');
210+
}
211+
});
212+
213+
return request;
214+
};
215+
}
216+
217+
it('attaches a proxy agent when HTTPS_PROXY is set', async () => {
218+
process.env.HTTPS_PROXY = 'http://proxy.example.test:8080';
219+
const captured: { agent: unknown } = { agent: undefined };
220+
221+
await expect(__testing.fetchStatusPagePath('/test', captureRequest(captured))).resolves.toBe('status body');
222+
expect(captured.agent).toBeTruthy();
223+
});
224+
225+
it('sends no proxy agent without HTTPS_PROXY', async () => {
226+
delete process.env.HTTPS_PROXY;
227+
const captured: { agent: unknown } = { agent: undefined };
228+
229+
await expect(__testing.fetchStatusPagePath('/test', captureRequest(captured))).resolves.toBe('status body');
230+
expect(captured.agent).toBeUndefined();
231+
});
232+
});
233+
185234
describe('claude-status prefetch predicates', () => {
186235
it('detects claude-status widgets in configured lines', () => {
187236
expect(hasClaudeStatusWidgets([[{ id: '1', type: 'model' }]])).toBe(false);

‎src/utils/__tests__/terminal.test.ts‎

Lines changed: 49 additions & 67 deletions
Original file line numberDiff line numberDiff line change
@@ -66,12 +66,8 @@ describe('terminal utils', () => {
6666
it('returns width from the immediate parent tty when available', () => {
6767
pinPosixPlatform();
6868
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
69-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
70-
return '1234\n';
71-
}
72-
73-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
74-
return 'ttys001\n';
69+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
70+
return '1234 ttys001\n';
7571
}
7672

7773
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {
@@ -83,29 +79,24 @@ describe('terminal utils', () => {
8379

8480
expect(getTerminalWidth()).toBe(120);
8581
expect(mockExecFileSync.mock.calls.map(([file, args]) => `${file as string} ${(args as string[]).join(' ')}`)).toEqual([
86-
`ps -o ppid= -p ${process.pid}`,
87-
'ps -o tty= -p 1234',
82+
`ps -o ppid= -o tty= -p ${process.ppid}`,
8883
'stty -F /dev/ttys001 size'
8984
]);
9085
});
9186

9287
it('walks ancestor processes until it finds a valid tty', () => {
9388
pinPosixPlatform();
9489
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
95-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
96-
return '1234\n';
97-
}
98-
99-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
100-
return '??\n';
90+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
91+
return '1234 ?\n';
10192
}
10293

103-
if (file === 'ps' && args.join(' ') === '-o ppid= -p 1234') {
104-
return '5678\n';
94+
if (file === 'ps' && args.join(' ') === '-o ppid= -o tty= -p 1234') {
95+
return '5678 ??\n';
10596
}
10697

107-
if (file === 'ps' && args.join(' ') === '-o tty= -p 5678') {
108-
return ' ttys009 \n';
98+
if (file === 'ps' && args.join(' ') === '-o ppid= -o tty= -p 5678') {
99+
return '1 ttys009\n';
109100
}
110101

111102
if (file === 'stty' && args.join(' ') === '-F /dev/ttys009 size') {
@@ -118,16 +109,31 @@ describe('terminal utils', () => {
118109
expect(getTerminalWidth()).toBe(104);
119110
});
120111

121-
it('falls back through stty variants when the first form returns no value', () => {
112+
it('reads the current generation TTY even when its PPID ends the walk', () => {
122113
pinPosixPlatform();
123-
// Simulates BSD/macOS, where `stty -F` exits with an error; `stty -f` succeeds.
114+
// A PPID of 0 terminates the walk after this row, not before it:
115+
// the parent's own width must still win over the tput fallback.
124116
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
125-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
126-
return '1234\n';
117+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
118+
return '0 ttys001\n';
119+
}
120+
121+
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {
122+
return '24 120\n';
127123
}
128124

129-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
130-
return 'ttys003\n';
125+
throw new Error(`Unexpected command: ${file} ${args.join(' ')}`);
126+
});
127+
128+
expect(getTerminalWidth()).toBe(120);
129+
});
130+
131+
it('falls back through stty variants when the first form returns no value', () => {
132+
pinPosixPlatform();
133+
// Simulates BSD/macOS, where `stty -F` exits with an error; `stty -f` succeeds.
134+
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
135+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
136+
return '1234 ttys003\n';
131137
}
132138

133139
if (file === 'stty' && args.join(' ') === '-F /dev/ttys003 size') {
@@ -154,25 +160,21 @@ describe('terminal utils', () => {
154160
expect(mockExecFileSync.mock.calls[1]?.[1]).toEqual(['cols']);
155161
});
156162

157-
it('returns null when ancestor and fallback probes fail', () => {
163+
it('returns null when ancestor and fallback probes all fail', () => {
158164
pinPosixPlatform();
159165
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
160-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
161-
return '1234\n';
166+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
167+
return '1234 ttys001\n';
162168
}
163169

164-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
165-
return 'ttys001\n';
170+
if (file === 'ps' && args.join(' ') === '-o ppid= -o tty= -p 1234') {
171+
return '0 ttys001\n';
166172
}
167173

168174
if (file === 'stty') {
169175
return 'not-a-number not-a-number\n';
170176
}
171177

172-
if (file === 'ps' && args.join(' ') === '-o ppid= -p 1234') {
173-
return '0\n';
174-
}
175-
176178
if (file === 'tput') {
177179
throw new Error('tput unavailable');
178180
}
@@ -186,20 +188,16 @@ describe('terminal utils', () => {
186188
it('detects availability when an ancestor tty probe succeeds', () => {
187189
pinPosixPlatform();
188190
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
189-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
190-
return '1234\n';
191-
}
192-
193-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
194-
return '??\n';
191+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
192+
return '1234 ?\n';
195193
}
196194

197-
if (file === 'ps' && args.join(' ') === '-o ppid= -p 1234') {
198-
return '5678\n';
195+
if (file === 'ps' && args.join(' ') === '-o ppid= -o tty= -p 1234') {
196+
return '5678 ??\n';
199197
}
200198

201-
if (file === 'ps' && args.join(' ') === '-o tty= -p 5678') {
202-
return 'ttys010\n';
199+
if (file === 'ps' && args.join(' ') === '-o ppid= -o tty= -p 5678') {
200+
return '1 ttys010\n';
203201
}
204202

205203
if (file === 'stty' && args.join(' ') === '-F /dev/ttys010 size') {
@@ -232,12 +230,8 @@ describe('terminal utils', () => {
232230
process.env.CCSTATUSLINE_WIDTH = '0';
233231

234232
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
235-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
236-
return '1234\n';
237-
}
238-
239-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
240-
return 'ttys001\n';
233+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
234+
return '1234 ttys001\n';
241235
}
242236

243237
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {
@@ -255,12 +249,8 @@ describe('terminal utils', () => {
255249
process.env.CCSTATUSLINE_WIDTH = 'wide';
256250

257251
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
258-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
259-
return '1234\n';
260-
}
261-
262-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
263-
return 'ttys001\n';
252+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
253+
return '1234 ttys001\n';
264254
}
265255

266256
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {
@@ -293,12 +283,8 @@ describe('terminal utils', () => {
293283
it('probes only once across repeated calls when a width is found', () => {
294284
pinPosixPlatform();
295285
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
296-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
297-
return '1234\n';
298-
}
299-
300-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
301-
return 'ttys001\n';
286+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
287+
return '1234 ttys001\n';
302288
}
303289

304290
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {
@@ -434,12 +420,8 @@ describe('terminal utils', () => {
434420
it('never persists a discovered numeric width to the L2 cache', () => {
435421
pinPosixPlatform();
436422
mockExecFileSync.mockImplementation((file: string, args: string[]) => {
437-
if (file === 'ps' && args.join(' ') === `-o ppid= -p ${process.pid}`) {
438-
return '1234\n';
439-
}
440-
441-
if (file === 'ps' && args.join(' ') === '-o tty= -p 1234') {
442-
return 'ttys001\n';
423+
if (file === 'ps' && args.join(' ') === `-o ppid= -o tty= -p ${process.ppid}`) {
424+
return '1234 ttys001\n';
443425
}
444426

445427
if (file === 'stty' && args.join(' ') === '-F /dev/ttys001 size') {

‎src/utils/claude-service-status.ts‎

Lines changed: 59 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import * as fs from 'fs';
22
import * as https from 'https';
3-
import { HttpsProxyAgent } from 'https-proxy-agent';
43
import * as os from 'os';
54
import * as path from 'path';
65
import { z } from 'zod';
@@ -282,55 +281,76 @@ type StatusPageRequestFn = (
282281

283282
const requestStatusPage: StatusPageRequestFn = (options, onResponse) => https.request(options, onResponse);
284283

284+
async function getStatusPageRequestOptions(): Promise<https.RequestOptions | null> {
285+
const proxyUrl = getStatusPageProxyUrl();
286+
287+
try {
288+
let agent: https.RequestOptions['agent'] | undefined;
289+
if (proxyUrl) {
290+
// Loaded on demand: the agent (and its transitive module graph) is
291+
// only needed when a proxy is actually configured, and the
292+
// statusline entry point re-runs on every repaint (#397).
293+
const { HttpsProxyAgent: ProxyAgent } = await import('https-proxy-agent');
294+
agent = new ProxyAgent(proxyUrl);
295+
}
296+
297+
return {
298+
hostname: STATUS_HOST,
299+
path: '',
300+
method: 'GET',
301+
timeout: STATUS_TIMEOUT_MS,
302+
...(agent ? { agent } : {})
303+
};
304+
} catch {
305+
return null;
306+
}
307+
}
308+
285309
function fetchStatusPagePath(
286310
pathName: string,
287311
requestFn: StatusPageRequestFn = requestStatusPage
288312
): Promise<string | null> {
289-
return new Promise((resolve) => {
290-
let settled = false;
313+
return getStatusPageRequestOptions().then((baseOptions) => {
314+
if (!baseOptions) {
315+
return null;
316+
}
291317

292-
const finish = (value: string | null) => {
293-
if (settled) {
294-
return;
295-
}
296-
settled = true;
297-
resolve(value);
298-
};
318+
return new Promise<string | null>((resolve) => {
319+
let settled = false;
299320

300-
let requestOptions: https.RequestOptions;
301-
try {
302-
const proxyUrl = getStatusPageProxyUrl();
303-
requestOptions = {
304-
hostname: STATUS_HOST,
305-
path: pathName,
306-
method: 'GET',
307-
timeout: STATUS_TIMEOUT_MS,
308-
...(proxyUrl ? { agent: new HttpsProxyAgent(proxyUrl) } : {})
321+
const finish = (value: string | null) => {
322+
if (settled) {
323+
return;
324+
}
325+
settled = true;
326+
resolve(value);
309327
};
310-
} catch {
311-
finish(null);
312-
return;
313-
}
314328

315-
const request = requestFn(requestOptions, (response) => {
316-
let data = '';
317-
response.setEncoding('utf8');
318-
response.on('data', (chunk: string) => {
319-
data += chunk;
320-
});
321-
response.on('end', () => {
322-
finish(response.statusCode === 200 && data ? data : null);
329+
const requestOptions: https.RequestOptions = {
330+
...baseOptions,
331+
path: pathName
332+
};
333+
334+
const request = requestFn(requestOptions, (response) => {
335+
let data = '';
336+
response.setEncoding('utf8');
337+
response.on('data', (chunk: string) => {
338+
data += chunk;
339+
});
340+
response.on('end', () => {
341+
finish(response.statusCode === 200 && data ? data : null);
342+
});
343+
response.on('aborted', () => { finish(null); });
344+
response.on('error', () => { finish(null); });
323345
});
324-
response.on('aborted', () => { finish(null); });
325-
response.on('error', () => { finish(null); });
326-
});
327346

328-
request.on('error', () => { finish(null); });
329-
request.on('timeout', () => {
330-
request.destroy();
331-
finish(null);
347+
request.on('error', () => { finish(null); });
348+
request.on('timeout', () => {
349+
request.destroy();
350+
finish(null);
351+
});
352+
request.end();
332353
});
333-
request.end();
334354
});
335355
}
336356

0 commit comments

Comments
 (0)