feat(transfer): 流式传输与原生打包,JSONL 预览/编辑与大文件分页预览

宿主半:
- /sidebar/file 与 /sidebar/html 改为 createReadStream + pipeline(新增
  file-stream.ts),删除 mediaLimit;流开始后失败由 writeJson 的
  headersSent 守卫降级为 destroy,不再抛 ERR_HTTP_HEADERS_SENT
- 上传本就是流式的,只删掉客户端 MAX_UPLOAD_BYTES 预检与宿主 limit 逐块检查
- 删除 readLimit / mediaLimit / uploadLimit 三个配置键,新增共享常量模块
  editor-limits.ts(MAX_EDITABLE_BYTES = 5 MiB、PAGE_BYTES、写入体护栏)
- fs.read 重塑为 text | binary | too-large 三态,不再有「截断文本」这个
  既不可信又不可保存的中间态;新增 fs.readPage 字节窗口分页(按行对齐、
  按 path+size+mtime 缓存首次探测到的编码)
- 删除 JSON 版 fs.write,改为 /sidebar/write raw 路由(文档即请求体),
  拆掉 MAX_BODY_BYTES=1MiB 这道保存墙;编码与行尾还原逻辑原样搬到
  fs-operations.writeWorkspaceText
- 打包改原生命令:新增 archive-tools.ts(zip → tar 探测、公共祖先定位、
  argv 规划、stdio 重定向),archive-route 改为后台写临时文件 + 流式下发,
  删除手写 ZIP writer src/zip.ts;新增 unavailable 错误码

客户端半:
- 新增 text-pages.ts(字节偏移分页游标,显式翻页)、jsonl.ts(逐行记录
  解析与摘要)、lang-jsonl.ts(每行独立的 JSON tokenizer,替代会为每条记录
  产生错误节点的 json() 语法)、LargeFileView.tsx(记录卡片 / 日志行两种
  只读分页视图)
- 新增 jsonl viewer 描述符(预览 = 记录列表,编辑 = 可保存的 CodeMirror)
- FileViewerProps 用 size/largeFile 取代 truncated;超限文件改为只读分页
  预览并可下载,不再提供编辑器
- tags.invalid 由纯白改为红色波浪线(浅色主题下原本白底白字不可见)
- zip 下载改回普通 <a download> 直链,不再把整包放进浏览器内存
This commit is contained in:
Menghuan1918 committed 2026-10-11 22:25:25 +08:00
1 parent 64a61ccfe4
commit d4ca9eb6fb
28 files changed
+2405 -858

No files matched your search

