mux-sesh 1.9.0 → 1.9.2

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.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "mux-sesh",
4
- "version": "1.9.0",
4
+ "version": "1.9.2",
5
5
  "description": "A beautiful tmux session manager built with OpenTUI - fuzzy search sessions, manage projects, clone from GitHub",
6
6
  "type": "module",
7
7
  "packageManager": "bun@1.3.5",
package/src/app/data.ts CHANGED
@@ -5,14 +5,13 @@ import { clearMatchIndices } from '../search'
5
5
  import { listTmuxSessions } from '../tmux'
6
6
  import { getProjectItems, getSessionCandidateItems } from '../tmux/projects'
7
7
  import { filterHiddenSessions } from '../tmux/workflows'
8
+ import { isOpencodeSessionItem } from '../opencode/session-name'
8
9
  import type { Config, Item } from '../types'
9
10
 
10
11
  export type Measure = <T>(name: string, fn: () => Promise<T>) => Promise<T>
11
12
 
12
13
  export function getSessionSelectionIndex(nextItems: Item[], selection?: string | null): number {
13
- const regularItems = nextItems.filter(
14
- item => !(item.isSession && item.title.startsWith('opencode-'))
15
- )
14
+ const regularItems = nextItems.filter(item => !isOpencodeSessionItem(item))
16
15
  if (regularItems.length === 0 || !selection) {
17
16
  return 0
18
17
  }
@@ -10,9 +10,12 @@ import {
10
10
  loadSessionCandidateItems,
11
11
  } from './data'
12
12
  import { AppMode, ViewMode, type Config, type Item } from '../types'
13
+ import { clampCursorIndex } from '../ui/list-window'
13
14
  import { isGitHubURL } from '../util/github'
14
15
  import { measure } from '../util/perf'
15
16
 
17
+ const FILE_SEARCH_DEBOUNCE_MS = 120
18
+
16
19
  export function useAutoUpdateScheduler(
17
20
  config: Config | null,
18
21
  hasScheduledAutoUpdateRef: MutableRefObject<boolean>
@@ -165,7 +168,7 @@ export function useBoundedCursor(length: number, setCursor: Dispatch<SetStateAct
165
168
  return
166
169
  }
167
170
 
168
- setCursor(current => Math.min(current, length - 1))
171
+ setCursor(current => clampCursorIndex(length, current))
169
172
  }, [length, setCursor])
170
173
  }
171
174
 
@@ -318,10 +321,13 @@ export function useNewSessionFileSearch(
318
321
  setCursor(0)
319
322
  }
320
323
 
321
- void runFileSearch()
324
+ const timeout = setTimeout(() => {
325
+ void runFileSearch()
326
+ }, FILE_SEARCH_DEBOUNCE_MS)
322
327
 
323
328
  return () => {
324
329
  cancelled = true
330
+ clearTimeout(timeout)
325
331
  }
326
332
  }, [appMode, config, searchQuery, setCursor, setItems])
327
333
  }
@@ -1,6 +1,7 @@
1
1
  import type { ModalState } from './modals'
2
2
  import type { SettingsEntry, SettingsOption } from '../settings'
3
3
  import type { CommandEntry } from '../ui/CommandsModal'
4
+ import { clampCursorIndex } from '../ui/list-window'
4
5
 
