Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(tui): stop the AI SDK warning that froze "Processing" above every reply

Salman Qureshiaaa17276f7d0
diff --git a/src/channels/cli.ts b/src/channels/cli.ts
index bb6fa9ac..794f8c79 100644
--- a/src/channels/cli.ts
+++ b/src/channels/cli.ts
@@ -2,6 +2,7 @@ import React from 'react';
import { EventEmitter } from 'node:events';
import { render } from 'ink';
import fs from 'node:fs';
+import { inspect } from 'node:util';
import path from 'node:path';
import { homedir } from 'node:os';
import { execSync, execFile, execFileSync } from 'node:child_process';
@@ -530,6 +531,7 @@ export class CLIChannel extends BaseChannel {
readonly type = 'cli' as const;
private agentName: string;
private inkInstance: ReturnType<typeof render> | null = null;
+ private restoreConsole: (() => void) | null = null;
private inputHandler: ((text: string) => void) | null = null;
private exitHandler: (() => void) | null = null;
/** Esc-during-a-turn: installed by the boot path with the agent's stop
@@ -646,6 +648,8 @@ export class CLIChannel extends BaseChannel {
// Unmount may throw on a corrupted Yoga heap; shutdown must still
// release the output wrapper and restore the terminal.
try { inkInstance?.unmount(); } catch { /* best effort teardown */ }
+ this.restoreConsole?.();
+ this.restoreConsole = null;
this.stateListeners.clear();
this.tuiOutput?.dispose();
this.tuiOutput = null;
@@ -1261,6 +1265,7 @@ export class CLIChannel extends BaseChannel {
// Single mount. Every later UI update flows through useSyncExternalStore
// notifications — never inkInstance.rerender(), whose synchronous
// reconciler entry caused re-entrant commits and Yoga WASM corruption.
+ this.captureConsole();
this.inkInstance = render(
React.createElement(TuiApp, {
channel: this,
@@ -1282,6 +1287,29 @@ export class CLIChannel extends BaseChannel {
);
}
+ /**
+ * While the TUI owns the terminal nothing may print behind the renderer's
+ * back. The renderer redraws only the rows that changed and assumes the
+ * screen holds exactly what it last wrote; a stray console line (a library
+ * warning, say) shifts everything down, the next erase misses rows, and the
+ * "Processing" block stays frozen in the transcript. Console output goes to
+ * the logger instead (silent unless --verbose) until teardown.
+ */
+ private captureConsole(): void {
+ if (this.restoreConsole) return;
+ const methods = ['log', 'info', 'warn', 'error', 'debug'] as const;
+ const original = methods.map((m) => [m, console[m]] as const);
+ for (const m of methods) {
+ console[m] = (...args: unknown[]) => {
+ const level = m === 'error' ? 'error' : m === 'warn' ? 'warn' : 'debug';
+ logger[level]({ console: m }, args.map((a) => (typeof a === 'string' ? a : inspect(a))).join(' '));
+ };
+ }
+ this.restoreConsole = () => {
+ for (const [m, fn] of original) console[m] = fn;
+ };
+ }
+
private inkPatchWarned = false;
/**
diff --git a/src/core/agent.ts b/src/core/agent.ts
index 6a7329b8..88d79002 100644
--- a/src/core/agent.ts
+++ b/src/core/agent.ts
@@ -392,6 +392,13 @@ class ToolCallLoopDetector {
}
}
+// AI SDK warnings go to Mercury's logger, never straight to the terminal: a raw
+// console.warn lands in the middle of the TUI's live region and the renderer
+// then erases the wrong rows (a stuck "Processing" block in the transcript).
+(globalThis as { AI_SDK_LOG_WARNINGS?: unknown }).AI_SDK_LOG_WARNINGS = (options: { warnings: unknown[]; provider?: string; model?: string }) => {
+ logger.warn({ warnings: options.warnings, provider: options.provider, model: options.model }, 'AI SDK warning');
+};
+
// Test/soak override: MERCURY_MAX_STEPS=3 forces cheap step-budget
// exhaustion to exercise the completion contract end to end.
/**
@@ -1614,6 +1621,9 @@ export class Agent {
const deadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;
const stream = streamText({
model: opts.provider.getModelInstance(),
+ // Mercury builds this system message itself (trusted, not user input);
+ // opting in stops the SDK printing a warning on every call.
+ allowSystemInMessages: true,
messages: this.withCachedSystem(opts.systemPrompt, opts.messages, opts.volatileSystem),
tools: this.capabilities.getTools(),
maxOutputTokens: opts.maxOutputTokens,
@@ -2951,6 +2961,9 @@ export class Agent {
let streamAborted = false;
const streamResult = streamText({
model: provider.getModelInstance(),
+ // Mercury builds this system message itself (trusted, not user input);
+ // opting in stops the SDK printing a warning on every call.
+ allowSystemInMessages: true,
messages: this.withCachedSystem(systemPrompt, providerMessages, volatileSystem),
tools: this.programmingMode.isPlan() ? this.capabilities.getPlanTools() : this.capabilities.getTools(),
maxOutputTokens: providerMaxOutputTokens,
@@ -3064,6 +3077,9 @@ export class Agent {
const continueResult: Awaited<ReturnType<typeof streamText>> = await this.withProviderDeadline(
Promise.resolve(streamText({
model: provider.getModelInstance(),
+ // Mercury builds this system message itself (trusted, not user input);
+ // opting in stops the SDK printing a warning on every call.
+ allowSystemInMessages: true,
messages: this.withCachedSystem(systemPrompt, [
...providerMessages,
{ role: 'assistant', content: continuationText },
@@ -3112,6 +3128,9 @@ export class Agent {
} else {
result = await this.withProviderDeadline(generateText({
model: provider.getModelInstance(),
+ // Mercury builds this system message itself (trusted, not user input);
+ // opting in stops the SDK printing a warning on every call.
+ allowSystemInMessages: true,
messages: this.withCachedSystem(systemPrompt, providerMessages, volatileSystem),
tools: this.programmingMode.isPlan() ? this.capabilities.getPlanTools() : this.capabilities.getTools(),
maxOutputTokens: providerMaxOutputTokens,
@@ -3449,6 +3468,9 @@ export class Agent {
const guardDeadlineAt = Date.now() + MAX_PROVIDER_ATTEMPT_MS;
const guardStream = streamText({
model: guardProvider.getModelInstance(),
+ // Mercury builds this system message itself (trusted, not user input);
+ // opting in stops the SDK printing a warning on every call.
+ allowSystemInMessages: true,
messages: this.withCachedSystem(systemPrompt, messages, volatileSystem),
tools: this.capabilities.getTools(),
maxOutputTokens: effectiveMaxOutputTokens,
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index b15ad84e..08b03cd4 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -1292,7 +1292,7 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
await agent.spotifyClient.authenticateWithCode(code.trim());
await channel.send('Spotify connected successfully! Try: play some music', channelId);
} else {
- await channel.send('Opening browser for Spotify authorization...', channelId);
+ await channel.send(`Opening browser for Spotify authorization...\nIf it doesn't open, visit ${agent.spotifyClient.getLocalLoginUrl()}`, channelId);
await agent.spotifyClient.authenticate();
await channel.send('Spotify connected successfully! Try: play some music', channelId);
}
diff --git a/src/core/system-message-warning.test.ts b/src/core/system-message-warning.test.ts
new file mode 100644
index 00000000..1cab3f7a
--- /dev/null
+++ b/src/core/system-message-warning.test.ts
@@ -0,0 +1,99 @@
+/**
+ * Regression: every model call printed "AI SDK Warning: System messages in the
+ * prompt…" straight to the terminal. The raw console.warn landed inside the
+ * TUI's live region, the renderer then erased the wrong rows, and a frozen
+ * "Processing · 0s / Starting task" block stayed above every reply.
+ */
+import { describe, expect, it, vi } from 'vitest';
+import fs from 'node:fs';
+import path from 'node:path';
+import { streamText } from 'ai';
+import { MockLanguageModelV3 } from 'ai/test';
+import { CLIChannel } from '../channels/cli.js';
+import './agent.js';
+
+const AGENT_SRC = fs.readFileSync(path.join(__dirname, 'agent.ts'), 'utf8');
+
+function mockModel() {
+ return new MockLanguageModelV3({
+ doStream: async () => ({
+ stream: new ReadableStream({
+ start(c) {
+ c.enqueue({ type: 'text-start', id: 't' });
+ c.enqueue({ type: 'text-delta', id: 't', delta: 'hi' });
+ c.enqueue({ type: 'text-end', id: 't' });
+ c.enqueue({
+ type: 'finish',
+ finishReason: { unified: 'stop', raw: 'stop' },
+ usage: {
+ inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 },
+ outputTokens: { total: 1, text: 1, reasoning: 0 },
+ },
+ });
+ c.close();
+ },
+ }),
+ }),
+ });
+}
+
+describe('AI SDK system-message warning', () => {
+ it('every call that passes Mercury\'s own system message opts in', () => {
+ const sites = AGENT_SRC.split('\n')
+ .map((line, i) => ({ line, i }))
+ .filter(({ line }) => /messages: this\.withCachedSystem\(/.test(line));
+ expect(sites.length).toBeGreaterThan(0);
+ for (const { i } of sites) {
+ const window = AGENT_SRC.split('\n').slice(Math.max(0, i - 4), i).join('\n');
+ expect(window, `agent.ts:${i + 1}`).toContain('allowSystemInMessages: true');
+ }
+ });
+
+ async function warningsFor(allowSystemInMessages: boolean | undefined): Promise<number> {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const result = streamText({
+ model: mockModel(),
+ allowSystemInMessages,
+ messages: [{ role: 'system', content: 'You are Mercury.' }, { role: 'user', content: 'so sup' }],
+ });
+ await result.text;
+ return warn.mock.calls.filter((c) => String(c[0]).includes('System messages')).length;
+ } finally {
+ warn.mockRestore();
+ }
+ }
+
+ it('a cached system message with the opt-in prints nothing', async () => {
+ expect(await warningsFor(undefined)).toBe(1); // control: the SDK does warn
+ expect(await warningsFor(true)).toBe(0);
+ });
+
+
+ it('other SDK warnings go to the logger, not the console', () => {
+ expect(typeof (globalThis as { AI_SDK_LOG_WARNINGS?: unknown }).AI_SDK_LOG_WARNINGS).toBe('function');
+ });
+});
+
+describe('console while the TUI is mounted', () => {
+ it('never reaches the terminal, and is restored on teardown', () => {
+ const channel = new CLIChannel() as any;
+ const original = console.warn;
+ const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);
+ const errWrite = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
+ try {
+ channel.captureConsole();
+ expect(console.warn).not.toBe(original);
+ console.warn('AI SDK Warning: stray');
+ console.log('stray log');
+ expect(write).not.toHaveBeenCalled();
+ expect(errWrite).not.toHaveBeenCalled();
+ channel.restoreConsole();
+ expect(console.warn).toBe(original);
+ } finally {
+ write.mockRestore();
+ errWrite.mockRestore();
+ channel.restoreConsole?.();
+ }
+ });
+});
diff --git a/src/spotify/client.ts b/src/spotify/client.ts
index a498fdc0..ad6897b5 100644
--- a/src/spotify/client.ts
+++ b/src/spotify/client.ts
@@ -127,7 +127,7 @@ export class SpotifyClient {
const port = new URL(redirectUri).port || '8888';
server.listen(parseInt(port, 10), () => {
logger.info({ port }, 'Spotify OAuth server listening');
- const callbackUrl = `http://127.0.0.1:${port}/login`;
+ const callbackUrl = this.getLocalLoginUrl();
console.log(`\n ${'─'.repeat(50)}`);
console.log(` Spotify Authorization`);
console.log(` ${'─'.repeat(50)}`);
@@ -146,6 +146,12 @@ export class SpotifyClient {
});
}
+ /** The local page authenticate() serves; it redirects to Spotify. */
+ getLocalLoginUrl(): string {
+ const port = new URL(this.config.spotify.redirectUri).port || '8888';
+ return `http://127.0.0.1:${port}/login`;
+ }
+
getAuthUrl(): string {
const clientId = this.config.spotify.clientId;
const redirectUri = this.config.spotify.redirectUri;