Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions packages/cli/src/config/extensions/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -560,6 +560,19 @@ export interface DownloadOptions {
headers?: Record<string, string>;
}

function cleanupAfterFileClosed(
file: fs.WriteStream,
err: Error,
cleanupAndReject: (err: Error) => void,
): void {
if (file.closed) {
cleanupAndReject(err);
return;
}
file.once('close', () => cleanupAndReject(err));
file.destroy();
}

export async function downloadFile(
url: string,
dest: string,
Expand All @@ -577,7 +590,14 @@ export async function downloadFile(
}

return new Promise((resolve, reject) => {
let settled = false;

const cleanupAndReject = (error: Error) => {
if (settled) {
return;
}
settled = true;

// Try to clean up the partial file, but don't mask the original error
fs.unlink(dest, (unlinkErr) => {
if (unlinkErr && unlinkErr.code !== 'ENOENT') {
Expand Down Expand Up @@ -619,17 +639,21 @@ export async function downloadFile(
// Handle file write errors
file.on('error', (err) => {
res.destroy();
cleanupAndReject(err);
cleanupAfterFileClosed(file, err, cleanupAndReject);
});

// Handle response stream errors
res.on('error', (err) => {
file.destroy();
cleanupAndReject(err);
cleanupAfterFileClosed(file, err, cleanupAndReject);
});

res.pipe(file);
file.on('finish', () => file.close(resolve as () => void));
file.on('finish', () => {
if (!settled) {
settled = true;
file.close(resolve as () => void);
}
Comment on lines +647 to +655

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the target file and show the relevant implementation region
FILE="packages/cli/src/config/extensions/github.ts"
echo "== file =="
ls -la "$FILE"

echo "== showing lines around 600-720 =="
nl -ba "$FILE" | sed -n '600,720p'

echo "== searching for downloadFile cleanup helpers =="
rg -n "function downloadFile|downloadFile\\(|cleanupAfterFileClosed\\(" "$FILE"

echo "== showing cleanupAfterFileClosed definition (if in-file) =="
# Try to find its definition and print around it
rg -n "cleanupAfterFileClosed" "$FILE" -n
# best-effort: print around each match
for line in $(rg -n "cleanupAfterFileClosed" "$FILE" | cut -d: -f1); do
  start=$((line-40))
  end=$((line+80))
  echo "---- around $line ----"
  nl -ba "$FILE" | sed -n "${start},${end}p" | head -n 200
done

echo "== looking for res.complete usage or settled logic =="
rg -n "settled|res\\.complete|on\\('close'\\)|on\\('finish'\\)|on\\('error'\\)" "$FILE"

Repository: vybestack/llxprt-code

Length of output: 268


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="packages/cli/src/config/extensions/github.ts"
echo "== file =="
ls -la "$FILE"

echo "== showing lines around 600-720 =="
cat -n "$FILE" | sed -n '600,720p'

echo "== searching for downloadFile cleanup helpers =="
rg -n "function downloadFile|downloadFile\\(|cleanupAfterFileClosed\\(" "$FILE" || true

echo "== showing cleanupAfterFileClosed definition (if in-file) =="
matches="$(rg -n "cleanupAfterFileClosed" "$FILE" || true)"
echo "$matches" | head -n 50
if [ -n "$matches" ]; then
  while read -r line; do
    ln="$(echo "$line" | cut -d: -f1)"
    start=$((ln-60))
    end=$((ln+120))
    echo "---- around $ln ----"
    cat -n "$FILE" | sed -n "${start},${end}p" | head -n 220
  done <<< "$matches"
fi

echo "== looking for res.complete / settled / close / finish / error logic =="
rg -n "settled|res\\.complete|on\\('close'\\)|on\\('finish'\\)|on\\('error'\\)" "$FILE" || true

Repository: vybestack/llxprt-code

Length of output: 15754


🏁 Script executed:

#!/bin/bash
set -euo pipefail

rg -n "res\\.complete|\\.complete\\b" packages/cli/src/config/extensions/github.ts packages/cli/src || true
rg -n "on\\('close'\\)|on\\(\"close\"\\)|on\\('aborted'\\)|aborted\\b|IncomingMessage" packages/cli/src || true

Repository: vybestack/llxprt-code

Length of output: 4593


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="packages/cli/src/config/extensions/github.ts"

echo "== call sites around line ~430-520 (downloadFile usage) =="
cat -n "$FILE" | sed -n '420,520p'

echo "== find downloadFile usages in github.ts =="
rg -n "downloadFile\\(" "$FILE"

echo "== search repo for similar pipe/finish download patterns =="
rg -n "res\\.pipe\\(file\\)|file\\.on\\('finish'\\)|cleanupAfterFileClosed\\(" packages/cli/src || true

echo "== check package.json for `@types/node` (or types) =="
fd -t f -a "package.json" . | head -n 20
# show top-level package.json first if exists
if [ -f package.json ]; then echo "--- root package.json ---"; cat package.json; fi

rg -n "\"`@types/node`\"" -S . || true
rg -n "node\"\\s*:\\s*\"|engines\"\\s*:\\s*\\{|target\\s*:\\s*\"|lib\\s*:\\s*\\[" -S package.json packages/cli/package.json packages/cli/tsconfig*.json tsconfig*.json 2>/dev/null || true

echo "== list tsconfig targets for `@types/node` compatibility clues =="
fd -t f "tsconfig*.json" . | head -n 20
for f in $(fd -t f "tsconfig*.json" . | head -n 10); do
  echo "--- $f ---"
  cat "$f"
done

Repository: vybestack/llxprt-code

Length of output: 22172


🌐 Web query:

Node.js IncomingMessage close event complete property res.complete premature connection closed promise resolve finish pipe file never finish hang

💡 Result:

In Node.js, the IncomingMessage.complete property is a boolean that indicates whether an HTTP message was fully received and successfully parsed [1][2]. It is commonly used to detect if a connection was terminated prematurely (i.e., before the complete message was delivered) by checking its value during the close event [1][3]. Handling premature connection closures and stream hangs requires understanding how Node.js manages HTTP streams: 1. Detecting Premature Closure: You can check res.complete inside the close event listener to determine if the message was truncated [1][3]. If res.complete is false, the connection was likely terminated unexpectedly [1][2]. javascript res.on('close', () => { if (!res.complete) { console.error('The connection was terminated while the message was still being sent'); } }); 2. Avoiding Stream Hangs: Using res.pipe(destination) can lead to issues where the destination stream does not finish if the source (IncomingMessage) encounters a premature closure [3][4]. Since Node.js 13.0, res.pipe() may not automatically call dst.end() if the response is truncated [3]. 3. Recommended Practices: - Use stream.pipeline instead of manual .pipe() calls [3][4]. stream.pipeline is designed to handle cleanup, errors, and premature closures automatically, ensuring that errors are propagated and resources are not leaked [3]. - If you are waiting for a process to complete, rely on stream.finished or the finish event of the destination stream rather than just the end event of the IncomingMessage [4]. - If your application involves complex streaming (e.g., pipelines where you need to detect errors early), verify if you are accidentally destroying the IncomingMessage (often via for await loops or manual socket destruction), which can prevent proper completion events [5]. If you find that your application hangs or does not finish, ensure that you are not manually handling end events in a way that ignores close or error events, as a premature closure will emit close but may not emit end or finish in the expected manner [3][6][7]. Using modern stream utilities helps maintain consistent behavior across different Node.js versions [3].

Citations:


🌐 Web query:

@types/node IncomingMessage complete boolean property

💡 Result:

In the Node.js TypeScript definitions provided by @types/node, the IncomingMessage interface includes a boolean property named complete [1][2]. The message.complete property indicates whether a complete HTTP message has been received and successfully parsed [2][3]. It is commonly used to verify if a client or server fully transmitted a message before the connection was terminated [2][4]. For example, when listening for the end event on an IncomingMessage object, you can check this property to detect incomplete transfers [2][5]: const req = http.request({ /*... */ }, (res) => { res.resume; res.on('end', => { if (!res.complete) { console.error('The connection was terminated while the message was still being sent'); } }); }); This property has been part of the Node.js http module since version 0.3.0 [2][6].

Citations:


Handle premature HTTP response closes in downloadFile()

downloadFile() settles only on file.on('finish') (resolve) and file/res 'error' (reject). If the server/socket closes mid-transfer without triggering 'error', there’s no 'close'/'aborted' handler, so the Promise can hang and leave a partial file.

Proposed fix
         // Handle response stream errors
         res.on('error', (err) => {
           cleanupAfterFileClosed(file, err, cleanupAndReject);
         });
+        res.on('close', () => {
+          if (!res.complete && !settled) {
+            cleanupAfterFileClosed(
+              file,
+              new Error('Download connection closed before completion'),
+              cleanupAndReject,
+            );
+          }
+        });
 
         res.pipe(file);
         file.on('finish', () => {
           if (!settled) {
             settled = true;
             file.close(resolve as () => void);
           }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
cleanupAfterFileClosed(file, err, cleanupAndReject);
});
res.pipe(file);
file.on('finish', () => file.close(resolve as () => void));
file.on('finish', () => {
if (!settled) {
settled = true;
file.close(resolve as () => void);
}
cleanupAfterFileClosed(file, err, cleanupAndReject);
});
res.on('close', () => {
if (!res.complete && !settled) {
cleanupAfterFileClosed(
file,
new Error('Download connection closed before completion'),
cleanupAndReject,
);
}
});
res.pipe(file);
file.on('finish', () => {
if (!settled) {
settled = true;
file.close(resolve as () => void);
}
});
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/cli/src/config/extensions/github.ts` around lines 647 - 655,
downloadFile currently only resolves on file.on('finish') and rejects on
'error', so if the HTTP response/socket closes mid-transfer without emitting
'error' the Promise can hang and leave a partial file; add handlers for
res.on('aborted') and res.on('close') and file.on('close') that check the
existing settled flag and, if not settled, mark settled, call
cleanupAfterFileClosed (or cleanupAndReject) to remove partial file and reject
the Promise with an appropriate error; ensure these handlers mirror the existing
file/res 'error' logic and remove their listeners when settled to avoid leaks
(reference downloadFile, settled, res, file, and
cleanupAfterFileClosed/cleanupAndReject).

});
})
.on('error', (err) => {
cleanupAndReject(err);
Expand Down
105 changes: 105 additions & 0 deletions packages/cli/src/runtime/providerMutations.issue1943.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/**
* @issue #1943 - /toolformat is not persisted into profile ephemerals
*
* Behavioral tests for setActiveToolFormatOverride() writing to both
* SettingsService AND Config ephemeral settings, so the tool-format value
* is captured during profile saves.
*
* Before the fix, only settingsService.updateSettings() was called.
* After the fix, config.setEphemeralSetting('tool-format', value) is also called,
* mirroring the pattern used by updateActiveProviderBaseUrl.
*/

import { describe, it, expect, vi, beforeEach } from 'vitest';

const mockConfig = {
setEphemeralSetting: vi.fn(),
getEphemeralSetting: vi.fn().mockReturnValue(undefined),
};

const mockSettingsService = {
updateSettings: vi.fn().mockResolvedValue(undefined),
getProviderSettings: vi.fn().mockReturnValue({}),
};

const mockProviderManager = {
getActiveProvider: vi.fn().mockReturnValue({ name: 'openai' }),
getActiveProviderName: vi.fn().mockReturnValue('openai'),
};

vi.mock('./runtimeAccessors.js', () => ({
getCliRuntimeServices: () => ({
config: mockConfig,
settingsService: mockSettingsService,
providerManager: mockProviderManager,
}),
_internal: {
getActiveProviderOrThrow: () => ({ name: 'openai' }),
getProviderSettingsSnapshot: () => ({}),
},
}));

import { setActiveToolFormatOverride } from './providerMutations.js';

describe('setActiveToolFormatOverride ephemeral persistence (issue #1943)', () => {
beforeEach(() => {
vi.clearAllMocks();
mockSettingsService.getProviderSettings.mockReturnValue({});
});

it('writes "openai" to config.setEphemeralSetting when setting toolFormat to "openai"', async () => {
await setActiveToolFormatOverride('openai');

expect(mockSettingsService.updateSettings).toHaveBeenCalledWith('openai', {
toolFormat: 'openai',
});
expect(mockConfig.setEphemeralSetting).toHaveBeenCalledWith(
'tool-format',
'openai',
);
});

it('writes "auto" to config.setEphemeralSetting when clearing override', async () => {
await setActiveToolFormatOverride(null);

expect(mockSettingsService.updateSettings).toHaveBeenCalledWith('openai', {
toolFormat: 'auto',
});
expect(mockConfig.setEphemeralSetting).toHaveBeenCalledWith(
'tool-format',
'auto',
);
});

it('writes "auto" to config.setEphemeralSetting when explicitly setting to "auto"', async () => {
await setActiveToolFormatOverride('auto');

expect(mockSettingsService.updateSettings).toHaveBeenCalledWith('openai', {
toolFormat: 'auto',
});
expect(mockConfig.setEphemeralSetting).toHaveBeenCalledWith(
'tool-format',
'auto',
);
});

it('writes "kimi" to config.setEphemeralSetting when setting toolFormat to "kimi"', async () => {
await setActiveToolFormatOverride('kimi');

expect(mockSettingsService.updateSettings).toHaveBeenCalledWith('openai', {
toolFormat: 'kimi',
});
expect(mockConfig.setEphemeralSetting).toHaveBeenCalledWith(
'tool-format',
'kimi',
);
});

it('calls both settingsService and config (mirrors updateActiveProviderBaseUrl pattern)', async () => {
await setActiveToolFormatOverride('openai');

// Both should be called exactly once
expect(mockSettingsService.updateSettings).toHaveBeenCalledTimes(1);
expect(mockConfig.setEphemeralSetting).toHaveBeenCalledTimes(1);
});
});
4 changes: 3 additions & 1 deletion packages/cli/src/runtime/providerMutations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -376,17 +376,19 @@ export async function getActiveToolFormatState(): Promise<ToolFormatState> {
export async function setActiveToolFormatOverride(
formatName: ToolFormatOverrideLiteral | null,
): Promise<ToolFormatState> {
const { settingsService } = getCliRuntimeServices();
const { config, settingsService } = getCliRuntimeServices();
const provider = _internal.getActiveProviderOrThrow();

if (!formatName || formatName === 'auto') {
await settingsService.updateSettings(provider.name, { toolFormat: 'auto' });
config.setEphemeralSetting('tool-format', 'auto');
return getActiveToolFormatState();
}

await settingsService.updateSettings(provider.name, {
toolFormat: formatName,
});
config.setEphemeralSetting('tool-format', formatName);
return getActiveToolFormatState();
}

Expand Down
Loading
Loading