mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-06 21:04:23 +01:00
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:
1 parent
217f5bd989
commit
a9b6f7ce46
21 files changed
+762
-58
No files matched your search
@@ -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
|
||||
@@ -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,
|
||||
]
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -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()
|
||||
}
|
||||
@@ -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)
|
||||
|
||||
@@ -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')
|
||||
})
|
||||
})
|
||||
@@ -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
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
Reference in new issue
Block a user