Skip to content

Commit ba71e74

Browse files
author
linyuan.yang
committed
vscode 文件下载
1 parent f71876f commit ba71e74

5 files changed

Lines changed: 141 additions & 3 deletions

File tree

‎packages/chat-ui/src/components/FileExplorer.vue‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -700,6 +700,23 @@ const rawDownloadHref = computed(() =>
700700
? props.transport.getRawFileUrl(selectedPath.value)
701701
: '',
702702
)
703+
// 宿主代为下载(如 VSCode 插件:webview 无法直接用 <a href> 触达服务器)。
704+
// 与 rawDownloadHref 天然互斥:实现了 downloadFile 的 transport 通常让 getRawFileUrl 返回空串。
705+
const useHostDownload = computed(() => typeof props.transport.downloadFile === 'function')
706+
707+
async function onDownload(): Promise<void> {
708+
const p = selectedPath.value
709+
if (!p) return
710+
if (typeof props.transport.downloadFile === 'function') {
711+
try {
712+
await props.transport.downloadFile(p)
713+
} catch (e: any) {
714+
errMsg.value = e?.message ?? String(e)
715+
}
716+
} else if (rawDownloadHref.value) {
717+
window.open(rawDownloadHref.value, '_blank', 'noopener')
718+
}
719+
}
703720
704721
function openImagePreview(): void {
705722
if (imageSrc.value) imageLightbox.value?.open(imageSrc.value)
@@ -877,7 +894,14 @@ onMounted(() => {
877894
<span class="chatui-explorer-meta">{{ fmtSize(fileSize) }}</span>
878895
<span v-if="isDirty" class="chatui-explorer-dirty" :title="L.explorerEditDirty">●</span>
879896
<SIconButton
880-
v-if="rawDownloadHref"
897+
v-if="useHostDownload"
898+
variant="outline"
899+
size="sm"
900+
:title="L.explorerDownload || 'Download'"
901+
@click="onDownload"
902+
>⤓</SIconButton>
903+
<SIconButton
904+
v-else-if="rawDownloadHref"
881905
variant="outline"
882906
size="sm"
883907
:href="rawDownloadHref"
@@ -910,7 +934,10 @@ onMounted(() => {
910934
<div v-else-if="errMsg" class="chatui-explorer-state chatui-explorer-error">{{ errMsg }}</div>
911935
<div v-else-if="fileTooLarge" class="chatui-explorer-state">
912936
<div>{{ tpl(L.explorerTooLarge, { size: fmtSize(fileSize) }) }}</div>
913-
<a v-if="rawDownloadHref" class="chatui-explorer-link" :href="rawDownloadHref" target="_blank" rel="noopener">
937+
<button v-if="useHostDownload" type="button" class="chatui-explorer-link" @click="onDownload">
938+
{{ L.explorerDownload || 'Download full file' }}
939+
</button>
940+
<a v-else-if="rawDownloadHref" class="chatui-explorer-link" :href="rawDownloadHref" target="_blank" rel="noopener">
914941
{{ L.explorerDownload || 'Download full file' }}
915942
</a>
916943
</div>
@@ -921,7 +948,10 @@ onMounted(() => {
921948
</div>
922949
<div v-else-if="isUnsupportedBinary" class="chatui-explorer-state">
923950
<div>{{ L.explorerBinaryFile }}</div>
924-
<a v-if="rawDownloadHref" class="chatui-explorer-link" :href="rawDownloadHref" target="_blank" rel="noopener">
951+
<button v-if="useHostDownload" type="button" class="chatui-explorer-link" @click="onDownload">
952+
{{ L.explorerDownload || 'Download file' }}
953+
</button>
954+
<a v-else-if="rawDownloadHref" class="chatui-explorer-link" :href="rawDownloadHref" target="_blank" rel="noopener">
925955
{{ L.explorerDownload || 'Download file' }}
926956
</a>
927957
</div>
@@ -1184,6 +1214,13 @@ onMounted(() => {
11841214
font-size: 12px;
11851215
text-decoration: underline;
11861216
}
1217+
button.chatui-explorer-link {
1218+
padding: 0;
1219+
border: none;
1220+
background: none;
1221+
font-family: inherit;
1222+
cursor: pointer;
1223+
}
11871224
.chatui-explorer-state {
11881225
flex: 1;
11891226
display: flex;

‎packages/chat-ui/src/transport.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,11 @@ export interface IChatTransport {
4545
writeFile(path: string, content: string, expectedMtime?: number): Promise<FsWriteResult>
4646
/** 返回可直接下载/在新标签页打开的原始文件 URL;用于 tooLarge 或 binary 等无法在 viewer 中显示的场景 */
4747
getRawFileUrl(path: string): string
48+
/**
49+
* 触发把文件下载/保存到用户本地。由 transport 决定具体方式(浏览器直接下载 vs 宿主弹保存对话框)。
50+
* 不实现时回退到 getRawFileUrl 的链接方式。
51+
*/
52+
downloadFile?(path: string): Promise<void>
4853
gitStatus(root: string): Promise<GitStatusResult>
4954
gitDiff(root: string, path: string, fullContent?: boolean): Promise<GitDiffResult>
5055

‎packages/vscode-extension/src/ChatViewProvider.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import * as vscode from 'vscode';
22
import * as path from 'node:path';
3+
import * as os from 'node:os';
34
import WebSocket from 'ws';
45
import { WebChatEventType, WsCommandType, type WebChatEvent } from 'sbot.commons';
56
import { SbotClient } from './SbotClient';
@@ -180,6 +181,8 @@ export class ChatViewProvider implements vscode.WebviewViewProvider, vscode.Disp
180181
return client.fetchThinks(args[0]);
181182
case 'listShells':
182183
return client.listShells();
184+
case 'downloadFile':
185+
return this.downloadFile(args[0]);
183186
default:
184187
throw new Error(`Unknown RPC method: ${method}`);
185188
}
@@ -261,6 +264,48 @@ export class ChatViewProvider implements vscode.WebviewViewProvider, vscode.Disp
261264
this.ptySockets.clear();
262265
}
263266

267+
// ── Download ──
268+
// The webview can't navigate to the server URL (CSP + server connection lives here),
269+
// so the host fetches the bytes and saves them via the native save dialog.
270+
271+
private async downloadFile(filePath: string): Promise<void> {
272+
const name = filePath.split(/[\\/]/).pop() || 'download';
273+
const baseDir = this.getWorkspaceFolder() ?? os.homedir();
274+
const target = await vscode.window.showSaveDialog({
275+
defaultUri: vscode.Uri.file(path.join(baseDir, name)),
276+
saveLabel: 'Download',
277+
});
278+
if (!target) return; // user cancelled the save dialog
279+
280+
const client = this.ensureClient();
281+
let cancelled = false;
282+
try {
283+
await vscode.window.withProgress(
284+
{ location: vscode.ProgressLocation.Notification, title: `Downloading ${name}`, cancellable: true },
285+
async (progress, token) => {
286+
const controller = new AbortController();
287+
token.onCancellationRequested(() => { cancelled = true; controller.abort(); });
288+
let lastPct = 0;
289+
await client.downloadToFile(filePath, target.fsPath, {
290+
signal: controller.signal,
291+
onProgress: (loaded, total) => {
292+
if (!total) { progress.report({ message: formatBytes(loaded) }); return; }
293+
const pct = Math.floor((loaded / total) * 100);
294+
if (pct > lastPct) {
295+
progress.report({ increment: pct - lastPct, message: `${pct}% · ${formatBytes(loaded)} / ${formatBytes(total)}` });
296+
lastPct = pct;
297+
}
298+
},
299+
});
300+
},
301+
);
302+
void vscode.window.showInformationMessage(`Downloaded: ${target.fsPath}`);
303+
} catch (e: any) {
304+
if (cancelled) return; // user aborted — stay quiet
305+
void vscode.window.showErrorMessage(`Download failed: ${e?.message ?? e}`);
306+
}
307+
}
308+
264309
private onServerEvent = (event: WebChatEvent) => {
265310
const chatType = EVENT_TYPE_MAP[event.type];
266311
if (!chatType) return;
@@ -328,6 +373,14 @@ function getNonce(): string {
328373
return text;
329374
}
330375

376+
function formatBytes(bytes: number): string {
377+
if (!bytes || bytes < 0) return '0 B';
378+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
379+
const i = Math.min(units.length - 1, Math.floor(Math.log(bytes) / Math.log(1024)));
380+
const value = bytes / Math.pow(1024, i);
381+
return `${i === 0 ? value : value.toFixed(1)} ${units[i]}`;
382+
}
383+
331384
function isLocalBaseUrl(baseUrl: string): boolean {
332385
try {
333386
const { hostname } = new URL(baseUrl);

‎packages/vscode-extension/src/SbotClient.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,48 @@ export class SbotClient {
235235
return `${this.baseUrl}/api/fs/entry/raw?path=${encodeURIComponent(filePath)}`;
236236
}
237237

238+
/**
239+
* Stream a file's raw bytes from the server straight to disk (no full-file buffering),
240+
* reporting progress as bytes arrive. Writes to a `.part` temp file and renames on
241+
* success; the partial file is removed on error/cancel so a failed download never
242+
* clobbers an existing target.
243+
*/
244+
async downloadToFile(
245+
filePath: string,
246+
destPath: string,
247+
opts: { signal?: AbortSignal; onProgress?: (loaded: number, total: number) => void } = {},
248+
): Promise<void> {
249+
const fs = require('node:fs') as typeof import('node:fs');
250+
const res = await this.http.get('/api/fs/entry/raw', {
251+
params: { path: filePath },
252+
responseType: 'stream',
253+
signal: opts.signal,
254+
});
255+
const total = Number(res.headers['content-length'] ?? 0);
256+
const stream = res.data as NodeJS.ReadableStream;
257+
const tmpPath = `${destPath}.part`;
258+
const out = fs.createWriteStream(tmpPath);
259+
let loaded = 0;
260+
261+
try {
262+
await new Promise<void>((resolve, reject) => {
263+
stream.on('data', (chunk: Buffer) => {
264+
loaded += chunk.length;
265+
opts.onProgress?.(loaded, total);
266+
});
267+
stream.on('error', reject);
268+
out.on('error', reject);
269+
out.on('finish', resolve);
270+
stream.pipe(out);
271+
});
272+
await fs.promises.rename(tmpPath, destPath);
273+
} catch (err) {
274+
try { out.destroy(); } catch { /* ignore */ }
275+
await fs.promises.unlink(tmpPath).catch(() => {});
276+
throw err;
277+
}
278+
}
279+
238280
async gitStatus(root: string): Promise<any> {
239281
const res = await this.http.get('/api/git/status', { params: { root } });
240282
return res.data.data ?? res.data;

‎packages/vscode-extension/webview/composables/useChat.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,7 @@ export class VsCodeTransport implements IChatTransport {
161161
readFile(path: string): Promise<FsReadResult> { return rpc('readFile', path) }
162162
writeFile(path: string, content: string, expectedMtime?: number): Promise<FsWriteResult> { return rpc('writeFile', path, content, expectedMtime) }
163163
getRawFileUrl(_path: string): string { return '' }
164+
downloadFile(path: string): Promise<void> { return rpc('downloadFile', path) }
164165
gitStatus(root: string): Promise<GitStatusResult> { return rpc('gitStatus', root) }
165166
gitDiff(root: string, path: string, fullContent = false): Promise<GitDiffResult> { return rpc('gitDiff', root, path, fullContent) }
166167

0 commit comments

Comments
 (0)