diff --git a/docs/bots.md b/docs/bots.md index 7717d612b..f880875ac 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -377,10 +377,11 @@ A bot can tell another of its owner's bots something: `bot_list()` names the own When the owner writes from one computer (here "the PC") to a bot of another (here "the Mac") that the PC uses one way, the Mac has no grant at the PC, so `bot_send` can't reach the PC's bots. The bot can offer the message instead (issue #2490): the PC shows the exact words, and a person there sends them, or doesn't. Nothing crosses from the Mac to the PC; the PC reads the offer on the chat stream it opened. - **The tool.** `bot_offer({ message, to? })` (`src/shared/bots/personal/offers.ts`, `BotEngine.offerBotMessage`), compiled only for the chat front desk (`compileBotThread`'s `bots` with `frontDesk`) and listed only for a chat turn. It works only in a chat turn the owner started from another device whose message said it takes offers: that device's router adds `offers` to `bots.chat.send` (`1` at version 3; `2`, "and hears what became of them", at version 4; added only when the bot's computer lists that version in `net.info`, and never taken from a window), and the turn keeps it on its owner (`BotOwnerTurn.offers`) with the device's node. Any other turn (this computer's own window, a phone, an older PC, a wake, work, another bot's message) is refused with `offer_unsupported` and words to tell the owner to write from the device it is for; there is no other way to send it, ever. Up to 3 offers in a turn (`MAX_OFFERS_PER_TURN`), each up to 2,000 characters and 6 KiB (`MAX_OFFER_CHARS`, `MAX_OFFER_BYTES`). `to` is a name the bot was told, shown as the first pick; it chooses nothing. A retry under the same tool call is the same offer (`replayed`). -- **Where it waits.** In the offering bot's chat, as a notice (`bm_offer_`: "I'd like to send a message to a bot on ANIMATRIX. It waits for you there.") with an `offer` card: the offer id, the words, `to`, the computer's name and the node it is for. The node never leaves the Mac: each reader gets the card through `offerCardFor` (in `remoteBotMessage`, so chat streams, `bots.chat.list` and every other bot method), which drops it and marks `forYou` for the device the offer is for alone. On the Mac, and on every other device, the card shows the words and where it waits, with no Send. +- **Where it waits.** In the offering bot's chat, as a notice (`bm_offer_`: "I'd like to send a message to a bot on ANIMATRIX."; offers made before this said "It waits for you there." too) with an `offer` card: the offer id, the words, `to`, the computer's name and the node it is for. The node never leaves the Mac: each reader gets the card through `offerCardFor` (in `remoteBotMessage`, so chat streams, `bots.chat.list` and every other bot method), which drops it and marks `forYou` for the device the offer is for alone. On the Mac, and on every other device, the card shows the words and where it waits, with no Send. - **Send.** On the PC the card shows the words as plain text (no Markdown, no HTML), a pick of the PC's bots that take offered messages (the one `to` names first, else the only one) and Send. `bots.remote.offerSend` (`BotRouter.offerSend`, a local method) takes only a person at a Mousse window of the PC (`clientType: 'gui'`, not through Bridge; the command line, agents and bots are `forbidden`; #2052 applies). It finds the offer in the PC's own copy of the chat (`RemoteBotChats`), or reads that one row from the Mac (`bots.chat.list` by `seq`), never from what the window says, and checks that it is the PC's (`offer_not_here`), that the words are the window's (`offer_changed`), and, with nothing awaited after it, that the PC still lists the bot and has not blocked the Mac (`sender_blocked`). Then `BotChatService.keepOffered` keeps it in one transaction: one row per offer (`bm_offered_`) and its receipt, kept apart from every chat (`bot_memory_state` under `mousse:offered`). So a second Send, after a reconnect, a restart, with the Mac away, or after that chat was cleared or that bot deleted, answers `replayed` from the PC alone, and one to another bot is `offer_sent`; the bot is here (`recipient_gone`) and takes offered messages (`recipient_closed`); at most 30 a hour on this computer (`too_many`, counted from the receipts, so clearing a chat makes no room). A second Send while one runs is `offer_busy`. - **What the receiving bot gets.** A notice in its chat ("**Message from your bot Loki on Mac mini**, sent by you" and the words as a quote), marked as outside text (`external`: its journal gives it as text from outside, not the owner's) and quiet. It starts no turn and answers nothing: the bot reads it with the owner's next message to it. Working on it is the owner's own message. -- **States on the PC's card** (`BotOfferRow`): Send; Sent to Alpha; a refusal in its words (`BOT_OFFER_REFUSALS`; `offer_offline` when the offer is in no copy here and the Mac can't be reached); "No bot here takes these." when none does. A Send whose answer was lost is looked up (`bots.remote.offerState`, which reads the PC alone) before Send comes back. +- **States on the PC's card** (`BotOfferRow`): Send; Sent to Alpha (by Send, or with no Send under the chat's grant); "This offer expired."; a refusal in its words (`BOT_OFFER_REFUSALS`; `offer_offline` when the offer is in no copy here and the Mac can't be reached); "No bot here takes these." when none does. A Send whose answer was lost is looked up (`bots.remote.offerState`, which reads the PC alone) before Send comes back. The card reads its state again when the Mac's copy says what became of it. +- **States on the Mac's card**, and on any device the offer is not for (`waitingLine` in `BotOfferCard.tsx`): Waiting for you on ANIMATRIX (on another device: Send it from ANIMATRIX); Sent to Alpha on ANIMATRIX; Waiting on ANIMATRIX, which took its limit this hour; Expired before it was sent; Waiting on ANIMATRIX, which won't say when it's sent (an older PC); No word from ANIMATRIX (still queued a day later). - **What the Mac hears.** An offer for a device that said `offers: 2` starts `queued` on the Mac's card (`BotOfferCard.state`); one for a device that said `1` is `unsupported` (an older PC: it never reports, and nothing wider is tried; `offerCardFor` sends it the card without the new fields, which its parser refuses, so its Send keeps working). The PC reports `delivered` (with the bot's name, `sentTo`), `busy` (the hourly cap, when sent under a grant) or `expired` through `bots.offers.outcome` (a Use row the Mac takes only from the device the offer is for; `delivered` and `expired` are final). Each report is sent once and not awaited: one that is lost is sent again when the offer next comes into the PC's copy (`RemoteBotChats.observe`), and on its own up to 4 more times, 30 seconds after and 4× longer each time (until the PC restarts). A queued card older than a day reads `unknown` (`offerShownState`). - **Expiry.** An offer expires a day after it was made (`OFFER_TTL_MS`), and one made under a grant expires when that grant ends; Send then answers `offer_expired`, and the Mac hears so. - **Which bots take them.** Every bot of a computer, until the owner says otherwise: Make private closes it first, then makes the bot private, and stops if closing fails (`bots.devices.offers`, this computer's alone: no other device has a row for it, at any bot access), and About → Devices has the switch "Messages from other computers' bots". Kept in `/bots/offers.json` (`BotOfferAccessStore`); a file that can't be read closes every bot, and the next change keeps the others closed. Make private on a bot of another computer closes its switch there too (`bots.devices.set` with `offers: false`, version 2; an older computer is sent the access alone). @@ -391,6 +392,7 @@ When the owner writes from one computer (here "the PC") to a bot of another (her While a PC window shows the Mac bot's chat, the person there can pick up to 8 of the PC's bots that take offered messages and allow the chat for them (`bots.remote.grantOpen`, `BotRouter.grantOpen`). While the grant is open, what the Mac bot offers one of them, in a turn that window's message started, is sent on the PC with no Send, through the same `keepOffered` as Send (same checks, caps and receipt). An offer to a bot outside the grant waits for Send as before. Messages only. +- **In the window** (`BotChatGrant.tsx`). The composer's link button, in a chat with a bot of another computer, opens a pick of the PC's bots that take offered messages (the only one picked already, at most 8) and "Allow for this chat". While it is open, the line above the composer says "Loki can message Alpha and Beta here", the minutes left and End access; another window shows "Allowed in another window" and no button; the button is lit while it is open. An end the window did not ask for says why once ("Nothing was sent for 10 minutes"), until dismissed; the window keeps reading the grant while the Mac is offline, so an end then ("The connection dropped") is said once it is back. A Mac from before grants shows no button. Each window reads the grant again on `bots.changed` with `grant`, which nothing else re-reads; it comes when the grant opens or ends, and when a message from its window starts its idle time again, so the minutes left move with it. An open pick drops a bot that stops taking offered messages, and an open Send card reads its offer again, so an offer whose grant ended says it expired even while the Mac can't say so. - **Where it lives.** On the PC alone, in memory (`ChatGrants`, `src/mms/bridge/routed/chatGrants.ts`), bound to the window's connection and to the chat that window shows (`AttachedBots.shows`). It holds its own listener on the chat's stream. Another window sees its state (`bots.remote.grantState`) and can neither end nor take it (`grant_elsewhere`); a Mac from before grants is `grant_unsupported`, with no wider way. - **Run tokens.** For each message from the granting window the PC's router adds a fresh token (`run`, a version 4 `bots.chat.send` param, issued by `ChatGrants.issueRun`, never taken from a window). A resend of the same message (same request id) carries the token it was first sent with, or none, so the Mac takes it as the same message. The Mac keeps it on the turn (`BotOwnerTurn.run`) and stamps it on that turn's offers (`BotOfferCard.run`, shown only to the device the offer is for). A message without one (another window, another device) that joins or continues the turn takes it off (`BotStore.narrowOwnerRun`), so what the turn offers from then on waits for Send; one with a token never swaps it in, so a grant opened later never takes over a turn an ended one started. The PC sends an offer on its own only when the token is one an open grant issued and `to` names exactly one bot of the grant. A forged or replayed token, or one from an ended grant, is held by none: the offer is expired. - **When it ends** (`CHAT_GRANT_ENDS`): End access (`bots.remote.grantEnd`, the granting window only); the window leaving the chat or closing; 10 minutes with no message from that window (`CHAT_GRANT_IDLE_MS`); an hour after it opened (`CHAT_GRANT_MAX_MS`); the stream ending, starting again or replaying from its copy (connection lost, either computer restarted); Make private of a granted bot, or any change from here to who reaches the offering bot; blocking the Mac or Bridge going off; the Mac no longer listing the bot. Each wins over a send in progress: the send checks them with nothing awaited between the check and the commit, and a grant past its time is ended when it is read, before its timer runs. An end that comes in while an Allow waits wins too: nothing opens after it. Offers left unsent under it expire and the Mac hears so. Reconnecting or another window needs a new Allow. @@ -1010,7 +1012,7 @@ NULL `owner_set` means set before v10 (or by an older writer) and preserves toda | Work and reminders | `BotEngine` (`startWork`, `listWork`, `noteWork`, `addReminder`, `deliverDueReminders`), `src/mms/bots/grants/compile.ts` (`frontDeskManifest`) | | Subagents of work | `BotEngine` (`startSubagent`, `compileSubagent`, `holdOf`, `prepareSubagent`, `settleSubagent`, `acknowledgeReportStops`), `src/shared/bots/personal/subagentHold.ts` (the hold rule), `HarnessDriver.botHold`, `src/mms/bots/grants/compile.ts` (`subagentManifest`), `subagent_*` in `src/mms/run/mcp/appTools/bots.ts` | | Messages between bots (`bot_list`, `bot_send`) | `src/shared/bots/personal/botMessages.ts`, `BotEngine.sendBotMessage`, `receiveBotMessage`, `otherBots` and `unownedChainOf`, `BotStore.botMessageRowAfter`, `botMessageRowSince`, `botMessagesReceivedAfter`; other computers' bots: `src/mms/bridge/routed/otherComputersBots.ts`, `src/mms/protocol/otherComputersBotsPort.ts`, `RemoteBotRegistry`'s `FeedState` | -| Offered messages (`bot_offer`) | `src/shared/bots/personal/offers.ts`, `BotEngine.offerBotMessage`, `offerCardFor` in `RemoteBots.ts`, `BotRouter.offerSend` and `offerState`, `BotChatService.keepOffered`, `src/mms/bots/definitions/BotOfferAccessStore.ts`, the card's `BotOfferCard.tsx`; what the Mac hears: `BotEngine.recordOfferOutcome`, `BotRouter.tellOutcome`; Allow for this chat: `src/mms/bridge/routed/chatGrants.ts`, `BotRouter.grantOpen`, `grantEnd`, `grantState` and `observed` | +| Offered messages (`bot_offer`) | `src/shared/bots/personal/offers.ts`, `BotEngine.offerBotMessage`, `offerCardFor` in `RemoteBots.ts`, `BotRouter.offerSend` and `offerState`, `BotChatService.keepOffered`, `src/mms/bots/definitions/BotOfferAccessStore.ts`, the card's `BotOfferCard.tsx`; what the Mac hears: `BotEngine.recordOfferOutcome`, `BotRouter.tellOutcome`; Allow for this chat: `src/mms/bridge/routed/chatGrants.ts`, `BotRouter.grantOpen`, `grantEnd`, `grantState` and `observed`, the window's `BotChatGrant.tsx` | | Questions (`question_ask`, taps, moving on, work that waits on one) | `src/shared/bots/personal/questions.ts`, `BotEngine.askOwner`, `askFromWork`, `postReply`, `parkForQuestion`, `answerWorkInTx` and `relayAnswer`, `BotChatService.answerQuestion`, `answerWork` and `send`, `src/renderer/components/bots/BotQuestionReplies.tsx` | | Cards (`show_card`, a question's card) | `src/shared/bots/personal/cards.ts` (`cardOf`, `plainCard`), `src/mms/bots/chat/replyCards.ts` (`galleryPicture`), `BotEngine.showCard`, `BotChatProjection.shown` and `toMessage`, `src/renderer/components/bots/BotCards.tsx` | | Question follow-ups (nudges, defaults, late answers) | `questionFollowOf` (`questions.ts`), `src/mms/bots/activation/questionFollowUps.ts` (`nudgeSlot`), `BotEngine.armDue`, `followUpQuestion`, `nudge`, `goWithDefault` and `lateWorkAnswerInTx`, `BotChatService.workAnswerMode` | diff --git a/src/mms/bridge/routed/chatGrants.ts b/src/mms/bridge/routed/chatGrants.ts index 1345ed9b8..f4e764445 100644 --- a/src/mms/bridge/routed/chatGrants.ts +++ b/src/mms/bridge/routed/chatGrants.ts @@ -140,11 +140,12 @@ export class ChatGrants { return grant?.runs.has(run) ? grant : undefined } - /** Its window sent a message: its idle time starts again. */ + /** Its window sent a message: its idle time starts again, and windows read its new end. */ touch(grant: ChatGrant): void { if (this.current(keyOf(grant.node, grant.botId)) !== grant) return grant.activeAt = this.options.now() this.arm(grant) + this.options.changed(grant.node, grant.botId) } /** The chat's grant as window `window` sees it, with the names of its bots from `names`. */ diff --git a/src/renderer/components/bots/BotCards.tsx b/src/renderer/components/bots/BotCards.tsx index 2473182ae..af407e8ac 100644 --- a/src/renderer/components/bots/BotCards.tsx +++ b/src/renderer/components/bots/BotCards.tsx @@ -79,10 +79,10 @@ function GalleryCard({ card }: { card: BotChatGalleryCard }) { /** * A message's cards, in the order the bot made them; an automation it created as its own row (`BotAutomationRow`), and an - * offered message with its Send where it is for this computer (`BotOfferRow`; `messageId` and `seq` name its row, - * `remote` a bot of another computer). + * offered message with its Send where it is for this computer (`BotOfferRow`; `messageId` and `seq` name its row, `at` + * when it was made, `remote` a bot of another computer). */ -export function BotCards({ cards, botId, messageId, seq, remote = false }: { cards: readonly BotChatCard[]; botId?: string; messageId?: string; seq?: number; remote?: boolean }) { +export function BotCards({ cards, botId, messageId, seq, at, remote = false }: { cards: readonly BotChatCard[]; botId?: string; messageId?: string; seq?: number; at?: string; remote?: boolean }) { if (!cards.length) return null return
{cards.map((card, index) => { @@ -92,7 +92,7 @@ export function BotCards({ cards, botId, messageId, seq, remote = false }: { car if (card.type === 'checklist') return if (card.type === 'progress') return if (card.type === 'gallery') return - if (card.type === 'offer') return botId ? : null + if (card.type === 'offer') return botId ? : null return null })}
diff --git a/src/renderer/components/bots/BotChatGrant.tsx b/src/renderer/components/bots/BotChatGrant.tsx new file mode 100644 index 000000000..02b121429 --- /dev/null +++ b/src/renderer/components/bots/BotChatGrant.tsx @@ -0,0 +1,246 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { + BOT_GRANT_REFUSALS, + MAX_CHAT_GRANT_RECIPIENTS, + isBotGrantRefusal, + type BotChatGrantEnd, + type BotChatGrantView, + type BotOfferRecipient +} from '../../../shared/bots/personal/offers' +import { botsClient } from '../../stores/botsStore' +import { errorText, personalBotsEvents } from '../../services/personalBotsClient' +import { useComposerNotice, type ComposerNoticeProps } from '../ComposerNotice' +import { Check, Link2 } from '../../lib/icons' +import { useDismiss } from './BotEmoji' + +/** + * "Allow for this chat" (issue #2490 stage 2), in the chat of a bot of another computer: the composer's link button + * picks bots of this computer that bot may message, and allows the chat for them; while it is allowed, the line above + * the composer says who it can reach and for how long, with End access. Another window shows that line only. This + * computer keeps the grant and decides everything (`bots.remote.grantOpen`); the window only shows what it says. + */ + +export interface ChatGrantState { + grant: BotChatGrantView | undefined + /** Why the grant this window last saw open ended, when this window did not end it; until dismissed or it opens again. */ + ended: BotChatGrantEnd | undefined + dismiss(): void + set(next: BotChatGrantView): void +} + +/** + * The chat's grant as this window sees it, read again when it opens, changes or ends anywhere here, or the bot's + * computer comes back. This computer keeps the grant, so it is read while that computer is offline too: an end then + * (the connection dropped) is still told once it is back. + */ +export function useChatGrant(botId: string, live: boolean, reachable: boolean): ChatGrantState { + const [grant, setGrant] = useState(undefined) + const [ended, setEnded] = useState(undefined) + // The last open grant this window saw, to tell an end it did not ask for. + const seen = useRef(undefined) + // A read asked for later wins over one that answers late. + const asked = useRef(0) + const read = useCallback(() => { + const ask = ++asked.current + void botsClient().grantState(botId).then((next) => { if (asked.current === ask) setGrant(next) }, () => undefined) + }, [botId]) + useEffect(() => { + setGrant(undefined) + setEnded(undefined) + seen.current = undefined + if (!live) return + read() + return personalBotsEvents().onChanged?.((event) => { + if (event?.grant === botId || (event?.reread && (!event.botId || event.botId === botId))) read() + }) + }, [botId, live, read]) + // Back from offline: whether that computer takes grants is read again with it. + const wasReachable = useRef(reachable) + useEffect(() => { + const back = reachable && !wasReachable.current + wasReachable.current = reachable + if (live && back) read() + }, [live, reachable, read]) + useEffect(() => { + if (grant?.active) { + seen.current = grant + setEnded(undefined) + return + } + // Not read yet: what was seen stands. + if (!grant) return + const was = seen.current + seen.current = undefined + if (was && grant.ended && !(was.mine && grant.ended === 'ended')) setEnded(grant.ended) + }, [grant]) + const set = useCallback((next: BotChatGrantView) => { + asked.current += 1 + setGrant(next) + }, []) + const dismiss = useCallback(() => setEnded(undefined), []) + return { grant, ended, dismiss, set } +} + +/** "Alpha", "Alpha and Beta", "Alpha, Beta and Gamma", "Alpha, Beta and 3 more". */ +export function grantNames(recipients: readonly BotOfferRecipient[]): string { + const names = recipients.map((bot) => bot.name) + if (names.length <= 1) return names[0] ?? '' + if (names.length <= 3) return `${names.slice(0, -1).join(', ')} and ${names.at(-1)}` + return `${names.slice(0, 2).join(', ')} and ${names.length - 2} more` +} + +/** Why access ended, in a few words, for the line a window shows once it does. */ +const ENDED_LINES: Record = { + ended: 'Access was ended', + left: 'The window that allowed it left the chat', + closed: 'The window that allowed it closed', + idle: 'Nothing was sent for 10 minutes', + expired: 'The hour is up', + offline: 'The connection dropped', + private: 'A bot it could message was made private', + blocked: 'That computer was blocked', + removed: 'That bot is no longer shared here' +} + +/** Whole minutes left until `endsAt`, at least 1 while it is open. */ +function minutesLeft(endsAt: string | undefined, now: number): number | undefined { + const at = endsAt ? Date.parse(endsAt) : Number.NaN + return Number.isFinite(at) ? Math.max(1, Math.ceil((at - now) / 60_000)) : undefined +} + +/** The time now, again every 30 seconds while `on`: a minute count that moves calmly. */ +function useMinuteClock(on: boolean): number { + const [now, setNow] = useState(() => Date.now()) + useEffect(() => { + if (!on) return + setNow(Date.now()) + const timer = setInterval(() => setNow(Date.now()), 30_000) + return () => clearInterval(timer) + }, [on]) + return now +} + +/** + * The line above the composer while the chat is allowed (who, time left, End access in the window that allowed it, + * "Allowed in another window" in any other), and once after it ends for a reason this window did not give. + */ +export function BotChatGrantNotice({ botName, state, onEnd }: { botName: string; state: ChatGrantState; onEnd(): Promise }) { + const { grant, ended, dismiss } = state + const active = grant?.active === true + const now = useMinuteClock(active) + const [ending, setEnding] = useState(false) + const end = async () => { + setEnding(true) + try { + await onEnd() + } finally { + setEnding(false) + } + } + const icon =