mux-sesh 1.6.3 → 1.7.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.
Files changed (82) hide show
  1. package/README.md +90 -59
  2. package/package.json +7 -5
  3. package/src/app/commands.ts +120 -0
  4. package/src/app/controller.ts +397 -0
  5. package/src/app/controls.ts +121 -0
  6. package/src/app/core-state.ts +71 -0
  7. package/src/app/data.ts +90 -0
  8. package/src/app/derived.ts +77 -0
  9. package/src/app/effects.ts +392 -0
  10. package/src/app/handlers.ts +325 -0
  11. package/src/app/keyboard.ts +161 -0
  12. package/src/app/modal-keyboard.ts +118 -0
  13. package/src/app/modal-state.ts +50 -0
  14. package/src/app/modals-layer.tsx +159 -0
  15. package/src/app/modals.ts +108 -0
  16. package/src/app/notifications.ts +21 -0
  17. package/src/app/opencode.ts +49 -0
  18. package/src/app/operations.ts +31 -0
  19. package/src/app/runtime.ts +76 -0
  20. package/src/app/screen.tsx +217 -0
  21. package/src/app/state.ts +166 -0
  22. package/src/app/textarea.ts +16 -0
  23. package/src/app/view.ts +89 -0
  24. package/src/app.tsx +7 -1101
  25. package/src/config/index.ts +36 -42
  26. package/src/config/listed-sessions.ts +2 -5
  27. package/src/config/paths.ts +13 -0
  28. package/src/config/session-rules.ts +10 -11
  29. package/src/config/store.ts +26 -0
  30. package/src/handlers/action-helpers.ts +50 -0
  31. package/src/handlers/actions.ts +34 -65
  32. package/src/handlers/keyboard/index.ts +5 -0
  33. package/src/handlers/keyboard/new-session.ts +57 -0
  34. package/src/handlers/keyboard/normal.ts +201 -0
  35. package/src/handlers/keyboard/opencode.ts +104 -0
  36. package/src/handlers/keyboard/search.ts +113 -0
  37. package/src/handlers/keyboard/shared.ts +116 -0
  38. package/src/items/order.ts +21 -2
  39. package/src/opencode/sqlite.ts +21 -6
  40. package/src/preview/project.ts +41 -15
  41. package/src/search/index.ts +4 -1
  42. package/src/settings.ts +294 -297
  43. package/src/styles/opencode-themes-a.ts +1442 -1
  44. package/src/styles/opencode-themes-b.ts +1212 -1
  45. package/src/styles/opencode-tui-colors.ts +1784 -1
  46. package/src/styles/theme.tsx +2 -1
  47. package/src/tmux/actions.ts +103 -0
  48. package/src/tmux/details.ts +123 -0
  49. package/src/tmux/helpers.ts +35 -0
  50. package/src/tmux/index.ts +10 -286
  51. package/src/tmux/list.ts +31 -0
  52. package/src/tmux/project-discovery.ts +113 -0
  53. package/src/tmux/project-loader.ts +74 -0
  54. package/src/tmux/project-zoxide.ts +128 -0
  55. package/src/tmux/projects.ts +23 -261
  56. package/src/types/index.ts +0 -1
  57. package/src/ui/CommandsModal.tsx +87 -22
  58. package/src/ui/HighlightedText.tsx +1 -5
  59. package/src/ui/ItemList.tsx +26 -11
  60. package/src/ui/Modal.tsx +8 -1
  61. package/src/ui/OpencodeSessionGroup.tsx +20 -9
  62. package/src/ui/OpencodeStatsPanel.tsx +48 -15
  63. package/src/ui/RenameModal.tsx +17 -17
  64. package/src/ui/SearchInput.tsx +1 -20
  65. package/src/ui/SessionDetailsPanel.tsx +43 -15
  66. package/src/ui/SessionList.tsx +25 -4
  67. package/src/ui/SettingEditorModal.tsx +15 -9
  68. package/src/ui/SettingOptionsModal.tsx +30 -12
  69. package/src/ui/SettingsModal.tsx +20 -14
  70. package/src/ui/VersionBadge.tsx +3 -1
  71. package/src/ui/item-icon.ts +5 -1
  72. package/src/ui/list-window.ts +5 -1
  73. package/src/ui/text-columns.ts +17 -0
  74. package/src/ui/use-textarea-focus.ts +26 -0
  75. package/src/update/index.ts +10 -2
  76. package/src/update/installation.ts +6 -2
  77. package/src/util/ansi.ts +3 -0
  78. package/src/util/glob.ts +5 -1
  79. package/src/util/path-display.ts +98 -0
  80. package/src/components/KeybindHelp.tsx +0 -289
  81. package/src/handlers/keyboard.ts +0 -654
  82. package/src/ui/SessionStats.tsx +0 -32
