diff --git a/apps/mobile/app/(tabs)/account/index.tsx b/apps/mobile/app/(tabs)/account/index.tsx index de967a00..130730e3 100644 --- a/apps/mobile/app/(tabs)/account/index.tsx +++ b/apps/mobile/app/(tabs)/account/index.tsx @@ -1,31 +1,24 @@ -import type { AvatarStyle } from "@milo/contracts"; +import type { AvatarStyle, Connection, ConnectionCatalogItem } from "@milo/contracts"; +import { abortableDelay, buildFeaturedConnectorTiles } from "@milo/core"; import { useLocalSearchParams, useRouter } from "expo-router"; -import { useEffect, useState, useSyncExternalStore } from "react"; +import { useEffect, useRef, useState } from "react"; import { ActivityIndicator, Alert, - Button, - Platform, + Image, + Linking, Pressable, ScrollView, StyleSheet, - Switch, Text, - TextInput, View, } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; +import { AgentLogo } from "../../../components/agent-logo"; import { useAvatarStyle } from "../../../components/avatar-style"; import { BotAvatar } from "../../../components/bot-avatar"; -import type { MobileBot, MobileMe } from "../../../lib/api"; -import { - currentApiBase, - deleteAccount, - loadSessionToken, - rpc, - selectedSpaceId, - signOut, -} from "../../../lib/api"; +import type { MobileMe, MobileModelCredential } from "../../../lib/api"; +import { rpc, signOut } from "../../../lib/api"; import { formatUpdateLabel, getAppVersionInfo } from "../../../lib/app-version"; import { getCachedAppearancePreference, @@ -33,62 +26,28 @@ import { setAppearancePreference, } from "../../../lib/appearance"; import { explicitSignInRoute } from "../../../lib/auth-routing"; -import { confirmDeleteBot } from "../../../lib/bot-lifecycle"; import { setUiLocale, useI18n } from "../../../lib/i18n"; -import type { LiveNotificationSettings } from "../../../lib/live-notifications"; -import { - canPostPromotedNotifications, - DEFAULT_LIVE_NOTIFICATION_SETTINGS, - getLiveNotificationSettings, - openLiveNotificationSettings, - openPromotedNotificationSettings, - setLiveNotificationSettings, -} from "../../../lib/live-notifications"; import { presentMessageActionSheet } from "../../../lib/message-action-sheet"; import { native, useResolvedAppearance, useThemedStyles } from "../../../lib/native"; -import { registerPushToken } from "../../../lib/push"; -import { - getCachedResponseStreamingEnabled, - setResponseStreamingPreference, - subscribeResponseStreaming, -} from "../../../lib/response-streaming"; import type { AccountUiLocale } from "../../../lib/ui-locale"; import { ACCOUNT_UI_LOCALES, UI_LOCALE_LABELS } from "../../../lib/ui-locale"; -/** Render account settings, including the entry point for voice configuration. */ +/** Settings is Usage, General, Allow list and Updates. Voice stays until thread C removes it. */ export default function Account() { const { t, locale } = useI18n(); const colorScheme = useResolvedAppearance(); const router = useRouter(); const { focus } = useLocalSearchParams<{ focus?: string }>(); const [me, setMe] = useState(null); - const [password, setPassword] = useState(""); + const [chatgpt, setChatgpt] = useState(false); const [localeSaving, setLocaleSaving] = useState(false); const [localeError, setLocaleError] = useState(null); const [pending, setPending] = useState(false); const [avatarPending, setAvatarPending] = useState(false); const [avatarError, setAvatarError] = useState(null); - const [notifications, setNotifications] = useState( - DEFAULT_LIVE_NOTIFICATION_SETTINGS, - ); - const [notificationsReady, setNotificationsReady] = useState(Platform.OS !== "android"); - const [notificationPending, setNotificationPending] = useState(false); - const [notificationError, setNotificationError] = useState(null); const [error, setError] = useState(null); - const [archivedBots, setArchivedBots] = useState([]); - const [usage, setUsage] = useState<{ - runs: number; - inputTokens: number; - outputTokens: number; - } | null>(null); const { avatarStyle, updateAvatarStyle } = useAvatarStyle(); const appearance = getCachedAppearancePreference(); - const streamReplies = useSyncExternalStore( - subscribeResponseStreaming, - getCachedResponseStreamingEnabled, - () => false, - ); - const [advancedOpen, setAdvancedOpen] = useState(false); const styles = useThemedStyles(createAccountStyles); const versionInfo = getAppVersionInfo(); const updateLabel = formatUpdateLabel(versionInfo.update, t); @@ -98,45 +57,14 @@ export default function Account() { void rpc("me") .then(setMe) .catch(() => undefined); - void rpc("bots/listArchived") - .then(setArchivedBots) - .catch(() => undefined); - void rpc<{ runs: number; inputTokens: number; outputTokens: number }>("usage/summary") - .then(setUsage) + void rpc("models/credentials") + .then((rows) => setChatgpt(rows.some((row) => row.provider === "chatgpt"))) .catch(() => undefined); - if (Platform.OS === "android") { - void getLiveNotificationSettings() - .then(setNotifications) - .catch(() => undefined) - .finally(() => setNotificationsReady(true)); - } }, []); - const usageBlock = ( - - {t("Usage")} - {usage ? ( - - {t("{runs} runs · {tokens} tokens", { - runs: usage.runs, - tokens: usage.inputTokens + usage.outputTokens, - })} - - ) : null} - - ); - - async function restoreBot(botId: string) { - try { - await rpc("bots/restore", { botId }); - setArchivedBots((bots) => bots.filter((bot) => bot.id !== botId)); - } catch (restoreError) { - Alert.alert( - t("Could not restore bot"), - restoreError instanceof Error ? restoreError.message : t("Try again."), - ); - } - } + useEffect(() => { + if (focus === "usage") router.push("/agent-models"); + }, [focus, router]); async function selectAvatarStyle(next: AvatarStyle) { if (next === avatarStyle) return; @@ -164,50 +92,6 @@ export default function Account() { } } - async function updateNotifications(next: LiveNotificationSettings) { - const previous = notifications; - setNotifications(next); - setNotificationPending(true); - setNotificationError(null); - try { - await setLiveNotificationSettings( - next, - currentApiBase(), - await loadSessionToken(), - selectedSpaceId() ?? "", - ); - if (next.liveConnection && !(await canPostPromotedNotifications())) { - await openPromotedNotificationSettings(); - } - await registerPushToken(); - } catch (cause) { - setNotifications(previous); - setNotificationError( - cause instanceof Error ? cause.message : t("Could not update notifications"), - ); - } finally { - setNotificationPending(false); - } - } - - function confirmDeletion() { - setError(null); - Alert.alert( - t("Delete your account?"), - t( - "This permanently deletes your account, bots, conversations, memories, files, and saved connections. This cannot be undone.", - ), - [ - { text: t("Cancel"), style: "cancel" }, - { - text: t("Delete account"), - style: "destructive", - onPress: () => void handleDeletion(), - }, - ], - ); - } - function applyLocale(code: AccountUiLocale) { if (code === locale || localeSaving) return; setLocaleSaving(true); @@ -233,43 +117,32 @@ export default function Account() { }); } - async function handleDeletion() { - setPending(true); - setError(null); - try { - await deleteAccount(password); - router.dismissAll(); - router.replace("/sign-in"); - } catch (err) { - setError(err instanceof Error ? err.message : t("Could not delete account")); - } finally { - setPending(false); - } - } - return ( - - ) : null} + -
- - - Advanced - - - -
-
- { - setStreamReplies(checked); - setResponseStreamingPreference(checked ? "on" : "off"); - }} - /> - -
-
- { - setShowToolActivity(checked); - setToolActivityPreference(checked ? "on" : "off"); - }} - /> - -
-
-
+
+ { + setShowToolActivity(checked); + setToolActivityPreference(checked ? "on" : "off"); + }} + /> + +
+ +
+ +
); } -export function UsageSettingsPanel({ - usage, - panelRef, - ownKeys = true, -}: { - usage?: { runs: number; inputTokens: number; outputTokens: number } | null; - panelRef?: RefObject; - /** Spend goes to the person's provider keys rather than an agent's plan. */ - ownKeys?: boolean; -}) { - // Nothing to say yet: keep only the focus target so the plan cards lead. - if (!usage && !ownKeys) { - return ( -
- ); +/** The featured catalog apps plus any other connected app, each with Connect or Disconnect. */ +function ConnectedAppsSection() { + const { t } = useLingui(); + const [catalog, setCatalog] = useState(null); + const [connections, setConnections] = useState([]); + const [pending, setPending] = useState(null); + const [error, setError] = useState(null); + const attempt = useRef(null); + + async function refresh() { + const [nextCatalog, nextConnections] = await Promise.all([ + rpc.connections.catalog({}), + rpc.connections.list(), + ]); + setCatalog(nextCatalog); + setConnections(nextConnections); } - return ( -
- {usage ? ( -

- - {usage.runs} runs · {usage.inputTokens + usage.outputTokens} tokens - -

- ) : null} - {ownKeys ? ( -

- Model spend uses your provider keys. -

- ) : null} -
- ); -} -export function ComputerSettingsPanel() { - return ( -
-

- Computers -

- -
- ); -} + useEffect(() => { + void refresh().catch(() => setCatalog([])); + return () => attempt.current?.abort(); + }, []); -export function UpdatesSettingsPanel({ - isDeploymentOwner = false, -}: { - isDeploymentOwner?: boolean; -}) { - return ( -
- - -
+ if (!catalog?.length) return null; + const featured = buildFeaturedConnectorTiles(catalog).flatMap((tile) => + tile.item ? [{ label: tile.label, item: tile.item }] : [], ); -} - -function ChangePasswordSection({ email }: { email?: string | null }) { - const { t } = useLingui(); - const [currentPassword, setCurrentPassword] = useState(""); - const [newPassword, setNewPassword] = useState(""); - const [confirmation, setConfirmation] = useState(""); - const [pending, setPending] = useState(false); - const [saved, setSaved] = useState(false); - const [error, setError] = useState(null); + const apps = [ + ...featured, + ...catalog + .filter((item) => item.connected && !featured.some((app) => app.item === item)) + .map((item) => ({ label: item.name, item })), + ]; - async function changePassword() { - if (pending) return; - if (newPassword !== confirmation) { - setError(t`Passwords do not match`); - return; + async function connect(label: string, item: ConnectionCatalogItem) { + attempt.current?.abort(); + const controller = new AbortController(); + attempt.current = controller; + setPending(item.slug); + setError(null); + try { + const outcome = await connectCatalogApp(item, label, controller.signal); + if (outcome === "pending") setError(t`Connection to ${label} is still pending.`); + await refresh(); + } catch (err) { + if (!controller.signal.aborted) { + setError(err instanceof Error ? err.message : t`Could not connect`); + } + } finally { + if (attempt.current === controller) { + attempt.current = null; + setPending(null); + } } - setPending(true); - setSaved(false); + } + + async function disconnect(item: ConnectionCatalogItem) { + setPending(item.slug); setError(null); try { - const result = await authClient.changePassword({ - currentPassword, - newPassword, - revokeOtherSessions: true, - }); - if (result.error) { - setError(result.error.message ?? t`Could not change password`); - return; + for (const row of appConnections(connections, item)) { + await rpc.connections.revoke({ connectionId: row.id }); } - setCurrentPassword(""); - setNewPassword(""); - setConfirmation(""); - setSaved(true); - } catch { - setError(t`Could not reach the server`); + await refresh(); + } catch (err) { + setError(err instanceof Error ? err.message : t`Could not revoke connection`); } finally { - setPending(false); + setPending(null); } } return ( -
+

- Password + Apps

-
- - - - -
+
    + {apps.map(({ label, item }) => ( +
  • + + {label} + {pending === item.slug ? ( + + Connecting… + + ) : item.connected ? ( + + ) : ( + + )} +
  • + ))} +
{error ? ( -

+

{error}

) : null} -
- - {saved ? : null} -
); } -function SettingsPasswordInput({ - label, - autoComplete, - value, - onChange, -}: { - label: string; - autoComplete: "current-password" | "new-password"; - value: string; - onChange: (value: string) => void; -}) { - const id = useId(); - return ( - - {label} - onChange(event.target.value)} - /> - +function appConnections(connections: Connection[], item: ConnectionCatalogItem) { + return connections.filter( + (row) => + row.connectorId === item.connectorId && + row.provider === item.slug && + (row.status === "connected" || row.status === "pending"), ); } +export function UpdatesSettingsPanel() { + return ; +} + function AppearancePicker({ value, onChange, diff --git a/apps/web/src/pages/AgentModelsPanel.tsx b/apps/web/src/pages/AgentModelsPanel.tsx index 9adc1ce8..5f64dafa 100644 --- a/apps/web/src/pages/AgentModelsPanel.tsx +++ b/apps/web/src/pages/AgentModelsPanel.tsx @@ -40,7 +40,20 @@ export function AgentModelsPanel() {

); } - if (!models) return null; + if (!models) { + return ( +

+ Loading… +

+ ); + } + if (models.length === 0) { + return ( +

+ Limits show after the next run. +

+ ); + } return (
    {models.map((model) => { diff --git a/apps/web/src/pages/LocalSettings.tsx b/apps/web/src/pages/LocalSettings.tsx index 75b20b8c..7a08bc93 100644 --- a/apps/web/src/pages/LocalSettings.tsx +++ b/apps/web/src/pages/LocalSettings.tsx @@ -3,19 +3,15 @@ import { Button } from "@milo/ui-web"; import { useEffect, useState } from "react"; import { IntegrationSetup } from "../components/integrations/IntegrationSetup"; import { rpc } from "../lib/rpc"; -import { ModelSettingsOverlay } from "./ModelSettingsOverlay"; export function LocalSettingsPage() { - const [section, setSection] = useState<"models" | "integrations" | null>(null); + const [integrations, setIntegrations] = useState(false); const [ready, setReady] = useState(false); - const [modelManaged, setModelManaged] = useState(false); const [error, setError] = useState(false); useEffect(() => { - void Promise.all([rpc.integrationSetup.get(), rpc.me()]) - .then(([, me]) => { - setModelManaged(me.modelManaged); - setReady(true); - }) + void rpc.integrationSetup + .get() + .then(() => setReady(true)) .catch(() => setError(true)); }, []); return ( @@ -35,22 +31,11 @@ export function LocalSettingsPage() { {ready ? ( <> - {section === "models" ? ( - setSection(null)} localOwner /> - ) : null} - {section === "integrations" ? : null} + {integrations ? : null} ) : null}
diff --git a/apps/web/src/pages/SettingsOverlay.test.tsx b/apps/web/src/pages/SettingsOverlay.test.tsx new file mode 100644 index 00000000..84bbef01 --- /dev/null +++ b/apps/web/src/pages/SettingsOverlay.test.tsx @@ -0,0 +1,77 @@ +// @vitest-environment jsdom + +import type { ReactNode } from "react"; +import { act } from "react"; +import { createRoot } from "react-dom/client"; +import { afterEach, expect, it, vi } from "vitest"; + +const bridge = vi.hoisted(() => ({ current: undefined as { update?: object } | undefined })); + +const lingui = vi.hoisted(() => { + const translate = (msg: { message?: string } | TemplateStringsArray) => { + if (typeof msg === "object" && msg !== null && "message" in msg) { + return String(msg.message ?? ""); + } + return Array.from(msg as TemplateStringsArray).join(""); + }; + return { useLingui: () => ({ t: translate, _: translate }) }; +}); +vi.mock("@lingui/react/macro", () => lingui); +vi.mock("@lingui/react", () => lingui); +vi.mock("@milo/ui-web", () => { + const Pass = ({ children }: { children?: ReactNode }) =>
{children}
; + return { + Button: () => null, + Dialog: Pass, + DialogClose: () => null, + DialogContent: Pass, + DialogTitle: Pass, + }; +}); +vi.mock("../components/ApprovalRulesSettings", () => ({ ApprovalRulesSettings: () => null })); +vi.mock("../lib/desktop", () => ({ desktopBridge: () => bridge.current })); +vi.mock("./AccountSettingsOverlay", () => ({ + GeneralSettingsPanels: () => null, + UpdatesSettingsPanel: () => null, +})); +vi.mock("./AgentModelsPanel", () => ({ AgentModelsPanel: () => null })); +vi.mock("./VoiceSettingsOverlay", () => ({ VoiceSettingsOverlay: () => null })); + +import { SettingsOverlay } from "./SettingsOverlay"; + +afterEach(() => { + bridge.current = undefined; + vi.unstubAllGlobals(); +}); + +async function navIds() { + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + await act(async () => { + root.render( + undefined} + onClose={() => undefined} + />, + ); + }); + const ids = [...container.querySelectorAll("[data-testid^='settings-nav-']")].map((node) => + node.getAttribute("data-testid")?.replace("settings-nav-", ""), + ); + await act(async () => root.unmount()); + container.remove(); + return ids.filter((id) => id !== "voice"); +} + +it("lists Usage, General, Allow list and Updates in the desktop app", async () => { + bridge.current = { update: {} }; + await expect(navIds()).resolves.toEqual(["usage", "general", "approvals", "updates"]); +}); + +it("leaves Updates out of a browser, which has nothing to update", async () => { + await expect(navIds()).resolves.toEqual(["usage", "general", "approvals"]); +}); diff --git a/apps/web/src/pages/SettingsOverlay.tsx b/apps/web/src/pages/SettingsOverlay.tsx index 7eb0b24f..3fc380a6 100644 --- a/apps/web/src/pages/SettingsOverlay.tsx +++ b/apps/web/src/pages/SettingsOverlay.tsx @@ -1,41 +1,15 @@ import { useLingui } from "@lingui/react/macro"; import type { AvatarStyle } from "@milo/contracts"; import { Button, Dialog, DialogClose, DialogContent, DialogTitle } from "@milo/ui-web"; -import { - Bell, - Brain, - CloudDownload, - Gauge, - Monitor, - Settings, - ShieldCheck, - Volume2, - XIcon, -} from "lucide-react"; +import { CloudDownload, Gauge, Settings, ShieldCheck, Volume2, XIcon } from "lucide-react"; import { type ComponentType, useEffect, useRef, useState } from "react"; import { ApprovalRulesSettings } from "../components/ApprovalRulesSettings"; -import { computersAreUnavailable } from "../components/ComputersUnavailableHint"; -import { NotificationSettings } from "../components/NotificationSettings"; -import { - ComputerSettingsPanel, - GeneralSettingsPanels, - UpdatesSettingsPanel, - UsageSettingsPanel, -} from "./AccountSettingsOverlay"; +import { desktopBridge } from "../lib/desktop"; +import { GeneralSettingsPanels, UpdatesSettingsPanel } from "./AccountSettingsOverlay"; import { AgentModelsPanel } from "./AgentModelsPanel"; -import { SpaceMemorySection } from "./KnowledgeSection"; -import { ModelSettingsOverlay } from "./ModelSettingsOverlay"; import { VoiceSettingsOverlay } from "./VoiceSettingsOverlay"; -export type SettingsSection = - | "general" - | "usage" - | "approvals" - | "notifications" - | "memory" - | "voice" - | "computer" - | "updates"; +export type SettingsSection = "general" | "usage" | "approvals" | "voice" | "updates"; type NavItem = { id: SettingsSection; @@ -43,31 +17,28 @@ type NavItem = { icon: ComponentType<{ className?: string; strokeWidth?: number }>; }; +/** Settings is Usage, General, Allow list and Updates. */ export function SettingsOverlay({ email, name, - usage, - initialSection = "general", avatarStyle, onAvatarStyleChange, - isDeploymentOwner = false, - modelManaged = false, - sandboxProvider, + initialSection = "general", onClose, onVoiceStatusMaybeChanged, - onBotUpdated, }: { email?: string | null; name: string; - usage?: { runs: number; inputTokens: number; outputTokens: number } | null; - initialSection?: SettingsSection; avatarStyle: AvatarStyle; onAvatarStyleChange: (style: AvatarStyle) => Promise; + initialSection?: SettingsSection; + onClose: () => void; + onVoiceStatusMaybeChanged?: () => void | Promise; + // Still passed by the shell; nothing in v0 settings reads them. + usage?: { runs: number; inputTokens: number; outputTokens: number } | null; isDeploymentOwner?: boolean; modelManaged?: boolean; sandboxProvider?: string | null; - onClose: () => void; - onVoiceStatusMaybeChanged?: () => void | Promise; onBotUpdated?: () => void; }) { const { t } = useLingui(); @@ -75,7 +46,8 @@ export function SettingsOverlay({ const usageRef = useRef(null); const [section, setSection] = useState(initialSection); const [voiceBusy, setVoiceBusy] = useState(false); - const showComputer = isDeploymentOwner && computersAreUnavailable(sandboxProvider); + // The desktop app updates itself; a browser has nothing to update here. + const showUpdates = Boolean(desktopBridge()?.update); const panelBusy = voiceBusy; useEffect(() => { @@ -89,14 +61,11 @@ export function SettingsOverlay({ }, [section]); const navItems: NavItem[] = [ + { id: "usage", label: t`Usage`, icon: Gauge }, { id: "general", label: t`General`, icon: Settings }, - { id: "usage", label: t`Models`, icon: Gauge }, - { id: "approvals", label: t`Approvals`, icon: ShieldCheck }, - { id: "notifications", label: t`Notifications`, icon: Bell }, - { id: "memory", label: t`Memory`, icon: Brain }, + { id: "approvals", label: t`Allow list`, icon: ShieldCheck }, { id: "voice", label: t`Voice`, icon: Volume2 }, - ...(showComputer ? [{ id: "computer" as const, label: t`Computer`, icon: Monitor }] : []), - { id: "updates", label: t`Updates`, icon: CloudDownload }, + ...(showUpdates ? [{ id: "updates" as const, label: t`Updates`, icon: CloudDownload }] : []), ]; const sectionTitle = @@ -106,11 +75,9 @@ export function SettingsOverlay({ const closeLabel = section === "usage" ? t`Close usage settings` - : section === "memory" - ? t`Close memory settings` - : section === "voice" - ? t`Close voice settings` - : t`Close user settings`; + : section === "voice" + ? t`Close voice settings` + : t`Close user settings`; async function refreshVoiceStatus() { await onVoiceStatusMaybeChanged?.(); @@ -125,8 +92,7 @@ export function SettingsOverlay({ leaveSettings(onClose); } - const showModels = section === "usage" && !modelManaged; - const widePane = showModels || section === "voice"; + const widePane = section === "voice"; return ( ) : null} - {section === "usage" && !showModels ? ( - <> - -
- -
- - ) : null} - {section === "approvals" ? : null} - {section === "notifications" ? ( - - ) : null} - {section === "computer" && showComputer ? : null} - {section === "updates" ? ( - - ) : null} - {showModels ? ( - <> -
- -
- - - ) : null} - {section === "memory" ? ( -
- + {section === "usage" ? ( +
+
) : null} + {section === "approvals" ? : null} + {section === "updates" && showUpdates ? : null} {section === "voice" ? ( ) : null}