All files / src sessionStore.ts

86.6% Statements 97/112
60% Branches 39/65
85.71% Functions 12/14
94.62% Lines 88/93

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214                          34x       2x       16x       12x 12x 12x   10x         4x 4x 4x 4x       8x 8x   8x 10x 8x   8x 9x 9x 9x 16x   9x     9x             9x 8x     7x     6x 6x     6x 6x 6x 6x 6x 6x 5x 5x 1x   1x 1x 1x 1x 1x 1x                   6x                         8x 8x       4x 4x   4x 6x 4x   4x 6x 6x 6x 12x 6x   6x           6x 6x   5x 5x   5x 5x   5x 5x 5x 5x   5x 5x 5x                   5x 5x     5x 5x       5x 5x 5x 3x 3x 3x               5x   3x                         4x 4x       2x 2x 2x          
import * as fs from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
 
export interface SessionMeta {
  id: string // Use 'id' to match webview expectations
  workingDir: string
  created: string
  title: string
  updatedAt: number
}
 
function sessionsDir(): string {
  return path.join(os.homedir(), '.boltzbit', 'sessions')
}
 
function sessionFile(sessionId: string): string {
  return path.join(sessionsDir(), `${sessionId}.jsonl`)
}
 
function titlesFile(): string {
  return path.join(sessionsDir(), '_titles.json')
}
 
function loadCustomTitles(): Record<string, string> {
  try {
    const raw = fs.readFileSync(titlesFile(), 'utf-8')
    return JSON.parse(raw) as Record<string, string>
  } catch {
    return {}
  }
}
 
export function setSessionTitle(sessionId: string, title: string): void {
  const titles = loadCustomTitles()
  titles[sessionId] = title
  fs.mkdirSync(sessionsDir(), { recursive: true })
  fs.writeFileSync(titlesFile(), JSON.stringify(titles, null, 2), 'utf-8')
}
 
export function listSessions(workingDir: string): SessionMeta[] {
  const dir = sessionsDir()
  Iif (!fs.existsSync(dir)) return []
 
  const customTitles = loadCustomTitles()
  const files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl'))
  const sessions: SessionMeta[] = []
 
  for (const file of files) {
    try {
      const filePath = path.join(dir, file)
      const content = fs.readFileSync(filePath, 'utf-8')
      const lines = content.split('\n').filter((l) => l.trim())
 
      Iif (lines.length === 0) continue
 
      // Parse first line (session metadata)
      const firstLine = JSON.parse(lines[0]) as {
        type: string
        sessionId: string
        workingDir: string
        created: string
      }
 
      Iif (firstLine.type !== 'session') continue
      if (firstLine.workingDir !== workingDir) continue
 
      // Skip empty sessions (only session metadata, no actual messages)
      if (lines.length < 2) continue
 
      // Get file mtime for updatedAt
      const stats = fs.statSync(filePath)
      const updatedAt = stats.mtimeMs
 
      // Extract title from first user message (second line if it exists)
      let title = 'New conversation'
      Eif (lines.length > 1) {
        try {
          const secondLine = JSON.parse(lines[1]) as { role?: string; content?: string | unknown[] }
          Eif (secondLine.role === 'user') {
            if (typeof secondLine.content === 'string') {
              const text = secondLine.content.trim()
              title = text.length > 60 ? `${text.slice(0, 57)}...` : text
            E} else if (Array.isArray(secondLine.content)) {
              // Handle content blocks (first text block)
              for (const block of secondLine.content) {
                const b = block as { type?: string; text?: string }
                Eif (b.type === 'text' && typeof b.text === 'string' && b.text.trim()) {
                  const text = b.text.trim()
                  title = text.length > 60 ? `${text.slice(0, 57)}...` : text
                  break
                }
              }
            }
          }
        } catch {
          // Failed to parse second line, keep default title
        }
      }
 
      sessions.push({
        id: firstLine.sessionId,
        workingDir: firstLine.workingDir,
        created: firstLine.created,
        title: customTitles[firstLine.sessionId] ?? title,
        updatedAt,
      })
    } catch {
      // Skip corrupted files
    }
  }
 
  // Sort by most recent first
  sessions.sort((a, b) => b.updatedAt - a.updatedAt)
  return sessions
}
 
export function searchSessions(workingDir: string, query: string): (SessionMeta & { snippet: string })[] {
  const dir = sessionsDir()
  Iif (!fs.existsSync(dir)) return []
 
  const lower = query.toLowerCase()
  const files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl'))
  const results: (SessionMeta & { snippet: string })[] = []
 
  for (const file of files) {
    try {
      const filePath = path.join(dir, file)
      const content = fs.readFileSync(filePath, 'utf-8')
      const lines = content.split('\n').filter((l) => l.trim())
      Iif (lines.length < 2) continue
 
      const firstLine = JSON.parse(lines[0]) as {
        type: string
        sessionId: string
        workingDir: string
        created: string
      }
      Iif (firstLine.type !== 'session') continue
      if (firstLine.workingDir !== workingDir) continue
 
      const stats = fs.statSync(filePath)
      const updatedAt = stats.mtimeMs
 
      let title = 'New conversation'
      let snippet = ''
 
      for (let i = 1; i < lines.length; i++) {
        try {
          const parsed = JSON.parse(lines[i]) as { role?: string; content?: string | unknown[] }
          Iif (parsed.role !== 'user') continue
 
          let text = ''
          if (typeof parsed.content === 'string') {
            text = parsed.content
          E} else if (Array.isArray(parsed.content)) {
            for (const block of parsed.content) {
              const b = block as { type?: string; text?: string }
              if (b.type === 'text' && typeof b.text === 'string') {
                text += b.text
              }
            }
          }
 
          text = text.trim()
          Iif (!text) continue
 
          // Extract title from first user message
          Eif (i === 1 || title === 'New conversation') {
            title = text.length > 60 ? `${text.slice(0, 57)}...` : text
          }
 
          // Check for query match
          Eif (!snippet) {
            const idx = text.toLowerCase().indexOf(lower)
            if (idx !== -1) {
              const start = Math.max(0, idx - 20)
              const end = Math.min(text.length, idx + query.length + 60)
              snippet = (start > 0 ? '...' : '') + text.slice(start, end) + (end < text.length ? '...' : '')
            }
          }
        } catch {
          // Skip malformed lines
        }
      }
 
      if (!snippet) continue
 
      results.push({
        id: firstLine.sessionId,
        workingDir: firstLine.workingDir,
        created: firstLine.created,
        title,
        updatedAt,
        snippet,
      })
    } catch {
      // Skip corrupted files
    }
  }
 
  results.sort((a, b) => b.updatedAt - a.updatedAt)
  return results.slice(0, 30)
}
 
export function deleteSession(sessionId: string): void {
  const filePath = sessionFile(sessionId)
  try {
    fs.unlinkSync(filePath)
  } catch {
    // Already gone or never existed
  }
}