Files
session-viewer/src/server/routes/sessions.ts
teernisse b0b330e0ba Add session list refresh with server cache bypass
useSession now exposes a refreshSessions() callback that fetches
/api/sessions?refresh=1. The sessions route checks for the refresh
query parameter and resets the cache timestamp to zero, forcing a
fresh scan of ~/.claude/projects/ on the next request.

This enables users to pick up new sessions without restarting the
server or waiting for the 30-second cache to expire.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-30 13:35:37 -05:00

54 lines
1.5 KiB
TypeScript

import { Router } from "express";
import { discoverSessions } from "../services/session-discovery.js";
import { parseSession } from "../services/session-parser.js";
import type { SessionEntry } from "../../shared/types.js";
export const sessionsRouter = Router();
// Simple cache to avoid re-discovering sessions on every detail request
let cachedSessions: SessionEntry[] = [];
let cacheTimestamp = 0;
const CACHE_TTL_MS = 30_000;
async function getCachedSessions(): Promise<SessionEntry[]> {
const now = Date.now();
if (now - cacheTimestamp > CACHE_TTL_MS) {
cachedSessions = await discoverSessions();
cacheTimestamp = now;
}
return cachedSessions;
}
sessionsRouter.get("/", async (req, res) => {
try {
if (req.query.refresh === "1") {
cacheTimestamp = 0;
}
const sessions = await getCachedSessions();
res.json({ sessions });
} catch (err) {
console.error("Failed to discover sessions:", err);
res.status(500).json({ error: "Failed to discover sessions" });
}
});
sessionsRouter.get("/:id", async (req, res) => {
try {
const sessions = await getCachedSessions();
const entry = sessions.find((s) => s.id === req.params.id);
if (!entry) {
res.status(404).json({ error: "Session not found" });
return;
}
const messages = await parseSession(entry.path);
res.json({
id: entry.id,
project: entry.project,
messages,
});
} catch (err) {
console.error("Failed to load session:", err);
res.status(500).json({ error: "Failed to load session" });
}
});