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 4eba222c38..6d351f1043 100644 --- a/app/src/components/approvals/settings.tsx +++ b/app/src/components/approvals/settings.tsx @@ -18,8 +18,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, @@ -46,7 +46,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 35a5adedf8..741e329729 100644 --- a/app/src/components/approvals/team-settings.tsx +++ b/app/src/components/approvals/team-settings.tsx @@ -29,7 +29,7 @@ import { Switch } from "@/components/ui/switch"; import { type ActionKind, type ActionKindPolicy, - approvalInboxOptions, + approvalSettingsOptions, createTeamApprovalRuleMutationOptions, revokeTeamApprovalRuleMutationOptions, teamApprovalSettingsMutationOptions, @@ -81,7 +81,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 107e0d491b..22bce9d41d 100644 --- a/app/src/components/approvals/waiting.tsx +++ b/app/src/components/approvals/waiting.tsx @@ -57,9 +57,9 @@ 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"; @@ -70,8 +70,8 @@ import type { WaitingWhere } from "@/lib/tasks/groups"; import { cn } from "@/lib/utils"; import { queryClient } from "@/query-client"; -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 961a272201..29684e7a9e 100644 --- a/app/src/components/bot-profile/settings-rows.tsx +++ b/app/src/components/bot-profile/settings-rows.tsx @@ -23,7 +23,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"; @@ -80,7 +80,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 2f646087d6..16ff5c6808 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -54,12 +54,13 @@ import { BOT_KEY_REFUSED } from "@/lib/agents/key-link"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { answerPersonQuestionMutationOptions, - approvalInboxOptions, - carryingOnAfterApproval, + approvalQueueOptions, + approvalsWaiting, type LeftCall, leftAnswers, leftInConversation, stoppedOnLeft, + useCarryingOnAfterApproval, withLeftAnswers, } from "@/lib/approvals"; import { useBotTakesModelChoice } from "@/lib/bot-agents/queries"; @@ -1832,18 +1833,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 @@ -1863,8 +1858,8 @@ export function ChannelChat({ */ const leftCalls = useQuery({ - ...approvalInboxOptions(), - select: (inbox) => leftInConversation(inbox, channel.threadId), + ...approvalQueueOptions(), + select: (queue) => leftInConversation(queue, channel.threadId), }).data ?? NO_CALLS; /* @@ -2134,7 +2129,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); @@ -2807,7 +2802,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; /* @@ -2862,7 +2858,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..1b9bcdccba 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, @@ -48,7 +48,7 @@ export function useCardsFirst({ botId ?? "", Boolean(botId) && computers, ); - 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 bfabef8a3f..90640ff4ef 100644 --- a/app/src/components/responsibilities/goal-page.tsx +++ b/app/src/components/responsibilities/goal-page.tsx @@ -23,6 +23,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, @@ -605,8 +606,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); @@ -675,6 +677,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 8e81634031..efd8d6849e 100644 --- a/app/src/components/routines/routine-page.tsx +++ b/app/src/components/routines/routine-page.tsx @@ -23,6 +23,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 { @@ -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); @@ -180,6 +182,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 0b6a1daf45..a606e1f5e9 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/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/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 4e9328d227..06700be41e 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"; import { taskKeys } from "@/lib/tasks/queries"; /** The person asking: every approval, question, preference and rule here is their own. */ @@ -105,8 +108,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; @@ -141,10 +147,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; @@ -159,20 +186,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 @@ -180,7 +193,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 ?? []) @@ -189,32 +202,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(), @@ -233,6 +264,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( @@ -243,18 +294,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( @@ -267,10 +306,8 @@ export const approvalInboxOptions = () => ]); return { enabled: preferences.enabled, - requests, rules, teamRules, - conversationGrants, preferences: { enabled: preferences.enabled, autoReview: preferences.autoReview, @@ -278,13 +315,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 @@ -297,7 +358,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( @@ -312,6 +373,7 @@ export const conversationApprovalsQueryOptions = (threadId: string) => ); return { items: answer.approvals, nextCursor: answer.nextCursor }; }), + ...hinted("approvals"), }); /** @@ -337,15 +399,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()), ); } @@ -358,7 +467,7 @@ export type LeftCall = { toolCallId: string; answer: string }; * With the answer each call got, which the thread never received. */ export function leftInConversation( - inbox: ApprovalInboxData | undefined, + inbox: Pick | undefined, threadId: string, ): LeftCall[] { return (inbox?.requests ?? []).flatMap((request) => @@ -553,7 +662,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 }); @@ -646,15 +755,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 4828a3b523..073bc28186 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,7 +14,14 @@ 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 { embedSocketRenewal } from "@/lib/embed/session"; +import { + applyEveryHint, + applyHint, + parseDataChanged, + retimeReads, +} from "@/lib/live/apply-hints"; import { nudgeMoment } from "@/lib/notices"; import { isBotReply, @@ -666,6 +674,18 @@ 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; @@ -684,9 +704,8 @@ export function useChannelEvents() { attempts += 1; }; - /** Read the lists again, as nothing patched while it was not heard can be trusted. */ - const readAgain = () => { - readTimer = undefined; + /** 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() }); @@ -694,8 +713,19 @@ 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. 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; @@ -721,7 +751,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(); + else readLists(); wasOpen = true; }; @@ -735,12 +765,22 @@ 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. readAgainSoon(); return; } diff --git a/app/src/lib/client.ts b/app/src/lib/client.ts index 6bc1aa46d2..ad5b937d15 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 { @@ -61,11 +62,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. */ @@ -401,6 +406,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 2de6679bcb..73134128ff 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,14 @@ 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 { revalidated } from "@/lib/api/revalidated"; 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,51 +129,79 @@ 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 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, - ...(kind === undefined ? {} : { kind }), - ...(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 }; }); } +/** + * 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) => { - 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 }; }), @@ -227,7 +260,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 +285,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 be58ecb001..de4f6423d7 100644 --- a/app/src/lib/computers/use-control.ts +++ b/app/src/lib/computers/use-control.ts @@ -6,6 +6,7 @@ import { watchWindowAttention, windowAttention, } from "@/lib/desktop/window-attention"; +import { type Hint, hintsSent, onHint } from "@/lib/live/hinted"; import { queryClient } from "@/query-client"; import { BOT_GONE, @@ -64,6 +65,20 @@ function createControlStore(computerId: string): ControlStore { clearTimeout(timer); timer = undefined; if (!listeners.size || gone) return; + /* + * 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 (`onComputerHint`). 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. From such a server only a read that did not come back, or a hand-over under way, is + * asked again on the pace below; a server that sends no such hint has it read on the pace, as before. + */ + if ( + hintsSent("computers") && + failures === 0 && + !snapshot.control?.transitioning + ) + return; const wait = nextReadIn( attention, snapshot.control?.transitioning ? 0 : unchanged, @@ -208,6 +223,13 @@ function createControlStore(computerId: string): ControlStore { unchanged = 0; schedule(); }; + // A hint about this computer (or about every computer): read at once, unless nobody can see it. + const onComputerHint = (hint: Hint) => { + if (!hint.changed.includes("computers")) return; + if (hint.botId !== undefined && hint.botId !== computerId) return; + if (attention !== "hidden" && !snapshot.busy) void refresh(); + }; + let stopHearing: (() => void) | undefined; const store: ControlStore = { getSnapshot: () => snapshot, // Asked for by the person (Retry): as fresh as a change. @@ -226,6 +248,7 @@ function createControlStore(computerId: string): ControlStore { activity: onActivity, }); if (!snapshot.busy) void refresh(); + stopHearing = onHint(onComputerHint); } return () => { listeners.delete(listener); @@ -234,6 +257,8 @@ function createControlStore(computerId: string): ControlStore { timer = undefined; stopWatching?.(); stopWatching = undefined; + stopHearing?.(); + stopHearing = undefined; reading?.abort(); version++; disposeWhenUnused(); 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..3d67dd4791 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,10 @@ 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, 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({ @@ -159,26 +161,52 @@ 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 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( + (message) => + (message.status === "running" || message.status === "queued") && + now - Date.parse(message.createdAt) < GROUP_STREAM_MS, + ) ?? + false) || + awaitingFirstReply(data, now) + ); +} + /** * 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 * 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 new file mode 100644 index 0000000000..f9382972c3 --- /dev/null +++ b/app/src/lib/live/apply-hints.ts @@ -0,0 +1,224 @@ +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.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/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-carry-on-browser.test.tsx b/app/tests/approval-left-carry-on-browser.test.tsx index 560cf45f49..d4178a1755 100644 --- a/app/tests/approval-left-carry-on-browser.test.tsx +++ b/app/tests/approval-left-carry-on-browser.test.tsx @@ -5,7 +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 { ApprovalInboxData } 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"; @@ -119,7 +119,7 @@ const inbox = { rules: [], teamRules: [], questions: [], -} as unknown as ApprovalInboxData; +} as unknown as ApprovalQueueData & Partial; /** What the runtime keeps of the thread, and every run asked for here. */ type Scene = { runs: unknown[]; recorded: unknown[]; stored: unknown[] }; diff --git a/app/tests/approval-left-carry-on.test.tsx b/app/tests/approval-left-carry-on.test.tsx index 1f03a5fc0b..7b82d5bb27 100644 --- a/app/tests/approval-left-carry-on.test.tsx +++ b/app/tests/approval-left-carry-on.test.tsx @@ -6,7 +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 { ApprovalInboxData } 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"; @@ -77,7 +77,7 @@ let stored: Message[]; let runs: RunAgentInput[] = []; let originalFetch: typeof fetch; -function inbox(): ApprovalInboxData { +function inbox(): ApprovalQueueData & Partial { return { enabled: true, requests: [ @@ -107,7 +107,7 @@ function inbox(): ApprovalInboxData { rules: [], teamRules: [], questions: [], - } as unknown as ApprovalInboxData; + } as unknown as ApprovalQueueData & Partial; } function sse(events: unknown[]) { 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/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/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/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 [ 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..51f225e5f8 --- /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 while it is owed, up to a deadline, and not after", () => { + const now = Date.now(); + expect(streamingReply(group("running", 1, now), now)).toBe(true); + 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); + expect(streamingReply(group("queued", 11, now), now)).toBe(false); + expect(streamingReply(group("completed", 0, now), now)).toBe(false); +});