termchat: 摸鱼模式 — Claude Code 全界面伪装 + 老板键
- Ctrl+B 老板键:伪装屏(banner+工具流+spinner)一键切换,双向清屏毁迹 - 聊天区伪装成 Claude Code 对话:灰底 > 提问 / ● 回复+工具调用痕迹 / ❯ 输入框(闪烁块光标、placeholder)/ 权限模式 footer - 发消息后橙色 spinner "干活中",回复到达记 ✻ Worked for Ns,esc 可打断 - 窗口标题伪装 --title,退出时清屏毁迹、恢复光标 - 消息输出改 console.log 同步管道,修复 Static 32ms 节流丢帧 (Ctrl+B 切回丢历史、spinner 期间消息偶发不显示) - serve/connect 支持位置参数昵称(Windows npm 吞 -n 短选项的兼容) Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
# termchat — 极简双人终端聊天
|
||||
|
||||
一个命令启动,两个人直连聊天。无用户系统、无历史存储,断线即散。
|
||||
自带摸鱼模式:老板键一键伪装、全程不留痕迹。
|
||||
|
||||
## 用法
|
||||
|
||||
@@ -22,7 +23,34 @@ chat serve -n 小明
|
||||
chat connect 192.168.x.x -n 小红
|
||||
```
|
||||
|
||||
开发模式(免编译):`npm run dev serve -n 小明`
|
||||
开发模式(免编译):`npm run dev -- serve 小明`(昵称可直接作位置参数;
|
||||
Windows 上 npm 会吞掉 `-n` 短选项,dev 模式下请用位置参数或 `--name` 长选项)
|
||||
|
||||
## 摸鱼模式
|
||||
|
||||
| 快捷键 | 作用 |
|
||||
|---|---|
|
||||
| `Ctrl+B` | **老板键**:一键切换伪装屏 / 切回聊天 |
|
||||
| `Esc` | 伪装屏下切回聊天;"干活中"打断(记一条 `✻ Worked for Ns`) |
|
||||
| `Ctrl+T` | 聊天区 Claude 风(默认) / 彩色风切换 |
|
||||
|
||||
- **整个界面伪装成 Claude Code**:启动是 Clawd 吉祥物 banner,
|
||||
你的消息显示成灰底 `> 提问`,对方消息显示成 `● 回复` 并带
|
||||
`● Read(…)` / ` ⎿ Read 120 lines` 工具调用痕迹,
|
||||
底部是 `❯` 上下线输入框(带闪烁块光标、权限模式 footer)——
|
||||
聊天状态被看到,也以为你在跟 Claude 对话
|
||||
- **聊天节奏也像**:你发出消息后底部出现橙色 spinner 转个不停
|
||||
(✻ Pondering… (3s · esc to interrupt)),对方回复到达时变成
|
||||
`✻ Worked for Ns`——看起来就是 Claude 刚干完活
|
||||
- **伪装屏**(`Ctrl+B`):全屏显示一个正在跑的 Claude Code 会话——
|
||||
工具调用步骤持续滚动、底部 spinner 转个不停,任由老板盯着看
|
||||
- **双向毁迹**:每次切换都清屏 + 清回滚缓冲,向上翻页也翻不到聊天记录;
|
||||
聊天内容保留在内存,切回自动恢复,未发送的草稿也不丢
|
||||
- **伪装期间**:按键全部吞掉(不会误发消息),对方发来的消息静默接收,
|
||||
切回即可查看
|
||||
- **窗口标题伪装**:任务栏/标签页显示 `claude`(毕竟是 2026 年,
|
||||
满屏 Claude Code 就是正在干活的铁证);`--title` 可自定义
|
||||
- **退出毁迹**:`Ctrl+C` 退出时清屏清缓冲,不留任何痕迹
|
||||
|
||||
## 参数
|
||||
|
||||
@@ -30,8 +58,10 @@ chat connect 192.168.x.x -n 小红
|
||||
|---|---|---|
|
||||
| `serve` | `-p, --port` | 9000 |
|
||||
| `serve` | `-n, --name` | A |
|
||||
| `serve` | `--title` | claude |
|
||||
| `connect <host>` | `-p, --port` | 9000 |
|
||||
| `connect <host>` | `-n, --name` | B |
|
||||
| `connect <host>` | `--title` | claude |
|
||||
|
||||
## 说明
|
||||
|
||||
|
||||
+9
-6
@@ -10,31 +10,34 @@ program
|
||||
.version("0.1.0");
|
||||
|
||||
program
|
||||
.command("serve")
|
||||
.command("serve [name]")
|
||||
.description("作为服务端,等待对方连接")
|
||||
.option("-p, --port <number>", "监听端口", "9000")
|
||||
.option("-n, --name <name>", "你的昵称", "A")
|
||||
.action((opts) => {
|
||||
.option("--title <text>", "终端标题伪装(任务栏可见)", "claude")
|
||||
.action((nameArg, opts) => {
|
||||
const port = Number(opts.port);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
console.error(`无效端口:${opts.port}`);
|
||||
process.exit(1);
|
||||
}
|
||||
runUI({ role: "server", port, name: opts.name });
|
||||
// 位置参数优先 —— Windows 上 npm run 会吞掉 -n 短选项,serve 小明 也能跑
|
||||
runUI({ role: "server", port, name: nameArg ?? opts.name, title: opts.title });
|
||||
});
|
||||
|
||||
program
|
||||
.command("connect <host>")
|
||||
.command("connect <host> [name]")
|
||||
.description("连接到对方")
|
||||
.option("-p, --port <number>", "端口", "9000")
|
||||
.option("-n, --name <name>", "你的昵称", "B")
|
||||
.action((host, opts) => {
|
||||
.option("--title <text>", "终端标题伪装(任务栏可见)", "claude")
|
||||
.action((host, nameArg, opts) => {
|
||||
const port = Number(opts.port);
|
||||
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
||||
console.error(`无效端口:${opts.port}`);
|
||||
process.exit(1);
|
||||
}
|
||||
runUI({ role: "client", host, port, name: opts.name });
|
||||
runUI({ role: "client", host, port, name: nameArg ?? opts.name, title: opts.title });
|
||||
});
|
||||
|
||||
program.parse();
|
||||
|
||||
+328
@@ -0,0 +1,328 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { Box, Text } from "ink";
|
||||
|
||||
/** 清屏并清空回滚缓冲 —— 切换/退出时毁迹用 */
|
||||
export function clearScreen(): void {
|
||||
process.stdout.write("\x1b[2J\x1b[3J\x1b[H");
|
||||
}
|
||||
|
||||
/** 设置终端窗口标题(OSC 序列),任务栏/标签页上显示的就是它 */
|
||||
export function setTerminalTitle(title: string): void {
|
||||
process.stdout.write(`\x1b]0;${title}\x07`);
|
||||
}
|
||||
|
||||
/* ---------- 原版配色(theme.ts darkTheme) ---------- */
|
||||
|
||||
/** Claude 橙 rgb(215,119,87):spinner 动词 */
|
||||
const ORANGE = "#d77757";
|
||||
/** success rgb(78,186,101):完成工具调用的 ⏺ */
|
||||
const SUCCESS = "#4eba65";
|
||||
/** clawd_background:吉祥物眼睛的黑背景 */
|
||||
const BLACK = "#000000";
|
||||
|
||||
/* ---------- 伪装内容素材池:要经得起盯着看 ---------- */
|
||||
|
||||
/** 假项目文件 */
|
||||
const FILES = [
|
||||
"src/auth/session.ts",
|
||||
"src/api/client.ts",
|
||||
"src/components/Table.tsx",
|
||||
"src/hooks/useForm.ts",
|
||||
"src/utils/format.ts",
|
||||
"src/store/auth.ts",
|
||||
"src/server/router.ts",
|
||||
"src/db/models.ts",
|
||||
"src/services/mailer.ts",
|
||||
"tests/api.test.ts",
|
||||
] as const;
|
||||
|
||||
/** Bash 块:命令与结果成对,结果要配得上命令 */
|
||||
const BASH: ReadonlyArray<readonly [string, readonly string[]]> = [
|
||||
[
|
||||
"git log --oneline -5",
|
||||
[
|
||||
"a3f8c21 fix: token refresh race condition",
|
||||
"b7e92d0 feat: add SSO support",
|
||||
"c41aa9e refactor: extract auth middleware",
|
||||
],
|
||||
],
|
||||
["npm test", ["✓ 42 passed (42)", "Duration 3.8s"]],
|
||||
["npm run build", ["tsc: 0 errors", "built dist/ in 4.2s"]],
|
||||
["git diff --stat", ["3 files changed, 47 insertions(+), 12 deletions(-)"]],
|
||||
["curl -s localhost:3000/api/health", ['{"status":"ok","uptime":8123}']],
|
||||
["git status --short", [" M src/auth/session.ts", "?? tests/session.test.ts"]],
|
||||
];
|
||||
|
||||
const GREPS = [
|
||||
"token.*refresh",
|
||||
"useEffect\\(",
|
||||
"TODO|FIXME",
|
||||
"export interface",
|
||||
"handleRetry",
|
||||
] as const;
|
||||
|
||||
const GLOBS = ["src/**/*.ts", "**/*.test.ts", "src/components/*.tsx"] as const;
|
||||
|
||||
/** 思考/说明文本,像真的在做这个活 */
|
||||
const THOUGHTS = [
|
||||
"我先看下现有的鉴权逻辑,再决定怎么改。",
|
||||
"这里的类型定义和调用方对不上,需要一起调整。",
|
||||
"单测都过了,再补几个边界用例。",
|
||||
"这个报错像是并发导致的,把请求串行化试试。",
|
||||
"先重构这一段,再接新的需求。",
|
||||
"日志里 500 都集中在 /api/orders,查一下这条查询。",
|
||||
"把公共逻辑抽到 utils 里,两处调用一起改。",
|
||||
] as const;
|
||||
|
||||
/** spinner 动词(原版 spinnerVerbs.ts 188 个里挑的) */
|
||||
export const SPINNER_VERBS = [
|
||||
"Booping",
|
||||
"Pondering",
|
||||
"Brewing",
|
||||
"Thinking",
|
||||
"Working",
|
||||
"Wrangling",
|
||||
"Vibing",
|
||||
"Noodling",
|
||||
"Percolating",
|
||||
"Reticulating",
|
||||
"Baking",
|
||||
"Calculating",
|
||||
"Cogitating",
|
||||
"Orchestrating",
|
||||
"Finagling",
|
||||
"Simmering",
|
||||
"Mulling",
|
||||
"Herding",
|
||||
"Puzzling",
|
||||
"Tinkering",
|
||||
"Wandering",
|
||||
"Musing",
|
||||
"Sketching",
|
||||
"Puttering",
|
||||
] as const;
|
||||
|
||||
/** spinner 帧(原版 Windows 序列:正放 + 倒放,120ms 一帧) */
|
||||
export const SPINNER_FRAMES = [
|
||||
"·",
|
||||
"✢",
|
||||
"*",
|
||||
"✶",
|
||||
"✻",
|
||||
"✽",
|
||||
"✻",
|
||||
"✶",
|
||||
"*",
|
||||
"✢",
|
||||
] as const;
|
||||
|
||||
/* ---------- 生成器 ---------- */
|
||||
|
||||
/** 一个工具调用块:⏺ 工具名(参数) + ⎿ 结果行 */
|
||||
export interface ToolStep {
|
||||
name: string;
|
||||
args: string;
|
||||
results: readonly string[];
|
||||
}
|
||||
|
||||
function pick<T>(arr: readonly T[]): T {
|
||||
return arr[Math.floor(Math.random() * arr.length)];
|
||||
}
|
||||
|
||||
function randInt(min: number, max: number): number {
|
||||
return min + Math.floor(Math.random() * (max - min + 1));
|
||||
}
|
||||
|
||||
/**
|
||||
* 按种子确定性生成一个工具调用块(Read/Bash/Grep/Update/Glob)。
|
||||
* 同一 seed 必得同一步骤 —— 聊天消息的装饰用它,渲染多少次都不变样。
|
||||
*/
|
||||
export function toolStepAt(seed: number): ToolStep {
|
||||
const r = seed % 100;
|
||||
const a = Math.floor(seed / 100);
|
||||
if (r < 25)
|
||||
return {
|
||||
name: "Read",
|
||||
args: FILES[a % FILES.length],
|
||||
results: [`Read ${20 + (a % 300)} lines`],
|
||||
};
|
||||
if (r < 50) {
|
||||
const [cmd, out] = BASH[a % BASH.length];
|
||||
return { name: "Bash", args: cmd, results: out };
|
||||
}
|
||||
if (r < 65)
|
||||
return {
|
||||
name: "Grep",
|
||||
args: GREPS[a % GREPS.length],
|
||||
results: [`Found ${2 + (a % 46)} matches`],
|
||||
};
|
||||
if (r < 85)
|
||||
return {
|
||||
name: "Update",
|
||||
args: FILES[a % FILES.length],
|
||||
results: [`Updated ${3 + (a % 57)} lines`],
|
||||
};
|
||||
return {
|
||||
name: "Glob",
|
||||
args: GLOBS[a % GLOBS.length],
|
||||
results: [`Found ${4 + (a % 27)} files`],
|
||||
};
|
||||
}
|
||||
|
||||
/** 伪装屏里的一"步":工具调用 / 正文 / thinking 折叠行 */
|
||||
type Block =
|
||||
| { kind: "tool"; step: ToolStep }
|
||||
| { kind: "text"; text: string }
|
||||
| { kind: "thinking" };
|
||||
|
||||
/** 随机生成下一步:12% thinking 折叠行、15% 正文、其余工具调用 */
|
||||
function nextStep(): Block {
|
||||
const r = Math.random();
|
||||
if (r < 0.12) return { kind: "thinking" };
|
||||
if (r < 0.27) return { kind: "text", text: pick(THOUGHTS) };
|
||||
return { kind: "tool", step: toolStepAt(Math.floor(Math.random() * 1e9)) };
|
||||
}
|
||||
|
||||
/** 渲染行(把 Block 展平,方便按屏高截断) */
|
||||
type Line =
|
||||
| { t: "blank" }
|
||||
| { t: "text"; text: string }
|
||||
| { t: "thinking" }
|
||||
| { t: "tool"; name: string; args: string }
|
||||
| { t: "result"; text: string };
|
||||
|
||||
function toLines(blocks: readonly Block[]): Line[] {
|
||||
const lines: Line[] = [];
|
||||
for (const b of blocks) {
|
||||
lines.push({ t: "blank" }); // 原版每个内容块上方恰好 1 空行
|
||||
if (b.kind === "thinking") lines.push({ t: "thinking" });
|
||||
else if (b.kind === "text") lines.push({ t: "text", text: b.text });
|
||||
else {
|
||||
lines.push({ t: "tool", name: b.step.name, args: b.step.args });
|
||||
b.step.results.forEach((r) => lines.push({ t: "result", text: r }));
|
||||
}
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/** cwd 过长截断(原版 truncatedCwd) */
|
||||
function shortCwd(cwd: string): string {
|
||||
return cwd.length > 40 ? `${cwd.slice(0, 39)}…` : cwd;
|
||||
}
|
||||
|
||||
/**
|
||||
* 启动 banner 的 React 版(和 ui.tsx 里的 ANSI 版同款):
|
||||
* Clawd 吉祥物 + Claude Code 版本/模型/cwd,原版 CondensedLogo 布局。
|
||||
*/
|
||||
function Banner() {
|
||||
return (
|
||||
<Box flexDirection="row" gap={2}>
|
||||
<Box flexDirection="column">
|
||||
<Text>
|
||||
<Text color={ORANGE}> ▐</Text>
|
||||
<Text color={ORANGE} backgroundColor={BLACK}>
|
||||
▛███▜
|
||||
</Text>
|
||||
<Text color={ORANGE}>▌</Text>
|
||||
</Text>
|
||||
<Text>
|
||||
<Text color={ORANGE}>▝▜</Text>
|
||||
<Text color={ORANGE} backgroundColor={BLACK}>
|
||||
█████
|
||||
</Text>
|
||||
<Text color={ORANGE}>▛▘</Text>
|
||||
</Text>
|
||||
<Text color={ORANGE}> ▘▘ ▝▝</Text>
|
||||
</Box>
|
||||
<Box flexDirection="column">
|
||||
<Text>
|
||||
<Text bold>Claude Code</Text> <Text dimColor>v2.1.7</Text>
|
||||
</Text>
|
||||
<Text dimColor>sonnet</Text>
|
||||
<Text dimColor>{shortCwd(process.cwd())}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 伪装屏:一个正在跑的 Claude Code 会话。
|
||||
* banner + 持续冒出的工具调用步骤 + 底部 spinner 转动,
|
||||
* 普通渲染不留 scrollback,配清屏即可无缝切换。
|
||||
*/
|
||||
export function Cover() {
|
||||
const [blocks, setBlocks] = useState<Block[]>(() =>
|
||||
Array.from({ length: 6 }, () => nextStep())
|
||||
);
|
||||
const [spin, setSpin] = useState(0);
|
||||
const [verb, setVerb] = useState<string>(() => pick(SPINNER_VERBS));
|
||||
const startedRef = useRef(Date.now());
|
||||
|
||||
// 随机间隔冒出新步骤,同时换 spinner 动词
|
||||
useEffect(() => {
|
||||
let timer: ReturnType<typeof setTimeout>;
|
||||
const tick = () => {
|
||||
setBlocks((prev) => [...prev, nextStep()]);
|
||||
setVerb(pick(SPINNER_VERBS));
|
||||
timer = setTimeout(tick, randInt(2000, 5000));
|
||||
};
|
||||
timer = setTimeout(tick, randInt(2000, 5000));
|
||||
return () => clearTimeout(timer);
|
||||
}, []);
|
||||
|
||||
// spinner 旋转(原版 120ms 一帧)
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setSpin((s) => s + 1), 120);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
// 只保留最近一屏(banner 3 行 + 2 空行 + spinner 1 行的预算)
|
||||
const rows = Math.max(process.stdout.rows ?? 24, 8);
|
||||
const visible = toLines(blocks).slice(-(rows - 7));
|
||||
const secs = Math.floor((Date.now() - startedRef.current) / 1000);
|
||||
|
||||
return (
|
||||
<Box flexDirection="column">
|
||||
<Banner />
|
||||
<Text> </Text>
|
||||
{visible.map((l, i) => {
|
||||
if (l.t === "thinking")
|
||||
return (
|
||||
<Text key={i} dimColor italic>
|
||||
∴ Thinking (ctrl+o to expand)
|
||||
</Text>
|
||||
);
|
||||
if (l.t === "text")
|
||||
return (
|
||||
<Text key={i}>● {l.text}</Text>
|
||||
);
|
||||
if (l.t === "tool")
|
||||
return (
|
||||
<Text key={i}>
|
||||
<Text color={SUCCESS}>● </Text>
|
||||
<Text bold>{l.name}</Text>({l.args})
|
||||
</Text>
|
||||
);
|
||||
if (l.t === "result")
|
||||
return (
|
||||
<Text key={i}>
|
||||
<Text dimColor>{" ⎿ "}</Text>
|
||||
{l.text}
|
||||
</Text>
|
||||
);
|
||||
return <Text key={i}> </Text>;
|
||||
})}
|
||||
<Text> </Text>
|
||||
<Text color={ORANGE}>
|
||||
{SPINNER_FRAMES[spin % SPINNER_FRAMES.length]} {verb}…{" "}
|
||||
<Text dimColor>
|
||||
({secs}s
|
||||
{secs >= 30
|
||||
? ` · ↓ ${Math.floor(secs * 27).toLocaleString()} tokens` // 原版 30s 后才显示 token 计数
|
||||
: ""}
|
||||
{" · esc to interrupt)"}
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
+6
-6
@@ -67,10 +67,10 @@ export function createSession(
|
||||
handlers.onMessage(JSON.parse(s) as ChatMessage);
|
||||
} catch {
|
||||
// 兜底:对方发来的不是 JSON 就当纯文本
|
||||
handlers.onMessage({ type: "msg", name: "对方", text: s, ts: Date.now() });
|
||||
handlers.onMessage({ type: "msg", name: "peer", text: s, ts: Date.now() });
|
||||
}
|
||||
});
|
||||
sock.on("error", (err) => sys(`连接出错:${err.message}`));
|
||||
sock.on("error", (err) => sys(`Connection error: ${err.message}`));
|
||||
sock.on("close", () => setPhase("closed"));
|
||||
};
|
||||
|
||||
@@ -79,21 +79,21 @@ export function createSession(
|
||||
server?.close(); // 只接受第一个连入的人
|
||||
wire(sock);
|
||||
setPhase("connected");
|
||||
sys("对方已连入,开始聊天吧");
|
||||
sys("Peer connected");
|
||||
});
|
||||
server.on("error", (err) => {
|
||||
sys(`监听失败:${err.message}`);
|
||||
sys(`Listen failed: ${err.message}`);
|
||||
setPhase("closed");
|
||||
});
|
||||
server.listen(opts.port, () => {
|
||||
sys(`等待对方连接 0.0.0.0:${opts.port} …`);
|
||||
sys(`Waiting for peer on 0.0.0.0:${opts.port}…`);
|
||||
});
|
||||
} else {
|
||||
const sock = net.connect({ host: opts.host ?? "127.0.0.1", port: opts.port });
|
||||
wire(sock);
|
||||
sock.on("connect", () => {
|
||||
setPhase("connected");
|
||||
sys(`已连接 ${opts.host}:${opts.port}`);
|
||||
sys(`Connected to ${opts.host}:${opts.port}`);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+262
-18
@@ -1,15 +1,63 @@
|
||||
import React, { useEffect, useRef, useState } from "react";
|
||||
import { Box, Static, Text, render, useInput } from "ink";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { Box, Text, render, useInput } from "ink";
|
||||
import { createSession, type ChatMessage, type Phase, type Session } from "./net.js";
|
||||
import {
|
||||
Cover,
|
||||
SPINNER_FRAMES,
|
||||
SPINNER_VERBS,
|
||||
clearScreen,
|
||||
setTerminalTitle,
|
||||
toolStepAt,
|
||||
} from "./cover.js";
|
||||
|
||||
export interface UIOptions {
|
||||
role: "server" | "client";
|
||||
host?: string;
|
||||
port: number;
|
||||
name: string;
|
||||
/** 终端标题伪装(任务栏可见),默认 "claude" */
|
||||
title?: string;
|
||||
}
|
||||
|
||||
/* 原版 theme.ts darkTheme 配色 */
|
||||
const ORANGE = "#d77757"; // claude:spinner 动词
|
||||
const PROMPT_BORDER = "#888888"; // promptBorder:输入框边框
|
||||
const AUTO_ACCEPT = "#af87ff"; // autoAccept:footer 权限模式
|
||||
|
||||
/* messageAnsi 用的 ANSI 序列(console.log 直拼,不走 Ink Text) */
|
||||
const A_SUCCESS = "\x1b[38;2;78;186;101m"; // success 绿:工具 ⏺
|
||||
const A_SUBTLE = "\x1b[38;2;80;80;80m"; // subtle:> 前缀
|
||||
const A_USER_BG = "\x1b[48;2;55;55;55m"; // userMessageBackground:我的消息灰底
|
||||
const A_GREEN = "\x1b[32m"; // 彩色风:我
|
||||
const A_CYAN = "\x1b[36m"; // 彩色风:对方
|
||||
|
||||
/**
|
||||
* 启动 banner:照原版 CondensedLogo 排 —— 左边 Clawd 吉祥物
|
||||
* (quadrant 字符画,clawd_body 橙 + 黑背景),右边版本/模型/cwd 三行。
|
||||
*/
|
||||
const CLAWD = "\x1b[38;2;215;119;87m";
|
||||
const CLAWD_BG = "\x1b[48;2;0;0;0m";
|
||||
const DIM = "\x1b[90m";
|
||||
const BOLD = "\x1b[1m";
|
||||
const RESET = "\x1b[0m";
|
||||
const CWD = process.cwd();
|
||||
const SHORT_CWD = CWD.length > 40 ? `${CWD.slice(0, 39)}…` : CWD; // 原版 truncatedCwd
|
||||
const BANNER = [
|
||||
`${CLAWD} ▐${CLAWD_BG}${CLAWD}▛███▜\x1b[49m${CLAWD}▌${RESET} ${BOLD}Claude Code${RESET} ${DIM}v2.1.7${RESET}`,
|
||||
`${CLAWD}▝▜${CLAWD_BG}${CLAWD}█████\x1b[49m${CLAWD}▛▘${RESET} ${DIM}sonnet${RESET}`,
|
||||
`${CLAWD} ▘▘ ▝▝${RESET} ${DIM}${SHORT_CWD}${RESET}`,
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
export function runUI(opts: UIOptions): void {
|
||||
setTerminalTitle(opts.title ?? "claude");
|
||||
console.log(BANNER);
|
||||
// 藏掉原生光标(输入框里画自己的光标),退出时恢复
|
||||
process.stdout.write("\x1b[?25l");
|
||||
process.on("exit", () => {
|
||||
clearScreen();
|
||||
process.stdout.write("\x1b[?25h");
|
||||
});
|
||||
render(<App {...opts} />);
|
||||
}
|
||||
|
||||
@@ -17,14 +65,56 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
const [messages, setMessages] = useState<ChatMessage[]>([]);
|
||||
const [input, setInput] = useState("");
|
||||
const [phase, setPhase] = useState<Phase>("waiting");
|
||||
const [cover, setCover] = useState(false); // 老板键开关
|
||||
const [plain, setPlain] = useState(true); // 低调渲染开关
|
||||
const [cursorOn, setCursorOn] = useState(true); // 自绘光标闪烁
|
||||
const [busy, setBusy] = useState<number | null>(null); // "Claude 干活中"起点
|
||||
const sessionRef = useRef<Session | null>(null);
|
||||
const busyRef = useRef<number | null>(null);
|
||||
const coverRef = useRef(false); // toggleCover 里同步读,不等 re-render
|
||||
const printedRef = useRef(0); // 已 console.log 打印的消息数
|
||||
|
||||
// 光标闪烁(终端原生块光标的节奏)
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setCursorOn((v) => !v), 530);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
/** 开始"干活":我方发出消息后转 spinner,像在等 Claude 回答 */
|
||||
const startWork = (): void => {
|
||||
if (busyRef.current === null) {
|
||||
busyRef.current = Date.now();
|
||||
setBusy(busyRef.current);
|
||||
}
|
||||
};
|
||||
/** 结束"干活":返回持续秒数(没在干活返回 null) */
|
||||
const stopWork = (): number | null => {
|
||||
const s = busyRef.current;
|
||||
busyRef.current = null;
|
||||
setBusy(null);
|
||||
return s === null ? null : Math.max(1, Math.round((Date.now() - s) / 1000));
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
const session = createSession(
|
||||
role,
|
||||
{ host, port, name },
|
||||
{
|
||||
onMessage: (m) => setMessages((prev) => [...prev, m]),
|
||||
onMessage: (m) => {
|
||||
// 对方回复到达 = "Claude 干完了":先记一条 ✻ Worked for Ns 再上消息
|
||||
const worked =
|
||||
m.type === "msg" && m.name !== name && busyRef.current !== null
|
||||
? stopWork()
|
||||
: null;
|
||||
setMessages((prev) => {
|
||||
if (worked === null) return [...prev, m];
|
||||
return [
|
||||
...prev,
|
||||
{ type: "sys", name: "", text: `✻ Worked for ${worked}s`, ts: m.ts },
|
||||
m,
|
||||
];
|
||||
});
|
||||
},
|
||||
onPhase: (p) => setPhase(p),
|
||||
}
|
||||
);
|
||||
@@ -32,7 +122,51 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
return () => session.close();
|
||||
}, []);
|
||||
|
||||
const toggleCover = (): void => {
|
||||
const next = !coverRef.current;
|
||||
coverRef.current = next;
|
||||
clearScreen(); // 双向切换都毁迹:清屏 + 清回滚缓冲
|
||||
if (!next) {
|
||||
// 切回聊天:重打全部历史。console.log 走 Ink 的同步管道
|
||||
// (擦动态区 → 写出 → 重画),不受渲染节流影响,稳定恢复
|
||||
for (const m of messages) console.log(messageAnsi(m, name, plain));
|
||||
printedRef.current = messages.length;
|
||||
}
|
||||
setCover(next);
|
||||
};
|
||||
|
||||
// 新消息到达即打印(伪装期间攒着,切回时统一重打)。
|
||||
// 不用 <Static>:它的新增输出依赖渲染帧,会被 32ms 节流吞掉
|
||||
useEffect(() => {
|
||||
if (coverRef.current) return;
|
||||
for (; printedRef.current < messages.length; printedRef.current++) {
|
||||
console.log(messageAnsi(messages[printedRef.current], name, plain));
|
||||
}
|
||||
}, [messages, plain]);
|
||||
|
||||
useInput((ch, key) => {
|
||||
if (key.ctrl && ch === "b") {
|
||||
toggleCover();
|
||||
return;
|
||||
}
|
||||
if (cover) {
|
||||
// 伪装期间吞掉其余按键:不发消息、不乱输入;esc 呼应伪装屏提示
|
||||
if (key.escape) toggleCover();
|
||||
return;
|
||||
}
|
||||
if (key.ctrl && ch === "t") {
|
||||
setPlain((p) => !p);
|
||||
return;
|
||||
}
|
||||
if (key.escape && busyRef.current !== null) {
|
||||
// 呼应 spinner 上的提示:esc 打断,记一条 Worked 行(原版同款)
|
||||
const worked = stopWork();
|
||||
setMessages((prev) => [
|
||||
...prev,
|
||||
{ type: "sys", name: "", text: `✻ Worked for ${worked}s`, ts: Date.now() },
|
||||
]);
|
||||
return;
|
||||
}
|
||||
if (key.return) {
|
||||
const text = input.trim();
|
||||
if (!text || phase !== "connected") return;
|
||||
@@ -42,6 +176,7 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
{ type: "msg", name, text, ts: Date.now() },
|
||||
]);
|
||||
setInput("");
|
||||
startWork();
|
||||
} else if (key.backspace || key.delete) {
|
||||
setInput((prev) => prev.slice(0, -1));
|
||||
} else if (ch && !key.ctrl && !key.meta && !key.escape) {
|
||||
@@ -49,6 +184,26 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
}
|
||||
});
|
||||
|
||||
if (cover) return <Cover />;
|
||||
|
||||
// 低调模式 footer:连接后显示原版权限模式行,等待/断开时显示状态
|
||||
const statusPlain =
|
||||
phase === "waiting"
|
||||
? role === "server"
|
||||
? `waiting for peer on 0.0.0.0:${port}…`
|
||||
: `connecting to ${host}:${port}…`
|
||||
: "disconnected · ctrl+c to exit";
|
||||
const footerPlain =
|
||||
phase === "connected" ? (
|
||||
<>
|
||||
<Text color={AUTO_ACCEPT}>⏵⏵ accept edits on </Text>
|
||||
<Text dimColor>(shift+tab to cycle) · ? for shortcuts</Text>
|
||||
</>
|
||||
) : (
|
||||
<Text dimColor>{statusPlain}</Text>
|
||||
);
|
||||
|
||||
// 彩色模式状态行
|
||||
const statusText =
|
||||
phase === "connected"
|
||||
? `已连接 · 你是「${name}」`
|
||||
@@ -63,9 +218,42 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
|
||||
return (
|
||||
<>
|
||||
<Static items={messages}>
|
||||
{(m, i) => <Message key={`${m.ts}-${i}`} m={m} me={name} />}
|
||||
</Static>
|
||||
{plain ? (
|
||||
<Box flexDirection="column">
|
||||
{busy !== null && (
|
||||
<Box marginTop={1}>
|
||||
<WorkSpinner start={busy} />
|
||||
</Box>
|
||||
)}
|
||||
<Box flexDirection="column" marginTop={1}>
|
||||
{/* 原版 PromptInput:只有上下两条横线(无左右边框),promptBorder 灰 */}
|
||||
<Box
|
||||
borderStyle="round"
|
||||
borderTop
|
||||
borderBottom
|
||||
borderLeft={false}
|
||||
borderRight={false}
|
||||
borderColor={PROMPT_BORDER}
|
||||
>
|
||||
{input ? (
|
||||
/* 有输入:文字末尾一个闪烁的反色块光标 */
|
||||
<Text>
|
||||
❯ {input}
|
||||
<Text inverse={cursorOn}> </Text>
|
||||
</Text>
|
||||
) : (
|
||||
/* 空输入:占位符首字符反色充当光标(原版 renderPlaceholder 同款) */
|
||||
<Text>
|
||||
❯ <Text inverse>T</Text>
|
||||
<Text dimColor>ry "fix lint errors"</Text>
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
<Text> {footerPlain}</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
) : (
|
||||
<Box flexDirection="column">
|
||||
<Box borderStyle="round" borderColor={borderColor} paddingLeft={1} paddingRight={1}>
|
||||
<Text dimColor>{statusText}</Text>
|
||||
</Box>
|
||||
@@ -76,27 +264,83 @@ function App({ role, host, port, name }: UIOptions) {
|
||||
<Text>{input}</Text>
|
||||
<Text color="green">▌</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function Message({ m, me }: { m: ChatMessage; me: string }) {
|
||||
if (m.type === "sys") {
|
||||
/** 简单字符串 hash:给消息装饰做确定性随机源,同一消息渲染多少次都一样 */
|
||||
function hashStr(s: string): number {
|
||||
let h = 0;
|
||||
for (let i = 0; i < s.length; i++) h = (h * 31 + s.charCodeAt(i)) | 0;
|
||||
return Math.abs(h);
|
||||
}
|
||||
|
||||
/**
|
||||
* "Claude 干活中" spinner:我方发出消息后转起来(原版 Spinner 动词 + 帧序列),
|
||||
* 对方回复到达时由外层停掉并记一条 ✻ Worked for Ns —— 聊天节奏伪装的关键。
|
||||
*/
|
||||
function WorkSpinner({ start }: { start: number }) {
|
||||
const [frame, setFrame] = useState(0);
|
||||
const [verb] = useState<string>(
|
||||
() => SPINNER_VERBS[Math.floor(Math.random() * SPINNER_VERBS.length)]
|
||||
);
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => setFrame((f) => f + 1), 120);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
const secs = Math.floor((Date.now() - start) / 1000);
|
||||
return (
|
||||
<Text dimColor color="yellow">
|
||||
· {m.text}
|
||||
<Text color={ORANGE}>
|
||||
{SPINNER_FRAMES[frame % SPINNER_FRAMES.length]} {verb}…{" "}
|
||||
<Text dimColor>({secs}s · esc to interrupt)</Text>
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 把一条消息渲染成 ANSI 字符串(console.log 打印,自动排在输入框上方)。
|
||||
* plain = Claude Code 对话风:> 灰底我的提问 / ● "Claude"的回复 / ⎿ 结果行。
|
||||
*/
|
||||
export function messageAnsi(m: ChatMessage, me: string, plain: boolean): string {
|
||||
const lines: string[] = [];
|
||||
if (plain) {
|
||||
lines.push(""); // 每个内容块上方 1 空行(原版 marginTop=1)
|
||||
if (m.type === "sys") {
|
||||
// ✻ 开头是 spinner 结束态,其余是系统提示
|
||||
lines.push(
|
||||
m.text.startsWith("✻")
|
||||
? `${DIM}${m.text}${RESET}`
|
||||
: `${DIM} ⎿ ${m.text}${RESET}`
|
||||
);
|
||||
} else if (m.name === me) {
|
||||
// 原版 UserPromptMessage:subtle "> " 前缀,整条灰底,右侧 1 列 padding
|
||||
lines.push(`${A_USER_BG}${A_SUBTLE}> ${RESET}${A_USER_BG}${m.text} ${RESET}`);
|
||||
} else {
|
||||
// 对方消息 = "Claude"的回复:正文 + 工具调用痕迹(确定性装饰)
|
||||
lines.push(`● ${m.text}`);
|
||||
const h = hashStr(`${m.name}:${m.text}`);
|
||||
// 双装饰时 +700 换文件(同工具不同文件),避免连续两条一模一样
|
||||
const decos = h % 8 === 0 ? [] : h % 5 === 0 ? [h, h + 700] : [h];
|
||||
for (const seed of decos) {
|
||||
const d = toolStepAt(seed);
|
||||
lines.push("");
|
||||
lines.push(`${A_SUCCESS}● ${RESET}${BOLD}${d.name}${RESET}(${d.args})`);
|
||||
for (const r of d.results) lines.push(`${DIM} ⎿ ${RESET}${r}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 彩色风
|
||||
if (m.type === "sys") {
|
||||
lines.push(`${DIM}· ${m.text}${RESET}`);
|
||||
} else {
|
||||
const mine = m.name === me;
|
||||
const time = new Date(m.ts).toLocaleTimeString("zh-CN", { hour12: false });
|
||||
return (
|
||||
<Text>
|
||||
<Text dimColor>{time} </Text>
|
||||
<Text bold color={mine ? "green" : "cyan"}>
|
||||
{mine ? "我" : m.name}:{" "}
|
||||
</Text>
|
||||
<Text>{m.text}</Text>
|
||||
</Text>
|
||||
lines.push(
|
||||
`${DIM}${time} ${RESET}${BOLD}${mine ? A_GREEN : A_CYAN}${mine ? "我" : m.name}: ${RESET}${m.text}`
|
||||
);
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user