diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b63dee07bf..4c00bcf057 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -435,7 +435,7 @@ jobs: --volume "$(command -v bun):/usr/local/bin/bun:ro" \ --env OPENBOT_APP_BROWSER=1 --env OPENBOT_APP_ENGINES=chromium,webkit \ "$PLAYWRIGHT_IMAGE" \ - bun test app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx + bun test app/tests/chunk-recovery.test.tsx app/tests/composer-dictation-language.test.tsx app/tests/sidebar-zoom-drag.test.tsx app/tests/service-terms.test.tsx app/tests/move-to-cloud-settings.test.tsx app/tests/moved-elsewhere.test.tsx app/tests/home-no-answer.test.tsx app/tests/section-strip-routines.test.tsx app/tests/organization-members-remove.test.tsx app/tests/settings-tool-cards-admin-layout.test.tsx app/tests/settings-tool-cards-personal.test.tsx app/tests/settings-tool-cards-core.test.tsx app/tests/one-press-connect-layout.test.tsx app/tests/admin-notion-one-press-layout.test.tsx app/tests/team-connections-directory-layout.test.tsx app/tests/conversation-switch.test.tsx app/tests/member-rows-long-names.test.tsx app/tests/people-lists.test.tsx app/tests/organization-moving.test.tsx app/tests/organization-removed.test.tsx app/tests/organization-held-reload.test.tsx app/tests/organization-unavailable-pages.test.tsx app/tests/organization-held-actions.test.tsx # Connect your AI's sign-in code, copied with one press and read back from WebKit's clipboard. # Only that test: the rest of the file runs in Chromium in the job above. - run: | diff --git a/app/src/components/admin/controls/computer-sections.tsx b/app/src/components/admin/controls/computer-sections.tsx index cec1565d30..6c29b72e64 100644 --- a/app/src/components/admin/controls/computer-sections.tsx +++ b/app/src/components/admin/controls/computer-sections.tsx @@ -57,7 +57,7 @@ import { type NetworkPolicy, type NetworkScopeKind, } from "@/lib/enterprise/queries"; -import { loadFailure, failureSaid } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { MISSING_TEAM, teamName } from "@/lib/teams/names"; import { type TeamSummary, teamListQueryOptions } from "@/lib/teams/queries"; import { queryClient } from "@/query-client"; @@ -535,7 +535,7 @@ function NetworkDialog({ {(save.error ?? remove.error) ? (

