feat: add session pinning for pinned/recent session groups (#301)

* feat: add session pinning for pinned/recent session groups

* refactor: extract buildSessionKey, deduplicate SessionCard rendering, clean up pins on delete
This commit is contained in:
Chris Scott authored and GitHub committed 2026-06-30 19:22:26 -04:00
1 parent 217f5bd989
commit a9b6f7ce46
21 files changed
+762 -58

No files matched your search

+1 -1
View File
@@ -9,7 +9,7 @@
"build": "bun build src/index.ts --outdir=dist --target=bun",
"typecheck": "tsc --noEmit",
"test": "pnpm run test:bun && pnpm run test:vitest",
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts",
"test:bun": "bun test test/services/assistant-mode.test.ts test/services/internal-token.test.ts test/auth/internal-token-middleware.test.ts test/routes/internal-schedules.test.ts test/routes/internal-notifications.test.ts test/routes/internal-settings.test.ts test/routes/internal-repos.test.ts test/routes/internal-assistant.test.ts src/db/model-state.test.ts src/routes/providers.test.ts src/routes/repos.test.ts src/routes/session-pins.test.ts",
"test:vitest": "vitest run",
"test:ui": "vitest --ui",
"test:watch": "vitest --watch",
@@ -0,0 +1,15 @@
import type { Migration } from '../migration-runner'
import { ensureSessionPinsTable } from '../session-pins'
const migration: Migration = {
version: 18,
name: 'session-pins',
up(db) {
ensureSessionPinsTable(db)
},
down(db) {
db.run('DROP TABLE IF EXISTS session_pins')
},
}
export default migration
+2
View File
@@ -16,6 +16,7 @@ import migration014 from './014-repos-add-name'
import migration015 from './015-schedule-worktree-isolation'
import migration016 from './016-schedule-permission-config'
import migration017 from './017-schedule-run-workspace-id'
import migration018 from './018-session-pins'
export const allMigrations: Migration[] = [
migration001,
@@ -35,4 +36,5 @@ export const allMigrations: Migration[] = [
migration015,
migration016,
migration017,
migration018,
]
+77
View File
@@ -0,0 +1,77 @@
import { describe, it, expect, beforeEach } from 'vitest'
import { Database } from 'bun:sqlite'
import { migrate } from './migration-runner'
import { allMigrations } from './migrations'
import { listSessionPins, setSessionPin, ensureSessionPinsTable } from './session-pins'
function createTestDb(): Database {
const db = new Database(':memory:')
migrate(db, allMigrations)
return db
}
describe('session-pins', () => {
let db: Database
beforeEach(() => {
db = createTestDb()
})
describe('listSessionPins', () => {
it('returns [] on a fresh db', () => {
expect(listSessionPins(db)).toEqual([])
})
})
describe('setSessionPin', () => {
it('pinning returns array with the pin', () => {
const pins = setSessionPin(db, 'ses_1', '/w/a', true)
expect(pins).toHaveLength(1)
expect(pins[0]!.sessionId).toBe('ses_1')
expect(pins[0]!.directory).toBe('/w/a')
expect(pins[0]!.pinnedAt).toEqual(expect.any(Number))
})
it('pinning the same (sessionId, directory) twice does not create a duplicate', async () => {
setSessionPin(db, 'ses_1', '/w/a', true)
const first = listSessionPins(db)
const firstPinnedAt = first[0]!.pinnedAt
// Delay to guarantee a different pinnedAt timestamp
await new Promise(r => setTimeout(r, 5))
const second = setSessionPin(db, 'ses_1', '/w/a', true)
expect(second).toHaveLength(1)
expect(second[0]!.pinnedAt).toBeGreaterThan(firstPinnedAt)
})
it('same sessionId with different directory produces two distinct pins', () => {
setSessionPin(db, 'ses_1', '/w/a', true)
const pins = setSessionPin(db, 'ses_1', '/w/b', true)
expect(pins).toHaveLength(2)
expect(pins.map(p => p.directory).sort()).toEqual(['/w/a', '/w/b'])
})
it('unpinning removes only that pin', () => {
setSessionPin(db, 'ses_1', '/w/a', true)
setSessionPin(db, 'ses_1', '/w/b', true)
const afterUnpin = setSessionPin(db, 'ses_1', '/w/a', false)
expect(afterUnpin).toHaveLength(1)
expect(afterUnpin[0]!.directory).toBe('/w/b')
})
})
describe('ensureSessionPinsTable', () => {
it('recreates the table if dropped', () => {
db.run('DROP TABLE session_pins')
ensureSessionPinsTable(db)
const table = db
.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'session_pins'")
.get() as { name: string } | undefined
expect(table).toBeTruthy()
expect(table!.name).toBe('session_pins')
})
})
})
+46
View File
@@ -0,0 +1,46 @@
import { Database } from 'bun:sqlite'
export interface SessionPinRecord {
sessionId: string
directory: string
pinnedAt: number
}
export function ensureSessionPinsTable(db: Database): void {
db.run(`
CREATE TABLE IF NOT EXISTS session_pins (
session_id TEXT NOT NULL,
directory TEXT NOT NULL,
pinned_at INTEGER NOT NULL,
PRIMARY KEY (session_id, directory)
)
`)
}
export function listSessionPins(db: Database): SessionPinRecord[] {
const rows = db
.prepare('SELECT session_id, directory, pinned_at FROM session_pins ORDER BY pinned_at DESC')
.all() as { session_id: string; directory: string; pinned_at: number }[]
return rows.map(r => ({ sessionId: r.session_id, directory: r.directory, pinnedAt: r.pinned_at }))
}
export function setSessionPin(
db: Database,
sessionId: string,
directory: string,
pinned: boolean,
): SessionPinRecord[] {
const run = db.transaction(() => {
if (pinned) {
db.prepare(`
INSERT INTO session_pins(session_id, directory, pinned_at)
VALUES(?,?,?)
ON CONFLICT(session_id, directory) DO UPDATE SET pinned_at=excluded.pinned_at
`).run(sessionId, directory, Date.now())
} else {
db.prepare('DELETE FROM session_pins WHERE session_id = ? AND directory = ?').run(sessionId, directory)
}
return listSessionPins(db)
})
return run()
}
+2
View File
@@ -34,6 +34,7 @@ import { createAuthRoutes, createAuthInfoRoutes, syncAdminFromEnv } from './rout
import { createAuth } from './auth'
import { createAuthMiddleware } from './auth/middleware'
import { createPromptTemplateRoutes } from './routes/prompt-templates'
import { createSessionPinRoutes } from './routes/session-pins'
import { createInternalRoutes } from './routes/internal'
import { sweepStaleUploadSessions } from './routes/internal/repo-mirror-helpers'
import { createOpenCodeProxyRoutes } from './routes/opencode-proxy'
@@ -355,6 +356,7 @@ protectedApi.route('/sse', createSSERoutes())
protectedApi.route('/ssh', createSSHRoutes(gitAuthService))
protectedApi.route('/notifications', createNotificationRoutes(notificationService))
protectedApi.route('/prompt-templates', createPromptTemplateRoutes(db))
protectedApi.route('/session-pins', createSessionPinRoutes(db))
protectedApi.route('/schedules', createScheduleRoutes(scheduleService))
app.route('/api', protectedApi)
+92
View File
@@ -0,0 +1,92 @@
import { describe, it, expect, beforeEach, afterEach } from 'bun:test'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { migrate } from '../db/migration-runner'
import { allMigrations } from '../db/migrations'
import { createSessionPinRoutes } from './session-pins'
function createTestApp(db: Database): Hono {
const app = new Hono()
app.route('/session-pins', createSessionPinRoutes(db))
return app
}
function createTestDb(): Database {
const db = new Database(':memory:')
migrate(db, allMigrations)
return db
}
describe('session pins routes', () => {
let db: Database
let app: Hono
beforeEach(() => {
db = createTestDb()
app = createTestApp(db)
})
afterEach(() => {
db.close()
})
it('GET / returns empty pins list initially', async () => {
const res = await app.request('/session-pins')
expect(res.status).toBe(200)
const data = await res.json() as { pins: unknown[] }
expect(data.pins).toEqual([])
})
it('PUT / creates a pin and returns updated list', async () => {
const res = await app.request('/session-pins', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
})
expect(res.status).toBe(200)
const data = await res.json() as { pins: Array<{ sessionId: string; directory: string }> }
expect(data.pins).toHaveLength(1)
expect(data.pins[0]).toMatchObject({ sessionId: 'ses_1', directory: '/w/a' })
})
it('GET / returns pins after creation', async () => {
await app.request('/session-pins', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
})
const res = await app.request('/session-pins')
expect(res.status).toBe(200)
const data = await res.json() as { pins: unknown[] }
expect(data.pins).toHaveLength(1)
})
it('PUT / with pinned: false removes the pin', async () => {
await app.request('/session-pins', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: true }),
})
const res = await app.request('/session-pins', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: 'ses_1', directory: '/w/a', pinned: false }),
})
expect(res.status).toBe(200)
const data = await res.json() as { pins: unknown[] }
expect(data.pins).toHaveLength(0)
})
it('PUT / with invalid body returns 400', async () => {
const res = await app.request('/session-pins', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId: '', directory: '/w/a', pinned: true }),
})
expect(res.status).toBe(400)
const data = await res.json() as { error: string }
expect(data.error).toBe('Invalid request')
})
})
+37
View File
@@ -0,0 +1,37 @@
import { Hono } from 'hono'
import type { Database } from 'bun:sqlite'
import { z } from 'zod'
import { ToggleSessionPinRequestSchema } from '@opencode-manager/shared/schemas'
import { listSessionPins, setSessionPin } from '../db/session-pins'
import { getErrorMessage } from '../utils/error-utils'
import { logger } from '../utils/logger'
export function createSessionPinRoutes(database: Database) {
const app = new Hono()
app.get('/', (c) => {
try {
return c.json({ pins: listSessionPins(database) })
} catch (error) {
logger.error('Failed to list session pins', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
app.put('/', async (c) => {
try {
const body = await c.req.json()
const input = ToggleSessionPinRequestSchema.parse(body)
const pins = setSessionPin(database, input.sessionId, input.directory, input.pinned)
return c.json({ pins })
} catch (error) {
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid request' }, 400)
}
logger.error('Failed to toggle session pin', error)
return c.json({ error: getErrorMessage(error) }, 500)
}
})
return app
}
+1
View File
@@ -20,6 +20,7 @@ export default defineConfig({
'src/db/model-state.test.ts',
'src/routes/providers.test.ts',
'src/routes/repos.test.ts',
'src/routes/session-pins.test.ts',
],
coverage: {
provider: 'v8',
+63
View File
@@ -0,0 +1,63 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { listSessionPins, toggleSessionPin } from './sessionPins'
describe('sessionPins', () => {
const fetchMock = vi.fn()
beforeEach(() => {
fetchMock.mockReset()
vi.stubGlobal('fetch', fetchMock)
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('listSessionPins', () => {
it('calls GET /api/session-pins and returns pins array', async () => {
const expectedPins = [
{ sessionId: 's1', directory: '/a', pinnedAt: 100 },
{ sessionId: 's2', directory: '/b', pinnedAt: 200 },
]
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }),
)
const result = await listSessionPins()
expect(result).toEqual(expectedPins)
const callUrl = fetchMock.mock.calls[0][0]
expect(callUrl).toEqual(expect.stringContaining('/api/session-pins'))
const callOptions = fetchMock.mock.calls[0][1]
expect(callOptions.method).toBeUndefined()
})
})
describe('toggleSessionPin', () => {
it('calls PUT /api/session-pins with JSON body and returns pins', async () => {
const input = { sessionId: 's1', directory: '/a', pinned: true }
const expectedPins = [
{ sessionId: 's1', directory: '/a', pinnedAt: 100 },
]
fetchMock.mockResolvedValue(
new Response(JSON.stringify({ pins: expectedPins }), { status: 200 }),
)
const result = await toggleSessionPin(input)
expect(result).toEqual(expectedPins)
const callUrl = fetchMock.mock.calls[0][0]
expect(callUrl).toEqual(expect.stringContaining('/api/session-pins'))
const callOptions = fetchMock.mock.calls[0][1]
expect(callOptions.method).toBe('PUT')
expect(callOptions.headers['Content-Type']).toBe('application/json')
const body = JSON.parse(callOptions.body)
expect(body).toEqual(input)
})
})
})
+17
View File
@@ -0,0 +1,17 @@
import { fetchWrapper } from './fetchWrapper'
import { API_BASE_URL } from '@/config'
import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
export async function listSessionPins(): Promise<SessionPin[]> {
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`)
return res.pins
}
export async function toggleSessionPin(input: ToggleSessionPinRequest): Promise<SessionPin[]> {
const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(input),
})
return res.pins
}
+55 -17
View File
@@ -2,10 +2,12 @@ import { useRef, useEffect } from "react";
import { Card } from "@/components/ui/card";
import { Checkbox } from "@/components/ui/checkbox";
import { SessionStatusIndicator } from "@/components/ui/session-status-indicator";
import { Trash2, Clock } from "lucide-react";
import { Trash2, Clock, MoreVertical, Pin, PinOff } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
import type { Session } from "@/api/types";
import { useSwipe } from "@/hooks/useSwipe";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { Button } from "@/components/ui/button";
interface SessionCardProps {
session: Session;
@@ -13,6 +15,8 @@ interface SessionCardProps {
isActive: boolean;
manageMode: boolean;
workspaceLabel?: string;
isPinned?: boolean;
onTogglePin?: () => void;
onSelect: (sessionID: string) => void;
onToggleSelection: (selected: boolean) => void;
onDelete: (e: React.MouseEvent<HTMLButtonElement>) => void;
@@ -24,6 +28,8 @@ export const SessionCard = ({
isActive,
manageMode,
workspaceLabel,
isPinned,
onTogglePin,
onSelect,
onToggleSelection,
onDelete,
@@ -98,6 +104,7 @@ export const SessionCard = ({
</div>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-1">
{isPinned && <Pin className="w-3 h-3 text-orange-500 shrink-0" />}
<h3 className="text-base font-semibold text-orange-600 dark:text-orange-400 truncate">
{session.title || "Untitled Session"}
</h3>
@@ -116,23 +123,54 @@ export const SessionCard = ({
</div>
</div>
) : (
<div className="flex flex-col flex-1 min-w-0">
<h3 className="text-sm font-semibold text-orange-600 dark:text-orange-400 truncate">
{session.title || "Untitled Session"}
</h3>
<div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
<span className="flex items-center">
<Clock className="w-3 h-3 mr-1" />
{formatDistanceToNow(new Date(session.time.updated), {
addSuffix: true,
})}
</span>
{workspaceLabel ? (
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
) : null}
<SessionStatusIndicator sessionID={session.id} size="sm" />
<>
<div className="flex flex-col flex-1 min-w-0">
<div className="flex items-center gap-1">
{isPinned && <Pin className="w-3 h-3 text-orange-500 shrink-0" />}
<h3 className="text-sm font-semibold text-orange-600 dark:text-orange-400 truncate">
{session.title || "Untitled Session"}
</h3>
</div>
<div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
<span className="flex items-center">
<Clock className="w-3 h-3 mr-1" />
{formatDistanceToNow(new Date(session.time.updated), {
addSuffix: true,
})}
</span>
{workspaceLabel ? (
<span className="text-purple-400 truncate max-w-[120px]">{workspaceLabel}</span>
) : null}
<SessionStatusIndicator sessionID={session.id} size="sm" />
</div>
</div>
</div>
{onTogglePin && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
aria-label="Session actions"
size="sm"
variant="ghost"
className="h-7 w-7 p-0 shrink-0"
onClick={(e) => e.stopPropagation()}
>
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="z-[200]"
onClick={(e) => e.stopPropagation()}
onPointerDown={(e) => e.stopPropagation()}
>
<DropdownMenuItem onClick={() => onTogglePin()}>
{isPinned ? <PinOff className="w-4 h-4 mr-2" /> : <Pin className="w-4 h-4 mr-2" />}
{isPinned ? "Unpin" : "Pin to top"}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
)}
</>
)}
{manageMode && (
<button
@@ -3,7 +3,7 @@ import { render, screen, waitFor, within, fireEvent } from '@testing-library/rea
import userEvent from '@testing-library/user-event'
import { SessionList } from './SessionList'
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs } = vi.hoisted(() => ({
const { createSessionMock, deleteSessionMock, sessionsData, createSessionState, fetchNextPageMock, hasNextPageRef, isFetchingNextPageRef, lastSessionsHookArgs, sessionPinsData, togglePinMock } = vi.hoisted(() => ({
createSessionMock: vi.fn(),
deleteSessionMock: vi.fn(),
sessionsData: [] as Array<{ id: string; title: string; directory: string; workspaceID?: string; parentID?: string; time: { updated: number } }>,
@@ -12,6 +12,8 @@ const { createSessionMock, deleteSessionMock, sessionsData, createSessionState,
hasNextPageRef: { current: false },
isFetchingNextPageRef: { current: false },
lastSessionsHookArgs: { current: undefined as { opcodeUrl: string; directories: string[]; options?: { search?: string; limit?: number } } | undefined },
sessionPinsData: [] as Array<{ sessionId: string; directory: string; pinnedAt: number }>,
togglePinMock: vi.fn(),
}))
vi.mock('@/hooks/useOpenCode', () => ({
@@ -34,6 +36,11 @@ vi.mock('@/hooks/useOpenCode', () => ({
useDeleteSession: () => ({ mutateAsync: deleteSessionMock, isPending: false }),
}))
vi.mock('@/hooks/useSessionPins', () => ({
useSessionPins: () => ({ data: sessionPinsData }),
useToggleSessionPin: () => ({ mutate: togglePinMock }),
}))
describe('SessionList', () => {
beforeEach(() => {
sessionsData.splice(0, sessionsData.length,
@@ -49,6 +56,8 @@ describe('SessionList', () => {
hasNextPageRef.current = false
isFetchingNextPageRef.current = false
lastSessionsHookArgs.current = undefined
sessionPinsData.splice(0, sessionPinsData.length)
togglePinMock.mockReset()
})
it('selects duplicate session IDs independently by workspace directory', async () => {
@@ -267,4 +276,48 @@ describe('SessionList', () => {
expect(fetchNextPageMock).toHaveBeenCalled()
})
})
it('renders pinned session under a Pinned heading and excludes it from Today', () => {
const pinnedTime = Date.now()
sessionPinsData.push({ sessionId: 'ses_a', directory: '/w/a', pinnedAt: pinnedTime })
sessionsData.splice(0, sessionsData.length,
{ id: 'ses_a', title: 'pinned session', directory: '/w/a', time: { updated: pinnedTime } },
)
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
expect(screen.getByText('Pinned')).toBeTruthy()
expect(screen.getByText('pinned session')).toBeTruthy()
// Pinned sessions are excluded from Today/Older, so Today heading should not appear
expect(screen.queryByText('Today')).toBeNull()
})
it('calls togglePinMock with correct args when Pin to top is clicked', async () => {
const user = userEvent.setup()
sessionsData.splice(0, sessionsData.length,
{ id: 'ses_x', title: 'test session', directory: '/w/a', time: { updated: Date.now() } },
)
render(
<SessionList
opcodeUrl="/api/opencode"
directories={['/w/a']}
onSelectSession={vi.fn()}
/>,
)
const actionsButton = screen.getByRole('button', { name: 'Session actions' })
await user.click(actionsButton)
const pinItem = screen.getByText('Pin to top')
await user.click(pinItem)
expect(togglePinMock).toHaveBeenCalledWith({ sessionId: 'ses_x', directory: '/w/a', pinned: true })
})
})
+50 -37
View File
@@ -1,6 +1,9 @@
import { useCallback, useState, useMemo, useEffect } from "react";
import { useSessionsAcrossDirectories, useDeleteSession, useCreateSession } from "@/hooks/useOpenCode";
import type { DeleteSessionTarget } from "@/hooks/useOpenCode";
import { useSessionPins, useToggleSessionPin } from '@/hooks/useSessionPins';
import { buildSessionKey } from '@/lib/sessionKey';
import { partitionSessions } from './session-partition';
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { SessionCard } from "./SessionCard";
import { Card } from "@/components/ui/card";
@@ -35,7 +38,7 @@ export const SessionList = ({
const primaryDirectory = directoriesList[0];
const sessionCreateDirectory = createDirectory ?? primaryDirectory;
const getSessionSelectionKey = useCallback((session: { id: string; directory?: string }) =>
`${session.directory ?? primaryDirectory ?? ''}:${session.id}`,
buildSessionKey(session.directory ?? primaryDirectory, session.id),
[primaryDirectory]);
const [searchQuery, setSearchQuery] = useState("");
const { data: sessions, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } = useSessionsAcrossDirectories(opcodeUrl, directoriesList, { search: searchQuery, limit: 25 });
@@ -43,6 +46,12 @@ export const SessionList = ({
const createSession = useCreateSession(opcodeUrl, sessionCreateDirectory, (newSession) => {
onSelectSession(newSession.id);
});
const { data: sessionPins } = useSessionPins();
const togglePin = useToggleSessionPin();
const pinnedKeys = useMemo(
() => new Set((sessionPins ?? []).map((p) => buildSessionKey(p.directory, p.sessionId))),
[sessionPins],
);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [sessionToDelete, setSessionToDelete] = useState<DeleteSessionTarget | DeleteSessionTarget[] | null>(null);
const [selectedSessions, setSelectedSessions] = useState<Set<string>>(new Set());
@@ -68,17 +77,16 @@ export const SessionList = ({
return Array.from(uniqueSessions.values()).sort((a, b) => b.time.updated - a.time.updated);
}, [sessions, directorySet, getSessionSelectionKey]);
const todaySessions = useMemo(() => {
const today = new Date();
today.setHours(0, 0, 0, 0);
return filteredSessions.filter((session) => new Date(session.time.updated) >= today);
}, [filteredSessions]);
const { pinned: pinnedSessions, today: todaySessions, older: olderSessions } = useMemo(
() => partitionSessions(filteredSessions, pinnedKeys, getSessionSelectionKey),
[filteredSessions, pinnedKeys, getSessionSelectionKey],
);
const olderSessions = useMemo(() => {
const today = new Date();
today.setHours(0, 0, 0, 0);
return filteredSessions.filter((session) => new Date(session.time.updated) < today);
}, [filteredSessions]);
const handleTogglePin = (session: { id: string; directory?: string }) => {
const directory = session.directory ?? primaryDirectory ?? '';
const key = getSessionSelectionKey(session);
togglePin.mutate({ sessionId: session.id, directory, pinned: !pinnedKeys.has(key) });
};
const handleSessionsScroll = useCallback((event: React.UIEvent<HTMLDivElement>) => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
@@ -188,6 +196,25 @@ export const SessionList = ({
}
};
const renderSessionCard = (session: (typeof filteredSessions)[number], isPinned: boolean) => {
const key = getSessionSelectionKey(session);
return (
<SessionCard
key={key}
session={session}
isSelected={selectedSessions.has(key)}
isActive={activeSessionID === session.id}
manageMode={manageMode}
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
isPinned={isPinned}
onSelect={onSelectSession}
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
onTogglePin={() => handleTogglePin(session)}
onDelete={(e) => handleDelete(session, e)}
/>
);
};
return (
<div className="flex flex-col h-full min-h-0">
<div className="px-4 pt-2 flex-shrink-0">
@@ -260,43 +287,29 @@ export const SessionList = ({
</div>
) : (
<>
{pinnedSessions.length > 0 && (
<>
<div className="text-xs font-semibold text-muted-foreground px-1 py-2">Pinned</div>
{pinnedSessions.map((session) => renderSessionCard(session, true))}
{(todaySessions.length > 0 || olderSessions.length > 0) && (
<div className="my-2 h-px bg-border/80" />
)}
</>
)}
{todaySessions.length > 0 && (
<>
<div className="text-xs font-semibold text-muted-foreground px-1 py-2">
Today
</div>
{todaySessions.map((session) => (
<SessionCard
key={getSessionSelectionKey(session)}
session={session}
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
isActive={activeSessionID === session.id}
manageMode={manageMode}
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
onSelect={onSelectSession}
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
onDelete={(e) => handleDelete(session, e)}
/>
))}
{todaySessions.map((session) => renderSessionCard(session, false))}
</>
)}
{todaySessions.length > 0 && olderSessions.length > 0 && (
<div className="my-2 h-px bg-border/80" />
)}
{olderSessions.map((session) => (
<SessionCard
key={getSessionSelectionKey(session)}
session={session}
isSelected={selectedSessions.has(getSessionSelectionKey(session))}
isActive={activeSessionID === session.id}
manageMode={manageMode}
workspaceLabel={session.directory ? directoryLabels?.[session.directory] : undefined}
onSelect={onSelectSession}
onToggleSelection={(selected) => toggleSessionSelection(session, selected)}
onDelete={(e) => handleDelete(session, e)}
/>
))}
{olderSessions.map((session) => renderSessionCard(session, false))}
</>
)}
{isFetchingNextPage && (
@@ -0,0 +1,142 @@
import { describe, it, expect } from 'vitest'
import { partitionSessions } from './session-partition'
import type { Session } from '@/api/types'
function createSession(id: string, updated: number, directory = '/test'): Session {
return {
id,
projectID: 'proj-1',
directory,
title: `Session ${id}`,
version: '1',
time: { created: updated - 10000, updated },
}
}
const keyFn = (s: { id: string; directory?: string }) =>
`${s.directory ?? ''}:${s.id}`
describe('partitionSessions', () => {
it('places pinned sessions in pinned array sorted by updated desc', () => {
const now = 1_000_000_000_000
const sessions = [
createSession('a', now - 2000),
createSession('b', now - 1000),
createSession('c', now - 3000),
]
const pinnedKeys = new Set(['/test:a', '/test:c'])
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
expect(result.pinned).toHaveLength(2)
expect(result.pinned[0].id).toBe('a')
expect(result.pinned[1].id).toBe('c')
expect(result.today).toHaveLength(1)
expect(result.today[0].id).toBe('b')
expect(result.older).toHaveLength(0)
})
it('places unpinned sessions with updated >= start of today in today', () => {
const now = 1_000_000_000_000
const todayStart = new Date(now)
todayStart.setHours(0, 0, 0, 0)
const todayTs = todayStart.getTime() + 5000
const yesterdayTs = todayStart.getTime() - 1000
const sessions = [
createSession('today-session', todayTs),
createSession('yesterday-session', yesterdayTs),
]
const result = partitionSessions(sessions, new Set(), keyFn, now)
expect(result.pinned).toHaveLength(0)
expect(result.today).toHaveLength(1)
expect(result.today[0].id).toBe('today-session')
expect(result.older).toHaveLength(1)
expect(result.older[0].id).toBe('yesterday-session')
})
it('sorts today and older arrays by updated desc', () => {
const now = 1_000_000_000_000
const todayStart = new Date(now)
todayStart.setHours(0, 0, 0, 0)
const todayTs = todayStart.getTime() + 5000
const sessions = [
createSession('older-1', todayStart.getTime() - 3000),
createSession('older-2', todayStart.getTime() - 1000),
createSession('today-1', todayTs),
createSession('today-2', todayTs - 2000),
]
const result = partitionSessions(sessions, new Set(), keyFn, now)
expect(result.today[0].id).toBe('today-1')
expect(result.today[1].id).toBe('today-2')
expect(result.older[0].id).toBe('older-2')
expect(result.older[1].id).toBe('older-1')
})
it('keeps old pinned sessions in pinned (not older)', () => {
const now = 1_000_000_000_000
const todayStart = new Date(now)
todayStart.setHours(0, 0, 0, 0)
const oldTs = todayStart.getTime() - 86400_000
const sessions = [
createSession('pinned-old', oldTs),
createSession('normal-old', oldTs),
]
const pinnedKeys = new Set(['/test:pinned-old'])
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
expect(result.pinned).toHaveLength(1)
expect(result.pinned[0].id).toBe('pinned-old')
expect(result.today).toHaveLength(0)
expect(result.older).toHaveLength(1)
expect(result.older[0].id).toBe('normal-old')
})
it('returns empty pinned when pinnedKeys is empty, matching today/older behavior', () => {
const now = 1_000_000_000_000
const todayStart = new Date(now)
todayStart.setHours(0, 0, 0, 0)
const todayTs = todayStart.getTime() + 5000
const yesterdayTs = todayStart.getTime() - 1000
const sessions = [
createSession('today-session', todayTs),
createSession('yesterday-session', yesterdayTs),
]
const result = partitionSessions(sessions, new Set(), keyFn, now)
expect(result.pinned).toHaveLength(0)
expect(result.today).toHaveLength(1)
expect(result.older).toHaveLength(1)
})
it('produces disjoint pinned/today/older arrays', () => {
const now = 1_000_000_000_000
const todayStart = new Date(now)
todayStart.setHours(0, 0, 0, 0)
const todayTs = todayStart.getTime() + 5000
const yesterdayTs = todayStart.getTime() - 1000
const sessions = [
createSession('pinned', todayTs),
createSession('normal-today', todayTs - 2000),
createSession('normal-old', yesterdayTs),
]
const pinnedKeys = new Set(['/test:pinned'])
const result = partitionSessions(sessions, pinnedKeys, keyFn, now)
const all = [...result.pinned, ...result.today, ...result.older]
expect(all).toHaveLength(sessions.length)
const allIds = all.map((s) => s.id).sort()
expect(allIds).toEqual(['normal-old', 'normal-today', 'pinned'])
})
})
@@ -0,0 +1,36 @@
import type { Session } from '@/api/types'
export interface PartitionedSessions {
pinned: Session[]
today: Session[]
older: Session[]
}
export function partitionSessions(
sessions: Session[],
pinnedKeys: Set<string>,
keyFn: (session: { id: string; directory?: string }) => string,
now: number = Date.now(),
): PartitionedSessions {
const startOfDay = new Date(now)
startOfDay.setHours(0, 0, 0, 0)
const startMs = startOfDay.getTime()
const byUpdatedDesc = (a: Session, b: Session) => b.time.updated - a.time.updated
const pinned: Session[] = []
const today: Session[] = []
const older: Session[] = []
for (const s of sessions) {
if (pinnedKeys.has(keyFn(s))) {
pinned.push(s)
} else if (s.time.updated >= startMs) {
today.push(s)
} else {
older.push(s)
}
}
pinned.sort(byUpdatedDesc)
today.sort(byUpdatedDesc)
older.sort(byUpdatedDesc)
return { pinned, today, older }
}
+29 -2
View File
@@ -15,6 +15,10 @@ import { useSendErrorStore } from "../stores/sendErrorStore";
import { useSessionStatus } from "../stores/sessionStatusStore";
import { invalidateSessionListCaches, messagesQueryKey } from "../lib/queryInvalidation";
import { reconcileConfirmedPrompt } from "../lib/sendErrorReconcile";
import { buildSessionKey } from "../lib/sessionKey";
import { toggleSessionPin } from "../api/sessionPins";
import { SESSION_PINS_QUERY_KEY } from "./useSessionPins";
import type { SessionPin } from "@opencode-manager/shared/schemas";
type AssistantMessage = components["schemas"]["AssistantMessage"];
@@ -200,7 +204,7 @@ const getDeleteSessionTargetWorkspaceID = (target: DeleteSessionTarget) =>
typeof target === 'string' ? undefined : target.workspaceID;
const getDeleteSessionTargetKey = (target: DeleteSessionTarget, fallbackDirectory?: string) =>
`${getDeleteSessionTargetDirectory(target, fallbackDirectory) ?? ''}:${getDeleteSessionTargetId(target)}`;
buildSessionKey(getDeleteSessionTargetDirectory(target, fallbackDirectory), getDeleteSessionTargetId(target));
const isMissingWorkspaceError = (error: unknown) =>
error instanceof Error && error.message.includes('Workspace not found:');
@@ -279,12 +283,35 @@ export const useDeleteSession = (opcodeUrl: string | null | undefined, directory
onError: () => {
showToast.error('Failed to delete sessions');
},
onSettled: () => {
onSettled: (_data, _error, variables) => {
invalidateSessionListCaches(queryClient, opcodeUrl);
cleanupSessionPins(queryClient, variables, primaryDirectory);
},
});
};
const cleanupSessionPins = (
queryClient: ReturnType<typeof useQueryClient>,
variables: DeleteSessionTarget | DeleteSessionTarget[],
primaryDirectory?: string,
) => {
const pins = queryClient.getQueryData<SessionPin[]>(SESSION_PINS_QUERY_KEY) ?? [];
if (pins.length === 0) return;
const pinnedKeys = new Set(pins.map((p) => buildSessionKey(p.directory, p.sessionId)));
const targets = (Array.isArray(variables) ? variables : [variables])
.map((target) => ({
sessionId: getDeleteSessionTargetId(target),
directory: getDeleteSessionTargetDirectory(target, primaryDirectory) ?? '',
}))
.filter((target) => pinnedKeys.has(buildSessionKey(target.directory, target.sessionId)));
if (targets.length === 0) return;
void Promise.allSettled(
targets.map((target) => toggleSessionPin({ ...target, pinned: false })),
).then(() => {
void queryClient.invalidateQueries({ queryKey: SESSION_PINS_QUERY_KEY });
});
};
export const useUpdateSession = (opcodeUrl: string | null | undefined, directory?: string) => {
const queryClient = useQueryClient();
const client = useOpenCodeClient(opcodeUrl, directory);
+23
View File
@@ -0,0 +1,23 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { listSessionPins, toggleSessionPin } from '@/api/sessionPins'
import type { SessionPin, ToggleSessionPinRequest } from '@opencode-manager/shared/schemas'
export const SESSION_PINS_QUERY_KEY = ['session-pins'] as const
export function useSessionPins() {
return useQuery({
queryKey: SESSION_PINS_QUERY_KEY,
queryFn: listSessionPins,
staleTime: 30000,
})
}
export function useToggleSessionPin() {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (input: ToggleSessionPinRequest) => toggleSessionPin(input),
onSuccess: (pins: SessionPin[]) => {
queryClient.setQueryData(SESSION_PINS_QUERY_KEY, pins)
},
})
}
+3
View File
@@ -0,0 +1,3 @@
export function buildSessionKey(directory: string | undefined, id: string): string {
return `${directory ?? ''}:${id}`
}
+1
View File
@@ -9,3 +9,4 @@ export * from './ssh'
export * from './schedule'
export * from './skills'
export * from './internal-assistant'
export * from './session-pins'
+16
View File
@@ -0,0 +1,16 @@
import { z } from "zod";
export const SessionPinSchema = z.object({
sessionId: z.string(),
directory: z.string(),
pinnedAt: z.number(),
});
export const ToggleSessionPinRequestSchema = z.object({
sessionId: z.string().min(1),
directory: z.string().min(1),
pinned: z.boolean(),
});
export type SessionPin = z.infer<typeof SessionPinSchema>;
export type ToggleSessionPinRequest = z.infer<typeof ToggleSessionPinRequestSchema>;