mux-sesh 1.9.6 → 1.9.8

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
@@ -122,6 +122,18 @@ In vim mode, `s` and `p` are also available as direct view switches.
122
122
 
123
123
  Full keybinding reference: [docs/keybindings.md](docs/keybindings.md)
124
124
 
125
+ ## Crash recovery
126
+
127
+ mux-sesh disables OpenTUI's automatic error console so a crash cannot trap the terminal. React UI failures show a recovery screen with these controls:
128
+
129
+ - `c` copies the complete diagnostics report with OSC 52 (including tmux passthrough)
130
+ - `o` opens a prefilled GitHub issue for review
131
+ - `r` retries the application UI
132
+ - `q`, `Esc`, or `Ctrl+C` restores the terminal and exits
133
+ - `↑`/`↓`, `j`/`k`, `PgUp`/`PgDn`, `Home`, and `End` scroll long diagnostics
134
+
135
+ Uncaught process-level failures restore the terminal first, then print the diagnostics and report URL to normal terminal scrollback before exiting with status 1. Prefilled issues are never submitted automatically; review the report before sending it.
136
+
125
137
  ## Docs
126
138
 
127
139
  - [Configuration](docs/configuration.md)
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.6",
4
+ "version": "1.9.8",
5
5
  "description": "An OpenTUI manager for tmux sessions and Herdr workspaces with fuzzy project search",
6
6
  "type": "module",
7
7
  "packageManager": "bun@1.3.14",
@@ -174,6 +174,10 @@ export function useAppController() {
174
174
  showMessage,
175
175
  refreshItems,
176
176
  setPendingKillSessionName,
177
+ regularSessions,
178
+ rememberedSessions: (key: string | null) => {
179
+ lastSessionSelectionRef.current = key
180
+ },
177
181
  }),
178
182
  setPendingKillSessionName,
179
183
  setRenameTarget,