5
6
  interface ModalKeyboardContext {
6
7
  modalState: ModalState
@@ -57,9 +58,13 @@ export function handleModalKeyboard(key: KeyboardInput, ctx: ModalKeyboardContex
57
58
  if (key.name === 'escape' || key.name === 'q') {
58
59
  ctx.closeModal()
59
60
  } else if (key.name === 'down' || key.name === 'j') {
60
- ctx.setCommandsCursor(current => Math.min(current + 1, ctx.filteredCommandEntries.length - 1))
61
+ ctx.setCommandsCursor(current =>
62
+ clampCursorIndex(ctx.filteredCommandEntries.length, current + 1)
63
+ )
61
64
  } else if (key.name === 'up' || key.name === 'k') {
62
- ctx.setCommandsCursor(current => Math.max(current - 1, 0))
65
+ ctx.setCommandsCursor(current =>
66
+ clampCursorIndex(ctx.filteredCommandEntries.length, current - 1)
67
+ )
63
68
  } else if (key.name === 'return') {
64
69
  const command = ctx.filteredCommandEntries[ctx.commandsCursor]
65
70
  if (!command) {
@@ -75,10 +80,12 @@ export function handleModalKeyboard(key: KeyboardInput, ctx: ModalKeyboardContex
75
80
  ctx.closeModal()
76
81
  } else if (key.name === 'down' || key.name === 'j') {
77
82
  ctx.setSettingsCursor(current =>
78
- Math.min(current + 1, ctx.filteredSettingsEntries.length - 1)
83
+ clampCursorIndex(ctx.filteredSettingsEntries.length, current + 1)
79
84
  )
80
85
  } else if (key.name === 'up' || key.name === 'k') {
81
- ctx.setSettingsCursor(current => Math.max(current - 1, 0))
86
+ ctx.setSettingsCursor(current =>
87
+ clampCursorIndex(ctx.filteredSettingsEntries.length, current - 1)
88
+ )
82
89
  } else if (key.name === 'return' || key.name === 'e') {
83
90
  openSelectedSetting(ctx)
84
91
  }
@@ -90,10 +97,12 @@ export function handleModalKeyboard(key: KeyboardInput, ctx: ModalKeyboardContex
90
97
  ctx.setModalState({ type: 'settings' })
91
98
  } else if (key.name === 'down' || key.name === 'j') {
92
99
  ctx.setSettingOptionsCursor(current =>
93
- Math.min(current + 1, ctx.filteredSettingOptions.length - 1)
100
+ clampCursorIndex(ctx.filteredSettingOptions.length, current + 1)
94
101
  )
95
102
  } else if (key.name === 'up' || key.name === 'k') {
96
- ctx.setSettingOptionsCursor(current => Math.max(current - 1, 0))
103
+ ctx.setSettingOptionsCursor(current =>
104
+ clampCursorIndex(ctx.filteredSettingOptions.length, current - 1)
105
+ )
97
106
  } else if (key.name === 'return') {
98
107
  const option = ctx.filteredSettingOptions[ctx.settingOptionsCursor]
99
108
  if (!option) {
package/src/app/view.ts CHANGED
@@ -1,12 +1,13 @@
1
1
  import { getPanelStyle } from '../styles/theme'
2
+ import { isOpencodeSessionItem } from '../opencode/session-name'
2
3
  import { AppMode, ViewMode, type ThemeColors } from '../types'
3
4
 
4
5
  export function splitVisibleSessions<T extends { isSession: boolean; title: string }>(
5
6
  items: readonly T[]
6
7
  ) {
7
8
  return {
8
- regularSessions: items.filter(item => !(item.isSession && item.title.startsWith('opencode-'))),
9
- opencodeSessions: items.filter(item => item.isSession && item.title.startsWith('opencode-')),
9
+ regularSessions: items.filter(item => !isOpencodeSessionItem(item)),
10
+ opencodeSessions: items.filter(isOpencodeSessionItem),
10
11
  }
11
12
  }
12
13
 
@@ -7,15 +7,22 @@ import { getDefaultConfig, normalizeConfig, serializeConfig } from './index'
7
7
  export async function loadConfig(): Promise<Config> {
8
8
  const homeDir = getHomeDir()
9
9
  const configPath = getConfigPath(homeDir)
10
+ const file = Bun.file(configPath)
10
11
 
11
- try {
12
- const file = Bun.file(configPath)
13
- return normalizeConfig(await file.json(), homeDir)
14
- } catch {
12
+ if (!(await file.exists())) {
15
13
  const defaultConfig = getDefaultConfig(homeDir)
16
14
  await saveConfig(defaultConfig, homeDir)
17
15
  return defaultConfig
18
16
  }
17
+
18
+ try {
19
+ return normalizeConfig(await file.json(), homeDir)
20
+ } catch (error) {
21
+ const detail = error instanceof Error ? ` ${error.message}` : ''
22
+ throw new Error(
23
+ `Failed to parse mux-sesh config at ${configPath}. Fix the JSON or move the file aside; existing config was not overwritten.${detail}`
24
+ )
25
+ }
19
26
  }
20
27
 
21
28
  export async function saveConfig(config: Config, homeDir = getHomeDir()): Promise<void> {
@@ -1,6 +1,7 @@
1
1
  import { basename, dirname, isAbsolute, join } from 'path'
2
2
  import { stat } from 'fs/promises'
3
3
  import type { Config, Item } from '../types'
4
+ import { quoteShellArg } from '../util/shell'
4
5
 
5
6
  export interface ResolvedFileSession {
6
7
  sessionName: string
@@ -10,10 +11,6 @@ export interface ResolvedFileSession {
10
11
 
11
12
  export type TypedPathTarget = { kind: 'file' | 'directory'; path: string }
12
13
 
13
- function quoteShellArg(value: string): string {
14
- return `'${value.replaceAll("'", "'\\''")}'`
15
- }
16
-
17
14
  function sanitizeSessionName(value: string): string {
18
15
  return value.replace(/[.\s/]+/g, '_')
19
16
  }
@@ -4,10 +4,9 @@ import { getGitRoot, resolveProjectSession } from '../config/session-rules'
4
4
  import { isFileItem, resolveFileSession } from '../files/target'
5
5
  import { createTmuxSession, getTmuxSessionDirectory } from '../tmux'
6
6
  import { requestShutdown } from '../util/shutdown'
7
+ import { quoteShellArg } from '../util/shell'
7
8
 
8
- export function quoteShellArg(value: string): string {
9
- return `'${value.replaceAll("'", "'\\''")}'`
10
- }
9
+ export { quoteShellArg } from '../util/shell'
11
10
 
12
11
  export function buildEditorCommand(editor: string, path: string): string {
13
12
  return `${editor} ${quoteShellArg(path)}`
@@ -1,4 +1,5 @@
1
1
  import { AppMode, ViewMode, type KeybindMode } from '../../types'
2
+ import { clampCursorIndex } from '../../ui/list-window'
2
3
  import { getKeyName, type KeyboardHandlerContext, type KeyboardInput } from './shared'
3
4
 
4
5
  export function handleNewSessionMode(
@@ -47,11 +48,11 @@ export function handleNewSessionMode(
47
48
  switch (keyName) {
48
49
  case 'down':
49
50
  ctx.clearPendingKill()
50
- ctx.setCursor(cursor => Math.min(cursor + 1, ctx.items.length - 1))
51
+ ctx.setCursor(cursor => clampCursorIndex(ctx.items.length, cursor + 1))
51
52
  break
52
53
  case 'up':
53
54
  ctx.clearPendingKill()
54
- ctx.setCursor(cursor => Math.max(cursor - 1, 0))
55
+ ctx.setCursor(cursor => clampCursorIndex(ctx.items.length, cursor - 1))
55
56
  break
56
57
  }
57
58
  }
@@ -1,4 +1,5 @@
1
1
  import { AppMode, ViewMode, type KeybindMode } from '../../types'
2
+ import { clampCursorIndex } from '../../ui/list-window'
2
3
  import { requestShutdown } from '../../util/shutdown'
3
4
  import {
4
5
  activatePrefix,
@@ -177,17 +178,22 @@ export function handleNormalMode(
177
178
  if (keyName === 'down' || (!isStandard && keyName === 'j')) {
178
179
  ctx.clearPendingKill()
179
180
  if (ctx.viewMode === ViewMode.Sessions) {
180
- ctx.setCursor(cursor => Math.min(cursor + 1, ctx.regularSessions.length - 1))
181
+ ctx.setCursor(cursor => clampCursorIndex(ctx.regularSessions.length, cursor + 1))
181
182
  return
182
183
  }
183
184
 
184
- ctx.setCursor(cursor => Math.min(cursor + 1, ctx.items.length - 1))
185
+ ctx.setCursor(cursor => clampCursorIndex(ctx.items.length, cursor + 1))
185
186
  return
186
187
  }
187
188
 
188
189
  if (keyName === 'up' || (!isStandard && keyName === 'k')) {
189
190
  ctx.clearPendingKill()
190
- ctx.setCursor(cursor => Math.max(cursor - 1, 0))
191
+ ctx.setCursor(cursor =>
192
+ clampCursorIndex(
193
+ ctx.viewMode === ViewMode.Sessions ? ctx.regularSessions.length : ctx.items.length,
194
+ cursor - 1
195
+ )
196
+ )
191
197
  return
192
198
  }
193
199
 
@@ -1,4 +1,5 @@
1
1
  import { AppMode, type KeybindMode } from '../../types'
2
+ import { clampCursorIndex } from '../../ui/list-window'
2
3
  import {
3
4
  activatePrefix,
4
5
  clearPrefix,
@@ -60,7 +61,7 @@ export function handleOpencodeManageMode(
60
61
  if (keyName === 'down' || (!isStandard && keyName === 'j')) {
61
62
  ctx.clearPendingKill()
62
63
  ctx.setOpencodeCursor(cursor => {
63
- const next = Math.min(cursor + 1, ctx.opencodeSessions.length - 1)
64
+ const next = clampCursorIndex(ctx.opencodeSessions.length, cursor + 1)
64
65
  if (next !== cursor && ctx.opencodeSessions[next]) {
65
66
  void ctx.loadOpencodeStatsForSession(ctx.opencodeSessions[next].title)
66
67
  }
@@ -72,7 +73,7 @@ export function handleOpencodeManageMode(
72
73
  if (keyName === 'up' || (!isStandard && keyName === 'k')) {
73
74
  ctx.clearPendingKill()
74
75
  ctx.setOpencodeCursor(cursor => {
75
- const next = Math.max(cursor - 1, 0)
76
+ const next = clampCursorIndex(ctx.opencodeSessions.length, cursor - 1)
76
77
  if (next !== cursor && ctx.opencodeSessions[next]) {
77
78
  void ctx.loadOpencodeStatsForSession(ctx.opencodeSessions[next].title)
78
79
  }
@@ -1,4 +1,5 @@
1
1
  import { AppMode, ViewMode, type KeybindMode } from '../../types'
2
+ import { clampCursorIndex } from '../../ui/list-window'
2
3
  import { requestShutdown } from '../../util/shutdown'
3
4
  import {
4
5
  activatePrefix,
@@ -98,16 +99,16 @@ export function handleSearchMode(
98
99
  case 'return':
99
100
  ctx.clearPendingKill()
100
101
  if (ctx.items.length > 0) {
101
- void ctx.handleSelect(ctx.items[0])
102
+ void ctx.handleSelect(ctx.items[clampCursorIndex(ctx.items.length, ctx.cursor)])
102
103
  }
103
104
  break
104
105
  case 'down':
105
106
  ctx.clearPendingKill()
106
- ctx.setCursor(cursor => Math.min(cursor + 1, ctx.items.length - 1))
107
+ ctx.setCursor(cursor => clampCursorIndex(ctx.items.length, cursor + 1))
107
108
  break
108
109
  case 'up':
109
110
  ctx.clearPendingKill()
110
- ctx.setCursor(cursor => Math.max(cursor - 1, 0))
111
+ ctx.setCursor(cursor => clampCursorIndex(ctx.items.length, cursor - 1))
111
112
  break
112
113
  }
113
114
  }
@@ -1,4 +1,5 @@
1
1
  import type { Item, SortOrder } from '../types'
2
+ import { isOpencodeSessionItem } from '../opencode/session-name'
2
3
  import { getLiveSessionSortKey } from '../util/path-display'
3
4
 
4
5
  export type SessionSection = 'pinned' | 'live' | 'configured'
@@ -19,10 +20,6 @@ function compareLiveSessions(left: Item, right: Item): number {
19
20
  return left.title.localeCompare(right.title)
20
21
  }
21
22
 
22
- function isOpencodeSession(item: Item): boolean {
23
- return item.isSession && item.title.startsWith('opencode-')
24
- }
25
-
26
23
  function isConfiguredSession(item: Item): boolean {
27
24
  return item.itemKind === 'configured'
28
25
  }
@@ -65,8 +62,8 @@ export function orderSessionItems(
65
62
  pinnedSessions: readonly string[] = []
66
63
  ): Item[] {
67
64
  const itemsWithPinnedState = applyPinnedState(items, pinnedSessions)
68
- const opencodeItems = itemsWithPinnedState.filter(isOpencodeSession).sort(compareByTitle)
69
- const regularItems = itemsWithPinnedState.filter(item => !isOpencodeSession(item))
65
+ const opencodeItems = itemsWithPinnedState.filter(isOpencodeSessionItem).sort(compareByTitle)
66
+ const regularItems = itemsWithPinnedState.filter(item => !isOpencodeSessionItem(item))
70
67
  const { pinnedItems, remainingItems } = splitPinnedItems(regularItems, pinnedSessions)
71
68
 
72
69
  const orderedRegularItems =
@@ -3,6 +3,7 @@ export * from './constants'
3
3
  export * from './parser'
4
4
  export * from './tokens'
5
5
  export * from './session'
6
+ export * from './session-name'
6
7
  export * from './stats'
7
8
 
8
9
  export function formatSessionAge(timestamp: number): string {
@@ -1,6 +1,10 @@
1
1
  import type { OpencodeStats } from './types'
2
2
  import { getGlobalStats } from './sqlite'
3
3
 
4
+ const GLOBAL_STATS_CACHE_TTL_MS = 10_000
5
+
6
+ let globalStatsCache: { stats: OpencodeStats; expiresAt: number } | null = null
7
+
4
8
  function formatTokenCount(value: number): string {
5
9
  if (value >= 1_000_000_000) return `${(value / 1_000_000_000).toFixed(1)}B`
6
10
  if (value >= 1_000_000) return `${(value / 1_000_000).toFixed(1)}M`
@@ -9,6 +13,10 @@ function formatTokenCount(value: number): string {
9
13
  }
10
14
 
11
15
  export async function getGlobalOpencodeStats(): Promise<OpencodeStats> {
16
+ if (globalStatsCache && globalStatsCache.expiresAt > Date.now()) {
17
+ return globalStatsCache.stats
18
+ }
19
+
12
20
  const stats = await getGlobalStats()
13
21
 
14
22
  const totalCost = stats.totalCost
@@ -17,7 +25,7 @@ export async function getGlobalOpencodeStats(): Promise<OpencodeStats> {
17
25
  const daySpan = Math.max(1, Math.ceil((newestUpdatedAt - oldestCreatedAt) / 86_400_000))
18
26
  const costPerDay = totalCost / daySpan
19
27
 
20
- return {
28
+ const formattedStats = {
21
29
  totalSessions: stats.totalSessions,
22
30
  totalMessages: stats.totalMessages,
23
31
  totalCost: `$${totalCost.toFixed(2)}`,
@@ -27,4 +35,11 @@ export async function getGlobalOpencodeStats(): Promise<OpencodeStats> {
27
35
  cacheRead: formatTokenCount(stats.cacheRead),
28
36
  cacheWrite: formatTokenCount(stats.cacheWrite),
29
37
  }
38
+
39
+ globalStatsCache = {
40
+ stats: formattedStats,
41
+ expiresAt: Date.now() + GLOBAL_STATS_CACHE_TTL_MS,
42
+ }
43
+
44
+ return formattedStats
30
45
  }
@@ -0,0 +1,11 @@
1
+ import type { Item } from '../types'
2
+
3
+ const OPENCODE_SESSION_PREFIX = 'opencode-'
4
+
5
+ export function isOpencodeSessionName(sessionName: string): boolean {
6
+ return sessionName.startsWith(OPENCODE_SESSION_PREFIX)
7
+ }
8
+
9
+ export function isOpencodeSessionItem(item: Pick<Item, 'isSession' | 'title'>): boolean {
10
+ return item.isSession && isOpencodeSessionName(item.title)
11
+ }
@@ -5,6 +5,7 @@ import {
5
5
  } from './session'
6
6
  import type { OpencodeStats } from './types'
7
7
  import { getTmuxSessionDirectory } from '../tmux'
8
+ import { getHomeDir } from '../config/paths'
8
9
 
9
10
  export async function getOpencodeSessionStats(
10
11
  tmuxSessionName: string
@@ -16,7 +17,7 @@ export async function getOpencodeSessionStats(
16
17
  return activeSession
17
18
  }
18
19
 
19
- const homeDir = process.env.HOME || '/home/ghost'
20
+ const homeDir = getHomeDir()
20
21
  if (tmuxDirectory === homeDir) {
21
22
  return getAggregatedOpencodeStats(tmuxDirectory)
22
23
  }
@@ -6,6 +6,8 @@ import type { Config, SessionDetails } from '../types'
6
6
  import { stripAnsi } from '../util/ansi'
7
7
  import { getGitRoot, resolveProjectSession } from '../config/session-rules'
8
8
  import { resolveFileSession } from '../files/target'
9
+ import { toHomeRelativePath } from '../util/path-display'
10
+ import { quoteShellArg } from '../util/shell'
9
11
 
10
12
  const MAX_PREVIEW_LINES = 24
11
13
  const MAX_PREVIEW_LINE_LENGTH = 120
@@ -38,10 +40,6 @@ interface PackageSummary {
38
40
  scripts: string[]
39
41
  }
40
42
 
41
- function displayPath(path: string): string {
42
- return path.replace(process.env.HOME || '', '~')
43
- }
44
-
45
43
  export function interpolatePreviewCommand(
46
44
  command: string | undefined,
47
45
  projectPath: string
@@ -50,7 +48,7 @@ export function interpolatePreviewCommand(
50
48
  return undefined
51
49
  }
52
50
 
53
- return command.replaceAll('{}', projectPath)
51
+ return command.replaceAll('{}', quoteShellArg(projectPath))
54
52
  }
55
53
 
56
54
  export function formatPreviewOutput(
@@ -229,12 +227,12 @@ export async function getProjectPreview(
229
227
 
230
228
  if (formattedCommandOutput && formattedCommandOutput.lines.length > 0) {
231
229
  const preview: ProjectPreview = {
232
- path: displayPath(projectPath),
230
+ path: toHomeRelativePath(projectPath),
233
231
  sessionName: resolvedSession.sessionName,
234
232
  source: resolvedSession.source,
235
233
  startupCommand: resolvedSession.startupCommand,
236
234
  previewCommand: resolvedPreviewCommand,
237
- gitRoot: gitRootPath ? displayPath(gitRootPath) : undefined,
235
+ gitRoot: gitRootPath ? toHomeRelativePath(gitRootPath) : undefined,
238
236
  gitBranch,
239
237
  linkedSession: linkedSession ?? undefined,
240
238
  previewKind: 'command',
@@ -257,12 +255,12 @@ export async function getProjectPreview(
257
255
  const formattedDirectoryOutput = formatPreviewOutput(fallbackLines.join('\n'))
258
256
 
259
257
  const preview: ProjectPreview = {
260
- path: displayPath(projectPath),
258
+ path: toHomeRelativePath(projectPath),
261
259
  sessionName: resolvedSession.sessionName,
262
260
  source: resolvedSession.source,
263
261
  startupCommand: resolvedSession.startupCommand,
264
262
  previewCommand: resolvedPreviewCommand,
265
- gitRoot: gitRootPath ? displayPath(gitRootPath) : undefined,
263
+ gitRoot: gitRootPath ? toHomeRelativePath(gitRootPath) : undefined,
266
264
  gitBranch,
267
265
  linkedSession: linkedSession ?? undefined,
268
266
  previewKind: 'directory',
@@ -340,11 +338,11 @@ export async function getFilePreview(
340
338
  ])
341
339
 
342
340
  const preview: ProjectPreview = {
343
- path: displayPath(filePath),
341
+ path: toHomeRelativePath(filePath),
344
342
  sessionName: resolvedSession.sessionName,
345
343
  source: 'file',
346
344
  startupCommand: resolvedSession.startupCommand,
347
- gitRoot: gitRootPath ? displayPath(gitRootPath) : undefined,
345
+ gitRoot: gitRootPath ? toHomeRelativePath(gitRootPath) : undefined,
348
346
  gitBranch,
349
347
  linkedSession: linkedSession ?? undefined,
350
348
  previewKind: 'file',
@@ -269,7 +269,7 @@ export function getModalStyle(theme: ThemeColors, columns: number, preferredWidt
269
269
  }
270
270
  }
271
271
 
272
- const ThemeContext = createContext<ThemeColors>(EXACT_TUI_THEME_COLORS.rosepine!.dark)
272
+ const ThemeContext = createContext<ThemeColors>(resolveTheme(DEFAULT_THEME_ID, {}, 'dark').colors)
273
273
 
274
274
  export function ThemeProvider(props: { theme: ThemeColors; children: ReactNode }) {
275
275
  return <ThemeContext.Provider value={props.theme}>{props.children}</ThemeContext.Provider>
@@ -1,6 +1,8 @@
1
1
  import { spawn } from 'bun'
2
2
  import { sanitizeTmuxSessionName } from './helpers'
3
3
 
4
+ type SpawnOptions = Parameters<typeof spawn>[1]
5
+
4
6
  export interface CreateTmuxSessionOptions {
5
7
  startupCommand?: string
6
8
  }
@@ -18,8 +20,43 @@ async function tmuxSessionExists(sessionName: string): Promise<boolean> {
18
20
  }
19
21
 
20
22
  async function switchClient(sessionName: string): Promise<void> {
21
- const proc = spawn(['tmux', 'switch-client', '-t', sessionName])
23
+ await runTmuxCommand(
24
+ ['tmux', 'switch-client', '-t', sessionName],
25
+ `Failed to switch to tmux session '${sessionName}'`
26
+ )
27
+ }
28
+
29
+ async function runTmuxCommand(
30
+ command: string[],
31
+ errorMessage: string,
32
+ options?: SpawnOptions
33
+ ): Promise<void> {
34
+ const proc = spawn(command, options)
35
+ const stderrPromise =
36
+ proc.stderr instanceof ReadableStream ? new Response(proc.stderr).text() : Promise.resolve('')
22
37
  await proc.exited
38
+ const stderr = (await stderrPromise).trim()
39
+
40
+ if (proc.exitCode !== 0) {
41
+ throw new Error(stderr ? `${errorMessage}: ${stderr}` : errorMessage)
42
+ }
43
+ }
44
+
45
+ async function openTmuxSession(sessionName: string): Promise<void> {
46
+ if (process.env.TMUX) {
47
+ await switchClient(sessionName)
48
+ return
49
+ }
50
+
51
+ await runTmuxCommand(
52
+ ['tmux', 'attach-session', '-t', sessionName],
53
+ `Failed to attach tmux session '${sessionName}'`,
54
+ {
55
+ stdin: 'inherit',
56
+ stdout: 'inherit',
57
+ stderr: 'inherit',
58
+ }
59
+ )
23
60
  }
24
61
 
25
62
  export async function createTmuxSession(
@@ -36,33 +73,29 @@ export async function createTmuxSession(
36
73
  command.push(options.startupCommand)
37
74
  }
38
75
 
39
- const proc = spawn(command, {
76
+ await runTmuxCommand(command, `Failed to create tmux session '${sessionName}'`, {
40
77
  stdin: 'inherit',
41
78
  stdout: 'inherit',
42
79
  stderr: 'inherit',
43
80
  })
44
- await proc.exited
45
81
  return
46
82
  }
47
83
 
48
84
  if (!(await tmuxSessionExists(sessionName))) {
49
- const createProc = spawn(['tmux', 'new-session', '-d', '-s', sessionName, '-c', path])
50
- await createProc.exited
85
+ await runTmuxCommand(
86
+ ['tmux', 'new-session', '-d', '-s', sessionName, '-c', path],
87
+ `Failed to create tmux session '${sessionName}'`
88
+ )
51
89
 
52
90
  if (options.startupCommand) {
53
- const startupProc = spawn([
54
- 'tmux',
55
- 'send-keys',
56
- '-t',
57
- sessionName,
58
- options.startupCommand,
59
- 'Enter',
60
- ])
61
- await startupProc.exited
91
+ await runTmuxCommand(
92
+ ['tmux', 'send-keys', '-t', sessionName, options.startupCommand, 'Enter'],
93
+ `Failed to run startup command for tmux session '${sessionName}'`
94
+ )
62
95
  }
63
96
  }
64
97
 
65
- await switchClient(sessionName)
98
+ await openTmuxSession(sessionName)
66
99
  }
67
100
 
68
101
  export async function createNamedTmuxSession(name: string): Promise<void> {
@@ -70,34 +103,43 @@ export async function createNamedTmuxSession(name: string): Promise<void> {
70
103
  const insideTmux = !!process.env.TMUX
71
104
 
72
105
  if (!insideTmux && !(await isTmuxRunning())) {
73
- const proc = spawn(['tmux', 'new-session', '-s', sessionName], {
74
- stdin: 'inherit',
75
- stdout: 'inherit',
76
- stderr: 'inherit',
77
- })
78
- await proc.exited
106
+ await runTmuxCommand(
107
+ ['tmux', 'new-session', '-s', sessionName],
108
+ `Failed to create tmux session '${sessionName}'`,
109
+ {
110
+ stdin: 'inherit',
111
+ stdout: 'inherit',
112
+ stderr: 'inherit',
113
+ }
114
+ )
79
115
  return
80
116
  }
81
117
 
82
118
  if (!(await tmuxSessionExists(sessionName))) {
83
- const createProc = spawn(['tmux', 'new-session', '-d', '-s', sessionName])
84
- await createProc.exited
119
+ await runTmuxCommand(
120
+ ['tmux', 'new-session', '-d', '-s', sessionName],
121
+ `Failed to create tmux session '${sessionName}'`
122
+ )
85
123
  }
86
124
 
87
- await switchClient(sessionName)
125
+ await openTmuxSession(sessionName)
88
126
  }
89
127
 
90
128
  export async function switchTmuxSession(name: string): Promise<void> {
91
- await switchClient(name)
129
+ await openTmuxSession(name)
92
130
  }
93
131
 
94
132
  export async function killTmuxSession(name: string): Promise<void> {
95
- const proc = spawn(['tmux', 'kill-session', '-t', name])
96
- await proc.exited
133
+ await runTmuxCommand(
134
+ ['tmux', 'kill-session', '-t', name],
135
+ `Failed to kill tmux session '${name}'`
136
+ )
97
137
  }
98
138
 
99
139
  export async function renameTmuxSession(oldName: string, newName: string): Promise<void> {
100
140
  const sanitizedName = sanitizeTmuxSessionName(newName)
101
- const proc = spawn(['tmux', 'rename-session', '-t', oldName, sanitizedName])
102
- await proc.exited
141
+ await runTmuxCommand(
142
+ ['tmux', 'rename-session', '-t', oldName, sanitizedName],
143
+ `Failed to rename tmux session '${oldName}'`
144
+ )
103
145
  }
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'bun'
2
2
  import type { SessionDetails, WindowInfo } from '../types'
3
3
  import { formatPanePreview, formatWindowCommand, readTmuxValue } from './helpers'
4
+ import { toHomeRelativePath } from '../util/path-display'
4
5
 
5
6
  const SESSION_DETAILS_CACHE_TTL_MS = 4000
6
7
  const sessionDetailsCache = new Map<string, { details: SessionDetails; expiresAt: number }>()
@@ -25,71 +26,51 @@ export async function getSessionDetails(sessionName: string): Promise<SessionDet
25
26
  return cached.details
26
27
  }
27
28
 
28
- const statusProc = spawn([
29
- 'tmux',
30
- 'list-sessions',
31
- '-F',
32
- '#{session_name}:#{session_attached}:#{session_windows}',
33
- '-f',
34
- `#{==:#{session_name},${sessionName}}`,
35
- ])
36
- const statusOutput = await new Response(statusProc.stdout).text()
29
+ const statusOutput = await readTmuxValue(
30
+ [
31
+ 'tmux',
32
+ 'list-sessions',
33
+ '-F',
34
+ '#{session_name}:#{session_attached}:#{session_windows}',
35
+ '-f',
36
+ `#{==:#{session_name},${sessionName}}`,
37
+ ],
38
+ `Failed to load tmux session details for '${sessionName}'`
39
+ )
37
40
  const [, attached, windowCount] = statusOutput.trim().split(':')
38
41
 
39
- const windowsProc = spawn([
40
- 'tmux',
41
- 'list-windows',
42
- '-t',
43
- sessionName,
44
- '-F',
45
- '#{window_index}:#{window_name}',
46
- ])
47
- const windowsOutput = await new Response(windowsProc.stdout).text()
42
+ const windowsOutput = await readTmuxValue(
43
+ [
44
+ 'tmux',
45
+ 'list-windows',
46
+ '-t',
47
+ sessionName,
48
+ '-F',
49
+ '#{window_index}\t#{window_name}\t#{pane_current_path}\t#{pane_current_command}\t#{window_active}',
50
+ ],
51
+ `Failed to load tmux windows for '${sessionName}'`
52
+ )
48
53
  const windowLines = windowsOutput.trim().split('\n').filter(Boolean)
49
54
 
50
55
  const windows: WindowInfo[] = []
56
+ let activeWindowIndex = ''
51
57
 
52
58
  for (const line of windowLines) {
53
- const [index, name] = line.split(':')
59
+ const [index = '', name = '', currentPath = '', currentCommand = '', active = '0'] =
60
+ line.split('\t')
54
61
 
55
- const dirProc = spawn([
56
- 'tmux',
57
- 'display-message',
58
- '-t',
59
- `${sessionName}:${index}`,
60
- '-p',
61
- '#{pane_current_path}',
62
- ])
63
- const currentPath = (await new Response(dirProc.stdout).text()).trim()
64
-
65
- const cmdProc = spawn([
66
- 'tmux',
67
- 'display-message',
68
- '-t',
69
- `${sessionName}:${index}`,
70
- '-p',
71
- '#{pane_current_command}',
72
- ])
73
- const currentCommand = (await new Response(cmdProc.stdout).text()).trim()
62
+ if (active === '1') {
63
+ activeWindowIndex = index
64
+ }
74
65
 
75
66
  windows.push({
76
67
  index,
77
68
  name,
78
- currentPath: currentPath.replace(process.env.HOME || '', '~'),
69
+ currentPath: toHomeRelativePath(currentPath),
79
70
  currentCommand: formatWindowCommand(currentCommand),
80
71
  })
81
72
  }
82
73
 
83
- const activeWindowProc = spawn([
84
- 'tmux',
85
- 'display-message',
86
- '-t',
87
- sessionName,
88
- '-p',
89
- '#{window_index}',
90
- ])
91
- const activeWindowIndex = (await new Response(activeWindowProc.stdout).text()).trim()
92
-
93
74
  let panePreviewLines: string[] | undefined
94
75
  if (activeWindowIndex.length > 0) {
95
76
  const paneProc = spawn([
@@ -19,14 +19,17 @@ const PROJECT_MARKERS = [
19
19
  'flake.nix',
20
20
  ]
21
21
 
22
+ export const PRUNED_PROJECT_DIRECTORY_NAMES = [
23
+ '.git',
24
+ '.jj',
25
+ 'node_modules',
26
+ 'target',
27
+ 'build',
28
+ 'dist',
29
+ ]
30
+
22
31
  export function isIgnoredProjectDirectory(baseName: string): boolean {
23
- return (
24
- baseName.startsWith('.') ||
25
- baseName === 'node_modules' ||
26
- baseName === 'target' ||
27
- baseName === 'build' ||
28
- baseName === 'dist'
29
- )
32
+ return baseName.startsWith('.') || PRUNED_PROJECT_DIRECTORY_NAMES.includes(baseName)
30
33
  }
31
34
 
32
35
  export function toProjectItem(projectPath: string): Item {
@@ -5,6 +5,7 @@ import {
5
5
  buildCacheKey,
6
6
  getCachedDiscovery,
7
7
  getExistingProjectRoots,
8
+ PRUNED_PROJECT_DIRECTORY_NAMES,
8
9
  toProjectItem,
9
10
  type DiscoveryCacheEntry,
10
11
  } from './project-discovery'
@@ -26,7 +27,24 @@ async function scanDirectories(projectRoots: string[], maxDepth: number): Promis
26
27
  return []
27
28
  }
28
29
 
29
- const args = [...projectRoots, '-mindepth', '1', '-maxdepth', String(maxDepth), '-type', 'd']
30
+ const pruneExpression = PRUNED_PROJECT_DIRECTORY_NAMES.flatMap((name, index) =>
31
+ index === 0 ? ['-name', name] : ['-o', '-name', name]
32
+ )
33
+ const args = [
34
+ ...projectRoots,
35
+ '-mindepth',
36
+ '1',
37
+ '-maxdepth',
38
+ String(maxDepth),
39
+ '(',
40
+ ...pruneExpression,
41
+ ')',
42
+ '-prune',
43
+ '-o',
44
+ '-type',
45
+ 'd',
46
+ '-print',
47
+ ]
30
48
  const proc = spawn(['find', ...args], {
31
49
  stderr: 'pipe',
32
50
  })
@@ -48,7 +48,7 @@ export function isWithinProjectRoots(projectPath: string, projectRoots: string[]
48
48
 
49
49
  function rankItemsByZoxide(items: Item[], entries: ZoxideEntry[], config: Config): Item[] {
50
50
  if (config.zoxideMode === 'off' || entries.length === 0) {
51
- return items.sort((a, b) => a.title.localeCompare(b.title))
51
+ return [...items].sort((a, b) => a.title.localeCompare(b.title))
52
52
  }
53
53
 
54
54
  const zoxideScores = new Map(
@@ -1,3 +1,5 @@
1
+ import type { OpencodeStats } from '../opencode/types'
2
+
1
3
  export enum AppMode {
2
4
  Normal,
3
5
  Search,
@@ -104,25 +106,7 @@ export interface ProjectWildcard {
104
106
  previewCommand?: string
105
107
  }
106
108
 
107
- export interface OpencodeSessionStats {
108
- sessionID?: string
109
- title?: string
110
- projectID?: string
111
- directory?: string
112
- messageCount?: number
113
- filesModified?: number
114
- additions?: number
115
- deletions?: number
116
- createdAt?: number
117
- updatedAt?: number
118
- // Aggregated stats (for home directory sessions)
119
- sessionCount?: number
120
- mostRecentTitle?: string
121
- // Current session live stats (last message)
122
- lastMessageTokens?: number
123
- contextLimit?: number
124
- sessionTotalCost?: number
125
- }
109
+ export type OpencodeSessionStats = OpencodeStats
126
110
 
127
111
  export type OpencodeStatsState =
128
112
  | { status: 'loading' }
@@ -1,4 +1,5 @@
1
1
  import type { SessionSection } from '../items/order'
2
+ import { isOpencodeSessionItem } from '../opencode/session-name'
2
3
  import type { IconConfig, Item, ThemeColors } from '../types'
3
4
 
4
5
  export interface ItemIconPresentation {
@@ -45,8 +46,7 @@ export function getItemIconPresentation(
45
46
  if (item.isSession) {
46
47
  return {
47
48
  glyph:
48
- item.icon ??
49
- (item.title.startsWith('opencode-') ? resolvedIcons.opencode : resolvedIcons.tmux),
49
+ item.icon ?? (isOpencodeSessionItem(item) ? resolvedIcons.opencode : resolvedIcons.tmux),
50
50
  color: item.isAttached ? theme.active : theme.inactive,
51
51
  }
52
52
  }
@@ -3,6 +3,14 @@ export interface VisibleWindow<T> {
3
3
  startIndex: number
4
4
  }
5
5
 
6
+ export function clampCursorIndex(length: number, cursor: number): number {
7
+ if (length <= 0) {
8
+ return 0
9
+ }
10
+
11
+ return Math.min(Math.max(cursor, 0), length - 1)
12
+ }
13
+
6
14
  export function getVisibleWindow<T>(
7
15
  items: T[],
8
16
  cursor: number,
@@ -17,7 +25,8 @@ export function getVisibleWindow<T>(
17
25
 
18
26
  const visibleCount = Math.max(1, Math.min(maxItems, items.length))
19
27
  const maxStartIndex = Math.max(0, items.length - visibleCount)
20
- const startIndex = Math.min(Math.max(0, cursor - Math.floor(visibleCount / 2)), maxStartIndex)
28
+ const safeCursor = clampCursorIndex(items.length, cursor)
29
+ const startIndex = Math.min(Math.max(0, safeCursor - Math.floor(visibleCount / 2)), maxStartIndex)
21
30
 
22
31
  return {
23
32
  items: items.slice(startIndex, startIndex + visibleCount),
@@ -3,29 +3,65 @@ import { join } from 'path'
3
3
  import { mkdir, stat } from 'fs/promises'
4
4
  import type { Config } from '../types'
5
5
 
6
- export function isGitHubURL(input: string): boolean {
7
- const trimmed = input.trim()
8
- return trimmed.startsWith('https://github.com/') || trimmed.startsWith('git@github.com:')
6
+ interface GitHubRepoRef {
7
+ owner: string
8
+ repo: string
9
9
  }
10
10
 
11
- export function extractRepoName(url: string): string {
12
- const trimmed = url.trim()
11
+ function isSafeGitHubPathSegment(value: string): boolean {
12
+ return value.length > 0 && value !== '.' && value !== '..' && /^[A-Za-z0-9._-]+$/.test(value)
13
+ }
14
+
15
+ function stripGitSuffix(value: string): string {
16
+ return value.endsWith('.git') ? value.slice(0, -4) : value
17
+ }
18
+
19
+ function parseGitHubRepo(input: string): GitHubRepoRef | null {
20
+ const trimmed = input.trim()
21
+
22
+ if (trimmed.startsWith('git@github.com:')) {
23
+ const path = stripGitSuffix(trimmed.slice('git@github.com:'.length))
24
+ const parts = path.split('/').filter(Boolean)
25
+ if (parts.length !== 2 || !parts.every(isSafeGitHubPathSegment)) {
26
+ return null
27
+ }
28
+
29
+ return { owner: parts[0], repo: parts[1] }
30
+ }
31
+
32
+ try {
33
+ const url = new URL(trimmed)
34
+ if (url.protocol !== 'https:' || url.hostname !== 'github.com') {
35
+ return null
36
+ }
13
37
 
14
- if (trimmed.startsWith('https://github.com/')) {
15
- const path = trimmed.replace('https://github.com/', '').replace('.git', '')
16
- const parts = path.split('/')
17
- if (parts.length >= 2) {
18
- return parts[1]
38
+ const parts = url.pathname.split('/').filter(Boolean)
39
+ if (parts.length !== 2) {
40
+ return null
19
41
  }
20
- } else if (trimmed.startsWith('git@github.com:')) {
21
- const path = trimmed.replace('git@github.com:', '').replace('.git', '')
22
- const parts = path.split('/')
23
- if (parts.length >= 2) {
24
- return parts[1]
42
+
43
+ const owner = parts[0]
44
+ const repo = stripGitSuffix(parts[1])
45
+ if (!isSafeGitHubPathSegment(owner) || !isSafeGitHubPathSegment(repo)) {
46
+ return null
25
47
  }
48
+
49
+ return { owner, repo }
50
+ } catch {
51
+ return null
26
52
  }
53
+ }
54
+
55
+ function isMissingPathError(error: unknown): boolean {
56
+ return typeof error === 'object' && error !== null && 'code' in error && error.code === 'ENOENT'
57
+ }
58
+
59
+ export function isGitHubURL(input: string): boolean {
60
+ return parseGitHubRepo(input) !== null
61
+ }
27
62
 
28
- return ''
63
+ export function extractRepoName(url: string): string {
64
+ return parseGitHubRepo(url)?.repo ?? ''
29
65
  }
30
66
 
31
67
  export async function cloneGitHubRepo(url: string, config: Config): Promise<string> {
@@ -40,15 +76,24 @@ export async function cloneGitHubRepo(url: string, config: Config): Promise<stri
40
76
  const targetDir = join(reposDir, repoName)
41
77
 
42
78
  try {
43
- await stat(targetDir)
79
+ const targetStat = await stat(targetDir)
80
+ if (!targetStat.isDirectory()) {
81
+ throw new Error(`Clone target exists but is not a directory: ${targetDir}`)
82
+ }
83
+
44
84
  return targetDir
45
- } catch {}
85
+ } catch (error) {
86
+ if (!isMissingPathError(error)) {
87
+ throw error
88
+ }
89
+ }
46
90
 
47
- const proc = spawn(['git', 'clone', url, targetDir])
91
+ const proc = spawn(['git', 'clone', url, targetDir], { stderr: 'pipe' })
92
+ const stderr = proc.stderr instanceof ReadableStream ? await new Response(proc.stderr).text() : ''
48
93
  await proc.exited
49
94
 
50
95
  if (proc.exitCode !== 0) {
51
- throw new Error('Failed to clone repository')
96
+ throw new Error(stderr.trim() || 'Failed to clone repository')
52
97
  }
53
98
 
54
99
  return targetDir
@@ -1,6 +1,6 @@
1
1
  import { basename, dirname } from 'path'
2
2
 
3
- function toHomeRelativePath(path: string): string {
3
+ export function toHomeRelativePath(path: string): string {
4
4
  const homeDir = process.env.HOME || ''
5
5
 
6
6
  if (!path) {
@@ -0,0 +1,3 @@
1
+ export function quoteShellArg(value: string): string {
2
+ return `'${value.replaceAll("'", "'\\''")}'`
3
+ }