start-command 0.5.2 → 0.5.3

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.
@@ -108,6 +108,14 @@ jobs:
108
108
  with:
109
109
  bun-version: latest
110
110
 
111
+ - name: Install screen (Linux)
112
+ if: runner.os == 'Linux'
113
+ run: sudo apt-get update && sudo apt-get install -y screen
114
+
115
+ - name: Install screen (macOS)
116
+ if: runner.os == 'macOS'
117
+ run: brew install screen
118
+
111
119
  - name: Install dependencies
112
120
  run: bun install
113
121
 
package/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # start-command
2
2
 
3
+ ## 0.5.3
4
+
5
+ ### Patch Changes
6
+
7
+ - 20d0c1c: Fix screen isolation not capturing output on macOS (issue #15)
8
+ - Added version detection for GNU Screen to handle differences between versions
9
+ - Screen >= 4.5.1 uses native `-L -Logfile` for log capture
10
+ - Screen < 4.5.1 (like macOS bundled 4.0.3) uses `tee` command fallback
11
+ - Added tests for version detection and -Logfile support checking
12
+ - Updated case study documentation with root cause analysis
13
+
3
14
  ## 0.5.2
4
15
 
5
16
  ### Patch Changes
@@ -15,7 +15,7 @@ The screen isolation environment does not display command output when running in
15
15
 
16
16
  - **Platform:** macOS (reported), Linux (reproduced)
17
17
  - **Package:** start-command@0.5.1
18
- - **Screen version:** Tested with GNU Screen
18
+ - **Screen version:** macOS bundled 4.0.3, Linux 4.09.01
19
19
 
20
20
  ## Timeline of Events
21
21
 
@@ -57,7 +57,42 @@ Exit code: 0
57
57
 
58
58
  ## Root Cause Analysis
59
59
 
60
- ### Investigation
60
+ ### PRIMARY ROOT CAUSE: macOS Screen Version Incompatibility
61
+
62
+ **macOS ships with GNU Screen version 4.0.3, which does NOT support the `-Logfile` option.**
63
+
64
+ The `-Logfile` option was introduced in **GNU Screen 4.5.1** (released February 2017).
65
+
66
+ | Platform | Screen Version | `-Logfile` Support |
67
+ | --------------- | -------------- | ------------------ |
68
+ | macOS (bundled) | 4.0.3 | **NO** |
69
+ | Linux (CI/Test) | 4.09.01 | YES |
70
+
71
+ The current implementation uses:
72
+
73
+ ```javascript
74
+ const screenArgs = [
75
+ '-dmS',
76
+ sessionName,
77
+ '-L',
78
+ '-Logfile',
79
+ logFile, // <-- NOT SUPPORTED on macOS bundled screen
80
+ shell,
81
+ shellArg,
82
+ command,
83
+ ];
84
+ ```
85
+
86
+ On macOS with screen 4.0.3:
87
+
88
+ 1. The `-Logfile` option is silently ignored or treated as a command argument
89
+ 2. The `-L` flag alone creates a log file named `screenlog.0` in the current directory
90
+ 3. The code tries to read from the wrong file path (`/tmp/screen-output-*.log`)
91
+ 4. Result: No output is captured or displayed
92
+
93
+ ### Secondary Root Cause: TTY Requirement
94
+
95
+ When TTY is available, the code attempts attached mode which fails:
61
96
 
62
97
  1. **TTY Requirement**: The GNU Screen command requires a connected terminal (TTY/PTY) to run in attached mode.
63
98
 
@@ -76,8 +111,21 @@ Exit code: 0
76
111
  Testing revealed:
77
112
 
78
113
  - `process.stdin.isTTY` and `process.stdout.isTTY` are `undefined` when running from Node.js
79
- - Detached mode with logging (`screen -dmS ... -L -Logfile ...`) captures output correctly
114
+ - Detached mode with logging (`screen -dmS ... -L -Logfile ...`) captures output correctly **on Linux only**
80
115
  - Using `script -q -c "screen ..." /dev/null` can provide a PTY but includes terminal escape codes
116
+ - On macOS with screen 4.0.3, the `-Logfile` option is unknown
117
+
118
+ ### Version Check Evidence
119
+
120
+ ```bash
121
+ # Linux (works)
122
+ $ screen --version
123
+ Screen version 4.09.01 (GNU) 20-Aug-23
124
+
125
+ # macOS bundled (broken)
126
+ $ screen --version
127
+ Screen version 4.00.03 (FAU) 23-Oct-06
128
+ ```
81
129
 
82
130
  ### Comparison with Docker
83
131
 
@@ -87,70 +135,67 @@ Docker isolation works because:
87
135
  2. Docker spawns an isolated container that manages its own pseudo-terminal
88
136
  3. The command output flows through Docker's I/O handling
89
137
 
90
- ## Solution Options
91
-
92
- ### Option 1: Use Script Command for PTY Allocation (Recommended)
93
-
94
- Wrap the screen command with `script -q -c "command" /dev/null` to allocate a pseudo-terminal.
95
-
96
- **Pros:**
97
-
98
- - Provides a real PTY that screen requires
99
- - Works across Linux/macOS
100
- - Maintains attached behavior
101
-
102
- **Cons:**
103
-
104
- - Adds terminal escape codes to output
105
- - Requires `script` command to be available
106
-
107
- ### Option 2: Switch to Detached Mode with Log Capture
108
-
109
- Run screen in detached mode (`-dmS`) with logging enabled (`-L -Logfile`), wait for completion, then display the log.
110
-
111
- **Pros:**
112
-
113
- - Clean output without escape codes
114
- - Reliable across platforms
115
- - Captures full command output
116
-
117
- **Cons:**
118
-
119
- - Not truly "attached" - user can't interact with the process
120
- - Requires polling or waiting for completion
121
-
122
- ### Option 3: Hybrid Approach (Chosen Solution)
123
-
124
- For attached mode:
125
-
126
- 1. Check if running in a TTY (`process.stdin.isTTY`)
127
- 2. If TTY available: Use standard screen spawn with `stdio: 'inherit'`
128
- 3. If no TTY: Use `script` command to allocate PTY
129
-
130
- For detached mode:
131
-
132
- - Use existing implementation with `-dmS` flags
133
-
134
- ## Implementation
138
+ ## Solution: Version Detection with Fallback
139
+
140
+ ### Approach
141
+
142
+ 1. **Detect screen version** at runtime
143
+ 2. **Version >= 4.5.1**: Use `-L -Logfile` approach
144
+ 3. **Version < 4.5.1**: Use output redirection (`tee`) approach within the command
145
+
146
+ ### Implementation
147
+
148
+ ```javascript
149
+ function getScreenVersion() {
150
+ try {
151
+ const output = execSync('screen --version', { encoding: 'utf8' });
152
+ const match = output.match(/(\d+)\.(\d+)\.(\d+)/);
153
+ if (match) {
154
+ return {
155
+ major: parseInt(match[1]),
156
+ minor: parseInt(match[2]),
157
+ patch: parseInt(match[3]),
158
+ };
159
+ }
160
+ } catch {
161
+ return null;
162
+ }
163
+ return null;
164
+ }
165
+
166
+ function supportsLogfileOption() {
167
+ const version = getScreenVersion();
168
+ if (!version) return false;
169
+ // -Logfile was added in 4.5.1
170
+ return (
171
+ version.major > 4 ||
172
+ (version.major === 4 && version.minor > 5) ||
173
+ (version.major === 4 && version.minor === 5 && version.patch >= 1)
174
+ );
175
+ }
176
+ ```
135
177
 
136
- The fix modifies `src/lib/isolation.js` to:
178
+ For older versions, wrap command with tee:
137
179
 
138
- 1. Check for TTY availability before spawning screen
139
- 2. Use `script` command as PTY allocator when no TTY is available
140
- 3. Clean terminal escape codes from output when using script wrapper
141
- 4. Maintain compatibility with existing detached mode
180
+ ```javascript
181
+ const wrappedCommand = `(${command}) 2>&1 | tee "${logFile}"`;
182
+ const screenArgs = ['-dmS', sessionName, shell, shellArg, wrappedCommand];
183
+ ```
142
184
 
143
185
  ## Testing Strategy
144
186
 
145
- 1. **Unit tests**: Test TTY detection logic
146
- 2. **Integration tests**: Test screen isolation in detached mode
147
- 3. **Environment tests**: Test behavior with and without TTY
187
+ 1. **Unit tests**: Test version detection logic
188
+ 2. **Unit tests**: Test screen version comparison
189
+ 3. **Integration tests**: Test output capture for both code paths
190
+ 4. **Regression tests**: Verify existing tests still pass
191
+ 5. **CI tests**: Ensure output is verified in assertions (not just exit code)
148
192
 
149
193
  ## References
150
194
 
195
+ - [GNU Screen v.4.5.1 changelog](https://lists.gnu.org/archive/html/info-gnu/2017-02/msg00000.html) - Introduction of `-Logfile` option
196
+ - [GitHub Issue: RHEL7 screen does not know the Logfile option](https://github.com/distributed-system-analysis/pbench/issues/1558)
197
+ - [How to install GNU Screen on OS X using Homebrew](https://gist.github.com/bigeasy/2327150)
151
198
  - [GNU Screen Manual](https://www.gnu.org/software/screen/manual/screen.html)
152
- - [Stack Overflow: Must be connected to terminal](https://stackoverflow.com/questions/tagged/gnu-screen+tty)
153
- - [node-pty for PTY allocation](https://github.com/microsoft/node-pty)
154
199
  - [script command man page](https://man7.org/linux/man-pages/man1/script.1.html)
155
200
 
156
201
  ## Appendix: Test Logs
@@ -160,3 +205,4 @@ See accompanying log files:
160
205
  - `test-output-1.log` - Initial reproduction
161
206
  - `screen-modes-test.log` - Screen modes investigation
162
207
  - `screen-attached-approaches.log` - Solution approaches testing
208
+ - `test-screen-logfile.js` - Version compatibility testing
@@ -0,0 +1,286 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Experiment to test screen's logfile capture functionality
4
+ * to understand the root cause of issue #15
5
+ */
6
+
7
+ const { execSync, spawnSync } = require('child_process');
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const os = require('os');
11
+
12
+ async function sleep(ms) {
13
+ return new Promise((resolve) => setTimeout(resolve, ms));
14
+ }
15
+
16
+ async function testScreenLogfile() {
17
+ console.log('=== Testing Screen Logfile Capture ===\n');
18
+
19
+ // Test environment info
20
+ console.log('Environment:');
21
+ console.log(` Platform: ${process.platform}`);
22
+ console.log(` Node: ${process.version}`);
23
+ try {
24
+ const screenVersion = execSync('screen --version', {
25
+ encoding: 'utf8',
26
+ }).trim();
27
+ console.log(` Screen: ${screenVersion}`);
28
+ } catch (e) {
29
+ console.log(` Screen: Not available - ${e.message}`);
30
+ return;
31
+ }
32
+ console.log(
33
+ ` TTY: stdin=${process.stdin.isTTY}, stdout=${process.stdout.isTTY}`
34
+ );
35
+ console.log('');
36
+
37
+ // Test 1: Basic logfile capture with -L -Logfile
38
+ console.log('Test 1: Basic -L -Logfile capture');
39
+ const sessionName1 = `logtest-${Date.now()}`;
40
+ const logFile1 = path.join(os.tmpdir(), `screen-log-${sessionName1}.log`);
41
+
42
+ try {
43
+ // Run screen with logging
44
+ const screenArgs = [
45
+ '-dmS',
46
+ sessionName1,
47
+ '-L',
48
+ '-Logfile',
49
+ logFile1,
50
+ '/bin/sh',
51
+ '-c',
52
+ 'echo "TESTOUTPUT123"',
53
+ ];
54
+
55
+ console.log(` Command: screen ${screenArgs.join(' ')}`);
56
+
57
+ execSync(`screen ${screenArgs.map((a) => `"${a}"`).join(' ')}`, {
58
+ stdio: 'inherit',
59
+ });
60
+
61
+ // Wait for completion (screen runs command and exits)
62
+ await sleep(500);
63
+
64
+ // Check if session still exists
65
+ let sessionExists = false;
66
+ try {
67
+ const sessions = execSync('screen -ls', {
68
+ encoding: 'utf8',
69
+ stdio: ['pipe', 'pipe', 'pipe'],
70
+ });
71
+ sessionExists = sessions.includes(sessionName1);
72
+ } catch {
73
+ // screen -ls returns non-zero if no sessions
74
+ }
75
+ console.log(` Session exists after 500ms: ${sessionExists}`);
76
+
77
+ // Check log file
78
+ if (fs.existsSync(logFile1)) {
79
+ const content = fs.readFileSync(logFile1, 'utf8');
80
+ console.log(` Log file exists: YES`);
81
+ console.log(` Log file size: ${content.length} bytes`);
82
+ console.log(
83
+ ` Log content: "${content.trim().replace(/\n/g, '\\n').slice(0, 200)}"`
84
+ );
85
+ console.log(
86
+ ` Contains expected output: ${content.includes('TESTOUTPUT123') ? 'YES ✓' : 'NO ✗'}`
87
+ );
88
+ fs.unlinkSync(logFile1);
89
+ } else {
90
+ console.log(` Log file exists: NO ✗`);
91
+ console.log(` Expected path: ${logFile1}`);
92
+ }
93
+
94
+ // Cleanup
95
+ try {
96
+ execSync(`screen -S ${sessionName1} -X quit 2>/dev/null`);
97
+ } catch {}
98
+ } catch (e) {
99
+ console.log(` Error: ${e.message}`);
100
+ }
101
+ console.log('');
102
+
103
+ // Test 2: Test with sleep to ensure buffer flush
104
+ console.log('Test 2: With sleep for buffer flush');
105
+ const sessionName2 = `logtest2-${Date.now()}`;
106
+ const logFile2 = path.join(os.tmpdir(), `screen-log-${sessionName2}.log`);
107
+
108
+ try {
109
+ const screenArgs = [
110
+ '-dmS',
111
+ sessionName2,
112
+ '-L',
113
+ '-Logfile',
114
+ logFile2,
115
+ '/bin/sh',
116
+ '-c',
117
+ 'echo "FLUSHED_OUTPUT" && sleep 0.5',
118
+ ];
119
+
120
+ console.log(` Command: screen ${screenArgs.join(' ')}`);
121
+
122
+ execSync(`screen ${screenArgs.map((a) => `"${a}"`).join(' ')}`, {
123
+ stdio: 'inherit',
124
+ });
125
+
126
+ // Wait longer for flush (default is 10 seconds)
127
+ await sleep(1500);
128
+
129
+ // Check log file
130
+ if (fs.existsSync(logFile2)) {
131
+ const content = fs.readFileSync(logFile2, 'utf8');
132
+ console.log(` Log file exists: YES`);
133
+ console.log(` Log file size: ${content.length} bytes`);
134
+ console.log(
135
+ ` Contains expected output: ${content.includes('FLUSHED_OUTPUT') ? 'YES ✓' : 'NO ✗'}`
136
+ );
137
+ fs.unlinkSync(logFile2);
138
+ } else {
139
+ console.log(` Log file exists: NO ✗`);
140
+ }
141
+
142
+ // Cleanup
143
+ try {
144
+ execSync(`screen -S ${sessionName2} -X quit 2>/dev/null`);
145
+ } catch {}
146
+ } catch (e) {
147
+ console.log(` Error: ${e.message}`);
148
+ }
149
+ console.log('');
150
+
151
+ // Test 3: Alternative - using hardstatus/output redirection
152
+ console.log('Test 3: Direct command output capture (no screen logging)');
153
+ const sessionName3 = `logtest3-${Date.now()}`;
154
+ const logFile3 = path.join(os.tmpdir(), `screen-log-${sessionName3}.log`);
155
+
156
+ try {
157
+ // Run command through screen but capture output to file within the command
158
+ const command = `echo "DIRECT_CAPTURE" | tee ${logFile3}`;
159
+ const screenArgs = ['-dmS', sessionName3, '/bin/sh', '-c', command];
160
+
161
+ console.log(` Command: screen ${screenArgs.join(' ')}`);
162
+
163
+ execSync(`screen ${screenArgs.map((a) => `"${a}"`).join(' ')}`, {
164
+ stdio: 'inherit',
165
+ });
166
+
167
+ await sleep(500);
168
+
169
+ // Check log file
170
+ if (fs.existsSync(logFile3)) {
171
+ const content = fs.readFileSync(logFile3, 'utf8');
172
+ console.log(` Log file exists: YES`);
173
+ console.log(
174
+ ` Contains expected output: ${content.includes('DIRECT_CAPTURE') ? 'YES ✓' : 'NO ✗'}`
175
+ );
176
+ fs.unlinkSync(logFile3);
177
+ } else {
178
+ console.log(` Log file exists: NO ✗`);
179
+ }
180
+
181
+ // Cleanup
182
+ try {
183
+ execSync(`screen -S ${sessionName3} -X quit 2>/dev/null`);
184
+ } catch {}
185
+ } catch (e) {
186
+ console.log(` Error: ${e.message}`);
187
+ }
188
+ console.log('');
189
+
190
+ // Test 4: Script command approach
191
+ console.log('Test 4: Using script command to capture output');
192
+ const sessionName4 = `logtest4-${Date.now()}`;
193
+ const logFile4 = path.join(os.tmpdir(), `script-log-${sessionName4}.log`);
194
+
195
+ try {
196
+ // Use script to capture output
197
+ const result = spawnSync(
198
+ 'script',
199
+ [
200
+ '-q',
201
+ logFile4,
202
+ '-c',
203
+ `screen -dmS ${sessionName4} /bin/sh -c "echo SCRIPT_CAPTURE"`,
204
+ ],
205
+ {
206
+ stdio: ['inherit', 'pipe', 'pipe'],
207
+ timeout: 5000,
208
+ }
209
+ );
210
+
211
+ await sleep(500);
212
+
213
+ console.log(` Exit code: ${result.status}`);
214
+
215
+ // Check log file
216
+ if (fs.existsSync(logFile4)) {
217
+ const content = fs.readFileSync(logFile4, 'utf8');
218
+ console.log(` Log file exists: YES`);
219
+ console.log(` Log file size: ${content.length} bytes`);
220
+ fs.unlinkSync(logFile4);
221
+ } else {
222
+ console.log(` Log file exists: NO`);
223
+ }
224
+
225
+ // Cleanup
226
+ try {
227
+ execSync(`screen -S ${sessionName4} -X quit 2>/dev/null`);
228
+ } catch {}
229
+ } catch (e) {
230
+ console.log(` Error: ${e.message}`);
231
+ }
232
+ console.log('');
233
+
234
+ // Test 5: Test with -T option (terminal type)
235
+ console.log('Test 5: With explicit terminal type -T xterm');
236
+ const sessionName5 = `logtest5-${Date.now()}`;
237
+ const logFile5 = path.join(os.tmpdir(), `screen-log-${sessionName5}.log`);
238
+
239
+ try {
240
+ const screenArgs = [
241
+ '-T',
242
+ 'xterm',
243
+ '-dmS',
244
+ sessionName5,
245
+ '-L',
246
+ '-Logfile',
247
+ logFile5,
248
+ '/bin/sh',
249
+ '-c',
250
+ 'echo "TERMINAL_OUTPUT" && sleep 0.3',
251
+ ];
252
+
253
+ console.log(` Command: screen ${screenArgs.join(' ')}`);
254
+
255
+ execSync(`screen ${screenArgs.map((a) => `"${a}"`).join(' ')}`, {
256
+ stdio: 'inherit',
257
+ });
258
+
259
+ await sleep(1000);
260
+
261
+ // Check log file
262
+ if (fs.existsSync(logFile5)) {
263
+ const content = fs.readFileSync(logFile5, 'utf8');
264
+ console.log(` Log file exists: YES`);
265
+ console.log(` Log file size: ${content.length} bytes`);
266
+ console.log(
267
+ ` Contains expected output: ${content.includes('TERMINAL_OUTPUT') ? 'YES ✓' : 'NO ✗'}`
268
+ );
269
+ fs.unlinkSync(logFile5);
270
+ } else {
271
+ console.log(` Log file exists: NO ✗`);
272
+ }
273
+
274
+ // Cleanup
275
+ try {
276
+ execSync(`screen -S ${sessionName5} -X quit 2>/dev/null`);
277
+ } catch {}
278
+ } catch (e) {
279
+ console.log(` Error: ${e.message}`);
280
+ }
281
+ console.log('');
282
+
283
+ console.log('=== Tests Complete ===');
284
+ }
285
+
286
+ testScreenLogfile();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "start-command",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "Gamification of coding, execute any command with ability to auto-report issues on GitHub",
5
5
  "main": "index.js",
6
6
  "bin": {
@@ -20,6 +20,83 @@ const setTimeout = globalThis.setTimeout;
20
20
  const DEBUG =
21
21
  process.env.START_DEBUG === '1' || process.env.START_DEBUG === 'true';
22
22
 
23
+ // Cache for screen version detection
24
+ let cachedScreenVersion = null;
25
+ let screenVersionChecked = false;
26
+
27
+ /**
28
+ * Get the installed screen version
29
+ * @returns {{major: number, minor: number, patch: number}|null} Version object or null if detection fails
30
+ */
31
+ function getScreenVersion() {
32
+ if (screenVersionChecked) {
33
+ return cachedScreenVersion;
34
+ }
35
+
36
+ screenVersionChecked = true;
37
+
38
+ try {
39
+ const output = execSync('screen --version', {
40
+ encoding: 'utf8',
41
+ stdio: ['pipe', 'pipe', 'pipe'],
42
+ });
43
+ // Match patterns like "4.09.01", "4.00.03", "4.5.1"
44
+ const match = output.match(/(\d+)\.(\d+)\.(\d+)/);
45
+ if (match) {
46
+ cachedScreenVersion = {
47
+ major: parseInt(match[1], 10),
48
+ minor: parseInt(match[2], 10),
49
+ patch: parseInt(match[3], 10),
50
+ };
51
+
52
+ if (DEBUG) {
53
+ console.log(
54
+ `[DEBUG] Detected screen version: ${cachedScreenVersion.major}.${cachedScreenVersion.minor}.${cachedScreenVersion.patch}`
55
+ );
56
+ }
57
+
58
+ return cachedScreenVersion;
59
+ }
60
+ } catch {
61
+ if (DEBUG) {
62
+ console.log('[DEBUG] Could not detect screen version');
63
+ }
64
+ }
65
+
66
+ return null;
67
+ }
68
+
69
+ /**
70
+ * Check if screen supports the -Logfile option
71
+ * The -Logfile option was introduced in GNU Screen 4.5.1
72
+ * @returns {boolean} True if -Logfile is supported
73
+ */
74
+ function supportsLogfileOption() {
75
+ const version = getScreenVersion();
76
+ if (!version) {
77
+ // If we can't detect version, assume older version and use fallback
78
+ return false;
79
+ }
80
+
81
+ // -Logfile was added in 4.5.1
82
+ // Compare: version >= 4.5.1
83
+ if (version.major > 4) {
84
+ return true;
85
+ }
86
+ if (version.major < 4) {
87
+ return false;
88
+ }
89
+ // major === 4
90
+ if (version.minor > 5) {
91
+ return true;
92
+ }
93
+ if (version.minor < 5) {
94
+ return false;
95
+ }
96
+ // minor === 5
97
+ return version.patch >= 1;
98
+ }
99
+
23
100
  /**
24
101
  * Check if a command is available on the system
25
102
  * @param {string} command - Command to check
@@ -58,6 +135,11 @@ function hasTTY() {
58
135
  /**
59
136
  * Run command in GNU Screen using detached mode with log capture
60
137
  * This is a workaround for environments without TTY
138
+ *
139
+ * Supports two methods based on screen version:
140
+ * - screen >= 4.5.1: Uses -L -Logfile option for native log capture
141
+ * - screen < 4.5.1: Uses tee command within the wrapped command for output capture
142
+ *
61
143
  * @param {string} command - Command to execute
62
144
  * @param {string} sessionName - Session name
63
145
  * @param {object} shellInfo - Shell info from getShell()
@@ -67,25 +149,45 @@ function runScreenWithLogCapture(command, sessionName, shellInfo) {
67
149
  const { shell, shellArg } = shellInfo;
68
150
  const logFile = path.join(os.tmpdir(), `screen-output-${sessionName}.log`);
69
151
 
152
+ // Check if screen supports -Logfile option (added in 4.5.1)
153
+ const useNativeLogging = supportsLogfileOption();
154
+
70
155
  return new Promise((resolve) => {
71
156
  try {
72
- // Use detached mode with logging to capture output
73
- // screen -dmS <session> -L -Logfile <logfile> <shell> -c '<command>'
74
- const screenArgs = [
75
- '-dmS',
76
- sessionName,
77
- '-L',
78
- '-Logfile',
79
- logFile,
80
- shell,
81
- shellArg,
82
- command,
83
- ];
157
+ let screenArgs;
158
+ let effectiveCommand = command;
159
+
160
+ if (useNativeLogging) {
161
+ // Modern screen (>= 4.5.1): Use -L -Logfile option for native log capture
162
+ // screen -dmS <session> -L -Logfile <logfile> <shell> -c '<command>'
163
+ screenArgs = [
164
+ '-dmS',
165
+ sessionName,
166
+ '-L',
167
+ '-Logfile',
168
+ logFile,
169
+ shell,
170
+ shellArg,
171
+ command,
172
+ ];
84
173
 
85
- if (DEBUG) {
86
- console.log(
87
- `[DEBUG] Running screen with log capture: screen ${screenArgs.join(' ')}`
88
- );
174
+ if (DEBUG) {
175
+ console.log(
176
+ `[DEBUG] Running screen with native log capture (-Logfile): screen ${screenArgs.join(' ')}`
177
+ );
178
+ }
179
+ } else {
180
+ // Older screen (< 4.5.1, e.g., macOS bundled 4.0.3): Use tee fallback
181
+ // Wrap the command to capture output using tee
182
+ // The parentheses ensure proper grouping of the command and its stderr
183
+ effectiveCommand = `(${command}) 2>&1 | tee "${logFile}"`;
184
+ screenArgs = ['-dmS', sessionName, shell, shellArg, effectiveCommand];
185
+
186
+ if (DEBUG) {
187
+ console.log(
188
+ `[DEBUG] Running screen with tee fallback (older screen version): screen ${screenArgs.join(' ')}`
189
+ );
190
+ }
89
191
  }
90
192
 
91
193
  execSync(`screen ${screenArgs.map((a) => `"${a}"`).join(' ')}`, {
@@ -665,6 +767,14 @@ function createLogPath(environment) {
665
767
  return path.join(logDir, logFilename);
666
768
  }
667
769
 
770
+ /**
771
+ * Reset screen version cache (useful for testing)
772
+ */
773
+ function resetScreenVersionCache() {
774
+ cachedScreenVersion = null;
775
+ screenVersionChecked = false;
776
+ }
777
+
668
778
  module.exports = {
669
779
  isCommandAvailable,
670
780
  hasTTY,
@@ -681,4 +791,8 @@ module.exports = {
681
791
  writeLogFile,
682
792
  getLogDir,
683
793
  createLogPath,
794
+ // Export screen version utilities for testing and debugging
795
+ getScreenVersion,
796
+ supportsLogfileOption,
797
+ resetScreenVersionCache,
684
798
  };
@@ -7,7 +7,13 @@
7
7
 
8
8
  const { describe, it } = require('node:test');
9
9
  const assert = require('assert');
10
- const { isCommandAvailable, hasTTY } = require('../src/lib/isolation');
10
+ const {
11
+ isCommandAvailable,
12
+ hasTTY,
13
+ getScreenVersion,
14
+ supportsLogfileOption,
15
+ resetScreenVersionCache,
16
+ } = require('../src/lib/isolation');
11
17
 
12
18
  describe('Isolation Module', () => {
13
19
  describe('isCommandAvailable', () => {
@@ -77,6 +83,92 @@ describe('Isolation Module', () => {
77
83
  assert.ok(typeof result === 'boolean');
78
84
  });
79
85
  });
86
+
87
+ describe('getScreenVersion', () => {
88
+ it('should return version object or null', () => {
89
+ // Reset cache before testing
90
+ resetScreenVersionCache();
91
+ const version = getScreenVersion();
92
+
93
+ if (isCommandAvailable('screen')) {
94
+ // If screen is installed, we should get a version object
95
+ assert.ok(
96
+ version !== null,
97
+ 'Should return version object when screen is installed'
98
+ );
99
+ assert.ok(typeof version.major === 'number', 'major should be number');
100
+ assert.ok(typeof version.minor === 'number', 'minor should be number');
101
+ assert.ok(typeof version.patch === 'number', 'patch should be number');
102
+ console.log(
103
+ ` Detected screen version: ${version.major}.${version.minor}.${version.patch}`
104
+ );
105
+ } else {
106
+ // If screen is not installed, we should get null
107
+ assert.strictEqual(
108
+ version,
109
+ null,
110
+ 'Should return null when screen is not installed'
111
+ );
112
+ console.log(' screen not installed, version is null');
113
+ }
114
+ });
115
+
116
+ it('should cache the version result', () => {
117
+ // Reset cache first
118
+ resetScreenVersionCache();
119
+
120
+ // Call twice
121
+ const version1 = getScreenVersion();
122
+ const version2 = getScreenVersion();
123
+
124
+ // Results should be identical (same object reference if cached)
125
+ assert.strictEqual(
126
+ version1,
127
+ version2,
128
+ 'Cached version should return same object'
129
+ );
130
+ });
131
+ });
132
+
133
+ describe('supportsLogfileOption', () => {
134
+ it('should return boolean', () => {
135
+ // Reset cache before testing
136
+ resetScreenVersionCache();
137
+ const result = supportsLogfileOption();
138
+ assert.ok(typeof result === 'boolean', 'Should return a boolean');
139
+ console.log(` supportsLogfileOption: ${result}`);
140
+ });
141
+
142
+ it('should return true for screen >= 4.5.1', () => {
143
+ // This tests the logic by checking the current system
144
+ resetScreenVersionCache();
145
+ const version = getScreenVersion();
146
+
147
+ if (version) {
148
+ const expected =
149
+ version.major > 4 ||
150
+ (version.major === 4 && version.minor > 5) ||
151
+ (version.major === 4 && version.minor === 5 && version.patch >= 1);
152
+ const result = supportsLogfileOption();
153
+ assert.strictEqual(
154
+ result,
155
+ expected,
156
+ `Version ${version.major}.${version.minor}.${version.patch} should ${expected ? 'support' : 'not support'} -Logfile`
157
+ );
158
+ console.log(
159
+ ` Version ${version.major}.${version.minor}.${version.patch}: -Logfile supported = ${result}`
160
+ );
161
+ } else {
162
+ // If no version detected, should return false (fallback to safe method)
163
+ const result = supportsLogfileOption();
164
+ assert.strictEqual(
165
+ result,
166
+ false,
167
+ 'Should return false when version cannot be detected'
168
+ );
169
+ }
170
+ });
171
+ });
80
172
  });
81
173
 
82
174
  describe('Isolation Runner Error Handling', () => {