package/src/app.tsx CHANGED
@@ -1,1109 +1,15 @@
1
- import type { TextareaRenderable } from '@opentui/core'
2
- import { useKeyboard } from '@opentui/react'
3
- import { useState, useEffect, useRef } from 'react'
4
- import { AppMode, ViewMode, type Item, type Config, type OpencodeStatsState } from './types'
5
- import { getConfigPath, loadConfig, saveConfig } from './config'
6
- import { getListedSessionItems, mergeSessionItems } from './config/listed-sessions'
7
- import { orderProjectItems, orderSessionItems } from './items/order'
8
- import { annotateProjectItemsWithSessionLinks } from './projects/session-links'
9
- import { listTmuxSessions } from './tmux'
10
- import { filterHiddenSessions } from './tmux/workflows'
11
- import { getProjectItems, getSessionCandidateItems } from './tmux/projects'
12
- import { filterAndSortItems, clearMatchIndices } from './search'
13
- import { isGitHubURL } from './util/github'
14
- import { getOpencodeSessionStats } from './opencode'
15
- import { ThemeProvider, getPanelStyle, resolveTheme } from './styles/theme'
16
- import { useTerminalSize, shouldShowDetailPanel } from './util/terminal'
17
- import { mark, measure } from './util/perf'
18
- import Toast from './ui/Toast'
19
- import { checkAndUpdate, updateEvents } from './update'
20
- import { CURRENT_VERSION } from './update/version'
21
- import OpencodeStatsPanel from './ui/OpencodeStatsPanel'
22
- import SessionDetailsPanel from './ui/SessionDetailsPanel'
23
- import SessionList from './ui/SessionList'
24
- import OpencodeSessionGroup from './ui/OpencodeSessionGroup'
25
- import SearchInput from './ui/SearchInput'
26
- import ItemList from './ui/ItemList'
27
- import VersionBadge from './ui/VersionBadge'
28
- import RenameModal from './ui/RenameModal'
29
- import CommandsModal, { filterCommandEntries, getCommandEntries, type CommandId } from './ui/CommandsModal'
30
- import SettingsModal from './ui/SettingsModal'
31
- import SettingOptionsModal from './ui/SettingOptionsModal'
32
- import SettingEditorModal from './ui/SettingEditorModal'
33
- import {
34
- applyEditorSetting,
35
- applyOptionSetting,
36
- filterSettingsEntries,
37
- filterSettingsOptions,
38
- getSettingEditorTitle,
39
- getSettingEditorValue,
40
- getSettingsEntries,
41
- getSettingOptions,
42
- isOptionSetting,
43
- type SettingsFieldId,
44
- } from './settings'
45
- import {
46
- type KeyboardHandlerContext,
47
- handleNormalMode,
48
- handleOpencodeManageMode,
49
- handleSearchMode,
50
- handleNewSessionMode,
51
- } from './handlers/keyboard'
52
- import {
53
- handleSelect as actionHandleSelect,
54
- handleKillSession as actionKillSession,
55
- handleLastSession as actionHandleLastSession,
56
- handleRenameSubmit as actionRenameSubmit,
57
- handleNewSessionSubmit as actionNewSessionSubmit,
58
- handleRootSession as actionHandleRootSession,
59
- handleEditTarget as actionHandleEditTarget,
60
- } from './handlers/actions'
61
-
62
- type ModalState =
63
- | { type: 'rename'; target: string }
64
- | { type: 'commands' }
65
- | { type: 'settings' }
66
- | { type: 'setting-options'; field: SettingsFieldId }
67
- | { type: 'setting-editor'; field: SettingsFieldId }
68
- | null
1
+ import { useAppController } from './app/controller'
2
+ import { AppModalsLayer } from './app/modals-layer'
3
+ import { AppScreen } from './app/screen'
4
+ import { ThemeProvider } from './styles/theme'
69
5
 
