Skip to content

Commit 24a4f0b

Browse files
authored
feat(cli): animate the claw banner and show it on gateway startup (#105540)
* feat(cli): animate the claw banner and show it on foreground gateway startup * fix(cli): restore the terminal when the banner animation is interrupted
1 parent c0f0107 commit 24a4f0b

8 files changed

Lines changed: 310 additions & 53 deletions

File tree

‎src/cli/claw-banner.test.ts‎

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,87 @@
1+
// Claw banner tests: static/animated gating and the final-frame invariant.
2+
import { describe, expect, it, vi } from "vitest";
3+
import { stripAnsi } from "../../packages/terminal-core/src/ansi.js";
4+
import type { RuntimeEnv } from "../runtime.js";
5+
import { printClawBanner, testing } from "./claw-banner.js";
6+
7+
const runtimeStub = () => {
8+
const log = vi.fn();
9+
return { runtime: { log } as unknown as RuntimeEnv, log };
10+
};
11+
12+
async function runAnimated(rng: () => number) {
13+
const chunks: string[] = [];
14+
const { runtime } = runtimeStub();
15+
await printClawBanner(runtime, {
16+
columns: 120,
17+
isTty: true,
18+
rich: true,
19+
env: {},
20+
rng,
21+
sleep: async () => {},
22+
write: (chunk) => chunks.push(chunk),
23+
});
24+
return chunks;
25+
}
26+
27+
describe("printClawBanner", () => {
28+
it("prints the static banner when not animatable", async () => {
29+
const { runtime, log } = runtimeStub();
30+
await printClawBanner(runtime, { columns: 120, isTty: false, env: {} });
31+
const output = stripAnsi(String(log.mock.calls[0]?.[0]));
32+
expect(output.split("\n")[0]).toBe("▄███▄ ▄███▄");
33+
expect(output).toContain("█▀▀▀█ █▀▀▀█ █▀▀▀▀ █▄ █");
34+
});
35+
36+
it("stays static under CI even on a rich TTY", async () => {
37+
const { runtime, log } = runtimeStub();
38+
await printClawBanner(runtime, { columns: 120, isTty: true, rich: true, env: { CI: "1" } });
39+
expect(log).toHaveBeenCalledTimes(1);
40+
});
41+
42+
it("falls back to the plain title on narrow terminals", async () => {
43+
const { runtime, log } = runtimeStub();
44+
await printClawBanner(runtime, { columns: 50, isTty: true, rich: true, env: {} });
45+
const output = String(log.mock.calls[0]?.[0]);
46+
expect(output).toContain("OPENCLAW");
47+
expect(output).not.toContain("█");
48+
});
49+
50+
it("animates on a rich TTY and settles on the exact static banner", async () => {
51+
const chunks = await runAnimated(() => 0);
52+
expect(chunks[0]).toBe("\x1b[?25l");
53+
expect(chunks).toContain("\x1b[?25h");
54+
const frames = chunks.filter((chunk) => chunk.includes("\x1b[K"));
55+
expect(frames.length).toBeGreaterThan(10);
56+
const finalRows = stripAnsi(frames[frames.length - 1] ?? "")
57+
.split("\n")
58+
.filter((row) => row.length > 0);
59+
expect(finalRows).toEqual(testing.staticBannerLines().map((line) => stripAnsi(line)));
60+
});
61+
62+
it("installs scoped signal handlers only while animating", async () => {
63+
const before = process.listenerCount("SIGINT");
64+
let during = -1;
65+
const { runtime } = runtimeStub();
66+
await printClawBanner(runtime, {
67+
columns: 120,
68+
isTty: true,
69+
rich: true,
70+
env: {},
71+
rng: () => 0.99,
72+
sleep: async () => {
73+
during = Math.max(during, process.listenerCount("SIGINT"));
74+
},
75+
write: () => {},
76+
});
77+
expect(during).toBe(before + 1);
78+
expect(process.listenerCount("SIGINT")).toBe(before);
79+
});
80+
81+
it("varies snips and shimmer passes with the rng", async () => {
82+
// rng below the thresholds adds a second shimmer pass and a second snip.
83+
const maximal = (await runAnimated(() => 0)).filter((c) => c.includes("\x1b[K"));
84+
const minimal = (await runAnimated(() => 0.99)).filter((c) => c.includes("\x1b[K"));
85+
expect(maximal.length).toBeGreaterThan(minimal.length);
86+
});
87+
});

‎src/cli/claw-banner.ts‎

Lines changed: 204 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,204 @@
1+
// Shared OpenClaw banner: the pixel lobster mascot beside the OPENCLAW
2+
// wordmark, with a short startup animation on rich interactive terminals.
3+
// Used by the wizard flows (doctor/onboard/configure) and the foreground
4+
// gateway run; non-TTY and CI paths always get the plain static banner.
5+
import {
6+
decorativeEmoji,
7+
supportsDecorativeEmoji,
8+
} from "../../packages/terminal-core/src/decorative-emoji.js";
9+
import { restoreTerminalState } from "../../packages/terminal-core/src/restore.js";
10+
import { isRich, theme } from "../../packages/terminal-core/src/theme.js";
11+
import type { RuntimeEnv } from "../runtime.js";
12+
13+
// Art is pregenerated from pixel bitmaps (two pixel rows per terminal row via
14+
// ▀▄█). Mascot and wordmark are separate so they can be tinted independently;
15+
// the wordmark starts on mascot row 2, keeping the claws above the text line.
16+
const MASCOT_ART = [
17+
"▄███▄ ▄███▄",
18+
"▀█▄█▀ ▀█▄█▀",
19+
" ▀▄ ▄▀",
20+
" ██ █ ██",
21+
" ▀█████▀",
22+
" ▄█▀ █ ▀█▄",
23+
] as const;
24+
// Claw tips with the pincer notch widened; swapping the top two rows in and
25+
// out produces the "snip".
26+
const MASCOT_OPEN_ROWS = ["▄█▀█▄ ▄█▀█▄", "▀█ █▀ ▀█ █▀"] as const;
27+
const MASCOT_WIDTH = 15;
28+
const WORDMARK_ROW_OFFSET = 2;
29+
30+
const WORDMARK_ART = [
31+
"█▀▀▀█ █▀▀▀█ █▀▀▀▀ █▄ █ █▀▀▀▀ █ █▀▀▀█ █ █",
32+
"█ █ █▀▀▀▀ █▀▀▀ █ ▀▄█ █ █ █▀▀▀█ █▄▀▄█",
33+
"▀▀▀▀▀ ▀ ▀▀▀▀▀ ▀ ▀ ▀▀▀▀▀ ▀▀▀▀▀ ▀ ▀ ▀ ▀",
34+
] as const;
35+
const GAP = 3;
36+
const BANNER_WIDTH = MASCOT_WIDTH + GAP + 48;
37+
const ROWS = MASCOT_ART.length;
38+
39+
export type ClawBannerOptions = {
40+
columns?: number;
41+
isTty?: boolean;
42+
rich?: boolean;
43+
env?: NodeJS.ProcessEnv;
44+
/** Injectable randomness for the animation garnish (tests pin it). */
45+
rng?: () => number;
46+
sleep?: (ms: number) => Promise<void>;
47+
write?: (chunk: string) => void;
48+
};
49+
50+
type CellTint = (col: number) => (text: string) => string;
51+
52+
const identityTint: (text: string) => string = (text) => text;
53+
54+
// Composes one banner frame. Tints run per glyph column so the wipe edge and
55+
// shimmer band can cut through individual letters.
56+
function composeFrame(params: {
57+
mascotRows?: readonly string[];
58+
mascotTint?: CellTint;
59+
wordmarkTint?: CellTint;
60+
}): string[] {
61+
const mascotRows = params.mascotRows ?? MASCOT_ART;
62+
const lines: string[] = [];
63+
for (let row = 0; row < ROWS; row++) {
64+
const mascotRow = (mascotRows[row] ?? "").padEnd(MASCOT_WIDTH).slice(0, MASCOT_WIDTH);
65+
let out = "";
66+
for (let col = 0; col < mascotRow.length; col++) {
67+
const ch = mascotRow[col] ?? " ";
68+
out += ch === " " ? " " : (params.mascotTint?.(col) ?? theme.accent)(ch);
69+
}
70+
const wordmarkRow = WORDMARK_ART[row - WORDMARK_ROW_OFFSET];
71+
if (wordmarkRow) {
72+
out += " ".repeat(GAP);
73+
for (let col = 0; col < wordmarkRow.length; col++) {
74+
const ch = wordmarkRow[col] ?? " ";
75+
out +=
76+
ch === " " ? " " : (params.wordmarkTint?.(MASCOT_WIDTH + GAP + col) ?? identityTint)(ch);
77+
}
78+
}
79+
lines.push(out.replace(/\s+$/, ""));
80+
}
81+
return lines;
82+
}
83+
84+
function staticBannerLines(): string[] {
85+
return composeFrame({});
86+
}
87+
88+
function plainTitleLine(): string {
89+
const icon = decorativeEmoji("🦞");
90+
return supportsDecorativeEmoji() && icon ? `${icon} OPENCLAW ${icon}` : "OPENCLAW";
91+
}
92+
93+
const defaultSleep = (ms: number) =>
94+
new Promise<void>((resolve) => {
95+
setTimeout(resolve, ms);
96+
});
97+
98+
// One combined entrance: a left-to-right molt wipe reveals the color, a
99+
// shimmer band sweeps the wordmark, and the claws snip. The rng varies the
100+
// shimmer passes and snip count a little so back-to-back runs don't feel
101+
// canned; every sequence ends on the exact static banner.
102+
async function animateBanner(opts: {
103+
rng: () => number;
104+
sleep: (ms: number) => Promise<void>;
105+
write: (chunk: string) => void;
106+
}): Promise<void> {
107+
const { rng, sleep, write } = opts;
108+
let drewFrame = false;
109+
const draw = (lines: string[]) => {
110+
const prefix = drewFrame ? `\x1b[${ROWS}F` : "";
111+
drewFrame = true;
112+
write(`${prefix}${lines.map((line) => `\x1b[K${line}`).join("\n")}\n`);
113+
};
114+
// Ctrl-C during the ~1s sequence would otherwise kill the process with the
115+
// cursor still hidden: default signal death skips the finally block. The
116+
// banner runs before any other component installs signal handlers, so a
117+
// scoped restore-and-exit handler is safe here and removed right after.
118+
const onSignal = (signal: "SIGINT" | "SIGTERM") => {
119+
restoreTerminalState(`claw banner ${signal}`);
120+
process.exit(signal === "SIGINT" ? 130 : 143);
121+
};
122+
const onSigint = () => onSignal("SIGINT");
123+
const onSigterm = () => onSignal("SIGTERM");
124+
process.once("SIGINT", onSigint);
125+
process.once("SIGTERM", onSigterm);
126+
write("\x1b[?25l");
127+
try {
128+
// Molt wipe: dim shell ahead of a bright 2-column edge, color behind it.
129+
const wipeSteps = 9;
130+
for (let step = 0; step <= wipeSteps; step++) {
131+
const edge = Math.round((BANNER_WIDTH * step) / wipeSteps);
132+
const tintAt =
133+
(colored: (text: string) => string): CellTint =>
134+
(col) =>
135+
col < edge ? colored : col < edge + 2 ? theme.accentBright : theme.muted;
136+
draw(
137+
composeFrame({
138+
mascotTint: tintAt(theme.accent),
139+
wordmarkTint: tintAt(identityTint),
140+
}),
141+
);
142+
await sleep(45);
143+
}
144+
// Shimmer: a bright band sweeps the wordmark; rarely it runs twice.
145+
const shimmerPasses = rng() < 0.2 ? 2 : 1;
146+
for (let pass = 0; pass < shimmerPasses; pass++) {
147+
for (let x = MASCOT_WIDTH; x < BANNER_WIDTH + 6; x += 4) {
148+
const band: CellTint = (col) =>
149+
col >= x && col < x + 6 ? theme.accentBright : identityTint;
150+
draw(composeFrame({ wordmarkTint: band }));
151+
await sleep(40);
152+
}
153+
}
154+
// Snip: claws open and close once, sometimes twice.
155+
const snips = rng() < 0.4 ? 2 : 1;
156+
for (let snip = 0; snip < snips; snip++) {
157+
draw(composeFrame({ mascotRows: [...MASCOT_OPEN_ROWS, ...MASCOT_ART.slice(2)] }));
158+
await sleep(95);
159+
draw(staticBannerLines());
160+
await sleep(115);
161+
}
162+
draw(staticBannerLines());
163+
} finally {
164+
process.off("SIGINT", onSigint);
165+
process.off("SIGTERM", onSigterm);
166+
write("\x1b[?25h");
167+
}
168+
}
169+
170+
/**
171+
* Prints the OpenClaw banner: animated on rich interactive terminals, static
172+
* otherwise, plain title on terminals too narrow for the art.
173+
*/
174+
export async function printClawBanner(
175+
runtime: RuntimeEnv,
176+
options: ClawBannerOptions = {},
177+
): Promise<void> {
178+
const columns = options.columns ?? process.stdout.columns ?? 80;
179+
if (columns < BANNER_WIDTH) {
180+
runtime.log(`${plainTitleLine()}\n`);
181+
return;
182+
}
183+
const env = options.env ?? process.env;
184+
const animate =
185+
(options.isTty ?? process.stdout.isTTY ?? false) &&
186+
(options.rich ?? isRich()) &&
187+
!env.CI &&
188+
!env.VITEST;
189+
if (!animate) {
190+
runtime.log(`${staticBannerLines().join("\n")}\n`);
191+
return;
192+
}
193+
await animateBanner({
194+
rng: options.rng ?? Math.random,
195+
sleep: options.sleep ?? defaultSleep,
196+
write: options.write ?? ((chunk) => process.stdout.write(chunk)),
197+
});
198+
(options.write ?? ((chunk: string) => process.stdout.write(chunk)))("\n");
199+
}
200+
201+
export const testing = {
202+
staticBannerLines,
203+
BANNER_WIDTH,
204+
};

‎src/cli/gateway-cli/run.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import { setConsoleSubsystemFilter, setConsoleTimestampPrefix } from "../../logg
5252
import { withDiagnosticPhase } from "../../logging/diagnostic-phase.js";
5353
import { createSubsystemLogger } from "../../logging/subsystem.js";
5454
import { defaultRuntime } from "../../runtime.js";
55+
import { printClawBanner } from "../claw-banner.js";
5556
import { formatCliCommand } from "../command-format.js";
5657
import { formatInvalidConfigPort, formatInvalidPortOption } from "../error-format.js";
5758
import { withProgress } from "../progress.js";
@@ -601,6 +602,12 @@ export async function runGatewayCommand(opts: GatewayRunOpts, hooks: GatewayRunR
601602
process.env.OPENCLAW_RAW_STREAM_PATH = rawStreamPath;
602603
}
603604

605+
// Foreground TTY runs get the banner before the module-loading spinner;
606+
// managed/piped runs (launchd, tests, logs) stay banner-free.
607+
if (process.stdout.isTTY) {
608+
await printClawBanner(defaultRuntime);
609+
}
610+
604611
const startupTrace = createGatewayCliStartupTrace();
605612

606613
// The heaviest part of gateway startup is loading the server module tree

‎src/commands/onboard-guided.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ async function runGuidedOnboardingFlow(
229229
const onboardHelpers = await import("./onboard-helpers.js");
230230
const prompter = await (deps.createPrompter?.() ??
231231
import("../wizard/clack-prompter.js").then(({ createClackPrompter }) => createClackPrompter()));
232-
onboardHelpers.printWizardHeader(runtime);
232+
await onboardHelpers.printWizardHeader(runtime);
233233
await prompter.intro(t("wizard.guided.intro"));
234234
await prompter.note(t("wizard.guided.escapeHatches"), t("wizard.guided.welcomeTitle"));
235235

‎src/commands/onboard-helpers.test.ts‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,11 @@ describe("onboard error summaries", () => {
3535
});
3636

3737
describe("printWizardHeader", () => {
38-
const withColumns = (columns: number | undefined, run: () => void) => {
38+
const withColumns = async (columns: number | undefined, run: () => Promise<void>) => {
3939
const previous = Object.getOwnPropertyDescriptor(process.stdout, "columns");
4040
Object.defineProperty(process.stdout, "columns", { value: columns, configurable: true });
4141
try {
42-
run();
42+
await run();
4343
} finally {
4444
if (previous) {
4545
Object.defineProperty(process.stdout, "columns", previous);
@@ -49,9 +49,9 @@ describe("printWizardHeader", () => {
4949
}
5050
};
5151

52-
it("prints the mascot beside the wordmark with claws above the text line", () => {
52+
it("prints the mascot beside the wordmark with claws above the text line", async () => {
5353
const log = vi.fn();
54-
withColumns(120, () => printWizardHeader({ log } as unknown as RuntimeEnv));
54+
await withColumns(120, () => printWizardHeader({ log } as unknown as RuntimeEnv));
5555
const output = stripAnsi(String(log.mock.calls[0]?.[0]));
5656
const rows = output.split("\n");
5757
// Claw row stands alone above the wordmark; the eye row shares a line with it.
@@ -60,9 +60,9 @@ describe("printWizardHeader", () => {
6060
expect(rows[3]).toContain("██ █ ██");
6161
});
6262

63-
it("falls back to the plain title on narrow terminals", () => {
63+
it("falls back to the plain title on narrow terminals", async () => {
6464
const log = vi.fn();
65-
withColumns(50, () => printWizardHeader({ log } as unknown as RuntimeEnv));
65+
await withColumns(50, () => printWizardHeader({ log } as unknown as RuntimeEnv));
6666
const output = String(log.mock.calls[0]?.[0]);
6767
expect(output).toContain("OPENCLAW");
6868
expect(output).not.toContain("█");

0 commit comments

Comments
 (0)