From 8952f5bd4bd73cb986061692c189775c54bb765d Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:53:42 -0800 Subject: [PATCH 01/39] A Conversations page lists every conversation, as the sidebar's panel does /conversations shows the sidebar's list as a page: pinned first, unread marked, the same search over the whole history, New conversation, and the same rows, which pin, rename and delete as they do in the sidebar. It shares the panel's query, rows, search results and pagination rather than copying them, and the sidebar draws as before. It is what the phone app's Conversations tab opens, and works in a browser too. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- .../app-sidebar/channel-pagination.tsx | 7 +- app/src/components/app-sidebar/channel.tsx | 16 +- .../app-sidebar/conversations-panel.tsx | 57 ++++-- app/src/lib/sections.tsx | 1 + app/src/routeTree.gen.ts | 21 ++ app/src/routes/_authed/_app/conversations.tsx | 181 ++++++++++++++++++ 6 files changed, 260 insertions(+), 23 deletions(-) create mode 100644 app/src/routes/_authed/_app/conversations.tsx 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 baa0c1d284..4722839943 100644 --- a/app/src/components/app-sidebar/channel.tsx +++ b/app/src/components/app-sidebar/channel.tsx @@ -45,6 +45,7 @@ export const Channel = memo(function Channel({ emphasis, view = "detailed", avatar = true, + layout = "sidebar", "data-slot": slot, }: { channelId: string; @@ -65,6 +66,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 full-width row of a card of rows (`PageRows`), as + * on the Conversations page, which squares it off and divides it from 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; }) { @@ -108,10 +114,12 @@ export const Channel = memo(function Channel({ data-slot={slot} type="button" className={cn( - "flex flex-row px-2.5 gap-2 items-center w-full 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]", + "flex flex-row gap-2 items-center w-full hover:bg-foreground/5 [content-visibility:auto]", + layout === "page" + ? "min-h-14 px-4 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-foreground/5", diff --git a/app/src/components/app-sidebar/conversations-panel.tsx b/app/src/components/app-sidebar/conversations-panel.tsx index e8b6f6ffc9..75a9dc6eaf 100644 --- a/app/src/components/app-sidebar/conversations-panel.tsx +++ b/app/src/components/app-sidebar/conversations-panel.tsx @@ -3,6 +3,7 @@ import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; import { Link, useParams } from "@tanstack/react-router"; import { AnimatePresence, motion, useReducedMotion } from "motion/react"; import { useEffect, useLayoutEffect, useRef, useState } from "react"; +import { PageEmpty, PageRows } from "@/components/layout/page-shell"; import { SectionPanel } from "@/components/layout/section-panel"; import { InputGroup, @@ -36,6 +37,7 @@ import { } from "@/lib/settings/message-list"; import { delegatingConversationsQueryOptions } from "@/lib/tasks/queries"; import { Button } from "../ui/button"; +import { Separator } from "../ui/separator"; import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "../ui/empty"; import { Channel } from "./channel"; import { ChannelPagination } from "./channel-pagination"; @@ -88,7 +90,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); @@ -161,18 +163,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 card (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` @@ -193,7 +201,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 (
@@ -287,21 +307,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 ? ( diff --git a/app/src/lib/sections.tsx b/app/src/lib/sections.tsx index 03aac4b836..2bd91ae002 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/routeTree.gen.ts b/app/src/routeTree.gen.ts index 719ba3b67e..498a53a770 100644 --- a/app/src/routeTree.gen.ts +++ b/app/src/routeTree.gen.ts @@ -23,6 +23,7 @@ import { Route as AuthedAppIndexRouteImport } from './routes/_authed/_app/index' import { Route as AuthedAppApprovalsRouteImport } from './routes/_authed/_app/approvals' 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' @@ -214,6 +215,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', @@ -898,6 +904,7 @@ export interface FileRoutesByFullPath { '/approvals': typeof AuthedAppApprovalsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute + '/conversations': typeof AuthedAppConversationsRoute '/memory': typeof AuthedAppMemoryRoute '/reachability': typeof AuthedAppReachabilityRoute '/reconnect': typeof AuthedAppReconnectRoute @@ -1031,6 +1038,7 @@ export interface FileRoutesByTo { '/approvals': typeof AuthedAppApprovalsRoute '/bot': typeof AuthedAppBotRoute '/browser': typeof AuthedAppBrowserRoute + '/conversations': typeof AuthedAppConversationsRoute '/memory': typeof AuthedAppMemoryRoute '/reachability': typeof AuthedAppReachabilityRoute '/reconnect': typeof AuthedAppReconnectRoute @@ -1168,6 +1176,7 @@ export interface FileRoutesById { '/_authed/_app/approvals': typeof AuthedAppApprovalsRoute '/_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 @@ -1307,6 +1316,7 @@ export interface FileRouteTypes { | '/approvals' | '/bot' | '/browser' + | '/conversations' | '/memory' | '/reachability' | '/reconnect' @@ -1440,6 +1450,7 @@ export interface FileRouteTypes { | '/approvals' | '/bot' | '/browser' + | '/conversations' | '/memory' | '/reachability' | '/reconnect' @@ -1576,6 +1587,7 @@ export interface FileRouteTypes { | '/_authed/_app/approvals' | '/_authed/_app/bot' | '/_authed/_app/browser' + | '/_authed/_app/conversations' | '/_authed/_app/memory' | '/_authed/_app/reachability' | '/_authed/_app/reconnect' @@ -1809,6 +1821,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' @@ -2848,6 +2867,7 @@ interface AuthedAppRouteChildren { AuthedAppApprovalsRoute: typeof AuthedAppApprovalsRoute AuthedAppBotRoute: typeof AuthedAppBotRoute AuthedAppBrowserRoute: typeof AuthedAppBrowserRoute + AuthedAppConversationsRoute: typeof AuthedAppConversationsRoute AuthedAppMemoryRoute: typeof AuthedAppMemoryRoute AuthedAppReachabilityRoute: typeof AuthedAppReachabilityRoute AuthedAppReconnectRoute: typeof AuthedAppReconnectRoute @@ -2906,6 +2926,7 @@ const AuthedAppRouteChildren: AuthedAppRouteChildren = { AuthedAppApprovalsRoute: AuthedAppApprovalsRoute, AuthedAppBotRoute: AuthedAppBotRoute, AuthedAppBrowserRoute: AuthedAppBrowserRoute, + AuthedAppConversationsRoute: AuthedAppConversationsRoute, AuthedAppMemoryRoute: AuthedAppMemoryRoute, AuthedAppReachabilityRoute: AuthedAppReachabilityRoute, AuthedAppReconnectRoute: AuthedAppReconnectRoute, diff --git a/app/src/routes/_authed/_app/conversations.tsx b/app/src/routes/_authed/_app/conversations.tsx new file mode 100644 index 0000000000..ac91f4f0d8 --- /dev/null +++ b/app/src/routes/_authed/_app/conversations.tsx @@ -0,0 +1,181 @@ +import { IconMessage, IconMessagePlus, IconSearch } from "@tabler/icons-react"; +import { useInfiniteQuery, useQuery } from "@tanstack/react-query"; +import { createFileRoute, Link } from "@tanstack/react-router"; +import { AnimatePresence } from "motion/react"; +import { useState } from "react"; +import { ChannelPagination } from "@/components/app-sidebar/channel-pagination"; +import { + ChannelRow, + NONE_DELEGATING, + pinnedFirst, + SEARCH_DEBOUNCE_MS, + SEARCH_HINT, + SEARCH_SCOPE, + SearchResults, + useDebounced, +} from "@/components/app-sidebar/conversations-panel"; +import { PageEmpty, PageRows, PageShell } from "@/components/layout/page-shell"; +import { Button } from "@/components/ui/button"; +import { + InputGroup, + InputGroupAddon, + InputGroupInput, +} from "@/components/ui/input-group"; +import { + channelListQueryOptions, + isChannelSearchable, + normalizeChannelSearch, +} from "@/lib/channels/queries"; +import { loadFailure } from "@/lib/load-failure"; +import { useConversationView } from "@/lib/settings/conversation-view"; +import { useMessageListEmphasis } from "@/lib/settings/message-list"; +import { delegatingConversationsQueryOptions } from "@/lib/tasks/queries"; + +export const Route = createFileRoute("/_authed/_app/conversations")({ + component: ConversationsPage, +}); + +/** 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 ?? []); + + return ( + } + size="sm" + variant="ghost" + > + + New conversation + + } + 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} + /> + ))} + + + + + )} +
+ ); +} From 77e53af9f1c65fa78c3c0f77215f8f54b30dba66 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:53:47 -0800 Subject: [PATCH 02/39] Inside the phone app's native shell, the web app draws only the page The phone app loads the web app in a web view and draws its own tab bar and sign-in screen around it. The page knows it is there from what the shell injects, its user agent, or ?native-shell=ios for testing (lib/native-shell), and then: - draws no sidebar, drawer or sidebar toggle, in the app, Settings and Admin; General lists Settings' other pages, and every Settings or Admin page leads back to its first page; - tells the shell it is ready and, after every navigation, its path, the shell's tab for it and whether someone is signed in; - shows a quiet page at /sign and tells the shell nobody is signed in, unless ?native-sign-in=web asks for the web sign-in; - offers no Home Screen push and no notifications of its own, and does not bounce past its edges. A page asked for with openbot:open that is already open is handled and left as it is. A screen with no sidebar no longer keeps an empty band for its toggle. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/index.html | 35 +++++ app/src/components/auth/native-signed-out.tsx | 28 ++++ .../components/layout/native-shell-frame.tsx | 56 +++++++ app/src/components/layout/page-shell.tsx | 36 +++-- app/src/components/layout/sidebar-toggle.tsx | 12 ++ .../components/settings/settings-pages.tsx | 60 ++++++++ .../components/settings/settings-sidebar.tsx | 19 ++- app/src/lib/desktop/open-requests.ts | 6 + app/src/lib/native-shell/bridge.ts | 71 +++++++++ app/src/lib/native-shell/route-reports.ts | 46 ++++++ app/src/lib/native-shell/shell.ts | 145 ++++++++++++++++++ app/src/lib/notifications/permission.ts | 3 + app/src/lib/web-push/browser.ts | 10 +- app/src/main.tsx | 5 + app/src/routes/__root.tsx | 6 +- app/src/routes/_authed/_app.tsx | 14 ++ app/src/routes/_authed/admin/route.tsx | 36 ++++- app/src/routes/_authed/settings/index.tsx | 3 + app/src/routes/_authed/settings/route.tsx | 33 +++- app/src/routes/sign.tsx | 28 +++- app/src/styles.css | 11 ++ 21 files changed, 641 insertions(+), 22 deletions(-) create mode 100644 app/src/components/auth/native-signed-out.tsx create mode 100644 app/src/components/layout/native-shell-frame.tsx create mode 100644 app/src/components/settings/settings-pages.tsx create mode 100644 app/src/lib/native-shell/bridge.ts create mode 100644 app/src/lib/native-shell/route-reports.ts create mode 100644 app/src/lib/native-shell/shell.ts diff --git a/app/index.html b/app/index.html index d743d064de..9773899fee 100644 --- a/app/index.html +++ b/app/index.html @@ -32,6 +32,41 @@ 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. + // 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 asked = new URLSearchParams(window.location.search).get("native-shell"); + 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" + : 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/auth/native-signed-out.tsx b/app/src/components/auth/native-signed-out.tsx new file mode 100644 index 0000000000..8c7eab50e4 --- /dev/null +++ b/app/src/components/auth/native-signed-out.tsx @@ -0,0 +1,28 @@ +import { useEffect } from "react"; +import AgentOrb from "@/components/agents/orb/agent-orb"; +import { postToShell } from "@/lib/native-shell/bridge"; + +/** + * The sign-in page inside the phone app's native shell, which shows its own sign-in screen over the + * web view: the shell is told nobody is signed in (`signed-out`), and the page shows only OpenBot's + * orb on the plain ground, as it does while it starts. No buttons: a second way in under the shell's + * would be one too many. + * + * Reached however the app ends up at `/sign`: opened signed out, a session that ran out (the + * sign-in gate in `_authed.tsx` sends the next page here), or Sign out. + */ +export function NativeSignedOut() { + useEffect(() => { + postToShell({ type: "signed-out" }); + }, []); + 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..82001a00ec --- /dev/null +++ b/app/src/components/layout/native-shell-frame.tsx @@ -0,0 +1,56 @@ +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"; + +/** + * 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. + */ +export function NativeShellFrame({ children }: { children: ReactNode }) { + useChannelEvents(); + return ( + + + + + + + + + + {children} + + ); +} diff --git a/app/src/components/layout/page-shell.tsx b/app/src/components/layout/page-shell.tsx index 6a604110d4..5e946a2a5f 100644 --- a/app/src/components/layout/page-shell.tsx +++ b/app/src/components/layout/page-shell.tsx @@ -1,6 +1,7 @@ import { IconChevronLeft } from "@tabler/icons-react"; import { Link, type LinkProps } from "@tanstack/react-router"; import type * as React from "react"; +import { createContext, useContext } from "react"; import { cn } from "@/lib/utils"; import { Button } from "../ui/button"; import { PageColumn, PageHeader, type ShellWidth } from "./page-parts"; @@ -22,6 +23,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, @@ -38,13 +55,10 @@ export function PageShell({ description?: 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; }) { + const fallbackBack = useContext(DefaultPageBack); + const back = backButton ?? fallbackBack ?? 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 @@ -61,7 +75,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 = ( @@ -70,18 +84,18 @@ export function PageShell({ const barRow = bar ? (
{showToggle ? : null} - {!backButton ? null : backButton.disabled ? ( + {!back ? null : back.disabled ? ( ) : ( )}
diff --git a/app/src/components/layout/sidebar-toggle.tsx b/app/src/components/layout/sidebar-toggle.tsx index 6e1ceb495a..c26a9713c1 100644 --- a/app/src/components/layout/sidebar-toggle.tsx +++ b/app/src/components/layout/sidebar-toggle.tsx @@ -127,6 +127,18 @@ export function SidebarToggle({ className }: { className?: string }) { * `children` sit at the band's right end, so a screen can put something there without a second bar. */ export function SidebarToggleBar({ children }: { children?: ReactNode }) { + /* + * With no sidebar at all (the phone app's native shell, `components/layout/native-shell-frame.tsx`) + * there is no toggle to keep a place for, so no band: only what the screen put at its end, and + * nothing when that draws nothing (`empty:hidden`). + */ + if (!useOptionalSidebar()) { + return children ? ( +
+ {children} +
+ ) : null; + } return (
diff --git a/app/src/components/settings/settings-pages.tsx b/app/src/components/settings/settings-pages.tsx new file mode 100644 index 0000000000..8b764e1366 --- /dev/null +++ b/app/src/components/settings/settings-pages.tsx @@ -0,0 +1,60 @@ +import { IconChevronRight } from "@tabler/icons-react"; +import { Link } from "@tanstack/react-router"; +import { Fragment } from "react"; +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 3acdb0da29..6b47c9f5b9 100644 --- a/app/src/components/settings/settings-sidebar.tsx +++ b/app/src/components/settings/settings-sidebar.tsx @@ -174,9 +174,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); @@ -201,6 +207,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/desktop/open-requests.ts b/app/src/lib/desktop/open-requests.ts index c3247cf11b..665afdc3a6 100644 --- a/app/src/lib/desktop/open-requests.ts +++ b/app/src/lib/desktop/open-requests.ts @@ -19,6 +19,10 @@ 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 + * (`lib/native-shell`). 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 +31,8 @@ export function useDesktopOpenRequests() { const path = (event as CustomEvent<{ path?: unknown }>).detail?.path; if (!isOwnPath(path)) return; event.preventDefault(); + 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/native-shell/bridge.ts b/app/src/lib/native-shell/bridge.ts new file mode 100644 index 0000000000..882f8c99fb --- /dev/null +++ b/app/src/lib/native-shell/bridge.ts @@ -0,0 +1,71 @@ +/** + * 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 }` on every change of page: the pathname only, never the + * query or the fragment, and which of the shell's tabs the page belongs to (`tabForPath`). + * - `{ 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; + } + | { type: "signed-out" }; + +type ShellWindow = { + webkit?: { + messageHandlers?: { + openbotShell?: { postMessage(message: unknown): void }; + }; + }; + OpenBotShellAndroid?: { postMessage(message: string): void }; +}; + +/** 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/route-reports.ts b/app/src/lib/native-shell/route-reports.ts new file mode 100644 index 0000000000..3d2cf139b1 --- /dev/null +++ b/app/src/lib/native-shell/route-reports.ts @@ -0,0 +1,46 @@ +import { useRouterState } from "@tanstack/react-router"; +import { useEffect } from "react"; +import { postToShell, tabForPath } from "./bridge"; +import { nativeShell } from "./shell"; + +/** `ready` goes once per page load, not once per mount (StrictMode mounts twice in development). */ +let readySent = false; + +/** For tests: let the next mount say `ready` again. */ +export function forgetReadyForTests(): void { + readySent = false; +} + +/** + * Tells the native shell the router is up, 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, + }); + + useEffect(() => { + if (!inShell || readySent) return; + readySent = true; + postToShell({ type: "ready" }); + }, [inShell]); + + useEffect(() => { + if (!inShell || settled === null) return; + const path = settled.slice(1); + postToShell({ + type: "route", + path, + tab: tabForPath(path), + signedIn: settled.startsWith("1"), + }); + }, [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..19b92d24e7 --- /dev/null +++ b/app/src/lib/native-shell/shell.ts @@ -0,0 +1,145 @@ +/** + * 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` on any address, remembered for the tab in sessionStorage, so a + * desktop browser or Playwright can open the shell's layout; `?native-shell=off` forgets it. It is + * reachable in production on purpose and harmless: all it does is hide the app's own navigation + * in that one tab. The platform it reports is "test". + * + * 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+)/; + +/** What detection reads, so a test can hand it anything. */ +export type NativeShellEnvironment = { + injected: unknown; + userAgent: string; + search: string; + /** 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 asked = new URLSearchParams(search).get(NATIVE_SHELL_PARAM); + 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") 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, + 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/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/web-push/browser.ts b/app/src/lib/web-push/browser.ts index 6c8a6b674a..9f93dd923f 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"; /** @@ -28,7 +29,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. @@ -40,7 +42,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 0ebfda46fa..149cc9ad5c 100644 --- a/app/src/main.tsx +++ b/app/src/main.tsx @@ -4,6 +4,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"; @@ -16,6 +17,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/routes/__root.tsx b/app/src/routes/__root.tsx index 7b850ab4db..ac647410f9 100644 --- a/app/src/routes/__root.tsx +++ b/app/src/routes/__root.tsx @@ -10,6 +10,7 @@ import { ThemeProvider } from "@/components/theme-provider"; import { Toaster } from "@/components/ui/toast"; import { TooltipProvider } from "@/components/ui/tooltip"; import { useDesktopOpenRequests } from "@/lib/desktop/open-requests"; +import { useNativeShellRouteReports } from "@/lib/native-shell/route-reports"; import { useServiceWorkerOpenRequests } from "@/lib/web-push/open-requests"; import type { RouterContext } from "../router-context"; import "@fontsource-variable/inter/wght.css"; @@ -123,8 +124,11 @@ 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(); + // The phone app's native shell is told where the page is. See `lib/native-shell/route-reports.ts`. + useNativeShellRouteReports(); // 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 f2259f46ee..9a20322ba0 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 { PlanBanner } from "@/components/layout/plan-banner"; import { SelfHostBanner } from "@/components/layout/self-host-banner"; import { SidebarShell } from "@/components/layout/sidebar-shell"; @@ -15,6 +16,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")({ @@ -24,6 +26,18 @@ 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/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 e7df615312..fe879484a3 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 { StarOnGitHubSection } from "@/components/settings/star-on-github"; import { ThemeRow } from "@/components/settings/theme-row"; @@ -43,6 +44,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 34612fc6f8..1c2980f682 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"; @@ -19,6 +20,7 @@ import { import { resumeUrlFor, verifierPathFor } from "@/lib/auth/resume"; import { appConfig } from "@/lib/generated/application-config"; import { type Failure, failureOf, failureSaid } from "@/lib/load-failure"; +import { nativeShell } from "@/lib/native-shell/shell"; import { inNoOrganization } from "@/lib/organizations/in-no-organization"; import { searchTextEntry } from "@/lib/search-text"; import { cn } from "@/lib/utils"; @@ -48,8 +50,12 @@ export const Route = createFileRoute("/sign")({ * gives for `?connected=`: present-but-undefined makes `search` a required prop on every Link to * this route, which is a lot of ripple for a parameter only the verifier sets. */ - validateSearch: (search: Record): { flow_id?: string } => - searchTextEntry("flow_id", search.flow_id), + validateSearch: ( + search: Record, + ): { flow_id?: string; "native-sign-in"?: string } => ({ + ...searchTextEntry("flow_id", search.flow_id), + ...searchTextEntry("native-sign-in", search["native-sign-in"]), + }), beforeLoad: async ({ context, search }) => { // Somebody signed in to no organization signs in like anybody: signing in again is how they come back once added. const user = await signedInUser(context.queryClient).catch((error) => { @@ -75,13 +81,29 @@ export const Route = createFileRoute("/sign")({ ? redirect({ href: verifier, reloadDocument: 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. + */ +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 } = Route.useSearch(); // Which provider is being opened, rather than whether one is: with three buttons, a single diff --git a/app/src/styles.css b/app/src/styles.css index 685fe0a892..f1198e8a94 100644 --- a/app/src/styles.css +++ b/app/src/styles.css @@ -537,3 +537,14 @@ 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; +} From 500e0158a15495f625f1c73bb564e0f0b7266882 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:59:37 -0800 Subject: [PATCH 03/39] The native shell hears ready before anything a page says Opened signed out, the sign-in page told the shell signed-out before the root said ready. Ready is sent from a layout effect now, so it comes first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/src/lib/native-shell/route-reports.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/app/src/lib/native-shell/route-reports.ts b/app/src/lib/native-shell/route-reports.ts index 3d2cf139b1..e01bd625e4 100644 --- a/app/src/lib/native-shell/route-reports.ts +++ b/app/src/lib/native-shell/route-reports.ts @@ -1,5 +1,5 @@ import { useRouterState } from "@tanstack/react-router"; -import { useEffect } from "react"; +import { useEffect, useLayoutEffect } from "react"; import { postToShell, tabForPath } from "./bridge"; import { nativeShell } from "./shell"; @@ -27,7 +27,8 @@ export function useNativeShellRouteReports(): void { : null, }); - useEffect(() => { + // A layout effect, so `ready` goes before anything a page says from its own effects (`signed-out`). + useLayoutEffect(() => { if (!inShell || readySent) return; readySent = true; postToShell({ type: "ready" }); From 998b069711f834eb64b9ee70d8bc2f78384d53f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 14:59:37 -0800 Subject: [PATCH 04/39] A mock server runs the built app signed in without OpenBot's server bun app/workbench/mock-server.ts answers /api on 127.0.0.1:3001 from the workbench's fake API and the spec's generated answers, with fixed Bots and conversations, so Home, Conversations, a conversation and Bots draw real-looking pages behind app/serve.ts. It keeps the live socket open and quiet. MOCK_SIGNED_OUT=1 refuses anybody without its session cookie, and /__mock/session reads or changes that at run time. It also stands in for the phone app's sign-in hand-off: /api/auth/shell/handoff gives a single-use ticket for a PKCE challenge, and /api/auth/shell/enter checks the verifier, sets the session cookie and goes to the page asked for. MOCK_NO_HANDOFF=1 answers both 404. For tests only; nothing in the app imports it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/workbench/mock-server.ts | 543 +++++++++++++++++++++++++++++++++++ 1 file changed, 543 insertions(+) create mode 100644 app/workbench/mock-server.ts diff --git a/app/workbench/mock-server.ts b/app/workbench/mock-server.ts new file mode 100644 index 0000000000..8694c8c89a --- /dev/null +++ b/app/workbench/mock-server.ts @@ -0,0 +1,543 @@ +/* + * 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: both /api/auth/shell/* answer 404. + * MOCK_NO_HANDOFF=1 MOCK_SIGNED_OUT=1 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/handoff?challenge=C[&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 openbotshell://signed-in?ticket=T. 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&verifier=V&to=/path + * Loaded by the web view. With a known, unused, unexpired T whose C is base64url(sha256(V)): + * sets the cookie better-auth.session_token=mock and answers 303 to `to` (an own path, else /). + * Otherwise 303 to /sign?native-sign-in=failed, setting nothing. + * + * 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 fixed person (Sam Rivera, in Acme), + * two Bots (General Assistant, Research Bot) and three conversations (Competitor pricing notes, + * pinned and unread; Quarterly forecast; Trip to Lisbon), each with a short transcript. 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 { Bot, ConversationSummary } from "../src/lib/api/generated/model"; +import { extraHandlers } from "./api/extraHandlers"; +import { installFakeApi } from "./api/fakeApi"; +import { pickAggregators } from "./api/handlers"; +import type { ApiRoute } from "../../desktop/workbench/appContract"; +import { DEFAULT_SESSION, sessionApi } from "./session"; + +const PORT = Number(process.env.SERVER_PORT ?? 3001); +const ORIGIN = `http://127.0.0.1:${PORT}`; +const ORGANIZATION = DEFAULT_SESSION.signedIn + ? DEFAULT_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"; +const TICKET_MS = 60_000; + +/** Whether a request with no mock cookie is signed in. */ +let signedInByDefault = process.env.MOCK_SIGNED_OUT !== "1"; + +// 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, +}; + +export const MOCK_BOTS: readonly Bot[] = [GENERAL_BOT, RESEARCH_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", + }), +]; + +/** Each conversation's transcript: what the person asked, and the Bot's answer. */ +function transcript(id: string) { + const found = MOCK_CONVERSATIONS.find((one) => one.id === id); + if (!found) return []; + 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 MOCK_CONVERSATIONS.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 conversations = MOCK_CONVERSATIONS.filter( + (one) => + (!botId || one.botIds.includes(botId)) && + (!q || + [one.name, one.summary, one.opening, one.lastMessage].some( + (field) => field?.toLowerCase().includes(q), + )), + ); + return HttpResponse.json({ conversations, nextCursor: null }); + }), + http.get(`${API}/conversations/:conversationId`, ({ params }) => { + const found = MOCK_CONVERSATIONS.find( + (one) => one.id === 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, + }, + }); + }), + http.get(`${API}/conversations/:conversationId/refused-turns`, () => + HttpResponse.json({ refusedTurns: [], nextCursor: null }), + ), + http.post( + `${API}/conversations/:conversationId/read`, + () => new HttpResponse(null, { status: 204 }), + ), + http.post( + `${API}/conversations/:conversationId/activity`, + () => 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; + }; + const threadId = body.threadId ?? ""; + const runId = body.runId ?? "mock-run"; + return new Response( + [ + { type: "RUN_STARTED", threadId, runId }, + { 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 { + 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(24)); + tickets.set(ticket, { + challenge, + expires: Date.now() + TICKET_MS, + used: false, + }); + const target = escapeHtml(`openbotshell://signed-in?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): Response { + const failed = new Response(null, { + status: 303, + headers: { location: "/sign?native-sign-in=failed" }, + }); + const ticket = tickets.get(url.searchParams.get("ticket") ?? ""); + const verifier = url.searchParams.get("verifier") ?? ""; + if (!ticket || ticket.used || ticket.expires < Date.now() || !verifier) + return failed; + const challenge = base64url(createHash("sha256").update(verifier).digest()); + if (challenge !== ticket.challenge) return failed; + ticket.used = true; + 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(DEFAULT_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/handoff" || + path === "/api/auth/shell/enter" + ) { + if (!HANDOFF) return new Response("Not found", { status: 404 }); + return path.endsWith("/handoff") ? handoffPage(url) : enter(url); + } + + 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; + 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(); From 637a20526ea0df630cd5cc71fca6b332506bbdb4 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:07:26 -0800 Subject: [PATCH 05/39] Tests hold the web app's side of the phone app's native shell How the page knows it is in the shell, the same before the first paint; which of the shell's tabs each page belongs to; what the shell is told and in what order; the frame with no sidebar in the shell and the sidebar as before in a browser; the Conversations page's states; and the quiet sign-in page. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/src/routes/sign.tsx | 4 +- app/tests/native-shell-app.test.tsx | 393 ++++++++++++++++++++++++++++ app/tests/native-shell.test.ts | 289 ++++++++++++++++++++ 3 files changed, 685 insertions(+), 1 deletion(-) create mode 100644 app/tests/native-shell-app.test.tsx create mode 100644 app/tests/native-shell.test.ts diff --git a/app/src/routes/sign.tsx b/app/src/routes/sign.tsx index 1c2980f682..dca7cfd6d4 100644 --- a/app/src/routes/sign.tsx +++ b/app/src/routes/sign.tsx @@ -95,7 +95,9 @@ export const Route = createFileRoute("/sign")({ * (`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. */ -function signsInNatively(search: { "native-sign-in"?: string }): boolean { +export function signsInNatively(search: { + "native-sign-in"?: string; +}): boolean { return nativeShell() !== null && search["native-sign-in"] !== "web"; } diff --git a/app/tests/native-shell-app.test.tsx b/app/tests/native-shell-app.test.tsx new file mode 100644 index 0000000000..238b5e3a9b --- /dev/null +++ b/app/tests/native-shell-app.test.tsx @@ -0,0 +1,393 @@ +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, render, waitFor } from "@testing-library/react"; +import type { ReactNode } from "react"; +import { NativeSignedOut } from "@/components/auth/native-signed-out"; +import { PageShell } from "@/components/layout/page-shell"; +import { SidebarToggleBar } from "@/components/layout/sidebar-toggle"; +import { useDesktopOpenRequests } from "@/lib/desktop/open-requests"; +import { + forgetReadyForTests, + useNativeShellRouteReports, +} from "@/lib/native-shell/route-reports"; +import { forgetNativeShellForTests } from "@/lib/native-shell/shell"; +import { notificationPermission } from "@/lib/notifications/permission"; +import { webPushSupport } from "@/lib/web-push/browser"; +import { Route as AppRoute } from "@/routes/_authed/_app"; +import { Route as ConversationsRoute } from "@/routes/_authed/_app/conversations"; +import { signsInNatively } from "@/routes/sign"; +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(); +} + +/** 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 path = new URL(String(input), "http://127.0.0.1:3010").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 }, + ); + return Response.json(conversationPage(list)); + } + 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(); + 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("/", () => ( + <> + +

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("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 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(); + }); +}); + +/** Where each "New conversation" on the page goes. */ +function newConversationLinks(container: HTMLElement): (string | null)[] { + return [...container.querySelectorAll("a")] + .filter((link) => 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 and offers New conversation", async () => { + serve([]); + const { view } = renderApp("/conversations"); + await view.findByText("No conversations yet"); + // The page's own, and the empty state's. + expect(newConversationLinks(view.container)).toEqual([ + "/channel/new", + "/channel/new", + ]); + // Nothing to search yet. + expect( + view.queryByRole("textbox", { name: "Search conversations" }), + ).toBeNull(); + }); + + 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(); + }); +}); + +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 }, + { type: "route", path: "/bots", tab: "bots", signedIn: false }, + { + type: "route", + path: "/conversations", + tab: "conversations", + signedIn: false, + }, + { type: "route", path: "/", tab: "home", signedIn: false }, + ]), + ); + // Opening the page already open adds no history entry. + expect(router.history.length).toBe(4); + }); + + 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("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("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"); + }); +}); diff --git a/app/tests/native-shell.test.ts b/app/tests/native-shell.test.ts new file mode 100644 index 0000000000..429f41fd4b --- /dev/null +++ b/app/tests/native-shell.test.ts @@ -0,0 +1,289 @@ +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. + */ + +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: "/" }, + 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: "", + storage: memoryStorage(), + }), + platform: null, + }, + { + name: "what the shell injects", + environment: () => ({ + injected: { platform: "android", version: "0.1", bridge: 1 }, + userAgent: IPHONE, + search: "", + storage: memoryStorage(), + }), + platform: "android", + }, + { + name: "something injected that is not the shell's", + environment: () => ({ + injected: { platform: "windows" }, + userAgent: IPHONE, + search: "", + storage: memoryStorage(), + }), + platform: null, + }, + { + name: "the shell's user agent on iOS", + environment: () => ({ + injected: undefined, + userAgent: `${IPHONE} OpenBotShell-iOS/0.1`, + search: "", + 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: "", + storage: memoryStorage(), + }), + platform: "android", + }, + { + name: "?native-shell=ios for testing", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + storage: memoryStorage(), + }), + platform: "test", + }, + { + name: "the override remembered by the tab", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "", + storage: memoryStorage({ [NATIVE_SHELL_STORAGE_KEY]: "test" }), + }), + platform: "test", + }, + { + name: "?native-shell=off forgetting it", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=off", + 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", + storage: memoryStorage(), + }), + platform: "ios", + }, + { + name: "?native-shell=ios where storage throws", + environment: () => ({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + storage: { + getItem: () => { + throw new Error("denied"); + }, + setItem: () => { + throw new Error("denied"); + }, + removeItem: () => { + throw new Error("denied"); + }, + }, + }), + 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).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("the override is remembered for the tab, and forgotten again", () => { + const storage = memoryStorage(); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=ios", + storage, + }); + expect(storage.values.get(NATIVE_SHELL_STORAGE_KEY)).toBe("test"); + detectNativeShell({ + injected: undefined, + userAgent: IPHONE, + search: "?native-shell=off", + 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, + }; + + 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(); + }); +}); From b8775631712f79e00e6a559dfc09a16aece5c2a6 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:32:45 -0800 Subject: [PATCH 06/39] Inside the native shell, a screen's title sits closer to the top The phone app's status bar is already above the page, so PageShell keeps 24px above the title there (16px under a Back bar), not 48px (32px). A browser keeps the spacing it had. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/src/components/layout/page-parts.tsx | 6 ++++-- app/src/components/layout/page-shell.tsx | 8 +++++++- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/app/src/components/layout/page-parts.tsx b/app/src/components/layout/page-parts.tsx index 1e7969c99b..c349d109b9 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 { Empty, @@ -65,8 +66,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 5e946a2a5f..87495e1fd5 100644 --- a/app/src/components/layout/page-shell.tsx +++ b/app/src/components/layout/page-shell.tsx @@ -2,6 +2,7 @@ import { IconChevronLeft } from "@tabler/icons-react"; import { Link, type LinkProps } from "@tanstack/react-router"; import type * as React from "react"; import { createContext, useContext } from "react"; +import { nativeShell } from "@/lib/native-shell/shell"; import { cn } from "@/lib/utils"; import { Button } from "../ui/button"; import { PageColumn, PageHeader, type ShellWidth } from "./page-parts"; @@ -109,7 +110,12 @@ export function PageShell({ */
{barRow} -
+
{header}
From 3519dacf0f1868a978b9e17d0387800905e05418 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 15:32:45 -0800 Subject: [PATCH 07/39] Inside the native shell, the account menu is at the top of the tab pages With no sidebar there was no way to Settings, Admin or Sign out. Home, Conversations and Bots now show the sidebar's own account menu at their top right, as the person's avatar named Account, opening below it. It is the same menu, made able to open below as well as beside the strip, and it needs no sidebar now. On Conversations, New conversation is the icon alone there, so both fit beside the title on a phone. A browser draws none of this. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- .../components/app-sidebar/account-label.tsx | 18 +++++++- .../components/app-sidebar/section-strip.tsx | 22 +++++++--- .../layout/native-shell-account.tsx | 15 +++++++ app/src/components/layout/sidebar-toggle.tsx | 2 +- app/src/routes/_authed/_app/bots.index.tsx | 25 ++++++----- app/src/routes/_authed/_app/conversations.tsx | 37 ++++++++++++---- app/src/routes/_authed/_app/index.tsx | 3 ++ app/tests/native-shell-app.test.tsx | 42 ++++++++++++++++++- app/tests/native-shell.test.ts | 2 +- 9 files changed, 137 insertions(+), 29 deletions(-) create mode 100644 app/src/components/layout/native-shell-account.tsx diff --git a/app/src/components/app-sidebar/account-label.tsx b/app/src/components/app-sidebar/account-label.tsx index 057bd8a5c2..80194326c1 100644 --- a/app/src/components/app-sidebar/account-label.tsx +++ b/app/src/components/app-sidebar/account-label.tsx @@ -111,7 +111,20 @@ 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 whole account row (`AccountLabel`), version included. */ -export function AccountMenu({ children }: { children: ReactNode }) { +export function AccountMenu({ + children, + label, + 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; + /** 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 ( @@ -120,6 +133,7 @@ export function AccountMenu({ children }: { children: ReactNode }) { } @@ -130,7 +144,7 @@ export function AccountMenu({ children }: { children: ReactNode }) { {organization ? `${person}, ${organization}` : person} - + {person} {organization ? ( diff --git a/app/src/components/app-sidebar/section-strip.tsx b/app/src/components/app-sidebar/section-strip.tsx index 9b6f2d5ff6..989e1d418e 100644 --- a/app/src/components/app-sidebar/section-strip.tsx +++ b/app/src/components/app-sidebar/section-strip.tsx @@ -12,7 +12,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 { appConfig } from "@/lib/generated/application-config"; import { @@ -140,8 +140,19 @@ function PageItem({ item }: { item: NavigationLink }) { /** * The account at the strip's foot, and the menu it opens: organizations, the account's pages, Get * the desktop app on OpenBot Cloud, Get troubleshooting logs, Sign out. + * + * 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, + side = "right", +}: { + /** The button's name, in place of the person's (see `AccountMenu`). */ + label?: string; + /** Beside the strip, or below a page's header. */ + side?: "right" | "bottom"; +} = {}) { const navigation = useNavigationItems(); const signOut = useSignOut(); const signOutOffered = useSignOutOffered(); @@ -149,13 +160,14 @@ 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 ?? (() => {}); return ( - + 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..6f4eaa0dd9 --- /dev/null +++ b/app/src/components/layout/native-shell-account.tsx @@ -0,0 +1,15 @@ +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. + */ +export function ShellAccountMenu() { + if (!nativeShell()) return null; + return ; +} diff --git a/app/src/components/layout/sidebar-toggle.tsx b/app/src/components/layout/sidebar-toggle.tsx index c26a9713c1..006029ae10 100644 --- a/app/src/components/layout/sidebar-toggle.tsx +++ b/app/src/components/layout/sidebar-toggle.tsx @@ -134,7 +134,7 @@ export function SidebarToggleBar({ children }: { children?: ReactNode }) { */ if (!useOptionalSidebar()) { return children ? ( -
+
{children}
) : null; diff --git a/app/src/routes/_authed/_app/bots.index.tsx b/app/src/routes/_authed/_app/bots.index.tsx index 95649a6932..379cd43235 100644 --- a/app/src/routes/_authed/_app/bots.index.tsx +++ b/app/src/routes/_authed/_app/bots.index.tsx @@ -8,6 +8,7 @@ import { useQuery } from "@tanstack/react-query"; import { createFileRoute, Link } from "@tanstack/react-router"; import { z } from "zod"; import { NewBotSheet } from "@/components/agents/new-bot-sheet"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; import { BotRoster } from "@/components/bots/bot-roster"; import { PageRows, @@ -49,16 +50,20 @@ function BotsPage() { return ( ( - - )} - size="sm" - variant="ghost" - > - - 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/conversations.tsx b/app/src/routes/_authed/_app/conversations.tsx index ac91f4f0d8..7f7d7c6863 100644 --- a/app/src/routes/_authed/_app/conversations.tsx +++ b/app/src/routes/_authed/_app/conversations.tsx @@ -14,6 +14,7 @@ import { SearchResults, useDebounced, } from "@/components/app-sidebar/conversations-panel"; +import { ShellAccountMenu } from "@/components/layout/native-shell-account"; import { PageEmpty, PageRows, PageShell } from "@/components/layout/page-shell"; import { Button } from "@/components/ui/button"; import { @@ -27,6 +28,7 @@ import { normalizeChannelSearch, } from "@/lib/channels/queries"; import { loadFailure } from "@/lib/load-failure"; +import { nativeShell } from "@/lib/native-shell/shell"; import { useConversationView } from "@/lib/settings/conversation-view"; import { useMessageListEmphasis } from "@/lib/settings/message-list"; import { delegatingConversationsQueryOptions } from "@/lib/tasks/queries"; @@ -63,18 +65,37 @@ function ConversationsPage() { const searching = term.length > 0; const searchable = isChannelSearchable(term); const rows = pinnedFirst(channels.data ?? []); + const shell = nativeShell() !== null; return ( } - size="sm" - variant="ghost" - > - - New conversation - +
+ {/* + * 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" > diff --git a/app/src/routes/_authed/_app/index.tsx b/app/src/routes/_authed/_app/index.tsx index 33c9d2b490..02b7fb8ccf 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"; @@ -269,6 +270,8 @@ function RouteComponent() { <> + {/* Only inside the phone app's native shell, which has no sidebar. */} +
[] | number | "never") { ); return Response.json(conversationPage(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 }); @@ -185,6 +197,8 @@ function renderApp(path: string) { page("/", () => ( <> + {/* Beside the bar, not in it: another file stands a stub in for the bar (mock.module). */} +

Home

)), @@ -235,6 +249,24 @@ describe("the frame", () => { 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(); + }); + test("in a browser, the sidebar is there as before", async () => { inShell(false); serve([]); @@ -246,13 +278,19 @@ describe("the frame", () => { 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.textContent?.trim() === "New conversation") + .filter( + (link) => + (link.getAttribute("aria-label") ?? link.textContent?.trim()) === + "New conversation", + ) .map((link) => link.getAttribute("href")); } diff --git a/app/tests/native-shell.test.ts b/app/tests/native-shell.test.ts index 429f41fd4b..27430a9f9e 100644 --- a/app/tests/native-shell.test.ts +++ b/app/tests/native-shell.test.ts @@ -183,7 +183,7 @@ describe("which shell the page is in", () => { test(`${name}: ${platform ?? "none"}, the same before the first paint`, () => { expect(detectNativeShell(environment())?.platform ?? null).toBe(platform); const painted = beforeFirstPaint(environment()); - expect(painted.platform).toBe(platform); + 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, From 93ea476005f36d095ed8cb6488d9584cb365cc0b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 17:26:30 -0800 Subject: [PATCH 08/39] Say in the changelog that there is a Conversations page Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- CHANGELOG.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9ab8cc2926..d38f55f704 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **A Conversations page.** `/conversations` lists every conversation, pinned first, with + search and New conversation, as the sidebar's Conversations panel does. Nothing links to it from + the sidebar. It is the page behind the Conversations tab of a phone app that shows the web app in + a native shell: inside such a shell (it names itself in its user agent) the web app draws only + the page, without its sidebar, and leaves sign-in and notifications to the shell. A browser, and + OpenBot Desktop, behave as before. + - **Bots on Gemini 3 no longer stop at their second tool step.** On a Gemini key, through OpenBot Cloud's AI connection or a key saved as Google's OpenAI-compatible endpoint, a Bot on the TypeScript LangGraph engine stopped partway through a task with Google's "Function call is missing From 9bd0418610b458f18041079e0cdadaf7f4fe67ea Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:19:24 -0800 Subject: [PATCH 09/39] In the phone app, keep every field at 16px so iOS does not zoom in on it Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/src/styles.css | 32 ++++++++++++++++++++++++++++++++ app/tests/native-shell.test.ts | 19 +++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/app/src/styles.css b/app/src/styles.css index 30d6d69314..1c71e781d3 100644 --- a/app/src/styles.css +++ b/app/src/styles.css @@ -580,3 +580,35 @@ 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; +} diff --git a/app/tests/native-shell.test.ts b/app/tests/native-shell.test.ts index 27430a9f9e..cac13a6acc 100644 --- a/app/tests/native-shell.test.ts +++ b/app/tests/native-shell.test.ts @@ -287,3 +287,22 @@ describe("telling the shell", () => { ).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;"); + }); +}); From 22767c95b0ba8186117c0eb8dad21b72def29498 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:10:07 -0800 Subject: [PATCH 10/39] In the phone app, a larger Account button and menu rows, in the same place on all three tabs Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- .../components/app-sidebar/account-label.tsx | 23 +++++++++++++++---- .../components/app-sidebar/section-strip.tsx | 19 ++++++++++----- .../layout/native-shell-account.tsx | 5 ++-- app/src/components/layout/sidebar-toggle.tsx | 11 +++++++-- app/tests/native-shell-app.test.tsx | 18 +++++++++++++++ 5 files changed, 62 insertions(+), 14 deletions(-) diff --git a/app/src/components/app-sidebar/account-label.tsx b/app/src/components/app-sidebar/account-label.tsx index 80194326c1..56385bbdbe 100644 --- a/app/src/components/app-sidebar/account-label.tsx +++ b/app/src/components/app-sidebar/account-label.tsx @@ -19,7 +19,7 @@ import { OpenBotVersion } from "../layout/openbot-version"; /** The version's type beside the account, in the menu's row and on the strip: tiny and quiet. */ const versionClassName = "text-[10px] leading-3 text-muted-foreground"; -function UserAvatar() { +function UserAvatar({ large = false }: { large?: boolean }) { const { data: currentUser } = useQuery(currentUserQueryOptions()); const initials = currentUser?.name @@ -32,7 +32,10 @@ function UserAvatar() { return ( @@ -104,6 +107,8 @@ export const accountMenuClassName = "w-max min-w-(--anchor-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 @@ -114,6 +119,7 @@ export const accountMenuItemClassName = "gap-2 px-2 py-1.5"; export function AccountMenu({ children, label, + large = false, side = "right", }: { children: ReactNode; @@ -122,6 +128,11 @@ export function AccountMenu({ * 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"; }) { @@ -134,11 +145,15 @@ export function AccountMenu({ render={ } > - + {/* Read out as the button's name: whose account, and the organization being worked in. */} {organization ? `${person}, ${organization}` : person} diff --git a/app/src/components/app-sidebar/section-strip.tsx b/app/src/components/app-sidebar/section-strip.tsx index 989e1d418e..3d7f99f222 100644 --- a/app/src/components/app-sidebar/section-strip.tsx +++ b/app/src/components/app-sidebar/section-strip.tsx @@ -38,6 +38,7 @@ import { AccountRow, accountMenuClassName, accountMenuItemClassName, + largeAccountMenuItemClassName, StripVersion, } from "./account-label"; import { DesktopAppMenuItem } from "./desktop-app-item"; @@ -146,10 +147,13 @@ function PageItem({ item }: { item: NavigationLink }) { */ 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"; } = {}) { @@ -162,8 +166,11 @@ export function StripAccount({ const switchOrganization = useSwitchOrganization(); // No sidebar in the native shell, so no sheet to close. const setOpenMobile = useOptionalSidebar()?.setOpenMobile ?? (() => {}); + const itemClassName = large + ? largeAccountMenuItemClassName + : accountMenuItemClassName; return ( - + { // A narrow window's sheet would wait behind the dialog. setOpenMobile(false); @@ -189,7 +196,7 @@ export function StripAccount({ .filter((item) => item.section === "account") .map((item) => ( {item.label} ))} - - + + {signOutOffered ? ( ; + return ; } diff --git a/app/src/components/layout/sidebar-toggle.tsx b/app/src/components/layout/sidebar-toggle.tsx index 006029ae10..c5a464a6e2 100644 --- a/app/src/components/layout/sidebar-toggle.tsx +++ b/app/src/components/layout/sidebar-toggle.tsx @@ -8,6 +8,7 @@ import { TooltipContent, TooltipTrigger, } from "@/components/ui/tooltip"; +import { nativeShell } from "@/lib/native-shell/shell"; import { sidebarToggleShown } from "@/lib/sidebar"; import { cn } from "@/lib/utils"; import { useSidebarPanelAvailable } from "./sidebar-shell"; @@ -130,11 +131,17 @@ export function SidebarToggleBar({ children }: { children?: ReactNode }) { /* * With no sidebar at all (the phone app's native shell, `components/layout/native-shell-frame.tsx`) * there is no toggle to keep a place for, so no band: only what the screen put at its end, and - * nothing when that draws nothing (`empty:hidden`). + * nothing when that draws nothing (`empty:hidden`). In the shell its padding is `PageShell`'s + * column's, so Home's account button sits where Conversations and Bots put theirs. */ if (!useOptionalSidebar()) { return children ? ( -
+
{children}
) : null; diff --git a/app/tests/native-shell-app.test.tsx b/app/tests/native-shell-app.test.tsx index dc94462bc5..ae913ce6c8 100644 --- a/app/tests/native-shell-app.test.tsx +++ b/app/tests/native-shell-app.test.tsx @@ -267,6 +267,24 @@ describe("the frame", () => { ).toBeTruthy(); }); + 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"); + }); + test("in a browser, the sidebar is there as before", async () => { inShell(false); serve([]); From b1e931ac45fafcbff795e093cfa09305710763f7 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 27 Nov 2026 22:10:08 -0800 Subject: [PATCH 11/39] In the phone app, larger tap targets for back, New conversation, the conversation header and Home's message box Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012xYtaUjbkB1hwLtK4TEzhq --- app/src/components/channels/composer/composer.tsx | 9 +++++++-- app/src/components/layout/page-shell.tsx | 2 ++ app/src/routes/_authed/_app/channel/$channelId.tsx | 8 +++++++- app/src/routes/_authed/_app/conversations.tsx | 2 ++ 4 files changed, 18 insertions(+), 3 deletions(-) diff --git a/app/src/components/channels/composer/composer.tsx b/app/src/components/channels/composer/composer.tsx index f927d18298..7795e583cd 100644 --- a/app/src/components/channels/composer/composer.tsx +++ b/app/src/components/channels/composer/composer.tsx @@ -42,6 +42,7 @@ import { shouldClaimPaste, } from "@/lib/channels/attachments"; import type { ComposerAttachmentLimits } from "@/lib/deployment/queries"; +import { nativeShell } from "@/lib/native-shell/shell"; import { newId } from "@/lib/new-id"; import { stopIfNeedsCard } from "@/lib/plan/queries"; import { cn } from "@/lib/utils"; @@ -1828,7 +1829,8 @@ export function Composer({ draft.isEmpty && draft.attachments.length === 0 ? voiceCall : undefined; const actionClassName = cn( "rounded-full p-0", - compact ? "size-8 self-end" : "size-7", + // The phone app draws Home's at the conversation's 32px, the easier size to hit. + compact ? "size-8 self-end" : nativeShell() ? "size-8" : "size-7", ); const primaryAction = canStop ? ( ) : (