Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix: short session titles that name the topic
Salman Qureshicc6f2cdb665c
diff --git a/src/core/agent.ts b/src/core/agent.tsindex dd425003..8178c7d7 100644--- a/src/core/agent.ts+++ b/src/core/agent.ts@@ -46,7 +46,7 @@ import type { ArrowSelectOption } from '../utils/arrow-select.js';import { setAskUserHandler } from '../capabilities/interaction/ask-user.js';import { classifyResearchIntent } from './research-intent.js';import type { SpotifyClient } from '../spotify/client.js';-import { normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';+import { fallbackSessionTitle, isThinOpening, normalizeGeneratedSessionTitle, SessionResolutionError, type SessionRepository } from '../sessions/index.js';import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../spotify/ui.js';import { getCloudTokenStore } from '../cloud/token-store.js';import {@@ -5345,16 +5345,68 @@ Is this productive iteration or a stuck loop?`,if (!this.generateTitle || this.titleGenerationInFlight.has(sessionId)) return;const session = this.sessions.get(sessionId);const exchange = session.messages.filter((message) => message.kind === 'message' && (message.role === 'user' || message.role === 'assistant'));- if (session.titleSource !== 'fallback' || exchange.length !== 2 || exchange[0].role !== 'user' || exchange[1].role !== 'assistant') return;+ if (session.titleSource !== 'fallback' || exchange[0]?.role !== 'user') return;+ // Name it after the first exchange, unless that opened with only "hi":+ // then after the second, when there is something to name.+ const at = exchange.length === 2 && !isThinOpening(exchange[0].content) ? 0 : exchange.length === 4 ? 2 : -1;+ if (at < 0 || exchange[at].role !== 'user' || exchange[at + 1].role !== 'assistant') return;+ const userText = at === 0 ? exchange[0].content : `${exchange[0].content}\n${exchange[2].content}`;this.titleGenerationInFlight.add(sessionId);const timer = setTimeout(() => {- void this.generateSessionTitle(sessionId, exchange[0].content, exchange[1].content, providerName).finally(() => {+ void this.generateSessionTitle(sessionId, userText, exchange[at + 1].content, providerName).finally(() => {this.titleGenerationInFlight.delete(sessionId);});}, 0);timer.unref?.();}+ /**+ * Fix titles made before titles were checked: a generated title that is+ * really a reply ("I appreciate your request, but…") is written again,+ * and fallback titles are re-cut from the first message. Renames don't+ * count as activity, so nothing moves in the list. Runs once at start-up;+ * fixed titles pass the check, so the next start finds nothing to do.+ */+ async repairSessionTitles(limit = 200): Promise<{ regenerated: number; recut: number }> {+ let regenerated = 0;+ let recut = 0;+ for (const session of this.sessions.list()) {+ const firstUser = session.messages.find((m) => m.role === 'user' && (m.kind ?? 'message') === 'message');+ if (!firstUser) continue;+ if (session.titleSource === 'fallback') {+ const title = fallbackSessionTitle(firstUser.content);+ if (title !== session.title) { this.sessions.updateTitle(session.id, title, 'fallback', { touch: false }); recut++; }+ continue;+ }+ if (session.titleSource !== 'generated') continue;+ const exchange = session.messages.filter((m) => (m.kind ?? 'message') === 'message' && (m.role === 'user' || m.role === 'assistant'));+ const thin = isThinOpening(firstUser.content);+ const tidy = normalizeGeneratedSessionTitle(session.title);+ if (tidy && !(thin && /greeting|check-in|hello/i.test(tidy))) {+ // A good title with wrappers left on ("# Heading"): tidy it, no model call.+ if (tidy !== session.title) { this.sessions.updateTitle(session.id, tidy, 'generated', { touch: false }); recut++; }+ continue;+ }+ if (regenerated >= limit) continue;+ // A chat that opened with "hi" is named after what came next.+ const users = exchange.filter((m) => m.role === 'user');+ const userText = thin && users[1] ? `${firstUser.content}\n${users[1].content}` : firstUser.content;+ const replyAfter = thin && users[1] ? users[1] : firstUser;+ const reply = exchange.find((m) => m.role === 'assistant' && m.sequence > replyAfter.sequence);+ let title: string | null = null;+ if (this.generateTitle && reply) {+ try {+ title = normalizeGeneratedSessionTitle(await this.generateTitle({ userMessage: userText, assistantMessage: reply.content, providerName: '' }));+ } catch { /* fall back below */ }+ }+ if (title) this.sessions.updateTitle(session.id, title, 'generated', { touch: false });+ else this.sessions.updateTitle(session.id, fallbackSessionTitle(firstUser.content), 'fallback', { touch: false });+ regenerated++;+ }+ if (regenerated || recut) logger.info({ regenerated, recut }, 'Repaired session titles');+ return { regenerated, recut };+ }+private async generateSessionTitle(sessionId: string, userMessage: string, assistantMessage: string, providerName: string): Promise<void> {try {const rawTitle = await this.generateTitle!({ userMessage, assistantMessage, providerName });diff --git a/src/index.ts b/src/index.tsindex 0144b41c..384dce67 100644--- a/src/index.ts+++ b/src/index.ts@@ -78,6 +78,7 @@ import { SignalChannel } from './channels/signal.js';import { DiscordChannel } from './channels/discord.js';import { WebChannel } from './channels/web.js';import { TokenBudget } from './utils/tokens.js';+import { TITLE_SYSTEM_PROMPT, titlePrompt } from './sessions/title.js';import { CapabilityRegistry } from './capabilities/registry.js';import { SkillLoader } from './skills/loader.js';import { registerSkillsCommand } from './skills/cli.js';@@ -2700,10 +2701,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler, sessions,async ({ userMessage, assistantMessage, providerName }) => {const provider = providers.get(providerName) ?? providers.getDefault();- const result = await provider.generateText(- `User: ${userMessage.slice(0, 1500)}\nAssistant: ${assistantMessage.slice(0, 1500)}`,- 'Create a concise 3-7 word title for this conversation. Return only the title with no quotes, markdown, prefix, or punctuation.',- );+ const result = await provider.generateText(titlePrompt(userMessage, assistantMessage), TITLE_SYSTEM_PROMPT);return result.text;},);@@ -3510,6 +3508,11 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {setWebStop(() => agent.stopAllWork('stopped'));setWebSessionBusy((sessionId) => agent.isBusyWith(sessionId));setWebBudgetControls({ config: () => config, tokens: () => tokenBudget, saver: () => agent.saverMode });+ // Titles made before they were checked: fix them once, quietly, after start-up.+ if (!daemonOwnsRuntime) {+ const titleRepair = setTimeout(() => { void agent.repairSessionTitles().catch(() => {}); }, 20_000);+ titleRepair.unref?.();+ }setWebCurrentProvider(() => agent.getCurrentProvider());// Live bottom bar for attached terminals and the dashboard: one snapshot,// pushed on every model switch and checked every 2 s for anything else.diff --git a/src/sessions/index.ts b/src/sessions/index.tsindex 64397c27..832a52fa 100644--- a/src/sessions/index.ts+++ b/src/sessions/index.ts@@ -2,7 +2,7 @@ export { SessionRepository, SessionResolutionError } from './repository.js';export { CloudSessionSynchronizer, buildSessionSyncBatches } from './cloud-sync.js';export { buildConversationHistoryPayload } from './live-history.js';export type { ConversationHistoryRequest } from './live-history.js';-export { normalizeGeneratedSessionTitle } from './title.js';+export { fallbackSessionTitle, isThinOpening, normalizeGeneratedSessionTitle } from './title.js';export type { SessionSyncBatch, SessionSyncConfig } from './cloud-sync.js';export type {AppendSessionMessageInput,diff --git a/src/sessions/repository.test.ts b/src/sessions/repository.test.tsindex bbfaa680..22124b3b 100644--- a/src/sessions/repository.test.ts+++ b/src/sessions/repository.test.ts@@ -174,3 +174,17 @@ describe('SessionRepository', () => {expect(readdirSync(short)).toContain('cli.json');});});++describe('SessionRepository.updateTitle without touching', () => {+ it('renames without moving the session in the list', () => {+ const repo = new SessionRepository({ rootDir: mkdtempSync(join(tmpdir(), 'mercury-retitle-')), autoMigrate: false });+ const older = repo.create({ title: 'Older' });+ repo.appendMessage(older.id, { role: 'user', content: 'a', timestamp: 1_000 });+ const newer = repo.create({ title: 'Newer' });+ repo.appendMessage(newer.id, { role: 'user', content: 'b' });+ const before = repo.get(older.id).updatedAt;+ repo.updateTitle(older.id, 'Fixed Title', 'generated', { touch: false });+ expect(repo.get(older.id)).toMatchObject({ title: 'Fixed Title', titleSource: 'generated', updatedAt: before });+ expect(repo.list().map((s) => s.id)).toEqual([newer.id, older.id]);+ });+});diff --git a/src/sessions/repository.ts b/src/sessions/repository.tsindex a458ee85..f5a9fce5 100644--- a/src/sessions/repository.ts+++ b/src/sessions/repository.ts@@ -3,6 +3,7 @@ import { basename, join } from 'node:path';import { randomUUID } from 'node:crypto';import { getMercuryHome, getMemoryDir } from '../utils/config.js';import type { ChannelType } from '../types/channel.js';+import { fallbackSessionTitle } from './title.js';import type { AppendSessionMessageInput, CreateSessionInput, Session, SessionBinding, SessionMessage } from './types.js';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;@@ -236,7 +237,11 @@ export class SessionRepository {return removed;}- updateTitle(ref: string, title: string, titleSource: Session['titleSource'] = 'user'): Session {+ /**+ * Rename a session. `touch: false` renames without counting as activity,+ * so the session keeps its place in the list (used when repairing titles).+ */+ updateTitle(ref: string, title: string, titleSource: Session['titleSource'] = 'user', options: { touch?: boolean } = {}): Session {const normalized = title.replace(/\s+/g, ' ').trim();if (!normalized) throw new Error('Session title is required');if (normalized.length > 120) throw new Error('Session title must be 120 characters or fewer');@@ -244,7 +249,14 @@ export class SessionRepository {if (session.title === normalized && session.titleSource === titleSource) return session;session.title = normalized;session.titleSource = titleSource;- this.touchAndWrite(session);+ if (options.touch === false) {+ session.revision++;+ this.writeSession(session);+ const index = this.index.sessions.findIndex((entry) => entry.id === session.id);+ if (index >= 0) this.index.sessions[index] = this.toIndexEntry(session);+ } else {+ this.touchAndWrite(session);+ }this.writeIndex();this.notifyMutation();return this.get(session.id);@@ -423,8 +435,7 @@ export class SessionRepository {}private fallbackTitle(content: string): string {- const normalized = content.replace(/\s+/g, ' ').trim();- return normalized.length > 60 ? `${normalized.slice(0, 57)}...` : normalized || 'New session';+ return fallbackSessionTitle(content);}private touchAndWrite(session: Session, timestamp = Date.now()): void {diff --git a/src/sessions/title.test.ts b/src/sessions/title.test.tsindex 7adf6d75..c667eb00 100644--- a/src/sessions/title.test.ts+++ b/src/sessions/title.test.ts@@ -1,16 +1,63 @@import { describe, expect, it } from 'vitest';-import { normalizeGeneratedSessionTitle } from './title.js';+import { fallbackSessionTitle, isThinOpening, normalizeGeneratedSessionTitle, titlePrompt } from './title.js';describe('normalizeGeneratedSessionTitle', () => {- it('removes wrappers and keeps a concise single-line title', () => {+ it('removes wrappers and keeps a short single-line title', () => {expect(normalizeGeneratedSessionTitle(' Title: “Canonical Session Sync”\nExtra explanation')).toBe('Canonical Session Sync');- expect(normalizeGeneratedSessionTitle('one two')).toBeNull();+ expect(normalizeGeneratedSessionTitle('**Hyperframes Skill Install.**')).toBe('Hyperframes Skill Install');+ expect(normalizeGeneratedSessionTitle('Budgets')).toBe('Budgets');});- it('limits generated titles to seven words and 80 characters', () => {- const title = normalizeGeneratedSessionTitle('extraordinary synchronization architecture handles canonical conversation histories safely today');- expect(title).toBe('extraordinary synchronization architecture handles canonical conversation');- expect(title!.length).toBeLessThanOrEqual(80);- expect(title!.split(' ').length).toBeLessThanOrEqual(7);+ it('keeps titles to a few words and a sidebar width', () => {+ const title = normalizeGeneratedSessionTitle('Extraordinary Synchronization Architecture Handles Canonical Histories');+ expect(title!.split(' ').length).toBeLessThanOrEqual(5);+ expect(title!.length).toBeLessThanOrEqual(40);+ });++ // Real titles the old prompt produced: replies and refusals, not titles.+ it.each([+ 'I appreciate you sharing that GitHub link,',+ 'I appreciate your request, but I need',+ "I'd be happy to help! However, I",+ "I don't have access to your personal",+ 'A concise 3-7 word title for this',+ 'Sure! Here is a title: Budget Review',+ 'This is a conversation where the user asks Mercury to install a skill from GitHub and it explains',+ ])('rejects a reply posing as a title: %s', (raw) => {+ expect(normalizeGeneratedSessionTitle(raw)).toBeNull();+ });+});++describe('fallbackSessionTitle', () => {+ it('drops greetings, asks and links', () => {+ expect(fallbackSessionTitle('Install this skill https://github.com/heygen-com/hyperframes/tree/main/.claude/skills')).toBe('Install this skill');+ expect(fallbackSessionTitle('hey can you find best videos and their scripts for us to make a video')).toBe('Find best videos and their');+ expect(fallbackSessionTitle('Okay, I want you to check the budget tracker. It is off.')).toBe('Check the budget tracker');+ });++ it('skips the note a voice question carries, and markdown', () => {+ expect(fallbackSessionTitle("[Voice, on the owner's own computer: they asked this out loud.] What's the weather in Lahore?")).toBe("What's the weather in Lahore");+ expect(fallbackSessionTitle('# COSMIC LEADER - Official Campaign Video')).toBe('COSMIC LEADER - Official Campaign');+ });++ it('never comes back empty', () => {+ expect(fallbackSessionTitle('hi')).toBe('New chat');+ expect(fallbackSessionTitle('https://example.com')).toBe('New chat');+ });+});++describe('isThinOpening', () => {+ it('spots a greeting with nothing to name yet', () => {+ expect(isThinOpening('hi')).toBe(true);+ expect(isThinOpening('Hey Mercury!')).toBe(true);+ expect(isThinOpening('install this skill')).toBe(false);+ });+});++describe('titlePrompt', () => {+ it('fences the exchange so the model titles it instead of joining it', () => {+ const prompt = titlePrompt('[Voice, a note.] Book a flight to Lisbon', 'Done.');+ expect(prompt).toContain('<user>\nBook a flight to Lisbon\n</user>');+ expect(prompt).not.toMatch(/^User:/m);});});diff --git a/src/sessions/title.ts b/src/sessions/title.tsindex 26deb21d..54de5616 100644--- a/src/sessions/title.ts+++ b/src/sessions/title.ts@@ -1,18 +1,95 @@+/**+ * Session titles: a few words in a narrow sidebar, naming what the+ * conversation is about ("Hyperframes Skill Install", "Q3 Budget Review").+ *+ * The model writes one after the first real exchange; until then (or if it+ * can't), the title comes from the owner's first message with the filler,+ * links and greetings taken out.+ */++export const TITLE_MAX_WORDS = 5;+export const TITLE_MAX_CHARS = 40;++/** System prompt for the title call. */+export const TITLE_SYSTEM_PROMPT = [+ 'You name conversations for a sidebar list. You never answer or continue the conversation.',+ 'Reply with a 2-4 word title naming its topic: a noun phrase in Title Case, like "Hyperframes Skill Install", "Q3 Budget Review" or "Flight to Lisbon".',+ 'Use the language the user wrote in. No quotes, no punctuation at the end, no "Chat about", no explanation. Only the title.',+].join('\n');++/** The title call's prompt: the exchange, fenced so it reads as material, not as a chat to join. */+export function titlePrompt(userMessage: string, assistantMessage: string): string {+ return [+ 'Title this conversation.',+ '',+ '<user>',+ userMessage.replace(/^\s*\[[^\]]*\]\s*/, '').slice(0, 1500),+ '</user>',+ '<assistant>',+ assistantMessage.slice(0, 600),+ '</assistant>',+ '',+ 'Title (2-4 words):',+ ].join('\n');+}++/** Openings of a reply or a request, never of a title. */+const CHATTY = /^(?:a concise|concise|title|i|i'm|i've|i'll|i'd|im|sure|here|here's|hi|hello|hey|thanks|thank|okay|ok|of course|certainly|great|absolutely|yes|no|sorry|as an|let me|you|you're|this conversation|the user|conversation|chat)\b/i;++/**+ * The model's answer as a title, or null when it isn't one (a sentence from+ * a reply, an empty line, a paragraph).+ */export function normalizeGeneratedSessionTitle(raw: string): string | null {- const firstLine = raw.split(/\r?\n/, 1)[0]- .replace(/^\s*(?:title\s*:\s*)?/i, '')- .replace(/^[`*_"'“”‘’]+|[`*_"'“”‘’]+$/g, '')- .replace(/[.!?,;:]+$/g, '')+ const firstLine = (raw.split(/\r?\n/).find((l) => l.trim()) ?? '')+ .replace(/^\s*(?:title\s*[:\-–]\s*)/i, '')+ .replace(/^[`*_#"'“”‘’\s]+|[`*_"'“”‘’\s]+$/g, '')+ .replace(/[.!?;:]+$/g, '')+ .replace(/\s+/g, ' ')+ .trim();+ if (!firstLine || CHATTY.test(firstLine) || /,$/.test(firstLine) || /[.!?]\s/.test(firstLine)) return null;+ const words = firstLine.split(' ').filter(Boolean);+ if (words.length > TITLE_MAX_WORDS + 3) return null; // a sentence, not a title+ return fit(words) || null;+}++const LEADING_FILLER = /^(?:(?:hey|hi|hello|yo|okay|ok|so|um|uh|well|please|pls|mercury|optimus|and|also|now|then|just|quick question|one more thing)(?:[\s,!.:-]+|$))+/i;+const ASK = /^(?:(?:can|could|would|will) you(?: please)?|i (?:want|need|would like|'d like) (?:you )?to|i want|i need|help me(?: to)?|let'?s|please)\s+/i;++/** A title from the owner's first message: no links, greetings or "can you". */+export function fallbackSessionTitle(content: string): string {+ let text = content+ .replace(/^\s*\[[^\]]*\]\s*/, '') // "[Voice, on the owner's computer: …]" and similar notes+ .replace(/```[\s\S]*?```/g, ' ')+ .replace(/https?:\/\/\S+/gi, ' ')+ .replace(/[`*_#>]/g, ' ').replace(/\s+/g, ' ').trim();- const words = firstLine.split(' ').filter(Boolean).slice(0, 7);- if (words.length < 3) return null;+ for (let i = 0; i < 3; i++) {+ const next = text.replace(LEADING_FILLER, '').replace(ASK, '').trim();+ if (next === text) break;+ text = next;+ }+ const sentence = text.split(/(?<=[.!?])\s/)[0] ?? '';+ const words = sentence.replace(/[.!?,;:]+$/g, '').split(' ').filter(Boolean);+ const title = fit(words);+ return title ? title[0].toUpperCase() + title.slice(1) : 'New chat';+}++/** Is this first message too thin to name the conversation ("hi", "hey there")? */+export function isThinOpening(content: string): boolean {+ const left = content.replace(/https?:\/\/\S+/gi, ' link ').replace(LEADING_FILLER, '').replace(/[^\p{L}\p{N}\s]/gu, ' ').trim();+ return left.split(/\s+/).filter(Boolean).length < 2;+}++/** At most TITLE_MAX_WORDS words and TITLE_MAX_CHARS characters, cut at a word. */+function fit(words: string[]): string {let title = '';- for (const word of words) {+ for (const word of words.slice(0, TITLE_MAX_WORDS)) {const candidate = title ? `${title} ${word}` : word;- if (candidate.length > 80) break;+ if (candidate.length > TITLE_MAX_CHARS) break;title = candidate;}- if (title.split(' ').length < 3) title = words.join(' ').slice(0, 80).trim();- return title || null;+ if (!title && words[0]) title = words[0].slice(0, TITLE_MAX_CHARS);+ return title.replace(/[,;:\-–]+$/g, '').trim();}