mux-sesh 1.8.0 → 1.9.1

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/README.md CHANGED
@@ -52,6 +52,8 @@ tmux source-file ~/.tmux.conf
52
52
  - Sessions view shows live tmux sessions.
53
53
  - Projects view shows scanned or configured directories.
54
54
  - Selecting a project attaches to an existing session when possible, or creates one.
55
+ - The new-session flow searches files and directories under `project_paths` as you type, powered by [fff](https://github.com/dmtrKovalenko/fff).
56
+ - Selecting a file creates a session in the file's directory and opens it in your editor.
55
57
  - The new-session flow can also clone a GitHub repository into your configured repos directory.
56
58
 
57
59
  ## Minimal Configuration
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.8.0",
4
+ "version": "1.9.1",
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",
@@ -48,13 +48,17 @@
48
48
  "engines": {
49
49
  "bun": ">=1.0.0"
50
50
  },
51
+ "overrides": {
52
+ "@types/node": "^24"
53
+ },
51
54
  "dependencies": {
55
+ "@ff-labs/fff-bun": "0.9.4",
52
56
  "@opentui/core": "0.1.60",
53
57
  "@opentui/react": "0.1.60",
54
58
  "react": "^19.2.2"
55
59
  },
56
60
  "devDependencies": {
57
- "@types/bun": "1.3.5",
61
+ "@types/bun": "1.3.14",
58
62
  "@types/react": "^19.2.7",
59
63
  "prettier": "3.6.2",
60
64
  "typescript": "^5.9.3"
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
  }
@@ -2,14 +2,20 @@ import { useEffect, useRef, type Dispatch, type MutableRefObject, type SetStateA
2
2
  import { checkAndUpdate, updateEvents } from '../update'
3
3
  import { showTemporaryToast } from './notifications'
4
4
  import { clearMatchIndices, filterAndSortItems } from '../search'
5
+ import { combineFileSearchResults, searchFilesAndDirectories, warmFileSearch } from '../search/fff'
6
+ import { annotateProjectItemsWithSessionLinks } from '../projects/session-links'
5
7
  import {
6
8
  getProjectSelectionIndex,
7
9
  getSessionSelectionIndex,
8
10
  loadSessionCandidateItems,
9
11
  } from './data'
10
12
  import { AppMode, ViewMode, type Config, type Item } from '../types'
13
+ import { clampCursorIndex } from '../ui/list-window'
14
+ import { isGitHubURL } from '../util/github'
11
15
  import { measure } from '../util/perf'
12
16
 
17
+ const FILE_SEARCH_DEBOUNCE_MS = 120
18
+
13
19
  export function useAutoUpdateScheduler(
14
20
  config: Config | null,
15
21
  hasScheduledAutoUpdateRef: MutableRefObject<boolean>
@@ -162,7 +168,7 @@ export function useBoundedCursor(length: number, setCursor: Dispatch<SetStateAct
162
168
  return
163
169
  }
164
170
 
165
- setCursor(current => Math.min(current, length - 1))
171
+ setCursor(current => clampCursorIndex(length, current))
166
172
  }, [length, setCursor])
167
173
  }
168
174
 
@@ -269,6 +275,63 @@ export function useSearchFiltering(
269
275
  }, [allItems, appMode, searchQuery, setCursor, setItems])
270
276
  }
271
277
 
278
+ export function useNewSessionFileSearch(
279
+ appMode: AppMode,
280
+ config: Config | null,
281
+ searchQuery: string,
282
+ sessionItems: Item[],
283
+ setItems: Dispatch<SetStateAction<Item[]>>,
284
+ setCursor: Dispatch<SetStateAction<number>>
285
+ ) {
286
+ const sessionItemsRef = useRef(sessionItems)
287
+ sessionItemsRef.current = sessionItems
288
+
289
+ useEffect(() => {
290
+ if (appMode !== AppMode.NewSession || !config) {
291
+ return
292
+ }
293
+
294
+ const nextConfig = config
295
+ const query = searchQuery.trim()
296
+
297
+ if (!query || isGitHubURL(query)) {
298
+ void warmFileSearch(nextConfig)
299
+ return
300
+ }
301
+
302
+ let cancelled = false
303
+
304
+ async function runFileSearch() {
305
+ const fileSearchItems = await searchFilesAndDirectories(query, nextConfig)
306
+ if (cancelled || fileSearchItems.length === 0) {
307
+ return
308
+ }
309
+
310
+ const liveSessions = sessionItemsRef.current.filter(item => item.isSession)
311
+ const annotated = await annotateProjectItemsWithSessionLinks(
312
+ fileSearchItems,
313
+ liveSessions,
314
+ nextConfig
315
+ )
316
+ if (cancelled) {
317
+ return
318
+ }
319
+
320
+ setItems(current => combineFileSearchResults(annotated, current, query))
321
+ setCursor(0)
322
+ }
323
+
324
+ const timeout = setTimeout(() => {
325
+ void runFileSearch()
326
+ }, FILE_SEARCH_DEBOUNCE_MS)
327
+
328
+ return () => {
329
+ cancelled = true
330
+ clearTimeout(timeout)
331
+ }
332
+ }, [appMode, config, searchQuery, setCursor, setItems])
333
+ }
334
+
272
335
  export function useOpencodeStatsPolling(
273
336
  selectedOpencodeSessionName: string | undefined,
274
337
  loadOpencodeStatsForSession: (sessionName: string) => Promise<unknown>
@@ -388,5 +451,13 @@ export function useAppBehaviors(options: UseAppBehaviorsOptions) {
388
451
  options.setItems,
389
452
  options.setCursor
390
453
  )
454
+ useNewSessionFileSearch(
455
+ options.appMode,
456
+ options.config,
457
+ options.searchQuery,
458
+ options.sessionItems,
459
+ options.setItems,
460
+ options.setCursor
461
+ )
391
462
  useOpencodeStatsPolling(options.selectedOpencodeSessionName, options.loadOpencodeStatsForSession)
392
463
  }
