Skip to content

Commit 091ddf1

Browse files
committed
fix(cli): avoid gateway delay from claw animation
1 parent 4be088e commit 091ddf1

4 files changed

Lines changed: 150 additions & 32 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ Docs: https://docs.openclaw.ai
3232
### Fixes
3333

3434
- **Provider network retries:** align provider read/poll/download and agent-wait recovery for transient connection errors, retry bounded provider `ENOTFOUND` failures while leaving gateway `ENOTFOUND` and non-idempotent create operations fail-fast. (#101496) Thanks @xialonglee.
35+
- **Gateway startup banner:** load gateway modules in parallel with the foreground claw animation and settle the banner early when loading wins, preventing terminal art from delaying readiness. (#105748)
3536
- **Session retry classification:** stop permanent provider errors whose identifiers or payload details merely contain 429/5xx digit sequences from re-sending full context, and share bounded rate-limit-window parsing across retry paths. (#105258) Thanks @destire-mio.
3637
- **LINE directive templates:** suppress confirms and buttons with blank required fields or unlabeled actions while preserving valid titleless buttons and surrounding reply text. (#105520) Thanks @edenfunf.
3738
- **SQLite maintenance schema validation:** reject current-version global and agent databases with missing or drifted canonical tables, constraints, indexes, triggers, or table options before compaction, while accepting supported additive-migration layouts.

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

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,41 @@ describe("printClawBanner", () => {
8787
expect(process.listenerCount("SIGINT")).toBe(before);
8888
});
8989

90+
it("settles on the static frame when parallel work finishes first", async () => {
91+
const staticRows = await runStatic();
92+
const chunks: string[] = [];
93+
const beforeSigint = process.listenerCount("SIGINT");
94+
let settle!: () => void;
95+
const settleWhen = new Promise<void>((resolve) => {
96+
settle = resolve;
97+
});
98+
const { runtime } = runtimeStub();
99+
const banner = printClawBanner(runtime, {
100+
columns: 120,
101+
isTty: true,
102+
rich: true,
103+
env: {},
104+
rng: () => 0.99,
105+
settleWhen,
106+
sleep: () => new Promise<void>(() => {}),
107+
write: (chunk) => chunks.push(chunk),
108+
});
109+
110+
expect(chunks[0]).toBe("\x1b[?25l");
111+
expect(process.listenerCount("SIGINT")).toBe(beforeSigint + 1);
112+
settle();
113+
await expect(banner).resolves.toBe("settled");
114+
115+
const frames = chunks.filter((chunk) => chunk.includes("\x1b[K"));
116+
const finalRows = stripAnsi(frames.at(-1) ?? "")
117+
.split("\n")
118+
.filter((row) => row.length > 0);
119+
expect(finalRows).toEqual(staticRows);
120+
expect(chunks.at(-2)).toBe("\x1b[?25h");
121+
expect(chunks.at(-1)).toBe("\n");
122+
expect(process.listenerCount("SIGINT")).toBe(beforeSigint);
123+
});
124+
90125
it("varies snips and shimmer passes with the rng", async () => {
91126
// rng below the thresholds adds a second shimmer pass and a second snip.
92127
const maximal = (await runAnimated(() => 0)).filter((c) => c.includes("\x1b[K"));

‎src/cli/claw-banner.ts‎

Lines changed: 56 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,14 @@ type ClawBannerOptions = {
4343
env?: NodeJS.ProcessEnv;
4444
/** Injectable randomness for the animation garnish (tests pin it). */
4545
rng?: () => number;
46+
/** Ends the animation on its static frame when parallel startup work settles. */
47+
settleWhen?: PromiseLike<unknown>;
4648
sleep?: (ms: number) => Promise<void>;
4749
write?: (chunk: string) => void;
4850
};
4951

52+
export type ClawBannerResult = "static" | "completed" | "settled";
53+
5054
type CellTint = (col: number) => (text: string) => string;
5155

5256
const identityTint: (text: string) => string = (text) => text;
@@ -101,10 +105,30 @@ const defaultSleep = (ms: number) =>
101105
// canned; every sequence ends on the exact static banner.
102106
async function animateBanner(opts: {
103107
rng: () => number;
108+
settleWhen?: PromiseLike<unknown>;
104109
sleep: (ms: number) => Promise<void>;
105110
write: (chunk: string) => void;
106-
}): Promise<void> {
107-
const { rng, sleep, write } = opts;
111+
}): Promise<Exclude<ClawBannerResult, "static">> {
112+
const { rng, settleWhen, sleep, write } = opts;
113+
let settleRequested = false;
114+
const settleSignal = settleWhen
115+
? Promise.resolve(settleWhen).then(
116+
() => {
117+
settleRequested = true;
118+
},
119+
() => {
120+
settleRequested = true;
121+
},
122+
)
123+
: null;
124+
const pause = async (ms: number): Promise<boolean> => {
125+
if (!settleSignal) {
126+
await sleep(ms);
127+
return true;
128+
}
129+
await Promise.race([sleep(ms), settleSignal]);
130+
return !settleRequested;
131+
};
108132
let drewFrame = false;
109133
const draw = (lines: string[]) => {
110134
const prefix = drewFrame ? `\x1b[${ROWS}F` : "";
@@ -139,7 +163,9 @@ async function animateBanner(opts: {
139163
wordmarkTint: tintAt(identityTint),
140164
}),
141165
);
142-
await sleep(45);
166+
if (!(await pause(45))) {
167+
return "settled";
168+
}
143169
}
144170
// Shimmer: a bright band sweeps the wordmark; rarely it runs twice.
145171
const shimmerPasses = rng() < 0.2 ? 2 : 1;
@@ -148,22 +174,37 @@ async function animateBanner(opts: {
148174
const band: CellTint = (col) =>
149175
col >= x && col < x + 6 ? theme.accentBright : identityTint;
150176
draw(composeFrame({ wordmarkTint: band }));
151-
await sleep(40);
177+
if (!(await pause(40))) {
178+
return "settled";
179+
}
152180
}
153181
}
154182
// Snip: claws open and close once, sometimes twice.
155183
const snips = rng() < 0.4 ? 2 : 1;
156184
for (let snip = 0; snip < snips; snip++) {
157185
draw(composeFrame({ mascotRows: [...MASCOT_OPEN_ROWS, ...MASCOT_ART.slice(2)] }));
158-
await sleep(95);
186+
if (!(await pause(95))) {
187+
return "settled";
188+
}
159189
draw(staticBannerLines());
160-
await sleep(115);
190+
if (!(await pause(115))) {
191+
return "settled";
192+
}
161193
}
162194
draw(staticBannerLines());
195+
return "completed";
163196
} finally {
164-
process.off("SIGINT", onSigint);
165-
process.off("SIGTERM", onSigterm);
166-
write("\x1b[?25h");
197+
try {
198+
// Parallel work owns startup latency; leave a complete banner instead of
199+
// an interrupted frame before its logs or errors take over the terminal.
200+
if (settleRequested && drewFrame) {
201+
draw(staticBannerLines());
202+
}
203+
} finally {
204+
process.off("SIGINT", onSigint);
205+
process.off("SIGTERM", onSigterm);
206+
write("\x1b[?25h");
207+
}
167208
}
168209
}
169210

@@ -174,11 +215,11 @@ async function animateBanner(opts: {
174215
export async function printClawBanner(
175216
runtime: RuntimeEnv,
176217
options: ClawBannerOptions = {},
177-
): Promise<void> {
218+
): Promise<ClawBannerResult> {
178219
const columns = options.columns ?? process.stdout.columns ?? 80;
179220
if (columns < BANNER_WIDTH) {
180221
runtime.log(`${plainTitleLine()}\n`);
181-
return;
222+
return "static";
182223
}
183224
const env = options.env ?? process.env;
184225
const animate =
@@ -188,12 +229,14 @@ export async function printClawBanner(
188229
!env.VITEST;
189230
if (!animate) {
190231
runtime.log(`${staticBannerLines().join("\n")}\n`);
191-
return;
232+
return "static";
192233
}
193-
await animateBanner({
234+
const result = await animateBanner({
194235
rng: options.rng ?? Math.random,
236+
settleWhen: options.settleWhen,
195237
sleep: options.sleep ?? defaultSleep,
196238
write: options.write ?? ((chunk) => process.stdout.write(chunk)),
197239
});
198240
(options.write ?? ((chunk: string) => process.stdout.write(chunk)))("\n");
241+
return result;
199242
}

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

Lines changed: 58 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +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";
55+
import { printClawBanner, type ClawBannerResult } from "../claw-banner.js";
5656
import { formatCliCommand } from "../command-format.js";
5757
import { formatInvalidConfigPort, formatInvalidPortOption } from "../error-format.js";
5858
import { withProgress } from "../progress.js";
@@ -131,20 +131,46 @@ function createGatewayCliStartupTrace() {
131131
);
132132
}
133133
};
134+
const startMeasure = <T>(name: string, run: () => Awaitable<T>) => {
135+
const before = performance.now();
136+
let completedAt = before;
137+
let emitted = false;
138+
const result = withDiagnosticPhase(name, run).finally(() => {
139+
completedAt = performance.now();
140+
});
141+
// Attach both outcomes immediately so callers can finish terminal UI before
142+
// consuming or rethrowing the measured result without an unhandled rejection.
143+
const settled = result.then(
144+
() => {},
145+
() => {},
146+
);
147+
return {
148+
result,
149+
settled,
150+
emit() {
151+
if (emitted) {
152+
return;
153+
}
154+
emitted = true;
155+
emit(name, completedAt - before, completedAt - started);
156+
last = completedAt;
157+
},
158+
};
159+
};
134160
return {
135161
mark(name: string) {
136162
const now = performance.now();
137163
emit(name, now - last, now - started);
138164
last = now;
139165
},
166+
startMeasure,
140167
async measure<T>(name: string, run: () => Awaitable<T>): Promise<T> {
141-
const before = performance.now();
168+
const measurement = startMeasure(name, run);
142169
try {
143-
return await withDiagnosticPhase(name, run);
170+
return await measurement.result;
144171
} finally {
145-
const now = performance.now();
146-
emit(name, now - before, now - started);
147-
last = now;
172+
await measurement.settled;
173+
measurement.emit();
148174
}
149175
},
150176
};
@@ -602,23 +628,36 @@ export async function runGatewayCommand(opts: GatewayRunOpts, hooks: GatewayRunR
602628
process.env.OPENCLAW_RAW_STREAM_PATH = rawStreamPath;
603629
}
604630

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-
611631
const startupTrace = createGatewayCliStartupTrace();
612632

613633
// The heaviest part of gateway startup is loading the server module tree
614-
// (channels, plugins, HTTP stack, etc.). Show a spinner so the user sees
615-
// progress instead of a silent 15-20 s pause (especially on Windows/NTFS).
616-
const { startGatewayServer } = await startupTrace.measure("cli.server-import", () =>
617-
withProgress(
618-
{ label: "Loading gateway modules…", indeterminate: true },
619-
async () => import("../../gateway/server.js"),
620-
),
634+
// (channels, plugins, HTTP stack, etc.). Start it before the foreground TTY
635+
// banner so the animation never extends readiness. If loading wins, the
636+
// banner settles cleanly; otherwise its existing spinner owns the wait.
637+
const serverImportMeasurement = startupTrace.startMeasure(
638+
"cli.server-import",
639+
() => import("../../gateway/server.js"),
621640
);
641+
const rawServerImport = serverImportMeasurement.result;
642+
const bannerDone: Promise<ClawBannerResult> = process.stdout.isTTY
643+
? printClawBanner(defaultRuntime, { settleWhen: rawServerImport })
644+
: Promise.resolve("static");
645+
const loadServerModule = async () => {
646+
try {
647+
const bannerResult = await bannerDone;
648+
return bannerResult === "settled"
649+
? await rawServerImport
650+
: await withProgress(
651+
{ label: "Loading gateway modules…", indeterminate: true },
652+
async () => rawServerImport,
653+
);
654+
} finally {
655+
// Trace output follows banner or spinner cleanup on both success and error.
656+
await serverImportMeasurement.settled;
657+
serverImportMeasurement.emit();
658+
}
659+
};
660+
const { startGatewayServer } = await loadServerModule();
622661

623662
setConsoleTimestampPrefix(true);
624663

0 commit comments

Comments
 (0)