Skip to content

Commit 70fc6be

Browse files
authored
Merge pull request TriDefender#36 from TriDefender/feat/tui
Feat: Introduced TUI, which supersedes CLI
2 parents f8d5db6 + d3c7581 commit 70fc6be

18 files changed

Lines changed: 112895 additions & 109699 deletions

File tree

‎Android-APP/app/src/main/assets/server_bundle/server.cjs‎

Lines changed: 110976 additions & 109662 deletions
Large diffs are not rendered by default.

‎README.md‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,9 @@ bun install
1010

1111
# Copy and edit config
1212
cp config.example.yaml config.yaml
13-
# Default auth is OAuth — log in first (see Authentication below)
13+
14+
# Log in (OAuth, browser-based)
15+
bun run src/index.ts auth login zai # or: bigmodel
1416

1517
# Start the proxy
1618
bun run src/index.ts
@@ -196,6 +198,34 @@ upload (auto-enabled for models whose id contains `v`), MCP HTTP servers,
196198
markdown + code-highlight rendering, light/dark theme, and per-browser
197199
multi-session autosave (localStorage). Open Settings (⚙) to configure.
198200

201+
### Terminal UI (TUI)
202+
203+
```bash
204+
bun run src/index.ts tui # same as serve, plus an interactive panel
205+
bun run src/index.ts tui debug # with per-request debug diagnostics
206+
```
207+
208+
A PC terminal control panel mirroring the Android app's layout — three cards
209+
(Settings & Login / Proxy Server / Logs) rendered in the alternate screen with
210+
zero extra dependencies. The proxy auto-starts on launch when credentials are
211+
available; the log card shows live per-request rows (console output is
212+
captured in-process) with scrollback and tail-following.
213+
214+
| Key | Action |
215+
|-----|--------|
216+
| `s` | Start / stop the proxy server |
217+
| `l` | OAuth login for the current provider (opens the browser) |
218+
| `o` | Logout (cancels an in-flight login and releases its callback port) |
219+
| `p` / `t` | Switch provider (`zai` ↔ `bigmodel`) / plan (`coding-plan` ↔ `start-plan`) — requires the proxy stopped, persisted to `config.yaml` |
220+
| `↑↓` / `PgUp`/`PgDn` / `Home`/`End` | Scroll the log pane |
221+
| `g` | Jump back to the tail (re-enable following) |
222+
| `c` | Clear the log pane |
223+
| `q` / `Ctrl+C` | Quit |
224+
225+
Set `ZCODE_TUI_LOGFILE=/path/to/file.log` to also tee every captured line to a
226+
file (best-effort; never affects handling). Requires a TTY with at least
227+
40x14 cells; Windows Terminal, mintty and common Unix terminals are supported.
228+
199229
## Configuration
200230

201231
| Field | Env Var | Default | Description |

‎src/config/edit.test.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
5+
import { updateConfigYaml } from "./edit.js";
6+
7+
describe("updateConfigYaml", () => {
8+
test("rewrites top-level provider and plan, preserving other keys", () => {
9+
const dir = mkdtempSync(join(tmpdir(), "zcode-tui-test-"));
10+
const path = join(dir, "config.yaml");
11+
writeFileSync(
12+
path,
13+
[
14+
"server:",
15+
" host: 127.0.0.1",
16+
" port: 8080",
17+
"provider: zai",
18+
"plan: coding-plan",
19+
"models:",
20+
" - glm-4.6",
21+
" - glm-5.3",
22+
"",
23+
].join("\n"),
24+
"utf-8",
25+
);
26+
27+
try {
28+
updateConfigYaml(path, { provider: "bigmodel", plan: "start-plan" });
29+
const updated = readFileSync(path, "utf-8");
30+
expect(updated).toContain("provider: bigmodel");
31+
expect(updated).toContain("plan: start-plan");
32+
expect(updated).toContain("port: 8080");
33+
expect(updated).toContain("- glm-5.3");
34+
} finally {
35+
rmSync(dir, { recursive: true, force: true });
36+
}
37+
});
38+
});

‎src/config/edit.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/**
2+
* Targeted YAML config editing helpers shared by the CLI entries (serve /
3+
* android / tui) and the TUI runtime.
4+
*/
5+
import { parse, stringify } from "yaml";
6+
import { readFileSync, writeFileSync } from "node:fs";
7+
import type { ProviderId } from "../provider/types.js";
8+
9+
/** Targeted YAML update of top-level `provider` and `plan` keys. */
10+
export function updateConfigYaml(
11+
path: string,
12+
fields: { provider: ProviderId; plan: "coding-plan" | "start-plan" },
13+
): void {
14+
const raw = readFileSync(path, "utf-8");
15+
const parsed = parse(raw) ?? {};
16+
parsed.provider = fields.provider;
17+
parsed.plan = fields.plan;
18+
writeFileSync(path, stringify(parsed), "utf-8");
19+
}