+229 -246
View File
@@ -1,50 +1,91 @@
/**
* Helpers for the `/sidebar/archive` route (the file tree's "zip and
* download" action): the download-name sanitizer and the recursive entry
* walk. Kept apart from index.ts so both are directly unit-testable — the
* walk's bounds live inside the collector, and the route module is a
* cordis plugin whose setup needs a whole fake context.
* The `/sidebar/archive` flow: the file tree's "zip and download" action.
*
* The walk is the security-relevant half: every row comes from an already
* fenced path (index.ts resolves each selection through
* `ensureWorkspacePath` first), and a symlink is skipped rather than followed,
* so it can neither escape the workspace nor cycle.
* Three steps, unchanged from before: `archive.build` fences every `path` and
* answers with an id immediately; `archive.status` reports
* `building → ready | error`; `GET /sidebar/archive` serves the finished bytes
* once. What changed is what happens in between.
*
* The archive is no longer BUILT BY US. The system's `zip` (or `tar` — see
* archive-tools.ts) writes it, straight into a temp file in the OS temp
* directory, and that file is what gets streamed out. Consequences worth
* stating plainly:
*
* - **No memory ceiling.** The old path concatenated every member into one
* `Buffer`, held it on the task table, and `res.end()`-ed it; a selection
* large enough to matter took the host down. Now only the OS's disk usage
* grows.
* - **No per-entry progress.** The old build reported `done / total` because
* our own writer visited each entry. A child process tells us nothing per
* entry, so the status reports BYTES written so far (the temp file's size)
* and the UI shows a plain "packing" line. Inventing an entry count would
* mean walking the tree a second time just to have a number to display.
* - **Failures still arrive before the download starts.** The tool runs to
* completion in the background; a non-zero exit settles the task as `error`
* with the tool's own stderr, which the client renders. That ordering is the
* whole reason the temp file exists rather than piping the tool directly
* into the response — a mid-stream tool failure would otherwise be a 200
* response carrying half an archive.
*
* A temp archive is removed on every exit path: a completed download, the TTL
* sweep, and plugin teardown (which also kills a build still running).
*/
import { randomUUID } from 'node:crypto'
import { lstat, readdir } from 'node:fs/promises'
import { basename, dirname, join } from 'node:path'
import { open, rm, stat } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { SidebarHttpResponse } from './context-types.ts'
import { streamFileToResponse } from './file-stream.ts'
import {
archiveFileName,
archiveTempName,
planArchive,
resolveArchiveTool,
runArchiveTool,
type ArchivePlan,
type ArchiveSpawn,
type ArchiveToolSpec,
} from './archive-tools.ts'
import { SidebarError } from './wire.ts'
import { buildZip, ZIP_MAX_ENTRIES, type ZipEntry } from './zip.ts'
/** Maximum archive-name length (keeps the Content-Disposition header sane). */
export const ARCHIVE_NAME_MAX = 120
/** How many archives one host may build at the same time. */
export const ARCHIVE_MAX_BUILDING = 4
/** How long a finished (or failed) archive stays downloadable. */
export const ARCHIVE_TTL_MS = 5 * 60 * 1000
/**
* Sanitize the archive's download name: one flat file name, never a path.
* Separators, control characters, quotes and leading dots are stripped (a
* name cannot look like a traversal or hide as a dotfile); an empty result
* falls back to `archive.zip`, and a `.zip` suffix is applied once.
*/
export function archiveNameOf(raw: string | null): string {
// A bare `.zip` (or nothing at all) is the caller asking for the default:
// check BEFORE the leading-dot strip below, which would turn it into `zip`.
const trimmed = (raw ?? '').trim()
if (trimmed === '' || trimmed === '.zip') return 'archive.zip'
// Character filter (not a character-class regex): separators, quotes and
// C0/DEL control characters cannot survive into the header.
const cleaned = [...trimmed]
.filter((char) => {
const code = char.codePointAt(0)!
return char !== '\\' && char !== '/' && char !== '"' && char !== '\'' && code >= 0x20 && code !== 0x7F
})
.join('')
.trim()
.replace(/^\.+/, '')
.slice(0, ARCHIVE_NAME_MAX)
if (cleaned === '') return 'archive.zip'
return cleaned.toLowerCase().endsWith('.zip') ? cleaned : `${cleaned}.zip`
/** The finished archive on disk. */
interface ArchiveFile {
path: string
size: number
}
/** One archive build: the state the client polls, plus the finished file. */
interface ArchiveTask {
id: string
sessionId: string
/** The final download name (the tool's extension already applied). */
name: string
state: 'building' | 'ready' | 'error'
/** Bytes written so far (the temp file's size while building). */
bytes: number
error?: string
file?: ArchiveFile
/** When the task stops being downloadable (set when it settles). */
expiresAt: number
}
/** The status shape the client reads (never carries the bytes). */
export interface ArchiveStatus {
state: 'building' | 'ready' | 'error'
bytes: number
error?: string
}
/** Why a download/status read could not be served. */
export type ArchiveLookup =
| { ok: true; task: ArchiveTask }
| { ok: false; reason: 'missing' | 'forbidden' | 'building' | 'expired' | 'error'; message: string }
/**
* The `content-disposition` value for one archive download.
*
@@ -74,163 +115,11 @@ function asciiFallbackOf(name: string): string {
return code >= 0x20 && code <= 0x7E && char !== '"' && char !== '\\'
})
.join('')
const stem = ascii.replace(/\.zip$/i, '')
const stem = ascii.replace(/\.(?:zip|tar\.gz)$/i, '')
if (stem === '' || /^\.+$/.test(stem)) return 'download.zip'
return ascii
}
/**
* The in-archive name of every selection, disambiguated.
*
* The common case keeps the intuition "one selection is named by its own
* basename" — archive `/ws/src` and the entries live under `src/`. Two
* selections that would collide (multi-select `/ws/a/index.ts` and
* `/ws/b/index.ts` both wanting `index.ts`) are extended with parent
* segments until every name is unique, so an extractor cannot silently
* overwrite one member with another. A path that runs out of ancestors
* (selecting the filesystem root, or `/a` twice) falls back to the full
* '/'-joined path, which is unique by construction.
*
* @param selections - absolute (already fenced) paths, in selection order.
* @returns one '/'-separated archive name per selection, same order.
*/
export function disambiguateArchiveNames(selections: readonly string[]): string[] {
const segmentsOf = (absolute: string, depth: number): string => {
const parts: string[] = []
let current = absolute
for (let level = 0; level < depth; level += 1) {
const part = basename(current)
const parent = dirname(current)
if (part === '' || parent === current) break
parts.unshift(part)
current = parent
}
return parts.join('/')
}
const deepEnough = (absolute: string, name: string): string => {
const full = segmentsOf(absolute, Number.MAX_SAFE_INTEGER)
// Still colliding after every segment is in play (two identical paths, or
// a root-level duplicate): the full path is the best available identity.
return full === name ? absolute.replace(/^\/+/, '') : name
}
const depth = new Map<string, number>(selections.map(path => [path, 1]))
for (let round = 0; round < 64; round += 1) {
const names = selections.map(path => segmentsOf(path, depth.get(path)!))
const counts = new Map<string, number>()
for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1)
if ([...counts.values()].every(count => count === 1)) return names
const grown = new Set<string>()
for (const [index, path] of selections.entries()) {
if ((counts.get(names[index]!) ?? 0) <= 1) continue
depth.set(path, depth.get(path)! + 1)
grown.add(path)
}
if (grown.size === 0) break
}
return selections.map(path => deepEnough(path, segmentsOf(path, depth.get(path)!)))
}
/**
* Collect one selected path into the archive: a file becomes one entry, a
* directory is walked depth-first and each level contributes its own entry
* (a trailing '/' name), files keep their layout under the directory's own
* name. Symlinks are skipped, never followed. Iterative (an explicit stack)
* because a deep tree must not blow the JS stack, and the count bound is
* enforced HERE so a runaway directory fails before its rows pile up.
*
* @param absolute - the (already fenced) absolute path of the selection.
* @param name - the in-archive name of that selection (its basename).
* @param out - the entry list appended to, in archive order.
* @param maxEntries - entry-count bound.
* @throws {SidebarError} fs-error when a row cannot be read or the bound is hit.
*/
export async function collectZipEntries(
absolute: string,
name: string,
out: ZipEntry[],
maxEntries = ZIP_MAX_ENTRIES,
): Promise<void> {
const stack: Array<{ path: string; name: string }> = [{ path: absolute, name }]
while (stack.length > 0) {
const item = stack.pop()!
if (out.length >= maxEntries) {
throw new SidebarError('fs-error', `too many entries for one archive (> ${maxEntries})`, 400)
}
const info = await lstat(item.path).catch((error: unknown) => {
throw new SidebarError('fs-error', `cannot read "${item.path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
if (info.isSymbolicLink()) {
// A link row is not a file to read and not a directory to walk: it is
// skipped (an archive of a dangling link has nothing to store). Never
// followed — no escape and no cycle.
continue
}
if (!info.isDirectory()) {
out.push({ path: item.path, name: item.name })
continue
}
out.push({ path: item.path, name: item.name, isDir: true })
let level
try {
level = await readdir(item.path, { withFileTypes: true })
} catch (error) {
throw new SidebarError('fs-error', `cannot list "${item.path}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
// Reverse order: the stack pops the first child next, so the archive reads
// top-down in directory order.
for (let index = level.length - 1; index >= 0; index -= 1) {
const child = level[index]!
stack.push({ path: join(item.path, child.name), name: `${item.name}/${child.name}` })
}
}
}
/** How many archives one host may build at the same time. */
export const ARCHIVE_MAX_BUILDING = 4
/** How long a finished (or failed) archive stays downloadable. */
export const ARCHIVE_TTL_MS = 5 * 60 * 1000
/** One archive build: the state the client polls, plus the finished bytes. */
interface ArchiveTask {
id: string
sessionId: string
name: string
state: 'building' | 'ready' | 'error'
done: number
total: number
bytes: number
error?: string
zip?: Buffer
/** When the task stops being downloadable (set when it settles). */
expiresAt: number
}
/** The status shape the client reads (never carries the bytes). */
export interface ArchiveStatus {
state: 'building' | 'ready' | 'error'
done: number
total: number
bytes: number
error?: string
}
/** Why a download/status read could not be served. */
export type ArchiveLookup =
| { ok: true; task: ArchiveTask }
| { ok: false; reason: 'missing' | 'forbidden' | 'building' | 'expired' | 'error'; message: string }
/** A resolved download: the bytes plus the sanitized name they were built for. */
export interface ArchiveDownload {
name: string
zip: Buffer
}
/** The response face {@link respondArchiveDownload} writes through. */
export interface ArchiveDownloadResponse {
writeHead(status: number, headers?: Record<string, string>): void
end(chunk?: Buffer | string): void
}
/**
* Answer one `GET /sidebar/archive?id=&sessionId=` from the task table.
*
@@ -239,75 +128,104 @@ export interface ArchiveDownloadResponse {
* for a failed build, 404 for unknown/expired/already-downloaded, 200 with the
* RFC 5987 disposition otherwise. Kept here so all six branches are testable
* without a live cordis mount.
*
* The bytes are STREAMED from the temp file and the task is released only once
* the stream settles: releasing first (as the buffered version could) would
* unlink the file the response is still reading from.
*
* @param tasks - the plugin's task table.
* @param query - the request's `sessionId` / `id` values (null = absent).
* @param res - a minimal response face.
* @param res - the response face.
* @throws {SidebarError} for every non-200 branch (callers turn it into the
* JSON error envelope they already use).
* JSON error envelope they already use). Thrown BEFORE any header commits, so
* the envelope is still deliverable.
*/
export function respondArchiveDownload(
export async function respondArchiveDownload(
tasks: ArchiveTasks,
query: { sessionId: string | null; id: string | null },
res: ArchiveDownloadResponse,
): void {
res: SidebarHttpResponse,
): Promise<void> {
if (query.sessionId === null || query.id === null || query.id === '') {
throw new SidebarError('bad-request', 'sessionId and id are required')
}
const found = tasks.lookup(query.id, query.sessionId)
if (!found.ok || found.task.state !== 'ready' || found.task.zip === undefined) {
if (!found.ok || found.task.state !== 'ready' || found.task.file === undefined) {
if (found.ok) throw new SidebarError('not-found', 'archive is gone', 404)
if (found.reason === 'building') throw new SidebarError('bad-request', found.message, 409)
if (found.reason === 'forbidden') throw new SidebarError('forbidden', found.message, 403)
if (found.reason === 'error') throw new SidebarError('fs-error', found.message, 410)
throw new SidebarError('not-found', found.message, 404)
}
const { name, zip } = found.task
// A download consumes the task: the bytes are not kept for a second fetch
// (the task table is a queue, not a store).
tasks.release(found.task.id)
res.writeHead(200, {
'content-type': 'application/zip',
// Never the raw name: a non-latin1 value (中文目录 → 报告.zip) makes Node's
// writeHead throw and turns the download into a 500.
'content-disposition': contentDispositionOf(name),
'content-length': String(zip.byteLength),
'cache-control': 'no-cache',
})
res.end(zip)
const { name, file } = found.task
const id = found.task.id
try {
await streamFileToResponse(file.path, file.size, res, {
// The extension follows the TOOL, not the client's guess: a host with
// only `tar` sends a real .tar.gz rather than a mislabelled .zip.
'content-type': name.endsWith('.tar.gz') ? 'application/gzip' : 'application/zip',
// Never the raw name: a non-latin1 value (中文目录 → 报告.zip) makes Node's
// writeHead throw and turns the download into a 500.
'content-disposition': contentDispositionOf(name),
'cache-control': 'no-cache',
})
} finally {
// A download consumes the task: the bytes are not kept for a second fetch
// (the task table is a queue, not a store).
tasks.release(id)
}
}
/**
* The host-side archive task table.
*
* A selection is collected up front (cheap: names + sizes) and then zipped in
* the BACKGROUND, so the client can show progress instead of staring at a
* spinner: `start` returns an id immediately, `status` reports
* `building → ready | error`, and `download` hands over the bytes exactly once.
* The table is bounded twice — {@link ARCHIVE_MAX_BUILDING} concurrent builds
* and {@link ARCHIVE_TTL_MS} since a finished one — and every read is
* A selection is planned up front (cheap: one probe + a couple of path joins)
* and then packed in the BACKGROUND, so the client gets an id immediately and
* the download only starts once the bytes actually exist. The table is bounded
* twice — {@link ARCHIVE_MAX_BUILDING} concurrent builds and
* {@link ARCHIVE_TTL_MS} since a finished one — and every read is
* session-scoped, so one session can never fetch another's archive.
*/
export interface ArchiveTasks {
/** Start a build; rejects with bad-request when the concurrency cap is hit. */
start(input: { sessionId: string; name: string; entries: readonly ZipEntry[] }): { id: string; entries: number }
/** Start a build; rejects when the tool is missing or the cap is hit. */
start(input: { sessionId: string; name: string; paths: readonly string[] }): Promise<{ id: string; name: string; entries: number }>
/** Poll one task (a settled task past its TTL reads as missing). */
status(id: string, sessionId: string): ArchiveStatus
/** Look one task up for a download; `sessionId` must match the builder's. */
lookup(id: string, sessionId: string): ArchiveLookup
/** Release a task (called after its bytes were served). */
/** Release a task (called after its bytes were served): deletes the temp file. */
release(id: string): void
/** Number of live tasks (tests / diagnostics). */
size(): number
/** Kill every running build and delete every temp file (plugin teardown). */
dispose(): void
}
/** Options of {@link createArchiveTasks} (tests inject the spawn + temp dir). */
export interface ArchiveTaskOptions {
spawn?: ArchiveSpawn
/** Directory the temp archives live in (defaults to the OS temp directory). */
tempDir?: string
/** Resolve the archive tool (defaults to the real probe). `spawner` is
* undefined when the table was built without an injected spawn. */
resolveTool?: (spawner: ArchiveSpawn | undefined) => Promise<ArchiveToolSpec | undefined>
}
/** Create one archive task table (one per plugin mount). */
export function createArchiveTasks(): ArchiveTasks {
export function createArchiveTasks(options: ArchiveTaskOptions = {}): ArchiveTasks {
const tasks = new Map<string, ArchiveTask>()
/** Running children, by task id (teardown kills them). */
const children = new Map<string, { kill(): void }>()
const spawner = options.spawn ?? undefined
/** Drop settled tasks past their TTL (called on every access). */
const tempPathOf = (id: string, ext: string): string =>
join(options.tempDir ?? tmpdir(), archiveTempName(id, ext))
/** Drop settled tasks past their TTL, deleting the temp files they held. */
const sweep = (now: number): void => {
for (const [id, task] of tasks) {
if (task.state !== 'building' && task.expiresAt <= now) tasks.delete(id)
if (task.state === 'building' || task.expiresAt > now) continue
tasks.delete(id)
if (task.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {})
}
}
@@ -323,42 +241,44 @@ export function createArchiveTasks(): ArchiveTasks {
}
return {
start({ sessionId, name, entries }) {
async start({ sessionId, name, paths }) {
sweep(Date.now())
let building = 0
for (const task of tasks.values()) if (task.state === 'building') building += 1
if (building >= ARCHIVE_MAX_BUILDING) {
throw new SidebarError('bad-request', `too many archives are being built (max ${ARCHIVE_MAX_BUILDING})`, 409)
}
const resolve = options.resolveTool ?? resolveArchiveTool
// One call either way: `spawn` has a default, so passing `undefined`
// selects the real implementation without a second code path.
const spec = await resolve(spawner)
if (spec === undefined) {
// A NEW wire code, and deliberately its own: "this machine has no zip
// and no tar" is not a failure of the selection, and the client shows
// it as an actionable sentence rather than a raw English message.
throw new SidebarError(
'unavailable',
'no archive tool is available: neither zip nor tar could be run',
501,
)
}
const plan = planArchive(paths, spec)
const id = `ar-${randomUUID()}`
const finalName = archiveFileName(name, spec.ext)
const tempPath = tempPathOf(id, spec.ext)
const task: ArchiveTask = {
id: `ar-${randomUUID()}`,
id,
sessionId,
name,
name: finalName,
state: 'building',
done: 0,
total: entries.length,
bytes: 0,
expiresAt: Number.POSITIVE_INFINITY,
}
tasks.set(task.id, task)
tasks.set(id, task)
// Detached on purpose: the POST answers as soon as the id exists, and the
// task table (not the request) owns the error from here on.
void buildZip([...entries], {
onProgress: (progress) => {
task.done = progress.done
task.bytes = progress.bytes
},
}).then((zip) => {
task.zip = zip
task.state = 'ready'
task.done = task.total
task.expiresAt = Date.now() + ARCHIVE_TTL_MS
}, (error: unknown) => {
task.state = 'error'
task.error = error instanceof Error ? error.message : String(error)
task.expiresAt = Date.now() + ARCHIVE_TTL_MS
})
return { id: task.id, entries: entries.length }
void pack(id, task, plan, tempPath, spawner)
return { id, name: finalName, entries: paths.length }
},
status(id, sessionId) {
sweep(Date.now())
@@ -367,19 +287,82 @@ export function createArchiveTasks(): ArchiveTasks {
if (task.sessionId !== sessionId) throw new SidebarError('forbidden', 'archive belongs to another session', 403)
return {
state: task.state,
done: task.done,
total: task.total,
bytes: task.bytes,
...(task.error === undefined ? {} : { error: task.error }),
}
},
lookup,
release(id) {
const task = tasks.get(id)
tasks.delete(id)
if (task?.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {})
},
size() {
sweep(Date.now())
return tasks.size
},
dispose() {
for (const child of children.values()) {
try {
child.kill()
} catch {
// A child that already exited cannot be killed; nothing to do.
}
}
children.clear()
for (const task of tasks.values()) {
if (task.file !== undefined) void rm(task.file.path, { force: true }).catch(() => {})
}
tasks.clear()
},
}
/**
* Pack one task: open the temp file, hand its descriptor to the tool, and
* settle the task from the exit code.
*
* The descriptor stays open across the spawn and is closed only after the
* child exits — closing it earlier would truncate output still being written.
*/
async function pack(
id: string,
task: ArchiveTask,
plan: ArchivePlan,
tempPath: string,
spawner: ArchiveSpawn | undefined,
): Promise<void> {
const settle = (error: string | undefined): void => {
task.state = error === undefined ? 'ready' : 'error'
if (error !== undefined) task.error = error
task.expiresAt = Date.now() + ARCHIVE_TTL_MS
children.delete(id)
}
let handle: Awaited<ReturnType<typeof open>> | undefined
try {
handle = await open(tempPath, 'w')
const result = await runArchiveTool(plan, handle.fd, spawner, child => { children.set(id, child) })
await handle.close()
handle = undefined
if (result.code !== 0) {
settle(result.stderr === '' ? `${plan.spec.bin} exited with code ${result.code}` : result.stderr)
await rm(tempPath, { force: true }).catch(() => {})
return
}
const info = await stat(tempPath).catch(() => undefined)
if (info === undefined) {
settle(`${plan.spec.bin} produced no archive`)
return
}
task.bytes = info.size
task.file = { path: tempPath, size: info.size }
settle(undefined)
} catch (error: unknown) {
// A tool that cannot be started at all, or a disk that refuses the temp
// file. Either way the task must not stay `building` forever.
await handle?.close().catch(() => {})
task.bytes = await stat(tempPath).then(info => info.size).catch(() => 0)
settle(error instanceof Error ? error.message : String(error))
await rm(tempPath, { force: true }).catch(() => {})
}
}
}
+329
View File
@@ -0,0 +1,329 @@
/**
* Archive packing by the system's own tool, not by a writer of ours.
*
* This module replaces a hand-written ZIP encoder (~300 lines of local file
* headers, central directory, CRC-32 and raw DEFLATE) plus a recursive walk.
* Everything it did, `zip -r` does better: real DEFLATE, the platform's own
* path handling, and streaming output that grows with the data instead of a
* `Buffer.concat` of the whole archive.
*
* Two tools, tried in order, because neither is universal:
*
* - `zip` — what the file tree asks for, present on macOS and most Linux
* distributions. Always passed `-y`: without it Info-ZIP FOLLOWS symlinks,
* and a symlink loop (`a -> .`) then recurses until it is killed. `-y`
* stores the link itself, which is both loop-proof and a truer archive.
* (Verified against a real loop before this was written.)
* - `tar` — present everywhere the plugin realistically runs, including
* Windows 10 1803+, where it is a built-in `bsdtar` and there is no `zip` at
* all. GNU tar and bsdtar both take the same `-czf -` invocation.
*
* Output always goes to stdout (`-` as the archive name) so the caller decides
* where the bytes land; the route redirects them into a temp file, which is
* what keeps the download streamable without holding the archive in memory.
*
* Nothing in this module runs a shell: `spawn` takes an argv array, and every
* path is data. A path is never interpolated into a command string, so a
* filename with `;` or `$(...)` in it is a filename.
*
* The spawn/probe functions are injectable so the test suite never depends on
* a real `zip` being installed (AGENTS §6) — the same pattern `open-external`
* and `search-engines` use.
*/
import { spawn } from 'node:child_process'
import { dirname, relative, sep } from 'node:path'
import { SidebarError } from './wire.ts'
/** The archive tool actually in use. */
export type ArchiveTool = 'zip' | 'tar'
/** One available tool: its binary name, the invocation flags, and its suffix. */
export interface ArchiveToolSpec {
tool: ArchiveTool
bin: string
/** `-czf -` / `-r -q -X -y -`: everything before the entry names. */
flags: readonly string[]
/** The download-name extension this tool produces. */
ext: string
}
/**
* The invocation of one tool.
*
* `zip`'s `-` as the archive name means stdout, and the leading `-` in the
* argv is understood as that operand rather than as an option because it
* follows other flags.
*/
const TOOL_SPECS: Readonly<Record<ArchiveTool, ArchiveToolSpec>> = {
zip: { tool: 'zip', bin: 'zip', flags: ['-r', '-q', '-X', '-y', '-'], ext: '.zip' },
tar: { tool: 'tar', bin: 'tar', flags: ['-czf', '-'], ext: '.tar.gz' },
}
/** Order the tools are tried in (the `.zip` output is the better default). */
const TOOL_ORDER: readonly ArchiveTool[] = ['zip', 'tar']
/** How long one availability probe may take before the tool counts as absent. */
const PROBE_TIMEOUT_MS = 3000
/** How much stderr is kept for the failure message (tail, not head). */
export const ARCHIVE_STDERR_LIMIT = 4096
/** The spawn face this module needs (injectable for tests). */
export type ArchiveSpawn = typeof spawn
/** A resolved plan: where to run, what to run, and what to name the result. */
export interface ArchivePlan {
spec: ArchiveToolSpec
/** Working directory the tool runs in (the selections' common ancestor). */
cwd: string
/** Relative entry names, '/'-separated. */
args: string[]
}
/**
* Whether one candidate binary actually runs.
*
* `--version` rather than `--help`: Info-ZIP's `zip -h` is fine but bsdtar's
* help exits non-zero on some builds, and a tool that cannot answer
* `--version` is not one worth handing a user's directory to.
*/
function probeTool(bin: string, spawner: ArchiveSpawn): Promise<boolean> {
return new Promise<boolean>((resolve) => {
let settled = false
const finish = (ok: boolean): void => {
if (settled) return
settled = true
clearTimeout(timer)
resolve(ok)
}
let child: ReturnType<ArchiveSpawn>
try {
child = spawner(bin, ['--version'], { stdio: 'ignore', windowsHide: true })
} catch {
finish(false)
return
}
const timer = setTimeout(() => {
child.kill()
finish(false)
}, PROBE_TIMEOUT_MS)
child.once('error', () => { finish(false) })
child.once('exit', (code) => { finish(code === 0) })
})
}
/** Probe result cache: one process-wide answer per tool. */
const availability = new Map<ArchiveTool, Promise<ArchiveToolSpec | undefined>>()
/**
* The archive tool this host will use, or undefined when it has neither.
*
* The answer is cached for the process: `zip` does not appear or disappear
* between two file-tree clicks, and a probe costs a process spawn.
*
* @param spawner - the spawn implementation (tests inject a fake).
* @returns the tool spec, or undefined when no tool is available.
*/
export function resolveArchiveTool(spawner: ArchiveSpawn = spawn): Promise<ArchiveToolSpec | undefined> {
return tryTools(TOOL_ORDER, spawner)
}
/**
* Resolve the first available tool from an ordered list.
*
* @param order - tool names to try, in order.
* @param spawner - the spawn implementation.
* @returns the first tool that answers, or undefined.
*/
export async function tryTools(
order: readonly ArchiveTool[],
spawner: ArchiveSpawn = spawn,
): Promise<ArchiveToolSpec | undefined> {
for (const tool of order) {
const spec = TOOL_SPECS[tool]
let pending = availability.get(tool)
if (pending === undefined) {
pending = probeTool(spec.bin, spawner).then(ok => (ok ? spec : undefined))
availability.set(tool, pending)
}
// Sequential on purpose: the tools are tried in preference order, and a
// parallel probe would spawn a binary we may never use.
const found = await pending
if (found !== undefined) return found
}
return undefined
}
/** Drop the cached probe results (tests, and a profile change in dev). */
export function resetArchiveToolCache(): void {
availability.clear()
}
/** `/`-joined path segments, whatever separator the platform produced. */
function toArchiveName(path: string): string {
return sep === '/' ? path : path.split(sep).join('/')
}
/**
* Build the argv/cwd plan for one selection.
*
* The tool's working directory is the selections' deepest COMMON ancestor, and
* every selection is passed as its path relative to that directory — so the
* archive names reproduce the tree the user sees: one selection is named by
* its own basename (`src/`), two same-named files from different folders land
* under different parents, and a selection that IS the common ancestor pushes
* the base one level up so its name keeps a component.
*
* This replaces the old per-path "grow parent segments until unique" logic.
* A path relative to a common ancestor is unique by construction, so the
* disambiguation it performed is now a property of the layout instead of an
* algorithm.
*
* @param selections - absolute paths, already fenced by the caller.
* @param spec - the resolved tool.
* @returns the plan to spawn.
* @throws {SidebarError} bad-request when a selection has no usable name.
*/
export function planArchive(selections: readonly string[], spec: ArchiveToolSpec): ArchivePlan {
if (selections.length === 0) {
throw new SidebarError('bad-request', 'no paths to archive')
}
let base = commonAncestor(selections)
// A selection that IS the base would produce an empty argument. Step the
// base up so every argument keeps at least one component — which is also
// what gives the archive a sensible top-level entry.
if (selections.some(selection => relative(base, selection) === '')) {
const parent = dirname(base)
if (parent === base) {
throw new SidebarError('bad-request', 'cannot archive the filesystem root')
}
base = parent
}
const args = selections.map(selection => toArchiveName(relative(base, selection)))
if (args.some(name => name === '' || name === '..' || name.startsWith('../'))) {
throw new SidebarError('bad-request', 'selection is not below the archive root')
}
return { spec, cwd: base, args: [...spec.flags, ...args] }
}
/**
* The deepest directory containing every selection.
*
* Walked segment by segment rather than by `dirname` until the paths agree, so
* a single selection resolves to its OWN directory (the case the archive needs:
* `zip -r archive.zip src` from the parent, not `zip -r archive.zip .` from
* inside `src`).
*/
function commonAncestor(selections: readonly string[]): string {
const [first, ...rest] = selections
if (first === undefined) throw new SidebarError('bad-request', 'no paths to archive')
if (rest.length === 0) return dirname(first)
let base = first
for (const selection of rest) {
while (!isWithin(base, selection)) {
const parent = dirname(base)
if (parent === base) return parent
base = parent
}
}
return base
}
/** Whether `target` is `base` itself or lives below it (lexically). */
function isWithin(base: string, target: string): boolean {
if (base === target) return true
const rel = relative(base, target)
return rel !== '' && !rel.startsWith('..') && !rel.startsWith(`..${sep}`)
}
/** The outcome of one tool run. */
export interface ArchiveRunResult {
/** The tool's exit code (0 = success). */
code: number
/** The tail of stderr, for the failure message. */
stderr: string
}
/**
* Run one planned tool, writing the archive to an already-open file handle.
*
* The caller owns the file descriptor: it stays open across the spawn so the
* tool writes straight into the temp file, and the caller closes it once this
* promise settles (closing it earlier would truncate a running child's output).
*
* @param plan - the plan from {@link planArchive}.
* @param outputFd - writable file descriptor for the archive bytes.
* @param spawner - the spawn implementation.
* @param onSpawn - receives the child as soon as it exists, so the caller can
* hold on to it (plug-in teardown kills the builds it started).
* @returns the exit code and the stderr tail; never rejects for a tool that
* ran and failed (a non-zero code is a result, not an exception).
* @throws {SidebarError} fs-error when the tool cannot be started at all.
*/
export function runArchiveTool(
plan: ArchivePlan,
outputFd: number,
spawner: ArchiveSpawn = spawn,
onSpawn?: (child: ReturnType<ArchiveSpawn>) => void,
): Promise<ArchiveRunResult> {
return new Promise<ArchiveRunResult>((resolve, reject) => {
const child = spawner(plan.spec.bin, plan.args, {
cwd: plan.cwd,
stdio: ['ignore', outputFd, 'pipe'],
windowsHide: true,
})
onSpawn?.(child)
let stderr = ''
child.stderr?.on('data', (chunk: Buffer | string) => {
stderr += typeof chunk === 'string' ? chunk : chunk.toString('utf8')
// Keep only the tail: the last lines are the ones that name the actual
// problem, and an unbounded log from a failed walk is not worth holding.
if (stderr.length > ARCHIVE_STDERR_LIMIT * 2) {
stderr = stderr.slice(-ARCHIVE_STDERR_LIMIT)
}
})
child.once('error', (error: Error) => {
reject(new SidebarError('fs-error', `cannot run ${plan.spec.bin}: ${error.message}`))
})
child.once('close', (code: number | null) => {
resolve({ code: code ?? 1, stderr: stderr.slice(-ARCHIVE_STDERR_LIMIT).trim() })
})
})
}
/** The default in-archive stem when the caller named nothing usable. */
const DEFAULT_STEM = 'archive'
/** Maximum stem length, so the Content-Disposition header stays sane. */
export const ARCHIVE_STEM_MAX = 100
/**
* Sanitize a caller-supplied archive NAME into a stem, then apply the tool's
* extension. Separators, control characters and quotes are stripped (a name
* must never look like a path), and any archive suffix the caller guessed is
* removed — the tool decides the real extension, not the client.
*
* @param raw - the requested name ('' or a bare suffix yields the default).
* @param ext - the extension the resolved tool produces ('.zip' / '.tar.gz').
* @returns a flat file name with that extension.
*/
export function archiveFileName(raw: string, ext: string): string {
const stripped = raw.trim()
.replace(/\.(?:zip|tar(?:\.gz)?|tgz)$/i, '')
.trim()
const cleaned = [...stripped]
.filter((char) => {
const code = char.codePointAt(0)!
return char !== '/' && char !== '\\' && char !== '"' && char !== '\'' && code >= 0x20 && code !== 0x7F
})
.join('')
.trim()
.replace(/^\.+/, '')
.slice(0, ARCHIVE_STEM_MAX)
return `${cleaned === '' ? DEFAULT_STEM : cleaned}${ext}`
}
/** The temporary archive file's name in the OS temp directory. */
export function archiveTempName(id: string, ext: string): string {
return `dsh-better-sidebar-${id}${ext}`
}
+12 -11
View File
@@ -50,7 +50,7 @@ import css from './sidebar.module.css'
type EditorLoad =
| { status: 'loading' }
| { status: 'error'; message: string }
| { status: 'ready'; viewer: FileViewerDescriptor; content?: string; truncated?: boolean; mtimeMs?: number; mediaUrl?: string; customData?: unknown }
| { status: 'ready'; viewer: FileViewerDescriptor; content?: string; size?: number; largeFile?: { size: number }; mtimeMs?: number; mediaUrl?: string; customData?: unknown }
| { status: 'binary' }
/** The docked tree panel's width bounds (drag-resize clamps into them). */
@@ -398,7 +398,8 @@ export function EditorHost(props: {
status: 'ready',
viewer: action.viewer,
content: action.content,
truncated: action.truncated,
size: action.size,
largeFile: action.largeFile,
mediaUrl: action.mediaUrl,
customData: action.customData,
})
@@ -415,13 +416,9 @@ export function EditorHost(props: {
case 'fetchFsRead':
api.fsRead(scope, path).then((result) => {
if (cancelled) return
// Binary reads carry the head bytes for the detect re-match.
const outcome = planFsReadOutcome(action.viewer, {
binary: result.kind === 'binary',
content: result.kind === 'text' ? result.content : '',
truncated: result.truncated,
head: result.kind === 'binary' ? result.head : undefined,
}, (head) => ctx.get('betterSidebar')?.matchFileViewer(path, head), mediaUrlOf)
// The host answers one of three shapes; binary and too-large both
// carry the head bytes for the detect re-match (see editor-load.ts).
const outcome = planFsReadOutcome(action.viewer, result, (head) => ctx.get('betterSidebar')?.matchFileViewer(path, head), mediaUrlOf)
// Carry the read's mtime into the rendered viewer: the text
// editor uses it as the save baseline (fs-conflict on drift).
if (outcome.kind === 'render') setLoad({ ...outcome, status: 'ready', mtimeMs: result.mtimeMs })
@@ -568,7 +565,7 @@ export function EditorHost(props: {
</div>
)}
{toolbar?.dirty === true && <span className={css.dirtyDot} title={t('unsaved')} />}
{toolbar?.editable === true && toolbar?.truncated !== true && (
{toolbar?.editable === true && toolbar?.largeFile !== true && (
<button
type="button"
className={css.iconButton}
@@ -618,12 +615,16 @@ export function EditorHost(props: {
// gets the field and ignores it.
line: tab.line,
content: load.content,
truncated: load.truncated,
size: load.size,
largeFile: load.largeFile,
mtimeMs: load.mtimeMs,
mediaUrl: load.mediaUrl,
customData: load.customData,
// The viewer's toolbar always hoists into this host's header.
toolbar: 'host',
// Native tabs stay mounted while parked; an over-limit preview
// reads pages only while somebody is looking (see FileViewerProps).
visible,
onToolbarState,
onToolbarControls,
onReload: refreshFile,
+51 -59
View File
@@ -53,7 +53,7 @@ import {
} from '@deepseek-ai/dsh-client-ui-primitives'
import { SiCursor, SiZedindustries } from 'react-icons/si'
import { VscFolderOpened, VscLinkExternal, VscPin, VscPinned } from 'react-icons/vsc'
import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type FsEntry, type FsLevel } from './api.ts'
import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, SidebarApiError, type FsEntry, type FsLevel } from './api.ts'
import { compactChain, compactLoadTargets } from './file-tree-compact.ts'
import { DEFAULT_FILE_TREE_SORT, sortEntries, type FileTreeSort } from './file-tree-sort.ts'
import { FS_TREES_MAX_PATHS } from '../fs-batch.ts'
@@ -144,12 +144,6 @@ function badgeToneOf(tone: GitTone): StatusTone {
return tone === 'copied' ? 'added' : tone
}
/** The archive progress line's percentage (`0/0` — an empty selection — is 0%). */
function archivePercent(progress: { done: number; total: number }): number {
if (progress.total <= 0) return 0
return Math.min(100, Math.round((progress.done / progress.total) * 100))
}
/**
* The drop overlay's hero art: an arrow rising out of a notched tray
* (upload zone — the same glyph family as the toolbar's upload icon) and a
@@ -1632,20 +1626,19 @@ export function FileTree(props: {
/**
* Zip the selection through the host's ASYNC archive route:
*
* archiveBuild(scope, paths, name) → { id, entries }
* archiveBuild(scope, paths, stem) → { id, name }
* → poll archiveStatus(id) every 250ms (self-scheduling: one request in
* flight) while the job builds, driving the `zipProgress` line
* → state 'ready' → fetch(archiveDownloadUrl(scope, id)) → blob → hidden
* `<a download>` (the bytes are fetched explicitly because a bare anchor
* would save the route's JSON error envelope as a broken .zip)
* → any failure (build / status / download) → `zipFailed` in the strip.
* flight) while the system's zip/tar packs into a temp file; the strip
* shows a plain "packing" line, because a child process reports no
* per-entry progress
* → state 'ready' → a plain `<a download>` on the route URL, which the
* browser streams to disk (see saveArchive for why it is not a blob)
* → any failure (tool missing / build / status) → `zipFailed` in the strip.
*
* `archiveBusyRef` keeps a repeated pick from starting a second job (the
* visible progress line is the feedback), and `archiveProgress` carries the
* live `done/total` for the line and its percentage.
* `archiveBusyRef` keeps a repeated pick from starting a second job — the
* visible packing line is the feedback.
*/
const [archiveBusy, setArchiveBusy] = useState(false)
const [archiveProgress, setArchiveProgress] = useState<{ done: number; total: number } | null>(null)
const archiveBusyRef = useRef(false)
/** The job being polled (state so the poller starts/stops with it). */
const [archiveJobId, setArchiveJobId] = useState<string | null>(null)
@@ -1663,7 +1656,6 @@ export function FileTree(props: {
archiveHandedOffRef.current = false
setArchiveJobId(null)
setArchiveBusy(false)
setArchiveProgress(null)
}, [])
// A session/cwd swap abandons the archive job with it — the progress strip
@@ -1680,37 +1672,33 @@ export function FileTree(props: {
settleArchive()
}, [settleArchive])
/** Save the finished archive as `name` through a hidden anchor. */
/**
* Save the finished archive through a plain anchor on the route URL.
*
* Deliberately NOT `fetch → blob → objectURL` any more, which is what the
* flow used to do: a Blob holds the whole archive in the TAB's memory, so a
* multi-gigabyte selection would kill the page — the very thing the host
* side was just changed to stop doing. A plain anchor hands the URL to the
* browser's download machinery, which streams it to disk.
*
* The cost, stated plainly: the route's JSON error envelope can no longer be
* inspected, so a failure at this point saves a JSON body under the archive's
* name. Everything that realistically fails — no tool installed, an
* unreadable selection, a tool that exited non-zero — is caught by the
* `archive.status` poll BEFORE this runs, so what is left is an
* already-consumed or expired task between the poll and the click.
*/
const saveArchive = useCallback((id: string, name: string): void => {
void fetch(archiveDownloadUrl({ sessionId, cwd }, id))
.then(async (response) => {
if (!response.ok) {
const envelope: { error?: { message?: string } } | null = await response.json().catch(() => null)
throw new Error(envelope?.error?.message ?? `HTTP ${response.status}`)
}
return await response.blob()
})
.then((blob) => {
setActionError(null)
const objectUrl = URL.createObjectURL(blob)
const anchor = document.createElement('a')
anchor.href = objectUrl
anchor.download = name
anchor.style.display = 'none'
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
// Revoke on the next task, not synchronously: some engines have not
// committed the download when click() returns, and revoking the URL
// under them loses the file. One tick is enough and keeps the blob
// from outliving the download.
window.setTimeout(() => { URL.revokeObjectURL(objectUrl) }, 0)
settleArchive()
})
.catch((error: unknown) => {
failArchive(error instanceof Error ? error.message : String(error))
})
}, [cwd, failArchive, sessionId, settleArchive])
setActionError(null)
const anchor = document.createElement('a')
anchor.href = archiveDownloadUrl({ sessionId, cwd }, id)
anchor.download = name
anchor.style.display = 'none'
document.body.appendChild(anchor)
anchor.click()
anchor.remove()
settleArchive()
}, [cwd, sessionId, settleArchive])
/** The poller's callbacks, read through a ref so the polling TASK stays
* identity-stable (a churned task restarts the loop every render). */
@@ -1727,7 +1715,6 @@ export function FileTree(props: {
// The transport may deliver a response after teardown; the signal is the
// only reliable staleness guard (the route call takes no signal).
if (signal.aborted) return
setArchiveProgress({ done: status.done, total: status.total })
if (status.state === 'error') {
archiveHandlersRef.current.fail(status.error ?? `HTTP ${status.state}`)
return
@@ -1750,21 +1737,30 @@ export function FileTree(props: {
const downloadArchive = (paths: readonly string[]): void => {
if (archiveBusyRef.current) return
const name = paths.length === 1 ? `${baseName(paths[0]!)}.zip` : 'archive.zip'
// The client names a STEM, not a file name: the host picks the extension
// from the tool it actually has (a host with only `tar` produces a real
// .tar.gz), and returns the final name with the build id.
const stem = paths.length === 1 ? baseName(paths[0]!) : 'archive'
const generation = scopeGenRef.current
archiveBusyRef.current = true
archiveHandedOffRef.current = false
setArchiveBusy(true)
setArchiveProgress(null)
void archiveBuild({ sessionId, cwd }, paths, name)
.then(({ id, entries }) => {
void archiveBuild({ sessionId, cwd }, paths, stem)
.then(({ id, name }) => {
if (generation !== scopeGenRef.current) return
setActionError(null)
archiveJobRef.current = { id, name }
setArchiveProgress({ done: 0, total: entries })
setArchiveJobId(id)
})
.catch((error: unknown) => {
if (generation !== scopeGenRef.current) return
// `unavailable` is its own sentence: "this machine has neither zip nor
// tar" is something the user can act on, and the host's English wire
// message is not the place to say it.
if (error instanceof SidebarApiError && error.code === 'unavailable') {
failArchive(t('archiveToolMissing'))
return
}
failArchive(error instanceof Error ? error.message : String(error))
})
}
@@ -2102,11 +2098,7 @@ export function FileTree(props: {
<Notice kind="warn" tone="inline">{loadError}</Notice>
)}
{archiveBusy && (
<Notice kind="loading" tone="inline" role="status">
{archiveProgress === null
? t('loading')
: `${t('zipProgress', { done: archiveProgress.done, total: archiveProgress.total })} · ${archivePercent(archiveProgress)}%`}
</Notice>
<Notice kind="loading" tone="inline" role="status">{t('loading')}</Notice>
)}
<RootRow
path={root}
+230
View File
@@ -0,0 +1,230 @@
/**
* The read-only paged preview for a file above the editable threshold.
*
* Two row shapes share one cursor ({@link useTextPager}):
*
* - `jsonl` — one row per record, collapsed to a one-line summary and
* expandable into the host's `JsonTree`. A page is line-aligned, so a page
* is exactly a run of whole records.
* - everything else — one row per line, monospace, no wrapping (horizontal
* scroll), which is the log-viewer shape and the reason a page's row count
* stays bounded.
*
* The pager is EXPLICIT (previous/next page) rather than an infinite scroll.
* Byte offsets only exist for pages already walked forward, so "scroll to the
* end" cannot be offered honestly without indexing the whole file on open;
* what the cursor CAN do is revisit any visited page in either direction, and
* the pager says exactly that. See text-pages.ts for the full reasoning.
*
* Nothing here fetches the document: the file is above the editor's limit
* precisely because holding it whole is what we are avoiding.
*/
import { useMemo, useState, type ReactNode } from 'react'
import clsx from 'clsx'
import { IconChevronLeftOutlineRegular, IconChevronRightOutlineRegular, IconRefreshOutlineRegular, JsonTree, type JsonTreeLabels } from '@deepseek-ai/dsh-client-ui-primitives'
import type { SessionScope } from './api.ts'
import { downloadUrl } from './api.ts'
import { formatByteSize, MAX_EDITABLE_LABEL } from '../editor-limits.ts'
import { isJsonlPath, isTreeRecord, parseRecord, summarizeRecord } from './jsonl.ts'
import { splitLines, useTextPager } from './text-pages.ts'
import { t } from './locales.ts'
import css from './sidebar.module.css'
/** Copy the host's `JsonTree` needs; this plugin owns the wording. */
function jsonLabels(): JsonTreeLabels {
return {
// The tree's primitive/compact copy actions are the same gesture as the
// code block's copy, so they reuse that wording rather than inventing a
// second vocabulary for the same button.
copyValue: t('copy'),
copyJson: t('copy'),
copyPath: t('jsonCopyPath'),
copyPrettyJson: t('jsonCopyPrettyJson'),
copyCompactJson: t('jsonCopyCompactJson'),
copied: t('copied'),
copyFailed: t('jsonCopyFailed'),
collapseNode: t('jsonCollapseNode'),
expandNode: t('jsonExpandNode'),
copyButtonTitle: (action) => t('jsonCopyButtonTitle', { action }),
}
}
/**
* The read-only preview of one over-limit file.
*
* @param props.scope - the session scope.
* @param props.path - the file being previewed.
* @param props.size - the file's size in bytes (from the read that refused it).
* @param props.visible - whether the tab is on screen; a parked tab stops reading.
* @param props.revision - bumped by the host's refresh to restart from page 1.
* @returns the preview.
*/
export function LargeFileView(props: {
scope: SessionScope
path: string
size: number
visible: boolean
revision: number
}): ReactNode {
const { scope, path, size, visible, revision } = props
const pager = useTextPager(scope, path, visible, revision)
const records = isJsonlPath(path)
const rows = useMemo(() => splitLines(pager.text), [pager.text])
/** Which record rows are expanded (reset with every page). */
const [expanded, setExpanded] = useState<ReadonlySet<number>>(new Set())
const pageKey = `${pager.page}`
const labels = useMemo(() => jsonLabels(), [])
const parsed = useMemo(
() => (records ? rows.map(parseRecord) : []),
[records, rows],
)
/** Absolute line/record number of row `index` on the current page. */
const numberAt = (index: number): number => pager.firstLine + index
const selectPage = (next: () => void): void => {
setExpanded(new Set())
next()
}
return (
<div className={css.largeFile}>
<div className={css.largeFileNotice}>
<span>{t('previewOnlyNotice', { size: formatByteSize(size), limit: MAX_EDITABLE_LABEL })}</span>
<a className={css.largeFileDownload} href={downloadUrl(scope, path)} download>
{t('downloadToView')}
</a>
</div>
<div className={clsx(css.largeFileBody, records && css.largeFileRecords)}>
{pager.error !== null && <div className={css.editorError}>{pager.error}</div>}
{pager.error === null && pager.loading && pager.text === '' && (
<div className={css.editorPlaceholder}>{t('loading')}</div>
)}
{pager.error === null && !(pager.loading && pager.text === '') && records && (
<ol className={css.largeFileList} start={pager.firstLine}>
{parsed.map((record, index) => (
<RecordRow
key={`${pageKey}:${index}`}
number={numberAt(index)}
line={rows[index] ?? ''}
record={record}
expanded={expanded.has(index)}
labels={labels}
onToggle={() => {
setExpanded((previous) => {
const next = new Set(previous)
if (next.has(index)) next.delete(index)
else next.add(index)
return next
})
}}
/>
))}
</ol>
)}
{pager.error === null && !(pager.loading && pager.text === '') && !records && (
<div className={css.largeFileLines}>
{rows.map((line, index) => (
<div className={css.largeFileLine} key={`${pageKey}:${index}`}>
<span className={css.largeFileLineNo} aria-hidden="true">{numberAt(index)}</span>
<span className={css.largeFileLineText}>{line === '' ? '\u00a0' : line}</span>
</div>
))}
{rows.length === 0 && !pager.loading && (
<div className={css.editorPlaceholder}>{t('largeFileEmpty')}</div>
)}
</div>
)}
</div>
<div className={css.largeFilePager}>
<button
type="button"
className={css.iconButton}
aria-label={t('pagedPrev')}
title={t('pagedPrev')}
disabled={pager.page <= 1 || pager.loading}
onClick={() => { selectPage(pager.prev) }}
>
<IconChevronLeftOutlineRegular size={14} />
</button>
<span className={css.largeFilePageLabel}>
{records
? t('jsonlRecordRange', { from: pager.firstLine, to: numberAt(Math.max(0, rows.length - 1)) })
: t('pagedLineRange', { from: pager.firstLine, to: numberAt(Math.max(0, rows.length - 1)) })}
{' · '}
{pager.atEnd ? t('pagedPageOfTotal', { page: pager.page, total: pager.page }) : t('pagedPage', { page: pager.page })}
</span>
<button
type="button"
className={css.iconButton}
aria-label={t('pagedNext')}
title={pager.atEnd ? t('pagedEnd') : t('pagedNext')}
disabled={pager.atEnd || pager.loading}
onClick={() => { selectPage(pager.next) }}
>
<IconChevronRightOutlineRegular size={14} />
</button>
<button
type="button"
className={css.iconButton}
aria-label={t('refresh')}
title={t('refresh')}
onClick={pager.reload}
>
<IconRefreshOutlineRegular size={14} />
</button>
</div>
</div>
)
}
/** One JSONL record row: a summary line, expanding into the host's JSON tree. */
function RecordRow(props: {
number: number
/** The raw line, shown verbatim when the record does not parse. */
line: string
record: ReturnType<typeof parseRecord>
expanded: boolean
labels: JsonTreeLabels
onToggle: () => void
}): ReactNode {
const { number, line, record, expanded, labels, onToggle } = props
if (!record.ok) {
// A blank line is not a broken record — JSONL files normally end with one,
// and the host's pages are line-aligned, so it lands as its own row.
if (record.error === '') return null
return (
<li className={clsx(css.largeFileRecord, css.largeFileRecordInvalid)}>
<span className={css.largeFileRecordNo} aria-hidden="true">{number}</span>
<div className={css.largeFileRecordBody}>
<div className={css.largeFileRecordSummary}>{t('jsonlInvalidRecord')}</div>
<pre className={css.largeFileRecordRaw}>{line}</pre>
</div>
</li>
)
}
const value = record.value
const tree = isTreeRecord(value)
return (
<li className={clsx(css.largeFileRecord, expanded && css.largeFileRecordExpanded)}>
<span className={css.largeFileRecordNo} aria-hidden="true">{number}</span>
<div className={css.largeFileRecordBody}>
<button
type="button"
className={css.largeFileRecordSummary}
aria-expanded={tree ? expanded : undefined}
disabled={!tree}
onClick={onToggle}
>
{summarizeRecord(value)}
</button>
{tree && expanded && (
<div className={css.largeFileRecordTree}>
<JsonTree data={value} label={`#${number}`} labels={labels} copyable expandTopLevel />
</div>
)}
</div>
</li>
)
}
+59 -28
View File
@@ -43,6 +43,7 @@ import { useSelectionPopup } from './selection-popup.ts'
import { buildSelectionInsert, linesOfSelection } from './selection-payload.ts'
import { analyzeMarkdownHtml } from './markdown-html.ts'
import { LazyMermaidMarkdown, MarkdownDocument, type MarkdownHtmlMedia } from './MarkdownHtml.tsx'
import { LargeFileView } from './LargeFileView.tsx'
import { useMarkdownSurface } from './use-markdown-surface.ts'
import { MdToc } from './md-toc.tsx'
import { splitMermaidBlocks } from './mermaid-blocks.ts'
@@ -72,7 +73,7 @@ function sameDocument(a: string, b: string): boolean {
}
export function TextEditor(props: FileViewerProps) {
const { ctx, scope, path, viewerId, content, truncated, line } = props
const { ctx, scope, path, viewerId, content, size, largeFile, line } = props
const [mode, setMode] = useState<ViewMode>('preview')
/** The editor's current text (null while clean); preview renders this. */
const [draft, setDraft] = useState<string | null>(null)
@@ -123,6 +124,12 @@ export function TextEditor(props: FileViewerProps) {
}, [markdownSurfaceRef])
const markdown = viewerId === 'markdown'
const html = viewerId === 'html'
/** Newline-delimited JSON: it has its own preview (one card per record) on
* top of the shared editable CodeMirror surface. */
const jsonl = viewerId === 'jsonl'
/** The file is above the editable threshold: the viewer renders the
* read-only paged preview and no editor at all. */
const readOnly = largeFile !== undefined
/** The uncommitted-change gutter (issue #212): the `code` viewer only,
* gated by ONE boolean setting (on by default). Nothing else — no
* end-of-line author widget, no badges, no animation. Read reactively
@@ -136,7 +143,7 @@ export function TextEditor(props: FileViewerProps) {
// client-side), so the store answers on both sides alike.
useCallback(() => props.store.getSnapshot().prefs.editorGitGutter !== false, [props.store]),
)
const gitGutterEnabled = viewerId === 'code' && gitGutterPref
const gitGutterEnabled = (viewerId === 'code' || viewerId === 'jsonl') && gitGutterPref
/** Bumped by every save: the uncommitted diff moved while the file's git
* status entry (which only tracks its XY code) did not. */
const [gitRevision, setGitRevision] = useState(0)
@@ -262,11 +269,6 @@ export function TextEditor(props: FileViewerProps) {
// is open, and the save key stays in the editor keymap unchanged.
...cmSearchExtensions(),
searchPhrases.of(),
// A truncated read only carries the first readLimit bytes; edits made
// on partial content must never be saved over the full file (issue
// #732), so the document is rendered read-only until a full read
// replaces it.
...(truncated === true ? [EditorState.readOnly.of(true)] : []),
...(language !== null ? [language] : []),
CodeMirrorView.updateListener.of((update) => {
if (update.docChanged) {
@@ -286,7 +288,7 @@ export function TextEditor(props: FileViewerProps) {
// selection anchors the floating "add to conversation" button above
// its head. Scrolling (geometry/viewport change) or losing focus
// hides it; typing collapses the selection and hides it too.
...(viewerId === 'code' || viewerId === 'markdown' ? [
...(viewerId === 'code' || viewerId === 'markdown' || viewerId === 'jsonl' ? [
CodeMirrorView.updateListener.of((update) => {
if (update.geometryChanged || update.viewportChanged) {
selectionPopup.hide()
@@ -340,7 +342,7 @@ export function TextEditor(props: FileViewerProps) {
// tab's lifetime, and the dark flip is handled by the reconfigure
// effect below (recreating the view here would drop the draft).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [content, path, truncated])
}, [content, path])
// Native sidebar tabs stay mounted while another tab is active. If a file
// is opened while that host is hidden, CodeMirror can measure its viewport at
@@ -408,10 +410,10 @@ export function TextEditor(props: FileViewerProps) {
if (view === null) return
const key = `${path}#${line}`
if (landedAtRef.current === key) return
// A markdown/html file opens in preview, which has no source lines to put
// a cursor on. The reference asked for source, so land in the editor; the
// key is NOT recorded yet, so the re-run after the flip does the jump.
if ((markdown || html) && mode === 'preview') {
// A markdown/html/jsonl file opens in a preview, which has no source lines
// to put a cursor on. The reference asked for source, so land in the
// editor; the key is NOT recorded yet, so the re-run after the flip jumps.
if ((markdown || html || jsonl) && mode === 'preview') {
setMode('edit')
return
}
@@ -474,14 +476,14 @@ export function TextEditor(props: FileViewerProps) {
view.dispatch({ effects: gitComp.reconfigure(gitGutterEnabled ? gitHost : null) })
}, [gitGutterEnabled, gitHost])
// Push the line map into the live view. `content` / `truncated` re-run this
// after the view was rebuilt for a new file, and `gitGutterEnabled` after a
// re-install (a reconfigured state field starts empty).
// Push the line map into the live view. `content` re-runs this after the
// view was rebuilt for a new file, and `gitGutterEnabled` after a re-install
// (a reconfigured state field starts empty).
useEffect(() => {
const view = viewRef.current
if (view === null) return
applyGitLineKinds(view, gitKinds)
}, [gitKinds, gitGutterEnabled, content, path, truncated])
}, [gitKinds, gitGutterEnabled, content, path])
// The editor may have been display:none while previewing; re-measure when
// it becomes visible again (CodeMirror sizes itself on reveal). A mode
@@ -558,11 +560,6 @@ export function TextEditor(props: FileViewerProps) {
const save = (): void => {
const view = viewRef.current
if (view === null || savingRef.current) return
// Defense in depth for issue #732: a truncated read only holds the first
// readLimit bytes, and fs.write replaces the whole file — saving partial
// content would destroy the tail. The readOnly extension already blocks
// edits; this guards the keymap path against future trigger points.
if (truncated === true) return
savingRef.current = true
setSaveState('saving')
// Optimistic concurrency: the draft was based on the bytes read at
@@ -701,6 +698,16 @@ export function TextEditor(props: FileViewerProps) {
)
}
const editable = content !== undefined
/**
* Whether the preview/edit toggle applies. It needs BOTH surfaces to exist:
* a read-only paged preview has no editor to switch to, and the `code`
* catch-all has no preview to switch to.
*/
const toggleable = !readOnly && (markdown || html || jsonl)
/** A non-CodeMirror surface currently owns the pane (markdown/html render, or
* the JSONL record list): the CodeMirror host stays mounted but hidden, so
* unsaved edits survive the round trip. */
const showingPreview = !readOnly && mode === 'preview' && (markdown || html || jsonl)
const saveLabel = saveState === 'saving' ? t('loading') : saveState === 'saved' ? t('saved') : saveState === 'failed' ? t('saveFailed') : ''
// Per-feature sandbox escape hatch: the global side card setting (warned)
// plus a per-surface temporary unlock. The unlock state starts at the
@@ -719,7 +726,7 @@ export function TextEditor(props: FileViewerProps) {
const lastToolbarRef = useRef('')
useEffect(() => {
if (!hostToolbar) return
const state: EditorToolbarState = { modes: markdown || html, mode, dirty, editable, truncated: truncated === true, saveState }
const state: EditorToolbarState = { modes: toggleable, mode, dirty, editable, ...(readOnly ? { largeFile: true } : {}), saveState }
const key = JSON.stringify(state)
if (lastToolbarRef.current === key) return
lastToolbarRef.current = key
@@ -734,11 +741,27 @@ export function TextEditor(props: FileViewerProps) {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [hostToolbar])
// Above the editable threshold there is no document to edit: the viewer is
// the read-only paged preview and nothing else. Returning before the editor
// subtree exists is deliberate — it is what guarantees no CodeMirror state
// can be built for a file we never loaded.
if (readOnly && largeFile !== undefined) {
return (
<LargeFileView
scope={scope}
path={path}
size={largeFile.size}
visible={props.visible !== false}
revision={props.mtimeMs ?? 0}
/>
)
}
return (
<>
{!hostToolbar && (
<div className={css.editorHeader}>
{(markdown || html) && (
{toggleable && (
<div className={css.editorModeToggle}>
<button
type="button"
@@ -767,7 +790,7 @@ export function TextEditor(props: FileViewerProps) {
// The panel lives in the CodeMirror surface: in preview mode the
// editor is hidden, so switch to edit first (the search panel is
// not part of the preview).
if (mode === 'preview' && (markdown || html)) setMode('edit')
if (mode === 'preview' && (markdown || html || jsonl)) setMode('edit')
const view = viewRef.current
if (view === null) return
view.focus()
@@ -777,7 +800,7 @@ export function TextEditor(props: FileViewerProps) {
<IconSearchOutlineRegular size={16} />
</button>
)}
{editable && truncated !== true && (
{editable && (
<button
type="button"
className={css.iconButton}
@@ -793,7 +816,6 @@ export function TextEditor(props: FileViewerProps) {
)}
{editable && (
<>
{truncated === true && <div className={css.editorBanner}>{t('truncation')}</div>}
{conflict && (
<div className={css.editorBanner}>
{t('saveConflict')}
@@ -807,11 +829,20 @@ export function TextEditor(props: FileViewerProps) {
</div>
)}
<div
className={clsx(css.editorCm, (markdown || html) && mode === 'preview' && css.editorCmHidden)}
className={clsx(css.editorCm, showingPreview && css.editorCmHidden)}
ref={hostRef}
/>
</>
)}
{jsonl && mode === 'preview' && (
<LargeFileView
scope={scope}
path={path}
size={size ?? content?.length ?? 0}
visible={props.visible !== false}
revision={props.mtimeMs ?? 0}
/>
)}
{markdown && mode === 'preview' && (
<div
className={css.editorMd}
+91 -28
View File
@@ -153,10 +153,35 @@ export interface GitBlameLine {
}
/** Text read result. `mtimeMs` is the save route's conflict baseline. */
export interface FsTextResult { kind: 'text'; content: string; truncated: boolean; mtimeMs?: number }
export interface FsTextResult { kind: 'text'; content: string; size: number; mtimeMs?: number }
/** Binary read result (no content; images load through the media route).
* `head` carries the first bytes (base64) for viewer detect sniffing. */
export interface FsBinaryResult { kind: 'binary'; size: number; truncated: boolean; mtimeMs?: number; head: string }
export interface FsBinaryResult { kind: 'binary'; size: number; mtimeMs?: number; head: string }
/**
* The file is above the editable threshold: the host sends no document, only
* the size and a 4 KiB sniff head. The viewer answers with a read-only paged
* preview, and the head still lets a `detect`-based viewer claim the file.
*/
export interface FsTooLargeResult { kind: 'too-large'; size: number; mtimeMs?: number; head: string }
/** One `fs.read` outcome. */
export type FsReadResult = FsTextResult | FsBinaryResult | FsTooLargeResult
/** One page of a large text file (see `fs.readPage`). */
export interface FsPageResult {
kind: 'text'
/** The page's decoded lines (normally whole lines — the host trims at a break). */
text: string
/** The byte offset this page started at (echoed back). */
offset: number
/** Where the next page starts; equals `size` once the file is exhausted. */
nextOffset: number
eof: boolean
/** The file's size in bytes. */
size: number
mtimeMs?: number
/** The encoding the first page established (later pages decode identically). */
encoding: string
}
/** The `subagents.live` response: one row per tree child (and the root). */
export type SubagentLiveResult = { live: Record<string, SidebarChildLiveView> }
@@ -271,8 +296,45 @@ async function fetchUpload<T>(
return readEnvelope<T>(response)
}
/** One request's session scope: the conversation id plus its cwd when known. */
export interface SessionScope {
/**
* Save one document through the sidebar's raw write route: the text IS the
* POST body, so the request never grows a JSON escaping layer and nothing caps
* the size a save can carry.
*
* The document is transported with LF line endings (CodeMirror has no other
* line model); the host restores the file's own encoding and line ending
* before writing, exactly as the old JSON route did.
*
* @param scope - the session scope.
* @param path - the file to write (absolute or session-relative).
* @param content - the document, LF line endings.
* @param expectedMtimeMs - the draft's baseline; a mismatch refuses with
* `fs-conflict`. Omitted = no gate.
* @returns the fresh mtime baseline after the write.
*/
async function fetchWrite(
scope: SessionScope,
path: string,
content: string,
expectedMtimeMs?: number,
): Promise<{ ok: true; mtimeMs?: number }> {
const params = new URLSearchParams({ sessionId: scope.sessionId, path })
if (scope.cwd !== undefined && scope.cwd !== '') params.set('cwd', scope.cwd)
if (expectedMtimeMs !== undefined) params.set('expectedMtimeMs', String(expectedMtimeMs))
let response: Response
try {
response = await fetch(hostRouteUrl(`sidebar/write?${params.toString()}`).href, {
method: 'POST',
headers: { 'content-type': 'text/plain; charset=utf-8' },
body: content,
})
} catch (error) {
throw new SidebarApiError('network', error instanceof Error ? error.message : String(error))
}
return readEnvelope<{ ok: true; mtimeMs?: number }>(response)
}
/** One request's session scope: the conversation id plus its cwd when known. */export interface SessionScope {
sessionId: string
/** The session's working directory from the client list summary (optional). */
cwd?: string
@@ -369,18 +431,21 @@ export const api = {
fsSearch: (scope: SessionScope, query: string, exclude?: readonly string[], signal?: AbortSignal) =>
call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query, exclude }), signal),
fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) =>
call<FsTextResult | FsBinaryResult>('fs.read', scopePayload(scope, { path }), signal),
/** Save a file. `expectedMtimeMs` is the mtime the draft was based on: a
* file that changed on disk since refuses with code `fs-conflict` (the
* editor then offers a reload) instead of clobbering those bytes. `null`
* (the file did not exist yet) and omitted (older callers) both mean no
* gate. The response carries the fresh baseline. */
call<FsReadResult>('fs.read', scopePayload(scope, { path }), signal),
/** One page of a large text file, for the read-only paged preview.
* `offset` is the byte position to start at (0 for the first page); the
* response carries where to continue. */
fsReadPage: (scope: SessionScope, path: string, offset: number, signal?: AbortSignal) =>
call<FsPageResult>('fs.readPage', scopePayload(scope, { path, offset }), signal),
/** Save a file through the raw `/sidebar/write` route (the document IS the
* request body — no JSON escaping, so nothing caps the saved size).
* `expectedMtimeMs` is the mtime the draft was based on: a file that
* changed on disk since refuses with code `fs-conflict` (the editor then
* offers a reload) instead of clobbering those bytes. `null` (the file did
* not exist yet) and omitted (older callers) both mean no gate. The
* response carries the fresh baseline. */
fsWrite: (scope: SessionScope, path: string, content: string, expectedMtimeMs?: number | null) =>
call<{ ok: true; mtimeMs?: number }>('fs.write', scopePayload(scope, {
path,
content,
...(expectedMtimeMs !== undefined ? { expectedMtimeMs } : {}),
})),
fetchWrite(scope, path, content, expectedMtimeMs ?? undefined),
/** Rename one tree row within its directory (single-segment name; the
* server refuses existing destinations, the workspace root, and — while
* the fence is armed — anything resolving outside the workspace). */
@@ -562,29 +627,27 @@ export function downloadUrl(scope: SessionScope, path: string): string {
}
/**
* Start one archive build. The host fences and walks the selection, then
* returns an id IMMEDIATELY — the zip itself is produced in the background and
* polled through {@link api.archiveStatus}. `paths` are absolute paths in the
* session's namespace (the same values `fsTree` / `downloadUrl` take).
* Start one archive build. The host fences the selection and returns an id
* IMMEDIATELY — the system's `zip` (or `tar`) packs it into a temp file in the
* background, polled through {@link api.archiveStatus}. `paths` are absolute
* paths in the session's namespace (the same values `fsTree` / `downloadUrl`
* take); `name` is a STEM, because the host appends the extension of the tool
* it actually has and returns the final name with the id.
*/
export function archiveBuild(
scope: SessionScope,
paths: readonly string[],
name: string,
): Promise<{ id: string; entries: number }> {
return call<{ id: string; entries: number }>('archive.build', scopePayload(scope, { paths: [...paths], name }))
): Promise<{ id: string; name: string; entries: number }> {
return call<{ id: string; name: string; entries: number }>('archive.build', scopePayload(scope, { paths: [...paths], name }))
}
/** One archive build's progress (the shape `archive.status` returns). */
/** One archive build's state (the shape `archive.status` returns). */
export interface ArchiveBuildStatus {
state: 'building' | 'ready' | 'error'
/** Entries finished so far. */
done: number
/** Entries the archive will contain. */
total: number
/** Uncompressed bytes read so far. */
/** Bytes written to the archive so far. */
bytes: number
/** Present only when `state === 'error'`. */
/** Present only when `state === 'error'` (the tool's own stderr tail). */
error?: string
}
+27 -3
View File
@@ -1,6 +1,6 @@
/**
* The 3 built-in file viewer descriptors (markdown / html / code), exactly
* like external plugins register theirs.
* The 4 built-in file viewer descriptors (markdown / html / jsonl / code),
* exactly like external plugins register theirs.
*
* DSH 0.1.7 ships `ui-sidebar-documentpreview`, its own code / spreadsheet /
* office / pdf / image / html / markdown / text previews with zoom and
@@ -10,6 +10,9 @@
* sanitation, floating TOC), which the user prefers to the host's;
* - `html` — the sandboxed iframe preview plus the host-less
* `htmlViewerNoSandbox` / `htmlViewerDefaultUnsafe` escape hatches;
* - `jsonl` — a record-per-row preview (the host maps `.jsonl` to its JSON
* highlighter but renders it as one long text document) with the JSONL
* editor behind the mode toggle;
* - `code` — the catch-all (`exts: []`, lowest priority) that claims any
* file no other viewer did, and it is an EDITABLE CodeMirror with save —
* the host's equivalents are read-only previews.
@@ -48,7 +51,7 @@ import { t } from '../locales.ts'
*/
const LazyTextEditor = lazyChunkComponent<FileViewerProps>('editor', (mod) => mod.TextEditor as ComponentType<FileViewerProps> | undefined)
/** The 3 built-in file viewer descriptors. */
/** The 4 built-in file viewer descriptors. */
export function builtinViewers(): readonly FileViewerDescriptor[] {
return [
{
@@ -81,6 +84,27 @@ export function builtinViewers(): readonly FileViewerDescriptor[] {
},
component: (props) => <LazyTextEditor {...props} />,
},
{
id: 'jsonl',
title: () => t('viewerJsonl'),
icon: (size: number) => <IconCodeOutlineRegular size={size} />,
// Newline-delimited JSON. It gets its own descriptor rather than riding
// the `code` catch-all so an external plugin can shadow exactly this
// format, and so the settings page can switch it off on its own.
exts: ['jsonl', 'ndjson'],
priority: 0,
fetchStrategy: 'fsRead',
// Same single gutter switch as the code viewer: the editor mode of a
// JSONL file is still an editable text surface.
settings: {
toggles: [{
key: 'editorGitGutter',
title: () => t('settingsEditorGitGutterTitle'),
desc: () => t('settingsEditorGitGutterDesc'),
}],
},
component: (props) => <LazyTextEditor {...props} />,
},
{
id: 'code',
title: () => t('viewerCode'),
+8 -2
View File
@@ -53,6 +53,7 @@ interface HighlightRule {
tag: Tag | readonly Tag[]
color?: string
fontStyle?: string
textDecoration?: string
}
/** one-dark syntax rules (mirrors @codemirror/theme-one-dark; hues from one-dark-palette.ts). */
@@ -76,7 +77,10 @@ const HIGHLIGHTS_DARK: HighlightRule[] = [
{ tag: tags.strong, fontStyle: 'bold' },
{ tag: tags.link, color: ONE_DARK.blue, fontStyle: 'underline' },
{ tag: tags.meta, color: ONE_DARK.yellow },
{ tag: tags.invalid, color: ONE_DARK.white, fontStyle: 'bold' },
// A visible mark, not the one-dark convention's white: `invalid` is the
// token a JSONL/JSON syntax error lands on, and white-on-a-light-panel is
// invisible. The reader must be able to SEE which text did not parse.
{ tag: tags.invalid, color: ONE_DARK.red, textDecoration: 'underline wavy' },
]
/** one-light syntax rules (the light counterpart; hues from one-dark-palette.ts). */
@@ -100,7 +104,9 @@ const HIGHLIGHTS_LIGHT: HighlightRule[] = [
{ tag: tags.strong, fontStyle: 'bold' },
{ tag: tags.link, color: ONE_LIGHT.link, fontStyle: 'underline' },
{ tag: tags.meta, color: ONE_LIGHT.yellow },
{ tag: tags.invalid, color: ONE_LIGHT.white, fontStyle: 'bold' },
// Same reasoning as the dark family: this used to be pure white, which on a
// light panel is exactly the background — an error the reader cannot see.
{ tag: tags.invalid, color: ONE_LIGHT.red, textDecoration: 'underline wavy' },
]
/** The scheme-dependent extension pair (surface tint + syntax highlight). */
+5
View File
@@ -280,6 +280,11 @@ const LANGS: Readonly<Record<string, LangConfig>> = {
cts: C_FAMILY(TS_WORDS),
jsonc: CONFIG_LANG,
json5: CONFIG_LANG,
// Newline-delimited JSON diffs with the JSON config highlighter: the diff
// renderer works line by line already, so the JSONL editor's own per-line
// tokenizer would add nothing here.
jsonl: CONFIG_LANG,
ndjson: CONFIG_LANG,
html: MARKUP_LANG,
htm: MARKUP_LANG,
xml: MARKUP_LANG,
+33 -12
View File
@@ -14,21 +14,29 @@
*/
import type { FileViewerDescriptor } from './service.ts'
/** One host fs.read result (mirror of the wire; `head` present when binary). */
export interface FsReadOutcome {
binary: boolean
content: string
truncated: boolean
/** base64 of the first bytes (present on binary reads; sniffing material). */
head?: string
}
/** One host fs.read result (mirror of the wire; `head` present when binary
* or when the file was too large to hand over as a document). */
export type FsReadOutcome =
| { kind: 'text'; content: string; size: number }
| { kind: 'binary'; size: number; head: string }
| { kind: 'too-large'; size: number; head: string }
/** What the editor host should do next. */
export type EditorLoadAction =
/** No renderer: show the download UI. */
| { kind: 'binary' }
/** Render `viewer`'s component with the carried payload. */
| { kind: 'render'; viewer: FileViewerDescriptor; content?: string; truncated?: boolean; mediaUrl?: string; customData?: unknown }
| {
kind: 'render'
viewer: FileViewerDescriptor
content?: string
size?: number
/** Present when the file is above the editable threshold: the viewer must
* render the read-only paged preview rather than an editor. */
largeFile?: { size: number }
mediaUrl?: string
customData?: unknown
}
/** Fetch the file through the host (fsRead strategy). */
| { kind: 'fetchFsRead'; viewer: FileViewerDescriptor }
/** Call the viewer's load() and render with its return value. */
@@ -67,6 +75,11 @@ export function planFirstMatch(
/**
* Decide what an fsRead result means for the editor.
* - Text: the first match stands (content is valid for any fsRead viewer).
* - Too large to edit: the viewer still renders, but with `largeFile` instead
* of a document — it shows the read-only paged preview. The head bytes ride
* the result so a `detect` viewer gets the same chance it gets on a binary
* read, which is what keeps a media viewer working for a huge image and what
* lets a plugin claim an oversized format it recognises.
* - Binary: the host head bytes enable a re-match — a `detect` viewer (e.g.
* a plugin sniffing a binary format) may claim the file. `custom` viewers
* load their own bytes; `mediaUrl`/`none` viewers render the media route;
@@ -78,15 +91,23 @@ export function planFsReadOutcome(
rematch: (head: Uint8Array) => FileViewerDescriptor | undefined,
mediaUrlOf: () => string,
): EditorLoadAction {
if (!result.binary) {
return { kind: 'render', viewer, content: result.content, truncated: result.truncated }
if (result.kind === 'text') {
return { kind: 'render', viewer, content: result.content, size: result.size }
}
const claimed = result.head === undefined ? undefined : rematch(decodeHead(result.head))
const claimed = rematch(decodeHead(result.head))
if (claimed !== undefined && claimed.fetchStrategy === 'custom') {
return { kind: 'customLoad', viewer: claimed }
}
if (claimed !== undefined && (claimed.fetchStrategy === 'mediaUrl' || claimed.fetchStrategy === 'none')) {
return { kind: 'render', viewer: claimed, mediaUrl: mediaUrlOf() }
}
if (result.kind === 'too-large') {
// Nobody claimed it by content: the matched text viewer renders the paged
// preview. A `custom`/`mediaUrl` viewer can never get here with content it
// cannot use, so an fsRead viewer is the only remaining sensible owner —
// and the host only reaches this branch after matching one.
if (viewer.fetchStrategy !== 'fsRead') return { kind: 'binary' }
return { kind: 'render', viewer, size: result.size, largeFile: { size: result.size } }
}
return { kind: 'binary' }
}
+95
View File
@@ -0,0 +1,95 @@
/**
* JSONL (newline-delimited JSON) parsing for the preview.
*
* The editor's CodeMirror surface keeps using `@codemirror/lang-json` for
* `.json`; JSONL gets its own per-line language (see `lang-jsonl.ts`) because
* the stock JSON grammar treats a second top-level value as an error. For the
* PREVIEW the grammar is irrelevant: one line IS one record, so the preview
* parses each line on its own and never has to reason about the document as a
* single JSON value.
*
* Kept dependency-free and pure so the record handling is unit-testable
* without a DOM.
*/
import { extOf } from './paths.ts'
/** Whether a path is newline-delimited JSON (one record per line). */
export function isJsonlPath(path: string): boolean {
const ext = extOf(path)
return ext === 'jsonl' || ext === 'ndjson'
}
/** One parsed line. */
export type JsonlRecord =
| { ok: true; value: unknown }
| { ok: false; error: string }
/** A record that is an object or array can render as a `JsonTree`. */
export function isTreeRecord(value: unknown): value is object | unknown[] {
return typeof value === 'object' && value !== null
}
/**
* Parse one JSONL line.
*
* A blank line is NOT a record — JSONL writers commonly end the file with one
* newline, and the host's pages are line-aligned, so a trailing blank must not
* render as a broken record. It is reported as `{ok: false}` with an empty
* error so the caller can skip it instead.
*
* @param line - one line of the file, without its newline.
* @returns the parsed value, or the failure reason.
*/
export function parseRecord(line: string): JsonlRecord {
const trimmed = line.trim()
if (trimmed === '') return { ok: false, error: '' }
try {
return { ok: true, value: JSON.parse(trimmed) as unknown }
} catch (error: unknown) {
return { ok: false, error: error instanceof Error ? error.message : String(error) }
}
}
/** How many characters of a collapsed record's summary are kept. */
const SUMMARY_MAX = 200
/**
* One-line summary of a record for its collapsed row.
*
* Objects and arrays become `{a: 1, b: "x", rest: …}` rather than raw JSON:
* a collapsed row has to be scannable, and a raw `JSON.stringify` of a session
* event is a wall of punctuation. Nesting beyond the first level is elided —
* the expanded `JsonTree` is where detail lives.
*
* @param value - the parsed record.
* @returns a single-line summary, never longer than {@link SUMMARY_MAX}.
*/
export function summarizeRecord(value: unknown): string {
if (value === null) return 'null'
if (Array.isArray(value)) return `[${value.length} items]`
if (typeof value === 'object') {
const entries = Object.entries(value as Record<string, unknown>)
if (entries.length === 0) return '{}'
const parts: string[] = []
for (const [key, item] of entries) {
parts.push(`${key}: ${preview(item)}`)
if (parts.join(', ').length > SUMMARY_MAX) break
}
const joined = parts.join(', ')
return truncate(`{${joined}${parts.length < entries.length ? ', …' : ''}}`)
}
return truncate(JSON.stringify(value) ?? String(value))
}
/** The first-level preview of one property value. */
function preview(value: unknown): string {
if (value === null) return 'null'
if (Array.isArray(value)) return `[…${value.length}]`
if (typeof value === 'object') return '{…}'
return JSON.stringify(value) ?? String(value)
}
/** Clamp a summary to one scannable line. */
function truncate(text: string): string {
return text.length <= SUMMARY_MAX ? text : `${text.slice(0, SUMMARY_MAX - 1)}…`
}
+128
View File
@@ -0,0 +1,128 @@
/**
* A per-line JSON language for JSONL / NDJSON editing.
*
* Reusing `@codemirror/lang-json` here is not free: its grammar accepts ONE
* top-level value, so every record after the first lands in an error node —
* measured on a 400-record file, 402 error nodes. They are zero-width for
* well-formed lines so the tinting looks right, but the parse is structurally
* wrong: every diagnostic, fold and structure query built on it inherits the
* damage, and a genuinely broken line is indistinguishable from the boundary
* noise. (Verified directly against `@lezer/json` before writing this.)
*
* A JSONL line IS an independent JSON document, so the honest parse is one
* JSON tokenizer per line. This is that tokenizer, written as a CodeMirror
* `StreamLanguage`: it walks a line once, tags what it recognises, and marks
* what it does not — which is exactly the signal a broken record deserves.
*
* Only the concerns an editor needs are covered: strings (with escapes and an
* unterminated tail), numbers, `true`/`false`/`null`, structural punctuation,
* and property names (a string followed by `:`). No validation of duplicate
* keys, no nesting depth, no number grammar beyond JSON's shape — a tokenizer
* is not a parser and pretending otherwise would only produce false errors.
*/
import { StreamLanguage, type StringStream } from '@codemirror/language'
/** JSON's number grammar (also used to decide whether a run IS a number). */
const NUMBER = /^-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/
/** A bare word: `true` / `false` / `null`, or something that is not JSON. */
const WORD = /^[A-Za-z_][A-Za-z0-9_]*/
/** Tags the tokenizer emits, by meaning rather than by name. */
interface JsonlToken {
text: string
kind: 'punctuation' | 'string' | 'number' | 'keyword' | 'invalid'
}
/**
* Read one token starting at the stream's position.
*
* @param stream - the line stream, positioned at a non-space character.
* @returns the token's text and kind.
*/
function readToken(stream: StringStream): JsonlToken {
const char = stream.peek()
if (char === '"') {
// A JSON string: everything up to an unescaped quote on this line. An
// unterminated string is `invalid` here rather than at end-of-line, and
// that IS provable for JSONL: a record is one line by definition, so a
// quote that never closes within it is always a broken record.
stream.next()
let body = '"'
for (;;) {
const next = stream.next()
if (next === null) return { text: body, kind: 'invalid' }
body += next
if (next === '\\') {
const escaped = stream.next()
if (escaped === null) return { text: body, kind: 'invalid' }
body += escaped
continue
}
if (next === '"') return { text: body, kind: 'string' }
}
}
if (char === '{' || char === '}' || char === '[' || char === ']' || char === ':' || char === ',') {
stream.next()
return { text: char, kind: 'punctuation' }
}
if (char !== undefined && (char === '-' || (char >= '0' && char <= '9'))) {
// Peeked from the remaining line rather than through `stream.match`, whose
// declared return type is the boolean legacy shape.
const matched = NUMBER.exec(stream.string.slice(stream.pos))
if (matched !== null) {
const text = matched[0]
for (let index = 0; index < text.length; index += 1) stream.next()
return { text, kind: 'number' }
}
// A leading '-' or digit that cannot start a JSON number: mark the one
// character, which is enough for the reader to see where it went wrong.
return { text: stream.next() ?? '', kind: 'invalid' }
}
const word = WORD.exec(stream.string.slice(stream.pos))
if (word !== null) {
const text = word[0]
for (let index = 0; index < text.length; index += 1) stream.next()
return text === 'true' || text === 'false' || text === 'null'
? { text, kind: 'keyword' }
: { text, kind: 'invalid' }
}
stream.next()
return { text: char ?? '', kind: 'invalid' }
}
/**
* The JSONL language: one JSON document per line, no cross-line state.
*
* A `StreamLanguage` carries a state object between lines; this grammar keeps
* none, because JSONL records are independent by definition — carrying
* anything would make line 2's tinting depend on line 1's.
*/
export const jsonlLanguage = StreamLanguage.define({
name: 'jsonl',
token(stream: StringStream): string | null {
if (stream.eatSpace()) return null
const token = readToken(stream)
switch (token.kind) {
case 'string':
// A string immediately followed (modulo spaces) by ':' is a property
// name — the one piece of context a token needs, and the reason the
// lookahead lives here rather than in the caller.
return isPropertyName(stream) ? 'propertyName' : 'string'
case 'number': return 'number'
case 'keyword': return 'atom'
case 'punctuation': return 'punctuation'
case 'invalid': return 'invalid'
}
},
startState() { return {} },
})
/**
* Whether a just-read string opens an object property: the next non-space
* character is a colon. JSON allows whitespace between the two, and a JSONL
* line commonly uses it after `{`.
*/
function isPropertyName(stream: StringStream): boolean {
const rest = stream.string.slice(stream.pos)
return /^\s*:/.test(rest)
}
+7
View File
@@ -6,6 +6,7 @@
import { Language, LanguageSupport, StreamLanguage } from '@codemirror/language'
import { javascript, jsxLanguage, typescriptLanguage, tsxLanguage } from '@codemirror/lang-javascript'
import { json } from '@codemirror/lang-json'
import { jsonlLanguage } from './lang-jsonl.ts'
import { markdown } from '@codemirror/lang-markdown'
import { python } from '@codemirror/lang-python'
import { html } from '@codemirror/lang-html'
@@ -63,6 +64,11 @@ export function languageKeyForExt(ext: string): string | null {
case 'ts': case 'mts': case 'cts': return 'ts'
case 'tsx': return 'tsx'
case 'json': case 'jsonc': return 'json'
// Newline-delimited JSON: one record per line, each an independent
// document — hence its own per-line language rather than `json`, whose
// grammar treats every record after the first as an error (see
// lang-jsonl.ts).
case 'jsonl': case 'ndjson': return 'jsonl'
case 'md': case 'markdown': return 'md'
case 'py': case 'pyw': return 'python'
case 'html': case 'htm': return 'html'
@@ -131,6 +137,7 @@ const FACTORIES: Record<string, () => Language | LanguageSupport> = {
ts: () => javascript({ typescript: true }),
tsx: () => javascript({ typescript: true, jsx: true }),
json: () => json(),
jsonl: () => jsonlLanguage,
md: () => markdown(),
python: () => python(),
html: () => html(),
+38 -4
View File
@@ -74,12 +74,12 @@ export const zh = {
editorEmptyHint: '从右侧文件树或上方路径输入框选择文件开始预览',
openFileNewTab: '在新 Tab 中打开',
openFileSide: '在侧边打开',
zipProgress: '正在打包 {done}/{total}',
settingsOpenWithPluginTitle: '始终显示插件自研的打开方式',
settingsOpenWithPluginDesc: '默认只在宿主探测不到本机关联应用时显示插件自研的打开方式(资源管理器 / VS Code / Cursor / Zed / 自定义编辑器、SSH 远端);打开后宿主应用与插件目标并存',
zipDownload: '压缩并下载',
zipDownloadCount: '压缩并下载({count} 项)',
zipFailed: '打包失败:{message}',
archiveToolMissing: '系统上没有可用的打包命令(zip 或 tar 都没有),无法打包下载',
openWithMenu: '在应用中打开',
openWithSshSuffix: ' (SSH)',
pinOpenWith: '固定到菜单',
@@ -178,7 +178,23 @@ export const zh = {
saveFailed: '保存失败',
saveConflict: '文件已在磁盘上被其他来源修改。保存已中止,你的修改仍在编辑器中。',
saveConflictReload: '重新载入磁盘内容',
truncation: '文件过大,仅显示前 512KB',
previewOnlyNotice: '文件过大({size}),仅提供分页预览;{limit} 以内可编辑',
largeFileEmpty: '(空文件)',
pagedPrev: '上一页',
pagedNext: '下一页',
pagedEnd: '已经是最后一页',
pagedPage: '第 {page} 页',
pagedPageOfTotal: '第 {page} / {total} 页',
pagedLineRange: '第 {from}–{to} 行',
jsonlRecordRange: '第 {from}–{to} 条记录',
jsonlInvalidRecord: '这一行不是合法 JSON',
jsonCopyPath: '复制路径',
jsonCopyPrettyJson: '复制为格式化 JSON',
jsonCopyCompactJson: '复制为紧凑 JSON',
jsonCopyFailed: '复制失败',
jsonCollapseNode: '折叠',
jsonExpandNode: '展开',
jsonCopyButtonTitle: '复制:{action}',
searchFind: '查找',
searchReplace: '替换',
searchNext: '下一个',
@@ -347,6 +363,7 @@ export const zh = {
viewerMarkdown: 'Markdown',
viewerCode: '代码',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
browser: '浏览器',
browserPlaceholder: '输入网址,例如 example.com',
browserGo: '前往',
@@ -645,12 +662,12 @@ export const en: Record<keyof typeof zh, string> = {
editorEmptyHint: 'Pick a file from the tree panel or the path input above to start previewing',
openFileNewTab: 'Open in New Tab',
openFileSide: 'Open to the Side',
zipProgress: 'Archiving {done}/{total}',
settingsOpenWithPluginTitle: 'Always show the plugin\u2019s own Open with targets',
settingsOpenWithPluginDesc: 'By default the plugin\u2019s own targets (file manager / VS Code / Cursor / Zed / custom editors, SSH remotes) show only when the host reports no local associated application; turn this on to keep both side by side',
zipDownload: 'Zip and download',
zipDownloadCount: 'Zip and download ({count} items)',
zipFailed: 'Archive failed: {message}',
archiveToolMissing: 'No archive command is available on this system (neither zip nor tar), so the selection cannot be packed for download',
openWithMenu: 'Open with',
openWithSshSuffix: ' (SSH)',
pinOpenWith: 'Pin to menu',
@@ -749,7 +766,23 @@ export const en: Record<keyof typeof zh, string> = {
saveFailed: 'Save failed',
saveConflict: 'The file changed on disk since it was loaded. The save was stopped; your edits are still in the editor.',
saveConflictReload: 'Reload from disk',
truncation: 'File too large — showing the first 512KB',
previewOnlyNotice: 'File is too large ({size}) — paged preview only; editable up to {limit}',
largeFileEmpty: '(empty file)',
pagedPrev: 'Previous page',
pagedNext: 'Next page',
pagedEnd: 'Already on the last page',
pagedPage: 'Page {page}',
pagedPageOfTotal: 'Page {page} / {total}',
pagedLineRange: 'Lines {from}–{to}',
jsonlRecordRange: 'Records {from}–{to}',
jsonlInvalidRecord: 'This line is not valid JSON',
jsonCopyPath: 'Copy path',
jsonCopyPrettyJson: 'Copy as formatted JSON',
jsonCopyCompactJson: 'Copy as compact JSON',
jsonCopyFailed: 'Copy failed',
jsonCollapseNode: 'Collapse',
jsonExpandNode: 'Expand',
jsonCopyButtonTitle: 'Copy: {action}',
searchFind: 'Find',
searchReplace: 'Replace',
searchNext: 'next',
@@ -918,6 +951,7 @@ export const en: Record<keyof typeof zh, string> = {
viewerMarkdown: 'Markdown',
viewerCode: 'Code',
viewerHtml: 'HTML',
viewerJsonl: 'JSONL',
browser: 'Browser',
browserPlaceholder: 'Enter a URL, e.g. example.com',
browserGo: 'Go',
+21 -8
View File
@@ -313,9 +313,18 @@ export interface FileViewerProps {
* positions the reader there once, on arrival; every other viewer ignores
* it. Absent on an ordinary open. */
line?: number
/** fsRead text content (fetchStrategy='fsRead'). */
/** fsRead text content (fetchStrategy='fsRead'). Absent when the file is
* above the editable threshold — see {@link largeFile}. */
content?: string
truncated?: boolean
/** The file's size in bytes, as the host measured it for this read. */
size?: number
/**
* Present when the host refused to hand the document over because the file
* exceeds the editable threshold. The viewer renders a read-only paged
* preview instead of an editor: CodeMirror has to hold the whole document in
* the browser, which is exactly what a file this size makes impossible.
*/
largeFile?: { size: number }
/** Last-modified time (ms) of the loaded bytes — the built-in text editor's
* save baseline (a file that changed on disk since refuses the write).
* Absent for viewers/loads that carry no baseline. */
@@ -329,6 +338,10 @@ export interface FileViewerProps {
* fed through the two callbacks below. Viewers that ignore these fields
* render exactly as before. */
toolbar?: 'self' | 'host'
/** Internal: whether this tab is the ACTIVE one with its panel open. Native
* tabs stay mounted while parked, so an over-limit preview must know to
* stop reading pages for a tab nobody is looking at. Absent = visible. */
visible?: boolean
/** Internal: the viewer reports its toolbar state (mode/dirty/save). */
onToolbarState?: (state: EditorToolbarState) => void
/** Internal: the viewer registers its toolbar commands on mount (null on
@@ -340,16 +353,16 @@ export interface FileViewerProps {
/** The toolbar state a text editor reports to the host's merged-mode header. */
export interface EditorToolbarState {
/** Whether the preview/edit mode toggle applies (markdown/html). */
/** Whether the preview/edit mode toggle applies (markdown / html / jsonl). */
modes: boolean
mode: 'preview' | 'edit'
dirty: boolean
/** Whether saving applies (text content loaded). */
/** Whether saving applies (an editable document was loaded). */
editable: boolean
/** Whether the loaded text was truncated at readLimit — the editor is
* read-only and saving is disabled (issue #732: saving partial content
* would overwrite and destroy the tail of the file). */
truncated?: boolean
/** Whether the viewer is showing the read-only paged preview for an
* over-limit file. Nothing can be edited or saved in that state, so the
* header drops the save button and reports the size instead. */
largeFile?: boolean
saveState: 'idle' | 'saving' | 'saved' | 'failed'
}
+158
View File
@@ -2490,3 +2490,161 @@ body[data-dsh-sidebar-dragging] .bottomPanel {
animation: dsh-toc-flash 1.2s ease-out;
border-radius: 4px;
}
/* ── Read-only paged preview (files above the editable threshold) ────────
The editor answers "too big to edit" with a windowed reader rather than a
refusal. Two row shapes share the chrome: the JSONL record list (one
expandable record per row) and the log-style line list (monospace, no
wrapping, horizontal scroll). Every ink is a theme token. */
.largeFile {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
}
.largeFileNotice {
flex: none;
display: flex;
align-items: baseline;
gap: 8px;
padding: 4px 8px;
font: var(--dsw-font-xxxs-11);
color: var(--dsw-alias-state-warn-label);
background: var(--dsw-alias-state-warn-tertiary);
}
.largeFileDownload {
margin-left: auto;
color: inherit;
text-decoration: underline;
}
.largeFileBody {
flex: 1;
min-height: 0;
overflow: auto;
}
.largeFileRecords {
padding: 4px 0;
}
/* The record list is an <ol> whose `start` attribute is the first record's
absolute number: the marker itself is suppressed, since the number column
is rendered explicitly and must stay aligned with the summary row. */
.largeFileList {
margin: 0;
padding: 0;
list-style: none;
}
.largeFileRecord {
display: flex;
gap: 8px;
padding: 2px 8px;
}
.largeFileRecordExpanded {
background: var(--dsw-alias-bg-layer-1);
}
.largeFileRecordInvalid {
color: var(--dsw-alias-state-error-primary);
}
.largeFileRecordNo {
flex: none;
min-width: 4ch;
text-align: right;
font: var(--dsw-font-xxxs-11);
color: var(--dsw-alias-label-tertiary);
user-select: none;
}
.largeFileRecordBody {
flex: 1;
min-width: 0;
}
.largeFileRecordSummary {
display: block;
width: 100%;
padding: 0;
border: 0;
background: none;
text-align: left;
font: var(--ds-font-family-code);
font-size: 12px;
color: var(--dsw-alias-label-primary);
white-space: pre;
overflow: hidden;
text-overflow: ellipsis;
cursor: pointer;
}
.largeFileRecordSummary:disabled {
cursor: default;
}
.largeFileRecordRaw {
margin: 2px 0 0;
font: var(--ds-font-family-code);
font-size: 12px;
white-space: pre-wrap;
word-break: break-all;
overflow-wrap: anywhere;
}
.largeFileRecordTree {
margin-top: 2px;
font: var(--ds-font-family-code);
font-size: 12px;
}
.largeFileLines {
padding: 4px 0;
font: var(--ds-font-family-code);
font-size: 12px;
white-space: pre;
}
.largeFileLine {
display: flex;
gap: 8px;
padding: 0 8px;
}
.largeFileLineNo {
flex: none;
min-width: 5ch;
text-align: right;
color: var(--dsw-alias-label-tertiary);
user-select: none;
}
.largeFileLineText {
flex: none;
color: var(--dsw-alias-label-primary);
}
.largeFilePager {
flex: none;
display: flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-top: 1px solid var(--dsw-alias-border-l2);
background: var(--dsw-alias-bg-layer-2);
}
.largeFilePageLabel {
flex: 1;
min-width: 0;
text-align: center;
font: var(--dsw-font-xxxs-11);
color: var(--dsw-alias-label-secondary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
+228
View File
@@ -0,0 +1,228 @@
/**
* Byte-offset paging over one text file, shared by every over-limit preview
* (the generic read-only text reader and the JSONL record list).
*
* Why paging at all: the editor answers "this file is too big to edit" by
* refusing to show it (VS Code pops a placeholder and offers "Open Anyway").
* That is safe but useless for the files people actually want to LOOK at —
* session logs, eval dumps, dataset rows — so instead of refusing, this reads
* the file in windows and renders one window at a time. Memory stays flat
* whatever the file weighs.
*
* The cursor model, and its one honest limitation:
*
* - `pageStarts[i]` is the byte offset page `i` starts at. It is filled in as
* the reader walks FORWARD, so it is only known up to the furthest page
* visited — byte offsets cannot be computed backwards.
* - Therefore navigation reaches any VISITED page in either direction, plus
* the next unvisited one. There is no "jump to the last page" and no total
* page count until the file is read to the end. A random-access index would
* mean scanning the whole file on open, which is exactly the cost paging
* exists to avoid.
* - Decoded page text is cached separately from the page table, in a bounded
* LRU, so revisiting a page does not re-read it while memory still cannot
* grow with the file.
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { api, type SessionScope } from './api.ts'
/** How many decoded pages stay in memory (the page table is tiny and unbounded). */
const PAGE_CACHE_MAX = 24
/** The cursor state one preview renders from. */
export interface TextPager {
/** Whether a load is in flight (the first page included). */
loading: boolean
/** Wire/transport failure of the last load; cleared once one succeeds. */
error: string | null
/** The current page's text; '' before the first load settles. */
text: string
/** 1-based page number. */
page: number
/** Absolute 1-based line number the current page starts at. */
firstLine: number
/** The file's size in bytes (0 until the first page reports it). */
size: number
/** True once the file's last page has been loaded. */
atEnd: boolean
/** 1-based number of the furthest page reachable right now. */
lastReachable: number
/** True when a page after the current one is reachable (possibly not yet read). */
hasNext: boolean
next: () => void
prev: () => void
/** Re-read from page 1 (the toolbar's refresh, and the conflict banner's action). */
reload: () => void
/** The file's detected encoding, as reported by the first page. */
encoding: string
}
/**
* Page through one file.
*
* @param scope - the session scope.
* @param path - the file to read ('' parks the hook).
* @param enabled - false issues no request and keeps the previous state (a
* viewer that is merely hidden must not keep reading).
* @param revision - bump to restart from page 1 (the host's refresh path).
* @returns the cursor and its navigation commands.
*/
export function useTextPager(
scope: SessionScope,
path: string,
enabled: boolean,
revision: number,
): TextPager {
/** `pageStarts[i]` = byte offset page `i` starts at; one extra slot past the
* last loaded page holds where the next one begins. */
const [pageStarts, setPageStarts] = useState<number[]>([0])
/** Absolute 1-based first line of each page, chained as pages are read. */
const [lineStarts, setLineStarts] = useState<number[]>([1])
/** Page index → decoded text, insertion-ordered for the LRU trim. */
const cacheRef = useRef(new Map<number, string>())
/** Mirror of `pageStarts` for the identity-stable `load` callback. */
const startsRef = useRef(pageStarts)
startsRef.current = pageStarts
const linesRef = useRef(lineStarts)
linesRef.current = lineStarts
const [page, setPage] = useState(0)
const [size, setSize] = useState(0)
const [atEnd, setAtEnd] = useState(false)
const [encoding, setEncoding] = useState('utf8')
const [loading, setLoading] = useState(false)
const [error, setError] = useState<string | null>(null)
/** Bumped after every cache write so the returned memo re-reads it. */
const [cacheStamp, setCacheStamp] = useState(0)
const [reloadSeq, setReloadSeq] = useState(0)
const inFlight = useRef<Set<number>>(new Set())
/** Guards a late response from the previous file/revision. */
const generationRef = useRef(0)
const reset = useCallback((): void => {
generationRef.current += 1
cacheRef.current = new Map()
inFlight.current = new Set()
setPageStarts([0])
setLineStarts([1])
setPage(0)
setSize(0)
setAtEnd(false)
setError(null)
setLoading(false)
setCacheStamp(stamp => stamp + 1)
}, [])
// A new file restarts the cursor; so does the host's refresh — the file may
// have moved on disk, and a stale byte offset would splice two different
// revisions of the document together.
useEffect(() => {
reset()
setReloadSeq(sequence => sequence + 1)
}, [reset, path, scope.sessionId, scope.cwd, revision])
const load = useCallback((index: number): void => {
if (inFlight.current.has(index)) return
const offset = index === 0 ? 0 : startsRef.current[index]
if (offset === undefined) return
const generation = generationRef.current
inFlight.current.add(index)
setLoading(true)
setError(null)
api.fsReadPage(scope, path, offset).then((result) => {
inFlight.current.delete(index)
if (generation !== generationRef.current) return
const cache = cacheRef.current
cache.set(index, result.text)
while (cache.size > PAGE_CACHE_MAX) {
const oldest = cache.keys().next()
if (oldest.done || oldest.value === index) break
cache.delete(oldest.value)
}
setPageStarts((previous) => {
// Chaining the page table HERE (rather than in a separate effect) keeps
// "page i was read" and "page i+1 starts at X" one atomic update: no
// render can observe a table that skips the page it just saw.
const next = [...previous]
if (next[index] === undefined) next[index] = result.offset
next[index + 1] = result.nextOffset
return next
})
setLineStarts((previous) => {
const next = [...previous]
next[index] = previous[index] ?? 1
next[index + 1] = next[index]! + lineCount(result.text)
return next
})
setSize(result.size)
setEncoding(result.encoding)
setAtEnd(result.eof)
setPage(index)
setLoading(false)
setCacheStamp(stamp => stamp + 1)
}).catch((reason: unknown) => {
inFlight.current.delete(index)
if (generation !== generationRef.current) return
setLoading(false)
setError(reason instanceof Error ? reason.message : String(reason))
})
}, [scope, path])
const reload = useCallback(() => {
reset()
setReloadSeq(sequence => sequence + 1)
}, [reset])
// Load the current page when it is not cached yet. A page past the table's
// reach has no known offset and must not be requested.
useEffect(() => {
void reloadSeq
if (!enabled || path === '') return
if (cacheRef.current.has(page)) return
if (page > 0 && page >= startsRef.current.length) return
load(page)
}, [enabled, path, page, load, cacheStamp, reloadSeq])
const current = cacheRef.current.get(page)
const lastReachable = Math.max(1, pageStarts.length)
const next = useCallback(() => {
setPage(currentPage => (currentPage + 1 < Math.max(1, startsRef.current.length) ? currentPage + 1 : currentPage))
}, [])
const prev = useCallback(() => { setPage(currentPage => Math.max(0, currentPage - 1)) }, [])
return useMemo<TextPager>(() => ({
loading,
error,
text: current ?? '',
page: page + 1,
firstLine: lineStarts[page] ?? 1,
size,
atEnd,
lastReachable,
hasNext: !atEnd && page + 1 < lastReachable,
next,
prev,
reload,
encoding,
// `cacheStamp` is the cache-generation signal this memo reads through.
// eslint-disable-next-line react-hooks/exhaustive-deps
}), [loading, error, current, page, lineStarts, size, atEnd, lastReachable, next, prev, reload, encoding, cacheStamp])
}
/** Lines in one page's text (a trailing newline does not open a new line). */
export function lineCount(text: string): number {
return splitLines(text).length
}
/**
* One page's text as rows. The host trims every page to a line break, so the
* '' a trailing newline produces is dropped — except on an empty page, which is
* no rows rather than one empty one.
*/
export function splitLines(text: string): string[] {
if (text === '') return []
const lines = text.split('\n')
if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop()
return lines
}
+3 -14
View File
@@ -29,7 +29,7 @@ export interface UploadResult {
relativePath: string
ok: boolean
path?: string
/** Wire error code when the host refused the upload ('too-large', ...). */
/** Wire error code when the host refused the upload. */
code?: string
/** The host's error message (English wire text; localize via `code`). */
error?: string
@@ -106,13 +106,6 @@ export async function uploadItemsFromDrop(data: DataTransfer | undefined): Promi
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
@@ -150,12 +143,8 @@ export async function uploadToDir(
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 })
}
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
+15 -16
View File
@@ -29,29 +29,31 @@ export {
/** Tunable sidebar host limits (every field optional; defaults fill in). */
export interface SidebarConfig {
/** Read cap of one text file (bytes); larger files return truncated. */
readLimit?: number
/** Media route cap (bytes); larger binaries are refused. */
mediaLimit?: number
/** Upload route cap (bytes); larger files are refused without touching disk. */
uploadLimit?: number
/** Explorer row bound of one level. */
listLimit?: number
}
/** Schemastery schema for the deployment-provided host limits. */
/**
* Schemastery schema for the deployment-provided host limits.
*
* The three transfer/read caps this schema used to carry (`readLimit` /
* `mediaLimit` / `uploadLimit`) are gone: upload, download and the HTML
* preview route all stream now, so there is nothing left for a byte cap to
* protect and a large file is simply a large file. What replaced `readLimit`
* is {@link MAX_EDITABLE_BYTES} — not a transfer cap but the size above which
* a text file gets a read-only paged preview instead of an editor, because
* CodeMirror has to hold the whole document in the browser.
*
* Old profiles that still write the retired keys are harmless: schemastery
* tolerates unknown keys (the same property that keeps a legacy
* `workspaceFence` field in an old profile from being fatal).
*/
const LimitsSchema = z.object({
readLimit: z.number().step(1).min(1).default(512 * 1024),
mediaLimit: z.number().step(1).min(1).default(20 * 1024 * 1024),
uploadLimit: z.number().step(1).min(1).default(128 * 1024 * 1024),
listLimit: z.number().step(1).min(1).default(1000),
})
/** Fully defaulted sidebar host settings. */
export interface ResolvedSidebarConfig {
readLimit: number
mediaLimit: number
uploadLimit: number
listLimit: number
}
@@ -63,9 +65,6 @@ export interface ResolvedSidebarConfig {
*/
export function resolveSidebarConfig(config: SidebarConfig | undefined): ResolvedSidebarConfig {
return {
readLimit: config?.readLimit ?? 512 * 1024,
mediaLimit: config?.mediaLimit ?? 20 * 1024 * 1024,
uploadLimit: config?.uploadLimit ?? 128 * 1024 * 1024,
listLimit: config?.listLimit ?? 1000,
}
}
+13 -1
View File
@@ -43,11 +43,23 @@ export interface SidebarHttpRequest {
}
/** The response face route handlers write to (structural subset of node's
* ServerResponse: the status/header/body writes the routes use). */
* ServerResponse: the status/header/body writes the routes use).
*
* `write` / `headersSent` / `destroy` exist for the raw byte routes
* (`/sidebar/file`, `/sidebar/html`, `/sidebar/archive`), which stream a file
* instead of buffering it. They stay plain structural members on purpose —
* see the module header on why node types cannot appear here. */
export interface SidebarHttpResponse {
statusCode: number
/** True once a status line went out; a late failure can no longer become a
* JSON envelope, so callers destroy the response instead. */
headersSent?: boolean
writeHead(status: number, headers?: Record<string, string>): void
/** Append one body chunk; false means "wait for drain". */
write(chunk: string | Uint8Array): boolean
end(body?: string | Uint8Array): void
/** Tear the connection down (mid-stream failure, client abort). */
destroy?(error?: Error): void
}
/** The upgrade socket face (structural subset: the destroy the fences use). */
+76
View File
@@ -0,0 +1,76 @@
/**
* The one size constant both halves need, kept dependency-free on purpose.
*
* This replaces the retired `readLimit` deployment knob (`config.ts`). The old
* cap answered "how many bytes may the host hand the client" by truncating the
* document — which produced an editor that could neither be trusted nor saved
* (issue #732: saving a partial document destroys the tail). Transfer size is
* no longer a thing this plugin limits at all: upload, download, the HTML
* preview route and the archive route all stream, so a 10 GB file is simply a
* 10 GB file.
*
* What is still bounded is what an EDITOR can hold. CodeMirror keeps the whole
* document in the browser, so a file above this size gets a read-only paged
* preview (see `paged-text.tsx` / `jsonl-preview.tsx`) instead of an edit
* buffer. VS Code draws the same line at a different number — its
* `getLargeFileConfirmationLimit()` is 50 MB on the web build — and the shape
* of the answer (threshold → degraded read-only view) is deliberately the same.
*
* Imported by BOTH halves, so this module must stay free of node builtins and
* of anything that reaches them.
*/
/**
* Text files at or below this size load whole and are editable; anything above
* gets the read-only paged preview.
*/
export const MAX_EDITABLE_BYTES = 5 * 1024 * 1024
/**
* Bytes one `fs.readPage` request returns. Pages are trimmed back to the last
* newline so a page is normally a whole number of lines (and therefore, for
* JSONL, a whole number of records); a single line longer than this is
* returned untrimmed and stitched back together by the client.
*
* Sized so that even a file of very short lines lands in the low thousands of
* rendered rows per page — the preview renders a page's rows as plain elements,
* and the page size is the only thing bounding that.
*/
export const PAGE_BYTES = 128 * 1024
/**
* Hard ceiling on one editor save request body.
*
* This is a SERVER-SIDE SANITY GUARD, not a product limit: the editor cannot
* produce more than {@link MAX_EDITABLE_BYTES} of text, so the UI can never
* reach it. It exists because the save route receives a raw body and the
* encoding transform (`restoreEol` + `encodeText`) needs the whole document as
* a string.
*/
export const WRITE_BODY_GUARD_BYTES = 8 * 1024 * 1024
/**
* Format a byte count for the "this file is too large to edit" notice. Kept
* here beside the constant so the host and the client round identically.
*
* @param bytes - the file's size.
* @returns e.g. `12.4 MB`, `512 KB`, `900 B`.
*/
export function formatByteSize(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 0) return '0 B'
if (bytes < 1024) return `${Math.round(bytes)} B`
const units = ['KB', 'MB', 'GB', 'TB']
let value = bytes / 1024
let unit = 0
while (value >= 1024 && unit < units.length - 1) {
value /= 1024
unit += 1
}
return `${value >= 10 ? Math.round(value) : value.toFixed(1)} ${units[unit]}`
}
/**
* The human-facing form of {@link MAX_EDITABLE_BYTES}, for copy that names the
* editing threshold.
*/
export const MAX_EDITABLE_LABEL = '5 MB'
+72
View File
@@ -0,0 +1,72 @@
/**
* One-shot file streaming for the plugin's raw byte routes.
*
* Every read-only byte route used to `readFile()` and hand the whole buffer to
* `res.end()`, which put a hard ceiling on the response and made the host's
* memory grow with the file. Streaming removes both: the bytes go from disk to
* socket through a bounded pipe, so a 10 GB image downloads through the same
* constant-memory path as a 10 KiB one.
*
* The one genuinely tricky part is WHERE the header is written. `writeHead`
* commits the response: an error after it can no longer become the plugin's
* JSON error envelope, and the client would see a `200` with a truncated body.
* So the stream is opened and awaited FIRST — `open` rejects for ENOENT /
* EACCES / EISDIR before a single header goes out — and only then does the
* status line commit. Failures after that point (the file changed under us,
* the client aborted) destroy the socket, which is the only honest signal left.
*/
import { createReadStream } from 'node:fs'
import { once } from 'node:events'
import type { ServerResponse } from 'node:http'
import { pipeline } from 'node:stream/promises'
import type { SidebarHttpResponse } from './context-types.ts'
import { SidebarError } from './wire.ts'
/**
* Stream one file into the response with the given headers.
*
* The caller keeps ownership of every header except `content-length`, which is
* derived from `size` here: browsers need it for a download's progress bar,
* and the routes always have a fresh `stat` at hand.
*
* @param path - absolute path of the file to send (already fenced by the caller).
* @param size - the file's size in bytes, from the same `stat` the caller ran.
* @param res - the response face.
* @param headers - status/type/disposition headers, written verbatim.
* @throws {SidebarError} fs-error when the file cannot be opened — thrown
* BEFORE the header commits, so the caller's `writeError` still produces a
* proper envelope. After that this function never throws: the response is
* already committed and the connection is destroyed instead.
*/
export async function streamFileToResponse(
path: string,
size: number,
res: SidebarHttpResponse,
headers: Record<string, string>,
): Promise<void> {
// `node:http` boundary cast: the host hands the routes a real ServerResponse,
// and the declaration graph deliberately cannot name it (see
// context-types.ts). This is the one place the cast is needed.
const node = res as unknown as ServerResponse
const stream = createReadStream(path)
try {
await once(stream, 'open')
} catch (error: unknown) {
stream.destroy()
throw new SidebarError(
'fs-error',
`cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`,
400,
)
}
res.writeHead(200, { ...headers, 'content-length': String(size) })
try {
await pipeline(stream, node)
} catch {
// Either the peer went away or the source failed mid-flight. The status
// line is already on the wire, so there is no envelope to write and no
// recovery to attempt — tear the socket down and let the client's own
// download UI report the truncation.
node.destroy()
}
}
+78 -8
View File
@@ -27,6 +27,7 @@ import { access, lstat, mkdir, rename, rm, stat, unlink, writeFile } from 'node:
import { basename, dirname, join } from 'node:path'
import { invalidateDirectoryCache, requireAbsolute } from './fs-tree.ts'
import { ensureWorkspaceWritePath, resolveTarget } from './path-security.ts'
import { encodeText, fileFormatOf, restoreEol } from './text-encoding.ts'
import { SidebarError } from './wire.ts'
/** Inputs of one upload: the session scope plus the request body stream. */
@@ -39,8 +40,6 @@ export interface WorkspaceUploadInput {
relativePath: string
/** The request body stream (raw bytes). */
chunks: AsyncIterable<string | Uint8Array>
/** Byte cap; an oversized upload is refused without touching the target. */
limit: number
/** @deprecated IGNORED — containment was removed. Do not pass it. */
fence?: boolean
}
@@ -53,11 +52,15 @@ export interface WorkspaceUploadInput {
* target independent (each writes and renames its own file; the last rename
* wins) and never blocks later uploads after a crashed process.
*
* @throws SidebarError with a wire code for shape and size failures; the temp
* file is always removed on failure.
* There is NO size cap: the bytes flow through a bounded write stream, so a
* 100 GB upload costs the host the same memory as a 1 KB one. A failed or
* aborted upload still leaves neither a partial target nor a temp file.
*
* @throws SidebarError with a wire code for shape failures; the temp file is
* always removed on failure.
*/
export async function writeWorkspaceUpload(input: WorkspaceUploadInput): Promise<{ path: string; size: number }> {
const { cwd, dir, relativePath, chunks, limit } = input
const { cwd, dir, relativePath, chunks } = input
// The shared resolution contract: an absolute `dir` normalizes, a
// session-relative one joins the cwd, `~` expands against the home (#713).
const base = resolveTarget(cwd, dir)
@@ -76,7 +79,6 @@ export async function writeWorkspaceUpload(input: WorkspaceUploadInput): Promise
// Resolves once the stream fully closes; created up front so a stream that
// already closed (successful end, later failure) cannot leave the wait hanging.
const closed = new Promise<void>((resolve) => { stream.once('close', () => resolve()) })
let size = 0
let streamError: unknown
// A permanent 'error' listener keeps a failing disk from crashing the host:
// every await below surfaces the failure through the promise chain instead.
@@ -84,8 +86,6 @@ export async function writeWorkspaceUpload(input: WorkspaceUploadInput): Promise
try {
for await (const chunk of chunks) {
const buffer = Buffer.from(chunk)
size += buffer.length
if (size > limit) throw new SidebarError('too-large', `upload exceeds the ${limit} byte limit`, 413)
if (!stream.write(buffer)) await once(stream, 'drain')
if (streamError !== undefined) throw streamError
}
@@ -108,6 +108,76 @@ export async function writeWorkspaceUpload(input: WorkspaceUploadInput): Promise
}
}
/** Inputs of one editor save. */
export interface WorkspaceWriteInput {
/** The session workspace root (the base of session-relative targets). */
cwd: string
/** Target path as the editor addresses it (absolute, session-relative, or `~`-relative). */
path: string
/** The document to store, with LF line endings (CodeMirror has no other line model). */
content: string
/**
* The mtime the draft was based on. A file that changed on disk since is
* REFUSED with `fs-conflict` instead of silently clobbering whatever wrote
* it; `undefined` = no gate (a brand-new file has no baseline).
*/
expectedMtimeMs?: number
}
/**
* Write one editor document to disk, preserving the file's own byte encoding
* and line ending.
*
* Two guarantees ride together here, and both are about NOT rewriting what the
* user did not touch:
*
* - **line endings** — the client transports an LF document, so writing it
* verbatim would turn one edited line into a whole-file diff on every CRLF
* checkout (#871). The EOL detected at read time is restored before encoding.
* - **byte encoding** — GBK / UTF-16 / BOM'd UTF-8 files stay in their own
* encoding instead of being rewritten as UTF-8 (#523).
*
* The write is atomic (uniquely named temp sibling + rename) and the temp file
* is removed on every failure path.
*
* @throws {SidebarError} fs-conflict (409) when `expectedMtimeMs` no longer
* matches the file, fs-error when the write itself fails.
*/
export async function writeWorkspaceText(input: WorkspaceWriteInput): Promise<{ mtimeMs?: number }> {
const { cwd, path, content, expectedMtimeMs } = input
const absolute = await ensureWorkspaceWritePath(cwd, path)
// Detect the byte encoding AND the line ending BEFORE the temp write, so the
// save round-trips what the file already used.
const { encoding, eol } = await fileFormatOf(absolute)
if (expectedMtimeMs !== undefined) {
const current = await stat(absolute).then(info => info.mtimeMs).catch(() => undefined)
if (current !== undefined && current !== expectedMtimeMs) {
throw new SidebarError(
'fs-conflict',
`"${absolute}" changed on disk since it was loaded (expected mtime ${expectedMtimeMs}, found ${current})`,
409,
)
}
}
// Per-request temp name (same pattern as writeWorkspaceUpload): a
// pid-suffixed name is shared by every concurrent save to the same path,
// letting two writers interleave into one temp file — and the failure-path
// rm could delete the other writer's in-flight temp.
const tmp = join(dirname(absolute), `.${basename(absolute)}.dsh-sidebar-tmp-${randomUUID()}.tmp`)
try {
await mkdir(dirname(absolute), { recursive: true })
await writeFile(tmp, encodeText(restoreEol(content, eol), encoding), { flag: 'wx' })
await rename(tmp, absolute)
} catch (error) {
await rm(tmp, { force: true }).catch(() => {})
throw new SidebarError('fs-error', `cannot write "${absolute}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
invalidateDirectoryCache(dirname(absolute))
// The fresh baseline the client adopts after a successful save.
const mtimeMs = await stat(absolute).then(info => info.mtimeMs).catch(() => undefined)
return { ...(mtimeMs !== undefined ? { mtimeMs } : {}) }
}
/** Inputs of one tree-row rename. */
export interface WorkspaceRenameInput {
/** The session workspace root (the base of session-relative targets). */
+252 -115
View File
@@ -12,9 +12,8 @@
* All operations are conversation-scoped: requests carry a sessionId and the
* session's authoritative cwd comes from the session store.
*/
import { randomUUID } from 'node:crypto'
import { mkdir, open, readFile, rename, rm, stat, writeFile } from 'node:fs/promises'
import { basename, dirname, extname, isAbsolute, join, sep } from 'node:path'
import { open, readFile, stat } from 'node:fs/promises'
import { basename, extname, isAbsolute, join, sep } from 'node:path'
import type { IncomingMessage } from 'node:http'
import type { Duplex } from 'node:stream'
import { WebSocket, WebSocketServer } from 'ws'
@@ -29,10 +28,10 @@ import {
type SidebarConfig,
type SidebarPrefs,
} from './config.ts'
import { invalidateDirectoryCache, listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
import { listDirectory, messageOf, parentOf, requireAbsolute, rootLabel, type SidebarFsEntry } from './fs-tree.ts'
import { resolveSessionPath } from './session-path.ts'
import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceUpload } from './fs-operations.ts'
import { ensureWorkspacePath, ensureWorkspaceWritePath } from './path-security.ts'
import { createWorkspaceFile, mkdirWorkspaceEntry, renameWorkspaceEntry, removeWorkspaceEntry, writeWorkspaceText, writeWorkspaceUpload } from './fs-operations.ts'
import { ensureWorkspacePath } from './path-security.ts'
import { searchFiles } from './fs-search.ts'
import { compileExcludePatterns } from './exclude-patterns.ts'
import { decodeHtmlUrl } from './html-route.ts'
@@ -40,8 +39,7 @@ import { isTrustedApiRequest } from './trust-fence.ts'
import { registerBundleRoute } from './bundle-route.ts'
import { createDirectoryWatchers, type DirectoryWatchers } from './fs-watch.ts'
import { launchExternal } from './open-external.ts'
import { archiveNameOf, collectZipEntries, createArchiveTasks, disambiguateArchiveNames, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts'
import type { ZipEntry } from './zip.ts'
import { createArchiveTasks, respondArchiveDownload, type ArchiveTasks } from './archive-route.ts'
import * as git from './git.ts'
import { SettingsConflictError } from '@deepseek-ai/dsh-settings'
import { AgentOpenRegistry, registerOpenTool, type AgentOpenRequest } from './agent-opens.ts'
@@ -50,7 +48,8 @@ import { buildTeamsApi, type SidebarTeamsRoutes } from './team-routes.ts'
import { buildWorkflowsApi, type SidebarWorkflowRoutes } from './workflow-routes.ts'
import { buildSidechatApi } from './sidechat-routes.ts'
import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts'
import { readJsonBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
import { readJsonBody, readTextBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts'
import { streamFileToResponse } from './file-stream.ts'
import { readPersistedSession } from './session-store.ts'
import { BlockAssembler, createUserMessage, type GenerateOptions, type StreamChunk } from '@deepseek-ai/dsh-llm'
import {
@@ -70,7 +69,8 @@ import {
// row bound, so it lives in a dependency-free module both can import.
import { FS_TREES_MAX_PATHS } from './fs-batch.ts'
import { activeWorktreeRootOf } from './active-worktree.ts'
import { decodeTextBytes, encodeText, fileFormatOf, restoreEol } from './text-encoding.ts'
import { decodeTextAs, decodeTextBytes, lastLineBreakEnd, type TextEncoding } from './text-encoding.ts'
import { MAX_EDITABLE_BYTES, PAGE_BYTES, WRITE_BODY_GUARD_BYTES } from './editor-limits.ts'
export { Config }
export type { SidebarConfig, ResolvedSidebarConfig }
@@ -89,10 +89,10 @@ export type {
FileViewerProps,
FileFetchStrategy,
} from './client/service.ts'
// The archive walk + name helpers are exercised directly by tests/zip.spec.ts:
// The archive naming helper is exercised directly by the archive specs:
// their bounds live inside the collector, so the suite needs them observable
// without creating 10 000 rows first.
export { archiveNameOf, collectZipEntries, contentDispositionOf, disambiguateArchiveNames } from './archive-route.ts'
export { contentDispositionOf } from './archive-route.ts'
/** Plugin identity for cordis.yml rows. */
export const name = 'dsh-better-sidebar'
@@ -397,19 +397,33 @@ async function resolveStatusPath(cwd: string, raw: string, selected?: string): P
/** How many leading bytes a binary read returns for client-side detect sniffing. */
const READ_HEAD_LIMIT = 4096
/** Text read of a file with the size cap; text encoding is detected before
* the NUL-based binary fallback so UTF-16/UTF-32 text remains editable.
* Binary reads also return the first {@link READ_HEAD_LIMIT} bytes (base64)
* so the client can re-match viewers by content (`detect`). */
async function readText(path: string, readLimit: number): Promise<{
content: string
truncated: boolean
binary: boolean
size: number
/** Last-modified time (ms) — the save route's conflict baseline. */
mtimeMs: number
head?: string
}> {
/** One file read, in the shape the client's viewer dispatch consumes. */
export type SidebarReadResult =
| { kind: 'text'; content: string; size: number; mtimeMs: number }
| { kind: 'binary'; size: number; mtimeMs: number; head: string }
| { kind: 'too-large'; size: number; mtimeMs: number; head: string }
/**
* Read one file for the editor host.
*
* Three outcomes, and the size policy is deliberately about EDITING rather
* than about transfer:
*
* - at or below {@link MAX_EDITABLE_BYTES}: the whole document (or the binary
* verdict + a 4 KiB sniff head);
* - above it: `too-large`, carrying only the 4 KiB head. The client answers it
* with the read-only paged preview, and the head still lets a `detect`-based
* third-party viewer claim the file — which is also what keeps the binary
* path (images, office documents) intact for a file of any size.
*
* There is no truncation outcome any more. The old capped read handed the
* editor a partial document it could neither trust nor save (issue #732);
* "too big to edit" is now its own state instead of a quietly damaged one.
*
* Text encoding is detected before the NUL-based binary verdict, so UTF-16 /
* UTF-32 / GBK text stays text.
*/
async function readText(path: string): Promise<SidebarReadResult> {
const info = await stat(path).catch((error: unknown) => {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
@@ -417,26 +431,141 @@ async function readText(path: string, readLimit: number): Promise<{
throw new SidebarError('fs-error', `"${path}" is a directory`, 400)
}
const size = info.size
const truncated = size > readLimit
const oversized = size > MAX_EDITABLE_BYTES
const handle = await open(path, 'r').catch((error: unknown) => {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
try {
const buffer = Buffer.alloc(Math.min(size, readLimit))
// An over-limit file still yields its first bytes: that is what decides
// text-vs-binary and what feeds the client's content sniffer.
const window = oversized ? READ_HEAD_LIMIT : size
const buffer = Buffer.alloc(window)
const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0)
const slice = buffer.subarray(0, bytesRead)
const decoded = decodeTextBytes(slice, truncated)
const binary = decoded === null
const head = binary
? slice.subarray(0, Math.min(slice.length, READ_HEAD_LIMIT)).toString('base64')
: undefined
const decoded = decodeTextBytes(slice, oversized)
if (decoded === null) {
return {
kind: 'binary',
size,
mtimeMs: info.mtimeMs,
head: slice.subarray(0, Math.min(slice.length, READ_HEAD_LIMIT)).toString('base64'),
}
}
if (oversized) {
return {
kind: 'too-large',
size,
mtimeMs: info.mtimeMs,
head: slice.toString('base64'),
}
}
return { kind: 'text', content: decoded.content, size, mtimeMs: info.mtimeMs }
} finally {
await handle.close()
}
}
/**
* The encoding last detected for one (path, size, mtime) triple.
*
* Page reads decode independently, and a page that happens to be pure ASCII
* sniffs as UTF-8 while a later page of a GBK document sniffs as GBK — the two
* would then be concatenated as one mojibake document. Caching the FIRST page's
* verdict keeps a paged read internally consistent; the size+mtime in the key
* drops the entry the moment the file changes on disk.
*/
const pageEncodingCache = new Map<string, TextEncoding>()
/** Bound on {@link pageEncodingCache} (a paged read is a handful of entries). */
const PAGE_ENCODING_CACHE_MAX = 64
/** One page of a large text file: whole lines, plus where to continue. */
interface ReadPageResult {
kind: 'text'
text: string
offset: number
nextOffset: number
eof: boolean
size: number
mtimeMs: number
encoding: TextEncoding
}
/**
* Read one byte window of a text file, trimmed back to the last newline so a
* page is a whole number of lines — and, for a JSONL file, a whole number of
* records.
*
* A window with no newline at all (one line longer than {@link PAGE_BYTES}) is
* returned untrimmed: the client stitches consecutive pages back together and
* gives up on a single record past its own bound.
*
* @param path - absolute, already resolved path.
* @param offset - byte offset to start at (`0` for the first page).
* @throws {SidebarError} fs-error for an unreadable path or a bad offset.
*/
async function readPage(path: string, offset: number): Promise<ReadPageResult> {
const info = await stat(path).catch((error: unknown) => {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
if (info.isDirectory()) {
throw new SidebarError('fs-error', `"${path}" is a directory`, 400)
}
const size = info.size
if (offset >= size) {
return {
content: decoded?.content ?? '',
truncated,
binary,
kind: 'text',
text: '',
offset,
nextOffset: size,
eof: true,
size,
mtimeMs: info.mtimeMs,
head,
encoding: 'utf8',
}
}
const handle = await open(path, 'r').catch((error: unknown) => {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
})
try {
const length = Math.min(PAGE_BYTES, size - offset)
const buffer = Buffer.alloc(length)
const { bytesRead } = await handle.read(buffer, 0, length, offset)
let slice = buffer.subarray(0, bytesRead)
let nextOffset = offset + bytesRead
const cacheKey = `${path}\u0000${size}\u0000${info.mtimeMs}`
const cached = pageEncodingCache.get(cacheKey)
if (nextOffset < size) {
// Trim back to a line break so a page is a whole number of lines — and,
// for JSONL, a whole number of records. Judged in the encoding's own
// character width, because a naive byte search for 0x0A cuts UTF-16
// characters in half (see lastLineBreakEnd). A window with no break at
// all is returned untrimmed and stitched by the client.
const lastBreak = lastLineBreakEnd(slice, cached ?? 'utf8')
if (lastBreak >= 0) {
slice = slice.subarray(0, lastBreak)
nextOffset = offset + lastBreak
}
}
// Page 1 sniffs (and strips a BOM); every later page decodes under the
// verdict page 1 established, so the concatenation cannot mix encodings.
const decoded = cached === undefined ? decodeTextBytes(slice, true) : null
const encoding = cached ?? decoded?.encoding ?? 'utf8'
if (cached === undefined) {
if (pageEncodingCache.size >= PAGE_ENCODING_CACHE_MAX) {
const oldest = pageEncodingCache.keys().next()
if (!oldest.done) pageEncodingCache.delete(oldest.value)
}
pageEncodingCache.set(cacheKey, encoding)
}
return {
kind: 'text',
text: decoded?.content ?? decodeTextAs(slice, encoding),
offset,
nextOffset,
eof: nextOffset >= size,
size,
mtimeMs: info.mtimeMs,
encoding,
}
} finally {
await handle.close()
@@ -593,56 +722,21 @@ function buildApi(
// cwd; thread it so the path resolves inside the authorized workspace.
const selected = selectedRepoOf(payload)
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected))
const { content, truncated, binary, size, mtimeMs, head } = await readText(path, resolved.readLimit)
if (binary) return { kind: 'binary', size, truncated, mtimeMs, head }
return { kind: 'text', content, truncated, mtimeMs }
return await readText(path)
},
'fs.write': async (payload) => {
// One byte window of a large text file, for the read-only paged preview.
// The window is line-aligned by the host, so the client can treat each
// response as whole lines (and, for a `.jsonl`, whole records) without
// having to re-split anything.
'fs.readPage': async (payload) => {
const { cwd } = await cwdOf(payload)
const path = await ensureWorkspaceWritePath(cwd, requireString(payload, 'path'))
const content = requireString(payload, 'content')
// Detect the byte encoding AND the line ending BEFORE the temp write, so
// the save round-trips what the file already used: GBK / UTF-16 / BOM'd
// UTF-8 stay put, and a CRLF file stays CRLF. The second half matters
// because the editor transports an LF document (CodeMirror has no other
// line model), so writing it verbatim turns one edited line into a
// whole-file diff for every Windows checkout (#871).
const { encoding, eol } = await fileFormatOf(path)
// Optimistic concurrency: the client sends the mtime its draft was based
// on; a file that changed on disk since (the model wrote it, another tab
// saved, an external editor touched it) refuses the write instead of
// silently clobbering those bytes. Omitted (older callers) = no gate.
const record = payload as { expectedMtimeMs?: unknown } | null
const expected = typeof record?.expectedMtimeMs === 'number' && Number.isFinite(record.expectedMtimeMs)
? record.expectedMtimeMs
: undefined
if (expected !== undefined) {
const current = await stat(path).then(info => info.mtimeMs).catch(() => undefined)
if (current !== undefined && current !== expected) {
throw new SidebarError(
'fs-conflict',
`"${path}" changed on disk since it was loaded (expected mtime ${expected}, found ${current})`,
409,
)
}
}
// Per-request temp name (same pattern as writeWorkspaceUpload): a
// pid-suffixed name is shared by every concurrent save to the same
// path, letting two writers interleave into one temp file — and the
// failure-path rm could delete the other writer's in-flight temp.
const tmp = join(dirname(path), `.${basename(path)}.dsh-sidebar-tmp-${randomUUID()}.tmp`)
try {
await mkdir(dirname(path), { recursive: true })
await writeFile(tmp, encodeText(restoreEol(content, eol), encoding), { flag: 'wx' })
await rename(tmp, path)
} catch (error) {
await rm(tmp, { force: true }).catch(() => {})
throw new SidebarError('fs-error', `cannot write "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
invalidateDirectoryCache(dirname(path))
// The fresh baseline the client adopts after a successful save.
const mtimeMs = await stat(path).then(info => info.mtimeMs).catch(() => undefined)
return { ok: true, ...(mtimeMs !== undefined ? { mtimeMs } : {}) }
const selected = selectedRepoOf(payload)
const path = await ensureWorkspacePath(cwd, await resolveGitPath(cwd, requireString(payload, 'path'), selected))
const record = payload as { offset?: unknown } | null
const offset = typeof record?.offset === 'number' && Number.isFinite(record.offset) && record.offset >= 0
? Math.floor(record.offset)
: 0
return await readPage(path, offset)
},
// The tree row's rename: single-segment name, destination-existence and
// workspace-root refusals, link-aware (renames the row, not its target).
@@ -1007,10 +1101,15 @@ function buildApi(
if (action === 'url') return launchExternal('url', requireString(payload, 'url'))
throw new SidebarError('bad-request', 'action must be "reveal" or "url"')
},
// Archive builds: collect the selection (fenced + disambiguated) and hand
// the zipping to the background task table, so the tree can show progress
// through `archive.status` and download the finished bytes from
// GET /sidebar/archive?id=.
// Archive builds: fence the selection and hand the packing to the
// background task table, which runs the system's zip/tar into a temp file.
// The tree watches it through `archive.status` and downloads the finished
// bytes from GET /sidebar/archive?id=.
//
// The selection arrives as absolute paths and is passed to the tool as
// paths relative to the selections' common ancestor — the tool decides the
// in-archive layout from the real directory structure, so there is no walk
// and no name disambiguation here any more.
'archive.build': async (payload) => {
const { sessionId, cwd } = await cwdOf(payload)
const record = payload as { paths?: unknown; name?: unknown } | null
@@ -1018,17 +1117,10 @@ function buildApi(
? record.paths.filter((value): value is string => typeof value === 'string' && value !== '')
: []
if (paths.length === 0) throw new SidebarError('bad-request', 'paths must be a non-empty array')
const name = archiveNameOf(typeof record?.name === 'string' ? record.name : null)
const name = typeof record?.name === 'string' ? record.name : ''
const selected: string[] = []
for (const raw of paths) selected.push(await ensureWorkspacePath(cwd, raw))
// Same-basename selections (a/index.ts + b/index.ts) get parent segments
// prepended, so no two archive members collide.
const entries: ZipEntry[] = []
const names = disambiguateArchiveNames(selected)
for (const [index, absolute] of selected.entries()) {
await collectZipEntries(absolute, names[index]!, entries)
}
return archiveTasks.start({ sessionId, name, entries })
return await archiveTasks.start({ sessionId, name, paths: selected })
},
'archive.status': (payload) =>
archiveTasks.status(requireString(payload, 'id'), requireString(payload, 'sessionId')),
@@ -1321,8 +1413,11 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
const assistantLive = createAssistantLiveBuffer(ctx)
ctx.effect(() => () => { assistantLive.dispose() }, 'dsh-better-sidebar: live assistant stream buffer')
// One archive task table per mount: the `archive.build` / `archive.status`
// API methods write it, the GET /sidebar/archive route reads it.
// API methods write it, the GET /sidebar/archive route reads it. Teardown
// kills a build still running and deletes the temp files it was holding —
// an unmounted plugin must not leave orphan archives in the OS temp dir.
const archiveTasks = createArchiveTasks()
ctx.effect(() => () => { archiveTasks.dispose() }, 'dsh-better-sidebar: archive task table')
const api = buildApi(ctx, resolved, () => settingsFace, assistantLive, archiveTasks)
ctx.effect(() => ctx.webServer.register({
kind: 'prefix',
@@ -1392,7 +1487,6 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
dir,
relativePath,
chunks: req,
limit: resolved.uploadLimit,
})
writeOk(res, { path, size })
} catch (error) {
@@ -1401,6 +1495,49 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
},
}), 'dsh-better-sidebar: /sidebar/upload route')
// ── Editor save route ──────────────────────────────────────────────────
// The document IS the body: no JSON string-escaping, so the 1 MiB JSON
// envelope no longer caps what an editor can write back. The encoding and
// line-ending round-trip lives in writeWorkspaceText, unchanged.
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/sidebar/write',
handler: async (req, res) => {
if (!fence(req)) {
writeJson(res, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
return
}
if (req.method !== 'POST') {
writeJson(res, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } })
return
}
try {
const url = new URL(req.url ?? '/', 'http://dsh.internal')
const sessionId = url.searchParams.get('sessionId')
const path = url.searchParams.get('path')
if (sessionId === null || path === null || path === '') {
throw new SidebarError('bad-request', 'sessionId and path are required')
}
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId, url.searchParams.get('cwd') ?? undefined))
// Optimistic concurrency: the client sends the mtime its draft was
// based on. Absent = no gate (a brand-new file has no baseline).
const raw = url.searchParams.get('expectedMtimeMs')
const parsed = raw === null ? Number.NaN : Number(raw)
const expectedMtimeMs = Number.isFinite(parsed) ? parsed : undefined
const content = await readTextBody(req, WRITE_BODY_GUARD_BYTES)
const result = await writeWorkspaceText({
cwd,
path,
content,
...(expectedMtimeMs === undefined ? {} : { expectedMtimeMs }),
})
writeOk(res, { ok: true, ...result })
} catch (error) {
writeError(res, error)
}
},
}), 'dsh-better-sidebar: /sidebar/write route')
// ── Lazy chunk route (client bundle splits) ─────────────────────────────
// Serves the client half's split bundles (lib/client-<name>.js) so the
// heavy preview/terminal libraries load on first use, not at page start
@@ -1410,11 +1547,11 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
// ── Archive routes (zip one selection, watch it build, download it) ─────
// The file tree's "zip and download" action is a three-step flow: POST
// `archive.build` fences every `path` through the SAME workspace fence as
// fs.tree / /sidebar/file, walks the directories (a symlink is skipped, never
// followed — no escape and no cycle) and returns an id IMMEDIATELY; the
// background build reports progress through `archive.status`; and
// GET /sidebar/archive serves the finished bytes once, with the RFC 5987
// disposition. `archiveTasks` owns the concurrency cap and the TTL.
// fs.tree / /sidebar/file and returns an id IMMEDIATELY; the system's zip
// (or tar) packs the selection into a temp file in the background, reported
// through `archive.status`; and GET /sidebar/archive STREAMS the finished
// file once, with the RFC 5987 disposition. `archiveTasks` owns the
// concurrency cap, the TTL, and deleting the temp file.
ctx.effect(() => ctx.webServer.register({
kind: 'exact',
path: '/sidebar/archive',
@@ -1429,7 +1566,7 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
}
try {
const url = new URL(req.url ?? '/', 'http://dsh.internal')
respondArchiveDownload(archiveTasks, {
await respondArchiveDownload(archiveTasks, {
sessionId: url.searchParams.get('sessionId'),
id: url.searchParams.get('id'),
}, res)
@@ -1470,11 +1607,10 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
// `~` target after the cwd and hide it from the resolver.
const path = await ensureWorkspacePath(cwd, raw)
const info = await stat(path)
if (!info.isFile() || info.size > resolved.mediaLimit) {
throw new SidebarError('fs-error', 'not a file or too large', 400)
if (!info.isFile()) {
throw new SidebarError('fs-error', 'not a file', 400)
}
const type = mediaTypeForPath(path)
const body = await readFile(path)
// Raw bytes either way (binary-safe); ?download=1 switches the
// disposition so the browser saves the file instead of showing it.
const headers: Record<string, string> = { 'content-type': type, 'cache-control': 'no-cache' }
@@ -1491,8 +1627,9 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
if (url.searchParams.get('download') === '1') {
headers['content-disposition'] = `attachment; filename*=UTF-8''${encodeURIComponent(basename(path))}`
}
res.writeHead(200, headers)
res.end(body)
// Streamed, not buffered: there is no size gate left, and the host's
// memory stays flat whatever the file weighs (see file-stream.ts).
await streamFileToResponse(path, info.size, res, headers)
} catch (error) {
writeError(res, error)
}
@@ -1540,12 +1677,13 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
const cwd = await activeWorktreeRootOf(ctx, sessionId, await sessionCwdOf(ctx, sessionId))
const absolute = await ensureWorkspacePath(cwd, path)
const info = await stat(absolute)
if (!info.isFile() || info.size > resolved.mediaLimit) {
throw new SidebarError('fs-error', 'not a file or too large', 400)
if (!info.isFile()) {
throw new SidebarError('fs-error', 'not a file', 400)
}
const type = mediaTypeForPath(absolute)
const body = await readFile(absolute)
res.writeHead(200, {
// Streamed for the same reason as the media route: the previewed page
// and every relative asset it pulls through here are unbounded now.
await streamFileToResponse(absolute, info.size, res, {
'content-type': type === 'text/html' ? 'text/html; charset=utf-8' : type,
'cache-control': 'no-cache',
'x-content-type-options': 'nosniff',
@@ -1555,7 +1693,6 @@ export function apply(ctx: Context, config?: SidebarConfig): void {
// object-src 'none' blocks plugin embeds.
'content-security-policy': "sandbox allow-scripts allow-popups allow-downloads allow-modals; object-src 'none'",
})
res.end(body)
} catch (error) {
writeError(res, error)
}
+99 -1
View File
@@ -239,8 +239,106 @@ export function decodeTextBytes(bytes: Buffer, truncated = false): DecodedText |
return { content: bytes.toString('utf8'), encoding: 'utf8' }
}
let gbkEncodeMap: Map<string, number> | undefined
/**
* Whether an encoding stores one character as a fixed-width code unit, and
* whether that unit is little-endian. `1` covers every byte-oriented encoding
* (UTF-8, GBK, GB18030), where a `\n` byte is unambiguous.
*/
function unitWidth(encoding: TextEncoding): 1 | 2 | 4 {
if (encoding === 'utf16le' || encoding === 'utf16le-bom' || encoding === 'utf16be' || encoding === 'utf16be-bom') return 2
if (encoding === 'utf32le-bom' || encoding === 'utf32be-bom') return 4
return 1
}
/** Whether a fixed-width encoding is little-endian. */
function unitLittleEndian(encoding: TextEncoding): boolean {
return encoding === 'utf16le' || encoding === 'utf16le-bom' || encoding === 'utf32le-bom'
}
/**
* The byte offset just past the LAST complete line break in `bytes`, or `-1`
* when the window holds none.
*
* A byte-oriented search would be wrong for the wide encodings: in UTF-16LE the
* low byte of U+0A41 is `0x0A`, so a naive `lastIndexOf(0x0A)` cuts a character
* in half. The search therefore only accepts a `0x0A` sitting in the unit
* position a U+000A code point would occupy — the first byte of a little-endian
* unit, the last byte of a big-endian one — and reports the end of that unit.
*
* @param bytes - the window just read.
* @param encoding - the encoding {@link decodeTextAs} will use for it.
* @returns an offset into `bytes`, or `-1` when the window has no line break.
*/
export function lastLineBreakEnd(bytes: Buffer, encoding: TextEncoding): number {
const width = unitWidth(encoding)
const littleEndian = unitLittleEndian(encoding)
for (let index = bytes.length - 1; index >= 0; index -= 1) {
if (bytes[index] !== 0x0A) continue
if (width === 1) return index + 1
const within = littleEndian ? index % width : width - 1 - (index % width)
if (within !== 0) continue
return littleEndian ? index + width : index + 1
}
return -1
}
/**
* Decode a buffer UNDER A KNOWN ENCODING, without sniffing.
*
* {@link decodeTextBytes} answers "what is this file?" from the bytes alone,
* which is the wrong question for the second page of a paged read: a page that
* happens to be pure ASCII sniffs as UTF-8 while a GBK page of the same
* document sniffs as GBK, and concatenating the two yields mojibake. The paged
* reader sniffs once and decodes every later window with this.
*
* BOM handling stays with the caller: `*-bom` encodings describe the file's
* first bytes, so a caller reading from a non-zero offset should pass the
* BOM-less spelling (see `bomlessEncoding`).
*
* @param bytes - the window to decode (already known to be text).
* @param encoding - the encoding the first window established.
* @returns the decoded text; undecodable bytes fall back to UTF-8, matching
* {@link decodeTextBytes}'s replacement-character behavior.
*/
export function decodeTextAs(bytes: Buffer, encoding: TextEncoding): string {
switch (encoding) {
case 'utf8':
case 'utf8-bom':
return tryDecode(UTF8_DECODER, bytes) ?? bytes.toString('utf8')
case 'utf16le':
case 'utf16le-bom':
return decodeUtf16(bytes, true)
case 'utf16be':
case 'utf16be-bom':
return decodeUtf16(bytes, false)
case 'utf32le-bom':
return decodeUtf32(bytes, true)
case 'utf32be-bom':
return decodeUtf32(bytes, false)
case 'gbk':
return tryDecode(GBK_DECODER, bytes) ?? bytes.toString('utf8')
case 'gb18030':
return tryDecode(GB18030_DECODER, bytes) ?? bytes.toString('utf8')
}
}
/**
* The same encoding minus its BOM marker, for windows that do not start at the
* beginning of the file (only offset 0 can carry a BOM).
*
* @param encoding - an encoding an earlier window detected.
* @returns the BOM-less spelling (unchanged for encodings that have none).
*/
export function bomlessEncoding(encoding: TextEncoding): TextEncoding {
switch (encoding) {
case 'utf8-bom': return 'utf8'
case 'utf16le-bom': return 'utf16le'
case 'utf16be-bom': return 'utf16be'
default: return encoding
}
}
let gbkEncodeMap: Map<string, number> | undefined
function getGbkEncodeMap(): Map<string, number> {
if (gbkEncodeMap !== undefined) return gbkEncodeMap
const map = new Map<string, number>()
+48 -2
View File
@@ -17,6 +17,7 @@ export type SidebarErrorCode =
| 'forbidden'
| 'method-error'
| 'too-large'
| 'unavailable'
| 'fs-error'
| 'fs-conflict'
| 'git-error'
@@ -76,8 +77,53 @@ export async function readJsonBody(req: SidebarHttpRequest): Promise<unknown> {
}
}
/** Write a JSON response with the given status. */
export function writeJson(res: SidebarHttpResponse, status: number, body: unknown): void {
/**
* Read a raw text request body (the editor save route).
*
* JSON framing was what capped a save at {@link MAX_BODY_BYTES}: the whole
* document had to be string-escaped into one JSON payload, so a file the
* editor could legitimately open could not be written back. The save route
* therefore takes the document as the raw body.
*
* `limit` is a server-side sanity guard rather than a product limit — the UI
* cannot produce more than the editable size — because the encoding transform
* the caller runs afterwards needs the document as one string.
*
* @param req - the request face (async-iterable body).
* @param limit - maximum accepted body size in bytes.
* @returns the body decoded as UTF-8.
* @throws {SidebarError} too-large beyond the limit, bad-request on invalid UTF-8.
*/
export async function readTextBody(req: SidebarHttpRequest, limit: number): Promise<string> {
const chunks: Buffer[] = []
let total = 0
for await (const chunk of req) {
const buffer = Buffer.from(chunk)
total += buffer.length
if (total > limit) {
throw new SidebarError('too-large', `request body exceeds the ${limit} byte limit`, 413)
}
chunks.push(buffer)
}
// `fatal` so a body that is not valid UTF-8 is refused instead of silently
// becoming replacement characters in the saved file.
try {
return new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks))
} catch {
throw new SidebarError('bad-request', 'request body is not valid UTF-8')
}
}
/** Write a JSON response with the given status. */export function writeJson(res: SidebarHttpResponse, status: number, body: unknown): void {
// The response may already be committed by one of the raw byte routes (a
// file stream that failed mid-flight): `writeHead` would then throw
// ERR_HTTP_HEADERS_SENT, and the route's catch block would turn a merely
// truncated download into a crashed request. There is nothing left to say to
// the client once the status line is out — tear the socket down instead.
if (res.headersSent === true) {
res.destroy?.()
return
}
const payload = JSON.stringify(body)
res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' })
res.end(payload)
-300
View File
@@ -1,300 +0,0 @@
/**
* Archive builder for the file tree's "zip and download" action.
*
* One self-contained ZIP writer: local file headers + central directory +
* EOCD, CRC-32 computed locally, `store` (method 0) or `zlib`'s raw DEFLATE
* (method 8) picked per entry by whichever is smaller, names written as
* UTF-8 (general-purpose bit 11) and DOS timestamps taken from one `Date`
* for the whole archive. No third-party dependency, no filesystem walking —
* the caller supplies the entries, this module only reads their bytes.
*
* The entries are bounded by `maxEntries` / `maxBytes`: the count is checked
* up front, and every source is stat'ed against the remaining byte budget
* BEFORE it is read, so a runaway selection fails with a clear error instead
* of filling memory with an archive nobody asked for.
*/
import { readFile, stat } from 'node:fs/promises'
import { deflateRaw } from 'node:zlib'
import { promisify } from 'node:util'
import { SidebarError } from './wire.ts'
/** One archive member: a file to read, or a directory to record. */
export interface ZipEntry {
/** Absolute filesystem path (source of the bytes). Ignored for a directory
* entry (`isDir: true`), which only contributes its own header row. */
path: string
/** In-archive name: '/'-separated and relative. A directory name must end
* with '/'. */
name: string
/** Write a directory entry (zero-length name + trailing '/') instead of
* reading the path as a file. */
isDir?: boolean
}
/** One progress report: entries finished, entries total, bytes read so far. */
export interface ZipProgress {
/** Entries fully processed (payload read, compressed, hashed). */
done: number
/** Entries the archive will contain (known up front: the entries array). */
total: number
/** Uncompressed bytes accumulated so far. */
bytes: number
}
/** The archive bounds and the optional progress hook. */
export interface ZipOptions {
/** Total uncompressed byte bound; exceeding it throws fs-error. */
maxBytes?: number
/** Entry-count bound (directory entries included); exceeding it throws
* fs-error. */
maxEntries?: number
/** Called once per finished entry, in archive order (never for a failed
* one). A throw from the hook aborts the build. */
onProgress?: (progress: ZipProgress) => void
}
/** Default total uncompressed payload bound of one archive (256 MiB). */
export const ZIP_MAX_BYTES = 256 * 1024 * 1024
/** Default entry-count bound of one archive. */
export const ZIP_MAX_ENTRIES = 10_000
/** DOS epoch (1980-01-01) — the smallest representable DOS timestamp. */
const DOS_YEAR_BASE = 1980
/** CRC-32 (IEEE 802.3, the ZIP polynomial), table built once per process. */
const CRC_TABLE = ((): Uint32Array => {
const table = new Uint32Array(256)
for (let i = 0; i < 256; i += 1) {
let value = i
for (let bit = 0; bit < 8; bit += 1) {
value = (value & 1) !== 0 ? (0xEDB88320 ^ (value >>> 1)) : (value >>> 1)
}
table[i] = value >>> 0
}
return table
})()
/** CRC-32 of one buffer. */
export function crc32(data: Uint8Array): number {
let crc = 0xFFFFFFFF
for (let i = 0; i < data.length; i += 1) {
crc = CRC_TABLE[(crc ^ data[i]!) & 0xFF]! ^ (crc >>> 8)
}
return (crc ^ 0xFFFFFFFF) >>> 0
}
/** One prepared member: the bytes to store plus their header fields. */
interface ZipMember {
name: Buffer
data: Buffer
crc: number
method: 0 | 8
/** Uncompressed size (the local/central header field). */
size: number
}
const deflateRawAsync = promisify(deflateRaw)
/** DOS date + time words for one instant (clamped to the 1980 epoch). */
function dosDateTime(date: Date): { time: number; date: number } {
const year = Math.max(date.getFullYear(), DOS_YEAR_BASE)
const month = date.getMonth() + 1
const day = date.getDate()
const hours = date.getHours()
const minutes = date.getMinutes()
const seconds = date.getSeconds()
return {
time: (hours << 11) | (minutes << 5) | (seconds >> 1),
date: ((year - DOS_YEAR_BASE) << 9) | (month << 5) | day,
}
}
/**
* Normalize an entry name to a '/'-separated relative archive path.
*
* A backslash is NOT a separator here: on POSIX (and on the host half, which
* builds the names) `a\b.txt` is one legal file name, so converting it would
* silently split one file into a directory. Windows separators never reach
* this point — the walk composes names from `basename`/`join` results.
* Leading slashes are dropped (names are archive-relative by definition) and
* `..` segments are refused, so a name can never traverse.
*/
function archiveName(raw: string, isDir: boolean): string {
const normalized = raw.replace(/^\/+/, '')
const segments = normalized.split('/').filter(segment => segment !== '' && segment !== '.')
if (raw === '..' || segments.length === 0 || segments.includes('..')) {
throw new SidebarError('bad-request', `invalid archive entry name "${raw}"`)
}
const name = segments.join('/')
return isDir ? `${name}/` : name
}
/** The absolute filesystem path shape the builder accepts. */
function requireSourcePath(raw: string): string {
if (raw === '' || raw.includes('\0')) {
throw new SidebarError('bad-request', 'archive entry path is required')
}
return raw
}
/**
* Read + compress one member (deflate only when it actually shrinks).
* @param limit - the archive's total uncompressed ceiling (for the message).
* @param budget - uncompressed bytes still available; the source is stat'ed
* FIRST and refused when it cannot fit, so an oversized archive never pulls
* the payload into memory (let alone deflates it) before failing.
*/
async function prepareFile(name: string, path: string, limit: number, budget: number): Promise<ZipMember> {
let size: number
try {
size = (await stat(path)).size
} catch (error) {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
// `budget <= 0` refuses even a zero-size source. That is not pedantry: a
// FIFO stats as 0 bytes and reading one BLOCKS until a writer shows up, so
// an exhausted budget must never reach open().
if (budget <= 0 || size > budget) {
throw new SidebarError('fs-error', `archive exceeds the ${limit} byte limit`, 400)
}
let data: Buffer
try {
data = await readFile(path)
} catch (error) {
throw new SidebarError('fs-error', `cannot read "${path}": ${error instanceof Error ? error.message : String(error)}`, 400)
}
const crc = crc32(data)
const deflated = await deflateRawAsync(data)
const useDeflate = deflated.byteLength < data.byteLength
return {
name: Buffer.from(name, 'utf8'),
data: useDeflate ? deflated : data,
crc,
method: useDeflate ? 8 : 0,
size: data.byteLength,
}
}
/** One directory member (zero payload, name already carries the '/'). */
function directoryMember(name: string): ZipMember {
return { name: Buffer.from(name, 'utf8'), data: Buffer.alloc(0), crc: 0, method: 0, size: 0 }
}
/** Write one local file header + payload into `out`. */
function writeLocalHeader(out: Buffer[], member: ZipMember, time: number, date: number): void {
const header = Buffer.alloc(30)
header.writeUInt32LE(0x04034B50, 0)
header.writeUInt16LE(20, 4) // version needed: 2.0 (deflate)
header.writeUInt16LE(0x0800, 6) // general purpose: UTF-8 names (bit 11)
header.writeUInt16LE(member.method, 8)
header.writeUInt16LE(time, 10)
header.writeUInt16LE(date, 12)
header.writeUInt32LE(member.crc, 14)
header.writeUInt32LE(member.data.byteLength, 18)
header.writeUInt32LE(member.size, 22)
header.writeUInt16LE(member.name.byteLength, 26)
header.writeUInt16LE(0, 28) // extra length
out.push(header, member.name, member.data)
}
/**
* Build one ZIP archive from the given entries.
* @param entries - files to read and/or directory rows to record; a directory
* row contributes its own header, its children are separate entries.
* @param opts - entry-count and total-byte bounds ({@link ZipOptions}).
* @returns the ZIP bytes.
* @throws {SidebarError} bad-request for malformed entry names/paths,
* fs-error when an entry cannot be read or a bound is exceeded.
*/
export async function buildZip(entries: readonly ZipEntry[], opts: ZipOptions = {}): Promise<Buffer> {
const maxEntries = opts.maxEntries ?? ZIP_MAX_ENTRIES
const maxBytes = opts.maxBytes ?? ZIP_MAX_BYTES
if (entries.length > maxEntries) {
throw new SidebarError('fs-error', `too many entries for one archive (${entries.length} > ${maxEntries})`, 400)
}
const now = new Date()
const stamp = dosDateTime(now)
const members: ZipMember[] = []
/** Total uncompressed payload (the bound is checked against it). */
let totalBytes = 0
/** Entries finished so far (the progress hook's `done`). */
let done = 0
const report = (): void => {
opts.onProgress?.({ done, total: entries.length, bytes: totalBytes })
}
for (const entry of entries) {
if (entry.isDir === true) {
members.push(directoryMember(archiveName(entry.name, true)))
done += 1
report()
continue
}
const path = requireSourcePath(entry.path)
// The bound is the archive's total UNCOMPRESSED payload: that is what the
// reader materializes, and it makes the limit independent of how well the
// input happens to compress.
const member = await prepareFile(archiveName(entry.name, false), path, maxBytes, maxBytes - totalBytes)
// A source can grow AFTER its stat (sparse files, concurrent writers), so
// the ceiling is re-checked against what was actually read.
if (totalBytes + member.size > maxBytes) {
throw new SidebarError('fs-error', `archive exceeds the ${maxBytes} byte limit`, 400)
}
totalBytes += member.size
members.push(member)
done += 1
report()
}
const out: Buffer[] = []
const offsets: number[] = []
let offset = 0
for (const member of members) {
offsets.push(offset)
writeLocalHeader(out, member, stamp.time, stamp.date)
offset += 30 + member.name.byteLength + member.data.byteLength
}
const directoryStart = offset
members.forEach((member, index) => {
const isDir = member.name.toString('utf8').endsWith('/')
const header = Buffer.alloc(46)
header.writeUInt32LE(0x02014B50, 0)
header.writeUInt16LE(0x031E, 4) // version made by: 3.0 / Unix
header.writeUInt16LE(20, 6) // version needed: 2.0
header.writeUInt16LE(0x0800, 8) // general purpose: UTF-8 names (bit 11)
header.writeUInt16LE(member.method, 10)
header.writeUInt16LE(stamp.time, 12)
header.writeUInt16LE(stamp.date, 14)
header.writeUInt32LE(member.crc, 16)
header.writeUInt32LE(member.data.byteLength, 20)
header.writeUInt32LE(member.size, 24)
header.writeUInt16LE(member.name.byteLength, 28)
header.writeUInt16LE(0, 30) // extra length
header.writeUInt16LE(0, 32) // comment length
header.writeUInt16LE(0, 34) // disk number
header.writeUInt16LE(0, 36) // internal attributes
// "version made by" says Unix, so the high word is the Unix mode and the
// low word carries the MS-DOS attributes. Both halves matter: without the
// mode, Info-ZIP extracts every file as mode 000 (unreadable). The mode is
// scaled with `* 0x10000` rather than `<< 16`: the shift is a signed int32
// operation and `0o100644 << 16` is negative, which writeUInt32LE rejects.
const mode = isDir ? 0o40755 : 0o100644
header.writeUInt32LE(mode * 0x10000 + (isDir ? 0x10 : 0), 38)
header.writeUInt32LE(offsets[index]!, 42)
out.push(header, member.name)
offset += 46 + member.name.byteLength
})
const eocd = Buffer.alloc(22)
eocd.writeUInt32LE(0x06054B50, 0)
eocd.writeUInt16LE(0, 4) // this disk
eocd.writeUInt16LE(0, 6) // disk with the central directory
eocd.writeUInt16LE(members.length, 8)
eocd.writeUInt16LE(members.length, 10)
eocd.writeUInt32LE(offset - directoryStart, 12)
eocd.writeUInt32LE(directoryStart, 16)
eocd.writeUInt16LE(0, 20) // comment length
out.push(eocd)
return Buffer.concat(out)
}