Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion .github/workflows/staging-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,13 @@ jobs:
echo "HQBASE_STAGING_AUTH_SECRET=$AUTH_SECRET" >> "$GITHUB_ENV"
AUTH_SECRET="$AUTH_SECRET" node --input-type=module -e '
import { writeFileSync } from "node:fs";
writeFileSync("/tmp/hqbase-e2e-secrets.json", `${JSON.stringify({ BETTER_AUTH_SECRET: process.env.AUTH_SECRET })}\n`, { mode: 0o600 });
import webpush from "web-push";
const vapid = webpush.generateVAPIDKeys();
writeFileSync("/tmp/hqbase-e2e-secrets.json", `${JSON.stringify({
BETTER_AUTH_SECRET: process.env.AUTH_SECRET,
VAPID_PUBLIC_KEY: vapid.publicKey,
VAPID_PRIVATE_KEY: vapid.privateKey
})}\n`, { mode: 0o600 });
'
pnpm build
pnpm exec wrangler d1 migrations apply DB --remote --config "$config"
Expand Down
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
# Changelog

## 0.1.23

- Add explicit per-device Web Push notifications for installed iOS, Android, and desktop PWAs.
- Show exact accessible Inbox and Catch-all unread totals in navigation, the document title, and
supported installed-app badges.
- Generate customer-owned VAPID secrets during installation and updates while keeping notification
payloads free of mail metadata.

## 0.1.22

- Keep the mobile and installed PWA shell below the iPhone Dynamic Island while preserving the
Expand Down
7 changes: 7 additions & 0 deletions app/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type { Mailbox } from "@/features/mailboxes/types";
import { listConversations, listMessages } from "@/features/messages/api";
import { mergeIncomingMessageIds } from "@/features/messages/incoming-sound";
import type { ConversationSummary } from "@/features/messages/types";
import { useNotifications } from "@/features/notifications/use-notifications";
import { SettingsPage } from "@/features/settings/settings-page";
import { getSetupStatus } from "@/features/setup/api";
import { SetupPage } from "@/features/setup/setup-page";
Expand Down Expand Up @@ -91,6 +92,9 @@ export function App(): React.ReactElement {
});
setConversations(nextConversations);
}, [activeFolder, mailboxId, search, user]);
const notifications = useNotifications(currentUserId, () => {
void reloadConversations();
});

