repoburg 1.3.325 → 1.3.327

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,214 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.TelemetryReporter = void 0;
7
+ const fs_1 = __importDefault(require("fs"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const redact_1 = require("./redact");
10
+ const MAX_PENDING = 200;
11
+ const MAX_BATCH = 50;
12
+ /** Below the server's 512 KB body limit. */
13
+ const MAX_BATCH_BYTES = 300 * 1024;
14
+ const MAX_SPOOL_BYTES = 1024 * 1024;
15
+ const REQUEST_TIMEOUT_MS = 10000;
16
+ const LIMITS = { message: 2000, stack: 6000, context: 8000 };
17
+ /**
18
+ * Collects events, merges repeats of one event between two sends (`count`),
19
+ * and sends them in batches. Nothing here throws or logs to the console: a
20
+ * reporter that fails must not create the errors it reports.
21
+ */
22
+ class TelemetryReporter {
23
+ constructor(options) {
24
+ this.options = options;
25
+ this.pending = new Map();
26
+ this.sending = null;
27
+ /** Events dropped because the queue was full (reported with the next batch). */
28
+ this.dropped = 0;
29
+ this.spoolPath = path_1.default.join(options.dir, 'spool.jsonl');
30
+ this.fetchImpl = options.fetchImpl ?? fetch;
31
+ this.now = options.now ?? Date.now;
32
+ }
33
+ /** Redacts and queues an event; repeats before the next send only count. */
34
+ capture(event) {
35
+ try {
36
+ const wire = this.toWire(event);
37
+ const key = [wire.source, wire.kind, wire.route ?? '', wire.message.slice(0, 300)].join('|');
38
+ const existing = this.pending.get(key);
39
+ if (existing) {
40
+ existing.count += 1;
41
+ return;
42
+ }
43
+ if (this.pending.size >= MAX_PENDING) {
44
+ this.dropped += 1;
45
+ return;
46
+ }
47
+ this.pending.set(key, wire);
48
+ }
49
+ catch {
50
+ // Never let reporting break the caller.
51
+ }
52
+ }
53
+ /**
54
+ * For a process about to die (uncaught exception): written to the spool
55
+ * file at once, sent at the next start.
56
+ */
57
+ captureSync(event) {
58
+ try {
59
+ fs_1.default.mkdirSync(this.options.dir, { recursive: true });
60
+ fs_1.default.appendFileSync(this.spoolPath, `${JSON.stringify(this.toWire(event))}\n`);
61
+ }
62
+ catch {
63
+ // Nothing to do: the process is going down.
64
+ }
65
+ }
66
+ /** Sends what is queued and spooled. Failed events are queued again. */
67
+ flush() {
68
+ if (!this.sending) {
69
+ this.sending = this.send().finally(() => {
70
+ this.sending = null;
71
+ });
72
+ }
73
+ return this.sending;
74
+ }
75
+ /** A batch without events: tells the server this install runs (versions in use). */
76
+ async heartbeat() {
77
+ return this.post([]);
78
+ }
79
+ /** Last send before exit; what cannot be sent goes to the spool. */
80
+ async close() {
81
+ await this.flush();
82
+ if (this.pending.size === 0)
83
+ return;
84
+ try {
85
+ fs_1.default.mkdirSync(this.options.dir, { recursive: true });
86
+ const lines = [...this.pending.values()].map((event) => JSON.stringify(event)).join('\n');
87
+ fs_1.default.appendFileSync(this.spoolPath, `${lines}\n`);
88
+ this.pending.clear();
89
+ }
90
+ catch {
91
+ // Lost: the next start begins without them.
92
+ }
93
+ }
94
+ get pendingCount() {
95
+ return this.pending.size;
96
+ }
97
+ toWire(event) {
98
+ const home = this.options.home;
99
+ const clean = (text, max, keepEnd = false) => text ? (keepEnd ? (0, redact_1.tail)((0, redact_1.redact)(text, home), max) : (0, redact_1.head)((0, redact_1.redact)(text, home), max)) : undefined;
100
+ const context = event.context ?? this.options.recentLines?.();
101
+ let extra;
102
+ if (event.extra) {
103
+ extra = JSON.parse((0, redact_1.redact)(JSON.stringify(event.extra), home));
104
+ }
105
+ return {
106
+ source: event.source,
107
+ kind: event.kind,
108
+ ...(event.level ? { level: event.level } : {}),
109
+ message: clean(event.message, LIMITS.message) || '(empty message)',
110
+ ...(event.stack ? { stack: clean(event.stack, LIMITS.stack) } : {}),
111
+ ...(event.route ? { route: event.route } : {}),
112
+ ...(context ? { context: clean(context, LIMITS.context, true) } : {}),
113
+ ...(extra ? { extra } : {}),
114
+ count: 1,
115
+ occurredAt: new Date(this.now()).toISOString(),
116
+ };
117
+ }
118
+ takeSpool() {
119
+ try {
120
+ const stat = fs_1.default.statSync(this.spoolPath);
121
+ const text = stat.size > MAX_SPOOL_BYTES
122
+ ? fs_1.default.readFileSync(this.spoolPath, 'utf8').slice(-MAX_SPOOL_BYTES)
123
+ : fs_1.default.readFileSync(this.spoolPath, 'utf8');
124
+ fs_1.default.unlinkSync(this.spoolPath);
125
+ return text
126
+ .split('\n')
127
+ .filter(Boolean)
128
+ .flatMap((line) => {
129
+ try {
130
+ return [JSON.parse(line)];
131
+ }
132
+ catch {
133
+ return [];
134
+ }
135
+ });
136
+ }
137
+ catch {
138
+ return [];
139
+ }
140
+ }
141
+ async send() {
142
+ const events = [...this.takeSpool(), ...this.pending.values()];
143
+ this.pending.clear();
144
+ if (this.dropped > 0) {
145
+ events.push({
146
+ source: 'daemon',
147
+ kind: 'log',
148
+ level: 'warn',
149
+ message: `telemetry queue full: ${this.dropped} events dropped`,
150
+ count: this.dropped,
151
+ occurredAt: new Date(this.now()).toISOString(),
152
+ });
153
+ this.dropped = 0;
154
+ }
155
+ for (let i = 0; i < events.length;) {
156
+ // Up to 50 events and 300 KB per request.
157
+ let end = i;
158
+ let bytes = 0;
159
+ while (end < events.length && end - i < MAX_BATCH) {
160
+ const size = JSON.stringify(events[end]).length;
161
+ if (end > i && bytes + size > MAX_BATCH_BYTES)
162
+ break;
163
+ bytes += size;
164
+ end++;
165
+ }
166
+ const batch = events.slice(i, end);
167
+ if (!(await this.post(batch))) {
168
+ // Offline or the server refused: keep them for the next send.
169
+ for (const event of events.slice(i)) {
170
+ if (this.pending.size >= MAX_PENDING)
171
+ break;
172
+ const key = [event.source, event.kind, event.route ?? '', event.message.slice(0, 300)].join('|');
173
+ const existing = this.pending.get(key);
174
+ if (existing)
175
+ existing.count += event.count;
176
+ else
177
+ this.pending.set(key, event);
178
+ }
179
+ return;
180
+ }
181
+ i = end;
182
+ }
183
+ }
184
+ async post(events) {
185
+ const headers = { 'Content-Type': 'application/json' };
186
+ try {
187
+ const token = fs_1.default.readFileSync(this.options.tokenPath, 'utf8').trim();
188
+ if (token)
189
+ headers.Authorization = `Bearer ${token}`;
190
+ }
191
+ catch {
192
+ // Not signed in: sent without an account.
193
+ }
194
+ const controller = new AbortController();
195
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
196
+ try {
197
+ const response = await this.fetchImpl(this.options.endpoint, {
198
+ method: 'POST',
199
+ headers,
200
+ body: JSON.stringify({ install: this.options.install, events }),
201
+ signal: controller.signal,
202
+ });
203
+ // 4xx: this batch will never be accepted; drop it rather than retry for ever.
204
+ return response.ok || (response.status >= 400 && response.status < 500);
205
+ }
206
+ catch {
207
+ return false;
208
+ }
209
+ finally {
210
+ clearTimeout(timer);
211
+ }
212
+ }
213
+ }
214
+ exports.TelemetryReporter = TelemetryReporter;
@@ -0,0 +1,105 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.routePattern = routePattern;
4
+ exports.requestWatch = requestWatch;
5
+ /** Paths that may wait long on purpose (a mini app's tool call can block). */
6
+ const LONG_BY_DESIGN = [/^\/api\/apps\/mcp\/call/];
7
+ const MAX_BODY = 4096;
8
+ /**
9
+ * The route of a path, without what differs per call: ids, numbers, long
10
+ * tokens. `/api/sessions/0d3f…/turns` → `/api/sessions/:id/turns`.
11
+ */
12
+ function routePattern(pathname) {
13
+ return pathname
14
+ .split('/')
15
+ .map((segment) => /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(segment) ||
16
+ /^\d+$/.test(segment) ||
17
+ /^[0-9a-f]{8,}$/i.test(segment) ||
18
+ /^[A-Za-z0-9_-]{24,}$/.test(segment)
19
+ ? ':id'
20
+ : segment)
21
+ .join('/');
22
+ }
23
+ /**
24
+ * Express middleware: reports a request that has not started its answer
25
+ * after `slowMs` (the pane hangs: a spinner that never ends, no error
26
+ * anywhere) and an answer with status 5xx, with the start of its body. A
27
+ * streaming answer (headers sent) is never "slow".
28
+ */
29
+ function requestWatch(report, options = {}) {
30
+ const slowMs = options.slowMs ?? 30000;
31
+ const source = options.source ?? 'pane';
32
+ return (req, res, next) => {
33
+ const pathname = (req.originalUrl || req.url).split('?')[0];
34
+ const route = `${req.method} ${routePattern(pathname)}`;
35
+ const started = Date.now();
36
+ let slowReported = false;
37
+ const timer = LONG_BY_DESIGN.some((pattern) => pattern.test(pathname))
38
+ ? null
39
+ : setTimeout(() => {
40
+ if (res.headersSent || res.writableEnded)
41
+ return;
42
+ slowReported = true;
43
+ const waiting = options.pending?.() ?? [];
44
+ report({
45
+ source,
46
+ kind: 'slow_request',
47
+ level: 'error',
48
+ route,
49
+ message: `${route}: no response after ${Math.round(slowMs / 1000)} s`,
50
+ ...(waiting.length > 0 ? { extra: { waitingOn: waiting } } : {}),
51
+ });
52
+ }, slowMs);
53
+ timer?.unref?.();
54
+ // The start of a 5xx body says why (the routes answer { error }).
55
+ const chunks = [];
56
+ let captured = 0;
57
+ const keep = (chunk) => {
58
+ if (captured >= MAX_BODY || chunk === undefined || chunk === null || typeof chunk === 'function')
59
+ return;
60
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));
61
+ chunks.push(buffer.subarray(0, MAX_BODY - captured));
62
+ captured += buffer.length;
63
+ };
64
+ const write = res.write.bind(res);
65
+ const end = res.end.bind(res);
66
+ res.write = ((...args) => {
67
+ if (res.statusCode >= 500)
68
+ keep(args[0]);
69
+ return write(...args);
70
+ });
71
+ res.end = ((...args) => {
72
+ if (res.statusCode >= 500)
73
+ keep(args[0]);
74
+ return end(...args);
75
+ });
76
+ res.once('close', () => {
77
+ if (timer)
78
+ clearTimeout(timer);
79
+ if (res.statusCode < 500)
80
+ return;
81
+ const body = Buffer.concat(chunks).toString('utf8');
82
+ let reason = body;
83
+ try {
84
+ const parsed = JSON.parse(body);
85
+ reason = String(parsed.error ?? parsed.message ?? body);
86
+ }
87
+ catch {
88
+ // Not JSON: the text itself.
89
+ }
90
+ report({
91
+ source,
92
+ kind: 'http_error',
93
+ level: 'error',
94
+ route,
95
+ message: `${route}: ${res.statusCode}${reason ? ` ${reason}` : ''}`,
96
+ extra: {
97
+ status: res.statusCode,
98
+ durationMs: Date.now() - started,
99
+ ...(slowReported ? { wasSlow: true } : {}),
100
+ },
101
+ });
102
+ });
103
+ next();
104
+ };
105
+ }
@@ -0,0 +1,356 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const fs_1 = __importDefault(require("fs"));
7
+ const os_1 = __importDefault(require("os"));
8
+ const path_1 = __importDefault(require("path"));
9
+ const http_1 = __importDefault(require("http"));
10
+ const express_1 = __importDefault(require("express"));
11
+ const redact_1 = require("./redact");
12
+ const reporter_1 = require("./reporter");
13
+ const logCapture_1 = require("./logCapture");
14
+ const pm2Logs_1 = require("./pm2Logs");
15
+ const requestWatch_1 = require("./requestWatch");
16
+ const index_1 = require("./index");
17
+ const inflight_1 = require("./inflight");
18
+ const clientRoute_1 = require("./clientRoute");
19
+ const tmp = () => fs_1.default.mkdtempSync(path_1.default.join(os_1.default.tmpdir(), 'rbtel-'));
20
+ const install = {
21
+ id: '00000000-0000-4000-8000-000000000001',
22
+ channel: 'release',
23
+ version: '1.3.330',
24
+ runtimeVersion: '1.3.330',
25
+ platform: 'darwin',
26
+ arch: 'arm64',
27
+ osVersion: '15.5',
28
+ nodeVersion: '24.22.2',
29
+ };
30
+ describe('redact', () => {
31
+ const home = '/Users/ali';
32
+ it('hides the user name, emails, tokens and keys', () => {
33
+ const text = [
34
+ 'open /Users/ali/projects/x/a.ts failed',
35
+ 'other user /Users/veli/secret.txt',
36
+ 'mail ali@example.com',
37
+ 'Authorization: Bearer abc.def.ghi',
38
+ 'token eyJhbGciOiJFZERTQSJ9.eyJzdWIiOiIxIn0.c2lnbmF0dXJl',
39
+ 'apiKey=sk-or-v1-0123456789abcdef',
40
+ '{"ollamaApiKey":"0f1e2d3c4b5a69788796a5b4c3d2e1f0.AbCdEfGhIjKl"}',
41
+ 'GET https://ollama.com/api/tags?key=secret123',
42
+ 'ghp_abcdefghijklmnopqrstuvwxyz0123',
43
+ ].join('\n');
44
+ const out = (0, redact_1.redact)(text, home);
45
+ expect(out).toContain('open ~/projects/x/a.ts failed');
46
+ expect(out).toContain('/Users/<user>/secret.txt');
47
+ expect(out).toContain('<email>');
48
+ expect(out).toContain('Bearer <redacted>');
49
+ expect(out).toContain('<jwt>');
50
+ expect(out).not.toMatch(/sk-or-v1|0f1e2d3c|secret123|ghp_abc|veli|ali@|abc\.def/);
51
+ expect(out).toContain('https://ollama.com/api/tags?<redacted>');
52
+ });
53
+ it('keeps long paths', () => {
54
+ const line = '~/.repoburg/runtime/versions/1.3.325/app/agent-pane/backend/dist/server.js:12';
55
+ expect((0, redact_1.redact)(line, home)).toBe(line);
56
+ });
57
+ });
58
+ describe('TelemetryReporter', () => {
59
+ function setup(respond = () => 202) {
60
+ const dir = tmp();
61
+ const bodies = [];
62
+ const headers = [];
63
+ const fetchImpl = (async (_url, init) => {
64
+ const body = JSON.parse(String(init.body));
65
+ bodies.push(body);
66
+ headers.push(init.headers);
67
+ return new Response(null, { status: respond(body) });
68
+ });
69
+ const reporter = new reporter_1.TelemetryReporter({
70
+ endpoint: 'https://example.test/telemetry/events',
71
+ install,
72
+ dir,
73
+ tokenPath: path_1.default.join(dir, 'token.jwt'),
74
+ recentLines: () => 'line one\nline two',
75
+ home: '/Users/ali',
76
+ fetchImpl,
77
+ });
78
+ return { dir, bodies, headers, reporter };
79
+ }
80
+ const event = {
81
+ source: 'pane',
82
+ kind: 'slow_request',
83
+ route: 'GET /api/providers/:id/inference',
84
+ message: 'GET /api/providers/:id/inference: no response after 30 s',
85
+ };
86
+ it('merges repeats, adds the recent lines and redacts', async () => {
87
+ const { reporter, bodies, headers } = setup();
88
+ reporter.capture(event);
89
+ reporter.capture(event);
90
+ reporter.capture({ source: 'daemon', kind: 'error', message: 'open /Users/ali/x failed' });
91
+ await reporter.flush();
92
+ expect(bodies).toHaveLength(1);
93
+ expect(bodies[0].install).toEqual(install);
94
+ expect(bodies[0].events).toEqual([
95
+ expect.objectContaining({ kind: 'slow_request', count: 2, context: 'line one\nline two' }),
96
+ expect.objectContaining({ kind: 'error', message: 'open ~/x failed', count: 1 }),
97
+ ]);
98
+ expect(headers[0].Authorization).toBeUndefined();
99
+ });
100
+ it('sends the device token when the machine is signed in', async () => {
101
+ const { reporter, dir, headers } = setup();
102
+ fs_1.default.writeFileSync(path_1.default.join(dir, 'token.jwt'), 'device-token\n');
103
+ reporter.capture(event);
104
+ await reporter.flush();
105
+ expect(headers[0].Authorization).toBe('Bearer device-token');
106
+ });
107
+ it('keeps events when the server cannot be reached, drops them on 4xx', async () => {
108
+ let status = 503;
109
+ const { reporter, bodies } = setup(() => status);
110
+ reporter.capture(event);
111
+ await reporter.flush();
112
+ expect(reporter.pendingCount).toBe(1);
113
+ status = 400;
114
+ await reporter.flush();
115
+ expect(reporter.pendingCount).toBe(0);
116
+ expect(bodies).toHaveLength(2);
117
+ });
118
+ it('sends a crash written to the spool at the next start', async () => {
119
+ const { reporter, dir, bodies } = setup();
120
+ reporter.captureSync({ source: 'daemon', kind: 'uncaught', message: 'boom' });
121
+ expect(fs_1.default.readFileSync(path_1.default.join(dir, 'spool.jsonl'), 'utf8')).toContain('boom');
122
+ await reporter.flush();
123
+ expect(bodies[0].events[0]).toMatchObject({ kind: 'uncaught', message: 'boom' });
124
+ expect(fs_1.default.existsSync(path_1.default.join(dir, 'spool.jsonl'))).toBe(false);
125
+ });
126
+ it('spools what it could not send on close', async () => {
127
+ const { reporter, dir } = setup(() => 503);
128
+ reporter.capture(event);
129
+ await reporter.close();
130
+ expect(fs_1.default.readFileSync(path_1.default.join(dir, 'spool.jsonl'), 'utf8')).toContain('slow_request');
131
+ });
132
+ it('keeps each request under the size limit', async () => {
133
+ const { reporter, bodies } = setup();
134
+ const big = 'some log text '.repeat(500);
135
+ for (let i = 0; i < 40; i++) {
136
+ reporter.capture({ source: 'daemon', kind: 'error', message: `e${i}`, stack: big, context: big });
137
+ }
138
+ await reporter.flush();
139
+ expect(bodies.length).toBeGreaterThan(1);
140
+ for (const body of bodies)
141
+ expect(JSON.stringify(body).length).toBeLessThan(512 * 1024);
142
+ expect(bodies.flatMap((b) => b.events)).toHaveLength(40);
143
+ });
144
+ it('splits large queues into batches of 50', async () => {
145
+ const { reporter, bodies } = setup();
146
+ for (let i = 0; i < 120; i++)
147
+ reporter.capture({ source: 'daemon', kind: 'error', message: `e${i}` });
148
+ await reporter.flush();
149
+ expect(bodies.map((b) => b.events.length)).toEqual([50, 50, 20]);
150
+ });
151
+ });
152
+ describe('captureConsole', () => {
153
+ it('buffers every line and reports console.error, not its own output', () => {
154
+ const buffer = new logCapture_1.LineBuffer(100);
155
+ const events = [];
156
+ const spy = jest.spyOn(process.stdout, 'write').mockImplementation(() => true);
157
+ const errSpy = jest.spyOn(process.stderr, 'write').mockImplementation(() => true);
158
+ const undo = (0, logCapture_1.captureConsole)(buffer, (event) => {
159
+ events.push(event);
160
+ console.log('inside the reporter');
161
+ });
162
+ try {
163
+ console.log('starting');
164
+ console.error('[agentPane] embed failed:', new Error('no dist'));
165
+ }
166
+ finally {
167
+ undo();
168
+ spy.mockRestore();
169
+ errSpy.mockRestore();
170
+ }
171
+ expect(buffer.recent()).toMatch(/LOG starting/);
172
+ expect(buffer.recent()).not.toMatch(/inside the reporter/);
173
+ expect(events).toHaveLength(1);
174
+ expect(events[0]).toMatchObject({ kind: 'error', message: '[agentPane] embed failed: no dist' });
175
+ expect(events[0].stack).toMatch(/Error: no dist/);
176
+ });
177
+ });
178
+ describe('pm2 error logs', () => {
179
+ it('groups stack lines with their entry and drops Node.js noise', () => {
180
+ const text = [
181
+ '2026-11-19 19:00:00 +03:00: [Nest] 123 - ERROR [ExceptionsHandler] SQLITE_BUSY: database is locked',
182
+ 'Error: SQLITE_BUSY: database is locked',
183
+ ' at Database.run (/x/db.js:1:1)',
184
+ '2026-11-19 19:00:01 +03:00: (node:1) ExperimentalWarning: something',
185
+ '2026-11-19 19:00:02 +03:00: second problem',
186
+ ].join('\n');
187
+ expect((0, pm2Logs_1.splitEntries)(text)).toEqual([
188
+ {
189
+ message: '[Nest] 123 - ERROR [ExceptionsHandler] SQLITE_BUSY: database is locked',
190
+ rest: 'Error: SQLITE_BUSY: database is locked\n at Database.run (/x/db.js:1:1)',
191
+ },
192
+ { message: 'second problem', rest: '' },
193
+ ]);
194
+ });
195
+ it('follows new lines only, across restarts', () => {
196
+ const dir = tmp();
197
+ const logs = path_1.default.join(dir, 'logs');
198
+ fs_1.default.mkdirSync(logs);
199
+ const errLog = path_1.default.join(logs, 'mf-error.log');
200
+ fs_1.default.writeFileSync(errLog, '2026-11-19 19:00:00 +03:00: old line\n');
201
+ fs_1.default.writeFileSync(path_1.default.join(logs, 'mf-out.log'), '2026-11-19 19:00:00 +03:00: [Nest] started\n');
202
+ const offsets = path_1.default.join(dir, 'offsets.json');
203
+ const events = [];
204
+ const watcher = new pm2Logs_1.Pm2LogWatcher(logs, offsets, (event) => events.push(event));
205
+ watcher.scan();
206
+ expect(events).toHaveLength(0);
207
+ fs_1.default.appendFileSync(errLog, '2026-11-19 19:01:00 +03:00: new failure\n');
208
+ watcher.scan();
209
+ expect(events).toEqual([
210
+ expect.objectContaining({
211
+ source: 'backend',
212
+ message: 'new failure',
213
+ context: '[Nest] started\n',
214
+ extra: { service: 'mf' },
215
+ }),
216
+ ]);
217
+ const again = new pm2Logs_1.Pm2LogWatcher(logs, offsets, (event) => events.push(event));
218
+ again.scan();
219
+ expect(events).toHaveLength(1);
220
+ });
221
+ });
222
+ describe('requestWatch', () => {
223
+ async function serve(handler, slowMs) {
224
+ const events = [];
225
+ const app = (0, express_1.default)();
226
+ app.use('/api', (0, requestWatch_1.requestWatch)((event) => events.push(event), { slowMs }));
227
+ app.all('/api/*', handler);
228
+ const server = http_1.default.createServer(app);
229
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
230
+ const port = server.address().port;
231
+ return { events, server, url: `http://127.0.0.1:${port}` };
232
+ }
233
+ it('names routes without ids', () => {
234
+ expect((0, requestWatch_1.routePattern)('/api/sessions/0d3f8c2e-1b2a-4c3d-9e8f-001122334455/turns/12')).toBe('/api/sessions/:id/turns/:id');
235
+ expect((0, requestWatch_1.routePattern)('/api/providers/repoburg/inference')).toBe('/api/providers/repoburg/inference');
236
+ });
237
+ it('reports a request that does not answer in time', async () => {
238
+ const { events, server, url } = await serve((_req, res) => {
239
+ setTimeout(() => res.json({ ok: true }), 120);
240
+ }, 30);
241
+ try {
242
+ await fetch(`${url}/api/providers/repoburg/inference?cwd=/Users/ali/x`);
243
+ }
244
+ finally {
245
+ server.close();
246
+ }
247
+ expect(events).toEqual([
248
+ expect.objectContaining({
249
+ kind: 'slow_request',
250
+ route: 'GET /api/providers/repoburg/inference',
251
+ message: 'GET /api/providers/repoburg/inference: no response after 0 s',
252
+ }),
253
+ ]);
254
+ });
255
+ it('reports a 5xx answer with its reason', async () => {
256
+ const { events, server, url } = await serve((_req, res) => {
257
+ res.status(500).json({ error: 'codex app-server exited' });
258
+ }, 1000);
259
+ try {
260
+ await fetch(`${url}/api/codex-sessions?workspace=/tmp/x`);
261
+ await new Promise((resolve) => setTimeout(resolve, 20));
262
+ }
263
+ finally {
264
+ server.close();
265
+ }
266
+ expect(events).toEqual([
267
+ expect.objectContaining({
268
+ kind: 'http_error',
269
+ route: 'GET /api/codex-sessions',
270
+ message: 'GET /api/codex-sessions: 500 codex app-server exited',
271
+ }),
272
+ ]);
273
+ });
274
+ it('leaves fast and long-by-design requests alone', async () => {
275
+ const { events, server, url } = await serve((req, res) => {
276
+ setTimeout(() => res.json({ ok: true }), req.path.includes('mcp') ? 80 : 0);
277
+ }, 30);
278
+ try {
279
+ await fetch(`${url}/api/sessions`);
280
+ await fetch(`${url}/api/apps/mcp/call`, { method: 'POST' });
281
+ }
282
+ finally {
283
+ server.close();
284
+ }
285
+ expect(events).toEqual([]);
286
+ });
287
+ });
288
+ describe('trackFetches', () => {
289
+ it('lists the outgoing calls still waiting, longest first, without query', async () => {
290
+ const hang = http_1.default.createServer(() => undefined);
291
+ await new Promise((resolve) => hang.listen(0, '127.0.0.1', resolve));
292
+ const port = hang.address().port;
293
+ const tracker = (0, inflight_1.trackFetches)((url) => url.includes('/telemetry/events'));
294
+ const controller = new AbortController();
295
+ try {
296
+ const call = fetch(`http://127.0.0.1:${port}/llm-provider/inference-providers?cwd=/Users/ali/x`, {
297
+ signal: controller.signal,
298
+ }).catch(() => undefined);
299
+ await new Promise((resolve) => setTimeout(resolve, 50));
300
+ expect(tracker.pending()).toEqual([
301
+ { method: 'GET', target: `http://127.0.0.1:${port}/llm-provider/inference-providers`, seconds: 0 },
302
+ ]);
303
+ controller.abort();
304
+ await call;
305
+ expect(tracker.pending()).toEqual([]);
306
+ }
307
+ finally {
308
+ tracker.undo();
309
+ hang.closeAllConnections();
310
+ hang.close();
311
+ }
312
+ });
313
+ });
314
+ describe('client errors route', () => {
315
+ it('turns a frontend error into an event', async () => {
316
+ const events = [];
317
+ const app = (0, express_1.default)();
318
+ app.use(express_1.default.json());
319
+ app.use('/telemetry', (0, clientRoute_1.createClientErrorRouter)((event) => events.push(event)));
320
+ const server = http_1.default.createServer(app);
321
+ await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
322
+ const port = server.address().port;
323
+ try {
324
+ const response = await fetch(`http://127.0.0.1:${port}/telemetry/client`, {
325
+ method: 'POST',
326
+ headers: { 'Content-Type': 'application/json' },
327
+ body: JSON.stringify({ message: "Cannot read properties of undefined (reading 'id')", stack: 'at x', page: '/s/1', type: 'error' }),
328
+ });
329
+ expect(response.status).toBe(204);
330
+ }
331
+ finally {
332
+ server.close();
333
+ }
334
+ expect(events).toEqual([
335
+ expect.objectContaining({ source: 'frontend', kind: 'client_error', extra: { page: '/s/1', type: 'error' } }),
336
+ ]);
337
+ });
338
+ });
339
+ describe('telemetryEnabled and channelOf', () => {
340
+ it('is off under jest, by env and by config', () => {
341
+ const home = tmp();
342
+ expect((0, index_1.telemetryEnabled)({ JEST_WORKER_ID: '1' }, home)).toBe(false);
343
+ expect((0, index_1.telemetryEnabled)({ REPOBURG_TELEMETRY: '0' }, home)).toBe(false);
344
+ expect((0, index_1.telemetryEnabled)({}, home)).toBe(true);
345
+ fs_1.default.mkdirSync(path_1.default.join(home, '.repoburg'));
346
+ fs_1.default.writeFileSync(path_1.default.join(home, '.repoburg', 'config.json'), JSON.stringify({ telemetry: false }));
347
+ expect((0, index_1.telemetryEnabled)({}, home)).toBe(false);
348
+ });
349
+ it('calls a git checkout dev and an install release', () => {
350
+ const checkout = tmp();
351
+ fs_1.default.mkdirSync(path_1.default.join(checkout, '.git'));
352
+ expect((0, index_1.channelOf)(checkout, {})).toBe('dev');
353
+ expect((0, index_1.channelOf)(tmp(), {})).toBe('release');
354
+ expect((0, index_1.channelOf)(checkout, { REPOBURG_TELEMETRY_CHANNEL: 'release' })).toBe('release');
355
+ });
356
+ });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "repoburg",
3
- "version": "1.3.325",
3
+ "version": "1.3.327",
4
4
  "description": "A local AI-powered software developer assistant that runs on your own machine.",
5
5
  "author": "Celal Ertug",
6
6
  "license": "SEE LICENSE IN LICENSE",