Skip to content

Commit 7cceced

Browse files
author
linyuan.yang
committed
vscode uploadfile
1 parent bff37a9 commit 7cceced

3 files changed

Lines changed: 104 additions & 3 deletions

File tree

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

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,10 +158,16 @@ export class ChatViewProvider implements vscode.WebviewViewProvider, vscode.Disp
158158
return client.listDrives();
159159
case 'mkdir':
160160
return client.mkdir(args[0]);
161+
case 'deleteEntry':
162+
return client.deleteEntry(args[0]);
163+
case 'uploadFile':
164+
return client.uploadFile(args[0], args[1], args[2]);
161165
case 'listTree':
162166
return client.listTree(args[0]);
163167
case 'readFile':
164168
return client.readFile(args[0]);
169+
case 'writeFile':
170+
return client.writeFile(args[0], args[1], args[2]);
165171
case 'gitStatus':
166172
return client.gitStatus(args[0]);
167173
case 'gitDiff':

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

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,8 @@ import {
77
} from 'sbot.commons';
88

99
export type WsListener = (event: WebChatEvent) => void;
10+
export type VscodeUploadFilePayload = { name: string; type?: string; size?: number; dataUrl: string };
11+
type UploadFileOptions = { overwrite?: boolean };
1012

1113
function getServerBaseUrl(): string {
1214
const { readFileSync, existsSync } = require('node:fs');
@@ -23,6 +25,48 @@ function getServerBaseUrl(): string {
2325
return `http://localhost:${DEFAULT_PORT}`;
2426
}
2527

28+
function escapeMultipartHeader(value: string): string {
29+
return value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\r|\n/g, ' ');
30+
}
31+
32+
function decodeDataUrl(dataUrl: string): Buffer {
33+
const comma = dataUrl.indexOf(',');
34+
if (comma < 0 || !/;base64/i.test(dataUrl.slice(0, comma))) {
35+
throw new Error('Invalid upload payload');
36+
}
37+
return Buffer.from(dataUrl.slice(comma + 1), 'base64');
38+
}
39+
40+
function buildMultipartUploadBody(
41+
parentDir: string,
42+
file: VscodeUploadFilePayload,
43+
opts: UploadFileOptions,
44+
): { body: Buffer; boundary: string } {
45+
const boundary = `----sbot-vscode-${Date.now()}-${Math.random().toString(16).slice(2)}`;
46+
const chunks: Buffer[] = [];
47+
const append = (text: string) => chunks.push(Buffer.from(text, 'utf-8'));
48+
const appendField = (name: string, value: string) => {
49+
append(`--${boundary}\r\n`);
50+
append(`Content-Disposition: form-data; name="${escapeMultipartHeader(name)}"\r\n\r\n`);
51+
append(`${value}\r\n`);
52+
};
53+
54+
appendField('dir', parentDir);
55+
if (opts.overwrite) appendField('overwrite', '1');
56+
57+
const data = decodeDataUrl(file.dataUrl);
58+
append(`--${boundary}\r\n`);
59+
append(
60+
`Content-Disposition: form-data; name="file"; filename="${escapeMultipartHeader(file.name)}"\r\n` +
61+
`Content-Type: ${file.type || 'application/octet-stream'}\r\n\r\n`,
62+
);
63+
chunks.push(data);
64+
append('\r\n');
65+
append(`--${boundary}--\r\n`);
66+
67+
return { body: Buffer.concat(chunks), boundary };
68+
}
69+
2670
export class SbotClient {
2771
private readonly http: AxiosInstance;
2872
private ws: WebSocket | null = null;
@@ -140,6 +184,30 @@ export class SbotClient {
140184
return res.data.data ?? res.data ?? { path: filePath };
141185
}
142186

187+
async deleteEntry(filePath: string): Promise<{ path: string }> {
188+
const res = await this.http.delete('/api/fs/entry', { params: { path: filePath } });
189+
return res.data.data ?? res.data ?? { path: filePath };
190+
}
191+
192+
async uploadFile(parentDir: string, file: VscodeUploadFilePayload, opts: UploadFileOptions = {}): Promise<{ path: string; size: number }> {
193+
try {
194+
const { body, boundary } = buildMultipartUploadBody(parentDir, file, opts);
195+
const res = await this.http.post('/api/fs/upload', body, {
196+
headers: {
197+
'Content-Type': `multipart/form-data; boundary=${boundary}`,
198+
'Content-Length': body.length,
199+
},
200+
});
201+
return res.data.data ?? res.data;
202+
} catch (err: any) {
203+
const status = err?.response?.status;
204+
const msg = err?.response?.data?.message ?? err?.message ?? 'uploadFile failed';
205+
const e: any = new Error(msg);
206+
if (status) e.status = status;
207+
throw e;
208+
}
209+
}
210+
143211
async listTree(filePath: string): Promise<any> {
144212
const res = await this.http.get('/api/fs/entry', { params: { type: 'tree', path: filePath } });
145213
return res.data.data ?? res.data;

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

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import type { IChatTransport, ChatEvent, ContentPart, Attachment, SessionItem, CreateSessionOpts, StoredMessage, UsageInfo, AppSettings, SessionStatus, ToolApprovalPayload, AskAnswerPayload, DirListResult, DriveEntry, QuickDir, FsTreeResult, FsReadResult, GitStatusResult, GitDiffResult, RemoteEntry, FsUploadOptions } from '@sbot/chat-ui'
1+
import type { IChatTransport, ChatEvent, ContentPart, Attachment, SessionItem, CreateSessionOpts, StoredMessage, UsageInfo, AppSettings, SessionStatus, ToolApprovalPayload, AskAnswerPayload, DirListResult, DriveEntry, QuickDir, FsTreeResult, FsReadResult, FsWriteResult, GitStatusResult, GitDiffResult, RemoteEntry, FsUploadOptions, FsUploadProgress } from '@sbot/chat-ui'
22

33
declare function acquireVsCodeApi(): { postMessage(msg: any): void }
44
const vscode = acquireVsCodeApi()
55

66
type EventHandler = (event: ChatEvent) => void
7+
type VscodeUploadFilePayload = { name: string; type: string; size: number; dataUrl: string }
78

89
let rpcId = 0
910
const pending = new Map<number, { resolve: (v: any) => void; reject: (e: Error) => void }>()
@@ -34,6 +35,22 @@ function cmd(method: string, ...args: any[]) {
3435
vscode.postMessage({ type: 'cmd', method, args: JSON.parse(JSON.stringify(args)) })
3536
}
3637

38+
function readFileAsDataUrl(file: File, onProgress?: (progress: FsUploadProgress) => void): Promise<string> {
39+
return new Promise((resolve, reject) => {
40+
const reader = new FileReader()
41+
reader.onprogress = (evt) => {
42+
const total = evt.lengthComputable ? evt.total : file.size
43+
const loaded = Math.min(evt.loaded, total || evt.loaded)
44+
const percent = total > 0 ? Math.min(95, Math.round((loaded / total) * 95)) : 95
45+
onProgress?.({ loaded, total, percent })
46+
}
47+
reader.onload = () => resolve(String(reader.result ?? ''))
48+
reader.onerror = () => reject(reader.error ?? new Error('Failed to read file'))
49+
reader.onabort = () => reject(new Error('File read aborted'))
50+
reader.readAsDataURL(file)
51+
})
52+
}
53+
3754
export class VsCodeTransport implements IChatTransport {
3855
connect(): void { cmd('connect') }
3956
disconnect(): void { cmd('disconnect') }
@@ -63,11 +80,21 @@ export class VsCodeTransport implements IChatTransport {
6380
listDrives(): Promise<DriveEntry[]> { return rpc('listDrives') }
6481
mkdir(path: string): Promise<{ path: string }> { return rpc('mkdir', path) }
6582
deleteEntry(path: string): Promise<{ path: string }> { return rpc('deleteEntry', path) }
66-
uploadFile(_parentDir: string, _file: File, _options?: FsUploadOptions): Promise<{ path: string; size: number }> {
67-
return Promise.reject(new Error('uploadFile is not supported in vscode webview'))
83+
async uploadFile(parentDir: string, file: File, options: FsUploadOptions = {}): Promise<{ path: string; size: number }> {
84+
options.onProgress?.({ loaded: 0, total: file.size, percent: 0 })
85+
const payload: VscodeUploadFilePayload = {
86+
name: file.name,
87+
type: file.type,
88+
size: file.size,
89+
dataUrl: await readFileAsDataUrl(file, options.onProgress),
90+
}
91+
const result = await rpc('uploadFile', parentDir, payload, { overwrite: Boolean(options.overwrite) })
92+
options.onProgress?.({ loaded: file.size, total: file.size, percent: 100 })
93+
return result
6894
}
6995
listTree(path: string): Promise<FsTreeResult> { return rpc('listTree', path) }
7096
readFile(path: string): Promise<FsReadResult> { return rpc('readFile', path) }
97+
writeFile(path: string, content: string, expectedMtime?: number): Promise<FsWriteResult> { return rpc('writeFile', path, content, expectedMtime) }
7198
getRawFileUrl(_path: string): string { return '' }
7299
gitStatus(root: string): Promise<GitStatusResult> { return rpc('gitStatus', root) }
73100
gitDiff(root: string, path: string, fullContent = false): Promise<GitDiffResult> { return rpc('gitDiff', root, path, fullContent) }

0 commit comments

Comments
 (0)