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,291 +1,304 @@
1
- /**
2
- * QwenProxy TUI - Storage & Cache Management View (Tab 4)
3
- */
4
-
5
- import fs from "node:fs";
6
- import path from "node:path";
7
- import type { TuiView } from "../types.ts";
8
- import type { KeyEvent } from "../screen.ts";
9
- import { theme, glyphs, drawBox, pad } from "../theme.ts";
10
- import { pruneAllPlaywrightProfiles } from "../../services/playwright.ts";
11
- import { getProfilesDir } from "../../core/paths.ts";
12
- import {
13
- formatBytes,
14
- getDirStats,
15
- cleanPlaywrightBrowsers,
16
- } from "../../clean-cache.ts";
17
- import { loadAccounts } from "../../core/accounts.ts";
18
- import { maskAccountIdentifier, resetAllCooldowns } from "../proxy-client.ts";
19
-
20
- export class StorageView implements TuiView {
21
- public readonly id = "storage";
22
- public readonly title = "Storage";
23
- public readonly tabNumber = 4;
24
-
25
- private profilesTotalBytes = 0;
26
- private profilesCount = 0;
27
- private profileStats: Array<{ name: string; size: string; files: number }> = [];
28
-
29
- private activeBrowser = "--";
30
- private unusedBrowsersCount = 0;
31
- private reclaimableBrowserBytes = 0;
32
-
33
- private actionLogs: string[] = [];
34
- private isScanning = false;
35
-
36
- constructor() {
37
- this.refresh();
38
- }
39
- private hoveredActionRow: number | null = null;
40
- private lastLeftW = 48;
41
- public getShortcuts(): Array<{ key: string; label: string }> {
42
- return [
43
- { key: "p", label: "Podar Caches" },
44
- { key: "b", label: "Limpar Navegadores" },
45
- { key: "z", label: "Zerar Cooldowns" },
46
- { key: "r", label: "Atualizar Disco" },
47
- ];
48
- }
49
-
50
- public async refresh(): Promise<void> {
51
- if (this.isScanning) return;
52
- this.isScanning = true;
53
-
54
- try {
55
- // 1. Scan profiles
56
- const profilesDir = getProfilesDir();
57
- let totalBytes = 0;
58
- let count = 0;
59
- this.profileStats = [];
60
- if (fs.existsSync(profilesDir)) {
61
- const entries = fs.readdirSync(profilesDir, { withFileTypes: true });
62
- for (const entry of entries) {
63
- if (entry.isDirectory()) {
64
- count++;
65
- const fullPath = path.join(profilesDir, entry.name);
66
- const stats = getDirStats(fullPath);
67
- totalBytes += stats.bytes;
68
- this.profileStats.push({
69
- name: entry.name,
70
- size: formatBytes(stats.bytes),
71
- files: stats.files,
72
- });
73
- }
74
- }
75
- }
76
- this.profilesTotalBytes = totalBytes;
77
- this.profilesCount = count;
78
-
79
- // 2. Scan Playwright browsers
80
- const browserRes = await cleanPlaywrightBrowsers(false);
81
- this.activeBrowser = browserRes.activeBrowserDir || "chromium";
82
- this.unusedBrowsersCount = browserRes.unusedDirs.length;
83
- this.reclaimableBrowserBytes = browserRes.unusedDirs.reduce(
84
- (acc, d) => acc + d.bytes,
85
- 0,
86
- );
87
- } catch (err: any) {
88
- this.actionLogs.unshift(
89
- theme.red(`✗ Erro ao calcular armazenamento: ${err?.message || String(err)}`),
90
- );
91
- } finally {
92
- this.isScanning = false;
93
- }
94
- }
95
-
96
- public async handleKey(key: KeyEvent): Promise<boolean | void> {
97
- // Mouse hover over quick actions
98
- if (key.name === "hover" && key.mouse) {
99
- const { row, col } = key.mouse;
100
- const leftW = this.lastLeftW || 48;
101
- if (col >= 2 && col <= leftW - 1 && row >= 13 && row <= 16) {
102
- if (this.hoveredActionRow !== row) {
103
- this.hoveredActionRow = row;
104
- return true;
105
- }
106
- } else if (this.hoveredActionRow !== null) {
107
- this.hoveredActionRow = null;
108
- return true;
109
- }
110
- }
111
-
112
- // Mouse click interactions
113
- if (key.name === "click" && key.mouse) {
114
- const { row, col } = key.mouse;
115
- const leftW = this.lastLeftW || 48;
116
- if (col >= 2 && col <= leftW - 1) {
117
- if (row === 13) {
118
- this.handleKey({ name: "p", ctrl: false, shift: false, meta: false });
119
- return true;
120
- }
121
- if (row === 14) {
122
- this.handleKey({ name: "b", ctrl: false, shift: false, meta: false });
123
- return true;
124
- }
125
- if (row === 15) {
126
- this.handleKey({ name: "z", ctrl: false, shift: false, meta: false });
127
- return true;
128
- }
129
- if (row === 16) {
130
- this.handleKey({ name: "r", ctrl: false, shift: false, meta: false });
131
- return true;
132
- }
133
- }
134
- }
135
-
136
- // Reset cooldowns with 'z'
137
- if ((key.name === "z" || key.name === "Z") && !key.ctrl) {
138
- const cleared = resetAllCooldowns();
139
- this.actionLogs.unshift(
140
- theme.green(`✓ Cooldowns zerados: ${cleared} conta(s) destravada(s)!`),
141
- );
142
- return true;
143
- }
144
-
145
- // Refresh storage stats
146
- if ((key.name === "r" || key.name === "R") && !key.ctrl) {
147
- this.actionLogs.unshift(theme.cyan("⏳ Recalculando medições de disco..."));
148
- await this.refresh();
149
- this.actionLogs.unshift(theme.green("✓ Medições de disco atualizadas."));
150
- return true;
151
- }
152
- // Prune profile caches
153
- if ((key.name === "p" || key.name === "P") && !key.ctrl) {
154
- this.actionLogs.unshift(theme.cyan("⏳ Limpando caches transitórios dos perfis..."));
155
- try {
156
- const res = pruneAllPlaywrightProfiles();
157
- this.actionLogs.unshift(
158
- theme.green(
159
- `✓ Caches limpos: ${formatBytes(res.totalFreedBytes)} liberados em ${res.totalFreedFiles} arquivos (${res.profilesCleaned} perfis).`,
160
- ),
161
- );
162
- this.actionLogs.unshift(theme.muted(" (Todos os cookies e logins foram 100% preservados!)"));
163
- await this.refresh();
164
- } catch (err: any) {
165
- this.actionLogs.unshift(theme.red(`✗ Falha ao limpar perfis: ${err?.message || String(err)}`));
166
- }
167
- return true;
168
- }
169
-
170
- // Clean unused playwright browsers
171
- if ((key.name === "b" || key.name === "B") && !key.ctrl) {
172
- this.actionLogs.unshift(
173
- theme.yellow("⏳ Removendo navegadores antigos do Playwright (~4GB)..."),
174
- );
175
- try {
176
- const res = await cleanPlaywrightBrowsers(true);
177
- this.actionLogs.unshift(
178
- theme.green(
179
- `✓ Sucesso: ${formatBytes(res.freedBytes)} recuperados no SSD! (${res.unusedDirs.length} navegadores removidos)`,
180
- ),
181
- );
182
- await this.refresh();
183
- } catch (err: any) {
184
- this.actionLogs.unshift(
185
- theme.red(`✗ Falha ao remover navegadores: ${err?.message || String(err)}`),
186
- );
187
- }
188
- return true;
189
- }
190
- }
191
-
192
- public render(width: number, height: number): string[] {
193
- const contentH = Math.max(12, height);
194
- const leftW = Math.max(48, Math.floor(width * 0.48));
195
- this.lastLeftW = leftW;
196
- const rightW = Math.max(34, width - leftW - 1);
197
-
198
- // Map account directory UUIDs to real user emails
199
- const accountMap = new Map<string, string>();
200
- try {
201
- const accs = loadAccounts();
202
- for (const a of accs) {
203
- accountMap.set(a.id, maskAccountIdentifier(a.email || a.id));
204
- }
205
- } catch {}
206
-
207
- // Left Panel: Storage Diagnostics
208
- const unusedStatus =
209
- this.unusedBrowsersCount > 0
210
- ? theme.yellow(`${glyphs.bullet} ${formatBytes(this.reclaimableBrowserBytes)} (${this.unusedBrowsersCount} versões)`)
211
- : theme.green("✓ Nenhum");
212
-
213
- const leftContent: string[] = [
214
- "",
215
- ` ${theme.bold(theme.white("Armazenamento dos Perfis:"))}`,
216
- ` ${theme.dim("Perfis Qwen:")} ${theme.cyan(formatBytes(this.profilesTotalBytes))} ${theme.muted(`(${this.profilesCount} conta${this.profilesCount === 1 ? "" : "s"})`)}`,
217
- ` ${theme.dim("Navegador Ativo:")} ${theme.green(`${glyphs.bullet} ${this.activeBrowser}`)}`,
218
- ` ${theme.dim("Navegadores Antigos:")} ${unusedStatus}`,
219
- ` ${theme.dim("Integridade:")} ${theme.green("✓ Sessões salvas")}`,
220
- "",
221
- ` ${theme.bold(theme.white("Ações Rápidas:"))}`,
222
- ` ${this.hoveredActionRow === 13 ? theme.bgHover(` ${theme.cyan("[ P ] Podar Caches")} `) : `${theme.cyan("[ P ]")} Podar Caches`}`,
223
- ` ${this.hoveredActionRow === 14 ? theme.bgHover(` ${theme.yellow("[ B ] Limpar Navegadores")} `) : `${theme.yellow("[ B ]")} Limpar Navegadores`}`,
224
- ` ${this.hoveredActionRow === 15 ? theme.bgHover(` ${theme.green("[ Z ] Zerar Todos os Cooldowns")} `) : `${theme.green("[ Z ]")} Zerar Todos os Cooldowns`}`,
225
- ` ${this.hoveredActionRow === 16 ? theme.bgHover(` ${theme.muted("[ R ] Atualizar Disco")} `) : `${theme.muted("[ R ]")} Atualizar Disco`}`,
226
- "",
227
- ];
228
-
229
- const leftBox = drawBox({
230
- title: "Espaço em Disco",
231
- width: leftW,
232
- height: contentH,
233
- borderColor: theme.borderInactive,
234
- titleColor: theme.cyan,
235
- content: leftContent,
236
- });
237
-
238
- // Right Panel: Account Profiles & Optimization Logs
239
- const rightContent: string[] = [
240
- "",
241
- ` ${theme.bold(theme.white("Perfis de Conta no Disco:"))}`,
242
- ` ${theme.dim("# Conta Tamanho Arquivos")}`,
243
- ` ${theme.dim("──────────────────────────────────────────────────────────")}`,
244
- ];
245
-
246
- if (this.profileStats.length === 0) {
247
- rightContent.push(` ${theme.muted("Nenhum perfil de navegador inicializado ainda.")}`);
248
- } else {
249
- this.profileStats.forEach((p, idx) => {
250
- const num = pad(String(idx + 1) + ".", 4);
251
- const rawName = accountMap.get(p.name) || maskAccountIdentifier(p.name);
252
- const name = pad(rawName, 22);
253
- rightContent.push(
254
- ` ${theme.dim(num)}${theme.white(name)} ${theme.cyan(pad(p.size, 12))} ${theme.muted(p.files + " arq")}`,
255
- );
256
- });
257
- }
258
-
259
- rightContent.push("");
260
- rightContent.push(` ${theme.bold(theme.white("Histórico de Otimizações:"))}`);
261
- rightContent.push(` ${theme.dim("──────────────────────────────────────────────────────────")}`);
262
-
263
- if (this.actionLogs.length === 0) {
264
- rightContent.push(theme.muted(" Nenhuma otimização executada nesta sessão."));
265
- rightContent.push(theme.muted(" Execute uma das Ações Rápidas ao lado para otimizar o disco."));
266
- } else {
267
- for (const log of this.actionLogs.slice(0, contentH - 12)) {
268
- rightContent.push(` ${log}`);
269
- }
270
- }
271
- const rightBox = drawBox({
272
- title: "Perfis & Histórico",
273
- width: rightW,
274
- height: contentH,
275
- borderColor: theme.borderInactive,
276
- titleColor: theme.cyan,
277
- content: rightContent,
278
- });
279
-
280
- // Merge columns side by side
281
- const mergedLines: string[] = [];
282
- const maxRows = Math.max(leftBox.length, rightBox.length);
283
- for (let r = 0; r < maxRows; r++) {
284
- const leftRow = leftBox[r] || " ".repeat(leftW);
285
- const rightRow = rightBox[r] || " ".repeat(rightW);
286
- mergedLines.push(leftRow + " " + rightRow);
287
- }
288
-
289
- return mergedLines;
290
- }
291
- }
1
+ /**
2
+ * QwenProxy TUI - Storage & Cache Management View (Tab 4)
3
+ */
4
+
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import type { TuiView } from "../types.ts";
8
+ import type { KeyEvent } from "../screen.ts";
9
+ import { theme, glyphs, drawBox, pad } from "../theme.ts";
10
+ import { pruneAllPlaywrightProfiles } from "../../services/playwright.ts";
11
+ import { getProfilesDir } from "../../core/paths.ts";
12
+ import {
13
+ formatBytes,
14
+ getDirStats,
15
+ cleanPlaywrightBrowsers,
16
+ } from "../../clean-cache.ts";
17
+ import { loadAccounts } from "../../core/accounts.ts";
18
+ import { maskAccountIdentifier, resetAllCooldowns } from "../proxy-client.ts";
19
+
20
+ export class StorageView implements TuiView {
21
+ public readonly id = "storage";
22
+ public readonly title = "Storage";
23
+ public readonly tabNumber = 4;
24
+
25
+ private profilesTotalBytes = 0;
26
+ private profilesCount = 0;
27
+ private profileStats: Array<{ name: string; size: string; files: number }> = [];
28
+
29
+ private activeBrowser = "--";
30
+ private unusedBrowsersCount = 0;
31
+ private reclaimableBrowserBytes = 0;
32
+
33
+ private actionLogs: string[] = [];
34
+ private isScanning = false;
35
+
36
+ private addLog(message: string): void {
37
+ const time = new Date().toTimeString().slice(0, 8);
38
+ this.actionLogs.push(`${theme.dim(`[${time}]`)} ${message}`);
39
+ if (this.actionLogs.length > 50) {
40
+ this.actionLogs.shift();
41
+ }
42
+ }
43
+
44
+ constructor() {
45
+ this.refresh();
46
+ }
47
+ private hoveredActionRow: number | null = null;
48
+ private lastLeftW = 48;
49
+ public getShortcuts(): Array<{ key: string; label: string }> {
50
+ return [
51
+ { key: "p", label: "Podar Caches" },
52
+ { key: "b", label: "Limpar Navegadores" },
53
+ { key: "z", label: "Zerar Cooldowns" },
54
+ { key: "r", label: "Atualizar Disco" },
55
+ ];
56
+ }
57
+
58
+ public async refresh(): Promise<void> {
59
+ if (this.isScanning) return;
60
+ this.isScanning = true;
61
+
62
+ try {
63
+ // 1. Scan profiles
64
+ const profilesDir = getProfilesDir();
65
+ let totalBytes = 0;
66
+ let count = 0;
67
+ this.profileStats = [];
68
+ if (fs.existsSync(profilesDir)) {
69
+ const entries = fs.readdirSync(profilesDir, { withFileTypes: true });
70
+ for (const entry of entries) {
71
+ if (entry.isDirectory()) {
72
+ count++;
73
+ const fullPath = path.join(profilesDir, entry.name);
74
+ const stats = getDirStats(fullPath);
75
+ totalBytes += stats.bytes;
76
+ this.profileStats.push({
77
+ name: entry.name,
78
+ size: formatBytes(stats.bytes),
79
+ files: stats.files,
80
+ });
81
+ }
82
+ }
83
+ }
84
+ this.profilesTotalBytes = totalBytes;
85
+ this.profilesCount = count;
86
+
87
+ // 2. Scan Playwright browsers
88
+ const browserRes = await cleanPlaywrightBrowsers(false);
89
+ this.activeBrowser = browserRes.activeBrowserDir || "chromium";
90
+ this.unusedBrowsersCount = browserRes.unusedDirs.length;
91
+ this.reclaimableBrowserBytes = browserRes.unusedDirs.reduce(
92
+ (acc, d) => acc + d.bytes,
93
+ 0,
94
+ );
95
+ } catch (err: any) {
96
+ this.addLog(
97
+ theme.red(`✗ Erro ao calcular armazenamento: ${err?.message || String(err)}`),
98
+ );
99
+ } finally {
100
+ this.isScanning = false;
101
+ }
102
+ }
103
+
104
+ public async handleKey(key: KeyEvent): Promise<boolean | void> {
105
+ // Mouse hover over quick actions
106
+ if (key.name === "hover" && key.mouse) {
107
+ const { row, col } = key.mouse;
108
+ const leftW = this.lastLeftW || 48;
109
+ if (col >= 2 && col <= leftW - 1 && row >= 13 && row <= 16) {
110
+ if (this.hoveredActionRow !== row) {
111
+ this.hoveredActionRow = row;
112
+ return true;
113
+ }
114
+ } else if (this.hoveredActionRow !== null) {
115
+ this.hoveredActionRow = null;
116
+ return true;
117
+ }
118
+ }
119
+
120
+ // Mouse click interactions
121
+ if (key.name === "click" && key.mouse) {
122
+ const { row, col } = key.mouse;
123
+ const leftW = this.lastLeftW || 48;
124
+ if (col >= 2 && col <= leftW - 1) {
125
+ if (row === 13) {
126
+ this.handleKey({ name: "p", ctrl: false, shift: false, meta: false });
127
+ return true;
128
+ }
129
+ if (row === 14) {
130
+ this.handleKey({ name: "b", ctrl: false, shift: false, meta: false });
131
+ return true;
132
+ }
133
+ if (row === 15) {
134
+ this.handleKey({ name: "z", ctrl: false, shift: false, meta: false });
135
+ return true;
136
+ }
137
+ if (row === 16) {
138
+ this.handleKey({ name: "r", ctrl: false, shift: false, meta: false });
139
+ return true;
140
+ }
141
+ }
142
+ }
143
+
144
+ // Reset cooldowns with 'z'
145
+ if ((key.name === "z" || key.name === "Z") && !key.ctrl) {
146
+ const cleared = resetAllCooldowns();
147
+ this.addLog(
148
+ theme.green(`✓ Cooldowns zerados: ${cleared} conta(s) destravada(s)`),
149
+ );
150
+ return true;
151
+ }
152
+
153
+ // Refresh storage stats
154
+ if ((key.name === "r" || key.name === "R") && !key.ctrl) {
155
+ await this.refresh();
156
+ this.addLog(
157
+ theme.green(`✓ Medições atualizadas: ${formatBytes(this.profilesTotalBytes)} em ${this.profilesCount} perfil(is)`),
158
+ );
159
+ return true;
160
+ }
161
+ // Prune profile caches
162
+ if ((key.name === "p" || key.name === "P") && !key.ctrl) {
163
+ try {
164
+ const res = pruneAllPlaywrightProfiles();
165
+ this.addLog(
166
+ theme.green(
167
+ `✓ Caches limpos: ${formatBytes(res.totalFreedBytes)} liberados em ${res.totalFreedFiles} arquivos (${res.profilesCleaned} perfis)`,
168
+ ),
169
+ );
170
+ await this.refresh();
171
+ } catch (err: any) {
172
+ this.addLog(theme.red(`✗ Falha ao limpar perfis: ${err?.message || String(err)}`));
173
+ }
174
+ return true;
175
+ }
176
+
177
+ // Clean unused playwright browsers
178
+ if ((key.name === "b" || key.name === "B") && !key.ctrl) {
179
+ try {
180
+ const res = await cleanPlaywrightBrowsers(true);
181
+ if (res.freedBytes > 0 || res.unusedDirs.length > 0) {
182
+ this.addLog(
183
+ theme.green(
184
+ `✓ Navegadores limpos: ${formatBytes(res.freedBytes)} recuperados no SSD (${res.unusedDirs.length} versões removidas)`,
185
+ ),
186
+ );
187
+ } else {
188
+ this.addLog(
189
+ theme.green(
190
+ `✓ Navegadores verificados: nenhum navegador antigo encontrado (SSD já otimizado)`,
191
+ ),
192
+ );
193
+ }
194
+ await this.refresh();
195
+ } catch (err: any) {
196
+ this.addLog(
197
+ theme.red(`✗ Falha ao remover navegadores: ${err?.message || String(err)}`),
198
+ );
199
+ }
200
+ return true;
201
+ }
202
+ }
203
+ public render(width: number, height: number): string[] {
204
+ const contentH = Math.max(12, height);
205
+ const leftW = Math.max(48, Math.floor(width * 0.48));
206
+ this.lastLeftW = leftW;
207
+ const rightW = Math.max(34, width - leftW - 1);
208
+
209
+ // Map account directory UUIDs to real user emails
210
+ const accountMap = new Map<string, string>();
211
+ try {
212
+ const accs = loadAccounts();
213
+ for (const a of accs) {
214
+ accountMap.set(a.id, maskAccountIdentifier(a.email || a.id));
215
+ }
216
+ } catch {}
217
+
218
+ // Left Panel: Storage Diagnostics
219
+ const unusedStatus =
220
+ this.unusedBrowsersCount > 0
221
+ ? theme.yellow(`${glyphs.bullet} ${formatBytes(this.reclaimableBrowserBytes)} (${this.unusedBrowsersCount} versões)`)
222
+ : theme.green("✓ Nenhum");
223
+
224
+ const leftContent: string[] = [
225
+ "",
226
+ ` ${theme.bold(theme.white("Armazenamento dos Perfis:"))}`,
227
+ ` ${theme.dim("Perfis Qwen:")} ${theme.cyan(formatBytes(this.profilesTotalBytes))} ${theme.muted(`(${this.profilesCount} conta${this.profilesCount === 1 ? "" : "s"})`)}`,
228
+ ` ${theme.dim("Navegador Ativo:")} ${theme.green(`${glyphs.bullet} ${this.activeBrowser}`)}`,
229
+ ` ${theme.dim("Navegadores Antigos:")} ${unusedStatus}`,
230
+ ` ${theme.dim("Integridade:")} ${theme.green("✓ Sessões salvas")}`,
231
+ "",
232
+ ` ${theme.bold(theme.white("Ações Rápidas:"))}`,
233
+ ` ${this.hoveredActionRow === 13 ? theme.bgHover(` ${theme.cyan("[ P ] Podar Caches")} `) : `${theme.cyan("[ P ]")} Podar Caches`}`,
234
+ ` ${this.hoveredActionRow === 14 ? theme.bgHover(` ${theme.yellow("[ B ] Limpar Navegadores")} `) : `${theme.yellow("[ B ]")} Limpar Navegadores`}`,
235
+ ` ${this.hoveredActionRow === 15 ? theme.bgHover(` ${theme.green("[ Z ] Zerar Todos os Cooldowns")} `) : `${theme.green("[ Z ]")} Zerar Todos os Cooldowns`}`,
236
+ ` ${this.hoveredActionRow === 16 ? theme.bgHover(` ${theme.muted("[ R ] Atualizar Disco")} `) : `${theme.muted("[ R ]")} Atualizar Disco`}`,
237
+ "",
238
+ ];
239
+
240
+ const leftBox = drawBox({
241
+ title: "Espaço em Disco",
242
+ width: leftW,
243
+ height: contentH,
244
+ borderColor: theme.borderInactive,
245
+ titleColor: theme.cyan,
246
+ content: leftContent,
247
+ });
248
+
249
+ // Right Panel: Account Profiles & Optimization Logs
250
+ const rightContent: string[] = [
251
+ "",
252
+ ` ${theme.bold(theme.white("Perfis de Conta no Disco:"))}`,
253
+ ` ${theme.dim("# Conta Tamanho Arquivos")}`,
254
+ ` ${theme.dim("──────────────────────────────────────────────────────────")}`,
255
+ ];
256
+
257
+ if (this.profileStats.length === 0) {
258
+ rightContent.push(` ${theme.muted("Nenhum perfil de navegador inicializado ainda.")}`);
259
+ } else {
260
+ this.profileStats.forEach((p, idx) => {
261
+ const num = pad(String(idx + 1) + ".", 4);
262
+ const rawName = accountMap.get(p.name) || maskAccountIdentifier(p.name);
263
+ const name = pad(rawName, 22);
264
+ rightContent.push(
265
+ ` ${theme.dim(num)}${theme.white(name)} ${theme.cyan(pad(p.size, 12))} ${theme.muted(p.files + " arq")}`,
266
+ );
267
+ });
268
+ }
269
+
270
+ rightContent.push("");
271
+ rightContent.push(` ${theme.bold(theme.white("Histórico de Otimizações:"))}`);
272
+ rightContent.push(` ${theme.dim("──────────────────────────────────────────────────────────")}`);
273
+
274
+ if (this.actionLogs.length === 0) {
275
+ rightContent.push(theme.muted(" Nenhuma otimização executada nesta sessão."));
276
+ rightContent.push(theme.muted(" Execute uma das Ações Rápidas ao lado para otimizar o disco."));
277
+ } else {
278
+ const maxLogs = Math.max(1, contentH - 12);
279
+ const visibleLogs = this.actionLogs.slice(-maxLogs);
280
+ for (const log of visibleLogs) {
281
+ rightContent.push(` ${log}`);
282
+ }
283
+ }
284
+ const rightBox = drawBox({
285
+ title: "Perfis & Histórico",
286
+ width: rightW,
287
+ height: contentH,
288
+ borderColor: theme.borderInactive,
289
+ titleColor: theme.cyan,
290
+ content: rightContent,
291
+ });
292
+
293
+ // Merge columns side by side
294
+ const mergedLines: string[] = [];
295
+ const maxRows = Math.max(leftBox.length, rightBox.length);
296
+ for (let r = 0; r < maxRows; r++) {
297
+ const leftRow = leftBox[r] || " ".repeat(leftW);
298
+ const rightRow = rightBox[r] || " ".repeat(rightW);
299
+ mergedLines.push(leftRow + " " + rightRow);
300
+ }
301
+
302
+ return mergedLines;
303
+ }
304
+ }