‎src/index.ts‎

Lines changed: 16 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,22 @@ import { EXAMPLE_CONFIG_YAML } from "./config/template.js";
77
import { AuthManager } from "./auth/manager.js";
88
import { startServer, type ProxyServer } from "./server/server.js";
99
import { startControlListener, LogBuffer, type ControlState } from "./android/control.js";
10-
import { ResponseStore } from "./responses/store.js";
1110
import { loadCredential, saveCredential, clearCredential, getStorePath } from "./auth/store.js";
1211
import { ZaiOAuthClient, BigmodelOAuthClient } from "./auth/oauth.js";
1312
import { KeyResolver } from "./auth/resolver.js";
1413
import type { Credential } from "./auth/types.js";
1514
import type { ProviderId } from "./provider/types.js";
1615
import type { ProxyConfig } from "./config/types.js";
17-
import { parse, stringify } from "yaml";
18-
import { spawn } from "node:child_process";
16+
import { updateConfigYaml } from "./config/edit.js";
17+
import { openBrowser } from "./runtime/open-browser.js";
18+
import { buildServerOptions } from "./server/server-options.js";
1919
import { readFileSync, existsSync, writeFileSync } from "node:fs";
2020
import { join } from "node:path";
2121
import { homedir } from "node:os";
2222
import { randomUUID } from "node:crypto";
2323
import { ensureNodeFetchNoTimeouts } from "./runtime/node-fetch-compat.js";
2424

25-
const VERSION = "2.6.0";
25+
export const VERSION = "2.6.0";
2626

2727
if (require.main === module) main();
2828

@@ -74,6 +74,16 @@ function runCli(): void {
7474
process.stderr.write(`zcode-proxy: android entry failed: ${(err as Error).stack ?? String(err)}\n`);
7575
process.exit(1);
7676
});
77+
} else if (cmd === "tui") {
78+
// Dynamic import: the TUI module imports helpers back from this file, so a
79+
// static edge would create a load-time cycle (same pattern as claimCommand).
80+
const tuiArgs = parseServeArgs(args.slice(1));
81+
import("./tui/app.js")
82+
.then((m) => m.runTui(tuiArgs))
83+
.catch((err: unknown) => {
84+
process.stderr.write(`zcode-proxy: tui failed: ${(err as Error).stack ?? String(err)}\n`);
85+
process.exit(1);
86+
});
7787
} else if (cmd === "serve" || cmd.endsWith(".yaml") || cmd.endsWith(".yml")) {
7888
const serveArgs = cmd === "serve"
7989
? parseServeArgs(args.slice(1))
@@ -97,6 +107,7 @@ Usage:
97107
zcode-proxy serve [config.yaml] Start the proxy server (default)
98108
zcode-proxy serve debug [config.yaml]
99109
Start with verbose per-request diagnostics
110+
zcode-proxy tui [config.yaml] Interactive terminal UI (login / start-stop / live logs)
100111
zcode-proxy android Android entry: proxy + localhost control listener
101112
zcode-proxy auth login <provider> Login via OAuth (provider: zai | bigmodel)
102113
zcode-proxy auth login <provider> --import
@@ -110,6 +121,7 @@ Usage:
110121
Examples:
111122
zcode-proxy Start server with default config.yaml
112123
zcode-proxy serve debug Start with extra debug logging
124+
zcode-proxy tui Terminal UI: login, start/stop, live logs
113125
zcode-proxy auth login bigmodel OAuth login for Bigmodel
114126
zcode-proxy auth login bigmodel --import
115127
Import existing key from ZCode config
@@ -170,15 +182,6 @@ async function serve(configPath: string | undefined, debug: boolean): Promise<vo
170182
});
171183
}
172184