@@ -213,6 +217,9 @@ export function useAppController() {
213
217
  refreshItems,
214
218
  agentCursor,
215
219
  regularSessions,
220
+ rememberedSessions: (key: string | null) => {
221
+ lastSessionSelectionRef.current = key
222
+ },
216
223
  agentSessions,
217
224
  selectedPrimaryItem,
218
225
  sessionCandidateItems,
@@ -28,6 +28,8 @@ interface SharedHandlerOptions {
28
28
 
29
29
  interface KillHandlerOptions extends SharedHandlerOptions {
30
30
  setPendingKillSessionName: (sessionName: string | null) => void
31
+ regularSessions: Item[]
32
+ rememberedSessions: (key: string | null) => void
31
33
  }
32
34
 
33
35
  interface SettingsHandlerOptions {
@@ -53,6 +55,8 @@ export async function handleKillSessionWithFeedback(
53
55
  onSuccess: msg => options.showMessage(msg),
54
56
  onError: msg => options.showMessage(msg, 3000),
55
57
  refreshItems: () => options.refreshItems(),
58
+ regularSessions: options.regularSessions,
59
+ rememberedSessions: options.rememberedSessions,
56
60
  })
57
61
  }
58
62
 
@@ -260,6 +264,7 @@ interface CreateAppHandlersOptions extends SharedHandlerOptions {
260
264
  renamedValue: string
261
265
  searchTerm: string
262
266
  loadOpencodeStatsForSession: (sessionName: string) => Promise<OpencodeSessionStats | null>
267
+ rememberedSessions: (key: string | null) => void
263
268
  }
264
269
 
265
270
  export function createAppHandlers(options: CreateAppHandlersOptions) {
@@ -277,6 +282,8 @@ export function createAppHandlers(options: CreateAppHandlersOptions) {
277
282
  await handleKillSessionWithFeedback(item, {
278
283
  ...sharedOptions,
279
284
  setPendingKillSessionName: options.setPendingKillSessionName,
285
+ regularSessions: options.regularSessions,
286
+ rememberedSessions: options.rememberedSessions,
280
287
  })
281
288
  }
282
289
 
package/src/app.tsx CHANGED
@@ -1,9 +1,40 @@
1
+ import { Component, type ReactNode } from 'react'
1
2
  import { useAppController } from './app/controller'
2
3
  import { AppModalsLayer } from './app/modals-layer'
3
4
  import { AppScreen } from './app/screen'
4
5
  import { ThemeProvider } from './styles/theme'
6
+ import { ErrorScreen } from './ui/ErrorScreen'
5
7
 
6
- export function App() {
8
+ interface ErrorBoundaryState {
9
+ error?: unknown
10
+ hasError: boolean
11
+ retryKey: number
12
+ }
13
+
14
+ class RootErrorBoundary extends Component<
15
+ { children: (retryKey: number) => ReactNode },
16
+ ErrorBoundaryState
17
+ > {
18
+ state: ErrorBoundaryState = { hasError: false, retryKey: 0 }
19
+
20
+ static getDerivedStateFromError(error: unknown): Partial<ErrorBoundaryState> {
21
+ return { error, hasError: true }
22
+ }
23
+
24
+ private retry = () => {
25
+ this.setState(state => ({ error: undefined, hasError: false, retryKey: state.retryKey + 1 }))
26
+ }
27
+
28
+ render() {
29
+ if (this.state.hasError) {
30
+ return <ErrorScreen error={this.state.error} onRetry={this.retry} />
31
+ }
32
+
33
+ return this.props.children(this.state.retryKey)
34
+ }
35
+ }
36
+
37
+ function AppTree() {
7
38
  const { theme, screenProps, modalProps } = useAppController()
8
39
 
9
40
  return (
@@ -13,3 +44,7 @@ export function App() {
13
44
  </ThemeProvider>
14
45
  )
15
46
  }
47
+
48
+ export function App() {
49
+ return <RootErrorBoundary>{retryKey => <AppTree key={retryKey} />}</RootErrorBoundary>
50
+ }
@@ -1,7 +1,7 @@
1
1
  import { dirname } from 'path'
2
2
  import type { Config, Item } from '../types'
3
3
  import type { MultiplexerBackend } from '../multiplexer'
4
- import { getWorkspaceRef, isLiveSessionItem } from '../multiplexer/items'
4
+ import { getItemKey, getWorkspaceRef, isLiveSessionItem } from '../multiplexer/items'
5
5
  import { getGitRoot, resolveProjectSession } from '../config/session-rules'
6
6
  import { isFileItem, resolveFileSession } from '../files/target'
7
7
  import { requestShutdown } from '../util/shutdown'
@@ -38,6 +38,14 @@ export function getNextSessionName(renameTarget: string, newName: string): strin
38
38
  return trimmedName
39
39
  }
40
40
 
41
+ export function getSessionSelectionAfterRemoval(
42
+ regularSessions: Item[],
43
+ removed: Item
44
+ ): string | null {
45
+ const neighbor = regularSessions.find(session => session.title === removed.title)
46
+ return neighbor ? getItemKey(neighbor) : null
47
+ }
48
+
41
49
  export async function openProjectSession(
42
50
  projectPath: string,
43
51
  config: Config,
@@ -1,7 +1,7 @@
1
1
  import { spawn } from 'bun'
2
2
  import type { Item, Config } from '../types'
3
3
  import type { MultiplexerBackend } from '../multiplexer'
4
- import { getWorkspaceRef, isLiveSessionItem } from '../multiplexer/items'
4
+ import { getItemKey, getWorkspaceRef, isLiveSessionItem } from '../multiplexer/items'
5
5
  import { getLastSessionTarget } from '../tmux/workflows'
6
6
  import { isFileItem, resolveTypedPathTarget } from '../files/target'
7
7
  import { isGitHubURL, cloneGitHubRepo } from '../util/github'
@@ -31,6 +31,13 @@ export async function handleSelect(item: Item, config: Config | null, backend: M
31
31
  await openProjectSession(item.path, requireConfig(config), backend)
32
32
  }
33
33
 
34
+ function getKillNeighbor(item: Item, regularSessions: Item[]): Item | undefined {
35
+ const sessions = regularSessions.filter(isLiveSessionItem)
36
+ const index = sessions.findIndex(session => getItemKey(session) === getItemKey(item))
37
+ if (index < 0) return undefined
38
+ return sessions[index - 1] ?? sessions[index + 1]
39
+ }
40
+
34
41
  export async function handleKillSession(
35
42
  item: Item,
36
43
  backend: MultiplexerBackend,
@@ -38,17 +45,47 @@ export async function handleKillSession(
38
45
  onSuccess: (message: string) => void
39
46
  onError: (message: string) => void
40
47
  refreshItems: () => Promise<void>
48
+ regularSessions: Item[]
49
+ rememberedSessions: (key: string | null) => void
41
50
  }
42
51
  ) {
52
+ let closed = false
53
+
43
54
  try {
44
55
  if (!isLiveSessionItem(item)) throw new Error('Select a live session to close')
45
- await backend.close(getWorkspaceRef(item))
56
+
57
+ const target = getWorkspaceRef(item)
58
+ const neighbor = getKillNeighbor(item, callbacks.regularSessions)
59
+ const prior = await backend.current().catch(() => undefined)
60
+ const wasCurrent = prior !== undefined && prior.id === target.id
61
+
62
+ await backend.close(target)
63
+ closed = true
64
+
65
+ callbacks.rememberedSessions(neighbor ? getItemKey(neighbor) : null)
66
+
67
+ if (!wasCurrent && prior) {
68
+ const now = await backend.current().catch(() => undefined)
69
+ if (!now || now.id !== prior.id) {
70
+ await backend.open(prior)
71
+ }
72
+ } else if (wasCurrent && neighbor && isLiveSessionItem(neighbor)) {
73
+ const preferred = getWorkspaceRef(neighbor)
74
+ const now = await backend.current().catch(() => undefined)
75
+ if (!now || now.id !== preferred.id) {
76
+ await backend.open(preferred)
77
+ }
78
+ }
79
+
46
80
  callbacks.onSuccess(
47
81
  `${backend.kind === 'herdr' ? 'Workspace' : 'Session'} '${item.title}' closed`
48
82
  )
49
- await callbacks.refreshItems()
50
83
  } catch (error) {
51
84
  callbacks.onError(`Error killing session: ${error}`)
85
+ } finally {
86
+ if (closed) {
87
+ await callbacks.refreshItems().catch(() => {})
88
+ }
52
89
  }
53
90
  }
54
91
 
package/src/index.tsx CHANGED
@@ -1,10 +1,13 @@
1
1
  import { createCliRenderer } from '@opentui/core'
2
2
  import { createRoot } from '@opentui/react'
3
3
  import { App } from './app'
4
- import { initializeShutdown, requestShutdown } from './util/shutdown'
4
+ import { initializeFatalErrorHandling, initializeShutdown, requestShutdown } from './util/shutdown'
5
+
6
+ initializeFatalErrorHandling()
5
7
 
6
8
  const renderer = await createCliRenderer({
7
9
  exitOnCtrlC: false,
10
+ openConsoleOnError: false,
8
11
  })
9
12
 
10
13
  initializeShutdown(renderer)
@@ -0,0 +1,102 @@
1
+ import type { ScrollBoxRenderable } from '@opentui/core'
2
+ import { useKeyboard, useTerminalDimensions } from '@opentui/react'
3
+ import { useMemo, useRef, useState } from 'react'
4
+ import { openBrowser } from '../util/browser'
5
+ import { writeClipboard } from '../util/clipboard'
6
+ import { buildIssueUrl, describeFailure, formatDiagnostics } from '../util/errors'
7
+ import { requestShutdown } from '../util/shutdown'
8
+
9
+ interface Props {
10
+ error: unknown
11
+ onRetry: () => void
12
+ }
13
+
14
+ export function ErrorScreen({ error, onRetry }: Props) {
15
+ const { width, height } = useTerminalDimensions()
16
+ const diagnostics = useMemo(() => formatDiagnostics(error), [error])
17
+ const issueUrl = useMemo(() => buildIssueUrl(error, diagnostics), [error, diagnostics])
18
+ const failure = useMemo(() => describeFailure(error), [error])
19
+ const [status, setStatus] = useState('')
20
+ const scrollRef = useRef<ScrollBoxRenderable | null>(null)
21
+
22
+ const copy = () => {
23
+ setStatus(
24
+ writeClipboard(diagnostics)
25
+ ? 'Diagnostics copied'
26
+ : 'Clipboard unavailable; use terminal selection'
27
+ )
28
+ }
29
+
30
+ const openIssue = () => {
31
+ setStatus('Opening prefilled GitHub issue...')
32
+ void openBrowser(issueUrl).then(opened => {
33
+ setStatus(
34
+ opened
35
+ ? 'Opened prefilled issue in your browser'
36
+ : 'Could not open browser; report URL copied'
37
+ )
38
+ if (!opened) writeClipboard(issueUrl.toString())
39
+ })
40
+ }
41
+
42
+ useKeyboard(key => {
43
+ if ((key.ctrl && key.name === 'c') || key.name === 'q' || key.name === 'escape') {
44
+ void requestShutdown(1)
45
+ return
46
+ }
47
+ if (key.name === 'c') copy()
48
+ else if (key.name === 'o') openIssue()
49
+ else if (key.name === 'r') onRetry()
50
+ else if (key.name === 'up' || key.name === 'k') scrollRef.current?.scrollBy(-1)
51
+ else if (key.name === 'down' || key.name === 'j') scrollRef.current?.scrollBy(1)
52
+ else if (key.name === 'pageup') scrollRef.current?.scrollBy(-Math.max(1, height - 12))
53
+ else if (key.name === 'pagedown') scrollRef.current?.scrollBy(Math.max(1, height - 12))
54
+ else if (key.name === 'home') scrollRef.current?.scrollTo(0)
55
+ else if (key.name === 'end') scrollRef.current?.scrollTo(scrollRef.current.scrollHeight)
56
+ })
57
+
58
+ const contentWidth = Math.max(24, Math.min(100, width - 4))
59
+
60
+ return (
61
+ <box
62
+ style={{
63
+ width,
64
+ height,
65
+ backgroundColor: '#0a0a0a',
66
+ flexDirection: 'column',
67
+ alignItems: 'center',
68
+ paddingTop: 1,
69
+ paddingBottom: 1,
70
+ }}
71
+ >
72
+ <box style={{ width: contentWidth, flexDirection: 'column', flexGrow: 1, gap: 1 }}>
73
+ <text style={{ fg: '#e06c75' }}>mux-sesh crashed</text>
74
+ <text style={{ fg: '#eeeeee' }}>{failure.message || 'An unexpected error occurred.'}</text>
75
+ <text style={{ fg: '#808080' }}>
76
+ c copy diagnostics · o open GitHub issue · r retry · q/esc/ctrl+c quit
77
+ </text>
78
+ {status ? <text style={{ fg: '#7fd88f' }}>{status}</text> : null}
79
+ <box
80
+ style={{
81
+ flexGrow: 1,
82
+ minHeight: 3,
83
+ border: true,
84
+ borderStyle: 'rounded',
85
+ borderColor: '#3c3c3c',
86
+ paddingLeft: 1,
87
+ paddingRight: 1,
88
+ }}
89
+ >
90
+ <scrollbox
91
+ ref={scrollRef}
92
+ style={{ flexGrow: 1 }}
93
+ verticalScrollbarOptions={{ visible: true }}
94
+ >
95
+ <text style={{ fg: '#b0b0b0' }}>{diagnostics}</text>
96
+ </scrollbox>
97
+ </box>
98
+ <text style={{ fg: '#808080' }}>↑/↓, j/k, PgUp/PgDn scroll · GitHub opens unsubmitted</text>
99
+ </box>
100
+ </box>
101
+ )
102
+ }
@@ -5,6 +5,17 @@ interface Options {
5
5
  gotoLineEnd?: boolean
6
6
  }
7
7
 
8
+ type FocusableTextarea = Pick<TextareaRenderable, 'isDestroyed' | 'focus' | 'gotoLineEnd'>
9
+
10
+ export function focusTextarea(textarea: FocusableTextarea | null, gotoLineEnd = false): void {
11
+ if (!textarea || textarea.isDestroyed) return
12
+
13
+ textarea.focus()
14
+ if (gotoLineEnd && !textarea.isDestroyed) {
15
+ textarea.gotoLineEnd()
16
+ }
17
+ }
18
+
8
19
  export function useTextareaFocus(
9
20
  textareaRef: { current: TextareaRenderable | null },
10
21
  dependencies: readonly unknown[],
@@ -12,15 +23,7 @@ export function useTextareaFocus(
12
23
  ) {
13
24
  useEffect(() => {
14
25
  queueMicrotask(() => {
15
- const textarea = textareaRef.current
16
- if (!textarea) {
17
- return
18
- }
19
-
20
- textarea.focus()
21
- if (options.gotoLineEnd) {
22
- textarea.gotoLineEnd()
23
- }
26
+ focusTextarea(textareaRef.current, options.gotoLineEnd)
24
27
  })
25
28
  }, [options.gotoLineEnd, textareaRef, ...dependencies])
26
29
  }
@@ -0,0 +1,37 @@
1
+ export function getBrowserCommand(
2
+ url: string,
3
+ targetPlatform: NodeJS.Platform
4
+ ): string[] | undefined {
5
+ if (targetPlatform === 'darwin') return ['open', url]
6
+ if (targetPlatform === 'linux') return ['xdg-open', url]
7
+ if (targetPlatform === 'win32') return ['rundll32.exe', 'url.dll,FileProtocolHandler', url]
8
+ return undefined
9
+ }
10
+
11
+ export async function openBrowser(
12
+ input: URL | string,
13
+ targetPlatform: NodeJS.Platform = process.platform
14
+ ): Promise<boolean> {
15
+ let url: URL
16
+ try {
17
+ url = input instanceof URL ? input : new URL(input)
18
+ } catch {
19
+ return false
20
+ }
21
+
22
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return false
23
+ const command = getBrowserCommand(url.toString(), targetPlatform)
24
+ if (!command) return false
25
+
26
+ try {
27
+ const proc = Bun.spawn(command, {
28
+ stdin: 'ignore',
29
+ stdout: 'ignore',
30
+ stderr: 'ignore',
31
+ })
32
+ await proc.exited
33
+ return proc.exitCode === 0
34
+ } catch {
35
+ return false
36
+ }
37
+ }
@@ -0,0 +1,22 @@
1
+ function osc52Sequence(text: string): string {
2
+ return `\u001b]52;c;${Buffer.from(text).toString('base64')}\u0007`
3
+ }
4
+
5
+ export function buildClipboardSequence(
6
+ text: string,
7
+ env: Readonly<Record<string, string | undefined>> = process.env
8
+ ): string {
9
+ const sequence = osc52Sequence(text)
10
+ return env.TMUX ? `\u001bPtmux;\u001b${sequence}\u001b\\` : sequence
11
+ }
12
+
13
+ export function writeClipboard(text: string): boolean {
14
+ if (!text || !process.stdout.isTTY) return false
15
+
16
+ try {
17
+ process.stdout.write(buildClipboardSequence(text))
18
+ return true
19
+ } catch {
20
+ return false
21
+ }
22
+ }
@@ -0,0 +1,170 @@
1
+ import { arch, homedir, platform, release } from 'os'
2
+ import { CURRENT_VERSION } from '../update/version'
3
+
4
+ const ISSUE_URL = 'https://github.com/quiet-ghost/mux-sesh/issues/new'
5
+ export const MAX_ISSUE_URL_LENGTH = 6000
6
+ const TRUNCATION_MARKER = '\n\n... (diagnostics truncated to fit the GitHub issue URL)'
7
+
8
+ export interface FailureDetails {
9
+ message: string
10
+ stack?: string
11
+ }
12
+
13
+ export interface DiagnosticContext {
14
+ muxSeshVersion?: string
15
+ bunVersion?: string
16
+ os?: string
17
+ architecture?: string
18
+ terminal?: string
19
+ backend?: string
20
+ }
21
+
22
+ function serializeUnknown(value: unknown): string {
23
+ if (typeof value === 'string') return value
24
+ if (value === undefined) return 'undefined'
25
+ if (value === null) return 'null'
26
+
27
+ if (typeof value === 'object') {
28
+ try {
29
+ const json = JSON.stringify(value, null, 2)
30
+ if (json && json !== '{}') return json
31
+
32
+ const text = String(value)
33
+ if (text !== '[object Object]') return text
34
+ const names = Object.getOwnPropertyNames(value)
35
+ return names.length > 0 ? `Object { ${names.join(', ')} }` : 'Object (no message)'
36
+ } catch {
37
+ return 'Unexpected failure (unserializable object)'
38
+ }
39
+ }
40
+
41
+ return String(value)
42
+ }
43
+
44
+ export function describeFailure(error: unknown): FailureDetails {
45
+ if (error instanceof Error) {
46
+ return {
47
+ message: error.message || error.name || 'Unknown error',
48
+ stack: error.stack,
49
+ }
50
+ }
51
+
52
+ if (typeof error === 'object' && error !== null) {
53
+ try {
54
+ const message = Reflect.get(error, 'message')
55
+ const stack = Reflect.get(error, 'stack')
56
+ return {
57
+ message: typeof message === 'string' && message ? message : serializeUnknown(error),
58
+ stack: typeof stack === 'string' && stack ? stack : undefined,
59
+ }
60
+ } catch {
61
+ return { message: serializeUnknown(error) }
62
+ }
63
+ }
64
+
65
+ return { message: serializeUnknown(error) }
66
+ }
67
+
68
+ function replaceLiteral(value: string, literal: string, replacement: string): string {
69
+ return literal ? value.split(literal).join(replacement) : value
70
+ }
71
+
72
+ export function redactDiagnosticText(value: string): string {
73
+ let result = replaceLiteral(value, process.cwd(), '<cwd>')
74
+ result = replaceLiteral(result, process.env.HOME ?? '', '~')
75
+ result = replaceLiteral(result, homedir(), '~')
76
+ return result
77
+ }
78
+
79
+ function bounded(value: string | undefined, fallback: string): string {
80
+ const normalized = value?.trim() || fallback
81
+ return redactDiagnosticText(normalized).slice(0, 300)
82
+ }
83
+
84
+ function detectBackend(): string {
85
+ if (process.env.HERDR_ENV === '1') return 'herdr'
86
+ if (process.env.TMUX) return 'tmux'
87
+ return 'unknown'
88
+ }
89
+
90
+ function detectTerminal(): string {
91
+ if (process.env.TERM_PROGRAM) {
92
+ return [process.env.TERM_PROGRAM, process.env.TERM_PROGRAM_VERSION].filter(Boolean).join(' ')
93
+ }
94
+ if (process.env.GHOSTTY_RESOURCES_DIR) return 'ghostty'
95
+ return process.env.TERM || 'unknown'
96
+ }
97
+
98
+ export function getDiagnosticContext(
99
+ overrides: DiagnosticContext = {}
100
+ ): Required<DiagnosticContext> {
101
+ return {
102
+ muxSeshVersion: bounded(overrides.muxSeshVersion, CURRENT_VERSION),
103
+ bunVersion: bounded(overrides.bunVersion, Bun.version),
104
+ os: bounded(overrides.os, `${platform()} ${release()}`),
105
+ architecture: bounded(overrides.architecture, arch()),
106
+ terminal: bounded(overrides.terminal, detectTerminal()),
107
+ backend: bounded(overrides.backend, detectBackend()),
108
+ }
109
+ }
110
+
111
+ export function formatDiagnostics(
112
+ error: unknown,
113
+ contextOverrides: DiagnosticContext = {}
114
+ ): string {
115
+ const failure = describeFailure(error)
116
+ const context = getDiagnosticContext(contextOverrides)
117
+ const lines = ['mux-sesh crashed', '', 'Message:', redactDiagnosticText(failure.message)]
118
+
119
+ if (failure.stack) {
120
+ lines.push('', 'Stack:', redactDiagnosticText(failure.stack))
121
+ }
122
+
123
+ lines.push(
124
+ '',
125
+ 'Environment:',
126
+ `mux-sesh: ${context.muxSeshVersion}`,
127
+ `Bun: ${context.bunVersion}`,
128
+ `OS: ${context.os}`,
129
+ `Architecture: ${context.architecture}`,
130
+ `Terminal: ${context.terminal}`,
131
+ `Backend: ${context.backend}`
132
+ )
133
+
134
+ return lines.join('\n')
135
+ }
136
+
137
+ export function buildIssueUrl(error: unknown, diagnostics = formatDiagnostics(error)): URL {
138
+ const failure = describeFailure(error)
139
+ const safeDiagnostics = redactDiagnosticText(diagnostics)
140
+ const title = redactDiagnosticText(failure.message).replaceAll('\n', ' ').slice(0, 160)
141
+ const url = new URL(ISSUE_URL)
142
+ url.searchParams.set('title', `Crash: ${title}`)
143
+
144
+ const prefix = [
145
+ '## What happened?',
146
+ '',
147
+ 'mux-sesh generated this report after an unexpected crash. Please add any reproduction steps above the diagnostics.',
148
+ '',
149
+ '## Diagnostics',
150
+ '',
151
+ '```text',
152
+ ].join('\n')
153
+ const suffix = '\n```'
154
+ const setBody = (value: string) => url.searchParams.set('body', `${prefix}\n${value}${suffix}`)
155
+
156
+ setBody(safeDiagnostics)
157
+ if (url.toString().length <= MAX_ISSUE_URL_LENGTH) return url
158
+
159
+ let low = 0
160
+ let high = safeDiagnostics.length
161
+ while (low < high) {
162
+ const middle = Math.ceil((low + high) / 2)
163
+ setBody(safeDiagnostics.slice(0, middle) + TRUNCATION_MARKER)
164
+ if (url.toString().length <= MAX_ISSUE_URL_LENGTH) low = middle
165
+ else high = middle - 1
166
+ }
167
+
168
+ setBody(safeDiagnostics.slice(0, low) + TRUNCATION_MARKER)
169
+ return url
170
+ }
@@ -1,4 +1,5 @@
1
1
  import type { CliRenderer } from '@opentui/core'
2
+ import { buildIssueUrl, formatDiagnostics } from './errors'
2
3
 
3
4
  const TERMINAL_RESET_SEQUENCE = [
4
5
  '\u001b[?1000l',
@@ -9,13 +10,16 @@ const TERMINAL_RESET_SEQUENCE = [
9
10
  '\u001b[?1015l',
10
11
  '\u001b[?1049l',
11
12
  '\u001b[?2004l',
13
+ '\u001b[<u',
12
14
  '\u001b[?25h',
13
15
  ].join('')
14
16
 
15
17
  const state: {
16
18
  renderer?: CliRenderer
17
19
  exiting?: Promise<never>
18
- listenersInstalled?: boolean
20
+ exitListenerInstalled?: boolean
21
+ fatalListenersInstalled?: boolean
22
+ fatalStarted?: boolean
19
23
  } = {}
20
24
 
21
25
  function resetTerminalModes(): void {
@@ -32,42 +36,74 @@ function resetTerminalModes(): void {
32
36
 
33
37
  function destroyRenderer(): void {
34
38
  const renderer = state.renderer
35
- if (!renderer || renderer.isDestroyed) {
36
- return
37
- }
39
+ if (!renderer || renderer.isDestroyed) return
38
40
 
39
41
  try {
40
42
  renderer.useMouse = false
41
43
  renderer.disableKittyKeyboard()
42
44
  renderer.setTerminalTitle('')
43
45
  renderer.destroy()
44
- } catch (error) {
45
- console.error('Failed during renderer shutdown:', error)
46
+ } catch {
47
+ // Terminal mode reset below is the final fallback if renderer teardown fails.
46
48
  }
47
49
  }
48
50
 
51
+ function restoreTerminal(): void {
52
+ destroyRenderer()
53
+ resetTerminalModes()
54
+ }
55
+
56
+ export function initializeFatalErrorHandling(): void {
57
+ if (state.fatalListenersInstalled) return
58
+
59
+ process.on('uncaughtException', error => {
60
+ requestFatalShutdown(error, 'uncaught exception')
61
+ })
62
+ process.on('unhandledRejection', reason => {
63
+ requestFatalShutdown(reason, 'unhandled rejection')
64
+ })
65
+ state.fatalListenersInstalled = true
66
+ }
67
+
49
68
  export function initializeShutdown(renderer: CliRenderer): void {
50
69
  state.renderer = renderer
51
70
 
52
- if (state.listenersInstalled) {
53
- return
71
+ if (!state.exitListenerInstalled) {
72
+ process.once('exit', resetTerminalModes)
73
+ state.exitListenerInstalled = true
54
74
  }
75
+ }
55
76
 
56
- process.once('exit', () => {
57
- resetTerminalModes()
58
- })
77
+ export function requestFatalShutdown(error: unknown, source = 'fatal error'): void {
78
+ if (state.fatalStarted) return
79
+ state.fatalStarted = true
80
+
81
+ let diagnostics: string
82
+ let reportUrl: string
83
+ try {
84
+ diagnostics = formatDiagnostics(error)
85
+ reportUrl = buildIssueUrl(error, diagnostics).toString()
86
+ } catch {
87
+ diagnostics = `mux-sesh crashed\n\nMessage:\n${String(error)}`
88
+ reportUrl = 'https://github.com/quiet-ghost/mux-sesh/issues/new'
89
+ }
59
90
 
60
- state.listenersInstalled = true
91
+ restoreTerminal()
92
+
93
+ try {
94
+ process.stderr.write(
95
+ `\nFatal ${source}:\n\n${diagnostics}\n\nReport this crash (review before submitting):\n${reportUrl}\n`
96
+ )
97
+ } finally {
98
+ process.exit(1)
99
+ }
61
100
  }
62
101
 
63
102
  export function requestShutdown(code = 0): Promise<never> {
64
- if (state.exiting) {
65
- return state.exiting
66
- }
103
+ if (state.exiting) return state.exiting
67
104
 
68
105
  state.exiting = (async () => {
69
- destroyRenderer()
70
- resetTerminalModes()
106
+ restoreTerminal()
71
107
  process.exit(code)
72
108
  })()
73
109