Skip to content

Commit 0f796ab

Browse files
committed
Potentially fix OSC detection by running inline
1 parent 08145ab commit 0f796ab

File tree

3 files changed

+69
-47
lines changed

3 files changed

+69
-47
lines changed

cli/src/index.tsx

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,13 @@ import { initializeThemeStore } from './state/theme-store'
3939
const require = createRequire(import.meta.url)
4040

4141
const INTERNAL_OSC_FLAG = '--internal-osc-detect'
42+
const OSC_DEBUG_ENABLED = process.env.CODEBUFF_OSC_DEBUG === '1'
43+
44+
function logOscDebug(message: string, data?: Record<string, unknown>) {
45+
if (!OSC_DEBUG_ENABLED) return
46+
const payload = data ? ` ${JSON.stringify(data)}` : ''
47+
console.error(`[osc:subprocess] ${message}${payload}`)
48+
}
4249

4350
function isOscDetectionRun(): boolean {
4451
return process.argv.includes(INTERNAL_OSC_FLAG)
@@ -48,23 +55,35 @@ async function runOscDetectionSubprocess(): Promise<void> {
4855
// Set env vars to keep subprocess quiet
4956
process.env.__INTERNAL_OSC_DETECT = '1'
5057
process.env.CODEBUFF_GITHUB_ACTIONS = 'true'
58+
if (process.env.CODEBUFF_OSC_DEBUG === undefined) {
59+
process.env.CODEBUFF_OSC_DEBUG = '1'
60+
}
61+
logOscDebug('Starting OSC detection flag run')
5162

5263
// Avoid importing logger or other modules that produce output
5364
const { detectTerminalTheme, terminalSupportsOSC } = await import(
5465
'./utils/terminal-color-detection'
5566
)
5667

57-
if (!terminalSupportsOSC()) {
68+
const oscSupported = terminalSupportsOSC()
69+
logOscDebug('terminalSupportsOSC result', { oscSupported })
70+
71+
if (!oscSupported) {
72+
logOscDebug('Terminal does not support OSC queries, returning null theme')
5873
console.log(JSON.stringify({ theme: null }))
5974
await new Promise((resolve) => setImmediate(resolve))
6075
process.exit(0)
6176
}
6277

6378
try {
6479
const theme = await detectTerminalTheme()
80+
logOscDebug('detectTerminalTheme resolved', { theme })
6581
console.log(JSON.stringify({ theme }))
6682
await new Promise((resolve) => setImmediate(resolve))
67-
} catch {
83+
} catch (error) {
84+
logOscDebug('detectTerminalTheme threw', {
85+
error: error instanceof Error ? error.message : String(error),
86+
})
6887
console.log(JSON.stringify({ theme: null }))
6988
await new Promise((resolve) => setImmediate(resolve))
7089
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import type { ReadStream } from 'tty'
2+
3+
let lockDepth = 0
4+
5+
function getReadableStdin(): ReadStream | null {
6+
const stdin = process.stdin as ReadStream | undefined
7+
if (!stdin) return null
8+
if (typeof stdin.pause !== 'function' || typeof stdin.resume !== 'function') {
9+
return null
10+
}
11+
return stdin
12+
}
13+
14+
export async function withTerminalInputGuard<T>(
15+
work: () => Promise<T> | T,
16+
): Promise<T> {
17+
const stdin = getReadableStdin()
18+
lockDepth += 1
19+
const manageInput = stdin && lockDepth === 1
20+
if (manageInput && stdin) {
21+
stdin.pause()
22+
}
23+
24+
try {
25+
return await work()
26+
} finally {
27+
lockDepth = Math.max(0, lockDepth - 1)
28+
if (manageInput && stdin && lockDepth === 0) {
29+
stdin.resume()
30+
}
31+
}
32+
}

cli/src/utils/theme-system.ts

Lines changed: 16 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { dirname, join } from 'path'
44

55
import { detectShell } from './detect-shell'
66
import { logger } from './logger'
7+
import { detectTerminalTheme } from './terminal-color-detection'
8+
import { withTerminalInputGuard } from './terminal-input-guard'
79

810
import type { MarkdownPalette } from './markdown-renderer'
911
import type {
@@ -1143,9 +1145,8 @@ process.on('SIGUSR2', () => {
11431145
* Initialize OSC theme detection with a one-time check
11441146
* Runs in a separate process to avoid blocking and hiding I/O from user
11451147
*/
1146-
export async function initializeOSCDetection(): Promise<void> {
1147-
// Don't await - fire and forget
1148-
detectOSCInBackground()
1148+
export function initializeOSCDetection(): void {
1149+
void detectOSCInBackground()
11491150
}
11501151

11511152
/**
@@ -1158,48 +1159,18 @@ async function detectOSCInBackground() {
11581159
return
11591160
}
11601161

1161-
try {
1162-
// Spawn self with internal flag to run OSC detection
1163-
// Use stored CLI entry point path
1164-
const cliEntryPoint = (globalThis as any).__CLI_ENTRY_POINT || Bun.main
1165-
const proc = Bun.spawn({
1166-
cmd: [process.execPath, cliEntryPoint, '--internal-osc-detect'],
1167-
stdio: ['ignore', 'pipe', 'ignore'], // pipe stdout only, ignore stdin/stderr
1168-
timeout: 2000, // 2 second timeout to allow for module loading
1169-
env: {
1170-
...process.env,
1171-
__INTERNAL_OSC_DETECT: '1', // Suppress console output
1172-
},
1173-
})
1174-
1175-
// Read result from stdout
1176-
const text = await new Response(proc.stdout).text()
1177-
1178-
// Extract JSON from output (ignore any console.log noise)
1179-
// Look for the last line that starts with { or contains "theme"
1180-
const lines = text.trim().split('\n')
1181-
let jsonLine = ''
1182-
for (let i = lines.length - 1; i >= 0; i--) {
1183-
const line = lines[i].trim()
1184-
if (line.startsWith('{') && line.includes('theme')) {
1185-
jsonLine = line
1186-
break
1162+
await withTerminalInputGuard(async () => {
1163+
try {
1164+
const theme = await detectTerminalTheme()
1165+
if (theme) {
1166+
oscDetectedTheme = theme
1167+
recomputeSystemTheme('osc-inline')
11871168
}
1169+
} catch (error) {
1170+
logger.warn(
1171+
{ error: error instanceof Error ? error.message : String(error) },
1172+
'OSC detection failed',
1173+
)
11881174
}
1189-
1190-
if (!jsonLine) return
1191-
1192-
const result = JSON.parse(jsonLine) as { theme: 'dark' | 'light' | null }
1193-
1194-
if (result.theme) {
1195-
oscDetectedTheme = result.theme
1196-
// Trigger theme recomputation to apply OSC-detected theme
1197-
recomputeSystemTheme('osc-background')
1198-
}
1199-
} catch (error) {
1200-
logger.warn(
1201-
{ error: error instanceof Error ? error.message : String(error) },
1202-
'OSC detection failed',
1203-
)
1204-
}
1175+
})
12051176
}

0 commit comments

Comments
 (0)