Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
test(cli-socket): undo the output capture after each test and drop a closed serve's exit listener
garrytanbd0ceda23e4e
diff --git a/src/core/cli-socket/output-capture.ts b/src/core/cli-socket/output-capture.tsindex 50da4d3897..b1c38d2d93 100644--- a/src/core/cli-socket/output-capture.ts+++ b/src/core/cli-socket/output-capture.ts@@ -35,16 +35,16 @@ export class OutputCapture {}const store = new AsyncLocalStorage<OutputCapture>();-let installed = false;+let uninstall: (() => void) | undefined;/** Route console and stderr writes made inside a capture scope into it; outside a scope nothing changes. Idempotent. */export function installOutputCapture(): void {- if (installed) return;- installed = true;+ if (uninstall) return;setWarnOnceScope(() => store.getStore()?.warned);setSourceNoteScope(() => store.getStore());setFallbackHopScope(() => store.getStore()?.fallbackHops);const methods = [['log', 'stdout'], ['info', 'stdout'], ['debug', 'stdout'], ['warn', 'stderr'], ['error', 'stderr']] as const;+ const originals = methods.map(([method]) => [method, console[method]] as const);for (const [method, stream] of methods) {const original = console[method];console[method] = (...args: unknown[]): void => {@@ -63,6 +63,23 @@ export function installOutputCapture(): void {if (callback) queueMicrotask(callback);return true;} as typeof process.stderr.write;+ uninstall = () => {+ for (const [method, original] of originals) console[method] = original;+ process.stderr.write = originalWrite;+ setWarnOnceScope(() => undefined);+ setSourceNoteScope(() => undefined);+ setFallbackHopScope(() => undefined);+ };+}++/**+ * Test-only: put console, stderr and the three per-request scopes back as they were before installOutputCapture.+ * The capture is process-global, so a test file that starts a serve or installs it must call this from an after+ * hook: otherwise every later file in the same bun process runs with the serve's routing (#7494).+ */+export function _uninstallOutputCaptureForTests(): void {+ uninstall?.();+ uninstall = undefined;}export function withOutputCapture<T>(capture: OutputCapture, fn: () => Promise<T>): Promise<T> {diff --git a/src/core/cli-socket/server.ts b/src/core/cli-socket/server.tsindex 7d66bd994c..2f8ba315d8 100644--- a/src/core/cli-socket/server.ts+++ b/src/core/cli-socket/server.ts@@ -222,6 +222,7 @@ export async function startCliSocketServer(opts: CliSocketServerOptions): Promisconst close = () => {if (closing) return;closing = true;+ process.off('exit', close);refusals.flush();server.close();for (const socket of sockets) socket.destroy();diff --git a/test/cli-socket.test.ts b/test/cli-socket.test.tsindex b1f9d79729..2aefcdb83b 100644--- a/test/cli-socket.test.ts+++ b/test/cli-socket.test.ts@@ -38,7 +38,7 @@ import { cliSocketRefusalsEntry } from '../src/commands/doctor/checks/cli-socketimport { loadOperation } from '../src/core/operation-load.ts';import { isResultFrame, reviveOperationError, serializeOperationError, type CliSocketRequest, type ResultFrame } from '../src/core/cli-socket/protocol.ts';import { queueFirstFallbackHop, takeChatFallbackHopNotices, __resetChatFallbackHopNoticeForTests } from '../src/core/ai/fallback-hop-queue.ts';-import { installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';+import { _uninstallOutputCaptureForTests, installOutputCapture, OutputCapture, withOutputCapture } from '../src/core/cli-socket/output-capture.ts';import { opError, OperationError } from '../src/core/ops/contract.ts';import { loadConfigWithEngine, type GBrainConfig } from '../src/core/config.ts';import { withEnv } from './helpers/with-env.ts';@@ -56,7 +56,7 @@ function runDir(): string {let root: string;beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'gbrain-cli-sock-')); });-afterEach(() => { rmSync(root, { recursive: true, force: true }); });+afterEach(() => { rmSync(root, { recursive: true, force: true }); _uninstallOutputCaptureForTests(); });function homeWithConfig(name: string, body = '{"engine":"postgres"}'): { dir: string; file: string } {const dir = join(root, name, '.gbrain');@@ -348,6 +348,17 @@ describe('serve listener', () => {return { binding, lines, path: cliSocketPath(home) };}+ test('closing a serve drops its exit listener and the test undo puts console and stderr back', async () => {+ const before = { exits: process.listenerCount('exit'), log: console.log, error: console.error, write: process.stderr.write };+ const { binding } = await start();+ expect(process.listenerCount('exit')).toBe(before.exits + 1);+ expect(console.log).not.toBe(before.log);+ binding!.close();+ expect(process.listenerCount('exit')).toBe(before.exits);+ _uninstallOutputCaptureForTests();+ expect([console.log, console.error, process.stderr.write]).toEqual([before.log, before.error, before.write]);+ });+test('this platform reads peer credentials (otherwise the serve would refuse to start)', () => {if (process.platform === 'linux' || process.platform === 'darwin') expect(peerCredSupport().ok).toBe(true);});