Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
Attached terminal and Mercury Code polish, picker and session hangs fixed, keyless web search that works (#213)
Salman Qureshi542faeec2944
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0a6dde93..c36fe5a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,19 +21,35 @@- **Skill categories and intents work again.** Discovery registered each skill's category, intents and tags and then rebuilt the index, wiping them; the prompt fell back to a flat list and intent routing matched on names only. Fixed by building the index first.- **No junk shelf.** `/skills self-made` shows each one with use counts; unused ones go dormant after 30 days (disabled, never deleted) and the shelf is capped at 40. `/skills self-made enable|disable|remove <name>`. Bots and channel members cannot create skills.+### Web search+- **Search returns real results again, still free and keyless.** Bing's web RSS feed, the main engine, now answers automated requests with pages unrelated to the query (train timetables for a TypeScript question), and DuckDuckGo, Mojeek and Startpage answer with bot challenges. `web_search` now asks Brave Search first, then Wikipedia, Hacker News, Bing News and Google News, and keeps only results that mention the query, so a source serving junk counts as empty and the next one is tried. A thin answer is topped up from Wikipedia, the same page is never listed twice, and Brave rests for a minute after rate-limiting instead of being retried every query. No new dependency.+- **Old DuckDuckGo skills stop failing.** `fetch_url` on a search-engine results page (DuckDuckGo, Google, Bing, Yahoo, Brave, Startpage, Mojeek) runs the query through `web_search` instead of returning the challenge page. An installed `web-search` skill that scrapes such a page and never mentions `web_search` is replaced by the built-in one on start, with the original kept as `SKILL.md.replaced.bak`; skills you edited that already use `web_search` are left alone.+- The built-in `web-search` skill (1.2.0) tells the model to rephrase once before giving up and never to fetch search pages directly.+### Chat- **Regular chat works like an agent again.** Its instructions forbade helper scripts and batching ("call write_file for each one individually"), so a task like converting an EPUB to Markdown was done file by file by hand. Chat now reaches for the strongest existing tool (pandoc, ffmpeg, a Python library) or one script, does a quick web search when it isn't sure what the best tool is, and checks the output before saying it is done. It also gets a short working contract like Mercury Code's: do the work, plan multi-step tasks, report what was checked.+- **`/model` and `/cloud` offer the arrow-key picker in the attached terminal again.** The picker was only wired to the foreground terminal; since the default launch attaches, `/model` printed a list and left you typing `/models use <name>`. Both now open the same ↑↓ picker on your own screens (attached terminal and dashboard), and Esc keeps the current model instead of silently taking the first option.+- **A model switch says what it does.** `/model` used to answer "Saved for future sessions", which read as "takes effect next session". It now says `✓ Switched to <model> (<provider>). In effect from your next message, and kept as the default.`, and the status row shows the new model at once.+- **Pickers answered in the attached terminal reach the runtime.** The answer endpoint only resolved permission prompts, so choosing in `/permissions`, `/model` or a question picker did nothing: the command waited out its 2-minute timeout behind a "Thinking" spinner. Choices and Esc now resolve at once, and the spinner is hidden while a picker waits on you.+- **`/new` no longer leaves the attached terminal "Thinking" forever.** After `/new` or `/session <ref>` the runtime re-bound your screen to the new session, but the terminal kept listening on the old one, so every reply went where nobody was looking and `/stop` seemed ignored. The runtime now tells the screen to follow, and the terminal also follows whenever a message is routed to another session.+- **Yes-or-no and "which one?" questions come as a picker, not prose.** Chat now asks decisions through its question tool (↑↓ and Enter) and keeps prose for questions that need free text (a name, a path).### Permissions-- **Mercury asks for your permission mode again, once, and remembers it.** Since 1.3.1 the default `mercury` launch attaches to the background runtime, which never showed the "Ask Me / Allow All" prompt, so every new user was silently in Ask Me. Setup now asks; existing users are asked once in the attached terminal; the choice is saved and applied to your terminal, attached terminal, Mercury Code and the dashboard.+- **Every new session asks for its permission mode again.** Since 1.3.1 the default `mercury` launch attaches to the background runtime, which never showed the "Ask Me / Allow All" prompt, so everyone was silently in Ask Me. The prompt is back wherever a session starts: the foreground terminal and Mercury Code at launch, the attached terminal when you start a new session or type `/new`. Your current mode is listed first, so Enter keeps it and ↓ Enter switches; the pick is remembered as the default for next time and applied to every screen. Resuming an existing session prints one dim line with the mode in effect instead.- **`/permissions` works everywhere you are the owner** (attached terminal and dashboard too, not just the foreground terminal), including `/permissions allow-all` and `/permissions ask-me`.- **"Always" on a command prompt now covers that command for the rest of the chat** (every `pandoc …`, `git commit …`), not just the exact string. Installs, wrappers like `sudo`/`sh -c`, and remote Mercury Cloud requests stay exact-match.- Telegram and Signal can switch back from Allow All to Ask Me (the switch used to be ignored until restart).### Bottom bar-- **One useful row, not a dump.** The row under the input now has two halves. Left: what is happening — a spinner, the phase (Thinking, the running tool, Writing) and the elapsed time while a turn runs, a notice when there is one, two short hints when idle. Right: where you are — permission mode, model, today's token use, Code mode, Optimus, an update, and the session last — fitted to the terminal width in priority order with compact forms (`claude-haiku-4-5` not `claude-haiku-4-5-20251001`, `⚡12%` not `⚡ 12% today`), so a long model or session name never crowds out the rest; what does not fit is dropped, lowest priority first, never cut mid-word. The attached terminal and the foreground TUI share one builder.+- **The session picker fits the screen, new session first.** `mercury` used to list up to six sessions under the launch pad regardless of the terminal height, so on a 24-row terminal Ink dropped the wordmark off the top. The list is now budgeted to the height (the tip goes first, then sessions fold into `… N more · /sessions in the chat`), and "Start a new session" is the first, pre-selected row instead of the last.+- **One useful row, not a dump.** The row under the input is status only. Left: the session (`⚿ copper-mint-thd · hi`). Right: permission mode, today's budget meter, model, Code mode, Optimus, an update — fitted to the terminal width in priority order with compact forms (`claude-haiku-4-5` not `claude-haiku-4-5-20251001`, `⚡12%` when narrow), so a long model or session name never crowds out the rest; what does not fit is dropped, lowest priority first, never cut mid-word.+- **Optimus wins the row.** While Optimus is listening or working, its activity is the first segment on the right and the last one the fit ever drops; the session on the left shrinks to its alias to make room.+- **Model only on the row.** The provider name is gone from the status row (`claude-sonnet-4-5`, not `Anthropic · claude-sonnet-4-5`); the model name already says who serves it.+- **The budget meter is back on the row.** `⚡ ██████░░ 76%` shows today's token use as a bar that goes green → yellow (70 %) → red (90 %), the colours the completion footer has always used. It outranks the model when the row is narrow, so it stays visible as `⚡76%` down to very small terminals. The attached terminal and the foreground TUI share one builder.- **The bar updates live.** The attached terminal (what `mercury` opens) read the model once on connect and never again; model switches, Code mode, permission changes and Optimus activity never reached it. The runtime now pushes a status update on every model switch and checks every 2 seconds for anything else. The bar shows the thread, model, Code mode, Ask Me / Allow All, today's token use and Optimus activity; the foreground and Mercury Code bars show the permission mode too.- The launch pad's budget row works again (it read field names the runtime never sent).+- **Said once, in the chat.** While a turn runs, one line above the input shows the spinner, the phase (Thinking, the running tool, Writing) and the elapsed time, cyan then yellow at 30 s and red at 90 s, under the finished steps' ✓ marks. The status row under the input never repeats it. Choosing a permission mode no longer prints a confirmation line either: the row shows the mode.+- **No key hints on the row.** `↵ send · /help · ctrl+c detach` is gone; Enter sends, `/help` lists the commands, and the row keeps its width for status. The right half is a single truncating line now, so it can no longer wrap onto a hidden second line and end in `Anthropic · `.## 1.4.0 — Pluggy Mercury: plugins, WhatsApp calls, and Optimus uses your computerdiff --git a/src/capabilities/web/fetch-url.ts b/src/capabilities/web/fetch-url.tsindex c115ccb5..e4e8488d 100644--- a/src/capabilities/web/fetch-url.ts+++ b/src/capabilities/web/fetch-url.ts@@ -1,6 +1,7 @@import { tool, zodSchema } from 'ai';import { z } from 'zod';import { guardedFetch } from '../../utils/ssrf.js';+import { formatResults, searchQueryFromUrl, webSearch } from './web-search.js';const MAX_CONTENT_LENGTH = 15000;@@ -96,6 +97,19 @@ export function createFetchUrlTool(opts: { isResearchMode: () => boolean } = { iconst outputFormat = format ?? 'markdown';const preserveImages = opts.isResearchMode();+ // A search-engine results page (DuckDuckGo, Google, Bing…) answers a+ // bot with a challenge or a wall of markup. Old skills still send the+ // model there, so run the query through web_search instead.+ const searchQuery = searchQueryFromUrl(url);+ if (searchQuery) {+ try {+ const { results, engine } = await webSearch(searchQuery, { max: 8 });+ return `${formatResults(results, engine, searchQuery, 'web')}\n\n(Search pages block automated reads, so this came from web_search. Call web_search directly next time; use fetch_url on a result link to read it.)`;+ } catch (err) {+ return `Error: search pages block automated reads, and web_search failed too: ${(err as Error).message}`;+ }+ }+try {const controller = new AbortController();const timeout = setTimeout(() => controller.abort(), 30000);diff --git a/src/capabilities/web/search-redirect.test.ts b/src/capabilities/web/search-redirect.test.tsnew file mode 100644index 00000000..338de212--- /dev/null+++ b/src/capabilities/web/search-redirect.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it, vi } from 'vitest';++const hit = (url: string, title: string) => `<a href="${url}" target="_self" class="l1"><div class="title search-snippet-title" title="${title}">x</div></a><div class="content">AI news today.</div>`;+const BRAVE = [+ hit('https://www.theverge.com/ai', 'Latest AI news - The Verge'),+ hit('https://www.reuters.com/technology/ai', 'AI News | Reuters'),+ hit('https://www.technologyreview.com/ai', 'AI - MIT Technology Review'),+ hit('https://techcrunch.com/ai', 'AI news | TechCrunch'),+].join('');++vi.mock('../../utils/ssrf.js', () => ({+ guardedFetch: vi.fn(async (url: string) => {+ if (url.includes('search.brave.com')) return new Response(BRAVE, { status: 200 });+ if (url.includes('duckduckgo.com')) return new Response('<html>anomaly challenge</html>', { status: 202 });+ return new Response('<html><body><p>An article</p></body></html>', { status: 200, headers: { 'content-type': 'text/html' } });+ }),+}));++import { createFetchUrlTool } from './fetch-url.js';+import { guardedFetch } from '../../utils/ssrf.js';+import { isBrokenSearchSkill } from '../../skills/loader.js';++/**+ * Old web-search skills tell the model to fetch DuckDuckGo's HTML page, which+ * answers bots with a 202 challenge — so search "sometimes did not work".+ */+describe('fetch_url on a search results page', () => {+ it('answers with web_search results instead of the bot challenge page', async () => {+ const t = createFetchUrlTool() as unknown as { execute: (a: unknown, o: unknown) => Promise<string> };+ const out = await t.execute({ url: 'https://html.duckduckgo.com/html/?q=latest+AI+news' }, {});+ expect(out).toMatch(/^Web results from Brave for "latest AI news":/);+ expect(out).toContain('1. Latest AI news - The Verge');+ expect(out).toContain('Call web_search directly next time');+ const urls = vi.mocked(guardedFetch).mock.calls.map((c) => String(c[0]));+ expect(urls.some((u) => u.includes('duckduckgo.com'))).toBe(false);+ });++ it('fetches an ordinary page as before', async () => {+ const t = createFetchUrlTool() as unknown as { execute: (a: unknown, o: unknown) => Promise<string> };+ expect(await t.execute({ url: 'https://example.com/post' }, {})).toContain('An article');+ });+});++describe('replacing a web-search skill that scrapes a blocked page', () => {+ it('flags a DuckDuckGo-scraping skill, never one that uses web_search or another skill dir', () => {+ const ddg = '---\nname: web-search\n---\nUse fetch_url on https://html.duckduckgo.com/html/?q=QUERY';+ expect(isBrokenSearchSkill('web-search', ddg)).toBe(true);+ expect(isBrokenSearchSkill('web-search', 'Use fetch_url on https://www.google.com/search?q=QUERY')).toBe(true);+ expect(isBrokenSearchSkill('web-search', ddg + '\nPrefer the web_search tool.')).toBe(false);+ expect(isBrokenSearchSkill('my-search', ddg)).toBe(false);+ expect(isBrokenSearchSkill('web-search', 'Search with Tavily using TAVILY_API_KEY')).toBe(false);+ });+});++describe('the installed web-search skill on upgrade', () => {+ it('a DuckDuckGo-scraping copy is replaced by the built-in one and kept as a backup; an edited working one is left alone', async () => {+ const { mkdtempSync, mkdirSync, writeFileSync, readFileSync, existsSync, rmSync } = await import('node:fs');+ const { tmpdir } = await import('node:os');+ const { join } = await import('node:path');+ const { SkillLoader } = await import('../../skills/loader.js');+ const dir = mkdtempSync(join(tmpdir(), 'mercury-search-skill-'));+ try {+ const ddg = '---\nname: web-search\ndescription: Search the web using DuckDuckGo.\n---\n\n1. Use `fetch_url` on https://html.duckduckgo.com/html/?q=QUERY\n';+ mkdirSync(join(dir, 'web-search'), { recursive: true });+ writeFileSync(join(dir, 'web-search', 'SKILL.md'), ddg);+ new SkillLoader(dir).discover();+ const now = readFileSync(join(dir, 'web-search', 'SKILL.md'), 'utf-8');+ expect(now).toContain('Call web_search with a focused query');+ expect(readFileSync(join(dir, 'web-search', 'SKILL.md.replaced.bak'), 'utf-8')).toBe(ddg);++ const mine = '---\nname: web-search\n---\nUse web_search, then summarise in Urdu.\n';+ writeFileSync(join(dir, 'web-search', 'SKILL.md'), mine);+ rmSync(join(dir, 'web-search', 'SKILL.md.replaced.bak'));+ new SkillLoader(dir).discover();+ expect(readFileSync(join(dir, 'web-search', 'SKILL.md'), 'utf-8')).toBe(mine);+ expect(existsSync(join(dir, 'web-search', 'SKILL.md.replaced.bak'))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});diff --git a/src/capabilities/web/web-search.test.ts b/src/capabilities/web/web-search.test.tsindex d63f0c66..b876fe72 100644--- a/src/capabilities/web/web-search.test.ts+++ b/src/capabilities/web/web-search.test.ts@@ -10,18 +10,46 @@ const BING = `<?xml version="1.0"?><rss><channel><item><title>Canberra - Wikipedia</title><link>https://en.wikipedia.org/wiki/Canberra</link><description>Canberra is the capital city of Australia.</description></item></channel></rss>`;-vi.mock('../../utils/ssrf.js', () => ({- guardedFetch: vi.fn(async (url: string) => {- if (url.includes('news.google.com')) return new Response(GOOGLE_NEWS, { status: 200 });- if (url.includes('bing.com')) return new Response(BING, { status: 200 });- return new Response('', { status: 404 });- }),-}));--import { createWebSearchTool, parseRss, webSearch } from './web-search.js';+/** What Bing's web RSS answers automated requests with today: pages unrelated to the query. */+const BING_JUNK = `<?xml version="1.0"?><rss><channel>+<item><title>SonyLIV Coupons, Promo Code & Subscription Offers</title><link>https://example.com/sonyliv</link><description>Save on SonyLIV.</description></item>+<item><title>Jammu to Chandigarh Trains - redBus</title><link>https://example.com/trains</link><description>Train timings.</description></item>+</channel></rss>`;++/** Two results trimmed from a real Brave Search page (markup as served in October 2026). */+const BRAVE = `<!doctype html><html><body><div class="snippet">+<a href="https://search.brave.com/settings" class="nav">Settings</a>+<a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html" target="_self" class="svelte-14r20fy l1"><div class="site-name-wrapper"><cite class="snippet-url">typescriptlang.org</cite></div> <div class="title search-snippet-title line-clamp-1 svelte-14r20fy" title="TypeScript: Documentation - TypeScript 4.9">TypeScript: Documentation - TypeScript 4.9</div></a><!----> <div class="generic-snippet svelte-1cwdgg3"><div class="content desktop-default-regular t-primary line-clamp-dynamic svelte-1cwdgg3"><!---->The new satisfies operator <strong>lets us validate that the type of an expression matches some type</strong>.<!----></div></div>+<a href="https://stackoverflow.com/questions/75000000/satisfies-vs-as" target="_self" class="svelte-14r20fy l1"><div class="title search-snippet-title line-clamp-1 svelte-14r20fy" title="What are the differences between TypeScript's satisfies operator and type assertions? - Stack Overflow">x</div></a><div class="generic-snippet"><div class="content desktop-default-regular">satisfies checks without widening; as asserts.</div></div>+</div></body></html>`;++const WIKI = JSON.stringify({ query: { search: [+ { title: 'Canberra', snippet: '<span class="searchmatch">Canberra</span> is the capital city of Australia.', timestamp: '2026-10-01T00:00:00Z' },+ { title: 'Australian Capital Territory', snippet: 'A federal territory around Canberra, the capital of Australia', timestamp: '2026-09-01T00:00:00Z' },+] } });++const HN = JSON.stringify({ hits: [+ { title: "TypeScript's satisfies operator", url: 'https://example.dev/satisfies', objectID: '41', points: 120, created_at: '2026-10-02T00:00:00Z' },+ { title: 'Ask HN: TypeScript satisfies vs as?', url: null, objectID: '42', points: 30 },+] });++const routes = (map: Record<string, string | number>) => async (url: string) => {+ for (const [host, body] of Object.entries(map)) {+ if (url.includes(host)) return typeof body === 'number' ? new Response('', { status: body }) : new Response(body, { status: 200 });+ }+ return new Response('', { status: 404 });+};++const defaultFetch = routes({ 'search.brave.com': BRAVE, 'news.google.com': GOOGLE_NEWS, 'bing.com/news': GOOGLE_NEWS, 'bing.com': BING, 'wikipedia.org': WIKI, 'hn.algolia.com': HN });++vi.mock('../../utils/ssrf.js', () => ({ guardedFetch: vi.fn() }));++import { createWebSearchTool, parseBrave, parseRss, relevant, resetBraveCooldown, searchQueryFromUrl, webSearch } from './web-search.js';import { guardedFetch } from '../../utils/ssrf.js';-afterEach(() => vi.mocked(guardedFetch).mockClear());+vi.mocked(guardedFetch).mockImplementation(defaultFetch as never);+// Tests that swap the fetch mock must not leak it (or a Brave cooldown) into the next test.+afterEach(() => { vi.mocked(guardedFetch).mockClear(); vi.mocked(guardedFetch).mockImplementation(defaultFetch as never); resetBraveCooldown(); });describe('web_search', () => {it('parses Google News items, strips the source suffix, keeps the date', () => {@@ -35,15 +63,84 @@ describe('web_search', () => {expect(parseRss(BING, 5).map((x) => x.url)).toEqual(['https://en.wikipedia.org/wiki/Canberra']);});- it('news uses Google News; web uses Bing; both through the SSRF guard', async () => {+ it('parses Brave results: link, title, snippet; skips Brave\'s own links', () => {+ const r = parseBrave(BRAVE, 5);+ expect(r).toHaveLength(2);+ expect(r[0]).toEqual({+ title: 'TypeScript: Documentation - TypeScript 4.9',+ url: 'https://www.typescriptlang.org/docs/handbook/release-notes/typescript-4-9.html',+ snippet: 'The new satisfies operator lets us validate that the type of an expression matches some type .',+ });+ expect(r[1].title).toBe("What are the differences between TypeScript's satisfies operator and type assertions? - Stack Overflow");+ expect(r[1].snippet).toBe('satisfies checks without widening; as asserts.');+ });++ it('web uses Brave first; news uses Google News; all through the SSRF guard', async () => {+ const web = await webSearch('typescript satisfies operator');+ expect(web.engine).toMatch(/^Brave/); // two hits here, so Wikipedia tops it up+ expect(web.results[0].url).toContain('typescriptlang.org');+ expect(String(vi.mocked(guardedFetch).mock.calls[0][0])).toMatch(/^https:\/\/search\.brave\.com\/search\?q=typescript%20satisfies%20operator/);expect((await webSearch('', { kind: 'news' })).engine).toBe('Google News');- expect(vi.mocked(guardedFetch).mock.calls[0][0]).toBe('https://news.google.com/rss?hl=en-US&gl=US&ceid=US:en');- expect((await webSearch('capital of australia')).engine).toBe('Bing');});- it('falls back to the other engine when one fails', async () => {- vi.mocked(guardedFetch).mockImplementationOnce(async () => new Response('', { status: 503 }));- expect((await webSearch('capital of australia')).engine).toBe('Google News');+ it('an engine answering with unrelated pages counts as empty: Bing\'s junk never reaches the model', async () => {+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 503, 'wikipedia.org': 503, 'hn.algolia.com': 503, 'news.google.com': 503, 'bing.com/news': 503, 'bing.com': BING_JUNK }) as never);+ await expect(webSearch('typescript satisfies operator')).rejects.toThrow(/Bing: only unrelated results/);+ });++ it('relevance: one or two words must all appear, longer queries need half', () => {+ const r = (title: string) => ({ title, url: 'https://x.dev', snippet: '' });+ expect(relevant('best pizza in srinagar', [r('Best pizza places in Srinagar'), r('Srinagar war history'), r('Pizza in Rome')]).map((x) => x.title)).toEqual(['Best pizza places in Srinagar']);+ expect(relevant('typescript satisfies operator', [r('The satisfies operator'), r('TypeScript handbook'), r('Train timings')]).map((x) => x.title)).toEqual(['The satisfies operator']);+ expect(relevant('', [r('anything')])).toHaveLength(1);+ });++ it('keeps going down the keyless chain: Wikipedia, then Hacker News', async () => {+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 429, 'wikipedia.org': WIKI, 'hn.algolia.com': HN }) as never);+ const wiki = await webSearch('canberra');+ expect(wiki.engine).toBe('Wikipedia');+ expect(wiki.results[0]).toMatchObject({ title: 'Canberra', url: 'https://en.wikipedia.org/wiki/Canberra', snippet: 'Canberra is the capital city of Australia.', source: 'Wikipedia' });++ resetBraveCooldown();+ vi.mocked(guardedFetch).mockImplementation(routes({ 'hn.algolia.com': HN }) as never);+ const hn = await webSearch('typescript satisfies');+ expect(hn.engine).toBe('Hacker News');+ expect(hn.results[0]).toMatchObject({ title: "TypeScript's satisfies operator", url: 'https://example.dev/satisfies', source: 'Hacker News' });+ // A story without its own link points at the discussion.+ expect(hn.results[1].url).toBe('https://news.ycombinator.com/item?id=42');+ });++ it('after a 429, Brave rests for a minute instead of being tried on every query', async () => {+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': 429, 'wikipedia.org': WIKI }) as never);+ await webSearch('canberra');+ await webSearch('canberra capital');+ const braveCalls = vi.mocked(guardedFetch).mock.calls.filter((c) => String(c[0]).includes('search.brave.com'));+ expect(braveCalls).toHaveLength(1);+ });++ it('tops a thin answer up with Wikipedia and lists each page once', async () => {+ const oneHit = `<a href="https://en.wikipedia.org/wiki/Canberra" target="_self" class="l1"><div class="title search-snippet-title" title="Canberra, capital of Australia">x</div></a><div class="content">The capital of Australia.</div>`;+ vi.mocked(guardedFetch).mockImplementation(routes({ 'search.brave.com': oneHit, 'wikipedia.org': WIKI }) as never);+ const r = await webSearch('canberra australia');+ expect(r.engine).toBe('Brave + Wikipedia');+ expect(r.results.filter((x) => /wiki\/Canberra$/.test(x.url))).toHaveLength(1);+ expect(r.results.map((x) => x.title)).toContain('Australian Capital Territory');+ });++ it('recognises search-engine result URLs, so fetch_url can answer them with real results', () => {+ expect(searchQueryFromUrl('https://html.duckduckgo.com/html/?q=latest+AI+news')).toBe('latest AI news');+ expect(searchQueryFromUrl('https://lite.duckduckgo.com/lite/?q=x')).toBe('x');+ expect(searchQueryFromUrl('https://duckduckgo.com/?q=pandoc%20epub')).toBe('pandoc epub');+ expect(searchQueryFromUrl('https://www.google.com/search?q=canberra')).toBe('canberra');+ expect(searchQueryFromUrl('https://www.google.co.uk/search?q=canberra')).toBe('canberra');+ expect(searchQueryFromUrl('https://www.bing.com/search?q=canberra')).toBe('canberra');+ expect(searchQueryFromUrl('https://search.yahoo.com/search?p=canberra')).toBe('canberra');+ // Not search pages: the feed web_search itself uses, articles, empty queries.+ expect(searchQueryFromUrl('https://www.bing.com/search?q=canberra&format=rss')).toBeNull();+ expect(searchQueryFromUrl('https://duckduckgo.com/about')).toBeNull();+ expect(searchQueryFromUrl('https://en.wikipedia.org/wiki/Canberra')).toBeNull();+ expect(searchQueryFromUrl('https://html.duckduckgo.com/html/')).toBeNull();+ expect(searchQueryFromUrl('not a url')).toBeNull();});it('the tool returns a readable list, or a clear error', async () => {diff --git a/src/capabilities/web/web-search.ts b/src/capabilities/web/web-search.tsindex 1ac04692..f7e4e58c 100644--- a/src/capabilities/web/web-search.ts+++ b/src/capabilities/web/web-search.ts@@ -5,8 +5,11 @@ import { guardedFetch } from '../../utils/ssrf.js';/*** web_search: free, keyless search for the model.*- * web → Bing's RSS results feed (falls back to Google News)- * news → Google News RSS, recent first (falls back to Bing)+ * web → Brave Search, then Wikipedia, Hacker News, Bing News, Google News, Bing RSS+ * news → Google News RSS, recent first, then Bing News, Hacker News+ *+ * Every answer must mention the query (relevant()); an engine serving junk+ * counts as empty and the next one is tried.** Read-only and through the same SSRF guard as fetch_url. Returns titles,* links, snippets and dates; the model follows up with fetch_url to read a@@ -82,10 +85,63 @@ async function fetchText(url: string): Promise<string> {}}+/**+ * Bing's web RSS feed. Kept as a late fallback only: since autumn 2026 it+ * answers automated requests with results unrelated to the query, which the+ * relevance check below throws away.+ */async function bing(query: string, max: number): Promise<SearchResult[]> {return parseRss(await fetchText(`https://www.bing.com/search?q=${encodeURIComponent(query)}&format=rss&count=${Math.min(20, max + 2)}`), max);}+/** Bing News RSS: relevant, recent, keyless. */+async function bingNews(query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ return parseRss(await fetchText(`https://www.bing.com/news/search?q=${encodeURIComponent(query)}&format=rss`), max);+}++/**+ * Brave Search's results page: a real, independent web index that answers a+ * plain browser request without a key or a challenge. Parsed from the HTML,+ * so a markup change shows up as "no results" and the chain moves on.+ */+export function parseBrave(html: string, max: number): SearchResult[] {+ const out: SearchResult[] = [];+ const anchor = /<a href="(https?:\/\/[^"]+)"[^>]*>([\s\S]*?)<\/a>/g;+ let m: RegExpExecArray | null;+ while ((m = anchor.exec(html)) && out.length < max) {+ const [, url, inner] = m;+ const title = /class="title search-snippet-title[^"]*"[^>]*title="([^"]*)"/.exec(inner)?.[1];+ if (!title || /^https?:\/\/([a-z]+\.)?search\.brave\.com/.test(url)) continue;+ const after = html.slice(anchor.lastIndex, anchor.lastIndex + 4000);+ const nextResult = after.search(/<a href="https?:\/\/[^"]+"[^>]*>[\s\S]{0,3000}?search-snippet-title/);+ const scope = nextResult > 0 ? after.slice(0, nextResult) : after;+ const snippet = /class="content[^"]*">([\s\S]*?)<\/div>/.exec(scope)?.[1] ?? '';+ out.push({ title: decode(title), url: unescape(url), snippet: decode(snippet).slice(0, 300) });+ }+ return out;+}++/** Brave rate-limits per IP: after a 429 it is skipped for a minute rather than tried (and waited on) every query. */+const BRAVE_COOLDOWN_MS = 60_000;+let braveBlockedUntil = 0;+export function resetBraveCooldown(): void { braveBlockedUntil = 0; }++async function brave(query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ if (Date.now() < braveBlockedUntil) throw new Error('rate-limited, resting for a minute');+ const ac = new AbortController();+ const timer = setTimeout(() => ac.abort(), TIMEOUT_MS);+ try {+ const res = await guardedFetch(`https://search.brave.com/search?q=${encodeURIComponent(query)}&source=web`, ac.signal, { 'User-Agent': UA, Accept: 'text/html', 'Accept-Language': 'en-US,en;q=0.9' });+ if (res.status === 429) braveBlockedUntil = Date.now() + BRAVE_COOLDOWN_MS;+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ return parseBrave(await res.text(), max);+ } finally {+ clearTimeout(timer);+ }+}+async function googleNews(query: string, max: number): Promise<SearchResult[]> {const url = query.trim()? `https://news.google.com/rss/search?q=${encodeURIComponent(query)}&hl=en-US&gl=US&ceid=US:en`@@ -93,16 +149,127 @@ async function googleNews(query: string, max: number): Promise<SearchResult[]> {return parseRss(await fetchText(url), max);}+async function fetchJson(url: string): Promise<unknown> {+ return JSON.parse(await fetchText(url));+}++/** Wikipedia's search API: keyless JSON, strong for facts, people, places, concepts. */+export async function wikipedia(query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ const data = await fetchJson(`https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${encodeURIComponent(query)}&format=json&srlimit=${Math.min(10, max)}&srprop=snippet|timestamp`) as {+ query?: { search?: Array<{ title: string; snippet?: string; timestamp?: string }> };+ };+ return (data.query?.search ?? []).map((hit) => ({+ title: hit.title,+ url: `https://en.wikipedia.org/wiki/${encodeURIComponent(hit.title.replace(/ /g, '_'))}`,+ snippet: decode(hit.snippet ?? '').slice(0, 300),+ source: 'Wikipedia',+ date: hit.timestamp,+ }));+}++/** Hacker News via Algolia: keyless JSON, strong for software, startups and tech news. */+export async function hackerNews(query: string, max: number): Promise<SearchResult[]> {+ if (!query.trim()) return [];+ const data = await fetchJson(`https://hn.algolia.com/api/v1/search?query=${encodeURIComponent(query)}&tags=story&hitsPerPage=${Math.min(10, max)}`) as {+ hits?: Array<{ title?: string; url?: string | null; objectID: string; created_at?: string; points?: number }>;+ };+ return (data.hits ?? []).filter((h) => h.title).map((h) => ({+ title: h.title!,+ url: h.url || `https://news.ycombinator.com/item?id=${h.objectID}`,+ snippet: `Hacker News discussion · ${h.points ?? 0} points · https://news.ycombinator.com/item?id=${h.objectID}`,+ source: 'Hacker News',+ date: h.created_at,+ }));+}++/**+ * The search query behind a search-engine results URL, or null. Old skills+ * (and models from habit) fetch DuckDuckGo/Google/Bing result pages with+ * fetch_url; those answer bots with a challenge page or a wall of markup.+ * fetch_url hands such a URL to web_search instead.+ */+export function searchQueryFromUrl(raw: string): string | null {+ let u: URL;+ try { u = new URL(raw); } catch { return null; }+ const host = u.hostname.replace(/^www\./, '');+ const isSearch =+ (/^(html\.|lite\.)?duckduckgo\.com$/.test(host) && (u.pathname === '/' || /^\/(html|lite)\/?$/.test(u.pathname)))+ || (/^google\.[a-z.]+$/.test(host) && u.pathname === '/search')+ || (host === 'bing.com' && u.pathname === '/search' && u.searchParams.get('format') !== 'rss')+ || (host === 'search.yahoo.com' && u.pathname.startsWith('/search'))+ || (host === 'search.brave.com' && u.pathname === '/search')+ || (host === 'startpage.com' && u.pathname.startsWith('/do/search'))+ || (host === 'mojeek.com' && u.pathname === '/search');+ if (!isSearch) return null;+ const q = (u.searchParams.get('q') ?? u.searchParams.get('p') ?? u.searchParams.get('query') ?? '').trim();+ return q || null;+}++/** web_search output as text, for the tool and for fetch_url's search redirect. */+export function formatResults(results: SearchResult[], engine: string, query: string, kind: 'web' | 'news'): string {+ const lines = results.map((r, i) => {+ const meta = [r.source, r.date ? new Date(r.date).toUTCString().slice(0, 16) : ''].filter(Boolean).join(' · ');+ return `${i + 1}. ${r.title}${meta ? ` (${meta})` : ''}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`;+ });+ return `${kind === 'news' ? 'News' : 'Web'} results from ${engine} for "${query || 'top stories'}":\n\n${lines.join('\n')}`;+}++const STOP = new Set(['the', 'and', 'for', 'with', 'what', 'who', 'how', 'are', 'was', 'is', 'of', 'in', 'on', 'to', 'a', 'an', 'best', 'top', 'latest', 'new', 'news', 'does', 'did', 'can', 'from', 'about', 'near', 'me', 'my', 'vs']);++/**+ * Keep results that mention the query: every significant word when there are+ * one or two, at least half of them otherwise (title, snippet or URL). An+ * engine that answers with unrelated pages — Bing's web RSS does this to+ * automated requests — then counts as "no results" and the chain moves on+ * instead of handing the model junk. A query with no usable words (empty,+ * all stopwords) keeps everything.+ */+export function relevant(query: string, results: SearchResult[]): SearchResult[] {+ const terms = [...new Set(query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((w) => w.length >= 3 && !STOP.has(w)))];+ if (terms.length === 0) return results;+ const need = terms.length <= 2 ? terms.length : Math.ceil(terms.length / 2);+ return results.filter((r) => {+ const hay = `${r.title} ${r.snippet} ${decodeURIComponent(r.url.replace(/%(?![0-9a-f]{2})/gi, '%25'))}`.toLowerCase();+ return terms.filter((t) => hay.includes(t)).length >= need;+ });+}++/** Results that point at the same page (http/https, www, trailing slash, fragments) count once. */+function dedupe(results: SearchResult[]): SearchResult[] {+ const seen = new Set<string>();+ return results.filter((r) => {+ const key = r.url.replace(/^https?:\/\/(www\.)?/, '').replace(/#.*$/, '').replace(/\/$/, '').toLowerCase();+ if (seen.has(key)) return false;+ seen.add(key);+ return true;+ });+}+export async function webSearch(query: string, opts: { kind?: 'web' | 'news'; max?: number } = {}): Promise<{ results: SearchResult[]; engine: string }> {const max = Math.max(1, Math.min(opts.max ?? 8, 15));+ // Every engine is free and keyless; no library. Brave is the main web+ // index (DuckDuckGo, Mojeek and Startpage answer automated requests with a+ // challenge; Bing's web RSS with unrelated pages). Then Wikipedia, Hacker+ // News, Bing News and Google News, so one blocked or empty source never+ // means "no results". Each answer must pass the relevance check.const engines: Array<[string, (q: string, n: number) => Promise<SearchResult[]>]> = opts.kind === 'news'- ? [['Google News', googleNews], ['Bing', bing]]- : [['Bing', bing], ['Google News', googleNews]];+ ? [['Google News', googleNews], ['Bing News', bingNews], ['Hacker News', hackerNews]]+ : [['Brave', brave], ['Wikipedia', wikipedia], ['Hacker News', hackerNews], ['Bing News', bingNews], ['Google News', googleNews], ['Bing', bing]];const errors: string[] = [];for (const [name, run] of engines) {try {- const results = await run(query, max);- if (results.length) return { results, engine: name };+ const raw = await run(query, max);+ let results = dedupe(relevant(query, raw));+ if (!results.length) { errors.push(`${name}: ${raw.length ? 'only unrelated results' : 'no results'}`); continue; }+ // A thin web answer (a few hits) is topped up with Wikipedia, which+ // is the most reliable second opinion for facts.+ if (opts.kind !== 'news' && results.length < Math.min(4, max) && name !== 'Wikipedia') {+ const extra = relevant(query, await wikipedia(query, max - results.length).catch(() => []));+ if (extra.length) return { results: dedupe([...results, ...extra]).slice(0, max), engine: `${name} + Wikipedia` };+ }+ results = results.slice(0, max);+ return { results, engine: name };errors.push(`${name}: no results`);} catch (err) {errors.push(`${name}: ${(err as Error).message}`);@@ -126,11 +293,7 @@ export function createWebSearchTool() {execute: async ({ query, kind, max }) => {try {const { results, engine } = await webSearch(query, { kind: kind ?? 'web', max: max ?? 8 });- const lines = results.map((r, i) => {- const meta = [r.source, r.date ? new Date(r.date).toUTCString().slice(0, 16) : ''].filter(Boolean).join(' · ');- return `${i + 1}. ${r.title}${meta ? ` (${meta})` : ''}\n ${r.url}${r.snippet ? `\n ${r.snippet}` : ''}`;- });- return `${kind === 'news' ? 'News' : 'Web'} results from ${engine} for "${query || 'top stories'}":\n\n${lines.join('\n')}`;+ return formatResults(results, engine, query, kind ?? 'web');} catch (err) {return `Error: web search is unavailable right now: ${(err as Error).message}`;}diff --git a/src/channels/cli.ts b/src/channels/cli.tsindex 0f386fc9..1c945449 100644--- a/src/channels/cli.ts+++ b/src/channels/cli.ts@@ -2080,15 +2080,23 @@ export class CLIChannel extends BaseChannel {return this.enqueuePrompt({ type: 'ask', message: question }, String);}- async askPermissionMode(): Promise<PermissionMode> {- if (!process.stdout.isTTY) return 'ask-me';+ /**+ * The Ask Me / Allow All prompt for this session. `current` (the saved+ * mode) is listed first, so Enter keeps it and ↓ Enter switches.+ */+ async askPermissionMode(current?: PermissionMode): Promise<PermissionMode> {+ if (!process.stdout.isTTY) return current ?? 'ask-me';+ const options = [+ { value: 'allow-all', label: 'Allow All — auto-approve everything (scopes, commands, loop continuation)' },+ { value: 'ask-me', label: 'Ask Me — confirm before file writes, shell commands, and scope changes' },+ ];+ if (current === 'ask-me') options.reverse();return this.enqueuePrompt({type: 'mode',- message: 'Choose how Mercury handles risky actions this session.',- options: [- { value: 'allow-all', label: 'Allow All — auto-approve everything (scopes, commands, loop continuation)' },- { value: 'ask-me', label: 'Ask Me — confirm before file writes, shell commands, and scope changes' },- ],+ message: current+ ? `Permission mode for this session? (now: ${current === 'allow-all' ? 'Allow All' : 'Ask Me'} — Enter keeps it)`+ : 'Choose how Mercury handles risky actions this session.',+ options,}, (val) => val as PermissionMode);}diff --git a/src/channels/web.test.ts b/src/channels/web.test.tsindex 1ac65abd..81853618 100644--- a/src/channels/web.test.ts+++ b/src/channels/web.test.ts@@ -133,6 +133,21 @@ describe('WebChannel durable streaming', () => {await expect(decision).resolves.toBe('');});+ it('tells only the screen listening on the old session to follow a re-bind', () => {+ const channel = new WebChannel('Mercury');+ const seen: Record<string, string[]> = { old: [], other: [] };+ for (const [key, sessionId] of [['old', 'sess-old'], ['other', 'sess-other']] as const) {+ channel.addSSEClient({+ enqueue(value: Uint8Array) { seen[key].push(new TextDecoder().decode(value)); },+ close() {},+ } as unknown as ReadableStreamDefaultController, sessionId);+ }+ channel.sendSessionSwitched('sess-old', { id: 'sess-new', shortId: 'sess-new', alias: 'obsidian-cedar', title: 'New session' });+ expect(seen.old.join('')).toContain('event: session_switched');+ expect(seen.old.join('')).toContain('"alias":"obsidian-cedar"');+ expect(seen.other).toEqual([]);+ });+it('scopes allow-all mode to its Cloud session', async () => {const channel = new WebChannel('Mercury');channel.setSessionPermissionMode('session-allowed', 'allow-all');diff --git a/src/channels/web.ts b/src/channels/web.tsindex 07253baa..a40aa149 100644--- a/src/channels/web.ts+++ b/src/channels/web.ts@@ -17,7 +17,7 @@ interface PendingInteraction {}export interface ChatEvent {- type: 'thinking' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status';+ type: 'thinking' | 'provider' | 'heartbeat' | 'step_start' | 'step_done' | 'text_delta' | 'text_done' | 'permission_request' | 'permission_continue' | 'permission_mode' | 'permission_resolved' | 'choice_prompt' | 'choice_resolved' | 'loop_warning' | 'error' | 'bot_activity' | 'status' | 'session_switched';data?: Record<string, unknown>;}@@ -105,6 +105,16 @@ export class WebChannel extends BaseChannel {this.broadcast({ type: 'status', data: { ...status } });}+ /**+ * The screen listening on `targetId` was re-bound to another session+ * (/new, /session <ref>, a deleted current session). Without this the+ * attached terminal kept streaming the old id: replies to the new session+ * never reached it, and it showed "Thinking" forever.+ */+ sendSessionSwitched(targetId: string, session: { id: string; shortId: string; alias: string; title: string }): void {+ this.broadcast({ type: 'session_switched', data: { targetId, id: session.id, shortId: session.shortId, alias: session.alias, title: session.title } });+ }+broadcastBotActivity(ev: { botId: string; jobId: string; kind: string; label: string; detail?: string; stepIndex: number; elapsedMs: number; status?: string }): void {this.broadcast({ type: 'bot_activity', data: { ...ev } });}diff --git a/src/cli/attach.ts b/src/cli/attach.tsindex 66295763..c1c0f5c3 100644--- a/src/cli/attach.ts+++ b/src/cli/attach.ts@@ -33,6 +33,7 @@ export type AttachEventType =| 'choice_resolved'| 'loop_warning'| 'error'+ | 'session_switched'// Client-transport pseudo-events (never sent by the server).| 'attach_disconnected'| 'attach_auth_error';diff --git a/src/core/agent.ts b/src/core/agent.tsindex 02883645..8a07be1d 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -2079,7 +2079,9 @@ export class Agent {saveConfig(this.config);updateCliProviderStatus(this.channels.get('cli'), providerName, model);- return { ok: true, message: `Default model switched to **${providerName}** · **${model}**. Saved for future sessions.` };+ // "Saved for future sessions" read as "takes effect next session"; it+ // applies to the next message and stays the default after a restart.+ return { ok: true, message: `✓ Switched to **${model}** (${providerName}). In effect from your next message, and kept as the default.` };}/** Returns the currently active provider name and model. */diff --git a/src/core/commands/chat-command.test.ts b/src/core/commands/chat-command.test.tsnew file mode 100644index 00000000..8f114091--- /dev/null+++ b/src/core/commands/chat-command.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it, vi } from 'vitest';+import { WebChannel } from '../../channels/web.js';+import { handleChatCommand } from './chat-command.js';++/**+ * Pickers on the owner's own screens. Since 1.3.1 the default launch attaches+ * to the runtime, which talks over the web channel — so a picker that was+ * only offered to the CLI channel was a picker nobody saw.+ */++type Agent = import('../agent.js').Agent;++function sseChannel(sessionId: string): { channel: WebChannel; events: Array<{ type: string; data: Record<string, unknown> }>; sent: string[] } {+ const channel = new WebChannel('Mercury');+ const events: Array<{ type: string; data: Record<string, unknown> }> = [];+ channel.addSSEClient({+ enqueue(value: Uint8Array) {+ const text = new TextDecoder().decode(value);+ const type = /event: (\S+)/.exec(text)?.[1];+ const data = /data: (.+)/.exec(text)?.[1];+ if (type && data) events.push({ type, data: JSON.parse(data) as Record<string, unknown> });+ },+ close() {},+ } as unknown as ReadableStreamDefaultController, sessionId);+ const sent: string[] = [];+ const realSend = channel.send.bind(channel);+ channel.send = async (content: string, targetId?: string, elapsedMs?: number) => { sent.push(content); await realSend(content, targetId, elapsedMs); };+ return { channel, events, sent };+}++function agentWith(channel: WebChannel, switchSessionProvider: (name: string) => Promise<{ ok: boolean; message: string }>): Agent {+ const providers = {+ anthropic: { name: 'anthropic', enabled: true, apiKey: 'k', model: 'claude-haiku-4-5' },+ openai: { name: 'openai', enabled: true, apiKey: 'k', model: 'gpt-4.1-mini' },+ default: 'anthropic',+ };+ return {+ config: { providers },+ providers: { getDefault: () => ({ name: 'anthropic', model: 'claude-haiku-4-5' }) },+ channels: { get: () => channel },+ capabilities: { getChatCommandContext: () => ({ config: () => ({ providers }) }) },+ switchSessionProvider,+ } as unknown as Agent;+}++const tick = () => new Promise((r) => setTimeout(r, 0));++describe('/model on the attached terminal (web channel)', () => {+ it('lists the models, then offers an arrow-key picker and switches to the pick', async () => {+ const { channel, events, sent } = sseChannel('sess-1');+ const switched = vi.fn(async (name: string) => ({ ok: true, message: `✓ Switched to ${name}` }));+ const done = handleChatCommand(agentWith(channel, switched), '/model', 'web', 'sess-1');+ await tick();++ expect(sent[0]).toContain('**Session Models**');+ expect(sent[0]).toContain('anthropic · claude-haiku-4-5 ← current');+ const prompt = events.find((e) => e.type === 'choice_prompt');+ expect(prompt?.data.question).toBe('Switch session model?');+ const options = prompt?.data.options as Array<{ value: string; label: string }>;+ expect(options.map((o) => o.label)).toEqual([+ 'anthropic · claude-haiku-4-5 (current)',+ 'openai · gpt-4.1-mini',+ 'Open doctor instructions',+ 'Keep current model',+ ]);++ expect(channel.resolveChoice(String(prompt!.data.id), '1', 'sess-1')).toBe(true);+ expect(await done).toBe(true);+ expect(switched).toHaveBeenCalledWith('openai');+ expect(sent.at(-1)).toBe('✓ Switched to openai');+ });++ it('Esc on the picker changes nothing — the first option is never taken by default', async () => {+ const { channel, events } = sseChannel('sess-1');+ const switched = vi.fn(async (name: string) => ({ ok: true, message: name }));+ const done = handleChatCommand(agentWith(channel, switched), '/model', 'web', 'sess-1');+ await tick();+ const id = String(events.find((e) => e.type === 'choice_prompt')!.data.id);+ expect(channel.cancelInteraction(id, 'sess-1')).toBe(true);+ expect(await done).toBe(true);+ expect(switched).not.toHaveBeenCalled();+ });++ it('/new asks which permission mode the fresh session runs in; Esc keeps the current one', async () => {+ const { channel, events, sent } = sseChannel('sess-1');+ const agent = agentWith(channel, async (name) => ({ ok: true, message: name }));+ (agent as unknown as { handleSessionCommand: () => Promise<void> }).handleSessionCommand = async () => { await channel.send('New session: quiet-harbour', 'sess-1'); };++ const done = handleChatCommand(agent, '/new', 'web', 'sess-1');+ await tick();+ expect(sent[0]).toBe('New session: quiet-harbour');+ const prompt = events.find((e) => e.type === 'choice_prompt')!;+ expect(prompt.data.question).toMatch(/^Permission mode for this session\? \(now: (Ask Me|Allow All)\)$/);+ expect(channel.cancelInteraction(String(prompt.data.id), 'sess-1')).toBe(true);+ expect(await done).toBe(true);+ expect(sent[1]).toMatch(/^(Ask Me|Allow All): Mercury .* Unchanged\. \/permissions switches any time\.$/);++ // Picking applies at once: the web channel's bypass flag follows the pick.+ const again = handleChatCommand(agent, '/new', 'web', 'sess-1');+ await tick();+ const second = events.filter((e) => e.type === 'choice_prompt').at(-1)!;+ expect(channel.resolveChoice(String(second.data.id), 'allow-all', 'sess-1')).toBe(true);+ expect(await again).toBe(true);+ expect(channel.getSettings().bypassPermissions).toBe(true);+ expect(sent.at(-1)).toMatch(/^Allow All: .* Saved: Mercury remembers this/);+ });++ it('with no attached screen for that session there is no picker, just the list', async () => {+ const { channel, events } = sseChannel('other-session');+ const switched = vi.fn(async (name: string) => ({ ok: true, message: name }));+ expect(await handleChatCommand(agentWith(channel, switched), '/model', 'web', 'sess-1')).toBe(true);+ expect(events.find((e) => e.type === 'choice_prompt')).toBeUndefined();+ expect(switched).not.toHaveBeenCalled();+ });+});diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.tsindex 3a7cdb29..8df771d3 100644--- a/src/core/commands/chat-command.ts+++ b/src/core/commands/chat-command.ts@@ -52,6 +52,73 @@ import { publishStatus, updateCliProviderStatus } from '../provider-status.js';import { whatsNewText } from '../../utils/whats-new.js';import { FORGET_THAT_RE, MEMORY_SUBCOMMAND_HELP, handleBeliefCommand } from './memory-commands.js';+/**+ * The owner's own screens: the foreground terminal (CLI channel) and the+ * attached terminal or dashboard (web channel). Both can show an arrow-key+ * picker; every other channel gets text. Since 1.3.1 the default launch+ * attaches, so a picker offered only to the CLI channel was a picker nobody+ * saw — /model made people type `/models use <name>`.+ */+function isOwnerScreen(channel: unknown, channelType: string): channel is CLIChannel | WebChannel {+ return channel instanceof WebChannel || (channelType === 'cli' && channel instanceof CLIChannel);+}++/**+ * An arrow-key choice on an owner screen. Returns the chosen label, or null+ * when the owner dismissed it (Esc) or the screen could not show it, so a+ * dismissed picker never silently acts on the first option.+ */+async function pickOnOwnerScreen(agent: Agent, channel: CLIChannel | WebChannel, channelType: string, channelId: string, question: string, labels: string[]): Promise<string | null> {+ if (channel instanceof WebChannel) {+ const value = await channel.presentChoicePrompt(question, labels.map((label, i) => ({ value: String(i), label })), channelId);+ const idx = Number.parseInt(value, 10);+ return Number.isInteger(idx) && labels[idx] !== undefined ? labels[idx] : null;+ }+ const picked = await agent.presentChoice(question, labels, channelId, channelType);+ return labels.includes(picked) ? picked : null;+}++/**+ * The Ask Me / Allow All picker on an owner screen (/permissions, and a+ * fresh /new session). The current mode is named in the question; Esc keeps+ * it. A pick is applied, saved and pushed to every status row.+ */+async function offerPermissionMode(agent: Agent, channel: CLIChannel | WebChannel, channelId: string, question: string): Promise<void> {+ if (channel instanceof CLIChannel) {+ const mode = await channel.askPermissionMode(loadPermissionMode() ?? undefined);+ if (mode === 'allow-all') {+ agent.capabilities.permissions.setAutoApproveAll(true);+ agent.capabilities.permissions.addTempScope('/', true, true);+ } else {+ agent.capabilities.permissions.setAutoApproveAll(false);+ }+ const chosen = mode === 'allow-all' ? 'allow-all' : 'ask-me';+ savePermissionMode(chosen);+ channel.setPermissionModeStatus(chosen);+ publishStatus();+ await channel.send(`${describePermissionMode(chosen)} Saved: Mercury remembers this. Change it any time with /permissions.`, channelId);+ return;+ }+ // The attached terminal and the dashboard (channel type 'web').+ const current = loadPermissionMode() ?? (channel.getSettings().bypassPermissions ? 'allow-all' : 'ask-me');+ const picked = await channel.presentChoicePrompt(+ `${question} (now: ${current === 'allow-all' ? 'Allow All' : 'Ask Me'})`,+ [+ { value: 'ask-me', label: 'Ask Me: ask before writing files or running commands' },+ { value: 'allow-all', label: 'Allow All: just do it (blocked commands stay blocked)' },+ ],+ channelId,+ );+ if (picked !== 'ask-me' && picked !== 'allow-all') {+ await channel.send(`${describePermissionMode(current)} Unchanged. /permissions switches any time.`, channelId);+ return;+ }+ channel.setBypassPermissions(picked === 'allow-all');+ savePermissionMode(picked);+ publishStatus();+ await channel.send(`${describePermissionMode(picked)} Saved: Mercury remembers this. Change it any time with /permissions.`, channelId);+}+export async function handleChatCommand(agent: Agent, content: string, channelType: string, channelId: string): Promise<boolean> {const trimmed = content.trim();const cmd = trimmed.toLowerCase();@@ -70,6 +137,9 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy// Unlike /reset this never halts agents, clears queues, or wipes state.if (cmd === '/new') {await agent.handleSessionCommand('/session new', channelType as ChannelType, channelId);+ // A fresh session on the owner's own screen asks which permission mode+ // to run in (the current one is shown; Esc keeps it).+ if (isOwnerScreen(channel, channelType)) await offerPermissionMode(agent, channel, channelId, 'Permission mode for this session?');return true;}@@ -169,41 +239,8 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy}if (cmd === '/permissions') {- if (channelType === 'cli' && channel instanceof CLIChannel) {- const mode = await channel.askPermissionMode?.();- if (mode === 'allow-all') {- agent.capabilities.permissions.setAutoApproveAll(true);- agent.capabilities.permissions.addTempScope('/', true, true);- } else {- agent.capabilities.permissions.setAutoApproveAll(false);- }- const chosen = mode === 'allow-all' ? 'allow-all' : 'ask-me';- savePermissionMode(chosen);- channel.setPermissionModeStatus(chosen);- publishStatus();- await channel.send(`${describePermissionMode(chosen)} Saved: Mercury remembers this. Change it any time with /permissions.`, channelId);- return true;- }- // The attached terminal and the dashboard are the owner's own screens- // (channel type 'web'): offer the same choice and remember it.- if (channel instanceof WebChannel) {- const current = loadPermissionMode() ?? (channel.getSettings().bypassPermissions ? 'allow-all' : 'ask-me');- const picked = await channel.presentChoicePrompt(- `How should Mercury handle risky actions? (now: ${current === 'allow-all' ? 'Allow All' : 'Ask Me'})`,- [- { value: 'ask-me', label: 'Ask Me: ask before writing files or running commands' },- { value: 'allow-all', label: 'Allow All: just do it (blocked commands stay blocked)' },- ],- channelId,- );- if (picked !== 'ask-me' && picked !== 'allow-all') {- await channel.send('No change. Type /permissions allow-all or /permissions ask-me to switch directly.', channelId);- return true;- }- channel.setBypassPermissions(picked === 'allow-all');- savePermissionMode(picked);- publishStatus();- await channel.send(`${describePermissionMode(picked)} Saved: Mercury remembers this. Change it any time with /permissions.`, channelId);+ if (isOwnerScreen(channel, channelType)) {+ await offerPermissionMode(agent, channel, channelId, 'How should Mercury handle risky actions?');return true;}await channel.send('On Telegram, use the /permissions button or command. Your own terminal and dashboard use /permissions too.', channelId);@@ -255,18 +292,18 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy];await channel.send(lines.join('\n'), channelId);- if (channelType === 'cli' && channel instanceof CLIChannel && activeProviders.length > 1) {+ if (activeProviders.length > 1 && isOwnerScreen(channel, channelType)) {const choices = [...activeProviders.map((p) => `${p.name} · ${p.model}${p.name === current.name ? ' (current)' : ''}`),'Open doctor instructions','Keep current model',];- const picked = await agent.presentChoice('Switch session model?', choices, channelId, channelType);+ const picked = await pickOnOwnerScreen(agent, channel, channelType, channelId, 'Switch session model?', choices);+ if (picked === null || picked === 'Keep current model') return true;if (picked === 'Open doctor instructions') {await channel.send('Run `mercury doctor` and update provider/model settings. Then restart Mercury to persist defaults.', channelId);return true;}- if (picked === 'Keep current model') return true;const providerName = picked.split(' · ')[0].trim();if (providerName && providerName !== current.name) {const switched = await agent.switchSessionProvider(providerName);@@ -368,7 +405,7 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy];await channel.send(lines.join('\n'), channelId);- if (channelType === 'cli' && channel instanceof CLIChannel) {+ if (isOwnerScreen(channel, channelType)) {const availableModels = models.filter((m) => m.available);const choices = [...availableModels.map((m) => `${m.id} · ${m.label}${m.id === currentModel ? ' (current)' : ''}`),@@ -378,8 +415,8 @@ export async function handleChatCommand(agent: Agent, content: string, channelTyawait channel.send('Only one model available for your tier. Upgrade to unlock more.', channelId);return true;}- const picked = await agent.presentChoice('Switch cloud model?', choices, channelId, channelType);- if (picked === 'Keep current model') return true;+ const picked = await pickOnOwnerScreen(agent, channel, channelType, channelId, 'Switch cloud model?', choices);+ if (picked === null || picked === 'Keep current model') return true;const modelId = picked.split(' · ')[0].trim();if (modelId) {cfg.providers.mercuryCloud.model = modelId;diff --git a/src/core/commands/session-command.ts b/src/core/commands/session-command.tsindex adef6cc2..89bc8b47 100644--- a/src/core/commands/session-command.ts+++ b/src/core/commands/session-command.ts@@ -5,12 +5,19 @@import type { Agent } from '../agent.js';import type { ChannelMessage, ChannelType } from '../../types/channel.js';import { CLIChannel } from '../../channels/cli.js';+import { WebChannel } from '../../channels/web.js';import { normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../../sessions/index.js';export async function handleSessionCommand(agent: Agent, content: string, channelType: ChannelType, channelId: string): Promise<void> {const channel = agent.channels.get(channelType);if (!channel) return;const bindingId = channelType === 'cli' ? 'current' : channelId;+ // The attached terminal / dashboard listens on the session id it started+ // with; after a re-bind it must follow, or it waits forever on the old one.+ // Sent after the reply so the reply still reaches the old subscription.+ const followSession = (session: { id: string; shortId: string; alias: string; title: string }) => {+ if (channelType === 'web' && channel instanceof WebChannel && session.id !== channelId) channel.sendSessionSwitched(channelId, session);+ };const format = (session: { alias: string; shortId: string; title: string }) => `${session.alias} [${session.shortId}] ${session.title}`;const transcript = (session: ReturnType<SessionRepository['get']>) => {const recent = session.messages@@ -43,6 +50,7 @@ export async function handleSessionCommand(agent: Agent, content: string, channeagent.sessions.bind(session.id, channelType, bindingId);syncCliSession(session);await channel.send(`New session: ${format(session)}`, channelId);+ followSession(session);return;}if (!argument || argument.toLowerCase() === 'current') {@@ -69,6 +77,7 @@ export async function handleSessionCommand(agent: Agent, content: string, channe`Deleted session ${session.alias} [${session.shortId}].${agent.sessionSyncEnabled ? ' Cloud deletion is queued.' : ''}${replacement ? ` New session: ${format(replacement)}` : ''}`,channelId,);+ if (replacement) followSession(replacement);return;}if (argument.toLowerCase().startsWith('archive ')) {@@ -86,6 +95,7 @@ export async function handleSessionCommand(agent: Agent, content: string, channeagent.sessions.bind(session.id, channelType, bindingId);syncCliSession(session);await channel.send(`Switched session: ${format(session)}\n\n${transcript(session)}`, channelId);+ followSession(session);} catch (error) {const message = error instanceof SessionResolutionError ? error.message : error instanceof Error ? error.message : String(error);await channel.send(message, channelId);diff --git a/src/core/provider-default.test.ts b/src/core/provider-default.test.tsindex 583f8b39..a303fbef 100644--- a/src/core/provider-default.test.ts+++ b/src/core/provider-default.test.ts@@ -22,9 +22,9 @@ const src = (p: string) => readFileSync(join(dirname(fileURLToPath(import.meta.udescribe('default provider is respected', () => {it('agent: /models use persists the switch via saveConfig', () => {const agent = src('agent.ts');- // The persisted message must say so — no silent session-only mutation.- expect(agent).toContain('Default model switched to');- expect(agent).toContain('Saved for future sessions');+ // The message must say it is in effect now AND kept — "saved for future+ // sessions" alone read as "takes effect next session".+ expect(agent).toContain('In effect from your next message, and kept as the default.');// switchSessionProvider saves after rebuilding the registry.expect(agent).toMatch(/saveConfig\(this\.config\);\s*\n\s*updateCliProviderStatus\(this\.channels\.get\('cli'\), providerName, model\);/);});diff --git a/src/core/system-prompt.test.ts b/src/core/system-prompt.test.tsindex ee4e09b7..21bcf749 100644--- a/src/core/system-prompt.test.ts+++ b/src/core/system-prompt.test.ts@@ -67,6 +67,8 @@ describe('system prompt assembly', () => {it('plain chat gets the work contract; Mercury Code keeps its own', () => {const chat = buildSystemPrompt(base);expect(chat).toContain('**How you work:**');+ // Decisions go through ask_user (an arrow-key picker), not a question in prose.+ expect(chat).toContain('Ask with ask_user');const code = buildSystemPrompt({ ...base, programmingSuffix: '\n\nCODE' });expect(code).not.toContain('**How you work:**');});diff --git a/src/core/system-prompt.ts b/src/core/system-prompt.tsindex 1ff29845..6daaee2f 100644--- a/src/core/system-prompt.ts+++ b/src/core/system-prompt.ts@@ -56,6 +56,7 @@ export const CHAT_WORK_CONTRACT = `**How you work:**- First work out the end result they want, then the fastest reliable way to get there (an existing command, library or service beats manual steps).- For tasks with several steps, keep a short plan with update_plan and work through it.- Report what you did and what you checked, briefly. If something failed or you could not confirm it, say so plainly.+- Need the user to decide before you go on — yes or no, or which of a few options? Ask with ask_user, so they pick with the arrow keys instead of typing an answer. Only a question that needs free text (a name, a path, a date) is asked in words.- Plain questions and conversation don't need tools: just answer.`;/**diff --git a/src/index.ts b/src/index.tsindex 1df61b79..c8c66c39 100644--- a/src/index.ts+++ b/src/index.ts@@ -3788,11 +3788,14 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {cliChannel.setCurrentSession(selected);}- // Ask once, then remember (also covers Mercury Code). /permissions changes it.+ // Every session starts by asking (also Mercury Code): the saved mode is+ // listed first so Enter keeps it. The pick is remembered as the default+ // for next time; /permissions changes it mid-session.const savedMode = loadPermissionMode();- const mode = savedMode ?? (cliChannel ? await cliChannel.askPermissionMode?.() : undefined);- if (!savedMode && (mode === 'allow-all' || mode === 'ask-me') && process.stdout.isTTY) savePermissionMode(mode);- if (savedMode && cliChannel) console.log(chalk.dim(` Permissions: ${savedMode === 'allow-all' ? 'Allow All' : 'Ask Me'} · /permissions to change`));+ const mode = cliChannel && process.stdout.isTTY+ ? await cliChannel.askPermissionMode(savedMode ?? undefined)+ : savedMode ?? 'ask-me';+ if ((mode === 'allow-all' || mode === 'ask-me') && process.stdout.isTTY) savePermissionMode(mode);cliChannel?.setPermissionModeStatus(mode === 'allow-all' ? 'allow-all' : 'ask-me');if (mode === 'allow-all') {capabilities.permissions.setAutoApproveAll(true);diff --git a/src/skills/default-skills.ts b/src/skills/default-skills.tsindex abb68b31..efa444ed 100644--- a/src/skills/default-skills.ts+++ b/src/skills/default-skills.ts@@ -26,6 +26,54 @@ export function getCategoryLabel(category: string): string {export const PREVIOUS_SEED_CONTENTS: Record<string, string[]> = {'web-search': [`---name: web-search+description: Search the web and the news with the web_search tool, read the best sources, and answer with links.+version: 1.1.0+category: web+categories:+ - web+ - research+intents:+ - search the web+ - look up+ - find online+ - what is+ - current news+ - search for+ - find information about+ - research+ - web search+ - latest news+ - what's happening+tags:+ - search+ - web+ - research+ - news+allowed-tools:+ - web_search+ - fetch_url+---++# Web Search++Use this skill when the user asks for current events, external facts, or web research.++## Workflow++1. Call web_search with a focused query. For news and recent events use kind "news"+ (an empty query gives today's top stories).+2. Open the most relevant one to three results with fetch_url when the snippets aren't enough.+3. Cross-check key facts across at least 2 sources when possible.+4. Return a concise answer with source links and clear caveats.++## Rules++- Prefer reliable sources (official docs, primary sources, reputable publications).+- If information is uncertain or conflicting, say so explicitly.+- Include source URLs in the response (on phone chats, keep it to the one or two that matter).+- Avoid fabricated citations.+`, `---+name: web-searchdescription: Perform web searches using DuckDuckGo HTML and summarize sources.version: 1.0.0category: web@@ -80,7 +128,7 @@ export const DEFAULT_SKILL_SEEDS: DefaultSkillSeed[] = [content: `---name: web-searchdescription: Search the web and the news with the web_search tool, read the best sources, and answer with links.-version: 1.1.0+version: 1.2.0category: webcategories:- web@@ -113,11 +161,13 @@ Use this skill when the user asks for current events, external facts, or web res## Workflow-1. Call web_search with a focused query. For news and recent events use kind "news"- (an empty query gives today's top stories).+1. Call web_search with a focused query of a few key words (names, product, place, year).+ For news and recent events use kind "news" (an empty query gives today's top stories).2. Open the most relevant one to three results with fetch_url when the snippets aren't enough.-3. Cross-check key facts across at least 2 sources when possible.-4. Return a concise answer with source links and clear caveats.+3. Nothing useful? Rephrase once (synonyms, the official name, fewer words) and search again+ before saying you could not find it.+4. Cross-check key facts across at least 2 sources when possible.+5. Return a concise answer with source links and clear caveats.## Rules@@ -125,6 +175,9 @@ Use this skill when the user asks for current events, external facts, or web res- If information is uncertain or conflicting, say so explicitly.- Include source URLs in the response (on phone chats, keep it to the one or two that matter).- Avoid fabricated citations.+- Never fetch a search engine's results page (DuckDuckGo, Google, Bing) with fetch_url: they block+ automated reads. web_search already tries several free engines (Brave, Wikipedia, Hacker News,+ news feeds) and keeps only results that match the query.`,},{diff --git a/src/skills/loader.ts b/src/skills/loader.tsindex aa4aa190..5aee83b6 100644--- a/src/skills/loader.ts+++ b/src/skills/loader.ts@@ -8,6 +8,18 @@ import { IntentRouter } from './intent-router.js';import { logger } from '../utils/logger.js';import { DEFAULT_SKILL_SEEDS, PREVIOUS_SEED_CONTENTS, getCategoryLabel } from './default-skills.js';+/**+ * The web-search skill dir holds a skill that tells the model to fetch a+ * search engine's HTML results page and never mentions the web_search tool.+ * Those pages answer automated requests with a bot challenge, so such a+ * skill only ever returns nothing.+ */+export function isBrokenSearchSkill(dirName: string, content: string): boolean {+ if (dirName !== 'web-search') return false;+ if (/\bweb_search\b/.test(content)) return false;+ return /(html|lite)\.duckduckgo\.com|duckduckgo\.com\/html|google\.[a-z.]+\/search\?|bing\.com\/search\?q=/i.test(content);+}+const SKILL_FILE = 'SKILL.md';const DISABLED_FILE = '.disabled';@@ -431,6 +443,14 @@ Describe what this skill enables Mercury to do. When invoked via the use_skill tif (current !== seed.content && (PREVIOUS_SEED_CONTENTS[seed.dirName] ?? []).includes(current)) {writeFileSync(skillFile, seed.content, 'utf-8');logger.info({ skill: seed.dirName }, 'Upgraded default skill');+ } else if (current !== seed.content && isBrokenSearchSkill(seed.dirName, current)) {+ // A web-search skill that scrapes a search engine's HTML page+ // (usually DuckDuckGo, which now answers bots with a challenge)+ // never works. Keep the owner's copy beside it and use the+ // built-in one, which calls the web_search tool.+ writeFileSync(`${skillFile}.replaced.bak`, current, 'utf-8');+ writeFileSync(skillFile, seed.content, 'utf-8');+ logger.info({ skill: seed.dirName, backup: `${skillFile}.replaced.bak` }, 'Replaced a web-search skill that scrapes a blocked search page');}} catch { /* leave it */ }continue;diff --git a/src/ui/App.tsx b/src/ui/App.tsxindex 5f4fe623..8a19bbe3 100644--- a/src/ui/App.tsx+++ b/src/ui/App.tsx@@ -2682,32 +2682,29 @@ export function MercuryCodeView({const git = mc.git;// '' = not read yet (async refresh pending); hide the segment until then.const hasGit = git.branch !== '' && git.branch !== 'no-git' && git.branch !== 'not-a-git-repo';- const rightSegs: Array<{ text: string; color: string }> = [{ text: mc.dirName, color: THEME_ACCENT }];- if (state.desktopActivity) rightSegs.push({ text: state.desktopActivity, color: 'yellow' });+ // Same row builder as chat (src/ui/status-bar.ts): permission, budget+ // meter, model (no provider name), mode, then the folder and branch;+ // fitted to the width in priority order so nothing collides or wraps.+ // Optimus activity, when there is any, is the last thing dropped.+ const extras: StatusSegment[] = [];if (hasGit) {const gitBits = [`⎇ ${git.branch}`];if (git.ahead > 0) gitBits.push(`↑${git.ahead}`);if (git.behind > 0) gitBits.push(`↓${git.behind}`);if (git.dirty > 0) gitBits.push(`±${git.dirty}`);- rightSegs.push({ text: gitBits.join(' '), color: 'blue' });+ extras.push({ text: gitBits.join(' '), compact: `⎇ ${git.branch}`, color: 'blue', priority: 6 });}- rightSegs.push({ text: modeLabel, color: mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : THEME_ACCENT });- if (state.provider) rightSegs.push({ text: `${state.provider.name} ${state.provider.model}`, color: 'magenta' });- rightSegs.push({ text: state.permissionMode === 'allow-all' ? 'Allow All' : 'Ask Me', color: state.permissionMode === 'allow-all' ? 'yellow' : 'gray' });- // Developer status HUD: token budget is otherwise invisible in Mercury- // Code (TokenBarView only renders in chat surfaces).- if (state.tokenInfo) rightSegs.push({ text: `⚡ ${Math.round(state.tokenInfo.percentage)}%`, color: 'green' });- // Update-available indicator: one dim segment, no extra row — ignorable via- // /update ignore, so it must never crowd the bar.- if (state.updateAvailable) rightSegs.push({ text: `⬆ v${state.updateAvailable}`, color: 'yellow' });- // Fit: drop whole segments from the right when the terminal is narrow.+ extras.push({ text: mc.dirName, color: THEME_ACCENT, priority: 7 });+ extras.push({ text: modeLabel, color: mode === 'execute' ? 'green' : mode === 'plan' ? 'yellow' : THEME_ACCENT, priority: 4 });+ const rightSegs = fitSegments(statusSegments({+ provider: state.provider,+ permission: state.permissionMode,+ tokensPct: state.tokenInfo ? state.tokenInfo.percentage : null,+ desktop: state.desktopActivity,+ updateAvailable: state.updateAvailable,+ extras,+ }), Math.max(10, cols - 6 - (ctrlCHint || state.tuiFrozen ? 40 : 0)));const SEP = ' · ';- let segWidth = 4; // paddingX on both sides- rightSegs.forEach((seg, i) => { segWidth += seg.text.length + (i > 0 ? SEP.length : 0); });- while (segWidth > cols - 2 && rightSegs.length > 1) {- const removed = rightSegs.pop()!;- segWidth -= removed.text.length + SEP.length;- }// Freeze hint lives in the status bar (not a new row) so the live region's// height stays constant — a new row would re-introduce scrollback churn.const leftHint = ctrlCHint@@ -2717,8 +2714,8 @@ export function MercuryCodeView({: mc.exitConfirm || state.permissionPrompt? '' // the prompt / confirm box already shows its own controls: state.isThinking || state.toolSteps.some((s) => s.status === 'running') || state.subAgents.some((a) => a.status === 'running')- ? 'esc interrupt' // the live feedback block above is showing progress- : '↵ send · esc esc exit · /help';+ ? '' // the live feedback block above is showing progress (esc interrupts)+ : ''; // idle: the row is status onlyconst showHints = finalizedMessages.length === 0 && streamTail.length === 0;@@ -2745,7 +2742,7 @@ export function MercuryCodeView({<Spacer /><Text wrap="truncate-end">{rightSegs.map((seg, i) => (- <React.Fragment key={seg.text}>+ <React.Fragment key={`${seg.priority}:${i}`}>{i > 0 && <Text color="gray">{SEP}</Text>}<Text color={seg.color}>{seg.text}</Text></React.Fragment>diff --git a/src/ui/attach-live-render.test.tsx b/src/ui/attach-live-render.test.tsxindex a58a19d0..2a75125b 100644--- a/src/ui/attach-live-render.test.tsx+++ b/src/ui/attach-live-render.test.tsx@@ -18,6 +18,7 @@ describe('attach TUI live rendering', () => {const { render } = await import('ink');const { AttachTui } = await import('./attach-tui.js');let emit: ((e: { type: string; data: Record<string, unknown> }) => void) | null = null;+ const streamedIds: string[] = [];const client = {getBaseUrl: () => 'http://127.0.0.1:6174',listThreads: async () => [],@@ -25,8 +26,9 @@ describe('attach TUI live rendering', () => {listBots: async () => [],currentModel: async () => ({ name: 'anthropic', model: 'x' }),budget: async () => null,+ permissionMode: async () => 'ask-me',createThread: async () => ({ id: 't1', shortId: 't1', alias: 'new', title: 'New' }),- streamEvents: async (_id: string, onEvent: (e: { type: string; data: Record<string, unknown> }) => void) => { emit = onEvent; await new Promise(() => {}); },+ streamEvents: async (id: string, onEvent: (e: { type: string; data: Record<string, unknown> }) => void) => { streamedIds.push(id); emit = onEvent; await new Promise(() => {}); },send: async () => ({ ok: true }),resolvePermission: async () => true,} as never;@@ -36,13 +38,25 @@ describe('attach TUI live rendering', () => {stdin.push('\r'); // "new session" is the only pick rowawait sleep(300);expect(emit).not.toBeNull();+ // A new session asks for its permission mode, the current one first so+ // Enter keeps it; no "—:" header rows anywhere.+ const entry = screen.text().join('\n');+ expect(entry).toContain('Permission mode for this session? (now: Ask Me — Enter keeps it)');+ expect(entry.indexOf('Ask Me: confirm')).toBeLessThan(entry.indexOf('Allow All: just do it'));+ expect(entry).not.toContain('—:');+ stdin.push('\r'); // keep Ask Me+ await sleep(200);+ expect(screen.text().join('\n')).not.toContain('Permission mode for this session?');emit!({ type: 'thinking', data: {} });await sleep(150);const a = screen.text().join('\n');- expect(a).toContain('working…');- const glyphA = a.match(/([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]) working/)?.[1];+ // The live phase is said once, on the status row under the input; the+ // old "working…" line above the input is gone.+ expect(a).not.toContain('working…');+ expect(a).toMatch(/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] Thinking · \d+s/);+ const glyphA = a.match(/([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]) Thinking/)?.[1];await sleep(350);- const glyphB = screen.text().join('\n').match(/([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]) working/)?.[1];+ const glyphB = screen.text().join('\n').match(/([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]) Thinking/)?.[1];expect(glyphA).toBeDefined();expect(glyphB).not.toBe(glyphA);emit!({ type: 'text_delta', data: { text: 'Here is the reply, still streaming.' } });@@ -51,6 +65,15 @@ describe('attach TUI live rendering', () => {expect(b).toContain('MERCURY:');expect(b).toContain('Here is the reply, still streaming.');expect(b).not.toContain('│ Here');+ // /new re-bound this screen: it follows the new session (status row shows+ // the new alias, the event stream re-subscribes to the new id) and the+ // spinner stops instead of waiting forever on the old session.+ emit!({ type: 'session_switched', data: { id: 't2', shortId: 't2', alias: 'obsidian-cedar', title: 'New session' } });+ await sleep(300);+ const c = screen.text().join('\n');+ expect(c).toContain('obsidian-cedar');+ expect(c).not.toMatch(/Thinking · \d+s/);+ expect(streamedIds).toEqual(['t1', 't2']);app.unmount();}, 20000);});diff --git a/src/ui/attach-pick.test.tsx b/src/ui/attach-pick.test.tsxnew file mode 100644index 00000000..90b2bc05--- /dev/null+++ b/src/ui/attach-pick.test.tsx@@ -0,0 +1,67 @@+process.env.CI = '0';+import { describe, expect, it } from 'vitest';+import React from 'react';+import { EventEmitter } from 'node:events';+import { VtScreen } from './vt-screen.js';+import { LAUNCH_WORDMARK, LAUNCH_WORDMARK_WIDTH, launchPadRows } from './launch-pad.js';++class FakeStdout extends EventEmitter { isTTY = true; constructor(public screen: VtScreen) { super(); } get columns() { return this.screen.columns; } get rows() { return this.screen.rows; } write(c: string) { this.screen.write(c); return true; } }+class FakeStdin extends EventEmitter { isTTY = true; private q: string[] = []; setEncoding() {} setRawMode() {} resume() {} pause() {} ref() {} unref() {} read() { return this.q.shift() ?? null; } push(c: string) { this.q.push(c); this.emit('readable'); } }+const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));++const threads = Array.from({ length: 8 }, (_, i) => ({ id: `t${i}`, shortId: `0000000${i}`, alias: `alias-${i}`, title: `title ${i}` }));++async function renderPick(cols: number, rows: number) {+ const { render } = await import('ink');+ const { AttachTui } = await import('./attach-tui.js');+ const client = {+ getBaseUrl: () => 'http://127.0.0.1:6174',+ listThreads: async () => threads,+ listSkills: async () => [], listBots: async () => [],+ currentModel: async () => ({ name: 'anthropic', model: 'claude-haiku-4-5' }),+ budget: async () => null,+ permissionMode: async () => 'ask-me',+ createThread: async () => ({ id: 'new', shortId: 'new', alias: 'new-one', title: 'New' }),+ streamEvents: async () => { await new Promise(() => {}); },+ send: async () => ({ ok: true }), resolvePermission: async () => true,+ } as never;+ const screen = new VtScreen(cols, rows);+ const app = render(<AttachTui client={client} pid={1} version="1.4.0" onExit={() => {}} />, { stdout: new FakeStdout(screen) as never, stdin: new FakeStdin() as never, exitOnCtrlC: false, patchConsole: false } as never);+ await sleep(400);+ const lines = screen.text();+ app.unmount();+ return lines;+}++/**+ * The session picker is the first thing `mercury` shows. Ink drops rows off+ * the top when the output is taller than the terminal, and what went first+ * was the wordmark. The list is budgeted to the height, and "Start a new+ * session" is the first, default row.+ */+describe('attach TUI session picker', () => {+ it('counts the launch pad rows the way it renders them', () => {+ expect(launchPadRows(100, 'a tip')).toBe(1 + LAUNCH_WORDMARK.length + 1 + 1 + 5 + 1 + 1 + 1 + 2);+ expect(launchPadRows(100, null)).toBe(launchPadRows(100, 'a tip') - 2);+ // Below the wordmark's width the header is two plain lines.+ expect(launchPadRows(LAUNCH_WORDMARK_WIDTH + 3, null)).toBe(2 + 1 + 5 + 1 + 1 + 1);+ });++ it('on a short terminal keeps the wordmark and folds the sessions it cannot show into one line', async () => {+ const lines = await renderPick(100, 24);+ const text = lines.join('\n');+ expect(lines.some((l) => l.includes('█'))).toBe(true); // the wordmark survived+ expect(text).toContain('Your soul-driven AI agent');+ expect(text).toContain('› Start a new session'); // first and selected+ expect(text).toMatch(/… \d+ more · \/sessions in the chat/);+ expect(text).toContain('↑↓ select · Enter attach');+ expect(text.indexOf('Start a new session')).toBeLessThan(text.indexOf('alias-0'));+ });++ it('on a tall terminal lists every session, new-session row first', async () => {+ const text = (await renderPick(100, 45)).join('\n');+ for (const t of threads) expect(text).toContain(`${t.alias} [${t.shortId}]`);+ expect(text).not.toContain('more · /sessions');+ expect(text).toContain('› Start a new session');+ });+});diff --git a/src/ui/attach-tui.tsx b/src/ui/attach-tui.tsxindex 8a47b454..11812ae1 100644--- a/src/ui/attach-tui.tsx+++ b/src/ui/attach-tui.tsx@@ -1,10 +1,10 @@import React from 'react';import { parseAttachHandoff } from './attach-handoff.js';-import { LaunchPad } from './launch-pad.js';+import { LaunchPad, launchPadRows } from './launch-pad.js';import { useTick, spinnerFrame } from './tick-store.js';import { rotateTip } from './tips.js';import type { TuiState } from '../channels/cli.js';-import { Box, Text, Spacer, Static, useApp, useInput } from 'ink';+import { Box, Text, Static, useApp, useInput } from 'ink';import type { AttachClient, AttachEvent, AttachThread } from '../cli/attach.js';import { renderMarkdown } from '../utils/markdown.js';import { useTerminalSize } from './use-terminal-size.js';@@ -89,15 +89,25 @@ const attachItemKey = (message: TranscriptMessage): string => message.id;function AttachMessageBlock({ message }: { message: TranscriptMessage }): React.ReactNode {const isUser = message.role === 'user';+ // A system note (the permission mode on entry) is one dim line, no header.+ if (message.role === 'system') {+ return (+ <Box flexDirection="column" marginBottom={1} paddingX={2} flexShrink={0}>+ {message.content.split('\n').map((line, idx) => (+ <Box key={`${message.id}:${idx}`} flexShrink={0}><Text dimColor>{line.length > 0 ? line : ' '}</Text></Box>+ ))}+ </Box>+ );+ }return (<Box flexDirection="column" marginBottom={1} flexShrink={0}><Box flexShrink={0}>- <Text bold color={isUser ? 'yellow' : message.role === 'system' ? 'gray' : 'cyan'}>- {isUser ? 'YOU' : message.role === 'system' ? '—' : 'MERCURY'}:+ <Text bold color={isUser ? 'yellow' : 'cyan'}>+ {isUser ? 'YOU' : 'MERCURY'}:</Text></Box><Box marginLeft={2} flexDirection="column" flexShrink={0}>- {(isUser || message.role === 'system' ? message.content : renderMarkdown(message.content)).split('\n').map((line, idx) => (+ {(isUser ? message.content : renderMarkdown(message.content)).split('\n').map((line, idx) => (<Box key={`${message.id}:${idx}`} flexShrink={0}><Text>{line.length > 0 ? line : ' '}</Text></Box>@@ -175,7 +185,7 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:React.useEffect(() => {client.listThreads()- .then((list) => { setThreads(list.slice(0, 6)); setThreadsLoaded(true); })+ .then((list) => { setThreads(list.slice(0, 12)); setThreadsLoaded(true); }).catch(() => setThreadsLoaded(true));}, [client]);@@ -215,6 +225,15 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:// Same input width as the main TUI's chat/Code input (App.tsx).const terminalSize = useTerminalSize();const inputWidth = Math.max(12, terminalSize.cols - 4);+ // The pick screen must fit the terminal: pad + 3 header rows + the list+ // (new-session row, sessions, maybe a "… more" row) + the key hint. On a+ // short terminal the tip goes first, then sessions fold into "… N more".+ const pickTip = terminalSize.rows - launchPadRows(terminalSize.cols, launchTip) - 5 >= 3 ? launchTip : null;+ const pickThreads = React.useMemo(() => {+ const free = terminalSize.rows - launchPadRows(terminalSize.cols, pickTip) - 5; // header(3) + new row + hint+ if (threads.length <= free) return threads;+ return threads.slice(0, Math.max(1, free - 1)); // leave a row for "… N more"+ }, [threads, terminalSize.rows, terminalSize.cols, pickTip]);// Live event stream for the attached session.React.useEffect(() => {@@ -239,6 +258,23 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:case 'status':applyStatus(event.data);break;+ case 'session_switched': {+ // /new, /session <ref> or a deleted current session re-bound this+ // screen: follow it, or every reply from now on goes somewhere we+ // are not listening and the spinner never stops.+ const id = String(event.data.id ?? '');+ if (!id || id === thread.id) break;+ setStreaming(false);+ setStreamTail('');+ setSteps([]);+ setThread({+ id,+ shortId: String(event.data.shortId ?? id.slice(0, 8)),+ alias: String(event.data.alias ?? 'session'),+ title: String(event.data.title ?? ''),+ });+ break;+ }case 'provider':// The model that actually answered this turn (fallbacks included).if (event.data.name) setProvider({ name: String(event.data.name), model: String(event.data.model ?? '') });@@ -337,6 +373,7 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:.map((m) => ({ id: m.id, role: m.role as TranscriptMessage['role'], content: m.content })));} else {// "New session": create it server-side so send + SSE target the same id.+ newSessionRef.current = true;const created = await client.createThread();setThread(created? { id: created.id, shortId: created.shortId, alias: created.alias, title: created.title }@@ -360,8 +397,11 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:setStreaming(false);return;}- if (!thread.id && result.sessionId) {- setThread({ ...thread, id: result.sessionId, alias: 'session', title: 'New session' });+ if (result.sessionId && result.sessionId !== thread.id) {+ // The runtime routed this to another session (re-bound meanwhile):+ // follow it so its reply reaches this screen.+ const known = (await client.listThreads().catch(() => [] as ThreadInfo[])).find((t) => t.id === result.sessionId);+ setThread(known ?? { ...thread, id: result.sessionId, shortId: result.sessionId.slice(0, 8), alias: thread.id ? 'session' : 'new session', title: thread.title || 'New session' });}}, [client, thread, onHandoff, exit]);@@ -372,33 +412,51 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:if (active.id === LOCAL_PERMISSION_MODE_PROMPT) {if (value === 'allow-all' || value === 'ask-me') {const ok = await client.setPermissionMode(value);- setNotice(ok- ? `${value === 'allow-all' ? 'Allow All' : 'Ask Me'} saved · change any time with /permissions`- : '⚠ could not save the permission mode — try /permissions');+ // Saved: the status row shows the mode from now on, so no extra line+ // above the input saying the same thing. Only a failure is announced.+ if (ok) setRuntimeStatus((st) => ({ mode: st?.mode ?? 'off', permission: value, desktop: st?.desktop ?? '' }));+ else setNotice('⚠ could not save the permission mode — try /permissions');}return;}await client.resolvePermission(active.id, value);}, [client, prompt]);- // First time in a chat with no saved permission mode (users from before- // the setup wizard asked): ask once, here, and remember it.+ // Entering a chat. A NEW session (or no saved mode yet) asks for the+ // permission mode, the current one listed first so Enter keeps it; a+ // resumed session just says which mode is in effect, in one dim line.const askedModeRef = React.useRef(false);+ const newSessionRef = React.useRef(false);React.useEffect(() => {if (phase !== 'chat' || askedModeRef.current) return;askedModeRef.current = true;// Older runtimes (and test doubles) don't expose it: then nothing to ask.if (typeof client.permissionMode !== 'function') return;client.permissionMode().then((mode) => {- if (mode !== null) return;+ if (mode === undefined) return;+ if (mode !== null) setRuntimeStatus((st) => ({ mode: st?.mode ?? 'off', permission: mode, desktop: st?.desktop ?? '' }));+ if (mode !== null && !newSessionRef.current) {+ setHistory((prev) => [...prev, {+ id: `a_mode_${Date.now().toString(36)}`,+ role: 'system',+ content: mode === 'allow-all'+ ? 'Allow All mode: Mercury acts without asking (blocked commands stay blocked) · /permissions to change'+ : 'Ask Me mode: Mercury asks before writing files or running commands · /permissions to change',+ }]);+ return;+ }+ const options = [+ { value: 'ask-me', label: 'Ask Me: confirm before writing files or running commands' },+ { value: 'allow-all', label: 'Allow All: just do it (blocked commands stay blocked)' },+ ];+ if (mode === 'allow-all') options.reverse();setPrompt((current) => current ?? {id: LOCAL_PERMISSION_MODE_PROMPT,kind: 'choice',- text: 'How should Mercury handle risky actions? (asked once, change with /permissions)',- options: [- { value: 'ask-me', label: 'Ask Me: confirm before writing files or running commands' },- { value: 'allow-all', label: 'Allow All: just do it (blocked commands stay blocked)' },- ],+ text: mode+ ? `Permission mode for this session? (now: ${mode === 'allow-all' ? 'Allow All' : 'Ask Me'} — Enter keeps it)`+ : 'How should Mercury handle risky actions? (change any time with /permissions)',+ options,});setPromptIdx(0);}).catch(() => {});@@ -412,16 +470,14 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:}if (phase === 'pick') {- if (threadsLoaded && threads.length >= 0) {- const rows = threads.length + 1; // threads + "new session"+ if (threadsLoaded) {+ // Row 0 is "Start a new session" (the default), then recent sessions.+ const rows = pickThreads.length + 1;if (key.upArrow) setPickIdx((i) => Math.max(0, i - 1));else if (key.downArrow) setPickIdx((i) => Math.min(rows - 1, i + 1));else if (key.return) {- if (pickIdx < threads.length) {- void startThread(threads[pickIdx]);- } else {- void startThread(null);- }+ if (pickIdx === 0) void startThread(null);+ else void startThread(pickThreads[pickIdx - 1]);} else if (key.escape) {exit();}@@ -540,6 +596,9 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:if (phase === 'pick') {// The same launch pad the main TUI opens with (ADR-024 made attach the// default launch; the first screen must not get plainer for it).+ // Everything below the pad is budgeted to the terminal height: Ink drops+ // rows off the top when the output is taller than the screen, and the+ // wordmark was what went. Sessions beyond the budget fold into one line.const padState = {version: version ?? 'dev',agentName: 'Mercury',@@ -548,9 +607,17 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:web: { enabled: true, port: Number(new URL(client.getBaseUrl()).port) || 6174 },tokenInfo: tokenInfo ? { used: tokenInfo.used, budget: tokenInfo.budget, percentage: tokenInfo.budget > 0 ? Math.round((tokenInfo.used / tokenInfo.budget) * 100) : 0 } : null,} as unknown as TuiState;+ const hidden = threads.length - pickThreads.length;+ const rowFor = (idx: number, label: React.ReactNode, title?: string) => (+ <Box key={`row:${idx}`}>+ <Text color={idx === pickIdx ? 'cyan' : 'gray'}>{idx === pickIdx ? '› ' : ' '}</Text>+ <Text bold={idx === pickIdx} color={idx === pickIdx ? 'white' : 'gray'}>{label}</Text>+ {title ? <Text dimColor> {title}</Text> : null}+ </Box>+ );return (<Box flexDirection="column" paddingX={1}>- <LaunchPad state={padState} cols={terminalSize.cols} showDetails={false} tip={launchTip} />+ <LaunchPad state={padState} cols={terminalSize.cols} showDetails={false} tip={pickTip} /><Text bold color="cyan">⚿ Attached to the running Mercury</Text>{pid != null && <Text dimColor>runtime PID {pid} · Ctrl+C detaches (Mercury keeps running)</Text>}<Text> </Text>@@ -558,19 +625,9 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:<Text dimColor>Loading sessions…</Text>) : ([- ...threads.map((t, idx) => (- <Box key={t.id}>- <Text color={idx === pickIdx ? 'cyan' : 'gray'}>{idx === pickIdx ? '› ' : ' '}</Text>- <Text bold={idx === pickIdx} color={idx === pickIdx ? 'white' : 'gray'}>- {t.alias} [{t.shortId}]- </Text>- <Text dimColor> {t.title}</Text>- </Box>- )),- <Box key="__new__">- <Text color={threads.length === pickIdx ? 'cyan' : 'gray'}>{threads.length === pickIdx ? '› ' : ' '}</Text>- <Text bold={threads.length === pickIdx} color={threads.length === pickIdx ? 'white' : 'gray'}>Start a new session</Text>- </Box>,+ rowFor(0, 'Start a new session'),+ ...pickThreads.map((t, idx) => rowFor(idx + 1, `${t.alias} [${t.shortId}]`, t.title)),+ ...(hidden > 0 ? [<Text key="more" dimColor> … {hidden} more · /sessions in the chat</Text>] : []),])}<Text dimColor>↑↓ select · Enter attach</Text>@@ -578,27 +635,45 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:);}- // Status row under the input (src/ui/status-bar.ts): left = what is- // happening now, right = where you are, fitted to the width in priority- // order so a long model or session name never crowds out the rest.+ // What is happening now (spinner, phase, elapsed) is drawn in the chat,+ // above the input, where the reply will appear. The row under the input+ // (src/ui/status-bar.ts) is status only — where you are — fitted to the+ // width in priority order so a long model or session name never crowds+ // out the rest.const runningStep = [...steps].reverse().find((s) => !s.done);- const left = activityLine({+ const live = activityLine({busy,phase: phaseFromStep(runningStep?.label, streamTail.length > 0),elapsedSec: turnStartedAt.current ? (Date.now() - turnStartedAt.current) / 1000 : 0,spinner: frame,- hints: terminalSize.cols < 70 ? '↵ send · /help' : '↵ send · /help · ctrl+c detach',});+ // Left: which session this is (alias, then its title). Right: mode,+ // budget, model — and Optimus while it is listening or working, which+ // outranks everything: it is the last segment the fit ever drops, and the+ // session shrinks to its alias to make room.const rowCols = Math.max(20, terminalSize.cols - 6);- const split = splitRow(rowCols, left.text);+ const desktopActive = Boolean(runtimeStatus?.desktop);+ const sessionLabel = !thread ? ''+ : desktopActive || !thread.title || thread.title === 'New session' ? `⚿ ${thread.alias}`+ : `⚿ ${thread.alias} · ${thread.title}`;+ // One continuous row, left-aligned: session first, then the status right+ // after it. Two halves pinned to opposite edges left a hole in the middle+ // on any wide terminal. The status gets what it needs first; the session+ // label takes what is left (shortened, or dropped on a very narrow row).+ const split = splitRow(rowCols, sessionLabel, desktopActive ? 0.25 : 0.45);const right = fitSegments(statusSegments({provider: provider && provider.name ? provider : null,permission: runtimeStatus?.permission === 'allow-all' || runtimeStatus?.permission === 'ask-me' ? runtimeStatus.permission : null,tokensPct: tokenInfo && tokenInfo.budget > 0 ? (tokenInfo.used / tokenInfo.budget) * 100 : null,codeMode: runtimeStatus?.mode ?? 'off',desktop: runtimeStatus?.desktop ?? '',- session: thread ? { alias: thread.alias, shortId: thread.shortId } : null,+ session: null, // shown on the left instead}), split.right);+ const rightWidth = right.reduce((n, seg, i) => n + seg.text.length + (i > 0 ? 3 : 0), 0);+ const sessionRoom = rowCols - rightWidth - (right.length > 0 ? 3 : 0);+ const sessionText = sessionRoom >= 6+ ? (sessionLabel.length <= sessionRoom ? sessionLabel : sessionLabel.slice(0, sessionRoom - 1) + '…')+ : '';// The live tail looks exactly like the settled block it becomes: the same// MERCURY header and indent, the same markdown pass (an unclosed fence is// closed for rendering only). It used to be drawn with a cyan "│" bar that@@ -623,19 +698,22 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:</Box></Box>)}- {steps.length > 0 && (+ {/* Finished steps with a ✓, then one live line: spinner, phase and+ elapsed time (cyan, yellow after 30 s, red after 90 s). Said here,+ in the chat, and nowhere else. */}+ {steps.some((step) => step.done) && (<Box flexDirection="column" paddingX={2} flexShrink={0}>- {steps.map((step) => (+ {steps.filter((step) => step.done).map((step) => (<Box key={step.key}>- <Text color={step.done ? 'green' : 'cyan'}>{step.done ? '✓' : frame}</Text>+ <Text color="green">✓</Text><Text dimColor> {step.label}</Text></Box>))}</Box>)}- {streaming && tailLines.length === 0 && steps.length === 0 && (+ {busy && !prompt && (<Box paddingX={2} flexShrink={0}>- <Text color="cyan">{frame}</Text><Text dimColor> working…</Text>+ <Text color={live.color}>{live.text}</Text></Box>)}{prompt && <AttachPromptView prompt={prompt} activeIdx={promptIdx} />}@@ -662,18 +740,17 @@ export function AttachTui({ client, pid, version, onExit, onHandoff }: { client:</Box></Box><Box paddingX={3} flexShrink={0} height={1} overflow="hidden">- <Box width={split.left} flexShrink={0}>- <Text color={left.color} dimColor={left.dim} wrap="truncate-end">{left.text}</Text>- </Box>- <Spacer />- <Box flexShrink={0}>+ {/* One Text so the row can only ever be truncated, never wrapped+ onto a second (hidden) line that cut it off mid-way. */}+ <Text wrap="truncate-end">+ {sessionText && <Text color="blue">{sessionText}</Text>}{right.map((seg, idx) => (<React.Fragment key={`${seg.priority}:${idx}`}>- {idx > 0 && <Text color="gray"> · </Text>}+ {(idx > 0 || sessionText) && <Text color="gray"> · </Text>}<Text color={seg.color}>{seg.text}</Text></React.Fragment>))}- </Box>+ </Text></Box></Box>);diff --git a/src/ui/launch-pad.tsx b/src/ui/launch-pad.tsxindex 7b1d74bc..14e93dfe 100644--- a/src/ui/launch-pad.tsx+++ b/src/ui/launch-pad.tsx@@ -100,6 +100,19 @@ export interface LaunchPadProps {tip?: string | null;}+/**+ * How many terminal rows the pad takes (details hidden), so a screen that+ * stacks something under it can fit the whole thing: Ink drops rows off the+ * TOP when the output is taller than the terminal, and the first casualty+ * was the wordmark. Mirrors the render below row for row.+ */+export function launchPadRows(cols: number, tip?: string | null): number {+ const showWordmark = cols >= LAUNCH_WORDMARK_WIDTH + 4;+ const header = showWordmark ? 1 + LAUNCH_WORDMARK.length + 1 : 2; // paddingTop + mark + tagline | mark line + tagline+ const checks = 5; // provider, skills, web, budget, workspace+ return header + 1 + checks + 1 + 1 + 1 + (tip ? 2 : 0); // blank, checks, blank, "Type to start", "/code … Tab", tip pair+}+export function LaunchPad({ state, cols, showDetails, tip }: LaunchPadProps) {// The wordmark needs its width plus the side padding; below that the// header is a single text line (Termux portrait, split panes).diff --git a/src/ui/status-bar.test.ts b/src/ui/status-bar.test.tsindex 1f331492..b8144810 100644--- a/src/ui/status-bar.test.ts+++ b/src/ui/status-bar.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest';-import { SEPARATOR, activityLine, fitSegments, phaseFromStep, shortModel, shortSession, splitRow, statusSegments } from './status-bar.js';+import { SEPARATOR, activityLine, budgetBar, fitSegments, phaseFromStep, shortModel, shortSession, splitRow, statusSegments } from './status-bar.js';const row = (segs: Array<{ text: string }>) => segs.map((s) => s.text).join(SEPARATOR);@@ -28,22 +28,39 @@ describe('status bar: fitting the right half', () => {session: { alias: 'quiet-harbour', shortId: 'ab12' },};- it('at full width shows everything, permission first and the session last', () => {+ it('at full width shows everything: permission, the budget meter, the model, the session last', () => {const segs = fitSegments(statusSegments(inputs), 120);- expect(row(segs)).toBe('Ask Me · mercuryCloud · minimax-m3.1-flash:free · ⚡ 12% today · quiet-harbour');+ expect(row(segs)).toBe('Ask Me · ⚡ █░░░░░░░ 12% · minimax-m3.1-flash:free · quiet-harbour');});- it('when narrow, compacts the least important first, then drops the session, never the permission mode', () => {- const at60 = row(fitSegments(statusSegments(inputs), 44));- expect(at60).toBe('Ask · minimax-m3.1-flash · ⚡12% · quiet-har…');- const at32 = row(fitSegments(statusSegments(inputs), 32));- expect(at32).toBe('Ask · minimax-m3.1-flash · ⚡12%');- expect(row(fitSegments(statusSegments(inputs), 30))).toBe('Ask · minimax-m3.1-flash');- const at12 = row(fitSegments(statusSegments(inputs), 12));- expect(at12).toBe('Ask · ⚡12%');+ it('when narrow, compacts the least important first, then drops the session and the model; permission and budget stay', () => {+ expect(row(fitSegments(statusSegments(inputs), 60))).toBe('Ask Me · ⚡ █░░░░░░░ 12% · minimax-m3.1-flash · quiet-har…');+ expect(row(fitSegments(statusSegments(inputs), 44))).toBe('Ask · ⚡12% · minimax-m3.1-flash · quiet-har…');+ expect(row(fitSegments(statusSegments(inputs), 32))).toBe('Ask · ⚡12% · minimax-m3.1-flash');+ expect(row(fitSegments(statusSegments(inputs), 12))).toBe('Ask · ⚡12%');expect(row(fitSegments(statusSegments(inputs), 4))).toBe('Ask');});+ it('the budget meter fills with use: green, yellow from 70 %, red from 90 %', () => {+ expect(budgetBar(0)).toBe('░░░░░░░░');+ expect(budgetBar(50)).toBe('████░░░░');+ expect(budgetBar(100)).toBe('████████');+ expect(budgetBar(140)).toBe('████████');+ const seg = (pct: number) => statusSegments({ tokensPct: pct })[0];+ expect(seg(12)).toMatchObject({ text: '⚡ █░░░░░░░ 12%', compact: '⚡12%', color: 'green' });+ expect(seg(75)).toMatchObject({ text: '⚡ ██████░░ 75%', color: 'yellow' });+ expect(seg(95)).toMatchObject({ text: '⚡ ████████ 95%', color: 'red' });+ // Unknown budget: no meter rather than a wrong one.+ expect(statusSegments({ tokensPct: null })).toEqual([]);+ });++ it('Optimus activity outranks everything: when the row is overloaded it is the last thing kept', () => {+ const busy = { ...inputs, desktop: '🎙 Optimus listening' };+ expect(row(fitSegments(statusSegments(busy), 30))).toBe('🎙 Optimus listening · Ask');+ expect(row(fitSegments(statusSegments(busy), 20))).toBe('🎙 Optimus listening');+ expect(row(fitSegments(statusSegments({ ...busy, desktop: '🖥 Optimus working: opening Finder' }), 40))).toBe('🖥 Optimus working: opening Finder · Ask');+ });+it('a long model never pushes tokens or permission off the row', () => {const segs = fitSegments(statusSegments({ ...inputs, provider: { name: 'aimlapi', model: 'anthropic/claude-sonnet-4.6-extended-thinking-preview-2026' } }), 40);const text = row(segs);@@ -54,28 +71,24 @@ describe('status bar: fitting the right half', () => {it('live things come first: Optimus, then Allow All in yellow, Code mode and an update', () => {const segs = fitSegments(statusSegments({ ...inputs, permission: 'allow-all', desktop: '🎙 Optimus listening', codeMode: 'auto', updateAvailable: 'v1.5.0' }), 200);- expect(row(segs)).toBe('🎙 Optimus listening · Allow All · mercuryCloud · minimax-m3.1-flash:free · ⚡ 12% today · CODE AUTO · ⬆ v1.5.0 · quiet-harbour');+ expect(row(segs)).toBe('🎙 Optimus listening · Allow All · ⚡ █░░░░░░░ 12% · minimax-m3.1-flash:free · CODE AUTO · ⬆ v1.5.0 · quiet-harbour');expect(segs[1].color).toBe('yellow');});-- it('token colour follows the budget', () => {- expect(statusSegments({ tokensPct: 95 })[0].color).toBe('red');- expect(statusSegments({ tokensPct: 75 })[0].color).toBe('yellow');- expect(statusSegments({ tokensPct: 10 })[0].color).toBe('cyan');- });});describe('status bar: the left half', () => {- it('shows the phase and elapsed time while busy, a notice above all, and hints when idle', () => {+ it('shows the phase and elapsed time while busy, a notice above all, and nothing when idle', () => {expect(activityLine({ busy: true, phase: 'run_command', elapsedSec: 7, spinner: '⠙' })).toEqual({ text: '⠙ run_command · 7s', color: 'cyan', dim: false });expect(activityLine({ busy: true, elapsedSec: 95 }).text).toBe('⠋ Thinking · 1m 35s');expect(activityLine({ busy: true, elapsedSec: 95 }).color).toBe('red');expect(activityLine({ busy: true, notice: '⚠ send failed' }).text).toBe('⚠ send failed');- expect(activityLine({ busy: false, hints: '↵ send · /help' })).toEqual({ text: '↵ send · /help', color: 'gray', dim: true });+ // No key hints: Enter sends, /help lists commands, and the row is for status.+ expect(activityLine({ busy: false }).text).toBe('');});- it('splits the row so the left never takes more than its share', () => {- expect(splitRow(80, '↵ send · /help')).toEqual({ left: 14, right: 65 });+ it('splits the row so the left never takes more than its share, and gives it all to the right when idle', () => {+ expect(splitRow(80, '⠙ Thinking · 4s')).toEqual({ left: 15, right: 64 });+ expect(splitRow(80, '')).toEqual({ left: 0, right: 79 });expect(splitRow(40, 'x'.repeat(60))).toEqual({ left: 22, right: 17 });});diff --git a/src/ui/status-bar.ts b/src/ui/status-bar.tsindex 30591715..fcddd532 100644--- a/src/ui/status-bar.ts+++ b/src/ui/status-bar.ts@@ -3,10 +3,10 @@* foreground TUI share it). Two halves:** left — what is happening now: a spinner + phase + elapsed while a turn- * runs, a notice when there is one, otherwise two short key hints.- * right — where you are: permission mode, model, today's token use, Code- * mode, Optimus, an update — each in priority order with a compact- * form, and the session alias last. Segments that do not fit are+ * runs, a notice when there is one, otherwise nothing.+ * right — where you are: permission mode, today's budget meter (green →+ * yellow → red), model, Code mode, Optimus, an update — each in+ * priority order with a compact form, and the session alias last. Segments that do not fit are* dropped from the lowest priority up; nothing is ever cut* mid-word, and a long model or session name never pushes the* useful parts off the row.@@ -73,29 +73,35 @@ function fit(text: string, max: number): string {return text.slice(0, max - 1).replace(/[-_ .:]+$/, '') + '…';}+/** Budget colour, as the completion footer has always shown it: green, then yellow from 70 %, red from 90 %. */export function tokenColor(pct: number): string {- return pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'cyan';+ return pct >= 90 ? 'red' : pct >= 70 ? 'yellow' : 'green';}-/** The right-hand segments in priority order (not yet fitted). */+/** A small meter for today's budget: `█░░░░░░░` at 12 %. */+export function budgetBar(pct: number, cells = 8): string {+ const filled = Math.round((Math.max(0, Math.min(100, pct)) / 100) * cells);+ return '█'.repeat(filled) + '░'.repeat(cells - filled);+}++/** The right-hand segments in priority order (not yet fitted): desktop 0, permission 1, budget 2, model 3, Code 4, update 5, extras, session 9. */export function statusSegments(i: StatusInputs): StatusSegment[] {const out: StatusSegment[] = [];if (i.desktop) out.push({ text: i.desktop, color: 'yellow', priority: 0 });if (i.permission === 'allow-all') out.push({ text: 'Allow All', compact: 'Allow', color: 'yellow', priority: 1 });else if (i.permission === 'ask-me') out.push({ text: 'Ask Me', compact: 'Ask', color: 'gray', priority: 1 });+ // The model only: the provider name made the row too long, and the model+ // name already says who serves it (claude-…, gpt-…, minimax-…).if (i.provider?.model || i.provider?.name) {const model = i.provider.model ? shortModel(i.provider.model) : '';const compact = i.provider.model ? shortModel(i.provider.model, { compact: true }) : i.provider.name;- out.push({- text: model ? `${i.provider.name} · ${model}` : i.provider.name,- compact,- color: 'magenta',- priority: 2,- });+ out.push({ text: model || i.provider.name, compact, color: 'magenta', priority: 3 });}+ // Today's budget outranks the model: the owner asked for the meter to stay+ // on the row, and the model is one /model away.if (typeof i.tokensPct === 'number' && Number.isFinite(i.tokensPct)) {const pct = Math.max(0, Math.min(999, Math.round(i.tokensPct)));- out.push({ text: `⚡ ${pct}% today`, compact: `⚡${pct}%`, color: tokenColor(pct), priority: 3 });+ out.push({ text: `⚡ ${budgetBar(pct)} ${pct}%`, compact: `⚡${pct}%`, color: tokenColor(pct), priority: 2 });}if (i.codeMode && i.codeMode !== 'off') out.push({ text: `CODE ${i.codeMode.toUpperCase()}`, compact: 'CODE', color: 'cyan', priority: 4 });if (i.updateAvailable) out.push({ text: `⬆ v${i.updateAvailable.replace(/^v/, '')}`, compact: '⬆', color: 'green', priority: 5 });@@ -152,8 +158,6 @@ export interface ActivityInputs {notice?: string | null;/** The spinner glyph for this tick. */spinner?: string;- /** Idle hints, already short ("↵ send · /help"). */- hints?: string;}export interface ActivityLine {@@ -162,7 +166,11 @@ export interface ActivityLine {dim: boolean;}-/** The left half: notice > live phase + elapsed > hints. */+/**+ * The left half: notice > live phase + elapsed > nothing. Idle, the row says+ * nothing on the left: Enter sends and /help lists the commands, and a row of+ * key hints under every message was noise people stopped reading.+ */export function activityLine(i: ActivityInputs): ActivityLine {if (i.notice) return { text: i.notice, color: 'yellow', dim: false };if (i.busy) {@@ -172,7 +180,7 @@ export function activityLine(i: ActivityInputs): ActivityLine {const tone = secs >= 90 ? 'red' : secs >= 30 ? 'yellow' : 'cyan';return { text: `${i.spinner ?? '⠋'} ${phase} · ${time}`, color: tone, dim: false };}- return { text: i.hints ?? '', color: 'gray', dim: true };+ return { text: '', color: 'gray', dim: true };}/**diff --git a/src/web/api/chat-answer-route.test.ts b/src/web/api/chat-answer-route.test.tsnew file mode 100644index 00000000..68e8e5e4--- /dev/null+++ b/src/web/api/chat-answer-route.test.ts@@ -0,0 +1,82 @@+import { describe, expect, it, vi } from 'vitest';++// Fixed config path: point MERCURY_HOME at a temp dir before importing routes.+await vi.hoisted(async () => {+ const fs = await import('node:fs');+ const os = await import('node:os');+ const path = await import('node:path');+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'mercury-answer-route-'));+ fs.writeFileSync(path.join(dir, 'mercury.yaml'), 'identity:\n owner: Test\n');+ process.env.MERCURY_HOME = dir;+});++import chat, { setWebChannel } from './chat.js';+import { WebChannel } from '../../channels/web.js';++function answer(id: string, action: string) {+ return chat.request(`http://127.0.0.1/api/chat/permission/${encodeURIComponent(id)}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ action }),+ });+}++function channelWithScreen(): { channel: WebChannel; promptIds: string[] } {+ const channel = new WebChannel('Mercury');+ const promptIds: string[] = [];+ channel.addSSEClient({+ enqueue(value: Uint8Array) {+ const text = new TextDecoder().decode(value);+ const id = /"id":"(choice_[^"]+|perm[^"]*)"/.exec(text)?.[1];+ if (id) promptIds.push(id);+ },+ close() {},+ } as unknown as ReadableStreamDefaultController, 'sess-1');+ setWebChannel(channel);+ return { channel, promptIds };+}++const tick = () => new Promise((r) => setTimeout(r, 0));++/**+ * The attached terminal answers every prompt through this one endpoint. It+ * used to resolve permission approvals only, so a choice picker (/model,+ * /permissions, ask_user) answered there never reached the runtime and the+ * screen sat on "Thinking" until the 2-minute timeout.+ */+describe('POST /api/chat/permission/:id', () => {+ it('answers a choice picker raised for an attached screen', async () => {+ const { channel, promptIds } = channelWithScreen();+ const picked = channel.presentChoicePrompt('Permission mode?', [+ { value: 'ask-me', label: 'Ask Me' },+ { value: 'allow-all', label: 'Allow All' },+ ], 'sess-1');+ await tick();+ expect(promptIds).toHaveLength(1);+ const res = await answer(promptIds[0], 'allow-all');+ expect(res.status).toBe(200);+ await expect(picked).resolves.toBe('allow-all');+ });++ it('an empty answer is Esc: the picker is cancelled, not left hanging', async () => {+ const { channel, promptIds } = channelWithScreen();+ const picked = channel.presentChoicePrompt('Switch model?', [{ value: '0', label: 'a' }, { value: '1', label: 'b' }], 'sess-1');+ await tick();+ const res = await answer(promptIds[0], '');+ expect(res.status).toBe(200);+ await expect(picked).resolves.toBe('');+ });++ it('still answers a permission approval, and refuses an unknown id', async () => {+ const { channel } = channelWithScreen();+ const events: string[] = [];+ channel.addSSEClient({ enqueue(v: Uint8Array) { events.push(new TextDecoder().decode(v)); }, close() {} } as unknown as ReadableStreamDefaultController, 'sess-1');+ const approved = channel.askPermission('Write file?', 'sess-1');+ await tick();+ const id = /"id":"([^"]+)"/.exec(events.find((e) => e.includes('permission_request')) ?? '')?.[1];+ expect(id).toBeTruthy();+ expect((await answer(id!, 'yes')).status).toBe(200);+ await expect(approved).resolves.toBe('yes');+ expect((await answer('nope', 'yes')).status).toBe(404);+ });+});diff --git a/src/web/api/chat.ts b/src/web/api/chat.tsindex 09bdd136..b7a1eec0 100644--- a/src/web/api/chat.ts+++ b/src/web/api/chat.ts@@ -218,14 +218,22 @@ chat.post('/api/chat/permission/:id', async (c) => {}const permId = c.req.param('id');- const body = await c.req.json<{ action: string; targetId?: string }>();+ const body = await c.req.json<{ action?: string; targetId?: string }>().catch(() => ({} as { action?: string; targetId?: string }));+ // One endpoint answers every prompt a screen shows: permission/continue/+ // mode approvals AND choice pickers (/model, /permissions, ask_user). It+ // used to resolve approvals only, so a picker answered in the attached+ // terminal never reached the runtime: the command hung until the 2-minute+ // timeout and the screen showed "Thinking" the whole time. An empty action+ // is Esc: the picker is cancelled (its caller treats that as "no change").if (!body.action) {+ if (webChannel.cancelInteraction(permId, body.targetId)) return c.json({ resolved: true, cancelled: true });return c.json({ error: 'Action required' }, 400);}// Prompts are bound to the chat session that raised them; without the// targetId the session check in resolveInteraction always fails.- const resolved = webChannel.resolveApproval(permId, body.action, body.targetId);+ const resolved = webChannel.resolveApproval(permId, body.action, body.targetId)+ || webChannel.resolveChoice(permId, body.action, body.targetId);if (resolved) {return c.json({ resolved: true });}