70
6
  export function App() {
71
- const [appMode, setAppMode] = useState(AppMode.Normal)
72
- const [viewMode, setViewMode] = useState(ViewMode.Sessions)
73
- const [items, setItems] = useState<Item[]>([])
74
- const [allItems, setAllItems] = useState<Item[]>([])
75
- const [projectSourceItems, setProjectSourceItems] = useState<Item[]>([])
76
- const [projectItems, setProjectItems] = useState<Item[]>([])
77
- const [sessionCandidateItems, setSessionCandidateItems] = useState<Item[]>([])
78
- const [sessionItems, setSessionItems] = useState<Item[]>([])
79
- const [cursor, setCursor] = useState(0)
80
- const [opencodeCursor, setOpencodeCursor] = useState(0)
81
- const [searchQuery, setSearchQuery] = useState('')
82
- const [message, setMessage] = useState('')
83
- const [renameTarget, setRenameTarget] = useState('')
84
- const [config, setConfig] = useState<Config | null>(null)
85
- const [modalState, setModalState] = useState<ModalState>(null)
86
- const [modalInputValue, setModalInputValue] = useState('')
87
- const [commandsCursor, setCommandsCursor] = useState(0)
88
- const [commandsSearchQuery, setCommandsSearchQuery] = useState('')
89
- const [settingsCursor, setSettingsCursor] = useState(0)
90
- const [settingsSearchQuery, setSettingsSearchQuery] = useState('')
91
- const [settingOptionsCursor, setSettingOptionsCursor] = useState(0)
92
- const [settingOptionsSearchQuery, setSettingOptionsSearchQuery] = useState('')
93
- const [settingEditorValue, setSettingEditorValue] = useState('')
94
- const [settingEditorError, setSettingEditorError] = useState('')
95
- const [pendingKillSessionName, setPendingKillSessionName] = useState<string | null>(null)
96
- const [prefixActive, setPrefixActive] = useState(false)
97
- const prefixTimeoutRef = useRef<NodeJS.Timeout | null>(null)
98
- const textareaRef = useRef<TextareaRenderable | null>(null)
99
- const modalTextareaRef = useRef<TextareaRenderable | null>(null)
100
- const commandsSearchTextareaRef = useRef<TextareaRenderable | null>(null)
101
- const settingsSearchTextareaRef = useRef<TextareaRenderable | null>(null)
102
- const settingOptionsSearchTextareaRef = useRef<TextareaRenderable | null>(null)
103
- const settingEditorTextareaRef = useRef<TextareaRenderable | null>(null)
104
- const lastSessionSelectionRef = useRef<string | null>(null)
105
- const lastProjectSelectionRef = useRef<string | null>(null)
106
- const { columns, rows } = useTerminalSize()
107
- const [toastMessage, setToastMessage] = useState('')
108
- const [toastVisible, setToastVisible] = useState(false)
109
- const [updatedVersion, setUpdatedVersion] = useState<string | null>(null)
110
- const configPath = getConfigPath()
111
- const resolvedTheme = resolveTheme(config?.theme, config?.themes, config?.colorScheme)
112
- const theme = resolvedTheme.colors
113
- const settingsEntries = config ? getSettingsEntries(config) : []
114
- const filteredSettingsEntries = filterSettingsEntries(settingsEntries, settingsSearchQuery)
115
- const currentOptionField = modalState?.type === 'setting-options' ? modalState.field : undefined
116
- const settingOptions = config && currentOptionField ? getSettingOptions(config, currentOptionField) : []
117
- const filteredSettingOptions = filterSettingsOptions(settingOptions, settingOptionsSearchQuery)
118
- const hasScheduledAutoUpdateRef = useRef(false)
119
-
120
- function getSessionSelectionIndex(nextItems: Item[]): number {
121
- const regularItems = nextItems.filter(item => !(item.isSession && item.title.startsWith('opencode-')))
122
- if (regularItems.length === 0) {
123
- return 0
124
- }
125
-
126
- const selection = lastSessionSelectionRef.current
127
- if (!selection) {
128
- return 0
129
- }
130
-
131
- const index = regularItems.findIndex(item => item.title === selection)
132
- return index >= 0 ? index : 0
133
- }
134
-
135
- function getProjectSelectionIndex(nextItems: Item[]): number {
136
- if (nextItems.length === 0) {
137
- return 0
138
- }
139
-
140
- const selection = lastProjectSelectionRef.current
141
- if (!selection) {
142
- return 0
143
- }
144
-
145
- const index = nextItems.findIndex(item => item.path === selection)
146
- return index >= 0 ? index : 0
147
- }
148
-
149
- function updateOpencodeState(sessionName: string, nextState: OpencodeStatsState) {
150
- const applyState = (existingItems: Item[]) =>
151
- existingItems.map(item =>
152
- item.title === sessionName ? { ...item, opencodeState: nextState } : item
153
- )
154
-
155
- setSessionItems(applyState)
156
- setAllItems(applyState)
157
- setItems(applyState)
158
- }
159
-
160
- async function loadLinkedProjectItems(nextConfig: Config, liveSessions: Item[], sourceItems = projectSourceItems) {
161
- return orderProjectItems(
162
- await measure('linkProjectItems', () => annotateProjectItemsWithSessionLinks(sourceItems, liveSessions, nextConfig)),
163
- nextConfig.sortOrder
164
- )
165
- }
166
-
167
- useEffect(() => {
168
- async function init() {
169
- mark('startup begin')
170
- const cfg = await measure('loadConfig', loadConfig)
171
- setConfig(cfg)
172
-
173
- // Standard mode always starts in search mode (non-modal)
174
- if (cfg.keybindMode === 'standard') {
175
- setAppMode(AppMode.Search)
176
- }
177
-
178
- const [sessions, listedSessions] = await measure('loadSessionsAndListed', () =>
179
- Promise.all([listTmuxSessions(), getListedSessionItems(cfg)])
180
- )
181
- const visibleSessions = filterHiddenSessions(sessions, cfg.hiddenSessions)
182
- const combinedSessions = orderSessionItems(mergeSessionItems(visibleSessions, listedSessions), cfg.sortOrder)
183
-
184
- if (combinedSessions.length > 0) {
185
- setViewMode(ViewMode.Sessions)
186
- setSessionItems(combinedSessions)
187
- setAllItems(combinedSessions)
188
- setItems(combinedSessions)
189
- setCursor(getSessionSelectionIndex(combinedSessions))
190
- }
191
-
192
- const rawProjects = await measure('getProjectItems', () => getProjectItems(cfg))
193
- const orderedProjects = orderProjectItems(rawProjects, cfg.sortOrder)
194
-
195
- setProjectSourceItems(orderedProjects)
196
- setProjectItems(orderedProjects)
197
-
198
- if (combinedSessions.length === 0) {
199
- const linkedProjects = await loadLinkedProjectItems(cfg, visibleSessions, orderedProjects)
200
- setProjectItems(linkedProjects)
201
- setViewMode(ViewMode.Projects)
202
- setAllItems(linkedProjects)
203
- setItems(linkedProjects)
204
- setCursor(getProjectSelectionIndex(linkedProjects))
205
- }
206
-
207
- mark('startup complete')
208
- }
209
- init()
210
- }, [])
211
-
212
- useEffect(() => {
213
- if (!config || hasScheduledAutoUpdateRef.current) {
214
- return
215
- }
216
-
217
- hasScheduledAutoUpdateRef.current = true
218
-
219
- const timeout = setTimeout(() => {
220
- checkAndUpdate(config).catch(error => {
221
- console.error('Auto-update check failed:', error)
222
- })
223
- }, 1000)
224
-
225
- return () => clearTimeout(timeout)
226
- }, [config])
227
- async function refreshItems(forceViewMode?: ViewMode, nextConfig = config) {
228
- if (!nextConfig) return
229
-
230
- const targetMode = forceViewMode ?? viewMode
231
-
232
- if (targetMode === ViewMode.Sessions) {
233
- const sessions = await measure('refresh:listTmuxSessions', listTmuxSessions)
234
- const visibleSessions = filterHiddenSessions(sessions, nextConfig.hiddenSessions)
235
- const listedSessions = await measure('refresh:getListedSessionItems', () => getListedSessionItems(nextConfig))
236
- const cleanSessions = clearMatchIndices(
237
- orderSessionItems(mergeSessionItems(visibleSessions, listedSessions), nextConfig.sortOrder)
238
- )
239
- setSessionItems(cleanSessions)
240
- setAllItems(cleanSessions)
241
- setItems(cleanSessions)
242
- setCursor(getSessionSelectionIndex(cleanSessions))
243
- } else {
244
- const sessions = await measure('refresh:listTmuxSessions', listTmuxSessions)
245
- const visibleSessions = filterHiddenSessions(sessions, nextConfig.hiddenSessions)
246
- const rawProjects = await measure('refresh:getProjectItems', () => getProjectItems(nextConfig))
247
- const orderedProjects = orderProjectItems(rawProjects, nextConfig.sortOrder)
248
- setProjectSourceItems(orderedProjects)
249
- const linkedProjects = await loadLinkedProjectItems(nextConfig, visibleSessions, orderedProjects)
250
- const cleanProjects = clearMatchIndices(linkedProjects)
251
- setProjectItems(cleanProjects)
252
- setAllItems(cleanProjects)
253
- setItems(cleanProjects)
254
- setCursor(getProjectSelectionIndex(cleanProjects))
255
- }
256
- }
257
-
258
- async function loadOpencodeStatsForSession(sessionName: string) {
259
- updateOpencodeState(sessionName, { status: 'loading' })
260
-
261
- try {
262
- const stats = await getOpencodeSessionStats(sessionName)
263
-
264
- if (stats) {
265
- updateOpencodeState(sessionName, { status: 'ready', stats })
266
- return stats
267
- }
268
-
269
- updateOpencodeState(sessionName, {
270
- status: 'missing',
271
- message: `No OpenCode stats found for '${sessionName}'`,
272
- })
273
- return null
274
- } catch (error) {
275
- const errorMessage = error instanceof Error ? error.message : `Failed to load stats for '${sessionName}'`
276
- updateOpencodeState(sessionName, { status: 'error', message: errorMessage })
277
- setMessage(errorMessage)
278
- setTimeout(() => setMessage(''), 4000)
279
- return null
280
- }
281
- }
282
-
283
- const regularSessions =
284
- viewMode === ViewMode.Sessions &&
285
- (appMode === AppMode.Normal || appMode === AppMode.OpencodeManage)
286
- ? items.filter(item => !(item.isSession && item.title.startsWith('opencode-')))
287
- : items
288
-
289
- const opencodeSessions =
290
- viewMode === ViewMode.Sessions &&
291
- (appMode === AppMode.Normal || appMode === AppMode.OpencodeManage)
292
- ? items.filter(item => item.isSession && item.title.startsWith('opencode-'))
293
- : []
294
- const selectedOpencodeSessionName =
295
- appMode === AppMode.OpencodeManage ? opencodeSessions[opencodeCursor]?.title : undefined
296
- const selectedPrimaryItem =
297
- viewMode === ViewMode.Sessions && appMode === AppMode.Normal ? regularSessions[cursor] : items[cursor]
298
- const commandEntries = getCommandEntries(appMode, config?.keybindMode, config?.prefixKey, selectedPrimaryItem)
299
- const filteredCommandEntries = filterCommandEntries(commandEntries, commandsSearchQuery)
300
-
301
- async function handleKillSessionWrapper(sessionName: string) {
302
- setPendingKillSessionName(null)
303
-
304
- await actionKillSession(sessionName, {
305
- onSuccess: msg => {
306
- setMessage(msg)
307
- setTimeout(() => setMessage(''), 2000)
308
- },
309
- onError: msg => {
310
- setMessage(msg)
311
- setTimeout(() => setMessage(''), 3000)
312
- },
313
- refreshItems,
314
- })
315
- }
316
-
317
- async function handleSelectWrapper(item: Item) {
318
- await actionHandleSelect(item, config)
319
- }
320
-
321
- async function handleLastSessionWrapper() {
322
- try {
323
- await actionHandleLastSession(sessionItems)
324
- } catch (error) {
325
- const errorMessage = error instanceof Error ? error.message : 'Failed to switch to the previous session'
326
- setMessage(errorMessage)
327
- setTimeout(() => setMessage(''), 3000)
328
- }
329
- }
330
-
331
- async function handleRootSessionWrapper(item?: Item) {
332
- try {
333
- await actionHandleRootSession(item, config)
334
- } catch (error) {
335
- const errorMessage = error instanceof Error ? error.message : 'Failed to open the root session'
336
- setMessage(errorMessage)
337
- setTimeout(() => setMessage(''), 3000)
338
- }
339
- }
340
-
341
- async function handleEditTargetWrapper(item?: Item) {
342
- try {
343
- await actionHandleEditTarget(item, config)
344
- } catch (error) {
345
- const errorMessage = error instanceof Error ? error.message : 'Failed to edit target'
346
- setMessage(errorMessage)
347
- setTimeout(() => setMessage(''), 3000)
348
- }
349
- }
350
-
351
- function clearPendingKill() {
352
- setPendingKillSessionName(null)
353
- }
354
-
355
- function requestKillSession(sessionName: string) {
356
- if (pendingKillSessionName === sessionName) {
357
- void handleKillSessionWrapper(sessionName)
358
- return
359
- }
360
-
361
- setPendingKillSessionName(sessionName)
362
- }
363
-
364
- function openRenameModal(sessionName: string) {
365
- clearPendingKill()
366
- setRenameTarget(sessionName)
367
- setModalInputValue(sessionName)
368
- setModalState({ type: 'rename', target: sessionName })
369
- }
370
-
371
- function openCommandsModal() {
372
- clearPendingKill()
373
- setCommandsSearchQuery('')
374
- setCommandsCursor(0)
375
- setModalState({ type: 'commands' })
376
- }
377
-
378
- function openSettingsModal() {
379
- if (!config) {
380
- return
381
- }
382
-
383
- clearPendingKill()
384
- setSettingEditorError('')
385
- setSettingsSearchQuery('')
386
- setSettingsCursor(0)
387
- setModalState({ type: 'settings' })
388
- }
389
-
390
- function openSettingOptions(field: SettingsFieldId) {
391
- setSettingOptionsSearchQuery('')
392
- setSettingOptionsCursor(0)
393
- setModalState({ type: 'setting-options', field })
394
- }
395
-
396
- function openSettingEditor(field: SettingsFieldId) {
397
- if (!config) {
398
- return
399
- }
400
-
401
- setSettingEditorError('')
402
- setSettingEditorValue(getSettingEditorValue(config, field))
403
- setModalState({ type: 'setting-editor', field })
404
- }
405
-
406
- function closeModal() {
407
- setModalState(null)
408
- setModalInputValue('')
409
- setCommandsSearchQuery('')
410
- setCommandsCursor(0)
411
- setSettingsSearchQuery('')
412
- setSettingOptionsSearchQuery('')
413
- setSettingEditorValue('')
414
- setSettingEditorError('')
415
- setRenameTarget('')
416
- }
417
-
418
- async function handleRenameSubmit() {
419
- const newName = (modalTextareaRef.current?.plainText ?? modalInputValue).trim()
420
- if (newName && newName !== renameTarget) {
421
- await actionRenameSubmit(renameTarget, newName, {
422
- onSuccess: msg => {
423
- setMessage(msg)
424
- setTimeout(() => setMessage(''), 2000)
425
- },
426
- onError: msg => {
427
- setMessage(msg)
428
- setTimeout(() => setMessage(''), 3000)
429
- },
430
- refreshItems,
431
- })
432
- }
433
-
434
- closeModal()
435
- }
436
-
437
- async function handleNewSessionSubmit() {
438
- const searchTerm = searchQuery.trim()
439
- if (!searchTerm) return
440
-
441
- try {
442
- await actionNewSessionSubmit(searchTerm, config, items, cursor)
443
- } catch (error) {
444
- const errorMessage = error instanceof Error ? error.message : 'Failed to create session'
445
- setMessage(errorMessage)
446
- setTimeout(() => setMessage(''), 3000)
447
- }
448
- }
449
-
450
- async function executeCommand(commandID: CommandId) {
451
- switch (commandID) {
452
- case 'search':
453
- closeModal()
454
- setAppMode(AppMode.Search)
455
- setSearchQuery('')
456
- return
457
- case 'new-session':
458
- closeModal()
459
- setAppMode(AppMode.NewSession)
460
- setViewMode(ViewMode.Projects)
461
- setAllItems(sessionCandidateItems.length > 0 ? sessionCandidateItems : projectSourceItems)
462
- setItems(sessionCandidateItems.length > 0 ? sessionCandidateItems : projectSourceItems)
463
- setCursor(Math.max(0, (sessionCandidateItems.length > 0 ? sessionCandidateItems : projectSourceItems).length - 1))
464
- setSearchQuery('')
465
- return
466
- case 'open-settings':
467
- openSettingsModal()
468
- return
469
- case 'view-projects':
470
- closeModal()
471
- setViewMode(ViewMode.Projects)
472
- await refreshItems(ViewMode.Projects)
473
- return
474
- case 'view-sessions':
475
- closeModal()
476
- setViewMode(ViewMode.Sessions)
477
- await refreshItems(ViewMode.Sessions)
478
- return
479
- case 'rename-session': {
480
- const target =
481
- appMode === AppMode.OpencodeManage ? opencodeSessions[opencodeCursor] : viewMode === ViewMode.Sessions ? regularSessions[cursor] : undefined
482
- if (target?.isSession) {
483
- openRenameModal(target.title)
484
- }
485
- return
486
- }
487
- case 'kill-session': {
488
- const target =
489
- appMode === AppMode.OpencodeManage ? opencodeSessions[opencodeCursor] : viewMode === ViewMode.Sessions ? regularSessions[cursor] : undefined
490
- if (target?.isSession) {
491
- closeModal()
492
- requestKillSession(target.title)
493
- }
494
- return
495
- }
496
- case 'last-session':
497
- closeModal()
498
- await handleLastSessionWrapper()
499
- return
500
- case 'root-session':
501
- closeModal()
502
- await handleRootSessionWrapper(selectedPrimaryItem)
503
- return
504
- case 'edit-target':
505
- closeModal()
506
- await handleEditTargetWrapper(selectedPrimaryItem)
507
- return
508
- case 'open-opencode':
509
- closeModal()
510
- if (viewMode === ViewMode.Sessions && opencodeSessions.length > 0) {
511
- setAppMode(AppMode.OpencodeManage)
512
- setOpencodeCursor(0)
513
- await loadOpencodeStatsForSession(opencodeSessions[0].title)
514
- }
515
- return
516
- case 'refresh':
517
- closeModal()
518
- await refreshItems()
519
- setMessage('Refreshed')
520
- setTimeout(() => setMessage(''), 2000)
521
- return
522
- case 'back':
523
- closeModal()
524
- setAppMode(AppMode.Normal)
525
- return
526
- }
527
- }
528
-
529
- async function applyAndPersistConfig(nextConfig: Config, successMessage: string) {
530
- await saveConfig(nextConfig)
531
- setConfig(nextConfig)
532
- await refreshItems(undefined, nextConfig)
533
- setMessage(successMessage)
534
- setTimeout(() => setMessage(''), 2000)
535
- }
536
-
537
- async function handleSettingsEditorSubmit(field: SettingsFieldId) {
538
- if (!config) {
539
- return
540
- }
541
-
542
- try {
543
- const rawText = settingEditorTextareaRef.current?.plainText ?? settingEditorValue
544
- const nextConfig = applyEditorSetting(config, field, rawText, process.env.HOME || '~')
545
-
546
- setSettingEditorError('')
547
- await applyAndPersistConfig(nextConfig, `${getSettingEditorTitle(field)} updated`)
548
- openSettingsModal()
549
- } catch (error) {
550
- const errorMessage = error instanceof Error ? error.message : 'Failed to save settings'
551
- setSettingEditorError(errorMessage)
552
- }
553
- }
554
-
555
- async function handleSettingOptionSubmit(field: SettingsFieldId, value: string) {
556
- if (!config) {
557
- return
558
- }
559
-
560
- const nextConfig = applyOptionSetting(config, field, value)
561
- await applyAndPersistConfig(nextConfig, `${getSettingEditorTitle(field)} updated`)
562
- }
563
-
564
- const keyboardContext: KeyboardHandlerContext = {
565
- appMode,
566
- viewMode,
567
- items,
568
- regularSessions,
569
- opencodeSessions,
570
- cursor,
571
- opencodeCursor,
572
- searchQuery,
573
- renameTarget,
574
- prefixKey: config?.prefixKey,
575
- projectItems: sessionCandidateItems.length > 0 ? sessionCandidateItems : projectSourceItems,
576
- sessionItems,
577
- prefixActive,
578
- prefixTimeoutRef,
579
- textareaRef,
580
- setAppMode,
581
- setViewMode,
582
- setCursor,
583
- setOpencodeCursor,
584
- setSearchQuery,
585
- setRenameTarget,
586
- setAllItems,
587
- setItems,
588
- setPrefixActive,
589
- refreshItems,
590
- requestKillSession,
591
- clearPendingKill,
592
- handleSelect: handleSelectWrapper,
593
- handleKillSession: handleKillSessionWrapper,
594
- handleLastSession: handleLastSessionWrapper,
595
- handleRootSession: handleRootSessionWrapper,
596
- handleEditTarget: handleEditTargetWrapper,
597
- openRenameModal,
598
- openCommandsModal,
599
- openSettingsModal,
600
- loadOpencodeStatsForSession,
601
- setMessage,
602
- }
603
-
604
- useKeyboard(key => {
605
- const keybindMode = config?.keybindMode || 'vim'
606
-
607
- if (modalState?.type === 'rename') {
608
- if (key.name === 'return') {
609
- void handleRenameSubmit()
610
- } else if (key.name === 'escape') {
611
- closeModal()
612
- }
613
- return
614
- }
615
-
616
- if (modalState?.type === 'commands') {
617
- if (key.name === 'escape' || key.name === 'q') {
618
- closeModal()
619
- } else if (key.name === 'down' || key.name === 'j') {
620
- setCommandsCursor(current => Math.min(current + 1, filteredCommandEntries.length - 1))
621
- } else if (key.name === 'up' || key.name === 'k') {
622
- setCommandsCursor(current => Math.max(current - 1, 0))
623
- } else if (key.name === 'return') {
624
- const command = filteredCommandEntries[commandsCursor]
625
- if (!command) {
626
- return
627
- }
628
- void executeCommand(command.id)
629
- }
630
- return
631
- }
632
-
633
- if (modalState?.type === 'settings') {
634
- if (key.name === 'escape') {
635
- closeModal()
636
- } else if (key.name === 'down' || key.name === 'j') {
637
- setSettingsCursor(current => Math.min(current + 1, filteredSettingsEntries.length - 1))
638
- } else if (key.name === 'up' || key.name === 'k') {
639
- setSettingsCursor(current => Math.max(current - 1, 0))
640
- } else if (key.name === 'return') {
641
- const entry = filteredSettingsEntries[settingsCursor]
642
- if (!entry) {
643
- return
644
- }
645
-
646
- if (isOptionSetting(entry.id)) {
647
- openSettingOptions(entry.id)
648
- } else {
649
- openSettingEditor(entry.id)
650
- }
651
- } else if (key.name === 'e') {
652
- const entry = filteredSettingsEntries[settingsCursor]
653
- if (!entry) return
654
- if (isOptionSetting(entry.id)) {
655
- openSettingOptions(entry.id)
656
- } else {
657
- openSettingEditor(entry.id)
658
- }
659
- }
660
- return
661
- }
662
-
663
- if (modalState?.type === 'setting-options') {
664
- if (key.name === 'escape') {
665
- setModalState({ type: 'settings' })
666
- } else if (key.name === 'down' || key.name === 'j') {
667
- setSettingOptionsCursor(current => Math.min(current + 1, filteredSettingOptions.length - 1))
668
- } else if (key.name === 'up' || key.name === 'k') {
669
- setSettingOptionsCursor(current => Math.max(current - 1, 0))
670
- } else if (key.name === 'return') {
671
- const option = filteredSettingOptions[settingOptionsCursor]
672
- if (!option) return
673
- void handleSettingOptionSubmit(modalState.field, option.value)
674
- }
675
- return
676
- }
677
-
678
- if (modalState?.type === 'setting-editor') {
679
- if (key.name === 'escape') {
680
- setModalState({ type: 'settings' })
681
- setSettingEditorError('')
682
- } else if (key.name === 'return') {
683
- void handleSettingsEditorSubmit(modalState.field)
684
- }
685
- return
686
- }
687
-
688
- if (appMode === AppMode.Normal) {
689
- handleNormalMode(key, keyboardContext, keybindMode)
690
- } else if (appMode === AppMode.Search) {
691
- handleSearchMode(key, keyboardContext, keybindMode)
692
- } else if (appMode === AppMode.NewSession) {
693
- if (key.name === 'return') {
694
- void handleNewSessionSubmit()
695
- } else {
696
- handleNewSessionMode(key, keyboardContext, keybindMode)
697
- }
698
- } else if (appMode === AppMode.OpencodeManage) {
699
- handleOpencodeManageMode(key, keyboardContext, keybindMode)
700
- }
701
- })
702
-
703
- useEffect(() => {
704
- const unsubscribe = updateEvents.on(event => {
705
- if (event.kind === 'updated') {
706
- setUpdatedVersion(event.version)
707
- setToastMessage(`Updated in background to v${event.version}. Restart mux-sesh to use it.`)
708
- } else if (event.kind === 'available') {
709
- setToastMessage(`Update available: v${event.version}`)
710
- } else {
711
- setToastMessage(`Background update to v${event.version} failed.`)
712
- }
713
- setToastVisible(true)
714
- setTimeout(() => {
715
- setToastVisible(false)
716
- }, 5000)
717
- })
718
- return unsubscribe
719
- }, [])
720
-
721
- useEffect(() => {
722
- if (appMode === AppMode.Search && searchQuery === '') {
723
- setItems(allItems)
724
- }
725
- }, [appMode, searchQuery, allItems])
726
-
727
- useEffect(() => {
728
- if (appMode === AppMode.Normal && viewMode === ViewMode.Sessions) {
729
- // Clear match indices when returning to normal mode
730
- const cleanSessions = clearMatchIndices(sessionItems)
731
- setAllItems(cleanSessions)
732
- setItems(cleanSessions)
733
- setCursor(getSessionSelectionIndex(cleanSessions))
734
- }
735
- }, [appMode, viewMode, sessionItems])
736
-
737
- useEffect(() => {
738
- if (appMode === AppMode.NewSession && viewMode === ViewMode.Projects) {
739
- setCursor(getProjectSelectionIndex(sessionCandidateItems.length > 0 ? sessionCandidateItems : projectSourceItems))
740
- }
741
- }, [appMode, viewMode, projectSourceItems, sessionCandidateItems])
742
-
743
- useEffect(() => {
744
- if (appMode !== AppMode.NewSession || !config) {
745
- return
746
- }
747
-
748
- const nextConfig = config
749
- let cancelled = false
750
-
751
- async function loadSessionCandidates() {
752
- const candidates = await measure('loadSessionCandidateItems', () => getSessionCandidateItems(nextConfig))
753
- if (cancelled) {
754
- return
755
- }
756
-
757
- setSessionCandidateItems(candidates)
758
- setAllItems(candidates)
759
- setItems(candidates)
760
- setCursor(getProjectSelectionIndex(candidates))
761
- }
762
-
763
- void loadSessionCandidates()
764
-
765
- return () => {
766
- cancelled = true
767
- }
768
- }, [appMode, config])
769
-
770
- useEffect(() => {
771
- if (filteredCommandEntries.length === 0) {
772
- setCommandsCursor(0)
773
- return
774
- }
775
-
776
- setCommandsCursor(current => Math.min(current, filteredCommandEntries.length - 1))
777
- }, [filteredCommandEntries.length])
778
-
779
- useEffect(() => {
780
- setCommandsCursor(0)
781
- }, [commandsSearchQuery])
782
-
783
- useEffect(() => {
784
- if (filteredSettingsEntries.length === 0) {
785
- setSettingsCursor(0)
786
- return
787
- }
788
-
789
- setSettingsCursor(current => Math.min(current, filteredSettingsEntries.length - 1))
790
- }, [filteredSettingsEntries.length])
791
-
792
- useEffect(() => {
793
- if (filteredSettingOptions.length === 0) {
794
- setSettingOptionsCursor(0)
795
- return
796
- }
797
-
798
- setSettingOptionsCursor(current => Math.min(current, filteredSettingOptions.length - 1))
799
- }, [filteredSettingOptions.length])
800
-
801
- useEffect(() => {
802
- const selectedItem = appMode === AppMode.NewSession ? items[cursor] : selectedPrimaryItem
803
-
804
- if (!selectedItem) {
805
- return
806
- }
807
-
808
- if (appMode === AppMode.NewSession || viewMode === ViewMode.Projects) {
809
- if (!selectedItem.isSession) {
810
- lastProjectSelectionRef.current = selectedItem.path
811
- }
812
- return
813
- }
814
-
815
- if (viewMode === ViewMode.Sessions && appMode === AppMode.Normal) {
816
- lastSessionSelectionRef.current = selectedItem.title
817
- }
818
- }, [appMode, viewMode, cursor, items, selectedPrimaryItem])
819
-
820
- useEffect(() => {
821
- if (!pendingKillSessionName) {
822
- return
823
- }
824
-
825
- const selectedSessionName =
826
- appMode === AppMode.OpencodeManage
827
- ? opencodeSessions[opencodeCursor]?.title
828
- : viewMode === ViewMode.Sessions
829
- ? regularSessions[cursor]?.title
830
- : undefined
831
-
832
- if (selectedSessionName !== pendingKillSessionName) {
833
- setPendingKillSessionName(null)
834
- }
835
- }, [appMode, cursor, opencodeCursor, opencodeSessions, pendingKillSessionName, regularSessions, viewMode])
836
-
837
- useEffect(() => {
838
- if (appMode === AppMode.Search || appMode === AppMode.NewSession) {
839
- if (searchQuery.trim()) {
840
- const filtered = filterAndSortItems(allItems, searchQuery)
841
- setItems(filtered)
842
- setCursor(0)
843
- } else {
844
- setItems(allItems)
845
- setCursor(0)
846
- }
847
- }
848
- }, [searchQuery, appMode, allItems])
849
-
850
- useEffect(() => {
851
- if (!selectedOpencodeSessionName) {
852
- return
853
- }
854
-
855
- void loadOpencodeStatsForSession(selectedOpencodeSessionName)
856
-
857
- const interval = setInterval(() => {
858
- void loadOpencodeStatsForSession(selectedOpencodeSessionName)
859
- }, 2000)
860
-
861
- return () => {
862
- clearInterval(interval)
863
- }
864
- }, [selectedOpencodeSessionName])
865
-
866
- const title =
867
- appMode === AppMode.Search
868
- ? 'Search'
869
- : appMode === AppMode.NewSession
870
- ? 'New Session'
871
- : appMode === AppMode.OpencodeManage
872
- ? 'OpenCode Sessions'
873
- : viewMode === ViewMode.Projects
874
- ? 'Projects'
875
- : 'Sessions'
876
-
877
- const listStyle =
878
- appMode === AppMode.NewSession
879
- ? {
880
- ...getPanelStyle(theme, 'full'),
881
- flexGrow: 1,
882
- flexShrink: 1,
883
- }
884
- : {
885
- ...getPanelStyle(theme, 'split'),
886
- flexGrow: 1,
887
- flexShrink: 1,
888
- minWidth: 40,
889
- }
890
-
891
- const totalSessions = sessionItems.filter(item => item.isSession).length
892
- const activeSessions = items.filter(item => item.isSession && item.isAttached).length
893
- const maxVisibleItems = Math.max(8, rows - (appMode === AppMode.NewSession ? 10 : 12))
894
- const prefixLabel = config?.prefixKey ? `${config.prefixKey} ...` : 'direct keys'
895
- const footerHint =
896
- appMode === AppMode.OpencodeManage
897
- ? `o back d kill ctrl+p commands ${prefixLabel}`
898
- : appMode === AppMode.NewSession
899
- ? 'enter create esc cancel'
900
- : appMode === AppMode.Search
901
- ? 'enter select esc cancel'
902
- : `enter select i search n new o opencode d kill ctrl+p commands ${prefixLabel}`
7
+ const { theme, screenProps, modalProps } = useAppController()
903
8
 
904
9
  return (
905
10
  <ThemeProvider theme={theme}>
906
- <box
907
- style={{
908
- flexDirection: 'row',
909
- alignItems: 'stretch',
910
- justifyContent: 'center',
911
- width: '100%',
912
- height: '100%',
913
- gap: 1,
914
- backgroundColor: theme.background,
915
- }}
916
- >
917
- <box style={listStyle}>
918
- <box style={{ justifyContent: 'space-between', marginBottom: 1 }}>
919
- <box style={{ flexDirection: 'column' }}>
920
- <text style={{ fg: theme.text }}>mux-sesh</text>
921
- <text style={{ fg: theme.textSubtle }}>{title}</text>
922
- </box>
923
- <box style={{ flexDirection: 'column', alignItems: 'flex-end' }}>
924
- <text style={{ fg: theme.textMuted }}>
925
- {viewMode === ViewMode.Sessions ? `${activeSessions}/${totalSessions} active` : `${projectItems.length} projects`}
926
- </text>
927
- <text style={{ fg: theme.textSubtle }}>{`${resolvedTheme.name} · ${resolvedTheme.mode}`}</text>
928
- </box>
929
- </box>
930
-
931
- {(appMode === AppMode.Search || appMode === AppMode.NewSession) && (
932
- <SearchInput
933
- key={appMode}
934
- appMode={appMode}
935
- searchQuery={searchQuery}
936
- textareaRef={textareaRef}
937
- prefixActive={prefixActive}
938
- onContentChange={() => {
939
- if (textareaRef.current && textareaRef.current.plainText !== undefined) {
940
- setSearchQuery(textareaRef.current.plainText)
941
- }
942
- }}
943
- />
944
- )}
945
-
946
- <box
947
- style={{
948
- alignSelf: 'auto',
949
- flexDirection: 'column',
950
- flexGrow: 0,
951
- flexShrink: 0,
952
- marginTop:
953
- viewMode === ViewMode.Sessions && (appMode === AppMode.Normal || appMode === AppMode.OpencodeManage)
954
- ? 1
955
- : 0,
956
- }}
957
- >
958
- {items.length === 0 ? (
959
- <text style={{ fg: theme.inactive }}>
960
- {appMode === AppMode.NewSession && searchQuery && isGitHubURL(searchQuery)
961
- ? 'Clone & create session'
962
- : appMode === AppMode.NewSession && searchQuery
963
- ? `Create session: ${searchQuery}`
964
- : 'No items found'}
965
- </text>
966
- ) : viewMode === ViewMode.Sessions && (appMode === AppMode.Normal || appMode === AppMode.OpencodeManage) ? (
967
- <>
968
- <SessionList
969
- items={regularSessions}
970
- cursor={cursor}
971
- searchQuery={searchQuery}
972
- maxItems={maxVisibleItems}
973
- icons={config?.icons}
974
- pendingKillSessionName={pendingKillSessionName}
975
- />
976
-
977
- <OpencodeSessionGroup
978
- sessions={opencodeSessions}
979
- appMode={appMode}
980
- cursor={opencodeCursor}
981
- icons={config?.icons}
982
- pendingKillSessionName={pendingKillSessionName}
983
- />
984
- </>
985
- ) : (
986
- <ItemList
987
- items={items}
988
- cursor={cursor}
989
- appMode={appMode}
990
- searchQuery={searchQuery}
991
- maxItems={maxVisibleItems}
992
- icons={config?.icons}
993
- pendingKillSessionName={pendingKillSessionName}
994
- />
995
- )}
996
- </box>
997
-
998
- {(message || columns < 80 || footerHint) && (
999
- <box style={{ flexDirection: 'column', marginTop: 1 }}>
1000
- {message && <text style={{ fg: theme.action }}>{message}</text>}
1001
- {columns < 80 && appMode !== AppMode.NewSession && (
1002
- <text style={{ fg: theme.textSubtle }}>Resize for the detail pane.</text>
1003
- )}
1004
- <text style={{ fg: theme.textSubtle }}>{footerHint}</text>
1005
- </box>
1006
- )}
1007
- </box>
1008
-
1009
- {shouldShowDetailPanel(columns, appMode === AppMode.NewSession) && (
1010
- <>
1011
- {viewMode === ViewMode.Sessions && appMode === AppMode.OpencodeManage ? (
1012
- <OpencodeStatsPanel selectedItem={opencodeSessions[opencodeCursor]} />
1013
- ) : (
1014
- <SessionDetailsPanel selectedItem={selectedPrimaryItem} config={config} />
1015
- )}
1016
- </>
1017
- )}
1018
-
1019
- {modalState?.type === 'rename' && (
1020
- <RenameModal
1021
- target={modalState.target}
1022
- initialValue={modalInputValue}
1023
- columns={columns}
1024
- textareaRef={modalTextareaRef}
1025
- onContentChange={() => {
1026
- if (modalTextareaRef.current?.plainText !== undefined) {
1027
- setModalInputValue(modalTextareaRef.current.plainText)
1028
- }
1029
- }}
1030
- />
1031
- )}
1032
-
1033
- {modalState?.type === 'commands' && (
1034
- <CommandsModal
1035
- columns={columns}
1036
- themeId={resolvedTheme.id}
1037
- entries={filteredCommandEntries}
1038
- cursor={commandsCursor}
1039
- searchQuery={commandsSearchQuery}
1040
- textareaRef={commandsSearchTextareaRef}
1041
- onContentChange={() => {
1042
- if (commandsSearchTextareaRef.current?.plainText !== undefined) {
1043
- setCommandsSearchQuery(commandsSearchTextareaRef.current.plainText)
1044
- setCommandsCursor(0)
1045
- }
1046
- }}
1047
- />
1048
- )}
1049
-
1050
- {modalState?.type === 'settings' && config && (
1051
- <SettingsModal
1052
- configPath={configPath}
1053
- themeName={resolvedTheme.name}
1054
- colorMode={resolvedTheme.mode}
1055
- columns={columns}
1056
- entries={filteredSettingsEntries}
1057
- cursor={settingsCursor}
1058
- searchQuery={settingsSearchQuery}
1059
- textareaRef={settingsSearchTextareaRef}
1060
- onContentChange={() => {
1061
- if (settingsSearchTextareaRef.current?.plainText !== undefined) {
1062
- setSettingsSearchQuery(settingsSearchTextareaRef.current.plainText)
1063
- setSettingsCursor(0)
1064
- }
1065
- }}
1066
- />
1067
- )}
1068
-
1069
- {modalState?.type === 'setting-options' && (
1070
- <SettingOptionsModal
1071
- title={getSettingEditorTitle(modalState.field)}
1072
- description='Select an option to apply it immediately'
1073
- columns={columns}
1074
- options={filteredSettingOptions}
1075
- cursor={settingOptionsCursor}
1076
- searchQuery={settingOptionsSearchQuery}
1077
- textareaRef={settingOptionsSearchTextareaRef}
1078
- onContentChange={() => {
1079
- if (settingOptionsSearchTextareaRef.current?.plainText !== undefined) {
1080
- setSettingOptionsSearchQuery(settingOptionsSearchTextareaRef.current.plainText)
1081
- setSettingOptionsCursor(0)
1082
- }
1083
- }}
1084
- />
1085
- )}
1086
-
1087
- {modalState?.type === 'setting-editor' && (
1088
- <SettingEditorModal
1089
- title={getSettingEditorTitle(modalState.field)}
1090
- description='Edit value and press Enter to apply immediately'
1091
- value={settingEditorValue}
1092
- error={settingEditorError}
1093
- columns={columns}
1094
- rows={rows}
1095
- textareaRef={settingEditorTextareaRef}
1096
- onContentChange={() => {
1097
- if (settingEditorTextareaRef.current?.plainText !== undefined) {
1098
- setSettingEditorValue(settingEditorTextareaRef.current.plainText)
1099
- }
1100
- }}
1101
- />
1102
- )}
1103
-
1104
- <Toast message={toastMessage} visible={toastVisible} />
1105
- <VersionBadge currentVersion={CURRENT_VERSION} updatedVersion={updatedVersion} />
1106
- </box>
11
+ <AppScreen {...screenProps} />
12
+ <AppModalsLayer {...modalProps} />
1107
13
  </ThemeProvider>
1108
14
  )
1109
15
  }