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(doctor): reconfigure applies — restart the daemon on a real config change; dashboard offers Restart (1.3.9)

Salman Qureshibe75132bd3a6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 95c4bec7..def6c055 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## 1.3.9 — hotfix: `mercury doctor` and dashboard saves take effect
+
+- **`mercury doctor` applies what you changed.** Providers, keys and channels are read at boot, so a reconfigure that only wrote the file looked like it did nothing until a manual `mercury restart`. Doctor now restarts the running daemon when the configuration actually changed (the Telegram/Discord commands already did this).
+- **Dashboard saves say "restart to apply" and offer a Restart button** (Settings → Restart Mercury), backed by a loopback-only `POST /api/restart`.
+
## 1.3.8 — hotfix: live reply rendering and spinners in the attach TUI
- **No more cyan bar beside a streaming reply.** The attach TUI (what `mercury` opens) drew the live reply with a cyan `│` strip that disappeared once the reply settled. The live tail now renders exactly like the settled block — same `MERCURY:` header, indent and markdown.
diff --git a/README.md b/README.md
index 9f69f23d..ea714d16 100644
--- a/README.md
+++ b/README.md
@@ -21,7 +21,7 @@
</p>
<p align="center">
- <strong>🔖 Current Stable: v1.3.8 — Steady Mercury</strong>
+ <strong>🔖 Current Stable: v1.3.9 — Steady Mercury</strong>
</p>
<p align="center">
diff --git a/package-lock.json b/package-lock.json
index 56667419..14a2cd85 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.8",
+ "version": "1.3.9",
"lockfileVersion": 2,
"requires": true,
"packages": {
"": {
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.8",
+ "version": "1.3.9",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
diff --git a/package.json b/package.json
index 0423c0e8..24b19412 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@cosmicstack/mercury-agent",
- "version": "1.3.8",
+ "version": "1.3.9",
"description": "Soul-driven AI agent with Second Brain memory, permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI or Telegram.",
"type": "module",
"main": "dist/index.js",
diff --git a/src/cli/daemon.ts b/src/cli/daemon.ts
index 65d30365..d5a26ef1 100644
--- a/src/cli/daemon.ts
+++ b/src/cli/daemon.ts
@@ -45,6 +45,23 @@ export function buildDaemonSpawnArgs(): { command: string; args: string[] } {
return { command: process.execPath, args: [script, 'start', '--daemon'] };
}
+/**
+ * Restart the daemon from INSIDE it (dashboard "Restart Mercury"): the
+ * process cannot stop and restart itself, so a detached `mercury restart`
+ * does it after we reply. Returns false when the entry script is unknown.
+ */
+export function spawnDetachedRestart(): boolean {
+ try {
+ const { command, args } = buildDaemonSpawnArgs();
+ const restartArgs = [...args.slice(0, -2), 'restart'];
+ const child = spawn(command, restartArgs, { detached: true, stdio: 'ignore', env: { ...process.env }, windowsHide: process.platform === 'win32' });
+ child.unref();
+ return !!child.pid;
+ } catch {
+ return false;
+ }
+}
+
const PID_FILE = 'daemon.pid';
const FOREGROUND_PID_FILE = 'foreground.pid';
const LOG_FILE = 'daemon.log';
diff --git a/src/index.ts b/src/index.ts
index f674b0cb..16c9a293 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,5 @@
import { readFileSync, writeFileSync, existsSync, statSync, chmodSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve as pathResolve } from 'node:path';
import { Command } from 'commander';
@@ -874,6 +875,15 @@ function printSlackAccessState(config: MercuryConfig): void {
console.log(` Pending: ${pending.length > 0 ? chalk.yellow(pendingSummary) : chalk.dim('none')}`);
}
+/** Content hash of mercury.yaml — `mercury doctor` restarts the daemon only when it changed. */
+function configFingerprint(): string {
+ try {
+ return createHash('sha256').update(readFileSync(join(getMercuryHome(), 'mercury.yaml'))).digest('hex');
+ } catch {
+ return '';
+ }
+}
+
function restartDaemonIfRunning(message?: string): void {
const daemon = getDaemonStatus();
if (!daemon.running) return;
@@ -3983,11 +3993,18 @@ program
runStorageDoctor();
return;
}
+ // The daemon reads providers, keys and channels at boot: a reconfigure
+ // that only wrote the file looked like it did nothing until a manual
+ // `mercury restart`. Restart it ourselves when something changed.
+ const before = configFingerprint();
if (isSetupComplete()) {
await configure(loadConfig());
} else {
await configure();
}
+ if (configFingerprint() !== before) {
+ restartDaemonIfRunning('Applying your changes — restarting the background Mercury...');
+ }
});
program
diff --git a/src/web/api/config.ts b/src/web/api/config.ts
index 6942a311..daacafb2 100644
--- a/src/web/api/config.ts
+++ b/src/web/api/config.ts
@@ -25,7 +25,8 @@ config.put('/api/config', async (c) => {
if (body.defaultProvider !== undefined) cfg.providers.default = body.defaultProvider;
if (body.tokenBudget !== undefined) cfg.tokens.dailyBudget = body.tokenBudget;
saveConfig(cfg);
- return c.json({ success: true });
+ // Providers and keys are read at boot — the save is durable, not live.
+ return c.json({ success: true, restartRequired: true });
});
export default config;
\ No newline at end of file
diff --git a/src/web/api/lifecycle.ts b/src/web/api/lifecycle.ts
index bf73e40d..fff862fa 100644
--- a/src/web/api/lifecycle.ts
+++ b/src/web/api/lifecycle.ts
@@ -1,6 +1,11 @@
import { Hono } from 'hono';
import { readAttachToken } from '../auth.js';
import { isLoopbackRequest } from '../middleware.js';
+import { spawnDetachedRestart } from '../../cli/daemon.js';
+
+let restartSpawner: () => boolean = spawnDetachedRestart;
+/** Test seam. */
+export function setRestartSpawner(fn: () => boolean): void { restartSpawner = fn; }
/**
* Local, authenticated shutdown for `mercury stop` / `restart` / `upgrade`.
@@ -29,6 +34,22 @@ function bearerToken(header: string | undefined): string | null {
return match ? match[1].trim() : null;
}
+/**
+ * Apply saved configuration by restarting the runtime. Loopback only — the
+ * dashboard runs on this machine; the auth guard has already admitted the
+ * session (or attach token). Providers, channels and keys are read at boot,
+ * so this is how a dashboard save actually takes effect.
+ */
+lifecycle.post('/api/restart', (c) => {
+ if (!isLoopbackRequest(c)) {
+ return c.json({ error: 'Restart is only accepted from this machine' }, 403);
+ }
+ if (!restartSpawner()) {
+ return c.json({ error: 'Could not start the restart helper — run `mercury restart` in a terminal' }, 503);
+ }
+ return c.json({ ok: true, pid: process.pid, message: 'Restarting — back in a few seconds' }, 202);
+});
+
lifecycle.post('/api/shutdown', (c) => {
if (!isLoopbackRequest(c)) {
return c.json({ error: 'Shutdown is only accepted from this machine' }, 403);
diff --git a/src/web/api/providers.ts b/src/web/api/providers.ts
index 353350f7..cde3b9db 100644
--- a/src/web/api/providers.ts
+++ b/src/web/api/providers.ts
@@ -45,7 +45,8 @@ providers.post('/api/providers/:name', async (c) => {
if (body.enabled !== undefined) p.enabled = body.enabled;
saveConfig(config);
- return c.json({ success: true });
+ // Keys and models are read at boot — the save is durable, not live.
+ return c.json({ success: true, restartRequired: true });
});
providers.post('/api/providers/:name/test', async (c) => {
diff --git a/src/web/lifecycle-restart.test.ts b/src/web/lifecycle-restart.test.ts
new file mode 100644
index 00000000..e269edbf
--- /dev/null
+++ b/src/web/lifecycle-restart.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import lifecycle, { setRestartSpawner } from './api/lifecycle.js';
+
+/**
+ * A dashboard save (providers, keys, default model) is durable but the
+ * runtime reads it at boot; `mercury doctor` had the same gap. The runtime
+ * must offer the restart and the CLI must do it when the file changed.
+ */
+describe('POST /api/restart', () => {
+ it('is loopback-only and hands off to a detached restart', async () => {
+ let spawned = 0;
+ setRestartSpawner(() => { spawned++; return true; });
+ const remote = await lifecycle.request('http://127.0.0.1:6174/api/restart', { method: 'POST' }, { incoming: { socket: { remoteAddress: '10.0.0.7' } } });
+ expect(remote.status).toBe(403);
+ const local = await lifecycle.request('http://127.0.0.1:6174/api/restart', { method: 'POST' }, { incoming: { socket: { remoteAddress: '127.0.0.1' } } });
+ expect(local.status).toBe(202);
+ expect(spawned).toBe(1);
+ setRestartSpawner(() => false);
+ const failed = await lifecycle.request('http://127.0.0.1:6174/api/restart', { method: 'POST' }, { incoming: { socket: { remoteAddress: '127.0.0.1' } } });
+ expect(failed.status).toBe(503);
+ });
+
+ it('mercury doctor restarts the running daemon when the config changed', () => {
+ const index = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'index.ts'), 'utf8').replace(/\r\n/g, '\n');
+ const doctor = index.slice(index.indexOf(".command('doctor')"), index.indexOf(".command('status')"));
+ expect(doctor).toContain('const before = configFingerprint();');
+ expect(doctor).toContain("if (configFingerprint() !== before) {\n restartDaemonIfRunning(");
+ });
+});
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index 6aac1898..bddaab29 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -90,7 +90,9 @@ export const auth = {
// ── Config ──
export const config = {
get: () => get<AppConfig>("/api/config"),
- update: (data: Partial<AppConfig>) => put<{ success: boolean }>("/api/config", data),
+ update: (data: Partial<AppConfig>) => put<{ success: boolean; restartRequired?: boolean }>("/api/config", data),
+ /** Apply saved configuration: the runtime reads providers/keys at boot. */
+ restart: () => post<{ ok: boolean; message: string }>("/api/restart"),
};
// ── Providers ──
diff --git a/ui/src/pages/Providers.tsx b/ui/src/pages/Providers.tsx
index d507a11d..c23435f3 100644
--- a/ui/src/pages/Providers.tsx
+++ b/ui/src/pages/Providers.tsx
@@ -126,7 +126,7 @@ export function ProvidersPage() {
model: f.model,
enabled: f.enabled,
});
- showFeedback(name, "success", "Configuration saved");
+ showFeedback(name, "success", "Saved — restart Mercury to apply (Settings → Restart Mercury, or `mercury restart`)");
updateForm(name, { apiKey: "", saving: false });
fetchProviders();
} catch (e) {
diff --git a/ui/src/pages/Settings.tsx b/ui/src/pages/Settings.tsx
index f536c88e..96b53255 100644
--- a/ui/src/pages/Settings.tsx
+++ b/ui/src/pages/Settings.tsx
@@ -24,6 +24,8 @@ import { useThemeStore } from "@/stores/theme";
interface Feedback {
type: "success" | "error";
message: string;
+ /** The save is durable but the runtime reads it at boot — offer the restart. */
+ restart?: boolean;
}
function FeedbackBanner({ feedback }: { feedback: Feedback | null }) {
@@ -50,6 +52,15 @@ function FeedbackBanner({ feedback }: { feedback: Feedback | null }) {
<XCircle className="h-4 w-4 shrink-0" />
)}
{feedback.message}
+ {feedback.restart && (
+ <button
+ type="button"
+ className="ml-auto rounded-md border border-emerald-500/40 px-2 py-0.5 text-xs hover:bg-emerald-500/10"
+ onClick={() => { void api.config.restart().then(() => window.setTimeout(() => window.location.reload(), 6000)); }}
+ >
+ Restart Mercury
+ </button>
+ )}
</div>
</motion.div>
)}
@@ -142,8 +153,8 @@ export function SettingsPage() {
const saveIdentity = async () => {
setIdentitySaving(true);
try {
- await api.config.update({ identity, defaultProvider, tokenBudget });
- showIdentityFb({ type: "success", message: "Settings saved" });
+ const saved = await api.config.update({ identity, defaultProvider, tokenBudget });
+ showIdentityFb({ type: "success", message: saved.restartRequired ? "Saved — restart Mercury to apply" : "Settings saved", restart: !!saved.restartRequired });
} catch (e) {
showIdentityFb({
type: "error",