@@ -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> {
@@ -0,0 +1,96 @@
1
+ import { basename, dirname, isAbsolute, join } from 'path'
2
+ import { stat } from 'fs/promises'
3
+ import type { Config, Item } from '../types'
4
+ import { quoteShellArg } from '../util/shell'
5
+
6
+ export interface ResolvedFileSession {
7
+ sessionName: string
8
+ cwd: string
9
+ startupCommand: string
10
+ }
11
+
12
+ export type TypedPathTarget = { kind: 'file' | 'directory'; path: string }
13
+
14
+ function sanitizeSessionName(value: string): string {
15
+ return value.replace(/[.\s/]+/g, '_')
16
+ }
17
+
18
+ export function isFileItem(item: Pick<Item, 'itemKind'>): boolean {
19
+ return item.itemKind === 'file'
20
+ }
21
+
22
+ export function expandUserPath(value: string, homeDir = process.env.HOME || ''): string {
23
+ if (value === '~') {
24
+ return homeDir || value
25
+ }
26
+
27
+ if (value.startsWith('~/') && homeDir) {
28
+ return join(homeDir, value.slice(2))
29
+ }
30
+
31
+ return value
32
+ }
33
+
34
+ export function buildFileSessionName(filePath: string): string {
35
+ const fileBase = basename(filePath)
36
+ const parentBase = basename(dirname(filePath))
37
+ const combined =
38
+ parentBase && parentBase !== '.' && parentBase !== '/' ? `${parentBase}_${fileBase}` : fileBase
39
+
40
+ return sanitizeSessionName(combined)
41
+ }
42
+
43
+ export function interpolateStartupCommand(command: string, filePath: string): string {
44
+ return command
45
+ .replaceAll('{file}', quoteShellArg(filePath))
46
+ .replaceAll('{dir}', quoteShellArg(dirname(filePath)))
47
+ .replaceAll('{}', quoteShellArg(filePath))
48
+ }
49
+
50
+ export function buildFileStartupCommand(filePath: string, config: Config): string {
51
+ const configured = config.defaultSession?.startupCommand
52
+ if (configured && /\{file\}|\{dir\}|\{\}/.test(configured)) {
53
+ return interpolateStartupCommand(configured, filePath)
54
+ }
55
+
56
+ return `${config.editor} ${quoteShellArg(filePath)}`
57
+ }
58
+
59
+ export function resolveFileSession(filePath: string, config: Config): ResolvedFileSession {
60
+ return {
61
+ sessionName: buildFileSessionName(filePath),
62
+ cwd: dirname(filePath),
63
+ startupCommand: buildFileStartupCommand(filePath, config),
64
+ }
65
+ }
66
+
67
+ export function looksLikePathInput(value: string): boolean {
68
+ return value.startsWith('/') || value === '~' || value.startsWith('~/') || value.startsWith('./')
69
+ }
70
+
71
+ export async function resolveTypedPathTarget(
72
+ searchTerm: string,
73
+ homeDir = process.env.HOME || ''
74
+ ): Promise<TypedPathTarget | null> {
75
+ if (!looksLikePathInput(searchTerm)) {
76
+ return null
77
+ }
78
+
79
+ const expanded = expandUserPath(searchTerm, homeDir)
80
+ const absolute = isAbsolute(expanded) ? expanded : join(process.cwd(), expanded)
81
+
82
+ try {
83
+ const info = await stat(absolute)
84
+ if (info.isFile()) {
85
+ return { kind: 'file', path: absolute }
86
+ }
87
+
88
+ if (info.isDirectory()) {
89
+ return { kind: 'directory', path: absolute }
90
+ }
91
+
92
+ return null
93
+ } catch {
94
+ return null
95
+ }
96
+ }
@@ -1,11 +1,12 @@
1
+ import { dirname } from 'path'
1
2
  import type { Config, Item } from '../types'
2
3
  import { getGitRoot, resolveProjectSession } from '../config/session-rules'
4
+ import { isFileItem, resolveFileSession } from '../files/target'
3
5
  import { createTmuxSession, getTmuxSessionDirectory } from '../tmux'
4
6
  import { requestShutdown } from '../util/shutdown'
7
+ import { quoteShellArg } from '../util/shell'
5
8
 
6
- export function quoteShellArg(value: string): string {
7
- return `'${value.replaceAll("'", "'\\''")}'`
8
- }
9
+ export { quoteShellArg } from '../util/shell'
9
10
 
10
11
  export function buildEditorCommand(editor: string, path: string): string {
11
12
  return `${editor} ${quoteShellArg(path)}`
@@ -44,7 +45,16 @@ export async function openProjectSession(projectPath: string, config: Config): P
44
45
  await requestShutdown(0)
45
46
  }
46
47
 
48
+ export async function openFileSession(filePath: string, config: Config): Promise<void> {
49
+ const resolvedSession = resolveFileSession(filePath, config)
50
+ await createTmuxSession(resolvedSession.sessionName, resolvedSession.cwd, {
51
+ startupCommand: resolvedSession.startupCommand,
52
+ })
53
+ await requestShutdown(0)
54
+ }
55
+
47
56
  export async function getRootSessionPath(item: Item): Promise<string> {
48
57
  const itemPath = item.isSession ? await getTmuxSessionDirectory(item.title) : item.path
49
- return (await getGitRoot(itemPath)) ?? itemPath
58
+ const searchRoot = !item.isSession && isFileItem(item) ? dirname(itemPath) : itemPath
59
+ return (await getGitRoot(searchRoot)) ?? searchRoot
50
60
  }
@@ -8,12 +8,14 @@ import {
8
8
  getCurrentTmuxSessionName,
9
9
  } from '../tmux'
10
10
  import { getLastSessionTarget } from '../tmux/workflows'
11
+ import { isFileItem, resolveTypedPathTarget } from '../files/target'
11
12
  import { isGitHubURL, cloneGitHubRepo } from '../util/github'
12
13
  import { requestShutdown } from '../util/shutdown'
13
14
  import {
14
15
  buildEditorCommand,
15
16
  getNextSessionName,
16
17
  getRootSessionPath,
18
+ openFileSession,
17
19
  openProjectSession,
18
20
  requireConfig,
19
21
  requireConfiguredItem,
@@ -26,6 +28,11 @@ export async function handleSelect(item: Item, config: Config | null) {
26
28
  return
27
29
  }
28
30
 
31
+ if (isFileItem(item)) {
32
+ await openFileSession(item.path, requireConfig(config))
33
+ return
34
+ }
35
+
29
36
  await openProjectSession(item.path, requireConfig(config))
30
37
  }
31
38
 
@@ -85,13 +92,33 @@ export async function handleNewSessionSubmit(
85
92
  } catch (error) {
86
93
  throw new Error(`Error cloning repository: ${error}`)
87
94
  }
88
- } else if (items.length > 0 && cursor < items.length) {
95
+ return
96
+ }
97
+
98
+ const typedTarget = await resolveTypedPathTarget(searchTerm)
99
+ if (typedTarget) {
100
+ if (typedTarget.kind === 'file') {
101
+ await openFileSession(typedTarget.path, requireConfig(config))
102
+ return
103
+ }
104
+
105
+ await openProjectSession(typedTarget.path, requireConfig(config))
106
+ return
107
+ }
108
+
109
+ if (items.length > 0 && cursor < items.length) {
89
110
  const selectedItem = items[cursor]
111
+ if (isFileItem(selectedItem)) {
112
+ await openFileSession(selectedItem.path, requireConfig(config))
113
+ return
114
+ }
115
+
90
116
  await openProjectSession(selectedItem.path, requireConfig(config))
91
- } else {
92
- await createNamedTmuxSession(searchTerm)
93
- await requestShutdown(0)
117
+ return
94
118
  }
119
+
120
+ await createNamedTmuxSession(searchTerm)
121
+ await requestShutdown(0)
95
122
  }
96
123
 
97
124
  export async function handleLastSession(items: Item[]) {
@@ -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
  }