diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1aaeeb74..45966df3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,9 @@
- 🔍 **宿主接管页头时也有「查找」入口了**([#1214](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1214)):v0.32.1 给编辑器自带工具条加的查找按钮,在侧栏真实的合并式页头(`EditorHost` 以 `toolbar: 'host'` 接管)下整行不渲染,markdown / html / jsonl 预览态更是没有任何查找入口,只剩可能被第三方插件全局截获的 Cmd/Ctrl+F。现在内置编辑器把查找命令注册给宿主页头:文件可编辑时页头显示查找按钮,点击与自带工具条按钮走同一套逻辑——预览态先切到编辑,再打开 CodeMirror 的查找面板(含替换行)。没有查找面的 viewer 不注册该命令,页头也就不显示按钮。
- 🧪 测试:`tests/editor-host.spec.tsx` 用真实 `TextEditor` 走「页头查找按钮 → 搜索面板打开 + markdown 预览切编辑」;`tests/editor-find.spec.tsx` 增加 host 模式命令测试。
+- 🪲 **单行几百 KB 的压缩文件不再在点「编辑」时卡死渲染进程**([#1165](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1165)):327 KB 的压缩 HTML(整份文件只有一行)能通过 5 MB 的字节上限,但 CodeMirror 按行虚拟化——一行几百 KB 会在首帧一次性解析、着色、排版,渲染进程直接卡死,只能重启。现在 `fs.read` 在宿主侧对已解码文档的**前 64 K 字符(65,536)**做一次有界探测:任一行达到 20,000 字符就以 `{ kind: 'too-large', reason: 'line' }` 拒绝文档,客户端从不扫描字节,也不会为它创建任何 CodeMirror 状态。它走既有的只读分页预览,提示改为「文件含超长单行(大小)」,不再假装是「文件过大」,下载出口照旧。字节上限(5 MiB)与分页逻辑都不变。
+ - 🧪 测试:`tests/editor-limits.spec.ts`(单行超限 / 正常多行 / 临界值 / CRLF / 有界探测)、`tests/editor-large-file.spec.tsx`(长单行提示 + 无编辑器)、`tests/editor-load.spec.ts` 与 `tests/editor-host.spec.tsx`(`reason` 沿线透传)。
+
- 🎯 **侧边对话「回到最新」胶囊不再塌成细条、端部恢复正圆**([#1208](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1208)):胶囊所在的 `.sidechatToLatestSlot` 是 `height: 0` 的绝对定位 flex 槽位(抄宿主 `ui-chat` 的 `.toBottomSlot` 配方),但子项没有尺寸约束——默认 `align-items: stretch` 会在零高容器里把它拉到 0 高,内容高度被丢掉,只剩 `padding + border` 的 10px,文字于是溢出到胶囊外。宿主自己的 `.toBottom` 靠显式 `34px` 高度绕开了同一个坑,这里改用 `align-items: flex-end` + `flex: none` 让胶囊保持自身内容高度(30px)。同时补上 `corner-shape: round`:宿主 `corner-shape.css` 对 `*` 施加 `superellipse(1.5)`,会把 `border-radius: 999px` 的胶囊端部削平,宿主的全圆元素都成对声明退出该效果,本插件此前漏了这条。该按钮在 v0.31.0 引入,v0.31.0–v0.32.1 均受影响。
- 🧪 真实宿主 + Chromium 挂载冒烟确认侧边对话渲染无回归;修复前后在 Chrome 157 用宿主真实 token 样式表做过 A/B 对照(高度 10px→30px、文字溢出 true→false、`corner-shape` 恢复 `superellipse(1)`)。
diff --git a/CHANGELOG_EN.md b/CHANGELOG_EN.md
index 772e53c7..d8019213 100644
--- a/CHANGELOG_EN.md
+++ b/CHANGELOG_EN.md
@@ -9,6 +9,9 @@
- 🔍 **Find is available when the host owns the editor header** ([#1214](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1214)): the find button added to the editor's own toolbar in v0.32.1 never rendered in the real sidebar, where `EditorHost` takes the header over with `toolbar: 'host'` and the whole self-toolbar row is skipped — and a markdown/html/jsonl preview had no find entry at all, leaving Cmd/Ctrl+F as the only way, which a third-party plugin can capture globally. The built-in text editor now registers its find command with the host header: the button appears while the file is editable and runs the same logic as the toolbar one — flip a preview to edit first, then open CodeMirror's search panel (replace row included). A viewer with no find surface omits the command, so no button appears for it.
- 🧪 `tests/editor-host.spec.tsx` drives the real `TextEditor` through "header find button → panel opens + markdown preview flips to edit"; `tests/editor-find.spec.tsx` covers the host-mode command.
+- 🪲 **A few-hundred-KB single-line file no longer freezes the renderer on 编辑** ([#1165](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1165)): a 327 KB minified HTML file (the whole document is one line) passes the 5 MB byte limit, but CodeMirror virtualizes by line — one line of a few hundred KB is parsed, tokenized and laid out in a single frame, hanging the renderer until the process is restarted. `fs.read` now runs a bounded probe over the **first 64K characters** (65,536) of the already-decoded document on the host: any line reaching 20,000 characters is refused with `{ kind: 'too-large', reason: 'line' }`, so the client never scans the bytes and no CodeMirror state is ever built for the file. It uses the existing read-only paged preview, whose notice now says "file has a very long line (size)" instead of pretending the file is too large, and the download escape hatch stays. The 5 MiB byte limit and the paging logic are unchanged.
+ - 🧪 Tests: `tests/editor-limits.spec.ts` (over-limit single line / normal multi-line / threshold / CRLF / bounded probe), `tests/editor-large-file.spec.tsx` (long-line notice + no editor), and `tests/editor-load.spec.ts` + `tests/editor-host.spec.tsx` (`reason` carried through).
+
- 🎯 **The side chat's "back to latest" pill no longer collapses into a sliver, and its ends are round again** ([#1208](https://github.com/omdsh-dev/DSH-better-sidebar/issues/1208)): the pill's `.sidechatToLatestSlot` is a `height: 0` absolutely-positioned flex slot (the host's `ui-chat` `.toBottomSlot` recipe), but its child carried no size constraint — the default `align-items: stretch` pulled it to zero height inside a zero-height box, discarding its content height and leaving only the `padding + border` 10px, so the label overflowed outside the capsule. The host's own `.toBottom` sidesteps the same trap with an explicit `34px` height; this uses `align-items: flex-end` + `flex: none` so the pill keeps its own content height (30px). `corner-shape: round` is added alongside: the host's `corner-shape.css` applies `superellipse(1.5)` to `*`, which squares off the ends of a `border-radius: 999px` capsule, and the host's own full-round elements opt out in pairs — this plugin had missed that. The button shipped in v0.31.0 and every release from v0.31.0 through v0.32.1 is affected.
- 🧪 The real-host + Chromium mount smoke confirms side-chat rendering has no regression; the before/after was A/B-checked in Chrome 157 against the host's real token sheets (height 10px → 30px, text overflow true → false, `corner-shape` back to `superellipse(1)`).
diff --git a/docs/external-plugin-guide.md b/docs/external-plugin-guide.md
index 1031f4d5..cc36cd16 100644
--- a/docs/external-plugin-guide.md
+++ b/docs/external-plugin-guide.md
@@ -540,7 +540,7 @@ interface FileViewerProps {
viewerId: string // 命中 viewer 的 id(如 'code' / 'my-plugin:csv')
content?: string // fetchStrategy='fsRead' 时;超过编辑上限的文件不带它
size?: number // 本次读取量到的文件字节数
- largeFile?: { size: number } // 见下方「超大文件」
+ largeFile?: { size: number; reason?: 'size' | 'line' } // 见下方「超大文件」
mtimeMs?: number // fetchStrategy='fsRead' 时:本次读取的磁盘 mtime(保存冲突基线)
mediaUrl?: string // fetchStrategy='mediaUrl' 时
customData?: unknown // fetchStrategy='custom' 时(load() 的返回值)
@@ -561,7 +561,7 @@ interface FileViewerProps {
> **页头查找(#1214)**:当 viewer 以 `toolbar: 'host'` 运行(本插件的合并式编辑器页头),查找按钮由宿主页头渲染,而命令来自 viewer 注册的 `EditorToolbarControls.search`。**不注册 `search` 就没有查找按钮**,第三方 viewer 无需改动。内置文本编辑器的 `search()` 与自带工具条的查找按钮同一套逻辑:markdown / html / jsonl 在预览态会先切到编辑,再打开 CodeMirror 的查找面板(含替换行);纯代码文件直接打开。
>
-> **超大文件(v0.26.0 起,`truncated` 已被取代)**:文件超过编辑上限(5 MiB,见 `src/editor-limits.ts` 的 `MAX_EDITABLE_BYTES`)时,`fs.read` 不再回一份被截断的文档,而是 `{ kind: 'too-large', size, mtimeMs, head }` —— **不带 `content`**。宿主把这个结果交给命中的 viewer 时,`content` 缺席、`largeFile: { size }` 到位(见 `planFsReadOutcome`)。内置的文本 viewer 据此渲染只读分页预览(`LargeFileView`),并提供下载出口;**你的 viewer 必须容忍 `content === undefined`**:要么自己处理 `largeFile`(分页预览 / 提示),要么把状态回给 `onToolbarState` 让宿主收起保存按钮。旧的 `truncated` 布尔字段与 `EditorToolbarState.truncated` 都已删除——「拿到半份文档但看起来能编辑」这个状态本身没有了,这正是它被删掉的原因(#732:保存半份文档会毁掉文件尾部)。
+> **超大文件(v0.26.0 起,`truncated` 已被取代)**:文件超过编辑上限(5 MiB,见 `src/editor-limits.ts` 的 `MAX_EDITABLE_BYTES`),**或文件头 64 K 字符内出现单行 ≥ 20,000 字符**(#1165:压缩成单行的 HTML/JS 远低于字节上限,却会让 CodeMirror 的单行虚拟化在首帧卡死)时,`fs.read` 不再回一份被截断的文档,而是 `{ kind: 'too-large', size, mtimeMs, head, reason }` —— **不带 `content`**;`reason` 为 `'size'` 或 `'line'`,让 UI 能说清是哪个上限。宿主把这个结果交给命中的 viewer 时,`content` 缺席、`largeFile: { size, reason? }` 到位(见 `planFsReadOutcome`)。内置的文本 viewer 据此渲染只读分页预览(`LargeFileView`),并提供下载出口;**你的 viewer 必须容忍 `content === undefined`**:要么自己处理 `largeFile`(分页预览 / 提示),要么把状态回给 `onToolbarState` 让宿主收起保存按钮。旧的 `truncated` 布尔字段与 `EditorToolbarState.truncated` 都已删除——「拿到半份文档但看起来能编辑」这个状态本身没有了,这正是它被删掉的原因(#732:保存半份文档会毁掉文件尾部)。
>
> **分页读取**:`fs.readPage({ sessionId, cwd?, path, offset })` 按字节窗口返回一页文本(宿主按行对齐,并在同一个文件内锁定宽字符编码),返回 `{ kind:'text', text, offset, nextOffset, eof, size, mtimeMs, encoding }`。消费方式就是**只向前追加**:把每页的 `text` 接到一起,下一次请求用上一页的 `nextOffset` 作为 `offset`,直到 `eof`。因此**必须串行**(下一页的偏移就是上一页的响应),也**不能跳到末尾**——随机访问需要打开时先扫全文件建索引,而那正是分页要避免的开销。内置预览在这之上加了两个策略:滚到底自动追加下一页,以及一条按**渲染行数**设的上限(`LargeFileView` 的 `MAX_PREVIEW_ROWS`),到顶后停止追加并提示下载。
diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx
index c49554a1..6cc0d7bd 100644
--- a/src/client/EditorHost.tsx
+++ b/src/client/EditorHost.tsx
@@ -27,6 +27,7 @@ import { createElement } from 'react'
import clsx from 'clsx'
import { Button, IconCheckOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular, IconSearchOutlineRegular, writeClipboard } from '@deepseek-ai/dsh-client-ui-primitives'
import type { Context } from '../context-types.ts'
+import type { EditLimitReason } from '../editor-limits.ts'
import { api, mediaUrl, SidebarApiError, type SessionScope } from './api.ts'
import { BinaryDownload } from './binary-download.tsx'
import { isDirectoryReadError, planFirstMatch, planFsReadOutcome, type EditorLoadAction } from './editor-load.ts'
@@ -79,7 +80,7 @@ interface LineNav { key: string; nonce: number | null; end?: number }
type EditorLoad =
| { status: 'loading' }
| { status: 'error'; message: string; fileNotFound?: boolean; windowsAbsolutePath?: boolean; repairStatus?: 'searching' | 'done'; repairMatches?: string[]; repairError?: string }
- | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; size?: number; largeFile?: { size: number }; mtimeMs?: number; mediaUrl?: string; customData?: unknown }
+ | { status: 'ready'; viewer: FileViewerDescriptor; content?: string; size?: number; largeFile?: { size: number; reason?: EditLimitReason }; mtimeMs?: number; mediaUrl?: string; customData?: unknown }
| { status: 'binary' }
/** The docked tree panel's width bounds (drag-resize clamps into them). */
diff --git a/src/client/LargeFileView.tsx b/src/client/LargeFileView.tsx
index d2458f34..c892fbd5 100644
--- a/src/client/LargeFileView.tsx
+++ b/src/client/LargeFileView.tsx
@@ -29,7 +29,7 @@ import clsx from 'clsx'
import { 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_BYTES, MAX_EDITABLE_LABEL } from '../editor-limits.ts'
+import { formatByteSize, MAX_EDITABLE_BYTES, MAX_EDITABLE_LABEL, type EditLimitReason } from '../editor-limits.ts'
import { isJsonlPath, isTreeRecord, parseRecord, summarizeRecord } from './jsonl.ts'
import { splitLines, useTextPager } from './text-pages.ts'
import { t } from './locales.ts'
@@ -75,6 +75,9 @@ function jsonLabels(): JsonTreeLabels {
* @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.reason - why the file stayed out of the edit buffer: the byte
+ * limit (`size`, also the fallback when absent) or the long-line probe
+ * (`line`, #1165). The notice names the actual limit.
* @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 one.
* @param props.maxRows - row ceiling (defaults to {@link MAX_PREVIEW_ROWS}).
@@ -84,6 +87,7 @@ export function LargeFileView(props: {
scope: SessionScope
path: string
size: number
+ reason?: EditLimitReason
visible: boolean
revision: number
maxRows?: number
@@ -101,14 +105,15 @@ export function LargeFileView(props: {
const labels = useMemo(() => jsonLabels(), [])
/**
- * Whether this file is over the EDITABLE threshold — a different question
- * from "is this view paged".
+ * Whether this file is over an EDITABLE limit — the byte threshold, or the
+ * long-line probe (#1165) — a different question from "is this view paged".
*
* A small `.jsonl` opens straight into this record list as its PREVIEW, and
* announcing "the file is too large, paged preview only" over a 2 KB file
- * would be a lie. The threshold decides, not the component.
+ * would be a lie. The host's reason (or the byte threshold, for a caller
+ * that carries none) decides, not the component.
*/
- const tooLarge = size > MAX_EDITABLE_BYTES
+ const overLimit = props.reason === 'line' || size > MAX_EDITABLE_BYTES
const rows = useMemo(() => pager.pages.map(splitLines), [pager.pages])
const totalRows = useMemo(() => rows.reduce((sum, page) => sum + page.length, 0), [rows])
@@ -151,9 +156,11 @@ export function LargeFileView(props: {
return (
- {tooLarge && (
+ {overLimit && (
- {t('previewOnlyNotice', { size: formatByteSize(size), limit: MAX_EDITABLE_LABEL })}
+ {props.reason === 'line'
+ ? t('previewLongLineNotice', { size: formatByteSize(size) })
+ : t('previewOnlyNotice', { size: formatByteSize(size), limit: MAX_EDITABLE_LABEL })}
diff --git a/src/client/api.ts b/src/client/api.ts
index 8be8cd11..aba825dc 100644
--- a/src/client/api.ts
+++ b/src/client/api.ts
@@ -8,6 +8,7 @@
* request). Failures surface as {@link SidebarApiError} with the wire code.
*/
import type { SidechatImageUpload } from '../sidechat-images.ts'
+import type { EditLimitReason } from '../editor-limits.ts'
import { encodeHtmlUrl } from '../html-route.ts'
import { hostRouteUrl } from './host-route-url.ts'
import { resolveSidebarPath } from './paths.ts'
@@ -182,11 +183,13 @@ export interface FsTextResult { kind: 'text'; content: string; size: number; mti
* `head` carries the first bytes (base64) for viewer detect sniffing. */
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.
+ * The host refused the document: above the editable byte threshold, or with a
+ * line above the edit buffer's line limit (#1165). It sends no document, only
+ * the size, a 4 KiB sniff head and (on a current host) which limit was hit.
+ * 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 }
+export interface FsTooLargeResult { kind: 'too-large'; size: number; mtimeMs?: number; head: string; reason?: EditLimitReason }
/** One `fs.read` outcome. */
export type FsReadResult = FsTextResult | FsBinaryResult | FsTooLargeResult
diff --git a/src/client/editor-load.ts b/src/client/editor-load.ts
index 0a6d6be1..c0305c8b 100644
--- a/src/client/editor-load.ts
+++ b/src/client/editor-load.ts
@@ -12,6 +12,7 @@
* re-match that lets a `detect` viewer claim a binary the extension
* match could not see (the builtin NUL probe on `binary-download`).
*/
+import type { EditLimitReason } from '../editor-limits.ts'
import type { FileViewerDescriptor } from './service.ts'
/**
@@ -36,7 +37,7 @@ export function isDirectoryReadError(error: unknown): boolean {
export type FsReadOutcome =
| { kind: 'text'; content: string; size: number }
| { kind: 'binary'; size: number; head: string }
- | { kind: 'too-large'; size: number; head: string }
+ | { kind: 'too-large'; size: number; head: string; reason?: EditLimitReason }
/** What the editor host should do next. */
export type EditorLoadAction =
@@ -48,9 +49,11 @@ export type EditorLoadAction =
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 }
+ /** Present when the host refused the document (byte limit or one line
+ * above the edit buffer's line limit): the viewer must render the
+ * read-only paged preview rather than an editor. `reason` tells the two
+ * apart so the viewer can say why. */
+ largeFile?: { size: number; reason?: EditLimitReason }
mediaUrl?: string
customData?: unknown
}
@@ -124,7 +127,13 @@ export function planFsReadOutcome(
// 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 } }
+ // `reason` rides through so the viewer's notice can tell "too big" from
+ // "one line too long" (#1165); an older host sends none, which reads as
+ // the size answer.
+ const largeFile = result.reason === undefined
+ ? { size: result.size }
+ : { size: result.size, reason: result.reason }
+ return { kind: 'render', viewer, size: result.size, largeFile }
}
return { kind: 'binary' }
}
diff --git a/src/client/locales-ar.ts b/src/client/locales-ar.ts
index e8e8afd9..cc6dced6 100644
--- a/src/client/locales-ar.ts
+++ b/src/client/locales-ar.ts
@@ -178,6 +178,7 @@ export const ar: Record = {
saveConflict: 'تم تغيير الملف على القرص من مصدر آخر. تم إيقاف الحفظ، وتعديلاتك ما زالت في المحرر.',
saveConflictReload: 'إعادة التحميل من القرص',
previewOnlyNotice: 'الملف كبير جداً ({size}) — معاينة مقسّمة إلى صفحات فقط؛ التحرير متاح حتى {limit}',
+ previewLongLineNotice: 'يحتوي الملف على سطر طويل جداً ({size}) — معاينة مقسّمة إلى صفحات فقط',
largeFileEmpty: '(ملف فارغ)',
pagedLineRange: 'الأسطر {from}–{to}',
loadAll: 'تحميل الكل',
diff --git a/src/client/locales-de.ts b/src/client/locales-de.ts
index 14292784..4034982e 100644
--- a/src/client/locales-de.ts
+++ b/src/client/locales-de.ts
@@ -163,6 +163,7 @@ export const de: Record = {
saveConflict: 'Die Datei wurde auf der Platte von anderer Stelle geändert. Speichern abgebrochen; Ihre Änderungen bleiben im Editor.',
saveConflictReload: 'Inhalt von der Platte neu laden',
previewOnlyNotice: 'Datei zu groß ({size}) – nur seitenweise Vorschau; bis {limit} bearbeitbar',
+ previewLongLineNotice: 'Datei enthält eine sehr lange Zeile ({size}) – nur seitenweise Vorschau',
largeFileEmpty: '(leere Datei)',
pagedLineRange: 'Zeilen {from}–{to}',
loadAll: 'Alle laden',
diff --git a/src/client/locales-fr.ts b/src/client/locales-fr.ts
index 99f087fe..fad69f51 100644
--- a/src/client/locales-fr.ts
+++ b/src/client/locales-fr.ts
@@ -170,6 +170,7 @@ export const fr: Record = {
saveConflict: 'Le fichier a été modifié sur le disque par une autre source. Enregistrement interrompu ; vos modifications restent dans l\'éditeur.',
saveConflictReload: 'Recharger depuis le disque',
previewOnlyNotice: 'Fichier trop volumineux ({size}) — aperçu paginé uniquement ; modifiable jusqu’à {limit}',
+ previewLongLineNotice: 'Le fichier contient une ligne très longue ({size}) — aperçu paginé uniquement',
largeFileEmpty: '(fichier vide)',
pagedLineRange: 'Lignes {from}–{to}',
loadAll: 'Tout charger',
diff --git a/src/client/locales-hi.ts b/src/client/locales-hi.ts
index 30511352..f82c1e6d 100644
--- a/src/client/locales-hi.ts
+++ b/src/client/locales-hi.ts
@@ -177,6 +177,7 @@ export const hi: Record = {
saveConflict: 'फ़ाइल डिस्क पर किसी अन्य स्रोत से बदल दी गई है। सहेजना रोक दिया गया; आपके संपादन एडिटर में बने हुए हैं।',
saveConflictReload: 'डिस्क से फिर लोड करें',
previewOnlyNotice: 'फ़ाइल बहुत बड़ी है ({size}) — केवल पेजित पूर्वावलोकन; {limit} तक संपादन संभव',
+ previewLongLineNotice: 'फ़ाइल में एक बहुत लंबी पंक्ति है ({size}) — केवल पेजित पूर्वावलोकन',
largeFileEmpty: '(खाली फ़ाइल)',
pagedLineRange: 'पंक्तियाँ {from}–{to}',
loadAll: 'सभी लोड करें',
diff --git a/src/client/locales-id.ts b/src/client/locales-id.ts
index a192e53f..aaec0cde 100644
--- a/src/client/locales-id.ts
+++ b/src/client/locales-id.ts
@@ -175,6 +175,7 @@ export const id: Record = {
saveConflict: 'File diubah di disk oleh sumber lain. Penyimpanan dihentikan; edit Anda tetap ada di editor.',
saveConflictReload: 'Muat ulang dari disk',
previewOnlyNotice: 'Berkas terlalu besar ({size}) — hanya pratinjau berhalaman; dapat diedit hingga {limit}',
+ previewLongLineNotice: 'Berkas memiliki baris yang sangat panjang ({size}) — hanya pratinjau berhalaman',
largeFileEmpty: '(berkas kosong)',
pagedLineRange: 'Baris {from}–{to}',
loadAll: 'Muat semua',
diff --git a/src/client/locales-it.ts b/src/client/locales-it.ts
index 136dc19d..65bef816 100644
--- a/src/client/locales-it.ts
+++ b/src/client/locales-it.ts
@@ -168,6 +168,7 @@ export const it: Record = {
saveConflict: 'Il file è stato modificato su disco da un\'altra origine. Salvataggio annullato; le modifiche restano nell\'editor.',
saveConflictReload: 'Ricarica dal disco',
previewOnlyNotice: 'File troppo grande ({size}) — solo anteprima paginata; modificabile fino a {limit}',
+ previewLongLineNotice: 'Il file contiene una riga molto lunga ({size}) — solo anteprima paginata',
largeFileEmpty: '(file vuoto)',
pagedLineRange: 'Righe {from}–{to}',
loadAll: 'Carica tutto',
diff --git a/src/client/locales-ja.ts b/src/client/locales-ja.ts
index ab6aee4b..005efda6 100644
--- a/src/client/locales-ja.ts
+++ b/src/client/locales-ja.ts
@@ -177,6 +177,7 @@ export const ja: Record = {
saveConflict: 'ファイルはディスク上で他によって変更されています。保存を中止しました。編集内容はそのまま残っています。',
saveConflictReload: 'ディスクの内容を再読み込み',
previewOnlyNotice: 'ファイルが大きすぎます({size})— ページ分割プレビューのみ、{limit} 以内は編集可能',
+ previewLongLineNotice: 'ファイルに非常に長い行があります({size}) — ページ分割プレビューのみ',
largeFileEmpty: '(空のファイル)',
pagedLineRange: '{from}–{to} 行',
loadAll: 'すべて読み込む',
diff --git a/src/client/locales-ko.ts b/src/client/locales-ko.ts
index 0614ad80..27f78a61 100644
--- a/src/client/locales-ko.ts
+++ b/src/client/locales-ko.ts
@@ -169,6 +169,7 @@ export const ko: Record = {
saveConflict: '파일이 디스크에서 다른 곳에 의해 변경되었습니다. 저장이 중단되었고 편집 내용은 그대로 남아 있습니다.',
saveConflictReload: '디스크에서 다시 불러오기',
previewOnlyNotice: '파일이 너무 큽니다({size}) — 페이지 단위 미리보기만 제공되며 {limit} 이내는 편집할 수 있습니다',
+ previewLongLineNotice: '파일에 매우 긴 줄이 있습니다({size}) — 페이지 단위 미리보기만 제공됩니다',
largeFileEmpty: '(빈 파일)',
pagedLineRange: '{from}–{to}번째 줄',
loadAll: '모두 불러오기',
diff --git a/src/client/locales-nl.ts b/src/client/locales-nl.ts
index f154b937..6861821c 100644
--- a/src/client/locales-nl.ts
+++ b/src/client/locales-nl.ts
@@ -175,6 +175,7 @@ export const nl: Record = {
saveConflict: 'Het bestand is op schijf door iets anders gewijzigd. Opslaan afgebroken; je wijzigingen blijven in de editor.',
saveConflictReload: 'Opnieuw laden vanaf schijf',
previewOnlyNotice: 'Bestand te groot ({size}) — alleen gepagineerd voorbeeld; bewerkbaar tot {limit}',
+ previewLongLineNotice: 'Bestand bevat een zeer lange regel ({size}) — alleen gepagineerd voorbeeld',
largeFileEmpty: '(leeg bestand)',
pagedLineRange: 'Regels {from}–{to}',
loadAll: 'Alles laden',
diff --git a/src/client/locales-pl.ts b/src/client/locales-pl.ts
index 4e6f4381..e67e54e5 100644
--- a/src/client/locales-pl.ts
+++ b/src/client/locales-pl.ts
@@ -179,6 +179,7 @@ export const pl: Record = {
saveConflict: 'Plik został zmieniony na dysku przez inne źródło. Zapis przerwany; zmiany pozostają w edytorze.',
saveConflictReload: 'Wczytaj ponownie z dysku',
previewOnlyNotice: 'Plik jest zbyt duży ({size}) — tylko podgląd stronicowany; edycja do {limit}',
+ previewLongLineNotice: 'Plik zawiera bardzo długi wiersz ({size}) — tylko podgląd stronicowany',
largeFileEmpty: '(pusty plik)',
pagedLineRange: 'Wiersze {from}–{to}',
loadAll: 'Wczytaj wszystko',
diff --git a/src/client/locales-pt.ts b/src/client/locales-pt.ts
index 28985248..a9ba278e 100644
--- a/src/client/locales-pt.ts
+++ b/src/client/locales-pt.ts
@@ -160,6 +160,7 @@ export const pt: Record = {
saveConflict: 'O arquivo foi alterado no disco por outra origem. Salvamento cancelado; suas edições permanecem no editor.',
saveConflictReload: 'Recarregar do disco',
previewOnlyNotice: 'Arquivo muito grande ({size}) — apenas pré-visualização paginada; editável até {limit}',
+ previewLongLineNotice: 'O arquivo contém uma linha muito longa ({size}) — apenas pré-visualização paginada',
largeFileEmpty: '(arquivo vazio)',
pagedLineRange: 'Linhas {from}–{to}',
loadAll: 'Carregar tudo',
diff --git a/src/client/locales-ru.ts b/src/client/locales-ru.ts
index 10954f3b..d03c7d66 100644
--- a/src/client/locales-ru.ts
+++ b/src/client/locales-ru.ts
@@ -173,6 +173,7 @@ export const ru: Record = {
saveConflict: 'Файл был изменён на диске другим источником. Сохранение прервано; ваши правки остались в редакторе.',
saveConflictReload: 'Перезагрузить с диска',
previewOnlyNotice: 'Файл слишком большой ({size}) — доступен только постраничный просмотр; редактирование до {limit}',
+ previewLongLineNotice: 'В файле есть очень длинная строка ({size}) — доступен только постраничный просмотр',
largeFileEmpty: '(пустой файл)',
pagedLineRange: 'Строки {from}–{to}',
loadAll: 'Загрузить всё',
diff --git a/src/client/locales-sv.ts b/src/client/locales-sv.ts
index c2078c14..2a57296f 100644
--- a/src/client/locales-sv.ts
+++ b/src/client/locales-sv.ts
@@ -160,6 +160,7 @@ export const sv: Record = {
saveConflict: 'Filen ändrades på disken av någon annan. Sparandet avbröts; dina ändringar finns kvar i redigeraren.',
saveConflictReload: 'Ladda om från disken',
previewOnlyNotice: 'Filen är för stor ({size}) — endast sidindelad förhandsvisning; redigerbar upp till {limit}',
+ previewLongLineNotice: 'Filen innehåller en mycket lång rad ({size}) — endast sidindelad förhandsvisning',
largeFileEmpty: '(tom fil)',
pagedLineRange: 'Rader {from}–{to}',
loadAll: 'Ladda allt',
diff --git a/src/client/locales-th.ts b/src/client/locales-th.ts
index 940423ed..50a27c58 100644
--- a/src/client/locales-th.ts
+++ b/src/client/locales-th.ts
@@ -177,6 +177,7 @@ export const th: Record = {
saveConflict: 'ไฟล์ถูกแก้ไขบนดิสก์จากแหล่งอื่น การบันทึกถูกยกเลิก การแก้ไขของคุณยังอยู่ในเอดิเตอร์',
saveConflictReload: 'โหลดใหม่จากดิสก์',
previewOnlyNotice: 'ไฟล์ใหญ่เกินไป ({size}) — แสดงตัวอย่างแบบแบ่งหน้าเท่านั้น แก้ไขได้ไม่เกิน {limit}',
+ previewLongLineNotice: 'ไฟล์มีบรรทัดที่ยาวมาก ({size}) — แสดงตัวอย่างแบบแบ่งหน้าเท่านั้น',
largeFileEmpty: '(ไฟล์ว่าง)',
pagedLineRange: 'บรรทัด {from}–{to}',
loadAll: 'โหลดทั้งหมด',
diff --git a/src/client/locales-tr.ts b/src/client/locales-tr.ts
index 816f3226..ddbdf649 100644
--- a/src/client/locales-tr.ts
+++ b/src/client/locales-tr.ts
@@ -177,6 +177,7 @@ export const tr: Record = {
saveConflict: 'Dosya diskte başka bir kaynak tarafından değiştirildi. Kaydetme durduruldu; düzenlemeleriniz düzenleyicide kaldı.',
saveConflictReload: 'Diskten yeniden yükle',
previewOnlyNotice: 'Dosya çok büyük ({size}) — yalnızca sayfalı önizleme; {limit} değerine kadar düzenlenebilir',
+ previewLongLineNotice: 'Dosyada çok uzun bir satır var ({size}) — yalnızca sayfalı önizleme',
largeFileEmpty: '(boş dosya)',
pagedLineRange: 'Satırlar {from}–{to}',
loadAll: 'Tümünü yükle',
diff --git a/src/client/locales-vi.ts b/src/client/locales-vi.ts
index 5e19f055..6b47ebf6 100644
--- a/src/client/locales-vi.ts
+++ b/src/client/locales-vi.ts
@@ -177,6 +177,7 @@ export const vi: Record = {
saveConflict: 'Tệp đã bị nguồn khác sửa trên đĩa. Đã hủy lưu; chỉnh sửa của bạn vẫn còn trong trình soạn thảo.',
saveConflictReload: 'Tải lại từ đĩa',
previewOnlyNotice: 'Tệp quá lớn ({size}) — chỉ xem trước theo trang; có thể chỉnh sửa trong {limit}',
+ previewLongLineNotice: 'Tệp có một dòng rất dài ({size}) — chỉ xem trước theo trang',
largeFileEmpty: '(tệp trống)',
pagedLineRange: 'Dòng {from}–{to}',
loadAll: 'Tải tất cả',
diff --git a/src/client/locales-zh-HK.ts b/src/client/locales-zh-HK.ts
index db30074e..f275fbdc 100644
--- a/src/client/locales-zh-HK.ts
+++ b/src/client/locales-zh-HK.ts
@@ -192,6 +192,7 @@ export const zhHK: Record = {
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
previewOnlyNotice: '檔案過大({size}),僅提供分頁預覽;{limit} 以內可編輯',
+ previewLongLineNotice: '檔案含超長單行({size}),僅提供分頁預覽',
largeFileEmpty: '(空檔案)',
pagedLineRange: '第 {from}–{to} 行',
loadAll: '載入全部',
diff --git a/src/client/locales-zh-MO.ts b/src/client/locales-zh-MO.ts
index 108bc6b7..05ee7937 100644
--- a/src/client/locales-zh-MO.ts
+++ b/src/client/locales-zh-MO.ts
@@ -192,6 +192,7 @@ export const zhMO: Record = {
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
previewOnlyNotice: '檔案過大({size}),僅提供分頁預覽;{limit} 以內可編輯',
+ previewLongLineNotice: '檔案含超長單行({size}),僅提供分頁預覽',
largeFileEmpty: '(空檔案)',
pagedLineRange: '第 {from}–{to} 行',
loadAll: '載入全部',
diff --git a/src/client/locales-zh-TW.ts b/src/client/locales-zh-TW.ts
index ed53c08f..24623640 100644
--- a/src/client/locales-zh-TW.ts
+++ b/src/client/locales-zh-TW.ts
@@ -192,6 +192,7 @@ export const zhTW: Record = {
saveConflict: '檔案已在磁碟上被其他來源修改。儲存已中止,你的編輯仍在編輯器中。',
saveConflictReload: '重新載入磁碟內容',
previewOnlyNotice: '檔案過大({size}),僅提供分頁預覽;{limit} 以內可編輯',
+ previewLongLineNotice: '檔案含超長單行({size}),僅提供分頁預覽',
largeFileEmpty: '(空檔案)',
pagedLineRange: '第 {from}–{to} 行',
loadAll: '載入全部',
diff --git a/src/client/locales.ts b/src/client/locales.ts
index 8abc82ff..ad6a4cc6 100644
--- a/src/client/locales.ts
+++ b/src/client/locales.ts
@@ -188,6 +188,7 @@ export const zh = {
saveConflict: '文件已在磁盘上被其他来源修改。保存已中止,你的修改仍在编辑器中。',
saveConflictReload: '重新载入磁盘内容',
previewOnlyNotice: '文件过大({size}),仅提供分页预览;{limit} 以内可编辑',
+ previewLongLineNotice: '文件含超长单行({size}),仅提供分页预览',
largeFileEmpty: '(空文件)',
pagedLineRange: '第 {from}–{to} 行',
loadAll: '加载全部',
@@ -911,6 +912,7 @@ export const en: Record = {
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',
previewOnlyNotice: 'File is too large ({size}) — paged preview only; editable up to {limit}',
+ previewLongLineNotice: 'File has a very long line ({size}) — paged preview only',
largeFileEmpty: '(empty file)',
pagedLineRange: 'Lines {from}–{to}',
loadAll: 'Load all',
diff --git a/src/client/service.ts b/src/client/service.ts
index a0974dc5..2d9edcc5 100644
--- a/src/client/service.ts
+++ b/src/client/service.ts
@@ -31,6 +31,7 @@ import { hostRouteUrl as resolveHostRoute } from './host-route-url.ts'
import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx'
import type { SessionScope } from './api.ts'
import type { SidebarPrefs } from '../prefs-shared.ts'
+import type { EditLimitReason } from '../editor-limits.ts'
import { bindSidechatSurfaces, type SidechatSurfaceAdapter } from './sidechat-surface.ts'
import { armLineEnd } from './line-target.ts'
export type { SidechatSurface, SidechatSurfaceAdapter } from './sidechat-surface.ts'
@@ -358,11 +359,13 @@ export interface FileViewerProps {
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.
+ * is above the editable threshold, or because one of its lines is too long
+ * for CodeMirror's per-line virtualization (#1165). 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 —
+ * or this line — makes impossible. `reason` carries which limit was hit.
*/
- largeFile?: { size: number }
+ largeFile?: { size: number; reason?: EditLimitReason }
/** 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. */
diff --git a/src/editor-limits.ts b/src/editor-limits.ts
index 892608ee..e7413c4f 100644
--- a/src/editor-limits.ts
+++ b/src/editor-limits.ts
@@ -26,6 +26,68 @@
*/
export const MAX_EDITABLE_BYTES = 5 * 1024 * 1024
+/**
+ * Why a read refused to hand a document to the editor at all.
+ *
+ * - `size` — the file is above {@link MAX_EDITABLE_BYTES};
+ * - `line` — the document's head contains one line at or above
+ * {@link MAX_EDITABLE_LINE_CHARS} (a minified single-line file, #1165).
+ *
+ * The client shows a different notice per reason, so "too large" and "one line
+ * too long" do not have to pretend to be the same fact.
+ */
+export type EditLimitReason = 'size' | 'line'
+
+/**
+ * Longest single line the editor will accept into a CodeMirror document.
+ *
+ * CodeMirror virtualizes by LINE: a document whose one line is a few hundred
+ * KB is parsed, tokenized (syntax highlighting) and laid out in a single frame,
+ * and the renderer hangs — the only recovery is restarting the process (#1165:
+ * a 327 KB minified HTML file, i.e. far below {@link MAX_EDITABLE_BYTES}).
+ * The diff renderer already bounds its own rows at 20 K chars
+ * (`MAX_RENDERED_LINE_CHARS` in `src/client/diff/DiffRows.tsx`); this is the
+ * editor-side twin of that line.
+ */
+export const MAX_EDITABLE_LINE_CHARS = 20_000
+
+/**
+ * How much of a document's head {@link hasOverlongLine} inspects.
+ *
+ * The probe has to stay cheap, and the files it guards against are single-line
+ * artifacts (minified HTML / JS / JSON) whose long line STARTS at byte zero, so
+ * the head is where the evidence is. A long line that only appears past this
+ * window is not detected — a deliberate bound, not an oversight.
+ */
+export const LINE_PROBE_CHARS = 64 * 1024
+
+/**
+ * Whether a document must stay out of the edit buffer because one of its lines
+ * is too long for CodeMirror.
+ *
+ * Only the first {@link LINE_PROBE_CHARS} characters are examined (see the
+ * constant). A line cut off by that window counts by the part inside it.
+ * `\r\n` counts as one separator; a lone `\r` is not an EOL for this editor
+ * either (see `text-encoding.ts`), so it is treated as part of the line.
+ *
+ * @param text - the decoded document (the host calls this on the bytes it is
+ * about to hand the client, never on the client itself).
+ * @returns true when some line inside the probe window reaches
+ * {@link MAX_EDITABLE_LINE_CHARS} characters.
+ */
+export function hasOverlongLine(text: string): boolean {
+ const end = Math.min(text.length, LINE_PROBE_CHARS)
+ let start = 0
+ while (start < end) {
+ const newline = text.indexOf('\n', start)
+ const stop = newline === -1 || newline > end ? end : newline
+ if (stop - start >= MAX_EDITABLE_LINE_CHARS) return true
+ if (newline === -1 || newline >= end) return false
+ start = newline + 1
+ }
+ return false
+}
+
/**
* 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
diff --git a/src/index.ts b/src/index.ts
index 5f8c5648..c7701dc4 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -72,7 +72,7 @@ import {
import { FS_TREES_MAX_PATHS } from './fs-batch.ts'
import { activeWorktreeRootOf } from './active-worktree.ts'
import { decodeTextAs, decodeTextBytes, isWideEncoding, lastLineBreakEnd, type TextEncoding } from './text-encoding.ts'
-import { MAX_EDITABLE_BYTES, PAGE_BYTES, WRITE_BODY_GUARD_BYTES } from './editor-limits.ts'
+import { hasOverlongLine, MAX_EDITABLE_BYTES, PAGE_BYTES, WRITE_BODY_GUARD_BYTES, type EditLimitReason } from './editor-limits.ts'
export { Config }
export type { SidebarConfig, ResolvedSidebarConfig }
@@ -505,7 +505,7 @@ async function statFileForRoute(path: string): Promise {
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 }
+ | { kind: 'too-large'; size: number; mtimeMs: number; head: string; reason: EditLimitReason }
/**
* Read one file for the editor host.
@@ -515,10 +515,17 @@ export type SidebarReadResult =
*
* - 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.
+ * - above it: `too-large` (reason `size`), carrying only the 4 KiB head;
+ * - at or below it, but with a line at or above `MAX_EDITABLE_LINE_CHARS` in
+ * the document head: also `too-large`, with reason `line` (#1165). CodeMirror
+ * virtualizes by line, so one line of a few hundred KB is laid out in one
+ * frame and hangs the renderer — the explicit probe is what keeps such a
+ * document out of the edit buffer even though it passes the byte limit.
+ *
+ * Every `too-large` carries 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);
@@ -564,6 +571,23 @@ async function readText(path: string): Promise {
size,
mtimeMs: info.mtimeMs,
head: slice.toString('base64'),
+ reason: 'size',
+ }
+ }
+ // The byte limit is not the only way a document is too much for the
+ // editor: one line of a few hundred KB hangs CodeMirror's per-line
+ // virtualization (#1165). The document is already decoded here, so the
+ // probe runs on the host — the client never scans the bytes, and no
+ // CodeMirror state is ever built for the file.
+ if (hasOverlongLine(decoded.content)) {
+ return {
+ kind: 'too-large',
+ size,
+ mtimeMs: info.mtimeMs,
+ // Sniff bytes only, never the document: the same `too-large`
+ // contract as the size branch above.
+ head: slice.subarray(0, Math.min(slice.length, READ_HEAD_LIMIT)).toString('base64'),
+ reason: 'line',
}
}
return { kind: 'text', content: decoded.content, size, mtimeMs: info.mtimeMs }
diff --git a/tests/editor-host.spec.tsx b/tests/editor-host.spec.tsx
index 9ff2f758..8fa132d6 100644
--- a/tests/editor-host.spec.tsx
+++ b/tests/editor-host.spec.tsx
@@ -819,7 +819,7 @@ describe('EditorHost (files window)', () => {
return createElement('div', null, 'paged-preview')
}
service.registerFileViewer({ id: 'test:big', exts: ['big'], fetchStrategy: 'fsRead', component: FakeViewer })
- fsRead.mockResolvedValueOnce({ kind: 'too-large', size, head: 'e30=' })
+ fsRead.mockResolvedValueOnce({ kind: 'too-large', size, head: 'e30=', reason: 'size' })
service.openTab({ type: 'editor', title: 'big.big', path: '/tmp/big.big', id: 'editor:/tmp/big.big' })
const fileTab = (): SidebarTab =>
allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs)
@@ -832,7 +832,7 @@ describe('EditorHost (files window)', () => {
})
expect(container.textContent).toContain('paged-preview')
expect(fsRead).toHaveBeenCalledWith(expect.anything(), '/tmp/big.big')
- expect(seen?.largeFile).toEqual({ size })
+ expect(seen?.largeFile).toEqual({ size, reason: 'size' })
expect(seen?.size).toBe(size)
expect(seen?.content, 'the document is not handed over').toBeUndefined()
} finally {
diff --git a/tests/editor-large-file.spec.tsx b/tests/editor-large-file.spec.tsx
index 1e0c9fb2..0f8de202 100644
--- a/tests/editor-large-file.spec.tsx
+++ b/tests/editor-large-file.spec.tsx
@@ -63,6 +63,8 @@ const SCOPE = { sessionId: 's1', cwd: '/p' }
const PATH = '/p/big.txt'
/** Above MAX_EDITABLE_BYTES (5 MiB): the host answers `too-large`. */
const SIZE = 6 * 1024 * 1024
+/** A long-line refusal is far BELOW the byte limit (issue #1165). */
+const LONG_LINE_SIZE = 327 * 1024
const PAGE = 'alpha\nbeta\n'
function viewerProps(overrides: Partial = {}): FileViewerProps {
@@ -128,6 +130,38 @@ describe('TextEditor over-limit preview', () => {
}
})
+ it('explains a long-line refusal even though the file is under the byte limit (#1165)', async () => {
+ attachLocale(new FakeLocale())
+ readPage.mockResolvedValue({
+ kind: 'text', text: 'x'.repeat(4096), offset: 0, nextOffset: LONG_LINE_SIZE, eof: true, size: LONG_LINE_SIZE, encoding: 'utf8',
+ })
+ const { container, unmount } = renderRoot(
+ createElement(TextEditor, viewerProps({
+ size: LONG_LINE_SIZE,
+ largeFile: { size: LONG_LINE_SIZE, reason: 'line' },
+ })),
+ )
+ try {
+ await flush()
+ // The notice names the actual reason: "the file is too large" would be
+ // a lie at 327 KB, and showing NO notice was the #1165 bug (the paged
+ // preview appeared silently).
+ expect(container.textContent).toContain(
+ t('previewLongLineNotice', { size: formatByteSize(LONG_LINE_SIZE) }),
+ )
+ expect(container.textContent).not.toContain(
+ t('previewOnlyNotice', { size: formatByteSize(LONG_LINE_SIZE), limit: MAX_EDITABLE_LABEL }),
+ )
+ // Same degraded path as the byte-limit refusal: no CodeMirror, no save.
+ expect(container.querySelector('.cm-editor')).toBeNull()
+ expect(container.querySelector('button[aria-label="Save"]')).toBeNull()
+ expect(container.querySelector('a[download]')).not.toBeNull()
+ expect(readPage).toHaveBeenCalledWith(expect.anything(), PATH, 0)
+ } finally {
+ unmount()
+ }
+ })
+
it('keeps the CodeMirror editor and its save button for an editable load', async () => {
attachLocale(new FakeLocale())
// (d) The contrast that gives the assertions above their meaning: the same
diff --git a/tests/editor-limits.spec.ts b/tests/editor-limits.spec.ts
new file mode 100644
index 00000000..2971a801
--- /dev/null
+++ b/tests/editor-limits.spec.ts
@@ -0,0 +1,52 @@
+/**
+ * The long-line guard (#1165): a document that CodeMirror cannot hold — one
+ * line of hundreds of KB — must be classified non-editable BEFORE any edit
+ * buffer is built, even when its byte size is far below
+ * `MAX_EDITABLE_BYTES`. The host calls this predicate on the already-decoded
+ * read (src/index.ts) and answers `too-large` with reason `line`, so the
+ * client never scans the document and never mounts CodeMirror for it.
+ *
+ * The probe is deliberately BOUNDED to the document head: the reported files
+ * are minified single-line artifacts whose long line starts at byte zero, and
+ * the host must not walk a whole 5 MB document to answer.
+ */
+import { describe, expect, it } from 'vitest'
+import { hasOverlongLine, LINE_PROBE_CHARS, MAX_EDITABLE_LINE_CHARS } from '../src/editor-limits.ts'
+
+describe('hasOverlongLine', () => {
+ it('classifies a document whose single line exceeds the limit as non-editable (#1165)', () => {
+ // The reported shape: a 327 KB minified HTML file, one line, no newline.
+ expect(hasOverlongLine('x'.repeat(327 * 1024))).toBe(true)
+ })
+
+ it('accepts a normal multi-line document', () => {
+ const text = 'const value = 1\n'.repeat(2_000)
+ // Long by BYTES, ordinary by lines: the guard must not flag it.
+ expect(text.length).toBeGreaterThan(MAX_EDITABLE_LINE_CHARS)
+ expect(hasOverlongLine(text)).toBe(false)
+ })
+
+ it('measures the longest line, not the document', () => {
+ const justUnder = 'a\n' + 'x'.repeat(MAX_EDITABLE_LINE_CHARS - 1) + '\n'
+ expect(hasOverlongLine(justUnder)).toBe(false)
+ const atLimit = 'a\n' + 'x'.repeat(MAX_EDITABLE_LINE_CHARS) + '\n'
+ expect(hasOverlongLine(atLimit)).toBe(true)
+ })
+
+ it('treats CRLF as one line separator', () => {
+ const text = 'x'.repeat(MAX_EDITABLE_LINE_CHARS + 1) + '\r\nnext\r\n'
+ expect(hasOverlongLine(text)).toBe(true)
+ })
+
+ it('keeps the probe bounded to the document head', () => {
+ // Ordinary short lines fill the probe window, so a later over-limit line
+ // is outside what the host inspects — the documented bound.
+ const head = 'ok\n'.repeat(Math.ceil(LINE_PROBE_CHARS / 3))
+ expect(head.length).toBeGreaterThanOrEqual(LINE_PROBE_CHARS)
+ expect(hasOverlongLine(head + 'x'.repeat(MAX_EDITABLE_LINE_CHARS + 1))).toBe(false)
+ })
+
+ it('treats an empty document as editable', () => {
+ expect(hasOverlongLine('')).toBe(false)
+ })
+})
diff --git a/tests/editor-load.spec.ts b/tests/editor-load.spec.ts
index ca6eceda..e8089271 100644
--- a/tests/editor-load.spec.ts
+++ b/tests/editor-load.spec.ts
@@ -128,6 +128,18 @@ describe('planFsReadOutcome', () => {
expect(action).not.toHaveProperty('content')
})
+ it('a long-line refusal carries its reason into largeFile (#1165)', () => {
+ const v = viewer({ id: 'code' })
+ const size = 327 * 1024
+ const action = planFsReadOutcome(
+ v,
+ { kind: 'too-large', size, head: 'e30=', reason: 'line' },
+ unclaimed,
+ () => '/m',
+ )
+ expect(action).toEqual({ kind: 'render', viewer: v, size, largeFile: { size, reason: 'line' } })
+ })
+
it('too-large whose matched viewer is not an fsRead viewer → binary', () => {
const custom = viewer({ id: 'my:csv', fetchStrategy: 'custom', load: async () => ({}) })
const action = planFsReadOutcome(custom, { kind: 'too-large', size: LARGE, head: 'e30=' }, unclaimed, () => '/m')
diff --git a/tests/smoke.spec.ts b/tests/smoke.spec.ts
index d657e32a..bb75e555 100644
--- a/tests/smoke.spec.ts
+++ b/tests/smoke.spec.ts
@@ -1241,8 +1241,9 @@ describe('session cwd resolution over the API route', () => {
expect(Buffer.byteLength(content, 'utf8')).toBeGreaterThan(5 * 1024 * 1024)
writeFileSync(target, Buffer.from(content, 'utf8'))
const result = await invoke(route, 'fs.read', { sessionId: 'readcap', path: target })
- const value = result.value as { kind?: string; size?: number; content?: string; head?: string } | undefined
+ const value = result.value as { kind?: string; size?: number; content?: string; head?: string; reason?: string } | undefined
expect(value?.kind).toBe('too-large')
+ expect(value?.reason).toBe('size')
expect(value?.size).toBe(Buffer.byteLength(content, 'utf8'))
// No document rides along — that is the point.
expect(value?.content).toBeUndefined()
@@ -1256,6 +1257,30 @@ describe('session cwd resolution over the API route', () => {
}
})
+ it('fs.read refuses a single-line document above the edit-buffer line limit (#1165)', async () => {
+ const root = mkdtempSync(join(tmpdir(), 'dsh-sidebar-fs-longline-'))
+ const workspace = join(root, 'workspace')
+ mkdirSync(workspace)
+ try {
+ const route = mount({ sessions: { get: () => ({ header: { cwd: workspace } }) } })
+ const target = join(workspace, 'minified.html')
+ // The reported shape: one 327 KB line, far below the 5 MiB byte cap.
+ // CodeMirror would lay that single line out in one frame and hang.
+ const content = '' + 'x'.repeat(327 * 1024) + ''
+ writeFileSync(target, content)
+ const result = await invoke(route, 'fs.read', { sessionId: 'longline', path: target })
+ const value = result.value as { kind?: string; size?: number; content?: string; head?: string; reason?: string } | undefined
+ expect(value?.kind).toBe('too-large')
+ expect(value?.reason).toBe('line')
+ expect(value?.content).toBeUndefined()
+ expect(value?.size).toBe(Buffer.byteLength(content, 'utf8'))
+ // Only the sniff head rides the refusal — never the document.
+ expect(Buffer.from(value!.head!, 'base64').length).toBe(4096)
+ } finally {
+ removeTree(root)
+ }
+ })
+
it('serves a home-relative media path (the ~ marker reaches the shared resolver, #713)', async () => {
// A real file under the user's home: the ~ expansion must happen on the
// ROUTE side (resolveTarget), not be pre-joined onto the session cwd.