qwenproxy-cli 1.0.0 → 1.0.2

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.
Files changed (109) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +77 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2878 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +259 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/update-cli.ts +121 -0
  105. package/src/utils/context-truncation.ts +84 -84
  106. package/src/utils/json.ts +380 -380
  107. package/src/utils/session-id.ts +37 -37
  108. package/src/utils/tool-call-guard.ts +84 -84
  109. package/src/utils/types.ts +109 -109
@@ -1,413 +1,479 @@
1
- /**
2
- * QwenProxy TUI - Server Logs View (Tab 6)
3
- * Real-time event log viewer with level filtering (All, Warnings, Errors).
4
- */
5
-
6
- import type { TuiView } from "../types.ts";
7
- import type { KeyEvent } from "../screen.ts";
8
- import { theme, drawBox, stringWidth, truncate, pad, stripAnsi, setClipboardText } from "../theme.ts";
9
- import { ServerManager } from "../server-manager.ts";
10
-
11
- export class LogsView implements TuiView {
12
- public readonly id = "logs";
13
- public readonly title = "Logs";
14
- public readonly tabNumber = 6;
15
-
16
- private filter: "all" | "warn" | "error" = "all";
17
- private scrollOffset = 0; // 0 = at the bottom (follow newest)
18
- private hoveredChip: "all" | "warn" | "error" | "copy" | "clear" | null = null;
19
- private selectedLogIndex: number | null = null;
20
- private copyNotification = false;
21
- private copyTimeout: NodeJS.Timeout | null = null;
22
- private lastStartIndex = 0;
23
- private lastVisibleCount = 0;
24
- private lastTotalCount = 0;
25
-
26
- private getChips(rawCount: number): {
27
- titlePrefix: string;
28
- chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }>;
29
- } {
30
- const titlePrefix = `Logs (${rawCount}) `;
31
- const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
32
- const defs = [
33
- { id: "all" as const, label: " [ T ] Todos " },
34
- { id: "warn" as const, label: " [ W ] Avisos " },
35
- { id: "error" as const, label: " [ E ] Erros " },
36
- { id: "copy" as const, label: copyLabel },
37
- { id: "clear" as const, label: " [ C ] Limpar " },
38
- ];
39
-
40
- let currentCol = 4 + stringWidth(titlePrefix);
41
- const chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }> = [];
42
-
43
- for (let i = 0; i < defs.length; i++) {
44
- const d = defs[i];
45
- const w = stringWidth(d.label);
46
- const startCol = currentCol;
47
- const endCol = startCol + w - 1;
48
- chips.push({
49
- id: d.id,
50
- label: d.label,
51
- startCol: startCol - (i === 0 ? 1 : 0),
52
- endCol: endCol + 1,
53
- });
54
- currentCol += w;
55
- }
56
- return { titlePrefix, chips };
57
- }
58
-
59
- public getShortcuts(): Array<{ key: string; label: string }> {
60
- return [
61
- { key: "T", label: "Todos" },
62
- { key: "W", label: "Avisos" },
63
- { key: "E", label: "Erros" },
64
- { key: "Y", label: "Copiar" },
65
- { key: "C", label: "Limpar" },
66
- { key: "↑/↓", label: "Rolar" },
67
- ];
68
- }
69
-
70
- public handleKey(key: KeyEvent): boolean | void {
71
- const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
72
- const { chips } = this.getChips(rawEntries.length);
73
-
74
- // Mouse hover on chips (accepts rows 3 to 5 for generous vertical target)
75
- if (key.name === "hover" && key.mouse && key.mouse.row >= 3 && key.mouse.row <= 5) {
76
- const col = key.mouse.col;
77
- let target: "all" | "warn" | "error" | "copy" | "clear" | null = null;
78
- for (const c of chips) {
79
- if (col >= c.startCol && col <= c.endCol) {
80
- target = c.id;
81
- break;
82
- }
83
- }
84
- if (this.hoveredChip !== target) {
85
- this.hoveredChip = target;
86
- return true;
87
- }
88
- } else if (this.hoveredChip !== null && key.mouse) {
89
- this.hoveredChip = null;
90
- return true;
91
- }
92
-
93
- // Mouse click on chips (accepts rows 3 to 5 for effortless immediate click matching tabs)
94
- if (key.name === "click" && key.mouse && key.mouse.row >= 3 && key.mouse.row <= 5) {
95
- const col = key.mouse.col;
96
- for (const c of chips) {
97
- if (col >= c.startCol && col <= c.endCol) {
98
- if (c.id === "all") {
99
- this.filter = "all";
100
- this.scrollOffset = 0;
101
- this.selectedLogIndex = null;
102
- return true;
103
- }
104
- if (c.id === "warn") {
105
- this.filter = "warn";
106
- this.scrollOffset = 0;
107
- this.selectedLogIndex = null;
108
- return true;
109
- }
110
- if (c.id === "error") {
111
- this.filter = "error";
112
- this.scrollOffset = 0;
113
- this.selectedLogIndex = null;
114
- return true;
115
- }
116
- if (c.id === "copy") {
117
- this.copyLogs();
118
- return true;
119
- }
120
- if (c.id === "clear") {
121
- ServerManager.getInstance().clearLogs();
122
- this.scrollOffset = 0;
123
- this.selectedLogIndex = null;
124
- return true;
125
- }
126
- }
127
- }
128
- }
129
-
130
- // Mouse click on log rows (terminal row 7+, accounting for 2-line top margin)
131
- if (key.name === "click" && key.mouse && key.mouse.row >= 7) {
132
- const rowOffset = key.mouse.row - 7;
133
- if (rowOffset >= 0 && rowOffset < this.lastVisibleCount) {
134
- const clickedIdx = this.lastStartIndex + rowOffset;
135
- if (this.selectedLogIndex === clickedIdx) {
136
- this.selectedLogIndex = null;
137
- } else {
138
- this.selectedLogIndex = clickedIdx;
139
- }
140
- return true;
141
- }
142
- }
143
-
144
- // Filter toggles
145
- if ((key.name === "t" || key.name === "T") && !key.ctrl) {
146
- this.filter = "all";
147
- this.scrollOffset = 0;
148
- this.selectedLogIndex = null;
149
- return true;
150
- }
151
- if ((key.name === "w" || key.name === "W") && !key.ctrl) {
152
- this.filter = "warn";
153
- this.scrollOffset = 0;
154
- this.selectedLogIndex = null;
155
- return true;
156
- }
157
- if ((key.name === "e" || key.name === "E") && !key.ctrl) {
158
- this.filter = "error";
159
- this.scrollOffset = 0;
160
- this.selectedLogIndex = null;
161
- return true;
162
- }
163
-
164
- // Clear logs with 'c'
165
- if ((key.name === "c" || key.name === "C") && !key.ctrl) {
166
- ServerManager.getInstance().clearLogs();
167
- this.scrollOffset = 0;
168
- this.selectedLogIndex = null;
169
- return true;
170
- }
171
-
172
- // Copy logs with 'y' or 'Y'
173
- if ((key.name === "y" || key.name === "Y") && !key.ctrl) {
174
- this.copyLogs();
175
- return true;
176
- }
177
-
178
- // Enter copies selected log if a row is selected
179
- if (key.name === "return" || key.name === "enter") {
180
- if (this.selectedLogIndex !== null) {
181
- this.copyLogs();
182
- return true;
183
- }
184
- }
185
-
186
- // Escape clears log selection
187
- if (key.name === "escape") {
188
- if (this.selectedLogIndex !== null) {
189
- this.selectedLogIndex = null;
190
- return true;
191
- }
192
- }
193
-
194
- // Navigate or scroll up (Up key, k)
195
- if (key.name === "up" || (key.name === "k" && !key.ctrl)) {
196
- if (this.selectedLogIndex !== null) {
197
- this.selectedLogIndex = Math.max(0, this.selectedLogIndex - 1);
198
- if (this.selectedLogIndex < this.lastStartIndex) {
199
- this.scrollOffset = Math.max(0, this.lastTotalCount - this.lastVisibleCount - this.selectedLogIndex);
200
- }
201
- } else {
202
- this.scrollOffset += 1;
203
- }
204
- return true;
205
- }
206
-
207
- // Mouse wheel up
208
- if (key.name === "wheelup") {
209
- this.scrollOffset += 2;
210
- return true;
211
- }
212
-
213
- // Navigate or scroll down (Down key, j)
214
- if (key.name === "down" || (key.name === "j" && !key.ctrl)) {
215
- if (this.selectedLogIndex !== null) {
216
- this.selectedLogIndex = Math.min(this.lastTotalCount - 1, this.selectedLogIndex + 1);
217
- if (this.selectedLogIndex >= this.lastStartIndex + this.lastVisibleCount) {
218
- this.scrollOffset = Math.max(0, this.scrollOffset - 1);
219
- }
220
- } else {
221
- this.scrollOffset = Math.max(0, this.scrollOffset - 1);
222
- }
223
- return true;
224
- }
225
-
226
- // Mouse wheel down
227
- if (key.name === "wheeldown") {
228
- this.scrollOffset = Math.max(0, this.scrollOffset - 2);
229
- return true;
230
- }
231
-
232
- // Page Up / Page Down
233
- if (key.name === "pageup") {
234
- this.scrollOffset += 10;
235
- return true;
236
- }
237
- if (key.name === "pagedown") {
238
- this.scrollOffset = Math.max(0, this.scrollOffset - 10);
239
- return true;
240
- }
241
-
242
- // Home / End
243
- if (key.name === "home") {
244
- this.scrollOffset = 500;
245
- return true;
246
- }
247
- if (key.name === "end") {
248
- this.scrollOffset = 0;
249
- return true;
250
- }
251
- }
252
-
253
- public render(width: number, height: number): string[] {
254
- const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
255
- const contentH = Math.max(8, height);
256
- const innerW = width - 4;
257
-
258
- // Filter Chips in Top Title
259
- const allChip =
260
- this.filter === "all"
261
- ? `\x1b[48;2;45;35;85m\x1b[38;2;247;248;252m [ T ] Todos \x1b[49m\x1b[39m`
262
- : this.hoveredChip === "all"
263
- ? theme.bgHover(" [ T ] Todos ")
264
- : theme.cyan(" [ T ] Todos ");
265
-
266
- const warnChip =
267
- this.filter === "warn"
268
- ? `\x1b[48;2;65;48;10m\x1b[38;2;242;178;45m [ W ] Avisos \x1b[49m\x1b[39m`
269
- : this.hoveredChip === "warn"
270
- ? theme.bgHover(" [ W ] Avisos ")
271
- : theme.yellow(" [ W ] Avisos ");
272
-
273
- const errChip =
274
- this.filter === "error"
275
- ? `\x1b[48;2;70;20;25m\x1b[38;2;252;109;109m [ E ] Erros \x1b[49m\x1b[39m`
276
- : this.hoveredChip === "error"
277
- ? theme.bgHover(" [ E ] Erros ")
278
- : theme.red(" [ E ] Erros ");
279
-
280
- const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
281
- const copyChip =
282
- this.copyNotification
283
- ? `\x1b[48;2;15;50;35m\x1b[38;2;8;229;166m${copyLabel}\x1b[49m\x1b[39m`
284
- : this.hoveredChip === "copy"
285
- ? theme.bgHover(copyLabel)
286
- : theme.green(copyLabel);
287
-
288
- const clearChip =
289
- this.hoveredChip === "clear"
290
- ? theme.bgHover(" [ C ] Limpar ")
291
- : theme.muted(" [ C ] Limpar ");
292
-
293
- const formattedLines: string[] = [];
294
-
295
- if (rawEntries.length === 0) {
296
- formattedLines.push("");
297
- formattedLines.push(
298
- theme.muted(` Nenhum log registrado para o filtro atual [${this.filter}].`),
299
- );
300
- formattedLines.push(
301
- theme.muted(" Eventos de inicialização, requisições e alertas do proxy aparecerão aqui."),
302
- );
303
- } else {
304
- for (const entry of rawEntries) {
305
- if (!entry || !entry.message || !entry.message.trim()) continue;
306
- let tag = theme.dim("[INFO]");
307
- if (entry.level === "WARN") {
308
- tag = theme.yellow("[WARN]");
309
- } else if (entry.level === "ERROR") {
310
- tag = theme.red("[ERR]");
311
- }
312
-
313
- const prefix = `${theme.dim(entry.time)} ${tag} `;
314
- const prefixW = stringWidth(prefix);
315
- const maxMsgW = Math.max(20, innerW - prefixW - 4);
316
- const truncatedMsg = truncate(entry.message, maxMsgW);
317
- formattedLines.push(`${prefix}${truncatedMsg}`);
318
- }
319
- }
320
-
321
- this.lastTotalCount = formattedLines.length;
322
-
323
- // Scroll Window with top margin breathing room (2 rows reserved at the top)
324
- const visibleCapacity = Math.max(1, contentH - 4);
325
- const total = formattedLines.length;
326
- const maxOffset = Math.max(0, total - visibleCapacity);
327
- const clampedOffset = Math.min(this.scrollOffset, maxOffset);
328
- const scrollFromTop = maxOffset - clampedOffset;
329
-
330
- const startIndex = Math.max(0, total - visibleCapacity - clampedOffset);
331
- const visibleSlice = formattedLines.slice(startIndex, startIndex + visibleCapacity);
332
-
333
- this.lastStartIndex = startIndex;
334
- this.lastVisibleCount = visibleSlice.length;
335
-
336
- // Scrollbar calculation
337
- const hasScrollbar = total > visibleCapacity;
338
- const thumbSize = hasScrollbar
339
- ? Math.max(1, Math.round((visibleCapacity / total) * visibleCapacity))
340
- : 0;
341
- const trackRange = Math.max(1, visibleCapacity - thumbSize);
342
- const thumbTop = hasScrollbar
343
- ? Math.min(
344
- visibleCapacity - thumbSize,
345
- Math.max(0, Math.round((scrollFromTop / maxOffset) * trackRange)),
346
- )
347
- : 0;
348
-
349
- // Lines 0 and 1 are empty breathing margin between filter chips and logs
350
- const finalRows: string[] = ["", ""];
351
-
352
- for (let r = 0; r < visibleCapacity; r++) {
353
- if (r < visibleSlice.length) {
354
- const actualIdx = startIndex + r;
355
- const rawLine = visibleSlice[r];
356
- let styledText = rawLine;
357
- if (this.selectedLogIndex === actualIdx) {
358
- styledText = theme.bgSelected(`▸ ${stripAnsi(rawLine)} `);
359
- } else {
360
- styledText = ` ${rawLine}`;
361
- }
362
-
363
- if (hasScrollbar) {
364
- const isThumb = r >= thumbTop && r < thumbTop + thumbSize;
365
- const scrollChar = isThumb ? theme.cyan("█") : theme.dark("│");
366
- const padded = pad(styledText, innerW - 1);
367
- finalRows.push(`${padded}${scrollChar}`);
368
- } else {
369
- finalRows.push(styledText);
370
- }
371
- } else {
372
- finalRows.push("");
373
- }
374
- }
375
-
376
- const scrollIndicator =
377
- clampedOffset > 0 ? theme.yellow(` [ Rolar: +${clampedOffset} ]`) : "";
378
-
379
- const { titlePrefix } = this.getChips(rawEntries.length);
380
- const box = drawBox({
381
- title: `${titlePrefix}${allChip}${warnChip}${errChip}${copyChip}${clearChip}${scrollIndicator}`,
382
- width,
383
- height: contentH,
384
- borderColor: theme.borderActive,
385
- titleColor: theme.cyan,
386
- content: finalRows,
387
- });
388
- return box;
389
- }
390
- private copyLogs(): void {
391
- const rawEntries = ServerManager.getInstance()
392
- .getLogEntries(this.filter)
393
- .filter((e) => e && e.message && e.message.trim().length > 0);
394
- if (rawEntries.length === 0) return;
395
-
396
- let text = "";
397
- if (this.selectedLogIndex !== null && rawEntries[this.selectedLogIndex]) {
398
- const entry = rawEntries[this.selectedLogIndex];
399
- text = `[${entry.time}] [${entry.level}] ${entry.message}`;
400
- } else {
401
- text = rawEntries
402
- .map((entry) => `[${entry.time}] [${entry.level}] ${entry.message}`)
403
- .join("\n");
404
- }
405
-
406
- setClipboardText(text);
407
- this.copyNotification = true;
408
- if (this.copyTimeout) clearTimeout(this.copyTimeout);
409
- this.copyTimeout = setTimeout(() => {
410
- this.copyNotification = false;
411
- }, 2500);
412
- }
413
- }
1
+ /**
2
+ * QwenProxy TUI - Server Logs View (Tab 6)
3
+ * Real-time event log viewer with level filtering (All, Warnings, Errors).
4
+ */
5
+
6
+ import type { TuiView } from "../types.ts";
7
+ import type { KeyEvent } from "../screen.ts";
8
+ import { theme, drawBox, stringWidth, truncate, pad, stripAnsi, setClipboardText } from "../theme.ts";
9
+ import { ServerManager } from "../server-manager.ts";
10
+
11
+ export class LogsView implements TuiView {
12
+ public readonly id = "logs";
13
+ public readonly title = "Logs";
14
+ public readonly tabNumber = 6;
15
+
16
+ private filter: "all" | "warn" | "error" = "all";
17
+ private scrollOffset = 0; // 0 = at the bottom (follow newest)
18
+ private hoveredChip: "all" | "warn" | "error" | "copy" | "clear" | null = null;
19
+ private selectedLogIndex: number | null = null;
20
+ private copyNotification = false;
21
+ private copyTimeout: NodeJS.Timeout | null = null;
22
+ private lastStartIndex = 0;
23
+ private lastVisibleCount = 0;
24
+ private lastTotalCount = 0;
25
+ private lastWidth = 80;
26
+ private lastHeight = 24;
27
+ private lastMaxOffset = 0;
28
+ private lastVisibleCapacity = 0;
29
+ private isScrollbarHovered = false;
30
+ private isDraggingScrollbar = false;
31
+ private getChips(rawCount: number): {
32
+ titlePrefix: string;
33
+ chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }>;
34
+ } {
35
+ const titlePrefix = `Logs (${rawCount}) `;
36
+ const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
37
+ const defs = [
38
+ { id: "all" as const, label: " [ T ] Todos " },
39
+ { id: "warn" as const, label: " [ W ] Avisos " },
40
+ { id: "error" as const, label: " [ E ] Erros " },
41
+ { id: "copy" as const, label: copyLabel },
42
+ { id: "clear" as const, label: " [ C ] Limpar " },
43
+ ];
44
+
45
+ let currentCol = 4 + stringWidth(titlePrefix);
46
+ const chips: Array<{ id: "all" | "warn" | "error" | "copy" | "clear"; label: string; startCol: number; endCol: number }> = [];
47
+
48
+ for (let i = 0; i < defs.length; i++) {
49
+ const d = defs[i];
50
+ const w = stringWidth(d.label);
51
+ const startCol = currentCol;
52
+ const endCol = startCol + w - 1;
53
+ chips.push({
54
+ id: d.id,
55
+ label: d.label,
56
+ startCol: startCol - (i === 0 ? 1 : 0),
57
+ endCol: endCol + 1,
58
+ });
59
+ currentCol += w;
60
+ }
61
+ return { titlePrefix, chips };
62
+ }
63
+
64
+ public getShortcuts(): Array<{ key: string; label: string }> {
65
+ return [
66
+ { key: "T", label: "Todos" },
67
+ { key: "W", label: "Avisos" },
68
+ { key: "E", label: "Erros" },
69
+ { key: "Y", label: "Copiar" },
70
+ { key: "C", label: "Limpar" },
71
+ { key: "↑/↓", label: "Rolar" },
72
+ ];
73
+ }
74
+
75
+ public handleKey(key: KeyEvent): boolean | void {
76
+ const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
77
+ const { chips } = this.getChips(rawEntries.length);
78
+
79
+ // Mouse hover on chips (accepts rows 3 to 6 for generous vertical target)
80
+ if (key.name === "hover" && key.mouse) {
81
+ if (key.mouse.row >= 3 && key.mouse.row <= 6) {
82
+ const col = key.mouse.col;
83
+ let target: "all" | "warn" | "error" | "copy" | "clear" | null = null;
84
+ for (const c of chips) {
85
+ if (col >= c.startCol && col <= c.endCol) {
86
+ target = c.id;
87
+ break;
88
+ }
89
+ }
90
+ if (this.hoveredChip !== target) {
91
+ this.hoveredChip = target;
92
+ return true;
93
+ }
94
+ } else if (this.hoveredChip !== null) {
95
+ this.hoveredChip = null;
96
+ return true;
97
+ }
98
+ }
99
+
100
+ // Mouse click on chips (accepts rows 3 to 6 for effortless immediate single-click)
101
+ if (key.name === "click" && key.mouse && key.mouse.row >= 3 && key.mouse.row <= 6) {
102
+ const col = key.mouse.col;
103
+ for (const c of chips) {
104
+ if (col >= c.startCol && col <= c.endCol) {
105
+ if (c.id === "all") {
106
+ this.filter = "all";
107
+ this.scrollOffset = 0;
108
+ this.selectedLogIndex = null;
109
+ return true;
110
+ }
111
+ if (c.id === "warn") {
112
+ this.filter = "warn";
113
+ this.scrollOffset = 0;
114
+ this.selectedLogIndex = null;
115
+ return true;
116
+ }
117
+ if (c.id === "error") {
118
+ this.filter = "error";
119
+ this.scrollOffset = 0;
120
+ this.selectedLogIndex = null;
121
+ return true;
122
+ }
123
+ if (c.id === "copy") {
124
+ this.copyLogs();
125
+ return true;
126
+ }
127
+ if (c.id === "clear") {
128
+ ServerManager.getInstance().clearLogs();
129
+ this.scrollOffset = 0;
130
+ this.selectedLogIndex = null;
131
+ return true;
132
+ }
133
+ }
134
+ }
135
+ }
136
+
137
+ // Helper to detect scrollbar mouse coordinates
138
+ const isMouseOnScrollbar = (col: number, row: number) => {
139
+ return (
140
+ col >= this.lastWidth - 3 &&
141
+ col <= this.lastWidth &&
142
+ row >= 7 &&
143
+ row <= 6 + this.lastVisibleCapacity
144
+ );
145
+ };
146
+
147
+ // Scrollbar Hover
148
+ if (key.name === "hover" && key.mouse) {
149
+ const onScrollbar = isMouseOnScrollbar(key.mouse.col, key.mouse.row);
150
+ if (this.isScrollbarHovered !== onScrollbar) {
151
+ this.isScrollbarHovered = onScrollbar;
152
+ return true;
153
+ }
154
+ }
155
+
156
+ // Scrollbar Click (Press)
157
+ if (key.name === "click" && key.mouse && isMouseOnScrollbar(key.mouse.col, key.mouse.row)) {
158
+ if (this.lastMaxOffset > 0 && this.lastVisibleCapacity > 0) {
159
+ this.isDraggingScrollbar = true;
160
+ const r = key.mouse.row - 7;
161
+ const pct = Math.max(0, Math.min(1, r / Math.max(1, this.lastVisibleCapacity - 1)));
162
+ const targetScrollFromTop = Math.round(pct * this.lastMaxOffset);
163
+ this.scrollOffset = Math.max(0, Math.min(this.lastMaxOffset, this.lastMaxOffset - targetScrollFromTop));
164
+ this.selectedLogIndex = null;
165
+ return true;
166
+ }
167
+ }
168
+
169
+ // Scrollbar Drag (Hold and Move)
170
+ if (key.name === "drag" && key.mouse) {
171
+ if (this.isDraggingScrollbar && this.lastMaxOffset > 0 && this.lastVisibleCapacity > 0) {
172
+ const r = key.mouse.row - 7;
173
+ const pct = Math.max(0, Math.min(1, r / Math.max(1, this.lastVisibleCapacity - 1)));
174
+ const targetScrollFromTop = Math.round(pct * this.lastMaxOffset);
175
+ this.scrollOffset = Math.max(0, Math.min(this.lastMaxOffset, this.lastMaxOffset - targetScrollFromTop));
176
+ this.selectedLogIndex = null;
177
+ return true;
178
+ }
179
+ }
180
+
181
+ // Mouse Release
182
+ if (key.name === "release") {
183
+ if (this.isDraggingScrollbar) {
184
+ this.isDraggingScrollbar = false;
185
+ return true;
186
+ }
187
+ }
188
+
189
+ // Mouse click on log rows (terminal row 7+, accounting for 2-line top margin)
190
+ if (key.name === "click" && key.mouse && key.mouse.row >= 7) {
191
+ const rowOffset = key.mouse.row - 7;
192
+ if (rowOffset >= 0 && rowOffset < this.lastVisibleCount) {
193
+ const clickedIdx = this.lastStartIndex + rowOffset;
194
+ if (this.selectedLogIndex === clickedIdx) {
195
+ this.selectedLogIndex = null;
196
+ } else {
197
+ this.selectedLogIndex = clickedIdx;
198
+ }
199
+ return true;
200
+ }
201
+ }
202
+
203
+ // Filter toggles
204
+ if ((key.name === "t" || key.name === "T") && !key.ctrl) {
205
+ this.filter = "all";
206
+ this.scrollOffset = 0;
207
+ this.selectedLogIndex = null;
208
+ return true;
209
+ }
210
+ if ((key.name === "w" || key.name === "W") && !key.ctrl) {
211
+ this.filter = "warn";
212
+ this.scrollOffset = 0;
213
+ this.selectedLogIndex = null;
214
+ return true;
215
+ }
216
+ if ((key.name === "e" || key.name === "E") && !key.ctrl) {
217
+ this.filter = "error";
218
+ this.scrollOffset = 0;
219
+ this.selectedLogIndex = null;
220
+ return true;
221
+ }
222
+
223
+ // Clear logs with 'c'
224
+ if ((key.name === "c" || key.name === "C") && !key.ctrl) {
225
+ ServerManager.getInstance().clearLogs();
226
+ this.scrollOffset = 0;
227
+ this.selectedLogIndex = null;
228
+ return true;
229
+ }
230
+
231
+ // Copy logs with 'y' or 'Y'
232
+ if ((key.name === "y" || key.name === "Y") && !key.ctrl) {
233
+ this.copyLogs();
234
+ return true;
235
+ }
236
+
237
+ // Enter copies selected log if a row is selected
238
+ if (key.name === "return" || key.name === "enter") {
239
+ if (this.selectedLogIndex !== null) {
240
+ this.copyLogs();
241
+ return true;
242
+ }
243
+ }
244
+
245
+ // Escape clears log selection
246
+ if (key.name === "escape") {
247
+ if (this.selectedLogIndex !== null) {
248
+ this.selectedLogIndex = null;
249
+ return true;
250
+ }
251
+ }
252
+
253
+ // Navigate or scroll up (Up key, k)
254
+ if (key.name === "up" || (key.name === "k" && !key.ctrl)) {
255
+ if (this.selectedLogIndex !== null) {
256
+ this.selectedLogIndex = Math.max(0, this.selectedLogIndex - 1);
257
+ if (this.selectedLogIndex < this.lastStartIndex) {
258
+ this.scrollOffset = Math.max(0, Math.min(this.lastMaxOffset, this.lastTotalCount - this.lastVisibleCount - this.selectedLogIndex));
259
+ }
260
+ } else {
261
+ this.scrollOffset = this.lastMaxOffset > 0 ? Math.min(this.lastMaxOffset, this.scrollOffset + 1) : this.scrollOffset + 1;
262
+ }
263
+ return true;
264
+ }
265
+ // Mouse wheel up
266
+ if (key.name === "wheelup") {
267
+ this.scrollOffset = this.lastMaxOffset > 0 ? Math.min(this.lastMaxOffset, this.scrollOffset + 2) : this.scrollOffset + 2;
268
+ return true;
269
+ }
270
+ // Navigate or scroll down (Down key, j)
271
+ if (key.name === "down" || (key.name === "j" && !key.ctrl)) {
272
+ if (this.selectedLogIndex !== null) {
273
+ this.selectedLogIndex = Math.min(this.lastTotalCount - 1, this.selectedLogIndex + 1);
274
+ if (this.selectedLogIndex >= this.lastStartIndex + this.lastVisibleCount) {
275
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
276
+ }
277
+ } else {
278
+ this.scrollOffset = Math.max(0, this.scrollOffset - 1);
279
+ }
280
+ return true;
281
+ }
282
+
283
+ // Mouse wheel down
284
+ if (key.name === "wheeldown") {
285
+ this.scrollOffset = Math.max(0, this.scrollOffset - 2);
286
+ return true;
287
+ }
288
+
289
+ // Page Up / Page Down
290
+ if (key.name === "pageup") {
291
+ this.scrollOffset = this.lastMaxOffset > 0 ? Math.min(this.lastMaxOffset, this.scrollOffset + 10) : this.scrollOffset + 10;
292
+ return true;
293
+ }
294
+ if (key.name === "pagedown") {
295
+ this.scrollOffset = Math.max(0, this.scrollOffset - 10);
296
+ return true;
297
+ }
298
+
299
+ // Home / End
300
+ if (key.name === "home") {
301
+ this.scrollOffset = this.lastMaxOffset;
302
+ return true;
303
+ }
304
+ if (key.name === "end") {
305
+ this.scrollOffset = 0;
306
+ return true;
307
+ }
308
+ }
309
+
310
+ public render(width: number, height: number): string[] {
311
+ const rawEntries = ServerManager.getInstance().getLogEntries(this.filter);
312
+ const contentH = Math.max(8, height);
313
+ const innerW = width - 4;
314
+
315
+ // Filter Chips in Top Title
316
+ const allChip =
317
+ this.filter === "all"
318
+ ? `\x1b[48;2;45;35;85m\x1b[38;2;247;248;252m [ T ] Todos \x1b[49m\x1b[39m`
319
+ : this.hoveredChip === "all"
320
+ ? theme.bgHover(" [ T ] Todos ")
321
+ : theme.cyan(" [ T ] Todos ");
322
+
323
+ const warnChip =
324
+ this.filter === "warn"
325
+ ? `\x1b[48;2;65;48;10m\x1b[38;2;242;178;45m [ W ] Avisos \x1b[49m\x1b[39m`
326
+ : this.hoveredChip === "warn"
327
+ ? theme.bgHover(" [ W ] Avisos ")
328
+ : theme.yellow(" [ W ] Avisos ");
329
+
330
+ const errChip =
331
+ this.filter === "error"
332
+ ? `\x1b[48;2;70;20;25m\x1b[38;2;252;109;109m [ E ] Erros \x1b[49m\x1b[39m`
333
+ : this.hoveredChip === "error"
334
+ ? theme.bgHover(" [ E ] Erros ")
335
+ : theme.red(" [ E ] Erros ");
336
+
337
+ const copyLabel = this.copyNotification ? " [ Y ] Copiado! " : " [ Y ] Copiar ";
338
+ const copyChip =
339
+ this.copyNotification
340
+ ? `\x1b[48;2;15;50;35m\x1b[38;2;8;229;166m${copyLabel}\x1b[49m\x1b[39m`
341
+ : this.hoveredChip === "copy"
342
+ ? theme.bgHover(copyLabel)
343
+ : theme.green(copyLabel);
344
+
345
+ const clearChip =
346
+ this.hoveredChip === "clear"
347
+ ? theme.bgHover(" [ C ] Limpar ")
348
+ : theme.muted(" [ C ] Limpar ");
349
+
350
+ const formattedLines: string[] = [];
351
+
352
+ if (rawEntries.length === 0) {
353
+ formattedLines.push("");
354
+ formattedLines.push(
355
+ theme.muted(` Nenhum log registrado para o filtro atual [${this.filter}].`),
356
+ );
357
+ formattedLines.push(
358
+ theme.muted(" Eventos de inicialização, requisições e alertas do proxy aparecerão aqui."),
359
+ );
360
+ } else {
361
+ for (const entry of rawEntries) {
362
+ if (!entry || !entry.message || !entry.message.trim()) continue;
363
+ let tag = theme.dim("[INFO]");
364
+ if (entry.level === "WARN") {
365
+ tag = theme.yellow("[WARN]");
366
+ } else if (entry.level === "ERROR") {
367
+ tag = theme.red("[ERR]");
368
+ }
369
+
370
+ const prefix = `${theme.dim(entry.time)} ${tag} `;
371
+ const prefixW = stringWidth(prefix);
372
+ const maxMsgW = Math.max(20, innerW - prefixW - 4);
373
+ const truncatedMsg = truncate(entry.message, maxMsgW);
374
+ formattedLines.push(`${prefix}${truncatedMsg}`);
375
+ }
376
+ }
377
+
378
+ this.lastTotalCount = formattedLines.length;
379
+
380
+ // Scroll Window with top margin breathing room (2 rows reserved at the top)
381
+ const visibleCapacity = Math.max(1, contentH - 4);
382
+ const total = formattedLines.length;
383
+ const maxOffset = Math.max(0, total - visibleCapacity);
384
+ this.lastWidth = width;
385
+ this.lastHeight = height;
386
+ this.lastMaxOffset = maxOffset;
387
+ this.lastVisibleCapacity = visibleCapacity;
388
+ this.scrollOffset = Math.max(0, Math.min(this.scrollOffset, maxOffset));
389
+ const clampedOffset = this.scrollOffset;
390
+ const scrollFromTop = maxOffset - clampedOffset;
391
+
392
+ const startIndex = Math.max(0, total - visibleCapacity - clampedOffset);
393
+ const visibleSlice = formattedLines.slice(startIndex, startIndex + visibleCapacity);
394
+
395
+ this.lastStartIndex = startIndex;
396
+ this.lastVisibleCount = visibleSlice.length;
397
+
398
+ // Scrollbar calculation
399
+ const hasScrollbar = total > visibleCapacity;
400
+ const thumbSize = hasScrollbar
401
+ ? Math.max(1, Math.round((visibleCapacity / total) * visibleCapacity))
402
+ : 0;
403
+ const trackRange = Math.max(1, visibleCapacity - thumbSize);
404
+ const thumbTop = hasScrollbar
405
+ ? Math.min(
406
+ visibleCapacity - thumbSize,
407
+ Math.max(0, Math.round((scrollFromTop / maxOffset) * trackRange)),
408
+ )
409
+ : 0;
410
+
411
+ // Lines 0 and 1 are empty breathing margin between filter chips and logs
412
+ const finalRows: string[] = ["", ""];
413
+ const boxInnerW = Math.max(1, width - 2);
414
+
415
+ for (let r = 0; r < visibleCapacity; r++) {
416
+ if (r < visibleSlice.length) {
417
+ const actualIdx = startIndex + r;
418
+ const rawLine = visibleSlice[r];
419
+ let styledText = rawLine;
420
+ if (this.selectedLogIndex === actualIdx) {
421
+ styledText = theme.bgSelected(`▸ ${stripAnsi(rawLine)} `);
422
+ } else {
423
+ styledText = ` ${rawLine}`;
424
+ }
425
+
426
+ if (hasScrollbar) {
427
+ const isThumb = r >= thumbTop && r < thumbTop + thumbSize;
428
+ const isHighlighted = this.isScrollbarHovered || this.isDraggingScrollbar;
429
+ let scrollChar: string;
430
+ if (isThumb) {
431
+ scrollChar = isHighlighted ? `\x1b[48;2;45;35;85m\x1b[38;2;0;255;255m\x1b[1m█\x1b[0m` : theme.cyan("█");
432
+ } else {
433
+ scrollChar = isHighlighted ? theme.cyan("│") : theme.dark("│");
434
+ }
435
+ const padded = pad(styledText, boxInnerW - 1);
436
+ finalRows.push(`${padded}${scrollChar}`);
437
+ } else {
438
+ finalRows.push(styledText);
439
+ }
440
+ } else {
441
+ finalRows.push("");
442
+ }
443
+ }
444
+
445
+ const { titlePrefix } = this.getChips(rawEntries.length);
446
+ const box = drawBox({
447
+ title: `${titlePrefix}${allChip}${warnChip}${errChip}${copyChip}${clearChip}`,
448
+ width,
449
+ height: contentH,
450
+ borderColor: theme.borderActive,
451
+ titleColor: theme.cyan,
452
+ content: finalRows,
453
+ });
454
+ return box;
455
+ }
456
+ private copyLogs(): void {
457
+ const rawEntries = ServerManager.getInstance()
458
+ .getLogEntries(this.filter)
459
+ .filter((e) => e && e.message && e.message.trim().length > 0);
460
+ if (rawEntries.length === 0) return;
461
+
462
+ let text = "";
463
+ if (this.selectedLogIndex !== null && rawEntries[this.selectedLogIndex]) {
464
+ const entry = rawEntries[this.selectedLogIndex];
465
+ text = `[${entry.time}] [${entry.level}] ${entry.message}`;
466
+ } else {
467
+ text = rawEntries
468
+ .map((entry) => `[${entry.time}] [${entry.level}] ${entry.message}`)
469
+ .join("\n");
470
+ }
471
+
472
+ setClipboardText(text);
473
+ this.copyNotification = true;
474
+ if (this.copyTimeout) clearTimeout(this.copyTimeout);
475
+ this.copyTimeout = setTimeout(() => {
476
+ this.copyNotification = false;
477
+ }, 2500);
478
+ }
479
+ }