Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(platform): detect Termux on android; service install never exits; pin and verify the Ink patch
Salman Qureshi2f1d4d87cfb4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6cb76251..db6df28a 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -133,6 +133,13 @@ jobs:node scripts/post-build.cjsnode -e "try { const Database = require('better-sqlite3'); const db = new Database(':memory:'); db.prepare('select 1').get(); db.close(); console.log('better-sqlite3 OK'); } catch (e) { console.log('better-sqlite3 unavailable (optional on Termux):', e.message); }"node -e "const { spawnSync } = require('node:child_process'); const r = spawnSync(process.execPath, ['dist/index.js', '--help'], { encoding: 'utf8' }); if (r.status !== 0 || !r.stdout.includes('Usage:')) process.exit(1)"+ # P0.6 Termux detection: Termux's own Node is an Android build, so+ # process.platform is 'android' on real devices ('linux' only for+ # glibc/proot builds). Print it, and assert that `service install`+ # (what autoDaemonize() runs after the wizard) is a clean Termux+ # hint with exit 0 — never "Unsupported platform: android" + exit 1.+ node -e "console.log('process.platform =', process.platform); if (process.platform !== 'android' && process.platform !== 'linux') { console.error('unexpected process.platform for Termux'); process.exit(1) }"+ node -e "const { spawnSync } = require('node:child_process'); const r = spawnSync(process.execPath, ['dist/index.js', 'service', 'install'], { encoding: 'utf8' }); const out = (r.stdout || '') + (r.stderr || ''); console.log(out); if (r.status !== 0 || /Unsupported platform/.test(out) || !/Termux/.test(out)) { console.error('service install on Termux must print the Termux hint and exit 0 (status ' + r.status + ')'); process.exit(1) }"node node_modules/vitest/vitest.mjs runCI_SCRIPTchmod +x /tmp/termux-ci.shdiff --git a/package-lock.json b/package-lock.jsonindex 9c792536..96c349c7 100644--- a/package-lock.json+++ b/package-lock.json@@ -25,7 +25,7 @@"dotenv": "^16.4.7","grammy": "^1.42.0","hono": "^4.12.15",- "ink": "^5.2.1",+ "ink": "5.2.1","marked": "^14.1.4","node-cron": "^3.0.3","ollama-ai-provider": "^1.2.0",diff --git a/package.json b/package.jsonindex 30f01ee3..588287f9 100644--- a/package.json+++ b/package.json@@ -20,7 +20,7 @@"typecheck": "tsc --noEmit","test": "vitest run","test:watch": "vitest",- "postinstall": "patch-package || echo 'patch-package unavailable — skipping ink patch (dev installs only)'",+ "postinstall": "patch-package || node scripts/apply-ink-patch.cjs || echo 'WARNING: ink patch not applied — run: node scripts/apply-ink-patch.cjs'","prepublishOnly": "npm run build"},"keywords": [@@ -59,6 +59,7 @@"files": ["dist","patches",+ "scripts/apply-ink-patch.cjs","src/web/static"],"dependencies": {@@ -77,7 +78,7 @@"dotenv": "^16.4.7","grammy": "^1.42.0","hono": "^4.12.15",- "ink": "^5.2.1",+ "ink": "5.2.1","marked": "^14.1.4","node-cron": "^3.0.3","ollama-ai-provider": "^1.2.0",diff --git a/scripts/apply-ink-patch.cjs b/scripts/apply-ink-patch.cjsindex 20062b1e..fe933b64 100644--- a/scripts/apply-ink-patch.cjs+++ b/scripts/apply-ink-patch.cjs@@ -26,7 +26,18 @@ const root = path.join(__dirname, '..');* exercise the applier against a synthetic ink tree without touching the* real node_modules. */function pathsFor(projectRoot) {- const inkDir = path.join(projectRoot, 'node_modules', 'ink', 'build');+ let inkDir = path.join(projectRoot, 'node_modules', 'ink', 'build');+ // When Mercury is installed as a dependency (not globally), npm hoists ink+ // to the consumer's node_modules — `<root>/node_modules/ink` does not+ // exist. Resolve the ink that Node will actually load from this root;+ // the plain join above stays as the fallback (synthetic trees in tests+ // carry no package.json for the resolver to find).+ try {+ const resolved = require.resolve('ink', { paths: [projectRoot] });+ if (fs.existsSync(resolved)) inkDir = path.dirname(resolved);+ } catch {+ // not installed / not resolvable — fall back to the conventional path+ }return {reconcilerPath: path.join(inkDir, 'reconciler.js'),staticJsPath: path.join(inkDir, 'components', 'Static.js'),@@ -388,5 +399,8 @@ if (require.main === module) {console.error(' ⚠ INK FIXES NOT APPLIED — the Yoga WASM crash class is UNPATCHED in this install.');console.error(` Reason: ${result.error}`);console.error(' Fix: reinstall dependencies (npm install) and re-run the build.');+ // Non-zero so a postinstall chain (`patch-package || node scripts/apply-ink-patch.cjs || echo …`)+ // falls through to the loud warning instead of reporting success.+ process.exitCode = 1;}}\ No newline at end of filediff --git a/scripts/verify-package.cjs b/scripts/verify-package.cjsindex 4c9d3e94..9a7f25b4 100755--- a/scripts/verify-package.cjs+++ b/scripts/verify-package.cjs@@ -60,12 +60,32 @@ check('no dangling script references', () => {const devOnlyScripts = ['build', 'build:ui', 'build:bin', 'build:bin:all', 'build:bin:force', 'build:bin:all:force', 'dev', 'lint', 'typecheck', 'test', 'test:watch', 'prepublishOnly'];for (const [key, val] of Object.entries(scripts)) {if (devOnlyScripts.includes(key)) continue;- if (val.includes('scripts/') || val.includes('bash ')) {+ if (val.includes('bash ')) {throw new Error(`script "${key}" references unpublished path: ${val}`);}+ // A `scripts/<file>` reference is fine only when that file ships in the+ // tarball (e.g. the postinstall ink-patch fallback).+ for (const m of val.matchAll(/scripts\/[\w.-]+/g)) {+ if (!existsSync(join(modDir, m[0]))) {+ throw new Error(`script "${key}" references unpublished path ${m[0]}: ${val}`);+ }+ }}});+check('scripts/apply-ink-patch.cjs ships in the tarball', () => {+ if (!existsSync(join(modDir, 'scripts', 'apply-ink-patch.cjs'))) throw new Error('missing scripts/apply-ink-patch.cjs');+});++check('ink is pinned exactly and the installed copy is patched', () => {+ const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));+ const ink = pkg.dependencies && pkg.dependencies.ink;+ if (!ink || !/^\d+\.\d+\.\d+$/.test(ink)) throw new Error(`ink must be pinned exactly (got ${ink})`);+ const { isPatched, pathsFor } = require(join(modDir, 'scripts', 'apply-ink-patch.cjs'));+ // ink is hoisted to the install root; pathsFor resolves it from modDir.+ if (!isPatched(pathsFor(modDir))) throw new Error('installed ink is NOT patched (Static.itemKey / frame gate markers missing) — postinstall fallback failed');+});+check('better-sqlite3 is optional', () => {const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));if (pkg.dependencies && pkg.dependencies['better-sqlite3']) {diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 1c9e163c..872133f3 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -16,6 +16,7 @@ import { TASK_SUMMARY_FILE_LIMIT } from '../ui/types.js';import { TuiApp } from '../ui/App.js';import { nextTip } from '../ui/tips.js';import { ResilientTuiOutput } from '../ui/resilient-output.js';+import { detectInkPatch, inkPatchWarning } from '../ui/ink-patch-check.js';/*** Strip mouse-report escape sequences from terminal input before Ink sees@@ -1061,6 +1062,7 @@ export class CLIChannel extends BaseChannel {this.tuiOutput?.dispose();this.tuiOutput = new ResilientTuiOutput(process.stdout, process.stderr);+ this.warnIfInkUnpatched();// 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.@@ -1084,6 +1086,32 @@ export class CLIChannel extends BaseChannel {);}+ private inkPatchWarned = false;++ /**+ * Stock ink ignores `<Static itemKey>`: the transcript silently stops+ * rendering new messages after ~100 (and the Yoga crash class is live).+ * The patch is applied by postinstall, which npm users never see fail —+ * so say it once, in the transcript, with the one command that fixes it.+ * Never aborts: a degraded TUI beats no TUI for a hotfix.+ */+ private warnIfInkUnpatched(): void {+ if (this.inkPatchWarned) return;+ this.inkPatchWarned = true;+ try {+ const status = detectInkPatch();+ if (status.patched) return;+ const text = inkPatchWarning(status);+ logger.warn({ missing: status.missing, inkBuildDir: status.inkBuildDir }, 'ink patch not applied');+ this.trimAndSetMessages([+ ...this.state.chatMessages,+ { id: `ink-patch-${Date.now().toString(36)}`, role: 'system', content: text, timestamp: Date.now() },+ ]);+ } catch (err) {+ logger.debug({ err }, 'ink patch detection failed');+ }+ }+private stdinProxy: TtyStdinProxy | null = null;/** Install the filtered-stdin proxy: Ink reads clean text; the mousediff --git a/src/cli/service.ts b/src/cli/service.tsindex a1a9f291..405aa02b 100644--- a/src/cli/service.ts+++ b/src/cli/service.ts@@ -76,12 +76,20 @@ function getServiceLaunchArgs(): string[] {return [getNodeBinPath(), getDistPath(), 'start', '--daemon'];}-export function installService(): void {+/**+ * Install the login/boot service. Returns whether a system service now+ * exists. Never calls `process.exit`: this runs inside the setup wizard and+ * `mercury up` (`autoDaemonize`), where a hard exit aborts the flow before+ * the daemon is even started. Termux (no systemd; `process.platform` is+ * `'android'` on real devices) and other unsupported platforms print a hint+ * and return false so the caller can still daemonize for this session.+ */+export function installService(): boolean {const platform = process.platform;if (isTermux()) {showTermuxServiceHelp('install');- return;+ return false;}if (platform === 'darwin') {@@ -91,17 +99,19 @@ export function installService(): void {} else if (platform === 'win32') {installWindows();} else {- console.log(chalk.red(` Unsupported platform: ${platform}`));- process.exit(1);+ console.log(chalk.yellow(` System service is not supported on this platform (${platform}).`));+ console.log(chalk.dim(' Run `mercury up` manually to start the daemon for this session.'));+ return false;}+ return true;}-export function uninstallService(): void {+export function uninstallService(): boolean {const platform = process.platform;if (isTermux()) {showTermuxServiceHelp('uninstall');- return;+ return false;}if (platform === 'darwin') {@@ -111,9 +121,10 @@ export function uninstallService(): void {} else if (platform === 'win32') {uninstallWindows();} else {- console.log(chalk.red(` Unsupported platform: ${platform}`));- process.exit(1);+ console.log(chalk.yellow(` System service is not supported on this platform (${platform}) — nothing to uninstall.`));+ return false;}+ return true;}/**@@ -245,11 +256,11 @@ function waitForServiceStop(): boolean {function showTermuxServiceHelp(action: 'install' | 'uninstall' | 'status'): void {console.log('');- console.log(chalk.yellow(` System service ${action} is not available in Termux (systemd is not present).`));- console.log(chalk.dim(' Start Mercury with: mercury start'));- console.log(chalk.dim(' Check it with: mercury status'));- console.log(chalk.dim(' Stop it with: mercury stop'));- console.log(chalk.dim(' For boot startup, use the Termux:Boot add-on and a ~/.termux/boot script.'));+ console.log(chalk.yellow(` System service ${action} is not supported on Termux yet (no systemd on Android).`));+ console.log(chalk.dim(' Start Mercury manually with: mercury up (or: mercury start)'));+ console.log(chalk.dim(' Check it with: mercury status'));+ console.log(chalk.dim(' Stop it with: mercury stop'));+ console.log(chalk.dim(' For boot startup, install the Termux:Boot add-on and put `mercury up` in ~/.termux/boot/mercury.sh.'));console.log('');}diff --git a/src/index.ts b/src/index.tsindex 61ca9530..ccdebc3e 100644--- a/src/index.ts+++ b/src/index.ts@@ -76,6 +76,7 @@ import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeimport { runUninstall } from './cli/uninstall.js';import { runAttach } from './cli/attach.js';import { installService, uninstallService, showServiceStatus, isServiceInstalled } from './cli/service.js';+import { detectInkPatch, inkPatchFixCommand } from './ui/ink-patch-check.js';import { runWithWatchdog } from './cli/watchdog.js';import { setGitHubToken } from './utils/github.js';import { selectWithArrowKeys } from './utils/arrow-select.js';@@ -2254,10 +2255,12 @@ function autoDaemonize(): void {console.log(chalk.dim(' Setting up background mode...'));+ // installService() never exits the process (Termux / unsupported platforms+ // print a hint and return false) \u2014 the daemon is still started below so+ // the wizard flow completes on phones too.+ let serviceInstalled = false;try {- if (!isServiceInstalled()) {- installService();- }+ serviceInstalled = isServiceInstalled() || installService();} catch {console.log(chalk.dim(' Service install skipped (can run `mercury service install` later).'));}@@ -2266,7 +2269,11 @@ function autoDaemonize(): void {if (ok) {const status = getDaemonStatus();console.log(chalk.green(` \u2713 Mercury is running in background (PID: ${status.pid})`));- console.log(chalk.green(' \u2713 Auto-starts on login. Auto-restarts on crash.'));+ if (serviceInstalled) {+ console.log(chalk.green(' \u2713 Auto-starts on login. Auto-restarts on crash.'));+ } else {+ console.log(chalk.dim(' No login service on this platform \u2014 run `mercury up` after a reboot.'));+ }console.log(chalk.dim(' Use `mercury stop` to stop. `mercury restart` to restart.'));} else {console.log(chalk.yellow(' Background mode not available. Run `mercury start` to set it up.'));@@ -2298,6 +2305,8 @@ function runPlatformDoctor(): void {console.log(` CI environment: ${ci ? chalk.yellow('yes') : chalk.green('no')}`);console.log(` Daemon: ${daemon.running ? chalk.green(`running (PID: ${daemon.pid})`) : chalk.dim('not running')}`);console.log(` Spotify inline art: ${canInlineArt ? chalk.green('supported (iTerm local)') : chalk.dim('disabled/fallback mode')}`);+ const inkPatch = detectInkPatch();+ console.log(` Ink TUI patch: ${inkPatch.patched ? chalk.green('applied') : chalk.red(`MISSING (${inkPatch.missing.join('; ')})`)}`);console.log('');console.log(chalk.bold.white(' Keybinding Notes'));console.log(` • View toggle: ${chalk.white('Ctrl+T')} (fallback: ${chalk.white('/view')})`);@@ -2310,6 +2319,12 @@ function runPlatformDoctor(): void {console.log(chalk.dim(' Try a local terminal session with TTY support for the best experience.'));console.log('');}++ if (!inkPatch.patched) {+ console.log(chalk.yellow(' Warning: the bundled ink patch is not applied — the TUI stops rendering new messages after ~100 and may crash on long sessions.'));+ console.log(chalk.dim(` Fix: ${inkPatchFixCommand()} (then restart Mercury)`));+ console.log('');+ }}async function runAgent(isDaemon: boolean = false): Promise<void> {diff --git a/src/ui/ink-patch-check.test.ts b/src/ui/ink-patch-check.test.tsnew file mode 100644index 00000000..f32eea74--- /dev/null+++ b/src/ui/ink-patch-check.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';+import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';+import { join } from 'node:path';+import { tmpdir } from 'node:os';+import {+ evaluateInkPatch,+ findInkPatchScript,+ inkPatchFixCommand,+ inkPatchWarning,+ detectInkPatch,+ INK_PATCH_MARKERS,+} from './ink-patch-check.js';++const PATCHED_STATIC = 'export default function Static(props) { const { itemKey } = props; const [t, setCommitTick] = useState(0); }';+const STOCK_STATIC = 'export default function Static(props) { const { items, children: render } = props; }';+const PATCHED_RECONCILER = 'const clearYogaRefs = (node) => {};';+const STOCK_RECONCILER = 'const cleanupYogaNode = (node) => {};';++describe('evaluateInkPatch', () => {+ it('reports patched when the gate and both file markers are present', () => {+ const s = evaluateInkPatch({ frameGate: { frozen: false, armed: false, marker: '' }, staticSource: PATCHED_STATIC, reconcilerSource: PATCHED_RECONCILER });+ expect(s.patched).toBe(true);+ expect(s.missing).toEqual([]);+ });++ it('flags stock ink: no frame gate, positional Static, no Yoga hygiene', () => {+ const s = evaluateInkPatch({ frameGate: undefined, staticSource: STOCK_STATIC, reconcilerSource: STOCK_RECONCILER });+ expect(s.patched).toBe(false);+ expect(s.missing).toEqual([+ INK_PATCH_MARKERS.frameGate,+ INK_PATCH_MARKERS.staticItemKey,+ INK_PATCH_MARKERS.yogaHygiene,+ ]);+ });++ it('flags a half-applied patch (itemKey without the commitTick re-render)', () => {+ const s = evaluateInkPatch({ frameGate: {}, staticSource: 'const { itemKey } = props;', reconcilerSource: PATCHED_RECONCILER });+ expect(s.patched).toBe(false);+ expect(s.missing).toEqual([INK_PATCH_MARKERS.staticItemKey]);+ });++ it('judges by the frame gate alone when the ink files are unreadable (standalone binary)', () => {+ expect(evaluateInkPatch({ frameGate: {}, staticSource: null, reconcilerSource: null }).patched).toBe(true);+ expect(evaluateInkPatch({ frameGate: undefined, staticSource: null, reconcilerSource: null }).missing)+ .toEqual([INK_PATCH_MARKERS.frameGate]);+ });+});++describe('detectInkPatch (this checkout)', () => {+ it('mirrors the result to globalThis.__mercuryInkPatchMissing', () => {+ const s = detectInkPatch(true);+ expect((globalThis as any).__mercuryInkPatchMissing).toBe(!s.patched);+ expect(detectInkPatch()).toBe(s); // cached+ });+});++describe('fix command', () => {+ it('finds scripts/apply-ink-patch.cjs by walking up from a nested dir', () => {+ const root = mkdtempSync(join(tmpdir(), 'mercury-inkcheck-'));+ try {+ mkdirSync(join(root, 'scripts'), { recursive: true });+ mkdirSync(join(root, 'dist', 'deep'), { recursive: true });+ writeFileSync(join(root, 'scripts', 'apply-ink-patch.cjs'), '// stub');+ const found = findInkPatchScript(join(root, 'dist', 'deep'));+ expect(found).toBe(join(root, 'scripts', 'apply-ink-patch.cjs'));+ expect(inkPatchFixCommand(found)).toBe(`node "${found}"`);+ } finally {+ rmSync(root, { recursive: true, force: true });+ }+ });++ it('falls back to a reinstall hint when the script is not shipped', () => {+ expect(findInkPatchScript(tmpdir())).toBeNull();+ expect(inkPatchFixCommand(null)).toContain('npm install -g @cosmicstack/mercury-agent');+ });++ it('builds a single-paragraph warning naming the missing markers and the fix', () => {+ const status = evaluateInkPatch({ frameGate: undefined, staticSource: STOCK_STATIC, reconcilerSource: PATCHED_RECONCILER });+ const text = inkPatchWarning(status, 'node /x/scripts/apply-ink-patch.cjs');+ expect(text).toContain(INK_PATCH_MARKERS.frameGate);+ expect(text).toContain(INK_PATCH_MARKERS.staticItemKey);+ expect(text).toContain('node /x/scripts/apply-ink-patch.cjs');+ expect(text.split('\n')).toHaveLength(1);+ });+});diff --git a/src/ui/ink-patch-check.ts b/src/ui/ink-patch-check.tsnew file mode 100644index 00000000..5e4dfc3a--- /dev/null+++ b/src/ui/ink-patch-check.ts@@ -0,0 +1,128 @@+/**+ * Runtime detection of the bundled ink patch (patches/ink+5.2.1.patch /+ * scripts/apply-ink-patch.cjs).+ *+ * On stock ink the TUI's `<Static itemKey>` prop is silently ignored: the+ * transcript stops rendering new messages once the bounded window starts+ * sliding (~100 messages), and the Yoga free-node hygiene is missing (WASM+ * "memory access out of bounds" crashes). The patch is applied by+ * postinstall, which npm users never see fail — so the TUI checks for the+ * patch markers at boot and says so loudly instead of degrading silently.+ *+ * Markers, in order of trust:+ * 1. `globalThis.__mercuryFrameGate` — set by patched ink.js at module+ * eval. Works for bundled/standalone binaries too (no file reads).+ * 2. `components/Static.js` contains `itemKey` + `setCommitTick`.+ * 3. `reconciler.js` contains `clearYogaRefs`.+ * File-based markers are only consulted when the file could be read, so a+ * standalone binary (no node_modules on disk) is judged by the gate alone.+ */+import { readFileSync, existsSync } from 'node:fs';+import { createRequire } from 'node:module';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++export interface InkPatchStatus {+ /** True when every observable marker is present. */+ patched: boolean;+ /** Human-readable names of the missing markers (empty when patched). */+ missing: string[];+ /** Directory of the ink build that was inspected, when resolvable. */+ inkBuildDir?: string;+}++export interface InkPatchProbe {+ /** `globalThis.__mercuryFrameGate` (object when patched ink.js loaded). */+ frameGate?: unknown;+ /** Contents of ink/build/components/Static.js; null/undefined = unreadable. */+ staticSource?: string | null;+ /** Contents of ink/build/reconciler.js; null/undefined = unreadable. */+ reconcilerSource?: string | null;+}++export const INK_PATCH_MARKERS = {+ frameGate: 'freeze gate (ink.js)',+ staticItemKey: 'Static.itemKey dedup (components/Static.js)',+ yogaHygiene: 'Yoga free-node hygiene (reconciler.js)',+} as const;++/** Pure evaluation of a probe — unit-testable without touching node_modules. */+export function evaluateInkPatch(probe: InkPatchProbe): InkPatchStatus {+ const missing: string[] = [];+ if (!probe.frameGate || typeof probe.frameGate !== 'object') {+ missing.push(INK_PATCH_MARKERS.frameGate);+ }+ if (typeof probe.staticSource === 'string'+ && !(probe.staticSource.includes('itemKey') && probe.staticSource.includes('setCommitTick'))) {+ missing.push(INK_PATCH_MARKERS.staticItemKey);+ }+ if (typeof probe.reconcilerSource === 'string' && !probe.reconcilerSource.includes('clearYogaRefs')) {+ missing.push(INK_PATCH_MARKERS.yogaHygiene);+ }+ return { patched: missing.length === 0, missing };+}++/** Best-effort read of the ink build files Node would load from here. */+export function readInkSources(): Pick<InkPatchProbe, 'staticSource' | 'reconcilerSource'> & { inkBuildDir?: string } {+ try {+ const req = createRequire(import.meta.url);+ const inkBuildDir = dirname(req.resolve('ink'));+ const read = (p: string): string | null => {+ try { return readFileSync(p, 'utf8'); } catch { return null; }+ };+ return {+ inkBuildDir,+ staticSource: read(join(inkBuildDir, 'components', 'Static.js')),+ reconcilerSource: read(join(inkBuildDir, 'reconciler.js')),+ };+ } catch {+ return { staticSource: null, reconcilerSource: null };+ }+}++let cached: InkPatchStatus | null = null;++/**+ * Detect whether the running ink is patched. Cached per process; the result+ * is also mirrored to `globalThis.__mercuryInkPatchMissing` so any surface+ * (doctor, status) can report it without importing this module.+ */+export function detectInkPatch(force = false): InkPatchStatus {+ if (cached && !force) return cached;+ const sources = readInkSources();+ const status = evaluateInkPatch({+ frameGate: (globalThis as any).__mercuryFrameGate,+ staticSource: sources.staticSource,+ reconcilerSource: sources.reconcilerSource,+ });+ cached = { ...status, inkBuildDir: sources.inkBuildDir };+ (globalThis as any).__mercuryInkPatchMissing = !cached.patched;+ return cached;+}++/** Locate the shipped applier: walk up from this module (dist/ or src/ui/). */+export function findInkPatchScript(startDir: string = dirname(fileURLToPath(import.meta.url))): string | null {+ let dir = startDir;+ for (let i = 0; i < 5; i++) {+ const candidate = join(dir, 'scripts', 'apply-ink-patch.cjs');+ if (existsSync(candidate)) return candidate;+ const parent = resolve(dir, '..');+ if (parent === dir) break;+ dir = parent;+ }+ return null;+}++/** The one command a user should run to fix an unpatched install. */+export function inkPatchFixCommand(scriptPath: string | null = findInkPatchScript()): string {+ if (scriptPath) return `node "${scriptPath}"`;+ return 'npm install -g @cosmicstack/mercury-agent --force (re-runs the ink patch postinstall)';+}++/** One-paragraph warning for the TUI transcript / doctor. */+export function inkPatchWarning(status: InkPatchStatus, fixCommand: string = inkPatchFixCommand()): string {+ return `⚠ Ink patch not applied (missing: ${status.missing.join('; ')}). `+ + 'On stock ink the transcript silently stops rendering new messages after ~100 and long sessions can crash '+ + '(Yoga WASM). The TUI keeps running, but to fix it run: '+ + `\`${fixCommand}\` and restart Mercury. If the script is missing, reinstall Mercury.`;+}diff --git a/src/utils/platform.test.ts b/src/utils/platform.test.tsindex bbf595fb..d7f01f56 100644--- a/src/utils/platform.test.ts+++ b/src/utils/platform.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { isTermux, resolveShell } from './platform.js';+import { isTermux, isTermuxEligiblePlatform, resolveShell } from './platform.js';describe('isTermux', () => {it('detects Termux environment markers on Linux', () => {@@ -7,9 +7,30 @@ describe('isTermux', () => {expect(isTermux({ PREFIX: '/data/data/com.termux/files/usr' }, 'linux')).toBe(true);});- it('does not classify desktop Linux or non-Linux platforms as Termux', () => {+ it('detects Termux when Node reports process.platform === "android" (real devices)', () => {+ // Termux's own nodejs package is an Android build: process.platform is+ // 'android', not 'linux'. Gating on 'linux' alone sent every real phone+ // down the "Unsupported platform: android" service-install path.+ expect(isTermux({ PREFIX: '/data/data/com.termux/files/usr' }, 'android')).toBe(true);+ expect(isTermux({ TERMUX_VERSION: '0.119' }, 'android')).toBe(true);+ expect(isTermux({ TERMUX_APP_PID: '1234' }, 'android')).toBe(true);+ });++ it('does not classify plain Linux, plain Android, or non-Linux platforms as Termux', () => {expect(isTermux({}, 'linux')).toBe(false);+ expect(isTermux({ PREFIX: '/usr' }, 'linux')).toBe(false);+ expect(isTermux({}, 'android')).toBe(false);expect(isTermux({ TERMUX_VERSION: '0.119' }, 'darwin')).toBe(false);+ expect(isTermux({ PREFIX: '/data/data/com.termux/files/usr' }, 'win32')).toBe(false);+ });+});++describe('isTermuxEligiblePlatform', () => {+ it('accepts linux and android only', () => {+ expect(isTermuxEligiblePlatform('linux')).toBe(true);+ expect(isTermuxEligiblePlatform('android')).toBe(true);+ expect(isTermuxEligiblePlatform('darwin')).toBe(false);+ expect(isTermuxEligiblePlatform('win32')).toBe(false);});});diff --git a/src/utils/platform.ts b/src/utils/platform.tsindex f435ef10..52d775db 100644--- a/src/utils/platform.ts+++ b/src/utils/platform.ts@@ -1,11 +1,23 @@import { existsSync } from 'node:fs';import { posix as posixPath } from 'node:path';+/**+ * Platforms on which a Termux environment can exist. Node built by the+ * Termux package repo (`pkg install nodejs`) reports `process.platform ===+ * 'android'`, NOT `'linux'` — gating on `'linux'` alone made every real+ * Termux device look like a desktop and sent `installService()` down the+ * "Unsupported platform: android" path. Keep both: some Termux setups (and+ * proot/glibc Node builds) still report `'linux'`.+ */+export function isTermuxEligiblePlatform(platform: NodeJS.Platform = process.platform): boolean {+ return platform === 'linux' || platform === 'android';+}+export function isTermux(env: NodeJS.ProcessEnv = process.env,platform: NodeJS.Platform = process.platform,): boolean {- if (platform !== 'linux') return false;+ if (!isTermuxEligiblePlatform(platform)) return false;return Boolean(env.TERMUX_VERSION ||env.TERMUX_APP_PID ||