From 3da9f7780a1a399ec92d41ed66caef2192683fb4 Mon Sep 17 00:00:00 2001 From: Ananovo Date: Sat, 8 Aug 2026 23:07:21 +0800 Subject: [PATCH] feat(web): support project and global pinned sessions (#1115) * feat(web): support persistent pinned sessions * fix(web): preserve project hierarchy for pinned sessions * fix(web): preserve pins during session deduplication * fix(hub): preserve pins when merging sessions * fix(hub): migrate session pins from schema v15 * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * fix: align pinning with schema and sidebar filters * fix(web): expose pinning in session header menu * test(hub): expect schema v17 after pin migration * fix(web): report pin action failures * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * chore: retrigger PR review * fix: address pinning review regressions * fix(web): scope pin error toast to session rows * test(hub): expect schema v20 after migration * fix(hub): preserve latest source pin during merge * test(hub): expect schema v22 after pin migration * feat(web): add project and global session pin modes Support mutually exclusive project vs global pins, surface both in the session action menu, and render globally pinned sessions in a top-level sidebar group with project path labels. * fix(web): polish pinned section icon and divider alignment * fix(web): tighten pinned section title icon alignment * fix(web): restore original pinned section pin icon shape * fix(web): rename pinned section to pinned sessions * fix(hub): prefer stronger pin mode when merging sessions Keep global pins over project pins during consolidation so a project-pinned source cannot downgrade an already or concurrently global-pinned target. Co-authored-by: Cursor * fix(web): keep inactive project-pinned groups expanded Pinned sessions should stay easy to find after reload; do not hide them behind the default inactive-group collapse. Co-authored-by: Cursor * fix(web): keep project pins in directory groups --------- Co-authored-by: Cursor --- hub/src/store/index.ts | 16 +- hub/src/store/migration-v13.test.ts | 6 +- hub/src/store/migration-v15.test.ts | 8 +- hub/src/store/migration-v18.test.ts | 2 +- hub/src/store/migration-v19.test.ts | 2 +- hub/src/store/migration-v20.test.ts | 2 +- hub/src/store/migration-v22.test.ts | 35 ++++ hub/src/store/sessionStore.ts | 11 ++ hub/src/store/sessions.test.ts | 25 +++ hub/src/store/sessions.ts | 25 +++ hub/src/store/types.ts | 2 + hub/src/sync/sessionCache.ts | 43 ++++ hub/src/sync/sessionModel.test.ts | 184 ++++++++++++++++++ hub/src/sync/syncEngine.ts | 8 + hub/src/web/routes/sessions.test.ts | 31 +++ hub/src/web/routes/sessions.ts | 24 +++ shared/src/apiTypes.ts | 7 + shared/src/schemas.ts | 2 + shared/src/sessionSummary.test.ts | 7 + shared/src/sessionSummary.ts | 4 + web/src/api/client.ts | 7 + web/src/components/SessionActionMenu.test.tsx | 34 ++++ web/src/components/SessionActionMenu.tsx | 46 +++++ web/src/components/SessionHeader.test.tsx | 75 ++++++- web/src/components/SessionHeader.tsx | 18 +- .../SessionList.directory-action.test.tsx | 71 +++++-- web/src/components/SessionList.test.ts | 55 +++++- web/src/components/SessionList.tsx | 152 +++++++++++++-- web/src/hooks/mutations/useSessionActions.ts | 11 ++ web/src/hooks/useSSE.ts | 6 + web/src/lib/locales/en.ts | 6 + web/src/lib/locales/zh-CN.ts | 6 + 32 files changed, 887 insertions(+), 44 deletions(-) create mode 100644 hub/src/store/migration-v22.test.ts diff --git a/hub/src/store/index.ts b/hub/src/store/index.ts index e30007ac..865a4054 100644 --- a/hub/src/store/index.ts +++ b/hub/src/store/index.ts @@ -33,7 +33,7 @@ export { SessionStore } from './sessionStore' export { UserStore } from './userStore' export { UsageStore } from './usageStore' -const SCHEMA_VERSION: number = 21 +const SCHEMA_VERSION: number = 22 const REQUIRED_TABLES = [ 'sessions', 'machines', @@ -289,6 +289,7 @@ export class Store { 18: () => this.migrateFromV18ToV19(), 19: () => this.migrateFromV19ToV20(), 20: () => this.migrateFromV20ToV21(), + 21: () => this.migrateFromV21ToV22(), }) if (currentVersion === 0) { @@ -355,6 +356,8 @@ export class Store { todos_updated_at INTEGER, team_state TEXT, team_state_updated_at INTEGER, + pinned INTEGER NOT NULL DEFAULT 0, + global_pinned INTEGER NOT NULL DEFAULT 0, active INTEGER DEFAULT 0, active_at INTEGER, seq INTEGER DEFAULT 0 @@ -839,6 +842,17 @@ export class Store { `) } + private migrateFromV21ToV22(): void { + const columns = this.getSessionColumnNames() + if (columns.size === 0) return + if (!columns.has('pinned')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN pinned INTEGER NOT NULL DEFAULT 0') + } + if (!columns.has('global_pinned')) { + this.db.exec('ALTER TABLE sessions ADD COLUMN global_pinned INTEGER NOT NULL DEFAULT 0') + } + } + private getSessionColumnNames(): Set { const rows = this.db.prepare('PRAGMA table_info(sessions)').all() as Array<{ name: string }> return new Set(rows.map((row) => row.name)) diff --git a/hub/src/store/migration-v13.test.ts b/hub/src/store/migration-v13.test.ts index 64df91f7..a099009b 100644 --- a/hub/src/store/migration-v13.test.ts +++ b/hub/src/store/migration-v13.test.ts @@ -10,7 +10,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { const store = new Store(':memory:') expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(21) + expect(getUserVersion(store)).toBe(22) store.close() }) @@ -34,7 +34,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(21) + expect(getUserVersion(store)).toBe(22) expect(store.messages.getMessageEpoch('session-1')).toBe(0) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { @@ -72,7 +72,7 @@ describe('Store V12/V13→V14 schema reconciliation', () => { store = new Store(dbPath) expect(tableExists(store, 'message_epochs')).toBe(true) expect(tableExists(store, 'session_scratchlist')).toBe(true) - expect(getUserVersion(store)).toBe(21) + expect(getUserVersion(store)).toBe(22) expect(store.messages.getMessages('session-1')).toHaveLength(1) } finally { store?.close() diff --git a/hub/src/store/migration-v15.test.ts b/hub/src/store/migration-v15.test.ts index aa931b96..ce8ade58 100644 --- a/hub/src/store/migration-v15.test.ts +++ b/hub/src/store/migration-v15.test.ts @@ -19,7 +19,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(21) + expect(getUserVersion(store)).toBe(22) store.close() }) @@ -40,14 +40,14 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { expect(cols).toContain('attachments') expect(getColumns(store, 'usage_events')).toContain('last_input_tokens') expect(getColumns(store, 'usage_scan_state')).toContain('last_seq') - expect(getUserVersion(store)).toBe(21) + expect(getUserVersion(store)).toBe(22) } finally { store?.close() rmSync(dir, { recursive: true, force: true }) } }) - it('V15 DB reopen is idempotent: schema unchanged', () => { + it('latest DB reopen is idempotent: schema unchanged', () => { const dir = mkdtempSync(join(tmpdir(), 'hapi-migration-v15-idempotent-')) const dbPath = join(dir, 'test.db') let store1: Store | undefined @@ -60,7 +60,7 @@ describe('Store V14→V15 migration: scratchlist attachments column', () => { store2 = new Store(dbPath) const cols2 = getColumns(store2, 'session_scratchlist') expect(cols2).toEqual(cols1) - expect(getUserVersion(store2)).toBe(21) + expect(getUserVersion(store2)).toBe(22) } finally { store2?.close() store1?.close() diff --git a/hub/src/store/migration-v18.test.ts b/hub/src/store/migration-v18.test.ts index 91b49551..af662bf1 100644 --- a/hub/src/store/migration-v18.test.ts +++ b/hub/src/store/migration-v18.test.ts @@ -38,7 +38,7 @@ describe('Store V18->V19 migration: usage scan state', () => { const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } expect(table?.name).toBe('usage_scan_state') - expect(version.user_version).toBe(21) + expect(version.user_version).toBe(22) expect(usageRows.count).toBe(0) } finally { store?.close() diff --git a/hub/src/store/migration-v19.test.ts b/hub/src/store/migration-v19.test.ts index 32a5e8bc..8e665934 100644 --- a/hub/src/store/migration-v19.test.ts +++ b/hub/src/store/migration-v19.test.ts @@ -37,7 +37,7 @@ describe('Store V19->current migration: usage re-index', () => { const scanRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_scan_state').get() as { count: number } const usageRows = internalDb.prepare('SELECT COUNT(*) AS count FROM usage_events').get() as { count: number } - expect(version.user_version).toBe(21) + expect(version.user_version).toBe(22) expect(scanRows.count).toBe(0) expect(usageRows.count).toBe(0) } finally { diff --git a/hub/src/store/migration-v20.test.ts b/hub/src/store/migration-v20.test.ts index 4f59e8bc..7cfec238 100644 --- a/hub/src/store/migration-v20.test.ts +++ b/hub/src/store/migration-v20.test.ts @@ -43,7 +43,7 @@ describe('Store V20->V21 migration: usage semantics re-index', () => { store = new Store(dbPath) const internalDb = (store as unknown as { db: Database }).db const count = (table: string): number => (internalDb.prepare(`SELECT COUNT(*) AS count FROM ${table}`).get() as { count: number }).count - expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(21) + expect((internalDb.prepare('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(22) expect(count('usage_events')).toBe(0) expect(count('usage_scan_state')).toBe(0) expect(store.messages.getMessages(session.id)).toHaveLength(1) diff --git a/hub/src/store/migration-v22.test.ts b/hub/src/store/migration-v22.test.ts new file mode 100644 index 00000000..f71573db --- /dev/null +++ b/hub/src/store/migration-v22.test.ts @@ -0,0 +1,35 @@ +import { afterEach, describe, expect, it } from 'bun:test' +import { Database } from 'bun:sqlite' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { Store } from './index' + +const tempDirs: string[] = [] + +afterEach(() => { + for (const dir of tempDirs.splice(0)) { + rmSync(dir, { recursive: true, force: true }) + } +}) + +describe('schema migration v21 to v22', () => { + it('adds pinned and global_pinned columns with unpinned defaults', () => { + const dir = mkdtempSync(join(tmpdir(), 'hapi-migration-v22-')) + tempDirs.push(dir) + const dbPath = join(dir, 'hapi.db') + + new Store(dbPath).close() + const legacy = new Database(dbPath) + legacy.exec('ALTER TABLE sessions DROP COLUMN pinned') + legacy.exec('ALTER TABLE sessions DROP COLUMN global_pinned') + legacy.exec('PRAGMA user_version = 21') + legacy.close() + + const migrated = new Store(dbPath) + const session = migrated.sessions.getOrCreateSession('migration-pin', {}, null, 'default') + expect(session.pinned).toBe(false) + expect(session.globalPinned).toBe(false) + migrated.close() + }) +}) diff --git a/hub/src/store/sessionStore.ts b/hub/src/store/sessionStore.ts index 75eed3c9..0efd403e 100644 --- a/hub/src/store/sessionStore.ts +++ b/hub/src/store/sessionStore.ts @@ -13,6 +13,9 @@ import { setSessionModelReasoningEffort, setSessionServiceTier, setSessionActive, + setSessionPinned, + setSessionPinMode, + type SessionPinMode, setSessionTeamState, setSessionTodos, replaceSessionTodos, @@ -101,6 +104,14 @@ export class SessionStore { return setSessionActive(this.db, id, active, activeAt, namespace) } + setSessionPinned(id: string, pinned: boolean, namespace: string): boolean { + return setSessionPinned(this.db, id, pinned, namespace) + } + + setSessionPinMode(id: string, mode: SessionPinMode, namespace: string): boolean { + return setSessionPinMode(this.db, id, mode, namespace) + } + touchSessionUpdatedAt(id: string, updatedAt: number, namespace: string): boolean { return touchSessionUpdatedAt(this.db, id, updatedAt, namespace) } diff --git a/hub/src/store/sessions.test.ts b/hub/src/store/sessions.test.ts index c3daba35..94762c86 100644 --- a/hub/src/store/sessions.test.ts +++ b/hub/src/store/sessions.test.ts @@ -32,6 +32,31 @@ describe('getOrCreateSession: active_at', () => { }) }) +describe('session pinning', () => { + it('persists project and global pin modes without changing session recency', () => { + const store = makeStore() + const session = store.sessions.getOrCreateSession('pin-test', {}, null, 'default') + + expect(session.pinned).toBe(false) + expect(session.globalPinned).toBe(false) + expect(store.sessions.setSessionPinMode(session.id, 'project', 'default')).toBe(true) + + const projectPinned = store.sessions.getSession(session.id) + expect(projectPinned?.pinned).toBe(true) + expect(projectPinned?.globalPinned).toBe(false) + expect(projectPinned?.updatedAt).toBe(session.updatedAt) + + expect(store.sessions.setSessionPinMode(session.id, 'global', 'default')).toBe(true) + const globalPinned = store.sessions.getSession(session.id) + expect(globalPinned?.pinned).toBe(false) + expect(globalPinned?.globalPinned).toBe(true) + + expect(store.sessions.setSessionPinMode(session.id, 'none', 'other')).toBe(false) + expect(store.sessions.getSession(session.id)?.globalPinned).toBe(true) + store.close() + }) +}) + describe('getOrCreateSession: requested identity', () => { it('creates and idempotently reloads a client-requested id', () => { const store = makeStore() diff --git a/hub/src/store/sessions.ts b/hub/src/store/sessions.ts index be8b8c5c..c0d23236 100644 --- a/hub/src/store/sessions.ts +++ b/hub/src/store/sessions.ts @@ -139,6 +139,8 @@ type DbSessionRow = { machine_id: string | null created_at: number updated_at: number + pinned: number + global_pinned: number metadata: string | null metadata_version: number agent_state: string | null @@ -164,6 +166,8 @@ function toStoredSession(row: DbSessionRow): StoredSession { machineId: row.machine_id, createdAt: row.created_at, updatedAt: row.updated_at, + pinned: row.pinned === 1, + globalPinned: row.global_pinned === 1, metadata: safeJsonParse(row.metadata), metadataVersion: row.metadata_version, agentState: safeJsonParse(row.agent_state), @@ -617,6 +621,27 @@ export function setSessionActive( } } +export type SessionPinMode = 'none' | 'project' | 'global' + +export function setSessionPinMode(db: Database, id: string, mode: SessionPinMode, namespace: string): boolean { + const pinned = mode === 'project' ? 1 : 0 + const globalPinned = mode === 'global' ? 1 : 0 + const result = db.prepare(` + UPDATE sessions + SET pinned = @pinned, + global_pinned = @global_pinned + WHERE id = @id + AND namespace = @namespace + AND (pinned != @pinned OR global_pinned != @global_pinned) + `).run({ id, namespace, pinned, global_pinned: globalPinned }) + return result.changes === 1 +} + +/** @deprecated Prefer setSessionPinMode — kept for project-pin merge helpers. */ +export function setSessionPinned(db: Database, id: string, pinned: boolean, namespace: string): boolean { + return setSessionPinMode(db, id, pinned ? 'project' : 'none', namespace) +} + export function touchSessionUpdatedAt( db: Database, id: string, diff --git a/hub/src/store/types.ts b/hub/src/store/types.ts index 0bd63f7c..a744ac22 100644 --- a/hub/src/store/types.ts +++ b/hub/src/store/types.ts @@ -5,6 +5,8 @@ export type StoredSession = { machineId: string | null createdAt: number updatedAt: number + pinned: boolean + globalPinned: boolean metadata: unknown | null metadataVersion: number agentState: unknown | null diff --git a/hub/src/sync/sessionCache.ts b/hub/src/sync/sessionCache.ts index cf364467..fdd3dd46 100644 --- a/hub/src/sync/sessionCache.ts +++ b/hub/src/sync/sessionCache.ts @@ -181,6 +181,8 @@ export class SessionCache { seq: stored.seq, createdAt: stored.createdAt, updatedAt: stored.updatedAt, + pinned: stored.pinned, + globalPinned: stored.globalPinned, active: existing?.active ?? stored.active, // Legacy / idle rows may still have active_at NULL in SQLite. // Public Session.activeAt is always a number for CLI Zod parse. @@ -222,6 +224,17 @@ export class SessionCache { } } + setSessionPinned(sessionId: string, pinned: boolean): void { + this.setSessionPinMode(sessionId, pinned ? 'project' : 'none') + } + + setSessionPinMode(sessionId: string, mode: 'none' | 'project' | 'global'): void { + const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) + if (!session) throw new Error('Session not found') + this.store.sessions.setSessionPinMode(sessionId, mode, session.namespace) + this.refreshSession(sessionId) + } + markSessionActive(sessionId: string, time: number = Date.now()): void { const t = clampAliveTime(time) ?? Date.now() const session = this.sessions.get(sessionId) ?? this.refreshSession(sessionId) @@ -1179,6 +1192,36 @@ export class SessionCache { } } + const latestSource = this.store.sessions.getSessionByNamespace(oldSessionId, namespace) + const latestSourceMode = latestSource?.globalPinned + ? 'global' as const + : latestSource?.pinned + ? 'project' as const + : 'none' as const + if (latestSourceMode !== 'none') { + const latest = this.store.sessions.getSessionByNamespace(newSessionId, namespace) + if (!latest) { + throw new Error('Session not found for merge') + } + const latestMode = latest.globalPinned ? 'global' : latest.pinned ? 'project' : 'none' + // Prefer the stronger pin: global > project > none. Never downgrade a + // concurrently (or already) global-pinned target to project-only. + const desiredMode = + latestSourceMode === 'global' || latestMode === 'global' + ? 'global' as const + : latestSourceMode === 'project' || latestMode === 'project' + ? 'project' as const + : 'none' as const + if (desiredMode !== latestMode) { + const updated = this.store.sessions.setSessionPinMode(newSessionId, desiredMode, namespace) + const now = this.store.sessions.getSessionByNamespace(newSessionId, namespace) + const nowMode = now?.globalPinned ? 'global' : now?.pinned ? 'project' : 'none' + if (!updated && nowMode !== desiredMode) { + throw new Error('Failed to preserve session pin during merge') + } + } + } + if (oldStored.todos !== null && oldStored.todosUpdatedAt !== null) { this.store.sessions.setSessionTodos( newSessionId, diff --git a/hub/src/sync/sessionModel.test.ts b/hub/src/sync/sessionModel.test.ts index 8ba8bc38..7a3fea13 100644 --- a/hub/src/sync/sessionModel.test.ts +++ b/hub/src/sync/sessionModel.test.ts @@ -280,6 +280,190 @@ describe('session model', () => { expect(store.sessions.getSession(newSession.id)?.serviceTier).toBe('fast') }) + it('preserves pin from old session when merging into resumed session', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-pin-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(oldSession.id, 'project', 'default') + const newSession = cache.getOrCreateSession( + 'session-pin-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(true) + expect(store.sessions.getSession(newSession.id)?.globalPinned).toBe(false) + expect(cache.getSession(newSession.id)?.pinned).toBe(true) + }) + + it('preserves global pin from old session when merging into resumed session', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-global-pin-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(oldSession.id, 'global', 'default') + const newSession = cache.getOrCreateSession( + 'session-global-pin-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(false) + expect(store.sessions.getSession(newSession.id)?.globalPinned).toBe(true) + expect(cache.getSession(newSession.id)?.globalPinned).toBe(true) + }) + + it('keeps a global-pinned merge target when the source is only project-pinned', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-pin-downgrade-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(oldSession.id, 'project', 'default') + const newSession = cache.getOrCreateSession( + 'session-pin-downgrade-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(newSession.id, 'global', 'default') + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(false) + expect(store.sessions.getSession(newSession.id)?.globalPinned).toBe(true) + expect(cache.getSession(newSession.id)?.globalPinned).toBe(true) + }) + + it('accepts a merge target pinned concurrently during pin preservation', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-pin-race-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + const newSession = cache.getOrCreateSession( + 'session-pin-race-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(oldSession.id, 'project', 'default') + + const setSessionPinMode = store.sessions.setSessionPinMode.bind(store.sessions) + store.sessions.setSessionPinMode = ((sessionId, mode, namespace) => { + setSessionPinMode(sessionId, mode, namespace) + return false + }) as typeof store.sessions.setSessionPinMode + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(true) + expect(cache.getSession(newSession.id)?.pinned).toBe(true) + }) + + it('keeps a concurrent global pin on the merge target when the source is project-pinned', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-pin-global-race-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + const newSession = cache.getOrCreateSession( + 'session-pin-global-race-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + store.sessions.setSessionPinMode(oldSession.id, 'project', 'default') + + const getSessionByNamespace = store.sessions.getSessionByNamespace.bind(store.sessions) + let targetReads = 0 + store.sessions.getSessionByNamespace = ((sessionId, namespace) => { + if (sessionId === newSession.id && ++targetReads === 1) { + store.sessions.setSessionPinMode(newSession.id, 'global', 'default') + } + return getSessionByNamespace(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(false) + expect(store.sessions.getSession(newSession.id)?.globalPinned).toBe(true) + expect(cache.getSession(newSession.id)?.globalPinned).toBe(true) + }) + + it('preserves the latest source pin when it changes during a merge', async () => { + const store = new Store(':memory:') + const events: SyncEvent[] = [] + const cache = new SessionCache(store, createPublisher(events)) + + const oldSession = cache.getOrCreateSession( + 'session-source-pin-race-old', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + const newSession = cache.getOrCreateSession( + 'session-source-pin-race-new', + { path: '/tmp/project', host: 'localhost', flavor: 'codex' }, + null, + 'default' + ) + + const getSessionByNamespace = store.sessions.getSessionByNamespace.bind(store.sessions) + let sourceReads = 0 + store.sessions.getSessionByNamespace = ((sessionId, namespace) => { + if (sessionId === oldSession.id && ++sourceReads === 2) { + store.sessions.setSessionPinMode(oldSession.id, 'project', 'default') + } + return getSessionByNamespace(sessionId, namespace) + }) as typeof store.sessions.getSessionByNamespace + + await cache.mergeSessions(oldSession.id, newSession.id, 'default') + + expect(store.sessions.getSession(oldSession.id)).toBeNull() + expect(store.sessions.getSession(newSession.id)?.pinned).toBe(true) + expect(cache.getSession(newSession.id)?.pinned).toBe(true) + }) + it('persists applied session model updates, including clear-to-auto', () => { const store = new Store(':memory:') const events: SyncEvent[] = [] diff --git a/hub/src/sync/syncEngine.ts b/hub/src/sync/syncEngine.ts index 949ae0ea..4e0644bc 100644 --- a/hub/src/sync/syncEngine.ts +++ b/hub/src/sync/syncEngine.ts @@ -301,6 +301,14 @@ export class SyncEngine { return this.sessionCache.getSessionsByNamespace(namespace) } + setSessionPinned(sessionId: string, pinned: boolean): void { + this.sessionCache.setSessionPinned(sessionId, pinned) + } + + setSessionPinMode(sessionId: string, mode: 'none' | 'project' | 'global'): void { + this.sessionCache.setSessionPinMode(sessionId, mode) + } + getFutureScheduledMessageCounts(sessionIds: string[], now: number = Date.now()): Map { return this.store.messages.countFutureScheduledBySessionIds(sessionIds, now) } diff --git a/hub/src/web/routes/sessions.test.ts b/hub/src/web/routes/sessions.test.ts index 24ed4a18..779d3b91 100644 --- a/hub/src/web/routes/sessions.test.ts +++ b/hub/src/web/routes/sessions.test.ts @@ -66,6 +66,8 @@ function createApp(session: Session, opts?: { getCursorChatStoreStatus?: SyncEngine['getCursorChatStoreStatus'] forkConversation?: SyncEngine['forkConversation'] rewindConversation?: SyncEngine['rewindConversation'] + setSessionPinned?: (sessionId: string, pinned: boolean) => void + setSessionPinMode?: (sessionId: string, mode: 'none' | 'project' | 'global') => void }) { const applySessionConfigCalls: Array<[string, Record]> = [] const applySessionConfig = async (sessionId: string, config: Record) => { @@ -136,6 +138,8 @@ function createApp(session: Session, opts?: { status: { onDisk: true, store: 'acp' as const } })), archiveSession: archiveSessionMock, + setSessionPinned: opts?.setSessionPinned ?? (() => {}), + setSessionPinMode: opts?.setSessionPinMode ?? (() => {}), getSessionExport: opts?.getSessionExport ?? (() => ({ type: 'success', payload: { @@ -165,6 +169,33 @@ function createApp(session: Session, opts?: { } describe('sessions routes', () => { + it('updates the persisted pin mode', async () => { + const calls: Array<[string, 'none' | 'project' | 'global']> = [] + const { app } = createApp(createSession(), { + setSessionPinMode: (sessionId, mode) => calls.push([sessionId, mode]) + }) + + const response = await app.request('/api/sessions/session-1/pin', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: 'global' }) + }) + + expect(response.status).toBe(200) + expect(calls).toEqual([['session-1', 'global']]) + }) + + it('rejects an invalid pin body', async () => { + const { app } = createApp(createSession()) + const response = await app.request('/api/sessions/session-1/pin', { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: 'yes' }) + }) + + expect(response.status).toBe(400) + }) + it('returns the machine-scoped Cursor chat store status', async () => { const session = createSession({ active: false, diff --git a/hub/src/web/routes/sessions.ts b/hub/src/web/routes/sessions.ts index 014fd657..ab3dafd2 100644 --- a/hub/src/web/routes/sessions.ts +++ b/hub/src/web/routes/sessions.ts @@ -5,6 +5,7 @@ import { getPermissionModesForFlavor, isPermissionModeAllowedForFlavor, RenameSessionRequestSchema, + SetSessionPinnedRequestSchema, ResumeSessionRequestSchema, RewindConversationRequestSchema, SCRATCHLIST_MAX_ENTRIES, @@ -89,6 +90,12 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho if (order === 'updatedAt') { return b.updatedAt - a.updatedAt } + if (Boolean(a.globalPinned) !== Boolean(b.globalPinned)) { + return a.globalPinned ? -1 : 1 + } + if (Boolean(a.pinned) !== Boolean(b.pinned)) { + return a.pinned ? -1 : 1 + } // Active sessions first (web session list) if (a.active !== b.active) { return a.active ? -1 : 1 @@ -790,6 +797,23 @@ export function createSessionsRoutes(getSyncEngine: () => SyncEngine | null): Ho } }) + app.put('/sessions/:id/pin', async (c) => { + const engine = requireSyncEngine(c, getSyncEngine) + if (engine instanceof Response) return engine + + const sessionResult = requireSessionFromParam(c, engine) + if (sessionResult instanceof Response) return sessionResult + + const body = await c.req.json().catch(() => null) + const parsed = SetSessionPinnedRequestSchema.safeParse(body) + if (!parsed.success) { + return c.json({ error: 'Invalid body: mode must be none, project, or global' }, 400) + } + + engine.setSessionPinMode(sessionResult.sessionId, parsed.data.mode) + return c.json({ ok: true }) + }) + app.delete('/sessions/:id', async (c) => { const engine = requireSyncEngine(c, getSyncEngine) if (engine instanceof Response) { diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index ca7f333d..5db9ee85 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -308,6 +308,13 @@ export const RenameSessionRequestSchema = z.object({ export type RenameSessionRequest = z.infer +export const SetSessionPinnedRequestSchema = z.object({ + mode: z.enum(['none', 'project', 'global']) +}) + +export type SetSessionPinnedRequest = z.infer +export type SessionPinMode = SetSessionPinnedRequest['mode'] + /** * An empty string clears the custom name, so unlike session rename there is no * `min(1)`: the machine falls back to its hostname. The length ceiling is diff --git a/shared/src/schemas.ts b/shared/src/schemas.ts index ace0208a..dc9288ae 100644 --- a/shared/src/schemas.ts +++ b/shared/src/schemas.ts @@ -299,6 +299,8 @@ export const SessionSchema = z.object({ seq: z.number(), createdAt: z.number(), updatedAt: z.number(), + pinned: z.boolean().optional(), + globalPinned: z.boolean().optional(), active: z.boolean(), // Hub may still emit null for legacy SQLite rows; keep output type number. activeAt: z.number().nullish().transform((value) => value ?? 0), diff --git a/shared/src/sessionSummary.test.ts b/shared/src/sessionSummary.test.ts index 82df97f3..379b79dd 100644 --- a/shared/src/sessionSummary.test.ts +++ b/shared/src/sessionSummary.test.ts @@ -69,6 +69,13 @@ describe('getPendingRequestKinds', () => { }) describe('toSessionSummary', () => { + it('includes the pinned state', () => { + expect(toSessionSummary(makeSession({ pinned: true })).pinned).toBe(true) + expect(toSessionSummary(makeSession({ globalPinned: true })).globalPinned).toBe(true) + expect(toSessionSummary(makeSession()).pinned).toBe(false) + expect(toSessionSummary(makeSession()).globalPinned).toBe(false) + }) + it('uses grokSessionId as the native resume token', () => { const summary = toSessionSummary(makeSession({ metadata: { diff --git a/shared/src/sessionSummary.ts b/shared/src/sessionSummary.ts index 0fde9b00..bf8bc485 100644 --- a/shared/src/sessionSummary.ts +++ b/shared/src/sessionSummary.ts @@ -51,6 +51,8 @@ export type SessionSummary = { thinking: boolean activeAt: number updatedAt: number + pinned?: boolean + globalPinned?: boolean metadata: SessionSummaryMetadata | null /** Watermarks for structured SSE patches (PR #897). List cache must gate * without requiring a detail query — otherwise global SSE forces O(N) @@ -206,6 +208,8 @@ export function toSessionSummary(session: Session): SessionSummary { thinking: session.thinking, activeAt: session.activeAt, updatedAt: session.updatedAt, + pinned: session.pinned ?? false, + globalPinned: session.globalPinned ?? false, metadata: toSessionSummaryMetadata(session.metadata), metadataVersion: session.metadataVersion, agentStateVersion: session.agentStateVersion, diff --git a/web/src/api/client.ts b/web/src/api/client.ts index ba8ed1a4..de06d4a9 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -916,6 +916,13 @@ export class ApiClient { }) } + async setSessionPinMode(sessionId: string, mode: 'none' | 'project' | 'global'): Promise { + await this.request(`/api/sessions/${encodeURIComponent(sessionId)}/pin`, { + method: 'PUT', + body: JSON.stringify({ mode }) + }) + } + async deleteSession(sessionId: string): Promise { await this.request(`/api/sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE' diff --git a/web/src/components/SessionActionMenu.test.tsx b/web/src/components/SessionActionMenu.test.tsx index 14d192c9..5ac0f5f6 100644 --- a/web/src/components/SessionActionMenu.test.tsx +++ b/web/src/components/SessionActionMenu.test.tsx @@ -40,6 +40,40 @@ beforeEach(() => { vi.clearAllMocks() }) +describe('SessionActionMenu - Pin action', () => { + it('renders project and global pin actions', () => { + const onSetPinMode = vi.fn() + const { rerender } = renderMenu({ onSetPinMode, sessionPinned: false, sessionGlobalPinned: false }) + + fireEvent.click(screen.getByRole('menuitem', { name: 'Pin in project' })) + expect(onSetPinMode).toHaveBeenCalledWith('project') + + fireEvent.click(screen.getByRole('menuitem', { name: 'Pin globally' })) + expect(onSetPinMode).toHaveBeenCalledWith('global') + + rerender( + + + + ) + expect(screen.getByRole('menuitem', { name: 'Unpin from project' })).toBeInTheDocument() + expect(screen.getByRole('menuitem', { name: 'Unpin globally' })).toBeInTheDocument() + }) +}) + describe('SessionActionMenu - Reopen action', () => { it('renders the Reopen item on inactive sessions when onReopen is provided', () => { renderMenu({ sessionActive: false }) diff --git a/web/src/components/SessionActionMenu.tsx b/web/src/components/SessionActionMenu.tsx index 1d0adaac..f7e66aa9 100644 --- a/web/src/components/SessionActionMenu.tsx +++ b/web/src/components/SessionActionMenu.tsx @@ -21,6 +21,9 @@ type SessionActionMenuProps = { sessionTitle: string sessionActive: boolean onRename: () => void + sessionPinned?: boolean + sessionGlobalPinned?: boolean + onSetPinMode?: (mode: 'none' | 'project' | 'global') => void onExport?: () => void onSyncCodex?: () => void onSyncPi?: () => void @@ -52,6 +55,18 @@ function EditIcon(props: { className?: string }) { ) } +function PinIcon(props: { className?: string; filled?: boolean }) { + return ( + + + + + + ) +} + function ArchiveIcon(props: { className?: string }) { return ( { + onClose() + onSetPinMode?.(mode) + } + const handleArchive = () => { onClose() onArchive() @@ -362,6 +385,29 @@ export function SessionActionMenu(props: SessionActionMenuProps) { {t('session.action.copyReference')} + {onSetPinMode ? ( + <> + + + + ) : null} + {onExport ? (
{toast.title}: {toast.body}
)} +} + function baseSession(overrides: Partial = {}): Session { return { id: 'session-1', @@ -266,4 +272,71 @@ describe('SessionHeader', () => { vi.useRealTimers() } }) + + it('toggles pin state from the header action menu', async () => { + const setSessionPinMode = vi.fn().mockResolvedValue(undefined) + const api = { + getScratchlist: vi.fn().mockResolvedValue({ entries: [] }), + setSessionPinMode + } as unknown as ApiClient + const session: Session = { + id: 'session-pin', + namespace: 'default', + seq: 0, + createdAt: 0, + updatedAt: 0, + active: false, + activeAt: 0, + metadata: { flavor: 'codex', path: '/repo', host: 'machine' }, + metadataVersion: 0, + agentState: null, + agentStateVersion: 0, + thinking: false, + thinkingAt: 0, + model: null, + modelReasoningEffort: null, + effort: null, + serviceTier: null, + pinned: false, + globalPinned: false + } + + render( + + + + + + + + ) + + fireEvent.click(screen.getByTitle('More actions')) + fireEvent.click(screen.getByRole('menuitem', { name: 'Pin globally' })) + + await waitFor(() => expect(setSessionPinMode).toHaveBeenCalledWith('session-pin', 'global')) + }) + + it('shows an error toast when toggling the pin fails', async () => { + const api = { + getScratchlist: vi.fn().mockResolvedValue({ entries: [] }), + setSessionPinMode: vi.fn().mockRejectedValue(new Error('Network unavailable')) + } as unknown as ApiClient + + render( + + + + + + + + + ) + + fireEvent.click(screen.getByTitle('More actions')) + fireEvent.click(screen.getByRole('menuitem', { name: 'Pin in project' })) + + expect(await screen.findByText('Could not update pin: Network unavailable')).toBeInTheDocument() + }) }) diff --git a/web/src/components/SessionHeader.tsx b/web/src/components/SessionHeader.tsx index cdb2a769..51cb37ca 100644 --- a/web/src/components/SessionHeader.tsx +++ b/web/src/components/SessionHeader.tsx @@ -220,12 +220,25 @@ export function SessionHeader(props: { const [isSyncingCodex, setIsSyncingCodex] = useState(false) const [isSyncingPi, setIsSyncingPi] = useState(false) - const { archiveSession, reopenSession, renameSession, deleteSession, isPending } = useSessionActions( + const { archiveSession, reopenSession, renameSession, setPinMode, deleteSession, isPending } = useSessionActions( api, session.id, session.metadata?.flavor ?? null ) const [reopenError, setReopenError] = useState(null) + + const handleSetPinMode = async (mode: 'none' | 'project' | 'global') => { + try { + await setPinMode(mode) + } catch (error) { + addToast({ + title: t('session.action.pinFailed'), + body: error instanceof Error ? error.message : t('dialog.error.default'), + sessionId: session.id, + url: `/sessions/${session.id}` + }) + } + } // tiann/hapi#893: surface the scratchlist entry count in the // delete-confirm copy so the operator knows what cascades when they // confirm. Read-only hook reuses the cache filled by SessionChat - @@ -499,7 +512,10 @@ export function SessionHeader(props: { sessionId={session.id} sessionTitle={title} sessionActive={session.active} + sessionPinned={Boolean(session.pinned)} + sessionGlobalPinned={Boolean(session.globalPinned)} onRename={() => setRenameOpen(true)} + onSetPinMode={api ? (mode) => void handleSetPinMode(mode) : undefined} onExport={() => setExportOpen(true)} onSyncCodex={api && codexSessionId ? handleSyncCodex : undefined} onSyncPi={api && piSessionId && !session.active ? handleSyncPi : undefined} diff --git a/web/src/components/SessionList.directory-action.test.tsx b/web/src/components/SessionList.directory-action.test.tsx index f3b90e9c..9eec0a04 100644 --- a/web/src/components/SessionList.directory-action.test.tsx +++ b/web/src/components/SessionList.directory-action.test.tsx @@ -359,18 +359,20 @@ describe('SessionList collapse behavior', () => { mutations: { retry: false }, } })}> - - - + + + + + ) } @@ -470,6 +472,30 @@ describe('SessionList collapse behavior', () => { expect(getProjectPanel().getAttribute('data-open')).toBeNull() }) + it('keeps project-pinned active sessions in their project group when the preference is on', () => { + localStorage.setItem('hapi-pin-in-progress-sessions', 'true') + const sessions = [ + makeSession({ + id: 'session-pinned-running', + active: true, + thinking: true, + pinned: true, + updatedAt: 100, + metadata: { path: '/work/hapi', name: 'Pinned running task', flavor: 'codex' }, + }), + makeSession({ + id: 'session-idle', + updatedAt: 50, + metadata: { path: '/work/hapi', name: 'Idle task', flavor: 'codex' }, + }), + ] + render(renderSessionList(sessions, null)) + + expect(screen.queryByTitle('In progress')).toBeNull() + expect(getProjectPanel().getAttribute('data-open')).toBe('true') + expect(screen.getByRole('button', { name: /Pinned running task/ })).toBeInTheDocument() + }) + it('does not label quiet active sessions as Idle', () => { const sessions = [ makeSession({ @@ -557,6 +583,27 @@ describe('SessionList collapse behavior', () => { }) }) + it('keeps an inactive project-pinned group expanded with no selection', () => { + const sessions = [ + makeSession({ + id: 'session-pinned', + pinned: true, + updatedAt: 100, + metadata: { path: '/work/hapi', name: 'Pinned task', flavor: 'codex' }, + }), + makeSession({ + id: 'session-idle', + updatedAt: 50, + metadata: { path: '/work/hapi', name: 'Idle task', flavor: 'codex' }, + }), + ] + render(renderSessionList(sessions, null)) + + expect(getProjectPanel().getAttribute('data-open')).toBe('true') + expect(screen.getByRole('button', { name: /Pinned task/ })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Idle task/ })).toBeInTheDocument() + }) + it('keeps the running section open while searching even when collapsed', () => { localStorage.setItem('hapi-pin-in-progress-sessions', 'true') const sessions = [ diff --git a/web/src/components/SessionList.test.ts b/web/src/components/SessionList.test.ts index decad12c..623ab87b 100644 --- a/web/src/components/SessionList.test.ts +++ b/web/src/components/SessionList.test.ts @@ -20,6 +20,7 @@ import { prepareSidebarSessions, sessionMatchesQuery, sessionMatchesTimeRange, + shouldShowPinnedDivider, shouldShowSessionInSidebar } from './SessionList' @@ -91,6 +92,27 @@ describe('getWorktreeSessionLabel', () => { }) }) +describe('shouldShowPinnedDivider', () => { + it('shows one divider at the visible pinned-to-unpinned boundary', () => { + const sessions = [ + makeSession({ id: 'pinned-a', pinned: true }), + makeSession({ id: 'pinned-b', pinned: true }), + makeSession({ id: 'regular-a' }), + makeSession({ id: 'regular-b' }) + ] + + expect(sessions.map((_, index) => shouldShowPinnedDivider(sessions, index))) + .toEqual([false, false, true, false]) + }) + + it('does not show a divider when all visible sessions have the same pin state', () => { + expect(shouldShowPinnedDivider([ + makeSession({ id: 'a' }), + makeSession({ id: 'b' }) + ], 1)).toBe(false) + }) +}) + describe('deduplicateSessionsByAgentId', () => { it('deduplicates sessions with the same agentSessionId', () => { const sessions = [ @@ -122,6 +144,26 @@ describe('deduplicateSessionsByAgentId', () => { expect(result[0].id).toBe('a') // selected wins despite older updatedAt }) + it('preserves a pinned session when deduplicating by recency', () => { + const sessions = [ + makeSession({ id: 'pinned', pinned: true, metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 100 }), + makeSession({ id: 'recent', metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 200 }) + ] + const result = deduplicateSessionsByAgentId(sessions) + expect(result).toHaveLength(1) + expect(result[0].id).toBe('pinned') + }) + + it('keeps the selected inactive session ahead of a pinned duplicate', () => { + const sessions = [ + makeSession({ id: 'selected', metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 100 }), + makeSession({ id: 'pinned', pinned: true, metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 200 }) + ] + const result = deduplicateSessionsByAgentId(sessions, 'selected') + expect(result).toHaveLength(1) + expect(result[0].id).toBe('selected') + }) + it('active always wins over selected inactive', () => { const sessions = [ makeSession({ id: 'a', metadata: { path: '/p', agentSessionId: 'thread-1' }, updatedAt: 200 }), @@ -286,6 +328,16 @@ describe('prepareSidebarSessions', () => { expect(result.map(session => session.id).sort()).toEqual(['real', 'stub']) }) + it('keeps a pinned inactive stub visible', () => { + const sessions = [ + makeSession({ id: 'pinned-stub', pinned: true, metadata: { path: '/work/hapi' } }), + makeSession({ id: 'stub', metadata: { path: '/work/hapi' } }) + ] + + const result = prepareSidebarSessions(sessions) + expect(result.map(session => session.id)).toEqual(['pinned-stub']) + }) + it('deduplicates before filtering stubs', () => { const sessions = [ makeSession({ id: 'stub', metadata: { path: '/work/hapi' } }), @@ -307,11 +359,12 @@ describe('prepareSidebarSessions', () => { }) describe('shouldShowSessionInSidebar', () => { - it('always shows active and selected sessions', () => { + it('always shows active, selected, and pinned sessions', () => { const stub = makeSession({ id: 'stub', metadata: { path: '/work/hapi' } }) expect(shouldShowSessionInSidebar(stub)).toBe(false) expect(shouldShowSessionInSidebar(stub, 'stub')).toBe(true) expect(shouldShowSessionInSidebar({ ...stub, active: true })).toBe(true) + expect(shouldShowSessionInSidebar({ ...stub, pinned: true })).toBe(true) }) }) diff --git a/web/src/components/SessionList.tsx b/web/src/components/SessionList.tsx index 3daa7aaa..24812d22 100644 --- a/web/src/components/SessionList.tsx +++ b/web/src/components/SessionList.tsx @@ -9,6 +9,16 @@ import { SessionExportDialog } from '@/components/SessionExportDialog' import { RenameSessionDialog } from '@/components/RenameSessionDialog' import { ConfirmDialog } from '@/components/ui/ConfirmDialog' import { CopyIcon, CheckIcon } from '@/components/icons' + +function PinnedSectionIcon(props: { className?: string }) { + return ( + + ) +} import { cn } from '@/lib/utils' import { useTranslation } from '@/lib/use-translation' import { DEFAULT_SESSION_PREVIEW_LIMIT, useSessionPreviewLimit } from '@/hooks/useSessionPreviewLimit' @@ -30,6 +40,7 @@ import { useCursorChatStoreStatus } from '@/hooks/queries/useCursorChatStoreStat import { SessionRowSummary } from '@/components/SessionRowSummary' import { Spinner } from '@/components/Spinner' import { transferComposerDraftThenNavigate } from '@/lib/composer-draft-transfer' +import { useToast } from '@/lib/toast-context' export { getWorktreeSessionLabel } from '@/lib/sessionWorktreeLabel' @@ -41,6 +52,7 @@ type SessionGroup = { sessions: SessionSummary[] latestUpdatedAt: number hasActiveSession: boolean + hasPinnedSession: boolean } const RUNNING_BUCKETS = [ @@ -147,6 +159,7 @@ type MachineGroup = { projectGroups: SessionGroup[] totalSessions: number hasActiveSession: boolean + hasPinnedSession: boolean latestUpdatedAt: number } @@ -194,6 +207,9 @@ export function deduplicateSessionsByAgentId(sessions: SessionSummary[], selecte // Among inactive duplicates, keep the selected one visible if (a.id === selectedSessionId) return -1 if (b.id === selectedSessionId) return 1 + // Preserve an explicit pin when otherwise choosing by recency + if (Boolean(a.globalPinned) !== Boolean(b.globalPinned)) return a.globalPinned ? -1 : 1 + if (Boolean(a.pinned) !== Boolean(b.pinned)) return a.pinned ? -1 : 1 return b.updatedAt - a.updatedAt }) result.push(group[0]) @@ -221,7 +237,7 @@ export function isSidebarEmptySessionStub(session: SessionSummary): boolean { export function shouldShowSessionInSidebar(session: SessionSummary, selectedSessionId?: string | null): boolean { if (session.id === selectedSessionId) return true - if (session.active) return true + if (session.active || session.pinned || session.globalPinned) return true return !isSidebarEmptySessionStub(session) } @@ -281,6 +297,7 @@ function groupSessionsByDirectory(sessions: SessionSummary[]): SessionGroup[] { return Array.from(groups.entries()) .map(([key, group]) => { const sortedSessions = [...group.sessions].sort((a, b) => { + if (Boolean(a.pinned) !== Boolean(b.pinned)) return a.pinned ? -1 : 1 const rankA = a.active ? (a.pendingRequestsCount > 0 ? 0 : 1) : 2 const rankB = b.active ? (b.pendingRequestsCount > 0 ? 0 : 1) : 2 if (rankA !== rankB) return rankA - rankB @@ -291,6 +308,7 @@ function groupSessionsByDirectory(sessions: SessionSummary[]): SessionGroup[] { -Infinity ) const hasActiveSession = group.sessions.some(s => s.active) + const hasPinnedSession = group.sessions.some(s => s.pinned) const displayName = getGroupDisplayName(group.directory) return { @@ -300,10 +318,14 @@ function groupSessionsByDirectory(sessions: SessionSummary[]): SessionGroup[] { machineId: group.machineId, sessions: sortedSessions, latestUpdatedAt, - hasActiveSession + hasActiveSession, + hasPinnedSession } }) .sort((a, b) => { + if (a.hasPinnedSession !== b.hasPinnedSession) { + return a.hasPinnedSession ? -1 : 1 + } if (a.hasActiveSession !== b.hasActiveSession) { return a.hasActiveSession ? -1 : 1 } @@ -342,6 +364,7 @@ function groupByMachine( projectGroups: [], totalSessions: 0, hasActiveSession: false, + hasPinnedSession: false, latestUpdatedAt: 0, } map.set(key, mg) @@ -349,9 +372,11 @@ function groupByMachine( mg.projectGroups.push(g) mg.totalSessions += g.sessions.length if (g.hasActiveSession) mg.hasActiveSession = true + if (g.hasPinnedSession) mg.hasPinnedSession = true if (g.latestUpdatedAt > mg.latestUpdatedAt) mg.latestUpdatedAt = g.latestUpdatedAt } return [...map.values()].sort((a, b) => { + if (a.hasPinnedSession !== b.hasPinnedSession) return a.hasPinnedSession ? -1 : 1 if (a.hasActiveSession !== b.hasActiveSession) return a.hasActiveSession ? -1 : 1 return b.latestUpdatedAt - a.latestUpdatedAt }) @@ -547,6 +572,11 @@ export function getVisibleSessionPreview( return visible } +export function shouldShowPinnedDivider(sessions: SessionSummary[], index: number): boolean { + if (index <= 0 || index >= sessions.length) return false + return Boolean(sessions[index - 1]?.pinned) && !sessions[index]?.pinned +} + function CalendarIcon(props: { className?: string }) { return ( @@ -847,6 +877,7 @@ function SessionItem(props: { machineLabel?: string }) { const { t } = useTranslation() + const { addToast } = useToast() const { session: s, onSelect, showPath = true, api, selected = false, showDetailedStatus = false, inRunningSection = false, projectLabel, machineLabel } = props const { haptic } = usePlatform() const [menuOpen, setMenuOpen] = useState(false) @@ -872,13 +903,26 @@ function SessionItem(props: { : t('session.action.reopenCursorChecking') : undefined - const { archiveSession, reopenSession, renameSession, deleteSession, isPending } = useSessionActions( + const { archiveSession, reopenSession, renameSession, deleteSession, setPinMode, isPending } = useSessionActions( api, s.id, s.metadata?.flavor ?? null ) const [reopenError, setReopenError] = useState(null) + const handleSetPinMode = async (mode: 'none' | 'project' | 'global') => { + try { + await setPinMode(mode) + } catch (error) { + addToast({ + title: t('session.action.pinFailed'), + body: error instanceof Error ? error.message : t('dialog.error.default'), + sessionId: s.id, + url: `/sessions/${s.id}` + }) + } + } + const handleReopen = async () => { setReopenError(null) try { @@ -956,6 +1000,9 @@ function SessionItem(props: { sessionId={s.id} sessionTitle={sessionName} sessionActive={s.active} + sessionPinned={Boolean(s.pinned)} + sessionGlobalPinned={Boolean(s.globalPinned)} + onSetPinMode={(mode) => void handleSetPinMode(mode)} onRename={() => setRenameOpen(true)} onExport={() => setExportOpen(true)} onArchive={() => setArchiveOpen(true)} @@ -1191,6 +1238,11 @@ export function SessionList(props: { ), [unreadFilteredSessions, activeMachineFilter] ) + const globalPinnedSessions = useMemo(() => { + return machineFilteredSessions + .filter((session) => Boolean(session.globalPinned)) + .sort((a, b) => b.updatedAt - a.updatedAt) + }, [machineFilteredSessions]) const runningSessions = useMemo(() => { const buckets: Record<'working' | 'pending', SessionSummary[]> = { working: [], @@ -1200,6 +1252,9 @@ export function SessionList(props: { return buckets } for (const session of machineFilteredSessions) { + if (session.globalPinned || session.pinned) { + continue + } if (!session.active) { continue } @@ -1220,9 +1275,11 @@ export function SessionList(props: { + runningSessions.pending.length const groups = useMemo( () => groupSessionsByDirectory( - pinInProgressSessions - ? machineFilteredSessions.filter((session) => !isPinnedInProgressSession(session)) - : machineFilteredSessions + machineFilteredSessions.filter((session) => { + if (session.globalPinned) return false + if (pinInProgressSessions && !session.pinned && isPinnedInProgressSession(session)) return false + return true + }) ), [machineFilteredSessions, pinInProgressSessions] ) @@ -1230,6 +1287,7 @@ export function SessionList(props: { () => new Map() ) const [runningSectionCollapsed, setRunningSectionCollapsed] = useState(false) + const [pinnedSectionCollapsed, setPinnedSectionCollapsed] = useState(false) const autoExpandedSelectedSessionKeyRef = useRef(null) const isGroupCollapsed = (group: SessionGroup): boolean => { if (isFiltering) return false @@ -1238,7 +1296,7 @@ export function SessionList(props: { const hasSelectedSession = selectedSessionId ? group.sessions.some(session => session.id === selectedSessionId) : false - return !group.hasActiveSession && !hasSelectedSession + return !group.hasActiveSession && !group.hasPinnedSession && !hasSelectedSession } const toggleGroup = (groupKey: string, isCollapsed: boolean) => { @@ -1587,12 +1645,63 @@ export function SessionList(props: { /> ) : null} - {props.sessions.length > 0 && (isFiltering || activeMachineFilter !== null || showUnreadOnly) && groups.length === 0 && runningSessionTotal === 0 ? ( + {props.sessions.length > 0 && (isFiltering || activeMachineFilter !== null || showUnreadOnly) && groups.length === 0 && runningSessionTotal === 0 && globalPinnedSessions.length === 0 ? (
{t('sessions.search.noResults')}
) : null} + {globalPinnedSessions.length > 0 ? ( +
+
setPinnedSectionCollapsed((value) => !value)} + onKeyDown={(event) => { + if (event.key === 'Enter' || event.key === ' ') { + event.preventDefault() + setPinnedSectionCollapsed((value) => !value) + } + }} + title={t('sessions.pinnedSection')} + > + + + + {t('sessions.pinnedSection')} + + + +
+
+
+
+ {globalPinnedSessions.map((s) => ( + + ))} +
+
+
+
+ ) : null} + {runningSessionTotal > 0 ? (
- {visibleGroupSessions.map((s) => ( - + {visibleGroupSessions.map((s, index) => ( +
+ {shouldShowPinnedDivider(visibleGroupSessions, index) ? ( + ))} {group.sessions.length > sessionPreviewLimit && (hiddenSessionCount > 0 || canShowFewerSessions) ? (
diff --git a/web/src/hooks/mutations/useSessionActions.ts b/web/src/hooks/mutations/useSessionActions.ts index fe86fd42..448a567d 100644 --- a/web/src/hooks/mutations/useSessionActions.ts +++ b/web/src/hooks/mutations/useSessionActions.ts @@ -27,6 +27,7 @@ export function useSessionActions( setEffort: (effort: string | null) => Promise setServiceTier: (serviceTier: string | null) => Promise renameSession: (name: string) => Promise + setPinMode: (mode: 'none' | 'project' | 'global') => Promise deleteSession: () => Promise isPending: boolean } { @@ -234,6 +235,14 @@ export function useSessionActions( onSuccess: () => void invalidateSession(), }) + const pinMutation = useMutation({ + mutationFn: async (mode: 'none' | 'project' | 'global') => { + if (!api || !sessionId) throw new Error('Session unavailable') + await api.setSessionPinMode(sessionId, mode) + }, + onSuccess: () => void invalidateSession(), + }) + const deleteMutation = useMutation({ mutationFn: async () => { if (!api || !sessionId) { @@ -262,6 +271,7 @@ export function useSessionActions( setEffort: effortMutation.mutateAsync, setServiceTier: serviceTierMutation.mutateAsync, renameSession: renameMutation.mutateAsync, + setPinMode: pinMutation.mutateAsync, deleteSession: deleteMutation.mutateAsync, isPending: abortMutation.isPending || archiveMutation.isPending @@ -275,6 +285,7 @@ export function useSessionActions( || effortMutation.isPending || serviceTierMutation.isPending || renameMutation.isPending + || pinMutation.isPending || deleteMutation.isPending, } } diff --git a/web/src/hooks/useSSE.ts b/web/src/hooks/useSSE.ts index 9667197f..051a66ca 100644 --- a/web/src/hooks/useSSE.ts +++ b/web/src/hooks/useSSE.ts @@ -93,6 +93,12 @@ const RECONNECT_SLOW_MAX_DELAY_MS = 300_000 const INVALIDATION_BATCH_MS = 16 function sortSessionSummaries(left: SessionSummary, right: SessionSummary): number { + if (Boolean(left.globalPinned) !== Boolean(right.globalPinned)) { + return left.globalPinned ? -1 : 1 + } + if (Boolean(left.pinned) !== Boolean(right.pinned)) { + return left.pinned ? -1 : 1 + } if (left.active !== right.active) { return left.active ? -1 : 1 } diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 92dc4d6e..20752c92 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -228,6 +228,12 @@ export default { // Session actions 'session.action.rename': 'Rename', + 'session.action.pinProject': 'Pin in project', + 'session.action.unpinProject': 'Unpin from project', + 'session.action.pinGlobal': 'Pin globally', + 'session.action.unpinGlobal': 'Unpin globally', + 'session.action.pinFailed': 'Could not update pin', + 'sessions.pinnedSection': 'Pinned sessions', 'session.action.export': 'Export conversation', 'session.action.syncCodex': 'Sync from Codex', 'session.action.syncPi': 'Sync Pi history', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index 1d28acbd..c1b56d8d 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -228,6 +228,12 @@ export default { // Session actions 'session.action.rename': '重命名', + 'session.action.pinProject': '项目置顶', + 'session.action.unpinProject': '取消项目置顶', + 'session.action.pinGlobal': '全局置顶', + 'session.action.unpinGlobal': '取消全局置顶', + 'session.action.pinFailed': '无法更新置顶状态', + 'sessions.pinnedSection': '置顶会话', 'session.action.export': '导出对话', 'session.action.syncCodex': '从 Codex 同步', 'session.action.syncPi': '同步 Pi 历史',