mux-sesh 1.3.7 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,278 +1,162 @@
1
1
  import { spawn } from 'bun'
2
- import { readdir, readFile } from 'fs/promises'
3
- import { join } from 'path'
4
- import { SESSION_STORAGE, MESSAGE_STORAGE } from './constants'
2
+ import {
3
+ getActiveSessionRow,
4
+ getDirectoryAggregate,
5
+ getMessageCountByDirectory,
6
+ getMessageCountBySession,
7
+ getMostRecentSessionRow,
8
+ getMostRecentSessionTitleForDirectory,
9
+ type OpencodeSessionRow,
10
+ } from './sqlite'
5
11
  import { getLastMessageTokens } from './tokens'
6
12
  import type { OpencodeStats } from './types'
7
13
 
8
- export async function getTmuxSessionDirectory(sessionName: string): Promise<string> {
9
- try {
10
- const proc = spawn(['tmux', 'display-message', '-t', sessionName, '-p', '#{pane_current_path}'])
11
- const output = await new Response(proc.stdout).text()
12
- return output.trim()
13
- } catch (error) {
14
- console.error('Failed to get tmux session directory:', error)
15
- return ''
16
- }
14
+ function toSummaryValue(value: number | null): number {
15
+ return value ?? 0
17
16
  }
18
17
 
19
- export async function getMessageCount(sessionID: string): Promise<number> {
20
- try {
21
- if (!sessionID) return 0
22
-
23
- const messageDir = join(MESSAGE_STORAGE, sessionID)
24
- const messageFiles = await readdir(messageDir).catch(() => [])
25
-
26
- return messageFiles.filter(file => file.endsWith('.json')).length
27
- } catch (error) {
28
- console.error('Failed to get message count:', error)
29
- return 0
18
+ async function buildSessionStats(row: OpencodeSessionRow): Promise<OpencodeStats> {
19
+ const [messageCount, lastMessageData] = await Promise.all([
20
+ getMessageCountBySession(row.sessionID),
21
+ getLastMessageTokens(row.sessionID),
22
+ ])
23
+
24
+ return {
25
+ sessionID: row.sessionID,
26
+ title: row.title,
27
+ projectID: row.projectID,
28
+ directory: row.directory,
29
+ messageCount,
30
+ filesModified: toSummaryValue(row.filesModified),
31
+ additions: toSummaryValue(row.additions),
32
+ deletions: toSummaryValue(row.deletions),
33
+ createdAt: row.createdAt,
34
+ updatedAt: row.updatedAt,
35
+ lastMessageTokens: lastMessageData?.lastMessageTokens,
36
+ contextLimit: lastMessageData?.contextLimit,
37
+ sessionTotalCost: lastMessageData?.totalCost,
30
38
  }
31
39
  }
32
40
 
33
- export async function getAggregatedMessageCount(directory: string): Promise<number> {
34
- try {
35
- const projectDirs = await readdir(SESSION_STORAGE)
36
- let totalMessages = 0
37
-
38
- for (const projectID of projectDirs) {
39
- const projectPath = join(SESSION_STORAGE, projectID)
40
-
41
- try {
42
- const sessionFiles = await readdir(projectPath)
41
+ export async function getTmuxSessionDirectory(sessionName: string): Promise<string> {
42
+ const proc = spawn(['tmux', 'display-message', '-t', sessionName, '-p', '#{pane_current_path}'])
43
+ const output = await new Response(proc.stdout).text()
44
+ await proc.exited
43
45
 
44
- for (const sessionFile of sessionFiles) {
45
- if (!sessionFile.endsWith('.json')) continue
46
+ if (proc.exitCode !== 0) {
47
+ throw new Error(`Failed to resolve tmux directory for session '${sessionName}'`)
48
+ }
46
49
 
47
- const sessionPath = join(projectPath, sessionFile)
48
- const content = await readFile(sessionPath, 'utf-8')
49
- const sessionData = JSON.parse(content)
50
+ const directory = output.trim()
51
+ if (!directory) {
52
+ throw new Error(`tmux returned an empty directory for session '${sessionName}'`)
53
+ }
50
54
 
51
- if (sessionData.directory === directory) {
52
- totalMessages += await getMessageCount(sessionData.id)
53
- }
54
- }
55
- } catch (err) {
56
- continue
57
- }
58
- }
55
+ return directory
56
+ }
59
57
 
60
- return totalMessages
61
- } catch (error) {
62
- console.error('Failed to get aggregated message count:', error)
58
+ export async function getMessageCount(sessionID: string): Promise<number> {
59
+ if (!sessionID) {
63
60
  return 0
64
61
  }
65
- }
66
-
67
- export async function getActiveOpencodeSession(directory: string): Promise<OpencodeStats | null> {
68
- try {
69
- const projectDirs = await readdir(SESSION_STORAGE)
70
- const now = Date.now()
71
- const fiveMinutesAgo = now - 5 * 60 * 1000
72
-
73
- let mostRecentActive: OpencodeStats | null = null
74
- let latestTime = 0
75
-
76
- for (const projectID of projectDirs) {
77
- const projectPath = join(SESSION_STORAGE, projectID)
78
-
79
- try {
80
- const sessionFiles = await readdir(projectPath)
81
-
82
- for (const sessionFile of sessionFiles) {
83
- if (!sessionFile.endsWith('.json')) continue
84
-
85
- const sessionPath = join(projectPath, sessionFile)
86
- const content = await readFile(sessionPath, 'utf-8')
87
- const sessionData = JSON.parse(content)
88
62
 
89
- if (sessionData.directory === directory) {
90
- const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
63
+ return getMessageCountBySession(sessionID)
64
+ }
91
65
 
92
- if (updatedAt >= fiveMinutesAgo && updatedAt > latestTime) {
93
- latestTime = updatedAt
94
- const lastMessageData = await getLastMessageTokens(sessionData.id)
95
- mostRecentActive = {
96
- sessionID: sessionData.id,
97
- title: sessionData.title,
98
- projectID,
99
- directory: sessionData.directory,
100
- messageCount: await getMessageCount(sessionData.id),
101
- filesModified: sessionData.summary?.files || 0,
102
- additions: sessionData.summary?.additions || 0,
103
- deletions: sessionData.summary?.deletions || 0,
104
- createdAt: sessionData.time?.created,
105
- updatedAt: sessionData.time?.updated,
106
- lastMessageTokens: lastMessageData?.lastMessageTokens,
107
- contextLimit: lastMessageData?.contextLimit,
108
- sessionTotalCost: lastMessageData?.totalCost,
109
- }
110
- }
111
- }
112
- }
113
- } catch (err) {
114
- continue
115
- }
116
- }
66
+ export async function getAggregatedMessageCount(directory: string): Promise<number> {
67
+ return getMessageCountByDirectory(directory)
68
+ }
117
69
 
118
- return mostRecentActive
119
- } catch (error) {
120
- console.error('Failed to get active OpenCode session:', error)
70
+ export async function getActiveOpencodeSession(directory: string): Promise<OpencodeStats | null> {
71
+ const row = await getActiveSessionRow(directory, Date.now() - 5 * 60 * 1000)
72
+ if (!row) {
121
73
  return null
122
74
  }
75
+
76
+ return buildSessionStats(row)
123
77
  }
124
78
 
125
79
  export async function getAggregatedOpencodeStats(directory: string): Promise<OpencodeStats | null> {
126
- try {
127
- const projectDirs = await readdir(SESSION_STORAGE)
128
-
129
- let totalSessions = 0
130
- let totalFiles = 0
131
- let totalAdditions = 0
132
- let totalDeletions = 0
133
- let oldestTime = Date.now()
134
- let newestTime = 0
135
- let mostRecentSession: any = null
136
-
137
- for (const projectID of projectDirs) {
138
- const projectPath = join(SESSION_STORAGE, projectID)
139
-
140
- try {
141
- const sessionFiles = await readdir(projectPath)
142
-
143
- for (const sessionFile of sessionFiles) {
144
- if (!sessionFile.endsWith('.json')) continue
145
-
146
- const sessionPath = join(projectPath, sessionFile)
147
- const content = await readFile(sessionPath, 'utf-8')
148
- const sessionData = JSON.parse(content)
149
-
150
- if (sessionData.directory === directory) {
151
- totalSessions++
152
- totalFiles += sessionData.summary?.files || 0
153
- totalAdditions += sessionData.summary?.additions || 0
154
- totalDeletions += sessionData.summary?.deletions || 0
155
-
156
- const createdAt = sessionData.time?.created || 0
157
- const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
158
-
159
- if (createdAt < oldestTime) oldestTime = createdAt
160
- if (updatedAt > newestTime) {
161
- newestTime = updatedAt
162
- mostRecentSession = sessionData
163
- }
164
- }
165
- }
166
- } catch (err) {
167
- continue
168
- }
169
- }
170
-
171
- if (totalSessions === 0) return null
172
-
173
- return {
174
- title: `Global OpenCode Sessions (${totalSessions} total)`,
175
- directory,
176
- messageCount: await getAggregatedMessageCount(directory),
177
- filesModified: totalFiles,
178
- additions: totalAdditions,
179
- deletions: totalDeletions,
180
- createdAt: oldestTime,
181
- updatedAt: newestTime,
182
- sessionCount: totalSessions,
183
- mostRecentTitle: mostRecentSession?.title || 'Unknown',
184
- }
185
- } catch (error) {
186
- console.error('Failed to get aggregated OpenCode stats:', error)
80
+ const aggregate = await getDirectoryAggregate(directory)
81
+ if (!aggregate) {
187
82
  return null
188
83
  }
84
+
85
+ const [messageCount, mostRecentTitle] = await Promise.all([
86
+ getAggregatedMessageCount(directory),
87
+ getMostRecentSessionTitleForDirectory(directory),
88
+ ])
89
+
90
+ return {
91
+ title: `Global OpenCode Sessions (${aggregate.sessionCount} total)`,
92
+ directory,
93
+ messageCount,
94
+ filesModified: aggregate.filesModified,
95
+ additions: aggregate.additions,
96
+ deletions: aggregate.deletions,
97
+ createdAt: aggregate.createdAt,
98
+ updatedAt: aggregate.updatedAt,
99
+ sessionCount: aggregate.sessionCount,
100
+ mostRecentTitle: mostRecentTitle ?? 'Unknown',
101
+ }
189
102
  }
190
103
 
191
104
  export async function getMostRecentSessionForDirectory(
192
105
  directory: string
193
106
  ): Promise<OpencodeStats | null> {
194
- try {
195
- const projectDirs = await readdir(SESSION_STORAGE)
196
-
197
- let mostRecent: OpencodeStats | null = null
198
- let latestTime = 0
199
-
200
- for (const projectID of projectDirs) {
201
- const projectPath = join(SESSION_STORAGE, projectID)
202
-
203
- try {
204
- const sessionFiles = await readdir(projectPath)
205
-
206
- for (const sessionFile of sessionFiles) {
207
- if (!sessionFile.endsWith('.json')) continue
208
-
209
- const sessionPath = join(projectPath, sessionFile)
210
- const content = await readFile(sessionPath, 'utf-8')
211
- const sessionData = JSON.parse(content)
107
+ const row = await getMostRecentSessionRow(directory)
108
+ if (!row) {
109
+ return null
110
+ }
212
111
 
213
- if (sessionData.directory === directory) {
214
- const updatedAt = sessionData.time?.updated || sessionData.time?.created || 0
112
+ return buildSessionStats(row)
113
+ }
215
114
 
216
- if (updatedAt > latestTime) {
217
- latestTime = updatedAt
218
- const lastMessageData = await getLastMessageTokens(sessionData.id)
219
- mostRecent = {
220
- sessionID: sessionData.id,
221
- title: sessionData.title,
222
- projectID,
223
- directory: sessionData.directory,
224
- messageCount: await getMessageCount(sessionData.id),
225
- filesModified: sessionData.summary?.files || 0,
226
- additions: sessionData.summary?.additions || 0,
227
- deletions: sessionData.summary?.deletions || 0,
228
- createdAt: sessionData.time?.created,
229
- updatedAt: sessionData.time?.updated,
230
- lastMessageTokens: lastMessageData?.lastMessageTokens,
231
- contextLimit: lastMessageData?.contextLimit,
232
- sessionTotalCost: lastMessageData?.totalCost,
233
- }
234
- }
235
- }
236
- }
237
- } catch (err) {
238
- continue
239
- }
115
+ interface DetailedSessionExport {
116
+ info?: {
117
+ id?: string
118
+ title?: string
119
+ projectID?: string
120
+ directory?: string
121
+ summary?: {
122
+ files?: number
123
+ additions?: number
124
+ deletions?: number
125
+ }
126
+ time?: {
127
+ created?: number
128
+ updated?: number
240
129
  }
241
-
242
- return mostRecent
243
- } catch (error) {
244
- console.error('Failed to get most recent session for directory:', error)
245
- return null
246
130
  }
131
+ messages?: unknown[]
247
132
  }
248
133
 
249
134
  export async function getDetailedSessionStats(sessionID: string): Promise<OpencodeStats | null> {
250
- try {
251
- const proc = spawn(['opencode', 'export', sessionID])
252
- const output = await new Response(proc.stdout).text()
253
-
254
- const jsonStart = output.indexOf('{')
255
- if (jsonStart === -1) return null
135
+ const proc = spawn(['opencode', 'export', sessionID])
136
+ const output = await new Response(proc.stdout).text()
137
+ await proc.exited
256
138
 
257
- const jsonData = output.slice(jsonStart)
258
- const data = JSON.parse(jsonData)
259
-
260
- const messageCount = data.messages?.length || 0
139
+ if (proc.exitCode !== 0) {
140
+ throw new Error(`Failed to export OpenCode session '${sessionID}'`)
141
+ }
261
142
 
262
- return {
263
- sessionID: data.info?.id,
264
- title: data.info?.title,
265
- projectID: data.info?.projectID,
266
- directory: data.info?.directory,
267
- messageCount,
268
- filesModified: data.info?.summary?.files || 0,
269
- additions: data.info?.summary?.additions || 0,
270
- deletions: data.info?.summary?.deletions || 0,
271
- createdAt: data.info?.time?.created,
272
- updatedAt: data.info?.time?.updated,
273
- }
274
- } catch (error) {
275
- console.error('Failed to get detailed session stats:', error)
143
+ const jsonStart = output.indexOf('{')
144
+ if (jsonStart === -1) {
276
145
  return null
277
146
  }
147
+
148
+ const data = JSON.parse(output.slice(jsonStart)) as DetailedSessionExport
149
+
150
+ return {
151
+ sessionID: data.info?.id,
152
+ title: data.info?.title,
153
+ projectID: data.info?.projectID,
154
+ directory: data.info?.directory,
155
+ messageCount: data.messages?.length ?? 0,
156
+ filesModified: data.info?.summary?.files ?? 0,
157
+ additions: data.info?.summary?.additions ?? 0,
158
+ deletions: data.info?.summary?.deletions ?? 0,
159
+ createdAt: data.info?.time?.created,
160
+ updatedAt: data.info?.time?.updated,
161
+ }
278
162
  }