diff --git a/AGENTS.md b/AGENTS.md index 853b1fc7..94ae5119 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -14,6 +14,16 @@ Read `CLAUDE.md` and the deployment runbook before changing runtime behavior. - Verify version/review requirements and the selected worktree before `gh ship`. Distinguish implemented, reviewed, merged, deployed and live-tested in reports. - Currency/FX functionality belongs in ExpenseSyncBot. This bot retains a general calculator and date/time arithmetic, not exchange-rate services. +## Analyzing a problem: read the production logs first + +Every analysis of a reported problem (a wrong or silent bot answer, an error, a stuck job) starts from the production logs, before any code reading, hypothesis or fix. The user's account of what the bot did is the symptom; the logs are the evidence of which tool calls ran, what each returned and what was delivered. Commands are in `docs/reference/deploy-runbook.md` (Diagnostics); use these three sources and cite what you found: + +1. **Per-chat AI debug logs** (`AI_DEBUG_LOGS=true`): `logs/chats//.log` in the container holds the system prompt, history, every round's tool calls and results, the model text and the FINAL section. Never `cat` a whole log into the conversation (it is calendar data, Telegram ids and a long prompt). Copy the newest file to a private local file outside the repository (`umask 077; f=$(mktemp /tmp/hcb-chat.XXXXXX)`: an absolute template, because a bare `mktemp` honours `TMPDIR`, which may point inside the checkout), read only what you need with `grep -n` and line ranges (the relevant rounds and the FINAL section), and delete the copy when done. Compare the model's last text with FINAL: they differ when a guard replaced the answer. +2. **Docker logs** (pino JSON), around the incident time: levels 40/50/60 (a tool result that says `ERROR` in the chat log usually has its stack here, e.g. `BUTTON_DATA_INVALID` from `sendButtons`) **and** the records that confirm a delivery. FINAL, or a guard-replaced answer, is the reply the bot intended to deliver, recorded before Telegram delivery and cut to 600 characters: it is not proof of delivery. Whether it was delivered is read only from records that exist: `AI request metric` (level 30, one per request) carries `deliveryOutcome` (`delivered`, `fallback` or `discarded`), where `delivered` means the final write did not throw, so a failed final edit or send beside it is logged at level 50 as `Finalize edit failed` or `Finalize send failed` (a throw as `Writer finalize failed`); an invitation shows `Delivered via bot API` or `Delivered via the inviter's own Telegram account` (level 30), `Bot API + inviter session failed — deep-link fallback attempted` (level 30: not delivered to the invitee) or `Delivery chain failed` (level 50). A successful `ask_user` question send logs nothing, so a **missing delivery record is unknown, not failure**: say it is unconfirmed, and do not turn it into a finding or a replay without other evidence (an error record, the user's account of what they saw). +3. **Host logs and evidence**: `/opt/hypercal/logs/` on the odroid (`failed--/`, `release-*`, `healthcheck*`, `backup*`); `/opt/hypercal/stage/logs` and `/opt/hypercal/stage/evidence` for the stage bot. + +Match the deployed revision (`docker ps` image tag) to the code you read. Raw logs stay out of the repository, issues, pull requests and commit messages; quote short anonymized excerpts only (no names, titles, ids or chat text). The tool result is the truth, not the model's explanation of it: a model text that blames "the system" must be checked against the actual result before it becomes a finding. + ## Heavy work runs on the server This workstation is shared by many agent sessions, the review queue and the owner's own diff --git a/docs/plans/2026-10-31-secretary-invitation-incident.md b/docs/plans/2026-10-31-secretary-invitation-incident.md new file mode 100644 index 00000000..e7aaab21 --- /dev/null +++ b/docs/plans/2026-10-31-secretary-invitation-incident.md @@ -0,0 +1,49 @@ +# Secretary invitation incident closeout — 2026-10-31 + +Scope: one private conversation in which a write-secretary asked the bot to create an event in the owner's calendar and invite named people. Evidence came from the per-chat AI debug log and the Docker log (procedure: AGENTS.md "Analyzing a problem", `docs/reference/deploy-runbook.md` Diagnostics). No private messages, names, titles or ids are recorded here or in the linked issues. + +## Root causes + +1. **ask_user never reached the user (#908).** A 45-character Russian option is 87 bytes in `ai_btn:`; Telegram refuses `callback_data` over 64 bytes (`BUTTON_DATA_INVALID`), so the whole question failed to send and the model got an error it could not act on. +2. **A write-secretary could not invite for the owner's events (#909).** `send_invitation` had no `owner_id`, so a secretary could not address an event in the owner's calendar. Recipient identity is unchanged in principle: invented ids are still refused by the existing verification; the change only treats the requester's own id as verified and adjusts the rejection hints for delegated calendars. +3. **The receipt after the partly failed run was unreadable (#526).** The turn-finish guard replaced the model's text with the `Попытка N` attempt ledger, so the user could not tell what was actually done. + +## Priority and work + +| Priority | Class | Work | Acceptance gate | +| --- | --- | --- | --- | +| P0 | Authorization / identity: invitations for another owner's events, invented recipient ids | #909: `fix(sharing): a write-secretary can invite, resend, cancel and read the roster for the owner's events (owner_id)` | Secretary access checked against the owner for the owner's own personal events only; existing recipient verification unchanged; owner/secretary denial paths unchanged. | +| P1 | Reliability: a question that cannot be delivered | #908: `fix(ai): ask_user options longer than Telegram's 64-byte callback_data are delivered through ai_opt index buttons` | Any option is delivered through an index button and answered verbatim, once; an empty question or option and more than 100 buttons are still rejected. | +| P1 | Truthful results: receipt after a partly failed turn | #526: `fix(ai): a partly failed turn gets a readable receipt instead of the 'Попытка N' ledger` | Event names shown instead of the ledger; unknown delivery is not reported as delivered. | +| P1 | Debugging procedure | `docs(agents): read production logs first when analyzing a problem`, revised in the review round below | Bounded capture of chat logs, delivery records beside warnings, anonymized excerpts only. | +| P2 | Deferred | #910 reason class of a rejected invitation; #911 stale not-deleted line after a retried delete/update with `owner_id`; #912 chat-logging stores an ask_user answer as a turn before the handler decides; #913 verify Telegram returns 200+ character labels whole and the unreadable-keyboard alert wording; #914 verify the 100-button and 10 KB keyboard caps and whether a very long label is carried whole (no option-length or keyboard-size limit is enforced); #915 `get_invitation_status` for secretaries is narrowed to the owner's own events, and whether a delegated roster read is refused in a group without a live invitation; #916 receipt wording for a delegated calendar whose owner name is unreadable; #917 ask_user tap handler claims the answer before the acknowledgement edit (ordering undocumented and untested, plus an async continuation failing before the run starts keeps the claim, and eviction of the in-memory consumed marker reopens an answered question); #918 cancel/resend denials lacked `mutationState` (set to `not_applied` in this round, tests for every denial still open); #923 (high, pre-existing on main) an ask_user tap is silently ignored when the question text itself starts or ends with a `✅ …` line, because the already-answered test reads the model's own text; #919 test fixtures contained production-looking values (now synthetic; verify by grep and close after merge); #920 ledger and receipt edge cases (fixed in the receipt commit: deleted create vs failed recreation, extra event_id, recurrence dates, string booleans, impossible dates, surrogate cut, a snoozed event is named without its pre-snooze time, one-off all-day spellings of one calendar day are one create; the day reading west of UTC and the Google mapping of local-midnight all-day starts stay open under #921 and #529) | Each keeps its own issue, tests and next action; none is closed by this incident's commits. | + +## Review findings fixed in the pre-commit review round (2026-10-31) + +- ask_user: an option of any length became `ai_opt:`, and the acknowledgement edit (`question + ✅ answer`) then failed past 4096 characters with the failure swallowed, so a second tap was not seen as answered and the AI got two continuations. Fixed in the tap handler (answer-only fallback, answers shortened to one bounded line, the answered message remembered in process memory so a failed edit or two racing taps reach the AI once). No label-length or keyboard-size limit is enforced: the 200-character and 10 KB checks were guesses and were removed; `ask_user` still rejects an empty question or option and more than 100 buttons. Whether Telegram carries a very long button label whole is still unverified (#914). Regression tests: `test/services/ai/tool-handlers/ask-user.test.ts`, `test/bot/handlers/ai-button-answers.test.ts`. +- Secretary invitations (#909): delegated paths looked the event up with `getEvent`, which also returns events visible through group membership, so a secretary could act on a group event the owner does not organise. They now use an owner-only personal-event lookup. Write access is re-checked after the awaited recipient lookup (a revoked secretary can no longer send or resend), and the event is re-read after the lookup so the card shows current details. **Behaviour change:** a secretary can no longer act on group-owned events, only on the owner's personal events. Tests: `test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts`. +- Receipt (#526): a parseable non-ISO `start_at` from a rejected create threw `RangeError` while rendering the receipt; the create identity lacked calendar scope and recurrence, so a failed group or recurring create was folded behind a personal success; markup in event titles and names could break the delivered message. The receipt now never throws on such input, keeps those creates apart and neutralises markup in names. Tests: `test/services/ai/write-receipt.test.ts`, `test/services/ai/write-outcomes.test.ts`. +- AGENTS.md log procedure: no private chat id (use ``), no whole-log `cat` (copy to a 0600 temp file, read ranges, delete), docker filter also shows level-30 delivery records (FINAL is recorded before delivery), anonymized excerpts only; the runbook commands changed to match. + +## Review findings fixed in the second review round (2026-10-31) + +1. ask_user single continuation (#908): the callback handler is built anew for every update (`src/bot/index.ts`), so the answered-message set inside it was empty on each tap; it is now one bounded process-wide set in `src/bot/handlers/callback/ai-routes.ts` (the bot is one container, and the in-memory delete-confirmation store follows the same convention). Test: a failed acknowledgement edit, then a second tap on a fresh handler, reaches the AI once (`test/bot/handlers/ai-button-answers.test.ts`). +2. `cancel_invitation` and `resend_invitation` (#909): the delegated cancel guard looked up the event of an invitation id before checking its inviter, so a secretary of owner A could learn that owner B's invitation exists and which event it names; and for every caller a foreign id answered `Not authorized to cancel` / `Not your invitation.` while a missing one answered `Invitation not found`, an existence oracle. Both tools now check the inviter first and answer a foreign id exactly as a missing one (`Invitation not found`), for the owner path too; `get_invitation_status` stays with #915. Tests: `test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts`, `test/services/ai/tool-handlers/sharing-failure-paths.test.ts` (the pinned `Not your invitation.` wording changed). +3. Group event the managed owner created (#909): the error still said `Retry with owner_id N` after `owner_id` was supplied. It is now an explicit scope denial (a secretary acts only on the owner's personal events) with no retry hint; the hint stays for a personal event when `owner_id` was forgotten. Same test file. +4. Receipt create identity (#526): the raw RRULE string was part of the key, so `FREQ=WEEKLY;BYDAY=MO` and `BYDAY=MO;FREQ=WEEKLY` were two events and the receipt said both "Not created" and "Created". The recurrence is normalised (part order, list order, case, spacing, `RRULE:` prefix, default `INTERVAL=1`); a different interval, weekday set, count or nth weekday stays distinct. Test: `test/services/ai/write-outcomes.test.ts`. +5. Log rule (#908): AGENTS.md treated a missing level-30 delivery record as failure. A successful `ask_user` send logs none, and an ordinary reply logs `AI request metric`, which the runbook filter dropped. A missing record is now unknown, not failure, and the rule names the records that exist (`AI request metric` with `deliveryOutcome`, `Finalize edit failed`, `Finalize send failed`, `Writer finalize failed`, `Delivered via ...`, `deep-link fallback attempted`, `Delivery chain failed`); the runbook filter was widened to match. +6. Private log copy (#908): the runbook used a bare `mktemp`, which honours `TMPDIR` (with `TMPDIR=.` the copy would land in the checkout). AGENTS.md and the runbook use `umask 077; mktemp /tmp/hcb-chat.XXXXXX`. +7. ask_user claim lost on a failed tap (#908): the answered-message claim was made before `ctx.answer()`, so an `answer()` failure (callback query too old, network) skipped the acknowledgement and the AI continuation while the message stayed claimed, and the retap was ignored until a restart. A failed `answer()` is now only logged, and any failure before the continuation starts releases the claim; a continuation that started keeps it. Tests: `test/bot/handlers/ai-button-answers.test.ts`. +8. Invitation denials (#909): the denials of `cancel_invitation` and `resend_invitation` (and the shared event-scope denial) lacked `mutationState`, so the executor classed a denied write as `uncertain` and the receipt would ask the user to check the calendar. They now carry `mutationState: 'not_applied'` like `send_invitation`. Tests: `test/services/ai/tool-handlers/sharing-failure-paths.test.ts`. +9. Receipt for a calendar whose owner has no name (#526): the delegated-calendar phrase is "чужой календарь, который ты ведёшь как секретарь" / "someone else’s calendar that you manage as a secretary" only while the requester holds active access; with none (never granted, revoked, expired or an invented id) it is the neutral "другой календарь" / "another calendar", so the receipt never states an access the user lacks (no raw id, no dangling label; a group chat still hides the target). Tests: `test/services/ai/write-receipt.test.ts`. +10. Exact-head review rounds (#909, #526, #920), final behaviour after three rounds; earlier rounds are in git history: + - `send_invitation` for the owner's calendar answers an event the owner sees only through a group with the scope denial (the secretary can read it anyway), and an event nobody can see (missing, deleted, cancelled) exactly as a missing id; the retry hint for a second managed owner is kept. This supersedes the wording of item 3 for the invisible-event case. A secretary can never invite the calendar owner to their own event (by id or by a username that resolves to the owner). + - Day and time in the receipt come only from the write itself, never from a read: a create's own request, or the start a successful update restated (an all-day start is parsed with `allDayCalendarDate`, so it is the calendar day written, in any zone; the all-day flag comes from the confirmed result when it carries one, else from the call, and when neither says, the event is named by title alone). Reads supply only the title and the calendar. A delete, a snooze, a failed or unconfirmed update, and an update without a start name the event by title alone. A start names a day or time only if it is a real ISO date, or a datetime with `Z` or an offset (a date-only all-day start is a real ISO date and is shown); anything else names none, in any write. The receipt no longer reads summary dates, read rows or snoozes for a day, which removes the cause of three rounds of fixes (occurrence rows, the first start of a series, a snooze with no data, shifted all-day dates); the summary builder itself (open in #921/#529) still shows the previous day west of UTC and stays open in #921/#529. + - A create is identified by title, start, all-day flag, owner, scope and recurrence; end, location and description are compared apart. A later success of the same event settles an earlier refused or skipped create whichever of those a corrected retry changed, a later failure is hidden behind a success only when it asked for the same details, and a failure kept visible names the fields it differs in. A refused create that differs from a success of the same title and start only by recurrence or all-day is a different create (those are part of the identity), so it stays visible and its line carries `fields: recurrence` or `fields: all day` to read as a variant, not a contradiction. A successful update re-keys the create to what the event now is (the title and all-day flag from the confirmed result when it carries one) and settles refused creates that asked for exactly that; a delete or a snooze (succeeded or unknown), or an unconfirmed update that may change what the create asked for, retires it, so a failed re-create stays visible. A success after an earlier unknown create leaves the duplicate warning. A repeat of a successful create that ends unknown has its own duplicate warning naming the repeated request; identical failed creates next to a success that asked for other details are told once, and a closing line asks the user to check the calendar, not to repeat, when a possible duplicate and a refusal occur together. + - An invitee key is the identifier the call named: a user id, or a username read case-insensitively without `@` (the `invitee_username` value `bob`, `@bob` or ` Bob` is one write; a display name is only ever resolved to a username or id by the tool, never used as a key by the ledger). One person's invitation keeps what was delivered and one failure apart (the latest, except that a refusal does not replace an attempt that may have gone through): a failure never erases a delivery, a delivery clears the failure it follows (an unknown one leaves the duplicate warning), and a refusal never erases an attempt that may have gone through. On one receipt line a contact named by username in any case or by id is counted once, and two different people with the same display name are both counted. + - Tests: `test/services/ai/write-receipt.test.ts` (day and time from the write, create identity, update re-keying, repeat warnings, invitee spellings and slots, `fields:` labels, offsets) and `test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts`. + - Open, tracked in #922: reminders and `location_abstract` are not compared when deciding whether two creates are the same; a create retired by an unconfirmed update is not re-keyed by a later successful retry; a later success of the same identity is taken for a corrected retry, so a refusal of a genuinely separate second event with the same title and start can disappear; two same-titled events in one receipt are told apart by nothing but their own write's time; one contact named by id and by username is two writes in the ledger (so a delivery by id followed by a refusal by `@name` shows both lines; needs a shared person resolution and the rejection reason class of #910); a long chain of mixed invitation outcomes (a delivery, a created-but-undelivered repeat, then an unknown one) can lose a line; a refused create whose start has no offset and its corrected retry read as two lines; `send_invitation` without `owner_id` on another member's group event answers a plain not found; `update_event` with `all_day: "false"` is stored truthy (the update schema lacks `all_day`); cancel, resend and the roster still call a group event of the owner not found. + +## Completion + +Record the exact merged commit, server full suite, typecheck and lint, independent review, the normal `gh ship` result and the deployed image revision as separate statuses in #908, #909 and #526. A conversation-level acceptance run (secretary invites a named person; a long-option question is answered once) is a separate, authorized live test. Do not close #910–#915 with these commits. diff --git a/docs/reference/deploy-runbook.md b/docs/reference/deploy-runbook.md index 0c9bf80a..5c911fd3 100644 --- a/docs/reference/deploy-runbook.md +++ b/docs/reference/deploy-runbook.md @@ -51,9 +51,24 @@ curl https://hypercal.mextner.com/ready system prompt, history, tool calls, responses. Enabled via `AI_DEBUG_LOGS=true`. ```bash -# Latest log for a chat (logs inside container at /app/logs/): -ssh root@odroidn2 'docker exec hypercal-bot ls -lt /app/logs/chats/5153477378/ | head -3' -ssh root@odroidn2 'docker exec hypercal-bot cat /app/logs/chats/5153477378/.log' +# Latest log for a chat (logs inside container at /app/logs/). Copy it to a private temp file and +# read ranges; never cat a whole chat log into a session (calendar data, Telegram ids): +ssh root@odroidn2 'docker exec hypercal-bot ls -lt /app/logs/chats// | head -3' +# Absolute template: a bare `mktemp` honours TMPDIR, which can point inside the checkout. +umask 077; f=$(mktemp /tmp/hcb-chat.XXXXXX) # mode 0600, outside the repository +ssh root@odroidn2 'docker exec hypercal-bot cat /app/logs/chats//.log' > "$f" +grep -n '^## ROUND\|^## FINAL\|^## END' "$f"; sed -n ',p' "$f" +rm -f "$f" + +# Docker logs around an incident: warnings and errors plus the records that exist for a delivery. +# A FINAL answer is recorded before delivery and does not prove it, and a successful ask_user send +# logs nothing: a missing delivery record is unknown, not failure. +# AI request metric (level 30; deliveryOutcome delivered|fallback|discarded) +# Finalize edit failed / Finalize send failed / Writer finalize failed (level 50) +# Delivered via bot API / Delivered via the inviter's own Telegram account (level 30, invitation sent) +# Bot API + inviter session failed — deep-link fallback attempted (level 30, invitation not delivered) +# Delivery chain failed (level 50) +ssh root@odroidn2 'docker logs --since 3h hypercal-bot 2>&1 | grep -E "\"level\":(40|50|60)|AI request metric|Delivered via|deep-link fallback attempted"' ``` ## Shared Server diff --git a/docs/reference/telegram-limits.md b/docs/reference/telegram-limits.md index 30fd7f63..1108abc4 100644 --- a/docs/reference/telegram-limits.md +++ b/docs/reference/telegram-limits.md @@ -20,6 +20,7 @@ When text may exceed 4 096 chars, use `splitMessage()` from `src/utils/telegram. - Max **8 buttons per row**, **100 buttons total** - Total `reply_markup` JSON: **10 KB** - `callback_data` per button: **64 bytes** (UTF-8). Exceeding -> `400 BUTTON_DATA_INVALID`. + - ask_user buttons (`src/services/ai/ask-user-buttons.ts`): the answer rides in `ai_btn:` while that fits in 64 bytes; a longer option is sent as `ai_opt:` and the tap handler reads the answer from the tapped button's label in the message's own keyboard. A 2026-10-31 incident (`BUTTON_DATA_INVALID` for a 45-character Russian option) was the byte-vs-character trap. `handleAskUser` rejects only an empty question or option and more than 100 buttons (the working limit above, which carries no source link); it enforces no label-length or keyboard-size limit, because none is documented. Whether Telegram carries a very long button label whole is unverified (#914). A tap is acknowledged by editing `question + "\n\n✅ " + answer` into the message; past the 4096-character message limit that edit fails, so the tap handler falls back to the answer alone, shortens an answer over 4000 characters, writes it on one line (the "already answered" test looks for a final `✅ ...` line), and also remembers the answered message in process memory, so a failed edit cannot let a second tap reach the AI. ## Commands - Command name: **1-32 chars** (lowercase a-z, 0-9, `_`) diff --git a/docs/specs/06-sharing-social.md b/docs/specs/06-sharing-social.md index cc0fb513..2aa2589f 100644 --- a/docs/specs/06-sharing-social.md +++ b/docs/specs/06-sharing-social.md @@ -705,12 +705,14 @@ share_event(params: { send_invitation(params: { event_id: number; invitee_id: number; // telegram_user_id + owner_id?: number; // secretary with write access: the calendar owner whose event it is }): Promise<{ success: boolean; invitation_id?: number; deep_link?: string }> // Check invitation status get_invitation_status(params: { invitation_id?: number; event_id?: number; // get all invitations for event + owner_id?: number; // secretary (read or write access) reading the owner's event }): Promise // Update sharing settings @@ -727,6 +729,8 @@ set_event_visibility(params: { }): Promise<{ success: boolean }> ``` +**Secretary invitations.** `send_invitation`, `resend_invitation` and `cancel_invitation` accept `owner_id` and need active `write` secretary access to that owner; `get_invitation_status` needs read access. The invitation's `inviter_id` is the event owner, not the secretary: cards, RSVP notices, the roster and reschedule all read the event as `(event_id, inviter_id)`. Delivery is Bot API first; on failure only the deep link goes to the secretary's private chat. No connected Telegram (MTProto) session sends for the owner. The requester can be invited with their own Telegram ID; inviting the owner is refused (the owner is the organizer). The user picker (`pick_users`) does not yet apply to a secretary-managed event. + --- ## 12. BullMQ Jobs diff --git a/pyproject.toml b/pyproject.toml index 0b0947dd..f53a1b15 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "hypercalendarbot" -version = "0.3.1" +version = "0.3.2" requires-python = ">=3.12" dependencies = [ "pyrofork>=2.3", diff --git a/src/bot/handlers/callback/ai-routes.ts b/src/bot/handlers/callback/ai-routes.ts index 9a47012e..0aed2385 100644 --- a/src/bot/handlers/callback/ai-routes.ts +++ b/src/bot/handlers/callback/ai-routes.ts @@ -3,6 +3,12 @@ import type { Lang } from '../../../config/constants.ts'; import { CB, t, toLang } from '../../../config/constants.ts'; +import { + AI_BUTTON_ACTION, + AI_OPTION_ACTION, + type InlineKeyboardRows, + parseAiOptionPayload, +} from '../../../services/ai/ask-user-buttons.ts'; import { approveDeletes, chooseTargets, @@ -17,7 +23,9 @@ import { cmdLogger } from '../../../utils/logger.ts'; import { isGroup } from '../../group-context.ts'; import type { BotCallbackContext } from '../../types.ts'; import { continueWithAgent } from '../agent-continuation.ts'; -import type { CallbackDispatch, CallbackRouteDeps } from './types.ts'; +import type { CallbackDispatch, CallbackHandlerOpts, CallbackRouteDeps } from './types.ts'; + +type CallbackHandler = NonNullable>; /** * Parse ai_btn payload into answer text and optional group restriction. @@ -41,15 +49,100 @@ export function parseAiBtnPayload( return { answerText: payload }; } +/** What a tap on an ask_user button means: the answer, and the one user allowed to give it in a group. */ +interface AiButtonTap { + /** Undefined for an `ai_opt` tap whose message no longer carries the tapped button: answered already, or inaccessible to the bot. */ + answerText: string | undefined; + restrictedToUserId?: number; +} + +/** + * Reads a tap on either ask_user button form (`ai_btn`, `ai_opt`). `keyboard` is the inline keyboard + * of the tapped message, where an `ai_opt` button's own label is the answer. Undefined when `data` + * is not an ask_user button or its payload is malformed. + */ +export function readAiButtonTap( + data: string, + inGroup: boolean, + keyboard: InlineKeyboardRows | undefined, +): AiButtonTap | undefined { + const firstColon = data.indexOf(':'); + const action = firstColon === -1 ? data : data.slice(0, firstColon); + const payload = firstColon === -1 ? '' : data.slice(firstColon + 1); + if (action === AI_BUTTON_ACTION) return parseAiBtnPayload(payload, inGroup); + if (action !== AI_OPTION_ACTION) return undefined; + const option = parseAiOptionPayload(payload); + if (!option) return undefined; + const tapped = keyboard?.flat().find((button) => button.callback_data === data); + return { answerText: tapped?.text, ...option }; +} + interface DeleteReportLabels { deleteDone: (count: number) => string; deleteKeptPast: (count: number) => string; deleteFailed: (titles: string) => string; } +/** Telegram refuses a message over 4096 characters; the "✅ " marker and an ellipsis ride on top of the answer. */ +const MAX_ACKNOWLEDGED_ANSWER_CHARS = 4000; + +/** + * The answer as shown after "✅ ". One line, because the "already answered" test needs the marker + * line to end the text, and short enough to be an acceptable message on its own whatever the label. + */ +function acknowledgedAnswer(answerText: string): string { + const oneLine = answerText.replace(/\s*[\r\n]+\s*/g, ' '); + return oneLine.length > MAX_ACKNOWLEDGED_ANSWER_CHARS + ? `${oneLine.slice(0, MAX_ACKNOWLEDGED_ANSWER_CHARS)}…` + : oneLine; +} + +/** A question whose text already ends in a "✅ answer" line: the edit that records an answer landed. */ +const ANSWERED_QUESTION = /(?:^|\n\n)✅ [^\n]*$/; + +const ANSWERED_MEMORY_LIMIT = 1000; + +/** + * Remembers which question messages were answered, for the taps a client still sends from a message + * it shows unanswered (the acknowledgement edit failed, or two taps raced before either edit landed). + * Bounded to the newest ANSWERED_MEMORY_LIMIT messages. A restart forgets it, as it forgets the + * pending AI turn it guards. + */ +function createAnsweredMessages() { + const answered = new Set(); + const keyOf = (ctx: BotCallbackContext) => + ctx.message?.id === undefined ? undefined : `${ctx.chatId}:${ctx.message.id}`; + return { + has: (ctx: BotCallbackContext) => { + const key = keyOf(ctx); + return key !== undefined && answered.has(key); + }, + add: (ctx: BotCallbackContext) => { + const key = keyOf(ctx); + if (key === undefined) return; + answered.add(key); + // Oldest first: a Set iterates in insertion order. + const oldest = answered.values().next(); + if (answered.size > ANSWERED_MEMORY_LIMIT && !oldest.done) answered.delete(oldest.value); + }, + release: (ctx: BotCallbackContext) => { + const key = keyOf(ctx); + if (key !== undefined) answered.delete(key); + }, + }; +} + +/** + * One memory for the whole process, not one per handler: src/bot/index.ts builds the callback handler + * (and so these routes) afresh for every update, so state held inside the handler is empty on each tap. + * The bot runs as a single container (docker-compose.yml), so process memory sees every tap; Redis + * would only add a round trip and a failure mode to a guard that the pending AI turn does not outlive. + */ +const answeredMessages = createAnsweredMessages(); + async function recordAskUserAnswer(ctx: BotCallbackContext, question: string, answerText: string): Promise { const entities = ctx.message?.entities?.map((entity) => entity.payload) ?? []; - const answered = `✅ ${answerText}`; + const answered = `✅ ${acknowledgedAnswer(answerText)}`; const kept = question ? `${question}\n\n${answered}` : answered; try { try { @@ -92,6 +185,77 @@ async function reportDeleteOutcome( } } +/** + * Acknowledges the tap, records the answer in the chat and starts the AI continuation. A callback + * query too old to answer says nothing about the user's answer, so that failure is only logged. + */ +async function acknowledgeAndContinue( + ctx: BotCallbackContext, + userId: number, + question: string, + answerText: string, + onAiButtonClick: CallbackHandlerOpts['onAiButtonClick'], +): Promise { + await ctx.answer().catch((err: unknown) => cmdLogger.warn({ err }, 'Failed to answer the ask_user tap')); + const recorded = await recordAskUserAnswer(ctx, question, answerText); + if (!recorded) return; + const cbChatId = ctx.chatId; + if (onAiButtonClick && cbChatId) { + onAiButtonClick(userId, cbChatId, answerText).catch((e) => { + cmdLogger.error({ err: e }, 'AI button continuation failed'); + }); + } +} + +/** Handler of both ask_user button forms: records the answer once and hands it to the AI. */ +function createAskUserTapHandler(onAiButtonClick: CallbackHandlerOpts['onAiButtonClick']): CallbackHandler { + return async (ctx, _payload, _parts, user, data) => { + const tap = readAiButtonTap(data, isGroup(ctx), ctx.message?.replyMarkup?.payload.inline_keyboard); + if (!tap) { + cmdLogger.warn({ userId: user.telegram_id, action: data.split(':')[0] }, 'ask_user button data is malformed'); + await ctx.answer(); + return; + } + const { answerText, restrictedToUserId } = tap; + const lang = (user.language ?? 'en') as Lang; + + // In groups, only the user who triggered the question can answer + if (restrictedToUserId !== undefined && ctx.from.id !== restrictedToUserId) { + await ctx.answer({ text: t(lang).callbackErrors.notYourQuestion, show_alert: false }); + return; + } + + // Keep the question: after a destructive confirmation it is the user's only record of + // what they agreed to. Appending at the end leaves the entity offsets valid. + const question = ctx.message?.text ?? ''; + // A later tap from a client that still shows the buttons finds an answer already recorded, + // the same option or another one: the AI must not get a second answer (a destructive + // confirmation would run again, or run after the user declined it). The recorded answer is + // either the "✅" line of the edited message or, when that edit failed or has not landed yet, + // this process's memory of the message. Answering removes the keyboard, so a late `ai_opt` + // tap has no label to read: this test comes before that one. + if (ANSWERED_QUESTION.test(question) || answeredMessages.has(ctx)) { + await ctx.answer(); + cmdLogger.info({ userId: user.telegram_id }, 'ai_btn tap on an already answered question ignored'); + return; + } + if (answerText === undefined) { + cmdLogger.warn({ userId: user.telegram_id }, 'ai_opt tap found no matching button in the tapped message'); + await ctx.answer({ text: t(lang).callbackErrors.unavailable, show_alert: true }); + return; + } + // Claimed before the first await: a second tap arriving while the edit is in flight sees it. + answeredMessages.add(ctx); + try { + await acknowledgeAndContinue(ctx, user.telegram_id, question, answerText, onAiButtonClick); + } catch (err) { + // The answer never reached the AI: release the claim so the user's retap is processed, not ignored. + answeredMessages.release(ctx); + throw err; + } + }; +} + export function registerAiRoutes(dispatch: CallbackDispatch, deps: CallbackRouteDeps): void { const { onAiButtonClick, agentContinuation, scenePauseDeps } = deps.opts; @@ -112,7 +276,7 @@ export function registerAiRoutes(dispatch: CallbackDispatch, deps: CallbackRoute try { await continueWithAgent( user, - `Confirmed recipient Telegram ID ${approved.recipientId} for event ${approved.eventId}. Send that invitation with force=true; do not change the ID or use a conflicting username.`, + `Confirmed recipient Telegram ID ${approved.recipientId} for event ${approved.eventId}. Send that invitation with force=true${approved.ownerId === undefined ? '' : ` and owner_id ${approved.ownerId}`}; do not change the ID or use a conflicting username.`, agentContinuation, ); finishRecipientApproval(payload, false); @@ -189,36 +353,6 @@ export function registerAiRoutes(dispatch: CallbackDispatch, deps: CallbackRoute }); // AI ask_user button responses — trigger AI continuation - dispatch.set('ai_btn', async (ctx, _payload, _parts, user, data) => { - const firstColon = data.indexOf(':'); - const { answerText, restrictedToUserId } = parseAiBtnPayload(data.slice(firstColon + 1), isGroup(ctx)); - const lang = (user.language ?? 'en') as Lang; - - // In groups, only the user who triggered the question can answer - const clickerId = ctx.from.id; - if (restrictedToUserId !== undefined && clickerId !== restrictedToUserId) { - await ctx.answer({ text: t(lang).callbackErrors.notYourQuestion, show_alert: false }); - return; - } - - await ctx.answer(); - // Keep the question: after a destructive confirmation it is the user's only record of - // what they agreed to. Appending at the end leaves the entity offsets valid. - const question = ctx.message?.text ?? ''; - // A later tap from a client that still shows the buttons finds an answer already recorded, - // the same option or another one: the AI must not get a second answer (a destructive - // confirmation would run again, or run after the user declined it). - if (/(?:^|\n\n)✅ [^\n]*$/.test(question)) { - cmdLogger.info({ userId: user.telegram_id }, 'ai_btn tap on an already answered question ignored'); - return; - } - const recorded = await recordAskUserAnswer(ctx, question, answerText); - if (!recorded) return; - const cbChatId = ctx.chatId; - if (onAiButtonClick && cbChatId) { - onAiButtonClick(user.telegram_id, cbChatId, answerText).catch((e) => { - cmdLogger.error({ err: e }, 'AI button continuation failed'); - }); - } - }); + const handleTap = createAskUserTapHandler(onAiButtonClick); + for (const action of [AI_BUTTON_ACTION, AI_OPTION_ACTION]) dispatch.set(action, handleTap); } diff --git a/src/bot/middleware/chat-logging.ts b/src/bot/middleware/chat-logging.ts index 8595af70..cd187be2 100644 --- a/src/bot/middleware/chat-logging.ts +++ b/src/bot/middleware/chat-logging.ts @@ -11,7 +11,7 @@ import type { ChatTurnReservation } from '../../services/ai/chat-run-gate.ts'; import { withChatTurn } from '../../services/ai/chat-turn-context.ts'; import type { ConversationLogger } from '../../services/conversation-logger.ts'; import { resolveCallbackButtonLabel } from '../callback-label.ts'; -import { parseAiBtnPayload } from '../handlers/callback.handler.ts'; +import { readAiButtonTap } from '../handlers/callback/ai-routes.ts'; import { CONNECT_WIZARD_REDACTION } from '../scenes/connect-telegram.scene.ts'; import type { ConnectWizardGuard } from './connect-wizard-guard.ts'; @@ -99,14 +99,18 @@ export function createChatLogging(deps: ChatLoggingDeps) { const action = firstColon >= 0 ? data.slice(0, firstColon) : data; const payload = firstColon >= 0 ? data.slice(firstColon + 1) : ''; const callbackMessage = callbackQuery.message; + const replyMarkup = callbackMessage && 'reply_markup' in callbackMessage ? callbackMessage.reply_markup : undefined; - if (action === 'ai_btn') { - const chatType = callbackMessage?.chat?.type; - const isGroupCallback = chatType === 'group' || chatType === 'supergroup'; - saveUserTurn(turn, parseAiBtnPayload(payload, isGroupCallback).answerText); + const chatType = callbackMessage?.chat?.type; + const isGroupCallback = chatType === 'group' || chatType === 'supergroup'; + // An ask_user answer is the user's next turn. A long option rides as an index, so the text is the + // tapped button's label; a tap whose label cannot be read is not an answer and logs as a press. + const keyboard = replyMarkup && 'inline_keyboard' in replyMarkup ? replyMarkup.inline_keyboard : undefined; + const answerText = readAiButtonTap(data, isGroupCallback, keyboard)?.answerText; + if (answerText !== undefined) { + saveUserTurn(turn, answerText); return; } - const replyMarkup = callbackMessage && 'reply_markup' in callbackMessage ? callbackMessage.reply_markup : undefined; const buttonLabel = resolveCallbackButtonLabel(replyMarkup, data, action); conversationLogger.logButtonPress(turn.userId, buttonLabel, payload || undefined, turn.logChatId); actionLog.insert({ diff --git a/src/config/constants/messages/en/workflow.ts b/src/config/constants/messages/en/workflow.ts index 4384c7bf..98cefcd2 100644 --- a/src/config/constants/messages/en/workflow.ts +++ b/src/config/constants/messages/en/workflow.ts @@ -1,5 +1,5 @@ // src/config/constants/messages/en/workflow.ts -// Intent-workflow outcome text, day headings and write-outcome (delivery/attempt) wording. +// Intent-workflow outcome text, day headings and write-receipt wording. import { capitalize } from '../../text-helpers.ts'; @@ -16,29 +16,90 @@ export const enWorkflow = { `${relative ? `${capitalize(relative)}, ` : ''}${weekday} ${month}/${day}`, }, writeOutcomes: { - completed: 'Completed', - notCompleted: 'Not completed', - uncertain: 'Outcome unknown', - failed: 'attempt failed; completion not confirmed', - notApplied: 'request rejected before applying changes', - skipped: 'skipped; no new write executed', + // What the model reads back from send_invitation: one invitation, said once. invitationDelivered: 'Invitation delivered', invitationManual: 'Invitation created; not delivered. Please forward the link sent to your private chat.', invitationFailed: 'Invitation created; not delivered.', - attendanceDeclined: 'Attendance declined; the event remains.', interrupted: 'The request was interrupted. Some actions may already have happened; no automatic replay will run.', - attempts: - 'These are distinct execution attempts, not a list of outstanding requests. Later successes are shown separately.', - write: 'Write', - field: 'field', - attempt: (n: number) => `Attempt ${n}`, spokenQuestion: (question: string, options: string) => `${question} Options: ${options}`, + // The receipt that replaces the model's text when a run had failed, skipped or unconfirmed writes. + anEvent: 'event', + theEvent: 'the event', + eventNamed: (title: string, when: string | null) => (when ? `event “${title}” (${when})` : `event “${title}”`), + eventTitle: (title: string) => `“${title}”`, + change: 'change', + calendarOf: (name: string) => `calendar: ${name}`, + otherCalendar: 'another calendar', + delegatedCalendar: 'someone else’s calendar that you manage as a secretary', + changedFields: (fields: readonly string[]) => `, fields: ${fields.join(', ')}`, + nothingChanged: 'nothing was changed', + skipped: 'skipped, not run again', + repeatUnknown: (event: string | null) => + event + ? `A repeat of the creation could not be confirmed: ${event}. Check the calendar for a duplicate.` + : 'A repeat of an event creation could not be confirmed. Check the calendar for a duplicate.', + retriedAfterUnknown: + 'The retry worked, but the first try may have gone through too: check the calendar for a duplicate.', + attendanceDeclined: (title: string | null) => + title ? `Attendance of “${title}” declined; the event remains.` : 'Attendance declined; the event remains.', + retry: 'Tell me what to repeat: I will not redo what already went through.', + checkFirst: 'Check the calendar before repeating anything; I never repeat a request on my own.', + people: (names: readonly string[], unnamed: number) => { + const count = `${unnamed} ${unnamed === 1 ? 'person' : 'people'}`; + if (names.length === 0) return count; + return unnamed === 0 ? names.join(', ') : `${names.join(', ')} and ${unnamed} more`; + }, + invitations: { + sent: (n: number, event: string, who: string) => + n === 1 ? `The invitation to ${event} was sent: ${who}.` : `The invitations to ${event} were sent: ${who}.`, + created: (n: number, event: string, who: string) => + n === 1 + ? `The invitation to ${event} was created: ${who}.` + : `The invitations to ${event} were created: ${who}.`, + manual: (n: number, event: string, who: string) => + n === 1 + ? `The invitation to ${event} was created but not delivered: ${who}. Please forward the link sent to your private chat.` + : `The invitations to ${event} were created but not delivered: ${who}. Please forward the links sent to your private chat.`, + undelivered: (n: number, event: string, who: string) => + n === 1 + ? `The invitation to ${event} was created but not delivered: ${who}.` + : `The invitations to ${event} were created but not delivered: ${who}.`, + rejected: (n: number, event: string, who: string) => + n === 1 + ? `The invitation to ${event} was not sent: ${who}.` + : `The invitations to ${event} were not sent: ${who}.`, + unknown: (n: number, event: string, who: string) => + n === 1 + ? `Could not confirm that the invitation to ${event} went through: ${who}.` + : `Could not confirm that the invitations to ${event} went through: ${who}.`, + skipped: (n: number, event: string, who: string) => + n === 1 + ? `The invitation to ${event} was skipped and not sent again: ${who}.` + : `The invitations to ${event} were skipped and not sent again: ${who}.`, + }, operations: { - delete_event: 'Delete event', - update_event: 'Update event', - create_event: 'Create event', - send_invitation: 'Send invitation', + create_event: { + done: 'Created', + notDone: 'Not created', + unknown: 'Could not confirm creation', + }, + update_event: { + done: 'Updated', + notDone: 'Not updated', + unknown: 'Could not confirm the update', + }, + delete_event: { + done: 'Deleted', + notDone: 'Not deleted', + unknown: 'Could not confirm the deletion', + }, }, + otherWrite: { + done: 'Done', + notDone: 'Not done', + unknown: 'Could not confirm it went through', + }, + field: 'field', fields: { title: 'title', start_at: 'start time', diff --git a/src/config/constants/messages/ru/workflow.ts b/src/config/constants/messages/ru/workflow.ts index 97c8558d..4a956bd7 100644 --- a/src/config/constants/messages/ru/workflow.ts +++ b/src/config/constants/messages/ru/workflow.ts @@ -1,6 +1,7 @@ // src/config/constants/messages/ru/workflow.ts -// Intent-workflow outcome text, day headings and write-outcome (delivery/attempt) wording. +// Intent-workflow outcome text, day headings and write-receipt wording. +import { ruPlural } from '../../../../services/event/formatters.ts'; import { capitalize } from '../../text-helpers.ts'; export const ruWorkflow = { @@ -15,29 +16,87 @@ export const ruWorkflow = { relative ? `${capitalize(relative)}, ${weekday} ${day}.${month}` : `${capitalize(weekday)} ${day}.${month}`, }, writeOutcomes: { - completed: 'Выполнено', - notCompleted: 'Не выполнено', - uncertain: 'Результат неизвестен', - failed: 'попытка не удалась; выполнение не подтверждено', - notApplied: 'запрос отклонён до внесения изменений', - skipped: 'пропущено; новое изменение не выполнялось', + // What the model reads back from send_invitation: one invitation, said once. invitationDelivered: 'Приглашение доставлено', invitationManual: 'Приглашение создано, но не доставлено. Перешли ссылку из личного чата.', invitationFailed: 'Приглашение создано, но не доставлено.', - attendanceDeclined: 'Участие отклонено; событие сохранено.', interrupted: 'Запрос прерван. Часть действий могла уже выполниться; автоматического повтора не будет.', - attempts: - 'Это отдельные попытки выполнения, а не список невыполненных запросов. Последующие успешные попытки показаны отдельно.', - write: 'Изменение', - field: 'поле', - attempt: (n: number) => `Попытка ${n}`, spokenQuestion: (question: string, options: string) => `${question} Варианты: ${options}`, + // The receipt that replaces the model's text when a run had failed, skipped or unconfirmed writes. + anEvent: 'событие', + theEvent: 'событие', + eventNamed: (title: string, when: string | null) => (when ? `событие «${title}» (${when})` : `событие «${title}»`), + eventTitle: (title: string) => `«${title}»`, + change: 'изменение', + calendarOf: (name: string) => `календарь: ${name}`, + otherCalendar: 'другой календарь', + delegatedCalendar: 'чужой календарь, который ты ведёшь как секретарь', + changedFields: (fields: readonly string[]) => `, поля: ${fields.join(', ')}`, + nothingChanged: 'ничего не изменилось', + skipped: 'пропущено, повторно не выполнялось', + repeatUnknown: (event: string | null) => + event + ? `Повторное создание не удалось подтвердить: ${event}. Проверь календарь на дубль.` + : 'Повторное создание события не удалось подтвердить. Проверь календарь на дубль.', + retriedAfterUnknown: 'Повторная попытка удалась, но первая могла тоже сработать: проверь календарь на дубль.', + attendanceDeclined: (title: string | null) => + title + ? `Участие в «${title}» отклонено; событие осталось в календаре.` + : 'Участие отклонено; событие осталось в календаре.', + retry: 'Скажи, что повторить: уже выполненное я повторять не буду.', + checkFirst: 'Проверь календарь, прежде чем повторять: сам я ничего не повторяю.', + people: (names: readonly string[], unnamed: number) => { + const count = `${unnamed} ${ruPlural(unnamed, 'человек', 'человека', 'человек')}`; + if (names.length === 0) return count; + return unnamed === 0 ? names.join(', ') : `${names.join(', ')} и ещё ${count}`; + }, + invitations: { + sent: (n: number, event: string, who: string) => + n === 1 ? `Приглашение на ${event} отправлено: ${who}.` : `Приглашения на ${event} отправлены: ${who}.`, + created: (n: number, event: string, who: string) => + n === 1 ? `Приглашение на ${event} создано: ${who}.` : `Приглашения на ${event} созданы: ${who}.`, + manual: (n: number, event: string, who: string) => + n === 1 + ? `Приглашение на ${event} создано, но не доставлено: ${who}. Перешли ссылку из личного чата.` + : `Приглашения на ${event} созданы, но не доставлены: ${who}. Перешли ссылки из личного чата.`, + undelivered: (n: number, event: string, who: string) => + n === 1 + ? `Приглашение на ${event} создано, но не доставлено: ${who}.` + : `Приглашения на ${event} созданы, но не доставлены: ${who}.`, + rejected: (n: number, event: string, who: string) => + n === 1 ? `Приглашение на ${event} не отправлено: ${who}.` : `Приглашения на ${event} не отправлены: ${who}.`, + unknown: (n: number, event: string, who: string) => + n === 1 + ? `Не удалось подтвердить, дошло ли приглашение на ${event}: ${who}.` + : `Не удалось подтвердить, дошли ли приглашения на ${event}: ${who}.`, + skipped: (n: number, event: string, who: string) => + n === 1 + ? `Приглашение на ${event} пропущено, повторно не отправлялось: ${who}.` + : `Приглашения на ${event} пропущены, повторно не отправлялись: ${who}.`, + }, operations: { - delete_event: 'Удаление события', - update_event: 'Изменение события', - create_event: 'Создание события', - send_invitation: 'Отправка приглашения', + create_event: { + done: 'Создано', + notDone: 'Не создано', + unknown: 'Не удалось подтвердить создание', + }, + update_event: { + done: 'Изменено', + notDone: 'Не изменено', + unknown: 'Не удалось подтвердить изменение', + }, + delete_event: { + done: 'Удалено', + notDone: 'Не удалено', + unknown: 'Не удалось подтвердить удаление', + }, }, + otherWrite: { + done: 'Выполнено', + notDone: 'Не выполнено', + unknown: 'Не удалось подтвердить выполнение', + }, + field: 'поле', fields: { title: 'название', start_at: 'начало', diff --git a/src/services/ai/agent/tool-round.ts b/src/services/ai/agent/tool-round.ts index 318abb01..d0403b83 100644 --- a/src/services/ai/agent/tool-round.ts +++ b/src/services/ai/agent/tool-round.ts @@ -114,8 +114,8 @@ async function executeFresh( const { ctx, writer, dbg, requestMetrics, exposure, ledger } = env; if (tc.name !== DISCOVERY_TOOL && !SILENT_TOOLS.has(tc.name)) { // Group chats: never surface raw tool arguments (invitee_id, owner_id, etc.) in the - // execution log — same "hide targets from other members" contract as finalNotice's - // hideTargets (ctx.isGroup). + // execution log — same "hide targets from other members" contract as the write receipt's + // ReceiptView.hideTargets (ctx.isGroup). writer.setToolLabel(tc.name, ctx.isGroup ? undefined : input); await writer.flush(true); } @@ -138,7 +138,7 @@ async function executeFresh( 'Tool call complete', ); } - ledger.writeOutcomes.record(tc.name, input, toolResult); + ledger.writeOutcomes.record(tc.name, input, toolResult, ctx.isGroup, ctx.user.timezone); // Record dedup key only after a successful execution — failed calls // must not block retries with a synthetic DUPLICATE result. diff --git a/src/services/ai/agent/turn-finish.ts b/src/services/ai/agent/turn-finish.ts index 63eb2a09..3530ff7d 100644 --- a/src/services/ai/agent/turn-finish.ts +++ b/src/services/ai/agent/turn-finish.ts @@ -7,6 +7,7 @@ import { elapsedMs } from '../request-metrics.ts'; import { unverifiedResponseNotice } from '../response-validator.ts'; import type { TelegramStreamWriter } from '../telegram-stream.ts'; import type { AgentContext } from '../types.ts'; +import { receiptView } from '../write-receipt.ts'; import { aiFailureNotices } from './failure-notices.ts'; import type { MessageParam } from './message-sanitizer.ts'; import { turnIds } from './queued-turn.ts'; @@ -48,8 +49,7 @@ export function planGuard(ctx: AgentContext, state: TurnState, runFailed: boolea const { writeOutcomes, toolEvidence } = ledger; const { termination, responseUnverified } = state; const evidence = writeOutcomes.finalNotice( - ctx.user.language, - ctx.isGroup, + receiptView(ctx), (runFailed || responseUnverified) && writeOutcomes.mayHaveMutated, ); // A supplement is optional text and stays quiet when guarded, unless it may have changed the @@ -240,7 +240,7 @@ export async function finishTurn( applyGuard(writer, plan, state, ledger); if (!plan.guarded) correctUtcClockTimesInReply(ctx, writer, state.pendingHistory); - const writes = writeOutcomes.summary(ctx.user.language, ctx.isGroup); + const writes = writeOutcomes.summary(receiptView(ctx)); const answeredByTool = writes === null && writeOutcomes.toolAnswered; const unansweredNotice = replaceSilentDraft(env, state, failure.failed, plan, writes, answeredByTool); persistTurnTail(env, state, plan, unansweredNotice, deps.saveTurn); diff --git a/src/services/ai/ask-user-buttons.ts b/src/services/ai/ask-user-buttons.ts new file mode 100644 index 00000000..470cd941 --- /dev/null +++ b/src/services/ai/ask-user-buttons.ts @@ -0,0 +1,64 @@ +// src/services/ai/ask-user-buttons.ts +// Callback data of ask_user buttons and the limits of the Telegram keyboard that carries them. +// +// Telegram rejects a button whose callback_data is over 64 UTF-8 bytes (BUTTON_DATA_INVALID) and +// Cyrillic costs two bytes a character, so an option over ~25 Russian characters cannot ride in +// its own callback data. Two forms therefore exist: +// - `ai_btn:{text}` / `ai_btn:{userId}:{text}`: the answer is the payload. Kept whenever it fits, +// so buttons already sitting in chats keep working. +// - `ai_opt:{index}` / `ai_opt:{userId}:{index}`: the payload only makes the button unique. The +// tap handler reads the answer from the label of the tapped button in the message's own inline +// keyboard, so the AI gets the full option text however long it is and nothing is stored +// server-side. A separate action name means an answer text can never be mistaken for an index +// (the colon/numeric-prefix ambiguity documented at `parseAiBtnPayload`). + +export const AI_BUTTON_ACTION = 'ai_btn'; +export const AI_OPTION_ACTION = 'ai_opt'; + +const CALLBACK_DATA_MAX_BYTES = 64; + +/** + * Buttons per ask_user keyboard: the 100-button total recorded in docs/reference/telegram-limits.md. + * That line carries no source link, so treat it as the repo's working limit, not a verified one. + */ +export const MAX_ASK_USER_OPTIONS = 100; + +/** Callback data for option `index`; the group form restricts the answer to `restrictedToUserId`. */ +export function askUserCallbackData(index: number, option: string, restrictedToUserId?: number): string { + const restriction = restrictedToUserId ? `${restrictedToUserId}:` : ''; + const direct = `${AI_BUTTON_ACTION}:${restriction}${option}`; + if (Buffer.byteLength(direct, 'utf8') <= CALLBACK_DATA_MAX_BYTES) return direct; + return `${AI_OPTION_ACTION}:${restriction}${index}`; +} + +/** Parses an `ai_opt` payload: "{index}" (private) or "{userId}:{index}" (group). Undefined when malformed. */ +export function parseAiOptionPayload(payload: string): { restrictedToUserId?: number } | undefined { + const segments = payload.split(':'); + if (segments.length > 2 || !segments.every((segment) => /^\d+$/.test(segment))) return undefined; + return segments.length === 2 ? { restrictedToUserId: Number(segments[0]) } : {}; +} + +/** The rows of an inline keyboard as Telegram returns them on the tapped message. */ +export type InlineKeyboardRows = ReadonlyArray>; + +/** + * What the keyboard cannot carry, worded for the model so it can correct the call: an empty question + * or option (a blank label removes its row) and more buttons than the documented keyboard limit. A + * label over 64 callback_data bytes is not a problem: it rides as an index, however long it is. + */ +export function askUserInputProblem( + question: string, + options: readonly string[], + addedButton?: string, +): string | undefined { + if (question.trim() === '') return 'the question is empty'; + if (options.length > MAX_ASK_USER_OPTIONS) { + // The cap is on buttons, so a button the tool appends itself counts: say so, in the model's own terms. + return addedButton === undefined + ? `${options.length} options do not fit on one Telegram keyboard (at most ${MAX_ASK_USER_OPTIONS}); offer fewer choices` + : `${options.length - 1} options plus the "${addedButton}" button this tool adds itself do not fit on one Telegram keyboard (at most ${MAX_ASK_USER_OPTIONS} buttons: ${MAX_ASK_USER_OPTIONS - 1} of your options); offer fewer choices`; + } + const blank = options.findIndex((option) => option.trim() === ''); + if (blank !== -1) return `option ${blank + 1} is empty; every option needs visible button text`; + return undefined; +} diff --git a/src/services/ai/recipient-confirmation.ts b/src/services/ai/recipient-confirmation.ts index 69dde05b..59d0fbf6 100644 --- a/src/services/ai/recipient-confirmation.ts +++ b/src/services/ai/recipient-confirmation.ts @@ -3,6 +3,8 @@ interface Approval { actorId: number; eventId: number; recipientId: number; + /** The calendar owner a secretary's invitation is for; absent for the user's own. */ + ownerId?: number; expiresAt: number; confirmed: boolean; } @@ -12,7 +14,7 @@ export function issueRecipientApproval( actorId: number, eventId: number, recipientId: number, - now = Date.now(), + { now = Date.now(), ownerId }: { now?: number; ownerId?: number } = {}, ): string { for (const [token, item] of approvals) if (item.expiresAt <= now) approvals.delete(token); if (approvals.size >= 1000) { @@ -20,7 +22,14 @@ export function issueRecipientApproval( if (first) approvals.delete(first); } const token = crypto.randomUUID(); - approvals.set(token, { actorId, eventId, recipientId, expiresAt: now + TTL, confirmed: false }); + approvals.set(token, { + actorId, + eventId, + recipientId, + ...(ownerId !== undefined && { ownerId }), + expiresAt: now + TTL, + confirmed: false, + }); return token; } export function confirmRecipientApproval( diff --git a/src/services/ai/recipient-identity.ts b/src/services/ai/recipient-identity.ts index 4197918f..bb9ab624 100644 --- a/src/services/ai/recipient-identity.ts +++ b/src/services/ai/recipient-identity.ts @@ -144,8 +144,9 @@ async function resolveGroupRecipient( } /** An explicit invitee_id that is an owned address-book row ID is ambiguous recipient evidence even when a saved - * contact has that Telegram ID: only an ID verified in this conversation (picker, username) or the invitation's - * own recipient overrides it. An ID derived from a saved @username is that contact's Telegram ID, not a row ID. */ + * contact has that Telegram ID: only an ID verified in this conversation (picker, username), the invitation's + * own recipient or the requester's own Telegram ID overrides it. An ID derived from a saved @username is that + * contact's Telegram ID, not a row ID. */ function findAmbiguousContactRow( ctx: AgentContext, input: RecipientInput, @@ -155,6 +156,7 @@ function findAmbiguousContactRow( if ( input.invitee_id === undefined || input.invitee_id === establishedInvitationRecipientId || + input.invitee_id === ctx.user.telegram_id || ctx.verifiedRecipientIds?.has(input.invitee_id) ) return null; diff --git a/src/services/ai/system-prompt.ts b/src/services/ai/system-prompt.ts index e16f2392..7a0614fd 100644 --- a/src/services/ai/system-prompt.ts +++ b/src/services/ai/system-prompt.ts @@ -500,6 +500,7 @@ If "Calendars you can manage as secretary" is listed in User Info: - If ambiguous (no person mentioned, the user could mean their own or a delegating user's calendar) — call ask_user with options like ["Мой", "@alice_cto"]. Do not assume. - If clearly the user's own calendar — do NOT pass owner_id. - When showing someone else's calendar, always say whose it is: "Вот расписание Алисы на сегодня:". +- INVITING to an event in another person's calendar: create_event with owner_id (the owner's Telegram ID; list_calendar_access shows it), then one send_invitation per person with the SAME owner_id (also for get_invitation_status, resend_invitation, cancel_invitation). The owner is the organizer, so unlike the PARTICIPANTS rule the user ("me", "меня") is invited like anyone else: invitee_id ${ctx.user.telegram_id} is the user's own Telegram ID. Resolve every other name with find_contact/get_contacts/find_user; when nobody is found ask for that person's @username (pick_users does not work for another person's calendar); never write a telegram_id no tool returned in this conversation. Never invite the owner. When the user wants to add a secretary to their calendar: 1. Use find_user to resolve name/username to telegram_id. diff --git a/src/services/ai/telegram-sender.ts b/src/services/ai/telegram-sender.ts index cf1a8f80..8d3e5d11 100644 --- a/src/services/ai/telegram-sender.ts +++ b/src/services/ai/telegram-sender.ts @@ -3,6 +3,7 @@ import { InlineKeyboard, Keyboard } from 'gramio'; import { CB } from '../../config/constants.ts'; import type { ParseMode } from '../../utils/telegram.ts'; import { groupRsvpKeyboard, invitationRsvpKeyboard } from '../sharing/invitation-rsvp-keyboard.ts'; +import { askUserCallbackData } from './ask-user-buttons.ts'; import type { InvitationKeyboardVariant, TelegramSender } from './types.ts'; interface TelegramSenderOptions { @@ -43,9 +44,8 @@ export function createTelegramSender(bot: Bot, options?: TelegramSenderOptions): }, async sendButtons(chatId: number, text: string, buttons: string[], parseMode?: ParseMode, userId?: number) { const kb = new InlineKeyboard(); - for (const btn of buttons) { - const cbData = userId ? `ai_btn:${userId}:${btn}` : `ai_btn:${btn}`; - kb.text(btn, cbData).row(); + for (const [index, btn] of buttons.entries()) { + kb.text(btn, askUserCallbackData(index, btn, userId)).row(); } const result = await bot.api.sendMessage({ chat_id: chatId, diff --git a/src/services/ai/tool-executor.ts b/src/services/ai/tool-executor.ts index 9c785ae4..08322015 100644 --- a/src/services/ai/tool-executor.ts +++ b/src/services/ai/tool-executor.ts @@ -117,13 +117,19 @@ export interface ToolInputMap { get_holidays: { limit?: number }; manage_settings: ManageSettingsInput; share_event: { event_id: number; target_type: 'user' | 'group'; target_id: number }; - send_invitation: { event_id: number; invitee_id?: number; invitee_username?: string; force?: boolean }; - get_invitation_status: { event_id: number }; + send_invitation: { + event_id: number; + invitee_id?: number; + invitee_username?: string; + force?: boolean; + owner_id?: number; + }; + get_invitation_status: { event_id: number; owner_id?: number }; share_agenda: { period: 'today' | 'tomorrow' | 'week'; target_type: 'user' | 'group'; target_id: number }; set_event_visibility: { event_id: number; visibility: 'private' | 'free_busy' | 'full'; owner_id?: number }; propose_edit: { event_id: number; changes: Record; reason?: string }; - cancel_invitation: { invitation_id: number }; - resend_invitation: { invitation_id: number; invitee_username?: string }; + cancel_invitation: { invitation_id: number; owner_id?: number }; + resend_invitation: { invitation_id: number; invitee_username?: string; owner_id?: number }; get_google_calendar_status: Record; list_google_calendars: Record; lookup_stress: { words: string[] }; diff --git a/src/services/ai/tool-handlers/meta.ts b/src/services/ai/tool-handlers/meta.ts index 37f45cee..6d013539 100644 --- a/src/services/ai/tool-handlers/meta.ts +++ b/src/services/ai/tool-handlers/meta.ts @@ -1,5 +1,6 @@ import { t, toLang } from '../../../config/constants.ts'; import { logger } from '../../../utils/logger.ts'; +import { askUserInputProblem } from '../ask-user-buttons.ts'; import { canResolveRecipientUsername, lookUpUsername, @@ -114,8 +115,16 @@ export async function handleAskUser( return { success: false, error: 'Buttons not supported.' }; } const CANCEL = 'Отмена'; - const options = askedOptions.some((o) => o === CANCEL) ? askedOptions : [...askedOptions, CANCEL]; + const cancelAdded = !askedOptions.some((o) => o === CANCEL); + const options = cancelAdded ? [...askedOptions, CANCEL] : askedOptions; const userId = ctx.isGroup ? ctx.user.telegram_id : undefined; + const problem = askUserInputProblem(question, options, cancelAdded ? CANCEL : undefined); + if (problem) { + return { + success: false, + error: `ASK_USER_INVALID_INPUT: ${problem}. Nothing was sent; correct the call and ask again.`, + }; + } try { await ctx.sender.sendButtons(ctx.chatId, question, options, 'HTML', userId); } catch (err) { diff --git a/src/services/ai/tool-handlers/sharing-invitation-delivery.ts b/src/services/ai/tool-handlers/sharing-invitation-delivery.ts index e71a9aed..2f994622 100644 --- a/src/services/ai/tool-handlers/sharing-invitation-delivery.ts +++ b/src/services/ai/tool-handlers/sharing-invitation-delivery.ts @@ -49,32 +49,41 @@ interface InvitationDeliveryTarget { inviteeUsername: string | undefined; event: CalendarEvent | null | undefined; isGroupTarget: boolean; + /** The event owner the invitation is sent for; differs from ctx.user when a secretary acts for them. */ + organizerId: number; } -/** Callers must have checked ctx.sender: deliverInvitation needs a sender to reach anyone. */ +/** + * Callers must have checked ctx.sender: deliverInvitation needs a sender to reach anyone. + * The card names the organizer (the event owner), while every message to the person who typed the + * request (the deep-link fallback) goes to ctx.user. A secretary never sends as the owner: neither + * the secretary's nor the owner's connected Telegram account is used on the owner's behalf. + */ export function deliverInvitationFromContext( ctx: AgentContext, sharing: SharingCapability, sender: NonNullable, target: InvitationDeliveryTarget, ): Promise { + const actingForOwner = target.organizerId !== ctx.user.telegram_id; + const organizer = actingForOwner ? ctx.userRepo.findByTelegramId(target.organizerId) : ctx.user; return deliverInvitation({ invitationId: target.invitationId, eventId: target.eventId, inviteeId: target.inviteeId, inviteeUsername: target.inviteeUsername, - inviterId: ctx.user.telegram_id, - inviterName: ctx.user.first_name ?? ctx.user.username ?? `User ${ctx.user.telegram_id}`, - inviterUsername: ctx.user.username ?? undefined, - inviterTimezone: ctx.user.timezone, + inviterId: target.organizerId, + inviterName: organizer?.first_name ?? organizer?.username ?? `User ${target.organizerId}`, + inviterUsername: organizer?.username ?? undefined, + inviterTimezone: organizer?.timezone ?? ctx.user.timezone, event: target.event, - lang: (ctx.user.language ?? 'en') as 'en' | 'ru', + lang: (organizer?.language ?? 'en') as 'en' | 'ru', inviterLang: (ctx.user.language ?? 'en') as 'en' | 'ru', // The deep-link fallback is a PRIVATE invite link — it must reach the inviter's // private chat, never ctx.chatId (which may be a group the bot was invoked from, // leaking the invitee's personal invitation to every member). fallbackChatId: ctx.user.telegram_id, - allowInviterSession: !target.isGroupTarget, + allowInviterSession: !target.isGroupTarget && !actingForOwner, isGroupTarget: target.isGroupTarget, deps: { sender, diff --git a/src/services/ai/tool-handlers/sharing-organizer-event.ts b/src/services/ai/tool-handlers/sharing-organizer-event.ts new file mode 100644 index 00000000..72120656 --- /dev/null +++ b/src/services/ai/tool-handlers/sharing-organizer-event.ts @@ -0,0 +1,20 @@ +// Which event an invitation tool may act on for a given organizer. For the caller's own calendar this is +// everything the caller sees (the group events of their chats included, as before). For a calendar a +// secretary manages it is only what the owner organises personally: EventService.getEvent also returns +// the group events the owner merely sees as a member, and the secretary's delegation never covered those. +import type { CalendarEvent } from '../../../database/types.ts'; +import type { AgentContext, ToolResult } from '../types.ts'; + +export function getEventForOrganizer(ctx: AgentContext, eventId: number, organizerId: number): CalendarEvent | null { + const event = ctx.eventService.getEvent(eventId, organizerId); + if (organizerId === ctx.user.telegram_id) return event; + return event && event.owner_type !== 'group' && event.user_id === organizerId ? event : null; +} + +export function eventNotInOwnerCalendar(eventId: number, ownerId: number): ToolResult { + return { + success: false, + mutationState: 'not_applied', + error: `Event ${eventId} not found in the calendar of user ${ownerId}.`, + }; +} diff --git a/src/services/ai/tool-handlers/sharing-recipient-rejection.ts b/src/services/ai/tool-handlers/sharing-recipient-rejection.ts index 9b3b7e59..80f96b71 100644 --- a/src/services/ai/tool-handlers/sharing-recipient-rejection.ts +++ b/src/services/ai/tool-handlers/sharing-recipient-rejection.ts @@ -18,13 +18,23 @@ type IdentityRecipient = Exclude { const inviteeId = input.invitee_id; if (input.force || ctx.isGroup || inviteeId === undefined || inviteeId <= 0 || !ctx.sender?.sendMessageWithKeyboard) { return null; } - const approval = issueRecipientApproval(ctx.user.telegram_id, input.event_id, inviteeId); + const approval = issueRecipientApproval(ctx.user.telegram_id, input.event_id, inviteeId, { + ownerId: forOwner ? input.owner_id : undefined, + }); const tr = t(ctx.user.language).aiTools.meta; const saved = ctx.contactRepo?.findByTelegramId(ctx.user.telegram_id, inviteeId); const details = [tr.recipientConfirmDetails(inviteeId, escapeHtml(input.invitee_username ?? '—'))]; @@ -79,8 +104,9 @@ async function requestRecipientConfirmation( mutationState: 'not_applied', stopLoop: true, output: tr.recipientConfirmationSent, - agentHint: - 'Wait for the actual confirmation callback or use pick_users. force=true alone cannot bypass identity confirmation; it never changes the numeric recipient.', + // The picker invites as the person who taps it, so it is no way round the confirmation for a secretary; + // the confirmation itself tells the model how to send for the owner. + agentHint: `Wait for the actual confirmation callback${forOwner ? '; it says how to send' : ' or use pick_users'}. force=true alone cannot bypass identity confirmation; it never changes the numeric recipient.`, }; } @@ -98,27 +124,31 @@ function pickRecipientForUsername( return handlePickUsers({ ...ctx, chatId: ctx.user.telegram_id }, { event_id: eventId, prompt }); } -function unverifiedRecipientRejection(ctx: AgentContext, recipient: IdentityRecipient): ToolResult { +function unverifiedRecipientRejection(ctx: AgentContext, recipient: IdentityRecipient, forOwner: boolean): ToolResult { const tr = t(ctx.user.language).aiTools.meta; return { success: false, mutationState: 'not_applied', error: recipient.reason === 'conflict' ? tr.recipientIdentityConflict : tr.recipientUnverified, - agentHint: - 'Use find_contact, an exact user-provided @username, or pick_users. Do not guess or reuse an unverified recipient ID.', + // The picker invites as the person who taps it, from their own calendar only. + agentHint: forOwner + ? "Use find_contact or an exact user-provided @username; pick_users cannot invite into another person's calendar, so ask the user for that person's @username instead. Do not guess or reuse an unverified recipient ID." + : 'Use find_contact, an exact user-provided @username, or pick_users. Do not guess or reuse an unverified recipient ID.', }; } +/** `forOwner`: a secretary invites into the owner's calendar, where the user picker does not apply. */ export async function rejectUnresolvedRecipient( ctx: AgentContext, input: SendInvitationRecipientInput, recipient: UnresolvedRecipient, + forOwner: boolean, ): Promise { - if (recipient.reason === 'contact_row_id') return contactRowIdRejection(ctx, input.event_id, recipient); - const confirmation = await requestRecipientConfirmation(ctx, input, recipient); + if (recipient.reason === 'contact_row_id') return contactRowIdRejection(ctx, input.event_id, recipient, forOwner); + const confirmation = await requestRecipientConfirmation(ctx, input, recipient, forOwner); if (confirmation) return confirmation; - if ((recipient.reason === 'not_found' || recipient.reason === 'unavailable') && recipient.username) { + if (!forOwner && (recipient.reason === 'not_found' || recipient.reason === 'unavailable') && recipient.username) { return pickRecipientForUsername(ctx, input.event_id, recipient.reason, recipient.username); } - return unverifiedRecipientRejection(ctx, recipient); + return unverifiedRecipientRejection(ctx, recipient, forOwner); } diff --git a/src/services/ai/tool-handlers/sharing.ts b/src/services/ai/tool-handlers/sharing.ts index 669c60bb..ce24e719 100644 --- a/src/services/ai/tool-handlers/sharing.ts +++ b/src/services/ai/tool-handlers/sharing.ts @@ -1,6 +1,6 @@ import { t, toLang } from '../../../config/constants.ts'; import { UNRESOLVED_PLACE } from '../../../database/repositories/event.repository.ts'; -import type { Invitation, Visibility } from '../../../database/types.ts'; +import type { CalendarEvent, Invitation, Visibility } from '../../../database/types.ts'; import type { InvitationDeliveryResult } from '../invitation-delivery.ts'; import { resolveInvitationRecipient } from '../recipient-identity.ts'; import type { AgentContext, SharingCapability, ToolHandlerMeta, ToolResult } from '../types.ts'; @@ -13,6 +13,7 @@ import { deliveryState, hintWithConnectSuggestion, } from './sharing-invitation-delivery.ts'; +import { eventNotInOwnerCalendar, getEventForOrganizer } from './sharing-organizer-event.ts'; import { type ResolvedRecipient, rejectUnresolvedRecipient, @@ -39,10 +40,12 @@ interface SendInvitationInput { event_id: number; invitee_id?: number; invitee_username?: string; + owner_id?: number; } interface GetInvitationStatusInput { event_id: number; + owner_id?: number; } interface ShareAgendaInput { @@ -104,6 +107,7 @@ const SEND_OUTCOME_KEYS = { async function resolveSendRecipient( ctx: AgentContext, input: SendInvitationInput, + forOwner: boolean, ): Promise<{ recipient: ResolvedRecipient } | { denied: ToolResult }> { let recipient: ResolvedRecipient | UnresolvedRecipient; try { @@ -123,13 +127,18 @@ async function resolveSendRecipient( }, }; } - if (!recipient.ok) return { denied: await rejectUnresolvedRecipient(ctx, input, recipient) }; + if (!recipient.ok) return { denied: await rejectUnresolvedRecipient(ctx, input, recipient, forOwner) }; return { recipient }; } -/** Auto-add the invitee to the inviter's contacts. */ +/** Auto-add the invitee to the contacts of the user who named them (never the user themself). */ function addInviteeToContacts(ctx: AgentContext, invitationId: number, recipient: ResolvedRecipient): void { - if (!ctx.contactRepo || recipient.isGroup || ctx.contactRepo.findByTelegramId(ctx.user.telegram_id, recipient.id)) { + if ( + !ctx.contactRepo || + recipient.isGroup || + recipient.id === ctx.user.telegram_id || + ctx.contactRepo.findByTelegramId(ctx.user.telegram_id, recipient.id) + ) { return; } const invitee = ctx.userRepo.findByTelegramId(recipient.id); @@ -143,30 +152,108 @@ function addInviteeToContacts(ctx: AgentContext, invitationId: number, recipient } } -export async function handleSendInvitation(ctx: AgentContext, input: SendInvitationInput): Promise { - if (!ctx.sharing?.invitationService) { - return { success: false, mutationState: 'not_applied', error: 'Invitations are not configured.' }; - } +const EVENT_NOT_FOUND = 'Event not found'; - if (input.invitee_id === undefined && !input.invitee_username) { - return { success: false, mutationState: 'not_applied', error: t(ctx.user.language).aiTools.meta.recipientMissing }; - } +const SENT_FOR_OWNER_HINT = + 'You sent it on behalf of the calendar owner: the invitation names the owner as organizer. Say it was sent for them.'; - if (!ctx.eventService.getEvent(input.event_id, ctx.user.telegram_id)) - return { success: false, mutationState: 'not_applied', error: 'Event not found' }; +/** The owner sees this event only through a group: a secretary acts on the owner's personal events alone. */ +function groupEventScopeDenial(eventId: number, ownerId: number): ToolResult { + return { + success: false, + mutationState: 'not_applied', + error: `Event ${eventId} is visible to user ${ownerId} through a group. A secretary acts only on the owner's personal events, so this invitation cannot be sent for the owner.`, + }; +} - const resolved = await resolveSendRecipient(ctx, input); - if ('denied' in resolved) return resolved.denied; - const { recipient } = resolved; - const isGroupTarget = recipient.isGroup; +/** + * The event is not in the calendar this call acts for. The caller learns about it only from a calendar + * they may write in (and so read: get_event already shows them its events), the one named by owner_id or + * the one that holds the event: a personal event of the latter gets the retry hint, an event that + * calendar's owner sees only through a group gets the scope denial. Anyone else, and an event nobody + * can see (missing, deleted, cancelled), gets the answer of a missing id. + */ +function eventNotFoundForInvitation(ctx: AgentContext, eventId: number, organizerId: number): ToolResult { + const notFound: ToolResult = { success: false, mutationState: 'not_applied', error: EVENT_NOT_FOUND }; + const holderId = ctx.eventService.getEventOwnerId(eventId); + const callerId = ctx.user.telegram_id; + for (const calendarId of new Set([organizerId, holderId])) { + if (calendarId === null || calendarId === callerId) continue; + const access = checkSecretaryAccess(callerId, calendarId, ctx.secretary?.secretaryRepo ?? null, 'write'); + const event = access.ok ? ctx.eventService.getEvent(eventId, calendarId) : null; + if (!event) continue; + if (event.owner_type === 'group' || event.user_id !== calendarId) return groupEventScopeDenial(eventId, calendarId); + if (calendarId !== organizerId) { + return { + ...notFound, + agentHint: `Event ${eventId} is in the calendar of user ${calendarId}, which you manage as a secretary. Retry with owner_id ${calendarId}.`, + }; + } + } + return notFound; +} - const result = ctx.sharing.invitationService.sendInvitation( - input.event_id, +const ORGANIZER_NEEDS_NO_INVITATION: ToolResult = { + success: false, + mutationState: 'not_applied', + error: 'The calendar owner is the organizer of this event and needs no invitation.', +}; + +/** + * Who sends for whom and which event, read now. Run before the recipient lookup (to refuse early) and + * again after it: the lookup awaits the network, and the delegation may be revoked or the event changed + * or deleted meanwhile. + */ +function sendScope( + ctx: AgentContext, + input: SendInvitationInput, +): { organizerId: number; actingForOwner: boolean; event: CalendarEvent } | { denied: ToolResult } { + const access = checkSecretaryAccess( ctx.user.telegram_id, - recipient.id, - recipient.username, + input.owner_id, + ctx.secretary?.secretaryRepo ?? null, + 'write', ); + if (!access.ok) return { denied: { success: false, mutationState: 'not_applied', error: access.error } }; + const organizerId = access.effectiveUserId; + const actingForOwner = organizerId !== ctx.user.telegram_id; + + const event = getEventForOrganizer(ctx, input.event_id, organizerId); + if (!event) return { denied: eventNotFoundForInvitation(ctx, input.event_id, organizerId) }; + if (actingForOwner && input.invitee_id === organizerId) return { denied: ORGANIZER_NEEDS_NO_INVITATION }; + return { organizerId, actingForOwner, event }; +} +/** The refusal before any recipient lookup: no recipient named, or no event this caller may invite into. */ +function prepareSend( + ctx: AgentContext, + input: SendInvitationInput, +): { actingForOwner: boolean } | { denied: ToolResult } { + if (input.invitee_id === undefined && !input.invitee_username) { + return { + denied: { + success: false, + mutationState: 'not_applied', + error: t(ctx.user.language).aiTools.meta.recipientMissing, + }, + }; + } + const scope = sendScope(ctx, input); + return 'denied' in scope ? scope : { actingForOwner: scope.actingForOwner }; +} + +/** Creates the invitation for the already verified recipient, delivers it and words the outcome. */ +async function createAndDeliverInvitation( + ctx: AgentContext, + invitationService: SharingCapability['invitationService'], + sharing: SharingCapability, + input: SendInvitationInput, + recipient: ResolvedRecipient, + scope: { organizerId: number; actingForOwner: boolean; event: CalendarEvent }, +): Promise { + const { organizerId, actingForOwner, event } = scope; + const isGroupTarget = recipient.isGroup; + const result = invitationService.sendInvitation(input.event_id, organizerId, recipient.id, recipient.username); if (!result.success) { return { success: false, mutationState: 'not_applied', error: result.error }; } @@ -174,19 +261,22 @@ export async function handleSendInvitation(ctx: AgentContext, input: SendInvitat const invitation = result.invitation!; addInviteeToContacts(ctx, invitation.id, recipient); - const event = ctx.eventService.getEvent(input.event_id, ctx.user.telegram_id); const delivery: InvitationDeliveryResult = ctx.sender - ? await deliverInvitationFromContext(ctx, ctx.sharing, ctx.sender, { + ? await deliverInvitationFromContext(ctx, sharing, ctx.sender, { invitationId: invitation.id, eventId: input.event_id, inviteeId: recipient.id, inviteeUsername: recipient.username, event, isGroupTarget, + organizerId, }) : { delivered: false, viaDeepLink: false, viaBotApi: false }; - const connectSuggestion = connectSuggestionAfterDelivery(ctx, delivery, isGroupTarget, invitation.id); + // /connect_telegram would not help here: a secretary's connected account never sends for the owner. + const connectSuggestion = actingForOwner + ? null + : connectSuggestionAfterDelivery(ctx, delivery, isGroupTarget, invitation.id); const state = deliveryState(delivery); return { @@ -200,17 +290,69 @@ export async function handleSendInvitation(ctx: AgentContext, input: SendInvitat t(toLang(ctx.user.language)).writeOutcomes[SEND_OUTCOME_KEYS[state]], ...(connectSuggestion ? [connectSuggestion] : []), ].join('\n'), - agentHint: hintWithConnectSuggestion(SEND_DELIVERY_HINTS[state], connectSuggestion), + agentHint: hintWithConnectSuggestion( + actingForOwner ? `${SEND_DELIVERY_HINTS[state]} ${SENT_FOR_OWNER_HINT}` : SEND_DELIVERY_HINTS[state], + connectSuggestion, + ), }; } -export function handleCancelInvitation(ctx: AgentContext, input: { invitation_id: number }): ToolResult { +/** + * Invitations on a secretary-managed event belong to the event owner, not to the secretary who typed + * the request: `inviter_id` is the owner. Every consumer of an invitation (the card, RSVP notices + * to the organizer, the roster, reschedule and cancel) reads the event as + * `findById(event_id, invitation.inviter_id)`, so the secretary's id there would find no event. + */ +export async function handleSendInvitation(ctx: AgentContext, input: SendInvitationInput): Promise { if (!ctx.sharing?.invitationService) { - return { success: false, error: 'Invitations are not configured.' }; + return { success: false, mutationState: 'not_applied', error: 'Invitations are not configured.' }; } - const result = ctx.sharing.invitationService.cancelInvitation(input.invitation_id, ctx.user.telegram_id); + + const prepared = prepareSend(ctx, input); + if ('denied' in prepared) return prepared.denied; + + const resolved = await resolveSendRecipient(ctx, input, prepared.actingForOwner); + if ('denied' in resolved) return resolved.denied; + const { recipient } = resolved; + + // The lookup awaited the network: decide on the delegation and the event as they are now, so a revoked + // secretary creates nothing and the card shows the current event. + const scope = sendScope(ctx, input); + if ('denied' in scope) return scope.denied; + if (scope.actingForOwner && recipient.id === scope.organizerId) return ORGANIZER_NEEDS_NO_INVITATION; + return createAndDeliverInvitation(ctx, ctx.sharing.invitationService, ctx.sharing, input, recipient, scope); +} + +export function handleCancelInvitation( + ctx: AgentContext, + input: { invitation_id: number; owner_id?: number }, +): ToolResult { + if (!ctx.sharing?.invitationService) { + return { success: false, mutationState: 'not_applied', error: 'Invitations are not configured.' }; + } + const access = checkSecretaryAccess( + ctx.user.telegram_id, + input.owner_id, + ctx.secretary?.secretaryRepo ?? null, + 'write', + ); + if (!access.ok) return { success: false, mutationState: 'not_applied', error: access.error }; + // The service answers a foreign invitation 'Not authorized to cancel' and a missing one 'Invitation + // not found'; either wording alone would tell a guesser which ids exist, so both get the missing answer. + const own = ctx.sharing.invitationRepo.findById(input.invitation_id); + if (!own || own.inviter_id !== access.effectiveUserId) { + return { success: false, mutationState: 'not_applied', error: 'Invitation not found' }; + } + // A delegated cancel reaches only invitations to events the owner organises personally (not group events). + if ( + access.effectiveUserId !== ctx.user.telegram_id && + !getEventForOrganizer(ctx, own.event_id, access.effectiveUserId) + ) { + return eventNotInOwnerCalendar(own.event_id, access.effectiveUserId); + } + const result = ctx.sharing.invitationService.cancelInvitation(input.invitation_id, access.effectiveUserId); if (!result.success) { - return { success: false, error: result.error }; + return { success: false, mutationState: 'not_applied', error: result.error }; } return { success: true, @@ -220,20 +362,52 @@ export function handleCancelInvitation(ctx: AgentContext, input: { invitation_id /** The owned pending invitation a resend may act on, or the reason it may not. */ function findResendableInvitation( - ctx: AgentContext, invitationRepo: SharingCapability['invitationRepo'], invitationId: number, + organizerId: number, ): { invitation: Invitation } | { denied: ToolResult } { const invitation = invitationRepo.findById(invitationId); - if (!invitation) return { denied: { success: false, error: 'Invitation not found.' } }; - if (invitation.inviter_id !== ctx.user.telegram_id) - return { denied: { success: false, error: 'Not your invitation.' } }; + // A foreign invitation answers exactly as a missing one, for every caller: a different wording would + // tell anyone who guesses ids which of them exist. + if (!invitation || invitation.inviter_id !== organizerId) { + return { denied: { success: false, mutationState: 'not_applied', error: 'Invitation not found.' } }; + } if (invitation.status !== 'pending') { - return { denied: { success: false, error: `Cannot resend — status is "${invitation.status}".` } }; + return { + denied: { + success: false, + mutationState: 'not_applied', + error: `Cannot resend — status is "${invitation.status}".`, + }, + }; } return { invitation }; } +/** + * Write access and the invitation's event as they are after the awaited recipient lookup. A secretary + * revoked meanwhile delivers nothing, and a calendar the owner does not personally organise is refused + * (the caller's own resend keeps going without an event: the card then carries no event details). + */ +function currentResendScope( + ctx: AgentContext, + input: { owner_id?: number }, + eventId: number, +): { event: CalendarEvent | null } | { denied: ToolResult } { + const access = checkSecretaryAccess( + ctx.user.telegram_id, + input.owner_id, + ctx.secretary?.secretaryRepo ?? null, + 'write', + ); + if (!access.ok) return { denied: { success: false, mutationState: 'not_applied', error: access.error } }; + const event = getEventForOrganizer(ctx, eventId, access.effectiveUserId); + if (!event && access.effectiveUserId !== ctx.user.telegram_id) { + return { denied: eventNotInOwnerCalendar(eventId, access.effectiveUserId) }; + } + return { event }; +} + const RESEND_DELIVERY_HINTS: Record = { delivered: 'The invitation reminder was delivered to the invitee. Tell the user it is sent.', manual_forward: 'Bot-API reminder failed. Deep-link fallback sent to the inviter.', @@ -242,12 +416,20 @@ const RESEND_DELIVERY_HINTS: Record = { export async function handleResendInvitation( ctx: AgentContext, - input: { invitation_id: number; invitee_username?: string }, + input: { invitation_id: number; invitee_username?: string; owner_id?: number }, ): Promise { if (!ctx.sharing) { - return { success: false, error: 'Invitations are not configured.' }; + return { success: false, mutationState: 'not_applied', error: 'Invitations are not configured.' }; } - const found = findResendableInvitation(ctx, ctx.sharing.invitationRepo, input.invitation_id); + const access = checkSecretaryAccess( + ctx.user.telegram_id, + input.owner_id, + ctx.secretary?.secretaryRepo ?? null, + 'write', + ); + if (!access.ok) return { success: false, mutationState: 'not_applied', error: access.error }; + const organizerId = access.effectiveUserId; + const found = findResendableInvitation(ctx.sharing.invitationRepo, input.invitation_id, organizerId); if ('denied' in found) return found.denied; const { invitation } = found; @@ -264,15 +446,19 @@ export async function handleResendInvitation( const tr = t(ctx.user.language).aiTools.meta; return { success: false, + mutationState: 'not_applied', error: recipient.reason === 'conflict' ? tr.recipientIdentityConflict : tr.recipientUnverified, }; } // Guard on the sender object (mirrors handleSendInvitation); deliverInvitation itself // reports non-delivery when the sender lacks the sendInvitation capability. - if (!ctx.sender) return { success: false, error: 'Message delivery not available.' }; + if (!ctx.sender) return { success: false, mutationState: 'not_applied', error: 'Message delivery not available.' }; - const event = ctx.eventService.getEvent(invitation.event_id, ctx.user.telegram_id); + // The recipient lookup awaited the network: access and the event are decided as they are now. + const current = currentResendScope(ctx, input, invitation.event_id); + if ('denied' in current) return current.denied; + const { event } = current; // A group invitation stores the (negative) group chat id as invitee_id. Resending it must use // the group delivery mode (per-member RSVP keyboard, no user-session send, no deep-link forward) — exactly // what the chat_shared picker does. Without this it would deliver the personal inv: keyboard @@ -287,8 +473,13 @@ export async function handleResendInvitation( inviteeUsername: isGroupTarget ? undefined : (recipient.username ?? invitation.invitee_username ?? undefined), event, isGroupTarget, + organizerId, }); - const connectSuggestion = connectSuggestionAfterDelivery(ctx, delivery, isGroupTarget, invitation.id); + // A secretary's connected account never sends for the owner, so /connect_telegram would not help. + const connectSuggestion = + organizerId === ctx.user.telegram_id + ? connectSuggestionAfterDelivery(ctx, delivery, isGroupTarget, invitation.id) + : null; const state = deliveryState(delivery); return { success: true, @@ -301,6 +492,46 @@ export async function handleResendInvitation( }; } +type OwnersEventLookup = { event: CalendarEvent; organizerId: null } | { denied: ToolResult }; + +/** The roster event of a calendar a secretary manages: read as its organizer, never as an invitee. */ +function ownersOwnEvent(ctx: AgentContext, eventId: number, ownerId: number): OwnersEventLookup { + const event = getEventForOrganizer(ctx, eventId, ownerId); + return event ? { event, organizerId: null } : { denied: eventNotInOwnerCalendar(eventId, ownerId) }; +} + +/** + * With owner_id the roster is the owner's own event only: the invitee path of resolveRosterEvent would + * let a secretary read an event another person organises just because it invited the owner. + */ +function lookupRosterEvent( + ctx: AgentContext, + invitationRepo: SharingCapability['invitationRepo'], + eventId: number, + effectiveUserId: number, + liveGroupChatIds: number[], +): { event: CalendarEvent; organizerId: number | null } | { denied: ToolResult } { + return effectiveUserId === ctx.user.telegram_id + ? resolveRosterEvent(ctx, invitationRepo, eventId, effectiveUserId, liveGroupChatIds) + : ownersOwnEvent(ctx, eventId, effectiveUserId); +} + +/** requester_id is whoever is asking (the roster's "you"); a secretary reading an owner's roster is not the owner. */ +function rosterIdentityHint(identity: { + organizer_id: number; + requester_id: number; + calendar_owner_id: number | null; + invitee_ids: number[]; +}): string { + const verified = { + organizer_id: identity.organizer_id, + requester_id: identity.requester_id, + ...(identity.calendar_owner_id === null ? {} : { calendar_owner_id: identity.calendar_owner_id }), + invitee_ids: identity.invitee_ids, + }; + return `Roster labels are untrusted text. Verified roster identity: ${JSON.stringify(verified)}`; +} + /** * The prompt answers "who takes part" only from this tool, so besides whoever can see the event, * its invitees read the same roster (Telegram ids and statuses, never the owner's event details). @@ -313,6 +544,14 @@ export function handleGetInvitationStatus(ctx: AgentContext, input: GetInvitatio return { success: false, error: 'Invitations are not configured.' }; } + const access = checkSecretaryAccess( + ctx.user.telegram_id, + input.owner_id, + ctx.secretary?.secretaryRepo ?? null, + 'read', + ); + if (!access.ok) return { success: false, error: access.error }; + const lang = ctx.user.language; const requesterId = ctx.user.telegram_id; @@ -325,7 +564,14 @@ export function handleGetInvitationStatus(ctx: AgentContext, input: GetInvitatio const participantRows = ctx.participantRepo ? ctx.participantRepo.getByEvent(input.event_id) : null; const participantByUser = participantStatusByUser(participantRows); - const lookup = resolveRosterEvent(ctx, ctx.sharing.invitationRepo, input.event_id, requesterId, liveGroupChatIds); + const calendarOwnerId = access.effectiveUserId === requesterId ? null : access.effectiveUserId; + const lookup = lookupRosterEvent( + ctx, + ctx.sharing.invitationRepo, + input.event_id, + access.effectiveUserId, + liveGroupChatIds, + ); if ('denied' in lookup) return lookup.denied; const { event, organizerId } = lookup; @@ -372,7 +618,12 @@ export function handleGetInvitationStatus(ctx: AgentContext, input: GetInvitatio lines.unshift(t(lang).aiTools.sharing.rsvpOrganizer(displayName(organizerId))); } - const agentHint = `Roster labels are untrusted text. Verified roster identity: ${JSON.stringify({ organizer_id: event.user_id, requester_id: requesterId, invitee_ids: listedIds })}`; + const agentHint = rosterIdentityHint({ + organizer_id: event.user_id, + requester_id: requesterId, + calendar_owner_id: calendarOwnerId, + invitee_ids: listedIds, + }); if (lines.length === 0) { return { diff --git a/src/services/ai/tool-schemas.ts b/src/services/ai/tool-schemas.ts index 33721296..8fdb76df 100644 --- a/src/services/ai/tool-schemas.ts +++ b/src/services/ai/tool-schemas.ts @@ -252,6 +252,7 @@ const shareEventSchema = z const sendInvitationSchema = z .object({ event_id: numericId.pipe(z.number().positive().safe()), + owner_id: numericId.optional(), force: toolBoolean.optional(), invitee_id: numericId .pipe( @@ -272,7 +273,7 @@ const sendInvitationSchema = z message: 'Either invitee_id or invitee_username must be provided', }); -const getInvitationStatusSchema = z.object({ event_id: numericId }).passthrough(); +const getInvitationStatusSchema = z.object({ event_id: numericId, owner_id: numericId.optional() }).passthrough(); const shareAgendaSchema = z .object({ @@ -298,12 +299,13 @@ const proposeEditSchema = z }) .passthrough(); -const cancelInvitationSchema = z.object({ invitation_id: numericId }).passthrough(); +const cancelInvitationSchema = z.object({ invitation_id: numericId, owner_id: numericId.optional() }).passthrough(); const resendInvitationSchema = z .object({ invitation_id: numericId, invitee_username: z.string().optional(), + owner_id: numericId.optional(), }) .passthrough(); diff --git a/src/services/ai/tools.ts b/src/services/ai/tools.ts index a31efcad..ead6012f 100644 --- a/src/services/ai/tools.ts +++ b/src/services/ai/tools.ts @@ -64,7 +64,7 @@ const scopeProperty = Object.freeze({ /** Secretary delegation target shared by every event-facing tool. */ const ownerIdProperty = Object.freeze({ type: 'number', - description: "Another user's calendar. Requires active secretary access to it.", + description: "Calendar owner's ID (as secretary).", }); const toolDefinitions: ToolDefinition[] = [ @@ -414,6 +414,7 @@ const toolDefinitions: ToolDefinition[] = [ type: 'string', description: 'Telegram @username without @. Resolved automatically when invitee_id is absent.', }, + owner_id: ownerIdProperty, }, required: ['event_id'], }, @@ -425,6 +426,7 @@ const toolDefinitions: ToolDefinition[] = [ type: 'object' as const, properties: { event_id: { type: 'number', description: 'ID of the event to check invitations for' }, + owner_id: ownerIdProperty, }, required: ['event_id'], }, @@ -676,6 +678,7 @@ const toolDefinitions: ToolDefinition[] = [ type: 'object' as const, properties: { invitation_id: { type: 'number', description: 'ID of the invitation to cancel' }, + owner_id: ownerIdProperty, }, required: ['invitation_id'], }, @@ -688,6 +691,7 @@ const toolDefinitions: ToolDefinition[] = [ properties: { invitation_id: { type: 'number', description: 'ID of the invitation to resend' }, invitee_username: { type: 'string', description: 'Telegram @username without @, if known.' }, + owner_id: ownerIdProperty, }, required: ['invitation_id'], }, diff --git a/src/services/ai/write-outcomes.ts b/src/services/ai/write-outcomes.ts index fcc82201..6a91eb4b 100644 --- a/src/services/ai/write-outcomes.ts +++ b/src/services/ai/write-outcomes.ts @@ -1,13 +1,35 @@ -/** Run-local mutation evidence. Receipts describe attempts, not durable operation intent. */ -import { type Messages, t, toLang } from '../../config/constants.ts'; +/** + * Run-local mutation evidence. It decides whether the model's own text may stand (a failed, + * skipped, unconfirmed or undelivered write means it may not) and supplies the receipt that + * replaces it (see write-receipt.ts). Receipts describe this run's attempts, not durable intent. + */ + import { EVENT_UPDATE_FIELDS, UNRESOLVED_PLACE } from '../../database/repositories/event.repository.ts'; +import { allDayCalendarDate } from '../../utils/date.ts'; +import { eventTimestampSchema } from '../../utils/event-timestamps.ts'; +import { extractEventSummaries } from './event-summaries.ts'; import { normalizeNumericId } from './numeric-id.ts'; +import { normalizeRecipientUsername } from './recipient-identity.ts'; import { DELIVERING_TOOLS, type ExecutorDisposition, isMutationTool, SILENT_TOOLS } from './tool-executor.ts'; +import { resolveScope } from './tool-handlers/shared.ts'; import type { ToolResult } from './types.ts'; +import { + type CreateDetails, + type CreateKeyParts, + type CreateKeys, + type EventRef, + type Invitee, + type KnownEvent, + type ReceiptView, + renderReceipt, + type Timing, + type WriteOutcome, +} from './write-receipt.ts'; const targets = { delete_event: ['event_id', 'scope', 'owner_id'], update_event: ['event_id', 'scope', 'owner_id'], + // No owner_id: event ids are global, so a retry that adds the calendar owner is the same invitation. send_invitation: ['event_id', 'invitee_id', 'invitee_username'], } satisfies { [operation: string]: string[] }; /** Fields update_event can change; the confirmed place is set only by the creator's tap or pin (#620). */ @@ -17,69 +39,275 @@ const updateFields = [...EVENT_UPDATE_FIELDS, 'location_abstract'].filter( function isTargetOperation(operation: string): operation is keyof typeof targets { return Object.hasOwn(targets, operation); } -function safeId(value: unknown): string | null { +function positiveId(value: unknown): number | null { const id = normalizeNumericId(value); - return typeof id === 'number' && Number.isSafeInteger(id) ? `#${id}` : null; + return typeof id === 'number' && Number.isSafeInteger(id) && id > 0 ? id : null; } /** - * What makes two calls the same write: the target fields of a target operation, normalized so an - * id sent as "7" and as 7 collide. Any other write is distinct per attempt. + * What makes two calls the same write: the target fields of a target operation, normalized so an id sent + * as "7" and as 7 collide, and an invitee is the person inviteeOf reads ("bob", "@bob" and " Bob" are one). + * Any other write is distinct per attempt. */ function attemptIdentity(operation: string, fields: object, attempt: number): number | unknown[] { if (!isTargetOperation(operation)) return attempt; + if (operation === 'send_invitation') { + const who = inviteeOf(fields); + const target = who + ? (who.id ?? `@${who.username}`) + : [Reflect.get(fields, 'invitee_id'), Reflect.get(fields, 'invitee_username')]; + return [normalizeNumericId(Reflect.get(fields, 'event_id')), target]; + } return targets[operation].map((field) => { - if (field === 'invitee_username' && Reflect.get(fields, 'invitee_id') !== undefined) return [field, undefined]; const value: unknown = Reflect.get(fields, field); return [field, field.endsWith('_id') ? normalizeNumericId(value) : value]; }); } -/** The `#id / #id` tail of a receipt line, from whichever id fields the call carried. */ -function targetLabel(fields: object): string { - return ['event_id', 'invitee_id', 'id'] - .map((field) => safeId(Reflect.get(fields, field))) - .filter((id) => id !== null) - .join(' / '); -} /** update_event is judged field by field; the fields the call actually set. */ function requestedUpdateFields(operation: string, fields: object): string[] { if (operation !== 'update_event') return []; return updateFields.filter((field) => Reflect.get(fields, field) !== undefined); } -interface WriteOutcome { - operation: string; - target: string; - field?: string; - success: boolean; - disposition: ExecutorDisposition; - mutationState?: ToolResult['mutationState']; - effect?: ToolResult['effect']; - attempt: number; +/** Who a send_invitation call named: the numeric id wins over a username, as in the identity. */ +function inviteeOf(fields: object): Invitee | null { + const id = positiveId(Reflect.get(fields, 'invitee_id')); + if (id !== null) return { id, username: null }; + const username: unknown = Reflect.get(fields, 'invitee_username'); + const name = typeof username === 'string' ? normalizeRecipientUsername(username) : ''; + return /^\w{1,64}$/.test(name) ? { id: null, username: name } : null; +} + +/** The event a create asked for, from its own input (a failed create returns no event). create_event stores the flag as sent. */ +function requestedEvent(fields: object): EventRef | null { + const title: unknown = Reflect.get(fields, 'title'); + if (typeof title !== 'string' || !title.trim()) return null; + const start: unknown = Reflect.get(fields, 'start_at'); + return { + title: title.trim(), + startAt: typeof start === 'string' ? start : null, + allDay: isTrue(Reflect.get(fields, 'all_day')), + }; +} + +/** + * When a successful write put its event: the start its own input carried, nothing else. A create is told + * by the request itself (requestedEvent); an update that restated its start is told by that start, with the + * all-day flag from its input or its confirmed result. Every other write (a delete, a snooze, an update + * without a start) says nothing about the day and time, so its line names the event by title alone. + */ +function timingOf(operation: string, fields: object, result: ToolResult): Timing | null { + const start: unknown = Reflect.get(fields, 'start_at'); + if (operation !== 'update_event' || typeof start !== 'string') return null; + const flag: unknown = Reflect.get(fields, 'all_day'); + const allDay = + extractEventSummaries(result.data)?.[0]?.all_day ?? (flag === undefined || flag === null ? null : isTrue(flag)); + // Whether the start is a day or an instant is unknown without a flag or a summary: name the event by title alone. + return allDay === null ? null : { startAt: start, allDay }; +} + +/** The executor accepts the JSON strings "true"/"false" for a boolean; the ledger reads them the same way. */ +function isTrue(value: unknown): boolean { + return value === true || value === 'true'; +} + +/** + * Reduces an RRULE line to what carries its meaning (RFC 5545 §3.3.10): the part order, the list + * order inside a part, case, spacing, the `RRULE:` prefix and an INTERVAL that only restates the + * default of 1 do not. Other lines of a stored rule (EXDATE, RDATE) are kept as written, uppercased. + */ +function canonicalRuleLine(line: string): string { + const body = line.startsWith('RRULE:') ? line.slice('RRULE:'.length) : line; + if (!/^[A-Z]+=/.test(body)) return line; + return body + .split(';') + .filter((part) => part !== '' && part !== 'INTERVAL=1') + .map((part) => { + const [name = '', ...value] = part.split('='); + return `${name}=${value.join('=').split(',').sort().join(',')}`; + }) + .sort() + .join(';'); +} + +/** The recurrence of a create request in a form equal for equal series, or null for a one-off event. */ +function canonicalRecurrence(rule: unknown): string | null { + if (typeof rule !== 'string') return null; + const lines = rule + .toUpperCase() + .split(/\r?\n/) + .map((line) => line.replace(/\s+/g, '')) + .filter((line) => line !== '') + .map(canonicalRuleLine) + .sort(); + return lines.length > 0 ? lines.join('\n') : null; +} + +/** + * What a create's start or end identifies. A one-off all-day value (`byDay`) is its calendar day as the + * bot itself reads it (the date-only form, T00:00:00Z and the user's local midnight in UTC are one day); + * any other value is its instant (a series expands from its start instant, so its spellings stay + * distinct), and anything that does not parse stays as written. Absent or blank is null. + */ +function momentKey(value: unknown, byDay: boolean, timezone: string): number | string | null { + const text = optionalText(value); + if (text === null) return null; + const ms = Date.parse(text); + if (!Number.isFinite(ms) || !eventTimestampSchema.safeParse(text).success) return text; + return byDay ? (calendarDayOf(text, timezone) ?? ms) : ms; +} + +/** + * The same requested event up to case and spacing of the title, the start instant, the calendar + * (owner and personal/group scope) and its recurrence: a failed group or recurring create is not + * the one-off personal event that later succeeded, so that success must not fold it away. An + * omitted scope means what the chat makes of it, as in the create handler. The end, location and + * description are kept apart: a later success of the event replaces an earlier failure whichever + * of them the corrected retry changed, but a later failure is hidden behind an earlier success only + * when it asked for the same details. + */ +function createKeysOf( + ref: EventRef | null, + owner: number | null, + fields: object, + isGroup: boolean, + timezone: string, +): CreateKeys | null { + if (!ref) return null; + const scope: unknown = Reflect.get(fields, 'scope'); + const recurrence = canonicalRecurrence(Reflect.get(fields, 'recurrence_rule')); + const byDay = ref.allDay && recurrence === null; + const parts: CreateKeyParts = { + title: titleKey(ref.title), + start: momentKey(ref.startAt, byDay, timezone), + allDay: ref.allDay, + owner, + scope: resolveScope({ scope: typeof scope === 'string' ? scope : undefined }, { isGroup }), + recurrence, + }; + const details: CreateDetails = { + end: momentKey(Reflect.get(fields, 'end_at'), byDay, timezone), + location: optionalText(Reflect.get(fields, 'location')), + description: optionalText(Reflect.get(fields, 'description')), + }; + return serializeKeys(parts, details); +} + +/** A create's keys: the fields kept by name, and the strings they are compared by, built from a fixed order. */ +function serializeKeys(parts: CreateKeyParts, details: CreateDetails): CreateKeys { + const { title, start, allDay, owner, scope, recurrence } = parts; + return { + parts, + details, + key: JSON.stringify([title, start, allDay, owner, scope, recurrence]), + detailsKey: JSON.stringify([details.end, details.location, details.description]), + }; +} + +/** Free text as the ledger compares it: trimmed, and empty means absent. */ +function optionalText(value: unknown): string | null { + return typeof value === 'string' && value.trim() !== '' ? value.trim() : null; +} + +/** A title as the create key compares it: spacing and case do not tell two requests apart. */ +function titleKey(title: string): string { + return title.replace(/\s+/g, ' ').trim().toLocaleLowerCase(); } -type WriteOutcomeText = Messages['writeOutcomes']; -/** The receipt line for a write that carries a delivery or attendance effect; null for a plain write. */ -function effectDetail(effect: WriteOutcome['effect'], tr: WriteOutcomeText): string | null { - if (effect?.kind === 'invitation') { - if (effect.delivery === 'delivered') return tr.invitationDelivered; - return effect.delivery === 'manual_forward' ? tr.invitationManual : tr.invitationFailed; +/** + * The end a create stands for after an update: restated, kept while its form is unchanged, or unknown + * (undefined). A moved start does not move a stored end: update_event writes only the fields it is given. + */ +function endAfterUpdate( + kept: number | string | null, + restated: unknown, + keptKind: boolean, + byDay: boolean, + timezone: string, +): number | string | null | undefined { + if (restated !== undefined) return momentKey(restated, byDay, timezone); + return keptKind || kept === null ? kept : undefined; +} + +/** + * What a create stands for once an update has changed the event: the update's own title, start, end, + * location, description, all-day flag and recurrence replace the create's. Null when the event can no + * longer be keyed: a start or end is keyed by its calendar day for a one-off all-day event and by its + * instant otherwise, so when an update flips that form without restating the value, the remembered one + * cannot be re-read in the other form. A title and all-day flag the confirmed result carries win over the input. + */ +function keysAfterUpdate( + keys: CreateKeys, + fields: object, + confirmed: { title: string; all_day: boolean } | undefined, + timezone: string, +): CreateKeys | null { + const { parts: before, details } = keys; + const newTitle: unknown = confirmed?.title ?? Reflect.get(fields, 'title'); + const newAllDay: unknown = confirmed?.all_day ?? Reflect.get(fields, 'all_day'); + const newRule: unknown = Reflect.get(fields, 'recurrence_rule'); + const newStart: unknown = Reflect.get(fields, 'start_at'); + const newEnd: unknown = Reflect.get(fields, 'end_at'); + const allDay = newAllDay === undefined ? before.allDay : isTrue(newAllDay); + const recurrence = newRule === undefined ? before.recurrence : canonicalRecurrence(newRule); + const byDay = allDay && recurrence === null; + const keptKind = byDay === (before.allDay && before.recurrence === null); + const start = + typeof newStart === 'string' ? momentKey(newStart, byDay, timezone) : keptKind ? before.start : undefined; + const end = endAfterUpdate(details.end, newEnd, keptKind, byDay, timezone); + if (start === undefined || end === undefined) return null; + const location: unknown = Reflect.get(fields, 'location'); + const description: unknown = Reflect.get(fields, 'description'); + const parts: CreateKeyParts = { + ...before, + title: typeof newTitle === 'string' ? titleKey(newTitle) : before.title, + start, + allDay, + recurrence, + }; + const asked: CreateDetails = { + end, + location: location === undefined ? details.location : optionalText(location), + description: description === undefined ? details.description : optionalText(description), + }; + return serializeKeys(parts, asked); +} + +/** The calendar day a written all-day start stands for in the user's zone, or null when it cannot be read. */ +function calendarDayOf(start: string, timezone: string): string | null { + try { + return allDayCalendarDate(start, timezone); + } catch { + return null; } - if (effect?.kind === 'attendance_declined') return tr.attendanceDeclined; - return null; } -/** The receipt line for a plain write: status, operation, target, changed field, and why it did not land. */ -function plainDetail(outcome: WriteOutcome, tr: WriteOutcomeText, hideTargets: boolean): string { - const { operation, target, field, success, disposition, mutationState } = outcome; - const label = Object.hasOwn(tr.operations, operation) ? Reflect.get(tr.operations, operation) : tr.write; - const fieldLabel = field ? ` (${Object.hasOwn(tr.fields, field) ? Reflect.get(tr.fields, field) : tr.field})` : ''; - const status = success ? tr.completed : mutationState === 'uncertain' ? tr.uncertain : tr.notCompleted; - const reason = disposition === 'skipped' ? tr.skipped : mutationState === 'not_applied' ? tr.notApplied : tr.failed; - return `${status}: ${label}${!hideTargets && target ? ` ${target}` : ''}${fieldLabel}${success ? '' : ` — ${reason}`}`; + +/** A recorded create of this event that still has keys to fold a later attempt into. */ +function isCreateOf(outcome: WriteOutcome, eventId: number): outcome is WriteOutcome & { create: CreateKeys } { + return outcome.operation === 'create_event' && outcome.eventId === eventId && outcome.create !== null; +} + +/** Whether `repeat` is the same failure as `told`: a create with the same details that ended the same way (skipped, refused or unknown). */ +function repeatsFailure(told: WriteOutcome, repeat: WriteOutcome): boolean { + const standing = (o: WriteOutcome) => + o.disposition === 'skipped' ? 'skipped' : endedUnknown(o) ? 'unknown' : 'refused'; + return !told.success && told.create?.detailsKey === repeat.create?.detailsKey && standing(told) === standing(repeat); +} + +/** Whether an invitation write succeeded and reached the person (not merely created, or failed). */ +function reached(outcome: WriteOutcome): boolean { + return outcome.success && !(outcome.effect?.kind === 'invitation' && outcome.effect.delivery !== 'delivered'); +} + +/** A write that failed and may still have happened, or whose result was never known. */ +function endedUnknown(outcome: WriteOutcome): boolean { + return !outcome.success && outcome.disposition !== 'skipped' && outcome.mutationState !== 'not_applied'; } export class WriteOutcomes { private readonly outcomes = new Map(); + /** Every event this run's successful results carried, so a later write can be named by its title and calendar. */ + private readonly events = new Map(); private attempts = 0; mayHaveMutated = false; /** A rendered image reached the chat. */ @@ -100,28 +328,168 @@ export class WriteOutcomes { constructor(private readonly writes: ReadonlySet = new Set(Object.keys(targets))) {} - record(operation: string, input: unknown, result: ToolResult & { disposition: ExecutorDisposition }): void { - this.noteTurnEffects(operation, result); - if (!this.writes.has(operation) || !isMutationTool(operation, input) || result.disposition === 'waiting') return; + /** `isGroup`: whether the chat is a group, which decides the scope of a create that names none. */ + record( + operation: string, + input: unknown, + result: ToolResult & { disposition: ExecutorDisposition }, + isGroup = false, + timezone = 'UTC', + ): void { const fields = typeof input === 'object' && input !== null ? input : {}; + const isWrite = this.writes.has(operation) && isMutationTool(operation, input); + this.noteTurnEffects(operation, result); + this.noteEvents(fields, result); + if (!isWrite || result.disposition === 'waiting') return; + const success = result.disposition === 'executed' && result.success; + const owner = positiveId(Reflect.get(fields, 'owner_id')); + const requested = operation === 'create_event' ? requestedEvent(fields) : null; const attempt = ++this.attempts; const identity = attemptIdentity(operation, fields, attempt); - const target = targetLabel(fields); - const requested = requestedUpdateFields(operation, fields); - for (const field of requested.length ? requested : [undefined]) { - const key = JSON.stringify([operation, identity, field]); - if (result.disposition === 'skipped' && this.outcomes.has(key)) continue; - this.outcomes.set(key, { - operation, - target, - field, - attempt, - success: result.disposition === 'executed' && result.success, - disposition: result.disposition, - mutationState: result.mutationState, - effect: result.effect, + const outcome: WriteOutcome = { + operation, + eventId: this.eventIdOf(operation, fields, result, success), + requested, + timing: success ? timingOf(operation, fields, result) : null, + owner, + invitee: operation === 'send_invitation' ? inviteeOf(fields) : null, + success, + disposition: result.disposition, + mutationState: result.mutationState, + effect: result.effect, + unknownRetried: false, + repeatUnknown: [], + create: createKeysOf(requested, owner, fields, isGroup, timezone), + }; + const unknown = endedUnknown(outcome); + if (success || unknown) this.updateCreatesOfEvent(operation, fields, result, outcome.eventId, timezone, unknown); + if (this.foldCreateAttempt(outcome)) return; + this.storeByField(outcome, identity, requestedUpdateFields(operation, fields)); + } + + /** + * A create whose event was deleted or snoozed no longer stands for that event, and neither does one + * whose update result is unknown and may have changed it: a later failed create of the same request + * is a new attempt and must stay visible, not be folded into it. A successful update rewrites what the + * create stands for (see keysAfterUpdate), so a later failure that asks for exactly what the event now + * is stays folded, and a rejected earlier one that asked for it is settled. + */ + private updateCreatesOfEvent( + operation: string, + fields: object, + result: ToolResult, + eventId: number | null, + timezone: string, + unknown: boolean, + ): void { + if (eventId === null) return; + const deleted = operation === 'delete_event' && (result.effect?.kind === 'event_deleted' || unknown); + const moved = operation === 'snooze_event'; + if (!deleted && !moved && operation !== 'update_event') return; + const confirmed = extractEventSummaries(result.data)?.find((event) => event.id === eventId); + for (const outcome of this.outcomes.values()) { + if (!isCreateOf(outcome, eventId)) continue; + const after = deleted || moved ? null : keysAfterUpdate(outcome.create, fields, confirmed, timezone); + this.reconcileCreate(outcome, outcome.create, after, unknown); + } + } + + /** Sets what a create stands for after a write to its event; an unknown result can only retire it, never rewrite it. */ + private reconcileCreate(outcome: WriteOutcome, before: CreateKeys, after: CreateKeys | null, unknown: boolean): void { + if (unknown) { + const changed = after === null || after.key !== before.key || after.detailsKey !== before.detailsKey; + if (changed) outcome.create = null; + return; + } + outcome.create = after; + if (after !== null) this.settleRejectedCreates(after); + } + + /** A create that was refused and asked for exactly what an event now is no longer needs telling. */ + private settleRejectedCreates({ key, detailsKey }: CreateKeys): void { + for (const [id, outcome] of this.outcomes) { + const refused = !outcome.success && !endedUnknown(outcome); + if (refused && outcome.create?.key === key && outcome.create.detailsKey === detailsKey) this.outcomes.delete(id); + } + } + + /** Keeps the outcome once per written field; a skipped repeat of a recorded write adds nothing. */ + private storeByField(outcome: WriteOutcome, identity: number | unknown[], requestedFields: string[]): void { + if (outcome.operation === 'send_invitation') { + this.storeInvitation(outcome, identity); + return; + } + for (const field of requestedFields.length ? requestedFields : [undefined]) { + const key = JSON.stringify([outcome.operation, identity, field]); + if (outcome.disposition === 'skipped' && this.outcomes.has(key)) continue; + this.outcomes.set(key, { ...outcome, field }); + } + } + + /** + * An invitation to one person keeps two places: what was delivered, and the latest failure. A later failure + * never erases a delivery, and a refusal never erases an attempt that may have gone through; a delivery clears + * the failure it follows (an unknown one leaves the duplicate warning). + */ + private storeInvitation(outcome: WriteOutcome, identity: number | unknown[]): void { + const deliveredKey = JSON.stringify([outcome.operation, identity, 'delivered']); + const failedKey = JSON.stringify([outcome.operation, identity, 'failed']); + const delivered = this.outcomes.get(deliveredKey); + const failed = this.outcomes.get(failedKey); + if (outcome.disposition === 'skipped' && (delivered || failed)) return; + // The attempt that may have gone through before this one makes this one a possible duplicate. + const priorUnknown = failed !== undefined && (endedUnknown(failed) || failed.unknownRetried); + // A success that did not reach the person is told beside a delivery, never over it. + const overDelivery = delivered !== undefined && reached(delivered) && !reached(outcome); + if (outcome.success && !overDelivery) { + this.outcomes.delete(failedKey); + this.outcomes.set(deliveredKey, { + ...outcome, + unknownRetried: outcome.unknownRetried || delivered?.unknownRetried === true || priorUnknown, }); + return; + } + // Only a refusal yields to what is stored: an attempt that may have gone through, or created an invitation. + const refusal = !outcome.success && !endedUnknown(outcome); + if (failed && refusal && (failed.success || endedUnknown(failed))) return; + this.outcomes.set(failedKey, { + ...outcome, + unknownRetried: outcome.unknownRetried || (outcome.success && priorUnknown), + }); + } + + /** The id of the event a successful create returned. */ + private createdEventId(operation: string, result: ToolResult): number | null { + return operation === 'create_event' ? (extractEventSummaries(result.data)?.[0]?.id ?? null) : null; + } + + /** + * A create has no target to match a retry by, so the same requested event decides. A later + * success replaces the failures of that event (an unknown one leaves a duplicate warning); a later + * failed or skipped try at an event that already exists, asking for the same details, adds nothing, + * unless its result is unknown, when the existing one may now be there twice (a separate warning: + * here the repeat is the unknown one). Returns true when the attempt is folded away. + */ + private foldCreateAttempt(attempt: WriteOutcome): boolean { + if (attempt.create === null) return false; + const { key, detailsKey } = attempt.create; + const same = [...this.outcomes].filter(([, outcome]) => outcome.create?.key === key); + if (!attempt.success) { + const settled = same.find(([, outcome]) => outcome.success && outcome.create?.detailsKey === detailsKey)?.[1]; + // Next to a success that asked for other details, an identical failure already told is not told again. + if (!settled) { + return same.some(([, o]) => o.success) && same.some(([, outcome]) => repeatsFailure(outcome, attempt)); + } + if (endedUnknown(attempt) && attempt.requested) + settled.repeatUnknown = [...settled.repeatUnknown, attempt.requested]; + return true; } + for (const [id, earlier] of same) { + if (earlier.success) continue; + this.outcomes.delete(id); + if (endedUnknown(earlier)) attempt.unknownRetried = true; + } + return false; } /** Run-wide flags a tool result sets whether or not it is a recorded write: speech question, mutation, delivery. */ @@ -135,36 +503,45 @@ export class WriteOutcomes { } else if (SILENT_TOOLS.has(operation) && sent) this.reacted = true; } - finalNotice(language: string, hideTargets = false, interrupted = false): string | null { + /** A create is named by the event it returned: an extra event_id in its input is not that event. */ + private eventIdOf(operation: string, fields: object, result: ToolResult, success: boolean): number | null { + if (operation !== 'create_event') return positiveId(Reflect.get(fields, 'event_id')); + return success ? this.createdEventId(operation, result) : null; + } + + /** + * Remembers the title and calendar of every event a successful result carried, read or written, so a + * later write can be named. Never a day or time: those come only from a write's own input (see timingOf), + * because a read lists occurrences, first starts and shifted all-day dates that are not what a write did. + */ + private noteEvents(input: object, result: ToolResult & { disposition: ExecutorDisposition }): void { + if (result.disposition !== 'executed' || !result.success) return; + const named = positiveId(Reflect.get(input, 'owner_id')); + for (const event of extractEventSummaries(result.data) ?? []) { + this.events.set(event.id, { title: event.title, owner: named ?? this.events.get(event.id)?.owner ?? null }); + } + } + + /** + * The receipt that replaces the model's text, or null when its text may stand: nothing failed, + * was skipped, left unconfirmed, declined or went undelivered. A failure a later write of the + * same target fixed is no longer in the ledger. + */ + finalNotice(view: ReceiptView, interrupted = false): string | null { const needsGuard = [...this.outcomes.values()].some( (outcome) => !outcome.success || + outcome.unknownRetried || + outcome.repeatUnknown.length > 0 || outcome.effect?.kind === 'attendance_declined' || (outcome.effect?.kind === 'invitation' && outcome.effect.delivery !== 'delivered'), ); if (!interrupted && !needsGuard) return null; - return this.describe(language, hideTargets, interrupted); + return renderReceipt([...this.outcomes.values()], this.events, view, interrupted); } /** Every recorded write, clean successes included — for a turn the model left without an answer. */ - summary(language: string, hideTargets: boolean): string | null { - return this.describe(language, hideTargets, false); - } - - private describe(language: string, hideTargets: boolean, interrupted: boolean): string | null { - const outcomes = [...this.outcomes.values()]; - // Attempt framing is useful only when something actually failed/skipped and - // a later receipt may correct it. On a clean success (including an - // interrupted run where writes already landed) it reads like internal debug - // output and replaced the normal conversational answer in production. - const frameAttempts = outcomes.some((outcome) => !outcome.success || outcome.disposition === 'skipped'); - const tr = t(toLang(language)).writeOutcomes; - const lines = outcomes.map((outcome) => { - const detail = effectDetail(outcome.effect, tr) ?? plainDetail(outcome, tr, hideTargets); - return frameAttempts ? `${tr.attempt(outcome.attempt)}: ${detail}` : detail; - }); - if (frameAttempts && outcomes.length) lines.unshift(tr.attempts); - if (interrupted) lines.push(tr.interrupted); - return lines.join('\n') || null; + summary(view: ReceiptView): string | null { + return renderReceipt([...this.outcomes.values()], this.events, view, false); } } diff --git a/src/services/ai/write-receipt.ts b/src/services/ai/write-receipt.ts new file mode 100644 index 00000000..4b72a488 --- /dev/null +++ b/src/services/ai/write-receipt.ts @@ -0,0 +1,496 @@ +/** + * The receipt shown instead of the model's own text when a run had failed, skipped or unconfirmed + * writes. It reads like an answer, not a ledger: what was done and to which event (title, local + * time, whose calendar), what was not, for whom, and the one safe next step. + * + * Invariants: + * - No raw ids, attempt counters or internal wording; an event or person that cannot be named is + * counted ("3 people"), never shown by id. + * - Group chats hide every target: no title, time, calendar or name. + * - A person is named only when the requester may see that name (their own contact, themselves, or + * the @username they typed); an id the model supplied never resolves to someone else's profile. + * - An unknown result is told apart from a rejection: after a rejection nothing changed, after an + * unknown result the calendar has to be checked before anything is repeated. + */ +import { TZDate } from '@date-fns/tz'; +import { type Messages, t, toLang } from '../../config/constants.ts'; +import { allDayCalendarDate, describeCalendarDay } from '../../utils/date.ts'; +import { eventTimestampSchema } from '../../utils/event-timestamps.ts'; +import { localToday } from './day-references.ts'; +import { DAY_MS, relativeDayWord } from './empty-agenda.ts'; +import type { AgentContext, ToolResult } from './types.ts'; + +/** When a write put its event: the raw start its own input carried (never a read), and whether it is all-day. */ +export interface Timing { + startAt: string | null; + allDay: boolean; +} +/** The event a write was about, by title and the timing that write itself carried. */ +export interface EventRef extends Timing { + title: string; +} +/** An event the run has seen (in a read or a write), by title and the calendar a call named for it. */ +export interface KnownEvent { + title: string; + owner: number | null; +} +export interface Invitee { + id: number | null; + username: string | null; +} +export interface WriteOutcome { + operation: string; + eventId: number | null; + /** What a create asked for: a failed create returns no event. */ + requested: EventRef | null; + /** When a successful update that restated its start put the event; null for every other write. */ + timing: Timing | null; + /** The calendar owner the call named (`owner_id`), when it named one. */ + owner: number | null; + invitee: Invitee | null; + field?: string; + success: boolean; + disposition: 'executed' | 'failed' | 'skipped' | 'waiting'; + mutationState?: ToolResult['mutationState']; + effect?: ToolResult['effect']; + /** An earlier try at this same write ended unknown: this success may have been written twice. */ + unknownRetried: boolean; + /** Later repeats of this successful create that ended unknown (what each asked for): the event may now exist twice. */ + repeatUnknown: readonly EventRef[]; + /** For a create: the event's identity (normalized title, start, calendar, recurrence) and the details it asked for. Null for any other write. */ + create: CreateKeys | null; +} + +/** What identifies a create, by name. */ +export interface CreateKeyParts { + title: string; + start: number | string | null; + allDay: boolean; + owner: number | null; + scope: string; + recurrence: string | null; +} + +/** + * What else a create asked for; a later success of the same event settles a failure whatever these were. + * Reminders and the location type (`location_abstract`) are deliberately not compared (tracked in #922). + */ +export interface CreateDetails { + end: number | string | null; + location: string | null; + description: string | null; +} + +/** A create as the ledger keys it: the identity of the event and the details it asked for, and the strings they are compared by. */ +export interface CreateKeys { + parts: CreateKeyParts; + details: CreateDetails; + key: string; + detailsKey: string; +} + +/** + * The create fields (recurrence, all-day, end, location, description) a refused or unconfirmed create + * asked for differently from a success of the same title and start, by field name, so its line cannot read + * as a contradiction of the success. Told against the closest such success: the one differing in the fewest. + */ +function differingFields(outcome: WriteOutcome, outcomes: readonly WriteOutcome[]): string[] { + const asked = outcome.create; + if (outcome.success || !asked) return []; + const start = Date.parse(outcome.requested?.startAt ?? ''); + let closest: string[] | null = null; + for (const made of outcomes) { + if (!made.success || !made.create || !sameEvent(made, made.create, asked, start)) continue; + const differing = differingBetween(made.create, asked); + if (closest === null || differing.length < closest.length) closest = differing; + } + return closest ?? []; +} + +/** A success of the same title, in the same calendar, at the same start (as keyed, or as first requested). */ +function sameEvent(made: WriteOutcome, had: CreateKeys, asked: CreateKeys, askedStart: number): boolean { + const sameCalendar = had.parts.owner === asked.parts.owner && had.parts.scope === asked.parts.scope; + if (!sameCalendar || had.parts.title !== asked.parts.title) return false; + return had.parts.start === asked.parts.start || Date.parse(made.requested?.startAt ?? '') === askedStart; +} + +/** The create fields two requests for one event disagree on, by field name. */ +function differingBetween(had: CreateKeys, asked: CreateKeys): string[] { + const names: [string, boolean][] = [ + ['recurrence_rule', had.parts.recurrence !== asked.parts.recurrence], + ['all_day', had.parts.allDay !== asked.parts.allDay], + ['end_at', had.details.end !== asked.details.end], + ['location', had.details.location !== asked.details.location], + ['description', had.details.description !== asked.details.description], + ]; + return names.filter(([, differs]) => differs).map(([name]) => name); +} + +/** What the receipt needs from the run's context; built by `receiptView`. */ +export interface ReceiptView { + language: string; + timezone: string; + hideTargets: boolean; + requesterId: number; + now: Date; + /** A name the requester may be shown for this person, or null. Already inert (see `inert`). */ + personLabel: (person: Invitee) => string | null; + /** One key per real person: a contact named by @username (any case) and by id is the same person. */ + personKey: (person: Invitee) => string; + /** The name of a calendar the requester manages as an active secretary, or null. Already inert. */ + calendarOwnerName: (ownerId: number) => string | null; + /** Whether the requester holds an active secretary delegation for this calendar. */ + hasCalendarAccess: (ownerId: number) => boolean; +} + +/** + * Text the model or another user wrote, made safe for the one renderer the receipt goes through + * (TelegramStreamWriter -> markdownToHtml). That renderer already HTML-escapes `<`, `>` and `&`, so + * escaping them here would show "&"; it has no way to escape `*`, `_` and backticks, so a + * title like "_a **b_ c**" would come out as overlapping tags that Telegram rejects, and the + * receipt would never arrive. Those characters become look-alikes, and line breaks collapse so + * a title cannot pass itself off as another receipt line. + */ +function inert(text: string): string { + return text.replace(/\s+/g, ' ').trim().replace(/\*/g, '∗').replace(/_/g, '_').replace(/`/g, 'ˋ'); +} + +function cleanName(value: string | null | undefined): string | null { + const name = value ? [...inert(value)].slice(0, 40).join('') : ''; + return name || null; +} + +/** + * A username is only `\w` characters, so an underscore inside it can neither open nor close + * emphasis; only a leading or trailing run can, and those are the ones swapped. + */ +function inertUsername(username: string): string { + return username.replace(/^_+|_+$/g, (run) => '_'.repeat(run.length)); +} + +export function receiptView(ctx: AgentContext): ReceiptView { + const requesterId = ctx.user.telegram_id; + const hasCalendarAccess = (ownerId: number): boolean => + ctx.secretary?.secretaryRepo.findByOwnerAndSecretary(ownerId, requesterId)?.status === 'active'; + return { + language: ctx.user.language, + timezone: ctx.user.timezone, + hideTargets: ctx.isGroup, + requesterId, + now: new Date(), + personKey: ({ id, username }) => { + if (id !== null) return `id:${id}`; + const contactId = username === null ? null : ctx.contactRepo?.findByUsername(requesterId, username)?.telegram_id; + return contactId ? `id:${contactId}` : `@${(username ?? '').toLowerCase()}`; + }, + personLabel: ({ id, username }) => { + if (id !== null) { + if (id === requesterId) return cleanName(ctx.user.first_name); + return cleanName(ctx.contactRepo?.findByTelegramId(requesterId, id)?.name); + } + if (username === null) return null; + const contact = ctx.contactRepo?.findByUsername(requesterId, username); + return cleanName(contact?.name) ?? `@${inertUsername(username)}`; + }, + hasCalendarAccess, + calendarOwnerName: (ownerId) => + hasCalendarAccess(ownerId) ? cleanName(ctx.userRepo.findByTelegramId(ownerId)?.first_name) : null, + }; +} + +type Tr = Messages['writeOutcomes']; +type Standing = 'done' | 'rejected' | 'unknown' | 'skipped'; +type InviteStanding = 'sent' | 'created' | 'manual' | 'undelivered' | 'rejected' | 'unknown' | 'skipped'; +const INVITE_ORDER: readonly InviteStanding[] = [ + 'sent', + 'created', + 'manual', + 'undelivered', + 'rejected', + 'unknown', + 'skipped', +]; +type EventOperation = keyof Tr['operations']; + +function isEventOperation(operation: string): operation is EventOperation { + return Object.hasOwn(t('en').writeOutcomes.operations, operation); +} + +function standingOf(outcome: WriteOutcome): Standing { + if (outcome.disposition === 'skipped') return 'skipped'; + if (outcome.success) return 'done'; + return outcome.mutationState === 'not_applied' ? 'rejected' : 'unknown'; +} + +function inviteStandingOf(outcome: WriteOutcome): InviteStanding { + const standing = standingOf(outcome); + if (standing !== 'done') return standing; + if (outcome.effect?.kind !== 'invitation') return 'created'; + if (outcome.effect.delivery === 'delivered') return 'sent'; + return outcome.effect.delivery === 'manual_forward' ? 'manual' : 'undelivered'; +} + +const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/; +const CLOCK_TIME = /^\d{2}:\d{2}$/; + +/** A real calendar date in `YYYY-MM-DD` form: "2030-02-31" and "01/01/2030" are not. */ +function isIsoDay(day: string): boolean { + const ms = Date.parse(`${day}T00:00:00Z`); + return ISO_DAY.test(day) && Number.isFinite(ms) && new Date(ms).toISOString().startsWith(day); +} + +/** The event's local day and time, read from the raw start its own write carried. */ +function localDayTime(ref: Timing, timezone: string): { day: string | null; time: string | null } { + if (ref.startAt === null) return { day: null, time: null }; + // The tool contract: a real ISO date, or a datetime with Z or an offset. Anything else has no readable day. + const ms = Date.parse(ref.startAt); + if (!Number.isFinite(ms) || !eventTimestampSchema.safeParse(ref.startAt).success) return { day: null, time: null }; + if (ref.allDay) return { day: allDayCalendarDate(ref.startAt, timezone), time: null }; + const local = new TZDate(ms, timezone); + const pad = (value: number) => String(value).padStart(2, '0'); + return { + day: `${local.getFullYear()}-${pad(local.getMonth() + 1)}-${pad(local.getDate())}`, + time: `${pad(local.getHours())}:${pad(local.getMinutes())}`, + }; +} + +/** "today, 17:00" / "1 November, 09:00" / "tomorrow", from the event's local day and time. */ +function describeWhen(ref: Timing, view: ReceiptView): string | null { + const { day, time } = localDayTime(ref, view.timezone); + if (day === null || !isIsoDay(day)) return null; + const lang = toLang(view.language); + const delta = Math.round( + (Date.parse(`${day}T00:00:00Z`) - Date.parse(`${localToday(view.now, view.timezone).today}T00:00:00Z`)) / DAY_MS, + ); + const dayText = + relativeDayWord(t(lang).aiTools.events.emptyAgenda.relativeDay, delta) ?? describeCalendarDay(day, lang).day; + return time !== null && CLOCK_TIME.test(time) ? `${dayText}, ${time}` : dayText; +} + +/** + * The receipt is the only thing the user reads when the guard fires, and its date comes from a + * model-supplied string and a stored timezone: a bad one costs the receipt its day and time, + * never the receipt (an invalid zone makes TZDate and Intl throw RangeError). + */ +function whenOf(ref: Timing, view: ReceiptView): string | null { + try { + return describeWhen(ref, view); + } catch { + return null; + } +} + +interface PlainLine { + base: string; + reason: string | null; + fields: string[]; +} +interface InviteGroup { + event: EventRef | null; + byStanding: Map; +} +type Entry = + | { kind: 'plain'; line: PlainLine } + | { kind: 'text'; text: string } + | { kind: 'invites'; group: InviteGroup }; + +/** The distinct people of one receipt line: how many, and who is named (the rest, and a second person with an already shown name, are only counted). */ +function describePeople(people: readonly Invitee[], view: ReceiptView, tr: Tr): { count: number; text: string } { + const seen = new Set(); + const names: string[] = []; + let unnamed = 0; + for (const person of people) { + const key = view.personKey(person); + if (seen.has(key)) continue; + seen.add(key); + const label = view.hideTargets ? null : view.personLabel(person); + if (!label) unnamed++; + else if (names.includes(label)) unnamed++; + else names.push(label); + } + return { count: seen.size, text: tr.people(names, unnamed) }; +} + +interface Draft { + entries: Entry[]; + plain: Map; + groups: Map; +} + +/** ", " when the write went to someone else's calendar, otherwise nothing. */ +function calendarSuffix( + outcome: WriteOutcome, + events: ReadonlyMap, + view: ReceiptView, + tr: Tr, +): string { + const owner = outcome.owner ?? (outcome.eventId !== null ? (events.get(outcome.eventId)?.owner ?? null) : null); + if (view.hideTargets || owner === null || owner === view.requesterId) return ''; + const name = view.calendarOwnerName(owner); + // Never state an access the requester does not hold (denied, revoked, expired, or an invented id). + const unnamed = view.hasCalendarAccess(owner) ? tr.delegatedCalendar : tr.otherCalendar; + return `, ${name ? tr.calendarOf(name) : unnamed}`; +} + +/** Invitations to one event are told together: the person joins the event's group under their outcome. */ +function addInvitation(draft: Draft, outcome: WriteOutcome, invitee: Invitee, ref: EventRef | null): void { + const groupKey = String(outcome.eventId); + let group = draft.groups.get(groupKey); + if (!group) { + group = { event: ref, byStanding: new Map() }; + draft.groups.set(groupKey, group); + draft.entries.push({ kind: 'invites', group }); + } + const inviteStanding = inviteStandingOf(outcome); + group.byStanding.set(inviteStanding, [...(group.byStanding.get(inviteStanding) ?? []), invitee]); +} + +/** + * The sentence for a successful write whose result is a side effect, not an event change: what + * reached an invitee (a resend, or a name that could not be read), or a declined attendance. + * Null for every other outcome. + */ +function effectText(outcome: WriteOutcome, ref: EventRef | null, tr: Tr): string | null { + if (!outcome.success) return null; + if (outcome.effect?.kind === 'invitation') { + return { + delivered: tr.invitationDelivered, + manual_forward: tr.invitationManual, + failed: tr.invitationFailed, + }[outcome.effect.delivery]; + } + return outcome.effect?.kind === 'attendance_declined' ? tr.attendanceDeclined(ref?.title ?? null) : null; +} + +/** The sentence for one write to an event and, when it did not go through, why. */ +function plainLineOf( + outcome: WriteOutcome, + ref: EventRef | null, + calendar: string, + view: ReceiptView, + tr: Tr, +): { base: string; reason: string | null } { + const standing = standingOf(outcome); + const labels = isEventOperation(outcome.operation) ? tr.operations[outcome.operation] : tr.otherWrite; + const prefix = standing === 'done' ? labels.done : standing === 'unknown' ? labels.unknown : labels.notDone; + const when = ref ? whenOf(ref, view) : null; + const subject = isEventOperation(outcome.operation) ? (ref ? tr.eventNamed(ref.title, when) : tr.anEvent) : tr.change; + const reason = standing === 'rejected' ? tr.nothingChanged : standing === 'skipped' ? tr.skipped : null; + return { base: `${prefix}: ${subject}${calendar}`, reason }; +} + +/** One line for a write to an event; the per-field lines of one event fold into one. */ +function addPlainLine( + draft: Draft, + outcome: WriteOutcome, + text: { base: string; reason: string | null }, + tr: Tr, + details: readonly string[], +): void { + const { base, reason } = text; + // Only the per-field lines of one event fold into one; two writes to unnamed events stay two. + const key = outcome.field ? `${outcome.eventId}\u0000${base}\u0000${reason}` : null; + let line = key ? draft.plain.get(key) : undefined; + if (!line) { + line = { base, reason, fields: [] }; + if (key) draft.plain.set(key, line); + draft.entries.push({ kind: 'plain', line }); + } + for (const name of outcome.field ? [outcome.field, ...details] : details) { + const label = Object.hasOwn(tr.fields, name) ? Reflect.get(tr.fields, name) : tr.field; + if (!line.fields.includes(label)) line.fields.push(label); + } +} + +/** The event a write was about, with its title made inert; null where targets are hidden or nothing names it. Its timing is only what that write carried. */ +function refOf(outcome: WriteOutcome, events: ReadonlyMap, view: ReceiptView): EventRef | null { + const title = outcome.requested?.title ?? (outcome.eventId !== null ? events.get(outcome.eventId)?.title : undefined); + const timing = outcome.requested ?? outcome.timing ?? { startAt: null, allDay: false }; + return inertRef(title === undefined ? null : { ...timing, title }, view); +} + +/** Every title in the receipt passes through here: it is the model's text or the user's, never ours. */ +function inertRef(named: EventRef | null, view: ReceiptView): EventRef | null { + return view.hideTargets || !named ? null : { ...named, title: inert(named.title) }; +} + +/** Files one recorded write under the kind of line it is told as: an invitation, a side effect or an event change. */ +function addOutcome( + draft: Draft, + outcome: WriteOutcome, + events: ReadonlyMap, + view: ReceiptView, + tr: Tr, + outcomes: readonly WriteOutcome[], +): void { + const ref = refOf(outcome, events, view); + if (outcome.operation === 'send_invitation' && outcome.invitee) { + addInvitation(draft, outcome, outcome.invitee, ref); + return; + } + const text = effectText(outcome, ref, tr); + if (text === null) { + const line = plainLineOf(outcome, ref, calendarSuffix(outcome, events, view, tr), view, tr); + addPlainLine(draft, outcome, line, tr, differingFields(outcome, outcomes)); + return; + } + // Two resends reporting the same delivery are one sentence; a declined attendance is told each time. + const repeated = draft.entries.some((entry) => entry.kind === 'text' && entry.text === text); + if (outcome.effect?.kind !== 'invitation' || !repeated) draft.entries.push({ kind: 'text', text }); +} + +function renderEntry(entry: Entry, view: ReceiptView, tr: Tr): string[] { + if (entry.kind === 'text') return [entry.text]; + if (entry.kind === 'plain') { + const { base, fields, reason } = entry.line; + return [`${base}${fields.length ? tr.changedFields(fields) : ''}${reason ? ` — ${reason}` : ''}.`]; + } + const { event, byStanding } = entry.group; + const named = event ? tr.eventTitle(event.title) : tr.theEvent; + return INVITE_ORDER.flatMap((standing) => { + const people = byStanding.get(standing); + if (!people) return []; + const { count, text } = describePeople(people, view, tr); + return [tr.invitations[standing](count, named, text)]; + }); +} + +/** + * The receipt for every recorded write, in the order the targets first appeared; null when there + * is nothing to say. Invitations to one event are told together, one line per outcome. + */ +export function renderReceipt( + outcomes: readonly WriteOutcome[], + events: ReadonlyMap, + view: ReceiptView, + interrupted: boolean, +): string | null { + const tr = t(toLang(view.language)).writeOutcomes; + const draft: Draft = { entries: [], plain: new Map(), groups: new Map() }; + const standings = outcomes.map(standingOf); + const unknown = standings.includes('unknown'); + const rejected = standings.includes('rejected'); + const duplicateRisk = outcomes.some((outcome) => outcome.unknownRetried); + + for (const outcome of outcomes) addOutcome(draft, outcome, events, view, tr, outcomes); + + const lines = draft.entries.flatMap((entry) => renderEntry(entry, view, tr)); + if (duplicateRisk) lines.push(tr.retriedAfterUnknown); + const repeats = new Set(); + for (const outcome of outcomes) { + for (const repeated of outcome.repeatUnknown) { + const ref = inertRef(repeated, view); + const event = ref + ? `${tr.eventNamed(ref.title, whenOf(ref, view))}${calendarSuffix(outcome, events, view, tr)}` + : null; + repeats.add(tr.repeatUnknown(event)); + } + } + lines.push(...repeats); + + // A possible duplicate is also a reason to check the calendar before repeating a refused write. + if (unknown || (rejected && (duplicateRisk || repeats.size > 0))) lines.push(tr.checkFirst); + else if (rejected) lines.push(tr.retry); + if (interrupted) lines.push(tr.interrupted); + return lines.join('\n') || null; +} diff --git a/src/utils/date.ts b/src/utils/date.ts index 742b41de..e16fe7ff 100644 --- a/src/utils/date.ts +++ b/src/utils/date.ts @@ -50,7 +50,7 @@ const LOCAL_DAY = 'EEE yyyy-MM-dd'; * converted to UTC (the model resolves local dates to UTC, e.g. Belgrade Mon 28 → 27T22:00Z), so it * is read on the user's wall clock. */ -function allDayCalendarDate(value: string, timezone: string): string { +export function allDayCalendarDate(value: string, timezone: string): string { const ms = Date.parse(value); if (ms % 86_400_000 === 0) return new Date(ms).toISOString().slice(0, 10); return format(new TZDate(ms, timezone), 'yyyy-MM-dd'); diff --git a/test/bot/handlers/ai-button-answers.test.ts b/test/bot/handlers/ai-button-answers.test.ts new file mode 100644 index 00000000..67a12878 --- /dev/null +++ b/test/bot/handlers/ai-button-answers.test.ts @@ -0,0 +1,364 @@ +// ask_user answers of any length: the real sender builds the keyboard on a Telegram that refuses +// callback_data over 64 bytes, and the real tap handler turns each tap back into the exact option +// text. A 45-character option (87 bytes with its prefix, the synthetic "Создать у меня и пригласить +// Ольгу, Сэма, Кима") made the whole question undeliverable (BUTTON_DATA_INVALID). + +import { describe, expect, mock, test } from 'bun:test'; +import { InlineKeyboardMarkup, type TelegramInlineKeyboardMarkup } from 'gramio'; +import type { CallbackHandlerOpts } from '../../../src/bot/handlers/callback/types.ts'; +import { t } from '../../../src/config/constants.ts'; +import { cyrillicOption, fakeTelegram } from '../../helpers/ask-user-keyboard.ts'; +import { makeCallbackHandler, makeCallbackTap } from '../../helpers/callback-handler.ts'; + +const ASKER = 2002; +const OTHER_MEMBER = 3001; +const GROUP_CHAT = -100200; +const QUESTION = 'Как поступить?'; +const INCIDENT_OPTIONS = ['Создать у меня и пригласить Ольгу, Сэма, Кима', 'Оставить только у Ольги', 'Отмена']; + +type ButtonClick = NonNullable; + +interface TapSetting { + by?: number; + group?: boolean; + /** Telegram's id of the tapped message. Each tap is a message of its own unless it names one: the answered-message memory is shared by every handler, so tests must not collide on ids. */ + messageId?: number; + /** The text of the tapped message as Telegram returns it; an answered question ends in "✅ answer". */ + text?: string; + /** The inline keyboard the tapped message still carries; absent once it was answered or is too old to be readable. */ + keyboard?: TelegramInlineKeyboardMarkup; +} + +let lastMessageId = 1000; +function nextMessageId(): number { + lastMessageId += 1; + return lastMessageId; +} + +function tap( + data: string, + { by = ASKER, group = false, text = QUESTION, keyboard, messageId = nextMessageId() }: TapSetting = {}, +) { + const { ctx, answer, editText } = makeCallbackTap(data, { telegram_id: by, language: 'ru' }); + const chatId = group ? GROUP_CHAT : by; + Object.assign(ctx, { + chatId, + from: { id: by }, + message: { + id: messageId, + text, + chat: { id: chatId, type: group ? 'supergroup' : 'private' }, + replyMarkup: keyboard && new InlineKeyboardMarkup(keyboard), + }, + }); + return { ctx, answer, editText }; +} + +/** Asks `options` with the real sender and returns the keyboard the chat now shows. */ +async function ask(options: string[], group: boolean): Promise { + const { sender, sent } = fakeTelegram(); + await sender.sendButtons!(group ? GROUP_CHAT : ASKER, QUESTION, options, 'HTML', group ? ASKER : undefined); + return sent[0]!; +} + +function dataOfButton(keyboard: TelegramInlineKeyboardMarkup, index: number): string { + return keyboard.inline_keyboard.flat()[index]!.callback_data!; +} + +function setup() { + const onAiButtonClick = mock(() => Promise.resolve()); + return { onAiButtonClick, handler: makeCallbackHandler({ onAiButtonClick }) }; +} + +describe('an ask_user option of any length reaches the AI unchanged', () => { + for (const group of [false, true]) { + for (const length of [20, 30, 60, 200]) { + test(`${length} Cyrillic characters, ${group ? 'group' : 'private chat'}`, async () => { + const option = cyrillicOption(length); + const keyboard = await ask([option, 'Нет'], group); + const { onAiButtonClick, handler } = setup(); + const { ctx, editText } = tap(dataOfButton(keyboard, 0), { group, keyboard }); + + await handler(ctx); + + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, group ? GROUP_CHAT : ASKER, option); + expect(editText).toHaveBeenCalledWith(`${QUESTION}\n\n✅ ${option}`, { entities: [] }); + }); + + test(`${length} Cyrillic characters: the short option beside it still answers, ${group ? 'group' : 'private chat'}`, async () => { + const keyboard = await ask([cyrillicOption(length), 'Нет'], group); + const { onAiButtonClick, handler } = setup(); + const { ctx, editText } = tap(dataOfButton(keyboard, 1), { group, keyboard }); + + await handler(ctx); + + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, group ? GROUP_CHAT : ASKER, 'Нет'); + expect(editText).toHaveBeenCalledWith(`${QUESTION}\n\n✅ Нет`, { entities: [] }); + }); + } + } + + test.each( + INCIDENT_OPTIONS.map((option, index) => [option, index] as const), + )('incident question: "%s" is delivered and answered verbatim', async (option, index) => { + const keyboard = await ask(INCIDENT_OPTIONS, false); + const { onAiButtonClick, handler } = setup(); + const { ctx } = tap(dataOfButton(keyboard, index), { keyboard }); + + await handler(ctx); + + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, option); + }); + + test('an option that looks like an index payload is still just text', async () => { + const keyboard = await ask(['ai_opt:1', '1001:Да'], true); + const { onAiButtonClick, handler } = setup(); + + await handler(tap(dataOfButton(keyboard, 0), { group: true, keyboard }).ctx); + expect(onAiButtonClick).toHaveBeenLastCalledWith(ASKER, GROUP_CHAT, 'ai_opt:1'); + await handler(tap(dataOfButton(keyboard, 1), { group: true, keyboard, messageId: 2 }).ctx); + expect(onAiButtonClick).toHaveBeenLastCalledWith(ASKER, GROUP_CHAT, '1001:Да'); + }); +}); + +// Messages already in chats were sent with these exact payloads. +describe('ask_user buttons sent before the index form keep working', () => { + test('private ai_btn payload', async () => { + const { onAiButtonClick, handler } = setup(); + await handler(tap('ai_btn:Да').ctx); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, 'Да'); + }); + + test('group ai_btn payload, tapped by the asker', async () => { + const { onAiButtonClick, handler } = setup(); + await handler(tap(`ai_btn:${ASKER}:19:00`, { group: true }).ctx); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, GROUP_CHAT, '19:00'); + }); +}); + +describe('only the asking user may answer in a group', () => { + test.each([ + ['a short option', 'Нет'], + ['a long option', cyrillicOption(60)], + ])('a tap by another member on %s is refused', async (_form, option) => { + const keyboard = await ask([option, 'Нет'], true); + const index = option === 'Нет' ? 1 : 0; + const { onAiButtonClick, handler } = setup(); + const { ctx, answer, editText } = tap(dataOfButton(keyboard, index), { by: OTHER_MEMBER, group: true, keyboard }); + + await handler(ctx); + + expect(answer).toHaveBeenCalledWith({ text: t('ru').callbackErrors.notYourQuestion, show_alert: false }); + expect(editText).not.toHaveBeenCalled(); + expect(onAiButtonClick).not.toHaveBeenCalled(); + }); +}); + +describe('an index tap that cannot be read as an answer', () => { + test('after the question was answered, a late tap is ignored quietly', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + // Answering edits the message without its keyboard, so a client still showing the buttons taps a message with none. + const { ctx, answer, editText } = tap(dataOfButton(keyboard, 0), { text: `${QUESTION}\n\n✅ Нет` }); + + await handler(ctx); + + expect(answer).toHaveBeenCalledWith(); + expect(editText).not.toHaveBeenCalled(); + expect(onAiButtonClick).not.toHaveBeenCalled(); + }); + + test('on a message whose keyboard is no longer readable, the user is told and the AI is not run', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + const { ctx, answer, editText } = tap(dataOfButton(keyboard, 0)); + + await handler(ctx); + + expect(answer).toHaveBeenCalledWith({ text: t('ru').callbackErrors.unavailable, show_alert: true }); + expect(editText).not.toHaveBeenCalled(); + expect(onAiButtonClick).not.toHaveBeenCalled(); + }); + + test.each([ + 'ai_opt:abc', + 'ai_opt:1:2:3', + 'ai_opt:', + ])('malformed data %p is acknowledged and ignored', async (data) => { + const { onAiButtonClick, handler } = setup(); + const { ctx, answer } = tap(data); + + await handler(ctx); + + expect(answer).toHaveBeenCalledWith(); + expect(onAiButtonClick).not.toHaveBeenCalled(); + }); +}); + +// An acknowledgement the chat cannot take (over 4096 characters, or a failed edit) used to leave +// the buttons live and the message without "✅": the next tap then looked unanswered and the AI got +// a second continuation. The answer is claimed when the first tap is accepted, not when the edit lands. +describe('an answer is recorded once even when the acknowledgement cannot be edited in', () => { + const MESSAGE_TOO_LONG = () => Promise.reject(new Error('Bad Request: MESSAGE_TOO_LONG')); + const NETWORK_DOWN = () => Promise.reject(new Error('network down')); + const LONG_QUESTION = 'К'.repeat(4090); + + test('a 3000-character option under a near-limit question is delivered, acknowledged without the question, reaches the AI whole and once', async () => { + const option = cyrillicOption(200).repeat(15); + const keyboard = await ask([option, 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + const first = tap(dataOfButton(keyboard, 0), { text: LONG_QUESTION, keyboard }); + first.editText.mockImplementationOnce(MESSAGE_TOO_LONG); + + await handler(first.ctx); + + expect(first.editText).toHaveBeenLastCalledWith(`✅ ${option}`); + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, option); + + // Telegram now shows the answer alone, which ends in "✅ answer". + await handler(tap(dataOfButton(keyboard, 0), { text: `✅ ${option}` }).ctx); + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + }); + + test.each([ + ['both edits are refused as too long', [MESSAGE_TOO_LONG, MESSAGE_TOO_LONG]], + ['the edit fails for another reason', [NETWORK_DOWN]], + ])('%s: the message still shows the old question and keyboard, a second tap is ignored', async (_case, failures) => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + const messageId = nextMessageId(); + const first = tap(dataOfButton(keyboard, 0), { text: LONG_QUESTION, keyboard, messageId }); + for (const failure of failures) first.editText.mockImplementationOnce(failure); + + await handler(first.ctx); + // The client still shows the unanswered message and its buttons. + const second = tap(dataOfButton(keyboard, 1), { text: LONG_QUESTION, keyboard, messageId }); + await handler(second.ctx); + + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, cyrillicOption(60)); + expect(second.editText).not.toHaveBeenCalled(); + expect(second.answer).toHaveBeenCalledWith(); + }); + + test('two taps in flight at once reach the AI once', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + const messageId = nextMessageId(); + const first = tap(dataOfButton(keyboard, 0), { keyboard, messageId }); + const second = tap(dataOfButton(keyboard, 1), { keyboard, messageId }); + + await Promise.all([handler(first.ctx), handler(second.ctx)]); + + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + }); + + test('an answer too long for any message is acknowledged in a shortened form that still reads as answered', async () => { + const label = 'Я'.repeat(5000); + const keyboard: TelegramInlineKeyboardMarkup = { inline_keyboard: [[{ text: label, callback_data: 'ai_opt:0' }]] }; + const { onAiButtonClick, handler } = setup(); + const { ctx, editText } = tap('ai_opt:0', { keyboard }); + + await handler(ctx); + + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, label); + const acknowledgement = String(editText.mock.calls.at(-1)?.[0]); + expect(acknowledgement.length).toBeLessThanOrEqual(4096); + expect(acknowledgement).toBe(`${QUESTION}\n\n✅ ${'Я'.repeat(4000)}…`); + }); + + test('an answer with line breaks is acknowledged on one line so the answered check recognises it', async () => { + const label = 'Создать\nу меня\r\nи пригласить'; + const keyboard: TelegramInlineKeyboardMarkup = { inline_keyboard: [[{ text: label, callback_data: 'ai_opt:0' }]] }; + const { onAiButtonClick, handler } = setup(); + const first = tap('ai_opt:0', { keyboard }); + + await handler(first.ctx); + + const [acknowledged] = first.editText.mock.calls.at(-1) as [string]; + expect(acknowledged).toBe(`${QUESTION}\n\n✅ Создать у меня и пригласить`); + await handler(tap('ai_opt:0', { text: acknowledged }).ctx); + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, label); + }); +}); + +// Production builds the callback handler anew for every update (src/bot/index.ts), so the memory of +// an answered message cannot live in the handler: each tap here gets a handler of its own. +describe('an answer is recorded once across handlers built per update', () => { + test('a failed acknowledgement edit, then a second tap on a fresh handler, reach the AI once', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const onAiButtonClick = mock(() => Promise.resolve()); + const messageId = nextMessageId(); + const first = tap(dataOfButton(keyboard, 0), { keyboard, messageId }); + first.editText.mockImplementationOnce(() => Promise.reject(new Error('network down'))); + + await makeCallbackHandler({ onAiButtonClick })(first.ctx); + // The client still shows the unanswered message and its buttons. + const second = tap(dataOfButton(keyboard, 1), { keyboard, messageId }); + await makeCallbackHandler({ onAiButtonClick })(second.ctx); + + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + expect(second.editText).not.toHaveBeenCalled(); + expect(second.answer).toHaveBeenCalledWith(); + }); + + test('the same message id in another chat is a different question', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const onAiButtonClick = mock(() => Promise.resolve()); + const messageId = nextMessageId(); + + await makeCallbackHandler({ onAiButtonClick })(tap(dataOfButton(keyboard, 0), { keyboard, messageId }).ctx); + await makeCallbackHandler({ onAiButtonClick })( + tap(dataOfButton(keyboard, 0), { keyboard, messageId, by: OTHER_MEMBER }).ctx, + ); + + expect(onAiButtonClick).toHaveBeenCalledTimes(2); + }); +}); + +// The claim keeps a second tap away from the AI, so it must not outlive a tap that never got the +// answer to the AI: otherwise the user's retap is ignored and the answer is lost until a restart. +describe('a tap that fails before the AI continuation does not swallow the retap', () => { + test('a callback query that can no longer be answered still records the answer and runs the AI once', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const { onAiButtonClick, handler } = setup(); + const first = tap(dataOfButton(keyboard, 0), { keyboard }); + first.answer.mockImplementationOnce(() => Promise.reject(new Error('query is too old'))); + + await handler(first.ctx); + + expect(first.editText).toHaveBeenCalledTimes(1); + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + expect(onAiButtonClick).toHaveBeenCalledWith(ASKER, ASKER, cyrillicOption(60)); + }); + + test('a failure before the continuation starts releases the claim, so the retap is processed', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const onAiButtonClick = mock(() => Promise.resolve()); + onAiButtonClick.mockImplementationOnce(() => { + throw new Error('agent factory failed'); + }); + const handler = makeCallbackHandler({ onAiButtonClick }); + const messageId = nextMessageId(); + + // The dispatcher answers a handler failure itself, so the handler's own rejection is not visible here. + await handler(tap(dataOfButton(keyboard, 0), { keyboard, messageId }).ctx); + await handler(tap(dataOfButton(keyboard, 0), { keyboard, messageId }).ctx); + + expect(onAiButtonClick).toHaveBeenCalledTimes(2); + }); + + test('a continuation that started and then failed keeps the claim: the AI is not run twice', async () => { + const keyboard = await ask([cyrillicOption(60), 'Нет'], false); + const onAiButtonClick = mock(() => Promise.reject(new Error('provider down'))); + const handler = makeCallbackHandler({ onAiButtonClick }); + const messageId = nextMessageId(); + + await handler(tap(dataOfButton(keyboard, 0), { keyboard, messageId }).ctx); + await handler(tap(dataOfButton(keyboard, 0), { keyboard, messageId }).ctx); + + expect(onAiButtonClick).toHaveBeenCalledTimes(1); + }); +}); diff --git a/test/bot/handlers/callback-dispatch.test.ts b/test/bot/handlers/callback-dispatch.test.ts index 14e09e51..d27715b9 100644 --- a/test/bot/handlers/callback-dispatch.test.ts +++ b/test/bot/handlers/callback-dispatch.test.ts @@ -28,7 +28,7 @@ import { makeUserRow, sentMessage, telegramUser } from '../telegram-fixtures.ts' type Registrar = (dispatch: CallbackDispatch, deps: CallbackRouteDeps) => void; const ROUTE_GROUPS: Array<{ name: string; register: Registrar; prefixes: string[] }> = [ - { name: 'ai', register: registerAiRoutes, prefixes: ['ric', 'dlc', CB.SCENE_HELP, 'ai_btn'] }, + { name: 'ai', register: registerAiRoutes, prefixes: ['ric', 'dlc', CB.SCENE_HELP, 'ai_btn', 'ai_opt'] }, { name: 'event', register: registerEventRoutes, @@ -110,7 +110,7 @@ describe('callback prefix table', () => { owners.set(prefix, group.name); } } - expect(owners.size).toBe(47); + expect(owners.size).toBe(48); }); }); diff --git a/test/bot/handlers/callback.handler.test.ts b/test/bot/handlers/callback.handler.test.ts index 8c3859d9..e219e151 100644 --- a/test/bot/handlers/callback.handler.test.ts +++ b/test/bot/handlers/callback.handler.test.ts @@ -27,6 +27,14 @@ interface MockCallbackCtxOverrides { data?: undefined; } +// Each tap is a message of its own: the answered-ask_user memory is shared by every handler, so a +// fixed id would make one test's answer silence the next test's tap. +let lastMessageId = 0; +function nextMessageId(): number { + lastMessageId += 1; + return lastMessageId; +} + function makeCtx(data: string, overrides: MockCallbackCtxOverrides = {}) { return { data, @@ -34,7 +42,7 @@ function makeCtx(data: string, overrides: MockCallbackCtxOverrides = {}) { dbUser: { telegram_id: 100, language: 'ru', timezone: 'UTC' }, answer: mock(() => Promise.resolve()), editText: mock(() => Promise.resolve()), - message: { id: 1, text: '', chat: { id: 100, type: 'private' }, send: mock(() => Promise.resolve()) }, + message: { id: nextMessageId(), text: '', chat: { id: 100, type: 'private' }, send: mock(() => Promise.resolve()) }, from: { id: 100 }, ...overrides, }; diff --git a/test/bot/middleware/chat-logging.test.ts b/test/bot/middleware/chat-logging.test.ts index 73378655..708601e5 100644 --- a/test/bot/middleware/chat-logging.test.ts +++ b/test/bot/middleware/chat-logging.test.ts @@ -1,11 +1,12 @@ import { describe, expect, test } from 'bun:test'; -import type { TelegramUpdate } from 'gramio'; +import type { TelegramInlineKeyboardMarkup, TelegramUpdate } from 'gramio'; import { createChatLogging } from '../../../src/bot/middleware/chat-logging.ts'; import { createConnectWizardGuard } from '../../../src/bot/middleware/connect-wizard-guard.ts'; import { CONNECT_WIZARD_REDACTION } from '../../../src/bot/scenes/connect-telegram.scene.ts'; import { DatabaseService } from '../../../src/database/index.ts'; import { currentChatTurn } from '../../../src/services/ai/chat-turn-context.ts'; import { ConversationLogger } from '../../../src/services/conversation-logger.ts'; +import { cyrillicOption, fakeTelegram } from '../../helpers/ask-user-keyboard.ts'; describe('chat logging when the connect-wizard state cannot be read (GH-519)', () => { test('the text is stored as the connect-wizard marker, stays in the chat and still reaches the next handler', async () => { @@ -144,3 +145,83 @@ describe('the row saved for each update', () => { db.db.close(); }); }); + +describe('chat logging of an ask_user answer', () => { + const ASKER = 2002; + const GROUP_CHAT = -100200; + + /** Runs one tap through the middleware and returns what chat_history stored. */ + async function logTap( + data: string, + { group, keyboard }: { group: boolean; keyboard?: TelegramInlineKeyboardMarkup }, + ): Promise<{ role: string; content: string; chat_id: number | null }[]> { + const db = new DatabaseService(':memory:'); + const user = db.users.create({ telegram_id: ASKER, language: 'ru', timezone: 'UTC' }); + const logging = createChatLogging({ + conversationLogger: new ConversationLogger(db.chatHistory), + actionLog: db.actionLog, + chatHistoryIds: new Map(), + reserveChatTurn: (chatId, rowId) => ({ chatId, rowId, release() {} }), + isConnectWizardInput: () => false, + }); + const update: TelegramUpdate = { + update_id: 1, + callback_query: { + id: 'tap-1', + chat_instance: 'synthetic', + from: { id: ASKER, is_bot: false, first_name: 'Synthetic' }, + data, + message: { + message_id: 7, + date: 1, + chat: group ? { id: GROUP_CHAT, type: 'supergroup', title: 'Synthetic' } : { id: ASKER, type: 'private' }, + text: 'Как поступить?', + ...(keyboard ? { reply_markup: keyboard } : {}), + }, + }, + }; + await logging({ dbUser: user, update }, async () => {}); + const stored = db.db + .query<{ role: string; content: string; chat_id: number | null }, []>( + 'SELECT role, content, chat_id FROM chat_history ORDER BY id', + ) + .all(); + db.db.close(); + return stored; + } + + for (const group of [false, true]) { + for (const length of [20, 30, 60, 200]) { + test(`a ${length}-character answer is stored as the user's turn, ${group ? 'group' : 'private chat'}`, async () => { + const option = cyrillicOption(length); + const { sender, sent } = fakeTelegram(); + await sender.sendButtons!( + group ? GROUP_CHAT : ASKER, + 'Как поступить?', + [option, 'Нет'], + 'HTML', + group ? ASKER : undefined, + ); + const keyboard = sent[0]!; + + const stored = await logTap(keyboard.inline_keyboard[0]![0]!.callback_data!, { group, keyboard }); + + expect(stored).toEqual([{ role: 'user', content: option, chat_id: group ? GROUP_CHAT : null }]); + }); + } + } + + test('a short answer sent before the index form existed is stored as before', async () => { + expect(await logTap('ai_btn:19:00', { group: false })).toEqual([{ role: 'user', content: '19:00', chat_id: null }]); + expect(await logTap(`ai_btn:${ASKER}:Да`, { group: true })).toEqual([ + { role: 'user', content: 'Да', chat_id: GROUP_CHAT }, + ]); + }); + + test('an index tap whose keyboard is gone is logged as a button press, not as something the user said', async () => { + const stored = await logTap('ai_opt:1', { group: false }); + + expect(stored).toHaveLength(1); + expect(JSON.parse(stored[0]!.content)).toMatchObject({ kind: 'button', label: 'ai_opt', detail: '1' }); + }); +}); diff --git a/test/helpers/ask-user-keyboard.ts b/test/helpers/ask-user-keyboard.ts new file mode 100644 index 00000000..c1061a5b --- /dev/null +++ b/test/helpers/ask-user-keyboard.ts @@ -0,0 +1,32 @@ +import type { Bot, InlineKeyboard, TelegramInlineKeyboardMarkup } from 'gramio'; +import { createTelegramSender } from '../../src/services/ai/telegram-sender.ts'; + +/** Telegram refuses an inline button whose callback_data is over 64 BYTES (BUTTON_DATA_INVALID); Cyrillic is 2 bytes a character. */ +export const TELEGRAM_CALLBACK_DATA_MAX_BYTES = 64; + +/** A Russian option of exactly `length` characters, with the colons and digits real answers carry. */ +export function cyrillicOption(length: number): string { + return 'Вариант: создать у меня на 19:00 и пригласить Ольгу, Сэма, Кима. '.repeat(5).slice(0, length); +} + +/** + * The real sender over a Telegram that refuses what Telegram refuses: a button over the callback_data + * limit fails the whole message, as it did in production on 2026-10-31. `sent` holds each keyboard + * the way the tapped message will later carry it back. + */ +export function fakeTelegram() { + const sent: TelegramInlineKeyboardMarkup[] = []; + const sendMessage = async (args: { reply_markup: InlineKeyboard }) => { + const keyboard = args.reply_markup.toJSON(); + for (const button of keyboard.inline_keyboard.flat()) { + const callbackData = 'callback_data' in button ? button.callback_data : undefined; + if (Buffer.byteLength(callbackData ?? '', 'utf8') > TELEGRAM_CALLBACK_DATA_MAX_BYTES) { + throw new Error('Bad Request: BUTTON_DATA_INVALID'); + } + } + sent.push(keyboard); + return { message_id: sent.length }; + }; + const bot = { api: { sendMessage } } as unknown as Bot; + return { sender: createTelegramSender(bot), sent }; +} diff --git a/test/regressions/recipient-confirmation.test.ts b/test/regressions/recipient-confirmation.test.ts index 7cb7e013..83aec826 100644 --- a/test/regressions/recipient-confirmation.test.ts +++ b/test/regressions/recipient-confirmation.test.ts @@ -39,7 +39,7 @@ test('confirmed force is scoped to actor,event,ID and consumed once', async () = expect(consumeRecipientApproval(7001, 92, 5000000001)).toBe(false); }); test('expired or duplicated buttons cannot trigger approval', () => { - const token = issueRecipientApproval(7001, 94, 5000000001, 1000); + const token = issueRecipientApproval(7001, 94, 5000000001, { now: 1000 }); expect(confirmRecipientApproval(token, 7001, 7001, 302000)).toBeNull(); const token2 = issueRecipientApproval(7001, 95, 5000000001); expect(confirmRecipientApproval(token2, 7001, 7001)).not.toBeNull(); diff --git a/test/regressions/recipient-tools.test.ts b/test/regressions/recipient-tools.test.ts index 05406d8f..3ac5768d 100644 --- a/test/regressions/recipient-tools.test.ts +++ b/test/regressions/recipient-tools.test.ts @@ -33,6 +33,7 @@ import { EventService } from '../../src/services/event/event-service.ts'; import { GroupMemberService } from '../../src/services/group/member-service.ts'; import { DeepLinkService } from '../../src/services/sharing/deep-link-service.ts'; import { InvitationService } from '../../src/services/sharing/invitation-service.ts'; +import { makeCallbackHandler, makeCallbackTap } from '../helpers/callback-handler.ts'; import { disabledServiceTier } from '../helpers/service-tier.ts'; function makeCtx(db: Database, overrides: Partial = {}): AgentContext { @@ -275,6 +276,41 @@ describe('recipient and contact tool boundaries', () => { }); } + test.each([ + [undefined, 'Send that invitation with force=true; do not change'], + [2002, 'Send that invitation with force=true and owner_id 2002; do not change'], + ])('the confirmation continuation for owner %p says how to send', async (ownerId, expected) => { + const event = ctx.eventService.createEvent({ + user_id: 10, + title: 'Continuation text', + start_at: new Date(Date.now() + 86400000).toISOString(), + timezone: 'UTC', + }); + const token = issueRecipientApproval(10, event.id, 5000000002, { ownerId }); + const texts: string[] = []; + const agentContinuation = { + agent: { + run: async (continuation: AgentContext) => { + texts.push(continuation.messageText); + return { responseText: '', toolCalls: [], toolResults: [] }; + }, + }, + buildContext: (user: User, chatId: number, messageText: string): AgentContext => ({ + ...ctx, + user, + chatId, + messageText, + conversationLogger: new ConversationLogger(new ChatHistoryRepository(db)), + }), + }; + const handler = makeCallbackHandler({ agentContinuation }, ctx.eventService); + const { ctx: tap } = makeCallbackTap(`ric:${token}`, ctx.user); + Object.assign(tap, { from: { id: 10 }, chatId: 10 }); + await handler(tap); + expect(texts).toHaveLength(1); + expect(texts[0]).toContain(expected); + }); + test('inspection metadata is reused for resend without refreshing the same scoped ID', async () => { const event = ctx.eventService.createEvent({ user_id: 10, diff --git a/test/services/ai/agent-run-errors-and-budgets.test.ts b/test/services/ai/agent-run-errors-and-budgets.test.ts index 15eca876..d37d85f2 100644 --- a/test/services/ai/agent-run-errors-and-budgets.test.ts +++ b/test/services/ai/agent-run-errors-and-budgets.test.ts @@ -125,7 +125,8 @@ describe('CalendarBotAgent.run()', () => { expect(ctx.eventService.getEvent(event.id, USER_ID)?.title).toBe('Confirmed title'); expect(result.toolCalls.filter((call) => call.name === 'update_event')).toHaveLength(1); expect(result.responseText).not.toContain('late unsupported claim'); - expect(result.responseText).toContain('Completed'); + expect(result.responseText).toContain('Updated: event “Confirmed title”'); + expect(result.responseText).toContain('fields: title'); expect(enqueue).not.toHaveBeenCalled(); }); diff --git a/test/services/ai/agent-run-execution-log.test.ts b/test/services/ai/agent-run-execution-log.test.ts index 2881ea90..b7cdfe20 100644 --- a/test/services/ai/agent-run-execution-log.test.ts +++ b/test/services/ai/agent-run-execution-log.test.ts @@ -107,7 +107,7 @@ describe('CalendarBotAgent.run()', () => { delivered = text; }; await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); - expect(delivered).toContain('Not completed:'); + expect(delivered).toContain('Not deleted: event'); expect(delivered).not.toContain('Готово! Событие удалено'); }); diff --git a/test/services/ai/agent-run-invitations-and-delivery.test.ts b/test/services/ai/agent-run-invitations-and-delivery.test.ts index 4e415403..2cda18d0 100644 --- a/test/services/ai/agent-run-invitations-and-delivery.test.ts +++ b/test/services/ai/agent-run-invitations-and-delivery.test.ts @@ -44,9 +44,10 @@ describe('CalendarBotAgent.run()', () => { { kind: 'error', error: new Error('Synthetic provider interruption') }, ]); const result = await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); - expect(result.responseText).toContain('Not completed:'); - expect(result.responseText).toContain('request rejected before applying changes'); - expect(result.responseText).not.toContain('Outcome unknown'); + expect(result.responseText).toContain( + { create_event: 'Not created: event', update_event: 'Not updated: event', send_invitation: 'was not sent' }[name], + ); + expect(result.responseText).not.toContain('Could not confirm'); expect(result.responseText).not.toContain('Confirmed changes remain'); expect(enqueue).toHaveBeenCalledTimes(1); }); @@ -121,8 +122,8 @@ describe('CalendarBotAgent.run()', () => { const result = await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); const stored = db.query('SELECT start_at FROM events WHERE id=?').get(event.id) as { start_at: string }; expect(stored.start_at).toBe('2030-01-01T10:00:00Z'); - expect(result.responseText).toContain('Outcome unknown'); - expect(result.responseText).not.toContain('request rejected before applying changes'); + expect(result.responseText).toContain('Could not confirm the update'); + expect(result.responseText).not.toContain('nothing was changed'); expect(enqueue).not.toHaveBeenCalled(); }); @@ -144,7 +145,7 @@ describe('CalendarBotAgent.run()', () => { expect(result.responseText).toBe(''); expect(sender.sendUserPicker).toHaveBeenCalledTimes(1); expect(db.query('SELECT id FROM invitations WHERE event_id = ?').all(event.id)).toHaveLength(0); - expect(JSON.stringify(ctx.chatHistory.getRecent(USER_ID))).not.toContain('Completed: Send invitation'); + expect(JSON.stringify(ctx.chatHistory.getRecent(USER_ID))).not.toContain('The invitation to'); }); test.each([ @@ -175,9 +176,8 @@ describe('CalendarBotAgent.run()', () => { ]); const result = await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); expect(db.query('SELECT id FROM invitations WHERE event_id = ?').all(event.id)).toHaveLength(1); - expect(result.responseText).toContain(delivery === 'delivered' ? 'Invitation delivered' : 'Invitation created'); expect(result.responseText).toContain( - delivery === 'manual' ? 'forward' : delivery === 'failed' ? 'not delivered' : 'delivered', + { delivered: 'was sent', manual: 'Please forward the link', failed: 'created but not delivered' }[delivery], ); expect(result.responseText).not.toContain('789'); expect(result.responseText).not.toContain('private'); @@ -281,6 +281,6 @@ describe('CalendarBotAgent.run()', () => { expect(ctx.eventService.getEvent(event.id, 789)).not.toBeNull(); expect(ctx.participantRepo.findByEventAndUser(event.id, USER_ID)?.status).toBe('declined'); expect(result.responseText).toContain('Attendance declined'); - expect(result.responseText).not.toContain('Completed: Delete event'); + expect(result.responseText).not.toContain('Deleted: event'); }); }); diff --git a/test/services/ai/agent-run-tool-exposure.test.ts b/test/services/ai/agent-run-tool-exposure.test.ts index 2b15c2a0..cff30aff 100644 --- a/test/services/ai/agent-run-tool-exposure.test.ts +++ b/test/services/ai/agent-run-tool-exposure.test.ts @@ -303,7 +303,7 @@ describe('CalendarBotAgent.run()', () => { }).run(ctx); expect(change).toHaveBeenCalledTimes(1); expect(ctx.eventService.getEvent(event.id, USER_ID)?.title).toBe('Verified later change'); - expect(result.responseText).not.toContain('Not completed'); + expect(result.responseText).not.toContain('Not updated'); expect(result.toolCalls.map((call) => call.name)).toEqual(['update_event', 'update_event']); } finally { change.mockRestore(); @@ -380,10 +380,11 @@ describe('CalendarBotAgent.run()', () => { expect(result.toolCalls.filter((call) => call.name === 'add_contact')).toHaveLength(2); // add_contact is not in WriteOutcomes' targeted-dedup map (unlike update_event/ // send_invitation), so the failed attempt 1 is never superseded by attempt 2's - // success — the user sees both as a receipt, not a clean "Saved." reply. That is - // pre-existing write-outcomes framing, not something this fix changes; pin what + // success — the user sees both in the receipt, not a clean "Saved." reply. That is + // pre-existing write-outcomes behaviour, not something this fix changes; pin what // is actually shown rather than a substring that happens to also match "Saved.". - expect(result.responseText).toContain('Attempt 2: Completed'); + expect(result.responseText).toContain('Not done: change'); + expect(result.responseText).toContain('Done: change'); expect(result.responseText).not.toContain('Saved.'); }); diff --git a/test/services/ai/agent-run-write-guards.test.ts b/test/services/ai/agent-run-write-guards.test.ts index 431b0f4e..a1cf58ab 100644 --- a/test/services/ai/agent-run-write-guards.test.ts +++ b/test/services/ai/agent-run-write-guards.test.ts @@ -86,7 +86,7 @@ describe('CalendarBotAgent.run()', () => { const result = await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); expect(ctx.eventService.getEvent(event.id, USER_ID)).toBeNull(); expect(enqueue).not.toHaveBeenCalled(); - expect(result.responseText).toContain('Completed: Delete event'); + expect(result.responseText).toContain('Deleted: event'); expect(result.responseText).toContain('interrupted'); expect(result.responseText).not.toContain('private provider'); }); @@ -121,7 +121,7 @@ describe('CalendarBotAgent.run()', () => { { kind: 'text', text: 'Successfully deleted everything.' }, ]); const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); - expect(result.responseText).toContain('Not completed: Delete event'); + expect(result.responseText).toContain('Not deleted: event'); expect(result.responseText).not.toContain('Successfully deleted everything.'); const history = ctx.chatHistory.getRecent(USER_ID); expect(JSON.stringify(history)).not.toContain('Successfully deleted everything.'); @@ -140,7 +140,7 @@ describe('CalendarBotAgent.run()', () => { { kind: 'text', text: 'Updated.' }, ]); const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); - expect(result.responseText).not.toContain('Not completed:'); + expect(result.responseText).not.toContain('Not updated'); expect(ctx.eventService.getEvent(event.id, USER_ID)?.title).toBe('Corrected'); }); @@ -173,8 +173,8 @@ describe('CalendarBotAgent.run()', () => { const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); expect(script.calls).toHaveLength(5); expect(result.toolResults.map((entry) => entry.success)).toEqual([true, true, false]); - expect(result.responseText).toContain('Completed: Delete event'); - expect(result.responseText).toContain('Not completed: Delete event'); + expect(result.responseText).toContain('Deleted: event'); + expect(result.responseText).toContain('Not deleted: event'); expect(result.responseText).not.toContain('Everything succeeded.'); expect(JSON.stringify(ctx.chatHistory.getRecent(USER_ID))).not.toContain('Everything succeeded.'); expect(ctx.eventService.getEvent(event.id, USER_ID)).toBeNull(); @@ -195,7 +195,7 @@ describe('CalendarBotAgent.run()', () => { if (name === 'supplement_skip') ctx.supplementMode = true; const result = await new CalendarBotAgent(config, sender, { streamImpl: script.impl }).run(ctx); expect(script.calls).toHaveLength(2); - expect(result.responseText).not.toContain('Not completed:'); + expect(result.responseText).not.toContain('Not deleted:'); if (name === 'ask_user') expect(sender.sendButtons).toHaveBeenCalledTimes(1); if (name === 'pick_users') expect(sender.sendUserPicker).toHaveBeenCalledTimes(1); if (name === 'supplement_skip') expect(sender.editMessageText).not.toHaveBeenCalled(); @@ -247,12 +247,12 @@ describe('CalendarBotAgent.run()', () => { date.mockRestore(); } if (ending === 'quiet-retry') expect(enqueue).toHaveBeenCalledTimes(1); - expect(result.responseText).toContain('Not completed:'); + expect(result.responseText).toContain('Not deleted:'); expect(result.responseText).not.toContain('Successfully deleted'); const history = JSON.stringify(ctx.chatHistory.getRecent(USER_ID)); - expect(history).toContain('Not completed:'); + expect(history).toContain('Not deleted:'); expect(history).not.toContain('Successfully deleted'); - expect(delivered).toContain('Not completed:'); + expect(delivered).toContain('Not deleted:'); expect(delivered).not.toContain('Successfully deleted'); }); @@ -322,11 +322,11 @@ describe('CalendarBotAgent.run()', () => { }; try { const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); - expect(result.responseText).toContain('Not completed:'); - expect(delivered).toContain('Not completed:'); + expect(result.responseText).toContain('Not deleted:'); + expect(delivered).toContain('Not deleted:'); expect(delivered).not.toContain('Deleted successfully'); const history = JSON.stringify(ctx.chatHistory.getRecent(USER_ID)); - expect(history).toContain('Not completed:'); + expect(history).toContain('Not deleted:'); expect(history).not.toContain('Deleted successfully'); expect(history).not.toContain('Unverified answer'); } finally { @@ -353,7 +353,7 @@ describe('CalendarBotAgent.run()', () => { const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); expect(result.responseText).toContain('title'); expect(result.responseText).toContain('start time'); - expect(delivered).toContain('Not completed:'); + expect(delivered).toContain('Not updated: event “Before”'); const saved = ctx.eventService.getEvent(event.id, USER_ID); expect(saved?.title).toBe('Before'); expect(saved?.location).toBe('Office'); @@ -374,7 +374,7 @@ describe('CalendarBotAgent.run()', () => { expect(sender.deleteMessage).toHaveBeenCalled(); expect(enqueue).not.toHaveBeenCalled(); const history = JSON.stringify(ctx.chatHistory.getRecent(USER_ID)); - expect(history).toContain('Not completed:'); + expect(history).toContain('Not deleted:'); expect(history).not.toContain('Deleted successfully'); }); @@ -384,7 +384,7 @@ describe('CalendarBotAgent.run()', () => { { kind: 'text', text: 'Created successfully.' }, ]); const result = await new CalendarBotAgent(config, sender, { streamImpl: impl }).run(ctx); - expect(result.responseText).toContain('Not completed: Create event'); + expect(result.responseText).toContain('Not created: event'); expect(result.responseText).not.toContain('Created successfully.'); expect(JSON.stringify(ctx.chatHistory.getRecent(USER_ID))).not.toContain('Created successfully.'); }); diff --git a/test/services/ai/recipient-identity-self.test.ts b/test/services/ai/recipient-identity-self.test.ts new file mode 100644 index 00000000..1f828de4 --- /dev/null +++ b/test/services/ai/recipient-identity-self.test.ts @@ -0,0 +1,67 @@ +// "Invite me" on an event in someone else's calendar: the requester's own Telegram ID is a verified +// recipient without a @username guess, a numeric mention in the message or a saved contact. +import { Database } from 'bun:sqlite'; +import { afterEach, beforeEach, expect, test } from 'bun:test'; +import { ContactRepository } from '../../../src/database/repositories/contact.repository.ts'; +import { isKnownRecipient, resolveInvitationRecipient } from '../../../src/services/ai/recipient-identity.ts'; +import type { AgentContext } from '../../../src/services/ai/types.ts'; + +const REQUESTER_ID = 1001; +const OWNER_ID = 2002; +const INVENTED_ID = 5005005; + +let db: Database; +let contacts: ContactRepository; + +beforeEach(() => { + db = new Database(':memory:'); + db.exec( + "CREATE TABLE contacts(id INTEGER PRIMARY KEY, user_id INTEGER, name TEXT, username TEXT, telegram_id INTEGER, preferred_name TEXT, created_at TEXT DEFAULT (datetime('now')))", + ); + contacts = new ContactRepository(db); +}); +afterEach(() => db.close()); + +function context(): AgentContext { + // Only the fields recipient verification reads; the rest of the context is irrelevant to it. + return { + user: { telegram_id: REQUESTER_ID, language: 'ru' }, + messageText: 'Настолки поставь в календарь Ольги и пригласи меня', + contactRepo: contacts, + userRepo: { findByTelegramId: () => null, findByUsername: () => null }, + } as unknown as AgentContext; +} + +test('the requester own id is a known recipient even when the message names no id', () => { + expect(isKnownRecipient(context(), REQUESTER_ID)).toBe(true); + expect(isKnownRecipient(context(), INVENTED_ID)).toBe(false); + expect(isKnownRecipient(context(), OWNER_ID)).toBe(false); +}); + +test('inviting oneself resolves to the requester id', async () => { + expect(await resolveInvitationRecipient(context(), { invitee_id: REQUESTER_ID })).toEqual({ + ok: true, + id: REQUESTER_ID, + isGroup: false, + }); +}); + +test('an address-book row that happens to carry the requester id as its row id does not shadow it', async () => { + db.prepare('INSERT INTO contacts(id, user_id, name, telegram_id) VALUES (?, ?, ?, ?)').run( + REQUESTER_ID, + REQUESTER_ID, + 'Anton', + 3001, + ); + expect(await resolveInvitationRecipient(context(), { invitee_id: REQUESTER_ID })).toMatchObject({ + ok: true, + id: REQUESTER_ID, + }); +}); + +test('an id no tool returned and the message never mentioned stays unverified', async () => { + expect(await resolveInvitationRecipient(context(), { invitee_id: INVENTED_ID })).toEqual({ + ok: false, + reason: 'unverified', + }); +}); diff --git a/test/services/ai/silent-final.test.ts b/test/services/ai/silent-final.test.ts index e9b07e18..4544eb0d 100644 --- a/test/services/ai/silent-final.test.ts +++ b/test/services/ai/silent-final.test.ts @@ -175,16 +175,17 @@ describe('silent final guard (#508)', () => { expect(invitations).toHaveLength(1); const tr = t('ru').writeOutcomes; const reply = delivered.at(-1) ?? ''; + const sent = 'Приглашение на «Синтетическая встреча» отправлено'; expect(deleted).toEqual([]); expect(reply).toContain('Ход выполнения'); expect(reply).toContain(t('ru').ai_unanswered_writes('').trim()); - expect(reply).toContain(`${tr.completed}: ${tr.operations.create_event}`); - expect(reply).toContain(tr.invitationDelivered); + expect(reply).toContain(`${tr.operations.create_event.done}: событие «Синтетическая встреча»`); + expect(reply).toContain(sent); expect(reply).not.toContain('[SKIP]'); - expect(result.responseText).toContain(tr.operations.create_event); + expect(result.responseText).toContain(tr.operations.create_event.done); // The next turn's model must see what the user was told, not the skip token. const history = assistantHistory(); - expect(history).toContain(tr.invitationDelivered); + expect(history).toContain(sent); expect(history).not.toContain('[SKIP]'); }); @@ -229,7 +230,7 @@ describe('silent final guard (#508)', () => { const tr = t('ru').writeOutcomes; expect(deleted).toEqual([]); - expect(delivered.at(-1)).toContain(`${tr.completed}: ${tr.operations.create_event}`); + expect(delivered.at(-1)).toContain(`${tr.operations.create_event.done}: событие «Синтетическая встреча»`); }); /** Wires a renderer and records every photo actually sent to the chat. */ diff --git a/test/services/ai/telegram-sender.test.ts b/test/services/ai/telegram-sender.test.ts index 5a7b5a8e..f11a7692 100644 --- a/test/services/ai/telegram-sender.test.ts +++ b/test/services/ai/telegram-sender.test.ts @@ -2,6 +2,7 @@ import { describe, expect, mock, test } from 'bun:test'; import type { Bot, InlineKeyboard } from 'gramio'; import { createTelegramSender } from '../../../src/services/ai/telegram-sender.ts'; import { invitationRsvpKeyboard } from '../../../src/services/sharing/invitation-rsvp-keyboard.ts'; +import { cyrillicOption, TELEGRAM_CALLBACK_DATA_MAX_BYTES } from '../../helpers/ask-user-keyboard.ts'; interface CapturedButton { text: string; @@ -50,3 +51,74 @@ describe('createTelegramSender.sendInvitation', () => { expect(data.some((d) => d.startsWith('inv:'))).toBe(false); }); }); + +describe('createTelegramSender.sendButtons', () => { + for (const userId of [undefined, 1001]) { + for (const length of [20, 30, 60, 200]) { + test(`a ${length}-character Cyrillic option ${userId ? 'in a group' : 'in a private chat'} fits Telegram's callback_data limit`, async () => { + const { sender, calls } = makeSender(); + const option = cyrillicOption(length); + await sender.sendButtons!(5, 'Вопрос?', [option], 'HTML', userId); + + const [button] = keyboardButtons(calls[0]!.reply_markup!); + expect(button!.text).toBe(option); + expect(Buffer.byteLength(button!.callback_data ?? '', 'utf8')).toBeLessThanOrEqual( + TELEGRAM_CALLBACK_DATA_MAX_BYTES, + ); + }); + } + } + + // Buttons already sitting in chats carry these exact payloads, so the short form must not change. + test('a short option keeps the ai_btn payload, with the asker prefix in a group', async () => { + const { sender, calls } = makeSender(); + await sender.sendButtons!(5, 'Вопрос?', ['Да', '19:00'], 'HTML'); + await sender.sendButtons!(5, 'Вопрос?', ['Да', '19:00'], 'HTML', 1001); + + expect(keyboardButtons(calls[0]!.reply_markup!).map((b) => b.callback_data)).toEqual(['ai_btn:Да', 'ai_btn:19:00']); + expect(keyboardButtons(calls[1]!.reply_markup!).map((b) => b.callback_data)).toEqual([ + 'ai_btn:1001:Да', + 'ai_btn:1001:19:00', + ]); + }); + + test('a long option rides as its index under a separate action, next to short ones', async () => { + const { sender, calls } = makeSender(); + const options = ['Да', cyrillicOption(60), 'Нет']; + await sender.sendButtons!(5, 'Вопрос?', options, 'HTML'); + await sender.sendButtons!(5, 'Вопрос?', options, 'HTML', 1001); + + expect(keyboardButtons(calls[0]!.reply_markup!).map((b) => b.callback_data)).toEqual([ + 'ai_btn:Да', + 'ai_opt:1', + 'ai_btn:Нет', + ]); + expect(keyboardButtons(calls[1]!.reply_markup!).map((b) => b.callback_data)).toEqual([ + 'ai_btn:1001:Да', + 'ai_opt:1001:1', + 'ai_btn:1001:Нет', + ]); + }); + + // 'ai_btn:' is 7 bytes and a Cyrillic letter 2: the limit is bytes, not characters. + test('the payload switches form exactly at 64 bytes', async () => { + const { sender, calls } = makeSender(); + const fits = `${'я'.repeat(28)}x`; + const overByOne = `${'я'.repeat(28)}xx`; + await sender.sendButtons!(5, 'Вопрос?', [fits, overByOne], 'HTML'); + + expect(keyboardButtons(calls[0]!.reply_markup!).map((b) => b.callback_data)).toEqual([ + `ai_btn:${fits}`, + 'ai_opt:1', + ]); + }); + + test('long options that differ only in their tail stay distinct buttons', async () => { + const { sender, calls } = makeSender(); + const shared = cyrillicOption(60); + await sender.sendButtons!(5, 'Вопрос?', [`${shared} (первый)`, `${shared} (второй)`], 'HTML'); + + const data = keyboardButtons(calls[0]!.reply_markup!).map((b) => b.callback_data); + expect(new Set(data).size).toBe(2); + }); +}); diff --git a/test/services/ai/tool-handlers/ask-user.test.ts b/test/services/ai/tool-handlers/ask-user.test.ts new file mode 100644 index 00000000..4efd4656 --- /dev/null +++ b/test/services/ai/tool-handlers/ask-user.test.ts @@ -0,0 +1,129 @@ +// ask_user delivery: what Telegram can carry reaches the user, what it cannot is named to the model. +// Incident 2026-10-31: two options of 45 and 22 characters made the whole question fail with +// BUTTON_DATA_INVALID and the model never got to ask. + +import { describe, expect, mock, test } from 'bun:test'; +import { MAX_ASK_USER_OPTIONS } from '../../../../src/services/ai/ask-user-buttons.ts'; +import { handleAskUser } from '../../../../src/services/ai/tool-handlers/meta.ts'; +import type { TelegramSender } from '../../../../src/services/ai/types.ts'; +import { cyrillicOption, fakeTelegram, TELEGRAM_CALLBACK_DATA_MAX_BYTES } from '../../../helpers/ask-user-keyboard.ts'; +import { agentContext, userRow } from '../context-fixtures.ts'; + +const ASKER = 2002; +const QUESTION = 'Как поступить?'; +const INCIDENT_OPTIONS = ['Создать у меня и пригласить Ольгу, Сэма, Кима', 'Оставить только у Ольги']; + +function askerContext(overrides: Parameters[0] = {}) { + return agentContext({ user: userRow({ telegram_id: ASKER, language: 'ru' }), chatId: ASKER, ...overrides }); +} + +/** A sender that records the buttons it was asked to show and fails the way Telegram does when told to. */ +function recordingSender(failWith?: Error) { + const sendButtons = mock>(() => + failWith ? Promise.reject(failWith) : Promise.resolve({ message_id: 1 }), + ); + const sender: TelegramSender = { + sendMessage: () => Promise.resolve({ message_id: 1 }), + editMessageText: () => Promise.resolve(), + sendButtons, + }; + return { sender, sendButtons }; +} + +describe('handleAskUser delivers what Telegram can carry', () => { + test.each([ + ['private chat', false], + ['group', true], + ])('the incident question (%s) is delivered with every button inside the callback_data limit', async (_chat, isGroup) => { + const { sender, sent } = fakeTelegram(); + + const result = await handleAskUser(askerContext({ sender, isGroup }), { + question: QUESTION, + options: INCIDENT_OPTIONS, + }); + + expect(result.success).toBe(true); + expect(result.stopLoop).toBe(true); + const buttons = sent[0]!.inline_keyboard.flat(); + expect(buttons.map((button) => button.text)).toEqual([...INCIDENT_OPTIONS, 'Отмена']); + for (const button of buttons) { + expect(Buffer.byteLength(button.callback_data ?? '', 'utf8')).toBeLessThanOrEqual( + TELEGRAM_CALLBACK_DATA_MAX_BYTES, + ); + } + }); + + test('the largest keyboard Telegram is trusted with is delivered', async () => { + const { sender, sent } = fakeTelegram(); + const options = Array.from({ length: MAX_ASK_USER_OPTIONS - 1 }, (_unused, index) => `Вариант ${index + 1}`); + + const result = await handleAskUser(askerContext({ sender }), { question: QUESTION, options }); + + expect(result.success).toBe(true); + expect(sent[0]!.inline_keyboard.flat()).toHaveLength(MAX_ASK_USER_OPTIONS); + }); + + test('a model that sent Cancel itself may use all 100 buttons; one more is refused counting Cancel once', async () => { + const { sender, sent } = fakeTelegram(); + const withCancel = [...Array.from({ length: MAX_ASK_USER_OPTIONS - 1 }, (_u, i) => `Вариант ${i + 1}`), 'Отмена']; + const ok = await handleAskUser(askerContext({ sender }), { question: QUESTION, options: withCancel }); + expect(ok.success).toBe(true); + expect(sent[0]!.inline_keyboard.flat()).toHaveLength(MAX_ASK_USER_OPTIONS); + const tooMany = await handleAskUser(askerContext({ sender }), { + question: QUESTION, + options: [...withCancel, 'Ещё'], + }); + expect(tooMany.success).toBe(false); + expect(tooMany.error).toContain(`${MAX_ASK_USER_OPTIONS + 1} options do not fit`); + expect(sent).toHaveLength(1); + }); + + // No label-length limit is enforced: a 3000-character option is delivered whole. Whether Telegram + // itself shows a very long label whole is unverified (#914). + test('long labels are delivered whole, not rejected', async () => { + const { sender, sent } = fakeTelegram(); + const options = [cyrillicOption(200).repeat(15), ...Array.from({ length: 15 }, () => cyrillicOption(300))]; + + const result = await handleAskUser(askerContext({ sender }), { question: QUESTION, options }); + + expect(result.success).toBe(true); + expect(sent[0]!.inline_keyboard.flat().map((button) => button.text)).toEqual([...options, 'Отмена']); + }); +}); + +describe('handleAskUser names what Telegram cannot carry', () => { + test.each([ + ['an empty option', { question: QUESTION, options: ['Да', ''] }, 'option 2 is empty'], + ['a whitespace-only option', { question: QUESTION, options: [' ', 'Нет'] }, 'option 1 is empty'], + ['an empty question', { question: ' ', options: ['Да', 'Нет'] }, 'the question is empty'], + [ + 'more options than a keyboard holds', + { + question: QUESTION, + options: Array.from({ length: MAX_ASK_USER_OPTIONS }, (_unused, index) => `Вариант ${index + 1}`), + }, + `${MAX_ASK_USER_OPTIONS} options plus the "Отмена" button this tool adds itself do not fit on one Telegram keyboard (at most ${MAX_ASK_USER_OPTIONS} buttons: ${MAX_ASK_USER_OPTIONS - 1} of your options)`, + ], + ])('%s is returned to the model and nothing is sent', async (_case, input, problem) => { + const { sender, sendButtons } = recordingSender(); + + const result = await handleAskUser(askerContext({ sender }), input); + + expect(result.success).toBe(false); + expect(result.error).toContain('ASK_USER_INVALID_INPUT'); + expect(result.error).toContain(problem); + expect(sendButtons).not.toHaveBeenCalled(); + }); +}); + +describe('handleAskUser when Telegram refuses the question anyway', () => { + test('the tool result carries no Telegram wording for the user to see', async () => { + const { sender } = recordingSender(new Error('Bad Request: BUTTON_DATA_INVALID')); + + const result = await handleAskUser(askerContext({ sender }), { question: QUESTION, options: ['Да', 'Нет'] }); + + expect(result.success).toBe(false); + expect(result.error).toStartWith('ASK_USER_DELIVERY_FAILED'); + expect(result.error).not.toContain('BUTTON_DATA_INVALID'); + }); +}); diff --git a/test/services/ai/tool-handlers/sharing-failure-paths.test.ts b/test/services/ai/tool-handlers/sharing-failure-paths.test.ts index f63e85b0..05e4daad 100644 --- a/test/services/ai/tool-handlers/sharing-failure-paths.test.ts +++ b/test/services/ai/tool-handlers/sharing-failure-paths.test.ts @@ -3,12 +3,16 @@ import { beforeEach, describe, expect, test } from 'bun:test'; import { ContactRepository } from '../../../../src/database/repositories/contact.repository.ts'; import { EditProposalRepository } from '../../../../src/database/repositories/edit-proposal.repository.ts'; +import { WRITE_TOOLS } from '../../../../src/services/ai/tool-executor.ts'; import { + handleCancelInvitation, handleProposeEdit, handleResendInvitation, handleSendInvitation, } from '../../../../src/services/ai/tool-handlers/sharing.ts'; -import type { AgentContext } from '../../../../src/services/ai/types.ts'; +import type { AgentContext, ToolResult } from '../../../../src/services/ai/types.ts'; +import { WriteOutcomes } from '../../../../src/services/ai/write-outcomes.ts'; +import type { ReceiptView } from '../../../../src/services/ai/write-receipt.ts'; import { createSharingFixture, futureStartAt, @@ -17,6 +21,18 @@ import { USER_ID, } from './sharing-fixtures.ts'; +const RECEIPT_VIEW: ReceiptView = { + language: 'en', + timezone: 'UTC', + hideTargets: false, + requesterId: USER_ID, + now: new Date('2026-10-31T09:00:00Z'), + personLabel: () => null, + personKey: ({ id, username }) => (id === null ? `@${username}` : `id:${id}`), + calendarOwnerName: () => null, + hasCalendarAccess: () => false, +}; + describe('sharing handlers: failure paths', () => { let fixture: SharingFixture; @@ -31,14 +47,46 @@ describe('sharing handlers: failure paths', () => { describe('handleResendInvitation refusals', () => { test('reports a missing invitation', async () => { const result = await handleResendInvitation(fixture.makeCtx(), { invitation_id: 9999 }); - expect(result).toEqual({ success: false, error: 'Invitation not found.' }); + expect(result).toEqual({ success: false, mutationState: 'not_applied', error: 'Invitation not found.' }); }); - test("refuses somebody else's invitation", async () => { + // A foreign id must answer exactly as a missing one, for the owner path too: 'Not your invitation.' + // used to tell anyone guessing ids which of them exist. + test("answers somebody else's invitation exactly as a missing one, and delivers nothing", async () => { const event = ownedEvent(OTHER_USER_ID, 'Not Mine'); const inv = fixture.invitationRepo.create({ event_id: event.id, inviter_id: OTHER_USER_ID, invitee_id: USER_ID }); - const result = await handleResendInvitation(fixture.makeCtx(), { invitation_id: inv.id }); - expect(result).toEqual({ success: false, error: 'Not your invitation.' }); + const delivered: number[] = []; + const ctx = fixture.makeCtx({ + sender: { + sendMessage: async () => ({ message_id: 1 }), + editMessageText: async () => {}, + sendInvitation: async (inviteeId, _text, invitationId) => { + delivered.push(inviteeId); + return { message_id: 700 + invitationId }; + }, + }, + }); + + const foreign = await handleResendInvitation(ctx, { invitation_id: inv.id }); + const missing = await handleResendInvitation(ctx, { invitation_id: inv.id + 1000 }); + + expect(foreign).toEqual(missing); + expect(foreign).toEqual({ success: false, mutationState: 'not_applied', error: 'Invitation not found.' }); + expect(delivered).toEqual([]); + expect(fixture.invitationRepo.findById(inv.id)).toEqual(inv); + }); + + test("answers cancelling somebody else's invitation exactly as a missing one, and cancels nothing", () => { + const event = ownedEvent(OTHER_USER_ID, 'Not Mine'); + const inv = fixture.invitationRepo.create({ event_id: event.id, inviter_id: OTHER_USER_ID, invitee_id: USER_ID }); + const ctx = fixture.makeCtx(); + + const foreign = handleCancelInvitation(ctx, { invitation_id: inv.id }); + const missing = handleCancelInvitation(ctx, { invitation_id: inv.id + 1000 }); + + expect(foreign).toEqual(missing); + expect(foreign.success).toBe(false); + expect(fixture.invitationRepo.findById(inv.id)).toEqual(inv); }); test('refuses an invitation that is no longer pending', async () => { @@ -46,7 +94,11 @@ describe('sharing handlers: failure paths', () => { const inv = fixture.invitationRepo.create({ event_id: event.id, inviter_id: USER_ID, invitee_id: OTHER_USER_ID }); fixture.invitationRepo.updateStatus(inv.id, 'accepted', 'pending'); const result = await handleResendInvitation(fixture.makeCtx(), { invitation_id: inv.id }); - expect(result).toEqual({ success: false, error: 'Cannot resend — status is "accepted".' }); + expect(result).toEqual({ + success: false, + mutationState: 'not_applied', + error: 'Cannot resend — status is "accepted".', + }); }); test('reports delivery failure with the exact hint when the bot API and deep link both fail', async () => { @@ -165,4 +217,60 @@ describe('sharing handlers: failure paths', () => { expect(result.error).toContain('The proposal has no editable change.'); }); }); + + // A denial changed nothing. Without mutationState the executor classifies a failed write as + // 'uncertain' and the receipt tells the user to check the calendar before repeating. + describe('cancel_invitation and resend_invitation denials are a plain "not applied"', () => { + type Tool = 'cancel_invitation' | 'resend_invitation'; + + async function denials(): Promise<{ name: string; tool: Tool; result: ToolResult }[]> { + const foreignEvent = ownedEvent(OTHER_USER_ID, 'Not Mine'); + const foreign = fixture.invitationRepo.create({ + event_id: foreignEvent.id, + inviter_id: OTHER_USER_ID, + invitee_id: USER_ID, + }); + const ownEvent = ownedEvent(USER_ID, 'Answered'); + const answered = fixture.invitationRepo.create({ + event_id: ownEvent.id, + inviter_id: USER_ID, + invitee_id: OTHER_USER_ID, + }); + fixture.invitationRepo.updateStatus(answered.id, 'accepted', 'pending'); + const ctx = fixture.makeCtx(); + const cancel = (name: string, input: { invitation_id: number; owner_id?: number }) => ({ + name: `cancel: ${name}`, + tool: 'cancel_invitation' as const, + result: handleCancelInvitation(ctx, input), + }); + const resend = async (name: string, input: { invitation_id: number; owner_id?: number }) => ({ + name: `resend: ${name}`, + tool: 'resend_invitation' as const, + result: await handleResendInvitation(ctx, input), + }); + return [ + cancel('no access to the named owner', { invitation_id: foreign.id, owner_id: OTHER_USER_ID }), + cancel('missing invitation', { invitation_id: 9999 }), + cancel('foreign invitation', { invitation_id: foreign.id }), + await resend('no access to the named owner', { invitation_id: foreign.id, owner_id: OTHER_USER_ID }), + await resend('missing invitation', { invitation_id: 9999 }), + await resend('foreign invitation', { invitation_id: foreign.id }), + await resend('no longer pending', { invitation_id: answered.id }), + ]; + } + + test('every denial carries mutationState not_applied and the receipt says nothing changed', async () => { + for (const { name, tool, result } of await denials()) { + expect({ name, success: result.success, mutationState: result.mutationState }).toEqual({ + name, + success: false, + mutationState: 'not_applied', + }); + const ledger = new WriteOutcomes(WRITE_TOOLS); + ledger.record(tool, { invitation_id: 1 }, { ...result, disposition: 'failed' }); + expect(ledger.mayHaveMutated).toBe(false); + expect(ledger.finalNotice(RECEIPT_VIEW)).not.toContain('Could not confirm'); + } + }); + }); }); diff --git a/test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts b/test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts new file mode 100644 index 00000000..09077c6f --- /dev/null +++ b/test/services/ai/tool-handlers/sharing-secretary-invitation-scope.test.ts @@ -0,0 +1,422 @@ +// What a secretary's owner_id invitation tools may touch, and when that is decided: only events the owner +// organises personally (not group events the owner merely sees as a member), and write access and event +// details as they are when the invitation is created, not as they were before the recipient lookup +// awaited. Ids are synthetic. +import { beforeEach, describe, expect, test } from 'bun:test'; +import { CalendarProposalRepository } from '../../../../src/database/repositories/calendar-proposal.repository.ts'; +import { ContactRepository } from '../../../../src/database/repositories/contact.repository.ts'; +import { SecretaryRepository } from '../../../../src/database/repositories/secretary.repository.ts'; +import type { SecretaryPermission, SecretaryStatus } from '../../../../src/database/types.ts'; +import { + handleCancelInvitation, + handleGetInvitationStatus, + handleResendInvitation, + handleSendInvitation, +} from '../../../../src/services/ai/tool-handlers/sharing.ts'; +import type { AgentContext, TelegramSender } from '../../../../src/services/ai/types.ts'; +import { createSharingFixture, futureStartAt, type SharingFixture } from './sharing-fixtures.ts'; + +const SECRETARY_ID = 1001; +const OWNER_ID = 2002; +const ANTON_ID = 3001; +const THIRD_PERSON_ID = 7007; +const GROUP_CHAT_ID = -100777; +const OTHER_OWNER_ID = 8008; + +interface Delivery { + inviteeId: number; + text: string; +} + +describe('secretary invitation tools: event scope and access timing', () => { + let fx: SharingFixture; + let secretaryRepo: SecretaryRepository; + let calendarProposalRepo: CalendarProposalRepository; + let contactRepo: ContactRepository; + let deliveries: Delivery[]; + + function grant(permission: SecretaryPermission, status: SecretaryStatus = 'active') { + secretaryRepo.upsert({ owner_id: OWNER_ID, secretary_id: SECRETARY_ID, permission }); + fx.db + .prepare('UPDATE calendar_secretaries SET permission = ?, status = ? WHERE owner_id = ? AND secretary_id = ?') + .run(permission, status, OWNER_ID, SECRETARY_ID); + } + + function ctxOf(callerId: number, overrides: Partial = {}): AgentContext { + const sender: TelegramSender = { + sendMessage: async () => ({ message_id: 1 }), + editMessageText: async () => {}, + sendInvitation: async (inviteeId, text, invitationId) => { + deliveries.push({ inviteeId, text }); + return { message_id: 700 + invitationId }; + }, + sendAsConnectedUser: async () => true, + }; + return fx.makeCtx({ + user: fx.userRepo.findByTelegramId(callerId)!, + chatId: callerId, + messageText: 'invite @anton_a', + contactRepo, + secretary: { secretaryRepo, secretaryForLine: undefined, calendarProposalRepo }, + sender, + deepLinkService: fx.deepLinkService, + botUsername: 'TestBot', + ...overrides, + }); + } + + function personalEvent(title: string): number { + return fx.eventService.createEvent({ + user_id: OWNER_ID, + title, + start_at: futureStartAt(), + timezone: 'UTC', + }).id; + } + + /** An event the owner sees only as a member of the group: someone else created it. */ + function groupEventSeenByOwner(): number { + fx.db.run('INSERT INTO group_members (chat_id, user_id) VALUES (?, ?)', [GROUP_CHAT_ID, OWNER_ID]); + return fx.eventService.createEvent({ + user_id: THIRD_PERSON_ID, + title: 'Group planning', + start_at: futureStartAt(), + timezone: 'UTC', + owner_type: 'group', + group_id: GROUP_CHAT_ID, + created_by: THIRD_PERSON_ID, + }).id; + } + + beforeEach(() => { + fx = createSharingFixture(); + deliveries = []; + secretaryRepo = new SecretaryRepository(fx.db); + calendarProposalRepo = new CalendarProposalRepository(fx.db); + contactRepo = new ContactRepository(fx.db); + fx.userRepo.create({ telegram_id: SECRETARY_ID, username: 'requester_a', first_name: 'Kim', language: 'ru' }); + fx.userRepo.create({ telegram_id: OWNER_ID, first_name: 'Olga', language: 'ru' }); + fx.userRepo.create({ telegram_id: ANTON_ID, username: 'anton_a', first_name: 'Anton' }); + fx.userRepo.create({ telegram_id: THIRD_PERSON_ID, first_name: 'Third' }); + contactRepo.upsert(SECRETARY_ID, 'Anton', undefined, ANTON_ID); + contactRepo.upsert(OWNER_ID, 'Anton', undefined, ANTON_ID); + }); + + describe('a group event the owner sees as a member but does not organise', () => { + test('send_invitation, resend_invitation, cancel_invitation and get_invitation_status are all denied', async () => { + grant('write'); + const eventId = groupEventSeenByOwner(); + // The owner themself can use it (their own, unchanged behaviour) — and that leaves an owner-inviter invitation. + expect(fx.eventService.getEvent(eventId, OWNER_ID)).not.toBeNull(); + const byOwner = await handleSendInvitation(ctxOf(OWNER_ID), { event_id: eventId, invitee_id: ANTON_ID }); + expect(byOwner.success).toBe(true); + const invitation = fx.invitationRepo.getByEvent(eventId)[0]!; + deliveries.length = 0; + + const secretary = ctxOf(SECRETARY_ID); + const sent = await handleSendInvitation(secretary, { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(sent).toMatchObject({ success: false, mutationState: 'not_applied' }); + + const resent = await handleResendInvitation(secretary, { invitation_id: invitation.id, owner_id: OWNER_ID }); + expect(resent.success).toBe(false); + + const cancelled = handleCancelInvitation(secretary, { invitation_id: invitation.id, owner_id: OWNER_ID }); + expect(cancelled.success).toBe(false); + + const roster = handleGetInvitationStatus(secretary, { event_id: eventId, owner_id: OWNER_ID }); + expect(roster.success).toBe(false); + expect(roster.output ?? '').not.toContain('Anton'); + + expect(deliveries).toEqual([]); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(1); + expect(fx.invitationRepo.findById(invitation.id)?.status).toBe('pending'); + }); + + test("the owner's own personal event keeps working for the same secretary", async () => { + grant('write'); + const eventId = personalEvent('Personal'); + const secretary = ctxOf(SECRETARY_ID); + + expect( + (await handleSendInvitation(secretary, { event_id: eventId, owner_id: OWNER_ID, invitee_id: ANTON_ID })) + .success, + ).toBe(true); + const invitation = fx.invitationRepo.getByEvent(eventId)[0]!; + expect(handleGetInvitationStatus(secretary, { event_id: eventId, owner_id: OWNER_ID }).success).toBe(true); + expect( + (await handleResendInvitation(secretary, { invitation_id: invitation.id, owner_id: OWNER_ID })).success, + ).toBe(true); + expect(handleCancelInvitation(secretary, { invitation_id: invitation.id, owner_id: OWNER_ID }).success).toBe( + true, + ); + }); + }); + + // A secretary of one owner who passes the id of another owner's invitation must learn nothing: not + // that it exists, not which event it points to. + describe("an invitation of another owner's calendar", () => { + test('cancel_invitation answers exactly as for an invitation that does not exist, and cancels nothing', async () => { + grant('write'); + fx.userRepo.create({ telegram_id: OTHER_OWNER_ID, first_name: 'Boris', language: 'ru' }); + contactRepo.upsert(OTHER_OWNER_ID, 'Anton', undefined, ANTON_ID); + const foreignEventId = fx.eventService.createEvent({ + user_id: OTHER_OWNER_ID, + title: 'Private plan', + start_at: futureStartAt(), + timezone: 'UTC', + }).id; + await handleSendInvitation(ctxOf(OTHER_OWNER_ID), { event_id: foreignEventId, invitee_id: ANTON_ID }); + const foreign = fx.invitationRepo.getByEvent(foreignEventId)[0]!; + const secretary = ctxOf(SECRETARY_ID); + + const foreignResult = handleCancelInvitation(secretary, { invitation_id: foreign.id, owner_id: OWNER_ID }); + const missingResult = handleCancelInvitation(secretary, { invitation_id: foreign.id + 1000, owner_id: OWNER_ID }); + + expect(foreignResult).toEqual(missingResult); + expect(foreignResult.success).toBe(false); + expect(JSON.stringify(foreignResult)).not.toContain(String(foreignEventId)); + expect(fx.invitationRepo.findById(foreign.id)?.status).toBe('pending'); + }); + }); + + describe('a group event the managed owner created', () => { + function groupEventCreatedByOwner(): number { + fx.db.run('INSERT INTO group_members (chat_id, user_id) VALUES (?, ?)', [GROUP_CHAT_ID, OWNER_ID]); + return fx.eventService.createEvent({ + user_id: OWNER_ID, + title: 'Group planning', + start_at: futureStartAt(), + timezone: 'UTC', + owner_type: 'group', + group_id: GROUP_CHAT_ID, + created_by: OWNER_ID, + }).id; + } + + test('send_invitation with owner_id on a group event the owner sees is an explicit scope denial without a retry hint', async () => { + grant('write'); + const eventId = groupEventCreatedByOwner(); + + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + + expect(result).toMatchObject({ success: false, mutationState: 'not_applied' }); + expect(result.error).toContain('personal events'); + expect(`${result.error} ${result.agentHint ?? ''}`).not.toContain('Retry with owner_id'); + expect(deliveries).toEqual([]); + }); + + test('a group event another member created, which the owner only sees, is a scope denial for owner_id', async () => { + grant('write'); + fx.db.run('INSERT INTO group_members (chat_id, user_id) VALUES (?, ?)', [GROUP_CHAT_ID, OWNER_ID]); + const eventId = fx.eventService.createEvent({ + user_id: THIRD_PERSON_ID, + title: 'Member event', + start_at: futureStartAt(), + timezone: 'UTC', + owner_type: 'group', + group_id: GROUP_CHAT_ID, + created_by: THIRD_PERSON_ID, + }).id; + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(result.error).toContain('personal events'); + expect(`${result.error} ${result.agentHint ?? ''}`).not.toContain('Retry with owner_id'); + }); + + test('a group event of a managed owner is the same denial when owner_id was forgotten', async () => { + grant('write'); + const eventId = groupEventCreatedByOwner(); + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { event_id: eventId, invitee_id: ANTON_ID }); + expect(result.error).toContain('personal events'); + expect(`${result.error} ${result.agentHint ?? ''}`).not.toContain('Retry with owner_id'); + expect(deliveries).toEqual([]); + }); + + test('a personal event of the owner still gets the retry hint when owner_id was forgotten', async () => { + grant('write'); + const eventId = personalEvent('Personal'); + + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { event_id: eventId, invitee_id: ANTON_ID }); + + expect(result.success).toBe(false); + expect(result.agentHint).toContain(`Retry with owner_id ${OWNER_ID}`); + }); + }); + + describe('an event of a second managed owner', () => { + test('owner_id naming the wrong owner still gets the retry hint for the right one', async () => { + grant('write'); + fx.userRepo.create({ telegram_id: OTHER_OWNER_ID, timezone: 'UTC' }); + const record = secretaryRepo.upsert({ + owner_id: OTHER_OWNER_ID, + secretary_id: SECRETARY_ID, + permission: 'write', + }); + secretaryRepo.updateStatus(record.id, 'active'); + const eventId = personalEvent('Personal'); + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId, + owner_id: OTHER_OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(result.agentHint).toContain(`Retry with owner_id ${OWNER_ID}`); + }); + }); + + describe('an event the owner cannot see answers as a missing id', () => { + test('a deleted personal event, with and without owner_id', async () => { + grant('write'); + const eventId = personalEvent('Gone'); + fx.eventService.deleteEvent(eventId, OWNER_ID); + for (const owner of [{}, { owner_id: OWNER_ID }]) { + const gone = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId, + invitee_id: ANTON_ID, + ...owner, + }); + const missing = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId + 1000, + invitee_id: ANTON_ID, + ...owner, + }); + expect(gone).toEqual(missing); + } + }); + }); + + describe('the calendar owner is never invited to their own event by a secretary', () => { + test('by id', async () => { + grant('write'); + const eventId = personalEvent('Own event'); + const result = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: OWNER_ID, + }); + expect(result).toMatchObject({ success: false, mutationState: 'not_applied' }); + expect(result.error).toBe('The calendar owner is the organizer of this event and needs no invitation.'); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(deliveries).toEqual([]); + }); + + test('by a username that resolves to the owner after the lookup', async () => { + grant('write'); + const eventId = personalEvent('Own event'); + let lookups = 0; + const result = await handleSendInvitation( + ctxOf(SECRETARY_ID, { + messageText: 'invite @owner_demo', + resolveUsername: async () => { + lookups++; + return { id: OWNER_ID, firstName: 'Olga', username: 'owner_demo' }; + }, + }), + { event_id: eventId, owner_id: OWNER_ID, invitee_username: 'owner_demo' }, + ); + expect(result).toMatchObject({ success: false, mutationState: 'not_applied' }); + expect(result.error).toBe('The calendar owner is the organizer of this event and needs no invitation.'); + expect(lookups).toBe(1); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(deliveries).toEqual([]); + }); + }); + + describe('write access is re-checked after the awaited recipient lookup', () => { + /** A username lookup that revokes the delegation while it is in flight, then answers. */ + function revokingLookup(): Pick { + return { + resolveUsername: async () => { + grant('write', 'revoked'); + return { id: ANTON_ID, firstName: 'Anton', username: 'anton_a' }; + }, + }; + } + + test('send_invitation creates and delivers nothing when access is revoked during the lookup', async () => { + grant('write'); + const eventId = personalEvent('Revoked mid-send'); + const result = await handleSendInvitation(ctxOf(SECRETARY_ID, revokingLookup()), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_username: 'anton_a', + }); + expect(result).toMatchObject({ success: false, error: 'SECRETARY_ACCESS_DENIED', mutationState: 'not_applied' }); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(deliveries).toEqual([]); + }); + + test('resend_invitation delivers nothing when access is revoked during the lookup', async () => { + grant('write'); + const eventId = personalEvent('Revoked mid-resend'); + await handleSendInvitation(ctxOf(SECRETARY_ID), { event_id: eventId, owner_id: OWNER_ID, invitee_id: ANTON_ID }); + const invitation = fx.invitationRepo.getByEvent(eventId)[0]!; + deliveries.length = 0; + + const result = await handleResendInvitation(ctxOf(SECRETARY_ID, revokingLookup()), { + invitation_id: invitation.id, + owner_id: OWNER_ID, + invitee_username: 'anton_a', + }); + expect(result).toMatchObject({ success: false, error: 'SECRETARY_ACCESS_DENIED' }); + expect(deliveries).toEqual([]); + }); + }); + + describe('the invitation card shows the event as it is when the invitation is created', () => { + function renamingLookup(eventId: number): Pick { + return { + resolveUsername: async () => { + fx.eventService.updateEvent(eventId, OWNER_ID, { title: 'Renamed during lookup' }); + return { id: ANTON_ID, firstName: 'Anton', username: 'anton_a' }; + }, + }; + } + + test('send_invitation', async () => { + grant('write'); + const eventId = personalEvent('Original title'); + const result = await handleSendInvitation(ctxOf(SECRETARY_ID, renamingLookup(eventId)), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_username: 'anton_a', + }); + expect(result.success).toBe(true); + expect(deliveries).toHaveLength(1); + expect(deliveries[0]!.text).toContain('Renamed during lookup'); + expect(deliveries[0]!.text).not.toContain('Original title'); + }); + + test('an event deleted during the lookup gets no invitation', async () => { + grant('write'); + const eventId = personalEvent('Deleted during lookup'); + const result = await handleSendInvitation( + ctxOf(SECRETARY_ID, { + resolveUsername: async () => { + fx.eventService.deleteEvent(eventId, OWNER_ID); + return { id: ANTON_ID, firstName: 'Anton', username: 'anton_a' }; + }, + }), + { event_id: eventId, owner_id: OWNER_ID, invitee_username: 'anton_a' }, + ); + const missing = await handleSendInvitation(ctxOf(SECRETARY_ID), { + event_id: eventId + 1000, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(result).toEqual(missing); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(deliveries).toEqual([]); + }); + }); +}); diff --git a/test/services/ai/tool-handlers/sharing-secretary-invitation.test.ts b/test/services/ai/tool-handlers/sharing-secretary-invitation.test.ts new file mode 100644 index 00000000..b548d305 --- /dev/null +++ b/test/services/ai/tool-handlers/sharing-secretary-invitation.test.ts @@ -0,0 +1,572 @@ +// A write-secretary invites people to an event in the delegating owner's calendar (incident +// 2026-10-31: the event was created with owner_id, then every send_invitation said "Event not found" +// because the handler looked only into the caller's own calendar). Ids are synthetic. +import { beforeEach, describe, expect, test } from 'bun:test'; +import { z } from 'zod'; +import { t } from '../../../../src/config/constants.ts'; +import { CalendarProposalRepository } from '../../../../src/database/repositories/calendar-proposal.repository.ts'; +import { ContactRepository } from '../../../../src/database/repositories/contact.repository.ts'; +import { SecretaryRepository } from '../../../../src/database/repositories/secretary.repository.ts'; +import type { SecretaryPermission, SecretaryStatus } from '../../../../src/database/types.ts'; +import { confirmRecipientApproval } from '../../../../src/services/ai/recipient-confirmation.ts'; +import { buildSystemPrompt } from '../../../../src/services/ai/system-prompt.ts'; +import { executeTool } from '../../../../src/services/ai/tool-executor.ts'; +import { + handleCancelInvitation, + handleGetInvitationStatus, + handleResendInvitation, + handleSendInvitation, +} from '../../../../src/services/ai/tool-handlers/sharing.ts'; +import { getToolDefinitions } from '../../../../src/services/ai/tools.ts'; +import type { AgentContext, TelegramSender } from '../../../../src/services/ai/types.ts'; +import { createSharingFixture, futureStartAt, type SharingFixture } from './sharing-fixtures.ts'; + +const SECRETARY_ID = 1001; +const OWNER_ID = 2002; +const ANTON_ID = 3001; +const YULIA_ID = 3002; +const STRANGER_ID = 4004; +/** An id no tool ever returned: what the model invented in the incident. */ +const INVENTED_ID = 5005005; +const INCIDENT_MESSAGE = 'Настолки поставь в календарь Ольги и пригласи меня, Сэма и Кима'; + +interface DeliveryLog { + invitations: { inviteeId: number; text: string; invitationId: number }[]; + messages: { chatId: number; text: string }[]; + connectedSessionSends: number; +} + +/** A bot sender that reaches everyone (botReachable) or nobody; it records every delivery. */ +function recordingSender(log: DeliveryLog, botReachable: boolean): TelegramSender { + return { + sendMessage: async (chatId, text) => { + log.messages.push({ chatId, text }); + return { message_id: 1 }; + }, + editMessageText: async () => {}, + sendInvitation: async (inviteeId, text, invitationId) => { + log.invitations.push({ inviteeId, text, invitationId }); + return botReachable ? { message_id: 700 + invitationId } : null; + }, + sendAsConnectedUser: async () => { + log.connectedSessionSends++; + return true; + }, + }; +} + +describe('send_invitation on behalf of the calendar owner (secretary)', () => { + let fx: SharingFixture; + let secretaryRepo: SecretaryRepository; + let calendarProposalRepo: CalendarProposalRepository; + let contactRepo: ContactRepository; + let log: DeliveryLog; + + /** Sets the delegation to exactly this permission and status (the repository never demotes an active record). */ + function grant(permission: SecretaryPermission, status: SecretaryStatus = 'active', secretaryId = SECRETARY_ID) { + secretaryRepo.upsert({ owner_id: OWNER_ID, secretary_id: secretaryId, permission }); + fx.db + .prepare('UPDATE calendar_secretaries SET permission = ?, status = ? WHERE owner_id = ? AND secretary_id = ?') + .run(permission, status, OWNER_ID, secretaryId); + } + + function secretaryCtx(overrides: Partial = {}, callerId = SECRETARY_ID): AgentContext { + return fx.makeCtx({ + user: fx.userRepo.findByTelegramId(callerId)!, + chatId: callerId, + messageText: INCIDENT_MESSAGE, + contactRepo, + secretary: { secretaryRepo, secretaryForLine: undefined, calendarProposalRepo }, + sender: recordingSender(log, true), + deepLinkService: fx.deepLinkService, + botUsername: 'TestBot', + ...overrides, + }); + } + + function ownersEvent(title = 'Board games'): number { + const startAt = futureStartAt(); + return fx.eventService.createEvent({ + user_id: OWNER_ID, + title, + start_at: startAt, + end_at: new Date(Date.parse(startAt) + 3_600_000).toISOString(), + timezone: 'UTC', + }).id; + } + + beforeEach(() => { + fx = createSharingFixture(); + log = { invitations: [], messages: [], connectedSessionSends: 0 }; + secretaryRepo = new SecretaryRepository(fx.db); + calendarProposalRepo = new CalendarProposalRepository(fx.db); + contactRepo = new ContactRepository(fx.db); + fx.userRepo.create({ telegram_id: SECRETARY_ID, username: 'requester_a', first_name: 'Kim', language: 'ru' }); + fx.userRepo.create({ telegram_id: OWNER_ID, first_name: 'Olga', language: 'ru' }); + fx.userRepo.create({ telegram_id: ANTON_ID, first_name: 'Anton' }); + fx.userRepo.create({ telegram_id: YULIA_ID, first_name: 'Yulia' }); + fx.userRepo.create({ telegram_id: STRANGER_ID, first_name: 'Stranger' }); + contactRepo.upsert(SECRETARY_ID, 'Anton', undefined, ANTON_ID); + contactRepo.upsert(SECRETARY_ID, 'Yulia', undefined, YULIA_ID); + }); + + test('replays the incident: create in the owner calendar, then invite me and two contacts', async () => { + grant('write'); + const ctx = secretaryCtx(); + const startAt = futureStartAt(); + const created = await executeTool(ctx, 'create_event', { + title: 'Board games', + start_at: startAt, + end_at: new Date(Date.parse(startAt) + 3_600_000).toISOString(), + owner_id: OWNER_ID, + scope: 'personal', + }); + expect(created.success).toBe(true); + const eventId = fx.eventRepo.findLatestCreatedByUser(OWNER_ID)!.id; + + for (const inviteeId of [SECRETARY_ID, ANTON_ID, YULIA_ID]) { + const sent = await executeTool(ctx, 'send_invitation', { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: inviteeId, + }); + expect(sent.error).toBeUndefined(); + expect(sent.success).toBe(true); + } + + const rows = fx.invitationRepo.getByEvent(eventId); + expect(rows.map((row) => row.invitee_id).sort()).toEqual([SECRETARY_ID, ANTON_ID, YULIA_ID].sort()); + // The organizer on every row is the event owner: cards, RSVP notices and the roster key off it. + expect(rows.every((row) => row.inviter_id === OWNER_ID)).toBe(true); + expect(log.invitations.map((d) => d.inviteeId).sort()).toEqual([SECRETARY_ID, ANTON_ID, YULIA_ID].sort()); + // Every card names the owner as the sender and organizer, and lists the requester as a plain invitee. + for (const delivery of log.invitations) { + expect(delivery.text).toContain(`приглашение от Olga`); + expect(delivery.text).toContain('Olga — организатор'); + } + // The requester is not added to his own address book by inviting himself. + expect(contactRepo.findByTelegramId(SECRETARY_ID, SECRETARY_ID)).toBeNull(); + }); + + test('the same call without owner_id still finds nothing and creates no invitation', async () => { + grant('write'); + const eventId = ownersEvent(); + const result = await handleSendInvitation(secretaryCtx(), { event_id: eventId, invitee_id: ANTON_ID }); + expect(result.success).toBe(false); + expect(result.error).toBe('Event not found'); + expect(result.mutationState).toBe('not_applied'); + // The model is told where the event is: the calendar this caller manages, not a stranger's. + expect(result.agentHint).toContain(`owner_id ${OWNER_ID}`); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(log.invitations).toHaveLength(0); + }); + + test('a stranger learns nothing about whose calendar holds the event', async () => { + const eventId = ownersEvent(); + const result = await handleSendInvitation(secretaryCtx({}, STRANGER_ID), { + event_id: eventId, + invitee_id: ANTON_ID, + }); + expect(result).toMatchObject({ success: false, error: 'Event not found' }); + expect(result.agentHint).toBeUndefined(); + }); + + test('a read-only secretary cannot invite into the owner calendar', async () => { + grant('read'); + const eventId = ownersEvent(); + const result = await handleSendInvitation(secretaryCtx(), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(result).toMatchObject({ success: false, error: 'SECRETARY_ACCESS_DENIED', mutationState: 'not_applied' }); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(log.invitations).toHaveLength(0); + }); + + test('a stranger, a pending secretary and a missing secretary capability are denied', async () => { + const eventId = ownersEvent(); + const input = { event_id: eventId, owner_id: OWNER_ID, invitee_id: ANTON_ID }; + + expect(await handleSendInvitation(secretaryCtx({}, STRANGER_ID), input)).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + grant('write', 'pending'); + expect(await handleSendInvitation(secretaryCtx(), input)).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + grant('write', 'revoked'); + expect(await handleSendInvitation(secretaryCtx(), input)).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + expect(await handleSendInvitation(secretaryCtx({ secretary: undefined }), input)).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(log.invitations).toHaveLength(0); + }); + + test('an invented numeric id is refused even with write access', async () => { + grant('write'); + const eventId = ownersEvent(); + const result = await executeTool(secretaryCtx(), 'send_invitation', { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: INVENTED_ID, + }); + expect(result.success).toBe(false); + expect(result.error).toBe(t('ru').aiTools.meta.recipientUnverified); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + expect(log.invitations).toHaveLength(0); + }); + + describe("a bare numeric id that needs the secretary's own confirmation tap", () => { + function withKeyboard(): { ctx: AgentContext; keyboards: number[]; tokens: string[] } { + const keyboards: number[] = []; + const tokens: string[] = []; + const sender = { + ...recordingSender(log, true), + sendMessageWithKeyboard: async ( + chatId: number, + _text: string, + keyboard: { toJSON(): { inline_keyboard?: { callback_data?: string }[][] } }, + ) => { + keyboards.push(chatId); + for (const row of keyboard.toJSON().inline_keyboard ?? []) + for (const b of row) tokens.push(b.callback_data ?? ''); + return { message_id: 2 }; + }, + } as unknown as TelegramSender; + return { ctx: secretaryCtx({ sender }), keyboards, tokens }; + } + + test("the hint offers no pick_users, which cannot invite into the owner's calendar", async () => { + grant('write'); + const eventId = ownersEvent(); + const { ctx, keyboards } = withKeyboard(); + const result = await handleSendInvitation(ctx, { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: INVENTED_ID, + }); + expect(keyboards).toEqual([SECRETARY_ID]); + expect(result.agentHint).toContain('Wait for the actual confirmation callback; it says how to send'); + expect(result.agentHint).not.toContain('pick_users'); + }); + + test('after the tap, the secretary sends for the owner with force=true and owner_id; without the tap nothing is sent', async () => { + grant('write'); + const eventId = ownersEvent(); + const { ctx, tokens } = withKeyboard(); + const send = { event_id: eventId, owner_id: OWNER_ID, invitee_id: INVENTED_ID, force: true }; + expect((await handleSendInvitation(ctx, send)).success).toBe(false); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + await handleSendInvitation(ctx, { ...send, force: undefined }); + const token = tokens.find((data) => data.startsWith('ric:'))?.slice('ric:'.length) ?? ''; + expect(confirmRecipientApproval(token, SECRETARY_ID, SECRETARY_ID)).not.toBeNull(); + const sent = await handleSendInvitation(ctx, send); + expect(sent.success).toBe(true); + expect(fx.invitationRepo.getByEvent(eventId).map((row) => row.invitee_id)).toEqual([INVENTED_ID]); + expect((await handleSendInvitation(ctx, send)).success).toBe(false); + }); + + test("the owner's own invitation keeps the hint with pick_users and remembers no owner", async () => { + const eventId = ownersEvent(); + const tokens: string[] = []; + const sender = { + ...recordingSender(log, true), + sendMessageWithKeyboard: async ( + _chatId: number, + _text: string, + keyboard: { toJSON(): { inline_keyboard?: { callback_data?: string }[][] } }, + ) => { + for (const row of keyboard.toJSON().inline_keyboard ?? []) + for (const b of row) tokens.push(b.callback_data ?? ''); + return { message_id: 2 }; + }, + } as unknown as TelegramSender; + const result = await handleSendInvitation(secretaryCtx({ sender }, OWNER_ID), { + event_id: eventId, + invitee_id: INVENTED_ID, + }); + expect(result.agentHint).toContain('pick_users'); + const token = tokens.find((data) => data.startsWith('ric:'))?.slice('ric:'.length) ?? ''; + const approval = confirmRecipientApproval(token, OWNER_ID, OWNER_ID); + expect(approval).toMatchObject({ eventId, recipientId: INVENTED_ID }); + expect(approval?.ownerId).toBeUndefined(); + }); + + test('the confirmation the secretary taps remembers the owner it was for', async () => { + grant('write'); + const eventId = ownersEvent(); + const { ctx, tokens } = withKeyboard(); + await handleSendInvitation(ctx, { event_id: eventId, owner_id: OWNER_ID, invitee_id: INVENTED_ID }); + const token = tokens.find((data) => data.startsWith('ric:'))?.slice('ric:'.length) ?? ''; + expect(confirmRecipientApproval(token, SECRETARY_ID, SECRETARY_ID)).toMatchObject({ + eventId, + recipientId: INVENTED_ID, + ownerId: OWNER_ID, + }); + }); + }); + + test('inviting the calendar owner is rejected with a reason, not "cannot invite yourself"', async () => { + grant('write'); + const eventId = ownersEvent(); + const result = await handleSendInvitation(secretaryCtx({ messageText: `invite ${OWNER_ID}` }), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: OWNER_ID, + }); + expect(result.success).toBe(false); + expect(result.mutationState).toBe('not_applied'); + expect(result.error).toContain('organizer'); + expect(fx.invitationRepo.getByEvent(eventId)).toHaveLength(0); + }); + + test('an unknown @username opens the picker for the owner but not for a secretary (the picker cannot invite there)', async () => { + grant('write'); + const eventId = ownersEvent(); + const pickerRequests: number[] = []; + const withPicker: TelegramSender = { + ...recordingSender(log, true), + sendUserPicker: async (_chatId, _text, requestId) => { + pickerRequests.push(requestId); + return { message_id: 9 }; + }, + }; + const unknownPerson = { + messageText: 'invite @nobody_here', + sender: withPicker, + resolveUsername: async () => null, + } satisfies Partial; + const input = { event_id: eventId, invitee_username: 'nobody_here' }; + + const forSecretary = await handleSendInvitation(secretaryCtx(unknownPerson), { ...input, owner_id: OWNER_ID }); + expect(forSecretary.success).toBe(false); + expect(forSecretary.agentHint).toContain('pick_users cannot invite into'); + expect(pickerRequests).toEqual([]); + + const forOwner = await handleSendInvitation(secretaryCtx(unknownPerson, OWNER_ID), input); + expect(forOwner.awaitingInput).toEqual({ kind: 'chat' }); + expect(pickerRequests).toEqual([eventId]); + }); + + test('a failed bot delivery reaches the secretary as a link, never the connected account of anyone', async () => { + grant('write'); + const eventId = ownersEvent(); + const result = await handleSendInvitation(secretaryCtx({ sender: recordingSender(log, false) }), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: ANTON_ID, + }); + expect(result.success).toBe(true); + expect(log.connectedSessionSends).toBe(0); + expect(log.messages.map((m) => m.chatId)).toEqual([SECRETARY_ID]); + expect(log.messages[0]!.text).toContain('t.me/TestBot'); + expect(result.effect).toEqual({ kind: 'invitation', delivery: 'manual_forward' }); + }); + + test('the owner flow keeps using the connected account of the inviter', async () => { + const eventId = ownersEvent(); + contactRepo.upsert(OWNER_ID, 'Anton', undefined, ANTON_ID); + const ctx = secretaryCtx({ sender: recordingSender(log, false) }, OWNER_ID); + const result = await handleSendInvitation(ctx, { event_id: eventId, invitee_id: ANTON_ID }); + expect(result.success).toBe(true); + expect(log.connectedSessionSends).toBe(1); + }); + + test('cancel_invitation and resend_invitation act for the owner only with write access', async () => { + grant('write'); + const eventId = ownersEvent(); + const ctx = secretaryCtx(); + await handleSendInvitation(ctx, { event_id: eventId, owner_id: OWNER_ID, invitee_id: ANTON_ID }); + await handleSendInvitation(ctx, { event_id: eventId, owner_id: OWNER_ID, invitee_id: YULIA_ID }); + const [toResend, toCancel] = fx.invitationRepo.getByEvent(eventId); + + expect(handleCancelInvitation(ctx, { invitation_id: toCancel!.id })).toMatchObject({ success: false }); + expect(await handleResendInvitation(ctx, { invitation_id: toResend!.id })).toMatchObject({ success: false }); + + log.invitations.length = 0; + const resent = await handleResendInvitation(ctx, { invitation_id: toResend!.id, owner_id: OWNER_ID }); + expect(resent.success).toBe(true); + expect(log.invitations.map((d) => d.inviteeId)).toEqual([toResend!.invitee_id]); + expect(log.connectedSessionSends).toBe(0); + + expect(handleCancelInvitation(ctx, { invitation_id: toCancel!.id, owner_id: OWNER_ID }).success).toBe(true); + expect(fx.invitationRepo.findById(toCancel!.id)?.status).toBe('cancelled'); + + grant('read'); + expect(handleCancelInvitation(ctx, { invitation_id: toResend!.id, owner_id: OWNER_ID })).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + expect(fx.invitationRepo.findById(toResend!.id)?.status).toBe('pending'); + }); + + test('get_invitation_status shows the owner roster to a secretary with owner_id', async () => { + grant('write'); + const eventId = ownersEvent('Board games roster'); + await handleSendInvitation(secretaryCtx(), { event_id: eventId, owner_id: OWNER_ID, invitee_id: ANTON_ID }); + + const without = handleGetInvitationStatus(secretaryCtx(), { event_id: eventId }); + expect(without.success).toBe(false); + + const withOwner = handleGetInvitationStatus(secretaryCtx(), { event_id: eventId, owner_id: OWNER_ID }); + expect(withOwner.success).toBe(true); + expect(withOwner.output).toContain('Anton'); + + grant('read'); + expect(handleGetInvitationStatus(secretaryCtx(), { event_id: eventId, owner_id: OWNER_ID }).success).toBe(true); + grant('write', 'revoked'); + expect(handleGetInvitationStatus(secretaryCtx(), { event_id: eventId, owner_id: OWNER_ID })).toMatchObject({ + success: false, + error: 'SECRETARY_ACCESS_DENIED', + }); + }); + + test('get_invitation_status with owner_id never exposes an event another person organises, even one that invited the owner', () => { + const THIRD_PERSON_ID = 7007; + fx.userRepo.create({ telegram_id: THIRD_PERSON_ID, first_name: 'Third' }); + const foreignEvent = fx.eventService.createEvent({ + user_id: THIRD_PERSON_ID, + title: 'Third party dinner', + start_at: futureStartAt(), + timezone: 'UTC', + }); + expect(fx.invitationService.sendInvitation(foreignEvent.id, THIRD_PERSON_ID, OWNER_ID).success).toBe(true); + fx.invitationService.sendInvitation(foreignEvent.id, THIRD_PERSON_ID, ANTON_ID); + + for (const permission of ['read', 'write'] as const) { + grant(permission); + const result = handleGetInvitationStatus(secretaryCtx(), { event_id: foreignEvent.id, owner_id: OWNER_ID }); + expect(result.success).toBe(false); + expect(result.output ?? '').not.toContain('Anton'); + expect(result.agentHint ?? '').not.toContain(String(THIRD_PERSON_ID)); + } + + // The owner reading it as an invitee keeps working (the invitee path is the owner's own right). + const asOwner = handleGetInvitationStatus(secretaryCtx({}, OWNER_ID), { event_id: foreignEvent.id }); + expect(asOwner.success).toBe(true); + }); + + test("get_invitation_status for the owner's own event names the owner as organizer and the secretary as requester", () => { + grant('read'); + const eventId = ownersEvent('Roster identity'); + fx.invitationService.sendInvitation(eventId, OWNER_ID, ANTON_ID); + + const result = handleGetInvitationStatus(secretaryCtx(), { event_id: eventId, owner_id: OWNER_ID }); + expect(result.success).toBe(true); + expect(result.agentHint).toContain(`"organizer_id":${OWNER_ID}`); + expect(result.agentHint).toContain(`"requester_id":${SECRETARY_ID}`); + expect(result.agentHint).toContain(`"calendar_owner_id":${OWNER_ID}`); + expect(result.agentHint).toContain(`"invitee_ids":[${ANTON_ID}]`); + // The secretary reads it as the organizer's roster, not as one of its invitees. + expect(result.output).not.toContain('Organizer'); + }); + + describe('a contact row id passed as invitee_id', () => { + function contactRowId(ownerOfBook: number, name: string, telegramId?: number, username?: string): number { + return contactRepo.upsert(ownerOfBook, name, username, telegramId).id; + } + + test('the secretary is sent to the real telegram_id or an @username, never to pick_users', async () => { + grant('write'); + const eventId = ownersEvent(); + const withTelegramId = contactRowId(SECRETARY_ID, 'Maria', 3003); + const withoutTelegramId = contactRowId(SECRETARY_ID, 'Katya', undefined, 'katya_k'); + const noUsernameEither = contactRowId(SECRETARY_ID, 'Dmitry'); + + for (const rowId of [withTelegramId, withoutTelegramId, noUsernameEither]) { + const result = await handleSendInvitation(secretaryCtx(), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: rowId, + }); + expect(result.success).toBe(false); + expect(result.mutationState).toBe('not_applied'); + // Never advice to use the picker; the explanatory "does not work" note may name it. + expect(result.agentHint).not.toMatch(/use pick_users|or pick_users|pick_users with/); + } + const hinted = await handleSendInvitation(secretaryCtx(), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: withTelegramId, + }); + expect(hinted.agentHint).toContain('invitee_id 3003'); + const named = await handleSendInvitation(secretaryCtx(), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: withoutTelegramId, + }); + expect(named.agentHint).toContain('invitee_username katya_k'); + const nameless = await handleSendInvitation(secretaryCtx(), { + event_id: eventId, + owner_id: OWNER_ID, + invitee_id: noUsernameEither, + }); + expect(nameless.agentHint).toContain('an @username the user gives you for that person'); + }); + + test('the owner keeps the pick_users advice for their own event', async () => { + const eventId = ownersEvent(); + const withTelegramId = contactRowId(OWNER_ID, 'Maria', 3003); + const withoutTelegramId = contactRowId(OWNER_ID, 'Katya', undefined, 'katya_k'); + const ownerCtx = secretaryCtx({}, OWNER_ID); + + const first = await handleSendInvitation(ownerCtx, { event_id: eventId, invitee_id: withTelegramId }); + expect(first.agentHint).toContain('invitee_id 3003'); + expect(first.agentHint).toContain('pick_users'); + const second = await handleSendInvitation(ownerCtx, { event_id: eventId, invitee_id: withoutTelegramId }); + expect(second.agentHint).toContain('invitee_username katya_k'); + expect(second.agentHint).toContain(`pick_users with event_id ${eventId}`); + }); + }); + + test('the prompt tells a secretary the exact invitee_id for "me", and the real tool call it describes works', async () => { + grant('write'); + // executeTool throttles identical writes for 5s process-wide, and every test's database starts at event 1. + ownersEvent('Placeholder'); + const eventId = ownersEvent(); + const ctx = secretaryCtx({ + secretary: { + secretaryRepo, + secretaryForLine: `User ${OWNER_ID} (read+write)`, + calendarProposalRepo, + }, + }); + const prompt = buildSystemPrompt(ctx); + const meId = Number(prompt.match(/invitee_id (\d+) is the user's own Telegram ID/)?.[1]); + expect(meId).toBe(SECRETARY_ID); + expect(prompt).toContain('SAME owner_id'); + expect(prompt).toContain('never write a telegram_id no tool returned'); + + const sent = await executeTool(ctx, 'send_invitation', { event_id: eventId, owner_id: OWNER_ID, invitee_id: meId }); + expect(sent.success).toBe(true); + expect(fx.invitationRepo.getByEvent(eventId)).toMatchObject([{ invitee_id: SECRETARY_ID, inviter_id: OWNER_ID }]); + }); + + test('a user without secretary access gets no invitation-on-behalf guidance and no own id', () => { + const prompt = buildSystemPrompt(secretaryCtx({ secretary: undefined })); + expect(prompt).not.toContain('SAME owner_id'); + expect(prompt).not.toContain("the user's own Telegram ID"); + }); + + test('every invitation tool accepts owner_id with the one shared description', () => { + const ownerIdParameters = z.object({ + properties: z.object({ owner_id: z.object({ description: z.string() }) }), + }); + const tools = getToolDefinitions('text').filter((tool) => tool.type === 'function'); + const descriptions = ['send_invitation', 'get_invitation_status', 'cancel_invitation', 'resend_invitation'].map( + (name) => { + const tool = tools.find((candidate) => candidate.function.name === name); + return ownerIdParameters.parse(tool?.function.parameters).properties.owner_id.description; + }, + ); + expect(new Set(descriptions).size).toBe(1); + }); +}); diff --git a/test/services/ai/validation-terminal.test.ts b/test/services/ai/validation-terminal.test.ts index 178a8ef0..4e5cf303 100644 --- a/test/services/ai/validation-terminal.test.ts +++ b/test/services/ai/validation-terminal.test.ts @@ -187,7 +187,7 @@ describe('validation rejection is terminal for unverified prose (#284)', () => { ); const result = await new CalendarBotAgent({}, sender, { streamImpl: script.impl }).run(ctx); expectNoRejectedProse(result.responseText); - expect(result.responseText).toContain('Completed:'); + expect(result.responseText).toContain('Created: event'); expect(result.toolCalls.filter((call) => call.name === 'create_event')).toHaveLength(1); expect(result.toolResults[0]?.success).toBe(true); const count = db.query<{ n: number }, []>('SELECT COUNT(*) AS n FROM events').get(); @@ -510,7 +510,7 @@ describe('re-validation accepts answers grounded in the same run (#492)', () => ); const result = await new CalendarBotAgent({}, sender, { streamImpl: script.impl }).run(ctx); - expect(result.responseText).toContain('Выполнено: Создание события'); + expect(result.responseText).toContain('Создано: событие «Пробежка»'); expect(result.responseText).not.toContain('22 сентября'); expect(script.counts.validator).toBe(0); const created = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE title = 'Пробежка'").get(); @@ -528,7 +528,7 @@ describe('re-validation accepts answers grounded in the same run (#492)', () => ); const result = await new CalendarBotAgent({}, sender, { streamImpl: script.impl }).run(ctx); - expect(result.responseText).toContain('Выполнено: Создание события'); + expect(result.responseText).toContain('Создано: событие «Пробежка»'); const created = db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM events WHERE title = 'Пробежка'").get(); expect(created?.n).toBe(1); }); @@ -545,8 +545,8 @@ describe('re-validation accepts answers grounded in the same run (#492)', () => ); const result = await new CalendarBotAgent({}, sender, { streamImpl: script.impl }).run(ctx); - expect(result.responseText).toContain('Выполнено: Создание события'); - expect(result.responseText).toContain('Не выполнено: Удаление события'); + expect(result.responseText).toContain('Создано: событие «Пробежка»'); + expect(result.responseText).toContain('Не удалено: событие'); }); test('a supplement backed by its own reads is still delivered (#515)', async () => { diff --git a/test/services/ai/write-outcomes.test.ts b/test/services/ai/write-outcomes.test.ts index 637d8548..357e934f 100644 --- a/test/services/ai/write-outcomes.test.ts +++ b/test/services/ai/write-outcomes.test.ts @@ -1,16 +1,36 @@ /** Structured evidence tests: prose and skipped calls cannot prove write success. */ -import { expect, test } from 'bun:test'; +import { describe, expect, test } from 'bun:test'; import { WRITE_TOOLS } from '../../../src/services/ai/tool-executor.ts'; import { WriteOutcomes } from '../../../src/services/ai/write-outcomes.ts'; +import type { ReceiptView } from '../../../src/services/ai/write-receipt.ts'; + +/** A requester (1001) who has no contacts and manages no calendar: nothing is named by id. */ +function view(language: string, overrides: Partial = {}): ReceiptView { + return { + language, + timezone: 'UTC', + hideTargets: false, + requesterId: 1001, + now: new Date('2026-10-31T09:00:00Z'), + personLabel: () => null, + personKey: ({ id, username }) => (id === null ? `@${username}` : `id:${id}`), + calendarOwnerName: () => null, + hasCalendarAccess: () => false, + ...overrides, + }; +} +const en = view('en'); +const rejected = { success: false, disposition: 'failed', mutationState: 'not_applied' } as const; +const unconfirmed = { success: false, disposition: 'failed' } as const; test('correction clears only the same operation and target', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); ledger.record('delete_event', { event_id: '1', owner_id: 123 }, { success: false, disposition: 'failed' }); ledger.record('update_event', { event_id: 1 }, { success: true, disposition: 'executed' }); ledger.record('delete_event', { event_id: 2 }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toContain('Not completed: Delete event'); + expect(ledger.finalNotice(en)).toContain('Could not confirm the deletion: event'); ledger.record('delete_event', { event_id: 1, owner_id: 123 }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); test('invitations distinguish recipients and never use output prose', () => { @@ -22,9 +42,28 @@ test('invitations distinguish recipients and never use output prose', () => { }; ledger.record('send_invitation', { event_id: 1, invitee_id: '2' }, failure); ledger.record('send_invitation', { event_id: '1', invitee_id: 3 }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toContain('Not completed: Send invitation'); + const notice = ledger.finalNotice(en) ?? ''; + expect(notice).toContain('Could not confirm that the invitation to the event went through: 1 person.'); + expect(notice).not.toContain('Successfully'); ledger.record('send_invitation', { event_id: '1', invitee_id: 2 }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toContain('duplicate'); +}); + +test('a corrected invitation retry that adds owner_id supersedes the rejected call (event ids are global)', () => { + const ledger = new WriteOutcomes(WRITE_TOOLS); + ledger.record('send_invitation', { event_id: 5, invitee_id: 77 }, rejected); + expect(ledger.finalNotice(en)).toContain('was not sent: 1 person'); + ledger.record( + 'send_invitation', + { event_id: 5, invitee_id: '77', owner_id: 2002 }, + { + success: true, + disposition: 'executed', + mutationState: 'confirmed', + effect: { kind: 'invitation', delivery: 'delivered' }, + }, + ); + expect(ledger.finalNotice(en)).toBeNull(); }); test('a delivered invitation does not replace a normal successful final response with execution jargon', () => { @@ -39,10 +78,10 @@ test('a delivered invitation does not replace a normal successful final response effect: { kind: 'invitation', delivery: 'delivered' }, }, ); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); -test('an interrupted successful run reports facts without the attempt-debug preamble', () => { +test('an interrupted successful run reports facts without any attempt framing', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); ledger.record( 'create_event', @@ -59,12 +98,11 @@ test('an interrupted successful run reports facts without the attempt-debug prea effect: { kind: 'invitation', delivery: 'delivered' }, }, ); - const notice = ledger.finalNotice('ru', false, true) ?? ''; - expect(notice).toContain('Выполнено: Создание события'); - expect(notice).toContain('Приглашение доставлено'); - expect(notice).toContain('Запрос прерван'); - expect(notice).not.toContain('Это отдельные попытки выполнения'); - expect(notice).not.toContain('Попытка 1'); + expect(ledger.finalNotice(view('ru'), true)?.split('\n')).toEqual([ + 'Создано: событие «Walk».', + 'Приглашение на событие отправлено: 1 человек.', + 'Запрос прерван. Часть действий могла уже выполниться; автоматического повтора не будет.', + ]); }); test('read and conversation controls do not become failed writes', () => { @@ -72,58 +110,49 @@ test('read and conversation controls do not become failed writes', () => { for (const operation of ['get_event', 'ask_user', 'supplement_skip', 'end_conversation']) { ledger.record(operation, {}, { success: false, disposition: 'failed' }); } - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); test('recipient ID is authoritative when a corrected invitation also supplies a username', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); - ledger.record('send_invitation', { event_id: 1, invitee_id: '2' }, { success: false, disposition: 'failed' }); + ledger.record('send_invitation', { event_id: 1, invitee_id: '2' }, rejected); ledger.record( 'send_invitation', { event_id: '1', invitee_id: 2, invitee_username: 'synthetic' }, { success: true, disposition: 'executed' }, ); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); test('unrelated update fields cannot erase failed intent', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); - ledger.record( - 'update_event', - { event_id: 42, title: 123, start_at: 'bad' }, - { success: false, disposition: 'failed' }, - ); + ledger.record('update_event', { event_id: 42, title: 123, start_at: 'bad' }, rejected); ledger.record('update_event', { event_id: 42, location: 'Office' }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toContain('title'); - expect(ledger.finalNotice('en')).toContain('start'); + expect(ledger.finalNotice(en)).toContain('Not updated: event, fields: title, start time'); ledger.record('update_event', { event_id: 42, title: 'Fixed' }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toContain('Not completed:'); + expect(ledger.finalNotice(en)).toContain('Not updated: event, fields: start time'); ledger.record( 'update_event', { event_id: 42, start_at: '2030-01-01T10:00:00Z' }, { success: true, disposition: 'executed' }, ); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); test('a place the model claims is never reported as written (#620)', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); const claimed = { location_verified: 1, resolved_address: 'Far Away 1', venue_name: 'Far Away Venue' }; - ledger.record( - 'update_event', - { event_id: 42, location: 'Office', ...claimed }, - { success: false, disposition: 'failed' }, - ); + ledger.record('update_event', { event_id: 42, location: 'Office', ...claimed }, rejected); ledger.record('update_event', { event_id: 42, location: 'Office' }, { success: true, disposition: 'executed' }); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); ledger.record( 'update_event', { event_id: 43, title: 'Lunch', ...claimed }, { success: true, disposition: 'executed' }, ); - expect(ledger.summary('en', false)?.split('\n')).toEqual([ - 'Completed: Update event #42 (location)', - 'Completed: Update event #43 (title)', + expect(ledger.summary(en)?.split('\n')).toEqual([ + 'Updated: event, fields: location.', + 'Updated: event, fields: title.', ]); }); @@ -135,23 +164,23 @@ test('safe localized targets never derive authoritative reasons from free-form e { event_id: 43 }, { success: false, disposition: 'failed', error: 'Not found\n at secret(provider)' }, ); - expect(ledger.finalNotice('en')).toContain('#42'); - expect(ledger.finalNotice('en')).toContain('#43'); - expect(ledger.finalNotice('en')).toContain('completion not confirmed'); - expect(ledger.finalNotice('en')).not.toContain('permission denied'); - expect(ledger.finalNotice('en')).not.toContain('secret'); - expect(ledger.finalNotice('ru')).toContain('Удаление'); - expect(ledger.finalNotice('ru')).not.toContain('delete_event'); + const notice = ledger.finalNotice(en) ?? ''; + expect(notice).toContain('Could not confirm the deletion: event.'); + expect(notice).not.toMatch(/#\d|42|43/); + expect(notice).not.toContain('permission denied'); + expect(notice).not.toContain('secret'); + expect(ledger.finalNotice(view('ru'))).toContain('Не удалось подтвердить удаление'); + expect(ledger.finalNotice(view('ru'))).not.toContain('delete_event'); }); test('skips never overwrite actual results or count as completion', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); ledger.record('delete_event', { event_id: 1 }, { success: true, disposition: 'skipped' }); - expect(ledger.finalNotice('en')).toContain('skipped'); - expect(ledger.finalNotice('en')).not.toContain('Completed:'); + expect(ledger.finalNotice(en)).toContain('skipped'); + expect(ledger.finalNotice(en)).not.toContain('Deleted:'); ledger.record('delete_event', { event_id: 1 }, { success: true, disposition: 'executed' }); ledger.record('delete_event', { event_id: 1 }, { success: true, disposition: 'skipped' }); - expect(ledger.finalNotice('en')).toBeNull(); + expect(ledger.finalNotice(en)).toBeNull(); }); test('successful create of another intent never erases a failed create', () => { @@ -162,15 +191,15 @@ test('successful create of another intent never erases a failed create', () => { { title: 'Second', start_at: '2030-01-01' }, { success: true, disposition: 'executed' }, ); - expect(ledger.finalNotice('en')).toContain('Not completed: Create event'); + expect(ledger.finalNotice(en)).toContain('Could not confirm creation: event “First”'); }); test('waiting UI is never recorded as a completed write alongside a failure', () => { const ledger = new WriteOutcomes(WRITE_TOOLS); - ledger.record('delete_event', { event_id: 42 }, { success: false, disposition: 'failed' }); + ledger.record('delete_event', { event_id: 42 }, unconfirmed); ledger.record('ask_user', {}, { success: true, disposition: 'waiting' }); ledger.record('pick_users', { event_id: 42 }, { success: true, disposition: 'waiting' }); - expect(ledger.finalNotice('en')).not.toContain('Completed:'); + expect(ledger.finalNotice(en)).not.toContain('Deleted:'); }); test('unsafe identifiers and stack payloads never reach the notice', () => { @@ -180,44 +209,136 @@ test('unsafe identifiers and stack payloads never reach the notice', () => { { event_id: '' }, { success: false, disposition: 'failed', error: 'Error: provider secret\n at internal.ts:42' }, ); - expect(ledger.finalNotice('en')).toContain('Not completed: Delete event'); - expect(ledger.finalNotice('en')).not.toContain('secret'); - expect(ledger.finalNotice('en')).not.toContain('