diff --git a/api/client-boundary.allow.ts b/api/client-boundary.allow.ts index 7c008bd9f9..830cdb2c2e 100644 --- a/api/client-boundary.allow.ts +++ b/api/client-boundary.allow.ts @@ -297,6 +297,12 @@ export const ALLOWED: Allowed[] = [ rule: "sign-in-protocol", why: "where sign-in sends a person back to finish verifying an app account", }, + { + file: "app/src/lib/auth/resume.ts", + what: "/api/auth/shell/handoff", + rule: "sign-in-protocol", + why: "where sign-in sends a phone app's sign-in sheet on to, a page the server draws (Continue to the OpenBot app): a document navigation in the sheet's browser, not a data request, so not through the generated client", + }, { file: "app/src/lib/plugins/finish-on-return.ts", what: "fetch()", diff --git a/app/index.html b/app/index.html index 8dd7b5784b..5c6e80bdb2 100644 --- a/app/index.html +++ b/app/index.html @@ -39,6 +39,52 @@ const skin = saved === "openmuse" ? "openfuse" : saved; if (skin && skin !== "openbot") document.documentElement.dataset.skin = skin; } catch {} + try { + // Inside the phone app's native shell (lib/native-shell/shell.ts works this out the same + // way, and app/tests/native-shell.test.ts holds the two together): what the shell + // injects, then its user agent, then ?native-shell=ios for testing, kept for the tab, only + // in a development build or on a development host (?native-shell=off forgets it anywhere). + // Marked for the styles, and the page takes the whole web view, which the shell lays out + // between its own bars. A browser's viewport is left as it is. + let remembered = null; + const host = String(window.location.hostname || "").toLowerCase(); + const overridable = + "%DEV%" === "true" || + host === "localhost" || + host === "127.0.0.1" || + host === "[::1]" || + host === "::1" || + host.endsWith(".localhost") || + host.endsWith(".test"); + const param = new URLSearchParams(window.location.search).get("native-shell"); + const asked = param === "off" || overridable ? param : null; + try { + if (asked === "off") window.sessionStorage.removeItem("openbot-native-shell"); + else if (asked === "ios" || asked === "android" || asked === "test") + window.sessionStorage.setItem("openbot-native-shell", "test"); + remembered = window.sessionStorage.getItem("openbot-native-shell"); + } catch {} + const injected = window.__OPENBOT_NATIVE_SHELL__; + const mark = /OpenBotShell-(\w+)/.exec(window.navigator.userAgent); + const platform = + injected && (injected.platform === "ios" || injected.platform === "android") + ? injected.platform + : mark + ? mark[1].toLowerCase() === "android" + ? "android" + : "ios" + : asked === "ios" || asked === "android" || asked === "test" + ? "test" + : overridable && asked !== "off" && remembered === "test" + ? "test" + : null; + if (platform) { + document.documentElement.dataset.nativeShell = platform; + const viewport = document.querySelector('meta[name="viewport"]'); + if (viewport && !viewport.content.includes("viewport-fit")) + viewport.content += ", viewport-fit=cover"; + } + } catch {} try { // Opened by OpenBot Desktop's setup, which faded out to the window's ground and marked the // address once (lib/desktop/from-setup.ts): the first paint fades up from that ground. The diff --git a/app/src/components/app-sidebar/account-label.tsx b/app/src/components/app-sidebar/account-label.tsx index 68091aae2e..98d6e09c2a 100644 --- a/app/src/components/app-sidebar/account-label.tsx +++ b/app/src/components/app-sidebar/account-label.tsx @@ -47,7 +47,7 @@ function initialsOf(name: string): string { .join(""); } -function UserAvatar() { +function UserAvatar({ large = false }: { large?: boolean }) { const { data: currentUser } = useQuery(currentUserQueryOptions()); const { person } = useAccountNames(); // On this computer the email is the stand-in, so its letters are never drawn either. @@ -60,7 +60,10 @@ function UserAvatar() { return ( @@ -135,6 +138,8 @@ export const accountMenuClassName = "w-max min-w-[min(16rem,var(--available-width))] max-w-[min(24rem,var(--available-width))] p-1.5"; /** The spacing of each of the account menu's rows. */ export const accountMenuItemClassName = "gap-2 px-2 py-1.5"; +/** The same rows at a thumb's height, 44px, for the phone app's native shell. */ +export const largeAccountMenuItemClassName = "gap-2 px-2 py-3"; /** * The account, as the strip draws it: the person's avatar at the strip's foot, a button that opens @@ -142,7 +147,26 @@ export const accountMenuItemClassName = "gap-2 px-2 py-1.5"; * OpenBot lists them, read in a tooltip on hover and keyboard focus, never while the menu is open. * The menu itself starts with the account row (`AccountRow`). */ -export function AccountMenu({ children }: { children: ReactNode }) { +export function AccountMenu({ + children, + label, + large = false, + side = "right", +}: { + children: ReactNode; + /** + * The button's name, in place of the person's. The phone app's native shell names it "Account", + * so its tests find it whoever is signed in. + */ + label?: string; + /** + * A thumb's size: the phone app's native shell draws the button 44px square, a whole tap target, + * round a 36px avatar. + */ + large?: boolean; + /** Where the tooltip opens: beside the strip, or below a page's header. */ + side?: "right" | "bottom"; +}) { const { person, organization } = useAccountNames(); const [menuOpen, setMenuOpen] = useState(false); return ( @@ -151,17 +175,22 @@ export function AccountMenu({ children }: { children: ReactNode }) { } > - + {/* Read out as the button's name: whose account, and the organization being worked in. */} {organization ? `${person}, ${organization}` : person} - + {person} {organization ? ( diff --git a/app/src/components/app-sidebar/bots-panel.tsx b/app/src/components/app-sidebar/bots-panel.tsx index a3e089a9d7..425141d9b2 100644 --- a/app/src/components/app-sidebar/bots-panel.tsx +++ b/app/src/components/app-sidebar/bots-panel.tsx @@ -6,6 +6,7 @@ import { import { Link, useNavigate, useParams } from "@tanstack/react-router"; import { createContext, + type ReactNode, useCallback, useContext, useEffect, @@ -184,6 +185,7 @@ function BotConversations({ {conversations.hasNextPage ? ( } + accessory={accessory} className="group-data-[collapsible=icon]:hidden" hidden={hidden} title="Bots" diff --git a/app/src/components/app-sidebar/channel-pagination.tsx b/app/src/components/app-sidebar/channel-pagination.tsx index 3ea0f66317..da853cbe65 100644 --- a/app/src/components/app-sidebar/channel-pagination.tsx +++ b/app/src/components/app-sidebar/channel-pagination.tsx @@ -14,7 +14,8 @@ type Props = { | "fetchNextPage" | "error" >; - scrollRoot: RefObject; + /** The list's scroller. Null for a list in the page's own scroller, watched against the window. */ + scrollRoot: RefObject | null; searching: boolean; }; @@ -37,7 +38,7 @@ export function ChannelPagination({ query, scrollRoot, searching }: Props) { !hasNextPage || isFetching || isFetchNextPageError || - !scrollRoot.current || + (scrollRoot !== null && !scrollRoot.current) || !sentinel.current || typeof IntersectionObserver === "undefined" ) { @@ -49,7 +50,7 @@ export function ChannelPagination({ query, scrollRoot, searching }: Props) { void fetchNextPage({ cancelRefetch: false }); } }, - { root: scrollRoot.current, rootMargin: "160px 0px" }, + { root: scrollRoot?.current ?? null, rootMargin: "160px 0px" }, ); observer.observe(sentinel.current); return () => observer.disconnect(); diff --git a/app/src/components/app-sidebar/channel.tsx b/app/src/components/app-sidebar/channel.tsx index 5f699ddee7..a9d4ac0c87 100644 --- a/app/src/components/app-sidebar/channel.tsx +++ b/app/src/components/app-sidebar/channel.tsx @@ -46,6 +46,7 @@ export const Channel = memo(function Channel({ emphasis, view = "detailed", avatar = true, + layout = "sidebar", "data-slot": slot, }: { channelId: string; @@ -68,6 +69,11 @@ export const Channel = memo(function Channel({ view?: ConversationView; /** False under its Bot in the Bots panel: see `ChannelItemContent`. */ avatar?: boolean; + /** + * `sidebar`: a rounded row in a panel. `page`: a row of a flat list (`PageRows`), as on the + * Conversations page: taller, on the column's edge, with a divider between it and the next. + */ + layout?: "sidebar" | "page"; /** Names the row's link for tests, as under its Bot in the Bots panel. Draws nothing. */ "data-slot"?: string; }) { @@ -112,10 +118,14 @@ export const Channel = memo(function Channel({ type="button" className={cn( // `group/row`: with a mouse, the row's age shows while the pointer or the keyboard is on it. - "group/row flex flex-row px-2.5 gap-2 items-center w-full not-data-[status=active]:hover:bg-foreground/5 rounded-lg [content-visibility:auto]", - view === "compact" - ? "py-1.5 [contain-intrinsic-size:auto_2rem]" - : "py-2 [contain-intrinsic-size:auto_3.25rem]", + "group/row flex flex-row gap-2 items-center w-full not-data-[status=active]:hover:bg-foreground/5 [content-visibility:auto]", + layout === "page" + ? // In `PageRows`, which reaches 8px past the column: 8px back in puts the row on + // the column's edge, under the title, with a rounded hover like its other rows. + "min-h-14 rounded-md px-2 py-3 [contain-intrinsic-size:auto_3.5rem]" + : view === "compact" + ? "px-2.5 rounded-lg py-1.5 [contain-intrinsic-size:auto_2rem]" + : "px-2.5 rounded-lg py-2 [contain-intrinsic-size:auto_3.25rem]", )} activeProps={{ className: "bg-sidebar-accent text-sidebar-accent-foreground", diff --git a/app/src/components/app-sidebar/conversations-panel.tsx b/app/src/components/app-sidebar/conversations-panel.tsx index 2ad590f28b..4d6cdf0760 100644 --- a/app/src/components/app-sidebar/conversations-panel.tsx +++ b/app/src/components/app-sidebar/conversations-panel.tsx @@ -9,6 +9,7 @@ import { useState, } from "react"; import { IconMessagePlus, IconSearch } from "@/components/icons"; +import { PageEmpty, PageRows } from "@/components/layout/page-shell"; import { SectionPanel } from "@/components/layout/section-panel"; import { InputGroup, @@ -44,6 +45,7 @@ import { import { delegatingConversationsQueryOptions } from "@/lib/tasks/queries"; import { Button } from "../ui/button"; import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty"; +import { Separator } from "../ui/separator"; import { Channel } from "./channel"; import { ChannelPagination } from "./channel-pagination"; @@ -95,7 +97,7 @@ export const SEARCH_HINT = "Type at least 2 characters to search history"; * `value`, once it has stopped changing for `delay`. Each search is a request, so one per pause in * typing rather than one per keystroke. */ -function useDebounced(value: string, delay: number): string { +export function useDebounced(value: string, delay: number): string { const [debounced, setDebounced] = useState(value); useEffect(() => { const timer = setTimeout(() => setDebounced(value), delay); @@ -188,18 +190,24 @@ export function isUnread( * moves to the top. Nothing else animates, a roster that reacts to being read is a roster that * moves under the cursor. */ -function ChannelRow({ +export function ChannelRow({ channel, animateOrder, emphasis, view, delegating, + layout = "sidebar", + divided = false, }: { channel: ChannelSummary; animateOrder: boolean; emphasis: MessageListEmphasis; view: ConversationView; delegating: readonly string[]; + /** In the sidebar, or a row of the Conversations page's list (see `Channel`). */ + layout?: "sidebar" | "page"; + /** On the page, a divider above every row but the first, inside the row so it moves with it. */ + divided?: boolean; }) { const shouldReduceMotion = useReducedMotion(); // Whether this row is unread, as a boolean, for the same reason `Channel` computes `isOpen` @@ -220,7 +228,9 @@ function ChannelRow({ layout={animateOrder && !shouldReduceMotion ? "position" : false} transition={{ duration: ENTRANCE_SECONDS, ease: EASE_OUT }} > + {divided ? : null} + {`No conversation has “${term}” in its name or recent messages.`} + + ); return (
@@ -315,21 +335,26 @@ function SearchResults({
); } + const rows = ( + /* Mounted with its first rows, so they appear without the entrance a new channel gets. */ + + {results.data.map((channel, index) => ( + 0} + /> + ))} + + ); return ( <> - {/* Mounted with its first rows, so they appear without the entrance a new channel gets. */} - - {results.data.map((channel) => ( - - ))} - + {page ? {rows} : rows} {results.hasNextPage ? (
{results.isFetchNextPageError ? ( @@ -402,7 +427,20 @@ function RosterGroup({ * a search over the whole history and New conversation at the top. Today's roster, moved beside the * strip and otherwise unchanged. */ -export function ConversationsPanel({ hidden = false }: { hidden?: boolean }) { +export function ConversationsPanel({ + hidden = false, + accessory, + saysLoadFailure = false, +}: { + hidden?: boolean; + /** At the end of the title's row, after New conversation: the phone app's account button. */ + accessory?: ReactNode; + /** + * Whether a first page that could not be read is said, with Try again: on the phone app's Chats + * tab, where this panel is the whole page and an empty one would read as no conversations. + */ + saysLoadFailure?: boolean; +}) { const emphasis = useMessageListEmphasis(); const [view] = useConversationView(); const channels = useInfiniteQuery(channelListQueryOptions()); @@ -468,6 +506,7 @@ export function ConversationsPanel({ hidden = false }: { hidden?: boolean }) { } + accessory={accessory} > @@ -521,6 +560,26 @@ export function ConversationsPanel({ hidden = false }: { hidden?: boolean }) { * and quotes it back (see SearchResults). Told "you don't have channels yet" while * holding a typo, a person reads their conversations as gone. */} + {saysLoadFailure && !channels.data && channels.isError ? ( +
+

+ {loadFailure( + channels.error, + channels.error?.message || + "Couldn't load your conversations.", + )} +

+ +
+ ) : null} {channels.data?.length === 0 ? (
{/* diff --git a/app/src/components/app-sidebar/section-strip.tsx b/app/src/components/app-sidebar/section-strip.tsx index a95153e8df..0c7c503197 100644 --- a/app/src/components/app-sidebar/section-strip.tsx +++ b/app/src/components/app-sidebar/section-strip.tsx @@ -18,7 +18,7 @@ import { DropdownMenuItem, DropdownMenuSeparator, } from "@/components/ui/dropdown-menu"; -import { useSidebar } from "@/components/ui/sidebar"; +import { useOptionalSidebar, useSidebar } from "@/components/ui/sidebar"; import { useSignOutOffered } from "@/lib/auth/sign-out-offered"; import { desktopConnectionQueryOptions } from "@/lib/desktop/queries"; import { desktopShell } from "@/lib/desktop/shell"; @@ -47,6 +47,7 @@ import { AccountRow, accountMenuClassName, accountMenuItemClassName, + largeAccountMenuItemClassName, StripVersion, } from "./account-label"; import { HelpMenu } from "./help-menu"; @@ -181,8 +182,22 @@ function ConnectInsteadItem() { * * OpenBot for Business is offered only outside a shared organization: somebody working in one * already has what it describes. + * + * Also at the top right of the phone app's tab pages, where there is no sidebar + * (`layout/native-shell-account.tsx`): opening below the avatar there, and named "Account". */ -function StripAccount() { +export function StripAccount({ + label, + large = false, + side = "right", +}: { + /** The button's name, in place of the person's (see `AccountMenu`). */ + label?: string; + /** The button and the menu's rows at a thumb's size, for the phone app (see `AccountMenu`). */ + large?: boolean; + /** Beside the strip, or below a page's header. */ + side?: "right" | "bottom"; +} = {}) { const navigation = useNavigationItems(); const signOut = useSignOut(); const signOutOffered = useSignOutOffered(); @@ -190,7 +205,11 @@ function StripAccount() { const organizationChoices = useOrganizationChoices(); const invitationsWaiting = useWaitingInvitationCount(); const switchOrganization = useSwitchOrganization(); - const { setOpenMobile } = useSidebar(); + // No sidebar in the native shell, so no sheet to close. + const setOpenMobile = useOptionalSidebar()?.setOpenMobile ?? (() => {}); + const itemClassName = large + ? largeAccountMenuItemClassName + : accountMenuItemClassName; const inSharedOrganization = organizationChoices?.organizations.some( (organization) => @@ -198,11 +217,11 @@ function StripAccount() { !organization.personal, ) ?? false; return ( - + @@ -211,7 +230,7 @@ function StripAccount() { { // A narrow window's sheet would wait behind the dialog. setOpenMobile(false); @@ -225,7 +244,7 @@ function StripAccount() { .filter((item) => item.kind !== "dialog" || !inSharedOrganization) .map((item) => ( {item.label} ))} - + {signOutOffered ? null : } {signOutOffered ? ( <> diff --git a/app/src/components/app-sidebar/troubleshooting-logs-item.tsx b/app/src/components/app-sidebar/troubleshooting-logs-item.tsx index 8f47af88a7..7b37f64264 100644 --- a/app/src/components/app-sidebar/troubleshooting-logs-item.tsx +++ b/app/src/components/app-sidebar/troubleshooting-logs-item.tsx @@ -4,6 +4,7 @@ import { useState } from "react"; import { DropdownMenuItem } from "@/components/ui/dropdown-menu"; import { toast } from "@/components/ui/toast"; import { currentUserQueryOptions } from "@/lib/auth/queries"; +import { nativeShell } from "@/lib/native-shell/shell"; import { currentOrganizationId } from "@/lib/organizations/current"; import { saveTroubleshootingLogs } from "@/lib/troubleshooting/logs"; @@ -13,6 +14,8 @@ const SAVED_TOAST = "troubleshooting-logs-saved"; /** * Get troubleshooting logs, in the account menu: one file to send in when something went wrong * (`lib/troubleshooting/logs.ts`), and a toast that says where it was saved and what was taken out. + * Not in the phone app's native shell, whose web view doesn't take a download yet: there the press + * would do nothing, or replace the page with the file. */ export function TroubleshootingLogsMenuItem({ className, @@ -21,6 +24,7 @@ export function TroubleshootingLogsMenuItem({ }) { const { data: person } = useQuery(currentUserQueryOptions()); const [saving, setSaving] = useState(false); + if (nativeShell()) return null; return ( { + tellShell({ type: "signed-out" }); + }, []); + return ( +
+ +
+ ); +} diff --git a/app/src/components/browser/learning-next.tsx b/app/src/components/browser/learning-next.tsx index 643649c100..45af0db2dc 100644 --- a/app/src/components/browser/learning-next.tsx +++ b/app/src/components/browser/learning-next.tsx @@ -22,6 +22,7 @@ import { type RecordingSkill, recordingSkillsQueryOptions, } from "@/lib/learning/queries"; +import { notificationPermission } from "@/lib/notifications/permission"; import { cn } from "@/lib/utils"; import { queryClient } from "@/query-client"; import type { Stopped } from "./recording"; @@ -203,16 +204,12 @@ export function useLearningNext(stopped: Stopped) { }; } -/** Whether this browser lets OpenBot interrupt. Some browsers throw on the mere question. */ +/** + * Whether this browser lets OpenBot interrupt: the browser's answer, read safely, and never inside + * the phone app's native shell, where the phone app notifies (`notificationPermission`). + */ function notificationsAllowed() { - try { - return ( - typeof Notification !== "undefined" && - Notification.permission === "granted" - ); - } catch { - return false; - } + return notificationPermission() === "granted"; } /** diff --git a/app/src/components/channels/channel-chat.tsx b/app/src/components/channels/channel-chat.tsx index 085e4e8314..7912c89980 100644 --- a/app/src/components/channels/channel-chat.tsx +++ b/app/src/components/channels/channel-chat.tsx @@ -188,6 +188,7 @@ import { useClearWhenHoldEnds } from "@/lib/held-ends"; import { type Failure, failureSaid, loadFailure } from "@/lib/load-failure"; import { modelCatalogueQueryOptions } from "@/lib/models/queries"; import { useConversationModel } from "@/lib/models/run-model"; +import { nativeShell } from "@/lib/native-shell/shell"; import { stopIfNeedsCard } from "@/lib/plan/queries"; import { useSkillCommands } from "@/lib/plugins/skill-commands"; import { @@ -3368,8 +3369,9 @@ export function ChannelChat({ taskRunning={agent.isRunning || runsInFlight > 0} /> fileInputRef.current?.click()} diff --git a/app/src/components/channels/group-chat.tsx b/app/src/components/channels/group-chat.tsx index 53ca37f763..99ce9a85cc 100644 --- a/app/src/components/channels/group-chat.tsx +++ b/app/src/components/channels/group-chat.tsx @@ -34,6 +34,7 @@ import { markdownPlugins, replyRemarkPlugins, } from "@/lib/markdown"; +import { nativeShell } from "@/lib/native-shell/shell"; import { newId } from "@/lib/new-id"; import { DELETED_USER, isDeletedUser } from "@/lib/people/deleted-user"; import { cn } from "@/lib/utils"; @@ -269,7 +270,8 @@ export function GroupChat({ channelId }: { channelId: string }) { compact disabled={bots.length === 0} pending={send.isPending || answer.isPending || working} - autoFocus + // Not in the phone app, where the keyboard would come up over the conversation by itself. + autoFocus={nativeShell() === null} draftKey={`conversation:${channelId}`} // While it waits, what is sent next answers it (below), and the box says so. {...(question ? ANSWER_PROMPT : {})} diff --git a/app/src/components/layout/native-shell-account.tsx b/app/src/components/layout/native-shell-account.tsx new file mode 100644 index 0000000000..48aa1f5ea6 --- /dev/null +++ b/app/src/components/layout/native-shell-account.tsx @@ -0,0 +1,16 @@ +import { StripAccount } from "@/components/app-sidebar/section-strip"; +import { nativeShell } from "@/lib/native-shell/shell"; + +/** The account button's name in the native shell, the same whoever is signed in. */ +export const SHELL_ACCOUNT_LABEL = "Account"; + +/** + * The sidebar's account menu (Settings, Admin, Sign out and the rest), at the top right of the + * phone app's tab pages: Home, Conversations and Bots. Only inside the native shell, which has no + * sidebar to reach them by (`lib/native-shell`). The same menu, opening below the avatar, with the + * button and the rows at a thumb's size. + */ +export function ShellAccountMenu() { + if (!nativeShell()) return null; + return ; +} diff --git a/app/src/components/layout/native-shell-back.tsx b/app/src/components/layout/native-shell-back.tsx new file mode 100644 index 0000000000..80e9354c54 --- /dev/null +++ b/app/src/components/layout/native-shell-back.tsx @@ -0,0 +1,32 @@ +import { useNavigate } from "@tanstack/react-router"; +import { IconChevronLeft } from "@/components/icons"; +import { Button } from "@/components/ui/button"; +import { nativeShell } from "@/lib/native-shell/shell"; +import { + currentTabRoot, + goBackInShell, +} from "@/lib/native-shell/use-tab-navigation"; + +/** + * Back, at the start of a conversation's header, inside the phone app's native shell only: the + * current tab's stack popped once (`lib/native-shell/use-tab-navigation.ts`), so it returns to where + * the conversation was opened from, the Chats list, a Bot's group or Home. Where the tab has nowhere + * to go back to, its root. 44px, a thumb's size; the shell's tab bar stays the way between tabs. + */ +export function ShellBackButton() { + const navigate = useNavigate(); + if (!nativeShell()) return null; + return ( + + ); +} diff --git a/app/src/components/layout/native-shell-frame.tsx b/app/src/components/layout/native-shell-frame.tsx new file mode 100644 index 0000000000..25b0ba16a2 --- /dev/null +++ b/app/src/components/layout/native-shell-frame.tsx @@ -0,0 +1,59 @@ +import type { ReactNode } from "react"; +import { BotsNavBadge } from "@/components/bot-profile/attention"; +import { ConnectionBanner } from "@/components/layout/connection-banner"; +import { PlanBanner } from "@/components/layout/plan-banner"; +import { SelfHostBanner } from "@/components/layout/self-host-banner"; +import { UpdateBanner } from "@/components/layout/update-banner"; +import { MovedAppsBanner } from "@/components/moves/moved-apps-notice"; +import { MovedElsewhereBanner } from "@/components/moves/moved-elsewhere-banner"; +import { LeftOrganizationBanner } from "@/components/organizations/left-organization-banner"; +import { SidebarInset } from "@/components/ui/sidebar"; +import { useChannelEvents } from "@/lib/channels/use-channel-events"; +import { useShellKeyboard } from "@/lib/native-shell/keyboard"; + +/** + * The page and nothing around it, for the phone app's native shell (`lib/native-shell`), which + * draws the status bar and the tab bar outside the web view. Exactly the web view's height, never + * scrolls itself: panes scroll inside, as in every other shell. No sidebar provider, so no sidebar, + * no drawer and no "Show sidebar" anywhere (`useSidebarToggleVisible`), and no safe-area padding: + * the shell lays the web view out between its bars. + * + * The same panel as the app's (`SidebarInset`, which needs no sidebar), so a screen that sizes + * itself against it (`route-error.tsx`) does here too. + */ +export function NativeShellPanel({ children }: { children: ReactNode }) { + return ( +
+ + {children} + +
+ ); +} + +/** + * The app's frame in the native shell: the banners the sidebar frame shows, and what the sidebar + * did beyond drawing (`app-sidebar.tsx`): the app's one socket, which keeps the conversation list + * live, and the Bots badge, which sends the browser notification when a Bot starts needing the + * person, mounted unseen as OpenDuet's frame does. And the keyboard, put away when the person is + * plainly done typing (`lib/native-shell/keyboard.ts`). + */ +export function NativeShellFrame({ children }: { children: ReactNode }) { + useChannelEvents(); + useShellKeyboard(); + return ( + + + + + + + + + + {children} + + ); +} diff --git a/app/src/components/layout/native-shell-panels.tsx b/app/src/components/layout/native-shell-panels.tsx new file mode 100644 index 0000000000..517dd92e2a --- /dev/null +++ b/app/src/components/layout/native-shell-panels.tsx @@ -0,0 +1,57 @@ +import type { ReactNode } from "react"; +import { NewBotSheet } from "@/components/agents/new-bot-sheet"; +import { BotsPanel } from "@/components/app-sidebar/bots-panel"; +import { ConversationsPanel } from "@/components/app-sidebar/conversations-panel"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; +import { SidebarProvider } from "@/components/ui/sidebar"; + +/** + * A panel of the sidebar as a whole page, for the phone app's native shell, whose tabs are the + * sidebar's sections: the same component OpenBot Desktop draws beside its strip, so the two never + * drift apart. The sidebar's panels are drawn with its primitives, which read the sidebar's state, so + * they get a provider here, as wide and as tall as the page. The rows are a thumb's height in the + * shell (styles.css, `[data-slot="section-panel"]`). + */ +function ShellPanel({ children }: { children: ReactNode }) { + return ( + + {children} + + ); +} + +/** + * The Chats tab: the sidebar's Conversations panel, with the account beside New conversation, the + * one way to Settings and Sign out in the shell. + */ +export function ShellChats() { + return ( + + } saysLoadFailure /> + + ); +} + +/** + * The Bots tab: the sidebar's Bots panel, with the account beside New Bot, and New Bot's sheet, + * which the panel's + opens at `/bots?new=true` as it does on Desktop. + */ +export function ShellBots({ + creating, + onClose, + onCreated, +}: { + creating: boolean; + onClose: () => void; + onCreated: (agentId: string) => void; +}) { + return ( + + } /> + + + ); +} diff --git a/app/src/components/layout/page-parts.tsx b/app/src/components/layout/page-parts.tsx index 82203b31d7..543fb22e8b 100644 --- a/app/src/components/layout/page-parts.tsx +++ b/app/src/components/layout/page-parts.tsx @@ -1,4 +1,5 @@ import type * as React from "react"; +import { nativeShell } from "@/lib/native-shell/shell"; import { cn } from "@/lib/utils"; import { Collapsible, @@ -78,8 +79,9 @@ export function PageColumn({ */ "mx-auto flex w-full flex-col px-4 pb-16", "[&>header+*]:mt-8 [&>header+nav]:mt-6 [&>header+nav+*]:mt-8", - // Without a bar above it the heading keeps the full original space. - bar ? "pt-8" : "pt-12", + // Without a bar above it the heading keeps the full original space. Inside the phone + // app's native shell, whose status bar is already above the page, less of it. + nativeShell() ? (bar ? "pt-4" : "pt-6") : bar ? "pt-8" : "pt-12", "max-w-3xl", className, )} diff --git a/app/src/components/layout/page-shell.tsx b/app/src/components/layout/page-shell.tsx index 434dd0c74e..207452a78f 100644 --- a/app/src/components/layout/page-shell.tsx +++ b/app/src/components/layout/page-shell.tsx @@ -1,6 +1,13 @@ -import { Link, type LinkProps } from "@tanstack/react-router"; +import { Link, type LinkProps, useRouter } from "@tanstack/react-router"; import type * as React from "react"; +import { createContext, useContext } from "react"; import { IconChevronLeft, IconPlus } from "@/components/icons"; +import { nativeShell } from "@/lib/native-shell/shell"; +import { rootTabOf } from "@/lib/native-shell/tab-stacks"; +import { + currentTabRoot, + goBackInShell, +} from "@/lib/native-shell/use-tab-navigation"; import { cn } from "@/lib/utils"; import { Button } from "../ui/button"; import { @@ -27,6 +34,22 @@ import { SidebarToggle, useSidebarToggleVisible } from "./sidebar-toggle"; * whichever it happened to see first. */ +/** A screen's Back link: where it goes and what it says. */ +export type PageBack = { + linkProps: LinkProps; + label: string; + /** Drawn, but not a link: leaving now would lose what the page is waiting on. */ + disabled?: boolean; +}; + +const DefaultPageBack = createContext(null); + +/** + * The Back link a screen gets when it names none of its own. Only where there is no sidebar to go + * back by: Settings and Admin inside the phone app's native shell lead back to their first page. + */ +export const DefaultPageBackProvider = DefaultPageBack.Provider; + export function PageShell({ action, children, @@ -50,15 +73,35 @@ export function PageShell({ learnMore?: React.ReactNode; title: string; width?: ShellWidth; - backButton?: { - linkProps: LinkProps; - label: string; - /** Drawn, but not a link: leaving now would lose what the page is waiting on. */ - disabled?: boolean; - }; + backButton?: PageBack; }) { // `wide` is the prose column made wider: its class comes after the column's own, and wins. const className = width === "wide" ? cn(WIDE_COLUMN, given) : given; + const fallbackBack = useContext(DefaultPageBack); + /* + * In the phone app's native shell every page under a tab's root has Back, even one that names + * none (Settings, Admin, opened from the Account menu): its tab's stack popped once, where the + * link's own address is only the fallback (`lib/native-shell/use-tab-navigation.ts`). + */ + const shell = nativeShell() !== null; + /* + * Read only in the shell, and from a router only where there is one: a screen drawn without a + * router (a test of a settings page) draws exactly as before, outside the shell. + */ + const router = useRouter({ warn: false }); + const atTabRoot = + shell && + rootTabOf(router?.state.location.pathname ?? window.location.pathname) !== + null; + const back: PageBack | undefined = + backButton ?? + fallbackBack ?? + (shell && !atTabRoot + ? { + label: "Back", + linkProps: { to: (currentTabRoot() ?? "/") as LinkProps["to"] }, + } + : undefined); /* * The bar carries the toggle and the Back link, and is drawn when it has at least one of them. * The screens with a Back link already drew exactly this bar, so for them nothing changes; what @@ -75,7 +118,7 @@ export function PageShell({ * provider at all, so there is nothing for a toggle to act on there. */ const showToggle = useSidebarToggleVisible(); - const bar = showToggle || !!backButton; + const bar = showToggle || !!back; const header = ( {backButton?.label}; + const backLabel = {back?.label}; const barRow = bar ? (
{showToggle ? : null} - {!backButton ? null : backButton.disabled ? ( + {!back ? null : back.disabled ? ( ) : ( - + {/* Not in the phone app, whose web view doesn't take a download yet. */} + {nativeShell() ? null : ( + + )}
{exportError ? ( diff --git a/app/src/components/settings/devices.tsx b/app/src/components/settings/devices.tsx index ae603da9ea..bb6f842faa 100644 --- a/app/src/components/settings/devices.tsx +++ b/app/src/components/settings/devices.tsx @@ -23,6 +23,7 @@ import { removePushDeviceMutationOptions, } from "@/lib/delivery"; import { failureSaid, isHeld } from "@/lib/load-failure"; +import { nativeShell } from "@/lib/native-shell/shell"; import { queryClient } from "@/query-client"; /** @@ -91,7 +92,10 @@ export function deliveryLine( .join(" · "); } -/** The phones that receive push notifications for every one of the person's Bots. */ +/** + * The phones that receive push notifications for every one of the person's Bots. Inside the phone + * app, which is one of them, no sentence telling the person to go and sign in to it. + */ export function NativeDevices() { const devices = useQuery(devicesQueryOptions()); const remove = useMutation(removePushDeviceMutationOptions(queryClient)); @@ -99,7 +103,11 @@ export function NativeDevices() { const error = (saidAbove ? null : devices.error) ?? remove.error; return ( {error ? ( diff --git a/app/src/components/settings/settings-pages.tsx b/app/src/components/settings/settings-pages.tsx new file mode 100644 index 0000000000..a5db81b7de --- /dev/null +++ b/app/src/components/settings/settings-pages.tsx @@ -0,0 +1,60 @@ +import { Link } from "@tanstack/react-router"; +import { Fragment } from "react"; +import { IconChevronRight } from "@/components/icons"; +import { PageRows, PageSection } from "@/components/layout/page-shell"; +import { + Item, + ItemActions, + ItemContent, + ItemMedia, + ItemTitle, +} from "@/components/ui/item"; +import { Separator } from "@/components/ui/separator"; +import { nativeShell } from "@/lib/native-shell/shell"; +import { useSettingsItems } from "./settings-sidebar"; + +/** + * Settings' other pages, as rows on General, inside the phone app's native shell only: there is no + * sidebar there to list them (`routes/_authed/settings/route.tsx`). The sidebar's entries, in its + * order, General left out since this is it. Each page leads back here. + */ +export function SettingsPageRows() { + if (!nativeShell()) return null; + return ; +} + +function SettingsPageRowsList() { + const { items, toFix } = useSettingsItems(); + const pages = items.filter((item) => item.linkOptions.to !== "/settings"); + if (pages.length === 0) return null; + return ( + + + {pages.map((page, index) => ( + + } + size="sm" + > + + + + + {page.title} + + + {page.setup && toFix > 0 ? ( + + {toFix} {toFix === 1 ? "needs" : "need"} setup + + ) : null} + + + + {index !== pages.length - 1 ? : null} + + ))} + + + ); +} diff --git a/app/src/components/settings/settings-sidebar.tsx b/app/src/components/settings/settings-sidebar.tsx index f3c6c9ce7a..4926d67dc8 100644 --- a/app/src/components/settings/settings-sidebar.tsx +++ b/app/src/components/settings/settings-sidebar.tsx @@ -187,9 +187,15 @@ export function settingsSidebarItems( ); } -export function SettingsSidebar({ - ...props -}: React.ComponentProps) { +/** + * The entries this person sees, and how many setup rows wait on them (counted beside Setup). The + * sidebar draws them, and General lists them inside the phone app's native shell, which has no + * sidebar (`settings-pages.tsx`). + */ +export function useSettingsItems(): { + items: SettingsSidebarItem[]; + toFix: number; +} { const user = useQuery(currentUserQueryOptions()).data; const capabilities = useQuery(deploymentCapabilitiesQueryOptions()).data; const canSetUp = mayOpenSetup(user, capabilities); @@ -214,6 +220,13 @@ export function SettingsSidebar({ (option) => (!option.setup || canSetUp) && (!option.organization || hasOrganization), ); + return { items, toFix }; +} + +export function SettingsSidebar({ + ...props +}: React.ComponentProps) { + const { items, toFix } = useSettingsItems(); return ( {/* Matched to the app sidebar's header, as Admin's is. See admin-sidebar.tsx. */} diff --git a/app/src/lib/auth/resume.ts b/app/src/lib/auth/resume.ts index 4a496c3eef..ba0f0b8745 100644 --- a/app/src/lib/auth/resume.ts +++ b/app/src/lib/auth/resume.ts @@ -112,3 +112,58 @@ export function resumeUrlFor( // Home without the query it was too long to keep is just the origin, as any other way home is. return fitted === `${origin}/` ? origin : fitted; } + +/** + * The phone app's sign-in hand-off, on this origin (the server's hand-off contract, "Returning + * through /sign"). On a self-hosted OpenBot a signed-out sign-in sheet lands on `/sign` carrying + * `shell_challenge`, `shell_platform` and `shell_callback`; once signed in, the sheet goes on to the + * hand-off, which shows "Continue to the OpenBot app", rather than into the web app inside the sheet. + */ +export const SHELL_HANDOFF_PATH = "/api/auth/shell/handoff"; + +/** What `/sign` was handed for the sheet, as its search names it. */ +export type ShellReturnSearch = { + shell_challenge?: string; + shell_platform?: string; + shell_callback?: string; +}; + +/** A PKCE S256 challenge: 43 characters of base64url, nothing else. */ +const SHELL_CHALLENGE = /^[A-Za-z0-9_-]{43}$/; + +/** + * The hand-off's path, built here from the 3 values once each checks out: the challenge exactly 43 + * base64url characters, the platform absent, `ios` or `android`, the callback absent or `https`. + * Anything else and all 3 are ignored (null). Values, never an address: as with `flow_id`, nothing + * taken from the query is ever a place to go. + */ +export function shellHandoffPathFor(search: ShellReturnSearch): string | null { + const challenge = search.shell_challenge; + const platform = search.shell_platform; + const callback = search.shell_callback; + if (typeof challenge !== "string" || !SHELL_CHALLENGE.test(challenge)) + return null; + if (platform !== undefined && platform !== "ios" && platform !== "android") + return null; + if (callback !== undefined && callback !== "https") return null; + return [ + `${SHELL_HANDOFF_PATH}?challenge=${challenge}`, + platform ? `&platform=${platform}` : "", + callback ? `&callback=${callback}` : "", + ].join(""); +} + +/** + * Where sign-in on `/sign` sends the browser back to: the phone app's hand-off when the sheet's + * values check out (they win over `flow_id` and `next`: the sheet is the app's), else as + * `resumeUrlFor` says. + */ +export function signInReturnUrlFor( + origin: string, + search: ShellReturnSearch & { flow_id?: string; next?: string }, +): string { + const handoff = shellHandoffPathFor(search); + return handoff === null + ? resumeUrlFor(origin, search.flow_id, search.next) + : `${origin}${handoff}`; +} diff --git a/app/src/lib/desktop/open-requests.ts b/app/src/lib/desktop/open-requests.ts index c3247cf11b..c680b1fe17 100644 --- a/app/src/lib/desktop/open-requests.ts +++ b/app/src/lib/desktop/open-requests.ts @@ -1,5 +1,7 @@ import { useRouter } from "@tanstack/react-router"; import { useEffect } from "react"; +import { nativeShell } from "@/lib/native-shell/shell"; +import { openFromShell } from "@/lib/native-shell/use-tab-navigation"; /** * The event OpenBot Desktop dispatches on the window when a click on a notification asks for one of @@ -19,6 +21,11 @@ export function isOwnPath(path: unknown): path is string { * middle of (a draft, an open dialog, a conversation's live stream) is kept, where loading the page * again lost it. The event is cancelled to tell the shell it was handled; an OpenBot page from before * this leaves it, and the shell loads the page instead. + * + * The phone app's native shell asks the same way when one of its tabs is tapped, and there the tabs' + * own stacks decide what it means (`lib/native-shell/use-tab-navigation.ts`). Elsewhere a page that + * is already open is handled and left as it is, as the sidebar's link to it does: Home keeps what is + * in its box, a conversation its scroll. */ export function useDesktopOpenRequests() { const router = useRouter(); @@ -27,6 +34,10 @@ export function useDesktopOpenRequests() { const path = (event as CustomEvent<{ path?: unknown }>).detail?.path; if (!isOwnPath(path)) return; event.preventDefault(); + // In the phone app's native shell a tab's root is a tab tap, kept by the tabs' own stacks. + if (nativeShell() && openFromShell(path)) return; + const here = router.history.location; + if (path === here.pathname + here.search + here.hash) return; router.history.push(path); }; window.addEventListener(OPEN_REQUEST, open); diff --git a/app/src/lib/markdown-table.tsx b/app/src/lib/markdown-table.tsx index 01a66a4abe..53a10ee7d6 100644 --- a/app/src/lib/markdown-table.tsx +++ b/app/src/lib/markdown-table.tsx @@ -16,6 +16,7 @@ import { tableDataToTSV, defaultTranslations as words, } from "streamdown"; +import { nativeShell } from "@/lib/native-shell/shell"; import { cn } from "@/lib/utils"; /** @@ -605,7 +606,9 @@ export function MarkdownTable({ const height = maxHeight(tableMaxHeight); const scroller = useFollowNewRows(isAnimating, Boolean(height), children); const showCopy = shows(controls, "copy"); - const showDownload = shows(controls, "download"); + // Not in the phone app: the file is built in the page, and the app's web view cannot save one + // yet. Copy stays. A code block's Download goes the same way (`styles.css`). + const showDownload = shows(controls, "download") && nativeShell() === null; const showFullscreen = shows(controls, "fullscreen"); return ( diff --git a/app/src/lib/native-shell/bridge.ts b/app/src/lib/native-shell/bridge.ts new file mode 100644 index 0000000000..634ad6127d --- /dev/null +++ b/app/src/lib/native-shell/bridge.ts @@ -0,0 +1,109 @@ +/** + * What the page tells the native shell (`shell.ts`), as plain JSON objects: + * + * - `{ type: "ready" }` once, when the router has mounted. + * - `{ type: "route", path, tab, signedIn, canGoBack }` on every change of page: the pathname only, + * never the query or the fragment; the tab whose stack the page is in (`use-tab-navigation.ts`; + * by the address, `tabForPath`, where the stacks have not started); and whether Back has somewhere + * to go inside that tab. Native sends `openbot:back` for its Back when it does. + * It also carries `depth`, how many locations the current tab's stack holds (1 at its root, so + * `canGoBack` is `depth > 1`), and `scrollRestored: true`: a list returned to by Back has its + * `route` sent once its scroll position is back. + * - `{ type: "will-navigate", tab, direction, depth }` before the page changes what is on screen, + * for a navigation inside a tab that the page started itself (a row, a link, its own Back) and + * that changes the path. `direction` is "push", "back" or "replace"; `depth` is where it leads. + * Not for a tab switch, a tap on the current tab, or Back native asked for (`openbot:back`). On + * iOS the page then waits for `openbot:navigate-ok` on `window`, at most 120 ms, before it shows + * the new page, so the app can take its snapshot for the swipe back. + * - `{ type: "signed-out" }` when the page reaches the signed-out state, where the shell shows its + * own sign-in screen. + * + * On iOS through `window.webkit.messageHandlers.openbotShell`, on Android through + * `window.OpenBotShellAndroid.postMessage(json)`. Nothing happens where neither is there. + * + * The shell asks for a page with the `openbot:open` event OpenBot Desktop already sends + * (`lib/desktop/open-requests.ts`). + */ + +/** The shell's tabs. */ +export type NativeTab = "conversations" | "home" | "bots"; + +export type ShellMessage = + | { type: "ready" } + | { + type: "route"; + path: string; + tab: NativeTab | null; + signedIn: boolean; + canGoBack: boolean; + /** How many locations the current tab's stack holds: 1 at its root. */ + depth: number; + /** Always true: a page whose list position is being put back is reported once it is. */ + scrollRestored: true; + } + | { + /** Sent before the page changes what is on screen, for a navigation the page started. */ + type: "will-navigate"; + tab: NativeTab; + direction: "push" | "back" | "replace"; + /** The depth the navigation leads to. */ + depth: number; + } + | { type: "signed-out" }; + +type ShellWindow = { + webkit?: { + messageHandlers?: { + openbotShell?: { postMessage(message: unknown): void }; + }; + }; + OpenBotShellAndroid?: { postMessage(message: string): void }; +}; + +/** Whether a shell is listening for messages: its iOS handler or its Android object is there. */ +export function shellListens( + target: ShellWindow = window as ShellWindow, +): boolean { + try { + return Boolean( + target.webkit?.messageHandlers?.openbotShell ?? + target.OpenBotShellAndroid, + ); + } catch { + return false; + } +} + +/** Sends `message` to the shell. Never throws: the shell not listening is no fault of the page's. */ +export function postToShell( + message: ShellMessage, + target: ShellWindow = window as ShellWindow, +): void { + try { + const ios = target.webkit?.messageHandlers?.openbotShell; + if (ios) { + ios.postMessage(message); + return; + } + target.OpenBotShellAndroid?.postMessage(JSON.stringify(message)); + } catch { + // A shell that went away mid-message has nothing to hear. + } +} + +/** + * Which of the shell's tabs a page belongs to, or null for a page none of them owns (Settings, a + * routine, Admin): Home and `/bot` are Home's; the conversations list and every conversation, + * started or starting, are Conversations'; the Bots list and every Bot's pages are Bots'. + */ +export function tabForPath(pathname: string): NativeTab | null { + const path = + pathname.length > 1 && pathname.endsWith("/") + ? pathname.replace(/\/+$/, "") || "/" + : pathname; + if (path === "/" || path === "/bot") return "home"; + if (path === "/conversations" || /^\/(channel|group|start)\/./.test(path)) + return "conversations"; + if (path === "/bots" || path.startsWith("/bots/")) return "bots"; + return null; +} diff --git a/app/src/lib/native-shell/keyboard.ts b/app/src/lib/native-shell/keyboard.ts new file mode 100644 index 0000000000..7a0df91c70 --- /dev/null +++ b/app/src/lib/native-shell/keyboard.ts @@ -0,0 +1,117 @@ +import { useRouter } from "@tanstack/react-router"; +import { useEffect } from "react"; + +/** + * The phone's keyboard, inside the phone app's native shell (`shell.ts`). The shell ends the web + * view at the keyboard's top edge and dismisses it on a drag down; the page puts it away when the + * person is plainly done typing: + * + * - moving to another page, so the keyboard never stays up over a page that has no field; + * - a tap on a part of the page that does nothing, as a native app does. On iOS a web page keeps + * the keyboard up there: WebKit sends no mousedown for a tap on something that is not clickable, + * so the field never loses focus. A drag that scrolls is not a tap (the browser cancels the + * pointer), so reading back up the conversation keeps the keyboard. + * + * Opening a menu, a select or a sheet needs nothing here: each moves focus into itself as it opens. + * Sending a message puts it away too, but that is the message box's own doing on every touch + * keyboard, in the app or not (`components/channels/composer/composer.tsx`). + */ + +/** Where a phone shows its keyboard: a text field, a text area or an editable box. */ +export function isTextField(element: Element | null): element is HTMLElement { + if (!(element instanceof HTMLElement)) return false; + if (element.isContentEditable || element instanceof HTMLTextAreaElement) + return true; + return ( + element instanceof HTMLInputElement && + ![ + "button", + "checkbox", + "color", + "file", + "radio", + "range", + "reset", + "submit", + ].includes(element.type) + ); +} + +/** Puts the keyboard away: takes the focus off the text field that has it, if one does. */ +export function dropKeyboard(): void { + const focused = document.activeElement; + if (isTextField(focused)) focused.blur(); +} + +/** + * What a tap may land on and keep the keyboard: anything that does something, any open menu or + * popup, and the parts of a field drawn around it (the message box's surface and buttons, a search + * field's icon, the chips beside the To field). + */ +export const KEEPS_KEYBOARD = [ + "a[href]", + "button", + "input", + "textarea", + "select", + "label", + "summary", + "[contenteditable]", + '[role="button"]', + '[role="link"]', + '[role="checkbox"]', + '[role="switch"]', + '[role="tab"]', + '[role="option"]', + '[role="menuitem"]', + '[role="slider"]', + "[data-base-ui-portal]", + '[data-slot="composer"]', + '[data-slot="input-group"]', + '[data-slot="combobox-chips"]', +].join(", "); + +/** How far a finger may move and how long it may rest and still be a tap. */ +const TAP_SLOP_PX = 10; +const TAP_MS = 500; + +/** Mounted once, by the shell's frame. */ +export function useShellKeyboard(): void { + const router = useRouter(); + useEffect(() => { + // Before the next page renders, so a field it focuses as it opens keeps that focus. + const off = router.subscribe("onBeforeNavigate", (event) => { + if (event.pathChanged) dropKeyboard(); + }); + let down: { x: number; y: number; at: number } | null = null; + const onDown = (event: PointerEvent) => { + down = { x: event.clientX, y: event.clientY, at: event.timeStamp }; + }; + const onUp = (event: PointerEvent) => { + const start = down; + down = null; + if ( + !start || + Math.abs(event.clientX - start.x) > TAP_SLOP_PX || + Math.abs(event.clientY - start.y) > TAP_SLOP_PX || + event.timeStamp - start.at > TAP_MS + ) + return; + const target = event.target; + if (target instanceof Element && target.closest(KEEPS_KEYBOARD)) return; + dropKeyboard(); + }; + const onCancel = () => { + down = null; + }; + document.addEventListener("pointerdown", onDown, true); + document.addEventListener("pointerup", onUp, true); + document.addEventListener("pointercancel", onCancel, true); + return () => { + off(); + document.removeEventListener("pointerdown", onDown, true); + document.removeEventListener("pointerup", onUp, true); + document.removeEventListener("pointercancel", onCancel, true); + }; + }, [router]); +} diff --git a/app/src/lib/native-shell/route-reports.ts b/app/src/lib/native-shell/route-reports.ts new file mode 100644 index 0000000000..421529e056 --- /dev/null +++ b/app/src/lib/native-shell/route-reports.ts @@ -0,0 +1,187 @@ +import { useRouterState } from "@tanstack/react-router"; +import { useEffect } from "react"; +import { postToShell, type ShellMessage, tabForPath } from "./bridge"; +import { nativeShell } from "./shell"; +import { shellTabState, whenScrollRestored } from "./use-tab-navigation"; + +/** + * WHEN THE SHELL HEARS `ready`: once per page load, when the first page has drawn something a person + * can read. The shell keeps its own loading screen over the web view until then, so `ready` sent at + * boot showed an empty page under the tabs for as long as a slow server took to answer. + * + * The rule, in this order: + * + * 1. The router has settled on the first address: it is idle with a resolved location, so no route + * is still loading and no pending component (the app frame's skeleton) stands in for the page. + * 2. The page then shows readable text (`hasReadableText`): not a skeleton, not text kept for a + * screen reader alone, not something hidden. A page whose own data is still loading draws none, + * so it waits; an error screen has its words, so it counts. The signed-out page inside the shell + * (`components/auth/native-signed-out.tsx`) draws only the orb, by design, and counts as drawn. + * Watched with a MutationObserver from the moment the router settles, so no polling. + * 3. Whatever happens, `ready` goes `READY_FALLBACK_MS` after the reports start, so a page whose + * drawing this cannot see still hands the screen over. + * + * THE ORDER THE SHELL CAN RELY ON: `ready` first, exactly once. Until then whatever else the page + * would say (`route`, `signed-out`) is held and then sent, in the order it was said, right after + * `ready`. So the first `route` always follows `ready`, and every `route` after it follows the + * navigation it reports. + */ +export const READY_FALLBACK_MS = 20_000; + +/** `ready` goes once per page load, not once per mount (StrictMode mounts twice in development). */ +let readySent = false; +/** Whether the reports are running, so that what the page says waits for `ready`. */ +let holding = false; +/** What the page said before `ready`, in order. */ +let held: ShellMessage[] = []; + +/** How long the fallback waits: `READY_FALLBACK_MS`, shorter only in tests. */ +let fallbackMs = READY_FALLBACK_MS; + +/** For tests: let the next mount say `ready` again, its fallback after `fallback` ms. */ +export function forgetReadyForTests(fallback = READY_FALLBACK_MS): void { + fallbackMs = fallback; + readySent = false; + holding = false; + held = []; +} + +function sendReady(): void { + if (readySent) return; + readySent = true; + postToShell({ type: "ready" }); + const waiting = held; + held = []; + for (const message of waiting) postToShell(message); +} + +/** + * Tells the shell `message`, after `ready` when the reports are running and `ready` has not gone + * yet. Everything the page says to the shell, but `ready`, goes through here. + */ +export function tellShell( + message: Exclude, +): void { + if (holding && !readySent) held.push(message); + else postToShell(message); +} + +/** What does not count as text a person can read: hidden, for screen readers alone, a skeleton. */ +const NOT_READABLE = [ + "[hidden]", + '[aria-hidden="true"]', + ".sr-only", + '[data-slot="skeleton"]', + "script", + "style", + "noscript", + "template", +].join(", "); + +/** + * Whether `root` shows text a person can read: a text node with words in it whose element is not + * hidden, not kept for a screen reader alone and not a skeleton, and, where the browser can say + * (`checkVisibility`), is drawn at all. + */ +export function hasReadableText(root: Node = document.body): boolean { + const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if (!node.textContent?.trim()) continue; + const element = node.parentElement; + if (!element || element.closest(NOT_READABLE)) continue; + if ( + typeof element.checkVisibility === "function" && + !element.checkVisibility({ + visibilityProperty: true, + opacityProperty: false, + }) + ) + continue; + return true; + } + return false; +} + +/** Whether the page has drawn what it is for (see the rule above). */ +function drawn(): boolean { + return ( + document.querySelector('[data-slot="native-signed-out"]') !== null || + hasReadableText() + ); +} + +/** + * Tells the native shell when the first page has drawn (`ready`, above), then where the page is after + * every navigation that settled: the pathname, the shell's tab for it, and whether the page is behind + * the sign-in gate (`/_authed`), which only a signed-in person reaches. Nothing outside the shell. + * + * Mounted once, at the root, so pages outside the gate (`/sign`) are told too. + */ +export function useNativeShellRouteReports(): void { + const inShell = nativeShell() !== null; + const settled = useRouterState({ + select: (state) => + state.status === "idle" && state.resolvedLocation + ? `${state.matches.some((match) => match.routeId === "/_authed") ? "1" : "0"}${state.resolvedLocation.pathname}` + : null, + }); + + /* + * Hold what the page says until `ready`, from this render on: a page's own effects (`signed-out`) + * run before this component's, so an effect here would start holding too late. Idempotent. + */ + if (inShell && !readySent) holding = true; + + // Hand the screen over in the end whatever happens. + useEffect(() => { + if (!inShell || readySent) return; + const fallback = setTimeout(sendReady, fallbackMs); + return () => clearTimeout(fallback); + }, [inShell]); + + // Once the router has settled, `ready` as soon as the page shows something to read. + const hasSettled = settled !== null; + useEffect(() => { + if (!inShell || readySent || !hasSettled) return; + if (drawn()) { + sendReady(); + return; + } + const observer = new MutationObserver(() => { + if (readySent) observer.disconnect(); + else if (drawn()) { + observer.disconnect(); + sendReady(); + } + }); + observer.observe(document.body, { + attributes: true, + characterData: true, + childList: true, + subtree: true, + }); + return () => observer.disconnect(); + }, [inShell, hasSettled]); + + useEffect(() => { + if (!inShell || settled === null) return; + const path = settled.slice(1); + /* + * The tab whose stack the page is in, whether Back can go anywhere in it and how deep it is. The + * sign-in page is in no tab: the shell shows its own sign-in over it. A list returned to by Back + * is reported once its scroll position is back, so the app drops its snapshot with no jump. + */ + return whenScrollRestored(() => { + const tabs = path === "/sign" ? null : shellTabState(); + tellShell({ + type: "route", + path, + tab: tabs ? tabs.tab : tabForPath(path), + signedIn: settled.startsWith("1"), + canGoBack: tabs?.canGoBack ?? false, + depth: tabs?.depth ?? 1, + scrollRestored: true, + }); + }); + }, [inShell, settled]); +} diff --git a/app/src/lib/native-shell/shell.ts b/app/src/lib/native-shell/shell.ts new file mode 100644 index 0000000000..cb0f227650 --- /dev/null +++ b/app/src/lib/native-shell/shell.ts @@ -0,0 +1,177 @@ +/** + * OpenBot inside its phone app: the web app loaded in a native shell (a WKWebView on iOS, a + * WebView on Android) that draws its own tab bar (Conversations, Home, Bots) and its own sign-in + * screen around the page. In the shell the page draws no sidebar and no sign-in of its own, and + * tells the shell where it is (`bridge.ts`). + * + * How the page knows, in this order: + * + * 1. `window.__OPENBOT_NATIVE_SHELL__`, which the shell injects before the page's first script: + * `{ platform: "ios" | "android", version, bridge: 1 }`. + * 2. The user agent, which the shell ends with `OpenBotShell-iOS/0.1` (or `OpenBotShell-Android/…`). + * 3. For testing, `?native-shell=ios`, remembered for the tab in sessionStorage, so a desktop browser + * or Playwright can open the shell's layout. The platform it reports is "test". Only in a + * development build or on a development host (`developmentHost`): elsewhere a link carrying it + * would leave a person with the shell's layout and no shell, signed out with no way to sign in or + * signed in with no navigation, until the tab closed. `?native-shell=off` forgets it anywhere, so + * a tab that kept it from before can be freed. + * + * index.html's inline script runs the same detection before the first paint and marks + * `` for the styles, and widens the viewport to the whole web view + * (`viewport-fit=cover`) only there. `app/tests/native-shell.test.ts` holds the two to one answer. + */ + +/** Which shell: its own platform, or "test" for the query-parameter override. */ +export type NativeShellPlatform = "ios" | "android" | "test"; + +export type NativeShell = { platform: NativeShellPlatform }; + +/** What the shell injects at document start. */ +export type InjectedNativeShell = { + platform: "ios" | "android"; + version: string; + bridge: 1; +}; + +declare global { + interface Window { + __OPENBOT_NATIVE_SHELL__?: InjectedNativeShell; + } +} + +/** The query parameter that turns the shell's layout on for a tab (`ios`), or off (`off`). */ +export const NATIVE_SHELL_PARAM = "native-shell"; +/** Where the tab remembers it. */ +export const NATIVE_SHELL_STORAGE_KEY = "openbot-native-shell"; +/** The mark on ``, as `dataset.nativeShell`, read by the styles as `[data-native-shell]`. */ +export const NATIVE_SHELL_ATTRIBUTE = "data-native-shell"; + +/** The user agent's mark: `OpenBotShell-iOS/0.1`. */ +const USER_AGENT_MARK = /OpenBotShell-(\w+)/; + +/** + * Where the testing override counts: a machine's own addresses and the names kept for development + * (`.localhost`, `.test`), where the phone apps' UI tests, the workbench and the screenshot scripts + * open the app. index.html asks the same. + */ +export function developmentHost(hostname: string): boolean { + const host = hostname.toLowerCase(); + return ( + host === "localhost" || + host === "127.0.0.1" || + host === "[::1]" || + host === "::1" || + host.endsWith(".localhost") || + host.endsWith(".test") + ); +} + +/** What detection reads, so a test can hand it anything. */ +export type NativeShellEnvironment = { + injected: unknown; + userAgent: string; + search: string; + /** The page's host name: the testing override counts only on a development host. */ + hostname: string; + /** A development build, where the override counts on any host. */ + dev?: boolean; + /** The tab's sessionStorage, or null where it can't be read. */ + storage: Pick | null; +}; + +/** + * Applies `?native-shell=` to the tab's memory: `ios` (or `android`, `test`) remembers it, `off` + * forgets it. Then answers which shell this page is in, or null in a plain browser. + */ +export function detectNativeShell( + environment: NativeShellEnvironment, +): NativeShell | null { + const { injected, userAgent, search, storage } = environment; + const overridable = + environment.dev === true || developmentHost(environment.hostname); + const param = new URLSearchParams(search).get(NATIVE_SHELL_PARAM); + // "off" is honoured anywhere; turning the override on only where it may count. + const asked = param === "off" || overridable ? param : null; + try { + if (asked === "off") storage?.removeItem(NATIVE_SHELL_STORAGE_KEY); + else if (asked === "ios" || asked === "android" || asked === "test") + storage?.setItem(NATIVE_SHELL_STORAGE_KEY, "test"); + } catch { + // Storage refused: the override lasts for this page only. + } + if ( + typeof injected === "object" && + injected !== null && + "platform" in injected && + (injected.platform === "ios" || injected.platform === "android") + ) + return { platform: injected.platform }; + const mark = USER_AGENT_MARK.exec(userAgent); + if (mark) + return { + platform: mark[1].toLowerCase() === "android" ? "android" : "ios", + }; + if (asked === "ios" || asked === "android" || asked === "test") + return { platform: "test" }; + if (asked === "off" || !overridable) return null; + try { + return storage?.getItem(NATIVE_SHELL_STORAGE_KEY) === "test" + ? { platform: "test" } + : null; + } catch { + return null; + } +} + +function pageStorage(): Storage | null { + try { + return window.sessionStorage; + } catch { + return null; + } +} + +/** This page's environment. */ +function pageEnvironment(): NativeShellEnvironment { + return { + injected: window.__OPENBOT_NATIVE_SHELL__, + userAgent: navigator.userAgent, + search: window.location.search, + hostname: window.location.hostname, + // A boolean under Vite, a string where another build (the Recorder) types the env, and no + // `import.meta.env` at all where the app is bundled without Vite (the real-browser tests): + // absent is not a development build. + dev: String(import.meta.env?.DEV) === "true", + storage: pageStorage(), + }; +} + +let detected: NativeShell | null | undefined; + +/** + * The native shell this page is in, or null in a browser, OpenBot Desktop included. Worked out once, + * on the first call, and the same answer after: a page does not move into or out of a shell. + */ +export function nativeShell(): NativeShell | null { + if (detected === undefined) { + detected = + typeof window === "undefined" + ? null + : detectNativeShell(pageEnvironment()); + } + return detected; +} + +/** For tests: forget the answer, so the next call works it out again. */ +export function forgetNativeShellForTests(): void { + detected = undefined; +} + +/** + * Marks `` for the styles, as index.html's inline script already did before the first paint. + * Again here for a page whose script could not run it; idempotent. + */ +export function markNativeShell(root: HTMLElement = document.documentElement) { + const shell = nativeShell(); + if (shell) root.dataset.nativeShell = shell.platform; +} diff --git a/app/src/lib/native-shell/tab-stacks.ts b/app/src/lib/native-shell/tab-stacks.ts new file mode 100644 index 0000000000..5dec291668 --- /dev/null +++ b/app/src/lib/native-shell/tab-stacks.ts @@ -0,0 +1,158 @@ +import { type NativeTab, tabForPath } from "./bridge"; + +/** + * WHERE EACH OF THE PHONE APP'S TABS IS: one stack of locations per tab, as a native tab bar app + * keeps them. The web app owns this inside the native shell (`use-tab-navigation.ts` applies it); + * outside the shell nothing reads it and the browser's own history is the history. + * + * - Each tab's stack starts at its root (`TAB_ROOTS`). Going deeper pushes onto the CURRENT tab's + * stack, so a page opened from a tab belongs to that tab: a conversation opened from the Bots + * panel is in the Bots stack, one sent from Home in Home's. A page no tab owns (Settings, Admin, + * opened from the Account menu) goes onto the current tab's stack too, so Back returns to where it + * was opened. + * - A tab tap is the shell asking for a tab's root. Another tab's root: switch to that tab, exactly + * where it was left. The current tab's root: pop it to its root, and at its root, scroll to the top. + * - Back pops the current tab's stack only, never into another tab; at a root it does nothing, and + * `canGoBack` is false there. + * - With no stacks yet (a cold start, a reload, a deep link) the stack is built from the address: + * the tab that owns it, with its root under it, so a deep page always has a way out. + * - Signing out clears every stack. + * + * Pure: every function returns the next state and what to show; nothing here touches the router. + */ + +/** Each tab's root, the location its tap asks for. */ +export const TAB_ROOTS: Record = { + conversations: "/conversations", + home: "/", + bots: "/bots", +}; + +const TABS = Object.keys(TAB_ROOTS) as NativeTab[]; + +export type TabStacks = { + /** The tab on screen. */ + current: NativeTab; + /** Each tab's locations, root first, top last: path, search and fragment. */ + stacks: Record; +}; + +/** What a change of the stacks asks the page to do. */ +export type TabStep = { + state: TabStacks; + /** The location to show now: the current tab's top. */ + show: string; + /** The current tab was tapped at its root: scroll its list to the top. */ + scrollToTop?: true; +}; + +/** A location's path, without its search or fragment. */ +export function pathOf(location: string): string { + const path = location.split(/[?#]/)[0] || "/"; + return path.length > 1 ? path.replace(/\/+$/, "") || "/" : path; +} + +/** The tab whose root `location` is, or null when it is no tab's root. */ +export function rootTabOf(location: string): NativeTab | null { + const path = pathOf(location); + return TABS.find((tab) => TAB_ROOTS[tab] === path) ?? null; +} + +/** The top of the current tab's stack: what is on screen. */ +export function topOf(state: TabStacks): string { + const stack = state.stacks[state.current]; + return stack[stack.length - 1] ?? TAB_ROOTS[state.current]; +} + +/** Whether Back has somewhere to go inside the current tab. */ +export function canGoBack(state: TabStacks): boolean { + return state.stacks[state.current].length > 1; +} + +function rootsOnly(): Record { + return { + conversations: [TAB_ROOTS.conversations], + home: [TAB_ROOTS.home], + bots: [TAB_ROOTS.bots], + }; +} + +/** + * The stacks for a page opened with none (a cold start, a reload, a deep link): the tab that owns + * the address (`tabForPath`), or Home where no tab does, with that tab's root under the page. + */ +export function stacksFor(location: string): TabStacks { + const stacks = rootsOnly(); + const root = rootTabOf(location); + if (root) { + stacks[root] = [location]; + return { current: root, stacks }; + } + const current = tabForPath(pathOf(location)) ?? "home"; + stacks[current] = [TAB_ROOTS[current], location]; + return { current, stacks }; +} + +function withStack( + state: TabStacks, + tab: NativeTab, + stack: string[], +): TabStacks { + return { current: tab, stacks: { ...state.stacks, [tab]: stack } }; +} + +function step(state: TabStacks, extra?: { scrollToTop: true }): TabStep { + return { state, show: topOf(state), ...extra }; +} + +/** + * The shell's tab tap: `location` is a tab's root. Another tab's: that tab, where it was left. The + * current tab's: popped to its root, or, at its root already, scrolled to the top. + */ +export function tapTab(state: TabStacks, location: string): TabStep { + const tab = rootTabOf(location); + if (!tab) return pushLocation(state, location); + if (tab !== state.current) return step({ ...state, current: tab }); + const stack = state.stacks[tab]; + if (stack.length <= 1) return step(state, { scrollToTop: true }); + return step(withStack(state, tab, [stack[0] ?? TAB_ROOTS[tab]])); +} + +/** + * Going somewhere from inside the page (a row, a link, a button). Deeper: onto the current tab's + * stack. A tab's root: that tab at its root, as following a link to a list does. The same location + * again: nothing. + */ +export function pushLocation(state: TabStacks, location: string): TabStep { + const tab = rootTabOf(location); + if (tab) return step(withStack(state, tab, [location])); + const stack = state.stacks[state.current]; + if (stack[stack.length - 1] === location) return step(state); + return step(withStack(state, state.current, [...stack, location])); +} + +/** + * The page put another location in place of the one on screen (a search change, a closed sheet): + * the current tab's top is replaced. A tab's root replacing a deeper page is that tab at its root. + */ +export function replaceLocation(state: TabStacks, location: string): TabStep { + const tab = rootTabOf(location); + const stack = state.stacks[state.current]; + if (tab && (tab !== state.current || stack.length > 1)) + return step(withStack(state, tab, [location])); + return step( + withStack(state, state.current, [...stack.slice(0, -1), location]), + ); +} + +/** Back: the current tab's stack popped once; at its root, nothing. */ +export function goBack(state: TabStacks): TabStep { + const stack = state.stacks[state.current]; + if (stack.length <= 1) return step(state); + return step(withStack(state, state.current, stack.slice(0, -1))); +} + +/** Signed out: every stack back to its root, on Home, with nowhere to go back to. */ +export function cleared(): TabStacks { + return { current: "home", stacks: rootsOnly() }; +} diff --git a/app/src/lib/native-shell/use-tab-navigation.ts b/app/src/lib/native-shell/use-tab-navigation.ts new file mode 100644 index 0000000000..d14c81ff2d --- /dev/null +++ b/app/src/lib/native-shell/use-tab-navigation.ts @@ -0,0 +1,348 @@ +import { useRouter } from "@tanstack/react-router"; +import { useEffect } from "react"; +import { type NativeTab, shellListens, tabForPath } from "./bridge"; +import { tellShell } from "./route-reports"; +import { nativeShell } from "./shell"; +import { + canGoBack, + cleared, + goBack, + pathOf, + pushLocation, + replaceLocation, + rootTabOf, + stacksFor, + TAB_ROOTS, + type TabStacks, + type TabStep, + tapTab, +} from "./tab-stacks"; + +/** + * THE PHONE APP'S TABS, APPLIED (`tab-stacks.ts` is the model). Inside the native shell the web app + * keeps one stack of locations per tab and shows the current tab's top: + * + * - Every navigation the page makes (a row, a link, `navigate`) goes onto the current tab's stack, + * and is written to the browser as a REPLACE, never a push: the web view's own back and forward + * list stays one entry long, so nothing native (Android's Back, iOS's edge swipe) can walk a + * history that mixes tabs. The stacks are the only history. + * - A tab tap arrives as `openbot:open` with the tab's root (`useDesktopOpenRequests` hands it + * here): another tab's root switches to that tab where it was left, the current tab's pops it to + * its root, or scrolls its list to the top at the root. + * - Back is `openbot:back` from native, or the page's own back control (`goBackInShell`): the + * current tab's stack popped once, never into another tab; nothing at a root. + * - The `route` message says which tab's stack the page is in and whether Back can go anywhere + * (`shellTabState`, read by `route-reports.ts`). + * - A list keeps its scroll: the panel's is saved as the page is left and put back when it is shown + * again, and its data comes from the query cache, so a tab comes back without a skeleton. + * - Reaching the sign-in page (signing out, a session that ran out) clears every stack. + * + * Outside the shell none of this is installed: the browser's history is the history. + */ + +/** The custom event native sends on `window` for Back, when the last `route` said `canGoBack`. */ +export const BACK_REQUEST = "openbot:back"; + +/** The tabs' stacks for this page load, once the shell's navigation has started. */ +let stacks: TabStacks | null = null; +/** Shows a step, announced to the app as `direction` when given (set while mounted). */ +let apply: ((next: TabStep, direction?: Direction) => void) | null = null; + +type Direction = "push" | "back" | "replace"; + +/** For tests: forget the stacks, as a new page load does. */ +export function forgetTabStacksForTests(): void { + stacks = null; + apply = null; + scrolls.clear(); + restoring = null; +} + +/** + * The tab the page is in, whether Back can go anywhere, and how deep its stack is (1 at its root), + * inside the shell; null outside it. + */ +export function shellTabState(): { + tab: NativeTab; + canGoBack: boolean; + depth: number; +} | null { + return stacks + ? { + tab: stacks.current, + canGoBack: canGoBack(stacks), + depth: stacks.stacks[stacks.current].length, + } + : null; +} + +/** The root of the tab the page is in, inside the shell: where a back control falls back to. */ +export function currentTabRoot(): string | null { + return stacks ? TAB_ROOTS[stacks.current] : null; +} + +/** + * Back from the page's own control: the current tab's stack popped once. False where there is + * nowhere to go in it (or outside the shell), and the control then follows its own link. + */ +export function goBackInShell(): boolean { + if (!stacks || !apply || !canGoBack(stacks)) return false; + apply(goBack(stacks), "back"); + return true; +} + +/** + * What the shell asked for with `openbot:open`: a tab's root is a tab tap; any other page (a + * notification's) opens in the tab that owns it, on top of where that tab was. False outside the + * shell's navigation, where the caller opens it as before. + */ +export function openFromShell(location: string): boolean { + if (!stacks || !apply) return false; + if (rootTabOf(location)) { + apply(tapTab(stacks, location)); + return true; + } + const owner = tabForPath(pathOf(location)) ?? stacks.current; + apply(pushLocation({ ...stacks, current: owner }, location)); + return true; +} + +/** Where each list was scrolled, by location, while the person was elsewhere. */ +const scrolls = new Map(); + +/** The scrolling part of a list the shell shows as a tab: a sidebar panel's content. */ +const LIST = '[data-slot="section-panel"] [data-slot="sidebar-content"]'; + +function saveScroll(location: string) { + const list = document.querySelector(LIST); + if (list) scrolls.set(location, list.scrollTop); +} + +/** + * A list being put back where it was, while it is: the `route` for its page waits for it + * (`whenScrollRestored`), so the app drops its snapshot only once nothing will jump. + */ +let restoring: { done: Promise; finish: () => void } | null = null; + +/** + * Ends a list's restore that is still under way: the page is moving on (a tab tap, another page), + * so whatever waits for it (the route of the page being left) is released, not held behind a list + * that is no longer on screen. + */ +function stopRestoring() { + restoring?.finish(); +} + +/** Puts `location`'s list back where it was, once it has drawn enough to scroll that far. */ +function restoreScroll(location: string) { + const saved = scrolls.get(location); + if (!saved) return; + let frames = 0; + let settle = () => {}; + const done = new Promise((resolve) => { + settle = resolve; + }); + const finish = () => { + if (restoring === current) restoring = null; + settle(); + }; + const current = { done, finish }; + restoring = current; + const tick = () => { + if (restoring !== current) return; + const list = document.querySelector(LIST); + if (list) { + list.scrollTop = saved; + if (Math.abs(list.scrollTop - saved) < 2) return finish(); + } + // About a second at most: a list that can no longer scroll that far is shown where it can. + if (++frames < 60) requestAnimationFrame(tick); + else finish(); + }; + requestAnimationFrame(tick); +} + +/** Runs `then` once no list is being put back (at once, mostly). */ +export function whenScrollRestored(then: () => void): () => void { + let live = true; + const pending = restoring; + if (!pending) then(); + else void pending.done.then(() => live && then()); + return () => { + live = false; + }; +} + +/** The app's answer to `will-navigate`: it holds its snapshot, so the page may change. */ +export const NAVIGATE_OK = "openbot:navigate-ok"; +/** How long the page waits for that answer before it goes ahead anyway. */ +export const NAVIGATE_OK_MS = 120; + +/** + * What is drawn over the page for a moment: a menu, a select's list, a popover, a tooltip, a sheet + * or a dialog, as the primitives portal them (Base UI). The toasts' region, always there, is not. + */ +const OVERLAY = + '[data-base-ui-portal] :is([role="menu"], [role="listbox"], [role="dialog"], [role="alertdialog"], [role="tooltip"], [data-slot$="-content"], [data-slot$="-popup"])'; + +function overlayOnScreen(): Element | null { + for (const element of document.querySelectorAll(OVERLAY)) + if (!element.closest('[data-slot="toast-viewport"]')) return element; + return null; +} + +/** How long a navigation may be held for an overlay to go, at most, and in frames. */ +const OVERLAY_MS = 100; +const OVERLAY_FRAMES = 2; + +/** + * Runs `then` once no overlay is on screen and that has been drawn, so the app's picture of the page + * at `will-navigate` has no menu open in it. With none, at once. An item's own press usually closes + * its menu by the next frame; one still open then is sent Escape, as a person would close it. + * Never more than `OVERLAY_FRAMES` frames and the frame that draws its going, and never more than + * `OVERLAY_MS`. Its exit animation is off in the shell (styles.css), so it goes at once. + */ +function withoutOverlays(then: () => void): void { + if (!overlayOnScreen()) { + then(); + return; + } + let done = false; + const finish = () => { + if (done) return; + done = true; + clearTimeout(cap); + then(); + }; + const cap = setTimeout(finish, OVERLAY_MS); + let frames = 0; + const tick = () => { + if (done) return; + const open = overlayOnScreen(); + // Gone: one more frame, so its going is drawn before the app takes its picture. + if (!open) return void requestAnimationFrame(finish); + frames += 1; + if (frames === 1) + open.dispatchEvent( + new KeyboardEvent("keydown", { + key: "Escape", + code: "Escape", + bubbles: true, + cancelable: true, + }), + ); + if (frames > OVERLAY_FRAMES) return finish(); + requestAnimationFrame(tick); + }; + requestAnimationFrame(tick); +} + +/** + * Tells the app a navigation the page started is coming (`will-navigate`), then runs `go`: at once, + * or on iOS, where the app takes a snapshot of the page for its swipe back, once the app answers + * `openbot:navigate-ok` or after `NAVIGATE_OK_MS`, whichever is first. Never waits where nothing + * received the message, nor on Android, which does not answer. + */ +function announce(direction: Direction, next: TabStacks, go: () => void): void { + withoutOverlays(() => say(direction, next, go)); +} + +/** `announce`, once nothing is drawn over the page. */ +function say(direction: Direction, next: TabStacks, go: () => void): void { + const message = { + type: "will-navigate", + tab: next.current, + direction, + depth: next.stacks[next.current].length, + } as const; + if (nativeShell()?.platform !== "ios" || !shellListens()) { + tellShell(message); + go(); + return; + } + // Listening before it is said, so an answer given at once is not missed. + let gone = false; + const once = () => { + if (gone) return; + gone = true; + clearTimeout(timer); + window.removeEventListener(NAVIGATE_OK, once); + go(); + }; + const timer = setTimeout(once, NAVIGATE_OK_MS); + window.addEventListener(NAVIGATE_OK, once); + tellShell(message); +} + +function scrollListToTop() { + document.querySelector(LIST)?.scrollTo({ top: 0, behavior: "smooth" }); +} + +/** Mounted once, at the root, next to the reports and Desktop's open requests. */ +export function useTabNavigation(): void { + const router = useRouter(); + useEffect(() => { + if (!nativeShell()) return; + const history = router.history; + const here = () => + `${history.location.pathname}${history.location.search}${history.location.hash}`; + /** Signing out, or a session that ran out, ends on the sign-in page: no stack survives it. */ + const signedOut = (location: string) => pathOf(location) === "/sign"; + stacks ??= signedOut(here()) ? cleared() : stacksFor(here()); + const push = history.push; + const replace = history.replace; + + /** Whether going from `from` to `to` changes the page, as opposed to its search or fragment. */ + const changesPage = (from: string, to: string) => + pathOf(from) !== pathOf(to); + + history.push = (path, state, options) => { + stopRestoring(); + const from = here(); + saveScroll(from); + stacks = signedOut(path) + ? cleared() + : pushLocation(stacks ?? stacksFor(from), path).state; + if (signedOut(path) || !changesPage(from, path)) + replace(path, state, options); + else announce("push", stacks, () => replace(path, state, options)); + }; + history.replace = (path, state, options) => { + stopRestoring(); + const from = here(); + stacks = signedOut(path) + ? cleared() + : replaceLocation(stacks ?? stacksFor(from), path).state; + if (signedOut(path) || !changesPage(from, path)) + replace(path, state, options); + else announce("replace", stacks, () => replace(path, state, options)); + }; + apply = (next, direction) => { + if (next.show !== here()) stopRestoring(); + const from = here(); + if (next.show !== from) saveScroll(from); + stacks = next.state; + if (next.scrollToTop) scrollListToTop(); + if (next.show === from) return; + const go = () => { + replace(next.show); + restoreScroll(next.show); + }; + if (direction && changesPage(from, next.show)) + announce(direction, next.state, go); + else go(); + }; + // Back the app asked for: popped as the page's own Back is, but not announced, since the app + // started it and already knows. + const onBack = () => { + if (stacks && apply && canGoBack(stacks)) apply(goBack(stacks)); + }; + window.addEventListener(BACK_REQUEST, onBack); + return () => { + history.push = push; + history.replace = replace; + apply = null; + window.removeEventListener(BACK_REQUEST, onBack); + }; + }, [router]); +} diff --git a/app/src/lib/notifications/permission.ts b/app/src/lib/notifications/permission.ts index 0dc6819998..9326889104 100644 --- a/app/src/lib/notifications/permission.ts +++ b/app/src/lib/notifications/permission.ts @@ -1,5 +1,6 @@ import { useSyncExternalStore } from "react"; import { desktopShell, type ShellIpc } from "@/lib/desktop/shell"; +import { nativeShell } from "@/lib/native-shell/shell"; /** * Whether this browser may show OpenBot's notifications: the browser's own answer, never a guess. @@ -36,6 +37,8 @@ export type NotificationPermissionState = /** What the browser says now. A browser that throws on reading it is one that cannot show them. */ export function notificationPermission(): NotificationPermissionState { + // In the phone app's native shell the phone app notifies, never the page: nothing to offer here. + if (nativeShell() !== null) return "unsupported"; try { return typeof Notification === "undefined" ? "unsupported" diff --git a/app/src/lib/sections.tsx b/app/src/lib/sections.tsx index 0dbad6d72f..f8d8577c6e 100644 --- a/app/src/lib/sections.tsx +++ b/app/src/lib/sections.tsx @@ -39,6 +39,7 @@ export function sectionForPath( ): SectionId | null { if ( pathname === "/" || + pathname === "/conversations" || pathname === "/channel" || pathname.startsWith("/channel/") ) { diff --git a/app/src/lib/web-push/browser.ts b/app/src/lib/web-push/browser.ts index 378ed3c99f..992ae8517a 100644 --- a/app/src/lib/web-push/browser.ts +++ b/app/src/lib/web-push/browser.ts @@ -1,5 +1,6 @@ import type { SaveWebPushSubscriptionRequest } from "@/lib/api/generated/model"; import { desktopShell } from "@/lib/desktop/shell"; +import { nativeShell } from "@/lib/native-shell/shell"; import { newId } from "@/lib/new-id"; import { scriptURL } from "@/lib/trusted-types"; @@ -29,7 +30,8 @@ const ID_STORAGE_KEY = "openbot-web-push-id"; * the Home Screen, on iOS 16.4 or later. The person is told how, since a switch here can't work. * - `newer-ios-first`: OpenBot opened from the Home Screen of an iPhone or iPad older than iOS 16.4. * - `unsupported`: anything else, OpenBot Desktop's window included, which shows notifications - * through the desktop app. Nothing is offered. + * through the desktop app, and the phone app's native shell, which is no Home Screen web app and + * whose notifications are the phone app's own. Nothing is offered. * * The Push API is offered only to a secure page (HTTPS, or this computer's own address), so an * OpenBot opened at a plain-HTTP address is `unsupported` too. @@ -41,7 +43,11 @@ export type WebPushSupport = | "unsupported"; export function webPushSupport(): WebPushSupport { - if (typeof window === "undefined" || desktopShell() !== null) + if ( + typeof window === "undefined" || + desktopShell() !== null || + nativeShell() !== null + ) return "unsupported"; if ( "serviceWorker" in navigator && diff --git a/app/src/main.tsx b/app/src/main.tsx index 509ee86a1b..d1f01a64cb 100644 --- a/app/src/main.tsx +++ b/app/src/main.tsx @@ -6,6 +6,7 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { settleFromSetup } from "./lib/desktop/from-setup"; import { installAppErrorReporting } from "./lib/error-reporting"; +import { markNativeShell } from "./lib/native-shell/shell"; import { queryClient } from "./query-client"; import { router } from "./router"; import "@copilotkit/react-core/v2/styles.css"; @@ -18,6 +19,10 @@ installAppErrorReporting(); // in the Desktop window (lib/desktop/from-setup.ts). settleFromSetup(); +// Inside the phone app's native shell: marked for the styles, as index.html did before the first +// paint (lib/native-shell/shell.ts), and worked out once for the app. +markNativeShell(); + const rootElement = document.getElementById("root"); if (!rootElement) { diff --git a/app/src/routeTree.gen.ts b/app/src/routeTree.gen.ts index d1f3cc991b..65ba6f334a 100644 --- a/app/src/routeTree.gen.ts +++ b/app/src/routeTree.gen.ts @@ -26,6 +26,7 @@ import { Route as AuthedAppApprovalsRouteImport } from './routes/_authed/_app/ap import { Route as AuthedAppArtifactsRouteImport } from './routes/_authed/_app/artifacts' import { Route as AuthedAppBotRouteImport } from './routes/_authed/_app/bot' import { Route as AuthedAppBrowserRouteImport } from './routes/_authed/_app/browser' +import { Route as AuthedAppConversationsRouteImport } from './routes/_authed/_app/conversations' import { Route as AuthedAppMemoryRouteImport } from './routes/_authed/_app/memory' import { Route as AuthedAppReachabilityRouteImport } from './routes/_authed/_app/reachability' import { Route as AuthedAppReconnectRouteImport } from './routes/_authed/_app/reconnect' @@ -247,6 +248,11 @@ const AuthedAppBrowserRoute = AuthedAppBrowserRouteImport.update({ path: '/browser', getParentRoute: () => AuthedAppRoute, } as any) +const AuthedAppConversationsRoute = AuthedAppConversationsRouteImport.update({ + id: '/conversations', + path: '/conversations', + getParentRoute: () => AuthedAppRoute, +} as any) const AuthedAppMemoryRoute = AuthedAppMemoryRouteImport.update({ id: '/memory', path: '/memory', @@ -1019,6 +1025,7 @@ export interface FileRoutesByFullPath { '/artifacts': typeof AuthedAppArtifactsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute + '/conversations': typeof AuthedAppConversationsRoute '/memory': typeof AuthedAppMemoryRoute '/reachability': typeof AuthedAppReachabilityRoute '/reconnect': typeof AuthedAppReconnectRoute @@ -1170,6 +1177,7 @@ export interface FileRoutesByTo { '/artifacts': typeof AuthedAppArtifactsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute + '/conversations': typeof AuthedAppConversationsRoute '/memory': typeof AuthedAppMemoryRoute '/reachability': typeof AuthedAppReachabilityRoute '/reconnect': typeof AuthedAppReconnectRoute @@ -1325,6 +1333,7 @@ export interface FileRoutesById { '/_authed/_app/artifacts': typeof AuthedAppArtifactsRoute '/_authed/_app/bot': typeof AuthedAppBotRoute '/_authed/_app/browser': typeof AuthedAppBrowserRoute + '/_authed/_app/conversations': typeof AuthedAppConversationsRoute '/_authed/_app/memory': typeof AuthedAppMemoryRoute '/_authed/_app/reachability': typeof AuthedAppReachabilityRoute '/_authed/_app/reconnect': typeof AuthedAppReconnectRoute @@ -1482,6 +1491,7 @@ export interface FileRouteTypes { | '/artifacts' | '/bot' | '/browser' + | '/conversations' | '/memory' | '/reachability' | '/reconnect' @@ -1633,6 +1643,7 @@ export interface FileRouteTypes { | '/artifacts' | '/bot' | '/browser' + | '/conversations' | '/memory' | '/reachability' | '/reconnect' @@ -1787,6 +1798,7 @@ export interface FileRouteTypes { | '/_authed/_app/artifacts' | '/_authed/_app/bot' | '/_authed/_app/browser' + | '/_authed/_app/conversations' | '/_authed/_app/memory' | '/_authed/_app/reachability' | '/_authed/_app/reconnect' @@ -2058,6 +2070,13 @@ declare module '@tanstack/react-router' { preLoaderRoute: typeof AuthedAppBrowserRouteImport parentRoute: typeof AuthedAppRoute } + '/_authed/_app/conversations': { + id: '/_authed/_app/conversations' + path: '/conversations' + fullPath: '/conversations' + preLoaderRoute: typeof AuthedAppConversationsRouteImport + parentRoute: typeof AuthedAppRoute + } '/_authed/_app/memory': { id: '/_authed/_app/memory' path: '/memory' @@ -3217,6 +3236,7 @@ interface AuthedAppRouteChildren { AuthedAppArtifactsRoute: typeof AuthedAppArtifactsRoute AuthedAppBotRoute: typeof AuthedAppBotRoute AuthedAppBrowserRoute: typeof AuthedAppBrowserRoute + AuthedAppConversationsRoute: typeof AuthedAppConversationsRoute AuthedAppMemoryRoute: typeof AuthedAppMemoryRoute AuthedAppReachabilityRoute: typeof AuthedAppReachabilityRoute AuthedAppReconnectRoute: typeof AuthedAppReconnectRoute @@ -3284,6 +3304,7 @@ const AuthedAppRouteChildren: AuthedAppRouteChildren = { AuthedAppArtifactsRoute: AuthedAppArtifactsRoute, AuthedAppBotRoute: AuthedAppBotRoute, AuthedAppBrowserRoute: AuthedAppBrowserRoute, + AuthedAppConversationsRoute: AuthedAppConversationsRoute, AuthedAppMemoryRoute: AuthedAppMemoryRoute, AuthedAppReachabilityRoute: AuthedAppReachabilityRoute, AuthedAppReconnectRoute: AuthedAppReconnectRoute, diff --git a/app/src/routes/__root.tsx b/app/src/routes/__root.tsx index cbe11be8ef..bd87e2a3c8 100644 --- a/app/src/routes/__root.tsx +++ b/app/src/routes/__root.tsx @@ -11,6 +11,8 @@ import { Toaster } from "@/components/ui/toast"; import { TooltipProvider } from "@/components/ui/tooltip"; import { useDesktopDownloads } from "@/lib/desktop/downloads"; import { useDesktopOpenRequests } from "@/lib/desktop/open-requests"; +import { useNativeShellRouteReports } from "@/lib/native-shell/route-reports"; +import { useTabNavigation } from "@/lib/native-shell/use-tab-navigation"; import { useServiceWorkerOpenRequests } from "@/lib/web-push/open-requests"; import type { RouterContext } from "../router-context"; import "@fontsource-variable/figtree/wght.css"; @@ -124,10 +126,14 @@ export function useUnclaimedDropGuard() { function RootComponent() { useUnclaimedDropGuard(); - // OpenBot Desktop opens a notice's page here, as a route change. See `lib/desktop/open-requests.ts`. + // OpenBot Desktop opens a notice's page here, as a route change, and the phone app's native shell + // a tab's page. See `lib/desktop/open-requests.ts`. useDesktopOpenRequests(); // And says where a file downloaded in OpenBot Desktop went. See `lib/desktop/downloads.ts`. useDesktopDownloads(); + // The phone app's native shell is told where the page is. See `lib/native-shell/route-reports.ts`. + useNativeShellRouteReports(); + useTabNavigation(); // And a click on a push notification, sent by the service worker. See `lib/web-push/open-requests.ts`. useServiceWorkerOpenRequests(); return ( diff --git a/app/src/routes/_authed/_app.tsx b/app/src/routes/_authed/_app.tsx index 62256138f4..fb0947cc15 100644 --- a/app/src/routes/_authed/_app.tsx +++ b/app/src/routes/_authed/_app.tsx @@ -1,6 +1,7 @@ import { createFileRoute, Outlet } from "@tanstack/react-router"; import { AppSidebar } from "@/components/app-sidebar/app-sidebar"; import { ConnectionBanner } from "@/components/layout/connection-banner"; +import { NativeShellFrame } from "@/components/layout/native-shell-frame"; import { PageArrival } from "@/components/layout/page-arrival"; import { PlanBanner } from "@/components/layout/plan-banner"; import { SelfHostBanner } from "@/components/layout/self-host-banner"; @@ -17,6 +18,7 @@ import { sectionHasPanel, useOpenSection, } from "@/lib/sections"; +import { nativeShell } from "@/lib/native-shell/shell"; import { useActiveSkin } from "@/skins/registry"; export const Route = createFileRoute("/_authed/_app")({ @@ -26,6 +28,20 @@ export const Route = createFileRoute("/_authed/_app")({ function RouteComponent() { const { Frame } = useActiveSkin(); + /* + * Inside the phone app's native shell, which draws the navigation itself: the page alone. Before + * the skin's frame, since the shell is this device's, the skin the account's. + */ + if (nativeShell()) { + return ( + + + + + + ); + } + if (Frame) { return ( diff --git a/app/src/routes/_authed/_app/bots.index.tsx b/app/src/routes/_authed/_app/bots.index.tsx index cc64b93cce..b112fdbeee 100644 --- a/app/src/routes/_authed/_app/bots.index.tsx +++ b/app/src/routes/_authed/_app/bots.index.tsx @@ -4,6 +4,8 @@ import { z } from "zod"; import { NewBotSheet } from "@/components/agents/new-bot-sheet"; import { BotRoster } from "@/components/bots/bot-roster"; import { IconChevronRight } from "@/components/icons"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; +import { ShellBots } from "@/components/layout/native-shell-panels"; import { PageAddButton, PageRows, @@ -24,6 +26,7 @@ import { deploymentCapabilitiesQueryOptions, useOffersMemory, } from "@/lib/deployment/queries"; +import { nativeShell } from "@/lib/native-shell/shell"; import { currentOrganizationId } from "@/lib/organizations/current"; import { organizationHasOthersQueryOptions, @@ -59,9 +62,41 @@ export const Route = createFileRoute("/_authed/_app/bots/")({ : []), ]); }, - component: BotsPage, + component: BotsRoute, }); +/** + * In the phone app's native shell, the Bots tab, which is the sidebar's Bots panel itself + * (`ShellBots`); in a browser and OpenBot Desktop, the page below. + */ +function BotsRoute() { + return nativeShell() ? : ; +} + +function ShellBotsRoute() { + const { new: creating } = Route.useSearch(); + const navigate = Route.useNavigate(); + return ( + void navigate({ search: {} })} + onCreated={(agentId) => { + // As the page below does: close first, then go, so Back from the new Bot lands here. + void navigate({ replace: true, search: {} }); + window.setTimeout( + () => + void navigate({ + params: { agentId }, + search: {}, + to: "/bots/$agentId", + }), + SHEET_CLOSE_MS, + ); + }} + /> + ); +} + function BotsPage() { const { new: creating } = Route.useSearch(); const navigate = Route.useNavigate(); @@ -72,9 +107,13 @@ function BotsPage() { return ( - New Bot - +
+ + New Bot + + {/* Only inside the phone app's native shell, which has no sidebar. */} + +
} description={ personal || alone diff --git a/app/src/routes/_authed/_app/channel/$channelId.tsx b/app/src/routes/_authed/_app/channel/$channelId.tsx index ac8acb3e0c..9331e487b5 100644 --- a/app/src/routes/_authed/_app/channel/$channelId.tsx +++ b/app/src/routes/_authed/_app/channel/$channelId.tsx @@ -23,6 +23,7 @@ import { DetailPanel, detailFitsBeside, } from "@/components/layout/detail-panel"; +import { ShellBackButton } from "@/components/layout/native-shell-back"; import { SidebarToggle } from "@/components/layout/sidebar-toggle"; import { TaskDetails } from "@/components/tasks/task-details"; import { Button } from "@/components/ui/button"; @@ -39,9 +40,11 @@ import { useNoBotComputers } from "@/lib/deployment/queries"; import { useConnectionLost } from "@/lib/desktop/connection-lost"; import { loadFailure } from "@/lib/load-failure"; import { EASE_OUT } from "@/lib/motion"; +import { nativeShell } from "@/lib/native-shell/shell"; import { useOrganizationChoices } from "@/lib/organizations/queries"; import { loadFirstScreen } from "@/lib/route-data"; import { taskListQueryOptions } from "@/lib/tasks/queries"; +import { cn } from "@/lib/utils"; const chatSearchSchema = z.object({ settings: z.boolean().optional(), @@ -233,12 +236,17 @@ function RouteComponent() { >
{/* Keyed on the displayed name so cold channel loads animate the resolved name, not the id. */}
+ + To: : ; +} + +/** Above this many rows a re-sort is not animated, as in the sidebar. */ +const MAX_ANIMATED_ROWS = 60; + +/** + * Every conversation, as a page: the sidebar's Conversations panel for a screen with no sidebar + * (the phone app's native shell, whose Conversations tab opens it), and at its own address in a + * browser too. The same list, read the same way: pinned first, then newest, unread marked, the + * same search over the whole history, and New conversation where the panel has it. The rows are + * the sidebar's (`Channel`), so pressing and holding one (or right-clicking it) pins, renames or + * deletes it there as well. + * + * Not virtualized, as the sidebar is not: rows off screen are skipped by `content-visibility`, and + * older ones are read a page at a time as the list is scrolled to its end. + */ +function ConversationsPage() { + const emphasis = useMessageListEmphasis(); + const [view] = useConversationView(); + const channels = useInfiniteQuery(channelListQueryOptions()); + const delegating = + useQuery(delegatingConversationsQueryOptions()).data ?? NONE_DELEGATING; + const [search, setSearch] = useState(""); + const debouncedTerm = normalizeChannelSearch( + useDebounced(search, SEARCH_DEBOUNCE_MS), + ); + const term = normalizeChannelSearch(search); + const searching = term.length > 0; + const searchable = isChannelSearchable(term); + const rows = pinnedFirst(channels.data ?? []); + const shell = nativeShell() !== null; + + return ( + + {/* + * Beside the account in the native shell, the icon alone, named for a screen reader: the + * words and the avatar do not both fit beside the title on a phone. + */} + {shell ? ( + + ) : ( + + )} + +
+ } + title="Conversations" + > + {/* Nothing to search before there is a list: the box comes with it. */} + {channels.data && channels.data.length > 0 ? ( +
+ + + + setSearch(event.target.value)} + placeholder="Search conversations" + value={search} + /> + + {searching ? ( +

+ {searchable ? SEARCH_SCOPE : SEARCH_HINT} +

+ ) : null} +
+ ) : null} + {searching ? ( + searchable ? ( + + ) : null + ) : channels.isPending ? null : channels.data === undefined ? ( + // Only when nothing ever loaded: a failed refetch keeps the list it had. +
+

+ {loadFailure( + channels.error, + "Couldn't load your conversations. Try again in a moment.", + )} +

+ +
+ ) : rows.length === 0 ? ( + } + size="sm" + variant="outline" + > + + New conversation + + } + icon={IconMessage} + title="No conversations yet" + > + Start a conversation with a Bot and it shows up here. + + ) : ( + <> + + + {rows.map((channel, index) => ( + 0} + emphasis={emphasis} + key={channel.id} + layout="page" + view={view} + /> + ))} + + + + + )} + + ); +} diff --git a/app/src/routes/_authed/_app/group/$channelId.tsx b/app/src/routes/_authed/_app/group/$channelId.tsx index cf66d9bf9c..a066b64d0a 100644 --- a/app/src/routes/_authed/_app/group/$channelId.tsx +++ b/app/src/routes/_authed/_app/group/$channelId.tsx @@ -12,6 +12,7 @@ import { ChannelAvatar } from "@/components/channels/avatar"; import { GroupChat } from "@/components/channels/group-chat"; import { GroupPeopleButton } from "@/components/channels/group-people"; import { DetailPanel } from "@/components/layout/detail-panel"; +import { ShellBackButton } from "@/components/layout/native-shell-back"; import { SidebarToggle } from "@/components/layout/sidebar-toggle"; import { useMarkOpenChannelRead } from "@/lib/channels/mark-read"; import { channelQueryOptions } from "@/lib/channels/queries"; @@ -93,6 +94,7 @@ function GroupBody({ data-slot="conversation-header" > + {name ?? "Group"} diff --git a/app/src/routes/_authed/_app/index.tsx b/app/src/routes/_authed/_app/index.tsx index 9241ee60df..92cb0b3720 100644 --- a/app/src/routes/_authed/_app/index.tsx +++ b/app/src/routes/_authed/_app/index.tsx @@ -20,6 +20,7 @@ import { ModelPicker } from "@/components/channels/composer/model-picker"; import { WorkingNow } from "@/components/channels/working-now"; import { BusinessLink } from "@/components/edition/business-link"; import { HomeField, useHomeIntro } from "@/components/home/home-field"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; import { SidebarToggleBar } from "@/components/layout/sidebar-toggle"; import { StarterSuggestions } from "@/components/starter-tour/starter-suggestions"; import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty"; @@ -53,6 +54,7 @@ import { } from "@/lib/load-failure"; import { modelCatalogueQueryOptions } from "@/lib/models/queries"; import { usePickedBotModel } from "@/lib/models/run-model"; +import { nativeShell } from "@/lib/native-shell/shell"; import { newId } from "@/lib/new-id"; import { takeInvitationLink } from "@/lib/organizations/invitation-link"; import { useAnyBotSkillCommands } from "@/lib/plugins/skill-commands"; @@ -349,6 +351,8 @@ function RouteComponent() {
+ {/* Only inside the phone app's native shell, which has no sidebar. */} +
{/* @@ -434,7 +438,8 @@ function RouteComponent() { ...(restored.files ? { initialFiles: restored.files } : {}), } : asked - ? { initialValue: asked, autoFocus: true } + ? // Not in the phone app: a keyboard over the first screen, unasked for. + { initialValue: asked, autoFocus: nativeShell() === null } : {})} onSubmit={(draft) => send(draft)} /> diff --git a/app/src/routes/_authed/admin/route.tsx b/app/src/routes/_authed/admin/route.tsx index 50bd72abe9..57b65e0415 100644 --- a/app/src/routes/_authed/admin/route.tsx +++ b/app/src/routes/_authed/admin/route.tsx @@ -1,9 +1,17 @@ -import { createFileRoute, Outlet, redirect } from "@tanstack/react-router"; +import { + createFileRoute, + Outlet, + useRouterState, + redirect, +} from "@tanstack/react-router"; import { AdminSidebar } from "@/components/admin/admin-sidebar"; import { ConnectionBanner } from "@/components/layout/connection-banner"; +import { NativeShellPanel } from "@/components/layout/native-shell-frame"; +import { DefaultPageBackProvider } from "@/components/layout/page-shell"; import { PlanBanner } from "@/components/layout/plan-banner"; import { SidebarShell } from "@/components/layout/sidebar-shell"; import { SidebarInset } from "@/components/ui/sidebar"; +import { nativeShell } from "@/lib/native-shell/shell"; import { BotListScopeProvider } from "@/lib/agents/list-scope"; import { isOrganizationAdmin } from "@/lib/auth/roles"; import { deploymentCapabilitiesQueryOptions } from "@/lib/deployment/queries"; @@ -33,6 +41,32 @@ export const Route = createFileRoute("/_authed/admin")({ }); function RouteComponent() { + const pathname = useRouterState({ + select: (state) => state.location.pathname, + }); + /* + * Inside the phone app's native shell, no sidebar (`NativeShellPanel`). Admin's first page lists + * every Admin page already, and every other page leads back to it. + */ + if (nativeShell()) { + return ( + + + + + + + + + + ); + } return ( // The same inset panel as the app's shell; see `_app.tsx`. diff --git a/app/src/routes/_authed/settings/index.tsx b/app/src/routes/_authed/settings/index.tsx index 6053425f65..194d1b5663 100644 --- a/app/src/routes/_authed/settings/index.tsx +++ b/app/src/routes/_authed/settings/index.tsx @@ -9,6 +9,7 @@ import { CompanySignInSection } from "@/components/settings/company-sign-in"; import { DeleteAccountSection } from "@/components/settings/delete-account"; import { MessageListPreference } from "@/components/settings/message-list-preference"; import { NameRow } from "@/components/settings/profile"; +import { SettingsPageRows } from "@/components/settings/settings-pages"; import { StandingInstructionsRow } from "@/components/settings/standing-instructions"; import { StarOnGitHubButton } from "@/components/settings/star-on-github"; import { ThemeRow } from "@/components/settings/theme-row"; @@ -70,6 +71,8 @@ function RouteComponent() { description="Set your name, how OpenBot looks, and the instructions every Bot follows." title="General" > + {/* Only inside the phone app's native shell, which has no sidebar: Settings' other pages. */} + {/* * What OpenBot and every Bot know of the person, first: their name and how they want things done. Both are free * text, so both are a summary that opens a dialog. diff --git a/app/src/routes/_authed/settings/route.tsx b/app/src/routes/_authed/settings/route.tsx index 57e53c39d9..baaf421c37 100644 --- a/app/src/routes/_authed/settings/route.tsx +++ b/app/src/routes/_authed/settings/route.tsx @@ -1,15 +1,46 @@ -import { createFileRoute, Outlet } from "@tanstack/react-router"; +import { + createFileRoute, + Outlet, + useRouterState, +} from "@tanstack/react-router"; import { ConnectionBanner } from "@/components/layout/connection-banner"; +import { NativeShellPanel } from "@/components/layout/native-shell-frame"; +import { DefaultPageBackProvider } from "@/components/layout/page-shell"; import { PlanBanner } from "@/components/layout/plan-banner"; import { SidebarShell } from "@/components/layout/sidebar-shell"; import { SettingsSidebar } from "@/components/settings/settings-sidebar"; import { SidebarInset } from "@/components/ui/sidebar"; +import { nativeShell } from "@/lib/native-shell/shell"; export const Route = createFileRoute("/_authed/settings")({ component: RouteComponent, }); function RouteComponent() { + const pathname = useRouterState({ + select: (state) => state.location.pathname, + }); + /* + * Inside the phone app's native shell, no sidebar (`NativeShellPanel`). General lists the other + * pages instead (`SettingsPageRows`), and every other page leads back to it. + */ + if (nativeShell()) { + return ( + + + + + + + + ); + } return ( // The same inset panel as the app's shell; see `_app.tsx`. diff --git a/app/src/routes/sign.tsx b/app/src/routes/sign.tsx index 4c7d75db44..a6ad357bf7 100644 --- a/app/src/routes/sign.tsx +++ b/app/src/routes/sign.tsx @@ -7,6 +7,7 @@ import { CLOUD_SIGN_IN_TITLE, CloudSignIn, } from "@/components/auth/cloud-sign-in"; +import { NativeSignedOut } from "@/components/auth/native-signed-out"; import { ProviderLogo } from "@/components/auth/provider-logo"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; @@ -18,7 +19,10 @@ import { } from "@/lib/auth/client"; import { resumeUrlFor, + type ShellReturnSearch, + shellHandoffPathFor, signInReturnPath, + signInReturnUrlFor, verifierPathFor, } from "@/lib/auth/resume"; import { @@ -29,6 +33,7 @@ import { import { appConfig } from "@/lib/generated/application-config"; import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; import { EASE_OUT } from "@/lib/motion"; +import { nativeShell } from "@/lib/native-shell/shell"; import { inNoOrganization } from "@/lib/organizations/in-no-organization"; import { searchText, searchTextEntry } from "@/lib/search-text"; import { cn } from "@/lib/utils"; @@ -72,14 +77,25 @@ export const Route = createFileRoute("/sign")({ * `?next=` is the page the signed-in gate sent somebody here from, which sign-in brings them back * to. Kept only when it is a path on this app (`signInReturnPath`); anything else is dropped here, * and they land on home as before. + * + * `shell_challenge`, `shell_platform` and `shell_callback` are what the server hands a phone app's + * sign-in sheet landing here (`shellHandoffPathFor`): values too, checked before any is used. */ validateSearch: ( search: Record, - ): { flow_id?: string; next?: string } => { + ): { + flow_id?: string; + next?: string; + "native-sign-in"?: string; + } & ShellReturnSearch => { const next = signInReturnPath(searchText(search.next)); return { ...searchTextEntry("flow_id", search.flow_id), ...(next ? { next } : {}), + ...searchTextEntry("native-sign-in", search["native-sign-in"]), + ...searchTextEntry("shell_challenge", search.shell_challenge), + ...searchTextEntry("shell_platform", search.shell_platform), + ...searchTextEntry("shell_callback", search.shell_callback), }; }, beforeLoad: async ({ context, search }) => { @@ -102,7 +118,9 @@ export const Route = createFileRoute("/sign")({ * the verifier was ever made. `reloadDocument` makes this a document navigation, which is * the only kind that leaves the app and therefore the only kind that arrives. */ - const verifier = verifierPathFor(search.flow_id); + // A phone app's sign-in sheet goes on to the hand-off, the same way and for the same reason. + const onward = + shellHandoffPathFor(search) ?? verifierPathFor(search.flow_id); // Signed in already (in another tab, say): straight on to the page they were sent here from. const next = signInReturnPath(search.next); /* @@ -111,25 +129,51 @@ export const Route = createFileRoute("/sign")({ * verifier's is above. Only that path: any other `next` stays a page of this app. */ const windowSignIn = next !== undefined && startsWindowSignIn(next); - throw verifier - ? redirect({ href: verifier, reloadDocument: true }) + throw onward + ? redirect({ href: onward, reloadDocument: true }) : windowSignIn ? redirect({ href: next, reloadDocument: true, replace: true }) : next ? redirect({ href: next, replace: true }) : redirect({ to: "/" }); } + // The phone app's native shell signs in on its own screen: nothing of this one is drawn. + if (signsInNatively(search)) return; // Loaded here so the screen paints with its buttons rather than painting empty and then // growing them, which reads as "no providers" for exactly as long as the request takes. await context.queryClient.ensureQueryData(authProvidersQueryOptions()); }, - component: SignScreen, + component: SignRoute, }); +/** + * Whether the phone app's native shell shows the sign-in, on its own screen, in place of this one + * (`components/auth/native-signed-out.tsx`). `?native-sign-in=web` asks for this screen anyway: the + * shell's way back to the web sign-in when its own can't be used. + */ +export function signsInNatively(search: { + "native-sign-in"?: string; +}): boolean { + return nativeShell() !== null && search["native-sign-in"] !== "web"; +} + +function SignRoute() { + const search = Route.useSearch(); + return signsInNatively(search) ? : ; +} + function SignScreen() { - const { flow_id: flowId, next } = Route.useSearch(); - // Where every way in below brings the browser back: the app's flow, else the page they were on, else home. - const resumeUrl = resumeUrlFor(window.location.origin, flowId, next); + const search = Route.useSearch(); + // Where every way in below brings the browser back: the phone app's hand-off, else the app's + // flow, else the page they were on, else home. + const returnUrl = signInReturnUrlFor(window.location.origin, search); + // Without the phone app's hand-off: where OpenBot Desktop's window and OpenBot Cloud's own screen + // come back to. Neither is a phone app's sign-in sheet, so the sheet's values never move them. + const resumeUrl = resumeUrlFor( + window.location.origin, + search.flow_id, + search.next, + ); // 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); @@ -166,7 +210,7 @@ function SignScreen() { try { if (await signedInInBrowser()) return; - await signInWithEmailDomain(email, undefined, resumeUrl); + await signInWithEmailDomain(email, undefined, returnUrl); } catch (caughtError) { setError( failureOf( @@ -184,7 +228,7 @@ function SignScreen() { try { if (await signedInInBrowser()) return; - await signInWith(provider, undefined, resumeUrl); + await signInWith(provider, undefined, returnUrl); } catch (caughtError) { setError( failureOf( diff --git a/app/src/styles.css b/app/src/styles.css index 6313565694..534b95eccb 100644 --- a/app/src/styles.css +++ b/app/src/styles.css @@ -856,3 +856,116 @@ html[data-from-setup] body { opacity: 0; } } + +/* + * Inside the phone app's native shell (lib/native-shell, marked by index.html before the first + * paint). The page is the web view between the shell's status bar and its tab bar, so it does not + * bounce past its edges like a web page: a bounce would show the web view's backing behind the + * page. Pressing and holding still selects text, in a message as anywhere. + */ +html[data-native-shell], +html[data-native-shell] body { + overscroll-behavior: none; +} + +/* + * A field under 16px makes iOS zoom the page in when it is focused, and the page stays zoomed after. + * In the shell every field a person types in is 16px, whatever its own class says; none in the app + * is drawn larger. A placeholder too long for a narrow phone ends in an ellipsis rather than + * mid-word, and the To field's long one keeps the smaller size it had: a placeholder's size does not + * make iOS zoom, only the field's own. + * + * This is on purpose the kind of rule theme.css warns about ("THERE IS DELIBERATELY NO `button, + * input, textarea, select { font: inherit }` HERE"): unlayered, on input, textarea and select, so it + * outranks every `text-*` on a field. There such a rule disabled the sizes by accident, everywhere. + * Here it is meant, and only under `html[data-native-shell]`, where one size for every field is the + * point. + */ +html[data-native-shell] +:is( + input:not( + [type="checkbox"], + [type="radio"], + [type="range"], + [type="color"], + [type="file"] + ), + textarea, + select +) { + font-size: 1rem; + text-overflow: ellipsis; +} +html[data-native-shell] [data-slot="combobox-chip-input"]::placeholder { + font-size: 0.875rem; +} + +/* + * The sidebar's panels as the phone app's Chats and Bots tabs (components/layout/native-shell-panels): + * the same rows as on Desktop, at a thumb's height, 44px. Only the sizes change: the title's buttons, + * the search fields, each conversation's row, each Bot's row with its + and its fold caret, and Show + * more under a Bot. + */ +html[data-native-shell] [data-slot="section-panel-header"] { + height: 3.5rem; +} +html[data-native-shell] + [data-slot="section-panel-header"] + [data-slot="button"] { + width: 2.75rem; + height: 2.75rem; +} +html[data-native-shell] [data-slot="section-panel"] [data-slot="input-group"] { + height: 2.75rem; +} +html[data-native-shell] + [data-slot="section-panel"] + :is(a[href^="/channel/"], a[href^="/group/"]) { + min-height: 2.75rem; +} +html[data-native-shell] + [data-slot="section-panel"] + [data-slot="bot-row"] + > * + > a, +html[data-native-shell] + [data-slot="section-panel"] + [data-slot="bot-row"] + > :is(a, button) { + height: 2.75rem; +} +/* The 2 squares at the row's end: the + that starts a conversation with the Bot, and the caret. */ +html[data-native-shell] + [data-slot="section-panel"] + [data-slot="bot-row"] + > :is(a, button) { + width: 2.75rem; +} +html[data-native-shell] [data-slot="section-panel"] [data-bot-list-action] { + height: 2.75rem; +} +html[data-native-shell] + [data-slot="section-panel"] + [data-slot="sidebar-menu-button"] { + height: 2.75rem; +} + +/* + * In the phone app, what opens over the page (a menu, a popover, a sheet, a dialog) leaves at once + * when it closes, without its fade: the app takes a picture of the page as a navigation starts, for + * its swipe back, and a menu half faded would be in it (lib/native-shell/use-tab-navigation.ts). + */ +html[data-native-shell] [data-base-ui-portal] [data-closed] { + animation: none; + transition: none; +} + +/* + * In the phone app a code block in a reply keeps Copy and loses Download: Streamdown builds that + * file in the page, and the app's web view cannot save one yet. A table's Download is left out the + * same way, where it is drawn (lib/markdown-table.tsx). A file sent in a conversation, a generated + * picture and an artifact's export come from the server, and the app saves those. + */ +html[data-native-shell] [data-streamdown="code-block-download-button"] { + display: none; +} diff --git a/app/tests/audit-export-truncated.test.tsx b/app/tests/audit-export-truncated.test.tsx index 349a8f10b4..96bf7c43de 100644 --- a/app/tests/audit-export-truncated.test.tsx +++ b/app/tests/audit-export-truncated.test.tsx @@ -9,6 +9,7 @@ import { } from "@tanstack/react-router"; import { cleanup, fireEvent, render } from "@testing-library/react"; import { agentKeys } from "@/lib/agents/queries"; +import { forgetNativeShellForTests } from "@/lib/native-shell/shell"; import { Route as AuditRoute } from "@/routes/_authed/admin/audit"; import { AUDIT_EXPORT_PATH, auditExport } from "./audit-api"; import { seedAuditPage } from "./seed-audit-page"; @@ -23,17 +24,7 @@ afterEach(() => { afterAll(() => GlobalRegistrator.unregister()); -async function exportWith(truncatedAt?: number) { - const asked: URL[] = []; - globalThis.fetch = (async (input: RequestInfo | URL) => { - const url = new URL(String(input), "http://127.0.0.1"); - asked.push(url); - if (url.pathname === AUDIT_EXPORT_PATH) - return auditExport("id\n", truncatedAt); - return Response.json({ error: "not served" }, { status: 404 }); - }) as unknown as typeof fetch; - URL.createObjectURL = () => "blob:audit"; - URL.revokeObjectURL = () => {}; +function renderAudit() { const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Number.POSITIVE_INFINITY }, @@ -45,11 +36,25 @@ async function exportWith(truncatedAt?: number) { routeTree: createRootRoute({ component: AuditRoute.options.component }), history: createMemoryHistory({ initialEntries: ["/"] }), }); - const view = render( + return render( , ); +} + +async function exportWith(truncatedAt?: number) { + const asked: URL[] = []; + globalThis.fetch = (async (input: RequestInfo | URL) => { + const url = new URL(String(input), "http://127.0.0.1"); + asked.push(url); + if (url.pathname === AUDIT_EXPORT_PATH) + return auditExport("id\n", truncatedAt); + return Response.json({ error: "not served" }, { status: 404 }); + }) as unknown as typeof fetch; + URL.createObjectURL = () => "blob:audit"; + URL.revokeObjectURL = () => {}; + const view = renderAudit(); fireEvent.click(await view.findByText("Export CSV")); await view.findByText("Export CSV"); return Object.assign(view, { asked }); @@ -70,3 +75,30 @@ test("a whole export says nothing extra", async () => { expect(exported?.searchParams.has("cursor")).toBe(false); expect(exported?.searchParams.has("format")).toBe(false); }); + +/* + * The phone app's web view doesn't take a download yet, and this one is a `blob:` address let go at + * once, which it could not fetch later: no Export there. + */ +test("inside the phone app's native shell there is no Export", async () => { + const page = window as { __OPENBOT_NATIVE_SHELL__?: unknown }; + page.__OPENBOT_NATIVE_SHELL__ = { + platform: "android", + version: "0.1", + bridge: 1, + }; + forgetNativeShellForTests(); + globalThis.fetch = (async () => + Response.json( + { error: "not served" }, + { status: 404 }, + )) as unknown as typeof fetch; + try { + const view = renderAudit(); + await view.findByText("Refresh"); + expect(view.queryByText("Export CSV")).toBeNull(); + } finally { + delete page.__OPENBOT_NATIVE_SHELL__; + forgetNativeShellForTests(); + } +}); diff --git a/app/tests/channel-join-replay.test.tsx b/app/tests/channel-join-replay.test.tsx index 019719e084..4a313080b9 100644 --- a/app/tests/channel-join-replay.test.tsx +++ b/app/tests/channel-join-replay.test.tsx @@ -21,6 +21,7 @@ import { } from "@/lib/channels/queries"; import { applyChannelEvent } from "@/lib/channels/use-channel-events"; import { forgetAgents } from "@/lib/copilot/kept-agents"; +import { forgetNativeShellForTests } from "@/lib/native-shell/shell"; import { queryClient } from "@/query-client"; import { Route as ChannelRoute } from "@/routes/_authed/_app/channel/$channelId"; import { MY_CAPABILITIES_PATH } from "./admin-settings-api"; @@ -631,3 +632,52 @@ test("the answers a step was still waiting on reach a conversation opened part w LOOKUPS.map((_, index) => answerOf(index)), ); }, 15_000); + +/* + * Opening a conversation puts the caret in its message box in a browser and in OpenBot Desktop. In + * the phone app's native shell it does not: the keyboard would come up by itself over what the + * person came to read. + */ +test("opening a conversation focuses its message box, except inside the phone app's shell", async () => { + const turn = [ + ...askPersonReplayStart(channel.threadId), + ...askPersonReplayEnd(channel.threadId), + ]; + script = async (send) => { + sending(send, turn); + send("replay_complete", { latestEventId: `event-${turn.length - 1}` }); + send("stream_idle", { latestEventId: `event-${turn.length - 1}` }); + }; + history = () => NativeResponse.json({ messages: askPersonStored("asked") }); + roster("2026-11-08T00:00:01.000Z", "Ask me which colour of apple"); + + const inBrowser = opened(); + const box = await inBrowser.findByRole("textbox", { name: "Message" }); + await waitFor(() => expect(document.activeElement).toBe(box), { + timeout: 4000, + }); + cleanup(); + (document.activeElement as HTMLElement | null)?.blur(); + + const page = window as { __OPENBOT_NATIVE_SHELL__?: unknown }; + page.__OPENBOT_NATIVE_SHELL__ = { + platform: "ios", + version: "0.1", + bridge: 1, + }; + forgetNativeShellForTests(); + try { + const inShell = opened(); + await inShell.findByRole("textbox", { name: "Message" }); + await waitFor( + () => + expect(shown(inShell.container, ASKED_TEXT)).toBeGreaterThanOrEqual(1), + { timeout: 4000 }, + ); + await sleep(300); + expect(document.activeElement).toBe(document.body); + } finally { + delete page.__OPENBOT_NATIVE_SHELL__; + forgetNativeShellForTests(); + } +}, 20_000); diff --git a/app/tests/home-fallback-routing.fixture.tsx b/app/tests/home-fallback-routing.fixture.tsx index bcb728e6da..5f19ac89ba 100644 --- a/app/tests/home-fallback-routing.fixture.tsx +++ b/app/tests/home-fallback-routing.fixture.tsx @@ -1,5 +1,20 @@ -import { mock } from "bun:test"; +import { afterAll, mock } from "bun:test"; +import * as SidebarToggleModule from "@/components/layout/sidebar-toggle"; + +/* + * Home's top bar, stood in for by a marker in the files that import this. Only the bar: everything + * else the module exports stays real. And only for the file that imported it: bun keeps a module + * mock for the rest of the process, so a later file in the same run would otherwise draw this stub + * wherever it drew the real bar (the native shell's band test did, in CI's shard 2). The real module + * goes back when the file is done. + */ +const real = { ...SidebarToggleModule }; mock.module("@/components/layout/sidebar-toggle", () => ({ + ...real, SidebarToggleBar: () =>
, })); + +afterAll(() => { + mock.module("@/components/layout/sidebar-toggle", () => real); +}); diff --git a/app/tests/native-shell-app.test.tsx b/app/tests/native-shell-app.test.tsx new file mode 100644 index 0000000000..7e43c48909 --- /dev/null +++ b/app/tests/native-shell-app.test.tsx @@ -0,0 +1,1453 @@ +import { + afterAll, + afterEach, + beforeAll, + beforeEach, + describe, + expect, + test, +} from "bun:test"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; +import { + createMemoryHistory, + createRootRoute, + createRoute, + createRouter, + Outlet, + RouterProvider, +} from "@tanstack/react-router"; +import { + act, + cleanup, + fireEvent, + render, + waitFor, + within, +} from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; +import { type ReactNode, useEffect, useState } from "react"; +import { NativeSignedOut } from "@/components/auth/native-signed-out"; +import { SEARCH_HINT } from "@/components/app-sidebar/conversations-panel"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; +import { ShellBackButton } from "@/components/layout/native-shell-back"; +import { ShellBots } from "@/components/layout/native-shell-panels"; +import { PageShell } from "@/components/layout/page-shell"; +import { SidebarToggleBar } from "@/components/layout/sidebar-toggle"; +import { + NOTIFY_PROMPT_KEY, + NotifyPrompt, +} from "@/components/notifications/notify-prompt"; +import { useDesktopOpenRequests } from "@/lib/desktop/open-requests"; +import { + forgetReadyForTests, + useNativeShellRouteReports, +} from "@/lib/native-shell/route-reports"; +import { forgetNativeShellForTests } from "@/lib/native-shell/shell"; +import { + forgetTabStacksForTests, + useTabNavigation, +} from "@/lib/native-shell/use-tab-navigation"; +import { + notificationPermission, + refreshNotificationPermission, +} from "@/lib/notifications/permission"; +import { webPushSupport } from "@/lib/web-push/browser"; +import { queryClient } from "@/query-client"; +import { Route as AppRoute } from "@/routes/_authed/_app"; +import { Route as ConversationsRoute } from "@/routes/_authed/_app/conversations"; +import { signsInNatively } from "@/routes/sign"; +import { ME_PATH, meBody } from "./accounts-api"; +import { DEPLOYMENT_PATH } from "./admin-settings-api"; +import { + CONVERSATIONS_PATH, + conversationPage, + TASKS_PATH, +} from "./conversations-api"; +import { settleReactWork } from "./settle-react-work"; + +/* + * The web app inside the phone app's native shell (lib/native-shell): the page alone, with no + * sidebar; the Conversations page the shell's Conversations tab opens; the quiet sign-in page; and + * what the shell is told. And outside the shell, the app as it was. + */ + +beforeAll(() => GlobalRegistrator.register({ url: "http://127.0.0.1:3010/" })); +afterAll(async () => { + cleanup(); + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +const originalFetch = global.fetch; +const originalSocket = globalThis.WebSocket; +afterEach(() => { + cleanup(); + global.fetch = originalFetch; + globalThis.WebSocket = originalSocket; + inShell(false); +}); + +/** Puts the page in the shell (as its injected object says) or takes it out. */ +function inShell(on: boolean) { + const page = window as { + __OPENBOT_NATIVE_SHELL__?: unknown; + webkit?: unknown; + }; + if (on) + page.__OPENBOT_NATIVE_SHELL__ = { + platform: "ios", + version: "0.1", + bridge: 1, + }; + else delete page.__OPENBOT_NATIVE_SHELL__; + delete page.webkit; + forgetNativeShellForTests(); + forgetReadyForTests(); + forgetTabStacksForTests(); +} + +/** What the shell is told, as its iOS handler receives it. */ +function listen(): unknown[] { + const heard: unknown[] = []; + (window as { webkit?: unknown }).webkit = { + messageHandlers: { + openbotShell: { postMessage: (message: unknown) => heard.push(message) }, + }, + }; + return heard; +} + +let sockets = 0; +class QuietSocket { + onopen: unknown = null; + onclose: unknown = null; + onmessage: unknown = null; + onerror: unknown = null; + constructor() { + sockets += 1; + } + close() {} + send() {} +} + +const now = "2026-11-27T10:00:00.000Z"; +function channel( + id: string, + summary: string, + { pinned = false, unread = false } = {}, +) { + return { + id, + name: "Research Bot", + agentIds: ["b-1"], + threadId: `t-${id}`, + active: true, + lastMessageAt: now, + summary, + opening: null, + lastMessage: summary, + lastMessageAgentId: "b-1", + createdAt: now, + pinned, + lastReadAt: unread ? "2026-11-27T09:00:00.000Z" : now, + canRename: true, + task: false, + work: [], + }; +} + +/** The API, answering the conversation list with `list` (a status for a failure, or never). */ +function serve(list: ReturnType[] | number | "never") { + global.fetch = (async (input: RequestInfo | URL) => { + const url = new URL(String(input), "http://127.0.0.1:3010"); + const path = url.pathname; + if (path === CONVERSATIONS_PATH) { + if (list === "never") return new Promise(() => {}); + if (typeof list === "number") + return Response.json( + { detail: "Couldn't load your conversations." }, + { status: list }, + ); + // A search (`q`) answers the conversations whose words have it, as the server does. + const q = url.searchParams.get("q")?.toLowerCase(); + return Response.json( + conversationPage( + q ? list.filter((c) => c.summary.toLowerCase().includes(q)) : list, + ), + ); + } + if (path === ME_PATH) + return Response.json( + meBody({ + user: { id: "sam", name: "Sam Rivera", email: "sam@example.com" }, + }), + ); + if (path === DEPLOYMENT_PATH) + return Response.json({ edition: "team", localEvaluation: false }); + if (path === TASKS_PATH) + return Response.json({ tasks: [], nextCursor: null }); + return Response.json({ detail: "not served" }, { status: 404 }); + }) as typeof fetch; + sockets = 0; + globalThis.WebSocket = QuietSocket as unknown as typeof WebSocket; +} + +function Reports({ children }: { children: ReactNode }) { + useNativeShellRouteReports(); + useDesktopOpenRequests(); + useTabNavigation(); + return children; +} + +/** The app's `_authed/_app` frame around a few pages, as the real route tree nests them. */ +function renderApp(path: string) { + const AppFrame = AppRoute.options.component as () => ReactNode; + const Conversations = ConversationsRoute.options.component as () => ReactNode; + const rootRoute = createRootRoute({ + component: () => ( + + + + ), + }); + const appRoute = createRoute({ + id: "_app", + getParentRoute: () => rootRoute, + component: AppFrame, + }); + const page = (routePath: string, body: () => ReactNode) => + createRoute({ + path: routePath, + getParentRoute: () => appRoute, + component: body, + }); + const router = createRouter({ + routeTree: rootRoute.addChildren([ + appRoute.addChildren([ + page("/", () => ( + <> + + {/* Beside the bar, not in it: another file stands a stub in for the bar (mock.module). */} + +

Home

+ + )), + page("/bots", () => ( + +

The roster

+
+ )), + page("/conversations", Conversations), + page("/channel/$channelId", () => ( + <> + +

A conversation

+ + )), + page("/channel/new", () =>

New conversation

), + ]), + ]), + history: createMemoryHistory({ initialEntries: [path] }), + }); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const view = render( + + + , + ); + return { view, router }; +} + +describe("the frame", () => { + test("in the shell: no sidebar, no toggle and no empty band, and the one socket still opens", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + expect(view.container.querySelector('[data-slot="sidebar"]')).toBeNull(); + expect( + view.container.querySelector('[data-slot="sidebar-wrapper"]'), + ).toBeNull(); + expect(view.queryByRole("button", { name: /sidebar/i })).toBeNull(); + // The band that held the toggle is gone, not left empty. + expect(view.container.querySelector(".h-12")).toBeNull(); + await waitFor(() => expect(sockets).toBeGreaterThan(0)); + }); + + test("a skin's frame with no sidebar, outside the shell, keeps the 48px band", () => { + inShell(false); + // No sidebar provider, as in OpenDuet's and OpenDots' frames. + const view = render( + + At the end + , + ); + const band = view.container.querySelector(".h-12"); + expect(band).not.toBeNull(); + expect(band?.textContent).toContain("At the end"); + }); + + test("in the shell, a configuration screen keeps no bar above its title", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/bots"); + await view.findByRole("heading", { name: "Bots" }); + expect(view.container.querySelector(".h-14")).toBeNull(); + }); + + test("in the shell, the sidebar's account menu sits at the top right, named Account", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + const account = view.getByRole("button", { name: "Account" }); + await userEvent + .setup({ document: view.container.ownerDocument }) + .click(account); + const settings = await within(document.body).findByRole("menuitem", { + name: "Settings", + }); + expect(settings.getAttribute("href")).toBe("/settings"); + expect( + within(document.body).getByRole("menuitem", { name: "Sign out" }), + ).toBeTruthy(); + // The web view doesn't take a download yet, so nothing in the menu offers one. The row lives + // under Help, so Help is opened: closed, it would be missing for anybody. + await userEvent + .setup({ document: view.container.ownerDocument }) + .click(within(document.body).getByRole("menuitem", { name: "Help" })); + const help = await waitFor(() => { + const content = document.body.querySelector( + '[data-slot="dropdown-menu-sub-content"]', + ); + if (!content) throw new Error("Help has not opened"); + return content as HTMLElement; + }); + expect( + within(help).queryByRole("menuitem", { + name: "Get troubleshooting logs", + }), + ).toBeNull(); + // Help is never empty there: Report a bug is offered in the phone app as anywhere, at a + // thumb's height, and says which page the person was on. + const report = within(help).getByRole("menuitem", { name: "Report a bug" }); + expect(report.getAttribute("href")).toBe("/report-a-bug?from=%2F"); + expect(report.className).toContain("py-3"); + }); + + test("in the shell, the account button and its menu's rows are a thumb's size", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + const account = view.getByRole("button", { name: "Account" }); + // 44px square, the whole tap target iOS asks for, round a 36px avatar. + expect(account.className).toContain("size-11"); + expect(account.querySelector(".size-9")).not.toBeNull(); + await userEvent + .setup({ document: view.container.ownerDocument }) + .click(account); + const settings = await within(document.body).findByRole("menuitem", { + name: "Settings", + }); + expect(settings.className).toContain("py-3"); + // Help, and Sign out after it, as well. + for (const name of ["Help", "Sign out"]) { + expect( + within(document.body).getByRole("menuitem", { name }).className, + ).toContain("py-3"); + } + }); + + test("in a browser, the sidebar is there as before", async () => { + inShell(false); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + expect( + view.container.querySelector('[data-slot="sidebar-wrapper"]'), + ).not.toBeNull(); + expect( + view.container.querySelector('[data-slot="sidebar"]'), + ).not.toBeNull(); + // The account is the sidebar's, named for the person: none is added at the top of the page. + expect(view.queryByRole("button", { name: "Account" })).toBeNull(); + }); +}); + +/** Where each "New conversation" on the page goes. */ +function newConversationLinks(container: HTMLElement): (string | null)[] { + return [...container.querySelectorAll("a")] + .filter( + (link) => + (link.getAttribute("aria-label") ?? link.textContent?.trim()) === + "New conversation", + ) + .map((link) => link.getAttribute("href")); +} + +describe("the Conversations page", () => { + // Drawn in the shell, so the sidebar's own list of the same conversations is not on screen too. + beforeEach(() => inShell(true)); + + test("pinned first, unread marked", async () => { + serve([ + channel("c-1", "Quarterly forecast"), + channel("c-2", "Competitor pricing notes", { + pinned: true, + unread: true, + }), + channel("c-3", "Trip to Lisbon"), + ]); + const { view } = renderApp("/conversations"); + await view.findByText("Trip to Lisbon"); + const titles = [ + ...view.container.querySelectorAll('a[href^="/channel/c-"]'), + ].map((row) => row.textContent ?? ""); + expect( + titles.map((text) => text.match(/Competitor|Quarterly|Lisbon/)?.[0]), + ).toEqual(["Competitor", "Quarterly", "Lisbon"]); + expect( + view.container.querySelectorAll('[data-slot="unread-dot"]'), + ).toHaveLength(1); + expect( + view.getByRole("textbox", { name: "Search conversations" }), + ).toBeTruthy(); + expect(newConversationLinks(view.container)).toEqual(["/channel/new"]); + }); + + test("while it loads, nothing: no empty state, no error", async () => { + serve("never"); + const { view } = renderApp("/conversations"); + await view.findByRole("heading", { name: "Conversations" }); + expect(view.queryByText("No conversations yet")).toBeNull(); + expect(view.queryByRole("alert")).toBeNull(); + }); + + test("with none, says how one arrives; New conversation is in the title's row", async () => { + serve([]); + const { view } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + // The panel's own, as on Desktop. + expect(newConversationLinks(view.container)).toEqual(["/channel/new"]); + }); + + test("a failure says so and offers Try again", async () => { + serve(500); + const { view } = renderApp("/conversations"); + const alert = await view.findByRole("alert"); + expect(alert.textContent).toContain("Couldn't load your conversations."); + expect(view.getByRole("button", { name: "Try again" })).toBeTruthy(); + }); + + test("it is the sidebar's Conversations panel, with the account in its title's row", async () => { + serve([channel("c-1", "Quarterly forecast")]); + const { view } = renderApp("/conversations"); + await view.findByText("Quarterly forecast"); + const panel = view.container.querySelector('[data-slot="section-panel"]'); + expect(panel).not.toBeNull(); + const header = panel?.querySelector('[data-slot="section-panel-header"]'); + expect(header?.textContent).toContain("Conversations"); + // New conversation, then the account, at the end of the title's row. + const buttons = [ + ...(header as HTMLElement).querySelectorAll("a, button"), + ].map((button) => button.getAttribute("aria-label")); + expect(buttons).toEqual(["New conversation", "Account"]); + expect( + within(header as HTMLElement).getByRole("button", { name: "Account" }), + ).toBeTruthy(); + }); +}); + +describe("what the shell is told", () => { + test("ready once, then each page's path, tab and sign-in, and openbot:open moves the page", async () => { + inShell(true); + const heard = listen(); + serve([]); + const { view, router } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + for (const path of ["/bots", "/conversations", "/", "/"]) { + const event = new CustomEvent("openbot:open", { + detail: { path }, + cancelable: true, + }); + act(() => { + window.dispatchEvent(event); + }); + expect(event.defaultPrevented).toBe(true); + await waitFor(() => expect(router.state.location.pathname).toBe(path)); + } + await waitFor(() => + expect(heard).toEqual([ + { type: "ready" }, + { + type: "route", + path: "/", + tab: "home", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + { + type: "route", + path: "/bots", + tab: "bots", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + { + type: "route", + path: "/conversations", + tab: "conversations", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + { + type: "route", + path: "/", + tab: "home", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + ]), + ); + // In the shell the tabs' stacks are the history: the web view's own stays one entry long. + expect(router.history.length).toBe(1); + }); + + test("outside the shell, nothing", async () => { + inShell(false); + const heard = listen(); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + expect(heard).toEqual([]); + }); +}); + +describe("the tabs' stacks in the shell", () => { + /** The shell tapping a tab: `openbot:open` with the tab's root. */ + function tap(path: string) { + act(() => { + window.dispatchEvent( + new CustomEvent("openbot:open", { detail: { path }, cancelable: true }), + ); + }); + } + const routes = (heard: unknown[]) => + heard.filter((m) => (m as { type: string }).type === "route") as { + path: string; + tab: string | null; + canGoBack: boolean; + }[]; + + test("Back in a conversation goes back to where it was opened, and the page keeps its tab", async () => { + inShell(true); + const heard = listen(); + serve([channel("c-1", "Quarterly forecast")]); + const { view, router } = renderApp("/bots"); + await view.findByText("The roster"); + await act(() => + router.navigate({ + to: "/channel/$channelId", + params: { channelId: "c-1" }, + }), + ); + await view.findByText("A conversation"); + // Opened from Bots: in Bots' stack, with somewhere to go back to. + await waitFor(() => + expect(routes(heard).at(-1)).toMatchObject({ + path: "/channel/c-1", + tab: "bots", + canGoBack: true, + }), + ); + fireEvent.click(view.getByRole("button", { name: "Back" })); + await waitFor(() => expect(router.state.location.pathname).toBe("/bots")); + await waitFor(() => + expect(routes(heard).at(-1)).toMatchObject({ + path: "/bots", + tab: "bots", + canGoBack: false, + depth: 1, + scrollRestored: true, + }), + ); + // In the shell the stacks are the history: the web view's own stays one entry long. + expect(router.history.length).toBe(1); + }); + + test("opened cold, a conversation's Back goes to the Chats list", async () => { + inShell(true); + serve([]); + const { view, router } = renderApp("/channel/c-9"); + await view.findByText("A conversation"); + fireEvent.click(view.getByRole("button", { name: "Back" })); + await waitFor(() => + expect(router.state.location.pathname).toBe("/conversations"), + ); + }); + + test("switching away and back shows the tab where it was; tapping the current tab pops it to its root", async () => { + inShell(true); + serve([]); + const { view, router } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + await act(() => + router.navigate({ + to: "/channel/$channelId", + params: { channelId: "c-2" }, + }), + ); + await view.findByText("A conversation"); + tap("/bots"); + await view.findByText("The roster"); + tap("/conversations"); + await waitFor(() => + expect(router.state.location.pathname).toBe("/channel/c-2"), + ); + tap("/conversations"); + await waitFor(() => + expect(router.state.location.pathname).toBe("/conversations"), + ); + }); + + test("openbot:back pops the current tab, and does nothing at its root", async () => { + inShell(true); + serve([]); + const { view, router } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + await act(() => + router.navigate({ + to: "/channel/$channelId", + params: { channelId: "c-3" }, + }), + ); + await view.findByText("A conversation"); + act(() => { + window.dispatchEvent(new CustomEvent("openbot:back")); + }); + await waitFor(() => expect(router.state.location.pathname).toBe("/")); + act(() => { + window.dispatchEvent(new CustomEvent("openbot:back")); + }); + await settleReactWork(); + expect(router.state.location.pathname).toBe("/"); + }); + + test("outside the shell, navigation is the browser's history as before, and no Back is drawn", async () => { + inShell(false); + serve([]); + const { view, router } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + await act(() => + router.navigate({ + to: "/channel/$channelId", + params: { channelId: "c-4" }, + }), + ); + await view.findByText("A conversation"); + expect(router.history.length).toBe(2); + expect(view.queryByRole("button", { name: "Back" })).toBeNull(); + act(() => { + window.dispatchEvent(new CustomEvent("openbot:back")); + }); + await settleReactWork(); + expect(router.state.location.pathname).toBe("/channel/c-4"); + }); +}); + +describe("the app's swipe back", () => { + type Heard = { + type: string; + direction?: string; + depth?: number; + path?: string; + at: number; + showing: string; + /** Whether a menu was drawn over the page when the app heard it. */ + menu: boolean; + }; + /** + * What the app hears, with when and what the page was showing at that moment. On iOS through its + * handler, which answers `will-navigate` with `openbot:navigate-ok` when `answer` is set; on Android + * through its object, which never answers. + */ + function hear(platform: "ios" | "android", answer = false): Heard[] { + const heard: Heard[] = []; + const page = window as unknown as Record; + page.__OPENBOT_NATIVE_SHELL__ = { platform, version: "0.1", bridge: 1 }; + forgetNativeShellForTests(); + const take = (message: Record) => { + heard.push({ + ...(message as { type: string }), + at: performance.now(), + showing: document.body.textContent ?? "", + menu: document.querySelector('[role="menu"]') !== null, + }); + if (answer && message.type === "will-navigate") + window.dispatchEvent(new CustomEvent("openbot:navigate-ok")); + }; + if (platform === "ios") + page.webkit = { + messageHandlers: { openbotShell: { postMessage: take } }, + }; + else + page.OpenBotShellAndroid = { + postMessage: (json: string) => take(JSON.parse(json)), + }; + return heard; + } + afterEach(() => { + delete (window as unknown as Record).OpenBotShellAndroid; + }); + const of = (heard: Heard[], type: string) => + heard.filter((message) => message.type === type); + const toConversation = (channelId: string, replace = false) => + ({ to: "/channel/$channelId", params: { channelId }, replace }) as const; + + test("depth: 1 at a root, deeper as pages open, back down on Back, kept by a replace, a tab's own", async () => { + inShell(true); + const heard = hear("ios", true); + serve([]); + const { view, router } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + await act(() => router.navigate(toConversation("c-1"))); + await view.findByText("A conversation"); + await act(() => router.navigate(toConversation("c-2", true))); + await waitFor(() => + expect(router.state.location.pathname).toBe("/channel/c-2"), + ); + act(() => { + window.dispatchEvent( + new CustomEvent("openbot:open", { + detail: { path: "/bots" }, + cancelable: true, + }), + ); + }); + await view.findByText("The roster"); + await waitFor(() => + expect( + of(heard, "route").map(({ path, depth }) => [path, depth]), + ).toEqual([ + ["/conversations", 1], + ["/channel/c-1", 2], + ["/channel/c-2", 2], + ["/bots", 1], + ]), + ); + }); + + test("a cold deep link starts at depth 2", async () => { + inShell(true); + const heard = hear("ios"); + serve([]); + const { view } = renderApp("/channel/c-9"); + await view.findByText("A conversation"); + await waitFor(() => + expect(of(heard, "route")[0]).toMatchObject({ + path: "/channel/c-9", + depth: 2, + canGoBack: true, + }), + ); + }); + + test("will-navigate comes before the page changes, with its direction and where it leads", async () => { + inShell(true); + const heard = hear("ios", true); + serve([]); + const { view, router } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + await act(() => router.navigate(toConversation("c-1"))); + await view.findByText("A conversation"); + fireEvent.click(view.getByRole("button", { name: "Back" })); + await view.findByText("No conversations yet"); + const announced = of(heard, "will-navigate"); + expect( + announced.map(({ direction, depth }) => ({ direction, depth })), + ).toEqual([ + { direction: "push", depth: 2 }, + { direction: "back", depth: 1 }, + ]); + // Each while the page it leaves is still on screen. + expect(announced[0]?.showing).toContain("No conversations yet"); + expect(announced[1]?.showing).toContain("A conversation"); + }); + + test("on iOS with no answer the page goes ahead after 120 ms; with an answer, at once", async () => { + inShell(true); + const silent = hear("ios"); + serve([]); + const first = renderApp("/conversations"); + await first.view.findByText("No conversations yet"); + const asked = performance.now(); + await act(() => first.router.navigate(toConversation("c-1"))); + await first.view.findByText("A conversation"); + const waited = performance.now() - asked; + expect(of(silent, "will-navigate")).toHaveLength(1); + expect(waited).toBeGreaterThanOrEqual(110); + expect(waited).toBeLessThan(1000); + cleanup(); + + inShell(true); + const answering = hear("ios", true); + serve([]); + const second = renderApp("/conversations"); + await second.view.findByText("No conversations yet"); + const askedAgain = performance.now(); + await act(() => second.router.navigate(toConversation("c-1"))); + await second.view.findByText("A conversation"); + expect(of(answering, "will-navigate")).toHaveLength(1); + expect(performance.now() - askedAgain).toBeLessThan(110); + }); + + test("on Android it is said and never waited for", async () => { + inShell(true); + const heard = hear("android"); + serve([]); + const { view, router } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + const asked = performance.now(); + await act(() => router.navigate(toConversation("c-1"))); + await view.findByText("A conversation"); + expect(performance.now() - asked).toBeLessThan(110); + expect(of(heard, "will-navigate")).toHaveLength(1); + }); + + test("in a browser nothing is said or waited for", async () => { + inShell(false); + const heard = listen(); + serve([]); + const { view, router } = renderApp("/conversations"); + await waitFor(() => + expect(view.getAllByText("No conversations yet").length).toBeGreaterThan( + 0, + ), + ); + await act(() => router.navigate(toConversation("c-1"))); + await view.findByText("A conversation"); + expect(heard).toEqual([]); + }); + + test("a page opened from the Account menu is announced only once the menu is gone", async () => { + inShell(true); + const heard = hear("ios", true); + serve([]); + const { view, router } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + await userEvent + .setup({ document: view.container.ownerDocument }) + .click(view.getByRole("button", { name: "Account" })); + const settings = await within(document.body).findByRole("menuitem", { + name: "Settings", + }); + expect(document.querySelector('[role="menu"]')).not.toBeNull(); + await userEvent + .setup({ document: view.container.ownerDocument }) + .click(settings); + await waitFor(() => + expect(router.state.location.pathname).toBe("/settings"), + ); + const announced = of(heard, "will-navigate"); + expect(announced).toHaveLength(1); + // The app's picture of the page has no menu open in it. + expect(announced[0]?.menu).toBe(false); + }); + + test("Back the app asks for is not announced back to it", async () => { + inShell(true); + const heard = hear("ios", true); + serve([]); + const { view, router } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + await act(() => router.navigate(toConversation("c-1"))); + await view.findByText("A conversation"); + act(() => { + window.dispatchEvent(new CustomEvent("openbot:back")); + }); + await view.findByText("No conversations yet"); + expect( + of(heard, "will-navigate").map(({ direction }) => direction), + ).toEqual(["push"]); + await waitFor(() => + expect(of(heard, "route").at(-1)).toMatchObject({ + path: "/conversations", + depth: 1, + scrollRestored: true, + }), + ); + }); +}); + +describe("a Back while a list's scroll is being put back", () => { + /** Frames the page asks for, run only when the test says: the scroll's restore is held meanwhile. */ + let frames: FrameRequestCallback[] = []; + let realFrame: typeof window.requestAnimationFrame; + beforeEach(() => { + frames = []; + realFrame = window.requestAnimationFrame; + window.requestAnimationFrame = ((callback: FrameRequestCallback) => { + frames.push(callback); + return frames.length; + }) as typeof window.requestAnimationFrame; + }); + afterEach(() => { + window.requestAnimationFrame = realFrame; + }); + const runFrames = () => + act(() => { + const now = frames; + frames = []; + for (const frame of now) frame(performance.now()); + }); + const routesOf = (heard: unknown[]) => + heard + .filter((m) => (m as { type: string }).type === "route") + .map((m) => (m as { path: string; depth: number }).path); + const back = () => + act(() => { + window.dispatchEvent(new CustomEvent("openbot:back")); + }); + + /** The Chats list scrolled down, then a conversation opened from it, then Back: the hold. */ + async function holding() { + inShell(true); + const heard = listen(); + serve( + Array.from({ length: 30 }, (_, index) => + channel(`c-${index}`, `Conversation ${index}`), + ), + ); + const { view, router } = renderApp("/conversations"); + await view.findByText("Conversation 29"); + const list = view.container.querySelector( + '[data-slot="section-panel"] [data-slot="sidebar-content"]', + ) as HTMLElement; + list.scrollTop = 400; + await act(() => + router.navigate({ + to: "/channel/$channelId", + params: { channelId: "c-3" }, + }), + ); + await view.findByText("A conversation"); + await back(); + await view.findByText("Conversation 29"); + await settleReactWork(); + return { heard, view, router }; + } + + test("a second Back at the root does nothing, and the held route goes out once", async () => { + const { heard, router } = await holding(); + // Held: the list has not been put back yet, so the root's route has not been said. + expect(routesOf(heard).at(-1)).toBe("/channel/c-3"); + // Android's Back still read canGoBack true and asks again. + await back(); + await settleReactWork(); + expect(router.state.location.pathname).toBe("/conversations"); + await runFrames(); + await waitFor(() => + expect(routesOf(heard)).toEqual([ + "/conversations", + "/channel/c-3", + "/conversations", + ]), + ); + await runFrames(); + await settleReactWork(); + expect( + routesOf(heard).filter((path) => path === "/conversations"), + ).toHaveLength(2); + }); + + test("a tab tap during the hold is not lost: the tapped tab is shown and reported", async () => { + const { heard, view, router } = await holding(); + act(() => { + window.dispatchEvent( + new CustomEvent("openbot:open", { + detail: { path: "/bots" }, + cancelable: true, + }), + ); + }); + await view.findByText("The roster"); + await runFrames(); + await waitFor(() => expect(routesOf(heard).at(-1)).toBe("/bots")); + expect(router.state.location.pathname).toBe("/bots"); + }); +}); + +describe("the Bots tab in the shell", () => { + test("is the sidebar's Bots panel, with New Bot and the account in its title's row", async () => { + inShell(true); + serve([]); + const rootRoute = createRootRoute({ + component: () => ( + {}} onCreated={() => {}} /> + ), + }); + const router = createRouter({ + routeTree: rootRoute, + history: createMemoryHistory({ initialEntries: ["/bots"] }), + }); + const client = new QueryClient({ + defaultOptions: { queries: { retry: false } }, + }); + const view = render( + + + , + ); + const header = await waitFor(() => { + const found = view.container.querySelector( + '[data-slot="section-panel-header"]', + ); + expect(found).not.toBeNull(); + return found as HTMLElement; + }); + expect(header.textContent).toContain("Bots"); + expect( + within(header).getByRole("button", { name: "New Bot" }), + ).toBeTruthy(); + expect( + within(header).getByRole("button", { name: "Account" }), + ).toBeTruthy(); + expect(view.getByRole("textbox", { name: "Search Bots" })).toBeTruthy(); + }); +}); + +/** + * The search box of the Chats tab, or of the page in a browser: 1 character says how many it takes, + * a match lists it, no match says so, and clearing the box puts the whole list back. + */ +async function searchesInPlace( + view: ReturnType, + field: HTMLElement, + empty: string, +) { + // Only where the box is: in a browser the sidebar's own list stays beside the page. + const scope = field.closest( + '[data-slot="section-panel"], main', + ) as HTMLElement; + const user = userEvent.setup({ document: view.container.ownerDocument }); + // Emptied a key at a time, as a person does. + const clear = () => + user.type( + field, + "{Backspace}".repeat((field as HTMLInputElement).value.length), + ); + await user.type(field, "q"); + await within(scope).findByText(SEARCH_HINT); + await clear(); + await user.type(field, "forecast"); + // The match, and only it: the list under the box is the search's results. + await within(scope).findByText("Quarterly forecast"); + expect(within(scope).queryByText("Trip to Lisbon")).toBeNull(); + await clear(); + await user.type(field, "zebra"); + await within(scope).findByText(empty); + await clear(); + await within(scope).findByText("Trip to Lisbon"); +} + +describe("searching the Chats tab", () => { + test("its own field, not focused as the tab opens, searches in place", async () => { + inShell(true); + serve([ + channel("c-1", "Quarterly forecast"), + channel("c-2", "Trip to Lisbon"), + ]); + const { view } = renderApp("/conversations"); + await view.findByText("Trip to Lisbon"); + const field = view.getByRole("textbox", { name: "Search conversations" }); + // The keyboard does not come up by itself as the tab opens. + expect(document.activeElement).not.toBe(field); + await searchesInPlace(view, field, "No conversations match your search"); + }); +}); + +describe("the Conversations page outside the shell", () => { + test("has its own search, which searches in place as the panel's does", async () => { + inShell(false); + serve([ + channel("c-1", "Quarterly forecast"), + channel("c-2", "Trip to Lisbon"), + ]); + const { view } = renderApp("/conversations"); + const field = await view.findByPlaceholderText("Search conversations"); + // The page's, not the panel's beside it ("Search…"). + expect(field.closest('[data-slot="section-panel"]')).toBeNull(); + await searchesInPlace(view, field, "No conversations match your search"); + }); + + test("is the page it was: its own title, beside the sidebar's panel", async () => { + inShell(false); + serve([channel("c-1", "Quarterly forecast")]); + const { view } = renderApp("/conversations"); + await waitFor(() => + expect(view.getAllByText("Quarterly forecast").length).toBeGreaterThan(0), + ); + // The page's own h1, as before; the panel's title is the sidebar's h2. + expect( + view + .getAllByRole("heading", { name: "Conversations" }) + .map((heading) => heading.tagName), + ).toContain("H1"); + }); +}); + +describe("when the shell hears ready", () => { + /** Something a test settles by hand: a route's data, or a page's own. */ + function later() { + let settle = () => {}; + const promise = new Promise((resolve) => { + settle = resolve; + }); + return { promise, settle }; + } + + /** + * A small app with the shell's reports at its root: `/` waits on `data` before it draws, showing + * a skeleton meanwhile, then draws `page`; `/next` draws at once; `/sign` is the shell's quiet page. + */ + function renderReady( + path: string, + { data, page }: { data?: Promise; page?: () => ReactNode } = {}, + ) { + const rootRoute = createRootRoute({ + component: () => ( + + + + ), + }); + const routes = [ + createRoute({ + path: "/", + getParentRoute: () => rootRoute, + loader: () => data, + pendingMs: 0, + pendingComponent: () =>
, + component: page ?? (() =>

Drawn

), + }), + createRoute({ + path: "/next", + getParentRoute: () => rootRoute, + component: () =>

Next

, + }), + createRoute({ + path: "/sign", + getParentRoute: () => rootRoute, + component: NativeSignedOut, + }), + ]; + const router = createRouter({ + routeTree: rootRoute.addChildren(routes), + history: createMemoryHistory({ initialEntries: [path] }), + }); + const view = render(); + return { view, router }; + } + + const readies = (heard: unknown[]) => + heard.filter((message) => (message as { type: string }).type === "ready"); + + test("not while the first page is still loading; once it has drawn, ready, then its route", async () => { + inShell(true); + const heard = listen(); + const data = later(); + const { view } = renderReady("/", { data: data.promise }); + await settleReactWork(); + await act(() => new Promise((resolve) => setTimeout(resolve, 50))); + // The skeleton is up; nothing a person can read, and no route reported ahead of ready. + expect(view.queryByText("Drawn")).toBeNull(); + expect(heard).toEqual([]); + await act(async () => data.settle()); + await view.findByText("Drawn"); + await waitFor(() => + expect(heard).toEqual([ + { type: "ready" }, + { + type: "route", + path: "/", + tab: "home", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + ]), + ); + }); + + test("a page whose own data is still loading is not drawn until its words are", async () => { + inShell(true); + const heard = listen(); + const own = later(); + function Page() { + const [loaded, setLoaded] = useState(false); + useEffect(() => { + void own.promise.then(() => setLoaded(true)); + }, []); + return loaded ? ( +

Three conversations

+ ) : ( + Loading + ); + } + const { view } = renderReady("/", { page: Page }); + await waitFor(() => expect(view.getByText("Loading")).toBeTruthy()); + await act(() => new Promise((resolve) => setTimeout(resolve, 50))); + expect(heard).toEqual([]); + await act(async () => own.settle()); + await view.findByText("Three conversations"); + await waitFor(() => expect(heard[0]).toEqual({ type: "ready" })); + expect(heard[1]).toEqual({ + type: "route", + path: "/", + tab: "home", + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }); + }); + + test("once only, however many pages follow", async () => { + inShell(true); + const heard = listen(); + const { view, router } = renderReady("/"); + await view.findByText("Drawn"); + await act(() => router.navigate({ to: "/next" as never })); + await view.findByText("Next"); + await act(() => router.navigate({ to: "/" })); + await view.findByText("Drawn"); + // Ready, then a route for each page, each change of page announced first. + await waitFor(() => + expect( + heard.filter((m) => (m as { type: string }).type === "route"), + ).toHaveLength(3), + ); + expect(readies(heard)).toHaveLength(1); + expect(heard[0]).toEqual({ type: "ready" }); + expect(heard.map((m) => (m as { type: string }).type)).toEqual([ + "ready", + "route", + "will-navigate", + "route", + "will-navigate", + "route", + ]); + }); + + test("signed out: the quiet page counts as drawn, and signed-out follows ready", async () => { + inShell(true); + const heard = listen(); + const { view } = renderReady("/sign"); + await waitFor(() => + expect( + view.container.querySelector('[data-slot="native-signed-out"]'), + ).not.toBeNull(), + ); + await waitFor(() => + expect(heard).toEqual([ + { type: "ready" }, + { type: "signed-out" }, + { + type: "route", + path: "/sign", + tab: null, + signedIn: false, + canGoBack: false, + depth: 1, + scrollRestored: true, + }, + ]), + ); + }); + + test("a page that never draws still hands the screen over, after the fallback", async () => { + inShell(true); + forgetReadyForTests(60); + const heard = listen(); + renderReady("/", { data: new Promise(() => {}) }); + await act(() => new Promise((resolve) => setTimeout(resolve, 20))); + expect(heard).toEqual([]); + await waitFor(() => expect(heard).toEqual([{ type: "ready" }])); + }); +}); + +describe("signed out in the shell", () => { + test("the quiet page tells the shell, and offers no way in of its own", () => { + inShell(true); + const heard = listen(); + const view = render(); + expect(heard).toEqual([{ type: "signed-out" }]); + expect(view.queryByRole("button")).toBeNull(); + expect(view.queryByRole("link")).toBeNull(); + }); + + test("only ?native-sign-in=web asks for the web sign-in, and only in the shell", () => { + inShell(true); + expect(signsInNatively({})).toBe(true); + expect(signsInNatively({ "native-sign-in": "failed" })).toBe(true); + expect(signsInNatively({ "native-sign-in": "web" })).toBe(false); + inShell(false); + expect(signsInNatively({})).toBe(false); + }); +}); + +describe("the keyboard in the shell", () => { + /** A field outside the pages, so it is still there after a move and only the shell can blur it. */ + function focusedField() { + const field = document.createElement("input"); + field.type = "text"; + document.body.append(field); + field.focus(); + expect(document.activeElement).toBe(field); + return field; + } + + test("moving to another page puts the keyboard away; a change of search alone does not", async () => { + inShell(true); + serve([]); + const { view, router } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + const field = focusedField(); + try { + await act(() => + router.navigate({ to: "/", search: { q: "x" } as never }), + ); + expect(document.activeElement).toBe(field); + await act(() => router.navigate({ to: "/bots" })); + await view.findByRole("heading", { name: "Bots" }); + expect(document.activeElement).not.toBe(field); + } finally { + field.remove(); + } + }); + + test("opening the Account menu takes the focus off a field", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/"); + await view.findByRole("heading", { name: "Home" }); + const field = focusedField(); + try { + // A click alone, which moves no focus itself: what moves it is the menu opening. + fireEvent.click(view.getByRole("button", { name: "Account" })); + await within(document.body).findByRole("menuitem", { name: "Settings" }); + await waitFor(() => expect(document.activeElement).not.toBe(field)); + } finally { + field.remove(); + } + }); + + test("a tap on a part of the page that does nothing puts the keyboard away; a tap on a button keeps it", async () => { + inShell(true); + serve([]); + const { view } = renderApp("/"); + const heading = await view.findByRole("heading", { name: "Home" }); + const field = focusedField(); + const tap = (target: Element) => { + fireEvent.pointerDown(target, { clientX: 20, clientY: 20 }); + fireEvent.pointerUp(target, { clientX: 22, clientY: 21 }); + }; + try { + tap(view.getByRole("button", { name: "Account" })); + expect(document.activeElement).toBe(field); + // A drag that scrolls is cancelled by the browser, not a tap. + fireEvent.pointerDown(heading, { clientX: 20, clientY: 20 }); + fireEvent.pointerCancel(heading); + fireEvent.pointerUp(heading, { clientX: 20, clientY: 200 }); + expect(document.activeElement).toBe(field); + tap(heading); + expect(document.activeElement).not.toBe(field); + } finally { + field.remove(); + } + }); + + test("outside the shell the page leaves the keyboard alone", async () => { + serve([]); + const { view } = renderApp("/"); + const heading = await view.findByRole("heading", { name: "Home" }); + const field = focusedField(); + try { + fireEvent.pointerDown(heading, { clientX: 20, clientY: 20 }); + fireEvent.pointerUp(heading, { clientX: 20, clientY: 20 }); + expect(document.activeElement).toBe(field); + } finally { + field.remove(); + } + }); +}); + +describe("what makes no sense in the shell", () => { + test("no Home Screen push and no notifications of the page's own", () => { + inShell(true); + expect(webPushSupport()).toBe("unsupported"); + expect(notificationPermission()).toBe("unsupported"); + }); + + /* + * A browser with push, as Chrome is: a service worker, the Push API and notifications not yet + * asked. The conversation's offer shows there, so the shell's half proves something. + */ + function pushAvailable() { + const page = window as unknown as Record; + page.PushManager = class {}; + page.Notification = { permission: "default" }; + Object.defineProperty(navigator, "serviceWorker", { + configurable: true, + value: { getRegistration: async () => undefined }, + }); + return () => { + delete page.PushManager; + delete page.Notification; + delete (navigator as unknown as Record).serviceWorker; + }; + } + + test("a conversation offers notifications in a browser with push, and never in the shell", async () => { + const restore = pushAvailable(); + try { + localStorage.removeItem(NOTIFY_PROMPT_KEY); + for (const shell of [false, true]) { + inShell(shell); + refreshNotificationPermission(); + const view = render( + + + , + ); + if (shell) { + await settleReactWork(); + expect(view.queryByText("Enable notifications")).toBeNull(); + expect( + view.container.querySelector("[data-notify-prompt]"), + ).toBeNull(); + } else { + expect(await view.findByText("Enable notifications")).toBeTruthy(); + } + cleanup(); + queryClient.clear(); + } + } finally { + restore(); + refreshNotificationPermission(); + } + }); +}); diff --git a/app/tests/native-shell-reply-downloads.test.tsx b/app/tests/native-shell-reply-downloads.test.tsx new file mode 100644 index 0000000000..a7ba309405 --- /dev/null +++ b/app/tests/native-shell-reply-downloads.test.tsx @@ -0,0 +1,136 @@ +import { + afterAll, + afterEach, + beforeAll, + describe, + expect, + test, +} from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import type { Message } from "@ag-ui/core"; +import { GlobalRegistrator } from "@happy-dom/global-registrator"; +import { cleanup, render, waitFor, within } from "@testing-library/react"; +import { ChatTranscript } from "@/components/channels/chat-transcript"; +import { forgetNativeShellForTests } from "@/lib/native-shell/shell"; +import { settleReactWork } from "./settle-react-work"; + +/** + * A reply in the phone app offers no Download that its web view cannot do. + * + * A table's Download and a code block's Download build their file in the page and hand the browser + * a `blob:` address. Read on 2026-12-02 in the phone apps' own code: the iOS app saves only a file + * from the app's own server address and drops this one without a word, and the Android app answers + * "This file can't be saved from the app." So in the app's shell neither is drawn, as "Get + * troubleshooting logs" and Audit's Export are not, and Copy stays on both. + * + * The table is OpenBot's own (`lib/markdown-table.tsx`) and is read here as drawn. The code block is + * Streamdown's, hidden by a rule in `styles.css` that is read here as written. + */ + +const REPLY = [ + "Here you go.", + "", + "```python", + "print('hi')", + "```", + "", + "| Item | Count |", + "|---|---|", + "| Apples | 3 |", +].join("\n"); + +type ShellWindow = { __OPENBOT_NATIVE_SHELL__?: unknown }; + +beforeAll(() => { + GlobalRegistrator.register({ url: "http://localhost/" }); +}); + +/** Puts the page in a phone app's shell (as its injected object says) or takes it out. */ +function inShell(platform: "ios" | "android" | null) { + const page = window as ShellWindow; + if (platform) + page.__OPENBOT_NATIVE_SHELL__ = { platform, version: "0.1", bridge: 1 }; + else delete page.__OPENBOT_NATIVE_SHELL__; + forgetNativeShellForTests(); +} + +afterEach(() => { + cleanup(); + inShell(null); +}); + +afterAll(async () => { + await settleReactWork(); + GlobalRegistrator.unregister(); +}); + +async function drawnReply() { + const messages: Message[] = [ + { id: "u1", role: "user", content: "A table and some code, please." }, + { id: "a1", role: "assistant", content: REPLY }, + ]; + const view = render(); + await waitFor(() => { + expect(view.container.querySelectorAll("tbody tr")).toHaveLength(1); + }); + await within(document.body).findByTitle("Copy table"); + return view; +} + +describe("a table in a reply", () => { + test("in a browser, offers Download beside Copy", async () => { + inShell(null); + await drawnReply(); + expect(within(document.body).queryByTitle("Download table")).not.toBeNull(); + expect(within(document.body).queryByTitle("Copy table")).not.toBeNull(); + }); + + for (const platform of ["ios", "android"] as const) + test(`in the ${platform} app, offers Copy and no Download`, async () => { + inShell(platform); + await drawnReply(); + expect(within(document.body).queryByTitle("Download table")).toBeNull(); + expect(within(document.body).queryByTitle("Copy table")).not.toBeNull(); + expect( + within(document.body).queryByTitle("View fullscreen"), + ).not.toBeNull(); + }); +}); + +describe("a code block in a reply", () => { + const styles = readFileSync( + join(import.meta.dir, "..", "src", "styles.css"), + "utf8", + ); + + // The mark the rule below goes by. A Streamdown that renamed it would leave the button drawn. + test("draws its Download as the button the shell's rule names", async () => { + const view = await drawnReply(); + const download = view.container.querySelector( + '[data-streamdown="code-block-download-button"]', + ); + expect(download).not.toBeNull(); + expect(download?.getAttribute("title")).toBe("Download file"); + expect( + view.container.querySelector( + '[data-streamdown="code-block-copy-button"]', + ), + ).not.toBeNull(); + }); + + test("has that button hidden in the shell and nowhere else, and Copy left alone", () => { + const selector = + 'html[data-native-shell] [data-streamdown="code-block-download-button"]'; + const at = styles.indexOf(`${selector} {`); + expect(at).toBeGreaterThan(-1); + expect(styles.slice(at, styles.indexOf("}", at))).toContain( + "display: none;", + ); + // Only under the shell's mark: a browser keeps the button. + expect( + styles.split('[data-streamdown="code-block-download-button"]'), + ).toHaveLength(2); + expect(styles).not.toContain("code-block-copy-button"); + }); +}); diff --git a/app/tests/native-shell-tab-stacks.test.ts b/app/tests/native-shell-tab-stacks.test.ts new file mode 100644 index 0000000000..610c4ce2d8 --- /dev/null +++ b/app/tests/native-shell-tab-stacks.test.ts @@ -0,0 +1,172 @@ +import { describe, expect, test } from "bun:test"; +import { + canGoBack, + cleared, + goBack, + pushLocation, + replaceLocation, + stacksFor, + type TabStacks, + tapTab, + topOf, +} from "../src/lib/native-shell/tab-stacks"; + +/* + * Where each of the phone app's tabs is (lib/native-shell/tab-stacks.ts): one stack per tab, as a + * native tab bar app keeps them. + */ + +/** Runs steps from a cold start at `start`, each a push, a tap, a replace or Back. */ +function walk( + start: string, + steps: (["push" | "tap" | "replace", string] | ["back"])[], +): { state: TabStacks; scrolled: boolean } { + let state = stacksFor(start); + let scrolled = false; + for (const [kind, location] of steps) { + const next = + kind === "back" + ? goBack(state) + : kind === "tap" + ? tapTab(state, location) + : kind === "push" + ? pushLocation(state, location) + : replaceLocation(state, location); + expect(next.show).toBe(topOf(next.state)); + scrolled = next.scrollToTop === true; + state = next.state; + } + return { state, scrolled }; +} + +describe("the phone app's tab stacks", () => { + test("going deeper pushes onto the current tab's stack, and the page belongs to that tab", () => { + const { state } = walk("/bots", [["push", "/channel/c-hiring"]]); + expect(state.current).toBe("bots"); + expect(state.stacks.bots).toEqual(["/bots", "/channel/c-hiring"]); + // The Chats tab is where it was: at its root. + expect(state.stacks.conversations).toEqual(["/conversations"]); + expect(canGoBack(state)).toBe(true); + }); + + test("a conversation sent from Home is in Home's stack", () => { + const { state } = walk("/", [ + ["push", "/start/s-1"], + ["replace", "/channel/c-new"], + ]); + expect(state.current).toBe("home"); + expect(state.stacks.home).toEqual(["/", "/channel/c-new"]); + }); + + test("switching away and back shows the tab exactly where it was left", () => { + const { state } = walk("/conversations", [ + ["push", "/channel/c-forecast"], + ["tap", "/bots"], + ["push", "/bots/research-bot"], + ["tap", "/conversations"], + ]); + expect(state.current).toBe("conversations"); + expect(topOf(state)).toBe("/channel/c-forecast"); + // And Bots kept its own place. + expect(state.stacks.bots).toEqual(["/bots", "/bots/research-bot"]); + }); + + test("tapping the current tab pops it to its root; at its root, scrolls to the top", () => { + const popped = walk("/conversations", [ + ["push", "/channel/c-forecast"], + ["push", "/settings"], + ["tap", "/conversations"], + ]); + expect(popped.state.stacks.conversations).toEqual(["/conversations"]); + expect(topOf(popped.state)).toBe("/conversations"); + expect(popped.scrolled).toBe(false); + const atRoot = walk("/conversations", [["tap", "/conversations"]]); + expect(atRoot.scrolled).toBe(true); + expect(topOf(atRoot.state)).toBe("/conversations"); + }); + + test("Back pops only the current tab, never into another tab's pages", () => { + const { state } = walk("/conversations", [ + ["push", "/channel/c-forecast"], + ["tap", "/bots"], + ["push", "/bots/research-bot"], + ["back"], + ]); + expect(state.current).toBe("bots"); + expect(topOf(state)).toBe("/bots"); + const again = goBack(state); + // At Bots' root: nothing, and still Bots, not the conversation left open in Chats. + expect(again.state).toEqual(state); + expect(again.show).toBe("/bots"); + expect(canGoBack(again.state)).toBe(false); + }); + + test("at a root Back does nothing and canGoBack is false", () => { + for (const root of ["/conversations", "/", "/bots"]) { + const state = stacksFor(root); + expect(canGoBack(state)).toBe(false); + expect(goBack(state).state).toEqual(state); + } + }); + + test("a deep link builds its stack from the address, so Back has somewhere to go", () => { + expect(stacksFor("/channel/c-forecast").stacks.conversations).toEqual([ + "/conversations", + "/channel/c-forecast", + ]); + expect(stacksFor("/channel/c-forecast").current).toBe("conversations"); + expect(stacksFor("/bots/research-bot").stacks.bots).toEqual([ + "/bots", + "/bots/research-bot", + ]); + // A page no tab owns belongs to Home when nothing says otherwise. + const settings = stacksFor("/settings/notifications"); + expect(settings.current).toBe("home"); + expect(settings.stacks.home).toEqual(["/", "/settings/notifications"]); + expect(canGoBack(settings)).toBe(true); + // A root's search is kept: New Bot's sheet. + expect(stacksFor("/bots?new=true").stacks.bots).toEqual(["/bots?new=true"]); + }); + + test("a page opened from the Account menu goes onto the tab it was opened from", () => { + const { state } = walk("/bots", [ + ["push", "/settings"], + ["push", "/settings/notifications"], + ]); + expect(state.current).toBe("bots"); + expect(state.stacks.bots).toEqual([ + "/bots", + "/settings", + "/settings/notifications", + ]); + const back = goBack(goBack(state).state); + expect(topOf(back.state)).toBe("/bots"); + }); + + test("a search change replaces the top, and the same location again pushes nothing", () => { + const { state } = walk("/bots", [ + ["replace", "/bots?new=true"], + ["replace", "/bots"], + ["push", "/bots/research-bot"], + ["push", "/bots/research-bot"], + ]); + expect(state.stacks.bots).toEqual(["/bots", "/bots/research-bot"]); + }); + + test("signing out clears every stack", () => { + const { state } = walk("/conversations", [ + ["push", "/channel/c-forecast"], + ["tap", "/bots"], + ["push", "/bots/research-bot"], + ]); + expect(state.stacks.bots.length).toBe(2); + const empty = cleared(); + expect(empty.current).toBe("home"); + expect(empty.stacks).toEqual({ + conversations: ["/conversations"], + home: ["/"], + bots: ["/bots"], + }); + expect(canGoBack(empty)).toBe(false); + }); +}); diff --git a/app/tests/native-shell.test.ts b/app/tests/native-shell.test.ts new file mode 100644 index 0000000000..267ec5d085 --- /dev/null +++ b/app/tests/native-shell.test.ts @@ -0,0 +1,425 @@ +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { + type NativeTab, + postToShell, + type ShellMessage, + tabForPath, +} from "../src/lib/native-shell/bridge"; +import { + detectNativeShell, + NATIVE_SHELL_STORAGE_KEY, + type NativeShellEnvironment, +} from "../src/lib/native-shell/shell"; + +/* + * The phone app's native shell and the web app agree on a small contract (lib/native-shell): how the + * page knows it is in the shell, which of the shell's tabs a page belongs to, and how it tells the + * shell. index.html works out the same answer before the first paint, so the two are held together + * here case by case. + */ + +/** Where the phone apps' UI tests and the screenshot scripts open the app. */ +const LOCAL = "127.0.0.1"; +/** A real deployment, where the testing override must not count. */ +const PRODUCTION = "my.open.bot"; + +const IPHONE = + "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148"; + +function memoryStorage(initial: Record = {}) { + const values = new Map(Object.entries(initial)); + return { + values, + getItem: (key: string) => values.get(key) ?? null, + setItem: (key: string, value: string) => void values.set(key, value), + removeItem: (key: string) => void values.delete(key), + }; +} + +const html = readFileSync(join(import.meta.dir, "..", "index.html"), "utf8"); +const inline = html.slice( + html.indexOf(""), +); + +/** index.html's inline script, run against `environment`: what it marks, and the viewport it leaves. */ +function beforeFirstPaint(environment: NativeShellEnvironment) { + const dataset: Record = {}; + const viewport = { content: "width=device-width, initial-scale=1.0" }; + const window = { + location: { + search: environment.search, + hash: "", + pathname: "/", + hostname: environment.hostname, + }, + navigator: { userAgent: environment.userAgent }, + sessionStorage: environment.storage, + localStorage: { getItem: () => null }, + matchMedia: () => ({ matches: false }), + history: { state: null, replaceState() {} }, + __OPENBOT_NATIVE_SHELL__: environment.injected, + }; + const document = { + documentElement: { classList: { toggle() {} }, style: {}, dataset }, + querySelector: (selector: string) => + selector === 'meta[name="viewport"]' ? viewport : null, + }; + new Function("window", "document", inline)(window, document); + return { platform: dataset.nativeShell ?? null, viewport: viewport.content }; +} + +const CASES: { + name: string; + environment: () => NativeShellEnvironment; + platform: "ios" | "android" | "test" | null; +}[] = [ + { + name: "a plain browser", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: null, + }, + { + name: "what the shell injects", + environment: () => ({ + injected: { platform: "android", version: "0.1", bridge: 1 }, + userAgent: IPHONE, + search: "", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: "android", + }, + { + name: "something injected that is not the shell's", + environment: () => ({ + injected: { platform: "windows" }, + userAgent: IPHONE, + search: "", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: null, + }, + { + name: "the shell's user agent on iOS", + environment: () => ({ + injected: undefined, + userAgent: `${IPHONE} OpenBotShell-iOS/0.1`, + search: "", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: "ios", + }, + { + name: "the shell's user agent on Android", + environment: () => ({ + injected: undefined, + userAgent: "Mozilla/5.0 (Linux; Android 15) OpenBotShell-Android/0.1", + search: "", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: "android", + }, + { + name: "?native-shell=ios for testing", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: "test", + }, + { + name: "the override remembered by the tab", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "", + hostname: LOCAL, + storage: memoryStorage({ [NATIVE_SHELL_STORAGE_KEY]: "test" }), + }), + platform: "test", + }, + { + name: "?native-shell=off forgetting it", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=off", + hostname: LOCAL, + storage: memoryStorage({ [NATIVE_SHELL_STORAGE_KEY]: "test" }), + }), + platform: null, + }, + { + name: "?native-shell=off inside the real shell", + environment: () => ({ + injected: undefined, + userAgent: `${IPHONE} OpenBotShell-iOS/0.1`, + search: "?native-shell=off", + hostname: LOCAL, + storage: memoryStorage(), + }), + platform: "ios", + }, + { + name: "?native-shell=ios where storage throws", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: LOCAL, + storage: { + getItem: () => { + throw new Error("denied"); + }, + setItem: () => { + throw new Error("denied"); + }, + removeItem: () => { + throw new Error("denied"); + }, + }, + }), + platform: "test", + }, +]; + +CASES.push( + { + name: "?native-shell=ios on a production host", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: PRODUCTION, + storage: memoryStorage(), + }), + platform: null, + }, + { + name: "the override a tab remembered, on a production host", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "", + hostname: PRODUCTION, + storage: memoryStorage({ [NATIVE_SHELL_STORAGE_KEY]: "test" }), + }), + platform: null, + }, + { + name: "the shell's user agent on a production host", + environment: () => ({ + injected: undefined, + userAgent: `${IPHONE} OpenBotShell-iOS/0.1`, + search: "", + hostname: PRODUCTION, + storage: memoryStorage(), + }), + platform: "ios", + }, + { + name: "what the shell injects, on a production host", + environment: () => ({ + injected: { platform: "android", version: "0.1", bridge: 1 }, + userAgent: "Mozilla/5.0 (Linux; Android 15)", + search: "?native-shell=off", + hostname: PRODUCTION, + storage: memoryStorage(), + }), + platform: "android", + }, + { + name: "?native-shell=ios on a .localhost name", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: "openbot.localhost", + storage: memoryStorage(), + }), + platform: "test", + }, +); + +describe("which shell the page is in", () => { + for (const { name, environment, platform } of CASES) { + test(`${name}: ${platform ?? "none"}, the same before the first paint`, () => { + expect(detectNativeShell(environment())?.platform ?? null).toBe(platform); + const painted = beforeFirstPaint(environment()); + expect(painted.platform as string | null).toBe(platform); + // The viewport takes the whole web view in the shell, and is left alone in a browser. + expect(painted.viewport.includes("viewport-fit=cover")).toBe( + platform !== null, + ); + }); + } + + test("on a production host the override is not remembered, and off still forgets one kept from before", () => { + const storage = memoryStorage(); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: PRODUCTION, + storage, + }); + expect(storage.values.has(NATIVE_SHELL_STORAGE_KEY)).toBe(false); + storage.values.set(NATIVE_SHELL_STORAGE_KEY, "test"); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=off", + hostname: PRODUCTION, + storage, + }); + expect(storage.values.has(NATIVE_SHELL_STORAGE_KEY)).toBe(false); + }); + + test("a development build honours the override on any host", () => { + expect( + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: PRODUCTION, + dev: true, + storage: memoryStorage(), + })?.platform, + ).toBe("test"); + }); + + test("the override is remembered for the tab, and forgotten again", () => { + const storage = memoryStorage(); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + hostname: LOCAL, + storage, + }); + expect(storage.values.get(NATIVE_SHELL_STORAGE_KEY)).toBe("test"); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=off", + hostname: LOCAL, + storage, + }); + expect(storage.values.has(NATIVE_SHELL_STORAGE_KEY)).toBe(false); + }); +}); + +describe("which of the shell's tabs a page belongs to", () => { + const TABLE: [string, NativeTab | null][] = [ + ["/", "home"], + ["/bot", "home"], + ["/conversations", "conversations"], + ["/conversations/", "conversations"], + ["/channel/c-1", "conversations"], + ["/channel/new", "conversations"], + ["/group/g-1", "conversations"], + ["/start/s-1", "conversations"], + ["/bots", "bots"], + ["/bots/", "bots"], + ["/bots/b-1", "bots"], + ["/bots/b-1/routines", "bots"], + ["/channel", null], + ["/botsy", null], + ["/settings", null], + ["/routines", null], + ["/admin", null], + ["/sign", null], + ]; + for (const [path, tab] of TABLE) { + test(`${path} → ${tab ?? "none"}`, () => { + expect(tabForPath(path)).toBe(tab); + }); + } +}); + +describe("telling the shell", () => { + const route: ShellMessage = { + type: "route", + path: "/bots", + tab: "bots", + signedIn: true, + canGoBack: false, + depth: 1, + scrollRestored: true, + }; + + test("on iOS, the object itself to the openbotShell handler", () => { + const got: unknown[] = []; + postToShell(route, { + webkit: { + messageHandlers: { + openbotShell: { postMessage: (message) => got.push(message) }, + }, + }, + }); + expect(got).toEqual([route]); + }); + + test("on Android, as JSON", () => { + const got: string[] = []; + postToShell( + { type: "ready" }, + { OpenBotShellAndroid: { postMessage: (json) => got.push(json) } }, + ); + expect(got).toEqual(['{"type":"ready"}']); + }); + + test("nothing, and no error, with no shell or a shell that throws", () => { + expect(() => postToShell({ type: "signed-out" }, {})).not.toThrow(); + expect(() => + postToShell( + { type: "signed-out" }, + { + webkit: { + messageHandlers: { + openbotShell: { + postMessage: () => { + throw new Error("gone"); + }, + }, + }, + }, + }, + ), + ).not.toThrow(); + }); +}); + +describe("the shell's fields", () => { + const styles = readFileSync( + join(import.meta.dir, "..", "src", "styles.css"), + "utf8", + ); + const rule = (selector: string) => { + const at = styles.indexOf(selector); + expect(at).toBeGreaterThan(-1); + return styles.slice(at, styles.indexOf("}", at)); + }; + + // iOS zooms the page into any field under 16px when it is focused. + test("every field a person types in is 16px, so iOS does not zoom in on it", () => { + const fields = rule("html[data-native-shell]\n:is(\n input:not("); + expect(fields).toContain("textarea"); + expect(fields).toContain("font-size: 1rem;"); + }); +}); diff --git a/app/tests/sign-resume.test.tsx b/app/tests/sign-resume.test.tsx index beddf04113..221a9a088f 100644 --- a/app/tests/sign-resume.test.tsx +++ b/app/tests/sign-resume.test.tsx @@ -13,7 +13,12 @@ import { import { cleanup, render, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { authKeys } from "@/lib/auth/queries"; -import { resumeUrlFor } from "@/lib/auth/resume"; +import { + resumeUrlFor, + type ShellReturnSearch, + shellHandoffPathFor, + signInReturnUrlFor, +} from "@/lib/auth/resume"; /* * The Better Auth client is replaced at the module boundary: its fetch is captured when it is built, @@ -119,7 +124,7 @@ function signedInContext() { return { queryClient }; } -async function redirectFrom(search: { flow_id?: string }) { +async function redirectFrom(search: { flow_id?: string } & ShellReturnSearch) { const beforeLoad = Route.options.beforeLoad as (a: unknown) => Promise; try { await beforeLoad({ context: signedInContext(), search }); @@ -144,6 +149,8 @@ function renderSignScreen(options: { providers: string[]; sso: boolean; ssoRequired: boolean; + /** Where the screen is opened: `/sign?flow_id=h1` unless said. */ + entry?: string; }) { const queryClient = new QueryClient(); queryClient.setQueryData(authKeys.providers(), options); @@ -159,7 +166,9 @@ function renderSignScreen(options: { const router = createRouter({ routeTree: root.addChildren([sign]), context: { queryClient }, - history: createMemoryHistory({ initialEntries: ["/sign?flow_id=h1"] }), + history: createMemoryHistory({ + initialEntries: [options.entry ?? "/sign?flow_id=h1"], + }), } as never) as never; const view = render( @@ -301,3 +310,191 @@ test("a signed-in arrival with a handle lands on the verifier, not back on the h }); } }); + +/* + * A PHONE APP'S SIGN-IN SHEET, LANDING ON /sign (the server's docs/shell-sign-in.md, "Returning + * through /sign"). The server hands it `shell_challenge`, `shell_platform` and `shell_callback`; once + * signed in, the sheet goes on to the hand-off on this origin, built from those values once they + * check out, rather than into the web app inside the sheet. + */ +const CHALLENGE = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; +const HANDOFF = `/api/auth/shell/handoff?challenge=${CHALLENGE}&platform=ios&callback=https`; + +test("well-formed sheet values build the hand-off's path, in the doc's order, the optional ones only when given", () => { + expect( + shellHandoffPathFor({ + shell_challenge: CHALLENGE, + shell_platform: "ios", + shell_callback: "https", + }), + ).toBe(HANDOFF); + expect(shellHandoffPathFor({ shell_challenge: CHALLENGE })).toBe( + `/api/auth/shell/handoff?challenge=${CHALLENGE}`, + ); + expect( + shellHandoffPathFor({ + shell_challenge: CHALLENGE, + shell_platform: "android", + }), + ).toBe(`/api/auth/shell/handoff?challenge=${CHALLENGE}&platform=android`); +}); + +test("malformed sheet values are ignored, all 3 together", () => { + for (const search of [ + { shell_challenge: CHALLENGE.slice(1) }, + { shell_challenge: `${CHALLENGE}x` }, + { shell_challenge: `${CHALLENGE.slice(1)}=` }, + { shell_challenge: `${CHALLENGE.slice(1)}/` }, + { shell_challenge: CHALLENGE, shell_platform: "web" }, + { shell_challenge: CHALLENGE, shell_callback: "scheme" }, + { shell_challenge: CHALLENGE, shell_callback: "https://elsewhere.example" }, + { shell_platform: "ios", shell_callback: "https" }, + ]) + expect(shellHandoffPathFor(search)).toBeNull(); +}); + +test("the sheet's hand-off wins over a flow handle; without sheet values, the resume is as before", () => { + const origin = "https://openbot.example"; + expect( + signInReturnUrlFor(origin, { + flow_id: "h1", + shell_challenge: CHALLENGE, + shell_platform: "ios", + shell_callback: "https", + }), + ).toBe(`${origin}${HANDOFF}`); + expect(signInReturnUrlFor(origin, { flow_id: "h1" })).toBe( + resumeUrlFor(origin, "h1"), + ); + expect(signInReturnUrlFor(origin, {})).toBe(origin); + expect( + signInReturnUrlFor(origin, { shell_challenge: "short", flow_id: "h1" }), + ).toBe(resumeUrlFor(origin, "h1")); +}); + +test("the sheet's hand-off wins over the page somebody was on; without sheet values, sign-in returns there", () => { + const origin = "https://openbot.example"; + expect( + signInReturnUrlFor(origin, { + next: "/bots?tab=mine", + shell_challenge: CHALLENGE, + shell_platform: "ios", + shell_callback: "https", + }), + ).toBe(`${origin}${HANDOFF}`); + expect(signInReturnUrlFor(origin, { next: "/bots?tab=mine" })).toBe( + `${origin}/bots?tab=mine`, + ); + // Malformed sheet values are ignored, and the page is still returned to. + expect( + signInReturnUrlFor(origin, { shell_challenge: "short", next: "/bots" }), + ).toBe(`${origin}/bots`); + // An address on another origin is no return address, with or without sheet values. + expect(signInReturnUrlFor(origin, { next: "//evil.example/x" })).toBe(origin); +}); + +test("a sign-in press with well-formed sheet values comes back to the hand-off", async () => { + const asked: string[] = []; + signInSpy = async (_provider, _start, callbackURL) => { + asked.push(callbackURL ?? ""); + }; + const { view, user } = renderSignScreen({ + providers: ["google"], + sso: false, + ssoRequired: false, + entry: `/sign?shell_challenge=${CHALLENGE}&shell_platform=ios&shell_callback=https`, + }); + await user.click(await view.findByText(/Continue with Google/)); + await waitFor(() => expect(asked).toHaveLength(1)); + expect(asked[0]).toBe(`${window.location.origin}${HANDOFF}`); +}); + +test("a sign-in press with malformed sheet values comes back as it would without them", async () => { + const asked: string[] = []; + signInSpy = async (_provider, _start, callbackURL) => { + asked.push(callbackURL ?? ""); + }; + const { view, user } = renderSignScreen({ + providers: ["google"], + sso: false, + ssoRequired: false, + entry: `/sign?shell_challenge=${CHALLENGE}&shell_callback=evil`, + }); + await user.click(await view.findByText(/Continue with Google/)); + await waitFor(() => expect(asked).toHaveLength(1)); + expect(asked[0]).toBe(window.location.origin); +}); + +test("already signed in with sheet values: a document navigation to the hand-off", async () => { + const validate = Route.options.validateSearch as ( + s: unknown, + ) => ShellReturnSearch & { flow_id?: string }; + const onward = (await redirectFrom( + validate({ + flow_id: "h1", + shell_challenge: CHALLENGE, + shell_platform: "ios", + shell_callback: "https", + }), + )) as { options: { href?: string; reloadDocument?: boolean } }; + expect(onward.options.href).toBe(HANDOFF); + expect(onward.options.reloadDocument).toBe(true); + // Malformed: the flow handle's resume, as before. + const asBefore = await redirectFrom( + validate({ flow_id: "h1", shell_challenge: "nope" }), + ); + expect(asBefore.options.href).toBe("/api/plugins/arcade/verify?flow_id=h1"); +}); + +test("already signed in with sheet values and a page to return to: the hand-off, not the page", async () => { + const validate = Route.options.validateSearch as ( + s: unknown, + ) => ShellReturnSearch & { flow_id?: string; next?: string }; + const onward = (await redirectFrom( + validate({ + next: "/bots", + shell_challenge: CHALLENGE, + shell_platform: "ios", + shell_callback: "https", + }), + )) as { options: { href?: string; reloadDocument?: boolean } }; + expect(onward.options.href).toBe(HANDOFF); + expect(onward.options.reloadDocument).toBe(true); + // Malformed sheet values: on to the page, as without them. + const toThePage = (await redirectFrom( + validate({ next: "/bots", shell_challenge: "nope" }), + )) as { options: { href?: string; reloadDocument?: boolean } }; + expect(toThePage.options.href).toBe("/bots"); + expect(toThePage.options.reloadDocument).toBeUndefined(); +}); + +test("already signed in: the phone app's hand-off comes before OpenBot Desktop's sign-in in this browser", async () => { + const validate = Route.options.validateSearch as ( + s: unknown, + ) => ShellReturnSearch & { flow_id?: string; next?: string }; + const DESKTOP = "/api/auth/window/sign-in?code=abc"; + // Without sheet values, Desktop's sign-in is a document navigation, as on main. + const desktop = (await redirectFrom(validate({ next: DESKTOP }))) as { + options: { href?: string; reloadDocument?: boolean }; + }; + expect(desktop.options.href).toBe(DESKTOP); + expect(desktop.options.reloadDocument).toBe(true); + // With well-formed sheet values the sheet is the phone app's: on to its hand-off. + const sheet = (await redirectFrom( + validate({ + next: DESKTOP, + shell_challenge: CHALLENGE, + shell_platform: "android", + }), + )) as { options: { href?: string; reloadDocument?: boolean } }; + expect(sheet.options.href).toBe( + `/api/auth/shell/handoff?challenge=${CHALLENGE}&platform=android`, + ); + expect(sheet.options.reloadDocument).toBe(true); + // Malformed sheet values move nothing: Desktop's sign-in goes ahead. + const ignored = (await redirectFrom( + validate({ next: DESKTOP, shell_challenge: "nope" }), + )) as { options: { href?: string; reloadDocument?: boolean } }; + expect(ignored.options.href).toBe(DESKTOP); + expect(ignored.options.reloadDocument).toBe(true); +}); diff --git a/app/workbench/mock-server.ts b/app/workbench/mock-server.ts new file mode 100644 index 0000000000..979ac0ed7e --- /dev/null +++ b/app/workbench/mock-server.ts @@ -0,0 +1,890 @@ +/* + * MOCK SERVER, FOR TESTS ONLY. Never part of OpenBot: nothing in app/src imports it, and nothing + * starts it but these commands. It stands in for OpenBot's server so the REAL built app can run + * signed in on a machine with no server and no Docker (the phone app's UI tests, screenshots). + * + * # The app, served as an install serves it, passing /api here: + * cd app && bun run build + * APP_PORT=3010 SERVER_PORT=3001 bun app/serve.ts + * + * # Signed in (everybody is, cookie or not): + * bun app/workbench/mock-server.ts + * + * # Signed out: only a browser holding the mock's session cookie is signed in, as after + * # /api/auth/shell/enter. Everybody else is answered 401, like the workbench's app-signed-out scene. + * MOCK_SIGNED_OUT=1 bun app/workbench/mock-server.ts + * + * # As a server without the phone app's sign-in hand-off: every /api/auth/shell/* answers 404. + * MOCK_NO_HANDOFF=1 MOCK_SIGNED_OUT=1 bun app/workbench/mock-server.ts + * + * # As a server from before /api/auth/shell/enter asked for the OpenBot-Shell header and checked + * # Sec-Fetch-Site and Sec-Fetch-Mode (below), for phone app builds that don't send the first yet. + * # The verifier is still read from its own header only, as OpenBot's server reads it: + * MOCK_ENTER_NO_HEADER_CHECK=1 bun app/workbench/mock-server.ts + * + * # Another person in another organization (Sam Rivera in Acme when unset), say for a second mock + * # standing in for a self-hosted OpenBot: + * MOCK_PERSON_NAME="Robin Park" MOCK_ORG_NAME="Globex" SERVER_PORT=3002 bun app/workbench/mock-server.ts + * + * It listens on 127.0.0.1:${SERVER_PORT:-3001}. Besides the API it answers: + * + * GET /__mock/session {"signedIn": boolean}: whether a request with no cookie is + * POST /__mock/session {"signedIn": bool} signed in, and to change it at run time. + * GET /api/auth/shell/config?platform=ios + * What the phone app asks before signing in: {"handoff":true,"callback":"scheme", + * "callbackUrl":"bot.open.shell:/signed-in"}. 404 under MOCK_NO_HANDOFF. + * GET /api/auth/shell/handoff?challenge=C[&platform=ios][&auto=1] + * The page the phone app opens in its sign-in sheet. C is a PKCE S256 challenge (43 + * characters of base64url). A page titled "Mock sign-in" with one link, #mock-sign-in, "Sign in + * as test person", to bot.open.shell:/signed-in?ticket=T (one slash). T is single use and + * lasts 60 s. + * With auto=1 the page follows its link by itself after 800 ms. 400 without a valid C. + * GET /api/auth/shell/enter?ticket=T&to=/path + * Loaded by the web view, which sends the headers `OpenBot-Shell: ios` (or `android`, exactly) + * and `OpenBot-Shell-Verifier: V`. Refused before T is looked at, leaving it unused: no such + * OpenBot-Shell, a Sec-Fetch-Site that is present and not `none`, a Sec-Fetch-Mode that is + * present and not `navigate`. Past those, a known T is spent whatever follows: a T that is + * unknown, used or expired, a missing or malformed V (43 to 128 of A-Z a-z 0-9 - . _ ~), or a + * V whose base64url(sha256(V)) is not T's C is refused. A `verifier` in the query is never + * read, so an enter that carries it only there fails, and spends T. Otherwise it sets the + * cookie better-auth.session_token=mock and answers 303 to `to` (an own path, else /). Every + * refusal is a 303 to /sign?native-sign-in=failed, setting nothing. MOCK_ENTER_NO_HEADER_CHECK=1 + * skips the OpenBot-Shell and Sec-Fetch checks, not the verifier's header. + * POST /api/auth/sign-out + * Ends the mock's session: its cookie stops counting until the next /enter. + * + * Signed in, the API answers as the workbench's app-home scene does (workbench/session.ts, + * api/extraHandlers.ts and the spec's generated answers), with a person (Sam Rivera, in Acme, unless + * MOCK_PERSON_NAME and MOCK_ORG_NAME say otherwise), + * three Bots (General Assistant, Research Bot, Writing Bot) and fifteen conversations, the first three + * Competitor pricing notes (pinned and unread), Quarterly forecast and Trip to Lisbon, then one a Bot + * is working in (Board update for December), another unread (Launch announcement) and more, eight of + * them General Assistant's, each with a short transcript. A + * conversation made while it runs (sending from Home) is kept in memory until it stops: its own GET + * answers it, the list shows it, its runs answer it and its messages read back. The live socket the + * app opens is accepted and kept quiet. + */ + +import { createHash, randomBytes } from "node:crypto"; +import { join } from "node:path"; +import type { ServerWebSocket } from "bun"; +import { HttpResponse, http, type RequestHandler } from "msw"; +import type { ApiRoute } from "../../desktop/workbench/appContract"; +import type { Bot, ConversationSummary } from "../src/lib/api/generated/model"; +import { extraHandlers } from "./api/extraHandlers"; +import { installFakeApi } from "./api/fakeApi"; +import { pickAggregators } from "./api/handlers"; +import { DEFAULT_SESSION, sessionApi } from "./session"; + +const PORT = Number(process.env.SERVER_PORT ?? 3001); +const ORIGIN = `http://127.0.0.1:${PORT}`; +/** + * The signed-in person and their organization: Sam Rivera in Acme, or the names in MOCK_PERSON_NAME + * and MOCK_ORG_NAME, so a second mock beside the first (a self-hosted OpenBot in a sign-in test) can + * show which server a screen is on. The app draws the initials from the name. + */ +const SESSION: typeof DEFAULT_SESSION = DEFAULT_SESSION.signedIn + ? { + ...DEFAULT_SESSION, + name: process.env.MOCK_PERSON_NAME?.trim() || DEFAULT_SESSION.name, + organization: { + ...DEFAULT_SESSION.organization, + name: + process.env.MOCK_ORG_NAME?.trim() || + DEFAULT_SESSION.organization.name, + }, + } + : DEFAULT_SESSION; +const ORGANIZATION = SESSION.signedIn ? SESSION.organization.id : "default"; +const API = `*/api/v2/organizations/:organizationId`; +/** The cookie that makes a request signed in, whatever the session's default. */ +export const MOCK_SESSION_COOKIE = "better-auth.session_token"; +const MOCK_SESSION_VALUE = "mock"; +const HANDOFF = process.env.MOCK_NO_HANDOFF !== "1"; +/** Whether /api/auth/shell/enter asks for the phone app's header, as OpenBot's server does. */ +const ENTER_HEADER_CHECK = process.env.MOCK_ENTER_NO_HEADER_CHECK !== "1"; +/** The header the phone app's web view sends on /api/auth/shell/enter, and what it may say. */ +const SHELL_HEADER = "OpenBot-Shell"; +const SHELL_PLATFORMS = new Set(["ios", "android"]); +/** The header that carries the PKCE verifier on /api/auth/shell/enter: never the address. */ +const VERIFIER_HEADER = "OpenBot-Shell-Verifier"; +/** A PKCE verifier (RFC 7636): 43 to 128 unreserved characters. */ +const VERIFIER = /^[A-Za-z0-9._~-]{43,128}$/; +/** Where the ticket goes: the custom scheme, reverse-domain, with one slash after the colon. */ +const SCHEME_CALLBACK = "bot.open.shell:/signed-in"; +// MOCK_REPLY=1: a run answers with one canned sentence (the iOS shell's video). Off by default. +const REPLY = process.env.MOCK_REPLY === "1"; +const TICKET_MS = 60_000; + +/** Whether a request with no mock cookie is signed in. */ +let signedInByDefault = process.env.MOCK_SIGNED_OUT !== "1"; +/** The mock's one session was signed out: its cookie no longer counts until the next sign-in. */ +let mockSessionEnded = false; + +// The Bots and conversations every signed-in page shows. --------------------------------------- + +const GENERAL_BOT: Bot = { + id: "general-assistant", + name: "General Assistant", + title: "Everyday Work", + roleDescription: + "Help with everyday work using clear, concise, and accurate answers.", + avatarSeed: "general-assistant", + visibility: "public", + hidden: false, + pinned: false, + systemOwned: true, + endpoint: null, + hasAuth: false, + hasCallbackToken: false, + isolated: false, + framework: "OpenBot", + canManage: false, + mine: false, + assignedToMe: false, + builtIn: false, + runsOnOpenBotModel: true, + keyFromOpenBot: false, + isolationActive: false, + isolationOffReason: null, +}; + +const RESEARCH_BOT: Bot = { + ...GENERAL_BOT, + id: "research-bot", + name: "Research Bot", + title: "Market Research", + roleDescription: "Find, compare and summarize what competitors publish.", + avatarSeed: "research-bot", + visibility: "private", + systemOwned: false, + canManage: true, + mine: true, +}; + +const WRITING_BOT: Bot = { + ...GENERAL_BOT, + id: "writing-bot", + name: "Writing Bot", + title: "Writing", + roleDescription: "Drafts, edits and tightens what you write.", + avatarSeed: "writing-bot", + visibility: "private", + systemOwned: false, + canManage: true, + mine: true, +}; + +export const MOCK_BOTS: readonly Bot[] = [ + GENERAL_BOT, + RESEARCH_BOT, + WRITING_BOT, +]; + +function conversation( + fields: Partial & + Pick, +): ConversationSummary { + const bot = MOCK_BOTS.find((one) => one.id === fields.botIds[0]); + return { + name: bot?.name ?? "Bot", + threadId: `thread-${fields.id}`, + active: true, + lastMessageAt: "2026-11-26T09:30:00.000Z", + opening: null, + lastMessage: null, + lastMessageBotId: fields.botIds[0] ?? null, + createdAt: "2026-11-20T09:00:00.000Z", + pinned: false, + lastReadAt: "2026-11-26T09:31:00.000Z", + canRename: true, + task: false, + work: [], + ...fields, + }; +} + +/** Newest first, as the server orders them (pinned first is the page's and the sidebar's). */ +export const MOCK_CONVERSATIONS: readonly ConversationSummary[] = [ + conversation({ + id: "c-pricing", + botIds: [RESEARCH_BOT.id], + summary: "Competitor pricing notes", + opening: "What do our three closest competitors charge?", + lastMessage: "All three moved to per-seat pricing this year.", + lastMessageAt: "2026-11-27T08:15:00.000Z", + // Pinned, and unread: the Bot answered after it was last opened. + pinned: true, + lastReadAt: "2026-11-27T08:00:00.000Z", + }), + conversation({ + id: "c-forecast", + botIds: [GENERAL_BOT.id], + summary: "Quarterly forecast", + opening: "Can you draft the quarterly forecast?", + lastMessage: "Here is the first draft.", + lastMessageAt: "2026-11-26T16:40:00.000Z", + lastReadAt: "2026-11-26T16:41:00.000Z", + }), + conversation({ + id: "c-lisbon", + botIds: [GENERAL_BOT.id], + summary: "Trip to Lisbon", + opening: "Plan three days in Lisbon in March.", + lastMessage: "Day one starts in Alfama.", + lastMessageAt: "2026-11-24T11:05:00.000Z", + lastReadAt: "2026-11-24T11:06:00.000Z", + }), + /* + * Enough more for the panels' states: a conversation a Bot is working in, another unread, a + * third Bot, and more under General Assistant than the Bots panel shows before Show more + * (`BOT_CONVERSATIONS_PAGE`, 5), and a list long enough to scroll. + */ + conversation({ + id: "c-board", + botIds: [GENERAL_BOT.id], + summary: "Board update for December", + opening: "Draft the December board update from last month's numbers.", + lastMessage: "Pulling the revenue figures now.", + lastMessageAt: "2026-11-24T10:20:00.000Z", + lastReadAt: "2026-11-24T10:21:00.000Z", + busy: true, + }), + conversation({ + id: "c-launch-post", + botIds: [WRITING_BOT.id], + summary: "Launch announcement", + opening: "Tighten the launch post to 200 words.", + lastMessage: "Here is a 196-word version.", + lastMessageAt: "2026-11-23T15:00:00.000Z", + // Unread: the Bot answered after it was last opened. + lastReadAt: "2026-11-23T14:00:00.000Z", + }), + conversation({ + id: "c-hiring", + botIds: [GENERAL_BOT.id], + summary: "Hiring plan", + opening: "Outline a hiring plan for two engineers.", + lastMessage: "Two roles, staggered by a month.", + lastMessageAt: "2026-11-22T09:10:00.000Z", + lastReadAt: "2026-11-22T09:11:00.000Z", + }), + conversation({ + id: "c-churn", + botIds: [RESEARCH_BOT.id], + summary: "Why customers churn", + opening: "What do churned customers say in their exit surveys?", + lastMessage: "Price comes up in a third of them.", + lastMessageAt: "2026-11-21T13:30:00.000Z", + lastReadAt: "2026-11-21T13:31:00.000Z", + }), + conversation({ + id: "c-offsite", + botIds: [GENERAL_BOT.id], + summary: "Team offsite agenda", + opening: "Plan a two-day offsite agenda.", + lastMessage: "Day two is workshops only.", + lastMessageAt: "2026-11-20T16:45:00.000Z", + lastReadAt: "2026-11-20T16:46:00.000Z", + }), + conversation({ + id: "c-newsletter", + botIds: [WRITING_BOT.id], + summary: "November newsletter", + opening: "Write the November customer newsletter.", + lastMessage: "Three stories and a product tip.", + lastMessageAt: "2026-11-19T10:00:00.000Z", + lastReadAt: "2026-11-19T10:01:00.000Z", + }), + conversation({ + id: "c-expenses", + botIds: [GENERAL_BOT.id], + summary: "Expense policy questions", + opening: "Can I expense a co-working day pass?", + lastMessage: "Yes, up to twice a month.", + lastMessageAt: "2026-11-18T12:20:00.000Z", + lastReadAt: "2026-11-18T12:21:00.000Z", + }), + conversation({ + id: "c-pitch", + botIds: [RESEARCH_BOT.id], + summary: "Market size for the pitch", + opening: "How big is the market for our pitch deck?", + lastMessage: "About 4 billion dollars a year.", + lastMessageAt: "2026-11-17T08:40:00.000Z", + lastReadAt: "2026-11-17T08:41:00.000Z", + }), + conversation({ + id: "c-roadmap", + botIds: [GENERAL_BOT.id], + summary: "Q1 roadmap", + opening: "Turn these notes into a Q1 roadmap.", + lastMessage: "Three themes, nine items.", + lastMessageAt: "2026-11-15T14:00:00.000Z", + lastReadAt: "2026-11-15T14:01:00.000Z", + }), + conversation({ + id: "c-style", + botIds: [WRITING_BOT.id], + summary: "House style guide", + opening: "Make a one-page style guide for our blog.", + lastMessage: "Short sentences, no jargon, one idea per paragraph.", + lastMessageAt: "2026-11-13T11:15:00.000Z", + lastReadAt: "2026-11-13T11:16:00.000Z", + }), + conversation({ + id: "c-vendors", + botIds: [GENERAL_BOT.id], + summary: "Compare payroll vendors", + opening: "Compare three payroll vendors for a team of 20.", + lastMessage: "The middle one is cheapest at our size.", + lastMessageAt: "2026-11-11T09:30:00.000Z", + lastReadAt: "2026-11-11T09:31:00.000Z", + }), + conversation({ + id: "c-retro", + botIds: [GENERAL_BOT.id], + summary: "Sprint retro notes", + opening: "Summarize the sprint retro.", + lastMessage: "Two things to keep, one to change.", + lastMessageAt: "2026-11-09T17:00:00.000Z", + lastReadAt: "2026-11-09T17:01:00.000Z", + }), +]; + +/** + * The conversations made while the mock runs (`POST /conversations`, as sending from Home does), + * newest first. Kept in memory for the life of the process and answered like the fixed ones above: + * by their own GET, in the list, and with their messages read back. + */ +const created: ConversationSummary[] = []; + +/** What a made conversation's runs said, by thread: the person's messages and the replies. */ +const said = new Map(); + +/** Every conversation the mock knows, newest first: the ones made here, then the fixed ones. */ +function allConversations(): ConversationSummary[] { + return [...created, ...MOCK_CONVERSATIONS]; +} + +function findConversation(id: string): ConversationSummary | undefined { + return allConversations().find((one) => one.id === id); +} + +/** Each conversation's transcript: what the person asked, and the Bot's answer. */ +function transcript(id: string) { + const found = findConversation(id); + if (!found) return []; + const kept = said.get(found.threadId); + if (kept) return kept; + return [ + { id: `${id}-1`, role: "user", content: found.opening ?? "Hello" }, + { + id: `${id}-2`, + role: "assistant", + content: found.lastMessage ?? "Hello!", + }, + ]; +} + +function byThread(threadId: string): ConversationSummary | undefined { + return allConversations().find((one) => one.threadId === threadId); +} + +/** One AG-UI stream that replays a transcript and ends. */ +function replay(threadId: string): Response { + const events = [ + { type: "RUN_STARTED", threadId, runId: "mock-join" }, + { + type: "MESSAGES_SNAPSHOT", + messages: transcript(byThread(threadId)?.id ?? ""), + }, + { type: "RUN_FINISHED", threadId, runId: "mock-join" }, + ]; + return new Response( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { + headers: { + "content-type": "text/event-stream", + "cache-control": "no-cache", + }, + }, + ); +} + +/** The answers that make the pages above real-looking. Ahead of the spec's generated ones. */ +function mockDataHandlers(): RequestHandler[] { + return [ + http.get(`${API}/bots`, ({ request }) => { + const hidden = new URL(request.url).searchParams.get("hidden"); + return HttpResponse.json({ + bots: hidden === "true" ? [] : MOCK_BOTS, + nextCursor: null, + }); + }), + http.get(`${API}/bots/:botId`, ({ params }) => { + const bot = MOCK_BOTS.find((one) => one.id === params.botId); + return bot + ? HttpResponse.json({ bot }) + : HttpResponse.json( + { detail: "There is no such Bot." }, + { status: 404 }, + ); + }), + http.get(`${API}/conversations`, ({ request }) => { + const url = new URL(request.url); + const q = url.searchParams.get("q")?.toLowerCase(); + const botId = url.searchParams.get("botId"); + const matching = allConversations().filter( + (one) => + (!botId || one.botIds.includes(botId)) && + (!q || + [one.name, one.summary, one.opening, one.lastMessage].some( + (field) => field?.toLowerCase().includes(q), + )), + ); + // Paged only where a page size is asked for (the Bots panel's 5 a Bot): the cursor is an offset. + const limit = Number(url.searchParams.get("limit")); + if (!Number.isInteger(limit) || limit <= 0) + return HttpResponse.json({ conversations: matching, nextCursor: null }); + const from = Number(url.searchParams.get("cursor") ?? 0) || 0; + const conversations = matching.slice(from, from + limit); + return HttpResponse.json({ + conversations, + nextCursor: + from + limit < matching.length ? String(from + limit) : null, + }); + }), + // A conversation made here, kept until the mock stops: its own GET, the list and its runs know it. + http.post(`${API}/conversations`, async ({ request }) => { + const body = (await request.json().catch(() => ({}))) as { + botIds?: unknown; + }; + const botIds = Array.isArray(body.botIds) + ? body.botIds.filter((one): one is string => typeof one === "string") + : []; + const now = new Date().toISOString(); + const made = conversation({ + id: crypto.randomUUID(), + botIds: botIds.length ? botIds : [GENERAL_BOT.id], + summary: null, + lastMessageAt: now, + createdAt: now, + lastReadAt: now, + }); + created.unshift(made); + const { id, name, threadId, active, lastMessageAt, work } = made; + return HttpResponse.json( + { + conversation: { + id, + name, + botIds: made.botIds, + threadId, + active, + lastMessageAt, + work, + }, + }, + { status: 201 }, + ); + }), + http.get(`${API}/conversations/:conversationId`, ({ params }) => { + const found = findConversation(String(params.conversationId)); + if (!found) + return HttpResponse.json( + { detail: "There is no such conversation." }, + { status: 404 }, + ); + const { id, name, botIds, threadId, active, lastMessageAt, work } = found; + return HttpResponse.json({ + conversation: { + id, + name, + botIds, + threadId, + active, + lastMessageAt, + work, + }, + }); + }), + // Push is set up here, as on a server that offers it: the phone app's tests check that the + // page still offers no browser notifications inside the native shell. + http.get(`${API}/notification-transports`, () => + HttpResponse.json({ + notificationTransports: [{ id: "push", title: "Push notifications" }], + nextCursor: null, + }), + ), + http.get(`${API}/conversations/:conversationId/refused-turns`, () => + HttpResponse.json({ refusedTurns: [], nextCursor: null }), + ), + http.post( + `${API}/conversations/:conversationId/read`, + () => new HttpResponse(null, { status: 204 }), + ), + // The last thing said, as the page reports it: a made conversation's row shows it, and its + // first message names it. The fixed ones keep the preview they were drawn with. + http.post( + `${API}/conversations/:conversationId/activity`, + async ({ params, request }) => { + const found = created.find((one) => one.id === params.conversationId); + const body = (await request.json().catch(() => ({}))) as { + text?: unknown; + botId?: unknown; + at?: unknown; + }; + if (found && typeof body.text === "string" && body.text.trim()) { + found.opening ??= body.text; + found.summary ??= body.text; + found.lastMessage = body.text; + found.lastMessageBotId = + typeof body.botId === "string" ? body.botId : null; + found.lastMessageAt = + typeof body.at === "string" ? body.at : new Date().toISOString(); + found.lastReadAt = found.lastMessageAt; + } + return new HttpResponse(null, { status: 204 }); + }, + ), + http.post( + `${API}/conversations/:conversationId/signal-busy`, + () => new HttpResponse(null, { status: 204 }), + ), + http.get(`${API}/conversations/:conversationId/voice-sessions`, () => + HttpResponse.json({ sessions: [], nextCursor: null }), + ), + http.get("*/api/copilotkit/threads/:threadId/messages", ({ params }) => + HttpResponse.json({ + messages: transcript(byThread(String(params.threadId))?.id ?? ""), + }), + ), + http.post( + "*/api/copilotkit/agent/:agentId/connect", + async ({ request }) => { + const body = (await request.json().catch(() => ({}))) as { + threadId?: string; + }; + return replay(body.threadId ?? ""); + }, + ), + // A run the mock can't answer: it starts and finishes with nothing said. + http.post("*/api/copilotkit/agent/:agentId/run", async ({ request }) => { + const body = (await request.json().catch(() => ({}))) as { + threadId?: string; + runId?: string; + messages?: { id?: unknown; role?: unknown; content?: unknown }[]; + }; + const threadId = body.threadId ?? ""; + const runId = body.runId ?? "mock-run"; + const reply = + "Two of the three cut their entry price; one added a free tier."; + // A made conversation keeps what its runs said, so its messages read back after a reload. + if (created.some((one) => one.threadId === threadId)) { + const messages = (Array.isArray(body.messages) ? body.messages : []) + .filter( + (one) => + (one.role === "user" || one.role === "assistant") && + typeof one.content === "string", + ) + .map((one, index) => ({ + id: typeof one.id === "string" ? one.id : `${threadId}-${index}`, + role: String(one.role), + content: String(one.content), + })); + if (REPLY) + messages.push({ + id: `${runId}-reply`, + role: "assistant", + content: reply, + }); + said.set(threadId, messages); + } + return new Response( + [ + { type: "RUN_STARTED", threadId, runId }, + ...(REPLY + ? [ + { + type: "TEXT_MESSAGE_START", + messageId: `${runId}-reply`, + role: "assistant", + }, + { + type: "TEXT_MESSAGE_CONTENT", + messageId: `${runId}-reply`, + delta: reply, + }, + { type: "TEXT_MESSAGE_END", messageId: `${runId}-reply` }, + ] + : []), + { type: "RUN_FINISHED", threadId, runId }, + ] + .map((event) => `data: ${JSON.stringify(event)}\n\n`) + .join(""), + { headers: { "content-type": "text/event-stream" } }, + ); + }), + ]; +} + +// The spec's generated answers. The workbench reads them with Vite's import.meta.glob +// (api/handlers.ts); under plain bun the same files are found with Bun.Glob. + +async function generatedHandlersFromDisk(): Promise { + const root = join(import.meta.dir, "../src/lib/api/generated"); + const modules: Record> = {}; + for await (const path of new Bun.Glob("*/*.msw.ts").scan(root)) { + modules[path] = (await import(join(root, path))) as Record; + } + return pickAggregators(modules); +} + +// Signed in or not, per request. --------------------------------------------------------------- + +function hasMockCookie(request: Request): boolean { + if (mockSessionEnded) return false; + const cookies = request.headers.get("cookie") ?? ""; + return cookies + .split(";") + .some( + (pair) => pair.trim() === `${MOCK_SESSION_COOKIE}=${MOCK_SESSION_VALUE}`, + ); +} + +function signedIn(request: Request): boolean { + return signedInByDefault || hasMockCookie(request); +} + +/** What a signed-out request is refused at: the same two the app-signed-out scene refuses. */ +const SIGNED_OUT_PATHS = [ + /^\/api\/v2\/organizations\/[^/]+\/people\/me$/, + /^\/api\/v2\/people\/me\/organizations$/, +]; + +// The phone app's sign-in hand-off. ------------------------------------------------------------ + +type Ticket = { challenge: string; expires: number; used: boolean }; +const tickets = new Map(); + +const CHALLENGE = /^[A-Za-z0-9_-]{43}$/; + +function base64url(bytes: Buffer): string { + return bytes + .toString("base64") + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +/** An own path: one slash, then anything but a second one. */ +function ownPath(to: string | null): string { + return to?.startsWith("/") && !to.startsWith("//") && !to.startsWith("/\\") + ? to + : "/"; +} + +function escapeHtml(text: string): string { + return text.replace( + /[&<>"']/g, + (char) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + char + ] ?? char, + ); +} + +function handoffPage(url: URL): Response { + const challenge = url.searchParams.get("challenge") ?? ""; + if (!CHALLENGE.test(challenge)) + return new Response("A PKCE S256 challenge is required.", { status: 400 }); + const ticket = base64url(randomBytes(32)); + tickets.set(ticket, { + challenge, + expires: Date.now() + TICKET_MS, + used: false, + }); + const target = escapeHtml(`${SCHEME_CALLBACK}?ticket=${ticket}`); + const auto = url.searchParams.get("auto") === "1"; + const html = ` + + + + +Mock sign-in +${auto ? `` : ""} + + +
+

Mock sign-in. Not OpenBot.

+Sign in as test person +
+${auto ? `` : ""} + +`; + return new Response(html, { + headers: { + "content-type": "text/html; charset=utf-8", + "cache-control": "no-store", + }, + }); +} + +function enter(url: URL, request: Request): Response { + const failed = new Response(null, { + status: 303, + headers: { location: "/sign?native-sign-in=failed" }, + }); + if (ENTER_HEADER_CHECK) { + // Only the phone app's web view, which says so in a header a link elsewhere can't set, and + // never a request another site started. + const shell = request.headers.get(SHELL_HEADER) ?? ""; + const site = request.headers.get("sec-fetch-site")?.toLowerCase(); + const mode = request.headers.get("sec-fetch-mode")?.toLowerCase(); + if (!SHELL_PLATFORMS.has(shell)) return failed; + // Only a load the web view started itself: no site, or `none`; a top-level navigation. + if (site !== undefined && site !== "none") return failed; + if (mode !== undefined && mode !== "navigate") return failed; + } + // Spent as it is read, as the server deletes its row: whatever is refused from here, it is gone. + const ticket = tickets.get(url.searchParams.get("ticket") ?? ""); + if (!ticket || ticket.used || ticket.expires < Date.now()) return failed; + ticket.used = true; + // From its header only: a `verifier` in the address is not read. + const verifier = request.headers.get(VERIFIER_HEADER) ?? ""; + if (!VERIFIER.test(verifier)) return failed; + const challenge = base64url(createHash("sha256").update(verifier).digest()); + if (challenge !== ticket.challenge) return failed; + mockSessionEnded = false; + return new Response(null, { + status: 303, + headers: { + location: ownPath(url.searchParams.get("to")), + "set-cookie": `${MOCK_SESSION_COOKIE}=${MOCK_SESSION_VALUE}; Path=/; HttpOnly; SameSite=Lax; Max-Age=604800`, + }, + }); +} + +// The server. ---------------------------------------------------------------------------------- + +async function start() { + const spec = await generatedHandlersFromDisk(); + // The fake API is a `fetch` it installs on a target: here an object of the server's own. + const notFound = () => + Promise.resolve(new Response("not found", { status: 404 })); + const unused = { fetch: notFound as unknown as typeof fetch }; + const api = installFakeApi(unused, { + origin: ORIGIN, + realFetch: notFound as unknown as typeof fetch, + groups: [ + { source: "extra", handlers: mockDataHandlers() }, + { + source: "extra", + handlers: extraHandlers({ agents: () => MOCK_BOTS.map((b) => b.id) }), + }, + { source: "spec", handlers: spec }, + ], + setTimer: (run, ms) => { + setTimeout(run, ms); + }, + now: () => performance.now(), + }); + // The signed-in session's answers. A signed-out request is refused before it gets here. + for (const [route, answer] of Object.entries(sessionApi(SESSION))) { + if (answer) api.setAnswer(route as ApiRoute, answer); + } + const answer = unused.fetch; + + Bun.serve({ + hostname: "127.0.0.1", + port: PORT, + websocket: { + // The live socket (conversation events, a computer's screen): accepted, and nothing said. + message() {}, + open(_socket: ServerWebSocket) {}, + }, + async fetch(incoming, server) { + const url = new URL(incoming.url); + const path = url.pathname; + + if (path === "/__mock/session") { + if (incoming.method === "POST") { + const body = (await incoming.json().catch(() => ({}))) as { + signedIn?: unknown; + }; + if (typeof body.signedIn === "boolean") + signedInByDefault = body.signedIn; + } + return Response.json({ signedIn: signedInByDefault }); + } + + if (path === "/api/auth/shell/config") { + if (!HANDOFF) return new Response("Not found", { status: 404 }); + return Response.json({ + handoff: true, + callback: "scheme", + callbackUrl: SCHEME_CALLBACK, + }); + } + + if ( + path === "/api/auth/shell/handoff" || + path === "/api/auth/shell/enter" + ) { + if (!HANDOFF) return new Response("Not found", { status: 404 }); + return path.endsWith("/handoff") + ? handoffPage(url) + : enter(url, incoming); + } + + if (incoming.headers.get("upgrade")?.toLowerCase() === "websocket") { + if (server.upgrade(incoming)) return undefined; + return new Response("expected a websocket upgrade", { status: 400 }); + } + + if (!path.startsWith("/api/")) + return new Response("Not found", { status: 404 }); + + const known = signedIn(incoming); + if (path === "/api/auth/sign-out" && incoming.method === "POST") { + signedInByDefault = false; + // As a real server does: the session is over, so the same cookie no longer signs anybody in. + if (hasMockCookie(incoming)) mockSessionEnded = true; + return Response.json( + { success: true }, + { + headers: { + "set-cookie": `${MOCK_SESSION_COOKIE}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0`, + }, + }, + ); + } + if (!known) { + if (path === "/api/auth/get-session") return Response.json(null); + if (SIGNED_OUT_PATHS.some((pattern) => pattern.test(path))) + return Response.json( + { detail: "Sign in to continue." }, + { status: 401 }, + ); + } + + // Read here, so the fake API, which builds a Request of its own, gets the same body. + const body = + incoming.method === "GET" || incoming.method === "HEAD" + ? undefined + : await incoming.arrayBuffer(); + return answer(`${ORIGIN}${path}${url.search}`, { + method: incoming.method, + headers: incoming.headers, + body, + }); + }, + }); + + console.log( + `OpenBot MOCK server on ${ORIGIN} (${signedInByDefault ? "signed in" : "signed out unless the mock cookie is sent"}${HANDOFF ? "" : ", no sign-in hand-off"}). Organization ${ORGANIZATION}.`, + ); +} + +if (import.meta.main) await start();