173-
/** Build `startServer` options, wiring the Responses store and MCP pool when their config gates are on. */
174-
function buildServerOptions(config: ProxyConfig, auth: AuthManager, debug: boolean): { config: ProxyConfig; auth: AuthManager; debug: boolean; responseStore?: ResponseStore } {
175-
const opts: { config: ProxyConfig; auth: AuthManager; debug: boolean; responseStore?: ResponseStore } = { config, auth, debug };
176-
if (config.responses.enabled) {
177-
opts.responseStore = new ResponseStore({ maxEntries: config.responses.storeMaxEntries, ttlMs: config.responses.storeTtlMs });
178-
}
179-
return opts;
180-
}
181-
182185
/**
183186
* Desktop-Linux identity defaults for the Android entry (anti-pattern #34).
184187
* Without these, the Node process on Android reports its true host values:
@@ -303,15 +306,6 @@ async function runAndroid(): Promise<void> {
303306
});
304307
}
305308

306-
/** Targeted YAML update of top-level `provider` and `plan` keys. */
307-
function updateConfigYaml(path: string, fields: { provider: ProviderId; plan: "coding-plan" | "start-plan" }): void {
308-
const raw = readFileSync(path, "utf-8");
309-
const parsed = parse(raw) ?? {};
310-
parsed.provider = fields.provider;
311-
parsed.plan = fields.plan;
312-
writeFileSync(path, stringify(parsed), "utf-8");
313-
}
314-
315309
function printDebugBanner(config: ProxyConfig, path: string, cred: Credential | null): void {
316310
const credShape = cred
317311
? `${cred.apiKey.slice(0, 6)}...${cred.apiKey.slice(-4)} (${cred.apiKey.length} chars)`
@@ -529,17 +523,3 @@ function importFromZCodeConfig(provider: ProviderId): Credential {
529523
if (jwt) console.log(` Start-plan JWT: ${jwt.slice(0, 12)}...`);
530524
return { apiKey, provider, jwt };
531525
}
532-
533-
function openBrowser(url: string): void {
534-
try {
535-
if (process.platform === "win32") {
536-
spawn("cmd.exe", ["/c", `start "" "${url}"`], {
537-
detached: true, stdio: "ignore", windowsHide: true, windowsVerbatimArguments: true,
538-
}).unref();
539-
} else if (process.platform === "darwin") {
540-
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
541-
} else {
542-
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
543-
}
544-
} catch { /* user copies URL manually */ }
545-
}

‎src/proxy/captcha-happy.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { describe, expect, test } from "bun:test";
2+
import { makeDualConsole } from "./captcha-happy.js";
3+
4+
describe("dual console (guest spam guard)", () => {
5+
test("drops every console method's call while the guest predicate holds", () => {
6+
const seen: string[] = [];
7+
const recorder: Record<string, unknown> = {};
8+
for (const m of ["log", "debug", "info", "dir", "table", "group", "warn", "error"]) {
9+
recorder[m] = (...a: unknown[]) => { seen.push(m + ": " + a.join(" ")); };
10+
}
11+
const orig = console as unknown as Record<string, unknown>;
12+
const saved = Object.fromEntries(
13+
Object.keys(recorder).map((k) => [k, orig[k]]),
14+
);
15+
Object.assign(orig, recorder);
16+
17+
try {
18+
// Build the dual console against the recorder and route calls through
19+
// it with the guest predicate forced on — the FeiLin spam condition.
20+
const dual = makeDualConsole(() => true) as Record<string, (...a: unknown[]) => void>;
21+
dual.log!("%c%d", "font-size:0;color:transparent", "Error");
22+
dual.debug!("anything");
23+
dual.dir!({ an: "object" });
24+
dual.table!([1, 2]);
25+
expect(seen).toEqual([]);
26+
27+
// Host condition — identical calls must forward untouched.
28+
const forward = makeDualConsole(() => false) as Record<string, (...a: unknown[]) => void>;
29+
forward.log!("hello", 42);
30+
forward.error!("[real] failure");
31+
expect(seen).toEqual(["log: hello 42", "error: [real] failure"]);
32+
} finally {
33+
Object.assign(orig, saved);
34+
}
35+
});
36+
});

‎src/proxy/captcha-happy.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1789,8 +1789,60 @@ const EXTRA_WINDOW_PROPS = [
17891789
// destroyDom() pulls `window` out from under a sibling mid-solve.
17901790
let _aliasRefCount = 0;
17911791

1792+
// Under Bun, guest scripts run in the HOST realm — a bare `console` inside
1793+
// SDK code resolves to the HOST console (that is the FeiLin spam channel:
1794+
// invisible devtools-format lines probed across every console method, ~1/sec
1795+
// while solving). While the aliases are installed, `console` on globalThis is
1796+
// replaced with a DUAL console: calls whose stack originates from guest SDK
1797+
// script URLs are dropped, everything else forwards to the console that was
1798+
// live at install time (the TUI's interception or the serve terminal — so
1799+
// host logging keeps working untouched). Restored on the last destroyDom.
1800+
// Skipped under CAPTCHA_DEBUG so guest logs stay inspectable.
1801+
let _savedConsoleDescriptor: PropertyDescriptor | undefined;
1802+
let _dualConsole: Record<string, unknown> | null = null;
1803+
1804+
function isGuestConsoleCall(): boolean {
1805+
const stack = new Error().stack ?? "";
1806+
return /alicdn\.com|aliyuncs\.com/i.test(stack);
1807+
}
1808+
1809+
/** Build a console facade that drops calls while `isGuest()` holds (test seam). */
1810+
export function makeDualConsole(isGuest: () => boolean = isGuestConsoleCall): Record<string, unknown> {
1811+
// Capture the console OBJECT at build time — methods must keep their
1812+
// original receiver (looking up `console` again inside the closure would
1813+
// resolve to the dual getter itself and recurse).
1814+
const host = console as unknown as Record<string, unknown>;
1815+
const dual: Record<string, unknown> = {};
1816+
for (const key of Object.keys(host)) {
1817+
const fn = host[key];
1818+
if (typeof fn !== "function") {
1819+
dual[key] = fn;
1820+
continue;
1821+
}
1822+
dual[key] = (...args: unknown[]) => {
1823+
if (isGuest()) return;
1824+
return (fn as (...a: unknown[]) => void).apply(host, args);
1825+
};
1826+
}
1827+
return dual;
1828+
}
1829+
17921830
function installGlobalWindowAlias(g, w) {
17931831
_aliasRefCount += 1;
1832+
if (_aliasRefCount === 1 && !process.env.CAPTCHA_DEBUG) {
1833+
_dualConsole = makeDualConsole(); _savedConsoleDescriptor = Object.getOwnPropertyDescriptor(g, "console");
1834+
try {
1835+
Object.defineProperty(g, "console", {
1836+
get() {
1837+
return _dualConsole;
1838+
},
1839+
set(v) {
1840+
try { w.console = v; } catch (_) {}
1841+
},
1842+
configurable: true,
1843+
});
1844+
} catch (_) {}
1845+
}
17941846
const props = new Set(Object.getOwnPropertyNames(w));
17951847
for (const name of EXTRA_WINDOW_PROPS) props.add(name);
17961848
// also walk the prototype chain one level (BrowserWindow getters like
@@ -1852,6 +1904,16 @@ function removeGlobalWindowAlias(g, w) {
18521904
for (const prop of ["window", "self", "top", "parent"]) {
18531905
try { delete g[prop]; } catch (_) {}
18541906
}
1907+
// Restore the pre-alias console descriptor — `delete g.console` above (the
1908+
// getter installed for the dual console) would otherwise leave globalThis
1909+
// without a console at all.
1910+
if (_savedConsoleDescriptor) {
1911+
try {
1912+
Object.defineProperty(g, "console", _savedConsoleDescriptor);
1913+
} catch (_) {}
1914+
_savedConsoleDescriptor = undefined;
1915+
_dualConsole = null;
1916+
}
18551917
}
18561918

18571919
function destroyDom(win) {

‎src/runtime/open-browser.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* Cross-platform default-browser launcher, shared by the CLI auth flows and
3+
* the TUI login action. Best-effort: a failure leaves the URL on screen for
4+
* the user to copy manually.
5+
*/
6+
import { spawn } from "node:child_process";
7+
8+
export function openBrowser(url: string): void {
9+
try {
10+
if (process.platform === "win32") {
11+
spawn("cmd.exe", ["/c", `start "" "${url}"`], {
12+
detached: true, stdio: "ignore", windowsHide: true, windowsVerbatimArguments: true,
13+
}).unref();
14+
} else if (process.platform === "darwin") {
15+
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
16+
} else {
17+
spawn("xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
18+
}
19+
} catch { /* user copies URL manually */ }
20+
}

‎src/server/server-options.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
/**
2+
* `startServer` option assembly shared by every entry that boots the proxy
3+
* in-process (serve / android / tui).
4+
*/
5+
import type { ProxyConfig } from "../config/types.js";
6+
import type { AuthManager } from "../auth/manager.js";
7+
import { ResponseStore } from "../responses/store.js";
8+
9+
/** Build `startServer` options, wiring the Responses store when its config gate is on. */
10+
export function buildServerOptions(
11+
config: ProxyConfig,
12+
auth: AuthManager,
13+
debug: boolean,
14+
): { config: ProxyConfig; auth: AuthManager; debug: boolean; responseStore?: ResponseStore } {
15+
const opts: { config: ProxyConfig; auth: AuthManager; debug: boolean; responseStore?: ResponseStore } = { config, auth, debug };
16+
if (config.responses.enabled) {
17+
opts.responseStore = new ResponseStore({ maxEntries: config.responses.storeMaxEntries, ttlMs: config.responses.storeTtlMs });
18+
}
19+
return opts;
20+
}

0 commit comments

Comments
 (0)