diff --git a/backend/src/routes/sse.ts b/backend/src/routes/sse.ts index bf8384b2..636e3473 100644 --- a/backend/src/routes/sse.ts +++ b/backend/src/routes/sse.ts @@ -94,7 +94,7 @@ export function createSSERoutes() { if (!result.success) { return c.json({ success: false, error: 'Invalid request', details: result.error.issues }, 400) } - const success = sseAggregator.setClientVisibility(result.data.clientId, result.data.visible) + const success = sseAggregator.setClientVisibility(result.data.clientId, result.data.visible, result.data.activeSessionId ?? null) if (!success) { return c.json({ success: false, error: 'Client not found' }, 404) } diff --git a/backend/src/services/notification.ts b/backend/src/services/notification.ts index ea7ce3ee..89bd9737 100644 --- a/backend/src/services/notification.ts +++ b/backend/src/services/notification.ts @@ -191,10 +191,6 @@ export class NotificationService { return rows.map((r) => r.user_id); } - private hasActiveSSEClients(): boolean { - return sseAggregator.hasVisibleClients(); - } - async handleSSEEvent( _directory: string, event: SSEEvent @@ -202,7 +198,8 @@ export class NotificationService { const config = EVENT_CONFIG[event.type]; if (!config) return; - if (this.hasActiveSSEClients()) return; + const sessionId = event.properties.sessionID as string | undefined; + if (sessionId && sseAggregator.isSessionBeingViewed(sessionId)) return; if (!this.isConfigured()) return; @@ -216,27 +213,38 @@ export class NotificationService { if (!notifPrefs.enabled) continue; if (!notifPrefs.events[config.preferencesKey]) continue; - const sessionId = event.properties.sessionID as string | undefined; - let notificationUrl = "/"; - if (sessionId && _directory) { + let repoName = ""; + let repoId: number | undefined; + + if (_directory) { const reposBasePath = getReposPath(); const localPath = path.relative(reposBasePath, _directory); const repo = getRepoByLocalPath(this.db, localPath); - + if (repo) { - notificationUrl = `/repos/${repo.id}/sessions/${sessionId}`; + repoId = repo.id; + repoName = path.basename(repo.localPath); + if (sessionId) { + notificationUrl = `/repos/${repo.id}/sessions/${sessionId}`; + } else { + notificationUrl = `/repos/${repo.id}`; + } } } + const body = config.bodyFn(event.properties); + const payload: PushNotificationPayload = { - title: config.title, - body: config.bodyFn(event.properties), + title: repoName ? `[${repoName.toUpperCase()}] ${config.title}` : config.title, + body: body, tag: `${event.type}-${sessionId ?? "global"}`, data: { eventType: event.type, sessionId, directory: _directory, + repoId, + repoName, url: notificationUrl, }, }; diff --git a/backend/src/services/sse-aggregator.ts b/backend/src/services/sse-aggregator.ts index a8f4610e..01cb8153 100644 --- a/backend/src/services/sse-aggregator.ts +++ b/backend/src/services/sse-aggregator.ts @@ -11,6 +11,7 @@ interface SSEClient { callback: SSEClientCallback directories: Set visible: boolean + activeSessionId: string | null } interface DirectoryConnection { @@ -51,7 +52,8 @@ class SSEAggregator { id, callback, directories: new Set(directories), - visible: false + visible: false, + activeSessionId: null } this.clients.set(id, client) @@ -353,19 +355,22 @@ class SSEAggregator { return this.clients.size } - setClientVisibility(id: string, visible: boolean): boolean { + setClientVisibility(id: string, visible: boolean, activeSessionId: string | null = null): boolean { const client = this.clients.get(id) if (!client) { logger.warn(`setClientVisibility: client ${id} not found`) return false } client.visible = visible + client.activeSessionId = visible ? activeSessionId : null return true } - hasVisibleClients(): boolean { + isSessionBeingViewed(sessionId: string): boolean { for (const client of this.clients.values()) { - if (client.visible) return true + if (client.visible && client.activeSessionId === sessionId) { + return true + } } return false } diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 49f36c20..79d339c2 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -6,7 +6,7 @@ import tseslint from 'typescript-eslint' import { defineConfig, globalIgnores } from 'eslint/config' export default defineConfig([ - globalIgnores(['dist']), + globalIgnores(['dist', 'src/sw.ts']), { files: ['**/*.{ts,tsx}'], extends: [ diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d4a96a39..b85936b6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,6 +1,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' -import { createBrowserRouter, RouterProvider, Outlet } from 'react-router-dom' +import { createBrowserRouter, RouterProvider, Outlet, useNavigate } from 'react-router-dom' +import { useEffect } from 'react' import { Toaster } from 'sonner' import { Repos } from './pages/Repos' import { RepoDetail } from './pages/RepoDetail' @@ -61,8 +62,19 @@ function PermissionDialogWrapper() { } function AppShell() { + const navigate = useNavigate() useTheme() + useEffect(() => { + const channel = new BroadcastChannel('notification-click') + channel.onmessage = (event: MessageEvent) => { + if (event.data?.url) { + navigate(event.data.url) + } + } + return () => channel.close() + }, [navigate]) + return ( diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx index 5f423922..129197a6 100644 --- a/frontend/src/components/session/SessionCard.tsx +++ b/frontend/src/components/session/SessionCard.tsx @@ -1,10 +1,11 @@ -import { useState, useRef } from "react"; +import { useRef, useEffect } from "react"; import { Card } from "@/components/ui/card"; import { Checkbox } from "@/components/ui/checkbox"; import { MiniScanner } from "@/components/ui/mini-scanner"; import { Trash2, Clock } from "lucide-react"; import { formatDistanceToNow } from "date-fns"; import type { Session } from "@/api/types"; +import { useSwipe } from "@/hooks/useSwipe"; interface SessionCardProps { session: Session; @@ -25,57 +26,26 @@ export const SessionCard = ({ onToggleSelection, onDelete, }: SessionCardProps) => { - const [swipeOffset, setSwipeOffset] = useState(0); - const [isSwipeOpen, setIsSwipeOpen] = useState(false); - const touchStartX = useRef(null); const cardRef = useRef(null); + const { bind, swipeOffset, isOpen, isSwipingBack, close, swipeStyles } = useSwipe(); - const handleTouchStart = (e: React.TouchEvent) => { - touchStartX.current = e.touches[0].clientX; - }; - - const handleTouchMove = (e: React.TouchEvent) => { - if (touchStartX.current === null) return; - - const currentX = e.touches[0].clientX; - const diff = touchStartX.current - currentX; - - if (diff > 0) { - const newOffset = Math.min(diff, 80); - setSwipeOffset(newOffset); - } else if (diff < 0 && isSwipeOpen) { - const newOffset = Math.max(0, 80 + diff); - setSwipeOffset(newOffset); + useEffect(() => { + if (cardRef.current) { + return bind(cardRef.current); } - }; - - const handleTouchEnd = () => { - if (swipeOffset > 50) { - setIsSwipeOpen(true); - setSwipeOffset(80); - } else if (swipeOffset < 30) { - setIsSwipeOpen(false); - setSwipeOffset(0); - } - touchStartX.current = null; - }; - - const closeSwipe = () => { - setSwipeOffset(0); - setIsSwipeOpen(false); - }; + }, [bind]); const handleDeleteClick = (e: React.MouseEvent) => { e.stopPropagation(); onDelete(e); - closeSwipe(); + close(); }; return ( -
+
20 || isSwipeOpen ? "opacity-100" : "opacity-0" + !isSwipingBack && (isOpen || swipeOffset > 40) ? "opacity-100" : "opacity-0" }`} >
-
+
{ - if (!isSwipeOpen) { + if (!isOpen) { onSelect(session.id); } }} diff --git a/frontend/src/components/session/SessionList.tsx b/frontend/src/components/session/SessionList.tsx index af623c22..dfe8c3f5 100644 --- a/frontend/src/components/session/SessionList.tsx +++ b/frontend/src/components/session/SessionList.tsx @@ -167,8 +167,8 @@ export const SessionList = ({ />
-
-
+
+
{filteredSessions.length === 0 ? (
No sessions found diff --git a/frontend/src/hooks/useSSE.ts b/frontend/src/hooks/useSSE.ts index 720a78cf..2a820873 100644 --- a/frontend/src/hooks/useSSE.ts +++ b/frontend/src/hooks/useSSE.ts @@ -43,6 +43,8 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, const client = useOpenCodeClient(opcodeUrl, directory) const queryClient = useQueryClient() const mountedRef = useRef(true) + const sessionIdRef = useRef(currentSessionId) + sessionIdRef.current = currentSessionId const [isConnected, setIsConnected] = useState(false) const [error, setError] = useState(null) const [isReconnecting, setIsReconnecting] = useState(false) @@ -363,7 +365,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, if (connected) { setError(null) fetchInitialData() - sseManager.reportVisibility(document.visibilityState === 'visible') + sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current) } else { setError('Connection lost. Reconnecting...') } @@ -378,7 +380,7 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } const handleVisibilityChange = () => { - sseManager.reportVisibility(document.visibilityState === 'visible') + sseManager.reportVisibility(document.visibilityState === 'visible', sessionIdRef.current) } document.addEventListener('visibilitychange', handleVisibilityChange) @@ -395,5 +397,11 @@ export const useSSE = (opcodeUrl: string | null | undefined, directory?: string, } }, [opcodeUrl, directory, handleSSEEvent, fetchInitialData]) + useEffect(() => { + if (isConnected && document.visibilityState === 'visible') { + sseManager.reportVisibility(true, currentSessionId) + } + }, [currentSessionId, isConnected]) + return { isConnected, error, isReconnecting } } diff --git a/frontend/src/hooks/useSwipe.ts b/frontend/src/hooks/useSwipe.ts new file mode 100644 index 00000000..5fe0199c --- /dev/null +++ b/frontend/src/hooks/useSwipe.ts @@ -0,0 +1,179 @@ +import { useState, useRef, useCallback } from 'react' + +interface SwipeOptions { + threshold?: number + directionRatio?: number + enabled?: boolean + onSwipeStart?: () => void + onSwipeEnd?: () => void +} + +interface SwipeState { + startX: number + startY: number + currentX: number + isSwiping: boolean + directionLocked: 'horizontal' | 'vertical' | null +} + +export function useSwipe(options: SwipeOptions = {}) { + const { + threshold = 80, + directionRatio = 1.5, + enabled = true, + onSwipeStart, + onSwipeEnd, + } = options + + const swipeRef = useRef({ + startX: 0, + startY: 0, + currentX: 0, + isSwiping: false, + directionLocked: null, + }) + + const [swipeOffset, setSwipeOffset] = useState(0) + const [isOpen, setIsOpen] = useState(false) + const isSwipingBackRef = useRef(false) + const isAnimatingRef = useRef(false) + + const handleTouchStart = useCallback((e: TouchEvent) => { + if (!enabled) return + + const touch = e.touches[0] + swipeRef.current = { + startX: touch.clientX, + startY: touch.clientY, + currentX: touch.clientX, + isSwiping: false, + directionLocked: null, + } + isAnimatingRef.current = false + }, [enabled]) + + const handleTouchMove = useCallback((e: TouchEvent) => { + if (!enabled) return + + const state = swipeRef.current + const touch = e.touches[0] + const deltaX = state.startX - touch.clientX + const deltaY = touch.clientY - state.startY + const absDeltaX = Math.abs(deltaX) + const absDeltaY = Math.abs(deltaY) + + if (!state.directionLocked && absDeltaX > 10 || absDeltaY > 10) { + if (absDeltaX > absDeltaY * directionRatio) { + state.directionLocked = 'horizontal' + } else { + state.directionLocked = 'vertical' + } + } + + if (state.directionLocked === 'vertical') { + return + } + + if (state.directionLocked === 'horizontal') { + if (!state.isSwiping) { + state.isSwiping = true + onSwipeStart?.() + } + + e.preventDefault() + + let newOffset: number + if (deltaX > 0) { + isSwipingBackRef.current = false + newOffset = Math.min(deltaX, threshold) + } else if (deltaX < 0 && isOpen) { + isSwipingBackRef.current = true + newOffset = Math.max(0, threshold + deltaX) + } else { + isSwipingBackRef.current = false + newOffset = 0 + } + + state.currentX = touch.clientX + setSwipeOffset(newOffset) + } + }, [enabled, threshold, directionRatio, isOpen, onSwipeStart]) + + const handleTouchEnd = useCallback(() => { + if (!enabled) return + + isAnimatingRef.current = true + onSwipeEnd?.() + + const state = swipeRef.current + + if (swipeOffset > threshold / 2) { + setIsOpen(true) + setSwipeOffset(threshold) + } else { + setIsOpen(false) + setSwipeOffset(0) + } + + state.startX = 0 + state.startY = 0 + state.currentX = 0 + state.isSwiping = false + state.directionLocked = null + }, [enabled, threshold, swipeOffset, onSwipeEnd]) + + const handleTouchCancel = useCallback(() => { + if (!enabled) return + + isAnimatingRef.current = true + setIsOpen(false) + setSwipeOffset(0) + + swipeRef.current = { + startX: 0, + startY: 0, + currentX: 0, + isSwiping: false, + directionLocked: null, + } + }, [enabled]) + + const bind = useCallback((element: HTMLElement | null) => { + if (!element || !enabled) return + + element.addEventListener('touchstart', handleTouchStart, { passive: true }) + element.addEventListener('touchmove', handleTouchMove, { passive: false }) + element.addEventListener('touchend', handleTouchEnd, { passive: true }) + element.addEventListener('touchcancel', handleTouchCancel, { passive: true }) + + return () => { + element.removeEventListener('touchstart', handleTouchStart) + element.removeEventListener('touchmove', handleTouchMove) + element.removeEventListener('touchend', handleTouchEnd) + element.removeEventListener('touchcancel', handleTouchCancel) + } + }, [enabled, handleTouchStart, handleTouchMove, handleTouchEnd, handleTouchCancel]) + + const close = useCallback(() => { + isAnimatingRef.current = true + setIsOpen(false) + setSwipeOffset(0) + }, []) + + const swipeStyles = { + transform: swipeOffset > 0 ? `translateX(-${swipeOffset}px)` : undefined, + transition: isAnimatingRef.current ? 'transform 0.2s ease-out' : undefined, + touchAction: 'pan-y', + } + + const isSwipingBack = isSwipingBackRef.current + + return { + bind, + swipeOffset, + isOpen, + isSwipingBack, + close, + swipeStyles, + } +} diff --git a/frontend/src/lib/sseManager.ts b/frontend/src/lib/sseManager.ts index 15a99b8b..9ddcee57 100644 --- a/frontend/src/lib/sseManager.ts +++ b/frontend/src/lib/sseManager.ts @@ -266,12 +266,12 @@ class SSEManager { return this.isConnected } - reportVisibility(visible: boolean): void { + reportVisibility(visible: boolean, activeSessionId?: string): void { if (!this.clientId || !this.isConnected) return fetch('/api/sse/visibility', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ clientId: this.clientId, visible }) + body: JSON.stringify({ clientId: this.clientId, visible, activeSessionId: activeSessionId ?? null }) }).catch(() => {}) } diff --git a/frontend/src/sw.ts b/frontend/src/sw.ts index 872ef4d6..4c07f2c2 100644 --- a/frontend/src/sw.ts +++ b/frontend/src/sw.ts @@ -25,6 +25,8 @@ interface PushNotificationData { eventType: string; sessionId?: string; directory?: string; + repoId?: number; + repoName?: string; }; } @@ -65,9 +67,10 @@ self.addEventListener("notificationclick", (event) => { .then((clientList) => { for (const client of clientList) { if (new URL(client.url).origin === self.location.origin) { - (client as WindowClient).focus(); - (client as WindowClient).navigate(url); - return; + const channel = new BroadcastChannel("notification-click"); + channel.postMessage({ url }); + channel.close(); + return (client as WindowClient).focus(); } } return self.clients.openWindow(url); diff --git a/shared/src/schemas/notifications.ts b/shared/src/schemas/notifications.ts index ee3eaed5..4726533e 100644 --- a/shared/src/schemas/notifications.ts +++ b/shared/src/schemas/notifications.ts @@ -64,6 +64,8 @@ export const PushNotificationPayloadSchema = z.object({ eventType: z.string(), sessionId: z.string().optional(), directory: z.string().optional(), + repoId: z.number().optional(), + repoName: z.string().optional(), }) .optional(), }); diff --git a/shared/src/schemas/sse.ts b/shared/src/schemas/sse.ts index 082f790a..da8043fa 100644 --- a/shared/src/schemas/sse.ts +++ b/shared/src/schemas/sse.ts @@ -8,6 +8,7 @@ export const SSESubscribeSchema = z.object({ export const SSEVisibilitySchema = z.object({ clientId: z.string().min(1), visible: z.boolean(), + activeSessionId: z.string().nullable().optional(), }); export type SSESubscribeRequest = z.infer;