qwenproxy-cli 1.0.0
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.
- package/LICENSE +14 -0
- package/README.md +907 -0
- package/bin/qwenproxy.js +141 -0
- package/package.json +78 -0
- package/src/api/error-classifier.ts +159 -0
- package/src/api/error-helpers.ts +118 -0
- package/src/api/models.ts +261 -0
- package/src/api/server.ts +859 -0
- package/src/cache/memory-cache.ts +385 -0
- package/src/clean-cache.ts +204 -0
- package/src/core/account-concurrency.ts +671 -0
- package/src/core/account-manager.ts +297 -0
- package/src/core/account-priority.ts +163 -0
- package/src/core/accounts.ts +186 -0
- package/src/core/config.ts +383 -0
- package/src/core/crypto-utils.ts +79 -0
- package/src/core/database.ts +276 -0
- package/src/core/errors.ts +118 -0
- package/src/core/logger.ts +269 -0
- package/src/core/memory-usage.ts +84 -0
- package/src/core/metrics.ts +291 -0
- package/src/core/model-alias.ts +77 -0
- package/src/core/model-registry.ts +544 -0
- package/src/core/mutex.ts +119 -0
- package/src/core/paths.ts +199 -0
- package/src/core/prompt-limits.ts +214 -0
- package/src/core/reasoning-effort.ts +102 -0
- package/src/core/stream-registry.ts +96 -0
- package/src/core/waf-isolation.ts +117 -0
- package/src/core/watchdog.ts +195 -0
- package/src/delete-chats.ts +23 -0
- package/src/index.ts +64 -0
- package/src/login.ts +147 -0
- package/src/reset-cooldowns.ts +11 -0
- package/src/routes/anthropic/index.ts +355 -0
- package/src/routes/anthropic/translate.ts +522 -0
- package/src/routes/anthropic/types.ts +154 -0
- package/src/routes/anthropic/validation.ts +144 -0
- package/src/routes/chat/account.ts +1817 -0
- package/src/routes/chat/context.ts +241 -0
- package/src/routes/chat/errors.ts +85 -0
- package/src/routes/chat/helpers.ts +268 -0
- package/src/routes/chat/index.ts +618 -0
- package/src/routes/chat/media.ts +285 -0
- package/src/routes/chat/retry-policy.ts +754 -0
- package/src/routes/chat/stop.ts +98 -0
- package/src/routes/chat/streaming.ts +2710 -0
- package/src/routes/chat/validation.ts +526 -0
- package/src/routes/chat.ts +2 -0
- package/src/routes/completions.ts +290 -0
- package/src/routes/images.ts +139 -0
- package/src/routes/responses/adapter.ts +503 -0
- package/src/routes/responses/index.ts +405 -0
- package/src/routes/responses/state.ts +230 -0
- package/src/routes/responses/streaming.ts +528 -0
- package/src/routes/responses/types.ts +285 -0
- package/src/routes/responses/validation.ts +202 -0
- package/src/routes/upload.ts +731 -0
- package/src/routes/videos.ts +214 -0
- package/src/services/auth-playwright.ts +173 -0
- package/src/services/captcha-coordinator.ts +161 -0
- package/src/services/captcha-solver.ts +553 -0
- package/src/services/chat-cleanup.ts +80 -0
- package/src/services/context-meter.ts +317 -0
- package/src/services/fingerprint.ts +242 -0
- package/src/services/human-behavior.ts +173 -0
- package/src/services/media-generation.ts +1748 -0
- package/src/services/playwright.ts +2800 -0
- package/src/services/qwen-chat-pool.ts +345 -0
- package/src/services/qwen-errors.ts +133 -0
- package/src/services/qwen-headers.ts +79 -0
- package/src/services/qwen-thread-state.ts +393 -0
- package/src/services/qwen-url.ts +19 -0
- package/src/services/qwen.ts +3126 -0
- package/src/services/session-keeper.ts +88 -0
- package/src/services/token-estimation-metrics.ts +118 -0
- package/src/sync/claude-code.ts +75 -0
- package/src/sync/codex.ts +123 -0
- package/src/sync/index.ts +362 -0
- package/src/sync/omp.ts +105 -0
- package/src/sync/opencode.ts +214 -0
- package/src/sync/types.ts +53 -0
- package/src/sync/utils.ts +27 -0
- package/src/sync-clients.ts +189 -0
- package/src/tools/instructions.ts +137 -0
- package/src/tools/manifest.ts +81 -0
- package/src/tools/parser.ts +2989 -0
- package/src/tools/toolcall-tags.ts +142 -0
- package/src/tools/types.ts +53 -0
- package/src/tui/app.ts +264 -0
- package/src/tui/index.ts +61 -0
- package/src/tui/markdown.ts +258 -0
- package/src/tui/proxy-client.ts +326 -0
- package/src/tui/screen.ts +278 -0
- package/src/tui/server-manager.ts +270 -0
- package/src/tui/theme.ts +432 -0
- package/src/tui/types.ts +33 -0
- package/src/tui/views/accounts-view.ts +656 -0
- package/src/tui/views/chat-view.ts +823 -0
- package/src/tui/views/logs-view.ts +413 -0
- package/src/tui/views/status-view.ts +204 -0
- package/src/tui/views/storage-view.ts +291 -0
- package/src/tui/views/sync-view.ts +409 -0
- package/src/types/ali-oss.d.ts +32 -0
- package/src/utils/context-truncation.ts +84 -0
- package/src/utils/json.ts +380 -0
- package/src/utils/session-id.ts +37 -0
- package/src/utils/tool-call-guard.ts +85 -0
- package/src/utils/types.ts +109 -0
|
@@ -0,0 +1,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
|
+
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
|
+
}
|
|
@@ -0,0 +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
|
+
}
|