diff --git a/docs/bots.md b/docs/bots.md index 9f2f737e4..81655d6c9 100644 --- a/docs/bots.md +++ b/docs/bots.md @@ -366,14 +366,25 @@ 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: 1` to `bots.chat.send` (a version 3 row; 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`). +- **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. -- **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`). A second Send while one runs is `offer_busy`. +- **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. The Mac's row is not told the outcome. -- **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 leaves that computer's switch alone. +- **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. +- **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). - **A bot that moves** to another computer takes its offers without the device each was for (`offerCardFor` in the bundle), so there they wait for no Send. -- **Not yet.** Offers don't expire. A picture's path in the words shows that picture in the receiving bot's chat on the PC, as in any message between bots; nothing leaves the PC. +- **Pictures.** A picture's path in the words shows that picture in the receiving bot's chat on the PC, as in any message between bots; nothing leaves the PC. + +#### Allow for this chat + +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. + +- **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. +- **#2052.** A grant adds nothing a window could not already do with Send, and only a client that says it is a window (`clientType: 'gui'`) opens one. Binding that to a real window is #2052's. ## Asks @@ -989,7 +1000,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` | +| 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` | | 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/main/ipc/registerGuiIpc.ts b/src/main/ipc/registerGuiIpc.ts index 3c4e32ace..67f4426c6 100644 --- a/src/main/ipc/registerGuiIpc.ts +++ b/src/main/ipc/registerGuiIpc.ts @@ -31,7 +31,7 @@ import { SPACES_LOCAL_METHODS } from '../../shared/spaces/local' import { BOTS_LOCAL_METHODS } from '../../shared/bots/space/local' import { BOTS_ELSEWHERE_METHODS, BOTS_PERSONAL_V2_METHODS, BOTS_WORK_METHODS } from '../../shared/bots/personal/methods' import { BOT_DEVICE_METHODS, BOT_OFFERS_SWITCH_METHOD } from '../../shared/bots/personal/deviceAccess' -import { BOT_OFFER_METHODS } from '../../shared/bots/personal/offers' +import { BOT_GRANT_METHODS, BOT_OFFER_METHODS } from '../../shared/bots/personal/offers' import { BOT_MARK_METHODS } from '../../shared/bots/personal/marks' import { BOTS_BROWSER_METHODS } from '../../shared/bots/personal/browser' import type { BotChatMessage } from '../../shared/bots/personal/chat' @@ -316,6 +316,7 @@ export const PLATFORM_REQUEST_METHODS: ReadonlySet = new ...BOT_DEVICE_METHODS, BOT_OFFERS_SWITCH_METHOD, ...BOT_OFFER_METHODS, + ...BOT_GRANT_METHODS, ...BOTS_BROWSER_METHODS, ...AUTOMATIONS_METHODS, ...SECRET_METHODS, diff --git a/src/mms/bots/activation/BotEngine.ts b/src/mms/bots/activation/BotEngine.ts index e5305067d..a9ac5c8aa 100644 --- a/src/mms/bots/activation/BotEngine.ts +++ b/src/mms/bots/activation/BotEngine.ts @@ -130,7 +130,7 @@ import { botTaskItems } from './botTasks' import type { BackgroundJobService } from '../../background/BackgroundJobService' import { BotWatchers, DEFAULT_WATCHER_MINUTES, MAX_WATCHER_COMMAND_CHARS, MAX_WATCHER_MINUTES, watcherMatchProblem, type WatcherEnd, type WatcherSpec, type WatcherView } from '../watchers' import { lockedEnv } from '../../harness/env' -import { BOT_OFFERS_VERSION, MAX_OFFERS_PER_TURN, MAX_OFFER_TO_CHARS, OFFER_ROW_PREFIX, offerMessageProblem, offerRowText, plainOfferName, type BotOfferCard } from '../../../shared/bots/personal/offers' +import { BOT_OFFERS_REPORTED, MAX_OFFERS_PER_TURN, MAX_OFFER_TO_CHARS, OFFER_ROW_PREFIX, isOffersTaken, isRunToken, offerMessageProblem, offerRowText, plainOfferName, type BotOfferCard, type BotOfferOutcome } from '../../../shared/bots/personal/offers' import { MAX_BOT_MESSAGE_CHARS, MAX_BOT_MESSAGES_UNANSWERED_BY_OWNER, botAddressName, botMessageInput, botMessageKey, botMessageRowId, botMessageRowText, botNamed, otherComputerNote, type BotMessageSender, type OtherComputerBotsStatus } from '../../../shared/bots/personal/botMessages' import { qualifyId } from '../../../shared/threadRef' import { OtherComputerBotRefusal, type OtherComputerBotMessage, type OtherComputersBotsPort } from '../../protocol/otherComputersBotsPort' @@ -236,12 +236,14 @@ function requestedMessageId(sender: string, requestKey: string): string { /** * The device to keep on a chat turn the owner's message starts (`deviceToSave`), with `offers` when that device takes * offered messages: kept on that turn's own trigger alone, never with what the turn sets up (a reminder, a schedule, - * work), so only a chat turn the owner started from that device offers it a message (`offerBotMessage`). + * work), so only a chat turn the owner started from that device offers it a message (`offerBotMessage`). The run token of + * a message sent under that device's chat grant goes with `offers: 2` alone; the turn's offers carry it back. */ function turnOwnerToSave(owner: BotOwnerTurn | undefined): BotOwnerTurn | undefined { const saved = deviceToSave(owner) if (!saved) return undefined - return saved.node && !saved.readOnly && owner?.offers === BOT_OFFERS_VERSION ? { ...saved, offers: BOT_OFFERS_VERSION } : saved + if (!saved.node || saved.readOnly || !isOffersTaken(owner?.offers)) return saved + return { ...saved, offers: owner.offers, ...(owner.offers === BOT_OFFERS_REPORTED && isRunToken(owner.run) ? { run: owner.run } : {}) } } /** The hold of a message held under its id: one per message, so a retry never holds it twice. */ @@ -11893,7 +11895,7 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { if (!device?.node || device.readOnly) throw new BotEngineError('offer_not_here', "Your owner didn't write this from another of their computers, so there is nowhere to offer it. Nothing was offered: use bot_send for your owner's bots you can reach, or tell your owner.") const computer = this.deviceName(device.node) - if (owner?.offers !== BOT_OFFERS_VERSION) + if (!isOffersTaken(owner?.offers)) throw new BotEngineError('offer_unsupported', `${computer} can't take offered messages: it needs a newer Mousse, or it is a phone. Nothing was offered: tell your owner instead.`) // The device must still reach this bot: one taken off it, or blocked here, is offered nothing. if (this.deviceLimitNow(row) === null) @@ -11913,12 +11915,44 @@ export class BotEngine implements BotTurnDispatcher, BotThreads { } if (this.store.countMessagesWithPrefix(row.id, OFFER_ROW_PREFIX) >= MAX_OFFERS_PER_TURN) throw new BotEngineError('invalid_params', `You offered ${MAX_OFFERS_PER_TURN} messages in this turn already. Nothing more was offered: put what is left in one of them next time.`) - const card: BotOfferCard = { type: 'offer', offerId, message, ...(to ? { to } : {}), computer, node: device.node! } + // Stamped from the turn, never from the bot: the run token of the message that started it (a grant's, on the device + // it is for), and whether that device will say what becomes of it. + const reports = owner!.offers === BOT_OFFERS_REPORTED + const card: BotOfferCard = { + type: 'offer', offerId, message, ...(to ? { to } : {}), computer, node: device.node!, + ...(reports && isRunToken(owner!.run) ? { run: owner!.run } : {}), + state: reports ? 'queued' : 'unsupported' + } this.chat.post({ id, botId, author: 'bot', kind: 'notice', text: offerRowText(computer), cards: [card], activationId: row.id, lane: 'chat' }) return { offerId, computer } }) } + /** + * `bots.offers.outcome` (issue #2490): what became of offer `offerId` of bot `botId`, as device `from` reports it. Only + * the device the offer was made for is heard; any other is told there is no such offer, as for a guess. Kept on the + * offer's card (`state`, and for `delivered` the bot's name there) and published again, so the chat shows it; it + * starts nothing. Sent and expired are final: a later report (a late retry of `busy`) never takes them back. The same + * report again changes nothing. + */ + recordOfferOutcome(input: { botId: string; offerId: string; from: string; state: BotOfferOutcome; to?: string }): { state: string } { + const id = `${OFFER_ROW_PREFIX}${input.offerId}` + return this.store.db.transaction(() => { + const row = this.store.message(id) + const cards = row?.botId === input.botId ? row.cards ?? [] : [] + const index = cards.findIndex((card) => card.type === 'offer' && card.offerId === input.offerId && card.node === input.from) + if (index < 0) throw new BotEngineError('offer_not_found', 'This bot has no such offer.') + const card = cards[index] as BotOfferCard + if (card.state === 'delivered' || card.state === 'expired' || card.state === input.state) return { state: card.state } + const sentTo = input.state === 'delivered' && input.to ? plainOfferName(input.to) : undefined + const { sentTo: _was, ...rest } = card + const next: BotOfferCard = { ...rest, state: input.state, ...(sentTo ? { sentTo } : {}), stateAt: this.store.now() } + this.store.setMessageCards(id, cards.map((each, n) => (n === index ? next : each))) + this.chat.republish(id) + return { state: input.state } + }) + } + /** A device's name as this computer knows it (Settings, Devices), for a bot's words; never its id. */ private deviceName(node: string): string { let name: string | undefined diff --git a/src/mms/bots/chat/BotChatService.ts b/src/mms/bots/chat/BotChatService.ts index bc94275cd..c83b0b9cb 100644 --- a/src/mms/bots/chat/BotChatService.ts +++ b/src/mms/bots/chat/BotChatService.ts @@ -1,4 +1,4 @@ -import { BOT_OFFER_REFUSALS, MAX_OFFERS_KEPT_PER_HOUR, OFFERED_ROW_PREFIX, offeredRowText, type BotOfferDelivered, type BotOfferRecipient, type BotOfferRefusal } from '../../../shared/bots/personal/offers' +import { BOT_OFFER_REFUSALS, BOT_OFFERS_REPORTED, MAX_OFFERS_KEPT_PER_HOUR, OFFERED_ROW_PREFIX, isOffersTaken, isRunToken, offeredRowText, type BotOfferDelivered, type BotOfferOutcome, type BotOfferRecipient, type BotOfferRefusal } from '../../../shared/bots/personal/offers' import type { BotOfferAccessStore } from '../definitions/BotOfferAccessStore' import { PageChecks } from '../pageChecks' import { botScheduleProblem } from '../../scheduled/botJobs' @@ -259,7 +259,7 @@ interface BotChatSendInput { clientRequestId: string replyTo?: string spoken?: true - from?: { limit: PermissionMode; node?: string; offers?: 1 } + from?: { limit: PermissionMode; node?: string; offers?: 1 | 2; run?: string } } export class BotChatService { @@ -336,7 +336,8 @@ export class BotChatService { if (!this.engine.botIds().includes(input.to)) refuse('recipient_gone') if (!this.options.offerAccess?.open(input.to)) refuse('recipient_closed') const since = new Date(Date.parse(this.store.now()) - 60 * 60_000).toISOString() - if (this.store.countRowsSince(OFFERED_ROW_PREFIX, since) >= MAX_OFFERS_KEPT_PER_HOUR) refuse('too_many') + // Counted from the receipts, so clearing the chat a message went to doesn't make room for more. + if (this.store.countReceiptsSince(OFFER_RECEIPTS, since) >= MAX_OFFERS_KEPT_PER_HOUR) refuse('too_many') const posted = this.engine.chat.post({ id: input.rowId, botId: input.to, @@ -375,7 +376,23 @@ export class BotChatService { .sort((a, b) => a.name.localeCompare(b.name)) } - private botName(botId: string): string { + /** + * `bots.offers.outcome`: what became of offer `offerId` of bot `botId`, as device `from` reports it, the device it was + * made for alone (`BotEngine.recordOfferOutcome`). Kept on the offer's card and shown in the chat; nothing starts. + */ + offerOutcome(input: { botId: string; offerId: string; from: string; state: BotOfferOutcome; to?: string }): { state: string } { + this.engine.definitionOf(input.botId) + return this.engine.recordOfferOutcome(input) + } + + /** Whether bot `botId` here takes offered messages now (`open`), is here but does not (`closed`), or is not here. */ + offerRecipientState(botId: string): 'open' | 'closed' | 'gone' { + if (!this.engine.botIds().includes(botId)) return 'gone' + return this.options.offerAccess?.open(botId) ? 'open' : 'closed' + } + + /** A bot's name here, for words about it; `a bot` for one that is gone. */ + botName(botId: string): string { try { return this.engine.definitionOf(botId).name } catch { @@ -837,8 +854,11 @@ export class BotChatService { const key = `${tap ? 'answer' : 'chat'}:${input.clientRequestId}` // The owner wrote this: the turn it starts or continues may start, message and stop their threads, held to the // limit of the device it came from (`BotOwnerTurn`; absent: this computer's own window). - // A device that takes offered messages says so; a turn it starts may offer it one (`bot_offer`). - const owner: BotOwnerTurn = input.from ? { limit: input.from.limit, ...(input.from.node ? { node: input.from.node, ...(input.from.offers === 1 ? { offers: 1 as const } : {}) } : {}) } : {} + // A device that takes offered messages says so; a turn it starts may offer it one (`bot_offer`), carrying back the + // run token of a message from the window that holds that chat's grant. + const from = input.from + const offers = from?.node && isOffersTaken(from.offers) ? { offers: from.offers, ...(from.offers === BOT_OFFERS_REPORTED && isRunToken(from.run) ? { run: from.run } : {}) } : {} + const owner: BotOwnerTurn = from ? { limit: from.limit, ...(from.node ? { node: from.node, ...offers } : {}) } : {} let messageId: string let prompt = '' let refused: BotEngineError | undefined @@ -886,6 +906,8 @@ export class BotChatService { // A message that joins a turn is read by it as it answers, or with its request: it starts no turn of its own. // Whatever it does, the chat turn running now stops its calls known to only read (`ChatQuickCalls.steered`). this.engine.ownerWroteInTx(input.botId, joined) + // A turn under a chat's grant keeps its run token only while every message in it carries one. + if (joined || target.continues) this.store.narrowOwnerRun(joined ?? target.activationId, owner.run) if (joined) this.engine.joinChatTurnInTx(input.botId, joined, posted.id, prompt) else if (!target.continues) refused = this.engine.queueChatInTx(input.botId, key, prompt, target.activationId, owner, { spoken: input.spoken }) // A message from another device that continues a turn waiting at a wall holds the rest of that turn to the diff --git a/src/mms/bots/definitions/BotOfferAccessStore.ts b/src/mms/bots/definitions/BotOfferAccessStore.ts index 9c1bacc83..407b8ccd8 100644 --- a/src/mms/bots/definitions/BotOfferAccessStore.ts +++ b/src/mms/bots/definitions/BotOfferAccessStore.ts @@ -43,6 +43,23 @@ const isChoice = (value: unknown): value is Choice => value === 'open' || value export class BotOfferAccessStore { private state?: State readonly path: string + private readonly closedListeners = new Set<(botId: string) => void>() + + /** Hears each bot closed here (`set(bot, false)`), after it is written: a chat grant naming it ends (issue #2490). */ + onClosed(listener: (botId: string) => void): () => void { + this.closedListeners.add(listener) + return () => this.closedListeners.delete(listener) + } + + private closed(botId: string): void { + for (const listener of [...this.closedListeners]) { + try { + listener(botId) + } catch { + // One listener's failure does not keep the others from hearing. + } + } + } constructor( /** `/bots`. */ @@ -67,13 +84,14 @@ export class BotOfferAccessStore { // Nothing of what was stored can be trusted: every other bot stays closed until the owner opens it. this.putAside() this.write({ version: 1, others: 'closed', bots: { [botId]: choice } }) - return + } else if ((state.bots.get(botId) ?? state.others) !== choice) { + const bots: Record = Object.fromEntries(state.bots) + if (choice === state.others) delete bots[botId] + else bots[botId] = choice + this.write({ version: 1, others: state.others, bots }) } - if ((state.bots.get(botId) ?? state.others) === choice) return - const bots: Record = Object.fromEntries(state.bots) - if (choice === state.others) delete bots[botId] - else bots[botId] = choice - this.write({ version: 1, others: state.others, bots }) + // Told whether or not it was closed before: a grant that still names it ends either way. + if (!open) this.closed(botId) } /** Takes bots that are no longer there off the file (`known` says which exist). Nothing is written when nothing changes. */ diff --git a/src/mms/bots/store/BotStore.ts b/src/mms/bots/store/BotStore.ts index fd4b80f58..a8b71c651 100644 --- a/src/mms/bots/store/BotStore.ts +++ b/src/mms/bots/store/BotStore.ts @@ -1829,6 +1829,20 @@ export class BotStore { return this.run('UPDATE bot_activations SET trigger_json = ? WHERE id = ?', JSON.stringify(trigger), id) > 0 } + /** + * An owner's message joined or continued chat activation `id` (issue #2490 stage 2). The turn keeps its own run token, + * never another: a message with one (its window's grant, or a newer grant's) changes nothing, so a grant opened later + * never takes over a turn an ended one started. A message with none (another window, another device) takes it off, + * so nothing the turn offers from then on is sent on its own. Inside the caller's transaction. + */ + narrowOwnerRun(id: string, run: string | undefined): void { + if (run !== undefined) return + const row = this.activation(id) + if (!row || row.trigger.kind !== 'manual' || row.trigger.owner?.run === undefined) return + const { run: _dropped, ...owner } = (row.trigger as { owner: BotOwnerTurn }).owner + this.run('UPDATE bot_activations SET trigger_json = ? WHERE id = ?', JSON.stringify({ ...row.trigger, owner }), id) + } + /** A running activation waits for the internet, or no longer does. False when it is not running (or did not wait). */ setOffline(id: string, offline: boolean): boolean { return offline @@ -2583,6 +2597,11 @@ export class BotStore { return row ? messageOf(row) : undefined } + /** Replaces a message's cards (an offer's outcome, issue #2490): Mousse's own cards only, never the bot's. */ + setMessageCards(messageId: string, cards: readonly BotCard[]): boolean { + return this.run('UPDATE bot_messages SET cards_json = ? WHERE id = ?', cards.length ? JSON.stringify(cards) : null, messageId) > 0 + } + /** Sets the owner's reaction on a message (one per message: a new one replaces it), or removes it (`null`). */ setOwnerReaction(messageId: string, emoji: string | null, at: string): boolean { return this.run('UPDATE bot_messages SET owner_reaction = ?, owner_reaction_at = ? WHERE id = ?', emoji, emoji === null ? null : at, messageId) > 0 @@ -3122,11 +3141,11 @@ export class BotStore { } /** - * How many chat rows of any bot whose id starts with `prefix` were kept at or after `since` (ISO): the offered - * messages this computer kept in the last hour. + * How many receipts kept under `owner` (`bot_memory_state` rows whose value says `at`) were kept at or after `since` + * (ISO): the offered messages this computer kept in the last hour, whether their chat rows are still there or not. */ - countRowsSince(prefix: string, since: string): number { - return num(this.get('SELECT COUNT(*) AS n FROM bot_messages WHERE substr(id, 1, ?) = ? AND at >= ?', prefix.length, prefix, since)?.n) ?? 0 + countReceiptsSince(owner: string, since: string): number { + return num(this.get("SELECT COUNT(*) AS n FROM bot_memory_state WHERE bot_id = ? AND json_extract(value, '$.at') >= ?", owner, since)?.n) ?? 0 } /** How many of bot `botId`'s chat rows whose id starts with `prefix` came after row `afterSeq`. */ diff --git a/src/mms/bridge/BridgeProfileService.ts b/src/mms/bridge/BridgeProfileService.ts index 9df18e814..7b898e348 100644 --- a/src/mms/bridge/BridgeProfileService.ts +++ b/src/mms/bridge/BridgeProfileService.ts @@ -639,7 +639,9 @@ export class BridgeProfileService { devices: () => botReach.devices(), // The account's devices whether connected now or not: a choice sent from another device may name only these. known: () => this.peers.accountDevices(), - changed: (botId) => services.personalBots?.reachChanged(botId) + changed: (botId) => services.personalBots?.reachChanged(botId), + // Make private from a device closes the bot to offered messages here (`offers: false`); a device never opens it. + offers: services.botOfferAccess }, // The bots feed and one bot's chat, read by the device that opened them alone. openStream: async (reader, stream, caller) => { @@ -877,6 +879,7 @@ export class BridgeProfileService { marks: services.botMarks, onTransferred: () => void this.remoteBots.reconcile(), blocked: (node) => rt.policy.isBlocked(node), + offersClosed: (listener) => services.botOfferAccess.onClosed(listener), online: (node) => this.router.isOnline(node), name: (node) => this.router.computer(node).name, self: () => rt.identity.self()?.node, diff --git a/src/mms/bridge/remote/RemoteBots.ts b/src/mms/bridge/remote/RemoteBots.ts index 05e5a75f6..9372c59cd 100644 --- a/src/mms/bridge/remote/RemoteBots.ts +++ b/src/mms/bridge/remote/RemoteBots.ts @@ -1,6 +1,6 @@ import { botActionRefusalText, isBotActionRefusalCode } from '../../../shared/bots/personal/actionRefusal' import { MAX_BOT_MESSAGE_CHARS } from '../../../shared/bots/personal/botMessages' -import { BOT_OFFERS_VERSION, offerCardFor } from '../../../shared/bots/personal/offers' +import { BOT_OFFERS_REPORTED, MAX_OFFER_TO_CHARS, isBotOfferOutcome, isOfferId, isOffersTaken, isRunToken, offerCardFor, type BotOfferOutcome } from '../../../shared/bots/personal/offers' import { NetError, isBlobId, type BlobId, type NodeCapability, type NodeId } from '../../../shared/net' import { isSendId, isStageId, type RoutedReply } from '../../../shared/bridge/routed' import type { RoutedStaging } from '../routed/staging' @@ -309,10 +309,17 @@ export function validateRemoteBotParams(method: RemoteBotMethod, value: unknown) // Files alone are a message too. ok(typeof p.text === 'string' && p.text.length <= REMOTE_BOT_MESSAGE_BYTES && Buffer.byteLength(p.text) <= REMOTE_BOT_MESSAGE_BYTES && (staged !== undefined || sent !== undefined || text(p.text, REMOTE_BOT_MESSAGE_BYTES))) if (p.replyTo !== undefined) ok(text(p.replyTo, 200)) - // The sending computer takes offered messages (its router's mark, version 3). - if (p.offers !== undefined) ok(p.offers === BOT_OFFERS_VERSION) + // The sending computer takes offered messages (its router's mark, version 3), and reports what becomes of them + // (version 4); a message from the window that holds its chat grant carries its run token, with that mark only. + if (p.offers !== undefined) ok(isOffersTaken(p.offers)) + if (p.run !== undefined) ok(p.offers === BOT_OFFERS_REPORTED && isRunToken(p.run)) break } + // What became of an offer, from the computer it is for (its router, never a window). + case 'bots.offers.outcome': + ok(isOfferId(p.offerId) && isBotOfferOutcome(p.state)) + if (p.to !== undefined) ok(p.state === 'delivered' && text(p.to, MAX_OFFER_TO_CHARS)) + break // A piece of work, or a background command (a watcher, `rem_…`): `/stop` and its line's Stop name either. The bot's // computer stops only one of the bot the call names (`BotEngine.stopWork`). case 'bots.work.stop': @@ -372,6 +379,8 @@ export function validateRemoteBotParams(method: RemoteBotMethod, value: unknown) break case 'bots.devices.set': ok(botDeviceAccessProblem(p.access) === undefined) + // Make private from that device (version 2): offered messages close too. A device never opens them here. + if (p.offers !== undefined) ok(p.offers === false) break case 'bots.reminders.snooze': ok(text(p.messageId, 200) && ['10m', '1h', 'tomorrow'].includes(p.choice as string)) @@ -808,7 +817,7 @@ export function remoteBotMethods(options: { * Absent: both refuse, as on a computer that keeps no such choice. `known`: the account's devices now, connected or * not, which a choice sent by another device may name (undefined while they can't be read: not checked then). */ - devices?: Pick & { known?(): readonly string[] | undefined } + devices?: Pick & { known?(): readonly string[] | undefined } /** * The profile's applets, where each bot's thread publishes them (`AppletStore`): what `bots.applets.*` read and save, * only for an applet a message of the named bot shows. Absent: those rows answer as for an applet that is not there. @@ -1258,8 +1267,14 @@ export function remoteBotMethods(options: { clientRequestId: p.clientRequestId as string, ...(typeof p.replyTo === 'string' ? { replyTo: p.replyTo } : {}), // The device it came from: a message still queued when the device loses the bot is not delivered. One whose - // router said it takes offered messages: a turn it starts may offer it one (`bot_offer`). - from: { limit: limitOf(context), node: context.caller.node, ...(p.offers === BOT_OFFERS_VERSION ? { offers: BOT_OFFERS_VERSION } : {}) } + // router said it takes offered messages: a turn it starts may offer it one (`bot_offer`), carrying back the + // run token of a message from the window that holds that chat's grant. + from: { + limit: limitOf(context), + node: context.caller.node, + ...(isOffersTaken(p.offers) ? { offers: p.offers } : {}), + ...(p.offers === BOT_OFFERS_REPORTED && isRunToken(p.run) ? { run: p.run } : {}) + } })) kept = true } finally { @@ -1298,6 +1313,15 @@ export function remoteBotMethods(options: { refusal(error) } }), + // What became of an offer of this bot's, from the device it was made for (that device's router, never a window): kept + // on the offer's card and shown in the chat. Any other device is told the offer is not there. + method('bots.offers.outcome', async (p, port, context) => { + try { + return port.offerOutcome({ botId: botId(p), offerId: p.offerId as string, from: context.caller.node, state: p.state as BotOfferOutcome, ...(typeof p.to === 'string' ? { to: p.to } : {}) }) + } catch (error) { + refusal(error) + } + }), method('bots.chat.stop', async (p, port) => port.chatStop(botId(p))), method('bots.work.stop', async (p, port) => { try { @@ -1449,8 +1473,10 @@ export function remoteBotMethods(options: { method( 'bots.devices.set', async (p, _port, context) => { - // Checked before the call was taken (`checkChosen`): saved as it is. + // Checked before the call was taken (`checkChosen`): saved as it is. Make private from that device closes the + // bot to offered messages first (`offers: false`), so it never shows private here while it still takes them. const source = devicesOf() + if (p.offers === false) source.offers?.set(botId(p), false) source.store.set(botId(p), keepingCaller(p.access as BotDeviceAccess, context.caller.node)) source.changed?.(botId(p)) return devicesView(botId(p), context.caller.node) diff --git a/src/mms/bridge/routed/BotRouter.ts b/src/mms/bridge/routed/BotRouter.ts index ba6f949ad..dd1c98513 100644 --- a/src/mms/bridge/routed/BotRouter.ts +++ b/src/mms/bridge/routed/BotRouter.ts @@ -40,20 +40,31 @@ import type { SendValue } from './sendUpload' import type { RemoteBotViews } from './remoteBotViews' import { isCount, isWatchId } from '../../browser/viewer/watchedParams' import { + BOT_GRANT_REFUSALS, + BOT_GRANT_SEND_VERSION, BOT_OFFERS_KEY, + BOT_OFFERS_REPORTED, BOT_OFFERS_SEND_VERSION, BOT_OFFERS_VERSION, BOT_OFFER_REFUSALS, + BOT_OFFER_RUN_KEY, + MAX_CHAT_GRANT_RECIPIENTS, MAX_OFFER_STATE_IDS, OFFERED_ROW_PREFIX, isBotOfferRefusal, isOfferId, + offerExpired, offerMessageProblem, + type BotChatGrantEnd, + type BotGrantApi, + type BotGrantRefusal, type BotOfferApi, type BotOfferCard, + type BotOfferOutcome, type BotOfferRefusal } from '../../../shared/bots/personal/offers' import { keptOfferOf } from '../../../shared/bots/personal/cards' +import { ChatGrants, type ChatGrant } from './chatGrants' /** * The id of the row an offered message is kept under here (`BotChatService.keepOffered`): one per offer of one bot of one @@ -66,11 +77,39 @@ export function offeredRowId(node: string, botId: string, offerId: string): stri /** A refusal of an offered message's Send, before anything was kept: its code, and the words the window shows. */ const offerRefused = (code: BotOfferRefusal, details?: Record): DomainRpcError => new DomainRpcError(code, BOT_OFFER_REFUSALS[code], { reason: code, ...details }) +/** A refusal to open a chat grant: its code, and the words the window shows. */ +const grantRefused = (code: BotGrantRefusal): DomainRpcError => new DomainRpcError(code, BOT_GRANT_REFUSALS[code], { reason: code }) + +/** An offer found in a bot's chat: its card as this computer was told it, and when the bot's computer made it. */ +interface FoundOffer { + card: BotOfferCard + at: string +} + +/** + * The one bot of `grant` an offer names (`to`, by that bot's name here, in any case and spacing), when it takes offered + * messages now (`nameOf` names only those); undefined when it names none of them, or two. + */ +function grantRecipient(grant: ChatGrant, to: string | undefined, nameOf: (botId: string) => string | undefined): string | undefined { + const fold = (name: string): string => name.replace(/\s+/g, ' ').trim().toLowerCase() + const wanted = to ? fold(to) : '' + if (!wanted) return undefined + const matches = grant.recipients.filter((id) => { + const name = nameOf(id) + return name !== undefined && fold(name) === wanted + }) + return matches.length === 1 ? matches[0] : undefined +} /** How long a read that has a copy here waits for the bot's computer before it answers from the copy, marked stale. */ const READ_WAIT_MS = 4_000 /** Keys a window sends that name this computer's own binding; the bot's computer has its own. */ const LOCAL_BINDING_KEYS = new Set(['profileId', 'expectedProfileId']) +/** How many times a lost outcome report is told on its own, the first retry this long after (then 4× longer each). */ +const OUTCOME_TRIES = 5 +const OUTCOME_RETRY_MS = 30_000 +/** Owner's messages whose run token a resend reuses (the newest). */ +const MAX_SENT_RUNS = 512 /** * Errors of a transfer's commit call that leave open whether the target committed: its reply was lost, the link went, @@ -187,7 +226,9 @@ export interface BotRouterOptions { client: Pick /** The other computers' bots as this one lists them, with the copies of their chats. */ registry: Pick & - Partial> & { chats: Pick } + Partial> & { + chats: Pick & Partial> + } /** The copies here of the files those bots' chats show. Absent: none show, and none are kept of what is sent. */ files?: Pick /** Those bots' applets, read and saved there, with the copies kept here. Absent: none open. */ @@ -218,6 +259,11 @@ export interface BotRouterOptions { onTransferred?: () => void /** Whether this computer blocked `node` (Settings, Devices): no offered message of its bots is sent here. */ blocked?(node: NodeId): boolean + /** Hears when a bot of this computer stops taking offered messages (Make private, About's switch): its grants end. */ + offersClosed?(listener: (botId: string) => void): () => void + /** Tests: the clock and the times of chat grants. */ + now?(): number + grantTimes?: { idleMs: number; maxMs: number } } /** @@ -253,6 +299,9 @@ export class BotRouter implements BotRouterPort { /** Window bindings whose end is already watched. */ private readonly watched = new WeakSet() private readonly offClosed?: () => void + /** The chat grants of this computer ("Allow for this chat"), in memory alone. */ + readonly grants: ChatGrants + private readonly offGrantWatch: Array<() => void> = [] constructor(private readonly options: BotRouterOptions) { this.attached = new AttachedBots({ @@ -264,7 +313,27 @@ export class BotRouter implements BotRouterPort { onChange: (listener) => options.registry.onChange(listener), emit: options.emit }) - this.offClosed = options.onConnectionClosed?.((id) => this.attached.dropLeases(id)) + this.grants = new ChatGrants({ + now: () => this.now(), + // Windows read the grant again (`bots.remote.grantState`); the event already tells them the bots changed. + changed: (node, botId) => options.emit('bots.changed', { remote: true, grant: qualifyId(node, botId) }), + ended: (grant) => this.expireGrantOffers(grant), + ...(options.grantTimes ? { idleMs: options.grantTimes.idleMs, maxMs: options.grantTimes.maxMs } : {}) + }) + this.offClosed = options.onConnectionClosed?.((id) => { + this.attached.dropLeases(id) + this.grants.endWhere((grant) => grant.window === id, 'closed') + }) + // A grant ends the moment its computer is blocked, removed, no longer lists the bot, or can't be reached. + this.offGrantWatch.push(options.registry.onChange(() => this.checkGrants())) + const offOffers = options.offersClosed?.((botId) => this.grants.endWhere((grant) => grant.recipients.includes(botId), 'private')) + if (offOffers) this.offGrantWatch.push(offOffers) + const offObserve = options.registry.chats.observe?.((node, botId, messages) => this.observed(node, botId, messages)) + if (offObserve) this.offGrantWatch.push(offObserve) + } + + private now(): number { + return this.options.now?.() ?? Date.now() } computer(node: NodeId): ComputerRef { @@ -574,11 +643,28 @@ export class BotRouter implements BotRouterPort { // A person's call: marked here, for a window's call only (the command line answers no held chain and reads or edits no // bot's system instructions), and never taken from the caller. const person = PERSON_METHODS.has(method) - const owner = this.ownerParams(method, row.remote, person ? withoutKey(given, BOT_PERSON_KEY) : given, ref?.id, [...(person ? [BOT_PERSON_KEY] : []), ...(sending ? [BOT_OFFERS_KEY] : [])]) + const owner = this.ownerParams(method, row.remote, person ? withoutKey(given, BOT_PERSON_KEY) : given, ref?.id, [...(person ? [BOT_PERSON_KEY] : []), ...(sending ? [BOT_OFFERS_KEY, BOT_OFFER_RUN_KEY] : [])]) if (person && ctx.connection.clientType === 'gui') owner[BOT_PERSON_KEY] = 'person' // This computer takes offered messages (issue #2490): said with the owner's message to a bot's computer that takes the - // word (`bots.chat.send` version 3), so a chat turn it starts may offer one here. Never taken from the caller. - if (sending && (await this.takesOffers(node))) owner[BOT_OFFERS_KEY] = BOT_OFFERS_VERSION + // word (`bots.chat.send` version 3), so a chat turn it starts may offer one here; from version 4 it also hears what + // becomes of them, and a message from the window holding the chat's grant carries a run token the turn's offers + // carry back. Never taken from the caller. + if (sending && ref) { + const version = await this.sendVersion(node, 'bots.chat.send') + if (version >= BOT_GRANT_SEND_VERSION) { + owner[BOT_OFFERS_KEY] = BOT_OFFERS_REPORTED + const run = this.runFor(node, ref.id, ctx.connection.id, params.clientRequestId) + if (run) owner[BOT_OFFER_RUN_KEY] = run + } else if (version >= BOT_OFFERS_SEND_VERSION) owner[BOT_OFFERS_KEY] = BOT_OFFERS_VERSION + } + // Make private from this window (`offers: false`): the bot takes no offered messages on its computer either, when + // that computer takes the word (`bots.devices.set` version 2); an older one keeps them as they were. + if (method === 'bots.devices.set' && owner.offers !== undefined) { + if (owner.offers !== false) throw new DomainRpcError('invalid_params', 'offers is false: Make private closes them.') + if ((await this.sendVersion(node, method)) < 2) delete owner.offers + } + // Who reaches the bot changes from here (Make private among them): its chat's grant ends first, whatever that answers. + if (method === 'bots.devices.set' && ref) this.grants.end(node, ref.id, 'private') const write = row.remote.mutating // Nothing is kept here to send later: the client refuses a call to a computer it does not reach at once. const signal = ctx.connection.lifetime @@ -614,12 +700,12 @@ export class BotRouter implements BotRouterPort { return { result: qualifyBotResult(node, raw) } } - /** Whether `node` takes the word that this computer takes offered messages; false when it cannot say (an older computer). */ - private async takesOffers(node: NodeId): Promise { + /** The version `node` says it takes `method` at (`net.info`); 0 when it does not say or can't be asked. */ + private async sendVersion(node: NodeId, method: string): Promise { try { - return ((await this.options.client.botVersions(node))?.['bots.chat.send'] ?? 0) >= BOT_OFFERS_SEND_VERSION + return (await this.options.client.botVersions(node))?.[method] ?? 0 } catch { - return false + return 0 } } @@ -627,12 +713,35 @@ export class BotRouter implements BotRouterPort { // // A bot of another computer, in a chat turn the owner's message from here started, offers a message for a bot of this // computer (`bot_offer`). Its computer keeps the offer in the bot's chat; this computer reads it on the chat stream it - // opened and keeps a copy (`RemoteBotChats`). Send is a person's, at a window here: the offer is checked against that - // copy (never what the window says it is), the bot picked here and this computer's own limits, and kept in one - // transaction (`BotChatService.keepOffered`). The bot's computer is never called back, so it works one way. + // opened and keeps a copy (`RemoteBotChats`). It is sent here by a person's Send at a window, or on its own while that + // chat's grant is open ("Allow for this chat"): either way the offer is checked against that copy (never what a window + // says it is), the bot it goes to and this computer's own limits, and kept in one transaction + // (`BotChatService.keepOffered`). The offering computer is told what became of it (`bots.offers.outcome`), by this + // computer's call: it never calls here, so it works one way. /** Offers whose Send runs now: a second Send of one meanwhile (another window's) is `offer_busy`. */ private readonly offering = new Set() + /** Outcomes the offering computer took, so each is told once while this computer runs (a lost one is told again). */ + private readonly told = new Map() + private closed = false + /** Lost outcome reports waiting to be told again. */ + private readonly retries = new Set>() + /** + * The run token each owner's message carried when it was first sent, by its request id: a resend carries the same one + * (or none), so the bot's computer takes it as the same message even after the chat's grant opened or ended. + */ + private readonly sentRuns = new Map() + + /** The run token for an owner's message: the one it was first sent with, else a new one if its window holds the grant. */ + private runFor(node: NodeId, botId: string, window: string, requestId: unknown): string | undefined { + if (typeof requestId !== 'string') return undefined + const key = `${node}\n${botId}\n${requestId}` + if (this.sentRuns.has(key)) return this.sentRuns.get(key) ?? undefined + const run = this.grants.issueRun(node, botId, window) + this.sentRuns.set(key, run ?? null) + if (this.sentRuns.size > MAX_SENT_RUNS) this.sentRuns.delete(this.sentRuns.keys().next().value!) + return run + } /** * Send on an offered message: `botId` is the offering bot's qualified id, `messageId` and `seq` the row its offer is on, @@ -640,9 +749,8 @@ export class BotRouter implements BotRouterPort { * its code (`BOT_OFFER_REFUSALS`): another caller than a person at a window here; an offer kept already for another bot * (`offer_sent`; for the same bot it answers as kept, `replayed`); an offer not in this computer's copy of the chat * and not read from its computer either (`offer_unknown`; `offer_offline` while that computer can't be reached); one - * that is not this computer's (`offer_not_here`), or whose words are not the window's (`offer_changed`); a bot of - * that computer this computer no longer lists, or a computer it blocked (`sender_blocked`); then what - * `keepOffered` refuses. + * that is not this computer's (`offer_not_here`), whose words are not the window's (`offer_changed`), or that expired + * (past its time, or made under a grant that is not open now: `offer_expired`); then what `commitOffer` refuses. */ async offerSend(ctx: HandlerContext, input: BotOfferApi['bots.remote.offerSend']['params']): Promise { // A person at a Mousse window of this computer: never its command line, an agent, a bot or another computer. @@ -665,29 +773,55 @@ export class BotRouter implements BotRouterPort { if (this.offering.has(key)) throw offerRefused('offer_busy') this.offering.add(key) try { - const card = await this.offerOf(node, botId, input.messageId, input.seq, input.offerId) - if (!card.forYou) throw offerRefused('offer_not_here') - if (card.message !== input.message) throw offerRefused('offer_changed') - // Checked again right before the commit, with nothing awaited in between: a computer blocked, removed or no longer - // listing the bot while the offer was read sends nothing here. - const listed = this.options.registry.row(node, botId) - if (!this.options.enabled() || !listed || this.options.blocked?.(node)) throw offerRefused('sender_blocked') + const found = await this.offerOf(node, botId, input.messageId, input.seq, input.offerId) + if (!found.card.forYou) throw offerRefused('offer_not_here') + if (found.card.message !== input.message) throw offerRefused('offer_changed') + // Checked right before the commit, with nothing awaited from here on. One found expired here: its computer hears so. + let done: ReturnType try { - const done = local.keepOffered({ rowId, to: input.to, fromName: listed.name, computer: this.options.name(node), message: card.message }) - return { state: 'delivered', delivered: done.delivered, ...(done.replayed ? { replayed: true as const } : {}) } + done = this.commitOffer(node, botId, found, input.to) } catch (error) { - if (error instanceof BotEngineError && isBotOfferRefusal(error.code)) throw offerRefused(error.code, error.details) - if (error instanceof BotEngineError) throw new DomainRpcError(error.code, error.message, error.details) + if ((error as { code?: unknown } | null)?.code === 'offer_expired') this.tellOutcome(node, botId, found.card, 'expired') throw error } + this.tellOutcome(node, botId, found.card, 'delivered', done.delivered.to.name) + return { state: 'delivered', delivered: done.delivered, ...(done.replayed ? { replayed: true as const } : {}) } } finally { this.offering.delete(key) } } /** - * What a window showing an offering bot's chat needs: the bots here an offer may go to, and of the offers `offerIds`, - * those kept here (to whom, when). Read here alone, never asking the offering computer. + * The one commit of an offered message here, by Send or by a grant, synchronous from its last check to the + * transaction, so nothing changes in between: an offer past its time, or made under a grant that is not open now + * (`offer_expired`); a bot of that computer this computer no longer lists, or a computer it blocked + * (`sender_blocked`); then what `keepOffered` refuses in its transaction (the bot here takes offered messages, the + * hour's limit, one receipt per offer). + */ + private commitOffer(node: NodeId, botId: string, found: FoundOffer, to: string): ReturnType { + const local = this.options.localBots?.() + if (!local) throw new DomainRpcError('bots_unavailable', 'Bots are unavailable on this computer.') + if (this.expired(node, botId, found)) throw offerRefused('offer_expired') + const listed = this.options.registry.row(node, botId) + if (!this.options.enabled() || !listed || this.options.blocked?.(node)) throw offerRefused('sender_blocked') + try { + return local.keepOffered({ rowId: offeredRowId(node, botId, found.card.offerId), to, fromName: listed.name, computer: this.options.name(node), message: found.card.message }) + } catch (error) { + if (error instanceof BotEngineError && isBotOfferRefusal(error.code)) throw offerRefused(error.code, error.details) + if (error instanceof BotEngineError) throw new DomainRpcError(error.code, error.message, error.details) + throw error + } + } + + /** Whether an offer is expired here: past its time, or made under a grant (its run token) that is not open now. */ + private expired(node: NodeId, botId: string, found: FoundOffer): boolean { + return offerExpired(found.at, this.now()) || (found.card.run !== undefined && !this.grants.holds(node, botId, found.card.run)) + } + + /** + * What a window showing an offering bot's chat needs: the bots here an offer may go to, of the offers `offerIds` those + * kept here (to whom, when), and those past their time or made under a grant that is not open now (`expired`). Read here alone, never + * asking the offering computer. */ offerState(ctx: HandlerContext, input: BotOfferApi['bots.remote.offerState']['params']): BotOfferApi['bots.remote.offerState']['result'] { if (!routesForPerson(ctx.connection)) throw onlyThisComputer() @@ -695,13 +829,17 @@ export class BotRouter implements BotRouterPort { if (!Array.isArray(input.offerIds) || input.offerIds.length > MAX_OFFER_STATE_IDS || !input.offerIds.every(isOfferId)) throw new DomainRpcError('invalid_params', `offerIds names up to ${MAX_OFFER_STATE_IDS} offers.`) const local = this.options.localBots?.() - if (!local) return { recipients: [], delivered: {} } + if (!local) return { recipients: [], delivered: {}, expired: [] } const delivered: BotOfferApi['bots.remote.offerState']['result']['delivered'] = {} - for (const offerId of new Set(input.offerIds)) { + const wanted = new Set(input.offerIds) + for (const offerId of wanted) { const kept = local.offerKept(offeredRowId(node, botId, offerId)) if (kept) delivered[offerId] = kept } - return { recipients: local.offerRecipients(), delivered } + const expired = this.offersIn(this.options.registry.chats.messages(node, botId)) + .filter((found) => wanted.has(found.card.offerId) && !delivered[found.card.offerId] && this.expired(node, botId, found)) + .map((found) => found.card.offerId) + return { recipients: local.offerRecipients(), delivered, expired } } /** The offering bot a window names by its qualified id: a bot of another computer. */ @@ -712,19 +850,28 @@ export class BotRouter implements BotRouterPort { return { node: ref.node as NodeId, botId: ref.id } } + /** The offers of a bot's chat rows as its computer sent them here (`keptOfferOf`), with when each was made. */ + private offersIn(messages: unknown): FoundOffer[] { + const found: FoundOffer[] = [] + for (const row of Array.isArray(messages) ? messages : []) { + if (!isRecord(row) || row.author !== 'bot' || !Array.isArray(row.cards) || typeof row.at !== 'string') continue + for (const card of row.cards) { + const offer = isRecord(card) && (card as { type?: unknown }).type === 'offer' ? keptOfferOf(card) : undefined + // A card naming a device is the bot's computer's own: never one this computer was sent. + if (offer && offer.node === undefined) found.push({ card: offer, at: row.at }) + } + } + return found + } + /** * The offer `offerId` on row `messageId` of the bot's chat, as its computer sent it to this one: from the copy kept * here, else read from that computer (that row alone, by its `seq`). Its card as `keptOfferOf` takes it, or refused. */ - private async offerOf(node: NodeId, botId: string, messageId: string, seq: number, offerId: string): Promise { - const find = (messages: unknown): BotOfferCard | undefined => { - const row = (Array.isArray(messages) ? messages : []).find((message): message is RemoteBotMessage => isRecord(message) && message.id === messageId) - if (!row || row.author !== 'bot' || !Array.isArray(row.cards)) return undefined - for (const card of row.cards) { - const offer = isRecord(card) && (card as { type?: unknown }).type === 'offer' ? keptOfferOf(card) : undefined - if (offer && offer.offerId === offerId && offer.node === undefined) return offer - } - return undefined + private async offerOf(node: NodeId, botId: string, messageId: string, seq: number, offerId: string): Promise { + const find = (messages: unknown): FoundOffer | undefined => { + const rows = (Array.isArray(messages) ? messages : []).filter((message) => isRecord(message) && message.id === messageId) + return this.offersIn(rows).find((offer) => offer.card.offerId === offerId) } if (!this.options.registry.row(node, botId)) throw offerRefused('offer_unknown') const copied = find(this.options.registry.chats.messages(node, botId)) @@ -743,6 +890,198 @@ export class BotRouter implements BotRouterPort { return read } + /** + * Messages a bot's chat stream brought into the copy here. Of the offers among them that are this computer's: one sent + * here already, or expired, has its outcome told to the bot's computer if that computer still waits for it; one made + * under the chat's open grant, naming one of its bots, is sent to that bot now, synchronously from the stream's + * message to the commit. + */ + private observed(node: NodeId, botId: string, messages: readonly RemoteBotMessage[]): void { + const local = this.options.localBots?.() + if (!local) return + for (const found of this.offersIn(messages)) { + const { card } = found + if (!card.forYou) continue + const kept = local.offerKept(offeredRowId(node, botId, card.offerId)) + if (kept) { + this.tellOutcome(node, botId, card, 'delivered', kept.to.name) + continue + } + if (this.expired(node, botId, found)) { + this.tellOutcome(node, botId, card, 'expired') + continue + } + const grant = this.grants.holds(node, botId, card.run) + if (!grant) continue + const to = grantRecipient(grant, card.to, (id) => local.offerRecipients().find((bot) => bot.botId === id)?.name) + // Not one of the grant's bots by name: it waits for a Send, as any offer. + if (!to) continue + const key = `${node}\n${botId}\n${card.offerId}` + // A Send of it is under way: that Send keeps it. + if (this.offering.has(key)) continue + this.offering.add(key) + try { + const done = this.commitOffer(node, botId, found, to) + this.tellOutcome(node, botId, card, 'delivered', done.delivered.to.name) + } catch (error) { + const code = (error as { code?: unknown } | null)?.code + // The hour's limit: it waits for a Send, and the bot's computer hears it could not go on its own now. + if (code === 'too_many') this.tellOutcome(node, botId, card, 'busy') + } finally { + this.offering.delete(key) + } + } + } + + /** + * Tells the bot's computer what became of one of its offers made for this computer, when that computer waits to hear + * it (the card says `queued` or `busy`) and it was not told it already. Never awaited by anything: a report that is + * lost is told again the next time the offer comes into the copy here, and on its own a few times, further apart each + * time (`OUTCOME_RETRY_MS`), for one that never does (a busy chat pushes it out of the next snapshot). + */ + private tellOutcome(node: NodeId, botId: string, card: BotOfferCard, state: BotOfferOutcome, to?: string, attempt = 0): void { + if (card.state !== 'queued' && card.state !== 'busy') return + if (card.state === state) return + const key = `${node}\n${botId}\n${card.offerId}` + if (this.told.get(key) === state) return + this.told.set(key, state) + void this.options.client + .callBot(node, 'bots.offers.outcome', { botId, offerId: card.offerId, state, ...(to ? { to } : {}) }, { write: false, deadlineMs: 10_000 }) + .catch(() => { + if (this.told.get(key) !== state) return + this.told.delete(key) + if (this.closed || attempt + 1 >= OUTCOME_TRIES) return + const timer = setTimeout(() => { + this.retries.delete(timer) + // Another outcome was told meanwhile (it expired after it was busy): that one stands. + if (!this.closed && !this.told.has(key)) this.tellOutcome(node, botId, card, state, to, attempt + 1) + }, OUTCOME_RETRY_MS * 4 ** attempt) + timer.unref?.() + this.retries.add(timer) + }) + } + + /** A grant ended: the offers made under it that were not sent here are expired, and their computer is told. */ + private expireGrantOffers(grant: ChatGrant): void { + if (!grant.runs.size) return + const local = this.options.localBots?.() + for (const found of this.offersIn(this.options.registry.chats.messages(grant.node, grant.botId))) { + const { card } = found + if (!card.forYou || !card.run || !grant.runs.has(card.run)) continue + if (local?.offerKept(offeredRowId(grant.node, grant.botId, card.offerId))) continue + this.tellOutcome(grant.node, grant.botId, card, 'expired') + } + } + + /** Each grant ends the moment Bridge goes off, its computer is blocked, can't be reached, or no longer lists the bot. */ + private checkGrants(): void { + for (const grant of this.grants.all()) { + const reason = this.grantEndReason(grant.node, grant.botId) + if (reason) this.grants.end(grant.node, grant.botId, reason) + } + } + + /** Why the chat's grant can't stay open now, if it can't: the first of blocked, removed and offline that holds. */ + private grantEndReason(node: NodeId, botId: string): BotChatGrantEnd | undefined { + if (!this.options.enabled() || this.options.blocked?.(node)) return 'blocked' + if (!this.options.registry.row(node, botId)) return 'removed' + if (!this.options.online(node)) return 'offline' + return undefined + } + + // -- Chat grants ("Allow for this chat", issue #2490 stage 2) ------------------------------------------------------ + + /** + * Opens a grant for the chat of `botId` (a bot of another computer) with `recipients`, bots of this computer: while it + * is open, what that bot offers one of them in a turn this window's message started is sent here without a Send. + * Only a person at a Mousse window that shows that chat now opens one, and only for bots here that take offered + * messages. Refused, each with its code (`BOT_GRANT_REFUSALS`): the bot's computer is blocked, or does not list the + * bot (`sender_blocked`), can't be reached (`grant_offline`) or takes no grants (`grant_unsupported`); another window + * holds the chat's grant (`grant_elsewhere`); the window does not show the chat (`grant_not_shown`); no bot, too many, + * or one that is gone or takes no offered messages (`grant_recipients`, `recipient_gone`, `recipient_closed`). + */ + async grantOpen(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantOpen']['params']): Promise { + if (ctx.connection?.clientType !== 'gui' || ctx.connection.bridgeCaller) + throw new DomainRpcError('forbidden', 'Only a person at a Mousse window on this computer allows a chat.') + const { node, botId } = this.offeringBot(input.botId) + const window = ctx.connection.id + const local = this.options.localBots?.() + if (!local) throw new DomainRpcError('bots_unavailable', 'Bots are unavailable on this computer.') + if (!Array.isArray(input.recipients) || !input.recipients.length || input.recipients.length > MAX_CHAT_GRANT_RECIPIENTS || !input.recipients.every(isBotId) || new Set(input.recipients).size !== input.recipients.length) + throw grantRefused('grant_recipients') + if (!this.options.enabled() || this.options.blocked?.(node) || !this.options.registry.row(node, botId)) throw grantRefused('sender_blocked') + if (!this.options.online(node)) throw grantRefused('grant_offline') + const held = this.grants.get(node, botId) + if (held && held.window !== window) throw grantRefused('grant_elsewhere') + if (!this.attached.shows(window, node, botId)) throw grantRefused('grant_not_shown') + // An end that comes in while this waits (End access, pressed after Allow) wins: nothing opens after it. + const ends = this.grants.ends(node, botId) + if ((await this.sendVersion(node, 'bots.chat.send')) < BOT_GRANT_SEND_VERSION) throw grantRefused('grant_unsupported') + // Its own hold on the chat's stream: the stream ending, or a new snapshot (a connection that dropped and came back, + // either computer restarted), ends the grant. The window's stream is open, so nothing is waited for here. + // Why it ended is read from what holds now (a block or a removal closes the stream first); a bot its computer + // stopped offering here (`stream_unknown`) is removed; anything else is the connection. + let grant: ChatGrant | undefined + const end = (code?: string): void => { + if (!grant || this.grants.get(node, botId) !== grant) return + this.grants.end(node, botId, this.grantEndReason(node, botId) ?? (code === 'stream_unknown' || code === 'forbidden' ? 'removed' : 'offline')) + } + const stream = await this.options.registry.chats.open(node, botId, { snapshot: () => end(), restarted: () => end(), ended: (code) => end(code) }) + // Checked again after the wait, with nothing awaited from here to the grant: what changed meanwhile wins. + try { + if (this.grants.ends(node, botId) !== ends) { + stream.close() + return { grant: this.grantView(node, botId, window) } + } + if (!this.options.enabled() || this.options.blocked?.(node) || !this.options.registry.row(node, botId)) throw grantRefused('sender_blocked') + if (!this.options.online(node)) throw grantRefused('grant_offline') + const now = this.grants.get(node, botId) + if (now && now.window !== window) throw grantRefused('grant_elsewhere') + if (!this.attached.shows(window, node, botId)) throw grantRefused('grant_not_shown') + for (const id of input.recipients) { + const state = local.offerRecipientState(id) + if (state === 'gone') throw grantRefused('recipient_gone') + if (state === 'closed') throw grantRefused('recipient_closed') + } + grant = this.grants.start({ node, botId, window, recipients: input.recipients, stream }) + } catch (error) { + stream.close() + throw error + } + return { grant: this.grantView(node, botId, window) } + } + + /** End access: the window that opened the chat's grant ends it. Another window shows it only (`grant_elsewhere`). */ + grantEnd(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantEnd']['params']): BotGrantApi['bots.remote.grantEnd']['result'] { + if (ctx.connection?.clientType !== 'gui' || ctx.connection.bridgeCaller) + throw new DomainRpcError('forbidden', 'Only a person at a Mousse window on this computer ends access.') + const { node, botId } = this.offeringBot(input.botId) + const held = this.grants.get(node, botId) + if (held && held.window !== ctx.connection.id) throw grantRefused('grant_elsewhere') + if (held) this.grants.end(node, botId, 'ended') + return { grant: this.grantView(node, botId, ctx.connection.id) } + } + + /** The chat's grant as this window sees it; whether its computer takes grants is read from what it said (`net.info`). */ + async grantState(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantState']['params']): Promise { + if (!routesForPerson(ctx.connection)) throw onlyThisComputer() + const { node, botId } = this.offeringBot(input.botId) + const view = this.grantView(node, botId, ctx.connection.id) + if (view.active || (await this.sendVersion(node, 'bots.chat.send')) >= BOT_GRANT_SEND_VERSION) return { grant: view } + return { grant: { ...view, unsupported: true } } + } + + private grantView(node: NodeId, botId: string, window: string | undefined) { + const local = this.options.localBots?.() + return this.grants.view(node, botId, window, (id) => { + try { + return local ? { botId: id, name: local.botName(id) } : undefined + } catch { + return undefined + } + }) + } + /** Whether `node` says it offers `method` to other devices; false when it cannot say (an older computer). */ private async offers(node: NodeId, method: string): Promise { try { @@ -988,6 +1327,8 @@ export class BotRouter implements BotRouterPort { const lease = ctx.connection.id const node = ref.node as NodeId if (!focused) { + // Leaving the chat in the window that allowed it ends its grant. + if (this.grants.get(node, ref.id)?.window === lease) this.grants.end(node, ref.id, 'left') this.attached.unfocus(lease, node, ref.id) return { routed: true, focused: false } } @@ -1013,7 +1354,12 @@ export class BotRouter implements BotRouterPort { } close(): void { + this.closed = true this.offClosed?.() + for (const off of this.offGrantWatch.splice(0)) off() + for (const timer of this.retries) clearTimeout(timer) + this.retries.clear() + this.grants.close() this.attached.close() } } diff --git a/src/mms/bridge/routed/RemoteBotChats.ts b/src/mms/bridge/routed/RemoteBotChats.ts index 8aa0df2c8..265a692e0 100644 --- a/src/mms/bridge/routed/RemoteBotChats.ts +++ b/src/mms/bridge/routed/RemoteBotChats.ts @@ -72,6 +72,8 @@ export interface RemoteBotChatListener { delta?(type: string, data: unknown): void /** The chat stream ended (`code`); the copy stays unless the bot was lost. */ ended?(code: string): void + /** The open stream starts again from its copy (a dropped connection came back, or a new snapshot): news may be missed. */ + restarted?(): void } export interface RemoteBotChatsOptions { @@ -116,10 +118,30 @@ export const botChatSubject = (botId: string): string => privateRecordSubject({ */ export class RemoteBotChats { private readonly chats = new Map() + private readonly observers = new Set<(node: NodeId, botId: string, messages: readonly RemoteBotMessage[]) => void>() private closed = false constructor(private readonly options: RemoteBotChatsOptions) {} + /** + * Hears every message a chat stream brings into the copy (a snapshot's, then each added or changed), after it is + * written, for whichever window opened it: offered messages are sent on and their outcomes told from it (`BotRouter`). + */ + observe(listener: (node: NodeId, botId: string, messages: readonly RemoteBotMessage[]) => void): () => void { + this.observers.add(listener) + return () => this.observers.delete(listener) + } + + private observed(chat: OpenChat, messages: readonly RemoteBotMessage[]): void { + for (const observer of [...this.observers]) { + try { + observer(chat.node, chat.botId, messages) + } catch { + // One observer's failure does not keep the copy or the windows from hearing. + } + } + } + /** The copy of a bot's chat, oldest first: what was last received, whether its computer is reached or not. */ messages(node: NodeId, botId: string): RemoteBotMessage[] { return this.options.safely('read a bot chat copy', () => this.options.store.messages(node, botId)) ?? [] @@ -171,7 +193,11 @@ export class RemoteBotChats { (code) => this.ended(chat, code), this.streamOptions(node, botId), // Display only: passed on as it comes, never written. - (type, data) => this.each(chat, (listener) => listener.delta?.(type, data)) + (type, data) => this.each(chat, (listener) => listener.delta?.(type, data)), + // The open stream replays from its copy again (a connection that dropped and came back, a new snapshot). + (caught) => { + if (!caught && chat.handle) this.each(chat, (listener) => listener.restarted?.()) + } ) if (this.closed || this.chats.get(keyOf(node, botId)) !== chat || !chat.listeners.size) { handle.close() @@ -199,6 +225,7 @@ export class RemoteBotChats { if (isRecord(value.bot)) this.row(chat, value.bot) this.each(chat, (listener) => listener.changed?.()) this.each(chat, (listener) => listener.snapshot?.()) + this.observed(chat, messages) } private event(chat: OpenChat, type: string, data: unknown): void { @@ -209,6 +236,7 @@ export class RemoteBotChats { this.trimmed(this.options.safely('copy a bot chat message', () => this.options.store.putMessage(chat.node, chat.botId, message, this.kept()))) this.each(chat, (listener) => listener.changed?.()) this.each(chat, (listener) => listener.message?.(message)) + this.observed(chat, [message]) } else if (type === 'bots.changed' && isRecord(data.bot)) { this.row(chat, data.bot) } diff --git a/src/mms/bridge/routed/ThreadRouter.ts b/src/mms/bridge/routed/ThreadRouter.ts index 4c0a00f25..0c223a040 100644 --- a/src/mms/bridge/routed/ThreadRouter.ts +++ b/src/mms/bridge/routed/ThreadRouter.ts @@ -232,7 +232,7 @@ export class ThreadRouter implements ThreadRouterPort { // `bots.focus`, `bots.remote.file` and the applet calls are the bot router's (`BotRouter.focus`, `BotRouter.file`, // `BotRouter.applet`, `BotRouter.appletSave`); an applet's state is its own words, never ids to route. So are an // offered message's Send and state (`BotRouter.offerSend`, `offerState`), which this computer answers alone. - if (method === 'threads.focus' || method === 'bots.focus' || method === 'bots.remote.file' || method === 'bots.remote.applet' || method === 'bots.remote.appletState' || method === 'bots.remote.offerSend' || method === 'bots.remote.offerState' || !isRecord(params)) return undefined + if (method === 'threads.focus' || method === 'bots.focus' || method === 'bots.remote.file' || method === 'bots.remote.applet' || method === 'bots.remote.appletState' || method === 'bots.remote.offerSend' || method === 'bots.remote.offerState' || method === 'bots.remote.grantOpen' || method === 'bots.remote.grantEnd' || method === 'bots.remote.grantState' || !isRecord(params)) return undefined // A CLI that names a qualified id is still refused below; a window's drag is the handler's to place. if ((method === 'threads.reorder' || method === 'projects.reorder') && ctx.connection?.clientType === 'gui') return undefined diff --git a/src/mms/bridge/routed/attachedBots.ts b/src/mms/bridge/routed/attachedBots.ts index 5de57777a..1fd6f7d54 100644 --- a/src/mms/bridge/routed/attachedBots.ts +++ b/src/mms/bridge/routed/attachedBots.ts @@ -93,6 +93,12 @@ export class AttachedBots { } } + /** Whether window `lease` shows the chat of `botId` on `node` now, with its stream open. */ + shows(lease: string, node: NodeId, botId: string): boolean { + const key = keyOf(node, botId) + return !!this.byLease.get(lease)?.has(key) && !!this.held.get(key)?.handle + } + /** The chats in view, for the tests and the device screens. */ state(): Array<{ node: NodeId; botId: string; windows: number; open: boolean }> { return [...this.held.values()].map((held) => ({ node: held.node, botId: held.botId, windows: held.leases.size, open: !!held.handle })) diff --git a/src/mms/bridge/routed/chatGrants.ts b/src/mms/bridge/routed/chatGrants.ts new file mode 100644 index 000000000..1345ed9b8 --- /dev/null +++ b/src/mms/bridge/routed/chatGrants.ts @@ -0,0 +1,217 @@ +import { randomUUID } from 'node:crypto' +import type { NodeId } from '../../../shared/net' +import { CHAT_GRANT_IDLE_MS, CHAT_GRANT_MAX_MS, type BotChatGrantEnd, type BotChatGrantView, type BotOfferRecipient } from '../../../shared/bots/personal/offers' + +/** + * The chat grants of this computer ("Allow for this chat", issue #2490 stage 2): for one bot of another computer, the + * bots of this computer that bot's offers may be sent to without a Send, while the window that opened the grant shows + * that chat. Kept in memory alone, so a restart ends every one. + * + * A grant covers only the offers of a turn started by a message that window sent while it was open: each such message + * gets a run token of its own (`issueRun`), which the bot's computer stamps on the turn's offers; an offer is the grant's + * only when its token is one of the grant's (`holds`). A grant ends once, for one reason, and never opens again: a new + * one needs a new click, and a token of an ended grant is held by none. + */ + +export interface ChatGrant { + node: NodeId + botId: string + /** The window that opened it (its connection id). */ + window: string + recipients: readonly string[] + /** The run tokens of the messages its window sent while it was open. */ + runs: Set + openedAt: number + /** The last message from its window (what the bot does under it never keeps it open). */ + activeAt: number + /** Its own hold on the chat's stream, to hear when that ends or comes back anew. */ + stream?: { close(): void } +} + +export interface ChatGrantsOptions { + now(): number + /** A grant opened or ended: windows read it again. */ + changed(node: NodeId, botId: string): void + /** A grant ended: the offers made under it that were not sent are expired (the caller tells the bot's computer). */ + ended?(grant: ChatGrant, reason: BotChatGrantEnd): void + idleMs?: number + maxMs?: number +} + +const keyOf = (node: NodeId, botId: string): string => `${node}\u0000${botId}` + +export class ChatGrants { + private readonly open = new Map() + /** Why the last grant of each chat ended, for its windows to say. */ + private readonly lastEnd = new Map() + private readonly timers = new Map>() + private readonly endCounts = new Map() + private readonly idleMs: number + private readonly maxMs: number + + constructor(private readonly options: ChatGrantsOptions) { + this.idleMs = options.idleMs ?? CHAT_GRANT_IDLE_MS + this.maxMs = options.maxMs ?? CHAT_GRANT_MAX_MS + } + + get(node: NodeId, botId: string): ChatGrant | undefined { + return this.current(keyOf(node, botId)) + } + + all(): ChatGrant[] { + return [...this.open.keys()].map((key) => this.current(key)).filter((grant): grant is ChatGrant => grant !== undefined) + } + + /** + * How many grants of the chat have ended while this computer runs: a caller that waited on something reads it before + * and after, and a change means an end (End access among them) came in between, which wins. + */ + ends(node: NodeId, botId: string): number { + return this.endCounts.get(keyOf(node, botId)) ?? 0 + } + + /** + * The chat's open grant, read at its time: one past its end is ended here and now, so nothing is sent under it + * between its deadline and its timer (a busy event loop runs that late). + */ + private current(key: string): ChatGrant | undefined { + const grant = this.open.get(key) + if (!grant) return undefined + const due = this.deadline(grant) + if (due.at > this.options.now()) return grant + this.finish(grant, due.reason, true) + return undefined + } + + /** + * Opens a grant (the caller checked everything first). The same window allowing the chat again (other bots) takes + * the place of its grant, with the tokens it issued: a turn under way keeps its offers. Another window's ends first. + */ + start(input: { node: NodeId; botId: string; window: string; recipients: readonly string[]; stream?: { close(): void } }): ChatGrant { + const key = keyOf(input.node, input.botId) + const before = this.current(key) + const runs = before?.window === input.window ? before.runs : new Set() + if (before) this.finish(before, 'ended', before.window !== input.window) + const now = this.options.now() + const grant: ChatGrant = { node: input.node, botId: input.botId, window: input.window, recipients: [...input.recipients], runs, openedAt: now, activeAt: now, ...(input.stream ? { stream: input.stream } : {}) } + this.open.set(key, grant) + this.lastEnd.delete(key) + this.arm(grant) + this.options.changed(grant.node, grant.botId) + return grant + } + + /** Ends the chat's grant, if one is open, for `reason`. */ + end(node: NodeId, botId: string, reason: BotChatGrantEnd): boolean { + const grant = this.current(keyOf(node, botId)) + if (!grant) return false + this.finish(grant, reason, true) + return true + } + + /** Ends every grant `match` names, for `reason`. */ + endWhere(match: (grant: ChatGrant) => boolean, reason: BotChatGrantEnd): number { + let ended = 0 + for (const grant of this.all()) { + if (!match(grant)) continue + this.finish(grant, reason, true) + ended += 1 + } + return ended + } + + /** + * A token for a message window `window` sends to the chat now, kept with the chat's grant: only when that window + * opened it. Undefined otherwise (no grant, or another window's), and the message then carries none. + */ + issueRun(node: NodeId, botId: string, window: string): string | undefined { + const grant = this.current(keyOf(node, botId)) + if (!grant || grant.window !== window) return undefined + const run = randomUUID() + grant.runs.add(run) + this.touch(grant) + return run + } + + /** The grant `run` was issued under, while it is open; undefined for a token of none, or of one that ended. */ + holds(node: NodeId, botId: string, run: string | undefined): ChatGrant | undefined { + if (!run) return undefined + const grant = this.current(keyOf(node, botId)) + return grant?.runs.has(run) ? grant : undefined + } + + /** Its window sent a message: its idle time starts again. */ + touch(grant: ChatGrant): void { + if (this.current(keyOf(grant.node, grant.botId)) !== grant) return + grant.activeAt = this.options.now() + this.arm(grant) + } + + /** The chat's grant as window `window` sees it, with the names of its bots from `names`. */ + view(node: NodeId, botId: string, window: string | undefined, names: (botId: string) => BotOfferRecipient | undefined): BotChatGrantView { + const grant = this.current(keyOf(node, botId)) + if (!grant) { + const ended = this.lastEnd.get(keyOf(node, botId)) + return { active: false, recipients: [], ...(ended ? { ended } : {}) } + } + return { + active: true, + ...(window !== undefined && window === grant.window ? { mine: true as const } : {}), + recipients: grant.recipients.map((id) => names(id) ?? { botId: id, name: 'a bot' }), + openedAt: new Date(grant.openedAt).toISOString(), + endsAt: new Date(this.deadline(grant).at).toISOString() + } + } + + /** Every grant ends without telling anyone (this computer's Bridge is going away). */ + close(): void { + for (const grant of [...this.open.values()]) this.finish(grant, 'closed', false) + for (const timer of this.timers.values()) clearTimeout(timer) + this.timers.clear() + } + + private deadline(grant: ChatGrant): { at: number; reason: BotChatGrantEnd } { + const idle = grant.activeAt + this.idleMs + const hard = grant.openedAt + this.maxMs + return idle < hard ? { at: idle, reason: 'idle' } : { at: hard, reason: 'expired' } + } + + private arm(grant: ChatGrant): void { + const key = keyOf(grant.node, grant.botId) + const before = this.timers.get(key) + if (before) clearTimeout(before) + const { at } = this.deadline(grant) + const timer = setTimeout(() => { + if (this.open.get(key) !== grant) return + const due = this.deadline(grant) + if (due.at <= this.options.now()) this.finish(grant, due.reason, true) + else this.arm(grant) + }, Math.max(0, at - this.options.now())) + timer.unref?.() + this.timers.set(key, timer) + } + + private finish(grant: ChatGrant, reason: BotChatGrantEnd, tell: boolean): void { + const key = keyOf(grant.node, grant.botId) + if (this.open.get(key) !== grant) return + this.open.delete(key) + this.lastEnd.set(key, reason) + this.endCounts.set(key, (this.endCounts.get(key) ?? 0) + 1) + const timer = this.timers.get(key) + if (timer) clearTimeout(timer) + this.timers.delete(key) + const stream = grant.stream + grant.stream = undefined + try { + stream?.close() + } catch { + // Its hold on the stream is let go whatever happens. + } + if (!tell) return + try { + this.options.ended?.(grant, reason) + } finally { + this.options.changed(grant.node, grant.botId) + } + } +} diff --git a/src/mms/protocol/botRouterPort.ts b/src/mms/protocol/botRouterPort.ts index 61742c836..674c1a6df 100644 --- a/src/mms/protocol/botRouterPort.ts +++ b/src/mms/protocol/botRouterPort.ts @@ -1,4 +1,4 @@ -import type { BotOfferApi } from '../../shared/bots/personal/offers' +import type { BotGrantApi, BotOfferApi } from '../../shared/bots/personal/offers' import type { BotSummary } from '../../shared/bots/personal/chat' import type { BotComputerChoice, BotElsewhereComputer } from '../../shared/bots/personal/methods' import type { BotTransferResult } from '../../shared/bots/personal/transfer' @@ -49,4 +49,10 @@ export interface BotRouterPort { offerSend?(ctx: HandlerContext, input: BotOfferApi['bots.remote.offerSend']['params']): Promise /** The bots here an offer may go to, and which offers of one chat are kept here (`bots.remote.offerState`). */ offerState?(ctx: HandlerContext, input: BotOfferApi['bots.remote.offerState']['params']): BotOfferApi['bots.remote.offerState']['result'] + /** "Allow for this chat": opens the chat's grant (`bots.remote.grantOpen`, issue #2490 stage 2). */ + grantOpen?(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantOpen']['params']): Promise + /** End access (`bots.remote.grantEnd`). */ + grantEnd?(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantEnd']['params']): BotGrantApi['bots.remote.grantEnd']['result'] + /** The chat's grant as a window sees it (`bots.remote.grantState`). */ + grantState?(ctx: HandlerContext, input: BotGrantApi['bots.remote.grantState']['params']): Promise } diff --git a/src/mms/protocol/gitAccess.ts b/src/mms/protocol/gitAccess.ts index b325ce200..1b256d325 100644 --- a/src/mms/protocol/gitAccess.ts +++ b/src/mms/protocol/gitAccess.ts @@ -70,6 +70,9 @@ export const GIT_ACCESS = { 'bots.remote.appletState': 'none', 'bots.remote.offerSend': 'none', 'bots.remote.offerState': 'none', + 'bots.remote.grantOpen': 'none', + 'bots.remote.grantEnd': 'none', + 'bots.remote.grantState': 'none', 'bots.marks.list': 'none', 'bots.marks.set': 'none', 'threads.markSeen': 'none', diff --git a/src/mms/protocol/handlers.ts b/src/mms/protocol/handlers.ts index 603a6363c..7cb28d227 100644 --- a/src/mms/protocol/handlers.ts +++ b/src/mms/protocol/handlers.ts @@ -2656,6 +2656,30 @@ async function dispatchOwnedMethod(ctx: HandlerContext, method: string, params: if (!router?.offerState) return { recipients: [], delivered: {} } return router.offerState(ctx, { botId, offerIds: p.offerIds as string[] }) } + case 'bots.remote.grantOpen': { + // "Allow for this chat" (issue #2490 stage 2): a person at a window showing a bot of another computer's chat lets + // its offers to the bots named here be sent without a Send, while that window shows the chat (`BotRouter.grantOpen`). + const p = isObject(params) ? params : {} + rejectUnknownKeys(p, ['profileId', 'botId', 'recipients']) + const botId = asString(p.botId, 'botId', 256) + const router = ctx.mms.botRouter + if (!router?.grantOpen) throw new DomainRpcError('computer_offline', 'Your other computers are not connected. Turn on networking in Settings, Devices.') + return router.grantOpen(ctx, { botId, recipients: p.recipients as string[] }) + } + case 'bots.remote.grantEnd': + case 'bots.remote.grantState': { + // End access (the window that allowed it), or how the chat's grant stands (any window here). + const p = isObject(params) ? params : {} + rejectUnknownKeys(p, ['profileId', 'botId']) + const botId = asString(p.botId, 'botId', 256) + const router = ctx.mms.botRouter + if (method === 'bots.remote.grantEnd') { + if (!router?.grantEnd) return { grant: { active: false, recipients: [] } } + return router.grantEnd(ctx, { botId }) + } + if (!router?.grantState) return { grant: { active: false, recipients: [] } } + return router.grantState(ctx, { botId }) + } case 'threads.markSeen': { // A window opened the thread or showed it in focus: it is no longer Done (finished and unseen). const p = isObject(params) ? params : {} diff --git a/src/mms/protocol/types.ts b/src/mms/protocol/types.ts index e37ef4361..716fd752f 100644 --- a/src/mms/protocol/types.ts +++ b/src/mms/protocol/types.ts @@ -334,6 +334,9 @@ export const PROTOCOL_METHODS = [ 'bots.remote.appletState', 'bots.remote.offerSend', 'bots.remote.offerState', + 'bots.remote.grantOpen', + 'bots.remote.grantEnd', + 'bots.remote.grantState', 'bots.marks.list', 'bots.marks.set', 'threads.markSeen', diff --git a/src/renderer/services/personalBotsClient.ts b/src/renderer/services/personalBotsClient.ts index 8b5dad214..6f03f6ceb 100644 --- a/src/renderer/services/personalBotsClient.ts +++ b/src/renderer/services/personalBotsClient.ts @@ -113,8 +113,11 @@ export interface PersonalBotsClient { editMemory(botId: string, ref: string, text: string): Promise /** Which of the owner's devices reach the bot, and the devices to pick from. An older service lacks it and rejects. */ devices(botId: string): Promise - /** Saves which devices reach the bot; only this computer's window and command line may. */ - setDevices(botId: string, access: BotDeviceAccess): Promise + /** + * Saves which devices reach the bot; only this computer's window and command line may. `closeOffers`: Make private of a + * bot of another computer, which takes no offered messages there either (when that computer takes the word). + */ + setDevices(botId: string, access: BotDeviceAccess, closeOffers?: boolean): Promise /** Opens or closes a bot of this computer to offered messages (About; Make private closes it). An older service rejects. */ setOffers(botId: string, open: boolean): Promise /** Send on a message a bot of another computer offered for a bot here (issue #2490): a person at this window only. */ @@ -183,7 +186,7 @@ export function createPersonalBotsClient(transport: PlatformRequestApi): Persona forgetMemory: async (botId, id) => { await call('bots.memory.forget', { botId, id }) }, editMemory: async (botId, ref, text) => (await call('bots.memory.edit', { botId, id: ref, text })).entry, devices: (botId) => transport.request('bots.devices.get', { botId }), - setDevices: (botId, access) => transport.request('bots.devices.set', { botId, access }), + setDevices: (botId, access, closeOffers) => transport.request('bots.devices.set', { botId, access, ...(closeOffers ? { offers: false } : {}) }), setOffers: (botId, open) => transport.request('bots.devices.offers', { botId, open }), offerSend: (input) => transport.request('bots.remote.offerSend', input), offerState: (botId, offerIds) => transport.request('bots.remote.offerState', { botId, offerIds }) diff --git a/src/renderer/stores/botsStore.ts b/src/renderer/stores/botsStore.ts index c9561c6a2..800bfa8e8 100644 --- a/src/renderer/stores/botsStore.ts +++ b/src/renderer/stores/botsStore.ts @@ -1273,8 +1273,10 @@ export const useBotsStore = create((set, get) => { try { // A bot of this computer takes no offered messages either (issue #2490), closed first: it never shows as private // while it still takes them, and when that fails it is not made private. An older service has no such switch. - if (!get().bots.find((bot) => bot.id === botId)?.lives) await bots().setOffers(botId, false).catch((cause: unknown) => { if (!missingMethod(cause)) throw cause }) - await bots().setDevices(botId, { mode: 'this_computer' }) + // A bot of another computer is closed by its computer with the same call, first there too. + const remote = !!get().bots.find((bot) => bot.id === botId)?.lives + if (!remote) await bots().setOffers(botId, false).catch((cause: unknown) => { if (!missingMethod(cause)) throw cause }) + await bots().setDevices(botId, { mode: 'this_computer' }, remote || undefined) if (owner !== epoch) return // The list's lock shows at once; the service's `bots.changed` reads it again too. A bot of another computer now // reaches its own computer and this one, which its list does not show. diff --git a/src/shared/bots/personal/cards.ts b/src/shared/bots/personal/cards.ts index 47da24280..1778ddec4 100644 --- a/src/shared/bots/personal/cards.ts +++ b/src/shared/bots/personal/cards.ts @@ -5,7 +5,7 @@ * (`plainCard`) for older apps, notifications, other devices, the journal and Forget. Browser-safe. */ -import { isOfferId, offerMessageProblem, plainOffer, MAX_OFFER_TO_CHARS, type BotOfferCard } from './offers' +import { isBotOfferOutcome, isOfferId, isRunToken, offerMessageProblem, plainOffer, MAX_OFFER_TO_CHARS, type BotOfferCard, type BotOfferStored } from './offers' export type { BotOfferCard } from './offers' @@ -228,12 +228,16 @@ export function keptCardOf(value: unknown): BotCard | undefined { * told it; the bot's computer never keeps one. */ export function keptOfferOf(given: Record): BotOfferCard | undefined { - const { offerId, message, to, computer, node, forYou } = given - if (Object.keys(given).some((key) => !['type', 'offerId', 'message', 'to', 'computer', 'node', 'forYou'].includes(key))) return undefined + const { offerId, message, to, computer, node, forYou, run, state, sentTo, stateAt } = given + if (Object.keys(given).some((key) => !OFFER_KEYS.includes(key))) return undefined if (!isOfferId(offerId) || typeof message !== 'string' || offerMessageProblem(message) || typeof computer !== 'string' || !computer.trim()) return undefined if (to !== undefined && (typeof to !== 'string' || !to.trim() || to.length > MAX_OFFER_TO_CHARS)) return undefined if (node !== undefined && (typeof node !== 'string' || !node)) return undefined if (forYou !== undefined && forYou !== true) return undefined + if (run !== undefined && !isRunToken(run)) return undefined + if (state !== undefined && state !== 'queued' && state !== 'unsupported' && !isBotOfferOutcome(state)) return undefined + if (sentTo !== undefined && (state !== 'delivered' || typeof sentTo !== 'string' || !sentTo.trim() || sentTo.length > MAX_OFFER_TO_CHARS)) return undefined + if (stateAt !== undefined && (typeof stateAt !== 'string' || !Number.isFinite(Date.parse(stateAt)))) return undefined return { type: 'offer', offerId, @@ -241,10 +245,16 @@ export function keptOfferOf(given: Record): BotOfferCard | unde ...(typeof to === 'string' ? { to: oneLine(to) } : {}), computer: oneLine(computer).slice(0, 120), ...(typeof node === 'string' ? { node } : {}), - ...(forYou === true ? { forYou: true as const } : {}) + ...(forYou === true ? { forYou: true as const } : {}), + ...(typeof run === 'string' ? { run } : {}), + ...(state !== undefined ? { state: state as BotOfferStored } : {}), + ...(typeof sentTo === 'string' ? { sentTo: oneLine(sentTo) } : {}), + ...(typeof stateAt === 'string' ? { stateAt } : {}) } } +const OFFER_KEYS = ['type', 'offerId', 'message', 'to', 'computer', 'node', 'forYou', 'run', 'state', 'sentTo', 'stateAt'] + /** Why `cards` can't go on one message (too large), or undefined when they can. */ export function cardsProblem(cards: readonly BotCard[]): string | undefined { if (new TextEncoder().encode(JSON.stringify(cards)).length > MAX_CARDS_JSON_BYTES) return CARDS_FULL_TEXT diff --git a/src/shared/bots/personal/definition.ts b/src/shared/bots/personal/definition.ts index a653aa2a4..0b0e5e404 100644 --- a/src/shared/bots/personal/definition.ts +++ b/src/shared/bots/personal/definition.ts @@ -356,9 +356,15 @@ export interface BotOwnerTurn { node?: string /** * The other device takes offered messages for its own bots (`BOT_OFFERS_VERSION`, issue #2490): its window's router - * said so with the owner's message. A chat turn it started may offer it a message (`bot_offer`). Older builds ignore it. + * said so with the owner's message. A chat turn it started may offer it a message (`bot_offer`). `2`: it also reports + * what becomes of each (`BOT_OFFERS_REPORTED`). Older builds ignore it. */ - offers?: 1 + offers?: 1 | 2 + /** + * The run token the device's router sent with the message, when its window holds a grant for this chat + * (`BOT_OFFER_RUN_KEY`): the turn's offers carry it back. Kept with `offers: 2` only. + */ + run?: string /** * The device was saved but can't be read (a bad saved value): the turn, and what it sets up, only reads the owner's * threads (`savedDevice`). `limit` is then the strictest, for builds that ignore this. diff --git a/src/shared/bots/personal/methodTable.ts b/src/shared/bots/personal/methodTable.ts index 4ae966710..0c2e97643 100644 --- a/src/shared/bots/personal/methodTable.ts +++ b/src/shared/bots/personal/methodTable.ts @@ -127,8 +127,14 @@ export const BOT_METHODS = { // `staged`: files another device sent ahead with `bots.stage`, for this bot and from that device alone. 2: `sent`, // the files of a send that device opened for this bot's chat (`bots.send.open`), each with its name; never with `staged`. // 3: `offers` (`BOT_OFFERS_KEY`), set by the sending computer's router: it takes offered messages (`bot_offer`). - remote: chats(['botId', 'text', 'clientRequestId'], ['replyTo', 'staged', 'sent', 'offers'], 3) + // 4: `offers: 2`, it also reports what becomes of each; and `run` (`BOT_OFFER_RUN_KEY`), the token of a message sent + // under its chat grant, which the turn's offers carry back. + remote: chats(['botId', 'text', 'clientRequestId'], ['replyTo', 'staged', 'sent', 'offers', 'run'], 4) }, + // What became of an offered message, from the computer it is for (issue #2490): sent by that computer's router itself, + // never a window (`fromBot`), and taken only for an offer made for that device. + // The same outcome again changes nothing, so it is not kept in the request ledger. + 'bots.offers.outcome': { level: 'use', remote: { capability: 'chat', mutating: false, required: ['botId', 'offerId', 'state'], optional: ['to'], fromBot: true } }, 'bots.chat.stop': { level: 'use', local: chat(['botId']), remote: chats(['botId']) }, 'bots.chat.markRead': { level: 'use', local: chat(['botId', 'seq']), remote: chats(['botId', 'seq']) }, // Allow on a permission ask is a grant, and Not now answers the same card. @@ -232,7 +238,8 @@ export const BOT_METHODS = { // ---------------------------------------------------------------- About → Devices (`BOT_DEVICE_METHODS`, `BOT_OFFERS_SWITCH_METHOD`) // From another device the list always keeps that device: it never shuts itself out of a bot it sets up. 'bots.devices.get': { level: 'full', local: devices(['botId']), remote: reads(['botId']) }, - 'bots.devices.set': { level: 'full', local: devices(['botId', 'access']), remote: writes(['botId', 'access']) }, + // 2: `offers: false`, Make private from that device: the bot takes no offered messages here either, closed first. + 'bots.devices.set': { level: 'full', local: devices(['botId', 'access']), remote: writes(['botId', 'access'], ['offers'], 2) }, // Whether the bot takes offered messages (issue #2490): set on its own computer alone, never from another device. 'bots.devices.offers': { level: 'local', local: devices(['botId', 'open']) }, diff --git a/src/shared/bots/personal/offers.ts b/src/shared/bots/personal/offers.ts index 65b65e374..bdb5d8e2a 100644 --- a/src/shared/bots/personal/offers.ts +++ b/src/shared/bots/personal/offers.ts @@ -20,10 +20,37 @@ export const BOT_OFFER_TOOL = 'bot_offer' * says `bots.chat.send` version 3 or more in `net.info` takes it; an older one is never sent it. */ export const BOT_OFFERS_KEY = 'offers' -/** The offers the computer the owner writes from takes; one kind so far. */ +/** The offers the computer the owner writes from takes: offered messages, each sent by a person there (stage 1). */ export const BOT_OFFERS_VERSION = 1 +/** + * It also says what becomes of each (`bots.offers.outcome`) and may hold a grant for the chat (stage 2): the offers of a + * turn its granting window started carry that message's run token back (`BOT_OFFER_RUN_KEY`). + */ +export const BOT_OFFERS_REPORTED = 2 +/** What `offers` may say. */ +export type BotOffersTaken = typeof BOT_OFFERS_VERSION | typeof BOT_OFFERS_REPORTED +export const isOffersTaken = (value: unknown): value is BotOffersTaken => value === BOT_OFFERS_VERSION || value === BOT_OFFERS_REPORTED /** The `bots.chat.send` version from which a bot's computer takes `offers`. */ export const BOT_OFFERS_SEND_VERSION = 3 +/** The `bots.chat.send` version from which it takes `offers: 2` and a run token: it reports outcomes and takes grants. */ +export const BOT_GRANT_SEND_VERSION = 4 +/** + * The key the router of the computer the owner writes from adds to a message sent from the window that holds that chat's + * grant (`bots.chat.send`): a token it made for this message alone and keeps with the grant. The bot's computer keeps it on + * the turn the message starts and stamps it on that turn's offers; the model never sees or sets it. + */ +export const BOT_OFFER_RUN_KEY = 'run' +/** A run token: a UUID, lower case. */ +export const isRunToken = (value: unknown): value is string => isOfferId(value) + +/** An offer older than this is expired: never sent, by Send or by a grant. */ +export const OFFER_TTL_MS = 24 * 60 * 60_000 +/** A grant ends after this long without a message from its window or a message it sent on. */ +export const CHAT_GRANT_IDLE_MS = 10 * 60_000 +/** A grant ends this long after it was opened, however busy. */ +export const CHAT_GRANT_MAX_MS = 60 * 60_000 +/** At most this many bots of this computer in one grant. */ +export const MAX_CHAT_GRANT_RECIPIENTS = 8 /** At most this many offers from one chat turn. */ export const MAX_OFFERS_PER_TURN = 3 @@ -63,6 +90,42 @@ export interface BotOfferCard { node?: string /** Another device only: this offer is for the device reading it. */ forYou?: true + /** + * The run token of the owner's message that started the turn (`BOT_OFFER_RUN_KEY`), stamped by the bot's computer from + * that turn: only the device it is for gets it, and sends the offer on its own only under the grant that made it. + */ + run?: string + /** + * What became of it, as the device it is for said (`bots.offers.outcome`); `queued` until then, and `unsupported` when + * that device does not say (an older Mousse). Absent on an offer made before outcomes. + */ + state?: BotOfferStored + /** `delivered`: the name of the bot it was sent to there. */ + sentTo?: string + /** When `state` last changed. */ + stateAt?: string +} + +/** What the device an offer is for may report of it. */ +export const BOT_OFFER_OUTCOMES = ['delivered', 'busy', 'expired'] as const +export type BotOfferOutcome = (typeof BOT_OFFER_OUTCOMES)[number] +export const isBotOfferOutcome = (value: unknown): value is BotOfferOutcome => typeof value === 'string' && (BOT_OFFER_OUTCOMES as readonly string[]).includes(value) +/** What the bot's computer keeps on an offer's card. */ +export type BotOfferStored = 'queued' | 'unsupported' | BotOfferOutcome + +/** Whether an offer made at `at` is past its time (`OFFER_TTL_MS`) at `now`. A time that can't be read is past. */ +export function offerExpired(at: string, now: number): boolean { + const made = Date.parse(at) + return !Number.isFinite(made) || now - made > OFFER_TTL_MS +} + +/** + * Where an offer stands, as the chat of the bot that offered it shows it: what the device it is for said, and `unknown` + * when it is past its time with nothing said (a report that was lost). + */ +export function offerShownState(card: Pick, at: string, now: number): BotOfferStored | 'unknown' { + const state = card.state ?? 'queued' + return state === 'queued' && offerExpired(at, now) ? 'unknown' : state } /** Why `message` can't be offered, in words for the bot, or undefined when it can. */ @@ -93,12 +156,17 @@ export function plainOffer(card: Pick message.split('\n').map((line) => (line ? `> ${line}` : '>')).join('\n') /** - * The card as `device` gets it from the bot's computer: never the node id kept there, and `forYou` when the offer is - * that device's. With no device (a stream every device may read), never for anyone. + * The card as `device` gets it from the bot's computer: never the node id kept there, and `forYou` with the run token + * when the offer is that device's. With no device (a stream every device may read), never for anyone. An offer for a + * device from before outcomes (`unsupported`) goes out in the shape that device reads (stage 1 takes no other field), + * so its Send keeps working; only this computer's own chat shows that state. */ export function offerCardFor(card: BotOfferCard, device: string | undefined): BotOfferCard { - const { node, forYou: _forYou, ...rest } = card - return { ...rest, ...(device !== undefined && node !== undefined && node === device ? { forYou: true as const } : {}) } + const { node, forYou: _forYou, run, ...given } = card + const { state: _state, sentTo: _sentTo, stateAt: _stateAt, ...older } = given + const rest = card.state === 'unsupported' ? older : given + const mine = device !== undefined && node !== undefined && node === device + return { ...rest, ...(mine ? { forYou: true as const, ...(run ? { run } : {}) } : {}) } } /** @@ -117,8 +185,9 @@ export function offeredRowText(input: { fromName: string; computer: string; mess * - `offline`: it can't be checked against the offering bot's computer now, so it was not sent. * - `unsupported`: the computer it would go to, or the one it came from, takes no offered messages (an older Mousse). * - `unknown`: a Send whose answer was lost: looked up here by the offer's id before Send is offered again. + * - `expired`: past its time (`OFFER_TTL_MS`), or made under a grant that ended: never sent. */ -export type BotOfferState = 'queued' | 'delivered' | 'busy' | 'offline' | 'unsupported' | 'unknown' +export type BotOfferState = 'queued' | 'delivered' | 'busy' | 'offline' | 'unsupported' | 'unknown' | 'expired' /** A bot of this computer an offered message may be sent to. */ export interface BotOfferRecipient { @@ -147,7 +216,8 @@ export const BOT_OFFER_REFUSALS = { recipient_gone: 'That bot is no longer on this computer.', sender_blocked: "Messages from that computer's bots can't be sent here now.", too_many: `This computer took ${MAX_OFFERS_KEPT_PER_HOUR} offered messages in the last hour. Try again later.`, - too_large: 'This message is too large to send.' + too_large: 'This message is too large to send.', + offer_expired: 'This offer expired.' } as const export type BotOfferRefusal = keyof typeof BOT_OFFER_REFUSALS export const isBotOfferRefusal = (value: unknown): value is BotOfferRefusal => typeof value === 'string' && Object.hasOwn(BOT_OFFER_REFUSALS, value) @@ -169,11 +239,79 @@ export interface BotOfferApi { params: { botId: string; messageId: string; seq: number; offerId: string; message: string; to: string } result: { state: 'delivered'; delivered: BotOfferDelivered; replayed?: true } } - /** `offerIds`: the offers of that chat the window shows, at most `MAX_OFFER_STATE_IDS`. */ + /** + * `offerIds`: the offers of that chat the window shows, at most `MAX_OFFER_STATE_IDS`. `expired`: those of them made + * under a grant that is not open now (it ended, or this computer restarted since), which are never sent; one past its + * time the window tells from its row. Absent from an older service. + */ 'bots.remote.offerState': { params: { botId: string; offerIds: string[] } - result: { recipients: BotOfferRecipient[]; delivered: Record } + result: { recipients: BotOfferRecipient[]; delivered: Record; expired?: string[] } } } /** The most offers one `bots.remote.offerState` names. */ export const MAX_OFFER_STATE_IDS = 200 + +/** + * Why a chat grant ended (`BotChatGrantView.ended`): + * - `ended`: End access. + * - `left`: its window left the chat, or `closed`: closed. + * - `idle`: nothing for `CHAT_GRANT_IDLE_MS`, or `expired`: `CHAT_GRANT_MAX_MS` since it opened. + * - `offline`: the chat's connection to the bot's computer dropped or came back anew (either computer restarted). + * - `private`: a bot it named was made private here, or no longer takes offered messages. + * - `blocked`: the bot's computer was blocked here, or `removed`: removed, or no longer lists the bot. + */ +export const CHAT_GRANT_ENDS = ['ended', 'left', 'closed', 'idle', 'expired', 'offline', 'private', 'blocked', 'removed'] as const +export type BotChatGrantEnd = (typeof CHAT_GRANT_ENDS)[number] + +/** + * A chat grant ("Allow for this chat", issue #2490 stage 2) as a window sees it. It is kept on this computer alone, for + * one bot of another computer: while it is open, what that bot offers one of `recipients` is sent here without a Send, + * when the turn that offered it was started by a message from the window that opened it. + */ +export interface BotChatGrantView { + active: boolean + /** This window opened it: its messages are covered, and it ends it. Another window shows it only. */ + mine?: true + /** The bots of this computer it names. */ + recipients: BotOfferRecipient[] + openedAt?: string + /** + * When it ends unless its window sends a message first: the earlier of its idle time and its end. Windows learn that + * it opened or ended from `bots.changed` with `grant` (the bot's qualified id), and read it again. + */ + endsAt?: string + /** None is open: why the last one ended, while this computer remembers. */ + ended?: BotChatGrantEnd + /** The bot's computer takes no grants (an older Mousse): offers there wait for Send, as before. */ + unsupported?: true +} + +/** + * Why a grant was not opened. Only the code crosses into the window, which says it in these words. + */ +export const BOT_GRANT_REFUSALS = { + grant_unsupported: "That bot's computer needs a newer Mousse to allow this.", + grant_elsewhere: 'Another window allowed this chat. End it there first.', + grant_not_shown: 'Open the chat first, then allow it.', + grant_offline: "That bot's computer is offline.", + grant_recipients: 'Pick at least one bot that takes messages from your bots on other computers.', + recipient_closed: BOT_OFFER_REFUSALS.recipient_closed, + recipient_gone: BOT_OFFER_REFUSALS.recipient_gone, + sender_blocked: BOT_OFFER_REFUSALS.sender_blocked +} as const +export type BotGrantRefusal = keyof typeof BOT_GRANT_REFUSALS +export const isBotGrantRefusal = (value: unknown): value is BotGrantRefusal => typeof value === 'string' && Object.hasOwn(BOT_GRANT_REFUSALS, value) + +/** + * The window's calls about chat grants, served by this computer alone and never routed or offered to another device: + * open one (a person at a Mousse window showing that chat), end it (that window), and read it (any window). + */ +export const BOT_GRANT_METHODS = ['bots.remote.grantOpen', 'bots.remote.grantEnd', 'bots.remote.grantState'] as const +export type BotGrantMethod = (typeof BOT_GRANT_METHODS)[number] +export interface BotGrantApi { + /** `botId`: the bot of another computer (qualified id). `recipients`: bots of this computer. */ + 'bots.remote.grantOpen': { params: { botId: string; recipients: string[] }; result: { grant: BotChatGrantView } } + 'bots.remote.grantEnd': { params: { botId: string }; result: { grant: BotChatGrantView } } + 'bots.remote.grantState': { params: { botId: string }; result: { grant: BotChatGrantView } } +} diff --git a/src/shared/platform.ts b/src/shared/platform.ts index 9d58492d5..0c8165d07 100644 --- a/src/shared/platform.ts +++ b/src/shared/platform.ts @@ -1,4 +1,4 @@ -import type { BotOfferMethod } from './bots/personal/offers' +import type { BotGrantMethod, BotOfferMethod } from './bots/personal/offers' import type { ChatMethod } from './chats' import type { ChatResourceMethod } from './chatResources' import type { WorkflowRunMethod } from './workflowRunPlatform' @@ -30,7 +30,7 @@ import type { RemoteDevicesMethod } from './bridge/remoteDevices' export type PlatformRequestMethod = ChatMethod | ChatResourceMethod | WorkflowRunMethod | BrowserGuiMethod | BrowserSetupMethod | BrowserTabRequestMethod | ChatNetworkMethod | NetLocalMethod | NetEngineLocalMethod | BridgeHubLocalMethod | BridgeActivityMethod | BridgeListsMethod | SpacesLocalMethod | BotsLocalMethod | SpaceArchiveMethod | SpeechHostMethod | SpeechRemoteMethod - | BotsPersonalV2Method | BotsElsewhereMethod | BotMarkMethod | BotDeviceLocalMethod | BotOfferMethod | BotsBrowserMethod | BrowserViewMethod + | BotsPersonalV2Method | BotsElsewhereMethod | BotMarkMethod | BotDeviceLocalMethod | BotOfferMethod | BotGrantMethod | BotsBrowserMethod | BrowserViewMethod | AutomationsMethod | RolloutMethod | RemoteDevicesMethod diff --git a/tests/bots/botMethodTable.test.ts b/tests/bots/botMethodTable.test.ts index 17b780644..2771cc426 100644 --- a/tests/bots/botMethodTable.test.ts +++ b/tests/bots/botMethodTable.test.ts @@ -63,6 +63,8 @@ describe('the bot method table', () => { 'bots.applets.state.save': 'use', 'bots.memory.list': 'use', 'bots.chat.send': 'use', + // What became of an offer the bot made for the calling computer: about its chat, as chat is. + 'bots.offers.outcome': 'use', // A message from a bot of the owner's on the calling computer: a message to the bot, as chat is. 'bots.botMessage.send': 'use', 'bots.chat.stop': 'use', diff --git a/tests/bots/offeredMessages.test.ts b/tests/bots/offeredMessages.test.ts index a4fdad12e..466700ffa 100644 --- a/tests/bots/offeredMessages.test.ts +++ b/tests/bots/offeredMessages.test.ts @@ -114,7 +114,9 @@ beforeEach(async () => { self: () => pc.node, enabled: () => true, emit: () => undefined, - blocked: (node) => blocked.has(node) + blocked: (node) => blocked.has(node), + // The two computers share one clock: the Mac's fixture's. + now: () => mac.f.clock.now }) }) afterEach(() => { @@ -338,10 +340,12 @@ describe('the owner sends an offered message from the PC', () => { expect(keptOnPc(alpha)).toHaveLength(1) }) - it(`keeps at most ${MAX_OFFERS_KEPT_PER_HOUR} in an hour on this computer`, async () => { + it(`keeps at most ${MAX_OFFERS_KEPT_PER_HOUR} in an hour on this computer, a cleared chat or not`, async () => { const service = pc.f.bots.service for (let n = 0; n < MAX_OFFERS_KEPT_PER_HOUR; n++) service.keepOffered({ rowId: `${OFFERED_ROW_PREFIX}${n}`, to: alpha, fromName: 'Loki', computer: 'Mac mini', message: `Note ${n}` }) expect(() => service.keepOffered({ rowId: `${OFFERED_ROW_PREFIX}late`, to: alpha, fromName: 'Loki', computer: 'Mac mini', message: 'One more' })).toThrow(expect.objectContaining({ code: 'too_many' })) + await service.chatClear(alpha) + expect(() => service.keepOffered({ rowId: `${OFFERED_ROW_PREFIX}late`, to: alpha, fromName: 'Loki', computer: 'Mac mini', message: 'One more' })).toThrow(expect.objectContaining({ code: 'too_many' })) pc.f.clock.now += 61 * 60_000 expect(service.keepOffered({ rowId: `${OFFERED_ROW_PREFIX}late`, to: alpha, fromName: 'Loki', computer: 'Mac mini', message: 'One more' }).delivered.to.botId).toBe(alpha) }) diff --git a/tests/bots/offeredMessagesGrant.test.ts b/tests/bots/offeredMessagesGrant.test.ts new file mode 100644 index 000000000..0d305a768 --- /dev/null +++ b/tests/bots/offeredMessagesGrant.test.ts @@ -0,0 +1,469 @@ +/** + * "Allow for this chat" (issue #2490 stage 2), on two real bot engines and `bots.db`s, one per computer: the Mac's real + * gate (`remoteBotMethods`) and the PC's real router (`BotRouter`), which calls the Mac one way only. The PC's chat stream + * of Loki is played by hand: its copy is the Mac's chat as the stream carries it to the PC, and what it brings in is + * handed to the router as `RemoteBotChats` does (`observe`). + * + * Rows: + * - a grant opens only from a person at a window showing that chat, for bots here that take offered messages, on a Mac + * that takes grants; another window sees it and does nothing else + * - an offer to a granted bot, from a turn the granting window's message started, is kept here without a Send: once, + * inert, and the Mac hears it went; one to another bot waits for a Send + * - another window's message, a forged token, a token of an ended grant, or an offer past its time: never sent on its own; + * expired ones are never sent by Send either, and the Mac hears so + * - every end rule ends the grant, once, and the next message carries no token + * - Make private and a block win while a Send waits on the Mac; a lost report is told again; the Mac takes reports from + * the device each offer was for alone; Make private of a Mac bot closes its offers there when the Mac takes the word + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { join } from 'node:path' +import { BotRouter, offeredRowId } from '../../src/mms/bridge/routed/BotRouter' +import type { HandlerContext } from '../../src/mms/protocol/handlers' +import { NetError, newId, type NodeId } from '../../src/shared/net' +import type { RpcContext, RpcMethod } from '../../src/mms/net/contracts' +import { fittedBotPage, remoteBotMethods, type RemoteBotMessage } from '../../src/mms/bridge/remote/RemoteBots' +import type { RemoteBotChatListener } from '../../src/mms/bridge/routed/RemoteBotChats' +import { translateNetError } from '../../src/mms/bridge/routed/computerErrors' +import { BotOfferAccessStore } from '../../src/mms/bots/definitions/BotOfferAccessStore' +import { botTools } from '../../src/mms/run/mcp/appTools/bots' +import type { MousseTool, ToolCallContext } from '../../src/mms/run/mcp/appTools/types' +import type { BotChatMessage } from '../../src/shared/bots/personal/chat' +import { OFFERED_ROW_PREFIX, OFFER_TTL_MS, isRunToken, type BotChatGrantEnd, type BotOfferCard } from '../../src/shared/bots/personal/offers' +import { qualifyId } from '../../src/shared/threadRef' +import { botFixture, chatOf, createBot, finish, flush, start, type BotFixture } from './botFixture' + +interface Computer { + node: NodeId + f: BotFixture + methods: RpcMethod[] +} + +let mac: Computer +let pc: Computer +let loki: string +let q: string +let alpha: string +let beta: string +let offers: BotOfferAccessStore +let versions: Record +let listed: boolean +let macOnline: boolean +let blocked: Set +let router: BotRouter +/** The calls the PC sent the Mac, by name, and the params of each. */ +const macCalls: Array<[string, Record]> = [] +/** Calls the Mac loses on the way back, by name, once each. */ +const lose = new Set() +/** The PC's side of Loki's chat stream: the listeners it holds, what hears what comes in, and the registry's changes. */ +const streamListeners = new Set() +const observers = new Set<(node: NodeId, botId: string, messages: readonly RemoteBotMessage[]) => void>() +const changes = new Set<() => void>() +const closings = new Set<(id: string) => void>() + +const ctx = (id: string, clientType = 'gui') => ({ connection: { clientType, id } }) as unknown as HandlerContext +const w1 = ctx('w1') +const w2 = ctx('w2') +const cli = ctx('c1', 'cli') + +async function callMac(name: string, params: Record): Promise { + macCalls.push([name, params]) + if (!macOnline) throw translateNetError(new NetError('peer_offline'), { node: mac.node, name: 'Mac mini' }, name) ?? new NetError('peer_offline') + if (lose.delete(name)) throw new NetError('deadline_exceeded') + return macHandles(pc.node, name, params) +} + +/** The Mac's gate, as a call from `caller` reaches it. */ +async function macHandles(caller: NodeId, name: string, params: Record): Promise { + const context = { caller: { node: caller, user: 'usr_owner' }, signal: new AbortController().signal } as unknown as RpcContext + const method = mac.methods.find((entry) => entry.method === name) + if (!method) throw new NetError('forbidden') + const valid = method.validate ? method.validate(params) : params + method.authorize?.(valid, context) + await method.authorizeNew?.(valid, context) + return method.handle(valid, context) +} + +/** Loki's chat as its stream carries it to the PC. */ +const pcRows = (): BotChatMessage[] => fittedBotPage(mac.f.bots.service.chatList(loki, { limit: 100 }), loki, pc.node).messages as unknown as BotChatMessage[] +/** The PC's stream brings `rows` in, as `RemoteBotChats` hands them on. */ +const streamBrings = (rows: readonly BotChatMessage[]) => { + for (const observer of [...observers]) observer(mac.node, loki, rows as unknown as RemoteBotMessage[]) +} +const offerOf = (row: { cards?: unknown[] }) => row.cards!.find((card) => (card as { type?: string }).type === 'offer') as BotOfferCard +const keptOnPc = (botId: string) => chatOf(pc.f, botId).filter((message) => message.id.startsWith(OFFERED_ROW_PREFIX)) +/** The offer's card on the Mac, as the Mac keeps it. */ +const onMac = (offerId: string) => offerOf(chatOf(mac.f, loki).find((row) => row.id === `bm_offer_${offerId}`)!) +const settled = async () => { for (let n = 0; n < 5; n++) await flush() } + +beforeEach(async () => { + versions = { 'bots.chat.send': 4, 'bots.devices.set': 2 } + listed = true + macOnline = true + blocked = new Set() + macCalls.length = 0 + lose.clear() + streamListeners.clear() + observers.clear() + changes.clear() + closings.clear() + mac = { node: newId('node') as NodeId } as Computer + mac.f = botFixture({ deviceLimit: () => 'accept_edits', deviceName: (node) => (node === pc?.node ? 'ANIMATRIX' : undefined) }) + mac.methods = remoteBotMethods({ bots: () => mac.f.bots.service, deviceLimit: () => 'accept_edits', reach: { level: () => 'use', canReach: () => true } }) + pc = { node: newId('node') as NodeId } as Computer + offers = new BotOfferAccessStore(join(mac.f.base, 'pc-bots')) + pc.f = botFixture({ offerAccess: offers }) + await mac.f.bots.reconcileOnStartup() + await pc.f.bots.reconcileOnStartup() + loki = (await createBot(mac.f, { name: 'Loki', description: 'Watch the Mac builds.', reply: 'Hello.' })).botId + q = qualifyId(mac.node, loki) + alpha = (await createBot(pc.f, { name: 'Alpha', description: 'Keep track of bugs.', reply: 'Hello.' })).botId + beta = (await createBot(pc.f, { name: 'Beta', description: 'Plan the week.', reply: 'Hello.' })).botId + router = new BotRouter({ + client: { callBot: (_node: NodeId, method: string, params: Record) => callMac(method, params), botVersions: async () => versions } as never, + registry: { + row: (node: NodeId, botId: string) => (listed && node === mac.node && botId === loki ? { name: 'Loki', node, botId } : undefined), + rows: () => [], + onChange: (listener: () => void) => { changes.add(listener); return () => changes.delete(listener) }, + chats: { + open: async (_node: NodeId, _botId: string, listener: RemoteBotChatListener = {}) => { + streamListeners.add(listener) + return { close: () => streamListeners.delete(listener) } + }, + messages: () => pcRows(), + observe: (listener: (node: NodeId, botId: string, messages: readonly RemoteBotMessage[]) => void) => { observers.add(listener); return () => observers.delete(listener) } + } + } as never, + localBots: () => pc.f.bots.service, + online: () => macOnline, + name: () => 'Mac mini', + self: () => pc.node, + enabled: () => true, + emit: () => undefined, + blocked: (node) => blocked.has(node), + offersClosed: (listener) => offers.onClosed(listener), + onConnectionClosed: (listener) => { closings.add(listener); return () => closings.delete(listener) }, + now: () => mac.f.clock.now + }) +}) +afterEach(() => { + router.close() + mac.f.close() + pc.f.close() +}) + +async function tool(prepared: Awaited>['prepared'], threadId: string, name: string, args: Record): Promise<{ text: string; isError?: boolean }> { + const tools = new Map(botTools(() => ({ host: mac.f.bots.tools })).map((entry) => [entry.name, entry])) + const call = { caller: { threadId, runId: 'r', provider: 'pi', accessLevel: 'lineage' }, turn: { threadId, bot: prepared.authority }, toolCallId: `call-${Math.random()}`, signal: new AbortController().signal, transport: 'mcp' } as unknown as ToolCallContext + return (tools.get(name) as MousseTool).handler(args, call) +} + +/** The owner writes to Loki from window `from`; Loki's chat turn that message started, running. */ +async function ownerFrom(from: HandlerContext, text: string) { + await router.dispatch(from, 'bots.chat.send', { botId: q, text, clientRequestId: `m-${Math.random()}` }) + await flush() + const activation = mac.f.store.laneActivations(loki, 'chat', ['running'])[0]! + return { activation, ...(await start(mac.f, activation.id)) } +} + +/** Loki offers `message` (for `to`) in `turn`; the row as the PC's stream carries it. */ +async function offers_(turn: Awaited>, message: string, to?: string) { + const answer = await tool(turn.prepared, turn.payload.threadId, 'bot_offer', { message, ...(to ? { to } : {}) }) + expect(answer.isError, answer.text).toBeFalsy() + const row = pcRows().filter((entry) => entry.id.startsWith('bm_offer_')).at(-1)! + return { row, card: offerOf(row) } +} + +const send = (from: HandlerContext, row: BotChatMessage, card: BotOfferCard, to: string) => + router.offerSend(from, { botId: q, messageId: row.id, seq: row.seq, offerId: card.offerId, message: card.message, to }) + +/** The window shows Loki's chat, and allows it for `recipients`. */ +async function allow(from: HandlerContext, recipients: string[]) { + await router.focus(from, q, true) + return router.grantOpen(from, { botId: q, recipients }) +} + +describe('Allow for this chat', () => { + it('opens only from a person at a window showing the chat, for bots here that take offered messages, on a Mac that takes grants', async () => { + await expect(router.grantOpen(cli, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'forbidden' }) + await expect(router.grantOpen(w1, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'grant_not_shown' }) + await router.focus(w1, q, true) + await expect(router.grantOpen(w1, { botId: q, recipients: [] })).rejects.toMatchObject({ code: 'grant_recipients' }) + await expect(router.grantOpen(w1, { botId: q, recipients: ['bot-000000000000'] })).rejects.toMatchObject({ code: 'recipient_gone' }) + offers.set(beta, false) + await expect(router.grantOpen(w1, { botId: q, recipients: [alpha, beta] })).rejects.toMatchObject({ code: 'recipient_closed' }) + blocked.add(mac.node) + await expect(router.grantOpen(w1, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'sender_blocked' }) + blocked.clear() + macOnline = false + await expect(router.grantOpen(w1, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'grant_offline' }) + macOnline = true + // A Mac from before grants: refused, and every window says so. No wider way. + versions = { 'bots.chat.send': 3 } + await expect(router.grantOpen(w1, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'grant_unsupported' }) + expect((await router.grantState(w2, { botId: q })).grant).toMatchObject({ active: false, unsupported: true }) + versions = { 'bots.chat.send': 4 } + + expect((await router.grantOpen(w1, { botId: q, recipients: [alpha] })).grant).toMatchObject({ active: true, mine: true, recipients: [{ botId: alpha, name: 'Alpha' }] }) + // Another window sees it, and does nothing else. + expect((await router.grantState(w2, { botId: q })).grant).toMatchObject({ active: true, recipients: [{ botId: alpha, name: 'Alpha' }] }) + expect((await router.grantState(w2, { botId: q })).grant).not.toHaveProperty('mine') + await router.focus(w2, q, true) + await expect(router.grantOpen(w2, { botId: q, recipients: [alpha] })).rejects.toMatchObject({ code: 'grant_elsewhere' }) + expect(() => router.grantEnd(w2, { botId: q })).toThrow(expect.objectContaining({ code: 'grant_elsewhere' })) + expect((await router.grantState(w1, { botId: q })).grant).toMatchObject({ active: true, mine: true }) + }) + + it('an offer to a granted bot, in a turn the window\'s message started, is kept there once with no Send, starts nothing, and the Mac hears it went', async () => { + await allow(w1, [alpha]) + const turn = await ownerFrom(w1, 'If the build breaks, tell Alpha.') + const owner = (turn.activation.trigger as { owner?: { offers?: number; run?: string } }).owner + expect(owner).toMatchObject({ node: pc.node, offers: 2 }) + expect(isRunToken(owner?.run)).toBe(true) + const turnsBefore = pc.f.store.listActivations(alpha).length + const { row, card } = await offers_(turn, 'Build 412 fails on the login page.', 'alpha') + expect(card).toMatchObject({ forYou: true, run: owner!.run, state: 'queued' }) + + streamBrings([row]) + await settled() + expect(keptOnPc(alpha)).toHaveLength(1) + expect(pc.f.store.listActivations(alpha)).toHaveLength(turnsBefore) + expect(onMac(card.offerId)).toMatchObject({ state: 'delivered', sentTo: 'Alpha' }) + // The stream brings it again (its outcome, a snapshot): still once, and told once. + streamBrings(pcRows()) + await settled() + expect(keptOnPc(alpha)).toHaveLength(1) + expect(macCalls.filter(([name]) => name === 'bots.offers.outcome')).toHaveLength(1) + + // One for a bot the grant does not name, or naming none, waits for a Send; Send then keeps it. + const other = await offers_(turn, 'Plan a fix for Friday.', 'Beta') + const unnamed = await offers_(turn, 'Ping someone.') + streamBrings([other.row, unnamed.row]) + await settled() + expect(keptOnPc(beta)).toEqual([]) + expect(onMac(other.card.offerId).state).toBe('queued') + expect(await send(w1, other.row, other.card, beta)).toMatchObject({ state: 'delivered' }) + await settled() + expect(onMac(other.card.offerId)).toMatchObject({ state: 'delivered', sentTo: 'Beta' }) + }) + + it('another window\'s message carries no token, and a forged token is never one of the grant\'s: neither offer is sent on its own', async () => { + await allow(w1, [alpha]) + await router.focus(w2, q, true) + const fromW2 = await ownerFrom(w2, 'Tell Alpha.') + expect((fromW2.activation.trigger as { owner?: { run?: string } }).owner?.run).toBeUndefined() + const plain = await offers_(fromW2, 'From the second window.', 'Alpha') + streamBrings([plain.row]) + await settled() + expect(keptOnPc(alpha)).toEqual([]) + await finish(mac.f, fromW2.payload, 'completed', { text: 'ok' }) + + // A turn whose token the PC never issued (written on the Mac's turn by hand): expired, by grant and by Send. + const turn = await ownerFrom(w1, 'Tell Alpha.') + const forged = '6f1d2a8e-4b0c-4c3e-9a1b-7d2e5f3a9c11' + const trigger = { ...turn.activation.trigger, owner: { ...(turn.activation.trigger as { owner: object }).owner, run: forged } } + mac.f.store.run('UPDATE bot_activations SET trigger_json = ? WHERE id = ?', JSON.stringify(trigger), turn.activation.id) + const { row, card } = await offers_(turn, 'Forged.', 'Alpha') + expect(card.run).toBe(forged) + streamBrings([row]) + await settled() + expect(keptOnPc(alpha)).toEqual([]) + expect(onMac(card.offerId).state).toBe('expired') + await expect(send(w1, row, card, alpha)).rejects.toMatchObject({ code: 'offer_expired' }) + }) + + it('another window\'s message that joins a granted turn takes its token off; a resend carries the token it was first sent with', async () => { + const runOf = (trigger: unknown) => (trigger as { owner?: { run?: string } }).owner?.run + await allow(w1, [alpha]) + await router.focus(w2, q, true) + const granted = await ownerFrom(w1, 'Tell Alpha when it builds.') + expect(isRunToken(runOf(granted.activation.trigger))).toBe(true) + await router.dispatch(w2, 'bots.chat.send', { botId: q, text: 'And add this.', clientRequestId: 'join-w2' }) + await flush() + expect(runOf(mac.f.store.activation(granted.activation.id)!.trigger)).toBeUndefined() + const after = await offers_(granted, 'After the join.', 'Alpha') + expect(after.card).not.toHaveProperty('run') + streamBrings([after.row]) + await settled() + expect(keptOnPc(alpha)).toEqual([]) + await finish(mac.f, granted.payload, 'completed', { text: 'ok' }) + + // The same message sent again (its answer lost): the token it first went with, the grant ended or not. + const sentRun = () => (macCalls.filter(([name]) => name === 'bots.chat.send').at(-1)![1] as { run?: string }).run + await router.dispatch(w1, 'bots.chat.send', { botId: q, text: 'Once.', clientRequestId: 'resend-1' }) + const first = sentRun() + expect(isRunToken(first)).toBe(true) + router.grantEnd(w1, { botId: q }) + await router.dispatch(w1, 'bots.chat.send', { botId: q, text: 'Once.', clientRequestId: 'resend-1' }).catch(() => undefined) + expect(sentRun()).toBe(first) + }) + + it.each<[BotChatGrantEnd, string, () => void | Promise]>([ + ['ended', 'End access', () => { router.grantEnd(w1, { botId: q }) }], + ['left', 'leaving the chat', async () => { await router.focus(w1, q, false) }], + ['closed', 'closing the window', () => { for (const close of [...closings]) close('w1') }], + ['private', 'Make private of a granted bot', () => { offers.set(alpha, false) }], + ['blocked', 'blocking the Mac', () => { blocked.add(mac.node); for (const change of [...changes]) change() }], + ['removed', 'the Mac no longer listing Loki here', () => { listed = false; for (const change of [...changes]) change() }], + ['offline', 'losing the Mac', () => { macOnline = false; for (const change of [...changes]) change() }], + ['offline', 'the stream coming back anew (a restart)', () => { for (const listener of [...streamListeners]) listener.snapshot?.() }], + ['offline', 'the stream replaying from its copy (a dropped connection came back)', () => { for (const listener of [...streamListeners]) listener.restarted?.() }], + ['offline', 'the stream ending', () => { for (const listener of [...streamListeners]) listener.ended?.('peer_offline') }], + ['removed', 'the Mac no longer offering Loki here (its stream ends so)', () => { for (const listener of [...streamListeners]) listener.ended?.('stream_unknown') }] + ])('ends on %s (%s), once; what it left unsent is expired and the Mac hears so; nothing reopens it', async (reason, _what, endIt) => { + await allow(w1, [alpha]) + const turn = await ownerFrom(w1, 'Tell Beta.') + // An offer under it that waits for a Send (not a granted bot). + const waiting = await offers_(turn, 'For Beta.', 'Beta') + await endIt() + await settled() + expect((await router.grantState(w1, { botId: q })).grant).toMatchObject({ active: false, ended: reason }) + expect(router.grants.all()).toEqual([]) + if (reason !== 'offline' && reason !== 'blocked' && reason !== 'removed') expect(onMac(waiting.card.offerId).state).toBe('expired') + // Another offer of that same turn: expired, never sent; Send too. + macOnline = true + listed = true + blocked.clear() + offers.set(alpha, true) + const late = await offers_(turn, 'After the end.', 'Alpha') + streamBrings([late.row]) + await settled() + expect(keptOnPc(alpha)).toEqual([]) + await expect(send(w1, late.row, late.card, alpha)).rejects.toMatchObject({ code: 'offer_expired' }) + await finish(mac.f, turn.payload, 'completed', { text: 'ok' }) + // The window's next message carries no token. + await router.focus(w1, q, true) + const next = await ownerFrom(w1, 'Again.') + expect((next.activation.trigger as { owner?: { run?: string } }).owner?.run).toBeUndefined() + }) + + it('Make private and a block win even while a Send waits on the Mac', async () => { + const turn = await ownerFrom(w1, 'Tell Alpha.') + const { row, card } = await offers_(turn, 'Waits on the Mac.', 'Alpha') + // The copy lacks it, so Send reads it from the Mac; meanwhile Alpha is made private. + const chats = (router as unknown as { options: { registry: { chats: { messages: () => unknown[] } } } }).options.registry.chats + const copyless = vi.spyOn(chats, 'messages').mockReturnValue([]) + const real = (router as unknown as { options: { client: { callBot: (...args: unknown[]) => Promise } } }).options.client + const callBot = real.callBot + real.callBot = async (...args: unknown[]) => { + const answer = await callBot(...args) + if (args[1] === 'bots.chat.list') offers.set(alpha, false) + return answer + } + await expect(send(w1, row, card, alpha)).rejects.toMatchObject({ code: 'recipient_closed' }) + offers.set(alpha, true) + real.callBot = async (...args: unknown[]) => { + const answer = await callBot(...args) + if (args[1] === 'bots.chat.list') blocked.add(mac.node) + return answer + } + await expect(send(w1, row, card, alpha)).rejects.toMatchObject({ code: 'sender_blocked' }) + copyless.mockRestore() + expect(keptOnPc(alpha)).toEqual([]) + }) + + it('an offer past its time is expired, by Send and by grant, and the Mac hears so; one with no word from the PC shows unknown there', async () => { + await allow(w1, [alpha]) + const turn = await ownerFrom(w1, 'Tell Alpha later.') + const { row, card } = await offers_(turn, 'Old news.', 'Beta') + mac.f.clock.now += OFFER_TTL_MS + 60_000 + await expect(send(w1, row, card, beta)).rejects.toMatchObject({ code: 'offer_expired' }) + // Send found it expired: the Mac hears so then, not only when the offer next comes in. + await settled() + expect(onMac(card.offerId).state).toBe('expired') + // Expired is final there: a late report of another state changes nothing. + await macHandles(pc.node, 'bots.offers.outcome', { botId: loki, offerId: card.offerId, state: 'busy' }) + expect(onMac(card.offerId).state).toBe('expired') + }) + + it('a grant opened later never takes over a turn an ended one started; End access wins over an Allow still on its way', async () => { + const runOf = (trigger: unknown) => (trigger as { owner?: { run?: string } }).owner?.run + await allow(w1, [alpha]) + const turn = await ownerFrom(w1, 'Tell Alpha when it builds.') + const first = runOf(turn.activation.trigger) + router.grantEnd(w1, { botId: q }) + await allow(w2, [alpha]) + // The second window's message, with its own grant's token, joins the turn: the turn keeps its own, now dead. + await router.dispatch(w2, 'bots.chat.send', { botId: q, text: 'And this.', clientRequestId: 'join-new-grant' }) + await flush() + expect(runOf(mac.f.store.activation(turn.activation.id)!.trigger)).toBe(first) + const { row, card } = await offers_(turn, 'After the takeover try.', 'Alpha') + streamBrings([row]) + await settled() + expect(keptOnPc(alpha)).toEqual([]) + expect(onMac(card.offerId).state).toBe('expired') + router.grantEnd(w2, { botId: q }) + + // Allow, then End access while Allow still waits on the Mac's versions: nothing opens after the end. + await allow(w1, [alpha]) + const client = (router as unknown as { options: { client: { botVersions: () => Promise> } } }).options.client + let release!: () => void + const held = new Promise((resolve) => { release = resolve }) + const versionsNow = vi.spyOn(client, 'botVersions').mockImplementationOnce(async () => { await held; return versions }) + const pending = router.grantOpen(w1, { botId: q, recipients: [alpha, beta] }) + await flush() + expect(router.grantEnd(w1, { botId: q }).grant).toMatchObject({ active: false, ended: 'ended' }) + release() + expect((await pending).grant).toMatchObject({ active: false }) + expect(router.grants.all()).toEqual([]) + versionsNow.mockRestore() + }) + + it('a report that was lost is told again the next time the offer comes in, or on its own a while later; the Mac takes reports from the device it was for alone', async () => { + const turn = await ownerFrom(w1, 'Tell Alpha.') + const { row, card } = await offers_(turn, 'Lost on the way back.', 'Alpha') + lose.add('bots.offers.outcome') + expect(await send(w1, row, card, alpha)).toMatchObject({ state: 'delivered' }) + await settled() + expect(onMac(card.offerId).state).toBe('queued') + streamBrings([row]) + await settled() + expect(onMac(card.offerId)).toMatchObject({ state: 'delivered', sentTo: 'Alpha' }) + + // One that never comes in again (a busy chat pushed it out of the next snapshot): told on its own. + const quiet = await offers_(turn, 'Pushed out of the snapshot.', 'Alpha') + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + try { + lose.add('bots.offers.outcome') + expect(await send(w1, quiet.row, quiet.card, alpha)).toMatchObject({ state: 'delivered' }) + await settled() + expect(onMac(quiet.card.offerId).state).toBe('queued') + await vi.advanceTimersByTimeAsync(30_000) + } finally { + vi.useRealTimers() + } + await settled() + expect(onMac(quiet.card.offerId)).toMatchObject({ state: 'delivered', sentTo: 'Alpha' }) + + // Another device says it was sent, or expired: there is no such offer for it. + const other = await offers_(turn, 'Only for the PC.', 'Alpha') + await expect(macHandles(newId('node') as NodeId, 'bots.offers.outcome', { botId: loki, offerId: other.card.offerId, state: 'delivered', to: 'Alpha' })).rejects.toMatchObject({ code: 'stream_unknown' }) + expect(onMac(other.card.offerId).state).toBe('queued') + // Sent is final. + await macHandles(pc.node, 'bots.offers.outcome', { botId: loki, offerId: card.offerId, state: 'expired' }) + expect(onMac(card.offerId).state).toBe('delivered') + }) + + it('Make private of a Mac bot ends its chat\'s grant here and asks the Mac to close its offered messages too, when the Mac takes the word', async () => { + const devicesSet = () => macCalls.filter(([name]) => name === 'bots.devices.set').at(-1)![1] + await allow(w1, [alpha]) + await router.dispatch(w1, 'bots.devices.set', { botId: q, access: { mode: 'this_computer' }, offers: false }).catch(() => undefined) + expect((await router.grantState(w1, { botId: q })).grant).toMatchObject({ active: false, ended: 'private' }) + expect(devicesSet()).toMatchObject({ offers: false }) + versions = { 'bots.chat.send': 4, 'bots.devices.set': 1 } + await router.dispatch(w1, 'bots.devices.set', { botId: q, access: { mode: 'this_computer' }, offers: false }).catch(() => undefined) + expect(devicesSet()).not.toHaveProperty('offers') + // A window never opens them there. + await expect(router.dispatch(w1, 'bots.devices.set', { botId: q, access: { mode: 'this_computer' }, offers: true })).rejects.toMatchObject({ code: 'invalid_params' }) + }) + + it('a PC that does not report (stage 1) has its offers marked unsupported on the Mac, and reads them in the shape it knows', async () => { + versions = { 'bots.chat.send': 3 } + const turn = await ownerFrom(w1, 'Tell Alpha.') + expect((turn.activation.trigger as { owner?: { offers?: number } }).owner?.offers).toBe(1) + const { card } = await offers_(turn, 'Older PC.', 'Alpha') + expect(onMac(card.offerId).state).toBe('unsupported') + // As the PC reads it: stage 1's card fields alone (its parser refuses any other), so its Send still works. + expect(Object.keys(card).sort()).toEqual(['computer', 'forYou', 'message', 'offerId', 'to', 'type']) + expect(offeredRowId(mac.node, loki, card.offerId)).toMatch(/^bm_offered_/) + }) +}) diff --git a/tests/net/bridge/remote/botDeviceAccess.test.ts b/tests/net/bridge/remote/botDeviceAccess.test.ts index b7db7cbad..9e5e23eb1 100644 --- a/tests/net/bridge/remote/botDeviceAccess.test.ts +++ b/tests/net/bridge/remote/botDeviceAccess.test.ts @@ -88,6 +88,7 @@ function paramsFor(botId: string): Record> { 'bots.systemInstructions.set': { botId, text: 'My own rules.', window: 'person' }, 'bots.devices.get': { botId }, 'bots.devices.set': { botId, access: { mode: 'this_computer' } }, + 'bots.offers.outcome': { botId, offerId: '0d6b3b62-8a5b-4b0c-9f1e-2f6c1d1a7b10', state: 'delivered' }, 'bots.browser.get': { botId }, 'bots.browser.open': { botId }, 'bots.browser.hold': { botId, viewId: 'v1', request: { op: 'take' } }, diff --git a/tests/net/bridge/remote/bots.test.ts b/tests/net/bridge/remote/bots.test.ts index aff1d4608..014e0846a 100644 --- a/tests/net/bridge/remote/bots.test.ts +++ b/tests/net/bridge/remote/bots.test.ts @@ -239,8 +239,10 @@ describe('bot method params', () => { }) const methods = remoteBotMethods({ bots: () => undefined }) expect(methods.map((entry) => entry.method).sort()).toEqual(Object.keys(REMOTE_BOT_METHODS).sort()) - // A read's result (the chat, the model rows, the devices) is never kept in the request ledger. - expect(methods.filter((entry) => entry.ephemeral).map((entry) => entry.method).sort()).toEqual(['bots.applets.get', 'bots.applets.state.get', 'bots.browser.get', 'bots.browser.hold', 'bots.browser.open', 'bots.browser.send', 'bots.browser.tab', 'bots.chat.attachment', 'bots.chat.file', 'bots.chat.list', 'bots.chat.webPicture', 'bots.devices.get', 'bots.get', 'bots.memory.list', 'bots.model.choices', 'bots.model.get', 'bots.systemInstructions.get', 'bots.transfer.read']) + // A read's result (the chat, the model rows, the devices) is never kept in the request ledger; nor is an offer's + // outcome, which the same report again leaves as it was. + expect(methods.filter((entry) => entry.ephemeral).map((entry) => entry.method).sort()).toEqual(['bots.applets.get', 'bots.applets.state.get', 'bots.browser.get', 'bots.browser.hold', 'bots.browser.open', 'bots.browser.send', 'bots.browser.tab', 'bots.chat.attachment', 'bots.chat.file', 'bots.chat.list', 'bots.chat.webPicture', 'bots.devices.get', 'bots.get', 'bots.memory.list', 'bots.model.choices', 'bots.model.get', 'bots.offers.outcome', 'bots.systemInstructions.get', 'bots.transfer.read']) + expect(REMOTE_BOT_METHODS).toMatchObject({ 'bots.offers.outcome': { capability: 'chat', mutating: false } }) expect(REMOTE_BOT_METHODS).toMatchObject({ 'bots.chat.attachment': { capability: 'read', mutating: false }, 'bots.chat.file': { capability: 'read', mutating: false }, @@ -661,6 +663,7 @@ describe('the bot level of the calling device', () => { 'bots.memory.list': { botId: BOT }, 'bots.chat.send': { botId: BOT, text: 'Hi', clientRequestId: 'r1' }, 'bots.botMessage.send': { botId: BOT, from: { botId: 'bot-0123456789ac', name: 'Loki', chain: 1 }, message: 'Hi', clientRequestId: '00000000-0000-4000-8000-000000000000' }, + 'bots.offers.outcome': { botId: BOT, offerId: '0d6b3b62-8a5b-4b0c-9f1e-2f6c1d1a7b10', state: 'delivered', to: 'Alpha' }, 'bots.chat.stop': { botId: BOT }, 'bots.work.stop': { botId: BOT, workId: 'act_00000000-0000-0000-0000-000000000000' }, 'bots.chat.markRead': { botId: BOT, seq: 1 }, @@ -708,7 +711,7 @@ describe('the bot level of the calling device', () => { } const names = Object.keys(REMOTE_BOT_METHODS) as RemoteBotMethod[] /** The rows another device may call at Use; every other remote row needs Full. */ - const USE_ROWS = ['bots.botMessage.send', 'bots.get', 'bots.chat.list', 'bots.chat.attachment', 'bots.chat.file', 'bots.stage', 'bots.send.open', 'bots.applets.get', 'bots.applets.state.get', 'bots.applets.state.save', 'bots.memory.list', 'bots.chat.send', 'bots.chat.stop', 'bots.work.stop', 'bots.chat.markRead', 'bots.questions.answer', 'bots.reminders.snooze', 'bots.chat.react', 'bots.chat.webPicture', 'bots.actions.answer', 'bots.chainHold.answer', 'bots.browser.get'] + const USE_ROWS = ['bots.botMessage.send', 'bots.offers.outcome', 'bots.get', 'bots.chat.list', 'bots.chat.attachment', 'bots.chat.file', 'bots.stage', 'bots.send.open', 'bots.applets.get', 'bots.applets.state.get', 'bots.applets.state.save', 'bots.memory.list', 'bots.chat.send', 'bots.chat.stop', 'bots.work.stop', 'bots.chat.markRead', 'bots.questions.answer', 'bots.reminders.snooze', 'bots.chat.react', 'bots.chat.webPicture', 'bots.actions.answer', 'bots.chainHold.answer', 'bots.browser.get'] /** Methods over a port that counts every read, for a device at `level`. */ const counted = (level: BotLevel) => { const seen = { reads: 0 } diff --git a/tests/net/bridge/routed/chatGrants.test.ts b/tests/net/bridge/routed/chatGrants.test.ts new file mode 100644 index 000000000..194ca9ad4 --- /dev/null +++ b/tests/net/bridge/routed/chatGrants.test.ts @@ -0,0 +1,105 @@ +/** + * Chat grants ("Allow for this chat", issue #2490 stage 2) as this computer keeps them (`ChatGrants`), on a clock of + * the test's: a token is issued only for the window that opened the chat's grant and is held only while that grant is + * open; it ends once, after its idle time or at its end however busy, and a token of an ended grant is held by none, + * not even by the chat's next grant. + */ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import type { NodeId } from '../../../../src/shared/net' +import { ChatGrants, type ChatGrant } from '../../../../src/mms/bridge/routed/chatGrants' +import type { BotChatGrantEnd } from '../../../../src/shared/bots/personal/offers' + +const MAC = 'nod_mac' as NodeId +const IDLE = 10_000 +const MAX = 60_000 + +let grants: ChatGrants +let ended: Array<[string, BotChatGrantEnd]> +let changed: number +const name = (botId: string) => ({ botId, name: botId.toUpperCase() }) + +beforeEach(() => { + vi.useFakeTimers() + ended = [] + changed = 0 + grants = new ChatGrants({ now: () => Date.now(), changed: () => { changed += 1 }, ended: (grant: ChatGrant, reason) => ended.push([grant.botId, reason]), idleMs: IDLE, maxMs: MAX }) +}) +afterEach(() => { + grants.close() + vi.useRealTimers() +}) + +describe('a chat grant', () => { + it('issues a token to its own window alone, and holds it while open only, never in the next grant', () => { + const stream = { close: vi.fn() } + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'], stream }) + expect(grants.issueRun(MAC, 'loki', 'w2')).toBeUndefined() + const run = grants.issueRun(MAC, 'loki', 'w1')! + expect(grants.holds(MAC, 'loki', run)).toBeTruthy() + expect(grants.holds(MAC, 'other', run)).toBeUndefined() + expect(grants.view(MAC, 'loki', 'w1', name)).toMatchObject({ active: true, mine: true, recipients: [{ botId: 'alpha', name: 'ALPHA' }] }) + expect(grants.view(MAC, 'loki', 'w2', name)).not.toHaveProperty('mine') + + expect(grants.end(MAC, 'loki', 'ended')).toBe(true) + expect(grants.end(MAC, 'loki', 'left')).toBe(false) + expect(ended).toEqual([['loki', 'ended']]) + expect(stream.close).toHaveBeenCalledTimes(1) + expect(grants.holds(MAC, 'loki', run)).toBeUndefined() + expect(grants.view(MAC, 'loki', 'w1', name)).toEqual({ active: false, recipients: [], ended: 'ended' }) + + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + expect(grants.holds(MAC, 'loki', run)).toBeUndefined() + }) + + it('the same window allowing it again keeps its tokens; another window can only follow an end', () => { + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + const run = grants.issueRun(MAC, 'loki', 'w1')! + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha', 'beta'] }) + expect(grants.holds(MAC, 'loki', run)?.recipients).toEqual(['alpha', 'beta']) + expect(ended).toEqual([]) + grants.start({ node: MAC, botId: 'loki', window: 'w2', recipients: ['beta'] }) + expect(grants.holds(MAC, 'loki', run)).toBeUndefined() + expect(ended).toEqual([['loki', 'ended']]) + }) + + it('ends after its idle time, which a message from its window starts again', () => { + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + vi.advanceTimersByTime(IDLE - 1_000) + grants.issueRun(MAC, 'loki', 'w1') + vi.advanceTimersByTime(IDLE - 1_000) + expect(grants.get(MAC, 'loki')).toBeDefined() + vi.advanceTimersByTime(1_000) + expect(grants.get(MAC, 'loki')).toBeUndefined() + expect(ended).toEqual([['loki', 'idle']]) + }) + + it('holds nothing past its time though its timer has not run yet (a busy event loop)', () => { + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + const run = grants.issueRun(MAC, 'loki', 'w1')! + // The clock moves on with no timer run. + vi.setSystemTime(Date.now() + IDLE + 1) + expect(grants.holds(MAC, 'loki', run)).toBeUndefined() + expect(grants.issueRun(MAC, 'loki', 'w1')).toBeUndefined() + expect(ended).toEqual([['loki', 'idle']]) + expect(grants.ends(MAC, 'loki')).toBe(1) + }) + + it('ends at its end however busy', () => { + const grant = grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + for (let at = 0; at < MAX; at += IDLE / 2) { + vi.advanceTimersByTime(IDLE / 2) + grants.touch(grant) + } + expect(grants.get(MAC, 'loki')).toBeUndefined() + expect(ended).toEqual([['loki', 'expired']]) + }) + + it('every grant a match names ends, each once', () => { + grants.start({ node: MAC, botId: 'loki', window: 'w1', recipients: ['alpha'] }) + grants.start({ node: MAC, botId: 'odin', window: 'w1', recipients: ['beta'] }) + expect(grants.endWhere((grant) => grant.recipients.includes('alpha'), 'private')).toBe(1) + expect(grants.endWhere((grant) => grant.window === 'w1', 'closed')).toBe(1) + expect(ended).toEqual([['loki', 'private'], ['odin', 'closed']]) + expect(changed).toBe(4) + }) +}) diff --git a/tests/netEngine/checks/offeredMessagesOneWay.test.ts b/tests/netEngine/checks/offeredMessagesOneWay.test.ts index 5997368b9..5c4132391 100644 --- a/tests/netEngine/checks/offeredMessagesOneWay.test.ts +++ b/tests/netEngine/checks/offeredMessagesOneWay.test.ts @@ -66,10 +66,10 @@ describe('an offered message over a one-way pairing', () => { params ) /** The owner writes to Loki from a PC window; the Mac's chat turn it queued, set running as a provider would. */ - const ownerWrites = async (text: string, id: string) => { + const ownerWrites = async (text: string, id: string, local = false) => { // The turn before has ended, so this message starts a turn of its own rather than joining that one. macStore().run("UPDATE bot_activations SET status = 'done', ended_at = ? WHERE bot_id = ? AND status = 'running'", new Date().toISOString(), loki) - await pc.dispatch('bots.chat.send', { botId: q, text, clientRequestId: id }) + await pc.dispatch('bots.chat.send', { botId: q, text, clientRequestId: id }, local) let activation: ReturnType[number] | undefined await eventually(() => { activation = macStore().laneActivations(loki, 'chat', ['queued']).find((row) => row.idempotencyKey === `chat:${id}`) @@ -118,8 +118,10 @@ describe('an offered message over a one-way pairing', () => { it('is offered by the Mac bot, read by the PC on its own stream, and kept once on the PC by a person', async () => { const turn = await ownerWrites('If the build breaks, tell Alpha.', 'one-way-1') - // The PC's router said with the owner's message that the PC takes offers; the Mac kept it on that turn. - expect(turn.trigger).toMatchObject({ kind: 'manual', owner: { node: pcOnMac, offers: 1 } }) + // The PC's router said with the owner's message that the PC takes offers and reports them; the Mac kept it on that + // turn. No grant: no run token. + expect(turn.trigger).toMatchObject({ kind: 'manual', owner: { node: pcOnMac, offers: 2 } }) + expect((turn.trigger as { owner?: { run?: unknown } }).owner?.run).toBeUndefined() const offered = mac.mms.personalBots!.tools.bots!.offer!(loki, turn.id, { message: 'Build 412 fails on the login page.', to: 'Alpha', requestKey: 'k1' }) expect(offered).toMatchObject({ offerId: expect.any(String) }) @@ -172,4 +174,109 @@ describe('an offered message over a one-way pairing', () => { } expect(macCalledPc()).toBe(0) }, 120_000) + + describe('with "Allow for this chat" (stage 2)', () => { + /** The PC's window-1, or with `local` its second window, as the harness's `dispatch` names them. */ + const grantOpen = (local = false) => pc.dispatch('bots.remote.grantOpen', { botId: q, recipients: [alpha] }, local) as Promise<{ grant: Record }> + const grantState = async (local = false) => ((await pc.dispatch('bots.remote.grantState', { botId: q }, local)) as { grant: Record }).grant + /** The PC's window-1 shows Loki's chat, with its stream open, then allows it for Alpha. */ + const allow = async () => { + await vi.waitFor(() => expect(pc.mms.bridge.remoteBots.row(macOnPc, loki)?.offline).toBeUndefined(), { timeout: 60_000 }) + await pc.dispatch('bots.focus', { botId: q, focused: true }) + await vi.waitFor(() => expect(pc.mms.bridge.botRouter.attached.state().find((chat) => chat.botId === loki)?.open).toBe(true), { timeout: 30_000 }) + return grantOpen() + } + const runOf = (turn: { trigger: unknown }) => (turn.trigger as { owner?: { run?: string } }).owner?.run + const offer = (turnId: string, message: string, to: string) => mac.mms.personalBots!.tools.bots!.offer!(loki, turnId, { message, to, requestKey: `k-${Math.random()}` }) + const onMac = (offerId: string) => mac.mms.personalBots!.service.chatList(loki, { limit: 200 }).messages.find((row) => row.id === `bm_offer_${offerId}`)!.cards!.find((card) => card.type === 'offer') as BotOfferCard + const ended = async (reason: string) => vi.waitFor(async () => expect(await grantState()).toMatchObject({ active: false, ended: reason }), { timeout: 60_000 }) + + it('sends a granted bot\'s offer with no Send, once, and the Mac hears it went; a second window sees it and does nothing else', async () => { + expect((await allow()).grant).toMatchObject({ active: true, mine: true, recipients: [{ botId: alpha, name: 'Alpha' }] }) + const before = keptOnPc(alpha).length + const turn = await ownerWrites('If the build breaks, tell Alpha.', 'grant-1') + expect(runOf(turn)).toEqual(expect.any(String)) + const { offerId } = offer(turn.id, 'Build 413 fails too.', 'Alpha') + await vi.waitFor(() => expect(keptOnPc(alpha)).toHaveLength(before + 1), { timeout: 30_000 }) + await vi.waitFor(() => expect(onMac(offerId)).toMatchObject({ state: 'delivered', sentTo: 'Alpha' }), { timeout: 30_000 }) + // The stream brings the offer in again, with its outcome: still once. + await vi.waitFor(() => expect(offerIn(copied().find((row) => row.id === `bm_offer_${offerId}`)!).state).toBe('delivered'), { timeout: 30_000 }) + expect(keptOnPc(alpha)).toHaveLength(before + 1) + + // The second window: it sees the grant, can't end it or take it, and its messages carry no token. + expect(await grantState(true)).toMatchObject({ active: true, recipients: [{ botId: alpha, name: 'Alpha' }] }) + expect(await grantState(true)).not.toHaveProperty('mine') + expect(codeOf(await pc.dispatch('bots.remote.grantEnd', { botId: q }, true).catch((error: unknown) => error))).toBe('grant_elsewhere') + const second = await ownerWrites('From the other window.', 'grant-w2', true) + expect(runOf(second)).toBeUndefined() + expect(runOf(await ownerWrites('From the first window again.', 'grant-w1-again'))).toEqual(expect.any(String)) + + // End access, from the window that allowed it. + expect(((await pc.dispatch('bots.remote.grantEnd', { botId: q })) as { grant: unknown }).grant).toMatchObject({ active: false, ended: 'ended' }) + expect(macCalledPc()).toBe(0) + }, 240_000) + + it('a forged token, an older Mac and a lost report: never sent on its own, refused, told again', async () => { + await allow() + // A turn whose token the PC never issued: expired, and the Mac hears so. + const turn = await ownerWrites('Tell Alpha.', 'grant-forged') + const trigger = { ...(turn.trigger as object), owner: { ...(turn.trigger as { owner: object }).owner, run: '6f1d2a8e-4b0c-4c3e-9a1b-7d2e5f3a9c11' } } + macStore().run('UPDATE bot_activations SET trigger_json = ? WHERE id = ?', JSON.stringify(trigger), turn.id) + const before = keptOnPc(alpha).length + const forged = offer(turn.id, 'Forged token.', 'Alpha') + await vi.waitFor(() => expect(onMac(forged.offerId).state).toBe('expired'), { timeout: 30_000 }) + expect(keptOnPc(alpha)).toHaveLength(before) + + // A report the Mac lost: told again when the offer next comes in (the chat's stream opens again). + const turn2 = await ownerWrites('Tell Alpha again.', 'grant-lost') + const lost = vi.spyOn(mac.mms.personalBots!.service, 'offerOutcome').mockImplementationOnce(() => { throw Object.assign(new Error('lost'), { code: 'internal' }) }) + const kept = offer(turn2.id, 'Report lost once.', 'Alpha') + await vi.waitFor(() => expect(keptOnPc(alpha)).toHaveLength(before + 1), { timeout: 30_000 }) + await vi.waitFor(() => expect(lost).toHaveBeenCalled(), { timeout: 30_000 }) + expect(onMac(kept.offerId).state).toBe('queued') + lost.mockRestore() + await pc.dispatch('bots.focus', { botId: q, focused: false }) + await pc.dispatch('bots.focus', { botId: q, focused: true }) + await vi.waitFor(() => expect(onMac(kept.offerId)).toMatchObject({ state: 'delivered', sentTo: 'Alpha' }), { timeout: 30_000 }) + // Leaving the chat ended that grant. + await ended('left') + + // A Mac from before grants: refused, and no wider way. + const client = (pcRouter() as unknown as { options: { client: RoutedClient } }).options.client + const versions = vi.spyOn(client, 'botVersions').mockResolvedValue({ 'bots.chat.send': 3 }) + try { + expect(codeOf(await grantOpen().catch((error: unknown) => error))).toBe('grant_unsupported') + expect(await grantState()).toMatchObject({ active: false, unsupported: true }) + } finally { + versions.mockRestore() + } + expect(macCalledPc()).toBe(0) + }, 240_000) + + it.each([ + ['private', 'Make private of Alpha', async () => { await pc.dispatch('bots.devices.offers', { botId: alpha, open: false }) }, async () => { await pc.dispatch('bots.devices.offers', { botId: alpha, open: true }) }], + ['blocked', 'blocking the Mac', async () => { await pc.dispatch('bridge.policy', { node: macOnPc, blocked: true }, true) }, async () => { await pc.dispatch('bridge.policy', { node: macOnPc, blocked: false }, true); await fabric.connect(pc, macOnPc) }], + ['removed', 'the Mac leaving the PC out of Loki\'s Devices', async () => { mac.mms.botDeviceAccess.set(loki, { mode: 'this_computer' }); mac.mms.personalBots!.reachChanged?.(loki) }, async () => { mac.mms.botDeviceAccess.set(loki, { mode: 'chosen', nodes: [pcOnMac] }); mac.mms.personalBots!.reachChanged?.(loki) }], + ['offline', 'the PC\'s networking restarting', async () => { await fabric.restartEngine(pc) }, async () => { await fabric.connect(pc, macOnPc) }], + ['offline', 'the Mac going away', async () => { await fabric.away(mac) }, async () => { await fabric.back(mac); await fabric.connect(pc, macOnPc) }] + ] as const)('ends on %s (%s); what it left unsent is expired; nothing reopens it', async (reason, _what, endIt, undo) => { + await allow() + const turn = await ownerWrites('Tell Beta.', `grant-end-${reason}-${Math.random()}`) + // An offer under the grant that waits for a Send: Beta is not in it. + const waiting = offer(turn.id, 'For Beta.', 'Beta') + try { + await endIt() + await ended(reason) + } finally { + await undo() + } + // The next message from the window carries no token, and the waiting offer is expired. + await vi.waitFor(() => expect(pc.mms.bridge.remoteBots.row(macOnPc, loki)?.offline).toBeUndefined(), { timeout: 60_000 }) + const next = await ownerWrites('Again.', `grant-after-${reason}-${Math.random()}`) + expect(runOf(next)).toBeUndefined() + await pc.dispatch('bots.focus', { botId: q, focused: true }) + await vi.waitFor(() => expect(onMac(waiting.offerId).state).toBe('expired'), { timeout: 60_000 }) + expect(macCalledPc()).toBe(0) + }, 240_000) + }) })