mux-sesh 1.4.1 → 1.5.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.
@@ -0,0 +1,235 @@
1
+ import { readdir } from 'fs/promises'
2
+ import { basename, join } from 'path'
3
+ import { spawn } from 'bun'
4
+ import { getSessionDetails } from '../tmux'
5
+ import type { Config, SessionDetails } from '../types'
6
+ import { getGitRoot, resolveProjectSession } from '../config/session-rules'
7
+
8
+ const MAX_PREVIEW_LINES = 24
9
+ const MAX_PREVIEW_LINE_LENGTH = 120
10
+ const PREVIEW_COMMAND_TIMEOUT_MS = 1500
11
+
12
+ export interface ProjectPreview {
13
+ path: string
14
+ sessionName: string
15
+ source: 'project' | 'wildcard' | 'default'
16
+ startupCommand?: string
17
+ previewCommand?: string
18
+ gitRoot?: string
19
+ gitBranch?: string
20
+ linkedSession?: SessionDetails
21
+ previewKind: 'command' | 'directory'
22
+ previewLabel: string
23
+ previewLines: string[]
24
+ previewNotice?: string
25
+ }
26
+
27
+ interface FormattedPreviewOutput {
28
+ lines: string[]
29
+ truncated: boolean
30
+ }
31
+
32
+ interface PackageSummary {
33
+ name?: string
34
+ scripts: string[]
35
+ }
36
+
37
+ function displayPath(path: string): string {
38
+ return path.replace(process.env.HOME || '', '~')
39
+ }
40
+
41
+ function stripAnsi(value: string): string {
42
+ return value.replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, '')
43
+ }
44
+
45
+ export function interpolatePreviewCommand(command: string | undefined, projectPath: string): string | undefined {
46
+ if (!command) {
47
+ return undefined
48
+ }
49
+
50
+ return command.replaceAll('{}', projectPath)
51
+ }
52
+
53
+ export function formatPreviewOutput(output: string, maxLines = MAX_PREVIEW_LINES): FormattedPreviewOutput {
54
+ const cleanedLines = stripAnsi(output)
55
+ .replace(/\r/g, '')
56
+ .split('\n')
57
+ .map(line => line.trimEnd())
58
+ .filter(line => line.length > 0)
59
+ .map(line => (line.length > MAX_PREVIEW_LINE_LENGTH ? `${line.slice(0, MAX_PREVIEW_LINE_LENGTH - 1)}…` : line))
60
+
61
+ if (cleanedLines.length === 0) {
62
+ return {
63
+ lines: [],
64
+ truncated: false,
65
+ }
66
+ }
67
+
68
+ const truncated = cleanedLines.length > maxLines
69
+
70
+ return {
71
+ lines: truncated ? cleanedLines.slice(0, maxLines) : cleanedLines,
72
+ truncated,
73
+ }
74
+ }
75
+
76
+ async function getGitBranch(projectPath: string): Promise<string | undefined> {
77
+ try {
78
+ const proc = spawn(['git', '-C', projectPath, 'branch', '--show-current'], {
79
+ stderr: 'pipe',
80
+ })
81
+ const output = (await new Response(proc.stdout).text()).trim()
82
+ await proc.exited
83
+
84
+ if (proc.exitCode !== 0 || output.length === 0) {
85
+ return undefined
86
+ }
87
+
88
+ return output
89
+ } catch {
90
+ return undefined
91
+ }
92
+ }
93
+
94
+ async function readPackageSummary(projectPath: string): Promise<PackageSummary | null> {
95
+ try {
96
+ const packageJson = (await Bun.file(join(projectPath, 'package.json')).json()) as {
97
+ name?: string
98
+ scripts?: Record<string, string>
99
+ }
100
+
101
+ return {
102
+ name: packageJson.name,
103
+ scripts: Object.keys(packageJson.scripts ?? {}).slice(0, 6),
104
+ }
105
+ } catch {
106
+ return null
107
+ }
108
+ }
109
+
110
+ async function getDirectoryPreviewLines(projectPath: string): Promise<string[]> {
111
+ try {
112
+ const [entries, packageSummary] = await Promise.all([
113
+ readdir(projectPath, { withFileTypes: true }),
114
+ readPackageSummary(projectPath),
115
+ ])
116
+
117
+ const visibleEntries = entries
118
+ .filter(entry => !entry.name.startsWith('.'))
119
+ .sort((left, right) => Number(right.isDirectory()) - Number(left.isDirectory()) || left.name.localeCompare(right.name))
120
+ .slice(0, 16)
121
+
122
+ const lines: string[] = []
123
+
124
+ if (packageSummary?.name) {
125
+ lines.push(`package ${packageSummary.name}`)
126
+ }
127
+
128
+ if (packageSummary && packageSummary.scripts.length > 0) {
129
+ lines.push(`scripts ${packageSummary.scripts.join(', ')}`)
130
+ }
131
+
132
+ if (lines.length > 0) {
133
+ lines.push('')
134
+ }
135
+
136
+ for (const entry of visibleEntries) {
137
+ lines.push(entry.isDirectory() ? `${entry.name}/` : entry.name)
138
+ }
139
+
140
+ if (lines.length === 0) {
141
+ lines.push(basename(projectPath))
142
+ }
143
+
144
+ return lines
145
+ } catch {
146
+ return [basename(projectPath)]
147
+ }
148
+ }
149
+
150
+ async function runPreviewCommand(command: string, cwd: string): Promise<{ output?: string; notice?: string }> {
151
+ try {
152
+ const proc = spawn(['sh', '-lc', command], {
153
+ cwd,
154
+ stderr: 'pipe',
155
+ })
156
+
157
+ const stdoutPromise = new Response(proc.stdout).text()
158
+ let timedOut = false
159
+ const timeout = setTimeout(() => {
160
+ timedOut = true
161
+ proc.kill()
162
+ }, PREVIEW_COMMAND_TIMEOUT_MS)
163
+
164
+ await proc.exited
165
+ clearTimeout(timeout)
166
+
167
+ if (timedOut) {
168
+ return { notice: 'Preview command timed out; showing directory listing instead.' }
169
+ }
170
+
171
+ const output = await stdoutPromise
172
+ if (proc.exitCode !== 0) {
173
+ return { notice: 'Preview command failed; showing directory listing instead.' }
174
+ }
175
+
176
+ return { output }
177
+ } catch {
178
+ return { notice: 'Preview command failed; showing directory listing instead.' }
179
+ }
180
+ }
181
+
182
+ export async function getProjectPreview(
183
+ projectPath: string,
184
+ config: Config,
185
+ linkedSessionName?: string
186
+ ): Promise<ProjectPreview> {
187
+ const [resolvedSession, gitRootPath, gitBranch, linkedSession] = await Promise.all([
188
+ resolveProjectSession(projectPath, config),
189
+ getGitRoot(projectPath),
190
+ getGitBranch(projectPath),
191
+ linkedSessionName ? getSessionDetails(linkedSessionName).catch(() => null) : Promise.resolve(null),
192
+ ])
193
+
194
+ const resolvedPreviewCommand = interpolatePreviewCommand(resolvedSession.previewCommand, projectPath)
195
+ const commandResult = resolvedPreviewCommand ? await runPreviewCommand(resolvedPreviewCommand, projectPath) : undefined
196
+ const formattedCommandOutput = commandResult?.output ? formatPreviewOutput(commandResult.output) : undefined
197
+
198
+ if (formattedCommandOutput && formattedCommandOutput.lines.length > 0) {
199
+ return {
200
+ path: displayPath(projectPath),
201
+ sessionName: resolvedSession.sessionName,
202
+ source: resolvedSession.source,
203
+ startupCommand: resolvedSession.startupCommand,
204
+ previewCommand: resolvedPreviewCommand,
205
+ gitRoot: gitRootPath ? displayPath(gitRootPath) : undefined,
206
+ gitBranch,
207
+ linkedSession: linkedSession ?? undefined,
208
+ previewKind: 'command',
209
+ previewLabel: 'Preview Output',
210
+ previewLines: formattedCommandOutput.lines,
211
+ previewNotice: formattedCommandOutput.truncated
212
+ ? 'Preview output truncated to fit the panel.'
213
+ : undefined,
214
+ }
215
+ }
216
+
217
+ const fallbackLines = await getDirectoryPreviewLines(projectPath)
218
+ const formattedDirectoryOutput = formatPreviewOutput(fallbackLines.join('\n'))
219
+
220
+ return {
221
+ path: displayPath(projectPath),
222
+ sessionName: resolvedSession.sessionName,
223
+ source: resolvedSession.source,
224
+ startupCommand: resolvedSession.startupCommand,
225
+ previewCommand: resolvedPreviewCommand,
226
+ gitRoot: gitRootPath ? displayPath(gitRootPath) : undefined,
227
+ gitBranch,
228
+ linkedSession: linkedSession ?? undefined,
229
+ previewKind: 'directory',
230
+ previewLabel: 'Directory Listing',
231
+ previewLines: formattedDirectoryOutput.lines,
232
+ previewNotice: commandResult?.notice ??
233
+ (formattedDirectoryOutput.truncated ? 'Directory listing truncated to fit the panel.' : undefined),
234
+ }
235
+ }
@@ -0,0 +1,31 @@
1
+ import type { Config, Item } from '../types'
2
+ import { resolveProjectSession } from '../config/session-rules'
3
+
4
+ export async function annotateProjectItemsWithSessionLinks(
5
+ projectItems: Item[],
6
+ liveSessions: Item[],
7
+ config: Config
8
+ ): Promise<Item[]> {
9
+ const liveSessionsByTitle = new Map(liveSessions.map(session => [session.title, session]))
10
+
11
+ return Promise.all(
12
+ projectItems.map(async projectItem => {
13
+ const resolvedSession = await resolveProjectSession(projectItem.path, config)
14
+ const linkedSession = liveSessionsByTitle.get(resolvedSession.sessionName)
15
+
16
+ if (!linkedSession) {
17
+ return {
18
+ ...projectItem,
19
+ linkedSessionName: undefined,
20
+ linkedSessionAttached: undefined,
21
+ }
22
+ }
23
+
24
+ return {
25
+ ...projectItem,
26
+ linkedSessionName: linkedSession.title,
27
+ linkedSessionAttached: linkedSession.isAttached,
28
+ }
29
+ })
30
+ )
31
+ }
@@ -1,4 +1,21 @@
1
- import type { Item, SearchResult, FuzzyMatch } from '../types'
1
+ import { basename } from 'path'
2
+ import type { FuzzyMatch, Item, SearchMatchMetadata, SearchResult } from '../types'
3
+
4
+ function withSearchMatch(item: Item, searchMatch?: SearchMatchMetadata): Item {
5
+ if (!searchMatch || (!searchMatch.titleIndices && !searchMatch.descIndices)) {
6
+ if (!item.searchMatch) {
7
+ return item
8
+ }
9
+
10
+ const { searchMatch: _searchMatch, ...itemWithoutSearchMatch } = item
11
+ return itemWithoutSearchMatch
12
+ }
13
+
14
+ return {
15
+ ...item,
16
+ searchMatch,
17
+ }
18
+ }
2
19
 
