* feat(explorer): upload files into the workspace from the file tree
- TreePanel header: upload-files / upload-folder buttons (folder picker keeps
the tree via webkitdirectory), with a one-line progress/result hint
- FileTree: drop files/folders onto the tree body (workspace root) or onto a
directory row (that directory); directory context menu gains 上传到此处
- api.ts: uploadFile posts base64 to /sidebar/upload (host writes it through
fs + shell decode; route provided for now by the local demo plugin)
- upload.ts: bytes->base64 (global-btoa-independent), FileList/DataTransfer
collection, sequential upload with per-file results; ~48MB per-file cap
- locales: zh/en strings; icons: IconUploadOutline16
* fix(explorer): reload tree after upload and auto-dismiss the status hint
The drop/context-menu upload path cleared the level cache but never
refetched (the refreshTick bump belongs to the button path), so the
visible tree emptied and only the persistent '已上传 N 个文件' hint
remained — the tree only came back after reopening the tab.
- FileTree.uploadInto now reloads root + expanded levels after clearing,
matching the refresh-tick path
- success status auto-dismisses after 3.5s (failures persist until the
next action) in both TreePanel and FileTree
* feat(host): add the /sidebar/upload route (raw bytes, workspace-safe)
The file tree's upload UI needs a host route; until now it pointed at a
locally-injected demo route. This is the real implementation:
- src/index.ts: register POST /sidebar/upload (exact route, same fence and
session-cwd resolution as every /sidebar route). Query params sessionId,
dir, relativePath; the raw request body is streamed into the workspace.
- src/fs-operations.ts: writeWorkspaceUpload streams chunks to a temp
sibling and renames into place, so a failed or oversized upload never
leaves a partial file. Upload dir must sit inside the session cwd, the
relativePath is sanitized (no '.', '..', empty or absolute segments) and
the target must stay inside both.
- src/config.ts: uploadLimit (default 128MiB; oversized -> 413 too-large,
a new wire code in src/wire.ts).
- client: send the File straight into the POST body (no base64 inflation)
and cap at the same 128MiB (upload.ts, api.ts).
Tests: tests/fs-operations.spec.ts covers write, nested dirs, traversal /
containment refusal, the size cap, and no-partial-file on failure.
(pnpm test: only pre-existing node-pty/git sandbox failures, identical on
clean main; typecheck and build pass.)
* fix(host): harden upload containment, temp-file atomicity and stream failure cleanup
- relativePath: absolute paths and empty segments are refused (400), not
silently collapsed or re-anchored (the spec's 'reject' semantics)
- temp file: uniquely named per request (randomUUID) so concurrent uploads
to the same target stay independent; crashed-process leftovers never
block later uploads (no pid reuse)
- write stream: permanent 'error' listener + error checks after every await
so a failing disk rejects the operation instead of crashing the host or
hanging the drain wait; the temp file is removed after the stream fully
closes (Windows file locks), never leaving a partial file
- docstring now states the containment is lexical (symlink trust model)
* fix(explorer): thread upload error codes and cancellation through the client
- api.uploadFile/fetchUpload accept an AbortSignal (long-op convention);
an aborted request rejects with the DOMException as-is instead of being
wrapped into a 'network' error
- UploadResult carries the wire error code; the client pre-check now emits
the same 'too-large' code as the host, and summarizeResults localizes
'too-large' instead of showing the raw English 413 message
- uploadToDir stops the queue on abort: completed files stay, in-flight
request is cancelled, nothing after is started
- uploadTooLarge copy no longer hardcodes a byte number (the host limit is
configurable); MAX_UPLOAD_BYTES is documented as a mirror, not authority
- relativePathOf rejects absolute paths (isAbsolutePath) instead of
stripping leading slashes, matching the host's 400 semantics
- progress text shared via uploadHintText for the hint and the overlay;
success-hint duration is the exported UPLOAD_HINT_MS
* feat(explorer): full-window upload progress with cancel and VSCode-style drop targets
- UploadOverlay: blurred scrim + card over the file window (Modal token
recipe: bg-mask-1 + mask blur, bg-layer-2, border-inverted, shadow-lv3),
file-level progress bar, cancel button and Esc; scrim clicks do not abort
- TreePanel owns the upload session: header pickers, tree drag-drop and the
context-menu picker funnel through startUpload; one session at a time
(buttons disabled while busy, drops guarded); on settle the tree refreshes
and the status hint shows success (3.5s, transient), failure or cancel
(error color, stays)
- FileTree: drops on directory rows target that directory, drops on FILE
rows target their parent (VSCode semantics, no more accidental root
uploads), root row and body drop into the workspace root; drag-over
highlights the target row (explorerRowDropTarget) plus the body outline
and a hint pill (uploadDropHint / uploadTo) — raw-color inline outline
replaced with the repo's dashed-accent classes
- upload status hint uses editorSearchHint + editorError like the search
status; duplicated upload flow removed from FileTree (single caller)
* test: register the upload route in the smoke inventory
The new /sidebar/upload route joined the fenced route list, so the mount
assertion must expect it (the PR's CI gate was red).
* chore: bump to 0.14.1
Rebased onto main and cut a release version for the upload feature:
package.json / dsh.plugin.json / SIDEBAR_SERVICE_VERSION stay in sync
(test-guarded), README changelogs get the v0.14.1 entry.
* feat(explorer): keep the drop hint above DSH's page overlay and suppress its intake over the tree
DSH's whole-page image-drop intake (ui-conversation InputBar) listens on
document in the bubble phase: any 'Files' drag entering the page shows its
full-screen overlay (z-1000) and a drop anywhere adds images to the chat.
Our tree handled dragover/drop but not dragenter, so the overlay flashed
over the file window and drops outside the tree rows could leak to the
chat.
- TreePanel root now swallows dragenter/dragover/drop (preventDefault +
stopPropagation) before the events reach document: the file window is an
upload target, not an image target. Row/body handlers still fire first
(bubble order) for their own targets; the root is the backstop for the
search row, gaps and the search-results view.
- The drop hint pill is portaled to document.body at z-index 1001 — above
DSH's overlay (z-1000) — so when a drag enters from outside the tree and
DSH's mask lingers until dragend, our 'Drop files/folders here' /
'Upload into {dir}' hint stays readable on top (transient decoration,
pointer-events none; the drop still lands on the tree).
* feat(explorer): zone-split the drop overlays and fix the mask flicker over the sidebar
Sidebar.tsx's panel host now swallows the whole file-drag quartet
(enter/over/leave/drop, gated on the 'Files' type): DSH's document-level
intake keeps an enter/leave depth counter, and the leaves that escaped
the tree unbalanced it — that was the native full-screen mask flickering
over the sidebar. The region is now a black hole to that listener, so the
conversation column keeps DSH's native overlay and image intake while the
sidebar presents its own upload surface (drops over it never add images
to the chat).
The tree's drop affordance is now a pointer-inert frame portaled to
document.body at z-1001, anchored to the explorer body's viewport rect:
it replaces DSH's mask over the sidebar instead of competing with it, and
the hint pill docks at the bottom edge so the rows — the actual drop
targets — stay visible and aimable instead of sitting behind a centered
pill. Inside the tree, enter/leave depth counting (InputBar's own
pattern) replaces the relatedTarget check, which is unreliable for drag
events and flickered the row highlight on icon/label transitions; the row
target is now set authoritatively by the continuously-firing dragover.
dragleave handlers on rows are gone.
Polish: capsule hint pill with the upload icon and a float shadow, the
progress overlay fades in (the repo's dsh-row-in motion), its title gains
the icon, and progress numbers render tabular. tests/file-tree-drop.spec
pins the depth-counter behavior (child transitions keep the zone) and the
parent-directory drop semantics.
* feat(explorer): dim the whole viewport behind the tree's drop zone
The bottom-docked pill sat below the fold of attention; the zone frame
alone also failed to teach the left/right split — a drag over the sidebar
gave no hint that the conversation column still accepts drops (into the
chat, natively). The zone frame now carries the full-viewport dim itself
(a 200vmax box-shadow spread in DSH's own mask-drop token): everything
outside the tree's rect fades, the tree stays clear and aimable, and a
muted invitation centered in the space left of the zone (skipped under
200px) names the chat as the image target. The pill moves to the TOP edge
of the zone, right under the search row — the first thing the eye meets.
* feat(explorer): colorful drop heroes for both zones
The overlay is this flow's one brand moment, so it gets the color the
rest of the UI never does: hand-drawn SVG illustrations in the palette of
DSH's own native drop art (#3964FE/#679EFE/#9CE5ED) so the two zones read
as one family. The upload zone docks a hero at its top edge — a tray
illustration over the hint pill, stacked so the rows below stay aimable;
the chat zone's invitation becomes a tilted photo-cards card over its
label.
* feat(explorer): traverse dropped folders instead of reading dataTransfer.files
A dropped OS folder never surfaces in dataTransfer.files (that flat list
carries files only), so folder drops were silent no-ops while the UI
advertised 'drop files/folders'. uploadItemsFromDrop now captures entry
handles via webkitGetAsEntry — synchronously, since the dataTransfer enters
protected mode once the drop dispatch ends, while the captured handles stay
readable — then drains each directory's readEntries batches recursively,
prefixing every descendant's relative path. Entry-derived paths go through
the same sanitizer as picker paths; an entry that fails to read is skipped
rather than failing the whole drop, and the flat file list remains the
fallback where the entry API is unavailable. The FileTree drop handlers
ride the resulting promise.
---------
Co-authored-by: dsh local <dsh@local>
Co-authored-by: Menghuan1918 <menghuan2003@outlook.com>
188 lines
7.6 KiB
TypeScript
188 lines
7.6 KiB
TypeScript
/**
|
|
* File-upload plumbing for the files window: turn a file picker or a drag-drop
|
|
* into per-file raw-byte uploads through the sidebar's `/sidebar/upload` route.
|
|
*
|
|
* Folders keep their tree in both flows: the picker's `webkitdirectory`
|
|
* selection arrives as Files with `webkitRelativePath` filled, and dropped
|
|
* folders — which never surface in `dataTransfer.files` — are traversed via
|
|
* `webkitGetAsEntry`, so the relative path is preserved for every nested file
|
|
* and the host recreates the tree under the chosen directory. The File is
|
|
* streamed straight into the POST body (no base64 inflation); uploads run
|
|
* sequentially so one slow file cannot starve the others, and each result
|
|
* reports its own outcome (the tree keeps going after a failure). An
|
|
* optional `AbortSignal` stops the queue at the next item boundary and
|
|
* aborts the in-flight request; the host cleans up its temp file when the
|
|
* request stream dies.
|
|
*/
|
|
import { api, SidebarApiError, type SessionScope } from './api.ts'
|
|
import { isAbsolutePath } from './paths.ts'
|
|
import type { CopyKey } from './locales.ts'
|
|
|
|
/** One pending file: the browser File plus the workspace-relative target path. */
|
|
export interface UploadItem {
|
|
file: File
|
|
relativePath: string
|
|
}
|
|
|
|
/** One settled upload. */
|
|
export interface UploadResult {
|
|
relativePath: string
|
|
ok: boolean
|
|
path?: string
|
|
/** Wire error code when the host refused the upload ('too-large', ...). */
|
|
code?: string
|
|
/** The host's error message (English wire text; localize via `code`). */
|
|
error?: string
|
|
}
|
|
|
|
/** Sanitize a relative target: absolute paths, traversal, and empty segments
|
|
* are rejected (the host enforces the same rules with a 400). */
|
|
function sanitizeRelativePath(rel: string): string | undefined {
|
|
if (rel === '' || isAbsolutePath(rel)) return undefined
|
|
if (rel.split(/[\\/]/).some((s) => s === '' || s === '.' || s === '..')) return undefined
|
|
return rel
|
|
}
|
|
|
|
/** The picker's relative path: webkitRelativePath when present, else the name. */
|
|
function relativePathOf(file: File): string | undefined {
|
|
return sanitizeRelativePath(file.webkitRelativePath || file.name || '')
|
|
}
|
|
|
|
/** Collect a picker selection (webkitdirectory folders carry relative paths). */
|
|
export function uploadItemsFromFiles(files: FileList | readonly File[]): UploadItem[] {
|
|
const items: UploadItem[] = []
|
|
for (const file of files) {
|
|
const rel = relativePathOf(file)
|
|
if (rel !== undefined) items.push({ file, relativePath: rel })
|
|
}
|
|
return items
|
|
}
|
|
|
|
/** Read one dropped file-system entry into upload items; directories
|
|
* recurse, prefixing their name onto every descendant's relative path. */
|
|
async function itemsFromEntry(entry: FileSystemEntry, prefix: string): Promise<UploadItem[]> {
|
|
if (entry.isFile) {
|
|
const file = await new Promise<File>((resolve, reject) => {
|
|
;(entry as FileSystemFileEntry).file(resolve, reject)
|
|
})
|
|
const rel = sanitizeRelativePath(prefix + file.name)
|
|
return rel === undefined ? [] : [{ file, relativePath: rel }]
|
|
}
|
|
if (entry.isDirectory) {
|
|
const reader = (entry as FileSystemDirectoryEntry).createReader()
|
|
const entries: FileSystemEntry[] = []
|
|
// readEntries returns one BATCH per call; drain until an empty batch.
|
|
for (;;) {
|
|
const batch = await new Promise<FileSystemEntry[]>((resolve, reject) => {
|
|
reader.readEntries(resolve, reject)
|
|
})
|
|
if (batch.length === 0) break
|
|
entries.push(...batch)
|
|
}
|
|
const nested = await Promise.all(entries.map(child => itemsFromEntry(child, `${prefix}${entry.name}/`)))
|
|
return nested.flat()
|
|
}
|
|
return []
|
|
}
|
|
|
|
/**
|
|
* Collect a drag-drop payload. Dropped folders do NOT surface in
|
|
* `dataTransfer.files` — they arrive as directory items, so entries are
|
|
* captured via `webkitGetAsEntry` and traversed (draining readEntries
|
|
* batches), keeping each nested file's relative path. MUST be invoked
|
|
* synchronously from the drop handler: the dataTransfer enters protected
|
|
* mode once the event dispatch ends, while the captured entry handles stay
|
|
* readable asynchronously. Falls back to the flat file list when the entry
|
|
* API is unavailable; an entry that fails to read is skipped, not fatal.
|
|
*/
|
|
export async function uploadItemsFromDrop(data: DataTransfer | undefined): Promise<UploadItem[]> {
|
|
if (data === undefined) return []
|
|
// Synchronous section: capture every entry handle before returning.
|
|
const entries = [...data.items]
|
|
.map(item => (item.kind === 'file' ? item.webkitGetAsEntry() : null))
|
|
.filter((entry): entry is FileSystemEntry => entry !== null)
|
|
if (entries.length === 0) return uploadItemsFromFiles(data.files)
|
|
const nested = await Promise.all(entries.map(entry => itemsFromEntry(entry, '').catch(() => [])))
|
|
return nested.flat()
|
|
}
|
|
|
|
/**
|
|
* Client-side pre-check cap. Mirrors the host's default (config `uploadLimit`)
|
|
* only — the host enforces the real, configurable limit, so a lowered host
|
|
* limit surfaces as a `too-large` wire error, never as a silent pass.
|
|
*/
|
|
export const MAX_UPLOAD_BYTES = 128 * 1024 * 1024
|
|
|
|
/** How long a success hint stays before fading (failures stay until the next action). */
|
|
export const UPLOAD_HINT_MS = 3500
|
|
|
|
/**
|
|
* One-line upload progress text: 'Uploading into {dir}…' while no file is in
|
|
* flight, then 'Uploading {done}/{total}: {name}' per file. Shared by the tree
|
|
* hint and the full-window upload overlay.
|
|
*/
|
|
export function uploadHintText(
|
|
done: number,
|
|
total: number,
|
|
current: string,
|
|
dir: string,
|
|
t: (key: CopyKey, params?: Record<string, string | number>) => string,
|
|
): string {
|
|
return current === '' ? t('uploadingTo', { dir }) : t('uploadProgress', { done, total, name: current })
|
|
}
|
|
|
|
/**
|
|
* Upload every item into `dir` (absolute, inside the session workspace),
|
|
* sequentially, reporting progress as `(done, total, currentRelativePath)`.
|
|
* Resolves with one result per item — never rejects; `signal.aborted` stops
|
|
* the queue at the next item boundary (completed items stay uploaded).
|
|
*/
|
|
export async function uploadToDir(
|
|
scope: SessionScope,
|
|
dir: string,
|
|
items: UploadItem[],
|
|
onProgress?: (done: number, total: number, current: string) => void,
|
|
signal?: AbortSignal,
|
|
): Promise<UploadResult[]> {
|
|
const results: UploadResult[] = []
|
|
let done = 0
|
|
for (const item of items) {
|
|
if (signal?.aborted) break
|
|
onProgress?.(done, items.length, item.relativePath)
|
|
try {
|
|
if (item.file.size > MAX_UPLOAD_BYTES) {
|
|
results.push({ relativePath: item.relativePath, ok: false, code: 'too-large' })
|
|
} else {
|
|
const res = await api.uploadFile(scope, dir, item.relativePath, item.file, signal)
|
|
results.push({ relativePath: item.relativePath, ok: true, path: res.path })
|
|
}
|
|
} catch (error) {
|
|
// An aborted in-flight request is a cancel, not a failure: stop quietly.
|
|
if (error instanceof DOMException && error.name === 'AbortError') break
|
|
results.push({
|
|
relativePath: item.relativePath,
|
|
ok: false,
|
|
code: error instanceof SidebarApiError ? error.code : undefined,
|
|
error: error instanceof Error ? error.message : String(error),
|
|
})
|
|
}
|
|
done++
|
|
}
|
|
onProgress?.(done, items.length, '')
|
|
return results
|
|
}
|
|
|
|
/** Fold a result list into a one-line status for the tree hint. */
|
|
export function summarizeResults(
|
|
results: UploadResult[],
|
|
t: (key: CopyKey, params?: Record<string, string | number>) => string,
|
|
): string {
|
|
const okCount = results.filter((r) => r.ok).length
|
|
const failed = results.find((r) => !r.ok)
|
|
if (failed !== undefined) {
|
|
const detail = failed.code === 'too-large' ? t('uploadTooLarge') : (failed.error ?? t('uploadFailedUnknown'))
|
|
return t('uploadFailed', { error: detail })
|
|
}
|
|
return t('uploadDone', { count: okCount })
|
|
}
|