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,409 +1,409 @@
1
- /**
2
- * QwenProxy TUI - Selective Client Sync View (Tab 3)
3
- */
4
-
5
- import type { TuiView } from "../types.ts";
6
- import type { KeyEvent } from "../screen.ts";
7
- import { theme, glyphs, drawBox, pad } from "../theme.ts";
8
- import {
9
- syncAllClients,
10
- restoreAllClients,
11
- getDefaultPaths,
12
- inspectClientSyncStatus,
13
- } from "../../sync/index.ts";
14
- import { fetchLiveModels } from "../proxy-client.ts";
15
-
16
- interface ClientOption {
17
- id: "claude-code" | "codex" | "opencode" | "omp";
18
- name: string;
19
- path: string;
20
- selected: boolean;
21
- detected: boolean;
22
- synced: boolean;
23
- configuredModel?: string;
24
- }
25
- export class SyncView implements TuiView {
26
- public readonly id = "sync";
27
- public readonly title = "Sync";
28
- public readonly tabNumber = 3;
29
- private clients: ClientOption[] = [];
30
- private selectedRowIndex = 0; // 0..3 for clients, 4 for model, 5 for scope, 6 for sync, 7 for restore
31
- private hoveredActionRow: number | null = null;
32
- private availableModels = [
33
- "qwen3.8-max",
34
- "qwen3.7-plus",
35
- "qwen3.7-max",
36
- "z-image-turbo",
37
- "qwen-image-3.0-pro",
38
- "wan3.0-video",
39
- ];
40
- private modelIndex = 0;
41
- private syncAllModels = true;
42
- private actionLog: string[] = [];
43
- private lastLeftW = 46;
44
- constructor() {
45
- this.detectClients();
46
- }
47
-
48
- public onActivate(): void {
49
- this.detectClients();
50
- void this.refreshModels();
51
- }
52
- private async refreshModels(): Promise<void> {
53
- try {
54
- const live = await fetchLiveModels();
55
- if (live && live.length > 0) {
56
- this.availableModels = live;
57
- }
58
- } catch {}
59
- }
60
-
61
- private detectClients(): void {
62
- const paths = getDefaultPaths();
63
- const defs: Array<{ id: "claude-code" | "codex" | "opencode" | "omp"; name: string; path: string }> = [
64
- { id: "claude-code", name: "Claude Code", path: paths.claudeCode },
65
- { id: "codex", name: "OpenAI Codex", path: paths.codex },
66
- { id: "opencode", name: "OpenCode", path: paths.openCode },
67
- { id: "omp", name: "OMP (Oh My Pi)", path: paths.omp },
68
- ];
69
-
70
- this.clients = defs.map((d) => {
71
- const status = inspectClientSyncStatus(d.id, d.path);
72
- return {
73
- id: d.id,
74
- name: d.name,
75
- path: d.path,
76
- selected: false,
77
- detected: status.installed,
78
- synced: status.synced,
79
- configuredModel: status.model,
80
- };
81
- });
82
- }
83
-
84
- public getShortcuts(): Array<{ key: string; label: string }> {
85
- return [
86
- { key: "Espaço", label: "Marcar/Desmarcar" },
87
- { key: "Enter", label: "Sincronizar" },
88
- { key: "r", label: "Restaurar Backups" },
89
- { key: "a", label: "Alternar Todos" },
90
- ];
91
- }
92
-
93
- public async handleKey(key: KeyEvent): Promise<boolean | void> {
94
- // Mouse hover interactions
95
- if (key.name === "hover" && key.mouse) {
96
- const { row, col } = key.mouse;
97
- const leftW = this.lastLeftW || 46;
98
- if (col >= 2 && col <= leftW - 1) {
99
- if (row >= 8 && row <= 11) {
100
- const targetRow = row - 8;
101
- if (this.selectedRowIndex !== targetRow) {
102
- this.selectedRowIndex = targetRow;
103
- return true;
104
- }
105
- } else if (row === 14) {
106
- if (this.selectedRowIndex !== 4) {
107
- this.selectedRowIndex = 4;
108
- return true;
109
- }
110
- } else if (row === 15) {
111
- if (this.selectedRowIndex !== 5) {
112
- this.selectedRowIndex = 5;
113
- return true;
114
- }
115
- } else if (row === 18 || row === 19) {
116
- if (this.hoveredActionRow !== row) {
117
- this.hoveredActionRow = row;
118
- return true;
119
- }
120
- } else if (this.hoveredActionRow !== null) {
121
- this.hoveredActionRow = null;
122
- return true;
123
- }
124
- } else if (this.hoveredActionRow !== null) {
125
- this.hoveredActionRow = null;
126
- return true;
127
- }
128
- }
129
-
130
- // Mouse click interactions
131
- if (key.name === "click" && key.mouse) {
132
- const { row, col } = key.mouse;
133
- const leftW = this.lastLeftW || 46;
134
- if (col >= 2 && col <= leftW - 1) {
135
- // Rows 8, 9, 10, 11: Toggle client
136
- if (row >= 8 && row <= 11) {
137
- const client = this.clients[row - 8];
138
- if (client) {
139
- client.selected = !client.selected;
140
- this.selectedRowIndex = row - 8;
141
- return true;
142
- }
143
- }
144
- // Row 14: Model selector
145
- if (row === 14) {
146
- this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
147
- this.selectedRowIndex = 4;
148
- return true;
149
- }
150
- // Row 15: Scope selector
151
- if (row === 15) {
152
- this.syncAllModels = !this.syncAllModels;
153
- this.selectedRowIndex = 5;
154
- return true;
155
- }
156
- // Row 18: Sincronizar button
157
- if (row === 18) {
158
- this.selectedRowIndex = 6;
159
- this.executeSync();
160
- return true;
161
- }
162
- // Row 19: Restaurar button
163
- if (row === 19) {
164
- this.selectedRowIndex = 7;
165
- this.executeRollback();
166
- return true;
167
- }
168
- }
169
- }
170
-
171
- // Navigate rows (Mouse wheel or Up/Down keys)
172
- if (key.name === "up" || key.name === "wheelup" || (key.name === "k" && !key.ctrl)) {
173
- this.selectedRowIndex = Math.max(0, this.selectedRowIndex - 1);
174
- return true;
175
- }
176
- if (key.name === "down" || key.name === "wheeldown" || (key.name === "j" && !key.ctrl)) {
177
- this.selectedRowIndex = Math.min(7, this.selectedRowIndex + 1);
178
- return true;
179
- }
180
-
181
- // Toggle client selection with Space
182
- if (key.name === "space") {
183
- if (this.selectedRowIndex < 4) {
184
- const client = this.clients[this.selectedRowIndex];
185
- if (client) {
186
- client.selected = !client.selected;
187
- }
188
- } else if (this.selectedRowIndex === 4) {
189
- // Cycle model with space
190
- this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
191
- } else if (this.selectedRowIndex === 5) {
192
- this.syncAllModels = !this.syncAllModels;
193
- }
194
- return true;
195
- }
196
-
197
- // Cycle model left/right on row 4
198
- if (this.selectedRowIndex === 4 && (key.name === "left" || key.name === "right")) {
199
- if (key.name === "left") {
200
- this.modelIndex =
201
- (this.modelIndex - 1 + this.availableModels.length) %
202
- this.availableModels.length;
203
- } else {
204
- this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
205
- }
206
- return true;
207
- }
208
-
209
- // Toggle all with 'a'
210
- if (key.name === "a" && !key.ctrl) {
211
- const allSelected = this.clients.every((c) => c.selected);
212
- for (const c of this.clients) {
213
- c.selected = !allSelected;
214
- }
215
- this.actionLog.unshift(
216
- allSelected ? "Desmarcados todos os clientes." : "Selecionados todos os clientes.",
217
- );
218
- return true;
219
- }
220
-
221
- // Rollback with 'r'
222
- if ((key.name === "r" || key.name === "R") && !key.ctrl) {
223
- this.executeRollback();
224
- return true;
225
- }
226
-
227
- // Confirm action on Enter
228
- if (key.name === "return") {
229
- if (this.selectedRowIndex === 7) {
230
- this.executeRollback();
231
- } else {
232
- this.executeSync();
233
- }
234
- return true;
235
- }
236
- }
237
-
238
- private executeSync(): void {
239
- const selectedTargets = this.clients
240
- .filter((c) => c.selected)
241
- .map((c) => c.id);
242
-
243
- if (selectedTargets.length === 0) {
244
- this.actionLog.unshift(theme.yellow("⚠ Nenhum cliente selecionado para sincronizar."));
245
- return;
246
- }
247
- const currentModel = this.availableModels[this.modelIndex] || "qwen3.8-max";
248
- this.actionLog.unshift(
249
- theme.cyan(`⏳ Sincronizando [${selectedTargets.join(", ")}] com modelo ${currentModel}...`),
250
- );
251
- try {
252
- const res = syncAllClients({
253
- targets: selectedTargets,
254
- });
255
-
256
- let successCount = 0;
257
- for (const [key, clientRes] of Object.entries(res.clients)) {
258
- if (clientRes && clientRes.success) {
259
- successCount++;
260
- this.actionLog.unshift(
261
- theme.green(`✓ [${key}] ${clientRes.message || "Configurado com sucesso"}`),
262
- );
263
- } else if (clientRes) {
264
- this.actionLog.unshift(
265
- theme.red(`✗ [${key}] Falha: ${clientRes.error || "Erro desconhecido"}`),
266
- );
267
- }
268
- }
269
-
270
- this.actionLog.unshift(
271
- theme.green(`🎉 Concluído: ${successCount} cliente(s) sincronizado(s) com zero perdas!`),
272
- );
273
- this.detectClients();
274
- } catch (err: any) {
275
- }
276
- }
277
-
278
- private executeRollback(): void {
279
- this.actionLog.unshift(theme.yellow("⏳ Restaurando backups anteriores de configuração..."));
280
- try {
281
- const res = restoreAllClients();
282
- this.actionLog.unshift(
283
- theme.green(`✓ Rollback concluído: ${res.restoredCount} arquivo(s) restaurados com sucesso.`),
284
- );
285
- this.detectClients();
286
- } catch (err: any) {
287
- this.actionLog.unshift(theme.red(`✗ Erro ao restaurar backups: ${err?.message || String(err)}`));
288
- }
289
- }
290
-
291
- public render(width: number, height: number): string[] {
292
- const contentH = Math.max(12, height);
293
- const leftW = Math.max(46, Math.floor(width * 0.52));
294
- this.lastLeftW = leftW;
295
- const rightW = Math.max(30, width - leftW - 1);
296
-
297
- // Left Panel: Options and Selectors
298
- const leftContent: string[] = [
299
- "",
300
- ` ${theme.bold("Clientes:")} (Espaço para marcar)`,
301
- "",
302
- ];
303
-
304
- this.clients.forEach((c, idx) => {
305
- const isFocused = this.selectedRowIndex === idx;
306
- const pointer = isFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
307
- const check = c.selected ? theme.green(glyphs.checkOn) : theme.muted(glyphs.checkOff);
308
- const name = pad(c.name, 16);
309
-
310
- let status: string;
311
- if (c.synced) {
312
- status = theme.green(`${glyphs.check} Sincronizado`);
313
- } else if (c.detected) {
314
- status = theme.yellow(`${glyphs.bullet} Outro provedor`);
315
- } else {
316
- status = theme.muted(`${glyphs.circle} Não instalado`);
317
- }
318
-
319
- const line = `${pointer}${check} ${name} ${status}`;
320
- leftContent.push(isFocused ? theme.bgSelected(line) : line);
321
- });
322
-
323
- leftContent.push("");
324
- leftContent.push(` ${theme.bold("Modelo:")}`);
325
-
326
- // Row index 4: Model Selector
327
- const isModelFocused = this.selectedRowIndex === 4;
328
- const modelPointer = isModelFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
329
- const currentModel = this.availableModels[this.modelIndex] || "qwen3.8-max";
330
- const modelText = `${currentModel} (${this.modelIndex + 1}/${this.availableModels.length})`;
331
-
332
- const modelLine = this.syncAllModels
333
- ? `${modelPointer}${theme.dim(`${modelText}`)}`
334
- : `${modelPointer}${theme.cyan(modelText)}`;
335
-
336
- leftContent.push(isModelFocused ? theme.bgSelected(modelLine) : modelLine);
337
-
338
- // Row index 5: Scope Selector
339
- const isScopeFocused = this.selectedRowIndex === 5;
340
- const scopePointer = isScopeFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
341
- const scopeCheck = this.syncAllModels ? theme.green(glyphs.radioOn) : theme.muted(glyphs.radioOff);
342
- const scopeLine = `${scopePointer}${scopeCheck} Registrar todos os modelos`;
343
- leftContent.push(isScopeFocused ? theme.bgSelected(scopeLine) : scopeLine);
344
- leftContent.push("");
345
- leftContent.push(` ${theme.bold("Ações:")}`);
346
- // Row 18: Sincronizar
347
- const isSyncFocused = this.selectedRowIndex === 6;
348
- const isSyncHovered = this.hoveredActionRow === 18;
349
- const syncLine = ` ${isSyncHovered || isSyncFocused ? theme.bgHover(` ${theme.cyan("[ Enter ] Sincronizar")} `) : `${theme.cyan("[ Enter ]")} Sincronizar`}`;
350
- leftContent.push(syncLine);
351
-
352
- // Row 19: Restaurar
353
- const isRestoreFocused = this.selectedRowIndex === 7;
354
- const isRestoreHovered = this.hoveredActionRow === 19;
355
- const restoreLine = ` ${isRestoreHovered || isRestoreFocused ? theme.bgHover(` ${theme.yellow("[ R ] Restaurar")} `) : `${theme.yellow("[ R ]")} Restaurar`}`;
356
- leftContent.push(restoreLine);
357
-
358
- const leftBox = drawBox({
359
- title: "Configurar",
360
- width: leftW,
361
- height: contentH,
362
- borderColor: theme.borderActive,
363
- titleColor: theme.cyan,
364
- content: leftContent,
365
- });
366
-
367
- // Right Panel: Action Log & Backups
368
- const rightContent: string[] = [
369
- "",
370
- ` ${theme.bold("Histórico:")}`,
371
- ` ${theme.dim("───────────────────────────────────────")}`,
372
- ];
373
-
374
- if (this.actionLog.length === 0) {
375
- rightContent.push("");
376
- rightContent.push(theme.muted(" Nenhuma sincronização recente executada nesta sessão."));
377
- rightContent.push("");
378
- rightContent.push(
379
- theme.muted(" Pressione [ Enter ] para sincronizar os clientes selecionados."),
380
- );
381
- rightContent.push(
382
- theme.muted(" Backups (.bak) são criados automaticamente antes de cada alteração."),
383
- );
384
- } else {
385
- for (const log of this.actionLog.slice(0, contentH - 5)) {
386
- rightContent.push(` ${log}`);
387
- }
388
- }
389
- const rightBox = drawBox({
390
- title: "Histórico & Backups",
391
- width: rightW,
392
- height: contentH,
393
- borderColor: theme.borderInactive,
394
- titleColor: theme.lavender,
395
- content: rightContent,
396
- });
397
-
398
- // Merge columns side by side
399
- const mergedLines: string[] = [];
400
- const maxRows = Math.max(leftBox.length, rightBox.length);
401
- for (let r = 0; r < maxRows; r++) {
402
- const leftRow = leftBox[r] || " ".repeat(leftW);
403
- const rightRow = rightBox[r] || " ".repeat(rightW);
404
- mergedLines.push(leftRow + " " + rightRow);
405
- }
406
-
407
- return mergedLines;
408
- }
409
- }
1
+ /**
2
+ * QwenProxy TUI - Selective Client Sync View (Tab 3)
3
+ */
4
+
5
+ import type { TuiView } from "../types.ts";
6
+ import type { KeyEvent } from "../screen.ts";
7
+ import { theme, glyphs, drawBox, pad } from "../theme.ts";
8
+ import {
9
+ syncAllClients,
10
+ restoreAllClients,
11
+ getDefaultPaths,
12
+ inspectClientSyncStatus,
13
+ } from "../../sync/index.ts";
14
+ import { fetchLiveModels } from "../proxy-client.ts";
15
+
16
+ interface ClientOption {
17
+ id: "claude-code" | "codex" | "opencode" | "omp";
18
+ name: string;
19
+ path: string;
20
+ selected: boolean;
21
+ detected: boolean;
22
+ synced: boolean;
23
+ configuredModel?: string;
24
+ }
25
+ export class SyncView implements TuiView {
26
+ public readonly id = "sync";
27
+ public readonly title = "Sync";
28
+ public readonly tabNumber = 3;
29
+ private clients: ClientOption[] = [];
30
+ private selectedRowIndex = 0; // 0..3 for clients, 4 for model, 5 for scope, 6 for sync, 7 for restore
31
+ private hoveredActionRow: number | null = null;
32
+ private availableModels = [
33
+ "qwen3.8-max",
34
+ "qwen3.7-plus",
35
+ "qwen3.7-max",
36
+ "z-image-turbo",
37
+ "qwen-image-3.0-pro",
38
+ "wan3.0-video",
39
+ ];
40
+ private modelIndex = 0;
41
+ private syncAllModels = true;
42
+ private actionLog: string[] = [];
43
+ private lastLeftW = 46;
44
+ constructor() {
45
+ this.detectClients();
46
+ }
47
+
48
+ public onActivate(): void {
49
+ this.detectClients();
50
+ void this.refreshModels();
51
+ }
52
+ private async refreshModels(): Promise<void> {
53
+ try {
54
+ const live = await fetchLiveModels();
55
+ if (live && live.length > 0) {
56
+ this.availableModels = live;
57
+ }
58
+ } catch {}
59
+ }
60
+
61
+ private detectClients(): void {
62
+ const paths = getDefaultPaths();
63
+ const defs: Array<{ id: "claude-code" | "codex" | "opencode" | "omp"; name: string; path: string }> = [
64
+ { id: "claude-code", name: "Claude Code", path: paths.claudeCode },
65
+ { id: "codex", name: "OpenAI Codex", path: paths.codex },
66
+ { id: "opencode", name: "OpenCode", path: paths.openCode },
67
+ { id: "omp", name: "OMP (Oh My Pi)", path: paths.omp },
68
+ ];
69
+
70
+ this.clients = defs.map((d) => {
71
+ const status = inspectClientSyncStatus(d.id, d.path);
72
+ return {
73
+ id: d.id,
74
+ name: d.name,
75
+ path: d.path,
76
+ selected: false,
77
+ detected: status.installed,
78
+ synced: status.synced,
79
+ configuredModel: status.model,
80
+ };
81
+ });
82
+ }
83
+
84
+ public getShortcuts(): Array<{ key: string; label: string }> {
85
+ return [
86
+ { key: "Espaço", label: "Marcar/Desmarcar" },
87
+ { key: "Enter", label: "Sincronizar" },
88
+ { key: "r", label: "Restaurar Backups" },
89
+ { key: "a", label: "Alternar Todos" },
90
+ ];
91
+ }
92
+
93
+ public async handleKey(key: KeyEvent): Promise<boolean | void> {
94
+ // Mouse hover interactions
95
+ if (key.name === "hover" && key.mouse) {
96
+ const { row, col } = key.mouse;
97
+ const leftW = this.lastLeftW || 46;
98
+ if (col >= 2 && col <= leftW - 1) {
99
+ if (row >= 8 && row <= 11) {
100
+ const targetRow = row - 8;
101
+ if (this.selectedRowIndex !== targetRow) {
102
+ this.selectedRowIndex = targetRow;
103
+ return true;
104
+ }
105
+ } else if (row === 14) {
106
+ if (this.selectedRowIndex !== 4) {
107
+ this.selectedRowIndex = 4;
108
+ return true;
109
+ }
110
+ } else if (row === 15) {
111
+ if (this.selectedRowIndex !== 5) {
112
+ this.selectedRowIndex = 5;
113
+ return true;
114
+ }
115
+ } else if (row === 18 || row === 19) {
116
+ if (this.hoveredActionRow !== row) {
117
+ this.hoveredActionRow = row;
118
+ return true;
119
+ }
120
+ } else if (this.hoveredActionRow !== null) {
121
+ this.hoveredActionRow = null;
122
+ return true;
123
+ }
124
+ } else if (this.hoveredActionRow !== null) {
125
+ this.hoveredActionRow = null;
126
+ return true;
127
+ }
128
+ }
129
+
130
+ // Mouse click interactions
131
+ if (key.name === "click" && key.mouse) {
132
+ const { row, col } = key.mouse;
133
+ const leftW = this.lastLeftW || 46;
134
+ if (col >= 2 && col <= leftW - 1) {
135
+ // Rows 8, 9, 10, 11: Toggle client
136
+ if (row >= 8 && row <= 11) {
137
+ const client = this.clients[row - 8];
138
+ if (client) {
139
+ client.selected = !client.selected;
140
+ this.selectedRowIndex = row - 8;
141
+ return true;
142
+ }
143
+ }
144
+ // Row 14: Model selector
145
+ if (row === 14) {
146
+ this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
147
+ this.selectedRowIndex = 4;
148
+ return true;
149
+ }
150
+ // Row 15: Scope selector
151
+ if (row === 15) {
152
+ this.syncAllModels = !this.syncAllModels;
153
+ this.selectedRowIndex = 5;
154
+ return true;
155
+ }
156
+ // Row 18: Sincronizar button
157
+ if (row === 18) {
158
+ this.selectedRowIndex = 6;
159
+ this.executeSync();
160
+ return true;
161
+ }
162
+ // Row 19: Restaurar button
163
+ if (row === 19) {
164
+ this.selectedRowIndex = 7;
165
+ this.executeRollback();
166
+ return true;
167
+ }
168
+ }
169
+ }
170
+
171
+ // Navigate rows (Mouse wheel or Up/Down keys)
172
+ if (key.name === "up" || key.name === "wheelup" || (key.name === "k" && !key.ctrl)) {
173
+ this.selectedRowIndex = Math.max(0, this.selectedRowIndex - 1);
174
+ return true;
175
+ }
176
+ if (key.name === "down" || key.name === "wheeldown" || (key.name === "j" && !key.ctrl)) {
177
+ this.selectedRowIndex = Math.min(7, this.selectedRowIndex + 1);
178
+ return true;
179
+ }
180
+
181
+ // Toggle client selection with Space
182
+ if (key.name === "space") {
183
+ if (this.selectedRowIndex < 4) {
184
+ const client = this.clients[this.selectedRowIndex];
185
+ if (client) {
186
+ client.selected = !client.selected;
187
+ }
188
+ } else if (this.selectedRowIndex === 4) {
189
+ // Cycle model with space
190
+ this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
191
+ } else if (this.selectedRowIndex === 5) {
192
+ this.syncAllModels = !this.syncAllModels;
193
+ }
194
+ return true;
195
+ }
196
+
197
+ // Cycle model left/right on row 4
198
+ if (this.selectedRowIndex === 4 && (key.name === "left" || key.name === "right")) {
199
+ if (key.name === "left") {
200
+ this.modelIndex =
201
+ (this.modelIndex - 1 + this.availableModels.length) %
202
+ this.availableModels.length;
203
+ } else {
204
+ this.modelIndex = (this.modelIndex + 1) % this.availableModels.length;
205
+ }
206
+ return true;
207
+ }
208
+
209
+ // Toggle all with 'a'
210
+ if (key.name === "a" && !key.ctrl) {
211
+ const allSelected = this.clients.every((c) => c.selected);
212
+ for (const c of this.clients) {
213
+ c.selected = !allSelected;
214
+ }
215
+ this.actionLog.unshift(
216
+ allSelected ? "Desmarcados todos os clientes." : "Selecionados todos os clientes.",
217
+ );
218
+ return true;
219
+ }
220
+
221
+ // Rollback with 'r'
222
+ if ((key.name === "r" || key.name === "R") && !key.ctrl) {
223
+ this.executeRollback();
224
+ return true;
225
+ }
226
+
227
+ // Confirm action on Enter
228
+ if (key.name === "return") {
229
+ if (this.selectedRowIndex === 7) {
230
+ this.executeRollback();
231
+ } else {
232
+ this.executeSync();
233
+ }
234
+ return true;
235
+ }
236
+ }
237
+
238
+ private executeSync(): void {
239
+ const selectedTargets = this.clients
240
+ .filter((c) => c.selected)
241
+ .map((c) => c.id);
242
+
243
+ if (selectedTargets.length === 0) {
244
+ this.actionLog.unshift(theme.yellow("⚠ Nenhum cliente selecionado para sincronizar."));
245
+ return;
246
+ }
247
+ const currentModel = this.availableModels[this.modelIndex] || "qwen3.8-max";
248
+ this.actionLog.unshift(
249
+ theme.cyan(`⏳ Sincronizando [${selectedTargets.join(", ")}] com modelo ${currentModel}...`),
250
+ );
251
+ try {
252
+ const res = syncAllClients({
253
+ targets: selectedTargets,
254
+ });
255
+
256
+ let successCount = 0;
257
+ for (const [key, clientRes] of Object.entries(res.clients)) {
258
+ if (clientRes && clientRes.success) {
259
+ successCount++;
260
+ this.actionLog.unshift(
261
+ theme.green(`✓ [${key}] ${clientRes.message || "Configurado com sucesso"}`),
262
+ );
263
+ } else if (clientRes) {
264
+ this.actionLog.unshift(
265
+ theme.red(`✗ [${key}] Falha: ${clientRes.error || "Erro desconhecido"}`),
266
+ );
267
+ }
268
+ }
269
+
270
+ this.actionLog.unshift(
271
+ theme.green(`🎉 Concluído: ${successCount} cliente(s) sincronizado(s) com zero perdas!`),
272
+ );
273
+ this.detectClients();
274
+ } catch (err: any) {
275
+ }
276
+ }
277
+
278
+ private executeRollback(): void {
279
+ this.actionLog.unshift(theme.yellow("⏳ Restaurando backups anteriores de configuração..."));
280
+ try {
281
+ const res = restoreAllClients();
282
+ this.actionLog.unshift(
283
+ theme.green(`✓ Rollback concluído: ${res.restoredCount} arquivo(s) restaurados com sucesso.`),
284
+ );
285
+ this.detectClients();
286
+ } catch (err: any) {
287
+ this.actionLog.unshift(theme.red(`✗ Erro ao restaurar backups: ${err?.message || String(err)}`));
288
+ }
289
+ }
290
+
291
+ public render(width: number, height: number): string[] {
292
+ const contentH = Math.max(12, height);
293
+ const leftW = Math.max(46, Math.floor(width * 0.52));
294
+ this.lastLeftW = leftW;
295
+ const rightW = Math.max(30, width - leftW - 1);
296
+
297
+ // Left Panel: Options and Selectors
298
+ const leftContent: string[] = [
299
+ "",
300
+ ` ${theme.bold("Clientes:")} (Espaço para marcar)`,
301
+ "",
302
+ ];
303
+
304
+ this.clients.forEach((c, idx) => {
305
+ const isFocused = this.selectedRowIndex === idx;
306
+ const pointer = isFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
307
+ const check = c.selected ? theme.green(glyphs.checkOn) : theme.muted(glyphs.checkOff);
308
+ const name = pad(c.name, 16);
309
+
310
+ let status: string;
311
+ if (c.synced) {
312
+ status = theme.green(`${glyphs.check} Sincronizado`);
313
+ } else if (c.detected) {
314
+ status = theme.yellow(`${glyphs.bullet} Outro provedor`);
315
+ } else {
316
+ status = theme.muted(`${glyphs.circle} Não instalado`);
317
+ }
318
+
319
+ const line = `${pointer}${check} ${name} ${status}`;
320
+ leftContent.push(isFocused ? theme.bgSelected(line) : line);
321
+ });
322
+
323
+ leftContent.push("");
324
+ leftContent.push(` ${theme.bold("Modelo:")}`);
325
+
326
+ // Row index 4: Model Selector
327
+ const isModelFocused = this.selectedRowIndex === 4;
328
+ const modelPointer = isModelFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
329
+ const currentModel = this.availableModels[this.modelIndex] || "qwen3.8-max";
330
+ const modelText = `${currentModel} (${this.modelIndex + 1}/${this.availableModels.length})`;
331
+
332
+ const modelLine = this.syncAllModels
333
+ ? `${modelPointer}${theme.dim(`${modelText}`)}`
334
+ : `${modelPointer}${theme.cyan(modelText)}`;
335
+
336
+ leftContent.push(isModelFocused ? theme.bgSelected(modelLine) : modelLine);
337
+
338
+ // Row index 5: Scope Selector
339
+ const isScopeFocused = this.selectedRowIndex === 5;
340
+ const scopePointer = isScopeFocused ? theme.cyan(`${glyphs.pointer} `) : " ";
341
+ const scopeCheck = this.syncAllModels ? theme.green(glyphs.radioOn) : theme.muted(glyphs.radioOff);
342
+ const scopeLine = `${scopePointer}${scopeCheck} Registrar todos os modelos`;
343
+ leftContent.push(isScopeFocused ? theme.bgSelected(scopeLine) : scopeLine);
344
+ leftContent.push("");
345
+ leftContent.push(` ${theme.bold("Ações:")}`);
346
+ // Row 18: Sincronizar
347
+ const isSyncFocused = this.selectedRowIndex === 6;
348
+ const isSyncHovered = this.hoveredActionRow === 18;
349
+ const syncLine = ` ${isSyncHovered || isSyncFocused ? theme.bgHover(` ${theme.cyan("[ Enter ] Sincronizar")} `) : `${theme.cyan("[ Enter ]")} Sincronizar`}`;
350
+ leftContent.push(syncLine);
351
+
352
+ // Row 19: Restaurar
353
+ const isRestoreFocused = this.selectedRowIndex === 7;
354
+ const isRestoreHovered = this.hoveredActionRow === 19;
355
+ const restoreLine = ` ${isRestoreHovered || isRestoreFocused ? theme.bgHover(` ${theme.yellow("[ R ] Restaurar")} `) : `${theme.yellow("[ R ]")} Restaurar`}`;
356
+ leftContent.push(restoreLine);
357
+
358
+ const leftBox = drawBox({
359
+ title: "Configurar",
360
+ width: leftW,
361
+ height: contentH,
362
+ borderColor: theme.borderActive,
363
+ titleColor: theme.cyan,
364
+ content: leftContent,
365
+ });
366
+
367
+ // Right Panel: Action Log & Backups
368
+ const rightContent: string[] = [
369
+ "",
370
+ ` ${theme.bold("Histórico:")}`,
371
+ ` ${theme.dim("───────────────────────────────────────")}`,
372
+ ];
373
+
374
+ if (this.actionLog.length === 0) {
375
+ rightContent.push("");
376
+ rightContent.push(theme.muted(" Nenhuma sincronização recente executada nesta sessão."));
377
+ rightContent.push("");
378
+ rightContent.push(
379
+ theme.muted(" Pressione [ Enter ] para sincronizar os clientes selecionados."),
380
+ );
381
+ rightContent.push(
382
+ theme.muted(" Backups (.bak) são criados automaticamente antes de cada alteração."),
383
+ );
384
+ } else {
385
+ for (const log of this.actionLog.slice(0, contentH - 5)) {
386
+ rightContent.push(` ${log}`);
387
+ }
388
+ }
389
+ const rightBox = drawBox({
390
+ title: "Histórico & Backups",
391
+ width: rightW,
392
+ height: contentH,
393
+ borderColor: theme.borderInactive,
394
+ titleColor: theme.lavender,
395
+ content: rightContent,
396
+ });
397
+
398
+ // Merge columns side by side
399
+ const mergedLines: string[] = [];
400
+ const maxRows = Math.max(leftBox.length, rightBox.length);
401
+ for (let r = 0; r < maxRows; r++) {
402
+ const leftRow = leftBox[r] || " ".repeat(leftW);
403
+ const rightRow = rightBox[r] || " ".repeat(rightW);
404
+ mergedLines.push(leftRow + " " + rightRow);
405
+ }
406
+
407
+ return mergedLines;
408
+ }
409
+ }