From 4721621eef8877544f005e66767ada55eb9cdaa0 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 14:33:48 -0800 Subject: [PATCH 1/5] Web app: read again on the server's change hints instead of polling The server already says on the conversation events socket when something the person sees outside their conversations changed (dataChanged), but the app never asked for it and polled instead: about 120 requests a minute from one idle conversation tab, all day in OpenBot Desktop, with several polls reading lists that only grow to their last page. - The socket asks for data-changed, and each hint marks stale the reads of its kind (lib/live/apply-hints.ts); one about one Bot reaches only that Bot's reads. Hint-fed reads keep their answer for five minutes and poll only for a kind the server does not say it sends (deployment.dataChanged), slowly (60 s) and never while the page is hidden. A reopened socket or a resync marks every hint-fed read stale. - Approvals: the inbox's seven lists become the live queue (approvals and questions, hint-fed), the settings (preferences, rules, organization settings: read once, refreshed by their writes) and the conversation grants. Carry-on after a decision is read from the hint-fed queue, with a timer for its ten-minute limit, instead of a 2 s/10 s poll. An approval card no longer reads seven lists on mount. - Computer control: read on the computers hint, not every second, and the conversation reads it only while the Computer is open as a sheet over it. A server without the hint keeps the old 1 s read while someone watches. - Run histories (a routine's, a goal's) read their newest page of 20, with Show more for older runs, instead of every page every 5 or 10 seconds. - Routines, goals, memory, check-ins, deliveries, shared-use and app access requests, a Bot's activity and attention, and a Bot's components are hint-fed. Components lists ask for view=summary or view=published, and the browser revalidates them by ETag. - Tasks: waiting on the person no longer counts as moving, so a task that needs input does not keep the list on a 3 s poll. Group chats poll only while a reply streams, up to ten minutes. --- app/src/components/approvals/bot-rules.tsx | 6 +- .../approvals/conversation-allowances.tsx | 10 +- .../components/approvals/inline-approval.tsx | 10 +- .../components/approvals/question-notice.tsx | 12 +- app/src/components/approvals/settings.tsx | 10 +- .../components/approvals/team-settings.tsx | 12 +- app/src/components/approvals/waiting.tsx | 22 +- .../components/bot-profile/settings-rows.tsx | 10 +- app/src/components/channels/channel-chat.tsx | 28 +- app/src/components/channels/group-chat.tsx | 15 +- .../components/computer/use-cards-first.ts | 13 +- .../onboarding/ask-first-switch.tsx | 8 +- .../components/responsibilities/goal-page.tsx | 13 +- .../responsibilities/use-goal-reads.ts | 5 +- app/src/components/routines/routine-page.tsx | 15 +- app/src/components/routines/routine-runs.tsx | 42 ++- .../components/routines/use-routine-runs.ts | 16 +- app/src/components/tasks/worked-for.tsx | 6 +- app/src/lib/app-access/queries.ts | 14 +- app/src/lib/approvals.ts | 259 +++++++++---- app/src/lib/bot-lifecycle/queries.ts | 11 +- app/src/lib/channels/use-channel-events.ts | 40 ++ app/src/lib/client.ts | 5 + app/src/lib/components/queries.ts | 57 ++- app/src/lib/computers/activity.ts | 8 +- app/src/lib/computers/use-control.ts | 31 +- app/src/lib/copilot/approval-tools.tsx | 9 +- app/src/lib/delivery.ts | 10 +- app/src/lib/deployment/queries.ts | 15 + app/src/lib/groups.ts | 40 +- app/src/lib/live/apply-hints.ts | 213 +++++++++++ app/src/lib/live/hinted.ts | 119 ++++++ app/src/lib/memory.ts | 7 +- app/src/lib/plugins/shared-use.ts | 4 +- app/src/lib/proactive.ts | 7 +- app/src/lib/responsibilities.ts | 46 ++- app/src/lib/routines/queries.ts | 56 +-- app/src/lib/tasks/queries.ts | 23 +- ...pproval-answered-old-conversation.test.tsx | 4 +- app/tests/approval-answered-stays.test.tsx | 6 +- .../approval-card-render-update.test.tsx | 10 +- app/tests/approval-carry-on-running.test.tsx | 19 +- .../approval-left-not-carried-on.test.tsx | 6 +- app/tests/approval-tools.test.tsx | 5 +- app/tests/cards-first.test.tsx | 7 +- app/tests/components-api-calls.test.tsx | 5 +- .../computer-activity-names-and-times.test.ts | 7 +- app/tests/computer-control-store.test.tsx | 27 ++ app/tests/conversation-allowances.test.tsx | 2 +- app/tests/data-changed-hints.test.tsx | 356 ++++++++++++++++++ .../responsibility-action-refresh.test.ts | 38 +- .../routines-list-follows-changes.test.tsx | 35 +- app/tests/skins-openfuse.test.tsx | 4 +- app/tests/task-thread.test.tsx | 12 +- app/tests/waiting-is-not-moving.test.ts | 83 ++++ 55 files changed, 1528 insertions(+), 325 deletions(-) create mode 100644 app/src/lib/live/apply-hints.ts create mode 100644 app/src/lib/live/hinted.ts create mode 100644 app/tests/data-changed-hints.test.tsx create mode 100644 app/tests/waiting-is-not-moving.test.ts diff --git a/app/src/components/approvals/bot-rules.tsx b/app/src/components/approvals/bot-rules.tsx index 7023a1752e..7e3ffe7041 100644 --- a/app/src/components/approvals/bot-rules.tsx +++ b/app/src/components/approvals/bot-rules.tsx @@ -1,7 +1,7 @@ -import { IconChecklist } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { Link } from "@tanstack/react-router"; import { Fragment } from "react"; +import { IconChecklist } from "@/components/icons"; import { PageEmpty, PageRows, @@ -9,7 +9,7 @@ import { } from "@/components/layout/page-shell"; import { Separator } from "@/components/ui/separator"; import { - approvalInboxOptions, + approvalSettingsOptions, createApprovalRuleMutationOptions, revokeApprovalRuleMutationOptions, ruleCoversBot, @@ -25,7 +25,7 @@ import { RuleForm, RuleRow } from "./rules"; * `botId` is the Bot's id, or a pattern covering it. */ export function BotApprovalRules({ agentId }: { agentId: string }) { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalSettingsOptions()); const addRule = useMutation(createApprovalRuleMutationOptions(queryClient)); const changeRule = useMutation( updateApprovalRuleMutationOptions(queryClient), diff --git a/app/src/components/approvals/conversation-allowances.tsx b/app/src/components/approvals/conversation-allowances.tsx index 61bc097fcf..0ce8554312 100644 --- a/app/src/components/approvals/conversation-allowances.tsx +++ b/app/src/components/approvals/conversation-allowances.tsx @@ -1,15 +1,15 @@ import { approvalPhrase } from "@openbot/shared/tool-name"; -import { IconCircleCheck } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; +import { IconCircleCheck } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { type ActionKind, - approvalInboxOptions, type ConversationGrant, + conversationGrantsOptions, revokeConversationGrantMutationOptions, } from "@/lib/approvals"; -import { queryClient } from "@/query-client"; import { failureSaid } from "@/lib/load-failure"; +import { queryClient } from "@/query-client"; /** A kind of action, as the start of a sentence about where it is allowed. */ const KIND_WORDS: Record = { @@ -44,11 +44,11 @@ function allowedWords(grant: ConversationGrant): string { * allowed here. */ export function ConversationAllowances({ threadId }: { threadId: string }) { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(conversationGrantsOptions()); const revoke = useMutation( revokeConversationGrantMutationOptions(queryClient), ); - const grants = (inbox.data?.conversationGrants ?? []).filter( + const grants = (inbox.data ?? []).filter( (grant) => grant.threadId === threadId, ); if (grants.length === 0) return null; diff --git a/app/src/components/approvals/inline-approval.tsx b/app/src/components/approvals/inline-approval.tsx index 73ff1fc02b..583509236d 100644 --- a/app/src/components/approvals/inline-approval.tsx +++ b/app/src/components/approvals/inline-approval.tsx @@ -16,7 +16,7 @@ import { settingsApprovalBodyFor } from "@/components/settings-tools/settings-to import { type ApprovalDecision, type ApprovalRequest, - approvalInboxOptions, + approvalQueueOptions, conversationApprovalsQueryOptions, decideApproval, } from "@/lib/approvals"; @@ -79,13 +79,13 @@ const CHOICE_WORDS: Record< * The requests a conversation's cards and answered lines are drawn from: the inbox, and the * conversation's own list. * - * The inbox is read again every few seconds, so a decision made on the Approvals page shows here - * too, but it keeps only the person's last hundred, across every conversation. In an older + * The inbox is read again when the server says it changed, so a decision made on the Approvals page + * shows here too, but it keeps only the person's last hundred, across every conversation. In an older * conversation those were all elsewhere and its answered lines never showed. The conversation's own * list reaches back past them. Where both hold a request, the inbox's copy is the newer. */ function useRequestsHere(): ApprovalRequest[] { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); // The conversation this is drawn in, where it is drawn in one. const threadId = useCopilotChatConfiguration()?.threadId; const here = useQuery({ @@ -270,7 +270,7 @@ export function InlineApproval({ * the sheet draws them too. The same card, from the same inbox, so answering either answers both. */ export function ConversationApprovals({ threadId }: { threadId: string }) { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); const ids = (inbox.data?.requests ?? []).flatMap((request) => request.status === "pending" && request.action.threadId === threadId && diff --git a/app/src/components/approvals/question-notice.tsx b/app/src/components/approvals/question-notice.tsx index 1314e4e5f0..81c78e5859 100644 --- a/app/src/components/approvals/question-notice.tsx +++ b/app/src/components/approvals/question-notice.tsx @@ -1,8 +1,8 @@ import type { Message } from "@ag-ui/core"; -import { IconX } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { useState } from "react"; import { BotOrb } from "@/components/agents/bot-orb"; +import { IconX } from "@/components/icons"; import { Button } from "@/components/ui/button"; import { Questionnaire, @@ -19,15 +19,15 @@ import { QuestionnaireTitle, } from "@/components/ui/questionnaire"; import { - type ApprovalInboxData, - approvalInboxOptions, + type ApprovalQueueData, + approvalQueueOptions, dismissPersonQuestionMutationOptions, } from "@/lib/approvals"; import { type Failure, failureSaid } from "@/lib/load-failure"; import { ANSWER_PREFIX } from "@/lib/question-answer"; import { queryClient } from "@/query-client"; -export type WaitingQuestion = ApprovalInboxData["questions"][number]; +export type WaitingQuestion = ApprovalQueueData["questions"][number]; /** * The question this conversation's Bot is waiting on, if one is: the newest open question asked in @@ -37,13 +37,13 @@ export function useConversationQuestion( channelId: string, threadId: string, ): WaitingQuestion | undefined { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); return conversationQuestion(inbox.data, channelId, threadId); } /** The newest open question asked in this conversation, from an inbox read. */ export function conversationQuestion( - inbox: ApprovalInboxData | undefined, + inbox: ApprovalQueueData | undefined, channelId: string, threadId: string, ): WaitingQuestion | undefined { diff --git a/app/src/components/approvals/settings.tsx b/app/src/components/approvals/settings.tsx index 2726697547..e559bc79f9 100644 --- a/app/src/components/approvals/settings.tsx +++ b/app/src/components/approvals/settings.tsx @@ -1,12 +1,12 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { Fragment } from "react"; import { IconChecklist, IconEyeCheck, IconHandStop, IconTerminal2, } from "@/components/icons"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { Link } from "@tanstack/react-router"; -import { Fragment } from "react"; import { PageEmpty, PageRows, @@ -24,8 +24,8 @@ import { Separator } from "@/components/ui/separator"; import { Switch } from "@/components/ui/switch"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { - approvalInboxOptions, approvalPreferencesMutationOptions, + approvalSettingsOptions, createApprovalRuleMutationOptions, revokeApprovalRuleMutationOptions, ruleCoversBot, @@ -50,7 +50,7 @@ import { HOST_LABELS, LabelSelect, RuleForm, RuleRow } from "./rules"; * administrators change them in Admin → Approvals. Rules for a single Bot are on that Bot's page. */ export function ApprovalSettings() { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalSettingsOptions()); const me = useQuery(currentUserQueryOptions()).data; // The personal edition has no team for team settings to govern, so no team rules to point at. const personal = diff --git a/app/src/components/approvals/team-settings.tsx b/app/src/components/approvals/team-settings.tsx index 139936d150..8509ea0a55 100644 --- a/app/src/components/approvals/team-settings.tsx +++ b/app/src/components/approvals/team-settings.tsx @@ -1,3 +1,6 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { Fragment } from "react"; import { IconChecklist, IconChevronRight, @@ -14,9 +17,6 @@ import { IconTrash, IconUserCog, } from "@/components/icons"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { Link } from "@tanstack/react-router"; -import { Fragment } from "react"; import { PageEmpty, PageRows, @@ -35,13 +35,13 @@ import { Switch } from "@/components/ui/switch"; import { type ActionKind, type ActionKindPolicy, - approvalInboxOptions, + approvalSettingsOptions, createTeamApprovalRuleMutationOptions, revokeTeamApprovalRuleMutationOptions, teamApprovalSettingsMutationOptions, updateTeamApprovalRuleMutationOptions, } from "@/lib/approvals"; -import { loadFailure, failureSaid } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { reviewerGuidanceQueryOptions } from "@/lib/reviewer-guidance/queries"; import { queryClient } from "@/query-client"; import { HOST_LABELS, LabelSelect, RuleForm, RuleRow } from "./rules"; @@ -87,7 +87,7 @@ const ACTION_KIND_LABELS: Record = { * Settings → Approvals. */ export function TeamApprovalSettings() { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalSettingsOptions()); const guidance = useQuery(reviewerGuidanceQueryOptions()); const team = useMutation(teamApprovalSettingsMutationOptions(queryClient)); const addTeamRule = useMutation( diff --git a/app/src/components/approvals/waiting.tsx b/app/src/components/approvals/waiting.tsx index 5865b54be2..22bce9d41d 100644 --- a/app/src/components/approvals/waiting.tsx +++ b/app/src/components/approvals/waiting.tsx @@ -4,17 +4,17 @@ import { approvalPhrase, approvalWords, } from "@openbot/shared/tool-name"; +import { useMutation, useQuery } from "@tanstack/react-query"; +import { useNavigate } from "@tanstack/react-router"; +import { Fragment, type ReactNode, useState } from "react"; +import { BotOrb } from "@/components/agents/bot-orb"; +import { ShareDetails, shareOf } from "@/components/approvals/share-details"; import { IconDots, IconHandStop, IconMessageQuestion, IconX, } from "@/components/icons"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { useNavigate } from "@tanstack/react-router"; -import { Fragment, type ReactNode, useState } from "react"; -import { BotOrb } from "@/components/agents/bot-orb"; -import { ShareDetails, shareOf } from "@/components/approvals/share-details"; import { PageRows } from "@/components/layout/page-shell"; import { BoardRow, @@ -57,21 +57,21 @@ import { useBotNames } from "@/lib/agents/bot-names"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { type ApprovalDecision, - type ApprovalInboxData, + type ApprovalQueueData, answerPersonQuestionMutationOptions, - approvalInboxOptions, + approvalQueueOptions, decideApprovalMutationOptions, dismissPersonQuestionMutationOptions, } from "@/lib/approvals"; +import { failureSaid } from "@/lib/load-failure"; import { readFailure } from "@/lib/read-failure"; import { relativeTime } from "@/lib/relative-time"; import type { WaitingWhere } from "@/lib/tasks/groups"; import { cn } from "@/lib/utils"; import { queryClient } from "@/query-client"; -import { failureSaid } from "@/lib/load-failure"; -type WaitingQuestion = ApprovalInboxData["questions"][number]; -type WaitingRequest = ApprovalInboxData["requests"][number]; +type WaitingQuestion = ApprovalQueueData["questions"][number]; +type WaitingRequest = ApprovalQueueData["requests"][number]; /** * What waits on the person in the approval inbox, for one Bot or for all of them: the questions its @@ -79,7 +79,7 @@ type WaitingRequest = ApprovalInboxData["requests"][number]; * the Bot whose conversation it is. */ function useWaiting(agentId: string | undefined) { - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); const ours = (botId: string) => agentId === undefined || botId === agentId; return { error: inbox.error, diff --git a/app/src/components/bot-profile/settings-rows.tsx b/app/src/components/bot-profile/settings-rows.tsx index 399ea3bf0a..c23b2df0ea 100644 --- a/app/src/components/bot-profile/settings-rows.tsx +++ b/app/src/components/bot-profile/settings-rows.tsx @@ -1,11 +1,11 @@ +import { useQuery } from "@tanstack/react-query"; +import { Link } from "@tanstack/react-router"; +import { Fragment } from "react"; import { IconChevronRight, IconDeviceMobile, IconUsersGroup, } from "@/components/icons"; -import { useQuery } from "@tanstack/react-query"; -import { Link } from "@tanstack/react-router"; -import { Fragment } from "react"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { Item, @@ -24,7 +24,7 @@ import { sharingSummary, } from "@/lib/agents/bot-summaries"; import type { AgentProfile } from "@/lib/agents/queries"; -import { approvalInboxOptions, ruleCoversBot } from "@/lib/approvals"; +import { approvalSettingsOptions, ruleCoversBot } from "@/lib/approvals"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { isOrganizationAdmin } from "@/lib/auth/roles"; import { destinationsQueryOptions } from "@/lib/delivery"; @@ -81,7 +81,7 @@ export function BotSettingsRows({ agent }: { agent: AgentProfile }) { const checkIns = useQuery(proactiveSettingsQueryOptions()); const sources = useQuery({ ...memorySourcesQueryOptions(), enabled: memory }); const plugins = useBotPlugins(agent.id); - const approvals = useQuery(approvalInboxOptions()); + const approvals = useQuery(approvalSettingsOptions()); const teamBots = useQuery({ ...teamBotsQueryOptions(), enabled: !personal }); const reach = useQuery({ ...destinationsQueryOptions(), diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index c26af07485..84d096d423 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -54,9 +54,10 @@ import { BOT_KEY_REFUSED } from "@/lib/agents/key-link"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { answerPersonQuestionMutationOptions, - approvalInboxOptions, - carryingOnAfterApproval, + approvalQueueOptions, + approvalsWaiting, leftAnswers, + useCarryingOnAfterApproval, } from "@/lib/approvals"; import { useBotTakesModelChoice } from "@/lib/bot-agents/queries"; import { attachmentUrl } from "@/lib/channels/attachments"; @@ -1781,18 +1782,12 @@ export function ChannelChat({ * the Bot went on working: found on the Mac, after Allow once on a Google Maps step. * * Read from the approval itself, which the server marks `completed` only once that turn has ended, - * so it is the same record whichever tab or device decided it. Polled faster while it is going, so - * the conversation stops saying it is working soon after it is done. + * so it is the same record whichever tab or device decided it. Not polled: the server announces the + * decision and the end (its `approvals` hint), and the queue is read again on each. The + * conversation's work (`carriedByServer` below) does not list this turn: the server lists only a + * turn it carries on its own queue, which an approval's carry-on joins only when handed on. */ - const carryingOn = - useQuery({ - ...approvalInboxOptions(), - select: (inbox) => carryingOnAfterApproval(inbox, channel.threadId), - refetchInterval: (query) => - carryingOnAfterApproval(query.state.data, channel.threadId) - ? 2_000 - : 10_000, - }).data === true; + const carryingOn = useCarryingOnAfterApproval(channel.threadId); /* * When the server's turn ends, what it wrote is read, whether or not the roster says the Bot * replied. A turn the person stopped has no reply to announce, and what it said before the Stop @@ -2070,7 +2065,7 @@ export function ChannelChat({ const repaired = repairUnansweredToolCalls( target.messages, undefined, - leftAnswers(queryClient.getQueryData(approvalInboxOptions().queryKey)), + leftAnswers(queryClient.getQueryData(approvalQueueOptions().queryKey)), ); if (repaired !== target.messages) { target.setMessages(repaired as typeof target.messages); @@ -2706,7 +2701,8 @@ export function ChannelChat({ // And a run that ended on a question to the person, the same way. askedSinceLastMessage(agent.messages) ) - void queryClient.invalidateQueries({ queryKey: ["approvals"] }); + // What waits on the person; their settings did not move. + void queryClient.invalidateQueries(approvalsWaiting); const wasOurs = awaitingReply.current; awaitingReply.current = false; /* @@ -2761,7 +2757,7 @@ export function ChannelChat({ if (question || !askedSinceLastMessage(agentRef.current.messages)) return question; const inbox = await queryClient - .fetchQuery({ ...approvalInboxOptions(), staleTime: 0 }) + .fetchQuery({ ...approvalQueueOptions(), staleTime: 0 }) .catch(() => undefined); return conversationQuestion(inbox, channel.id, channel.threadId); }; diff --git a/app/src/components/channels/group-chat.tsx b/app/src/components/channels/group-chat.tsx index b73836c6ee..4e2a1ccd96 100644 --- a/app/src/components/channels/group-chat.tsx +++ b/app/src/components/channels/group-chat.tsx @@ -14,9 +14,9 @@ import { } from "@/components/ui/message"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { - type ApprovalInboxData, + type ApprovalQueueData, answerPersonQuestionMutationOptions, - approvalInboxOptions, + approvalQueueOptions, } from "@/lib/approvals"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { @@ -78,7 +78,7 @@ export function GroupChat({ channelId }: { channelId: string }) { (message) => message.status === "running" || message.status === "queued", ); - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); const question = groupQuestion(inbox.data, channelId); // The Bot whose conversation it is: for a hand-off, the one that handed the work on. const askerId = question?.conversationBotId ?? question?.botId; @@ -94,14 +94,15 @@ export function GroupChat({ channelId }: { channelId: string }) { }); }; /* - * The inbox is read every 10 s, and a Bot that asks ends its turn on the question. Read again the - * moment the Bots stop, so the question is above the composer when the reply that asks it is. + * The inbox is read again on the server's word that it changed, and a Bot that asks ends its turn + * on the question. Read again the moment the Bots stop too, so the question is above the composer + * when the reply that asks it is, whichever arrives first. */ const wasWorking = useRef(working); useEffect(() => { if (wasWorking.current && !working) void queryClient.invalidateQueries({ - queryKey: approvalInboxOptions().queryKey, + queryKey: approvalQueueOptions().queryKey, }); wasWorking.current = working; }, [working, queryClient]); @@ -292,7 +293,7 @@ export function GroupChat({ channelId }: { channelId: string }) { * thread of its own, so it is found by the conversation, not by a thread. */ export function groupQuestion( - inbox: ApprovalInboxData | undefined, + inbox: ApprovalQueueData | undefined, channelId: string, ): WaitingQuestion | undefined { return inbox?.questions.find((question) => question.channelId === channelId); diff --git a/app/src/components/computer/use-cards-first.ts b/app/src/components/computer/use-cards-first.ts index f013ea61b3..63aef1e331 100644 --- a/app/src/components/computer/use-cards-first.ts +++ b/app/src/components/computer/use-cards-first.ts @@ -1,6 +1,6 @@ import { useQuery } from "@tanstack/react-query"; import { useEffect, useRef } from "react"; -import { approvalInboxOptions } from "@/lib/approvals"; +import { approvalQueueOptions } from "@/lib/approvals"; import { useComputerControl } from "@/lib/computers/use-control"; import { FINAL_SIGN_IN, @@ -22,7 +22,7 @@ import { * Beside a wide conversation the cards are already in view, and nothing here does anything. * * The cards, by what each is waiting on: the Bot's request to be taken over (its computer's - * wheel), an approval for a step in this conversation (the approvals inbox), and a private sign-in + * wheel, read only while the sheet is open over the conversation), an approval for a step in this conversation (the approvals inbox), and a private sign-in * this conversation's Bot asked for (the sign-in requests, read only where the sheet covers). */ export function useCardsFirst({ @@ -44,11 +44,16 @@ export function useCardsFirst({ /** This OpenBot has computers for Bots, so the wheel can be read. */ computers?: boolean; }): { cardWaiting: boolean } { + /* + * The wheel matters here only while the Computer is open as a sheet over the conversation: that is + * when a take-over waiting under it closes it. Read only then, not on every conversation of a Bot + * with a computer. + */ const { control } = useComputerControl( botId ?? "", - Boolean(botId) && computers, + Boolean(botId) && computers && covers && watching, ); - const inbox = useQuery(approvalInboxOptions()); + const inbox = useQuery(approvalQueueOptions()); const signIns = useQuery({ ...pendingSignInRequestsQueryOptions(), enabled: covers && Boolean(threadId), diff --git a/app/src/components/onboarding/ask-first-switch.tsx b/app/src/components/onboarding/ask-first-switch.tsx index 1788acdedc..6bca104fbe 100644 --- a/app/src/components/onboarding/ask-first-switch.tsx +++ b/app/src/components/onboarding/ask-first-switch.tsx @@ -1,9 +1,9 @@ -import { IconHandStop } from "@/components/icons"; import { useMutation, useQuery } from "@tanstack/react-query"; import { ASK_FIRST_DESCRIPTION, ASK_FIRST_TITLE, } from "@/components/approvals/ask-first-copy"; +import { IconHandStop } from "@/components/icons"; import { Item, ItemActions, @@ -14,8 +14,8 @@ import { } from "@/components/ui/item"; import { Switch } from "@/components/ui/switch"; import { - approvalInboxOptions, approvalPreferencesMutationOptions, + approvalSettingsOptions, } from "@/lib/approvals"; import { loadFailure } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; @@ -29,8 +29,8 @@ import { queryClient } from "@/query-client"; * picture's frame, because it is the one real control here. */ export function AskFirstSwitch() { - // Read once: the inbox's own polling is for the approvals page, not for a single switch. - const inbox = useQuery({ ...approvalInboxOptions(), refetchInterval: false }); + // The person's settings, read once and kept. + const inbox = useQuery(approvalSettingsOptions()); const preferences = useMutation( approvalPreferencesMutationOptions(queryClient), ); diff --git a/app/src/components/responsibilities/goal-page.tsx b/app/src/components/responsibilities/goal-page.tsx index 6f8b1a812a..d242c02637 100644 --- a/app/src/components/responsibilities/goal-page.tsx +++ b/app/src/components/responsibilities/goal-page.tsx @@ -1,3 +1,6 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Link, type LinkProps, useNavigate } from "@tanstack/react-router"; +import { Fragment, useId, useState } from "react"; import { IconChevronRight, IconCircleCheck, @@ -10,9 +13,6 @@ import { IconTarget, IconWebhook, } from "@/components/icons"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { Link, type LinkProps, useNavigate } from "@tanstack/react-router"; -import { Fragment, useId, useState } from "react"; import { LoadingRows } from "@/components/layout/loading-rows"; import { PageCard, @@ -27,6 +27,7 @@ import { RoutineDetailMissing, useDeletedHere, } from "@/components/routines/routine-detail-missing"; +import { MoreRuns } from "@/components/routines/routine-runs"; import { Button } from "@/components/ui/button"; import { Dialog, @@ -618,8 +619,9 @@ function runStatusClass(status: string) { } /** - * The runs, newest first, polled while the page is open so the one Run now started appears and - * moves through its states without a reload. + * The runs, newest first: the newest page, read again when the server says a run started or ended, + * so the one Run now started appears and moves through its states without a reload. Older runs on + * Show more. */ function Runs({ goalId, channelId }: { goalId: string; channelId: string }) { const runs = useGoalRuns(goalId); @@ -691,6 +693,7 @@ function Runs({ goalId, channelId }: { goalId: string; channelId: string }) { ) : (

No runs yet.

)} + ); } diff --git a/app/src/components/responsibilities/use-goal-reads.ts b/app/src/components/responsibilities/use-goal-reads.ts index 16f4d5e661..7a3d29ab05 100644 --- a/app/src/components/responsibilities/use-goal-reads.ts +++ b/app/src/components/responsibilities/use-goal-reads.ts @@ -1,4 +1,4 @@ -import { useQuery } from "@tanstack/react-query"; +import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { useDeletedHere } from "@/components/routines/routine-detail-missing"; import { deleteResponsibilityMutationKey, @@ -31,9 +31,10 @@ export function useGoalTriggers(goalId: string, { enabled = true } = {}) { }); } +/** The goal's runs, newest first, a page at a time: `fetchNextPage` reads the next page. */ export function useGoalRuns(goalId: string) { const deleted = useGoalDeletedHere(goalId); - return useQuery({ + return useInfiniteQuery({ ...responsibilityRunsQueryOptions(goalId), enabled: !deleted, }); diff --git a/app/src/components/routines/routine-page.tsx b/app/src/components/routines/routine-page.tsx index 7a7723db35..539d70ce35 100644 --- a/app/src/components/routines/routine-page.tsx +++ b/app/src/components/routines/routine-page.tsx @@ -1,3 +1,6 @@ +import { useMutation, useQuery } from "@tanstack/react-query"; +import { Link, type LinkProps, useNavigate } from "@tanstack/react-router"; +import { Fragment, useState } from "react"; import { IconCalendarTime, IconChevronRight, @@ -10,9 +13,6 @@ import { IconRobot, IconWorld, } from "@/components/icons"; -import { useMutation, useQuery } from "@tanstack/react-query"; -import { Link, type LinkProps, useNavigate } from "@tanstack/react-router"; -import { Fragment, useState } from "react"; import { LoadingRows } from "@/components/layout/loading-rows"; import { PageRows, @@ -26,6 +26,7 @@ import { RoutineDetailMissing, useDeletedHere, } from "@/components/routines/routine-detail-missing"; +import { MoreRuns } from "@/components/routines/routine-runs"; import { useRoutineRuns } from "@/components/routines/use-routine-runs"; import { Button } from "@/components/ui/button"; import { @@ -49,7 +50,7 @@ import { Separator } from "@/components/ui/separator"; import { Switch } from "@/components/ui/switch"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { deleteQuestion } from "@/lib/delete-question"; -import { loadFailure, failureSaid } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { stopIfNeedsCard } from "@/lib/plan/queries"; import { relativeTime } from "@/lib/relative-time"; import { routineDoes } from "@/lib/routines/merged"; @@ -65,8 +66,8 @@ import { routinesQueryOptions, } from "@/lib/routines/queries"; import { runSourceLabel } from "@/lib/routines/run-source"; -import { cn } from "@/lib/utils"; import { lastRunLabel } from "@/lib/routines/words"; +import { cn } from "@/lib/utils"; import { queryClient } from "@/query-client"; export { @@ -114,7 +115,8 @@ export function runStatusOf(status: string) { /** * Every firing of one routine, newest first, each linking to the conversation it ran in. A run's * reason, a skipped one's included, is the server's own words under it; nothing is inferred from a - * status. Polled with the routine's runs read, so the one Run now started appears without a reload. + * status. The newest page, read again when the server says a run started or ended, so the one Run now + * started appears without a reload; older runs on Show more. */ function RoutineRuns({ routine }: { routine: RoutineRecord }) { const runs = useRoutineRuns(routine.id); @@ -183,6 +185,7 @@ function RoutineRuns({ routine }: { routine: RoutineRecord }) { ) : (

No runs yet.

)} + ); } diff --git a/app/src/components/routines/routine-runs.tsx b/app/src/components/routines/routine-runs.tsx index 6bf2a04396..9f5c8f9cb6 100644 --- a/app/src/components/routines/routine-runs.tsx +++ b/app/src/components/routines/routine-runs.tsx @@ -1,10 +1,11 @@ import { Link } from "@tanstack/react-router"; +import { Button } from "@/components/ui/button"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { relativeTime } from "@/lib/relative-time"; import type { RoutineRecord, RoutineRunRecord } from "@/lib/routines/queries"; import { runSourceLabel } from "@/lib/routines/run-source"; import { cn } from "@/lib/utils"; import { useRoutineRuns } from "./use-routine-runs"; -import { failureSaid } from "@/lib/load-failure"; /* * What a routine has done, where a person sees a routine: its own row on the Routines list, and each @@ -193,6 +194,45 @@ export function RoutineRuns({ routine }: { routine: RoutineRecord }) { ); })} + {runs.hasNextPage ? ( +
  • + +
  • + ) : null} ); } + +/** + * Show more, under a run history that has older runs than it shows: the next page, read when asked + * for. A history only grows, so it is never read to its end by itself. Nothing when every run is + * shown. + */ +export function MoreRuns({ + runs, +}: { + runs: Pick< + ReturnType, + "hasNextPage" | "isFetchingNextPage" | "isFetchNextPageError" | "error" + > & { fetchNextPage: () => unknown }; +}) { + if (!runs.hasNextPage) return null; + return ( +
    + {runs.isFetchNextPageError ? ( +

    + {loadFailure(runs.error, "Couldn't load more runs. Try again.")} +

    + ) : null} + +
    + ); +} diff --git a/app/src/components/routines/use-routine-runs.ts b/app/src/components/routines/use-routine-runs.ts index 54f4c97d3f..70bdc2d5c6 100644 --- a/app/src/components/routines/use-routine-runs.ts +++ b/app/src/components/routines/use-routine-runs.ts @@ -1,23 +1,23 @@ -import { useQuery } from "@tanstack/react-query"; +import { useInfiniteQuery } from "@tanstack/react-query"; import { deleteRoutineMutationKey } from "@/lib/routines/mutations"; import { routineRunsQueryOptions } from "@/lib/routines/queries"; import { useDeletedHere } from "./routine-detail-missing"; /** - * A routine's runs, read until the routine is deleted from this browser. + * A routine's runs, newest first, a page at a time (`data` is every run read so far, and + * `fetchNextPage` reads the next page), read until the routine is deleted from this browser. * - * The runs are polled while a routine is on screen, and the screen stays up for a moment after a - * delete: its list is still being read again, which is what takes it down. A read in that moment - * asks for the runs of a routine that is gone and is answered 404. So from the moment a delete of - * this routine is on its way, its runs are not read: the delete drops what was read - * (`deleteRoutineMutationOptions`), and nothing here asks again. + * The screen stays up for a moment after a delete, and a read in that moment asks for the runs of a + * routine that is gone and is answered 404. So from the moment a delete of this routine is on its + * way, its runs are not read: the delete drops what was read (`deleteRoutineMutationOptions`), and + * nothing here asks again. */ export function useRoutineRuns(routineId: string) { const deleted = useDeletedHere( deleteRoutineMutationKey, (id) => id === routineId, ); - return useQuery({ + return useInfiniteQuery({ ...routineRunsQueryOptions(routineId), enabled: !deleted, }); diff --git a/app/src/components/tasks/worked-for.tsx b/app/src/components/tasks/worked-for.tsx index 3642004a83..6d95b12975 100644 --- a/app/src/components/tasks/worked-for.tsx +++ b/app/src/components/tasks/worked-for.tsx @@ -21,7 +21,7 @@ import { WorkingNow, } from "@/components/channels/tool-activity"; import { ToolLine } from "@/components/channels/tool-line"; -import { type ApprovalInboxData, approvalInboxOptions } from "@/lib/approvals"; +import { type ApprovalQueueData, approvalQueueOptions } from "@/lib/approvals"; import { briefDuration, useSecondsSince } from "@/lib/elapsed"; import { FolderNamesContext } from "@/lib/folders/folder-steps"; import { researchRoleOfCall } from "@/lib/plugins/research-results"; @@ -56,7 +56,7 @@ const NOTHING_TO_LEAVE = () => undefined; export function useWaitingToolCalls( client: QueryClient | undefined, ): ReadonlySet { - const key = approvalInboxOptions().queryKey; + const key = approvalQueueOptions().queryKey; // Told after a render that changed the cache, not during it: see `subscribeToQueryCache`. const subscribe = useCallback( (change: () => void) => @@ -64,7 +64,7 @@ export function useWaitingToolCalls( [client], ); const inbox = useSyncExternalStore(subscribe, () => - client?.getQueryData(key), + client?.getQueryData(key), ); return useMemo(() => { const ids = (inbox?.requests ?? []).flatMap((request) => diff --git a/app/src/lib/app-access/queries.ts b/app/src/lib/app-access/queries.ts index cbc32a6769..ebee14c18e 100644 --- a/app/src/lib/app-access/queries.ts +++ b/app/src/lib/app-access/queries.ts @@ -14,6 +14,7 @@ import type { BotApp, } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { HINTED_STALE_MS, hintsSent } from "@/lib/live/hinted"; /** * What each work app is for the person looking, on one Bot, and the requests they file when only an @@ -411,15 +412,18 @@ export function appAccessInboxQueryOptions(enabled: boolean, app?: string) { export const INBOX_POLL_MS = 30_000; /** - * Every waiting request, kept fresh for as long as OpenBot is open: read again on a timer, out of - * sight too, and when the window comes back to the front. The same key as the whole inbox, so the - * Admin sidebar's count, the Requests on Admin, Apps, and the notice for a new request read one - * answer. One watcher holds it (`AccessRequestWatch`); everything else reads what it keeps. + * Every waiting request, kept fresh for as long as OpenBot is open: read again when the server says a + * request was made or decided (its `grants` hint, heard out of sight too, which is when a notice is + * worth raising), and when the window comes back to the front. On a server that sends no such hint + * it is read on a timer, out of sight too, as before. The same key as the whole inbox, so the Admin + * sidebar's count, the Requests on Admin, Apps, and the notice for a new request read one answer. One + * watcher holds it (`AccessRequestWatch`); everything else reads what it keeps. */ export function liveAppAccessInboxQueryOptions(enabled: boolean) { return queryOptions({ ...appAccessInboxQueryOptions(enabled), - refetchInterval: INBOX_POLL_MS, + staleTime: HINTED_STALE_MS, + refetchInterval: () => (hintsSent("grants") ? false : INBOX_POLL_MS), refetchIntervalInBackground: true, refetchOnWindowFocus: true, }); diff --git a/app/src/lib/approvals.ts b/app/src/lib/approvals.ts index c925279a77..44ce4e114f 100644 --- a/app/src/lib/approvals.ts +++ b/app/src/lib/approvals.ts @@ -2,7 +2,9 @@ import { mutationOptions, type QueryClient, queryOptions, + useQuery, } from "@tanstack/react-query"; +import { useEffect, useState } from "react"; import { createApprovalRule as createOrganizationRule, deleteApprovalRule as deleteOrganizationRule, @@ -30,6 +32,7 @@ import { } from "@/lib/api/generated/approvals/approvals"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries"; +import { hinted } from "@/lib/live/hinted"; /** The person asking: every approval, question, preference and rule here is their own. */ const ME = "me"; @@ -104,8 +107,11 @@ export const BEHAVIOUR_LABELS: Record = { ask: "Ask before taking action", hand_off: "Hand off to you", }; -export type ApprovalInboxData = { - enabled: boolean; +/** + * What waits on the person and what they decided lately: the live half of the inbox, read again on + * the server's `approvals` hint ({@link approvalQueueOptions}). + */ +export type ApprovalQueueData = { requests: { id: string; status: string; @@ -140,10 +146,31 @@ export type ApprovalInboxData = { }; }; }[]; + questions: { + id: string; + botId: string; + /** The Bot whose conversation this belongs to: for a hand-off, the Bot that handed it on. */ + conversationBotId?: string; + threadId: string; + /** The conversation it was asked in, which is where it is answered. */ + channelId?: string; + question: string; + why?: string; + /** The separate decisions inside the question, each answered on its own. */ + parts?: { header: string; question: string; options?: string[] }[]; + createdAt: string; + }[]; +}; + +/** + * What the person set for themselves and what the organization set for everybody: the settings half + * of the inbox, read once and again only when one of them is changed here + * ({@link approvalSettingsOptions}). + */ +export type ApprovalSettingsData = { + enabled: boolean; rules: ApprovalRuleRow[]; teamRules: ApprovalRuleRow[]; - /** "Allow for this conversation" answers still in force, in every conversation. */ - conversationGrants?: ConversationGrant[]; preferences?: { enabled: boolean; autoReview: boolean; @@ -158,20 +185,6 @@ export type ApprovalInboxData = { }; /** The member's command policy after the team cap. */ hostCommands?: HostCommandPolicy; - questions: { - id: string; - botId: string; - /** The Bot whose conversation this belongs to: for a hand-off, the Bot that handed it on. */ - conversationBotId?: string; - threadId: string; - /** The conversation it was asked in, which is where it is answered. */ - channelId?: string; - question: string; - why?: string; - /** The separate decisions inside the question, each answered on its own. */ - parts?: { header: string; question: string; options?: string[] }[]; - createdAt: string; - }[]; }; /** * The answers the Bot never received, by the call each belongs to: actions decided whose @@ -179,7 +192,7 @@ export type ApprovalInboxData = { * came back", so the Bot knows a post it asked for went out and does not make it again. */ export function leftAnswers( - inbox: ApprovalInboxData | undefined, + inbox: Pick | undefined, ): ReadonlyMap { const answers = new Map(); for (const request of inbox?.requests ?? []) @@ -188,32 +201,50 @@ export function leftAnswers( return answers; } -export const approvalInboxOptions = () => +/** The inbox's keys. Every approval write invalidates the root: the queue, the settings and the grants. */ +export const approvalKeys = { + all: ["approvals"] as const, + queue: ["approvals", "queue"] as const, + settings: ["approvals", "settings"] as const, + grants: ["approvals", "grants"] as const, + conversations: ["approvals", "conversation"] as const, + conversation: (threadId: string) => + ["approvals", "conversation", threadId] as const, +}; + +/** + * Every read of what waits on the person, and none of their settings: what a Bot asking something + * changes. The queue, each conversation's own list, and the conversation grants a decision makes. + */ +export const approvalsWaiting = { + queryKey: approvalKeys.all, + predicate: (query: { queryKey: readonly unknown[] }) => + query.queryKey[1] !== "settings", +}; + +const page = (cursor: string | undefined) => ({ + limit: 100, + ...(cursor ? { cursor } : {}), +}); + +/** + * What waits on the person, and what they decided lately: their approvals and their questions. + * + * READ ON THE SERVER'S WORD. It used to be one read of seven lists, each to its last page, every ten + * seconds (every two while a Bot carried a conversation on), and again on every approval card's mount: + * 42 requests a minute from an idle tab, 210 during a carry-on. Now the two lists that move are their + * own read, kept until the server's `approvals` hint says they changed (`lib/live/hinted.ts`), and the + * settings ({@link approvalSettingsOptions}) are read once. + */ +export const approvalQueueOptions = () => queryOptions({ - queryKey: ["approvals"], - /* - * One inbox for the screens, read from the API's separate resources: what waits on the person, - * what they set for themselves, and what the organization set for everybody. Each list is read - * to its last page. - */ - queryFn: async ({ signal }): Promise => { + queryKey: approvalKeys.queue, + queryFn: async ({ signal }): Promise => { const options = { signal, fallback: "Your approvals could not be loaded.", }; - const page = (cursor: string | undefined) => ({ - limit: 100, - ...(cursor ? { cursor } : {}), - }); - const [ - requests, - questions, - preferences, - rules, - conversationGrants, - team, - teamRules, - ] = await Promise.all([ + const [requests, questions] = await Promise.all([ everyPage(async (cursor) => { const answer = await listApprovals( organizationId(), @@ -232,6 +263,26 @@ export const approvalInboxOptions = () => ); return { items: answer.questions, nextCursor: answer.nextCursor }; }), + ]); + return { requests, questions }; + }, + ...hinted("approvals"), + }); + +/** + * What the person set for themselves and what the organization set for everybody: their preferences + * and rules, and the organization's settings and rules. They change when somebody changes them, and + * every write that does invalidates {@link approvalKeys.all}, so they are read once and kept. + */ +export const approvalSettingsOptions = () => + queryOptions({ + queryKey: approvalKeys.settings, + queryFn: async ({ signal }): Promise => { + const options = { + signal, + fallback: "Your approval settings could not be loaded.", + }; + const [preferences, rules, team, teamRules] = await Promise.all([ getApprovalPreferences(organizationId(), ME, options), everyPage(async (cursor) => { const answer = await listPersonApprovalRules( @@ -242,18 +293,6 @@ export const approvalInboxOptions = () => ); return { items: answer.approvalRules, nextCursor: answer.nextCursor }; }), - everyPage(async (cursor) => { - const answer = await listConversationGrants( - organizationId(), - ME, - page(cursor), - options, - ); - return { - items: answer.conversationGrants, - nextCursor: answer.nextCursor, - }; - }), getApprovalSettings(organizationId(), options), everyPage(async (cursor) => { const answer = await listApprovalRules( @@ -266,10 +305,8 @@ export const approvalInboxOptions = () => ]); return { enabled: preferences.enabled, - requests, rules, teamRules, - conversationGrants, preferences: { enabled: preferences.enabled, autoReview: preferences.autoReview, @@ -277,13 +314,37 @@ export const approvalInboxOptions = () => }, team, hostCommands: preferences.effectiveHostCommands, - questions, }; }, - refetchInterval: 10_000, + staleTime: Number.POSITIVE_INFINITY, }); + +/** + * "Allow for this conversation" answers still in force, in every conversation. Made by a decision, + * which the server announces as an `approvals` change, so read again on that hint, and by every + * approval write here. + */ +export const conversationGrantsOptions = () => + queryOptions({ + queryKey: approvalKeys.grants, + queryFn: ({ signal }): Promise => + everyPage(async (cursor) => { + const answer = await listConversationGrants( + organizationId(), + ME, + page(cursor), + { signal, fallback: "Your approvals could not be loaded." }, + ); + return { + items: answer.conversationGrants, + nextCursor: answer.nextCursor, + }; + }), + ...hinted("approvals"), + }); + /** One request the person was asked, as the inbox and a conversation's own list both hold it. */ -export type ApprovalRequest = ApprovalInboxData["requests"][number]; +export type ApprovalRequest = ApprovalQueueData["requests"][number]; /** * Every request the person was asked in one conversation, by its thread, however long ago: the ones @@ -296,7 +357,7 @@ export type ApprovalRequest = ApprovalInboxData["requests"][number]; */ export const conversationApprovalsQueryOptions = (threadId: string) => queryOptions({ - queryKey: ["approvals", "conversation", threadId] as const, + queryKey: approvalKeys.conversation(threadId), queryFn: ({ signal }): Promise => everyPage(async (cursor) => { const answer = await listConversationApprovals( @@ -311,6 +372,7 @@ export const conversationApprovalsQueryOptions = (threadId: string) => ); return { items: answer.approvals, nextCursor: answer.nextCursor }; }), + ...hinted("approvals"), }); /** @@ -336,15 +398,62 @@ const CARRY_ON_MS = 2 * 5 * 60_000; /** Whether the server is carrying this conversation on after one of its approvals was decided. */ export function carryingOnAfterApproval( - inbox: ApprovalInboxData | undefined, + inbox: Pick | undefined, threadId: string, now = Date.now(), ): boolean { - return (inbox?.requests ?? []).some( - (request) => - request.action.threadId === threadId && - CARRYING_ON.has(request.status) && - now - Date.parse(request.decidedAt ?? request.createdAt) < CARRY_ON_MS, + return carryOnEndsAt(inbox, threadId, now) !== null; +} + +/** + * When the last carry-on of this conversation stops counting ({@link CARRY_ON_MS} after its + * decision), or null when none counts now. + */ +export function carryOnEndsAt( + inbox: Pick | undefined, + threadId: string, + now = Date.now(), +): number | null { + let last: number | null = null; + for (const request of inbox?.requests ?? []) { + if ( + request.action.threadId !== threadId || + !CARRYING_ON.has(request.status) + ) + continue; + const ends = + Date.parse(request.decidedAt ?? request.createdAt) + CARRY_ON_MS; + if (ends > now && (last === null || ends > last)) last = ends; + } + return last; +} + +/** + * Whether the server is carrying this conversation on after one of its approvals was decided, from + * the approval queue as the server's `approvals` hints keep it: a decision and the carry-on's end are + * both announced (the request decided, then `completed`), so nothing is polled for it. It was read + * every two seconds during a carry-on and every ten otherwise. + * + * The one thing no hint says is the time running out on a carry-on that never ended + * ({@link CARRY_ON_MS}): a timer wakes the conversation when it does. + */ +export function useCarryingOnAfterApproval(threadId: string): boolean { + const queue = useQuery(approvalQueueOptions()); + const [now, setNow] = useState(() => Date.now()); + const ends = carryOnEndsAt(queue.data, threadId, now); + useEffect(() => { + if (ends === null) return; + const timer = setTimeout( + () => setNow(Date.now()), + Math.max(ends - Date.now(), 0) + 50, + ); + return () => clearTimeout(timer); + }, [ends]); + // A read that lands later than the last tick is judged against the time it is drawn. + return carryingOnAfterApproval( + queue.data, + threadId, + Math.max(now, Date.now()), ); } @@ -453,7 +562,7 @@ export const updateTeamApprovalRule = ( }); /** The inbox's key, which every approval write invalidates: requests, rules and settings alike. */ -export const approvalsKey = ["approvals"] as const; +export const approvalsKey = approvalKeys.all; const settle = (queryClient: QueryClient) => () => queryClient.invalidateQueries({ queryKey: approvalsKey }); @@ -546,15 +655,17 @@ export const answerPersonQuestionMutationOptions = (queryClient: QueryClient) => * goes at once, and the badge that counted it is read again rather than on its next poll. */ onSuccess: (_continueHere, { id }) => { - queryClient.setQueryData(approvalsKey, (inbox) => - inbox - ? { - ...inbox, - questions: inbox.questions.filter( - (question) => question.id !== id, - ), - } - : inbox, + queryClient.setQueryData( + approvalKeys.queue, + (inbox) => + inbox + ? { + ...inbox, + questions: inbox.questions.filter( + (question) => question.id !== id, + ), + } + : inbox, ); void queryClient.invalidateQueries({ queryKey: botLifecycleKeys.attention, diff --git a/app/src/lib/bot-lifecycle/queries.ts b/app/src/lib/bot-lifecycle/queries.ts index 66cbc586cb..e38006d501 100644 --- a/app/src/lib/bot-lifecycle/queries.ts +++ b/app/src/lib/bot-lifecycle/queries.ts @@ -19,6 +19,7 @@ import type { } from "@/lib/api/generated/model"; import { getNotificationSettings } from "@/lib/api/generated/notification-settings/notification-settings"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { hinted } from "@/lib/live/hinted"; /** How loudly one Bot may reach the signed-in person. Badges on the web always show. */ export type BotNotify = BotNotifyModel; @@ -96,8 +97,11 @@ async function everyAttention(): Promise { const attentionQuery = { queryKey: botLifecycleKeys.attention, queryFn: (): Promise => everyAttention(), - // Questions, approvals and pings arrive from headless work nobody is watching, so this polls. - refetchInterval: 15_000, + /* + * Questions, approvals and pings arrive from headless work nobody is watching. The server says so + * (`approvals`, `needsYou`, `bots`), and this is read again then, not every fifteen seconds. + */ + ...hinted(["approvals", "needsYou", "bots"]), }; export function botAttentionQueryOptions() { @@ -140,7 +144,8 @@ export function botActivityQueryOptions(agentId: string) { getBotActivity(organizationId(), agentId, { fallback: "Could not load this Bot's activity", }), - refetchInterval: 10_000, + // Read again when the server says what the Bot is doing for the person changed (`activity`). + ...hinted("activity"), }); } diff --git a/app/src/lib/channels/use-channel-events.ts b/app/src/lib/channels/use-channel-events.ts index d53ba5d759..800fe7d8db 100644 --- a/app/src/lib/channels/use-channel-events.ts +++ b/app/src/lib/channels/use-channel-events.ts @@ -2,6 +2,7 @@ import { CAPABILITIES_QUERY } from "@openbot/shared/client-capabilities"; import { type Query, type QueryClient, + useQuery, useQueryClient, } from "@tanstack/react-query"; import { useRouter } from "@tanstack/react-router"; @@ -13,6 +14,13 @@ import { } from "@/lib/artifacts/activity"; import { HELD_OUT_NOW, holdOut, SSO_REQUIRED_CLOSE } from "@/lib/auth/held-out"; import { CAPABILITIES } from "@/lib/client"; +import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; +import { + applyEveryHint, + applyHint, + parseDataChanged, + retimeReads, +} from "@/lib/live/apply-hints"; import { nudgeMoment } from "@/lib/notices"; import { isBotReply, @@ -636,11 +644,25 @@ export function useChannelEvents() { const queryClient = useQueryClient(); const router = useRouter(); + /* + * Which kinds of change this server sends as hints (`lib/live/hinted.ts`): read here, where the + * hints are heard, so it is known on every page that hears them. + */ + const sent = useQuery(deploymentCapabilitiesQueryOptions(), queryClient).data + ?.dataChanged; + const sentKey = sent?.join(" "); + // Known now: the reads already polling for a kind the server sends stop, at once. + useEffect(() => { + if (sentKey !== undefined) retimeReads(queryClient); + }, [sentKey, queryClient]); + useEffect(() => { let socket: WebSocket | undefined; let retryTimer: number | undefined; let retryDelay = FIRST_RETRY_MS; let stopped = false; + /** The socket opened before: opening again, it may have missed hints. */ + let openedBefore = false; const connect = () => { if (stopped) return; @@ -648,6 +670,13 @@ export function useChannelEvents() { socket.onopen = () => { retryDelay = FIRST_RETRY_MS; + /* + * Hints sent while the socket was down were never heard: every hint-fed read is marked + * stale, and those on screen read again. Not on the first opening, which follows the page's + * own first reads. + */ + if (openedBefore) applyEveryHint(queryClient); + openedBefore = true; /* * A turn's end said while the socket was down was never heard, so what it said before is * let go of: the read below is the best word there is. This tab's own turns stay held. @@ -671,12 +700,23 @@ export function useChannelEvents() { deliverArtifactActivity(artifact); return; } + /* + * Something the person sees outside their conversations changed (lib/live/apply-hints.ts): + * the reads of that kind are read again. It names no conversation. + */ + const hint = parseDataChanged(message.data, currentOrganizationId()); + if (hint) { + applyHint(queryClient, hint); + return; + } const parsed = parseChannelSocketMessage(message.data); if (!parsed) return; // Refetch rather than patch: there is no delta to apply. Checked before anything reads // `channelId`, because this message has none. if (isResync(parsed)) { + // The server may have missed telling what changed, hints among it. + applyEveryHint(queryClient); resyncArtifacts(); void queryClient.invalidateQueries({ queryKey: channelKeys.list() }); void queryClient.invalidateQueries({ diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 6607afe8f5..5e70dbf8bf 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -18,6 +18,7 @@ import { COMPUTER_STEP_TAKEN, CONVERSATION_WORK_TURN, capabilitiesValue, + DATA_CHANGED, } from "@openbot/shared/client-capabilities"; import { CLIENT_HEADER, clientToken } from "@openbot/shared/client-version"; import { @@ -49,11 +50,15 @@ export const CLIENT_NAME = clientToken("web"); * - `artifact-activity`: the conversation events socket says what changes on an artifact the person * has open (its comments, who else has it open, a page's shared data), and the socket hands it to * whoever shows that artifact (lib/artifacts/activity.ts). No REST answer reads it. + * - `data-changed`: the conversation events socket says when something the person sees outside their + * conversations changed (`dataChanged`), and the reads of that kind are read again + * (lib/live/apply-hints.ts) instead of on a timer. No REST answer reads it. */ export const PAGE_CAPABILITIES: readonly string[] = [ COMPUTER_STEP_TAKEN, CONVERSATION_WORK_TURN, ARTIFACT_ACTIVITY, + DATA_CHANGED, ]; /** {@link PAGE_CAPABILITIES} as the header and the conversation events socket carry it. */ diff --git a/app/src/lib/components/queries.ts b/app/src/lib/components/queries.ts index 2de6679bcb..bc0bf88643 100644 --- a/app/src/lib/components/queries.ts +++ b/app/src/lib/components/queries.ts @@ -1,4 +1,5 @@ import { queryOptions } from "@tanstack/react-query"; +import { everyPage } from "@/lib/api/every-page"; import { announceComponents, callComponentFunction as callComponentFunctionApi, @@ -7,10 +8,13 @@ import { listComponentFunctions, listComponents, } from "@/lib/api/generated/components/components"; -import type { Component } from "@/lib/api/generated/model"; -import { everyPage } from "@/lib/api/every-page"; +import type { + Component, + ComponentListViewParameter, +} from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; +import { hinted } from "@/lib/live/hinted"; /** The kind the API gives a component an admin wrote in Playground. */ export const PLAYGROUND_KIND = "playground"; @@ -124,14 +128,24 @@ function componentRecord(component: Component): ComponentRecord { }; } -/** Every component the caller may see, every page read, optionally of one kind. */ -async function everyComponent(kind?: string): Promise { +/** + * Every component the caller may see, every page read, optionally of one kind, with as much of each + * as `view` asks for (listComponents): `summary` leaves out every source and draft, `published` every + * draft. A server from before `view` sends everything, which reads the same. + * + * Each page answers with an ETag and allows the browser to keep it only to ask again with it, so a + * page read again unchanged comes back 304, with no body, and the browser hands back the copy it kept. + */ +async function everyComponent( + options: { kind?: string; view?: ComponentListViewParameter } = {}, +): Promise { return everyPage(async (cursor) => { const page = await listComponents( organizationId(), { limit: 100, - ...(kind === undefined ? {} : { kind }), + ...(options.kind === undefined ? {} : { kind: options.kind }), + ...(options.view === undefined ? {} : { view: options.view }), ...(cursor === undefined ? {} : { cursor }), }, { fallback: "The components could not be loaded." }, @@ -140,27 +154,33 @@ async function everyComponent(kind?: string): Promise { }); } +/** + * Every component, as the components screens list them: no source and no draft, which none of them + * draws (`summary`). Read again when the server says the components changed. + */ export function componentListQueryOptions() { return queryOptions({ queryKey: componentKeys.list(), queryFn: async (): Promise => - (await everyComponent()).map(componentRecord), + (await everyComponent({ view: "summary" })).map(componentRecord), + ...hinted("components"), }); } /** * What one Bot may answer with. * - * Polled so open conversations stop offering revoked components; call-time checks still enforce - * the grant. + * Read again when the server says the components changed (`components`), so an open conversation + * stops offering a revoked component, and when the tab is looked at again. It was read every five + * seconds. Call-time checks still enforce the grant. */ export function agentComponentsQueryOptions(agentId: string | undefined) { return queryOptions({ queryKey: componentKeys.forAgent(agentId ?? ""), enabled: Boolean(agentId), - refetchInterval: 5_000, - // Refetched when the tab is looked at again, so a grant changed on another screen is not waiting - // out an interval before it shows. + ...hinted("components"), + // Refetched when the tab is looked at again, so a grant changed on another screen shows even from a + // server that sends no hint. Answered 304 while nothing changed. refetchOnWindowFocus: true, queryFn: async (): Promise => everyPage(async (cursor) => { @@ -227,7 +247,7 @@ export function playgroundListQueryOptions() { return queryOptions({ queryKey: componentKeys.playground(), queryFn: async (): Promise => - (await everyComponent(PLAYGROUND_KIND)).map((component) => { + (await everyComponent({ kind: PLAYGROUND_KIND })).map((component) => { const draft = component.draft?.source; return { name: component.name, @@ -252,18 +272,21 @@ export function playgroundListQueryOptions() { } /** - * The published source, which is what a conversation renders from. + * The published source, which is what a conversation renders from, and no drafts (`published`). * - * Refetched periodically so publishing takes effect in an open conversation without a reload. It is - * not what enforces anything: whether this Bot may use the component at all is the grant, which the + * Read again when the server says the components changed, so publishing takes effect in an open + * conversation without a reload. It was read whole, drafts and all, every thirty seconds. It is not + * what enforces anything: whether this Bot may use the component at all is the grant, which the * server is asked about separately and at call time. */ export function publishedPlaygroundQueryOptions() { return queryOptions({ queryKey: componentKeys.published(), - refetchInterval: 30_000, + ...hinted("components"), queryFn: async (): Promise => - (await everyComponent(PLAYGROUND_KIND)).flatMap((component) => + ( + await everyComponent({ kind: PLAYGROUND_KIND, view: "published" }) + ).flatMap((component) => component.source ? [ { diff --git a/app/src/lib/computers/activity.ts b/app/src/lib/computers/activity.ts index 3e76d681b6..bc7fba88bf 100644 --- a/app/src/lib/computers/activity.ts +++ b/app/src/lib/computers/activity.ts @@ -13,8 +13,8 @@ import { useQuery } from "@tanstack/react-query"; import { useEffect } from "react"; import { type ApprovalDecision, - type ApprovalInboxData, - approvalInboxOptions, + type ApprovalQueueData, + approvalQueueOptions, } from "@/lib/approvals"; import type { ToolOutcome } from "./call"; import { followView, latestView } from "./panel-view"; @@ -138,7 +138,7 @@ const NO_DECISIONS: StepDecisions = new Map(); * no line in Activity, and a step declined there had no time once the conversation was opened again. */ export function decisionsIn( - inbox: ApprovalInboxData | undefined, + inbox: ApprovalQueueData | undefined, ): StepDecisions { const decisions = new Map(); for (const request of inbox?.requests ?? []) { @@ -1127,7 +1127,7 @@ export function useConversationActivity( const { copilotkit } = useCopilotKit(); // The person's answers on the steps' cards: the same inbox the conversation's cards read. const decisions = useQuery({ - ...approvalInboxOptions(), + ...approvalQueueOptions(), select: decisionsIn, }).data; useEffect( diff --git a/app/src/lib/computers/use-control.ts b/app/src/lib/computers/use-control.ts index fef8c1ff3d..d5b8238622 100644 --- a/app/src/lib/computers/use-control.ts +++ b/app/src/lib/computers/use-control.ts @@ -1,6 +1,7 @@ import { useQuery } from "@tanstack/react-query"; import { useSyncExternalStore } from "react"; import { currentUserQueryOptions } from "@/lib/auth/queries"; +import { type Hint, hintsSent, onHint } from "@/lib/live/hinted"; import { queryClient } from "@/query-client"; import { BOT_GONE, @@ -145,6 +146,28 @@ function createControlStore(computerId: string): ControlStore { const refreshWhenShown = () => { if (!document.hidden && !snapshot.busy && !reading) void refresh(); }; + /* + * READ AGAIN ON THE SERVER'S WORD. Who has the wheel, a request for a person, a hand-over finishing + * and the computer starting or sleeping are all announced (the `computers` hint, `lib/live`), so the + * wheel is read when one about this computer arrives. It was read every second on every open + * conversation of a Bot with a computer, whether or not anybody looked at it: 60 requests a minute. + * A server that sends no such hint has it read every second as before, while somebody watches. + */ + const pollTick = () => { + if (document.hidden || gone) return; + if (hintsSent("computers")) { + // A read that did not come back is tried again soon, since no tick follows it. + if (failures > 0 && !snapshot.busy && !reading) void refresh(); + return; + } + if (!snapshot.busy && !reading) void refresh(); + }; + const onComputerHint = (hint: Hint) => { + if (!hint.changed.includes("computers")) return; + if (hint.botId !== undefined && hint.botId !== computerId) return; + if (!document.hidden && !snapshot.busy) void refresh(); + }; + let stopHearing: (() => void) | undefined; const store: ControlStore = { getSnapshot: () => snapshot, refresh, @@ -154,10 +177,8 @@ function createControlStore(computerId: string): ControlStore { if (timer === undefined) { if (!snapshot.busy) void refresh(); // Not while the tab is hidden: nobody is looking, and it is read again the moment they are. - timer = setInterval(() => { - if (document.hidden || gone) return; - if (!snapshot.busy && !reading) void refresh(); - }, 1000); + timer = setInterval(pollTick, 1000); + stopHearing = onHint(onComputerHint); document.addEventListener("visibilitychange", refreshWhenShown); } return () => { @@ -165,6 +186,8 @@ function createControlStore(computerId: string): ControlStore { if (listeners.size) return; clearInterval(timer); timer = undefined; + stopHearing?.(); + stopHearing = undefined; document.removeEventListener("visibilitychange", refreshWhenShown); reading?.abort(); version++; diff --git a/app/src/lib/copilot/approval-tools.tsx b/app/src/lib/copilot/approval-tools.tsx index 5e61068664..25cdca65e2 100644 --- a/app/src/lib/copilot/approval-tools.tsx +++ b/app/src/lib/copilot/approval-tools.tsx @@ -12,7 +12,10 @@ import { InlineApproval } from "@/components/approvals/inline-approval"; import { runComputerStep } from "@/lib/api/generated/approvals/approvals"; import type { ComputerStepOutcome } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; -import { threadAsksEveryStepQueryOptions } from "@/lib/approvals"; +import { + approvalsWaiting, + threadAsksEveryStepQueryOptions, +} from "@/lib/approvals"; import { ClientError } from "@/lib/client"; import { failedComputerCall } from "@/lib/computers/call"; import { useBotOfCall } from "./active-bot"; @@ -263,8 +266,8 @@ export function useFrontendTool>( // Stop signals the SDK to discard this handler's unfinished result. The server owns // resume: the decision executes the action once and continues this conversation. copilotkit.stopAgent({ agent: context.agent }); - // Draw the card now rather than on the inbox's next poll. - void queryClient.invalidateQueries({ queryKey: ["approvals"] }); + // Draw the card now rather than on the server's hint. + void queryClient.invalidateQueries(approvalsWaiting); return WAITING_FOR_PERSON; } // The computer is held for a person: told to the Bot as the refusal it has always been. diff --git a/app/src/lib/delivery.ts b/app/src/lib/delivery.ts index 2125f0041f..455bb227d8 100644 --- a/app/src/lib/delivery.ts +++ b/app/src/lib/delivery.ts @@ -17,6 +17,7 @@ import { listNotificationTransports } from "@/lib/api/generated/notification-set import { idempotencyKey, organizationId } from "@/lib/api/request"; import type { UpdateTransport } from "@/lib/bot-lifecycle/queries"; import { ClientError } from "@/lib/client"; +import { hinted } from "@/lib/live/hinted"; /** * How a person's Bots reach them outside OpenBot, through the API: their phones for push @@ -76,8 +77,9 @@ export function destinationsQueryOptions() { ); return { items: page.destinations, nextCursor: page.nextCursor }; }), - // A Slack or Teams link is finished from the chat app, so the list is read again until it shows. - refetchInterval: 10_000, + // A Slack or Teams link is finished from the chat app: the server says so (`deliveries`), and the + // list is read again then, not every ten seconds. + ...hinted("deliveries"), }); } @@ -93,7 +95,7 @@ export function devicesQueryOptions() { }); return { items: page.devices, nextCursor: page.nextCursor }; }), - refetchInterval: 10_000, + ...hinted("deliveries"), }); } @@ -110,7 +112,7 @@ export function deliveriesQueryOptions() { { signal, fallback: FALLBACK }, ) ).deliveries, - refetchInterval: 10_000, + ...hinted("deliveries"), }); } diff --git a/app/src/lib/deployment/queries.ts b/app/src/lib/deployment/queries.ts index 4b003776b9..63f11c5131 100644 --- a/app/src/lib/deployment/queries.ts +++ b/app/src/lib/deployment/queries.ts @@ -22,6 +22,7 @@ import { import { ClientError } from "@/lib/client"; import { invokeDesktop } from "@/lib/desktop/queries"; import { desktopShell } from "@/lib/desktop/shell"; +import { noteKindsSent } from "@/lib/live/hinted"; import { currentOrganizationId } from "@/lib/organizations/current"; /** @@ -84,6 +85,12 @@ export type DeploymentCapabilities = { * from that email, with no OpenBot link that accepts it. */ hostedSignIn?: boolean; + /** + * The kinds of change this server sends as a hint on the conversation events socket. A list fed by + * one of them is read again on the hint instead of on a timer (`lib/live/hinted.ts`). Empty from a + * server that does not say, which every list is polled for, slowly. + */ + dataChanged?: readonly string[]; }; /** @@ -291,7 +298,15 @@ export function deploymentCapabilitiesQueryOptions() { signal, fallback: "Couldn't load what OpenBot can do.", }); + const dataChanged = Array.isArray(body.dataChanged) + ? body.dataChanged.filter( + (kind): kind is string => typeof kind === "string", + ) + : []; + // What the hint-fed lists poll for: only the kinds this server does not send. + noteKindsSent(dataChanged); return { + dataChanged, generativeUi: body.generativeUi === true, selfHostBanner: body.selfHostBanner === true, localEvaluation: body.localEvaluation === true, diff --git a/app/src/lib/groups.ts b/app/src/lib/groups.ts index 72de6e4f48..f1f9aa6d54 100644 --- a/app/src/lib/groups.ts +++ b/app/src/lib/groups.ts @@ -1,3 +1,4 @@ +import { attachmentUrl as storedAttachmentUrl } from "@openbot/shared/attachments"; import { mutationOptions, type QueryClient, @@ -15,7 +16,6 @@ import type { ConversationMember, ConversationMessage, } from "@/lib/api/generated/model"; -import { attachmentUrl as storedAttachmentUrl } from "@openbot/shared/attachments"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { type AgentChannel, @@ -124,8 +124,9 @@ export const groupKeys = { }; /** - * The shared transcript. Bot turns run on the server with nobody's browser attached, so the page - * polls while a turn is still owed an answer and stops once every Bot has spoken. + * The shared transcript. Bot turns run on the server with nobody's browser attached. A Bot starting, + * finishing or queued moves the conversation's events, which read this again; while a reply streams + * its words are read every second and a half, up to a deadline ({@link streamingReply}). */ export function groupQueryOptions(channelId: string) { return queryOptions({ @@ -159,15 +160,36 @@ export function groupQueryOptions(channelId: string) { }; }, refetchInterval: (query) => - query.state.data?.messages.some( - (message) => - message.status === "running" || message.status === "queued", - ) || awaitingFirstReply(query.state.data) - ? 1_500 - : false, + streamingReply(query.state.data) ? 1_500 : false, }); } +/** + * How long after a Bot's reply began its words are still read as they stream. The server ends a turn + * it runs at five minutes; this allows twice that. A reply still running after it is one the server + * gave up on, and reading it every second and a half for ever (as before) only cost requests. + */ +export const GROUP_STREAM_MS = 10 * 60_000; + +/** + * Whether a Bot's reply is being written now, so its words are read again every second and a half + * as they stream: a reply running, begun within {@link GROUP_STREAM_MS}. Nothing else is polled: a + * Bot starting, finishing or being queued moves the conversation's own events, which read the + * transcript again (`useChannelEvents`). + */ +export function streamingReply( + data: GroupConversation | undefined, + now = Date.now(), +): boolean { + return ( + data?.messages.some( + (message) => + message.status === "running" && + now - Date.parse(message.createdAt) < GROUP_STREAM_MS, + ) ?? false + ); +} + /** * The last line is still a person's: the server has queued it but no Bot has started yet. Bounded, * so a turn the server gave up on before any Bot started does not poll for ever. The transcript diff --git a/app/src/lib/live/apply-hints.ts b/app/src/lib/live/apply-hints.ts new file mode 100644 index 0000000000..c53ad3cdb7 --- /dev/null +++ b/app/src/lib/live/apply-hints.ts @@ -0,0 +1,213 @@ +import type { QueryClient, QueryKey } from "@tanstack/react-query"; +import { agentKeys } from "@/lib/agents/queries"; +import { approvalKeys } from "@/lib/approvals"; +import { artifactKeys } from "@/lib/artifacts/queries"; +import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries"; +import { componentKeys } from "@/lib/components/queries"; +import { computerKeys } from "@/lib/computers/queries"; +import { deliveryKeys } from "@/lib/delivery"; +import { memoryKeys } from "@/lib/memory"; +import { pluginKeys } from "@/lib/plugins/queries"; +import { sharedUseKeys } from "@/lib/plugins/shared-use"; +import { proactiveKeys } from "@/lib/proactive"; +import { responsibilityKeys } from "@/lib/responsibilities"; +import { routineKeys } from "@/lib/routines/queries"; +import { taskKeys } from "@/lib/tasks/queries"; +import { teamBotKeys } from "@/lib/team-bots"; +import { + HINT_KINDS, + type Hint, + type HintKind, + isHintKind, + tellHint, +} from "./hinted"; + +/** + * A `dataChanged` frame from the conversation events socket, or null for anything else. + * + * It names no conversation and carries `changed`, which tells it from a conversation's activity and + * from a resync (api/asyncapi.yaml, `DataChanged`). One about another organization than the one this + * tab works in is dropped: the socket is the person's, and its hint is about rows this tab does not + * hold. Kinds this app does not know are dropped too; a frame left with none is no hint. + */ +export function parseDataChanged( + data: unknown, + organization: string | undefined, +): Hint | null { + if (typeof data !== "string") return null; + let parsed: unknown; + try { + parsed = JSON.parse(data); + } catch { + return null; + } + if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) + return null; + const frame = parsed as { + changed?: unknown; + organizationId?: unknown; + botId?: unknown; + channelId?: unknown; + }; + if (!Array.isArray(frame.changed) || frame.channelId !== undefined) + return null; + if ( + typeof frame.organizationId === "string" && + organization !== undefined && + frame.organizationId !== organization + ) + return null; + const changed = frame.changed.filter(isHintKind); + if (changed.length === 0) return null; + return { + changed: [...new Set(changed)], + ...(typeof frame.botId === "string" && frame.botId + ? { botId: frame.botId } + : {}), + }; +} + +/** One set of reads a hint marks stale: a key prefix, narrowed by a predicate where it has to be. */ +type Reads = { + queryKey: QueryKey; + predicate?: (query: { queryKey: readonly unknown[] }) => boolean; +}; + +/** Whether a per-Bot key (`[..., botId]` at `at`) is about the Bot a hint names, or any Bot. */ +const ofBot = + (botId: string | undefined, at: number) => + (query: { queryKey: readonly unknown[] }) => + botId === undefined || + query.queryKey.length <= at || + query.queryKey[at] === botId; + +/** + * What each kind of change makes stale: the reads `DataChanged.changed` names for it, by the key + * factories that hold them. A hint about one Bot reaches only that Bot's per-Bot reads. + */ +export function readsFor(kind: HintKind, botId?: string): Reads[] { + switch (kind) { + case "approvals": + return [ + { queryKey: approvalKeys.queue }, + { queryKey: approvalKeys.conversations }, + { queryKey: approvalKeys.grants }, + { queryKey: botLifecycleKeys.attention }, + ]; + case "needsYou": + return [ + // The task list and each task's card: not the reactions or the turns kept under the root. + { + queryKey: taskKeys.all, + predicate: (query) => + query.queryKey[1] === "list" || query.queryKey[1] === "one", + }, + { queryKey: proactiveKeys.suggestions }, + { queryKey: botLifecycleKeys.attention }, + ]; + case "bots": + return [ + { queryKey: agentKeys.all }, + { queryKey: teamBotKeys.all }, + { + queryKey: ["bot-lifecycle", "lifecycle"], + predicate: ofBot(botId, 2), + }, + { queryKey: botLifecycleKeys.routing }, + { queryKey: botLifecycleKeys.attention }, + ]; + case "activity": + return [ + { + queryKey: ["bot-lifecycle", "activity"], + predicate: ofBot(botId, 2), + }, + { queryKey: responsibilityKeys.all }, + { queryKey: proactiveKeys.settings }, + ]; + case "routines": + return [ + { queryKey: routineKeys.all }, + { queryKey: responsibilityKeys.all }, + ]; + case "computers": + return [ + { + queryKey: computerKeys.all, + predicate: (query) => + query.queryKey[1] === "status" && ofBot(botId, 2)(query), + }, + ]; + case "artifacts": + return [ + { queryKey: artifactKeys.lists() }, + { queryKey: ["artifacts", "sharing"] }, + ]; + case "components": + return [ + { + queryKey: componentKeys.all, + // One Bot's components changed: that Bot's list, and the lists of every component. + predicate: (query) => + query.queryKey[1] !== "for-agent" || ofBot(botId, 2)(query), + }, + ]; + case "grants": + return [ + { + queryKey: ["plugins", "for-agent"], + predicate: ofBot(botId, 2), + }, + { queryKey: ["plugins", "app-access"] }, + { queryKey: sharedUseKeys.requests() }, + { queryKey: pluginKeys.connections() }, + ]; + case "deliveries": + return [{ queryKey: deliveryKeys.all }]; + case "memory": + return [{ queryKey: memoryKeys.all }]; + } +} + +/** + * Mark stale what a hint says changed. Reads on screen are read again now, once; a read already under + * way is let finish (`cancelRefetch: false`), since the server sends at most one hint a second and + * gathers the rest into the next. Reads not on screen are only marked, and read when next shown. + */ +export function applyHint(queryClient: QueryClient, hint: Hint): void { + const seen = new Set(); + for (const kind of hint.changed) + for (const reads of readsFor(kind, hint.botId)) { + const id = JSON.stringify(reads.queryKey) + String(reads.predicate); + if (seen.has(id)) continue; + seen.add(id); + void queryClient.invalidateQueries( + { + queryKey: reads.queryKey, + ...(reads.predicate ? { predicate: reads.predicate } : {}), + }, + { cancelRefetch: false }, + ); + } + tellHint(hint); +} + +/** + * Every read on screen works out again how often it polls. A hint-fed read's interval depends on + * whether the server sends its kind (`hintedInterval`), which is known only once the deployment + * answer is in, often after the read began; TanStack Query works an interval out again only when a + * read's options are set, so they are set again here, as they are. Nothing is read by it. + */ +export function retimeReads(queryClient: QueryClient): void { + for (const query of queryClient.getQueryCache().getAll()) + for (const observer of query.observers) + observer.setOptions(observer.options); +} + +/** + * Every hint-fed read marked stale, as for a hint of every kind: what the socket opening, or the + * server's resync, asks for, since any hint sent while the socket was down was never heard. + */ +export function applyEveryHint(queryClient: QueryClient): void { + applyHint(queryClient, { changed: HINT_KINDS }); +} diff --git a/app/src/lib/live/hinted.ts b/app/src/lib/live/hinted.ts new file mode 100644 index 0000000000..e72a04d467 --- /dev/null +++ b/app/src/lib/live/hinted.ts @@ -0,0 +1,119 @@ +/** + * READ AGAIN ON THE SERVER'S WORD, NOT ON A TIMER. + * + * The server says on the conversation events socket when something the person sees outside their + * conversations changed (`dataChanged` in api/asyncapi.yaml): a hint naming what kind of thing + * changed, never the data. The app read none of them and polled instead: about 120 requests a minute + * from one idle conversation tab, all day in OpenBot Desktop, several of them reading lists that only + * grow to their last page. Now each list fed by a kind is read once, kept for a long while, and read + * again when a hint of its kind arrives (`lib/live/apply-hints.ts`). + * + * WHICH KINDS THE SERVER SENDS is in its deployment answer (`dataChanged`). A list whose kind the + * server does not name (an older server, or a kind it doesn't send yet) is still polled, slowly, and + * never while the page is hidden, so it never stays stale for good. + */ + +/** What changed, as `DataChanged.changed` names it. A kind this app doesn't know is ignored. */ +export type HintKind = + | "approvals" + | "needsYou" + | "bots" + | "activity" + | "routines" + | "computers" + | "artifacts" + | "components" + | "grants" + | "deliveries" + | "memory"; + +export const HINT_KINDS: readonly HintKind[] = [ + "approvals", + "needsYou", + "bots", + "activity", + "routines", + "computers", + "artifacts", + "components", + "grants", + "deliveries", + "memory", +]; + +export function isHintKind(value: unknown): value is HintKind { + return (HINT_KINDS as readonly unknown[]).includes(value); +} + +/** + * How long a hint-fed list is taken as it stands. A screen mounting within this reads nothing; a + * hint marks it stale at once whatever this says. + */ +export const HINTED_STALE_MS = 5 * 60_000; + +/** + * How often a list is read while its server sends no hint of its kind. Slow, and paused while the + * page is hidden (TanStack Query's `refetchIntervalInBackground` is left false). + */ +export const HINT_FALLBACK_MS = 60_000; + +/** The kinds the server this tab talks to says it sends. Empty until its deployment answer is read. */ +let sent: ReadonlySet = new Set(); + +/** Record what the deployment answer says the server sends (`dataChanged`). */ +export function noteKindsSent(kinds: readonly unknown[] | undefined): void { + sent = new Set((kinds ?? []).filter(isHintKind)); +} + +/** Whether the server sends hints of every one of these kinds. */ +export function hintsSent(kinds: HintKind | readonly HintKind[]): boolean { + const all = typeof kinds === "string" ? [kinds] : kinds; + return all.every((kind) => sent.has(kind)); +} + +/** The interval for a list fed by these kinds: none while the server sends them, else the slow fallback. */ +export function hintedInterval( + kinds: HintKind | readonly HintKind[], +): number | false { + return hintsSent(kinds) ? false : HINT_FALLBACK_MS; +} + +/** + * The options that make a read hint-fed: kept for {@link HINTED_STALE_MS}, read again on a hint of + * one of `kinds` (by `apply-hints.ts`, through its key), and polled slowly only while the server sends + * none of them. Spread into a `queryOptions` factory; a factory that polls faster while something is + * moving passes its own `refetchInterval` and falls back to {@link hintedInterval}. + */ +export function hinted(kinds: HintKind | readonly HintKind[]) { + return { + staleTime: HINTED_STALE_MS, + refetchInterval: (): number | false => hintedInterval(kinds), + }; +} + +/** One hint, as the socket carried it. */ +export type Hint = { changed: readonly HintKind[]; botId?: string }; + +const listeners = new Set<(hint: Hint) => void>(); + +/** + * Hear every hint, for a reader that keeps its state outside the query cache (the computer's wheel, + * `lib/computers/use-control.ts`). Returns the way to stop. + */ +export function onHint(listener: (hint: Hint) => void): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +/** Tell every listener about a hint. */ +export function tellHint(hint: Hint): void { + for (const listener of listeners) { + try { + listener(hint); + } catch { + // One listener's failure is its own; the others still hear it. + } + } +} diff --git a/app/src/lib/memory.ts b/app/src/lib/memory.ts index fa3be43e4f..c87e087e59 100644 --- a/app/src/lib/memory.ts +++ b/app/src/lib/memory.ts @@ -23,6 +23,7 @@ import type { UpdateMemoryRequest, } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { hinted } from "@/lib/live/hinted"; import { everyPage } from "@/lib/routines/queries"; /** Memory is always the signed-in person's own: the API addresses them as `me`. */ @@ -56,6 +57,8 @@ export const memoriesQueryOptions = () => }); return { items: page.memories, nextCursor: page.nextCursor }; }), + // Read again when the server says the person's memory changed (`memory`), not on a timer. + ...hinted("memory"), }); /** Every source the person's Bots read facts in from. */ @@ -70,7 +73,9 @@ export const memorySourcesQueryOptions = () => }); return { items: page.sources, nextCursor: page.nextCursor }; }), - refetchInterval: 15_000, + // A source's read moving on (synced, failed) is announced as a `memory` change: read again then, + // not every fifteen seconds. + ...hinted("memory"), }); /** The read actions one Bot could read facts in from. */ diff --git a/app/src/lib/plugins/shared-use.ts b/app/src/lib/plugins/shared-use.ts index 2221ce3f4d..f386f6c8a6 100644 --- a/app/src/lib/plugins/shared-use.ts +++ b/app/src/lib/plugins/shared-use.ts @@ -16,6 +16,7 @@ import { listSharedUseRequests, } from "@/lib/api/generated/shared-use/shared-use"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { hinted } from "@/lib/live/hinted"; import { teamName } from "@/lib/teams/names"; /** @@ -86,7 +87,8 @@ export function sharedUseRequestsQueryOptions(enabled: boolean) { queryKey: sharedUseKeys.requests(), queryFn: ({ signal }) => waitingRequests(signal), enabled, - refetchInterval: 10_000, + // A request made or decided is announced (`grants`): read again then, not every ten seconds. + ...hinted("grants"), }); } diff --git a/app/src/lib/proactive.ts b/app/src/lib/proactive.ts index 0c611119ba..8aa7675824 100644 --- a/app/src/lib/proactive.ts +++ b/app/src/lib/proactive.ts @@ -25,6 +25,7 @@ import type { } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; import { botLifecycleKeys } from "@/lib/bot-lifecycle/queries"; +import { hinted } from "@/lib/live/hinted"; import { everyPage } from "@/lib/routines/queries"; import { taskKeys } from "@/lib/tasks/queries"; @@ -109,7 +110,8 @@ const proactiveSettingsQuery = { }); return { settings, allowed: allowed ?? true }; }, - refetchInterval: 30_000, + // A check-in run moves its Bot's work on (`activity`); read again then, not every 30 seconds. + ...hinted("activity"), }; export const proactiveSettingsQueryOptions = () => @@ -136,7 +138,8 @@ export const proactiveSuggestionsQueryOptions = () => }); return { items: page.checkInItems, nextCursor: page.nextCursor }; }), - refetchInterval: 30_000, + // An item raised or cleared waits on the person (`needsYou`): read again then. + ...hinted("needsYou"), }); /** diff --git a/app/src/lib/responsibilities.ts b/app/src/lib/responsibilities.ts index 934acc5c85..760b637ce9 100644 --- a/app/src/lib/responsibilities.ts +++ b/app/src/lib/responsibilities.ts @@ -1,4 +1,5 @@ import { + infiniteQueryOptions, mutationOptions, type QueryClient, queryOptions, @@ -36,10 +37,12 @@ import type { UpdateGoalRequest, } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { hinted } from "@/lib/live/hinted"; import { sharedUseKeys } from "@/lib/plugins/shared-use"; import { everyPage, - ROUTINES_REFETCH_MS, + RUNS_PAGE, + type RunsPage, routineKeys, } from "@/lib/routines/queries"; @@ -78,22 +81,39 @@ export function responsibilitiesQueryOptions() { a.updatedAt === b.updatedAt ? 0 : a.updatedAt < b.updatedAt ? 1 : -1, ); }, - // The routines' interval: the Routines list builds a goal's row from both reads. - refetchInterval: ROUTINES_REFETCH_MS, + // Read again when the server says a goal or a routine changed, as the routines are: the Routines + // list builds a goal's row from both reads. + ...hinted(["routines", "activity"]), }); } +/** + * A goal's runs, newest first, a page at a time: the newest page, read again when the server says a + * run started or ended, and older ones on Show more. Never read to the end of a history that only + * grows (it was, every ten seconds). + */ export function responsibilityRunsQueryOptions(id: string) { - return queryOptions({ + return infiniteQueryOptions({ queryKey: responsibilityKeys.runs(id), - queryFn: ({ signal }): Promise => - everyPage(async (params) => { - const page = await listGoalRuns(organizationId(), id, params, { + queryFn: async ({ + pageParam, + signal, + }): Promise> => { + const page = await listGoalRuns( + organizationId(), + id, + { limit: RUNS_PAGE, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal, fallback: "Couldn't load this goal's runs. Try again in a moment.", - }); - return { items: page.runs, nextCursor: page.nextCursor }; - }), - refetchInterval: 10_000, + }, + ); + return { runs: page.runs ?? [], nextCursor: page.nextCursor ?? null }; + }, + initialPageParam: undefined as string | undefined, + getNextPageParam: (last) => last.nextCursor ?? undefined, + select: (data): ResponsibilityRunRecord[] => + data.pages.flatMap((p) => p.runs), + ...hinted(["routines", "activity"]), }); } export function githubBindingsQueryOptions() { @@ -304,8 +324,8 @@ export function responsibilityActionMutationOptions(queryClient: QueryClient) { // Completing a goal switches off the routines that serve it, on the server, before this // response returns, so only "complete" refreshes them. A run can also complete a goal, but // it is accepted (202) and finishes later, so refreshing routines now would see nothing - // new: the routines' own poll (`ROUTINES_REFETCH_MS`) reads them once it has. Pause and - // resume leave routines as they were. + // new: the server's `routines` hint reads them once it has. Pause and resume leave routines + // as they were. if (action !== "complete") return goals; return Promise.all([ goals, diff --git a/app/src/lib/routines/queries.ts b/app/src/lib/routines/queries.ts index 77bd78ffdc..7aa16d2602 100644 --- a/app/src/lib/routines/queries.ts +++ b/app/src/lib/routines/queries.ts @@ -1,10 +1,11 @@ -import { queryOptions } from "@tanstack/react-query"; +import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query"; import type { Routine, RoutineRun } from "@/lib/api/generated/model"; import { listRoutineRuns, listRoutines, } from "@/lib/api/generated/routines/routines"; import { organizationId } from "@/lib/api/request"; +import { hinted } from "@/lib/live/hinted"; /** * One standing instruction, as the Routines page sees it: the API's `Routine`, generated from the @@ -30,14 +31,6 @@ export type RoutineRecord = Routine; /** What the routines screens read: every one of the person's routines. */ export type RoutinesPage = { routines: RoutineRecord[] }; -/** - * How often routines and goals are read again while a screen shows them. A Routines row and a goal's - * page are built from both reads, and either changes without this screen: a run completes a goal and - * the server switches its schedule off, or a Bot gives a goal a schedule. Both reads use this one - * interval, so neither stays stale longer than the other. - */ -export const ROUTINES_REFETCH_MS = 10_000; - export const routineKeys = { all: ["routines"] as const, list: () => ["routines", "list"] as const, @@ -72,19 +65,39 @@ export async function everyPage( return all; } +/** How many runs a routine's history shows at first, and how many more each Show more adds. */ +export const RUNS_PAGE = 20; + +/** One page of a run history, as the screens keep it: the runs, and where the next page starts. */ +export type RunsPage = { runs: T[]; nextCursor: string | null }; + +/** + * A routine's runs, newest first, a page at a time: the first page, and more on Show more. + * + * A HISTORY ONLY GROWS, SO IT IS NEVER READ TO ITS END. It was, every five seconds while a routine was + * on screen: a routine that runs every five minutes holds about 8,600 runs after a month, 87 pages a + * read. Now the newest page is read, kept, and read again when the server says one of the routine's + * runs started or ended (its `routines` hint, `lib/live/hinted.ts`). + */ export function routineRunsQueryOptions(id: string) { - return queryOptions({ + return infiniteQueryOptions({ queryKey: routineKeys.runs(id), - queryFn: ({ signal }): Promise => - everyPage(async (params) => { - const page = await listRoutineRuns(organizationId(), id, params, { - signal, - fallback: "This routine's runs could not be loaded.", - }); - return { items: page.runs, nextCursor: page.nextCursor }; - }), - // A run in flight settles within minutes; poll so Running turns into its outcome. - refetchInterval: 5_000, + queryFn: async ({ + pageParam, + signal, + }): Promise> => { + const page = await listRoutineRuns( + organizationId(), + id, + { limit: RUNS_PAGE, ...(pageParam ? { cursor: pageParam } : {}) }, + { signal, fallback: "This routine's runs could not be loaded." }, + ); + return { runs: page.runs ?? [], nextCursor: page.nextCursor ?? null }; + }, + initialPageParam: undefined as string | undefined, + getNextPageParam: (last) => last.nextCursor ?? undefined, + select: (data): RoutineRunRecord[] => data.pages.flatMap((p) => p.runs), + ...hinted("routines"), }); } @@ -106,6 +119,7 @@ export function routinesQueryOptions() { return { items: page.routines, nextCursor: page.nextCursor }; }), }), - refetchInterval: ROUTINES_REFETCH_MS, + // Read again when the server says a routine or a goal changed, not every ten seconds. + ...hinted(["routines", "activity"]), }); } diff --git a/app/src/lib/tasks/queries.ts b/app/src/lib/tasks/queries.ts index 8853822035..87ae969e30 100644 --- a/app/src/lib/tasks/queries.ts +++ b/app/src/lib/tasks/queries.ts @@ -8,6 +8,7 @@ import { } from "@/lib/api/generated/tasks/tasks"; import { organizationId } from "@/lib/api/request"; import { ClientError } from "@/lib/client"; +import { HINTED_STALE_MS, hintedInterval, hintsSent } from "@/lib/live/hinted"; /* * The person's tasks: what Start makes of an item a Bot's check-in found. Each runs in a conversation @@ -104,11 +105,16 @@ export const taskKeys = { /** A Bot's reaction to one of the person's messages, in place of a line of its own. */ export type { Reaction }; -/** Something is moving: read again soon. Otherwise only now and then, for a change made elsewhere. */ +/** + * A task is working: read again soon, so its steps and its end show. Otherwise only when the server + * says what waits on the person changed (`needsYou`, `lib/live/hinted.ts`). + * + * WAITING ON THE PERSON IS NOT MOVING. A task that needs input waits for them, which can be days, and + * the list used to be read every three seconds for as long as one did. Their answer, and anything + * else that moves the task, is announced. + */ const LIVE_MS = 3_000; -const QUIET_MS = 30_000; -const moving = (status: TaskStatus) => - status === "working" || status === "needs_input"; +const moving = (status: TaskStatus) => status === "working"; /** * Every open task of the person's, and the ones marked done in the last 7 days, kept live while any @@ -152,10 +158,17 @@ export const taskListQueryOptions = () => } while (cursor && !seen.has(cursor)); return tasks; }, + staleTime: HINTED_STALE_MS, + /* + * Every change of a task's state is announced (`needsYou`), so the list, read to its end, is read + * on that word alone. Only a server that sends no such word has it read every few seconds while + * a task works. + */ refetchInterval: (query) => + !hintsSent("needsYou") && query.state.data?.some((task) => moving(task.status)) ? LIVE_MS - : QUIET_MS, + : hintedInterval("needsYou"), }); /** diff --git a/app/tests/approval-answered-old-conversation.test.tsx b/app/tests/approval-answered-old-conversation.test.tsx index 4e5deef1ae..6325a128f6 100644 --- a/app/tests/approval-answered-old-conversation.test.tsx +++ b/app/tests/approval-answered-old-conversation.test.tsx @@ -9,7 +9,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { act, cleanup, render, waitFor } from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { forgetOpenedLines } from "@/components/channels/tool-line"; -import { approvalInboxOptions } from "@/lib/approvals"; +import { approvalQueueOptions } from "@/lib/approvals"; import { queryClient } from "@/query-client"; import { approvalInboxResponse, @@ -184,7 +184,7 @@ test("somebody who wasn't asked sees no answer in the conversation", async () => expect(asked).toContain(conversationApprovalsPath(OLD_THREAD)), ); await act(() => - queryClient.refetchQueries({ queryKey: approvalInboxOptions().queryKey }), + queryClient.refetchQueries({ queryKey: approvalQueueOptions().queryKey }), ); for (const said of ["Allowed once:", "Always allowed:", "Denied:"]) expect(view.queryByText(said)).toBeNull(); diff --git a/app/tests/approval-answered-stays.test.tsx b/app/tests/approval-answered-stays.test.tsx index e7a97367af..4b9b65d74f 100644 --- a/app/tests/approval-answered-stays.test.tsx +++ b/app/tests/approval-answered-stays.test.tsx @@ -13,7 +13,7 @@ import { } from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; import { forgetOpenedLines } from "@/components/channels/tool-line"; -import { approvalInboxOptions } from "@/lib/approvals"; +import { approvalQueueOptions } from "@/lib/approvals"; import { queryClient } from "@/query-client"; import { approvalInboxResponse, approvalWriteResponse } from "./approvals-api"; import { settleReactWork } from "./settle-react-work"; @@ -219,7 +219,7 @@ test("answered in the conversation, the card folds into the answer's line and st // The inbox's next read says it was decided, and the card gives way to its line. await waitFor(() => expect(inbox[0]?.decision).toBe("allow_once")); await act(() => - queryClient.refetchQueries({ queryKey: approvalInboxOptions().queryKey }), + queryClient.refetchQueries({ queryKey: approvalQueueOptions().queryKey }), ); const line = await answerLine(view, "Allowed once"); expect(summaryOf(line)).toBe("Allowed once: Create event on Google Calendar"); @@ -243,7 +243,7 @@ test("a request a rule decided, with no answer from the person, draws no answer const view = draw(turn("Event created.")); expect(await view.findByText("Done.")).toBeTruthy(); await act(() => - queryClient.refetchQueries({ queryKey: approvalInboxOptions().queryKey }), + queryClient.refetchQueries({ queryKey: approvalQueueOptions().queryKey }), ); for (const said of ["Allowed once:", "Always allowed:", "Denied:"]) expect(view.queryByText(said)).toBeNull(); diff --git a/app/tests/approval-card-render-update.test.tsx b/app/tests/approval-card-render-update.test.tsx index bec011406f..b44a604625 100644 --- a/app/tests/approval-card-render-update.test.tsx +++ b/app/tests/approval-card-render-update.test.tsx @@ -5,7 +5,7 @@ import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClientProvider } from "@tanstack/react-query"; import { act, cleanup, render } from "@testing-library/react"; import { ChatTranscript } from "@/components/channels/chat-transcript"; -import { approvalInboxOptions } from "@/lib/approvals"; +import { approvalQueueOptions } from "@/lib/approvals"; import { queryClient } from "@/query-client"; import { approvalInboxResponse } from "./approvals-api"; import { settleReactWork } from "./settle-react-work"; @@ -132,10 +132,10 @@ function transcript(messages: Message[]) { test("a step and the approval it waits on, arriving together, draw the card without updating the transcript mid-render", async () => { // The inbox as it reads once the server has stopped the turn to ask the person. inbox = [waiting]; - const asked = await queryClient.fetchQuery(approvalInboxOptions()); + const asked = await queryClient.fetchQuery(approvalQueueOptions()); inbox = []; - queryClient.removeQueries({ queryKey: approvalInboxOptions().queryKey }); - await queryClient.fetchQuery(approvalInboxOptions()); + queryClient.removeQueries({ queryKey: approvalQueueOptions().queryKey }); + await queryClient.fetchQuery(approvalQueueOptions()); const errors = spyOn(console, "error"); try { @@ -150,7 +150,7 @@ test("a step and the approval it waits on, arriving together, draw the card with // The Bot's step streams in as the inbox read that holds its approval lands: one render. inbox = [waiting]; act(() => { - queryClient.setQueryData(approvalInboxOptions().queryKey, asked); + queryClient.setQueryData(approvalQueueOptions().queryKey, asked); view.rerender(transcript(invited)); }); expect( diff --git a/app/tests/approval-carry-on-running.test.tsx b/app/tests/approval-carry-on-running.test.tsx index 4f9597c1a1..dedb354f1b 100644 --- a/app/tests/approval-carry-on-running.test.tsx +++ b/app/tests/approval-carry-on-running.test.tsx @@ -7,7 +7,8 @@ import { act, cleanup, render, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { ChannelChat } from "@/components/channels/channel-chat"; import { - type ApprovalInboxData, + type ApprovalQueueData, + type ApprovalSettingsData, carryingOnAfterApproval, } from "@/lib/approvals"; import { type AgentChannel, channelKeys } from "@/lib/channels/queries"; @@ -109,9 +110,9 @@ const said = (content: string) => let originalFetch: typeof fetch; /** Requests the server's turn opened after the first, as the inbox lists them. */ -let later: ApprovalInboxData["requests"] = []; +let later: ApprovalQueueData["requests"] = []; -function inbox(): ApprovalInboxData { +function inbox(): ApprovalQueueData & Partial { return { enabled: true, requests: [ @@ -299,7 +300,9 @@ test("after Allow once, the conversation shows the Bot working until the server' // Still going once the action has started. status = "consumed"; - await act(() => queryClient.invalidateQueries({ queryKey: ["approvals"] })); + await act(() => + queryClient.invalidateQueries({ queryKey: ["approvals", "queue"] }), + ); expect(view.container.querySelector(WORKING)).not.toBeNull(); /* * No Stop: this tab has no run of its own to stop, and the server's turn cannot be reached from @@ -309,7 +312,9 @@ test("after Allow once, the conversation shows the Bot working until the server' // The server's turn ends: nothing says the Bot is working any more. status = "completed"; - await act(() => queryClient.invalidateQueries({ queryKey: ["approvals"] })); + await act(() => + queryClient.invalidateQueries({ queryKey: ["approvals", "queue"] }), + ); await waitFor(() => expect(view.container.querySelector(WORKING)).toBeNull()); }); @@ -358,7 +363,9 @@ async function carriedOnThenEnded( ); stored = history; status = "completed"; - await act(() => queryClient.invalidateQueries({ queryKey: ["approvals"] })); + await act(() => + queryClient.invalidateQueries({ queryKey: ["approvals", "queue"] }), + ); await waitFor(() => expect(view.container.querySelector(WORKING)).toBeNull()); } diff --git a/app/tests/approval-left-not-carried-on.test.tsx b/app/tests/approval-left-not-carried-on.test.tsx index 7815025baf..c4c28bc526 100644 --- a/app/tests/approval-left-not-carried-on.test.tsx +++ b/app/tests/approval-left-not-carried-on.test.tsx @@ -7,7 +7,7 @@ import { InlineApproval, PendingApprovals, } from "@/components/approvals/inline-approval"; -import { type ApprovalInboxData, leftAnswers } from "@/lib/approvals"; +import { type ApprovalQueueData, leftAnswers } from "@/lib/approvals"; import { repairUnansweredToolCalls, UNANSWERED, @@ -70,10 +70,10 @@ function inbox(left: { done: boolean; message: string; answer: string }) { rules: [], teamRules: [], questions: [], - } as unknown as ApprovalInboxData; + } as unknown as ApprovalQueueData; } -function drawn(data: ApprovalInboxData) { +function drawn(data: ApprovalQueueData) { global.fetch = (async (input: RequestInfo | URL) => approvalInboxResponse(input, data) ?? Response.json({})) as unknown as typeof fetch; diff --git a/app/tests/approval-tools.test.tsx b/app/tests/approval-tools.test.tsx index da78d024be..5a55cb812c 100644 --- a/app/tests/approval-tools.test.tsx +++ b/app/tests/approval-tools.test.tsx @@ -3,6 +3,7 @@ import * as ReactCoreV2 from "@copilotkit/react-core/v2"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { cleanup, render } from "@testing-library/react"; +import { approvalsWaiting } from "@/lib/approvals"; import { failedComputerCall } from "@/lib/computers/call"; import { observeApprovalAgent } from "@/lib/copilot/approval-context"; import { useFrontendTool } from "@/lib/copilot/approval-tools"; @@ -166,8 +167,8 @@ test("a change goes to the server's gate even when nothing about approvals has l ]); expect(result).toEqual({ waiting: true }); expect(stopped).toHaveLength(1); - // The card is drawn now, not on the inbox's next poll. - expect(invalidated).toEqual([{ queryKey: ["approvals"] }]); + // The card is drawn now, not on the server's hint: what waits on the person, not their settings. + expect(invalidated).toEqual([approvalsWaiting]); } finally { global.fetch = originalFetch; } diff --git a/app/tests/cards-first.test.tsx b/app/tests/cards-first.test.tsx index f31ab5442d..4dd79e8f99 100644 --- a/app/tests/cards-first.test.tsx +++ b/app/tests/cards-first.test.tsx @@ -70,7 +70,7 @@ function conversation(covers: boolean) { const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity } }, }); - client.setQueryData(["approvals"], { requests: [], questions: [] }); + client.setQueryData(["approvals", "queue"], { requests: [], questions: [] }); client.setQueryData(passwordKeys.pending(), []); const closed: number[] = []; const wrapper = ({ children }: { children: ReactNode }) => ( @@ -93,7 +93,10 @@ function conversation(covers: boolean) { /** The server's answer changes, and the screen has read it. */ approvals: (...requests: unknown[]) => settled(() => - client.setQueryData(["approvals"], { requests, questions: [] }), + client.setQueryData(["approvals", "queue"], { + requests, + questions: [], + }), ), signIns: (...requests: unknown[]) => settled(() => client.setQueryData(passwordKeys.pending(), requests)), diff --git a/app/tests/components-api-calls.test.tsx b/app/tests/components-api-calls.test.tsx index 8baec5712a..240b9196be 100644 --- a/app/tests/components-api-calls.test.tsx +++ b/app/tests/components-api-calls.test.tsx @@ -145,9 +145,10 @@ test("the components gallery shows every page of the list", async () => { ); expect(await view.findByText("Table")).toBeTruthy(); expect(view.getByText("Bar chart")).toBeTruthy(); + // Without source or draft, which the gallery never draws. expect(sent.map(({ path }) => path)).toEqual([ - `${COMPONENTS_PATH}?limit=100`, - `${COMPONENTS_PATH}?limit=100&cursor=next`, + `${COMPONENTS_PATH}?limit=100&view=summary`, + `${COMPONENTS_PATH}?limit=100&view=summary&cursor=next`, ]); }); diff --git a/app/tests/computer-activity-names-and-times.test.ts b/app/tests/computer-activity-names-and-times.test.ts index 1a8d3acff9..2c7e098bbe 100644 --- a/app/tests/computer-activity-names-and-times.test.ts +++ b/app/tests/computer-activity-names-and-times.test.ts @@ -5,7 +5,10 @@ import { HANDLED_BY_PERSON, } from "@openbot/shared/approval-outcomes"; import { withFinishedAt } from "@openbot/shared/computer-control"; -import type { ApprovalInboxData } from "../src/lib/approvals"; +import type { + ApprovalQueueData, + ApprovalSettingsData, +} from "../src/lib/approvals"; import { activityFor, conversationActivity, @@ -280,7 +283,7 @@ function inboxWith( toolCallId: string, decision: "allow_conversation" | "deny", decidedAt: string, -): ApprovalInboxData { +): ApprovalQueueData & Partial { return { enabled: true, rules: [], diff --git a/app/tests/computer-control-store.test.tsx b/app/tests/computer-control-store.test.tsx index 5ce34fafdb..3bed42e630 100644 --- a/app/tests/computer-control-store.test.tsx +++ b/app/tests/computer-control-store.test.tsx @@ -2,6 +2,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { cleanup, render, waitFor } from "@testing-library/react"; import { useComputerControl } from "@/lib/computers/use-control"; +import { noteKindsSent, tellHint } from "@/lib/live/hinted"; const originalFetch = globalThis.fetch; @@ -86,3 +87,29 @@ test("the same answer every second draws the screen once", async () => { }); expect(seen.filter((holder) => holder === "human")).toHaveLength(1); }); + +/* + * The wheel was read every second on every open conversation of a Bot with a computer, whether or + * not anybody looked at it: 60 requests a minute. A server that announces a change of hands (the + * `computers` hint) is read on that word instead, and only for the computer it is about. + */ +test("from a server that announces changes of hands, the wheel is read on the hint, not every second", async () => { + noteKindsSent(["computers"]); + try { + const reads = answering(["human"]); + const seen: Array = []; + render(); + await waitFor(() => expect(reads()).toBe(1)); + await new Promise((resolve) => setTimeout(resolve, 2_500)); + expect(reads()).toBe(1); + // About another Bot's computer: nothing. + tellHint({ changed: ["computers"], botId: "another-bot" }); + await new Promise((resolve) => setTimeout(resolve, 100)); + expect(reads()).toBe(1); + // About this one: read again, once. + tellHint({ changed: ["computers"], botId: "control-hinted" }); + await waitFor(() => expect(reads()).toBe(2)); + } finally { + noteKindsSent([]); + } +}); diff --git a/app/tests/conversation-allowances.test.tsx b/app/tests/conversation-allowances.test.tsx index f2639bda31..49dba03498 100644 --- a/app/tests/conversation-allowances.test.tsx +++ b/app/tests/conversation-allowances.test.tsx @@ -114,7 +114,7 @@ test("another conversation's answer isn't shown here", async () => { const view = draw("thread-1"); await settleReactWork(); await waitFor(() => - expect(queryClient.getQueryData(["approvals"])).toBeTruthy(), + expect(queryClient.getQueryData(["approvals", "grants"])).toBeTruthy(), ); expect( view.queryByRole("region", { name: "Allowed in this conversation" }), diff --git a/app/tests/data-changed-hints.test.tsx b/app/tests/data-changed-hints.test.tsx new file mode 100644 index 0000000000..ac7a2c8e4e --- /dev/null +++ b/app/tests/data-changed-hints.test.tsx @@ -0,0 +1,356 @@ +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { + environmentManager, + QueryClient, + QueryClientProvider, + type TimeoutCallback, + timeoutManager, + useQuery, +} from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRouter, + RouterProvider, +} from "@tanstack/react-router"; +import { act, cleanup, render, waitFor } from "@testing-library/react"; +import { useState } from "react"; +import { RoutineRuns } from "@/components/routines/routine-runs"; +import { approvalQueueOptions } from "@/lib/approvals"; +import { useChannelEvents } from "@/lib/channels/use-channel-events"; +import { parseDataChanged, readsFor } from "@/lib/live/apply-hints"; +import { HINT_KINDS, noteKindsSent } from "@/lib/live/hinted"; +import { + currentOrganizationId, + setCurrentOrganization, +} from "@/lib/organizations/current"; +import type { RoutineRecord, RoutineRunRecord } from "@/lib/routines/queries"; +import { settleReactWork } from "./settle-react-work"; + +/** + * THE WEB APP READS AGAIN ON THE SERVER'S WORD, NOT ON A TIMER. + * + * The server says on the conversation events socket what changed (`dataChanged`), and the app used to + * ignore it and poll: a routine's whole run history every five seconds, the approval inbox's seven + * lists every ten, and so on, about 120 requests a minute from an idle tab. Driven here through the + * real socket hook, the real query factories and the real screens, against an account that has been + * running a while: a routine that runs every five minutes, a month of it (8,640 runs). + */ + +const ORG = "default"; +const BASE = `/api/v2/organizations/${ORG}`; +const RUNS = 8_640; + +/** The browser's socket, held so the test can speak as the server. */ +class ServerSocket extends EventTarget implements WebSocket { + static readonly CONNECTING = 0; + static readonly OPEN = 1; + static readonly CLOSING = 2; + static readonly CLOSED = 3; + static opened: ServerSocket[] = []; + readonly CONNECTING = 0; + readonly OPEN = 1; + readonly CLOSING = 2; + readonly CLOSED = 3; + binaryType: BinaryType = "blob"; + bufferedAmount = 0; + extensions = ""; + protocol = ""; + readyState = 1; + onclose: WebSocket["onclose"] = null; + onerror: WebSocket["onerror"] = null; + onmessage: WebSocket["onmessage"] = null; + onopen: WebSocket["onopen"] = null; + readonly url: string; + constructor(url: string | URL) { + super(); + this.url = String(url); + ServerSocket.opened.push(this); + } + close() {} + send() {} + /** One frame from the server. */ + say(frame: unknown) { + this.onmessage?.( + new MessageEvent("message", { data: JSON.stringify(frame) }), + ); + } +} + +/** Query intervals by id, never run by the clock: a test asserts which exist. */ +const intervals = new Map< + number, + { callback: TimeoutCallback; delay: number } +>(); +let nextInterval = 1; + +const run = (at: number): RoutineRunRecord => + ({ + id: `run-${at}`, + routineId: "r1", + status: "succeeded", + source: "schedule", + startedAt: new Date(Date.UTC(2026, 10, 1) - at * 300_000).toISOString(), + finishedAt: null, + error: null, + }) as unknown as RoutineRunRecord; + +/** What the server holds: a month of runs, newest first, and what the person waits on. */ +const server = { + runs: Array.from({ length: RUNS }, (_, at) => run(at)), + sends: [...HINT_KINDS] as string[], +}; + +/** Every request the page made, by path and query. */ +let requests: string[] = []; +const NativeResponse = globalThis.Response; +const originalFetch = globalThis.fetch; +let originalWebSocket: typeof WebSocket; +let originalOrganization: string | undefined; +type Globals = { WebSocket: typeof WebSocket }; +const globals = globalThis as unknown as Globals; + +const serve = (async (input: RequestInfo | URL) => { + const url = new URL(String(input), "http://127.0.0.1:3010"); + requests.push(`${url.pathname}${url.search}`); + if (url.pathname === `${BASE}/deployment`) + return NativeResponse.json({ + edition: "team", + localEvaluation: false, + generativeUi: true, + selfHostBanner: false, + transcription: false, + voice: false, + durableHistory: true, + authProviders: [], + ssoConfigured: false, + ssoRequired: false, + builtInBots: true, + isolatedBots: false, + botComputers: true, + dataChanged: server.sends, + }); + if (url.pathname === `${BASE}/routines/r1/runs`) { + const limit = Number(url.searchParams.get("limit") ?? 100); + const from = Number(url.searchParams.get("cursor") ?? 0); + const runs = server.runs.slice(from, from + limit); + const next = from + limit < server.runs.length ? from + limit : null; + return NativeResponse.json({ + runs, + nextCursor: next === null ? null : String(next), + }); + } + if (url.pathname === `${BASE}/people/me/approvals`) + return NativeResponse.json({ approvals: [], nextCursor: null }); + if (url.pathname === `${BASE}/people/me/questions`) + return NativeResponse.json({ questions: [], nextCursor: null }); + return NativeResponse.json({ error: "not served" }, { status: 404 }); +}) as unknown as typeof fetch; + +let wasServer = true; +beforeAll(() => { + GlobalRegistrator.register({ url: "http://127.0.0.1:3010" }); + originalWebSocket = globals.WebSocket; + globals.WebSocket = ServerSocket; + globalThis.fetch = serve; + originalOrganization = currentOrganizationId(); + setCurrentOrganization(ORG); + wasServer = environmentManager.isServer(); + environmentManager.setIsServer(() => false); + timeoutManager.setTimeoutProvider({ + setTimeout: (callback, delay) => + setTimeout(callback, delay) as unknown as number, + clearTimeout: (id) => clearTimeout(id as number), + setInterval: (callback, delay) => { + const id = nextInterval++; + intervals.set(id, { callback, delay }); + return id; + }, + clearInterval: (id) => { + intervals.delete(id as number); + }, + }); +}); +afterEach(() => { + cleanup(); + noteKindsSent([]); +}); +afterAll(async () => { + await settleReactWork(); + timeoutManager.setTimeoutProvider({ + setTimeout: (callback, delay) => + setTimeout(callback, delay) as unknown as number, + clearTimeout: (id) => clearTimeout(id as number), + setInterval: (callback, delay) => + setInterval(callback, delay) as unknown as number, + clearInterval: (id) => clearInterval(id as number), + }); + environmentManager.setIsServer(() => wasServer); + globalThis.fetch = originalFetch; + globals.WebSocket = originalWebSocket; + setCurrentOrganization(originalOrganization); + GlobalRegistrator.unregister(); +}); + +const routine = { + id: "r1", + conversation: { id: "c1", name: null, title: "Daily", gone: false }, +} as unknown as RoutineRecord; + +/** How many approval cards are drawn now: a conversation draws more as the person scrolls back. */ +let cardCount = 0; +let cardsChanged = () => {}; +function showCards(count: number) { + cardCount = count; + cardsChanged(); +} + +/** Approval cards, as many as a long conversation draws, each reading the queue. */ +function Cards() { + const [count, setCount] = useState(cardCount); + cardsChanged = () => setCount(cardCount); + return ( + <> + {Array.from({ length: count }, (_, at) => ( + // biome-ignore lint/suspicious/noArrayIndexKey: fixed cards + + ))} + + ); +} +function Card() { + useQuery(approvalQueueOptions()); + return null; +} + +function Page() { + useChannelEvents(); + return ( + <> + + + + ); +} + +async function draw() { + requests = []; + ServerSocket.opened = []; + cardCount = 0; + const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const router = createRouter({ + routeTree: createRootRoute({ component: Page }), + history: createMemoryHistory({ initialEntries: ["/"] }), + }); + const view = render( + + + , + ); + await waitFor(() => expect(ServerSocket.opened).toHaveLength(1)); + const socket = ServerSocket.opened[0] as ServerSocket; + act(() => socket.onopen?.(new Event("open"))); + await waitFor(() => expect(view.getAllByRole("listitem").length).toBe(21)); + await act(settleReactWork); + return { view, socket, queryClient }; +} + +const runReads = () => + requests.filter((request) => request.startsWith(`${BASE}/routines/r1/runs`)); + +test("the socket asks for the hints", async () => { + await draw(); + const socket = ServerSocket.opened[0] as ServerSocket; + expect( + new URL(socket.url).searchParams.get("capabilities")?.split(" "), + ).toContain("data-changed"); +}); + +test("a month of runs is read one page at a time, polls nothing, and a run the server announces reaches the screen", async () => { + const { view, socket } = await draw(); + // The newest page only, never the 432 pages behind it. + expect(runReads()).toEqual([`${BASE}/routines/r1/runs?limit=20`]); + // The server sends every kind, so nothing on this page polls. + await waitFor(() => expect([...intervals.values()]).toEqual([])); + + // A run starts on the server: a hint about another organization reads nothing... + server.runs = [ + { ...run(-1), id: "run-new", status: "running" } as RoutineRunRecord, + ...server.runs, + ]; + act(() => + socket.say({ changed: ["routines"], organizationId: "org_elsewhere" }), + ); + // ...nor one about something this page doesn't show... + act(() => socket.say({ changed: ["memory"], organizationId: ORG })); + await act(settleReactWork); + expect(runReads()).toHaveLength(1); + expect(view.queryByText(/Running/)).toBeNull(); + + // ...and the one about routines reads the newest page again, once, and the run is on screen. + act(() => + socket.say({ + changed: ["routines", "activity"], + organizationId: ORG, + botId: "b1", + }), + ); + await waitFor(() => expect(view.getAllByText(/Running/).length).toBe(1)); + expect(runReads()).toEqual([ + `${BASE}/routines/r1/runs?limit=20`, + `${BASE}/routines/r1/runs?limit=20`, + ]); + + // Older runs on Show more, one page. + act(() => view.getByRole("button", { name: "Show more" }).click()); + await waitFor(() => expect(view.getAllByRole("listitem").length).toBe(41)); + expect(runReads().at(-1)).toBe(`${BASE}/routines/r1/runs?limit=20&cursor=20`); +}); + +test("from a server that sends no hints, the history is polled only slowly", async () => { + server.sends = []; + await draw(); + const delays = [...intervals.values()].map(({ delay }) => delay); + expect(delays.length).toBeGreaterThan(0); + for (const delay of delays) expect(delay).toBeGreaterThanOrEqual(60_000); + server.sends = [...HINT_KINDS]; +}); + +test("forty approval cards drawn one after another read the queue once, and none of the settings", async () => { + await draw(); + for (let count = 1; count <= 40; count++) { + act(() => showCards(count)); + await act(settleReactWork); + } + const approvalReads = requests.filter((request) => + request.startsWith(`${BASE}/people/me/`), + ); + expect(approvalReads.sort()).toEqual([ + `${BASE}/people/me/approvals?limit=100`, + `${BASE}/people/me/questions?limit=100`, + ]); +}); + +test("a hint names only what it is about", () => { + expect(parseDataChanged('{"changed":["components","future"]}', ORG)).toEqual({ + changed: ["components"], + }); + expect(parseDataChanged('{"changed":["future"]}', ORG)).toBeNull(); + // A conversation's activity is not a hint, nor is a resync. + expect( + parseDataChanged('{"channelId":"c1","changed":["bots"]}', ORG), + ).toBeNull(); + expect(parseDataChanged('{"resync":true}', ORG)).toBeNull(); + // One Bot's components: that Bot's list, not another's. + const [reads] = readsFor("components", "b1"); + expect( + reads?.predicate?.({ queryKey: ["components", "for-agent", "b1"] }), + ).toBe(true); + expect( + reads?.predicate?.({ queryKey: ["components", "for-agent", "b2"] }), + ).toBe(false); + expect(reads?.predicate?.({ queryKey: ["components", "list"] })).toBe(true); +}); diff --git a/app/tests/responsibility-action-refresh.test.ts b/app/tests/responsibility-action-refresh.test.ts index 496ddf027f..366b2bf02e 100644 --- a/app/tests/responsibility-action-refresh.test.ts +++ b/app/tests/responsibility-action-refresh.test.ts @@ -1,16 +1,14 @@ import { expect, test } from "bun:test"; import type { QueryClient } from "@tanstack/react-query"; +import { readsFor } from "../src/lib/live/apply-hints"; +import { HINT_FALLBACK_MS, noteKindsSent } from "../src/lib/live/hinted"; import { responsibilitiesQueryOptions, responsibilityActionMutationOptions, responsibilityKeys, updateResponsibilityMutationOptions, } from "../src/lib/responsibilities"; -import { - ROUTINES_REFETCH_MS, - routineKeys, - routinesQueryOptions, -} from "../src/lib/routines/queries"; +import { routineKeys, routinesQueryOptions } from "../src/lib/routines/queries"; function invalidationRecorder() { const invalidated: unknown[] = []; @@ -72,15 +70,27 @@ test("editing a goal does not refresh routines", async () => { /* * A run that completes its goal finishes after the response, and the server then switches the goal's - * schedules off. Nothing invalidates routines at that moment, so they are polled, at the goals' own - * interval: a goal's row and its dialog are built from both reads, and a completed goal showed its - * schedule still on, or a goal a Bot gave a schedule said "When you ask", until the page was opened - * again. `routines-list-follows-changes.test.tsx` drives it through the list. + * schedules off. Nothing here invalidates routines at that moment: the server says so (its `routines` + * and `activity` hints), and both reads are read again on the same hints, or, from a server that sends + * none, at the same slow interval. A goal's row and its dialog are built from both reads, and a + * completed goal showed its schedule still on until the page was opened again. + * `routines-list-follows-changes.test.tsx` drives it through the list. */ -test("routines are read again at the goals' interval", () => { - expect(ROUTINES_REFETCH_MS).toBeGreaterThan(0); - expect(routinesQueryOptions().refetchInterval).toBe(ROUTINES_REFETCH_MS); - expect(responsibilitiesQueryOptions().refetchInterval).toBe( - ROUTINES_REFETCH_MS, +test("routines and goals are read again on the same hints", () => { + for (const kind of ["routines", "activity"] as const) { + const routines = readsFor(kind).map((reads) => reads.queryKey); + expect(routines).toContainEqual(responsibilityKeys.all); + } + expect(readsFor("routines").map((reads) => reads.queryKey)).toContainEqual( + routineKeys.all, ); + const interval = (options: { refetchInterval?: unknown }) => + (options.refetchInterval as () => number | false)(); + noteKindsSent([]); + expect(interval(routinesQueryOptions())).toBe(HINT_FALLBACK_MS); + expect(interval(responsibilitiesQueryOptions())).toBe(HINT_FALLBACK_MS); + noteKindsSent(["routines", "activity"]); + expect(interval(routinesQueryOptions())).toBe(false); + expect(interval(responsibilitiesQueryOptions())).toBe(false); + noteKindsSent([]); }); diff --git a/app/tests/routines-list-follows-changes.test.tsx b/app/tests/routines-list-follows-changes.test.tsx index 338a65e26e..66347ee526 100644 --- a/app/tests/routines-list-follows-changes.test.tsx +++ b/app/tests/routines-list-follows-changes.test.tsx @@ -17,11 +17,10 @@ import { act, cleanup, render, waitFor } from "@testing-library/react"; import type { ReactNode } from "react"; import { GoalRoutePage } from "@/components/responsibilities/goal-page"; import { RoutinesList } from "@/components/routines/routines-list"; +import { applyHint } from "@/lib/live/apply-hints"; +import { HINT_FALLBACK_MS, noteKindsSent } from "@/lib/live/hinted"; import type { ResponsibilityRecord } from "@/lib/responsibilities"; -import { - ROUTINES_REFETCH_MS, - type RoutineRecord, -} from "@/lib/routines/queries"; +import type { RoutineRecord } from "@/lib/routines/queries"; import { answerBotsList } from "./bots-api"; import { answerScheduleLists, pathOf, ROUTINES_PATH } from "./schedules-api"; import { settleReactWork } from "./settle-react-work"; @@ -29,7 +28,8 @@ import { settleReactWork } from "./settle-react-work"; /** * The Routines list and a goal's page while they stay open: what changes on the server without * this screen (a run completes a goal and the server switches its schedule off, a Bot gives a goal a - * schedule) reaches them within one interval, with no remount. + * schedule) reaches them on the server's hint (`routines`), with no remount; and, from a server that + * sends no hint, within one slow interval. * * The intervals are TanStack Query's own timers, moved by hand through its `timeoutManager`: only * the query's polls are held, and everything else (React, testing-library's waits) keeps real time. @@ -164,9 +164,12 @@ function serving() { ); } +/** The client the page last drawn reads through, to hand it a hint as the socket would. */ +let client: QueryClient; + /** Draws `page` alone, with a client of its own that doesn't retry. */ function draw(page: () => ReactNode) { - const client = new QueryClient({ + client = new QueryClient({ defaultOptions: { queries: { retry: false } }, }); const router = createRouter({ @@ -180,7 +183,8 @@ function draw(page: () => ReactNode) { ); } -test("the Routines list reads routines again at the goals' interval, so a goal's row follows the server", async () => { +test("from a server that sends no hint, the Routines list reads routines again at the goals' slow interval, so a goal's row follows the server", async () => { + noteKindsSent([]); server.goals = [goal()]; server.routines = []; serving(); @@ -193,11 +197,12 @@ test("the Routines list reads routines again at the goals' interval, so a goal's // A Bot gives the goal a schedule. Goals were read again every interval; routines were not, so // the row said "When you ask" until the page was opened again. server.routines = [routine()]; - await act(async () => advance(ROUTINES_REFETCH_MS)); + await act(async () => advance(HINT_FALLBACK_MS)); await waitFor(() => expect(row.textContent).toContain("Weekdays at 09:00")); }); -test("a goal's page follows its schedules while it is open", async () => { +test("a goal's page follows its schedules while it is open, on the server's hints and nothing else", async () => { + noteKindsSent(["routines", "activity"]); server.goals = [goal()]; server.routines = []; serving(); @@ -207,9 +212,12 @@ test("a goal's page follows its schedules while it is open", async () => { expect(view.queryByText("Its events and triggers start it.")).toBeTruthy(), ); - // A Bot gives it a schedule while the page is open. + // Nothing is polled: the server sends these hints. + expect([...intervals.values()]).toEqual([]); + + // A Bot gives it a schedule while the page is open, and the server says so. server.routines = [routine()]; - await act(async () => advance(ROUTINES_REFETCH_MS)); + await act(async () => applyHint(client, { changed: ["routines"] })); await view.findByText("Starts it on a schedule · UTC"); expect( view @@ -220,10 +228,13 @@ test("a goal's page follows its schedules while it is open", async () => { // Its run meets the outcome: the goal completes, and the server switches its schedule off. server.goals = [goal({ status: "completed" })]; server.routines = [routine({ enabled: false })]; - await act(async () => advance(ROUTINES_REFETCH_MS)); + await act(async () => + applyHint(client, { changed: ["routines", "activity"] }), + ); await view.findByText( "The goal is completed, so this schedule won't start it again.", ); expect(view.queryByText("Starts it on a schedule · UTC")).toBeNull(); expect(view.queryByRole("switch")).toBeNull(); + noteKindsSent([]); }); diff --git a/app/tests/skins-openfuse.test.tsx b/app/tests/skins-openfuse.test.tsx index 08932f10bb..d738322609 100644 --- a/app/tests/skins-openfuse.test.tsx +++ b/app/tests/skins-openfuse.test.tsx @@ -26,7 +26,7 @@ import { } from "@testing-library/react"; import { RoutineRoutePage } from "@/components/routines/routine-page"; import type { AgentProfile } from "@/lib/agents/queries"; -import type { ApprovalInboxData } from "@/lib/approvals"; +import type { ApprovalQueueData, ApprovalSettingsData } from "@/lib/approvals"; import type { BotActivity, BotAttention } from "@/lib/bot-lifecycle/queries"; import type { ChannelSummary } from "@/lib/channels/queries"; import { appConfig } from "@/lib/generated/application-config"; @@ -184,7 +184,7 @@ const channels = [ }), ]; -const inbox: ApprovalInboxData = { +const inbox: ApprovalQueueData & Partial = { enabled: true, rules: [], teamRules: [], diff --git a/app/tests/task-thread.test.tsx b/app/tests/task-thread.test.tsx index e287b2e16b..bb3c5b18f6 100644 --- a/app/tests/task-thread.test.tsx +++ b/app/tests/task-thread.test.tsx @@ -33,6 +33,7 @@ import { ThreadLinks, } from "@/components/tasks/task-thread"; import { refreshTaskCards } from "@/lib/channels/use-channel-events"; +import { applyHint } from "@/lib/live/apply-hints"; import { inAppPath, markdownComponents } from "@/lib/markdown"; import { queryClient } from "@/query-client"; import { settleReactWork } from "./settle-react-work"; @@ -458,8 +459,12 @@ test("one card follows its task through every state without a reload: working, n lastActivityAt: ago(4), }; // The card is drawn once and never drawn again: every change below reaches this one card. + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); const view = draw( , + client, ); await view.findByText("Working"); expect(stateOf(view)).toBe("working"); @@ -478,7 +483,11 @@ test("one card follows its task through every state without a reload: working, n // Nothing is counted while it waits on the person. expect(elapsedOf(view)).toBeUndefined(); - // The person stops it in its thread. Its status is failed, and the card does not call it a failure. + /* + * The person stops it in its thread. Its status is failed, and the card does not call it a failure. + * Waiting on the person is not moving, so the card does not read it every few seconds meanwhile: + * the server's word that what waits on the person changed (`needsYou`) reads it again. + */ task = { ...task, status: "failed", @@ -487,6 +496,7 @@ test("one card follows its task through every state without a reload: working, n failedAt: ago(1), stoppedAt: ago(1), }; + applyHint(client, { changed: ["needsYou"] }); await view.findByText("Stopped", {}, { timeout: 6_000 }); expect(stateOf(view)).toBe("stopped"); expect(view.queryByText("Couldn't finish")).toBeNull(); diff --git a/app/tests/waiting-is-not-moving.test.ts b/app/tests/waiting-is-not-moving.test.ts new file mode 100644 index 0000000000..2ff165f1ff --- /dev/null +++ b/app/tests/waiting-is-not-moving.test.ts @@ -0,0 +1,83 @@ +import { afterEach, expect, test } from "bun:test"; +import type { Query } from "@tanstack/react-query"; +import { type GroupConversation, streamingReply } from "@/lib/groups"; +import { HINT_FALLBACK_MS, noteKindsSent } from "@/lib/live/hinted"; +import { + type BotTask, + taskListQueryOptions, + taskQueryOptions, +} from "@/lib/tasks/queries"; + +/** + * WAITING IS NOT MOVING. A task that needs the person's input waits for them, which can be days, and + * the task list was read to its end every three seconds for as long as one did. A group conversation + * read its transcript every second and a half for as long as a reply said it was running, with no + * end, so a reply the server gave up on was read for good. Against a list of three hundred tasks. + */ + +afterEach(() => noteKindsSent([])); + +const task = (at: number, status: string): BotTask => + ({ id: `task-${at}`, status }) as BotTask; + +/** The interval a read's options give for the data it holds. */ +function intervalFor( + options: { refetchInterval?: unknown }, + data: T, +): number | false | undefined { + const interval = options.refetchInterval as + | ((query: Query) => number | false | undefined) + | undefined; + return interval?.({ state: { data } } as Query); +} + +const waiting = Array.from({ length: 300 }, (_, at) => + task(at, at % 3 === 0 ? "needs_input" : "resolved"), +); + +test("three hundred tasks, a hundred of them waiting on the person, are not read again every three seconds", () => { + noteKindsSent(["needsYou"]); + expect(intervalFor(taskListQueryOptions(), waiting)).toBe(false); + // A task card waiting on the person is read on the server's word too. + expect(intervalFor(taskQueryOptions("task-0"), waiting[0])).toBe(false); + // From a server that sends no hint, slowly. + noteKindsSent([]); + expect(intervalFor(taskListQueryOptions(), waiting)).toBe(HINT_FALLBACK_MS); +}); + +test("a task that works is still followed closely where no hint says what it did", () => { + const working = [...waiting, task(300, "working")]; + noteKindsSent([]); + expect(intervalFor(taskListQueryOptions(), working)).toBe(3_000); + expect(intervalFor(taskQueryOptions("task-300"), working.at(-1))).toBe(3_000); + // Every change of a task's state is announced, so the list is read on that word alone. + noteKindsSent(["needsYou"]); + expect(intervalFor(taskListQueryOptions(), working)).toBe(false); +}); + +const group = ( + status: string, + minutesAgo: number, + now: number, +): GroupConversation => + ({ + bots: [], + people: [], + messages: [ + { + status, + agentId: "bot", + createdAt: new Date(now - minutesAgo * 60_000).toISOString(), + }, + ], + }) as unknown as GroupConversation; + +test("a group reply is read as it streams, up to a deadline, and a queued one waits for the conversation's events", () => { + const now = Date.now(); + expect(streamingReply(group("running", 1, now), now)).toBe(true); + // A reply still running after ten minutes is one the server gave up on. + expect(streamingReply(group("running", 11, now), now)).toBe(false); + // Queued: a Bot starting is an event on the conversation, which reads it again. + expect(streamingReply(group("queued", 0, now), now)).toBe(false); + expect(streamingReply(group("completed", 0, now), now)).toBe(false); +}); From 926ed86d5cf7b6019404e436046e29a3ec4c7095 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 14:59:24 -0800 Subject: [PATCH 2/5] Web app hints: group replies still read while owed, the wheel watched only where shown, components asked with their ETag, grants left out of a reconnect's re-read --- .../components/computer/computer-controls.tsx | 2 + .../components/computer/use-cards-first.ts | 11 +- app/src/lib/api/request.ts | 14 ++- app/src/lib/api/revalidated.ts | 40 ++++++ app/src/lib/client.ts | 3 + app/src/lib/components/queries.ts | 45 ++++--- app/src/lib/computers/use-control.ts | 51 ++++++-- app/src/lib/groups.ts | 30 +++-- app/src/lib/live/apply-hints.ts | 13 +- app/tests/components-etag.test.ts | 117 ++++++++++++++++++ app/tests/waiting-is-not-moving.test.ts | 8 +- 11 files changed, 285 insertions(+), 49 deletions(-) create mode 100644 app/src/lib/api/revalidated.ts create mode 100644 app/tests/components-etag.test.ts diff --git a/app/src/components/computer/computer-controls.tsx b/app/src/components/computer/computer-controls.tsx index 34c4f778f6..d140a0bb49 100644 --- a/app/src/components/computer/computer-controls.tsx +++ b/app/src/components/computer/computer-controls.tsx @@ -82,9 +82,11 @@ export function ComputerChatControls({ open: boolean; onOpenChange: (open: boolean) => void; }) { + // Only a sign of the computer while it is closed: read on the server's hint, or slowly without one. const { control, someoneElse } = useComputerControl( computerId ?? "", Boolean(computerId) && !noComputers, + open, ); const needsYou = Boolean( control && diff --git a/app/src/components/computer/use-cards-first.ts b/app/src/components/computer/use-cards-first.ts index 63aef1e331..d7584e6606 100644 --- a/app/src/components/computer/use-cards-first.ts +++ b/app/src/components/computer/use-cards-first.ts @@ -22,7 +22,7 @@ import { * Beside a wide conversation the cards are already in view, and nothing here does anything. * * The cards, by what each is waiting on: the Bot's request to be taken over (its computer's - * wheel, read only while the sheet is open over the conversation), an approval for a step in this conversation (the approvals inbox), and a private sign-in + * wheel, watched while the sheet is open over the conversation), an approval for a step in this conversation (the approvals inbox), and a private sign-in * this conversation's Bot asked for (the sign-in requests, read only where the sheet covers). */ export function useCardsFirst({ @@ -45,13 +45,14 @@ export function useCardsFirst({ computers?: boolean; }): { cardWaiting: boolean } { /* - * The wheel matters here only while the Computer is open as a sheet over the conversation: that is - * when a take-over waiting under it closes it. Read only then, not on every conversation of a Bot - * with a computer. + * The wheel, as every view of this computer shares it (read on the server's hint). It is watched + * only while the Computer is open as a sheet over the conversation, which is when a take-over + * waiting under it closes it; otherwise this is only a sign of it. */ const { control } = useComputerControl( botId ?? "", - Boolean(botId) && computers && covers && watching, + Boolean(botId) && computers, + covers && watching, ); const inbox = useQuery(approvalQueueOptions()); const signIns = useQuery({ diff --git a/app/src/lib/api/request.ts b/app/src/lib/api/request.ts index 4b474c9fc2..e03ba0e98c 100644 --- a/app/src/lib/api/request.ts +++ b/app/src/lib/api/request.ts @@ -21,6 +21,12 @@ export type ApiRequestOptions = RequestInit & { * trail an export holds. */ onResponse?: (response: Response) => void; + /** + * The answer the caller already holds, with the ETag it came with: sent as If-None-Match, and a 304 + * (the page unchanged) is answered with it, so an unchanged page costs no body. See + * `revalidated` in lib/api/revalidated.ts. + */ + kept?: { etag: string; body: unknown }; }; /** @@ -63,9 +69,15 @@ export async function apiRequest( url: string, options: ApiRequestOptions = {}, ): Promise { - const { fallback, onResponse, ...init } = options; + const { fallback, onResponse, kept, ...init } = options; + if (kept) { + const headers = new Headers(init.headers); + headers.set("If-None-Match", kept.etag); + init.headers = headers; + } const response = await clientRequest(url, init, fallback); onResponse?.(response); + if (response.status === 304 && kept) return kept.body as T; if (response.status === 204) return undefined as T; const type = response.headers.get("content-type") ?? ""; if (TEXT_ANSWERS.some((answer) => type.startsWith(answer))) { diff --git a/app/src/lib/api/revalidated.ts b/app/src/lib/api/revalidated.ts new file mode 100644 index 0000000000..cc5aa23aa8 --- /dev/null +++ b/app/src/lib/api/revalidated.ts @@ -0,0 +1,40 @@ +import type { ApiRequestOptions } from "./request"; + +/** + * READ AGAIN FOR THE PRICE OF A 304. An answer that comes with an ETag is kept here with it, and the + * next read of the same page names it in If-None-Match: while the page is unchanged the server + * answers 304 with no body, and the kept answer stands. Asked by the app itself, not left to the + * browser's cache, which OpenBot Desktop's relay and a `no-store` answer from an older server both + * leave out. + * + * Kept per page, under a key that names the organization and everything the request asked; a page + * whose answer carries no ETag (an older server) is not kept, and every read of it is whole. + */ +const held = new Map(); + +/** The most pages kept: a page per Bot drawn and a few lists, with room to spare. */ +const MOST_KEPT = 200; + +export async function revalidated( + key: string, + read: (options: Pick) => Promise, +): Promise { + const kept = held.get(key); + let etag: string | null = null; + const body = await read({ + ...(kept ? { kept } : {}), + onResponse: (response) => { + etag = response.headers.get("ETag"); + }, + }); + held.delete(key); + if (etag) { + held.set(key, { etag, body }); + // The oldest kept page goes first: a Map keeps the order pages were set in. + if (held.size > MOST_KEPT) { + const oldest = held.keys().next().value; + if (oldest !== undefined) held.delete(oldest); + } + } + return body; +} diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 5e70dbf8bf..204701af95 100644 --- a/app/src/lib/client.ts +++ b/app/src/lib/client.ts @@ -332,6 +332,9 @@ export async function clientRequest( fallback?: string, ): Promise { const response = await request(path, init); + // A 304 is an answer only to a request that named the copy it holds (`If-None-Match`). + if (response.status === 304 && new Headers(init.headers).has("If-None-Match")) + return response; if (!response.ok) throw await refusal(response, fallback, { path, init }); return response; } diff --git a/app/src/lib/components/queries.ts b/app/src/lib/components/queries.ts index bc0bf88643..73134128ff 100644 --- a/app/src/lib/components/queries.ts +++ b/app/src/lib/components/queries.ts @@ -13,6 +13,7 @@ import type { ComponentListViewParameter, } from "@/lib/api/generated/model"; import { idempotencyKey, organizationId } from "@/lib/api/request"; +import { revalidated } from "@/lib/api/revalidated"; import { ClientError } from "@/lib/client"; import { hinted } from "@/lib/live/hinted"; @@ -133,22 +134,27 @@ function componentRecord(component: Component): ComponentRecord { * as `view` asks for (listComponents): `summary` leaves out every source and draft, `published` every * draft. A server from before `view` sends everything, which reads the same. * - * Each page answers with an ETag and allows the browser to keep it only to ask again with it, so a - * page read again unchanged comes back 304, with no body, and the browser hands back the copy it kept. + * Each page answers with an ETag, and is asked for again with it (`revalidated`): a page read again + * unchanged comes back 304, with no body, and the page already held stands. */ async function everyComponent( options: { kind?: string; view?: ComponentListViewParameter } = {}, ): Promise { return everyPage(async (cursor) => { - const page = await listComponents( - organizationId(), - { - limit: 100, - ...(options.kind === undefined ? {} : { kind: options.kind }), - ...(options.view === undefined ? {} : { view: options.view }), - ...(cursor === undefined ? {} : { cursor }), - }, - { fallback: "The components could not be loaded." }, + const organization = organizationId(); + const params = { + limit: 100, + ...(options.kind === undefined ? {} : { kind: options.kind }), + ...(options.view === undefined ? {} : { view: options.view }), + ...(cursor === undefined ? {} : { cursor }), + }; + const page = await revalidated( + JSON.stringify(["components", organization, params]), + (kept) => + listComponents(organization, params, { + fallback: "The components could not be loaded.", + ...kept, + }), ); return { items: page.components, nextCursor: page.nextCursor }; }); @@ -184,11 +190,18 @@ export function agentComponentsQueryOptions(agentId: string | undefined) { refetchOnWindowFocus: true, queryFn: async (): Promise => everyPage(async (cursor) => { - const page = await listBotComponents( - organizationId(), - agentId ?? "", - { limit: 100, ...(cursor === undefined ? {} : { cursor }) }, - { fallback: "This Bot's components could not be loaded." }, + const organization = organizationId(); + const params = { + limit: 100, + ...(cursor === undefined ? {} : { cursor }), + }; + const page = await revalidated( + JSON.stringify(["bot-components", organization, agentId, params]), + (kept) => + listBotComponents(organization, agentId ?? "", params, { + fallback: "This Bot's components could not be loaded.", + ...kept, + }), ); return { items: page.components, nextCursor: page.nextCursor }; }), diff --git a/app/src/lib/computers/use-control.ts b/app/src/lib/computers/use-control.ts index d5b8238622..bc03490b75 100644 --- a/app/src/lib/computers/use-control.ts +++ b/app/src/lib/computers/use-control.ts @@ -1,5 +1,5 @@ import { useQuery } from "@tanstack/react-query"; -import { useSyncExternalStore } from "react"; +import { useCallback, useSyncExternalStore } from "react"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { type Hint, hintsSent, onHint } from "@/lib/live/hinted"; import { queryClient } from "@/query-client"; @@ -23,8 +23,15 @@ type ControlStore = { getSnapshot: () => Snapshot; refresh: () => Promise; change: (action: Action) => Promise; - subscribe: (listener: () => void) => () => void; + /** `watching`: the one subscribing shows the computer itself, not only a sign of it. */ + subscribe: (listener: () => void, watching: boolean) => () => void; }; + +/** + * How often a computer nobody is watching is read, on a server that sends no hint when its wheel + * changes hands: often enough for the Computer button's "needs you" mark to follow. + */ +const UNWATCHED_READ_MS = 30_000; const stores = new Map(); /** How many reads in a row may fail before input is paused: two, about two seconds. */ const MISSED_READS_BEFORE_PAUSE = 2; @@ -40,11 +47,16 @@ function createControlStore(computerId: string): ControlStore { /** The last read answered that the Bot is not this person's to use. See `refresh`. */ let gone = false; const listeners = new Set<() => void>(); + /** The subscribers that show the computer itself (its screen, terminal, or the sheet over a chat). */ + let watchers = 0; + /** When it was last read, for the slow read of a computer nobody watches. */ + let readAt = 0; const publish = (next: Snapshot) => { snapshot = next; for (const listener of listeners) listener(); }; const refresh = async () => { + readAt = Date.now(); const mine = version; reading?.abort(); const abort = new AbortController(); @@ -151,16 +163,19 @@ function createControlStore(computerId: string): ControlStore { * and the computer starting or sleeping are all announced (the `computers` hint, `lib/live`), so the * wheel is read when one about this computer arrives. It was read every second on every open * conversation of a Bot with a computer, whether or not anybody looked at it: 60 requests a minute. - * A server that sends no such hint has it read every second as before, while somebody watches. + * A server that sends no such hint has it read every second as before while somebody watches the + * computer (its screen, its terminal, the sheet over a conversation), and every half minute while + * only a sign of it shows (the Computer button's "needs you"). */ const pollTick = () => { - if (document.hidden || gone) return; + if (document.hidden || gone || snapshot.busy || reading) return; if (hintsSent("computers")) { // A read that did not come back is tried again soon, since no tick follows it. - if (failures > 0 && !snapshot.busy && !reading) void refresh(); + if (failures > 0) void refresh(); return; } - if (!snapshot.busy && !reading) void refresh(); + if (watchers > 0 || Date.now() - readAt >= UNWATCHED_READ_MS) + void refresh(); }; const onComputerHint = (hint: Hint) => { if (!hint.changed.includes("computers")) return; @@ -172,8 +187,9 @@ function createControlStore(computerId: string): ControlStore { getSnapshot: () => snapshot, refresh, change, - subscribe: (listener: () => void) => { + subscribe: (listener: () => void, watching: boolean) => { listeners.add(listener); + if (watching) watchers++; if (timer === undefined) { if (!snapshot.busy) void refresh(); // Not while the tab is hidden: nobody is looking, and it is read again the moment they are. @@ -183,6 +199,7 @@ function createControlStore(computerId: string): ControlStore { } return () => { listeners.delete(listener); + if (watching) watchers--; if (listeners.size) return; clearInterval(timer); timer = undefined; @@ -197,7 +214,6 @@ function createControlStore(computerId: string): ControlStore { }; return store; } -const noSubscription = () => () => undefined; const emptySnapshot = () => EMPTY; /** * Whether a person other than the signed-in one holds the wheel. @@ -220,14 +236,29 @@ export function heldByOther( ); } -export function useComputerControl(computerId: string, enabled = true) { +/** + * Who has a computer's wheel, shared by every view of that computer. `watching` is false for a view + * that shows only a sign of the computer (its button's "needs you"), not the computer itself: on a + * server that sends no hint when the wheel changes hands, a computer only signed is read every half + * minute, a watched one every second. + */ +export function useComputerControl( + computerId: string, + enabled = true, + watching = true, +) { let store = enabled ? stores.get(computerId) : undefined; if (enabled && !store) { store = createControlStore(computerId); stores.set(computerId, store); } + const subscribe = useCallback( + (listener: () => void) => + store ? store.subscribe(listener, watching) : () => undefined, + [store, watching], + ); const snapshot = useSyncExternalStore( - store?.subscribe ?? noSubscription, + subscribe, store?.getSnapshot ?? emptySnapshot, emptySnapshot, ); diff --git a/app/src/lib/groups.ts b/app/src/lib/groups.ts index f1f9aa6d54..3d67dd4791 100644 --- a/app/src/lib/groups.ts +++ b/app/src/lib/groups.ts @@ -124,9 +124,10 @@ export const groupKeys = { }; /** - * The shared transcript. Bot turns run on the server with nobody's browser attached. A Bot starting, - * finishing or queued moves the conversation's events, which read this again; while a reply streams - * its words are read every second and a half, up to a deadline ({@link streamingReply}). + * The shared transcript. Bot turns run on the server with nobody's browser attached, so while a turn + * is owed an answer the page reads it every second and a half, up to a deadline + * ({@link streamingReply}), and stops once every Bot has spoken. Otherwise the conversation's own + * events read it again (`useChannelEvents`). */ export function groupQueryOptions(channelId: string) { return queryOptions({ @@ -172,21 +173,23 @@ export function groupQueryOptions(channelId: string) { export const GROUP_STREAM_MS = 10 * 60_000; /** - * Whether a Bot's reply is being written now, so its words are read again every second and a half - * as they stream: a reply running, begun within {@link GROUP_STREAM_MS}. Nothing else is polled: a - * Bot starting, finishing or being queued moves the conversation's own events, which read the - * transcript again (`useChannelEvents`). + * Whether a turn is owed an answer now, so the transcript is read again every second and a half: a + * reply queued or running, begun within {@link GROUP_STREAM_MS}, or the person's last line not yet + * answered (`awaitingFirstReply`, bounded the same way). A reply that says it is running past the + * deadline is one the server gave up on; it used to be read for as long as it said so, for good. */ export function streamingReply( data: GroupConversation | undefined, now = Date.now(), ): boolean { return ( - data?.messages.some( + (data?.messages.some( (message) => - message.status === "running" && + (message.status === "running" || message.status === "queued") && now - Date.parse(message.createdAt) < GROUP_STREAM_MS, - ) ?? false + ) ?? + false) || + awaitingFirstReply(data, now) ); } @@ -195,12 +198,15 @@ export function streamingReply( * so a turn the server gave up on before any Bot started does not poll for ever. The transcript * draws "Thinking" under that line for as long as this holds (`group-chat.tsx`). */ -export function awaitingFirstReply(data: GroupConversation | undefined) { +export function awaitingFirstReply( + data: GroupConversation | undefined, + now = Date.now(), +) { const last = data?.messages.at(-1); return ( last !== undefined && last.agentId === null && - Date.now() - Date.parse(last.createdAt) < 10 * 60_000 + now - Date.parse(last.createdAt) < GROUP_STREAM_MS ); } diff --git a/app/src/lib/live/apply-hints.ts b/app/src/lib/live/apply-hints.ts index c53ad3cdb7..f9382972c3 100644 --- a/app/src/lib/live/apply-hints.ts +++ b/app/src/lib/live/apply-hints.ts @@ -209,5 +209,16 @@ export function retimeReads(queryClient: QueryClient): void { * server's resync, asks for, since any hint sent while the socket was down was never heard. */ export function applyEveryHint(queryClient: QueryClient): void { - applyHint(queryClient, { changed: HINT_KINDS }); + applyHint(queryClient, { changed: HINT_KINDS.filter(missedHintsReread) }); +} + +/** + * Every kind but `grants`. A Bot's grants are read for every Bot the home page draws, a few large + * apps whole being twenty pages each, and every tab reconnects at once after a deploy: read again + * for all of them then, they were the load that slowed OpenBot Cloud on 2026-11-30. They are taken + * as they stand for a minute and read again when the window is looked at (`plugins/queries.ts`), + * which a missed hint costs at most. + */ +function missedHintsReread(kind: HintKind): boolean { + return kind !== "grants"; } diff --git a/app/tests/components-etag.test.ts b/app/tests/components-etag.test.ts new file mode 100644 index 0000000000..b502acf7af --- /dev/null +++ b/app/tests/components-etag.test.ts @@ -0,0 +1,117 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClient } from "@tanstack/react-query"; +import { + agentComponentsQueryOptions, + publishedPlaygroundQueryOptions, +} from "@/lib/components/queries"; +import { + currentOrganizationId, + setCurrentOrganization, +} from "@/lib/organizations/current"; + +/** + * A COMPONENTS LIST READ AGAIN UNCHANGED COSTS A 304. A conversation reads a Bot's components and + * every published Playground component's source; both were read whole every few seconds. Now each + * page comes with an ETag, the app asks with it (If-None-Match), and an unchanged page is answered + * 304 with no body while the page it holds stands. Sixty published components with large sources. + */ + +const ORG = "default"; +const BASE = `/api/v2/organizations/${ORG}`; +const SOURCE = "x".repeat(20_000); + +const published = Array.from({ length: 60 }, (_, at) => ({ + name: `custom_card_${at}`, + title: `Card ${at}`, + kind: "playground", + published: true, + publishedAt: "2026-11-01T00:00:00.000Z", + description: "A card.", + source: { + html: `
    ${SOURCE}
    `, + css: "", + jsFunctions: "", + argumentSchema: {}, + revision: 1, + }, + draft: null, + hasUnpublishedChanges: null, + withheldFrom: null, + functions: null, + updatedBy: null, + updatedAt: "2026-11-01T00:00:00.000Z", +})); + +/** What each request asked with, and how it was answered. */ +const seen: { path: string; ifNoneMatch: string | null; status: number }[] = []; +let version = 1; +const NativeResponse = globalThis.Response; +const originalFetch = globalThis.fetch; +let originalOrganization: string | undefined; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://127.0.0.1:3010" }); + originalOrganization = currentOrganizationId(); + setCurrentOrganization(ORG); + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const url = new URL(String(input), "http://127.0.0.1:3010"); + const ifNoneMatch = new Headers(init?.headers).get("If-None-Match"); + const etag = `"v${version}-${url.search}"`; + const answer = (status: number, body?: unknown) => { + seen.push({ path: `${url.pathname}${url.search}`, ifNoneMatch, status }); + return status === 304 + ? new NativeResponse(null, { status, headers: { ETag: etag } }) + : NativeResponse.json(body, { headers: { ETag: etag } }); + }; + if (ifNoneMatch === etag) return answer(304); + if (url.pathname === `${BASE}/components`) + return answer(200, { components: published, nextCursor: null }); + if (url.pathname === `${BASE}/bots/b1/components`) + return answer(200, { + components: [{ name: "showBarChart", description: "A chart." }], + nextCursor: null, + }); + return NativeResponse.json({ error: "not served" }, { status: 404 }); + }) as unknown as typeof fetch; +}); + +afterAll(() => { + globalThis.fetch = originalFetch; + setCurrentOrganization(originalOrganization); + GlobalRegistrator.unregister(); +}); + +test("an unchanged page is asked for with its ETag and answered 304, and a changed one is read whole", async () => { + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const first = await client.fetchQuery(publishedPlaygroundQueryOptions()); + expect(first).toHaveLength(60); + await client.fetchQuery(agentComponentsQueryOptions("b1")); + expect(seen.map(({ ifNoneMatch, status }) => [ifNoneMatch, status])).toEqual([ + [null, 200], + [null, 200], + ]); + // A conversation draws only the published source, never the drafts. + expect(seen[0]?.path).toBe( + `${BASE}/components?limit=100&kind=playground&view=published`, + ); + + // Read again (a hint, a window looked at again): unchanged, a 304 each, and the same answer. + await client.invalidateQueries(); + const again = await client.fetchQuery(publishedPlaygroundQueryOptions()); + const bot = await client.fetchQuery(agentComponentsQueryOptions("b1")); + expect(again).toEqual(first); + expect(bot).toEqual([{ name: "showBarChart", description: "A chart." }]); + expect(seen.slice(2).map(({ status }) => status)).toEqual([304, 304]); + expect(seen[2]?.ifNoneMatch).toBe( + '"v1-?limit=100&kind=playground&view=published"', + ); + + // A component published again: the page has a new ETag, and is read whole. + version = 2; + await client.invalidateQueries(); + await client.fetchQuery(publishedPlaygroundQueryOptions()); + expect(seen.at(-1)?.status).toBe(200); +}); diff --git a/app/tests/waiting-is-not-moving.test.ts b/app/tests/waiting-is-not-moving.test.ts index 2ff165f1ff..51f225e5f8 100644 --- a/app/tests/waiting-is-not-moving.test.ts +++ b/app/tests/waiting-is-not-moving.test.ts @@ -72,12 +72,12 @@ const group = ( ], }) as unknown as GroupConversation; -test("a group reply is read as it streams, up to a deadline, and a queued one waits for the conversation's events", () => { +test("a group reply is read while it is owed, up to a deadline, and not after", () => { const now = Date.now(); expect(streamingReply(group("running", 1, now), now)).toBe(true); - // A reply still running after ten minutes is one the server gave up on. + expect(streamingReply(group("queued", 0, now), now)).toBe(true); + // A reply still running or queued after ten minutes is one the server gave up on. expect(streamingReply(group("running", 11, now), now)).toBe(false); - // Queued: a Bot starting is an event on the conversation, which reads it again. - expect(streamingReply(group("queued", 0, now), now)).toBe(false); + expect(streamingReply(group("queued", 11, now), now)).toBe(false); expect(streamingReply(group("completed", 0, now), now)).toBe(false); }); From 9b0159c775effd631a509b97e04911cc629e30a2 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 15:01:08 -0800 Subject: [PATCH 3/5] Web app hints: every view of a computer shares its wheel's read, which runs only on the server's hint where the server sends one --- .../components/computer/computer-controls.tsx | 2 - .../components/computer/use-cards-first.ts | 8 +-- app/src/lib/computers/use-control.ts | 51 ++++--------------- 3 files changed, 11 insertions(+), 50 deletions(-) diff --git a/app/src/components/computer/computer-controls.tsx b/app/src/components/computer/computer-controls.tsx index d140a0bb49..34c4f778f6 100644 --- a/app/src/components/computer/computer-controls.tsx +++ b/app/src/components/computer/computer-controls.tsx @@ -82,11 +82,9 @@ export function ComputerChatControls({ open: boolean; onOpenChange: (open: boolean) => void; }) { - // Only a sign of the computer while it is closed: read on the server's hint, or slowly without one. const { control, someoneElse } = useComputerControl( computerId ?? "", Boolean(computerId) && !noComputers, - open, ); const needsYou = Boolean( control && diff --git a/app/src/components/computer/use-cards-first.ts b/app/src/components/computer/use-cards-first.ts index d7584e6606..1b9bcdccba 100644 --- a/app/src/components/computer/use-cards-first.ts +++ b/app/src/components/computer/use-cards-first.ts @@ -22,7 +22,7 @@ import { * Beside a wide conversation the cards are already in view, and nothing here does anything. * * The cards, by what each is waiting on: the Bot's request to be taken over (its computer's - * wheel, watched while the sheet is open over the conversation), an approval for a step in this conversation (the approvals inbox), and a private sign-in + * wheel), an approval for a step in this conversation (the approvals inbox), and a private sign-in * this conversation's Bot asked for (the sign-in requests, read only where the sheet covers). */ export function useCardsFirst({ @@ -44,15 +44,9 @@ export function useCardsFirst({ /** This OpenBot has computers for Bots, so the wheel can be read. */ computers?: boolean; }): { cardWaiting: boolean } { - /* - * The wheel, as every view of this computer shares it (read on the server's hint). It is watched - * only while the Computer is open as a sheet over the conversation, which is when a take-over - * waiting under it closes it; otherwise this is only a sign of it. - */ const { control } = useComputerControl( botId ?? "", Boolean(botId) && computers, - covers && watching, ); const inbox = useQuery(approvalQueueOptions()); const signIns = useQuery({ diff --git a/app/src/lib/computers/use-control.ts b/app/src/lib/computers/use-control.ts index bc03490b75..387d99c048 100644 --- a/app/src/lib/computers/use-control.ts +++ b/app/src/lib/computers/use-control.ts @@ -1,5 +1,5 @@ import { useQuery } from "@tanstack/react-query"; -import { useCallback, useSyncExternalStore } from "react"; +import { useSyncExternalStore } from "react"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { type Hint, hintsSent, onHint } from "@/lib/live/hinted"; import { queryClient } from "@/query-client"; @@ -23,15 +23,8 @@ type ControlStore = { getSnapshot: () => Snapshot; refresh: () => Promise; change: (action: Action) => Promise; - /** `watching`: the one subscribing shows the computer itself, not only a sign of it. */ - subscribe: (listener: () => void, watching: boolean) => () => void; + subscribe: (listener: () => void) => () => void; }; - -/** - * How often a computer nobody is watching is read, on a server that sends no hint when its wheel - * changes hands: often enough for the Computer button's "needs you" mark to follow. - */ -const UNWATCHED_READ_MS = 30_000; const stores = new Map(); /** How many reads in a row may fail before input is paused: two, about two seconds. */ const MISSED_READS_BEFORE_PAUSE = 2; @@ -47,16 +40,11 @@ function createControlStore(computerId: string): ControlStore { /** The last read answered that the Bot is not this person's to use. See `refresh`. */ let gone = false; const listeners = new Set<() => void>(); - /** The subscribers that show the computer itself (its screen, terminal, or the sheet over a chat). */ - let watchers = 0; - /** When it was last read, for the slow read of a computer nobody watches. */ - let readAt = 0; const publish = (next: Snapshot) => { snapshot = next; for (const listener of listeners) listener(); }; const refresh = async () => { - readAt = Date.now(); const mine = version; reading?.abort(); const abort = new AbortController(); @@ -163,19 +151,16 @@ function createControlStore(computerId: string): ControlStore { * and the computer starting or sleeping are all announced (the `computers` hint, `lib/live`), so the * wheel is read when one about this computer arrives. It was read every second on every open * conversation of a Bot with a computer, whether or not anybody looked at it: 60 requests a minute. - * A server that sends no such hint has it read every second as before while somebody watches the - * computer (its screen, its terminal, the sheet over a conversation), and every half minute while - * only a sign of it shows (the Computer button's "needs you"). + * Only a server that sends no such hint has it read every second, as before. */ const pollTick = () => { - if (document.hidden || gone || snapshot.busy || reading) return; + if (document.hidden || gone) return; if (hintsSent("computers")) { // A read that did not come back is tried again soon, since no tick follows it. - if (failures > 0) void refresh(); + if (failures > 0 && !snapshot.busy && !reading) void refresh(); return; } - if (watchers > 0 || Date.now() - readAt >= UNWATCHED_READ_MS) - void refresh(); + if (!snapshot.busy && !reading) void refresh(); }; const onComputerHint = (hint: Hint) => { if (!hint.changed.includes("computers")) return; @@ -187,9 +172,8 @@ function createControlStore(computerId: string): ControlStore { getSnapshot: () => snapshot, refresh, change, - subscribe: (listener: () => void, watching: boolean) => { + subscribe: (listener: () => void) => { listeners.add(listener); - if (watching) watchers++; if (timer === undefined) { if (!snapshot.busy) void refresh(); // Not while the tab is hidden: nobody is looking, and it is read again the moment they are. @@ -199,7 +183,6 @@ function createControlStore(computerId: string): ControlStore { } return () => { listeners.delete(listener); - if (watching) watchers--; if (listeners.size) return; clearInterval(timer); timer = undefined; @@ -214,6 +197,7 @@ function createControlStore(computerId: string): ControlStore { }; return store; } +const noSubscription = () => () => undefined; const emptySnapshot = () => EMPTY; /** * Whether a person other than the signed-in one holds the wheel. @@ -236,29 +220,14 @@ export function heldByOther( ); } -/** - * Who has a computer's wheel, shared by every view of that computer. `watching` is false for a view - * that shows only a sign of the computer (its button's "needs you"), not the computer itself: on a - * server that sends no hint when the wheel changes hands, a computer only signed is read every half - * minute, a watched one every second. - */ -export function useComputerControl( - computerId: string, - enabled = true, - watching = true, -) { +export function useComputerControl(computerId: string, enabled = true) { let store = enabled ? stores.get(computerId) : undefined; if (enabled && !store) { store = createControlStore(computerId); stores.set(computerId, store); } - const subscribe = useCallback( - (listener: () => void) => - store ? store.subscribe(listener, watching) : () => undefined, - [store, watching], - ); const snapshot = useSyncExternalStore( - subscribe, + store?.subscribe ?? noSubscription, store?.getSnapshot ?? emptySnapshot, emptySnapshot, ); From 4b154fe49e43df14927b35e1c18f08ee622cd46e Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 19:31:17 -0800 Subject: [PATCH 4/5] Web app hints: a reconnect or resync re-reads hint-fed lists inside the spread-out read Main now waits a random 0 to 2 s before a reconnected or resynced socket reads its lists again (#2668). The hint-fed reads join that read instead of going out the moment the socket opens, so a deploy that drops every tab doesn't bring their hint-fed reads back together. The first opening reads only the lists, as before. --- app/src/lib/channels/use-channel-events.ts | 34 +++++----- .../conversation-socket-reconnect.test.tsx | 67 +++++++++++++++++++ 2 files changed, 84 insertions(+), 17 deletions(-) diff --git a/app/src/lib/channels/use-channel-events.ts b/app/src/lib/channels/use-channel-events.ts index 71dd68e671..736ae067ef 100644 --- a/app/src/lib/channels/use-channel-events.ts +++ b/app/src/lib/channels/use-channel-events.ts @@ -695,15 +695,8 @@ export function useChannelEvents() { let wasOpen = false; let stopped = false; - /** - * Read the lists again, as nothing patched while it was not heard can be trusted. After a - * reconnect or a resync (`missedHints`), hints sent meanwhile were never heard either: every - * hint-fed read is marked stale too (`lib/live/apply-hints.ts`), and those on screen read again. - * Not on the first opening, which follows the page's own first reads. - */ - const readAgain = (missedHints: boolean) => { - readTimer = undefined; - if (missedHints) applyEveryHint(queryClient); + /** Read the lists, as nothing patched while the socket was not heard can be trusted. */ + const readLists = () => { // An artifact open on screen reads its comments and viewers again, as the roster does. resyncArtifacts(); void queryClient.invalidateQueries({ queryKey: channelKeys.list() }); @@ -711,16 +704,23 @@ export function useChannelEvents() { void queryClient.invalidateQueries({ queryKey: channelKeys.byBots() }); }; /** - * The same read, after a random moment (`recoveryReadDelayMs`): what every open tab does at - * once, after a deploy or a resync, is spread out rather than sent together, hint-fed reads - * among them. One wait at a time. + * After a reconnect or a resync, hints sent meanwhile were never heard either: every hint-fed + * read is marked stale too (`lib/live/apply-hints.ts`), and those on screen read again, with + * the lists. Not on the first opening, which follows the page's own first reads. + */ + const readAgain = () => { + readTimer = undefined; + applyEveryHint(queryClient); + readLists(); + }; + /** + * That read, after a random moment (`recoveryReadDelayMs`): what every open tab does at once, + * after a deploy or a resync, is spread out rather than sent together, hint-fed reads among + * them. One wait at a time. */ const readAgainSoon = () => { if (readTimer !== undefined) return; - readTimer = window.setTimeout( - () => readAgain(true), - recoveryReadDelayMs(), - ); + readTimer = window.setTimeout(readAgain, recoveryReadDelayMs()); }; const connect = () => { @@ -739,7 +739,7 @@ export function useChannelEvents() { * the page loads; on a reconnect after a random moment, since a deploy brings every tab back. */ if (wasOpen) readAgainSoon(); - else readAgain(false); + else readLists(); wasOpen = true; }; diff --git a/app/tests/conversation-socket-reconnect.test.tsx b/app/tests/conversation-socket-reconnect.test.tsx index b92f07418d..7598b79dda 100644 --- a/app/tests/conversation-socket-reconnect.test.tsx +++ b/app/tests/conversation-socket-reconnect.test.tsx @@ -18,6 +18,7 @@ import { reconnectDelayMs, useChannelEvents, } from "@/lib/channels/use-channel-events"; +import { type Hint, onHint } from "@/lib/live/hinted"; import { currentOrganizationId, setCurrentOrganization, @@ -219,6 +220,72 @@ test("after a deploy, the tabs it dropped reconnect and read their conversations }); }, 10_000); +/** + * The reads fed by the server's change hints (`lib/live/apply-hints.ts`) are read again after a + * reconnect or a resync too, since a hint sent while the socket was down was never heard. They join + * the spread-out read rather than going out the moment the socket opens, which every tab dropped by a + * deploy would do together; the first opening, which follows the page's own reads, reads none. + */ +test("a reconnect or a resync reads every hint-fed list again but a Bot's grants, within the spread, never at the moment it opens", async () => { + ServerSocket.opened = []; + const heard: Hint[] = []; + const stop = onHint((hint) => heard.push(hint)); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false, staleTime: Infinity } }, + }); + render( + ( + + + + ), + }), + history: createMemoryHistory({ initialEntries: ["/"] }), + })} + />, + ); + await waitFor(() => expect(ServerSocket.opened).toHaveLength(1)); + const first = ServerSocket.opened[0] as ServerSocket; + act(() => first.onopen?.(new Event("open"))); + await act(settleReactWork); + expect(heard).toHaveLength(0); + + const missed = (hint: Hint | undefined) => { + expect(hint?.changed).toContain("memory"); + expect(hint?.changed).toContain("approvals"); + expect(hint?.changed).not.toContain("grants"); + }; + + // The socket drops and comes back: nothing at the moment it opens, the hint-fed reads soon after. + act(() => first.onclose?.(new CloseEvent("close", { code: 1006 }))); + await waitFor(() => expect(ServerSocket.opened).toHaveLength(2), { + timeout: 2_000, + }); + const second = ServerSocket.opened[1] as ServerSocket; + act(() => second.onopen?.(new Event("open"))); + expect(heard).toHaveLength(0); + await waitFor(() => expect(heard).toHaveLength(1), { + timeout: RECOVERY_READ_SPREAD_MS + 1_000, + }); + missed(heard[0]); + + // The server's resync: the same, within the spread. + act(() => + second.onmessage?.( + new MessageEvent("message", { data: JSON.stringify({ resync: true }) }), + ), + ); + expect(heard).toHaveLength(1); + await waitFor(() => expect(heard).toHaveLength(2), { + timeout: RECOVERY_READ_SPREAD_MS + 1_000, + }); + missed(heard[1]); + stop(); +}, 10_000); + test("the wait before reconnecting grows with each try, up to thirty seconds, and is drawn anywhere below that", () => { const draws = Array.from({ length: 10_000 }, (_, client) => client / 10_000); for (const [attempt, ceiling] of [ From c49a7679890aeddc8d9a4163e41460e00859b907 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 23:29:52 -0800 Subject: [PATCH 5/5] Format the two approval-left tests' imports --- app/tests/approval-left-carry-on-browser.test.tsx | 5 +---- app/tests/approval-left-carry-on.test.tsx | 5 +---- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/app/tests/approval-left-carry-on-browser.test.tsx b/app/tests/approval-left-carry-on-browser.test.tsx index 0e6e1c711f..d4178a1755 100644 --- a/app/tests/approval-left-carry-on-browser.test.tsx +++ b/app/tests/approval-left-carry-on-browser.test.tsx @@ -5,10 +5,7 @@ import type { Server } from "bun"; import type { Browser, BrowserType, Page } from "playwright-core"; import { compile } from "tailwindcss"; import { getGetBotResponseMock } from "@/lib/api/generated/bots/bots.msw"; -import type { - ApprovalQueueData, - ApprovalSettingsData, -} from "@/lib/approvals"; +import type { ApprovalQueueData, ApprovalSettingsData } from "@/lib/approvals"; import { TURN_INTERRUPTED } from "@/lib/copilot/stopped-turn"; import { personBody } from "./accounts-api"; import { approvalInboxResponse } from "./approvals-api"; diff --git a/app/tests/approval-left-carry-on.test.tsx b/app/tests/approval-left-carry-on.test.tsx index 16ef7f6574..7b82d5bb27 100644 --- a/app/tests/approval-left-carry-on.test.tsx +++ b/app/tests/approval-left-carry-on.test.tsx @@ -6,10 +6,7 @@ import { QueryClientProvider } from "@tanstack/react-query"; import { act, cleanup, render, waitFor, within } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { ChannelChat } from "@/components/channels/channel-chat"; -import type { - ApprovalQueueData, - ApprovalSettingsData, -} from "@/lib/approvals"; +import type { ApprovalQueueData, ApprovalSettingsData } from "@/lib/approvals"; import { type AgentChannel, channelKeys } from "@/lib/channels/queries"; import { TURN_INTERRUPTED } from "@/lib/copilot/stopped-turn"; import { queryClient } from "@/query-client";