React.useEffect(() => {
void reload();
Expand Down Expand Up @@ -184,6 +188,7 @@ export function App(): React.ReactElement {
immersiveOnCompact={activeFolder !== "settings" && selectedId !== null}
mailboxId={mailboxId}
mailboxes={contentMailboxes}
unread={notifications.unread}
search={search}
user={user}
updateInProgress={updateMonitor.progress !== null}
Expand Down Expand Up @@ -215,6 +220,7 @@ export function App(): React.ReactElement {
activeTab={settingsTab}
canManage={user.role === "owner" || user.role === "admin"}
mailboxes={mailboxes}
notifications={notifications}
setup={setup}
users={users}
onRefresh={() => void reload()}
Expand All @@ -231,6 +237,7 @@ export function App(): React.ReactElement {
mailboxes={contentMailboxes}
selectedId={selectedId}
onRefresh={() => void reloadConversations()}
onUnreadChange={notifications.refresh}
onMessageRouteChange={(folder, messageId) =>
navigate({ kind: "mail", folder, messageId })
}
Expand Down
4 changes: 4 additions & 0 deletions app/components/layout/app-shell.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type * as React from "react";
import type { CurrentUser } from "@/features/auth/types";
import type { Mailbox } from "@/features/mailboxes/types";
import type { UnreadCounts } from "@/features/notifications/types";
import type { UpdateStatus } from "@/features/updates/types";
import { UpdateBanner } from "@/features/updates/update-banner";
import { cn } from "@/lib/cn";
Expand All @@ -18,6 +19,7 @@ type AppShellProps = {
user: CurrentUser;
updateInProgress: boolean;
updateStatus: UpdateStatus | null;
unread: UnreadCounts;
onCompose: () => void;
onFolderChange: (folder: FolderId) => void;
onMailboxChange: (mailboxId: string) => void;
Expand All @@ -31,6 +33,7 @@ export function AppShell(props: AppShellProps): React.ReactElement {
<div className="flex h-screen h-[100dvh] overflow-hidden bg-background pt-[env(safe-area-inset-top)] text-foreground">
<Sidebar
activeFolder={props.activeFolder}
unread={props.unread}
user={props.user}
onFolderChange={props.onFolderChange}
onSignedOut={props.onSignedOut}
Expand All @@ -39,6 +42,7 @@ export function AppShell(props: AppShellProps): React.ReactElement {
<div className={cn(props.immersiveOnCompact && "hidden lg:contents")}>
<TopBar
activeFolder={props.activeFolder}
unread={props.unread}
mailboxId={props.mailboxId}
mailboxes={props.mailboxes}
search={props.search}
Expand Down
4 changes: 4 additions & 0 deletions app/components/layout/mobile-navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,21 @@ import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTitle, SheetTrigger } from "@/components/ui/sheet";
import type { CurrentUser } from "@/features/auth/types";
import { McpConnectionDialog } from "@/features/mcp/connection-dialog";
import type { UnreadCounts } from "@/features/notifications/types";
import type { FolderId } from "@/lib/routes";
import { Sidebar } from "./sidebar";

type MobileNavigationProps = {
activeFolder: FolderId;
user: CurrentUser;
unread: UnreadCounts;
onFolderChange: (folder: FolderId) => void;
onSignedOut: () => void;
};

export function MobileNavigation({
activeFolder,
unread,
user,
onFolderChange,
onSignedOut
Expand Down Expand Up @@ -61,6 +64,7 @@ export function MobileNavigation({
<SheetTitle className="sr-only">Navigation</SheetTitle>
<Sidebar
activeFolder={activeFolder}
unread={unread}
drawerAction={
<Button
className="h-11 w-full justify-start gap-2.5 px-2.5 text-sm font-normal text-muted-foreground"
Expand Down
13 changes: 12 additions & 1 deletion app/components/layout/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type * as React from "react";

import { Button } from "@/components/ui/button";
import type { CurrentUser } from "@/features/auth/types";
import type { UnreadCounts } from "@/features/notifications/types";
import { ThemeSwitcher } from "@/features/theme/theme-switcher";
import { cn } from "@/lib/cn";
import type { FolderId } from "@/lib/routes";
Expand All @@ -14,6 +15,7 @@ type SidebarProps = {
activeFolder: FolderId;
drawerAction?: React.ReactNode;
user: CurrentUser;
unread: UnreadCounts;
onFolderChange: (folder: FolderId) => void;
onSignedOut: () => void;
variant?: "desktop" | "drawer";
Expand All @@ -32,6 +34,7 @@ const icons: Record<FolderId, LucideIcon> = {
export function Sidebar({
activeFolder,
drawerAction,
unread,
user,
onFolderChange,
onSignedOut,
Expand All @@ -55,6 +58,8 @@ export function Sidebar({
<nav className="flex flex-1 flex-col gap-0.5">
{mailFolders.map((folder) => {
const Icon = icons[folder.id];
const unreadCount =
folder.id === "inbox" ? unread.inbox : folder.id === "catchall" ? unread.catchall : 0;
return (
<Button
asChild
Expand All @@ -77,7 +82,13 @@ export function Sidebar({
}}
>
<Icon />
{folder.label}
<span className="min-w-0 flex-1 truncate">{folder.label}</span>
{unreadCount > 0 ? (
<span className="ml-auto font-mono text-[11px] text-foreground">
<span className="sr-only">{unreadCount} unread</span>
<span aria-hidden="true">{unreadCount.toLocaleString()}</span>
</span>
) : null}
</a>
</Button>
);
Expand Down
4 changes: 4 additions & 0 deletions app/components/layout/top-bar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import {
import type { CurrentUser } from "@/features/auth/types";
import type { Mailbox } from "@/features/mailboxes/types";
import { McpConnectionDialog } from "@/features/mcp/connection-dialog";
import type { UnreadCounts } from "@/features/notifications/types";
import type { FolderId } from "@/lib/routes";
import { MobileNavigation } from "./mobile-navigation";

Expand All @@ -23,6 +24,7 @@ type TopBarProps = {
mailboxes: Mailbox[];
mailboxId: string;
search: string;
unread: UnreadCounts;
onCompose: () => void;
onFolderChange: (folder: FolderId) => void;
onMailboxChange: (mailboxId: string) => void;
Expand All @@ -36,6 +38,7 @@ export function TopBar({
mailboxes,
mailboxId,
search,
unread,
onCompose,
onFolderChange,
onMailboxChange,
Expand All @@ -49,6 +52,7 @@ export function TopBar({
<header className="flex h-14 w-full shrink-0 items-center gap-2 border-b bg-background px-3 md:px-4">
<MobileNavigation
activeFolder={activeFolder}
unread={unread}
user={user}
onFolderChange={onFolderChange}
onSignedOut={onSignedOut}
Expand Down
4 changes: 4 additions & 0 deletions app/features/auth/api.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { disableCurrentDeviceNotificationsBeforeSignOut } from "@/features/notifications/sign-out";
import { apiGet } from "@/lib/api-client";
import type { CurrentUser } from "./types";

Expand Down Expand Up @@ -30,6 +31,9 @@ export async function signIn(email: string, password: string): Promise<string |
}

export async function signOut(): Promise<void> {
await disableCurrentDeviceNotificationsBeforeSignOut().catch(() => {
// Signing out remains available if browser notification cleanup is unavailable.
});
await fetch("/api/auth/sign-out", {
body: JSON.stringify({}),
credentials: "include",
Expand Down
6 changes: 5 additions & 1 deletion app/features/inbox/inbox-page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ type InboxPageProps = {
mailboxes: Mailbox[];
selectedId: string | null;
onRefresh: () => void;
onUnreadChange: () => void;
onMessageRouteChange: (folder: MailFolderId, messageId: string | null) => void;
onSelect: (messageId: string) => void;
};
Expand All @@ -28,6 +29,7 @@ export function InboxPage({
mailboxes,
selectedId,
onRefresh,
onUnreadChange,
onMessageRouteChange,
onSelect
}: InboxPageProps): React.ReactElement {
Expand Down Expand Up @@ -76,6 +78,7 @@ export function InboxPage({
);
}
onRefreshRef.current();
onUnreadChange();
})
.catch(() => undefined);
}
Expand All @@ -91,7 +94,7 @@ export function InboxPage({
return () => {
cancelled = true;
};
}, [activeFolder, selectedId]);
}, [activeFolder, onUnreadChange, selectedId]);

const selectedThreadId =
thread[0]?.threadId ??
Expand All @@ -117,6 +120,7 @@ export function InboxPage({
if (!selectedId) return;
await runConversationAction(selectedId, action, activeFolder);
onRefresh();
onUnreadChange();
if (
action === "archive" ||
action === "trash" ||
Expand Down
25 changes: 25 additions & 0 deletions app/features/notifications/api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { apiDelete, apiGet, apiPut } from "@/lib/api-client";
import type { NotificationStatus } from "./types";

export type SerializedPushSubscription = {
endpoint: string;
expirationTime: number | null;
keys: {
auth: string;
p256dh: string;
};
};

export function getNotificationStatus(): Promise<NotificationStatus> {
return apiGet<NotificationStatus>("/api/notifications/status");
}

export async function saveNotificationSubscription(
subscription: SerializedPushSubscription
): Promise<void> {
await apiPut("/api/notifications/subscription", subscription);
}

export async function deleteNotificationSubscription(endpoint: string): Promise<void> {
await apiDelete("/api/notifications/subscription", { endpoint });
}
80 changes: 80 additions & 0 deletions app/features/notifications/browser.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { SerializedPushSubscription } from "./api";
import type { UnreadCounts } from "./types";

type BadgeNavigator = Navigator & {
clearAppBadge?: () => Promise<void>;
setAppBadge?: (count?: number) => Promise<void>;
};

export function supportsPushNotifications(): boolean {
return "Notification" in window && "serviceWorker" in navigator && "PushManager" in window;
}

export async function currentPushSubscription(): Promise<PushSubscription | null> {
if (!supportsPushNotifications()) return null;
const registration = await navigator.serviceWorker.ready;
return registration.pushManager.getSubscription();
}

export async function subscribeToPush(publicKey: string): Promise<PushSubscription> {
const permission = await Notification.requestPermission();
if (permission !== "granted") {
throw new Error(
permission === "denied"
? "Notifications are blocked in your browser or system settings."
: "Notification permission was not granted."
);
}
const registration = await navigator.serviceWorker.ready;
return (
(await registration.pushManager.getSubscription()) ??
(await registration.pushManager.subscribe({
applicationServerKey: base64UrlToBytes(publicKey),
userVisibleOnly: true
}))
);
}

export function serializePushSubscription(
subscription: PushSubscription
): SerializedPushSubscription {
const serialized = subscription.toJSON();
const auth = serialized.keys?.auth;
const p256dh = serialized.keys?.p256dh;
if (!serialized.endpoint || !auth || !p256dh) {
throw new Error("The browser returned an incomplete push subscription.");
}
return {
endpoint: serialized.endpoint,
expirationTime: serialized.expirationTime ?? null,
keys: { auth, p256dh }
};
}

export async function applyUnreadIndicators(unread: UnreadCounts): Promise<void> {
document.title = unread.total > 0 ? `(${unread.total}) HQBase` : "HQBase";
const badgeNavigator = navigator as BadgeNavigator;
try {
if (unread.total > 0 && badgeNavigator.setAppBadge) {
await badgeNavigator.setAppBadge(unread.total);
} else if (unread.total === 0 && badgeNavigator.clearAppBadge) {
await badgeNavigator.clearAppBadge();
}
} catch {
// In-app counts remain authoritative when the platform declines app badging.
}
}

export function notificationPermission(): NotificationPermission | "unsupported" {
return supportsPushNotifications() ? Notification.permission : "unsupported";
}

function base64UrlToBytes(value: string): Uint8Array<ArrayBuffer> {
const padding = "=".repeat((4 - (value.length % 4)) % 4);
const binary = atob(`${value}${padding}`.replaceAll("-", "+").replaceAll("_", "/"));
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
for (let index = 0; index < binary.length; index += 1) {
bytes[index] = binary.charCodeAt(index);
}
return bytes;
}
Loading