diff --git a/backend/package.json b/backend/package.json index d62550b2..456eb40c 100644 --- a/backend/package.json +++ b/backend/package.json @@ -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", diff --git a/backend/src/db/migrations/018-session-pins.ts b/backend/src/db/migrations/018-session-pins.ts new file mode 100644 index 00000000..1cf09c6e --- /dev/null +++ b/backend/src/db/migrations/018-session-pins.ts @@ -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 diff --git a/backend/src/db/migrations/index.ts b/backend/src/db/migrations/index.ts index 55955070..514d74ca 100644 --- a/backend/src/db/migrations/index.ts +++ b/backend/src/db/migrations/index.ts @@ -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, ] diff --git a/backend/src/db/session-pins.test.ts b/backend/src/db/session-pins.test.ts new file mode 100644 index 00000000..fc5317ed --- /dev/null +++ b/backend/src/db/session-pins.test.ts @@ -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') + }) + }) +}) diff --git a/backend/src/db/session-pins.ts b/backend/src/db/session-pins.ts new file mode 100644 index 00000000..4d6e30a7 --- /dev/null +++ b/backend/src/db/session-pins.ts @@ -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() +} diff --git a/backend/src/index.ts b/backend/src/index.ts index 0a50fa2a..6e17feea 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -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) diff --git a/backend/src/routes/session-pins.test.ts b/backend/src/routes/session-pins.test.ts new file mode 100644 index 00000000..acd831d8 --- /dev/null +++ b/backend/src/routes/session-pins.test.ts @@ -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') + }) +}) diff --git a/backend/src/routes/session-pins.ts b/backend/src/routes/session-pins.ts new file mode 100644 index 00000000..d18b839e --- /dev/null +++ b/backend/src/routes/session-pins.ts @@ -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 +} diff --git a/backend/vitest.config.ts b/backend/vitest.config.ts index da53ef82..8fff8255 100644 --- a/backend/vitest.config.ts +++ b/backend/vitest.config.ts @@ -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', diff --git a/frontend/src/api/sessionPins.test.ts b/frontend/src/api/sessionPins.test.ts new file mode 100644 index 00000000..bb289f92 --- /dev/null +++ b/frontend/src/api/sessionPins.test.ts @@ -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) + }) + }) +}) diff --git a/frontend/src/api/sessionPins.ts b/frontend/src/api/sessionPins.ts new file mode 100644 index 00000000..5fff4bb3 --- /dev/null +++ b/frontend/src/api/sessionPins.ts @@ -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 { + const res = await fetchWrapper<{ pins: SessionPin[] }>(`${API_BASE_URL}/api/session-pins`) + return res.pins +} + +export async function toggleSessionPin(input: ToggleSessionPinRequest): Promise { + 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 +} diff --git a/frontend/src/components/session/SessionCard.tsx b/frontend/src/components/session/SessionCard.tsx index f2cb71d4..97268d5b 100644 --- a/frontend/src/components/session/SessionCard.tsx +++ b/frontend/src/components/session/SessionCard.tsx @@ -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) => void; @@ -24,6 +28,8 @@ export const SessionCard = ({ isActive, manageMode, workspaceLabel, + isPinned, + onTogglePin, onSelect, onToggleSelection, onDelete, @@ -98,6 +104,7 @@ export const SessionCard = ({
+ {isPinned && }

{session.title || "Untitled Session"}

@@ -116,23 +123,54 @@ export const SessionCard = ({
) : ( -
-

- {session.title || "Untitled Session"} -

-
- - - {formatDistanceToNow(new Date(session.time.updated), { - addSuffix: true, - })} - - {workspaceLabel ? ( - {workspaceLabel} - ) : null} - + <> +
+
+ {isPinned && } +

+ {session.title || "Untitled Session"} +

+
+
+ + + {formatDistanceToNow(new Date(session.time.updated), { + addSuffix: true, + })} + + {workspaceLabel ? ( + {workspaceLabel} + ) : null} + +
-
+ {onTogglePin && ( + + + + + e.stopPropagation()} + onPointerDown={(e) => e.stopPropagation()} + > + onTogglePin()}> + {isPinned ? : } + {isPinned ? "Unpin" : "Pin to top"} + + + + )} + )} {manageMode && (