3
20
  /**
4
21
  * Performs fuzzy matching and returns match positions and score
@@ -10,12 +27,10 @@ export function fuzzyMatch(text: string, query: string): FuzzyMatch | null {
10
27
  const textLower = text.toLowerCase()
11
28
  const queryLower = query.toLowerCase()
12
29
 
13
- // Track matched character positions
14
30
  const indices: number[] = []
15
31
  let textIndex = 0
16
32
  let queryIndex = 0
17
33
 
18
- // Find all query characters in order
19
34
  while (queryIndex < queryLower.length && textIndex < textLower.length) {
20
35
  if (textLower[textIndex] === queryLower[queryIndex]) {
21
36
  indices.push(textIndex)
@@ -24,25 +39,20 @@ export function fuzzyMatch(text: string, query: string): FuzzyMatch | null {
24
39
  textIndex++
25
40
  }
26
41
 
27
- // If we didn't match all characters, no match
28
42
  if (queryIndex !== queryLower.length) {
29
43
  return null
30
44
  }
31
45
 
32
- // Calculate score based on match quality
33
46
  let score = 100
34
47
 
35
- // Bonus for exact match
36
48
  if (text.toLowerCase() === query.toLowerCase()) {
37
49
  score += 10000
38
50
  }
39
51
 
40
- // Bonus for match at start
41
52
  if (indices[0] === 0) {
42
53
  score += 1000
43
54
  }
44
55
 
45
- // Bonus for consecutive characters
46
56
  let consecutiveBonus = 0
47
57
  for (let i = 1; i < indices.length; i++) {
48
58
  if (indices[i] === indices[i - 1] + 1) {
@@ -51,7 +61,6 @@ export function fuzzyMatch(text: string, query: string): FuzzyMatch | null {
51
61
  }
52
62
  score += consecutiveBonus
53
63
 
54
- // Bonus for matches after word boundaries (-, _, ., space, /)
55
64
  let boundaryBonus = 0
56
65
  for (const idx of indices) {
57
66
  if (idx > 0) {
@@ -63,86 +72,113 @@ export function fuzzyMatch(text: string, query: string): FuzzyMatch | null {
63
72
  }
64
73
  score += boundaryBonus
65
74
 
66
- // Bonus for case-sensitive exact character matches
67
75
  let caseBonus = 0
68
- for (const idx of indices) {
69
- if (text[idx] === query[indices.indexOf(idx)]) {
76
+ for (let index = 0; index < indices.length; index += 1) {
77
+ if (text[indices[index]] === query[index]) {
70
78
  caseBonus += 10
71
79
  }
72
80
  }
73
81
  score += caseBonus
74
82
 
75
- // Penalty for early gaps (characters not matched at the beginning)
76
83
  const firstMatchPos = indices[0]
77
84
  score -= firstMatchPos * 5
78
-
79
- // Penalty for length of text (shorter matches are better)
80
85
  score -= text.length * 2
81
86
 
82
- // Bonus for matching a higher percentage of the text
83
87
  const matchPercentage = indices.length / text.length
84
88
  score += matchPercentage * 100
85
89
 
86
90
  return { score, indices }
87
91
  }
88
92
 
89
- export function calculateSearchScore(item: Item, query: string): number {
93
+ interface ScoredSearchResult extends SearchResult {
94
+ item: Item
95
+ }
96
+
97
+ function calculateItemBonus(item: Item, query: string): number {
98
+ const normalizedQuery = query.toLowerCase()
99
+ const title = item.title.toLowerCase()
100
+ const pathBaseName = basename(item.path).toLowerCase()
101
+ const description = item.desc.toLowerCase()
102
+
103
+ let bonus = 0
104
+
105
+ if (title === normalizedQuery || pathBaseName === normalizedQuery) {
106
+ bonus += 5000
107
+ } else if (title.startsWith(normalizedQuery) || pathBaseName.startsWith(normalizedQuery)) {
108
+ bonus += 1200
109
+ }
110
+
111
+ if (item.path.toLowerCase().endsWith(`/${normalizedQuery}`) || description.endsWith(`/${normalizedQuery}`)) {
112
+ bonus += 2000
113
+ }
114
+
115
+ if (!item.isSession) {
116
+ const depth = item.path.split('/').filter(Boolean).length
117
+ bonus -= depth * 2
118
+ }
119
+
120
+ return bonus
121
+ }
122
+
123
+ function buildSearchResult(item: Item, query: string): ScoredSearchResult | null {
90
124
  const queryTrimmed = query.trim()
91
- if (queryTrimmed === '') return 1
125
+ if (queryTrimmed === '') {
126
+ return {
127
+ item: withSearchMatch(item),
128
+ score: 1,
129
+ }
130
+ }
92
131
 
93
132
  let bestScore = 0
94
133
  let hasMatch = false
134
+ let searchMatch: SearchMatchMetadata | undefined
95
135
 
96
- // Try fuzzy matching on title
97
136
  const titleMatch = fuzzyMatch(item.title, queryTrimmed)
98
137
  if (titleMatch && titleMatch.score > 0) {
99
- ;(item as any).titleMatchIndices = titleMatch.indices
138
+ searchMatch = {
139
+ ...searchMatch,
140
+ titleIndices: titleMatch.indices,
141
+ }
100
142
  bestScore = Math.max(bestScore, titleMatch.score)
101
143
  hasMatch = true
102
- } else {
103
- delete (item as any).titleMatchIndices
104
144
  }
105
145
 
106
- // Try fuzzy matching on description
107
146
  if (item.desc) {
108
147
  const descMatch = fuzzyMatch(item.desc, queryTrimmed)
109
148
  if (descMatch && descMatch.score > 0) {
110
- ;(item as any).descMatchIndices = descMatch.indices
111
- // Use the better score - prefer title matches slightly
149
+ searchMatch = {
150
+ ...searchMatch,
151
+ descIndices: descMatch.indices,
152
+ }
112
153
  bestScore = Math.max(bestScore, descMatch.score * 0.8)
113
154
  hasMatch = true
114
- } else {
115
- delete (item as any).descMatchIndices
116
155
  }
117
156
  }
118
157
 
119
- return hasMatch ? bestScore : 0
158
+ if (!hasMatch) {
159
+ return null
160
+ }
161
+
162
+ return {
163
+ item: withSearchMatch(item, searchMatch),
164
+ score: bestScore + calculateItemBonus(item, queryTrimmed),
165
+ }
120
166
  }
121
167
 
122
- /**
123
- * Clears match indices from items
124
- */
125
- export function clearMatchIndices(items: Item[]): void {
126
- items.forEach(item => {
127
- delete (item as any).titleMatchIndices
128
- delete (item as any).descMatchIndices
129
- })
168
+ export function clearMatchIndices(items: Item[]): Item[] {
169
+ return items.map(item => withSearchMatch(item))
130
170
  }
131
171
 
132
172
  export function filterAndSortItems(items: Item[], query: string): Item[] {
133
173
  if (!query.trim()) {
134
- // Clear any previous match indices
135
- clearMatchIndices(items)
136
- return items
174
+ return clearMatchIndices(items)
137
175
  }
138
176
 
139
- const scored: SearchResult[] = items
140
- .map(item => ({
141
- item,
142
- score: calculateSearchScore(item, query),
143
- }))
144
- .filter(({ score }) => score > 0)
177
+ return items
178
+ .flatMap(item => {
179
+ const result = buildSearchResult(item, query)
180
+ return result ? [result] : []
181
+ })
145
182
  .sort((a, b) => b.score - a.score)
146
-
147
- return scored.map(({ item }) => item)
183
+ .map(({ item }) => item)
148
184
  }
package/src/tmux/index.ts CHANGED
@@ -1,6 +1,31 @@
1
1
  import { spawn } from 'bun'
2
2
  import type { Item, SessionDetails, WindowInfo } from '../types'
3
3
 
4
+ export interface CreateTmuxSessionOptions {
5
+ startupCommand?: string
6
+ }
7
+
8
+ function sanitizeSessionName(name: string): string {
9
+ return name.replace(/\./g, '_').replace(/ /g, '_')
10
+ }
11
+
12
+ async function readTmuxValue(args: string[], errorMessage: string): Promise<string> {
13
+ const proc = spawn(args)
14
+ const output = await new Response(proc.stdout).text()
15
+ await proc.exited
16
+
17
+ if (proc.exitCode !== 0) {
18
+ throw new Error(errorMessage)
19
+ }
20
+
21
+ const value = output.trim()
22
+ if (!value) {
23
+ throw new Error(errorMessage)
24
+ }
25
+
26
+ return value
27
+ }
28
+
4
29
  export async function listTmuxSessions(): Promise<Item[]> {
5
30
  const proc = spawn([
6
31
  'tmux',
@@ -19,6 +44,7 @@ export async function listTmuxSessions(): Promise<Item[]> {
19
44
  path: name,
20
45
  desc: '',
21
46
  isSession: true,
47
+ itemKind: 'tmux' as const,
22
48
  isAttached: attached === '1',
23
49
  windowCount: windows,
24
50
  createdAt: parseInt(created, 10),
@@ -29,8 +55,12 @@ export async function listTmuxSessions(): Promise<Item[]> {
29
55
  return sessions.sort((a, b) => a.title.localeCompare(b.title))
30
56
  }
31
57
 
32
- export async function createTmuxSession(name: string, path: string): Promise<void> {
33
- const sessionName = name.replace(/\./g, '_')
58
+ export async function createTmuxSession(
59
+ name: string,
60
+ path: string,
61
+ options: CreateTmuxSessionOptions = {}
62
+ ): Promise<void> {
63
+ const sessionName = sanitizeSessionName(name)
34
64
  const insideTmux = !!process.env.TMUX
35
65
 
36
66
  // Check if tmux is running
@@ -39,7 +69,12 @@ export async function createTmuxSession(name: string, path: string): Promise<voi
39
69
  const isTmuxRunning = tmuxRunning.exitCode === 0
40
70
 
41
71
  if (!insideTmux && !isTmuxRunning) {
42
- const proc = spawn(['tmux', 'new-session', '-s', sessionName, '-c', path], {
72
+ const command = ['tmux', 'new-session', '-s', sessionName, '-c', path]
73
+ if (options.startupCommand) {
74
+ command.push(options.startupCommand)
75
+ }
76
+
77
+ const proc = spawn(command, {
43
78
  stdin: 'inherit',
44
79
  stdout: 'inherit',
45
80
  stderr: 'inherit',
@@ -55,15 +90,10 @@ export async function createTmuxSession(name: string, path: string): Promise<voi
55
90
  const createProc = spawn(['tmux', 'new-session', '-d', '-s', sessionName, '-c', path])
56
91
  await createProc.exited
57
92
 
58
- const nvimProc = spawn([
59
- 'tmux',
60
- 'send-keys',
61
- '-t',
62
- sessionName,
63
- "nvim -c \"lua vim.defer_fn(function() if pcall(require, 'telescope') then vim.cmd('Telescope find_files') end end, 100)\"",
64
- 'Enter',
65
- ])
66
- await nvimProc.exited
93
+ if (options.startupCommand) {
94
+ const startupProc = spawn(['tmux', 'send-keys', '-t', sessionName, options.startupCommand, 'Enter'])
95
+ await startupProc.exited
96
+ }
67
97
  }
68
98
 
69
99
  const switchProc = spawn(['tmux', 'switch-client', '-t', sessionName])
@@ -71,7 +101,7 @@ export async function createTmuxSession(name: string, path: string): Promise<voi
71
101
  }
72
102
 
73
103
  export async function createNamedTmuxSession(name: string): Promise<void> {
74
- const sessionName = name.replace(/\./g, '_').replace(/ /g, '_')
104
+ const sessionName = sanitizeSessionName(name)
75
105
  const insideTmux = !!process.env.TMUX
76
106
 
77
107
  const tmuxRunning = spawn(['pgrep', 'tmux'])
@@ -105,13 +135,27 @@ export async function switchTmuxSession(name: string): Promise<void> {
105
135
  await proc.exited
106
136
  }
107
137
 
138
+ export async function getCurrentTmuxSessionName(): Promise<string> {
139
+ return readTmuxValue(
140
+ ['tmux', 'display-message', '-p', '#S'],
141
+ 'Failed to resolve the current tmux session name'
142
+ )
143
+ }
144
+
145
+ export async function getTmuxSessionDirectory(sessionName: string): Promise<string> {
146
+ return readTmuxValue(
147
+ ['tmux', 'display-message', '-t', sessionName, '-p', '#{pane_current_path}'],
148
+ `Failed to resolve tmux directory for session '${sessionName}'`
149
+ )
150
+ }
151
+
108
152
  export async function killTmuxSession(name: string): Promise<void> {
109
153
  const proc = spawn(['tmux', 'kill-session', '-t', name])
110
154
  await proc.exited
111
155
  }
112
156
 
113
157
  export async function renameTmuxSession(oldName: string, newName: string): Promise<void> {
114
- const sanitizedName = newName.replace(/\./g, '_').replace(/ /g, '_')
158
+ const sanitizedName = sanitizeSessionName(newName)
115
159
  const proc = spawn(['tmux', 'rename-session', '-t', oldName, sanitizedName])
116
160
  await proc.exited
117
161
  }