- {(save.error ?? remove.error)?.message} + {failureSaid(save.error ?? remove.error)}

) : null} diff --git a/app/src/components/admin/controls/controls-section.tsx b/app/src/components/admin/controls/controls-section.tsx index 93ebb7429b..49f96a3824 100644 --- a/app/src/components/admin/controls/controls-section.tsx +++ b/app/src/components/admin/controls/controls-section.tsx @@ -12,7 +12,7 @@ import { type EnterpriseSettings, enterpriseOverviewQueryOptions, } from "@/lib/enterprise/queries"; -import { loadFailure } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; /** What a section of the admin's controls reads and changes. */ @@ -102,7 +102,7 @@ export function ControlsSection({ > {failure ? (

- {failure.message} + {failureSaid(failure)}

) : null} {children({ diff --git a/app/src/components/admin/controls/describe-capabilities.tsx b/app/src/components/admin/controls/describe-capabilities.tsx index 416bb82ada..312d11ca6d 100644 --- a/app/src/components/admin/controls/describe-capabilities.tsx +++ b/app/src/components/admin/controls/describe-capabilities.tsx @@ -43,10 +43,10 @@ import type { CapabilityChange, CapabilityChangeProblem, } from "@/lib/capability-changes/translate"; +import { failureSaid } from "@/lib/load-failure"; import { MISSING_TEAM, teamName } from "@/lib/teams/names"; import type { TeamSummary } from "@/lib/teams/queries"; import { cn } from "@/lib/utils"; -import { failureSaid } from "@/lib/load-failure"; /** The organization's teams, by which a change's or an answer's team id is given its name. */ type Teams = readonly Pick[]; @@ -133,7 +133,7 @@ export function ChangeRows({ {scopeWords(change, teams)} {wrong.map((problem) => (

- {problem.message} + {failureSaid(problem)}

))} diff --git a/app/src/components/agents/new-bot-sheet.tsx b/app/src/components/agents/new-bot-sheet.tsx index 81d91d17f5..f55837cbe6 100644 --- a/app/src/components/agents/new-bot-sheet.tsx +++ b/app/src/components/agents/new-bot-sheet.tsx @@ -73,7 +73,12 @@ import { isComposing } from "@/lib/composing"; import { ALWAYS_ON_APP } from "@/lib/connections/rows"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { myCapabilitiesQueryOptions } from "@/lib/enterprise/queries"; -import { failureSaid, loadFailure } from "@/lib/load-failure"; +import { + type Failure, + failureOf, + failureSaid, + loadFailure, +} from "@/lib/load-failure"; import { useOrganizationAudience } from "@/lib/organizations/queries"; import { type PluginServer, pluginKeys } from "@/lib/plugins/queries"; import { cn } from "@/lib/utils"; @@ -234,8 +239,11 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { const [tried, setTried] = useState(false); /** Continue on the address is dialling it, before anything is created. */ const [checking, setChecking] = useState(false); - /** Why the server could not reach the address on the last Continue, in its own words. */ - const [unreachable, setUnreachable] = useState(); + /** + * Why the server could not reach the address on the last Continue, in its own words. The refusal + * itself, not its words: a hold is drawn calmly (lib/load-failure.tsx). + */ + const [unreachable, setUnreachable] = useState(); /** The Bot just made, held for the moment the sheet spends saying so before it hands over. */ const [createdId, setCreatedId] = useState(); /** @@ -391,11 +399,7 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { await create(runtime); } catch (error) { createAgent.reset(); - setUnreachable( - error instanceof Error && error.message - ? error.message - : MASTRA_UNREACHABLE, - ); + setUnreachable(failureOf(error, MASTRA_UNREACHABLE)); focusAddress(); } return; @@ -526,7 +530,13 @@ function NewBotFlow({ onCreated }: { onCreated: (agentId: string) => void }) { ) : ( { setEndpoint(value); @@ -1060,7 +1070,7 @@ export function EndpointStep({ harness: string | null; endpoint: string; secret: string; - endpointError?: string; + endpointError?: Failure; onEndpoint: (value: string) => void; onKey: (value: string) => void; }) { @@ -1099,10 +1109,9 @@ export function EndpointStep({ value={endpoint} /> {endpointError ? ( - + + {failureSaid(endpointError)} + ) : mastra ? ( Give the address of your Mastra server. It needs to run one agent, diff --git a/app/src/components/agents/proposed-bot.tsx b/app/src/components/agents/proposed-bot.tsx index 1ee16aa9e9..f9875ef4dd 100644 --- a/app/src/components/agents/proposed-bot.tsx +++ b/app/src/components/agents/proposed-bot.tsx @@ -10,6 +10,7 @@ import { type ProposedBot, wasCreated, } from "@/lib/agents/proposal"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; /** * The coworker a Bot has written, put in front of the person before it exists. @@ -71,7 +72,7 @@ export function ProposedBotCard({ * after whatever the refusal named has been dealt with, or declining. Answering the tool with the * error would end the turn and leave the person retyping their request. */ - const [refusal, setRefusal] = useState(null); + const [refusal, setRefusal] = useState(null); if (result !== undefined) { /* @@ -115,9 +116,8 @@ export function ProposedBotCard({ } catch (cause) { // Left on the card with the buttons still live. See `refusal` above. setSending(null); - setRefusal( - cause instanceof Error ? cause.message : "The Bot wasn't created.", - ); + // The refusal itself, not its words: a hold is drawn calmly (lib/load-failure.tsx). + setRefusal(failureOf(cause, "The Bot wasn't created.")); return; } /* @@ -177,7 +177,7 @@ export function ProposedBotCard({ {refusal ? (

- {refusal} + {failureSaid(refusal)}

) : null} diff --git a/app/src/components/app-sidebar/channel.tsx b/app/src/components/app-sidebar/channel.tsx index 91122037da..baa0c1d284 100644 --- a/app/src/components/app-sidebar/channel.tsx +++ b/app/src/components/app-sidebar/channel.tsx @@ -16,6 +16,7 @@ import { ContextMenuTrigger, } from "@/components/ui/context-menu"; import { setChannelPinnedMutationOptions } from "@/lib/channels/mutations"; +import { type Failure, failureSaid } from "@/lib/load-failure"; import type { ConversationView } from "@/lib/settings/conversation-view"; import type { MessageListEmphasis } from "@/lib/settings/message-list"; import { useTypedReveal } from "@/lib/typed-reveal"; @@ -90,7 +91,7 @@ export const Channel = memo(function Channel({ * app, and the row is where the person was looking, so the sentence goes here and is replaced by * the next attempt. */ - const [pinProblem, setPinProblem] = useState(null); + const [pinProblem, setPinProblem] = useState(null); return ( <> @@ -138,7 +139,7 @@ export const Channel = memo(function Channel({ setPinProblem(null); setPinned.mutate( { channelId, pinned: !pinned }, - { onError: (thrown) => setPinProblem(thrown.message) }, + { onError: (thrown) => setPinProblem(thrown) }, ); }} > @@ -162,7 +163,7 @@ export const Channel = memo(function Channel({ {pinProblem ? (

- {pinProblem} + {failureSaid(pinProblem)}

) : null} decision.mutate(value as ApprovalDecision)} options={choices.map((choice) => ({ value: choice, @@ -199,7 +200,7 @@ export function InlineApproval({ data-testid="approval-left" role={request.left.done ? "status" : "alert"} > - {request.left.message} + {failureSaid(request.left)}

) : null} diff --git a/app/src/components/approvals/question-notice.tsx b/app/src/components/approvals/question-notice.tsx index 5451304920..16dfdd21ba 100644 --- a/app/src/components/approvals/question-notice.tsx +++ b/app/src/components/approvals/question-notice.tsx @@ -23,8 +23,8 @@ import { approvalInboxOptions, dismissPersonQuestionMutationOptions, } from "@/lib/approvals"; +import { type Failure, failureSaid } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; -import { failureSaid } from "@/lib/load-failure"; export type WaitingQuestion = ApprovalInboxData["questions"][number]; @@ -145,7 +145,7 @@ function QuestionParts({ onAnswered: (answer: string) => Promise; }) { const [sending, setSending] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); const several = parts.length > 1; return ( setError(failure.message)) + .catch((failure: Error) => setError(failure)) .finally(() => setSending(false)); }} shortcuts="numbers" @@ -212,7 +212,7 @@ function QuestionParts({ {error ? (

- {error} + {failureSaid(error)}

) : null}
diff --git a/app/src/components/audit/ask-the-trail.tsx b/app/src/components/audit/ask-the-trail.tsx index 70e734c6e5..406ddd97f0 100644 --- a/app/src/components/audit/ask-the-trail.tsx +++ b/app/src/components/audit/ask-the-trail.tsx @@ -13,6 +13,7 @@ import { } from "@/components/ui/input-group"; import { type AuditAnswer, askAuditTrail } from "@/lib/audit/ask"; import { isComposing } from "@/lib/composing"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; /** The longest question the server takes. */ const QUESTION_LIMIT = 500; @@ -31,7 +32,7 @@ export function AskTheTrail({ }) { const [text, setText] = useState(""); const [asking, setAsking] = useState(false); - const [problem, setProblem] = useState(null); + const [problem, setProblem] = useState(null); const question = text.trim(); const ask = async () => { @@ -41,7 +42,7 @@ export function AskTheTrail({ try { onAnswer({ ...(await askAuditTrail(question)), question }); } catch (thrown) { - setProblem((thrown as Error).message); + setProblem(failureOf(thrown, String(thrown))); } finally { setAsking(false); } @@ -89,7 +90,7 @@ export function AskTheTrail({ data-audit-ask-problem role="alert" > - {problem} + {failureSaid(problem)}

) : null} diff --git a/app/src/components/auth/link-company-account.tsx b/app/src/components/auth/link-company-account.tsx index a1370c6923..b901e58cc5 100644 --- a/app/src/components/auth/link-company-account.tsx +++ b/app/src/components/auth/link-company-account.tsx @@ -2,6 +2,7 @@ import { useState } from "react"; import { Button } from "@/components/ui/button"; import type { CompanySignInProvidersItem } from "@/lib/api/generated/model"; import { linkCompanyAccount } from "@/lib/auth/client"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { cn } from "@/lib/utils"; export const LINK_COMPANY_ACCOUNT = "Link your company account"; @@ -23,7 +24,7 @@ export function LinkCompanyAccount({ className?: string; }) { const [linking, setLinking] = useState(null); - const [problem, setProblem] = useState(null); + const [problem, setProblem] = useState(null); if (providers.length === 0) return null; const link = async (providerId: string) => { @@ -34,9 +35,7 @@ export function LinkCompanyAccount({ await linkCompanyAccount(providerId); } catch (error) { setProblem( - error instanceof Error - ? error.message - : "Couldn't start signing in with your company.", + failureOf(error, "Couldn't start signing in with your company."), ); setLinking(null); } @@ -61,7 +60,7 @@ export function LinkCompanyAccount({ ))} {problem ? (

- {problem} + {failureSaid(problem)}

) : null} diff --git a/app/src/components/bot-profile/default-model.tsx b/app/src/components/bot-profile/default-model.tsx index a26c58ece2..becdec759c 100644 --- a/app/src/components/bot-profile/default-model.tsx +++ b/app/src/components/bot-profile/default-model.tsx @@ -23,7 +23,12 @@ import { } from "@/components/ui/item"; import type { AgentProfile } from "@/lib/agents/queries"; import { useBotTakesModelChoice } from "@/lib/bot-agents/queries"; -import { loadFailure } from "@/lib/load-failure"; +import { + type Failure, + failureOf, + failureSaid, + loadFailure, +} from "@/lib/load-failure"; import { effortLabel, type ModelPick, @@ -61,7 +66,8 @@ export function DefaultModelSection({ const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(); const [useDeploymentDefault, setUseDeploymentDefault] = useState(true); - const [error, setError] = useState(); + // A refused save is kept whole, not as its words, so a hold is drawn calmly (`failureSaid`). + const [error, setError] = useState(); if (!eligible) return null; const open = () => { @@ -83,11 +89,7 @@ export function DefaultModelSection({ await onSave(useDeploymentDefault ? null : (custom ?? null)); setEditing(false); } catch (failure) { - setError( - failure instanceof Error - ? failure.message - : "Couldn't save the default model.", - ); + setError(failureOf(failure, "Couldn't save the default model.")); } }; const deploymentSummary = deploymentModel @@ -223,7 +225,7 @@ export function DefaultModelSection({ {error ? (

- {error} + {failureSaid(error)}

) : null} diff --git a/app/src/components/bot-profile/setup.tsx b/app/src/components/bot-profile/setup.tsx index 52d10db584..c350b1708d 100644 --- a/app/src/components/bot-profile/setup.tsx +++ b/app/src/components/bot-profile/setup.tsx @@ -67,6 +67,7 @@ import { shownSubtitle } from "@/lib/agents/subtitle"; import { isComposing } from "@/lib/composing"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; import { myCapabilitiesQueryOptions } from "@/lib/enterprise/queries"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { useOrganizationAudience } from "@/lib/organizations/queries"; import { queryClient } from "@/query-client"; @@ -263,7 +264,7 @@ function VisibilityRow({ onSave: (visibility: AgentProfile["visibility"]) => Promise; }) { const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); // Public is everyone in this organization, by name where the app knows it. const everyone = publicVisibilityWords(useOrganizationAudience()); return ( @@ -274,7 +275,7 @@ function VisibilityRow({ Visibility - {error ?? + {failureSaid(error) ?? (agent.visibility === "private" ? agent.isolationActive ? `Only you can see it and start conversations with it. ${ISOLATED_MAKING_PUBLIC}` @@ -297,11 +298,7 @@ function VisibilityRow({ try { await onSave(next as AgentProfile["visibility"]); } catch (failure) { - setError( - failure instanceof Error - ? failure.message - : "Couldn't save. Try again.", - ); + setError(failureOf(failure, "Couldn't save. Try again.")); } finally { setSaving(false); } @@ -348,7 +345,7 @@ function IsolatedRow({ const { data: capabilities } = useQuery(deploymentCapabilitiesQueryOptions()); const { data: mine } = useQuery(myCapabilitiesQueryOptions()); const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); const available = capabilities?.isolatedBots ?? false; // OpenBot Cloud gives each person one computer; the row says so and where a Bot can have its own. const cloud = capabilities?.hostedSignIn === true; @@ -388,7 +385,7 @@ function IsolatedRow({ Isolated - {error ?? summary} + {failureSaid(error) ?? summary} {cloud && deploymentCant && !agent.systemOwned && !error ? ( @@ -406,11 +403,7 @@ function IsolatedRow({ try { await onSave(next); } catch (failure) { - setError( - failure instanceof Error - ? failure.message - : "Couldn't save. Try again.", - ); + setError(failureOf(failure, "Couldn't save. Try again.")); } finally { setSaving(false); } @@ -464,21 +457,23 @@ function EditTextDialog({ }) { const [draft, setDraft] = useState(value); const [saving, setSaving] = useState(false); - const [error, setError] = useState(null); + // A refused save is kept whole, not as its words, so a hold is drawn calmly (`failureSaid`). + const [error, setError] = useState(null); const errorId = useId(); const [field, setField] = useState< HTMLInputElement | HTMLTextAreaElement | null >(null); - const refuse = (message: string) => { - setError(message); + const refuse = (failure: Failure) => { + setError(failure); field?.focus(); }; const submit = async () => { const parsed = schema.safeParse(draft); if (!parsed.success) { - refuse( - parsed.error.issues[0]?.message ?? "Check this field and try again.", - ); + refuse({ + message: + parsed.error.issues[0]?.message ?? "Check this field and try again.", + }); return; } setSaving(true); @@ -486,11 +481,7 @@ function EditTextDialog({ await onSave(parsed.data); onClose(); } catch (failure) { - refuse( - failure instanceof Error - ? failure.message - : "Couldn't save. Try again.", - ); + refuse(failureOf(failure, "Couldn't save. Try again.")); } finally { setSaving(false); } @@ -551,7 +542,7 @@ function EditTextDialog({ )} {error ? ( ) : null} diff --git a/app/src/components/boundaries/describe-rule.tsx b/app/src/components/boundaries/describe-rule.tsx index ccf9fd35df..178aa4131c 100644 --- a/app/src/components/boundaries/describe-rule.tsx +++ b/app/src/components/boundaries/describe-rule.tsx @@ -7,6 +7,7 @@ import { type PolicyTranslation, translatePolicyRule, } from "@/lib/computers/policy-translate"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; /** What came back for one description, kept beside the words it came from. */ export type WrittenRule = PolicyTranslation & { text: string }; @@ -37,7 +38,7 @@ export function DescribeField({ }) { const [text, setText] = useState(""); const [writing, setWriting] = useState(false); - const [problem, setProblem] = useState(null); + const [problem, setProblem] = useState(null); const described = text.trim(); const ask = async () => { @@ -45,9 +46,10 @@ export function DescribeField({ setProblem(null); setWriting(true); try { - setProblem(await write(described)); + const unusable = await write(described); + setProblem(unusable === null ? null : { message: unusable }); } catch (thrown) { - setProblem((thrown as Error).message); + setProblem(failureOf(thrown, String(thrown))); } finally { setWriting(false); } @@ -87,7 +89,7 @@ export function DescribeField({ {problem ? (

- {problem} + {failureSaid(problem)}

) : null} diff --git a/app/src/components/browser/browser-page.tsx b/app/src/components/browser/browser-page.tsx index 146ce78a63..78e746913f 100644 --- a/app/src/components/browser/browser-page.tsx +++ b/app/src/components/browser/browser-page.tsx @@ -12,7 +12,7 @@ import { Button } from "@/components/ui/button"; import { openBrowserMutationOptions } from "@/lib/browser/mutations"; import { browserStateQueryOptions } from "@/lib/browser/queries"; import { settledRefusal } from "@/lib/computers/refusal"; -import { loadFailure } from "@/lib/load-failure"; +import { type Failure, failureSaid, loadFailure } from "@/lib/load-failure"; import { recorderKeys } from "@/lib/recorder/queries"; import { queryClient } from "@/query-client"; import { TEACH_A_BOT } from "./browser-nav-item"; @@ -141,7 +141,10 @@ function OpenedBrowser({ state }: { state: BrowserApiState }) { reopen.data ?? open.data; if (!opened) { // A browser that is there and not answering says so while it is asked to open, rather than leaving the page empty. - const said = state.problem ?? open.error?.message; + // The refusal kept whole, not as its words, so a hold is drawn calmly (`failureSaid`). + const said: Failure | null = state.problem + ? { message: state.problem } + : open.error; /* * Refused for good (the organization is at its computer limit, say): asking again would be refused again, so the * page says so calmly, with no Try again. A browser that isn't answering is still the news over it. @@ -183,7 +186,7 @@ function OpenedBrowser({ state }: { state: BrowserApiState }) { ) : said ? (

- {said} + {failureSaid(said)}

{retry ? (
diff --git a/app/src/components/channels/group-people.tsx b/app/src/components/channels/group-people.tsx index 1afdfbfdd2..5f5012bc0c 100644 --- a/app/src/components/channels/group-people.tsx +++ b/app/src/components/channels/group-people.tsx @@ -26,6 +26,7 @@ import { groupQueryOptions, removeGroupMemberMutationOptions, } from "@/lib/groups"; +import { failureSaid } from "@/lib/load-failure"; import { personName } from "@/lib/organizations/words"; import type { OrganizationPerson } from "@/lib/teams/queries"; @@ -154,7 +155,7 @@ export function GroupPeopleButton({ channelId }: { channelId: string }) { /> {add.error || remove.error ? (

- {(add.error ?? remove.error)?.message} + {failureSaid(add.error ?? remove.error)}

) : null} diff --git a/app/src/components/channels/voice-call-widget.tsx b/app/src/components/channels/voice-call-widget.tsx index 05a12eb07c..a42ab76d0a 100644 --- a/app/src/components/channels/voice-call-widget.tsx +++ b/app/src/components/channels/voice-call-widget.tsx @@ -20,6 +20,7 @@ import { } from "@/components/ui/dropdown-menu"; import { LiveWaveform } from "@/components/ui/live-waveform"; import { currentUserQueryOptions } from "@/lib/auth/queries"; +import { failureSaid } from "@/lib/load-failure"; import { EASE_OUT, ENTRANCE_SECONDS } from "@/lib/motion"; import { stopIfNeedsCard } from "@/lib/plan/queries"; import { cn } from "@/lib/utils"; @@ -273,7 +274,7 @@ export function VoiceCallWidget({ {failed && (

- {state.error} + {failureSaid(state.error)}

); - const error = give.error?.message ?? tab.error; + const error = give.error ?? tab.error; return (
{error ? (

- {error} + {failureSaid(error)}

) : null} {tab.blockedUrl ? ( @@ -811,12 +811,12 @@ function PersonalConnectAction({ ); - const error = approve.error?.message ?? tab.error; + const error = approve.error ?? tab.error; return (
{error ? (

- {error} + {failureSaid(error)}

) : null} {tab.blockedUrl ? ( @@ -944,7 +944,7 @@ function ConnectAction({
{tab.error ? (

- {tab.error} + {failureSaid(tab.error)}

) : null} {tab.blockedUrl ? ( diff --git a/app/src/components/plugins/broker-directory.tsx b/app/src/components/plugins/broker-directory.tsx index 89f8e15f9e..a265315920 100644 --- a/app/src/components/plugins/broker-directory.tsx +++ b/app/src/components/plugins/broker-directory.tsx @@ -36,7 +36,7 @@ import { } from "@/lib/apps/queries"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { isOrganizationAdmin } from "@/lib/auth/roles"; -import { loadFailure } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { useManagePaths } from "@/lib/manage-paths"; import { type DirectoryAppState, @@ -196,7 +196,7 @@ export function BrokerDirectory({ {press.error ? (

- {press.error} + {failureSaid(press.error)}

) : null} diff --git a/app/src/components/plugins/brokered-account-row.tsx b/app/src/components/plugins/brokered-account-row.tsx index 5cc736c948..ece4671cbe 100644 --- a/app/src/components/plugins/brokered-account-row.tsx +++ b/app/src/components/plugins/brokered-account-row.tsx @@ -22,7 +22,7 @@ import { } from "@/components/ui/item"; import { Separator } from "@/components/ui/separator"; import { vendorNameOf } from "@/lib/apps/vendor-name"; -import { failureSaid } from "@/lib/load-failure"; +import { type Failure, failureInstead, failureSaid } from "@/lib/load-failure"; import { useManagePaths } from "@/lib/manage-paths"; import { type AdminName, withAdmins } from "@/lib/organizations/admin-names"; import { useConnectionEnding } from "@/lib/plugins/connection-ending"; @@ -271,9 +271,9 @@ export type BrokeredAccount = { * Carried out of the hook as well as reported to the screen's banner, because the form is a * modal. The banner is behind its backdrop, so Composio's own sentence — the one this path spends * a dropped `cause` to preserve — arrived where the person could not read it, over a form still - * holding the key it was about. + * holding the key it was about. Drawn through the shared rule, so a hold reads calm (`failureSaid`). */ - submissionError: string | null; + submissionError: ReactNode; /** Spend one read-only call at the vendor to find out whether the key still works. */ recheck: () => void; rechecking: boolean; @@ -350,9 +350,10 @@ export function useBrokeredAccount(input: { * Where this row's failures go: the screen's own banner. * * Called with null as an action starts, so the reason the last attempt failed is not left sitting - * over the one now in flight. + * over the one now in flight. A refusal is handed on whole, not as its words, so the banner can + * draw a hold calmly (`failureSaid`). */ - report: (message: string | null) => void; + report: (failure: Failure | null) => void; }): BrokeredAccount { const queryClient = useQueryClient(); const { @@ -455,7 +456,9 @@ export function useBrokeredAccount(input: { const recheck = useMutation({ ...recheckBrokeredConnectionMutationOptions(queryClient, shared), onError: (thrown: Error) => - report(readableRefusal(thrown.message, RECHECK_FAILED)), + report( + failureInstead(thrown, readableRefusal(thrown.message, RECHECK_FAILED)), + ), }); /* * The check's answer is thrown away whenever an action changes the account it was about. @@ -480,7 +483,7 @@ export function useBrokeredAccount(input: { const connect = useMutation({ ...connectAccountMutationOptions(returnTo, shared), - onError: (thrown: Error) => report(thrown.message), + onError: (thrown: Error) => report(thrown), /* * A full page navigation, not a fetch. The consent screen is the vendor's own and has to be * shown to this person in their own browser; there is deliberately nothing here that could @@ -524,9 +527,10 @@ export function useBrokeredAccount(input: { setKeyInstead(true); return; } - report( - "This app connects with a key, not a sign-in page, so nothing was connected. Open this app again from Connections and press Connect.", - ); + report({ + message: + "This app connects with a key, not a sign-in page, so nothing was connected. Open this app again from Connections and press Connect.", + }); return; } return leaveFor(start.authorizationUrl); @@ -571,7 +575,7 @@ export function useBrokeredAccount(input: { const disconnect = useMutation({ ...disconnectBrokeredMutationOptions(queryClient, shared), onError: (thrown: Error) => { - report(thrown.message); + report(thrown); forgetAnswers(); }, onSuccess: forgetAnswers, @@ -587,7 +591,7 @@ export function useBrokeredAccount(input: { */ const fieldsRequest = useMutation({ ...brokeredConnectionFieldsMutationOptions(returnTo, shared), - onError: (thrown: Error) => report(thrown.message), + onError: (thrown: Error) => report(thrown), }); /* @@ -636,7 +640,12 @@ export function useBrokeredAccount(input: { const submission = useMutation({ ...connectBrokeredWithFieldsMutationOptions(queryClient, returnTo, shared), onError: (thrown: Error) => { - report(readableRefusal(thrown.message, KEY_CHECK_FAILED)); + report( + failureInstead( + thrown, + readableRefusal(thrown.message, KEY_CHECK_FAILED), + ), + ); forgetAnswers(); }, onSuccess: forgetAnswers, @@ -680,7 +689,7 @@ export function useBrokeredAccount(input: { */ const connectAnother = useMutation({ ...connectAnotherAccountMutationOptions(returnTo), - onError: (thrown: Error) => report(thrown.message), + onError: (thrown: Error) => report(thrown), onSuccess: (start) => { forgetConfirmation(); forgetRecheck(); @@ -689,9 +698,10 @@ export function useBrokeredAccount(input: { return; } if (start === null) { - report( - "This app connects with a key, not a sign-in page, so nothing was connected. Open this app again from Connections and press Connect.", - ); + report({ + message: + "This app connects with a key, not a sign-in page, so nothing was connected. Open this app again from Connections and press Connect.", + }); return; } return leaveFor(start.authorizationUrl); @@ -699,12 +709,12 @@ export function useBrokeredAccount(input: { }); const makeDefault = useMutation({ ...setDefaultBrokeredAccountMutationOptions(queryClient), - onError: (thrown: Error) => report(thrown.message), + onError: (thrown: Error) => report(thrown), }); const disconnectAccount = useMutation({ ...disconnectBrokeredAccountMutationOptions(queryClient), onError: (thrown: Error) => { - report(thrown.message); + report(thrown); forgetAnswers(); }, onSuccess: forgetAnswers, @@ -826,7 +836,7 @@ export function useBrokeredAccount(input: { submission.mutate({ serverId, values }); }, submittingFields: submission.isPending, - submissionError: submission.error?.message ?? null, + submissionError: failureSaid(submission.error), serverId, shared, fieldsSubmitted: submission.isSuccess, diff --git a/app/src/components/plugins/connect-in-new-tab.ts b/app/src/components/plugins/connect-in-new-tab.ts index a0a6d850ef..f3d0a90f1b 100644 --- a/app/src/components/plugins/connect-in-new-tab.ts +++ b/app/src/components/plugins/connect-in-new-tab.ts @@ -2,6 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query"; import { createElement, useCallback, useEffect, useRef, useState } from "react"; import { ConsentHandoffDialog } from "@/components/plugins/consent-handoff"; import { desktopShell } from "@/lib/desktop/shell"; +import { failureOf } from "@/lib/load-failure"; import { markConnectReturn } from "@/lib/plugins/connect-return"; import { brokeredConsentFor, @@ -288,11 +289,12 @@ export function useConnectInNewTab() { needsKey, blockedUrl, pending: connect.isPending, - /** The connect route's own sentence, when it refused. */ + /** + * The connect route's refusal, when it refused: kept whole, so whoever draws it draws a hold calmly + * (`failureSaid`). + */ error: connect.isError - ? connect.error instanceof Error - ? connect.error.message - : "Couldn't connect that account." + ? failureOf(connect.error, "Couldn't connect that account.") : null, }; } diff --git a/app/src/components/plugins/grant-list.tsx b/app/src/components/plugins/grant-list.tsx index b954929617..b412cea2a9 100644 --- a/app/src/components/plugins/grant-list.tsx +++ b/app/src/components/plugins/grant-list.tsx @@ -10,6 +10,7 @@ import { ItemDescription, ItemTitle, } from "@/components/ui/item"; +import { type Failure, failureSaid } from "@/lib/load-failure"; import { consentCopy } from "@/lib/plugins/enablement-notes"; import { finishOnReturn } from "@/lib/plugins/finish-on-return"; import { @@ -62,16 +63,18 @@ export function GrantList({ const grants = useQuery(grantsQueryOptions(serverId, true, shared)); const [search, setSearch] = useState(""); const [choosing, setChoosing] = useState(null); - const [notice, setNotice] = useState(null); + // The refusal itself, not its words: a hold is drawn calmly (`failureSaid`). + const [notice, setNotice] = useState(null); const authorize = useMutation({ ...authorizeActionMutationOptions(returnTo, shared), - onError: (thrown: Error) => setNotice(thrown.message), + onError: (thrown: Error) => setNotice(thrown), /* A full page navigation: the consent screen is the vendor's own and shown in this browser. */ onSuccess: (authorizationUrl) => { if (authorizationUrl === null) { - setNotice( - "OpenBot answered without a consent link, so nothing was authorized. Try again, or ask an admin if it keeps happening.", - ); + setNotice({ + message: + "OpenBot answered without a consent link, so nothing was authorized. Try again, or ask an admin if it keeps happening.", + }); return; } finishOnReturn(); @@ -151,7 +154,7 @@ export function GrantList({ > {notice ? (

- {notice} + {failureSaid(notice)}

) : null} (null); + // The refusal itself, not its words: a hold is drawn calmly (`failureSaid`). + const [error, setError] = useState(null); const add = useMutation({ ...addDirectoryAppMutationOptions(queryClient), onMutate: () => setError(null), - onError: (thrown: Error) => setError(thrown.message), + onError: (thrown: Error) => setError(thrown), onSuccess: (keyAppId) => mode === "connect" ? navigate({ @@ -127,7 +129,7 @@ export function KeyVersionOffer({ /> {error ? (

- {error} + {failureSaid(error)}

) : null} diff --git a/app/src/components/plugins/use-directory-press.ts b/app/src/components/plugins/use-directory-press.ts index 7105928623..5a37d9fe4f 100644 --- a/app/src/components/plugins/use-directory-press.ts +++ b/app/src/components/plugins/use-directory-press.ts @@ -8,6 +8,7 @@ import { type DirectoryAppInput, } from "@/lib/apps/mutations"; import { type DirectoryApp, directorySlug } from "@/lib/apps/queries"; +import type { Failure } from "@/lib/load-failure"; import { directoryConnect } from "@/lib/plugins/directory-state"; import { invalidatePlugins } from "@/lib/plugins/mutations"; import { connectionsQueryOptions } from "@/lib/plugins/queries"; @@ -38,7 +39,8 @@ export function useDirectoryPress(mode: DirectoryPressMode) { const queryClient = useQueryClient(); const navigate = useNavigate(); const tab = useConnectInNewTab(); - const [error, setError] = React.useState(null); + // The refusal itself, not its words: a hold is drawn calmly (`failureSaid`). + const [error, setError] = React.useState(null); const [adding, setAdding] = React.useState>(new Set()); const [requesting, setRequesting] = React.useState>( new Set(), @@ -61,7 +63,7 @@ export function useDirectoryPress(mode: DirectoryPressMode) { setError(null); setAdding((set) => held(set, input.directoryEntryId)); }, - onError: (thrown: Error) => setError(thrown.message), + onError: (thrown: Error) => setError(thrown), // Spelled out: a second `onSettled` replaces the spread one, and its refetch is what turns the // added row into its connection state. onSettled: (_data, _error, input) => { @@ -82,7 +84,7 @@ export function useDirectoryPress(mode: DirectoryPressMode) { setError(null); setAddingKey((set) => held(set, input.directoryEntryId)); }, - onError: (thrown: Error) => setError(thrown.message), + onError: (thrown: Error) => setError(thrown), onSettled: (_data, _error, input) => { setAddingKey((set) => released(set, input.directoryEntryId)); return invalidatePlugins(queryClient); @@ -94,7 +96,7 @@ export function useDirectoryPress(mode: DirectoryPressMode) { setError(null); setRequesting((set) => held(set, slug)); }, - onError: (thrown: Error) => setError(thrown.message), + onError: (thrown: Error) => setError(thrown), onSettled: (_data, _error, slug) => { setRequesting((set) => released(set, slug)); return queryClient.invalidateQueries({ queryKey: ["plugins"] }); diff --git a/app/src/components/settings/ai-connection-chooser.tsx b/app/src/components/settings/ai-connection-chooser.tsx index 9d4bbfaf6e..dd27c42e05 100644 --- a/app/src/components/settings/ai-connection-chooser.tsx +++ b/app/src/components/settings/ai-connection-chooser.tsx @@ -107,9 +107,9 @@ import type { import { currentUserQueryOptions } from "@/lib/auth/queries"; import { ClientError } from "@/lib/client"; import { desktopShell } from "@/lib/desktop/shell"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { markFor } from "@/lib/marks"; import { queryClient } from "@/query-client"; -import { failureSaid } from "@/lib/load-failure"; /** * Choosing an AI connection: the provider list, the way in (a key, an address, or a sign-in), and @@ -395,7 +395,7 @@ export function ChooseConnection({ const [waiting, setWaiting] = useState(null); const [signInCode, setSignInCode] = useState(""); const [signedIn, setSignedIn] = useState(false); - const [signInFailure, setSignInFailure] = useState(null); + const [signInFailure, setSignInFailure] = useState(null); const [signingIn, setSigningIn] = useState(false); const [chatGptWay, setChatGptWay] = useState(firstChatGptWay); /* @@ -704,9 +704,7 @@ export function ChooseConnection({ attempt.current = null; setWaiting(null); setSigningIn(false); - setSignInFailure( - error instanceof Error ? error.message : "Couldn't sign in. Try again.", - ); + setSignInFailure(failureOf(error, "Couldn't sign in. Try again.")); } } @@ -724,7 +722,7 @@ export function ChooseConnection({ const wrong = signInId && provider?.id === "openai" ? wrongPage(pasted) : null; if (wrong) { - setSignInFailure(wrong); + setSignInFailure({ message: wrong }); return; } setSigningIn(true); @@ -742,9 +740,7 @@ export function ChooseConnection({ setSignedIn(true); } catch (error) { if (run.current !== mine) return; - const message = - error instanceof Error ? error.message : "Couldn't sign in. Try again."; - setSignInFailure(message); + setSignInFailure(failureOf(error, "Couldn't sign in. Try again.")); /* * The server refused what was pasted (400: from another sign-in, or with no code in it) and * the sign-in waits on: the box stays open for the right one. Anything else, a sign-in that @@ -1193,7 +1189,7 @@ function SignInFields({ /** This sign-in finishes through Desktop's listener: no paste box, and no page that won't load. */ noPaste: boolean; code: string; - failure: string | null; + failure: Failure | null; /** Signed in already: the admin's own sign-in, kept for them, to share as it is. */ kept: boolean; login: AiConnectionLogin; @@ -1380,7 +1376,7 @@ function SignInFields({ {failure && !waiting && !signedIn ? (

- {failure} + {failureSaid(failure)}

{/* A code that didn't work: the setting it needs is the likeliest reason. */} {chatGptCode ? ( @@ -1444,7 +1440,7 @@ function SignInFields({ {/* A code the server refused while the sign-in waits on; ChatGPT's paste box says it itself. */} {failure && waiting && !chatGptInBrowser ? (

- {failure} + {failureSaid(failure)}

) : null}
diff --git a/app/src/components/settings/browsers/this-browser.tsx b/app/src/components/settings/browsers/this-browser.tsx index b8efc7b588..81e81fc81f 100644 --- a/app/src/components/settings/browsers/this-browser.tsx +++ b/app/src/components/settings/browsers/this-browser.tsx @@ -1,6 +1,6 @@ import { IconBrowser } from "@tabler/icons-react"; import { useQuery } from "@tanstack/react-query"; -import { useEffect, useState } from "react"; +import { type ReactNode, useEffect, useState } from "react"; import { noteStoreTabOpened } from "@/components/browser/browser-nav-item"; import { PageRows, PageSection } from "@/components/layout/page-shell"; import { Button, buttonVariants } from "@/components/ui/button"; @@ -12,7 +12,12 @@ import { ItemMedia, ItemTitle, } from "@/components/ui/item"; -import { loadFailure } from "@/lib/load-failure"; +import { + type Failure, + failureOf, + failureSaid, + loadFailure, +} from "@/lib/load-failure"; import { CONFIRM_WINDOW_MS, connectRefusalSentence, @@ -45,7 +50,8 @@ type Attempt = | { state: "expired" } | { state: "cancelled" } | { state: "closed" } - | { state: "failed"; message: string }; + // The refusal kept whole, not as its words, so a hold is drawn calmly (`failureSaid`). + | { state: "failed"; failure: Failure }; /** Whether the Recorder in this browser is installed, and connected to this OpenBot as you. `onInstallId` hears this * browser's own copy once it is known (it answers with it only once connected: not while its Connect page waits for @@ -146,7 +152,9 @@ export function ThisBrowser({ if (!answer.ok) { setAttempt({ state: "failed", - message: connectRefusalSentence(answer.error, answer.retryAfterMs), + failure: { + message: connectRefusalSentence(answer.error, answer.retryAfterMs), + }, }); return; } @@ -162,10 +170,7 @@ export function ThisBrowser({ } catch (error) { setAttempt({ state: "failed", - message: - error instanceof Error - ? error.message - : "Couldn't connect this browser.", + failure: failureOf(error, "Couldn't connect this browser."), }); } } @@ -240,7 +245,7 @@ function describe( detected: DetectedRecorder | null, connected: boolean, attempt: Attempt, -): string { +): ReactNode { if (!detected) return "The OpenBot Recorder isn't installed in this browser."; if (connected) return "Connected"; switch (attempt.state) { @@ -253,7 +258,7 @@ function describe( case "closed": return "The OpenBot Recorder tab closed before you confirmed. Nothing was connected."; case "failed": - return attempt.message; + return failureSaid(attempt.failure); default: return "Installed. Connect it to record tasks for your Bots."; } diff --git a/app/src/components/settings/chatgpt-browser-sign-in.tsx b/app/src/components/settings/chatgpt-browser-sign-in.tsx index 5fc1af79ef..1b9d42f604 100644 --- a/app/src/components/settings/chatgpt-browser-sign-in.tsx +++ b/app/src/components/settings/chatgpt-browser-sign-in.tsx @@ -8,6 +8,7 @@ import { IllustrationFrame } from "@/components/onboarding/illustration-frame"; import { Button } from "@/components/ui/button"; import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"; import { Input } from "@/components/ui/input"; +import { type Failure, failureSaid } from "@/lib/load-failure"; /** * ChatGPT's sign-in in the browser, where the server runs it (a person's own AI on OpenBot Cloud). @@ -216,7 +217,7 @@ export function ChatGptPaste({ busy: boolean; code: string; /** What was wrong with the last paste, said under the box, which stays open for another. */ - failure: string | null; + failure: Failure | null; onCode: (code: string) => void; /** Send this text, or what is in the box. */ onFinish: (text?: string) => void; @@ -276,7 +277,7 @@ export function ChatGptPaste({ } } - const said = failure ?? clipboardNote; + const said = failure ? failureSaid(failure) : clipboardNote; return ( diff --git a/app/src/components/settings/learning-review.tsx b/app/src/components/settings/learning-review.tsx index dd6f1f09ac..d60a721581 100644 --- a/app/src/components/settings/learning-review.tsx +++ b/app/src/components/settings/learning-review.tsx @@ -32,8 +32,8 @@ import { personalProposalQueryOptions, personalReviewQueryOptions, } from "@/lib/learning/queries"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; -import { failureSaid } from "@/lib/load-failure"; /** What a proposal would do to the Skills, in the person's words. */ function operationLabel(proposal: LearningProposal): string { @@ -73,7 +73,8 @@ export function latestRunLine( type StartState = { pending: boolean; started: { from: string | null } | null; - error: string | null; + /** Kept whole, so a hold is said calmly (lib/load-failure.tsx). */ + error: Failure | null; }; /** Whether a run is going for one group: one it started and has not seen finish, or one the review shows running. */ @@ -106,7 +107,7 @@ function GroupError({ state }: { state: StartState | undefined }) { if (!state || state.pending || !state.error) return null; return (

- {state.error} + {failureSaid(state.error)}

); } @@ -131,16 +132,7 @@ export function LearningReview() { ); // One Learn now covers a whole group: every source is tried, and the button waits for all of them. // Each group keeps its own state, keyed by label. `from` is the group's latest run when it started. - const [starting, setStarting] = useState< - Record< - string, - { - pending: boolean; - started: { from: string | null } | null; - error: string | null; - } - > - >({}); + const [starting, setStarting] = useState>({}); // When a refetch finds fewer proposals waiting, some were approved on their own: Your skills shows them now. const waitingCount = review.data?.spaces.reduce( (count, source) => @@ -262,13 +254,13 @@ export function LearningReview() { [group.label]: { pending: true, started: null, error: null }, })); let started = false; - let error: string | null = null; + let error: Failure | null = null; for (const container of group.containers) { try { await learnNow.mutateAsync(container); started = true; } catch (failure) { - error = failure instanceof Error ? failure.message : String(failure); + error = failureOf(failure, String(failure)); } } setStarting((all) => ({ diff --git a/app/src/components/settings/learning-sharing.tsx b/app/src/components/settings/learning-sharing.tsx index 743a153ebf..747bc76052 100644 --- a/app/src/components/settings/learning-sharing.tsx +++ b/app/src/components/settings/learning-sharing.tsx @@ -37,8 +37,8 @@ import { type PersonalLearningSharing, personalLearningQueryOptions, } from "@/lib/learning/queries"; -import { queryClient } from "@/query-client"; import { failureSaid } from "@/lib/load-failure"; +import { queryClient } from "@/query-client"; /** The three choices, each with the one plain line that says who sees what. */ export const SHARING_CHOICES: { @@ -473,7 +473,7 @@ export function LearningSharing({ {choiceSection} {failure ? (

- {failure.message} + {failureSaid(failure)}

) : null} diff --git a/app/src/components/settings/standing-instructions.tsx b/app/src/components/settings/standing-instructions.tsx index 96b0b7c797..3f3b89163b 100644 --- a/app/src/components/settings/standing-instructions.tsx +++ b/app/src/components/settings/standing-instructions.tsx @@ -19,7 +19,7 @@ import { ItemTitle, } from "@/components/ui/item"; import { Textarea } from "@/components/ui/textarea"; -import { loadFailure, failureSaid } from "@/lib/load-failure"; +import { type Failure, failureSaid, loadFailure } from "@/lib/load-failure"; import { saveInstructionsMutationOptions } from "@/lib/settings/mutations"; import { INSTRUCTIONS_LIMIT, @@ -89,7 +89,7 @@ function StandingInstructionsEditor() { const save = useMutation(saveInstructionsMutationOptions(queryClient)); const [draft, setDraft] = useState(null); - const [problem, setProblem] = useState(null); + const [problem, setProblem] = useState(null); const [saved, setSaved] = useState(false); /* @@ -111,7 +111,7 @@ function StandingInstructionsEditor() { setProblem(null); setSaved(false); save.mutate(text, { - onError: (thrown: Error) => setProblem(thrown.message), + onError: (thrown: Error) => setProblem(thrown), /* The server trims, so the box settles to what was actually stored rather than what was sent. */ onSuccess: (asStored) => { setDraft(asStored); @@ -156,7 +156,7 @@ function StandingInstructionsEditor() { */} {problem ? ( - {problem} + {failureSaid(problem)} ) : saved ? ( Saved diff --git a/app/src/components/skills/proposed-skill.tsx b/app/src/components/skills/proposed-skill.tsx index 9580439fa9..b5322af394 100644 --- a/app/src/components/skills/proposed-skill.tsx +++ b/app/src/components/skills/proposed-skill.tsx @@ -2,6 +2,7 @@ import { Link } from "@tanstack/react-router"; import { useEffect, useRef, useState } from "react"; import { Badge, GalleryFrame } from "@/components/gallery/frame"; import { Button } from "@/components/ui/button"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import type { SkillFormValues } from "@/lib/skills/form"; import { checkProposal, @@ -61,7 +62,7 @@ export function ProposedSkillCard({ * Create again after connecting the connector the refusal named, or declining. Answering the tool * with the error would end the turn and leave the person re-typing their request. */ - const [refusal, setRefusal] = useState(null); + const [refusal, setRefusal] = useState(null); if (result !== undefined) { return ( @@ -99,9 +100,7 @@ export function ProposedSkillCard({ } catch (cause) { // Left on the card with the buttons still live. See `refusal` above. setSending(null); - setRefusal( - cause instanceof Error ? cause.message : "Couldn't save the skill.", - ); + setRefusal(failureOf(cause, "Couldn't save the skill.")); return; } await answer(respond, skillCardAnswer.saved(values.slug)); @@ -158,7 +157,7 @@ export function ProposedSkillCard({ {refusal ? (

- {refusal} + {failureSaid(refusal)}

) : null} diff --git a/app/src/components/skills/skills-settings-page.tsx b/app/src/components/skills/skills-settings-page.tsx index f00e789b50..01b004638f 100644 --- a/app/src/components/skills/skills-settings-page.tsx +++ b/app/src/components/skills/skills-settings-page.tsx @@ -43,7 +43,7 @@ import { grantSummary } from "@/lib/agents/grant-summary"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { browserStateQueryOptions } from "@/lib/browser/queries"; -import { loadFailure } from "@/lib/load-failure"; +import { type Failure, failureSaid, loadFailure } from "@/lib/load-failure"; import { useManagePaths } from "@/lib/manage-paths"; import { removeSkillMutationOptions } from "@/lib/skills/mutations"; import { type Skill, skillListQueryOptions } from "@/lib/skills/queries"; @@ -82,10 +82,11 @@ export function SkillsSettingsPage({ const { data: agents } = useQuery(agentListQueryOptions()); const { data: hiddenAgents } = useQuery(agentListQueryOptions(true)); const browser = useQuery(browserStateQueryOptions()); - const [error, setError] = useState(null); + // The error itself, not its words, so a hold is drawn calmly (lib/load-failure.tsx). + const [error, setError] = useState(null); const removeSkill = useMutation({ ...removeSkillMutationOptions(queryClient), - onError: (thrown: Error) => setError(thrown.message), + onError: (thrown: Error) => setError(thrown), onSuccess: () => setError(null), }); @@ -217,7 +218,7 @@ export function SkillsSettingsPage({ > {error ? (

- {error} + {failureSaid(error)}

) : null} {loaded && !writtenKnown ? ( diff --git a/app/src/components/starter-tour/starter-suggestions.tsx b/app/src/components/starter-tour/starter-suggestions.tsx index 89947b744a..a652401de5 100644 --- a/app/src/components/starter-tour/starter-suggestions.tsx +++ b/app/src/components/starter-tour/starter-suggestions.tsx @@ -4,6 +4,7 @@ import { useQuery } from "@tanstack/react-query"; import { useRef, useState } from "react"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { userPreferencesQueryOptions } from "@/lib/settings/message-list"; import { INTERACTIVE_STARTER, @@ -45,7 +46,7 @@ function StarterSuggestionChoices({ onSelect, disabled = false }: Props) { const capabilities = useQuery(deploymentCapabilitiesQueryOptions()); const [sending, setSending] = useState(false); const sendingRef = useRef(false); - const [error, setError] = useState(null); + const [error, setError] = useState(null); const choose = async (index: number) => { if (disabled || sendingRef.current) return; @@ -56,11 +57,11 @@ function StarterSuggestionChoices({ onSelect, disabled = false }: Props) { suggestion === INTERACTIVE_STARTER && capabilities.data?.generativeUi !== true ) { - setError( - capabilities.isPending + setError({ + message: capabilities.isPending ? "Still checking whether interactive answers are available. Try again in a moment." : "Interactive answers are disabled for this installation. Try another starter task.", - ); + }); return; } sendingRef.current = true; @@ -68,11 +69,7 @@ function StarterSuggestionChoices({ onSelect, disabled = false }: Props) { try { await onSelect(suggestion.message); } catch (caught) { - setError( - caught instanceof Error - ? caught.message - : "Couldn't start that task. Try again.", - ); + setError(failureOf(caught, "Couldn't start that task. Try again.")); } finally { sendingRef.current = false; setSending(false); @@ -104,7 +101,7 @@ function StarterSuggestionChoices({ onSelect, disabled = false }: Props) { /> {error ? (

- {error} + {failureSaid(error)}

) : null} diff --git a/app/src/components/tasks/task-thread.tsx b/app/src/components/tasks/task-thread.tsx index 843ad93233..9b14c1d965 100644 --- a/app/src/components/tasks/task-thread.tsx +++ b/app/src/components/tasks/task-thread.tsx @@ -20,6 +20,7 @@ import { type ReactNode, useContext, useState } from "react"; import { Button } from "@/components/ui/button"; import { agentListQueryOptions } from "@/lib/agents/queries"; import { elapsed, useNow } from "@/lib/elapsed"; +import { type Failure, failureSaid } from "@/lib/load-failure"; import { relativeTime } from "@/lib/relative-time"; import { stopTaskMutationOptions } from "@/lib/tasks/mutations"; import { @@ -234,12 +235,13 @@ function StopTask({ onError, }: { taskId: string; - onError: (message: string | null) => void; + /** The failure kept whole, so a hold is drawn calmly (lib/load-failure.tsx). */ + onError: (failure: Failure | null) => void; }) { const stop = useMutation({ ...stopTaskMutationOptions(queryClient), onMutate: () => onError(null), - onError: (error) => onError(error.message), + onError: (error) => onError(error), }); return ( ); - // The not-entitled refusal is the state itself below, so it isn't said twice. - const notice = notEntitled ? null : (failure?.message ?? status.lastError); + // The not-entitled refusal is the state itself below, so it isn't said twice. A refused press is + // drawn through the shared rule, so a hold is said calmly. + const notice = notEntitled + ? null + : failure + ? failureSaid(failure) + : status.lastError; return ( diff --git a/app/src/routes/_authed/admin/people.tsx b/app/src/routes/_authed/admin/people.tsx index 30e40378ec..79d1fc9a39 100644 --- a/app/src/routes/_authed/admin/people.tsx +++ b/app/src/routes/_authed/admin/people.tsx @@ -39,7 +39,7 @@ import { Switch } from "@/components/ui/switch"; import { currentUserQueryOptions } from "@/lib/auth/queries"; import { isOrganizationAdmin } from "@/lib/auth/roles"; import { terminateMemberComputersMutationOptions } from "@/lib/enterprise/mutations"; -import { loadFailure, failureSaid } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { useCurrentOrganizationId } from "@/lib/organizations/current"; import { useOrganizationChoices } from "@/lib/organizations/queries"; import { @@ -177,7 +177,7 @@ function PeoplePage() { > {failure ? (

- {failure.message} + {failureSaid(failure)}

) : null} {terminate.data ? ( diff --git a/app/src/routes/_authed/admin/playground.tsx b/app/src/routes/_authed/admin/playground.tsx index 8ae21633f7..0d0bea5e14 100644 --- a/app/src/routes/_authed/admin/playground.tsx +++ b/app/src/routes/_authed/admin/playground.tsx @@ -25,6 +25,7 @@ import { type PlaygroundRecord, playgroundListQueryOptions, } from "@/lib/components/queries"; +import { type Failure, failureSaid } from "@/lib/load-failure"; /** * Browser-authored components are edited as drafts, previewed in the production sandbox renderer, @@ -120,7 +121,8 @@ function PlaygroundPage() { const queryClient = useQueryClient(); const { data: components } = useQuery(playgroundListQueryOptions()); const [draft, setDraft] = useState(STARTER); - const [error, setError] = useState(null); + // The error itself, not its words, so a hold is drawn calmly (lib/load-failure.tsx). + const [error, setError] = useState(null); const [notice, setNotice] = useState(null); const set = (field: keyof Draft) => (value: string) => { @@ -133,7 +135,7 @@ function PlaygroundPage() { const sample = validation.ok ? validation.input.sampleArguments : null; /* Every write here reports into the same banner, so they share one failure handler. */ - const report = { onError: (thrown: Error) => setError(thrown.message) }; + const report = { onError: (thrown: Error) => setError(thrown) }; const saveDraft = useMutation({ ...savePlaygroundDraftMutationOptions(queryClient), ...report, @@ -154,10 +156,11 @@ function PlaygroundPage() { const current = validatePlaygroundDraft(draft); if (!current.ok) { setNotice(null); - setError( - Object.values(current.fields)[0] ?? + setError({ + message: + Object.values(current.fields)[0] ?? "Fix the JSON fields before saving.", - ); + }); return null; } return current.input; @@ -241,7 +244,7 @@ function PlaygroundPage() { className="border-border border-b bg-destructive/10 px-6 py-2 text-destructive text-sm" role="alert" > - {error} + {failureSaid(error)}
) : null} {notice ? ( diff --git a/app/src/routes/_authed/admin/proactive.tsx b/app/src/routes/_authed/admin/proactive.tsx index 2b53336bc5..3119e86724 100644 --- a/app/src/routes/_authed/admin/proactive.tsx +++ b/app/src/routes/_authed/admin/proactive.tsx @@ -62,7 +62,7 @@ import { type EnterpriseOverview, enterpriseOverviewQueryOptions, } from "@/lib/enterprise/queries"; -import { loadFailure } from "@/lib/load-failure"; +import { failureSaid, loadFailure } from "@/lib/load-failure"; import { queryClient } from "@/query-client"; export const Route = createFileRoute("/_authed/admin/proactive")({ @@ -241,7 +241,7 @@ function CheckInSettings({ data }: { data: EnterpriseOverview }) { {failure ? (

- {failure.message} + {failureSaid(failure)}

) : null} (null); + const [askProblem, setAskProblem] = useState(null); const [unclear, setUnclear] = useState(null); /** The question the chips were read from, until the admin starts over. */ const [asked, setAsked] = useState(null); @@ -79,7 +84,7 @@ function WhatIfPage() { ); const [checked, setChecked] = useState(null); const [checking, setChecking] = useState(false); - const [checkProblem, setCheckProblem] = useState(null); + const [checkProblem, setCheckProblem] = useState(null); const question = text.trim(); const setAction = (next: WhatIfAction) => { @@ -102,7 +107,7 @@ function WhatIfPage() { setAction(reading.action); } } catch (thrown) { - setAskProblem((thrown as Error).message); + setAskProblem(failureOf(thrown, String(thrown))); } finally { setAsking(false); } @@ -119,7 +124,7 @@ function WhatIfPage() { try { setChecked(await checkWhatIf(action, asked ?? undefined)); } catch (thrown) { - setCheckProblem((thrown as Error).message); + setCheckProblem(failureOf(thrown, String(thrown))); } finally { setChecking(false); } @@ -171,7 +176,7 @@ function WhatIfPage() { data-what-if-problem role="alert" > - {askProblem} + {failureSaid(askProblem)}

) : unclear ? (

@@ -224,7 +229,7 @@ function WhatIfPage() { ) : null} {checkProblem ? (

- {checkProblem} + {failureSaid(checkProblem)}

) : null} diff --git a/app/src/routes/sign.tsx b/app/src/routes/sign.tsx index 327197e454..34612fc6f8 100644 --- a/app/src/routes/sign.tsx +++ b/app/src/routes/sign.tsx @@ -18,6 +18,7 @@ import { } from "@/lib/auth/client"; import { resumeUrlFor, verifierPathFor } from "@/lib/auth/resume"; import { appConfig } from "@/lib/generated/application-config"; +import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { inNoOrganization } from "@/lib/organizations/in-no-organization"; import { searchTextEntry } from "@/lib/search-text"; import { cn } from "@/lib/utils"; @@ -86,7 +87,7 @@ function SignScreen() { // Which provider is being opened, rather than whether one is: with three buttons, a single // boolean would put "Opening…" on all of them. const [opening, setOpening] = useState(null); - const [error, setError] = useState(null); + const [error, setError] = useState(null); const { data: options } = useQuery(authProvidersQueryOptions()); const providers = options?.providers ?? []; // OpenBot Cloud: its own screen (`CloudSignIn`), and none of the ways in below. @@ -112,9 +113,10 @@ function SignScreen() { ); } catch (caughtError) { setError( - caughtError instanceof Error - ? caughtError.message - : "No company sign-in is set up for that address.", + failureOf( + caughtError, + "No company sign-in is set up for that address.", + ), ); setOpening(null); } @@ -132,9 +134,10 @@ function SignScreen() { ); } catch (caughtError) { setError( - caughtError instanceof Error - ? caughtError.message - : `Couldn't open ${providerName(provider)} sign-in. Try again.`, + failureOf( + caughtError, + `Couldn't open ${providerName(provider)} sign-in. Try again.`, + ), ); setOpening(null); } @@ -284,7 +287,7 @@ function SignScreen() { ) : null} {error ? (

- {error} + {failureSaid(error)}

) : null} diff --git a/app/src/skins/opendots/sidebar.tsx b/app/src/skins/opendots/sidebar.tsx index b34da77ac7..8d188b6592 100644 --- a/app/src/skins/opendots/sidebar.tsx +++ b/app/src/skins/opendots/sidebar.tsx @@ -50,7 +50,7 @@ import { } from "@/lib/channels/queries"; import { useOffersMemory } from "@/lib/deployment/queries"; import { appConfig } from "@/lib/generated/application-config"; -import { loadFailure } from "@/lib/load-failure"; +import { type Failure, failureSaid, loadFailure } from "@/lib/load-failure"; import { memoriesQueryOptions } from "@/lib/memory"; import { isNavigationLink, useNavigationItems } from "@/lib/navigation"; import { routinesQueryOptions } from "@/lib/routines/queries"; @@ -303,7 +303,7 @@ function ThreadRow({ const navigate = useNavigate(); const setPinned = useMutation(setChannelPinnedMutationOptions(queryClient)); const [confirming, setConfirming] = useState(false); - const [pinProblem, setPinProblem] = useState(null); + const [pinProblem, setPinProblem] = useState(null); const unread = isUnread(channel, open ? channel.id : undefined); const title = channel.summary || untitledLine(channel) || channel.name; const link: LinkProps = @@ -353,7 +353,7 @@ function ThreadRow({ setPinProblem(null); setPinned.mutate( { channelId: channel.id, pinned: !channel.pinned }, - { onError: (thrown) => setPinProblem(thrown.message) }, + { onError: (thrown) => setPinProblem(thrown) }, ); }} > @@ -371,7 +371,7 @@ function ThreadRow({ {pinProblem ? (

- {pinProblem} + {failureSaid(pinProblem)}

) : null} (null); + const [problem, setProblem] = useState(null); const title = channel.summary || untitledLine(channel) || "New conversation"; const when = channel.lastMessageAt ? relativeTime(channel.lastMessageAt) @@ -451,7 +451,7 @@ function ConversationRow({ setProblem(null); setPinned.mutate( { channelId: channel.id, pinned: !channel.pinned }, - { onError: (thrown) => setProblem(thrown.message) }, + { onError: (thrown) => setProblem(thrown) }, ); }} > @@ -472,7 +472,7 @@ function ConversationRow({ className="openduet-type-caption px-3 pb-1 text-openduet-problem" role="alert" > - {problem} + {failureSaid(problem)}

) : null} void }) { > Sign out - + ) : null}
@@ -320,10 +317,7 @@ function ConversationRow({ Delete
- + navigate({ to: "/" }) : undefined} diff --git a/app/src/skins/openfuse/ui.tsx b/app/src/skins/openfuse/ui.tsx index 25ab9099f4..403ce8ab4d 100644 --- a/app/src/skins/openfuse/ui.tsx +++ b/app/src/skins/openfuse/ui.tsx @@ -16,6 +16,7 @@ import { ItemMedia, ItemTitle, } from "@/components/ui/item"; +import { type Failure, unavailableSaid } from "@/lib/load-failure"; import { cn } from "@/lib/utils"; /* @@ -257,23 +258,31 @@ export function FuseEmpty({ export function ErrorNotice({ error, held = false, + failure, }: { error?: string | null; /** OpenBot holding off for now (lib/load-failure.tsx): drawn calm, never as a failure. */ held?: boolean; + /** + * A press's failure, kept whole: its words, drawn calm when it is OpenBot holding off for now, so + * the caller needn't work that out (lib/load-failure.tsx). + */ + failure?: Failure | null; }) { - if (!error) return null; + const words = failure ? failure.message : error; + const calm = failure ? unavailableSaid(failure) !== undefined : held; + if (!words) return null; return (
- {error} + {words}
); } diff --git a/app/tests/dictation-session.test.ts b/app/tests/dictation-session.test.ts index d0e65367ea..4b2d7148b9 100644 --- a/app/tests/dictation-session.test.ts +++ b/app/tests/dictation-session.test.ts @@ -73,7 +73,7 @@ test("retry uses the same recording and never opens a new microphone", async () expect(session.getSnapshot()).toMatchObject({ phase: "error", canRetry: true, - error: "Service unavailable", + error: { message: "Service unavailable" }, }); await session.retry(); expect(recordings).toBe(1); @@ -112,7 +112,9 @@ test("permission errors have an actionable recovery", async () => { expect(session.getSnapshot()).toMatchObject({ phase: "error", canRetry: false, - error: - "Microphone access was denied. Allow it in your browser and try again.", + error: { + message: + "Microphone access was denied. Allow it in your browser and try again.", + }, }); }); diff --git a/app/tests/failure-said.test.ts b/app/tests/failure-said.test.ts index 58234ba2bb..d7cbae3e91 100644 --- a/app/tests/failure-said.test.ts +++ b/app/tests/failure-said.test.ts @@ -3,7 +3,7 @@ import { readdirSync, readFileSync } from "node:fs"; import { join, relative } from "node:path"; /** - * No page draws an error's own words straight into the page. + * No page draws an error's own words straight into the page, or keeps only the words to draw later. * * A failure said in the error's own words (`{save.error.message}`) is drawn in the red the app keeps * for what failed. While OpenBot moves an organization, or its database is out of reach, the server @@ -13,55 +13,142 @@ import { join, relative } from "node:path"; * same words for a real failure and the server's sentence calmly for a hold, so every place draws an * error's words through it, and this test finds any that doesn't. * - * What it finds: an error's `.message` as the whole of a JSX child (`{x.error.message}`, - * `{error?.message}`), or as the start or end of an `||`/`??` choice inside one. + * A press that failed did the same a step earlier: it kept `error.message` in its state + * (`setFailure(error.message)`) and drew that string red, so the hold was lost before anything was + * drawn (exporting the audit log, adding someone to a team, creating a Bot). A press keeps the error + * itself (`failureOf`, `failureInstead`), and a toast takes its type from it (`failureToastType`). + * + * What it finds: + * - a `.message` as the whole of a JSX child (`{x.error.message}`, `{failure?.message}`, + * `{(save.error ?? remove.error)?.message}`), or as the start or end of an `||`/`??` choice in one; + * - an error's `.message` handed to a state setter (`setError(thrown.message)`, + * `setError(error instanceof Error ? error.message : "…")`) or to a prop named for an error + * (`error={save.error?.message}`); + * - a toast that says an error's `.message` as an error without asking `failureToastType`. */ const SRC = join(import.meta.dir, "..", "src"); /** The primitives draw what they are given (a form's field errors), not a server's answer. */ -const OUTSIDE = [join(SRC, "components", "ui")]; +const OUTSIDE = [ + join(SRC, "components", "ui"), + join(SRC, "lib", "api", "generated"), +]; function sources(dir: string): string[] { return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { const path = join(dir, entry.name); if (entry.isDirectory()) return OUTSIDE.includes(path) ? [] : sources(path); - return entry.name.endsWith(".tsx") ? [path] : []; + return /\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts") + ? [path] + : []; }); } -const ERROR_MESSAGE = String.raw`[A-Za-z_$][\w$.]*[eE]rror\??\.message`; -/** `{ x.error.message }`, `{x.error?.message || ...`, `... ?? x.error.message}` as a JSX child. */ -const RAW = new RegExp( - String.raw`>\s*\{\s*${ERROR_MESSAGE}\s*(\}|\|\||\?\?)|(\|\||\?\?)\s*${ERROR_MESSAGE}\s*\}\s*<|^\s*\{\s*${ERROR_MESSAGE}\s*(\}|\|\||\?\?)`, +/** `x.message`, `x.error?.message`, `(a.error ?? b.error)?.message`. */ +const MESSAGE = String.raw`(?:[A-Za-z_$][\w$.?]*|\([^(){}]*\))\??\.message`; +/** `{ x.error.message }`, `{failure?.message || ...`, `... ?? x.error.message}` as a JSX child. */ +const DRAWN = new RegExp( + String.raw`>\s*\{\s*${MESSAGE}\s*(\}|\|\||\?\?)|(\|\||\?\?)\s*${MESSAGE}\s*\}\s*<|^\s*\{\s*${MESSAGE}\s*(\}|\|\||\?\?)`, "m", ); +/** `error={x.error?.message}`, `submissionError={failure?.message ?? null}`. */ +const PROP = new RegExp(String.raw`\b\w*[eE]rror=\{\s*${MESSAGE}`); + +/** A zod issue's words are the form's own, not a server's answer. */ +const ISSUE = /issues\[\d+\]\??\.message|\bissue\.message/g; +/** An error's words as what a call keeps: the thrown thing's `.message`, alone or chosen. */ +const KEPT_MESSAGE = + /^\s*(?:\(\s*)?[A-Za-z_$][\w$]*(?:\s+as\s+\w+\s*\))?\??\.message\b|^\s*[A-Za-z_$][\w$]*\s+instanceof\s+\w+(?:\s*&&\s*[\w$.]+)?\s*\?\s*[A-Za-z_$][\w$]*\.message\b/; + +/** Each call of `callee` in `text`, with the line it starts on and what it is called with. */ +function calls( + text: string, + callee: RegExp, +): { line: number; argument: string }[] { + const found: { line: number; argument: string }[] = []; + for (const match of text.matchAll(callee)) { + const open = (match.index ?? 0) + match[0].length - 1; + let depth = 0; + let end = open; + for (; end < text.length; end++) { + if (text[end] === "(") depth++; + else if (text[end] === ")" && --depth === 0) break; + } + found.push({ + line: text.slice(0, match.index).split("\n").length, + argument: text.slice(open + 1, end), + }); + } + return found; +} + +/** Every place in `text` that draws or keeps an error's words around the shared rule. */ +function bypasses(text: string): number[] { + const lines: number[] = []; + text.split("\n").forEach((line, index) => { + if (DRAWN.test(line) || PROP.test(line)) lines.push(index + 1); + }); + // A state setter, or a callback that hands a failure on to one (`report`, `onError`). + for (const { line, argument } of calls( + text, + /\b(?:set[A-Z]\w*|report|onError)\(/g, + )) + if (KEPT_MESSAGE.test(argument.replace(ISSUE, ""))) lines.push(line); + for (const { line, argument } of calls(text, /\btoast\.add\(/g)) + if ( + /\.message\b/.test(argument) && + /type:\s*"error"/.test(argument) && + !argument.includes("failureToastType") + ) + lines.push(line); + return [...new Set(lines)].sort((a, b) => a - b); +} describe("an error's own words", () => { - test("are drawn through failureSaid on every page", () => { + test("are drawn through failureSaid on every page, and kept whole until then", () => { const raw: string[] = []; for (const file of sources(SRC)) { - const lines = readFileSync(file, "utf8").split("\n"); - lines.forEach((line, index) => { - if (RAW.test(line)) - raw.push(`${relative(SRC, file)}:${index + 1}: ${line.trim()}`); - }); + const text = readFileSync(file, "utf8"); + const lines = text.split("\n"); + for (const line of bypasses(text)) + raw.push(`${relative(SRC, file)}:${line}: ${lines[line - 1]?.trim()}`); } expect(raw).toEqual([]); }); test("the scan finds the shapes it is meant to", () => { - for (const line of [ + for (const text of [ " {memories.error.message}", " {review.error?.message}", ' {bots.error?.message || "Couldn\'t load your Bots."}', "

{delivery.error.message}

", + " {failure.message}", + " {(save.error ?? remove.error)?.message}", + " error={signOut.error?.message}", + " onError: (thrown: Error) => setProblem(thrown.message),", + " setError((thrown as Error).message);", + " report(thrown.message);", + " onError: (error) => onError(error.message),", + ' setFailure(\n error instanceof Error\n ? error.message\n : "Couldn\'t add them. Try again in a moment.",\n );', + " setUnreachable(\n error instanceof Error && error.message\n ? error.message\n : MASTRA_UNREACHABLE,\n );", + ' toast.add({\n id: SWITCH_TOAST,\n title: error.message,\n type: "error",\n }),', ]) - expect({ line, found: RAW.test(line) }).toEqual({ line, found: true }); - for (const line of [ + expect({ text, found: bypasses(text).length > 0 }).toEqual({ + text, + found: true, + }); + for (const text of [ " {failureSaid(memories.error)}", " error: error ? error.message : null,", " return error instanceof Error ? error.message : String(error);", + " setNameError(parsed.error.issues[0]?.message);", + ' setExportError(failureOf(error, "Couldn\'t export these events. Try again."));', + " setError(GROUP_TAKES_NO_FILES);", + " toast.add({\n title: error.message,\n type: failureToastType(error),\n }),", ]) - expect({ line, found: RAW.test(line) }).toEqual({ line, found: false }); + expect({ text, found: bypasses(text).length > 0 }).toEqual({ + text, + found: false, + }); }); }); diff --git a/app/tests/organization-held-actions.test.tsx b/app/tests/organization-held-actions.test.tsx new file mode 100644 index 0000000000..9279cf65a4 --- /dev/null +++ b/app/tests/organization-held-actions.test.tsx @@ -0,0 +1,152 @@ +import { afterAll, beforeAll, describe, expect, test } from "bun:test"; +import type { Page } from "playwright-core"; +import { + asked, + drawnColor, + engines, + FakeServer, + go, + LOOKS, + type Look, + open, + shoot, + start, + stop, + TEAM, + UNAVAILABLE, +} from "./organization-notices-browser"; + +/** + * A press refused because the organization's database is out of reach says the server's sentence + * calmly, never in the destructive red. + * + * Pages that draw a failed read went through the shared rule (lib/load-failure.tsx) already + * (organization-unavailable-pages.test.tsx), but a press kept only the error's words in its state + * and drew them red later, so the hold was lost before anything was drawn: adding somebody to a team + * said "This organization is unavailable right now. Try again in a moment." in red, and so did + * creating a Bot from the card a Bot puts in a conversation. Each keeps the error itself now. + * + * In a real browser, Chromium and WebKit, at 1440 and 390 wide, light and dark: Northwind's reads are + * answered and its writes refused with the hold. The person adds Priya to Operations, then presses + * Create it on a proposed Bot. Each says the server's sentence once, not drawn in the destructive red. + * With Northwind reachable and the create refused for a real reason, the card still says it in red. + * + * OPENBOT_APP_BROWSER=1 OPENBOT_APP_ENGINES=chromium,webkit bun test app/tests/organization-held-actions.test.tsx + * + * With OPENBOT_APP_SHOTS= each step is saved as organization-held----.png. + */ +beforeAll(async () => { + if (asked) await start(); +}, 120_000); + +afterAll(async () => { + await stop(); +}); + +/** The words a press draws when it is refused for a reason that isn't a hold. */ +const NOT_FOUND = "Not found."; + +/** The server's sentence is said in an alert, once, and not in the destructive red. */ +async function saidCalmly( + page: Page, + where: string, + engine: string, + look: Look, +): Promise { + const alert = page.getByRole("alert").filter({ hasText: UNAVAILABLE }); + await alert.first().waitFor({ timeout: 8_000 }); + await shoot(page, "organization-held", where, engine, look); + expect({ where, said: await alert.count() }).toEqual({ where, said: 1 }); + const color = await drawnColor(page, UNAVAILABLE); + expect({ where, drawn: color.drawn === null }).toEqual({ + where, + drawn: false, + }); + expect({ where, red: color.drawn === color.destructive }).toEqual({ + where, + red: false, + }); +} + +describe.skipIf(!asked)( + "A press while the organization's database is out of reach", + () => { + for (const engine of engines) + for (const look of LOOKS) { + test(`adding somebody to a team says the server's sentence calmly, in ${engine}, ${look.width}, ${look.theme}`, async () => { + const server = new FakeServer(); + const page = await open(engine, look, server, `/teams/${TEAM.id}`); + try { + await page + .getByRole("heading", { name: TEAM.name }) + .first() + .waitFor(); + server.holdWrites = true; + server.holdSaid = UNAVAILABLE; + server.retryAfterSeconds = 60; + await page + .getByRole("button", { name: "Add person" }) + .first() + .click(); + await page.getByRole("dialog").getByRole("combobox").fill("Priya"); + // Chosen as a person does from the box: the best match is highlighted, and Enter adds them. + await page.getByRole("option", { name: /Priya Shah/ }).waitFor(); + await page.getByRole("dialog").getByRole("combobox").press("Enter"); + await saidCalmly(page, "add-to-team", engine, look); + expect(server.wrote).toContain( + `PUT /teams/${TEAM.id}/members/priya`, + ); + } finally { + await page.close(); + } + }, 60_000); + + test(`creating a Bot says the server's sentence calmly, in ${engine}, ${look.width}, ${look.theme}`, async () => { + const server = new FakeServer(); + const page = await open(engine, look, server, "/"); + try { + await page.getByRole("heading", { name: "Home" }).waitFor(); + await go(page, "/propose-bot"); + const create = page.getByRole("button", { name: "Create it" }); + await create.waitFor(); + server.holdWrites = true; + server.holdSaid = UNAVAILABLE; + server.retryAfterSeconds = 60; + await create.click(); + await saidCalmly(page, "create-bot", engine, look); + expect(server.wrote).toContain("POST /bots"); + } finally { + await page.close(); + } + }, 60_000); + + test(`a press refused for a real reason still says it in red, in ${engine}, ${look.width}, ${look.theme}`, async () => { + // Northwind is reachable; the test's server takes no writes, and says so with 404. + const server = new FakeServer(); + const page = await open(engine, look, server, "/"); + try { + await page.getByRole("heading", { name: "Home" }).waitFor(); + await go(page, "/propose-bot"); + await page.getByRole("button", { name: "Create it" }).click(); + await page + .getByRole("alert") + .filter({ hasText: NOT_FOUND }) + .first() + .waitFor({ timeout: 8_000 }); + await shoot( + page, + "organization-held", + "real-failure", + engine, + look, + ); + const color = await drawnColor(page, NOT_FOUND); + expect(color.drawn).not.toBeNull(); + expect(color.drawn).toBe(color.destructive); + } finally { + await page.close(); + } + }, 60_000); + } + }, +); diff --git a/app/tests/organization-notices-browser.ts b/app/tests/organization-notices-browser.ts index 01b78f2c0a..0b2387c171 100644 --- a/app/tests/organization-notices-browser.ts +++ b/app/tests/organization-notices-browser.ts @@ -19,9 +19,18 @@ import type { Browser, BrowserType, Page, Request } from "playwright-core"; import { compile } from "tailwindcss"; import { ListCheckInsResponse } from "@/lib/api/generated/check-ins/check-ins.zod"; import { ListGoalsResponse } from "@/lib/api/generated/goals/goals.zod"; -import { ListOrganizationsResponse } from "@/lib/api/generated/organizations/organizations.zod"; +import { + ListOrganizationMembersResponse, + ListOrganizationsResponse, +} from "@/lib/api/generated/organizations/organizations.zod"; import { GetPreferencesResponse } from "@/lib/api/generated/people/people.zod"; import { ListRoutinesResponse } from "@/lib/api/generated/routines/routines.zod"; +import { + GetTeamModelsResponse, + GetTeamResponse, + ListTeamMembersResponse, + ListTeamsResponse, +} from "@/lib/api/generated/teams/teams.zod"; import { personBody } from "./accounts-api"; import { conversationPage, problemBody } from "./conversations-api"; @@ -115,6 +124,13 @@ export class FakeServer { holdSaid: string = MOVING; /** A hold that lasts this long from the first request it refuses, however long that takes to come. */ private holdFromFirstRefusalMs: number | undefined; + /** + * Hold only what writes: every read about Northwind is answered, and a press (create a Bot, add + * somebody to a team) is refused with the hold, as it is when the move begins after the page opened. + */ + holdWrites = false; + /** Each write asked of Northwind, as `METHOD /path`, in order. */ + wrote: string[] = []; /** Hold Northwind from now, until `ms` after the first request the hold refuses. */ holdFromFirstRefusal(ms: number): void { @@ -162,7 +178,12 @@ export class FakeServer { }; if (organization === NORTHWIND.id && this.removed === "403") return { status: 403, json: { error: LEFT_REFUSAL } }; - if (organization === NORTHWIND.id && Date.now() < this.movingUntil) { + if (organization === NORTHWIND.id && method !== "GET") + this.wrote.push(`${method} ${rest}`); + if ( + organization === NORTHWIND.id && + (Date.now() < this.movingUntil || (this.holdWrites && method !== "GET")) + ) { if (this.holdFromFirstRefusalMs !== undefined) { this.movingUntil = Date.now() + this.holdFromFirstRefusalMs; this.holdFromFirstRefusalMs = undefined; @@ -242,6 +263,43 @@ export class FakeServer { status: 200, json: { attention: [], lastPingId: null, nextCursor: null }, }; + // One team, which Dana may add people to, and one person in the organization to add. + case "/teams": + return { + status: 200, + json: ListTeamsResponse.parse({ + teams: [TEAM], + canCreate: true, + nextCursor: null, + }), + }; + case `/teams/${TEAM.id}`: + return { status: 200, json: GetTeamResponse.parse({ team: TEAM }) }; + case `/teams/${TEAM.id}/members`: + return { + status: 200, + json: ListTeamMembersResponse.parse({ + members: url.searchParams.get("search") ? [] : [TEAM_MEMBER], + nextCursor: null, + }), + }; + case `/teams/${TEAM.id}/models`: + return { + status: 200, + json: GetTeamModelsResponse.parse({ + models: null, + updatedBy: null, + updatedAt: null, + }), + }; + case "/members": + return { + status: 200, + json: ListOrganizationMembersResponse.parse({ + members: [PRIYA], + nextCursor: null, + }), + }; default: return this.notFound(); } @@ -273,6 +331,43 @@ export class FakeServer { } } +/** Northwind's one team: Dana keeps it, so she may add people to it. */ +export const TEAM = { + id: "team_ops", + name: "Operations", + description: null, + parentTeamId: null, + source: "openbot" as const, + memberCount: 1, + role: "maintainer" as const, + canManage: true, + canMove: false, + canDelete: false, + createdAt: "2026-11-20T09:00:00.000Z", +}; + +const TEAM_MEMBER = { + id: "dana", + email: "dana@example.com", + name: "Dana Whitfield", + image: null, + role: "maintainer" as const, + isCaller: true, + joinedAt: "2026-11-20T09:00:00.000Z", +}; + +/** Somebody in Northwind who isn't in the team yet. */ +export const PRIYA = { + removable: true, + assignableRoles: [], + id: "priya", + email: "priya@example.com", + name: "Priya Shah", + image: null, + role: "member", + joinedAt: "2026-11-20T09:00:00.000Z", +}; + const DEPLOYMENT = { generativeUi: true, selfHostBanner: false, diff --git a/app/tests/organization-notices.fixture.tsx b/app/tests/organization-notices.fixture.tsx index 1ff49cf119..cd1ac7073a 100644 --- a/app/tests/organization-notices.fixture.tsx +++ b/app/tests/organization-notices.fixture.tsx @@ -11,9 +11,11 @@ import type { ReactNode } from "react"; import { createRoot } from "react-dom/client"; import { PageShell } from "@/components/layout/page-shell"; import { OrganizationBoundary } from "@/components/organizations/organization-boundary"; +import { TeamDetailPage } from "@/components/teams/team-page"; import { ThemeProvider } from "@/components/theme-provider"; import { TooltipProvider } from "@/components/ui/tooltip"; import { signedInUser } from "@/lib/auth/queries"; +import { ProposedBotRender } from "@/lib/copilot/bot-tools"; import { ReportedErrorComponent } from "@/lib/error-reporting"; import { queryClient } from "@/query-client"; import { Route as AppRoute } from "@/routes/_authed/_app"; @@ -27,7 +29,8 @@ import { Route as TeamsRoute } from "@/routes/_authed/_app/teams"; * the signed-in gate's first step (who is signed in, and the organization they work in), the * organization boundary `_authed` puts around everything, and the app's real frame (`_authed/_app`: * the strip, its panels and every bar over the page). Inside it, Routines is the real page; home is - * a stand-in heading. Memory and Teams are the real pages too. OpenBot's API is the test's routes. + * a stand-in heading. Memory and Teams are the real pages too, and so are a team's page and the card a + * Bot proposes a new Bot on (organization-held-actions.test.tsx). OpenBot's API is the test's routes. * * `window.openbotRouter` lets the test move between pages as a link does, at any window width. */ @@ -76,12 +79,49 @@ const teamsRoute = createRoute({ component: TeamsRoute.options.component as () => ReactNode, }); +// A press refused while Northwind is held (organization-held-actions.test.tsx): adding somebody to a +// team on the team's real page, and creating a Bot from the card a Bot puts in a conversation. +const teamRoute = createRoute({ + getParentRoute: () => appRoute, + path: "/teams/$teamId", + component: function Team() { + const { teamId } = teamRoute.useParams(); + return ; + }, +}); + +// The card as a conversation draws it, with the run waiting on the person's answer. +const proposedBotRoute = createRoute({ + getParentRoute: () => appRoute, + path: "/propose-bot", + component: () => ( + + {}} + /> + + ), +}); + const router = createRouter({ history: createBrowserHistory(), // The app's own error boundary, as router.tsx gives every route. defaultErrorComponent: ReportedErrorComponent, routeTree: rootRoute.addChildren([ - appRoute.addChildren([homeRoute, routinesRoute, memoryRoute, teamsRoute]), + appRoute.addChildren([ + homeRoute, + routinesRoute, + memoryRoute, + teamsRoute, + teamRoute, + proposedBotRoute, + ]), ]), });