Skip to content
This repository was archived by the owner on Aug 5, 2026. It is now read-only.

Commit d5c2204

Browse files
committed
feat: add recent sessions dashboard and quick session switcher (#87, #88, #89)
- Add /api/sessions/recent endpoint for sessions active in last 8 hours - Add RecentSessions component on home page showing recent sessions with status - Add SessionSwitcher component (Cmd/Ctrl+K) for quick session switching - Add global SSE listener for push notifications across all sessions - Push notifications now work for all sessions, not just open ones - Click notification to navigate directly to completed session
1 parent 97beb68 commit d5c2204

10 files changed

Lines changed: 611 additions & 1 deletion

File tree

‎backend/src/index.ts‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import os from 'os'
88
import path from 'path'
99
import { initializeDatabase } from './db/schema'
1010
import { createRepoRoutes } from './routes/repos'
11+
import { createSessionRoutes } from './routes/sessions'
1112
import { createSettingsRoutes } from './routes/settings'
1213
import { createHealthRoutes } from './routes/health'
1314
import { createTTSRoutes, cleanupExpiredCache } from './routes/tts'
@@ -26,6 +27,7 @@ import { cleanupOrphanedDirectories, cleanupStaleRepoEntries, registerExternalDi
2627
import { proxyRequest } from './services/proxy'
2728
import { logger } from './utils/logger'
2829
import { chatterboxServerManager } from './services/chatterbox'
30+
import { startGlobalSSEListener, stopGlobalSSEListener } from './services/global-sse'
2931
import {
3032
getWorkspacePath,
3133
getReposPath,
@@ -284,6 +286,13 @@ try {
284286
logger.warn('Failed to sync projects from OpenCode:', error)
285287
}
286288

289+
try {
290+
startGlobalSSEListener(db)
291+
logger.info('Global SSE listener started for push notifications')
292+
} catch (error) {
293+
logger.warn('Failed to start global SSE listener:', error)
294+
}
295+
287296
try {
288297
await whisperServerManager.start()
289298
logger.info(`Whisper STT server running on port ${whisperServerManager.getPort()}`)
@@ -303,6 +312,7 @@ try {
303312
}
304313

305314
app.route('/api/repos', createRepoRoutes(db))
315+
app.route('/api/sessions', createSessionRoutes(db))
306316
app.route('/api/settings', createSettingsRoutes(db))
307317
app.route('/api/health', createHealthRoutes(db))
308318
app.route('/api/files', createFileRoutes(db))
@@ -423,6 +433,8 @@ const shutdown = async (signal: string) => {
423433

424434
logger.info(`${signal} received, shutting down gracefully...`)
425435
try {
436+
stopGlobalSSEListener()
437+
logger.info('Global SSE listener stopped')
426438
terminalService.destroyAllSessions()
427439
logger.info('Terminal sessions destroyed')
428440
await whisperServerManager.stop()

‎backend/src/routes/sessions.ts‎

Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
import { Hono } from 'hono'
2+
import type { Database } from 'bun:sqlite'
3+
import * as db from '../db/queries'
4+
import { opencodeServerManager } from '../services/opencode-single-server'
5+
import { logger } from '../utils/logger'
6+
7+
interface SessionWithRepo {
8+
id: string
9+
title: string
10+
directory: string
11+
repoId?: number
12+
repoName?: string
13+
status?: 'idle' | 'busy' | 'retry'
14+
time: {
15+
created: number
16+
updated: number
17+
}
18+
}
19+
20+
export function createSessionRoutes(database: Database) {
21+
const app = new Hono()
22+
23+
app.get('/recent', async (c) => {
24+
try {
25+
const hoursParam = c.req.query('hours')
26+
const hours = hoursParam ? parseInt(hoursParam, 10) : 8
27+
const cutoffTime = Date.now() - (hours * 60 * 60 * 1000)
28+
29+
const repos = db.listRepos(database)
30+
const opencodePort = opencodeServerManager.getPort()
31+
32+
const recentSessions: SessionWithRepo[] = []
33+
34+
let sessionStatuses: Record<string, { type: string }> = {}
35+
try {
36+
const statusRes = await fetch(`http://127.0.0.1:${opencodePort}/session/status`)
37+
if (statusRes.ok) {
38+
sessionStatuses = await statusRes.json()
39+
}
40+
} catch (err) {
41+
logger.warn('Failed to fetch session statuses:', err)
42+
}
43+
44+
for (const repo of repos) {
45+
try {
46+
const sessionsRes = await fetch(
47+
`http://127.0.0.1:${opencodePort}/session?directory=${encodeURIComponent(repo.fullPath)}`
48+
)
49+
50+
if (!sessionsRes.ok) continue
51+
52+
const sessions = await sessionsRes.json() as Array<{
53+
id: string
54+
title?: string
55+
directory: string
56+
parentID?: string
57+
time: { created: number; updated: number }
58+
}>
59+
60+
for (const session of sessions) {
61+
if (session.parentID) continue
62+
if (session.time.updated < cutoffTime) continue
63+
64+
const status = sessionStatuses[session.id]
65+
66+
recentSessions.push({
67+
id: session.id,
68+
title: session.title || 'Untitled Session',
69+
directory: session.directory,
70+
repoId: repo.id,
71+
repoName: repo.name,
72+
status: (status?.type as 'idle' | 'busy' | 'retry') || 'idle',
73+
time: session.time,
74+
})
75+
}
76+
} catch (err) {
77+
logger.warn(`Failed to fetch sessions for repo ${repo.id}:`, err)
78+
}
79+
}
80+
81+
recentSessions.sort((a, b) => b.time.updated - a.time.updated)
82+
83+
return c.json({
84+
sessions: recentSessions,
85+
cutoffTime,
86+
count: recentSessions.length,
87+
})
88+
} catch (error: unknown) {
89+
logger.error('Failed to get recent sessions:', error)
90+
const message = error instanceof Error ? error.message : 'Unknown error'
91+
return c.json({ error: message }, 500)
92+
}
93+
})
94+
95+
return app
96+
}

‎backend/src/services/global-sse.ts‎

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
import type { Database } from 'bun:sqlite'
2+
import * as db from '../db/queries'
3+
import { opencodeServerManager } from './opencode-single-server'
4+
import { sendSessionCompleteNotification, sendPermissionRequestNotification } from './push'
5+
import { logger } from '../utils/logger'
6+
7+
interface SSEEvent {
8+
type: string
9+
properties: Record<string, unknown>
10+
}
11+
12+
type EventSourceType = typeof globalThis.EventSource
13+
14+
let globalEventSources: Map<string, InstanceType<EventSourceType>> = new Map()
15+
let database: Database | null = null
16+
let isRunning = false
17+
18+
async function getSessionTitle(directory: string, sessionId: string): Promise<string | undefined> {
19+
try {
20+
const port = opencodeServerManager.getPort()
21+
const response = await fetch(
22+
`http://127.0.0.1:${port}/session/${sessionId}?directory=${encodeURIComponent(directory)}`
23+
)
24+
if (response.ok) {
25+
const session = await response.json()
26+
return session.title
27+
}
28+
} catch (err) {
29+
logger.warn(`Failed to fetch session title for ${sessionId}:`, err)
30+
}
31+
return undefined
32+
}
33+
34+
function getRepoIdByDirectory(directory: string): number | undefined {
35+
if (!database) return undefined
36+
const repos = db.listRepos(database)
37+
const repo = repos.find((r) => r.fullPath === directory)
38+
return repo?.id
39+
}
40+
41+
function handleSSEMessage(directory: string, event: SSEEvent): void {
42+
if (!database) return
43+
44+
const { type, properties: props } = event
45+
46+
if (type === 'session.idle' && 'sessionID' in props) {
47+
const sessionId = props.sessionID as string
48+
const repoId = getRepoIdByDirectory(directory)
49+
50+
logger.info(`[GlobalSSE] Session idle: ${sessionId} in ${directory}`)
51+
52+
getSessionTitle(directory, sessionId).then((title) => {
53+
sendSessionCompleteNotification(database!, sessionId, repoId?.toString(), title)
54+
.catch((err) => logger.warn('[GlobalSSE] Failed to send push notification:', err))
55+
})
56+
}
57+
58+
if (type === 'permission.updated' && 'id' in props && 'sessionID' in props) {
59+
const sessionId = props.sessionID as string
60+
const toolName = (props.tool as string) || 'A tool'
61+
const repoId = getRepoIdByDirectory(directory)
62+
63+
logger.info(`[GlobalSSE] Permission requested: ${toolName} for session ${sessionId}`)
64+
65+
sendPermissionRequestNotification(database!, sessionId, toolName, repoId?.toString())
66+
.catch((err) => logger.warn('[GlobalSSE] Failed to send permission push notification:', err))
67+
}
68+
}
69+
70+
function connectToRepo(directory: string): void {
71+
if (globalEventSources.has(directory)) {
72+
return
73+
}
74+
75+
const port = opencodeServerManager.getPort()
76+
const url = `http://127.0.0.1:${port}/event?directory=${encodeURIComponent(directory)}`
77+
78+
logger.info(`[GlobalSSE] Connecting to ${directory}`)
79+
80+
const EventSourceClass = globalThis.EventSource
81+
const es = new EventSourceClass(url)
82+
globalEventSources.set(directory, es)
83+
84+
es.onopen = () => {
85+
logger.info(`[GlobalSSE] Connected to ${directory}`)
86+
}
87+
88+
es.onerror = (err) => {
89+
logger.warn(`[GlobalSSE] Error for ${directory}:`, err)
90+
globalEventSources.delete(directory)
91+
92+
if (isRunning) {
93+
setTimeout(() => {
94+
if (isRunning && !globalEventSources.has(directory)) {
95+
connectToRepo(directory)
96+
}
97+
}, 5000)
98+
}
99+
}
100+
101+
es.onmessage = (e) => {
102+
try {
103+
const event = JSON.parse(e.data) as SSEEvent
104+
handleSSEMessage(directory, event)
105+
} catch (err) {
106+
logger.warn('[GlobalSSE] Failed to parse SSE event:', err)
107+
}
108+
}
109+
}
110+
111+
function disconnectFromRepo(directory: string): void {
112+
const es = globalEventSources.get(directory)
113+
if (es) {
114+
es.close()
115+
globalEventSources.delete(directory)
116+
logger.info(`[GlobalSSE] Disconnected from ${directory}`)
117+
}
118+
}
119+
120+
function syncRepoConnections(): void {
121+
if (!database) return
122+
123+
const repos = db.listRepos(database)
124+
const currentDirs = new Set(repos.map((r) => r.fullPath))
125+
126+
for (const [dir] of globalEventSources) {
127+
if (!currentDirs.has(dir)) {
128+
disconnectFromRepo(dir)
129+
}
130+
}
131+
132+
for (const repo of repos) {
133+
if (!globalEventSources.has(repo.fullPath)) {
134+
connectToRepo(repo.fullPath)
135+
}
136+
}
137+
}
138+
139+
export function startGlobalSSEListener(db: Database): void {
140+
if (isRunning) return
141+
142+
database = db
143+
isRunning = true
144+
145+
logger.info('[GlobalSSE] Starting global SSE listener')
146+
147+
syncRepoConnections()
148+
149+
setInterval(() => {
150+
if (isRunning) {
151+
syncRepoConnections()
152+
}
153+
}, 30000)
154+
}
155+
156+
export function stopGlobalSSEListener(): void {
157+
isRunning = false
158+
159+
for (const [dir] of globalEventSources) {
160+
disconnectFromRepo(dir)
161+
}
162+
163+
logger.info('[GlobalSSE] Stopped global SSE listener')
164+
}

‎frontend/src/App.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { QuestionDialog } from './components/question/QuestionDialog'
1818
import { usePermissionContext } from './contexts/PermissionContext'
1919
import { GlobalPermissionNotification } from './components/permissions/GlobalPermissionNotification'
2020
import { NotificationProvider } from './components/providers/NotificationProvider'
21+
import { SessionSwitcher } from './components/session/SessionSwitcher'
2122

2223
const queryClient = new QueryClient({
2324
defaultOptions: {
@@ -41,6 +42,7 @@ return (
4142
<Route path="/repos/:id/terminal" element={<TerminalPage />} />
4243
</Routes>
4344
<GlobalPermissionNotification />
45+
<SessionSwitcher />
4446
<SettingsDialog open={isOpen} onOpenChange={close} />
4547
<Toaster
4648
position="bottom-right"

‎frontend/src/api/sessions.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { API_BASE_URL } from '@/config'
2+
3+
export interface RecentSession {
4+
id: string
5+
title: string
6+
directory: string
7+
repoId?: number
8+
repoName?: string
9+
status?: 'idle' | 'busy' | 'retry'
10+
time: {
11+
created: number
12+
updated: number
13+
}
14+
}
15+
16+
export interface RecentSessionsResponse {
17+
sessions: RecentSession[]
18+
cutoffTime: number
19+
count: number
20+
}
21+
22+
export async function getRecentSessions(hours: number = 8): Promise<RecentSessionsResponse> {
23+
const response = await fetch(`${API_BASE_URL}/api/sessions/recent?hours=${hours}`, {
24+
credentials: 'include',
25+
})
26+
27+
if (!response.ok) {
28+
throw new Error('Failed to get recent sessions')
29+
}
30+
31+
return response.json()
32+
}

0 commit comments

Comments
 (0)