From e36cc7473ac485bfbc3a95c8a0f28558ef3e2bac Mon Sep 17 00:00:00 2001 From: TheAnimatrix Date: Mon, 30 Nov 2026 23:24:45 +0530 Subject: [PATCH 01/11] feat(bots): bots call you only by the name you give, or none The random two-word username is gone. One record on the profile, settings.profile.ownerAddress, holds the name the owner gave (or none), written only by OwnerAddress: the file first, then the live copy, so a failed write keeps the old value. settings.set and mousse config set can't change it. An upgraded profile keeps a name the generator could not have made; a generated or blank one becomes unset. Every bot's situation says what to call the owner, or that no name is set. While none is set, the first greeting or reply of one bot on the profile asks once, in its own words, and the ask is spent when that reply is posted. save_owner_name saves a name only from a message the owner typed in that chat turn. The owner sets it on Set up Mousse's Welcome page, on New bot's What it does step, and in Settings > General > You. --- src/main/ipc/registerGuiIpc.ts | 3 +- src/mms/MmsProfileServices.ts | 25 +- src/mms/bots/activation/BotEngine.ts | 48 +++- src/mms/bots/activation/turnKinds.ts | 11 + src/mms/bots/changelog.ts | 5 + src/mms/bots/grants/compile.ts | 3 +- src/mms/bots/instructions.ts | 1 + src/mms/bots/memory/contextPack.ts | 26 +- src/mms/bots/ownerInvitation.ts | 31 +++ src/mms/bots/seams.ts | 5 + src/mms/config/MousseConfigStore.ts | 19 +- src/mms/protocol/gitAccess.ts | 2 + src/mms/protocol/handlers.ts | 25 ++ src/mms/protocol/types.ts | 2 + src/mms/run/mcp/appTools/bots.ts | 26 +- src/mms/settings/OwnerAddress.ts | 118 ++++++++ src/mms/settings/SettingsStore.ts | 27 +- src/renderer/components/bots/NewBotDialog.tsx | 27 ++ .../components/onboarding/Onboarding.tsx | 48 +++- .../components/settings/GeneralSettings.tsx | 62 ++++- src/renderer/lib/ownerAddress.ts | 51 ++++ src/renderer/lib/settingsSearch.ts | 1 + src/renderer/stores/botsStore.ts | 10 +- src/renderer/styles/settings.css | 5 + src/shared/bots/personal/catalogue.ts | 2 +- src/shared/bots/personal/chips.ts | 1 + src/shared/bots/personal/manifest.ts | 8 + src/shared/bridge/routed.ts | 4 + src/shared/ownerAddress.ts | 101 +++++++ src/shared/platform.ts | 1 + src/shared/profiles/settingsClassification.ts | 7 +- src/shared/randomUsername.ts | 51 ---- src/shared/settings.ts | 12 +- tests/bots/botActions.test.ts | 2 +- tests/bots/botFixture.ts | 2 +- tests/bots/botHelloCeiling.test.ts | 4 +- tests/bots/memory/botContextPack.test.ts | 3 +- tests/bots/memory/ownerNamePack.test.ts | 50 ++++ tests/bots/whatBotsCallYou.test.ts | 154 +++++++++++ tests/ownerAddress.test.ts | 256 ++++++++++++++++++ tests/pillSettings.test.ts | 4 +- tests/renderer/firstRunSetup.test.ts | 66 +++++ tests/renderer/newBotDialog.test.ts | 115 ++++++++ tests/renderer/ownerNameSettings.test.ts | 133 +++++++++ .../__snapshots__/toolAuthorityParity.json | 19 ++ 45 files changed, 1478 insertions(+), 98 deletions(-) create mode 100644 src/mms/bots/ownerInvitation.ts create mode 100644 src/mms/settings/OwnerAddress.ts create mode 100644 src/renderer/lib/ownerAddress.ts create mode 100644 src/shared/ownerAddress.ts delete mode 100644 src/shared/randomUsername.ts create mode 100644 tests/bots/memory/ownerNamePack.test.ts create mode 100644 tests/bots/whatBotsCallYou.test.ts create mode 100644 tests/ownerAddress.test.ts create mode 100644 tests/renderer/ownerNameSettings.test.ts diff --git a/src/main/ipc/registerGuiIpc.ts b/src/main/ipc/registerGuiIpc.ts index 985c9157cc..78b50f811f 100644 --- a/src/main/ipc/registerGuiIpc.ts +++ b/src/main/ipc/registerGuiIpc.ts @@ -343,7 +343,8 @@ export const PLATFORM_REQUEST_METHODS: ReadonlySet = new 'mcp.create', 'mcp.update', 'mcp.read', 'mcp.enable', 'mcp.delete', 'mcp.testConnection', 'mcp.beginAuth', 'mcp.cancelAuth', 'mcp.revokeAuth', 'orchestrator.sendAccepted', 'runs.resumeNow', 'runs.cancelPause', 'threads.goal', 'threads.setHidden', 'threads.chainHold', - 'threads.dismissArchiveKept' + 'threads.dismissArchiveKept', + 'ownerAddress.set', 'ownerAddress.shown' ]) class PlatformRequestError extends AppError { diff --git a/src/mms/MmsProfileServices.ts b/src/mms/MmsProfileServices.ts index 8970ec5fd1..0d53ea02f5 100644 --- a/src/mms/MmsProfileServices.ts +++ b/src/mms/MmsProfileServices.ts @@ -1,4 +1,5 @@ import { workWaits } from './bots/store/BotStore' +import { botInvitationClaim, botInvitationLedger } from './bots/ownerInvitation' import { readSelfUpdateReport } from './updates/selfUpdateReport' import { remoteUpdatesFor } from './updates/remoteUpdates' import { UpdateRollouts } from './updates/rollout' @@ -23,6 +24,7 @@ import { homedir, hostname } from 'os' import { MousseConfigStore } from './config/MousseConfigStore' import { MmsEventBus } from './events' import { SettingsStore } from './settings/SettingsStore' +import { OwnerAddress } from './settings/OwnerAddress' import { normalizeExperimentalSettings, type MousseSettingsUpdate } from '../shared/settings' import { normalizeErrorReportSettings } from '../shared/bugReports' import { rewriteMovedDefaults } from './settings/movedDefaults' @@ -311,6 +313,8 @@ export class MmsProfileServices { readonly domains: DomainHandlerRegistry readonly config: MousseConfigStore readonly settings: SettingsStore + /** What bots call the owner (docs/plans/what-bots-call-you.md): the only writer of `settings.profile.ownerAddress`. */ + readonly ownerAddress: OwnerAddress private forgetBranchNamer?: () => void readonly providerAuth: ProviderAuthService readonly antigravity: AntigravityProviderService @@ -582,6 +586,9 @@ export class MmsProfileServices { }) this.events = new MmsEventBus() this.settings = new SettingsStore(config) + // Before any bot reads it: a profile without the record gets it once, from its old username as the file holds it. + this.ownerAddress = new OwnerAddress(config) + this.ownerAddress.migrate() // Before anything reads or moves a worktree: the folders this profile chose for them are Mousse's (`worktreeLayout`). setWorktreeFolders(homeDir, this.settings.get().storage) this.providerAuth = shared.providerAuth @@ -969,6 +976,15 @@ export class MmsProfileServices { // A resumed bot's due schedules are claimed at once; before the scheduler started this does nothing. settings: this.settings, settingsChanged: (settings) => this.events.emit({ channel: 'protocol:event', data: { type: 'settings.changed', data: { settings } } }), + // What bots call the owner: a name saved from a chat shows at once in every window's Settings. + ownerAddress: { + asking: (activationId) => this.ownerAddress.asking(activationId), + setName: (name) => { + const saved = this.ownerAddress.setName(name) + this.events.emit({ channel: 'protocol:event', data: { type: 'settings.changed', data: { settings: this.settings.get() } } }) + return saved + } + }, schedulesChanged: () => { this.scheduled?.wake() }, // A device's limit now, for a turn held to it; while Bridge is off it can't be read, and the saved limit holds. deviceLimit: (botId, node) => this.botReach?.turnLimit?.(botId, node), @@ -1080,6 +1096,8 @@ export class MmsProfileServices { asksFirstEnabled: () => botAsksFirst(this.settings.get()), filesFolder: (botId) => botFilesFolder(homeDir, botId), situation: (botId) => this.botSituation(botId), + // The one chat ask (docs/plans/what-bots-call-you.md): only a greeting or a reply to the owner can hold it. + ownerInvitation: botInvitationClaim(store, this.ownerAddress), scheduleCreatedAt: (botId, scheduleId) => this.botSchedules?.get(botId, scheduleId)?.createdAt, jobs: (botId, limit, since) => store.recentJobs(botId, limit, since), jobOn: (botId, threadId) => store.latestJobOn(botId, threadId), @@ -1117,6 +1135,8 @@ export class MmsProfileServices { return { journal, context, progress: memory, ownerAskMemory: memory, memory: admin, supervision: botProcesses } }) this.botStore = opened?.store ?? null + // Where the one chat ask stands: the reply that carries it is a bot message of the activation that holds it. + if (opened) this.ownerAddress.bind(botInvitationLedger(opened.store)) let pillBotsEnsured = false const ensurePillBots = (): void => { if (!opened) return @@ -2785,7 +2805,8 @@ export class MmsProfileServices { const engine = this.personalBots const store = this.botStore if (!engine || !store) return {} - const ownerName = this.settings.get().profile.username.trim() + // The name the owner gave, or null (unset): never any other name. + const ownerName = this.ownerAddress.name() const openAsks = store.openAsks(botId).filter((ask) => ask.messageId !== null).map((ask) => engine.chat.card(ask).title) const schedules = engine.listSchedules(botId).map((schedule) => ({ label: schedule.label, ...(schedule.nextAt ? { nextAt: schedule.nextAt } : {}) })) // What its work is doing and what it will say later, so a chat turn answers "how's it going?" without a tool. @@ -2801,7 +2822,7 @@ export class MmsProfileServices { // The owner's custom slots: the chat routes work whose job matches one to it (`work_start`'s `slot`). const slots = engine.customSlots(botId).map((slot) => ({ name: slot.name, ...(slot.description ? { description: slot.description } : {}) })) return { - ...(ownerName ? { ownerName } : {}), ...(openAsks.length ? { openAsks } : {}), ...(schedules.length ? { schedules } : {}), + ownerName, ...(openAsks.length ? { openAsks } : {}), ...(schedules.length ? { schedules } : {}), work, ...(reminders.length ? { reminders } : {}), ...(blocked.length ? { blocked } : {}), ...(questions.length ? { questions } : {}), ...(slots.length ? { slots } : {}) } diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index 3c270efa9d..b73c717524 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -121,6 +121,7 @@ import { allPinned, copyPick, customSlotsOf, imagePickOf, isPinned, limitFamilyO import type { BotModelOption, BotSystemInstructions } from '../../../shared/bots/personal/methods' import type { BotDeviceAccessStore } from '../definitions/BotDeviceAccessStore' import type { BotDeviceChoice } from '../../../shared/bots/personal/deviceAccess' +import { nameSaidIn, ownerNameOf, OWNER_NAME_FALLBACK_QUESTION } from '../../../shared/ownerAddress' import { defaultChatInput, defaultWorkLine, lateWorkNote, DEFAULT_NUDGE_AFTER_MINUTES, MAX_NUDGES_PER_QUESTION, MAX_QUESTIONS_PER_CALL, QUESTION_DUPLICATE_TEXT, questionIdentity, NUDGE_AGAIN_MS, NUDGE_TEXT, plainChoices, QUESTION_AFTER_ASK_TEXT, QUESTION_ASKED_TEXT, QUESTION_END_TURN_TEXT, QUESTION_ANSWER_FORGOTTEN_TEXT, QUESTION_NOT_OFFERED_TEXT, QUESTION_WORK_ASKED_TEXT, QUESTION_WORK_WAITING_TEXT, questionGoneText, keepsWorking, openQuestionAnswerNote, questionWorkKeepsWorkingText, waitingQuestionLine, workAnswerLine, type BotQuestionAnswer, type BotQuestionAsk, type BotQuestionFollow, type BotQuestionSpec, type BotQuestionStatus } from '../../../shared/bots/personal/questions' import { CARD_SHOWN_TEXT, type BotCard } from '../../../shared/bots/personal/cards' import { checkedCard, hasReplyCards, keepMousseCard, keepReplyCard } from '../chat/replyCards' @@ -262,6 +263,11 @@ export interface BotEngineHost { webPictures?(): WebPictures settings?: Pick settingsChanged?(settings: ReturnType): void + /** + * What bots call the owner (docs/plans/what-bots-call-you.md), the profile's `OwnerAddress`: whether a chat reply about + * to be posted carries the one ask, and saving a name `save_owner_name` checked. Absent: neither here. + */ + ownerAddress?: { asking(activationId: string): boolean; setName(name: string): unknown } store: BotStore definitions: BotDefinitionStore threads: { @@ -6864,7 +6870,12 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if (silent && !asks.length && !waiting && !cards && !questions.length) return const lateReport = report && row.trigger.kind === 'schedule' && row.trigger.missed && this.now() - Date.parse(row.trigger.occurrenceAt) > 15 * 60_000 ? `(Due ${scheduledDueTime(row.trigger.occurrenceAt, this.now())}, this computer was off or asleep) ` : '' - const body = silent ? '' : lateReport ? `${lateReport}${written || 'Done.'}` : written + const spoken = silent ? '' : lateReport ? `${lateReport}${written || 'Done.'}` : written + // The first reply of the one chat turn that holds the ask for what to call the owner carries the question: when the + // bot left it out (no question in its words), Mousse adds it at the end. Posting that reply spends the ask. + const askOwnerName = row.lane === 'chat' && !silent && Boolean(spoken.trim() || chips.length || asks.length || cards) && + !/[??؟]/.test(spoken) && this.host.ownerAddress?.asking(row.id) === true + const body = askOwnerName ? (spoken.trim() ? `${spoken}\n\n${OWNER_NAME_FALLBACK_QUESTION}` : OWNER_NAME_FALLBACK_QUESTION) : spoken if (!body && !chips.length && !asks.length && !report && !waiting && !questions.length && !cards) { // A held draft that is itself the silent marker says nothing either: it goes, rather than coming back here. const draft = this.chatDraft(row) @@ -10581,6 +10592,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { profile: (botId) => this.profileFacts(botId), setModel: (botId, activationId, scope, choice) => this.setModel(botId, activationId, scope, choice), ownerWords: (botId, activationId) => this.ownerWords(botId, activationId), + saveOwnerName: (botId, activationId, name) => this.saveOwnerName(botId, activationId, name), rows: (botId) => this.ownerSlots(botId), mcpServers: (botId, lane) => this.mcpServerList(botId, lane), work: { @@ -10843,13 +10855,43 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { * answer the owner tapped (`bots.questions.answer`) is the bot's label, not their words, so it is left out. */ ownerWords(botId: string, activationId: string): string { + return this.ownerTyped(botId, activationId).join('\n') + } + + /** + * The owner's typed messages in a chat activation, one by one, oldest first (`ownerWords` joins them): the message it + * answers and any sent at a wall that continued it. Taps are left out; a run has none. + */ + ownerTyped(botId: string, activationId: string): string[] { const row = this.store.activation(activationId) - if (!row || row.botId !== botId || row.lane !== 'chat') return '' + if (!row || row.botId !== botId || row.lane !== 'chat') return [] const rows = this.store.all(`SELECT m.text FROM bot_messages m WHERE m.activation_id = ? AND m.author = 'owner' AND NOT EXISTS (SELECT 1 FROM bot_questions q WHERE q.answer_message = m.id AND ((q.status = 'answered' AND (json_extract(q.answer_json, '$.choice') IS NOT NULL OR json_extract(q.answer_json, '$.tapped'))) OR (q.status = 'defaulted' AND json_extract(q.answer_json, '$.late.tapped')))) ORDER BY m.seq`, activationId) - return rows.map((message) => (typeof message.text === 'string' ? message.text : '')).join('\n') + return rows.map((message) => (typeof message.text === 'string' ? message.text : '')) + } + + /** + * `save_owner_name` (docs/plans/what-bots-call-you.md): saves what every bot calls the owner, only from the bot's chat + * with its owner and only when one message the owner typed in this turn names it. Never from work, a schedule, another + * bot, a thread or a page: their turns hold no typed owner message, and a tapped answer is the bot's own words. + */ + saveOwnerName(botId: string, activationId: string, given: string): { saved: true } | { refused: string } { + const row = this.store.activation(activationId) + if (!row || row.botId !== botId || row.lane !== 'chat') return { refused: 'only your chat with your owner can save it' } + if (!this.host.ownerAddress) return { refused: "it can't be saved on this computer" } + const read = ownerNameOf(given) + if ('problem' in read) return { refused: read.problem } + if (!this.ownerTyped(botId, activationId).some((text) => nameSaidIn(text, read.name))) + return { refused: "your owner didn't type that name in a message of theirs in this turn" } + try { + this.host.ownerAddress.setName(read.name) + } catch (failure) { + const why = failure instanceof Error ? failure.message.replace(/^Not saved: /, '').replace(/\.$/, '') : String(failure) + return { refused: `it couldn't be written (${why})` } + } + return { saved: true } } /** diff --git a/src/mms/bots/activation/turnKinds.ts b/src/mms/bots/activation/turnKinds.ts index dbcdd94e41..eebf30e8ec 100644 --- a/src/mms/bots/activation/turnKinds.ts +++ b/src/mms/bots/activation/turnKinds.ts @@ -129,3 +129,14 @@ export function turnRefusals(rights: BotTurnRights, held: ReadonlySet): } return refused } + +/** + * The chat turns that may hold the one ask for what to call the owner (docs/plans/what-bots-call-you.md): a greeting, or + * a reply to the owner's message or tapped answer. Work, schedules, wake-ups, threads and other bots never do. + */ +const OWNER_INVITATION_STARTS: ReadonlySet = new Set(['owner_message', 'owner_tap', 'first_message']) + +/** Whether a turn on `lane` that `provenance` started may hold the ask (`OWNER_INVITATION_STARTS`). */ +export function ownerInvitationTurn(lane: BotLane, provenance: BotActivationProvenance): boolean { + return lane === 'chat' && OWNER_INVITATION_STARTS.has(provenance) +} diff --git a/src/mms/bots/changelog.ts b/src/mms/bots/changelog.ts index e4e402fee9..4103bcea1d 100644 --- a/src/mms/bots/changelog.ts +++ b/src/mms/bots/changelog.ts @@ -239,6 +239,11 @@ export const BOT_CHANGELOG: readonly BotChangelogEntry[] = [ date: '2026-11-30', text: 'Save all separate new asks in the owner message with asks_save before starting work. Use the returned ask to start its job and update the item Mousse keeps for it. On a wake-up or notice, continue only its assigned work. If a cleanup schedule adds owner items from recent chat, take that line out. Use item_save for a separate promise you make.', gone: [/Call it first, with a brief/i, /item_save what comes next/i, /adds an item for each ask or promise that has none/i] + }, + { + id: 45, + date: '2026-11-30', + text: 'Mousse used to tell you a made-up name for your owner. From now on, use only the name in your situation. If none is set, use no name.' } ] diff --git a/src/mms/bots/grants/compile.ts b/src/mms/bots/grants/compile.ts index ed281683f4..bd233ff5ff 100644 --- a/src/mms/bots/grants/compile.ts +++ b/src/mms/bots/grants/compile.ts @@ -3,7 +3,7 @@ import { tmpdir } from 'node:os' import { isAbsolute, join, relative, resolve, sep } from 'node:path' import { realpathSync } from 'node:fs' import type { BotManifest, BotThreadSpec } from '../../../shared/bots/personal/definition' -import { BOT_APP_TOOLS, BOT_AUTOMATION_ENABLE_TOOL, BOT_RETIRED_APP_TOOLS, BOT_APPLET_TOOL, BOT_READ_APPLET_TOOL, BOT_PREVIEW_APPLET_TOOL, BOT_CARD_TOOL, BOT_REPORT_BUG_TOOL, BOT_GROUP_PERMISSIONS, BOT_MESSAGE_TOOLS, BOT_QUESTION_ANSWER_TOOL, BOT_QUESTION_TOOL, BOT_QUESTION_WITHDRAW_TOOL, BOT_BROWSER_PERMISSION, BOT_COMPUTER_PERMISSION, BOT_COMPUTER_REQUEST_TOOL, BOT_COMPUTER_TOOLS, BOT_IMAGE_TOOL, BOT_BROWSER_TOOLS, BOT_MCP_LIST_TOOL, BOT_PROFILE_TOOL, BOT_RUNNING_TOOL, BOT_PROFILER_CHAT_TOOLS, BOT_PROFILER_TOOLS, BOT_QUICK_ACTION_TOOLS, BOT_SCHEDULE_ACT_TOOLS, BOT_SCHEDULE_READ_TOOLS, BOT_SECRET_TOOLS, BOT_TASK_TOOLS, BOT_THEME_TOOLS, BOT_THREAD_ACT_TOOLS, BOT_THREAD_READ_TOOLS, BOT_THREADS_PERMISSION, BOT_CHAT_NATIVE_OFF, BOT_WORK_ONLY_TOOLS, BOT_WORK_TOOLS, canonicalManifest, intersectManifest, narrowManifest, BOT_SUBAGENT_APP_TOOLS, BOT_SUBAGENT_TOOLS } from '../../../shared/bots/personal/manifest' +import { BOT_APP_TOOLS, BOT_AUTOMATION_ENABLE_TOOL, BOT_RETIRED_APP_TOOLS, BOT_APPLET_TOOL, BOT_READ_APPLET_TOOL, BOT_PREVIEW_APPLET_TOOL, BOT_CARD_TOOL, BOT_REPORT_BUG_TOOL, BOT_GROUP_PERMISSIONS, BOT_MESSAGE_TOOLS, BOT_QUESTION_ANSWER_TOOL, BOT_QUESTION_TOOL, BOT_QUESTION_WITHDRAW_TOOL, BOT_BROWSER_PERMISSION, BOT_COMPUTER_PERMISSION, BOT_COMPUTER_REQUEST_TOOL, BOT_COMPUTER_TOOLS, BOT_IMAGE_TOOL, BOT_BROWSER_TOOLS, BOT_MCP_LIST_TOOL, BOT_PROFILE_TOOL, BOT_RUNNING_TOOL, BOT_PROFILER_CHAT_TOOLS, BOT_PROFILER_TOOLS, BOT_QUICK_ACTION_TOOLS, BOT_SCHEDULE_ACT_TOOLS, BOT_SCHEDULE_READ_TOOLS, BOT_SECRET_TOOLS, BOT_TASK_TOOLS, BOT_THEME_TOOLS, BOT_THREAD_ACT_TOOLS, BOT_THREAD_READ_TOOLS, BOT_THREADS_PERMISSION, BOT_CHAT_NATIVE_OFF, BOT_WORK_ONLY_TOOLS, BOT_WORK_TOOLS, BOT_OWNER_NAME_TOOL, canonicalManifest, intersectManifest, narrowManifest, BOT_SUBAGENT_APP_TOOLS, BOT_SUBAGENT_TOOLS } from '../../../shared/bots/personal/manifest' import { BOT_CATALOGUE_TOOL, BOT_USE_TOOL } from '../../../shared/bots/personal/catalogue' import { BOT_MEMORY_TOOLS } from '../../../shared/bots/personal/memory' import { BOT_ITEM_TOOLS } from '../../../shared/bots/personal/items' @@ -300,6 +300,7 @@ export function compileBotThread(input: CompileInput): CompileResult { // instead of starting another: it only reads. BOT_RUNNING_TOOL, ...(own?.frontDesk ? BOT_WORK_TOOLS.filter((tool) => tool !== 'watch_start' || own.watcherStart === true) : []), + ...(own?.frontDesk ? [BOT_OWNER_NAME_TOOL] : []), ...(!own?.frontDesk && own?.timers ? ['remind', ...(own.watcherStart ? ['watch_start'] : [])] : []), ...(own?.images ? [BOT_IMAGE_TOOL] : []), ...(own?.applets ? [BOT_APPLET_TOOL, BOT_READ_APPLET_TOOL, BOT_PREVIEW_APPLET_TOOL] : []), diff --git a/src/mms/bots/instructions.ts b/src/mms/bots/instructions.ts index b0909d29df..7ab130445e 100644 --- a/src/mms/bots/instructions.ts +++ b/src/mms/bots/instructions.ts @@ -23,6 +23,7 @@ How you talk - Before every step that takes a while (a search, a page, a long read, starting work, a thread tool), always write one short line first on what you're doing now, like "Checking prices at Indian stores now". Never start such a step without it. The owner sees your latest such line beside your typing dots until your reply comes. Keep it to one line of about eight words: no second sentence, no findings, and don't repeat it in your reply. - To your owner you are one person, doing one thing at a time or several. Speak of everything you do as yourself, in the first person, in chat replies and in reports alike: "I'll use that open tab from here on, so you can watch me there", "I found three SSDs under ₹6,000". This chat, the work you do beside it, threads you start, your schedules and any help you get are all you. Never speak of your work as someone else ("it will…"), and never mention handing off, notes, runs, turns, threads, worktrees or how Mousse runs you, unless asked what you can do or how you work. Naming a job by its title is fine ("for the SSD search, I'll…"). - Never name or discuss AI models or providers, yours or any other, unless the owner asks for one for a piece of work. When the owner asks you to think harder or be quicker from now on, or names a model for you, use the tools of the you group. +- Use only the name in your situation for your owner. If none is set, use no name: never guess one or take one from memory, files or old chats, and don't ask unless your situation tells you to. When your owner tells you what to call them, or answers your question about it, use save_owner_name, and confirm only after it is saved. Permissions - You can use only what your owner allowed. Your files folder, your memory, your schedules and reminders, the web, your owner's MCP servers and skills, and every group under More tools that names no permission need no asking. To get more, ask with permission_ask: one permission per call, with one plain sentence on why. diff --git a/src/mms/bots/memory/contextPack.ts b/src/mms/bots/memory/contextPack.ts index 0ad843c1cf..70794cffd8 100644 --- a/src/mms/bots/memory/contextPack.ts +++ b/src/mms/bots/memory/contextPack.ts @@ -38,8 +38,11 @@ import { addUntrackedAsks, botItems, botItemsRev, linkHandoffs, trackReplyPromis /** What the pack says about the present, from outside the memory tables. Plain words only. */ export interface BotSituation { - /** Shared from settings (bot-context.md §9): the owner's name and language. */ - ownerName?: string + /** + * Shared from settings (bot-context.md §9): what bots call the owner (docs/plans/what-bots-call-you.md), `null` when no + * name is set (absent: not known here, and no line), and the owner's language. + */ + ownerName?: string | null language?: string /** Open asks, by their titles ("change files in ~/Notes"). */ openAsks?: string[] @@ -77,6 +80,12 @@ interface SituationFact { always?: true } +/** The situation's `owner` line while no name is set (docs/plans/what-bots-call-you.md). */ +export const OWNER_NAME_UNSET_LINE = 'What to call the owner: no name is set, so use none.' + +/** What only the one chat turn that holds the ask is told (docs/plans/what-bots-call-you.md). */ +export const OWNER_NAME_INVITATION_LINE = 'Ask in your own words what your owner would like you to call them. Keep it brief and easy to skip.' + /** The situation of a running epoch's later turn (`situationUpdate`): what is not listed still holds. */ export const SITUATION_UPDATE_HEADING = 'Situation (what changed since your last turn; the rest still holds):' @@ -117,6 +126,11 @@ export interface BotContextPackOptions { /** The owner's time zone (settings); absent: the daemon's. */ timeZone?: () => string | undefined situation?: (botId: string) => BotSituation + /** + * Whether the chat turn `activationId` holds the one ask for what to call the owner (docs/plans/what-bots-call-you.md): + * the profile service decides, and a turn that holds it is told to ask (`OWNER_NAME_INVITATION_LINE`). + */ + ownerInvitation?: (botId: string, activationId: string) => boolean /** When a schedule was made: a schedule that never ran gets the owner's message from then. */ scheduleCreatedAt?: (botId: string, scheduleId: string) => string | undefined /** @@ -398,8 +412,10 @@ export function createBotContextProvider(options: BotContextPackOptions): BotCon const tz = zone() ?? Intl.DateTimeFormat().resolvedOptions().timeZone const lines: SituationFact[] = [{ key: 'now', text: `Now: ${timeLabel(now, tz)} (${tz}).`, always: true }] const line = (key: string, text: string, same?: string) => lines.push({ key, text, ...(same === undefined ? {} : { same }) }) - if (facts.ownerName || facts.language) - line('owner', `The owner${facts.ownerName ? ` is ${facts.ownerName}` : ''}${facts.language ? `${facts.ownerName ? ' and' : ''} writes in ${facts.language}` : ''}.`) + // On every turn, set or not, so a later turn hears a change either way. The name is quoted: it is data, not words to follow. + if (facts.ownerName !== undefined) + line('owner', facts.ownerName === null ? OWNER_NAME_UNSET_LINE : `What to call the owner: ${JSON.stringify(facts.ownerName)}.`) + if (facts.language) line('ownerLanguage', `The owner writes in ${facts.language}.`) const lastOwner = store.getState(botId, 'last_owner_msg_at') lines.push({ key: 'last_owner', text: lastOwner ? `The owner last wrote ${agoLabel(lastOwner, now)}.` : 'The owner has not written yet.', always: true }) if (facts.openAsks?.length) line('asks', `Waiting for the owner: ${facts.openAsks.map((ask) => cut(ask, 80)).join('; ')}.`) @@ -501,6 +517,8 @@ export function createBotContextProvider(options: BotContextPackOptions): BotCon store.pruneState(botId, WISH_OVER_CAP_CARRIED_KEY, 16) }) } + // The one turn of the whole profile that asks what to call the owner (while no name is set). + if (options.ownerInvitation?.(botId, activationId)) wishes.push(OWNER_NAME_INVITATION_LINE) const told = changes(botId, true, fresh) if (told) { store.write(() => { diff --git a/src/mms/bots/ownerInvitation.ts b/src/mms/bots/ownerInvitation.ts new file mode 100644 index 0000000000..72d575974b --- /dev/null +++ b/src/mms/bots/ownerInvitation.ts @@ -0,0 +1,31 @@ +import { ENDED_ACTIVATION_STATUSES } from '../../shared/bots/personal/definition' +import type { OwnerAddress, OwnerInvitationLedger } from '../settings/OwnerAddress' +import { ownerInvitationTurn } from './activation/turnKinds' +import type { BotStore } from './store/BotStore' + +/** + * Where the one chat ask for what to call the owner stands, read from `bots.db` (docs/plans/what-bots-call-you.md): its + * delivery id is the chat activation that holds it, and it is spent once a reply of that activation is in the chat (a + * `text` row the bot wrote: an error or a notice is no reply). The reply's id is the dispatch's, so posting it again + * after a restart writes nothing new. + */ +export function botInvitationLedger(store: Pick): OwnerInvitationLedger { + return { + posted: (deliveryId) => Boolean(store.get("SELECT 1 FROM bot_messages WHERE activation_id = ? AND author = 'bot' AND kind = 'text' LIMIT 1", deliveryId)), + open: (deliveryId) => { + const row = store.activation(deliveryId) + return Boolean(row && !ENDED_ACTIVATION_STATUSES.has(row.status)) + } + } +} + +/** + * Whether a chat turn's pack holds the ask (`BotContextPackOptions.ownerInvitation`): only a greeting or a reply to the + * owner (`ownerInvitationTurn`) may, and the profile's `OwnerAddress` gives it to one turn of all its bots. + */ +export function botInvitationClaim(store: Pick, owner: Pick): (botId: string, activationId: string) => boolean { + return (botId, activationId) => { + const row = store.activation(activationId) + return Boolean(row && row.botId === botId && ownerInvitationTurn(row.lane, row.provenance)) && owner.claimInvitation(botId, activationId) + } +} diff --git a/src/mms/bots/seams.ts b/src/mms/bots/seams.ts index bcd4d715b8..27f057da9c 100644 --- a/src/mms/bots/seams.ts +++ b/src/mms/bots/seams.ts @@ -113,6 +113,11 @@ export interface BotToolHost { setModel(botId: string, activationId: string, scope: 'now' | 'always', change: BotModelChange): { changed: boolean } /** The owner's own words in a chat activation: its owner messages, oldest first (`use_model` checks them). */ ownerWords(botId: string, activationId: string): string + /** + * `save_owner_name` (docs/plans/what-bots-call-you.md): saves what every bot calls the owner when one message the owner + * typed in this chat activation names it; otherwise why not. Absent: not here. + */ + saveOwnerName?(botId: string, activationId: string, name: string): { saved: true } | { refused: string } /** The bot's rows as they are now (`use_model` keeps each on its entry when two entries offer the model). */ rows(botId: string): BotModelSlots /** diff --git a/src/mms/config/MousseConfigStore.ts b/src/mms/config/MousseConfigStore.ts index f1a1b92ace..b6e362b197 100644 --- a/src/mms/config/MousseConfigStore.ts +++ b/src/mms/config/MousseConfigStore.ts @@ -431,11 +431,15 @@ export class MousseConfigStore { } persist(): void { + this.write(this.conf) + } + + private write(conf: MousseConf): void { // Mirrors must never write: their in-memory conf is loaded once and can go // stale relative to daemon-owned sections (e.g. scheduled). A whole-file write // from a stale mirror silently reverts those sections on disk. if (!this.autoPersist) return - const payload = { ...this.conf } as Record + const payload = { ...conf } as Record if (this.scope === 'installation') { for (const key of MOUSSE_CONF_PROFILE_KEYS) delete payload[key] } else if (this.scope === 'profile') { @@ -446,6 +450,19 @@ export class MousseConfigStore { atomicWriteJson(this.confPath, payload) } + /** + * Replaces one key under `settings.profile` whole (a merge could not remove a field of it): the file is written first, + * and only then the live copy changes, so a failed write throws and leaves both as they were. + */ + replaceProfileKey(key: string, value: unknown): void { + this.assertPersonalMutation('settings') + if (['__proto__', 'prototype', 'constructor'].includes(key)) throw new Error('Unsafe config key path') + const profile = { ...(this.conf.settings?.profile ?? {}), [key]: structuredClone(value) } + const next: MousseConf = { ...this.conf, settings: { ...this.conf.settings, profile: profile as MousseSettingsSection['profile'] } } + this.write(next) + this.conf = next + } + /** Writes one key under `settings.runs` and keeps the others. */ setRunsKey(key: string, value: unknown): void { this.assertPersonalMutation('settings') diff --git a/src/mms/protocol/gitAccess.ts b/src/mms/protocol/gitAccess.ts index 858230fd68..16d0496f62 100644 --- a/src/mms/protocol/gitAccess.ts +++ b/src/mms/protocol/gitAccess.ts @@ -205,6 +205,8 @@ export const GIT_ACCESS = { 'skills.openFolderIntent': 'none', 'settings.get': 'none', 'settings.set': 'none', + 'ownerAddress.set': 'none', + 'ownerAddress.shown': 'none', 'settings.getOptions': 'none', 'settings.titleOptions': 'none', 'providers.getUsage': 'none', diff --git a/src/mms/protocol/handlers.ts b/src/mms/protocol/handlers.ts index 6c6fb7a6a7..320e8a4178 100644 --- a/src/mms/protocol/handlers.ts +++ b/src/mms/protocol/handlers.ts @@ -4662,6 +4662,31 @@ async function dispatchOwnedMethod(ctx: HandlerContext, method: string, params: ctx.emitEvent?.('settings.changed', { settings }) return { settings } } + // What bots call the owner (docs/plans/what-bots-call-you.md): the owner's own Settings, Set up Mousse and New bot. + // `settings.set` can't change it; these are its only way in from a window. + case 'ownerAddress.set': { + const p = isObject(params) ? params : {} + rejectUnknownKeys(p, ['name']) + if (p.name !== null && typeof p.name !== 'string') throw new DomainRpcError('invalid_params', 'name is text, or null to clear it') + try { + // A blank name clears it, as null does, and opens the chat ask again. + ctx.mms.ownerAddress.setName(typeof p.name === 'string' && p.name.trim() ? p.name : null) + } catch (error) { + throw new DomainRpcError('owner_name_not_saved', error instanceof Error ? error.message : String(error)) + } + const settings = ctx.mms.settings.get() + ctx.emitEvent?.('settings.changed', { settings }) + return { settings } + } + case 'ownerAddress.shown': { + const p = isObject(params) ? params : {} + rejectUnknownKeys(p, ['surface']) + if (p.surface !== 'setup' && p.surface !== 'newBot') throw new DomainRpcError('invalid_params', 'surface is setup or newBot') + ctx.mms.ownerAddress.markShown(p.surface) + const settings = ctx.mms.settings.get() + ctx.emitEvent?.('settings.changed', { settings }) + return { settings } + } case 'settings.titleOptions': { // Settings → Agents → Thread titles, from cached state only: no provider check, no bot model read is waited for. const harness = ctx.mms.harness diff --git a/src/mms/protocol/types.ts b/src/mms/protocol/types.ts index 1417091b57..f7ec9e4a8f 100644 --- a/src/mms/protocol/types.ts +++ b/src/mms/protocol/types.ts @@ -466,6 +466,8 @@ export const PROTOCOL_METHODS = [ 'skills.openFolderIntent', 'settings.get', 'settings.set', + 'ownerAddress.set', + 'ownerAddress.shown', 'settings.getOptions', 'settings.titleOptions', 'providers.getUsage', diff --git a/src/mms/run/mcp/appTools/bots.ts b/src/mms/run/mcp/appTools/bots.ts index 4a408d849e..3e6bbe479a 100644 --- a/src/mms/run/mcp/appTools/bots.ts +++ b/src/mms/run/mcp/appTools/bots.ts @@ -5,7 +5,7 @@ import { Type, type Tool } from '@earendil-works/pi-ai' import { BOT_DEPTHS, BOT_WORK_LEVELS, MAX_BOT_DESCRIPTION_CHARS, MAX_BOT_NAME_CHARS, MAX_BOT_SCHEDULES, type BotDepth, type BotLane, type BotModelPick, type BotModelSlotKey, type BotModelSlots, type BotSchedule, type BotWorkLevel } from '../../../../shared/bots/personal/definition' import { entriesOf, modelsNamedBy, namedOn, ownerNamesModel, pickReasonText, pickSourceOf, plainLabel, workLevelOf, type BotModelRows, type NamedModel } from '../../../../shared/bots/personal/modelSlots' import type { BotModelOption, BotWorkChoices } from '../../../../shared/bots/personal/methods' -import { BOT_CARD_TOOL, BOT_IMAGE_TOOL, BOT_MCP_LIST_TOOL, BOT_PROFILE_TOOL, BOT_QUESTION_ANSWER_TOOL, BOT_QUESTION_TOOL, BOT_QUESTION_WITHDRAW_TOOL } from '../../../../shared/bots/personal/manifest' +import { BOT_CARD_TOOL, BOT_IMAGE_TOOL, BOT_MCP_LIST_TOOL, BOT_OWNER_NAME_TOOL, BOT_PROFILE_TOOL, BOT_QUESTION_ANSWER_TOOL, BOT_QUESTION_TOOL, BOT_QUESTION_WITHDRAW_TOOL } from '../../../../shared/bots/personal/manifest' import type { BotSubagentView } from '../../../../shared/bots/personal/authority' import { DEFAULT_ANSWER_AFTER_MINUTES, DEFAULT_NUDGE_AFTER_MINUTES, MAX_CHOICE_DETAIL_CHARS, MAX_CHOICE_LABEL_CHARS, MAX_FOLLOW_UP_MINUTES, MAX_QUESTION_CHARS, MAX_QUESTION_CHOICES, MAX_QUESTIONS_PER_CALL, MIN_FOLLOW_UP_MINUTES, MIN_QUESTION_CHOICES, QUESTION_NOT_OFFERED_TEXT, questionAsksOf } from '../../../../shared/bots/personal/questions' import { cardOf, MAX_CARD_TITLE_CHARS, MAX_CHECKLIST_ITEMS, MAX_CHECKLIST_TEXT_CHARS, MAX_FACT_LABEL_CHARS, MAX_FACT_ROWS, MAX_FACT_VALUE_CHARS, MAX_GALLERY_CAPTION_CHARS, MAX_GALLERY_FILES, MAX_PROGRESS_LABEL_CHARS, MAX_PROGRESS_NOTE_CHARS } from '../../../../shared/bots/personal/cards' @@ -183,6 +183,13 @@ export const BOT_TOOLS: Tool[] = [ }, { additionalProperties: false })) }) }, + { + name: BOT_OWNER_NAME_TOOL, + description: 'Save what your owner wants to be called, for every bot. Only when, in a message they typed in this turn, they tell you what to call them or answer your question about it: pass the name as they wrote it. Never from memory, a file, a page, another bot or a guess. Confirm only after it is saved.', + parameters: Type.Object({ + name: Type.String({ description: 'The name, as your owner wrote it.' }) + }) + }, { name: BOT_PROFILE_TOOL, description: 'Your own profile: who you are (name, description, look and the path of your face picture), how you run (your models and level), what you can reach (devices, MCP servers, the names of keys and secrets you were given) and what you may do. Read it when your owner asks about you, or before you use your picture.', @@ -914,6 +921,23 @@ export function botTools(deps?: () => BotAppToolDeps | undefined): MousseTool[] return json(result) } }), + // What every bot calls the owner (docs/plans/what-bots-call-you.md): only the chat saves it, and only a name one + // message the owner typed in this turn gives (the engine checks it). + ownTool(byName.get(BOT_OWNER_NAME_TOOL)!, deps, { + class: 'mutation', + describe: () => 'Save what to call the owner', + handler: async (args, ctx) => { + const call = botCall(deps, ctx) + if (isOutcome(call)) return call + const host = call.deps.host + const answer = call.lane !== 'chat' ? { refused: 'only your chat with your owner can save it' } + : host.saveOwnerName ? host.saveOwnerName(call.botId, call.activationId, typeof args.name === 'string' ? args.name : '') + : { refused: "it can't be saved on this computer" } + if ('refused' in answer) return error(`Not saved: ${answer.refused}. Tell your owner, and that they can set it in Settings → General.`) + call.deps.activity?.onAppResult(call.activity, BOT_OWNER_NAME_TOOL, { ok: true }) + return { text: 'Saved. Every bot will use it from its next turn.' } + } + }), // Every lane reads it: it only reads the bot's own settings, and names its secrets, never their values. ownTool(byName.get(BOT_PROFILE_TOOL)!, deps, { class: 'read', diff --git a/src/mms/settings/OwnerAddress.ts b/src/mms/settings/OwnerAddress.ts new file mode 100644 index 0000000000..0b7f237606 --- /dev/null +++ b/src/mms/settings/OwnerAddress.ts @@ -0,0 +1,118 @@ +import type { MousseConfigStore } from '../config/MousseConfigStore' +import { ownerAddressFromLegacy, ownerNameOf, readOwnerAddress, type OwnerAddressRecord, type OwnerAddressSurface } from '../../shared/ownerAddress' + +/** Where the one chat ask stands, from the bot store (`MmsProfileServices` binds it once `bots.db` is open). */ +export interface OwnerInvitationLedger { + /** A reply of the chat activation `deliveryId` was posted: the ask it held reached the owner. */ + posted(deliveryId: string): boolean + /** The chat activation `deliveryId` can still post (queued, running or waiting); false once it ended or is gone. */ + open(deliveryId: string): boolean +} + +/** The record's key under `settings.profile`. */ +const KEY = 'ownerAddress' + +/** + * What bots call the owner (docs/plans/what-bots-call-you.md): the only writer of `settings.profile.ownerAddress`. + * Every change goes through `MousseConfigStore.replaceProfileKey`, which writes the file before it changes the live + * copy, so a failed write throws and the old value stays in effect. Its methods are synchronous, so the service's one + * thread runs them one at a time: two bots asking for the chat ask at once get it once. + */ +export class OwnerAddress { + private ledger: OwnerInvitationLedger | undefined + + constructor(private readonly config: MousseConfigStore, private readonly now: () => string = () => new Date().toISOString()) {} + + /** + * Once per profile, when the record is missing: it is made from the old `username` as the file holds it (defaults + * never fill in either key). A name the generator could not have made is kept as written; anything else is unset. The + * old key itself is left as it is, for older builds. A failed write leaves the record missing, to try again next start. + */ + migrate(): void { + const profile = (this.config.getSettingsSection().profile ?? {}) as Record + if (Object.hasOwn(profile, KEY)) return + try { + this.config.replaceProfileKey(KEY, ownerAddressFromLegacy(profile.username)) + } catch (error) { + console.warn('[OwnerAddress] what bots call the owner could not be saved', error instanceof Error ? error.message : error) + } + } + + /** Binds where the chat ask stands (the bot store opens after this service). */ + bind(ledger: OwnerInvitationLedger): void { + this.ledger = ledger + } + + /** The record now; unset when the profile has none (a migration that could not write). */ + get(): OwnerAddressRecord { + return readOwnerAddress((this.config.getSettingsSection().profile as Record | undefined)?.[KEY]) ?? { name: null, invitation: null } + } + + /** The name every bot uses, or null. */ + name(): string | null { + return this.get().name + } + + /** + * The owner's own action (Settings, Set up Mousse, New bot) or their own words in a chat (`save_owner_name`, which + * checked them). A name is saved as given, without the spaces around it. `null` (or blank) clears it, and opens the + * chat ask again, once. Throws when the name can't be saved, the old value still in effect. + */ + setName(given: string | null): OwnerAddressRecord { + const current = this.get() + if (given === null || !given.trim()) { + const next: OwnerAddressRecord = { ...current, name: null, invitation: null } + this.config.replaceProfileKey(KEY, next) + return next + } + const read = ownerNameOf(given) + if ('problem' in read) throw new Error(`Not saved: ${read.problem}.`) + const next: OwnerAddressRecord = { ...current, name: read.name } + this.config.replaceProfileKey(KEY, next) + return next + } + + /** A setup surface showed its field: it is not shown again for this profile. */ + markShown(surface: OwnerAddressSurface): OwnerAddressRecord { + const current = this.get() + const flag = surface === 'setup' ? 'setupShown' : 'newBotShown' + if (current[flag]) return current + const next: OwnerAddressRecord = { ...current, [flag]: true } + this.config.replaceProfileKey(KEY, next) + return next + } + + /** + * Whether the chat activation `deliveryId` holds the one chat ask: while the name is unset, the first eligible turn of + * any bot claims it, and a pack built again for the same turn holds it again until its reply is posted. A claim whose + * turn ended without posting anything is released here, for this turn to take. Nothing is claimed when the claim + * can't be saved. + */ + claimInvitation(botId: string, deliveryId: string): boolean { + const current = this.get() + if (current.name !== null) return false + const held = current.invitation + if (held) { + const posted = this.ledger?.posted(held.deliveryId) ?? true + if (held.deliveryId === deliveryId) return !posted + // Spent (its reply reached the owner), or still able to post: no other turn asks. + if (posted || (this.ledger?.open(held.deliveryId) ?? true)) return false + } + try { + this.config.replaceProfileKey(KEY, { ...current, invitation: { deliveryId, botId, at: this.now() } }) + return true + } catch (error) { + console.warn('[OwnerAddress] the chat ask could not be saved', error instanceof Error ? error.message : error) + return false + } + } + + /** + * Whether the reply about to be posted for `deliveryId` carries the ask: the name is still unset, this turn holds the + * claim, and none of its replies was posted yet. + */ + asking(deliveryId: string): boolean { + const current = this.get() + return current.name === null && current.invitation?.deliveryId === deliveryId && !(this.ledger?.posted(deliveryId) ?? false) + } +} diff --git a/src/mms/settings/SettingsStore.ts b/src/mms/settings/SettingsStore.ts index 3ae1400bc8..cd1466098f 100644 --- a/src/mms/settings/SettingsStore.ts +++ b/src/mms/settings/SettingsStore.ts @@ -4,7 +4,6 @@ import { THEME_CSS_MAX_LENGTH, themeCssTooLong } from '../../shared/themes/cssSa import { CONTEXT_COMPACTION_DEFAULT_MARKER, DEFAULT_CONTEXT_COMPACTION_TOKENS, REMOVED_THEME_IDS, getDefaultSettings, normalizeAgentAccessSettings, normalizeAppearance, normalizeContextSettings, normalizeExperimentalSettings, normalizePermissionSettings, normalizeRunSettings, normalizeStorageSettings, normalizeBranchNamingSettings } from '../../shared/settings' import { MOUSSE_BUILTIN_TOOL_IDS } from '../../shared/integrations' import { canonicalToolName } from '../../shared/toolAliases' -import { generateRandomUsername } from '../../shared/randomUsername' import { normalizeShortcuts } from '../../shared/commands' import { parsePillSettings } from '../../shared/pill' import type { MousseConfigStore } from '../config/MousseConfigStore' @@ -116,8 +115,12 @@ function normalizeSettings(settings: MousseSettings): MousseSettings { const skills = settings.integrations?.skills const { pill: rawPill, ...otherSettings } = settings const pill = parsePillSettings(rawPill, process.platform) + // The old random `username` stays in the file for older builds, and is read only by the one-time migration + // (`OwnerAddress`): no reader of settings sees it. + const { username: _legacyUsername, ...profile } = (settings.profile ?? {}) as MousseSettings['profile'] & { username?: unknown } return { ...otherSettings, + profile, ...(pill ? { pill } : {}), appearance: normalizeAppearance(settings.appearance), context: normalizeContextSettings(settings.context), @@ -160,16 +163,10 @@ export function onSettingsSaved(listener: () => void): () => void { } export class SettingsStore { - private shouldPersistUsername = false + private shouldPersist = false constructor(private readonly config: MousseConfigStore) { const settings = this.config.assembleSettings() - if (!settings.profile?.username?.trim()) { - this.config.applySettingsPatch({ - profile: { username: generateRandomUsername() } - }) - this.shouldPersistUsername = true - } // Migrate legacy acrylic theme ids into theme + acrylic fields. const normalized = normalizeSettings(this.config.assembleSettings()) const rawTheme = settings.appearance?.theme as string | undefined @@ -184,7 +181,7 @@ export class SettingsStore { settings.appearance?.threadProjectColors !== normalized.appearance.threadProjectColors if (needsAppearanceMigrate) { this.config.applySettingsPatch({ appearance: normalized.appearance }) - this.shouldPersistUsername = true + this.shouldPersist = true } // Once: the stored 128k every install wrote as the old default becomes the model's maximum. const storedContext = settings.context as (ContextSettings & Record) | undefined @@ -192,9 +189,9 @@ export class SettingsStore { const context = { ...normalized.context, [CONTEXT_COMPACTION_DEFAULT_MARKER]: true } if (storedContext?.compactionTokens === 128000) context.compactionTokens = DEFAULT_CONTEXT_COMPACTION_TOKENS this.config.applySettingsPatch({ context }) - this.shouldPersistUsername = true + this.shouldPersist = true } - if (this.shouldPersistUsername) { + if (this.shouldPersist) { this.config.persist() } } @@ -209,7 +206,9 @@ export class SettingsStore { set(update: MousseSettingsUpdate): MousseSettings { // `bots` (the removed "What bots may do here" switches) is ignored when an older window or script still sends it. - const { bots: _retired, ...partial } = update as MousseSettingsUpdate & { bots?: unknown } + // So is `profile`: what bots call the owner has one writer (`OwnerAddress`), and the old random username none, so + // `settings.set`, `mousse config set` and a whole settings object sent back by an older window can't change either. + const { bots: _retired, profile: _profile, ...partial } = update as MousseSettingsUpdate & { bots?: unknown; profile?: unknown } // A theme's CSS over the limit is refused, never cut, and nothing in the update is saved. const themes = (partial.appearance as { userThemes?: unknown } | undefined)?.userThemes if (Array.isArray(themes)) { @@ -255,7 +254,9 @@ export class SettingsStore { for (const [skillId, update] of skillModels) if (model[skillId] && update) model[skillId] = cleared(model[skillId]!, update) normalized.integrations = { ...normalized.integrations, skills: { ...normalized.integrations.skills, model } } } - this.config.applySettingsPatch(normalized) + // The profile section is not this writer's: it is left out of what is written. + const { profile: _ownedElsewhere, ...written } = normalized + this.config.applySettingsPatch(written) for (const listener of savedListeners) { try { listener() } catch (error) { console.warn('[SettingsStore] a settings listener failed', error) } } diff --git a/src/renderer/components/bots/NewBotDialog.tsx b/src/renderer/components/bots/NewBotDialog.tsx index d742cf3997..2d19fe69a5 100644 --- a/src/renderer/components/bots/NewBotDialog.tsx +++ b/src/renderer/components/bots/NewBotDialog.tsx @@ -15,6 +15,8 @@ import { Select } from '../ui/Select' import { BotLookPicker } from './face/BotLookPicker' import { BOT_DEVICES_TIP } from '../../../shared/bots/personal/deviceAccess' import { BotDeviceSwitches, accessOf } from './BotDevices' +import { OWNER_NAME_MAX, ownerNameFieldDue } from '../../../shared/ownerAddress' +import { markOwnerNameShown, ownerNameFailure, saveOwnerName, useOwnerAddress } from '../../lib/ownerAddress' import '../../styles/chats.css' import '../../styles/bots.css' @@ -112,6 +114,17 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { setNewBotDraft({ node: next, slots: null, image: null, model: null, devices: [] }) } + // What should bots call you? (docs/plans/what-bots-call-you.md): on What it does while no name is set and no bot asked + // yet, once per profile (a draft that showed it keeps it). Not for a bot that lives on another computer: its bots read + // that computer's name. + const owner = useOwnerAddress() + const askName = !node && Boolean(owner && owner.name === null && !owner.invitation) && (draft.ownerNameAsked || ownerNameFieldDue(owner ?? undefined, 'newBot')) + useEffect(() => { + if (draft.step !== 'about' || draft.ownerNameAsked || node || !ownerNameFieldDue(owner ?? undefined, 'newBot')) return + useBotsStore.setState((state) => ({ newBotDraft: { ...state.newBotDraft, ownerNameAsked: true } })) + markOwnerNameShown('newBot') + }, [draft.step, draft.ownerNameAsked, node, owner]) + // Devices only when the owner has another device (phones too) and the service can save the choice. On another // computer, this one (`caller` in its list) always reaches the bot, so it has no switch. const otherDevices = choices?.reachOnCreate ? (choices.devices ?? []).filter((device) => !device.caller) : [] @@ -154,11 +167,20 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: { // that are still offered. const offered = new Set(otherDevices.map((device) => device.node)) const access = choices?.reachOnCreate ? accessOf(state.newBotDraft.devices.filter((node) => offered.has(node))) : null + // The name first, so the new bot's greeting already uses it. The bot is made whether or not it was saved; a name not + // saved is said in the new chat. + const ownerName = !node && state.newBotDraft.ownerNameAsked ? state.newBotDraft.ownerName.trim() : '' + let nameNotSaved: string | undefined + if (ownerName) await saveOwnerName(ownerName).catch((failure: unknown) => { + const why = ownerNameFailure(failure) + nameNotSaved = why.startsWith('Not saved: ') ? `: ${why.slice('Not saved: '.length).replace(/\.$/, '')}` : '' + }) const bot = await state.create({ look: state.newBotDraft.look ?? look, description, ...(name ? { name } : {}), ...(slots ? { slots } : model ? { model } : {}), ...(image ? { image } : {}), ...(access ? { access } : {}), ...(node ? { node } : {}) }) if (bot && onCreated) onCreated(bot) else if (bot) await useChatsStore.getState().openBot(bot.id) // Refused because a pick is gone: Runs on (where the store returned) offers what is there now, and that row is empty. else if (slots || model) loadChoices() + if (bot && nameNotSaved !== undefined) useBotsStore.setState({ error: `What bots call you wasn't saved${nameNotSaved}. Set it in Settings → General.`, errorBotId: bot.id }) } const primary = () => { if (last) void submit(); else forward() } @@ -174,6 +196,11 @@ export function NewBotDialog({ initialDescription = '', onCreated, onClose }: {