diff --git a/src/active-worktree.ts b/src/active-worktree.ts index c1120106..a3ecff12 100644 --- a/src/active-worktree.ts +++ b/src/active-worktree.ts @@ -24,7 +24,7 @@ import { stat } from 'node:fs/promises' import { dirname, isAbsolute, join, sep } from 'node:path' import type { Context, SidebarSessionEvent } from './context-types.ts' import { requireAbsolute } from './fs-tree.ts' -import { runGitRaw } from './git.ts' +import { runGit } from './git.ts' import { readPersistedSessionOf } from './session-store.ts' /** How long one computed root is reused before the event log is scanned again. */ @@ -76,7 +76,7 @@ async function gitTopLevelOf(cwd: string): Promise { if (cwd === '' || !isAbsolute(cwd)) return undefined try { if (!(await stat(cwd)).isDirectory()) return undefined - return (await runGitRaw(cwd, ['rev-parse', '--show-toplevel'])).trim() + return (await runGit(cwd, ['rev-parse', '--show-toplevel'])).trim() } catch { return undefined } @@ -168,7 +168,7 @@ async function isLinkedWorktree(top: string): Promise { if (cached !== undefined) return cached let linked = false try { - const out = (await runGitRaw(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/) + const out = (await runGit(top, ['rev-parse', '--absolute-git-dir', '--git-common-dir'])).trim().split(/\r?\n/) const gitDir = out[0] const commonRaw = out[1] ?? '' if (gitDir !== undefined && gitDir !== '' && commonRaw !== '') { diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index ec13e152..cadcaced 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -347,7 +347,7 @@ export function EditorHost(props: { useEffect(() => { if (path === '' || isDir) return setEditorDirty(tab.id, toolbar?.dirty === true, scope.sessionId, path) - return () => { clearEditorDirty(tab.id) } + return () => { clearEditorDirty(tab.id, scope.sessionId) } }, [tab.id, toolbar?.dirty, scope.sessionId, path, isDir]) // The docked panel's drag-resize: pointer capture on the handle itself diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index df3bec2d..eed4a734 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -1796,6 +1796,25 @@ export function FileTree(props: { } }, [data]) + /** + * One level's rows in the caller's chosen order, resolved ONCE per + * level-cache revision and reused by both walkers below: `renderLevel` draws + * them and {@link visibleRows} ranges over them, so re-sorting per render + * would both repeat the comparison and hand the memoized rows a fresh array. + * `sortEntries` copies (the level cache keeps the host's own order and is + * never reordered in place). + */ + const entriesFor = useMemo(() => { + const cache = new Map() + return (dir: string): readonly FsEntry[] => { + const cached = cache.get(dir) + if (cached !== undefined) return cached + const sorted = sortEntries(data[dir]?.entries ?? [], sort) + cache.set(dir, sorted) + return sorted + } + }, [data, sort]) + // The Shift range walks the rows the user can actually see: the level's // rows in the SAME order `renderLevel` draws them (the sort choice), then // depth-first, expanded state decides. Recomputed with the level cache, @@ -1805,7 +1824,7 @@ export function FileTree(props: { const walk = (dir: string): void => { const level = data[dir] if (level?.entries === undefined) return - for (const entry of sortEntries(level.entries, sort)) { + for (const entry of entriesFor(dir)) { // A folded row IS one row: its identity is the chain head (the level // entry the walk is on), and it descends into the chain TAIL — the // same shape `renderLevel` draws, so a Shift range covers what the @@ -1818,7 +1837,7 @@ export function FileTree(props: { } if (root !== undefined) walk(root) return rows - }, [chainFor, data, expandedSet, root, sort]) + }, [chainFor, data, entriesFor, expandedSet, root]) visibleRowsRef.current = visibleRows /** @@ -1866,13 +1885,15 @@ export function FileTree(props: { if (isLikelyImeKey(event)) return if (event.key === 'Enter') { event.preventDefault() - commitRename(entry.path, renaming?.value ?? '') + // A folded row renders at the chain HEAD while its menu addressed + // the TAIL: commit the path the editor was opened for. + commitRename(renaming?.path ?? entry.path, renaming?.value ?? '') } else if (event.key === 'Escape') { event.preventDefault() setRenaming(null) } }} - onBlur={() => { commitRename(entry.path, renaming?.value ?? '') }} + onBlur={() => { commitRename(renaming?.path ?? entry.path, renaming?.value ?? '') }} /> ) @@ -1982,9 +2003,8 @@ export function FileTree(props: { ) } - // The ORDER is the caller's choice (the header's sort control); the level - // cache keeps the host's own order and is never reordered in place. - const entries = sortEntries(level.entries ?? [], sort) + // The ORDER is the caller's choice (the header's sort control). + const entries = entriesFor(dir) return ( <> {head} diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index d0abe8a2..84480df1 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -587,7 +587,8 @@ export function SideChatView(props: { * nothing else is left. */ const newestThreadId = useCallback((candidates: readonly SideThreadRow[]): string | undefined => { const catalog = list.projectionsBySession?.[scope.sessionId]?.values.subagentCatalog - const rank = (id: string): number => catalog?.find(entry => entry.id === id)?.createdAt ?? 0 + const createdAt = new Map((catalog ?? []).map(entry => [entry.id, entry.createdAt])) + const rank = (id: string): number => createdAt.get(id) ?? 0 const real = candidates.filter(row => row.title !== SIDE_NEW_THREAD_TITLE) const pool = real.length > 0 ? real : candidates if (pool.length === 0) return undefined diff --git a/src/client/Sidebar.tsx b/src/client/Sidebar.tsx index de413f61..8beba9f8 100644 --- a/src/client/Sidebar.tsx +++ b/src/client/Sidebar.tsx @@ -488,7 +488,7 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { // The confirmation is the SAME guard the refresh button uses, so every // close path (tab X, middle click, tab context menu, the tree's // close-on-rename/delete) funnels through here and warns exactly once. - if (!confirmDiscardDraft(tabId, t('closeUnsavedConfirm'))) return + if (!confirmDiscardDraft(tabId, t('closeUnsavedConfirm'), sessionId)) return // Route through the service: the tab-bar close is the canonical close // path (finds the pane itself, fires descriptor.onClose); the session // scope (with its cwd) rides to the callback. diff --git a/src/client/TerminalView.tsx b/src/client/TerminalView.tsx index 10d6e666..4d0bafd8 100644 --- a/src/client/TerminalView.tsx +++ b/src/client/TerminalView.tsx @@ -50,7 +50,7 @@ import type { SidebarTab } from './state.ts' import { t } from './locales.ts' import { isDarkScheme, subscribeColorScheme } from './theme.ts' import { - bottomTerminalContentId, bottomTerminalKey, nextTerminalMeta, terminalRunOf, webTerminals, + bottomTerminalContentId, nextTerminalMeta, terminalRunOf, webTerminals, type HostTerminalEnvironment, type HostTerminalView, type HostTerminalViewState, } from './terminal-client.ts' import css from './terminal.module.css' @@ -74,12 +74,13 @@ export function TerminalBottomView({ ctx, scope, tab, visible }: TerminalBottomP // it keeps the tray row disabled and renders the explanation below. const service = useMemo(() => webTerminals(ctx), [ctx]) const run = terminalRunOf(tab) + const contentId = bottomTerminalContentId(run) // `view()` allocates the terminal eagerly and memoizes one model per // (session, key) on the host side, so this memo must be the ONLY creation // path: a repeat `view()` for the same key is free, a new key is a new PTY. const model = useMemo( - () => service?.view(sessionId, bottomTerminalKey(run), bottomTerminalContentId(run)), - [service, sessionId, run], + () => service?.view(sessionId, contentId, contentId), + [service, sessionId, contentId], ) const state = useSyncExternalStore( useMemo(() => (callback: () => void) => model?.state.subscribe(callback) ?? (() => {}), [model]), diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 2566cdb9..97be92b0 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -19,7 +19,7 @@ * drop over the file window uploads here and never reaches DSH's chat * intake. */ -import { useEffect, useRef, useState, type InputHTMLAttributes } from 'react' +import { useEffect, useMemo, useRef, useState, type InputHTMLAttributes } from 'react' import clsx from 'clsx' import { IconChevronsUpDownOutlineRegular, IconFolderOpenRegular, IconRefreshOutlineRegular, Menu } from '@deepseek-ai/dsh-client-ui-primitives' import { api } from './api.ts' @@ -220,7 +220,7 @@ export function TreePanel(props: { const busy = upload !== null /** Directory hits (the host reports them separately): a click navigates the * tree for those rows instead of opening them as files. */ - const dirHits = new Set(results?.dirs) + const dirHits = useMemo(() => new Set(results?.dirs), [results]) /** * Jump to a DIRECTORY hit in the tree. Results include directories (they diff --git a/src/client/changes/DiffPane.tsx b/src/client/changes/DiffPane.tsx index 886bb67d..34d1a1b7 100644 --- a/src/client/changes/DiffPane.tsx +++ b/src/client/changes/DiffPane.tsx @@ -437,7 +437,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, ) : target.kind === 'op' && mdOp && reading && readingText !== '' - ? + ? : target.kind === 'op' && op !== null && op.isError ? (
diff --git a/src/client/conversation-draft.ts b/src/client/conversation-draft.ts index d0b41581..f3f815e6 100644 --- a/src/client/conversation-draft.ts +++ b/src/client/conversation-draft.ts @@ -33,7 +33,7 @@ * position (A|B + C + D → ACD|B). */ import type { Context, SidebarConversation } from '../context-types.ts' -import { workspaceRelativePath } from './paths.ts' +import { baseName, workspaceRelativePath } from './paths.ts' /** A resolved composer caret/selection in draft coordinates. */ export interface DraftCaret { @@ -222,9 +222,7 @@ export function mentionFor( if (/[\u0000-\u001f\u007f-\u009f"]/u.test(path)) return undefined const target = kind === 'folder' ? `${path}/` : path const mention = /\s/u.test(target) ? `@"${target}"` : `@${target}` - const at = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\')) - const label = at === -1 ? path : path.slice(at + 1) - return { mention, label } + return { mention, label: baseName(path) } } /** diff --git a/src/client/editor-dirty.ts b/src/client/editor-dirty.ts index d8708144..286d7f77 100644 --- a/src/client/editor-dirty.ts +++ b/src/client/editor-dirty.ts @@ -9,16 +9,21 @@ * - the browser unload (refresh / close tab / navigate away) through a * `beforeunload` guard. * - * Module-level and keyed by tab id — the same "one instance per client plugin - * activation" lifetime the store has, since the module only loads with the - * client bundle. An entry is written while a tab is dirty and deleted the - * moment it goes clean (save) or its host unmounts (tab closed, session - * switched), so a stale entry can never keep a guard armed. + * Module-level and keyed by `sessionId::tabId`: a tab id is unique only WITHIN + * one session — the native right column counts its own `tab1`…, and the bottom + * workbench reuses `editor:` for the same file in every session. Keyed by + * the bare tab id, session B's editor mounting over the same id DELETED session + * A's record (its mount reports `dirty === false`), so A's still-live draft + * outlived its guard and a refresh dropped it without a word. The native + * surface accounts the same way (`viewKey`, native/tab-adapter.tsx). + * An entry is written while a tab is dirty and deleted the moment it goes + * clean (save) or its host unmounts (tab closed, in-place path switch), so a + * stale entry can never keep a guard armed. */ -/** One registered draft: the owning session (the guard's scope) and the file. */ +/** One registered draft: the id it was recorded under and the file. */ interface DirtyEntry { - sessionId: string + tabId: string path: string } @@ -27,6 +32,11 @@ const listeners = new Set<() => void>() /** Monotonic change counter: a stable `useSyncExternalStore` snapshot. */ let revision = 0 +/** The map key of one tab: ids only identify a tab inside their session. */ +function keyOf(sessionId: string, tabId: string): string { + return `${sessionId}::${tabId}` +} + /** Notify every subscriber (the `beforeunload` guard). */ function notify(): void { revision += 1 @@ -38,37 +48,49 @@ function notify(): void { * ride along for scoped queries), `false` / `undefined` clears it. */ export function setEditorDirty(tabId: string, dirty: boolean, sessionId: string, path: string): void { - const had = dirtyTabs.has(tabId) + const key = keyOf(sessionId, tabId) if (!dirty) { - if (had) { - dirtyTabs.delete(tabId) - notify() - } + if (dirtyTabs.delete(key)) notify() return } - const previous = dirtyTabs.get(tabId) - if (previous !== undefined && previous.sessionId === sessionId && previous.path === path) return - dirtyTabs.set(tabId, { sessionId, path }) + const previous = dirtyTabs.get(key) + if (previous !== undefined && previous.path === path) return + dirtyTabs.set(key, { tabId, path }) notify() } -/** Drop a tab's entry (its editor host unmounted). Idempotent. */ -export function clearEditorDirty(tabId: string): void { - if (dirtyTabs.delete(tabId)) notify() -} - -/** Whether one tab holds an unsaved draft. */ -export function isEditorDirty(tabId: string): boolean { - return dirtyTabs.has(tabId) -} - -/** How many tabs of one session hold unsaved drafts. */ -export function dirtyCountForSession(sessionId: string): number { - let count = 0 - for (const entry of dirtyTabs.values()) { - if (entry.sessionId === sessionId) count += 1 +/** + * Drop a tab's entry (its editor host unmounted). Idempotent. + * @param sessionId - the owning session; omitted drops the id in EVERY session + * (the shape tests use for cleanup — a caller that knows its session should + * always name it, or it would clear a same-numbered tab elsewhere). + */ +export function clearEditorDirty(tabId: string, sessionId?: string): void { + if (sessionId !== undefined) { + if (dirtyTabs.delete(keyOf(sessionId, tabId))) notify() + return } - return count + let removed = false + for (const [key, entry] of dirtyTabs) { + if (entry.tabId !== tabId) continue + dirtyTabs.delete(key) + removed = true + } + if (removed) notify() +} + +/** + * Whether one tab holds an unsaved draft. + * @param sessionId - the owning session; omitted matches the id in any session + * (the conservative read: a caller that cannot name the session should still + * warn rather than pass a live draft through). + */ +export function isEditorDirty(tabId: string, sessionId?: string): boolean { + if (sessionId !== undefined) return dirtyTabs.has(keyOf(sessionId, tabId)) + for (const entry of dirtyTabs.values()) { + if (entry.tabId === tabId) return true + } + return false } /** How many tabs hold unsaved drafts across every session (the unload guard). */ @@ -90,17 +112,19 @@ export function editorDirtyRevision(): number { /** * Ask before dropping `tabId`'s unsaved draft. Returns true when the caller * may proceed (the tab is clean, the user confirmed, or no `confirm` is - * available — the same fallback the refresh guard uses). On confirm the - * entry is cleared immediately, so a follow-up close in the same tick does - * not double-prompt; the editor host's own cleanup would do it one commit - * later anyway. + * available — letting a tab become unclosable would be worse than skipping one + * prompt). On confirm the entry is cleared immediately, so a follow-up close in + * the same tick does not double-prompt; the editor host's own cleanup would do + * it one commit later anyway. * * Shared by the sidebar's tab close and the file tree's close-on-delete so * both paths warn exactly once, with the same copy. + * @param sessionId - the owning session (see {@link isEditorDirty} for the + * omitted case). */ -export function confirmDiscardDraft(tabId: string, message: string): boolean { - if (!dirtyTabs.has(tabId)) return true +export function confirmDiscardDraft(tabId: string, message: string, sessionId?: string): boolean { + if (!isEditorDirty(tabId, sessionId)) return true const confirmed = typeof window.confirm === 'function' ? window.confirm(message) : true - if (confirmed) clearEditorDirty(tabId) + if (confirmed) clearEditorDirty(tabId, sessionId) return confirmed } diff --git a/src/client/sidebar/dock-fallback.tsx b/src/client/sidebar/dock-fallback.tsx index 415cfa98..8e2ca631 100644 --- a/src/client/sidebar/dock-fallback.tsx +++ b/src/client/sidebar/dock-fallback.tsx @@ -150,7 +150,9 @@ export function DockFallback({ store }: { store: SidebarStore }): ReactNode { const [headerEntry, setHeaderEntry] = useState(headerEntryPresent) useEffect(() => { const onResize = (): void => { - setPos(measure()) + // 坐标没变就不换 state 对象:500ms 的周期重测在版面静止时不该引起重渲染。 + const next = measure() + setPos(prev => (prev.top === next.top && prev.left === next.left ? prev : next)) setHeaderEntry(headerEntryPresent()) } window.addEventListener('resize', onResize) diff --git a/src/client/state.ts b/src/client/state.ts index 43b83af6..22928799 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -983,7 +983,7 @@ export class SidebarStore { markUnread(type: TabType): boolean { const state = this.snapshot.state if (state === undefined || state.unread.includes(type)) return false - this.replaceCurrent(markUnread(state, type)) + this.reduce(current => markUnread(current, type)) return true } @@ -1009,7 +1009,7 @@ export class SidebarStore { if (target === undefined) return false if (target === this.snapshot.sessionId) { if (state === undefined || !state.unread.includes(type)) return false - this.replaceCurrent(clearUnread(state, type)) + this.reduce(current => clearUnread(current, type)) return true } const stored = this.bySession.get(target) @@ -1018,19 +1018,6 @@ export class SidebarStore { return true } - /** - * Commit a state this class already minted (identity-checked by the caller) - * as the current session's state, persisting it like any other change. - */ - private replaceCurrent(state: SidebarState): void { - const sessionId = this.snapshot.sessionId - if (sessionId === undefined) return - this.bySession.set(sessionId, state) - this.snapshot = { sessionId, state, prefs: this.prefs } - this.schedulePersist(sessionId, state) - this.notify() - } - getSnapshot(): SidebarSnapshot { return this.snapshot } diff --git a/src/client/terminal-client.ts b/src/client/terminal-client.ts index 8a52b882..fe606ae3 100644 --- a/src/client/terminal-client.ts +++ b/src/client/terminal-client.ts @@ -171,23 +171,16 @@ const RUN_FIELD = 'terminalRun' * it: the old binding points at a process that is gone — a host restart, or a * terminal closed elsewhere — and reusing it would wedge the tab on * `missingTerminal` forever. + * + * The SAME value is the occurrence key the host memoizes one view by + * (`view(sessionId, key, contentId)`), so a run bump has to move both: the + * namespace is what keeps it from colliding with a host layout tab id (`tab1`). * @param run - the content-identity generation (0 for a tab's first terminal). */ export function bottomTerminalContentId(run: number): string { return run === 0 ? TERMINAL_NS : `${TERMINAL_NS}#${run}` } -/** - * The occurrence key: what the host service memoizes one `TerminalView` by, - * per session. It equals the content identity so both move together when a - * replacement terminal is minted, and it is namespaced so it can never collide - * with a host sidebar occurrence key (those are layout tab ids such as `tab1`). - * @param run - the content-identity generation. - */ -export function bottomTerminalKey(run: number): string { - return bottomTerminalContentId(run) -} - /** The content-identity generation a tab carries (absent/corrupt reads as 0). */ export function terminalRunOf(tab: { meta?: unknown }): number { const meta = tab.meta !== null && typeof tab.meta === 'object' && !Array.isArray(tab.meta) @@ -214,6 +207,6 @@ export function nextTerminalMeta(tab: { meta?: unknown }): Record { */ export async function renameWorkspaceEntry(input: WorkspaceRenameInput): Promise<{ path: string }> { const { cwd, path, name } = input - if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) { - throw new SidebarError('bad-request', 'name must be a single path segment', 400) - } + assertSingleSegmentName(name) const { absolute, realCwd } = resolveEntry(cwd, path) if (await isWorkspaceRoot(absolute, realCwd)) { throw new SidebarError('fs-error', 'cannot rename the workspace root', 400) @@ -334,9 +343,7 @@ export interface WorkspaceMkdirInput { */ export async function mkdirWorkspaceEntry(input: WorkspaceMkdirInput): Promise<{ path: string }> { const { cwd, path, name } = input - if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) { - throw new SidebarError('bad-request', 'name must be a single path segment', 400) - } + assertSingleSegmentName(name) const { absolute } = resolveEntry(cwd, path) const destination = await ensureWorkspaceWritePath(cwd, join(absolute, name)) if (await pathExists(destination)) { @@ -386,8 +393,8 @@ const RESERVED_FILE_NAMES = new Set([ ]) /** - * The NEW FILE name rule: one path segment (the shared rename/mkdir rule) plus - * the two Windows-only refusals — illegal characters and reserved device + * The NEW FILE name rule: one path segment ({@link assertSingleSegmentName}) + * plus the two Windows-only refusals — illegal characters and reserved device * names. Refusing them HERE, as a shape error, is what lets the inline editor * say which rule was broken instead of surfacing a bare `EPERM` from the * filesystem on one platform and nothing at all on the others. @@ -395,9 +402,7 @@ const RESERVED_FILE_NAMES = new Set([ * @throws SidebarError with a wire code of `bad-request` for every refusal. */ function assertCreatableFileName(name: string): void { - if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) { - throw new SidebarError('bad-request', 'name must be a single path segment', 400) - } + assertSingleSegmentName(name) const illegal = firstIllegalNameChar(name) if (illegal !== undefined) { throw new SidebarError('bad-request', `name contains a character that is not allowed in a file name: ${JSON.stringify(illegal)}`, 400) diff --git a/src/fs-tree.ts b/src/fs-tree.ts index bc8356a4..3d238c5f 100644 --- a/src/fs-tree.ts +++ b/src/fs-tree.ts @@ -206,26 +206,37 @@ async function readDirectory(path: string, maxEntries: number, exclude?: Exclude return { path, entries: rows, truncated } } -/** Probe each symlink row's target once (bounded concurrency, order-preserving). */ -async function probeSymlinkTargets(rows: SidebarFsEntry[], concurrency = SYMLINK_PROBE_CONCURRENCY): Promise { +/** + * Visit every row with at most `concurrency` visitors in flight, in row order. + * Both probes below spend one await per row (a network stat, an opendir) on a + * level that can hold thousands of rows, so the bound has to exist — and be + * shared, or the two probes drift into two different ones. + */ +async function forEachRow(rows: readonly SidebarFsEntry[], concurrency: number, visit: (row: SidebarFsEntry) => Promise): Promise { let next = 0 const workers = Array.from({ length: Math.min(concurrency, rows.length) }, async () => { for (;;) { const index = next next += 1 if (index >= rows.length) return - const row = rows[index]! - if (!row.isSymlink) continue - // stat follows the chain; any failure (missing target, ELOOP, permission) - // leaves the row as a broken file-shaped link the editor refuses to read. - const info = await stat(row.path).catch(() => undefined) - row.isDir = info !== undefined ? info.isDirectory() : row.isDir - row.broken = info === undefined + await visit(rows[index]!) } }) await Promise.all(workers) } +/** Probe each symlink row's target once (bounded concurrency, order-preserving). */ +async function probeSymlinkTargets(rows: SidebarFsEntry[], concurrency = SYMLINK_PROBE_CONCURRENCY): Promise { + await forEachRow(rows, concurrency, async (row) => { + if (!row.isSymlink) return + // stat follows the chain; any failure (missing target, ELOOP, permission) + // leaves the row as a broken file-shaped link the editor refuses to read. + const info = await stat(row.path).catch(() => undefined) + row.isDir = info !== undefined ? info.isDirectory() : row.isDir + row.broken = info === undefined + }) +} + /** How many compact probes run in flight during one level listing. */ const COMPACT_PROBE_CONCURRENCY = 32 @@ -240,18 +251,10 @@ const COMPACT_PROBE_CONCURRENCY = 32 * not fold. */ async function probeCompactRows(rows: SidebarFsEntry[], exclude?: ExcludeMatcher, concurrency = COMPACT_PROBE_CONCURRENCY): Promise { - let next = 0 - const workers = Array.from({ length: Math.min(concurrency, rows.length) }, async () => { - for (;;) { - const index = next - next += 1 - if (index >= rows.length) return - const row = rows[index]! - if (!row.isDir || row.broken) continue - if (await hasSingletonChild(row.path, exclude)) row.compact = true - } + await forEachRow(rows, concurrency, async (row) => { + if (!row.isDir || row.broken) return + if (await hasSingletonChild(row.path, exclude)) row.compact = true }) - await Promise.all(workers) } /** diff --git a/src/git.ts b/src/git.ts index b66a567e..a19e56f6 100644 --- a/src/git.ts +++ b/src/git.ts @@ -244,7 +244,7 @@ export function parseLogLines(output: string): GitLogEntry[] { } /** Run one git command; resolves with stdout, rejects with GitCommandError. */ -function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise { +export function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise { // `core.quotePath=false`: emit paths verbatim instead of C-quoting them // (git's default turns a CJK/space path into an octal-escaped, quoted // string, and every diff surface renders that string as the file name). @@ -280,12 +280,6 @@ function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise { - return runGit(cwd, args, timeoutMs) -} - /** One parsed `git blame --porcelain` row (the editor's hover blame). */ export interface GitBlameLine { /** 1-based line number in the file as it exists in the worktree. */ diff --git a/src/index.ts b/src/index.ts index ba5d102a..18a26e50 100644 --- a/src/index.ts +++ b/src/index.ts @@ -253,19 +253,9 @@ function conversationModelRoute(ctx: Context, sessionId: string): CommitModelRou return { provider: options.provider, model: options.model } } const events = ctx.sessions.get(sessionId)?.snapshotEvents() - if (events === undefined) return undefined - for (let index = events.length - 1; index >= 0; index--) { - const event = events[index] - if (event === undefined || event.type !== 'request/header') continue - const config = (event.data as { header?: { config?: unknown } } | undefined)?.header?.config - if (config === null || typeof config !== 'object') continue - const provider = (config as { provider?: unknown }).provider - const model = (config as { model?: unknown }).model - if (typeof provider === 'string' && provider !== '' && typeof model === 'string' && model !== '') { - return { provider, model } - } - } - return undefined + // The newest route, through the same `request/header` reader the picker's + // candidate list uses — the shape is parsed in exactly one place. + return events === undefined ? undefined : collectModelRoutes(events, 1)[0] } /** diff --git a/src/open-external.ts b/src/open-external.ts index 5140b133..5151057e 100644 --- a/src/open-external.ts +++ b/src/open-external.ts @@ -11,7 +11,7 @@ */ import { execFileSync, spawn } from 'node:child_process' import { readFileSync } from 'node:fs' -import { parentOf, requireAbsolute } from './fs-tree.ts' +import { messageOf, parentOf, requireAbsolute } from './fs-tree.ts' import { SidebarError } from './wire.ts' /** The two external open actions the route accepts. */ @@ -231,10 +231,6 @@ export function validateExternalUrl(raw: string): string { return raw } -function messageOf(error: unknown): string { - return error instanceof Error ? error.message : String(error) -} - /** One attempted launch that failed; kept for the aggregated error message. */ interface LaunchAttemptFailure { command: string diff --git a/src/text-encoding.ts b/src/text-encoding.ts index 8e7aadf0..b1269763 100644 --- a/src/text-encoding.ts +++ b/src/text-encoding.ts @@ -105,7 +105,52 @@ function encodeUtf32(text: string, littleEndian: boolean): Buffer { return body } -/** Detect BOM-less UTF-16 from the NUL-byte lane typical of scripts/config. */ +/** + * Whether one UTF-16 code unit is plausible as TEXT: tab / LF / CR, printable + * ASCII, or anything from U+00A0 up (letters, CJK, full-width punctuation) + * outside the surrogate range and the U+FFFE/FFFF tail. C0 controls other than + * whitespace, DEL and the whole C1 block never appear in text, while a 16-bit + * number stream spends a large share of its units exactly there. + */ +function isUtf16TextUnit(unit: number): boolean { + if (unit === 0x09 || unit === 0x0a || unit === 0x0d) return true + if (unit >= 0x20 && unit <= 0x7e) return true + if (unit >= 0xa0 && unit <= 0xd7ff) return true + return unit >= 0xe000 && unit <= 0xfffd +} + +/** + * Whether the lane sample reads as text in the given byte order: at least 90% + * of its code units must be text units ({@link isUtf16TextUnit}). A low + * amplitude 16-bit table sits far below that, real script/config text at or + * near 100%. + * @param bytes - the buffer (only the lane sample is read). + * @param pairs - how many code units to judge (the caller's lane window). + * @param littleEndian - the byte order of the candidate lane. + */ +function looksLikeUtf16Text(bytes: Uint8Array, pairs: number, littleEndian: boolean): boolean { + if (pairs === 0) return false + let text = 0 + for (let index = 0; index < pairs; index += 1) { + const unit = littleEndian + ? bytes[index * 2]! | (bytes[index * 2 + 1]! << 8) + : (bytes[index * 2]! << 8) | bytes[index * 2 + 1]! + if (isUtf16TextUnit(unit)) text += 1 + } + return text * 10 >= pairs * 9 +} + +/** + * Detect BOM-less UTF-16 from the NUL-byte lane typical of scripts/config. + * + * The lane alone is NOT enough: a raw 16-bit little-endian stream (a sample + * table, an audio buffer) leaves the high byte 0 for every value below 256 and + * matches it exactly. Its code units then land all over the C0/C1 control + * blocks instead of text, so the candidate must also read as text + * ({@link looksLikeUtf16Text}) — otherwise a binary file opened as an editable + * buffer, and a save rewrote it as UTF-16 (dropping the trailing byte of an + * odd-length file, which `decodeUtf16` truncates in the same way). + */ function bomlessUtf16(bytes: Uint8Array): 'utf16le' | 'utf16be' | undefined { if (bytes.length < 4) return undefined const pairs = Math.min(Math.floor(bytes.length / 2), 1024) @@ -116,8 +161,10 @@ function bomlessUtf16(bytes: Uint8Array): 'utf16le' | 'utf16be' | undefined { if (bytes[i * 2 + 1] === 0) oddZeros += 1 } const minimumZeros = Math.max(2, Math.floor(pairs * 0.2)) - if (oddZeros >= minimumZeros && oddZeros >= evenZeros * 4) return 'utf16le' - if (evenZeros >= minimumZeros && evenZeros >= oddZeros * 4) return 'utf16be' + if (oddZeros >= minimumZeros && oddZeros >= evenZeros * 4 + && looksLikeUtf16Text(bytes, pairs, true)) return 'utf16le' + if (evenZeros >= minimumZeros && evenZeros >= oddZeros * 4 + && looksLikeUtf16Text(bytes, pairs, false)) return 'utf16be' return undefined } diff --git a/tests/active-worktree.spec.ts b/tests/active-worktree.spec.ts index 1c9f604f..73d4c407 100644 --- a/tests/active-worktree.spec.ts +++ b/tests/active-worktree.spec.ts @@ -15,9 +15,9 @@ vi.mock('../src/git.ts', async (importOriginal) => { const actual = await importOriginal() return { ...actual, - runGitRaw: (cwd: string, args: string[], timeoutMs?: number) => { + runGit: (cwd: string, args: string[], timeoutMs?: number) => { probed.push(cwd) - return actual.runGitRaw(cwd, args, timeoutMs) + return actual.runGit(cwd, args, timeoutMs) }, } }) diff --git a/tests/commit-message.spec.ts b/tests/commit-message.spec.ts index cb68adfd..d9e45d8d 100644 --- a/tests/commit-message.spec.ts +++ b/tests/commit-message.spec.ts @@ -11,7 +11,6 @@ import { cleanSuggestion, collectModelRoutes, defaultRouteOf, - formatModelRoute, lowestReasoningEffortOf, modelEntryOf, normalizeLanguage, @@ -38,13 +37,6 @@ describe('parseModelRoute', () => { }) }) -describe('formatModelRoute', () => { - it('round-trips through parseModelRoute', () => { - const route = { provider: 'deepseek', model: 'deepseek-chat' } - expect(parseModelRoute(formatModelRoute(route))).toEqual(route) - }) -}) - describe('normalizeLanguage', () => { it('is zh only on the exact marker, en otherwise', () => { expect(normalizeLanguage('zh')).toBe('zh') diff --git a/tests/editor-unsaved-guard.spec.tsx b/tests/editor-unsaved-guard.spec.tsx index 5ff72a23..bf9f8663 100644 --- a/tests/editor-unsaved-guard.spec.tsx +++ b/tests/editor-unsaved-guard.spec.tsx @@ -20,7 +20,7 @@ import { Sidebar } from '../src/client/Sidebar.tsx' import { createBetterSidebarService, type BetterSidebarService, type FileViewerProps } from '../src/client/service.ts' import { allLeaves, createSidebarStore, toggleBottomPanel, type SidebarStore } from '../src/client/state.ts' import { - clearEditorDirty, confirmDiscardDraft, dirtyCount, dirtyCountForSession, editorDirtyRevision, + clearEditorDirty, confirmDiscardDraft, dirtyCount, editorDirtyRevision, isEditorDirty, setEditorDirty, subscribeEditorDirty, } from '../src/client/editor-dirty.ts' import { clearRetargetedPath, closePathTabs, consumeRetargetedPath, pathTabKey, retargetPathTabs } from '../src/client/tree-mutations.ts' @@ -162,10 +162,9 @@ describe('editor-dirty registry', () => { it('registers a dirty tab and clears it again, bumping the revision each time', () => { const before = editorDirtyRevision() setEditorDirty('t1', true, 's1', '/tmp/a.ts') - expect(isEditorDirty('t1')).toBe(true) + expect(isEditorDirty('t1', 's1')).toBe(true) expect(dirtyCount()).toBe(1) - expect(dirtyCountForSession('s1')).toBe(1) - expect(dirtyCountForSession('other')).toBe(0) + expect(isEditorDirty('t1', 'other')).toBe(false) expect(editorDirtyRevision()).toBeGreaterThan(before) const afterRegister = editorDirtyRevision() @@ -174,17 +173,36 @@ describe('editor-dirty registry', () => { // otherwise re-subscribe on every render). expect(editorDirtyRevision()).toBe(afterRegister) - clearEditorDirty('t1') - expect(isEditorDirty('t1')).toBe(false) + clearEditorDirty('t1', 's1') + expect(isEditorDirty('t1', 's1')).toBe(false) expect(dirtyCount()).toBe(0) expect(editorDirtyRevision()).toBeGreaterThan(afterRegister) }) - it('re-points an entry when the tab switches file or session', () => { + it('keeps one record per session for the same tab id', () => { + // The id is session-scoped: the native right column counts its own `tab1`… + // and the workbench reuses `editor:` across sessions, so both records + // must be able to exist at once. setEditorDirty('t2', true, 's1', '/tmp/a.ts') setEditorDirty('t2', true, 's2', '/tmp/b.ts') - expect(dirtyCountForSession('s1')).toBe(0) - expect(dirtyCountForSession('s2')).toBe(1) + expect(dirtyCount()).toBe(2) + expect(isEditorDirty('t2', 's1')).toBe(true) + expect(isEditorDirty('t2', 's2')).toBe(true) + }) + + it('a second session mounting the same tab id never clears the first session draft', () => { + // Session A's editor holds a draft … + setEditorDirty('tab1', true, 's1', '/tmp/a.ts') + // … then B's editor mounts over the same native id and reports clean (its + // mount always does: the toolbar has not reported yet), and B's body is + // unmounted again. Neither may touch A's record: losing it disarms the + // unload guard and a refresh drops A's draft without a word. + setEditorDirty('tab1', false, 's2', '/tmp/b.ts') + clearEditorDirty('tab1', 's2') + expect(isEditorDirty('tab1', 's1')).toBe(true) + expect(dirtyCount()).toBe(1) + // Without a session the read is the conservative one: any session matches. + expect(isEditorDirty('tab1')).toBe(true) }) it('notifies subscribers and stops after unsubscribe', () => { @@ -192,7 +210,7 @@ describe('editor-dirty registry', () => { const unsubscribe = subscribeEditorDirty(listener) setEditorDirty('t1', true, 's1', '/tmp/a.ts') expect(listener).toHaveBeenCalledTimes(1) - clearEditorDirty('t1') + clearEditorDirty('t1', 's1') expect(listener).toHaveBeenCalledTimes(2) unsubscribe() setEditorDirty('t1', true, 's1', '/tmp/a.ts') @@ -202,19 +220,24 @@ describe('editor-dirty registry', () => { it('confirmDiscardDraft passes clean tabs through and prompts for dirty ones', () => { const confirmSpy = vi.fn().mockReturnValue(false) vi.stubGlobal('confirm', confirmSpy) - expect(confirmDiscardDraft('t1', 'sure?')).toBe(true) + expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(true) expect(confirmSpy).not.toHaveBeenCalled() setEditorDirty('t1', true, 's1', '/tmp/a.ts') - expect(confirmDiscardDraft('t1', 'sure?')).toBe(false) + expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(false) expect(confirmSpy).toHaveBeenCalledWith('sure?') // Declined: the draft survives. - expect(isEditorDirty('t1')).toBe(true) + expect(isEditorDirty('t1', 's1')).toBe(true) confirmSpy.mockReturnValue(true) - expect(confirmDiscardDraft('t1', 'sure?')).toBe(true) + expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(true) // Confirmed: the entry is cleared so a follow-up close cannot re-prompt. - expect(isEditorDirty('t1')).toBe(false) + expect(isEditorDirty('t1', 's1')).toBe(false) + // Another session's same-numbered tab is untouched by that clear. + setEditorDirty('t1', true, 's9', '/tmp/other.ts') + confirmSpy.mockReturnValue(false) + expect(confirmDiscardDraft('t1', 'sure?', 's1')).toBe(true) + expect(isEditorDirty('t1', 's9')).toBe(true) }) }) @@ -459,9 +482,9 @@ describe('EditorHost dirty registration', () => { expanded: [], revealed: [], onToggleDir: () => {}, onReferenceFile: () => {}, })) await act(async () => { await Promise.resolve() }) - expect(isEditorDirty(tab.id)).toBe(true) + expect(isEditorDirty(tab.id, 'editor-host-dirty')).toBe(true) mounted.unmount() - expect(isEditorDirty(tab.id)).toBe(false) + expect(isEditorDirty(tab.id, 'editor-host-dirty')).toBe(false) }) }) @@ -473,14 +496,14 @@ describe('close guard', () => { try { await act(async () => { await Promise.resolve() }) expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts') - expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true) + expect(isEditorDirty('editor:/tmp/a.ts', mounted.sessionId)).toBe(true) // Cancel: the tab survives and stays dirty. confirmSpy.mockReturnValue(false) click(closeButton(mounted.container)) expect(confirmSpy).toHaveBeenCalledTimes(1) expect(openTabIds(mounted.store)).toContain('editor:/tmp/a.ts') - expect(isEditorDirty('editor:/tmp/a.ts')).toBe(true) + expect(isEditorDirty('editor:/tmp/a.ts', mounted.sessionId)).toBe(true) // Confirm: the tab closes. confirmSpy.mockReturnValue(true) @@ -498,7 +521,7 @@ describe('close guard', () => { const mounted = mountSidebarWithEditor() try { await act(async () => { await Promise.resolve() }) - clearEditorDirty('editor:/tmp/a.ts') + clearEditorDirty('editor:/tmp/a.ts', mounted.sessionId) click(closeButton(mounted.container)) expect(confirmSpy).not.toHaveBeenCalled() expect(openTabIds(mounted.store)).not.toContain('editor:/tmp/a.ts') diff --git a/tests/file-tree-compact-fold.spec.tsx b/tests/file-tree-compact-fold.spec.tsx index e6788a86..1eadfd6b 100644 --- a/tests/file-tree-compact-fold.spec.tsx +++ b/tests/file-tree-compact-fold.spec.tsx @@ -28,12 +28,18 @@ beforeAll(() => { Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true }) }) -const fsTrees = vi.hoisted(() => vi.fn()) +const { fsTrees, fsRename } = vi.hoisted(() => ({ + fsTrees: vi.fn(), + fsRename: vi.fn(async (scope: unknown, path: string, name: string) => ({ + path: `${path.slice(0, path.lastIndexOf('/') + 1)}${name}`, + })), +})) vi.mock('../src/client/api.ts', () => ({ api: { fsTree: vi.fn(), fsTrees: (...args: unknown[]) => fsTrees(...args), + fsRename: (...args: unknown[]) => fsRename(...(args as [unknown, string, string])), gitStatus: async () => ({ isRepo: false, entries: [] }), }, downloadUrl: () => '/sidebar/file', @@ -158,6 +164,40 @@ function rowByLabel(container: HTMLElement, label: string): HTMLElement { return row } +/** One row by its rendered label (a folded row's label is the whole chain). */ +function rowByName(container: HTMLElement, name: string): HTMLElement { + const row = [...container.querySelectorAll('[class*="explorerRow"]')] + .find(element => element.querySelector('[class*="explorerName"]')?.textContent === name) + if (row === undefined) throw new Error(`no row "${name}" in ${JSON.stringify(rowLabels(container))}`) + return row +} + +/** Right-click one row (the row menu addresses what the row's label names). */ +function openMenu(container: HTMLElement, name: string): void { + const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 20, clientY: 30 }) + act(() => { rowByName(container, name).dispatchEvent(event) }) +} + +/** Click one row-menu entry by its (English, locale-pinned) label. */ +function clickMenuitem(label: string): void { + const item = [...document.querySelectorAll('[role="menuitem"]')] + .find(element => element.textContent === label) + if (item === undefined) throw new Error(`menuitem "${label}" not found`) + act(() => { item.click() }) +} + +/** Set a controlled input's value the React way (native setter + input). */ +function setNativeValue(element: HTMLInputElement, value: string): void { + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set + if (setter === undefined) throw new Error('no native value setter') + setter.call(element, value) + element.dispatchEvent(new Event('input', { bubbles: true })) +} + +function pressKey(element: HTMLElement, key: string): void { + element.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true })) +} + /** Every path the tree has asked for, across all batches. */ function requestedPaths(): string[] { return fsTrees.mock.calls.flatMap(call => call[1] as string[]) @@ -167,6 +207,7 @@ let harness: Harness beforeEach(() => { vi.stubGlobal('WebSocket', FakeSocket) fsTrees.mockReset() + fsRename.mockClear() fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ levels: paths.map(path => levelOf(path)), })) @@ -221,6 +262,22 @@ describe('FileTree breadcrumb folding', () => { expect(rowLabels(harness.container).some(label => label.startsWith('a/b/c'))).toBe(true) }) + it('renames the chain TAIL the row shows, not the fold head', async () => { + // The row renders at `/tmp/a` (the chain head) and its menu addressed the + // TAIL, so the commit has to land on `/tmp/a/b/c` — the directory the label + // names. Committing the head renamed the PARENT directory instead. + harness = mountTree() + await flush() + openMenu(harness.container, 'a/b/c') + clickMenuitem('Rename') + const input = harness.container.querySelector('input[class*="explorerRenameInput"]') + expect(input).not.toBeNull() + expect(input!.value).toBe('c') + setNativeValue(input!, 'renamed') + await act(async () => { pressKey(input!, 'Enter') }) + expect(fsRename).toHaveBeenCalledWith({ sessionId: 's1', cwd: '/tmp' }, '/tmp/a/b/c', 'renamed') + }) + it('carries the exclude list on every request, and a changed list wipes the cache', async () => { harness = mountTree([], ['node_modules']) await flush() diff --git a/tests/terminal-tab.spec.tsx b/tests/terminal-tab.spec.tsx index 8d27b0aa..a95c2adc 100644 --- a/tests/terminal-tab.spec.tsx +++ b/tests/terminal-tab.spec.tsx @@ -35,7 +35,7 @@ import { allLeaves, createSidebarStore, openTabInBottomPane } from '../src/clien import { createBetterSidebarService, type TabDescriptor } from '../src/client/service.ts' import { builtinTabs } from '../src/client/builtins/tabs.tsx' import { - bottomTerminalContentId, bottomTerminalKey, nextTerminalMeta, terminalRunOf, + bottomTerminalContentId, nextTerminalMeta, terminalRunOf, type HostTerminalView, type HostTerminalViewState, type WebTerminalsFace, } from '../src/client/terminal-client.ts' import { TerminalBottomView } from '../src/client/TerminalView.tsx' @@ -323,10 +323,10 @@ describe('terminal-bottom: the host terminal contract', () => { expect(terminals.viewCalls).toHaveLength(1) expect(terminals.viewCalls[0]).toEqual({ sessionId: 's1', - key: bottomTerminalKey(0), + key: bottomTerminalContentId(0), contentId: bottomTerminalContentId(0), }) - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! expect(view.mounted).toBe(1) expect(xterm.emulators).toHaveLength(1) expect(xterm.emulators[0]!.open).toHaveLength(1) @@ -346,7 +346,7 @@ describe('terminal-bottom: the host terminal contract', () => { const first = render(ctx, bottomTab()) await flush() const allocated = terminals.allocated - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! first.unmount() // A page reload looks exactly like this to the plugin: a fresh mount of @@ -360,7 +360,7 @@ describe('terminal-bottom: the host terminal contract', () => { bottomTerminalContentId(0), ]) expect(terminals.allocated, 'no second terminal was allocated').toBe(allocated) - expect(terminals.views.get('s1\u0000' + bottomTerminalKey(0))!.id).toBe(view.id) + expect(terminals.views.get('s1\u0000' + bottomTerminalContentId(0))!.id).toBe(view.id) second.unmount() }) @@ -369,7 +369,7 @@ describe('terminal-bottom: the host terminal contract', () => { const { ctx } = viewSetup(terminals) const { unmount } = render(ctx, bottomTab()) await flush() - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! // Keystrokes go through the MODEL (it serializes them and refuses them // while the view is not writable), never straight to the remote. @@ -399,7 +399,7 @@ describe('terminal-bottom: the host terminal contract', () => { const { ctx } = viewSetup(terminals) const { unmount } = render(ctx, bottomTab()) await flush() - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! act(() => { view.patch({ @@ -450,7 +450,7 @@ describe('terminal-bottom: degradation and recovery', () => { const { ctx, order } = viewSetup(terminals) const { container, rerender, unmount } = render(ctx, bottomTab()) await flush() - const first = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const first = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! act(() => { first.patch({ phase: 'failed', writable: false, issue: 'missingTerminal' }) }) const action = container.querySelector('button') @@ -482,7 +482,7 @@ describe('terminal-bottom: degradation and recovery', () => { const { ctx } = viewSetup(terminals) const { container, unmount } = render(ctx, bottomTab()) await flush() - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! act(() => { view.patch({ info: { id: view.id, title: 'Terminal', cwd: '/w', cols: 80, rows: 24, state: 'exited', exitCode: 0 }, @@ -517,7 +517,7 @@ describe('terminal-bottom: degradation and recovery', () => { const { ctx } = viewSetup(terminals) const { container, unmount } = render(ctx, bottomTab()) await flush() - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! act(() => { view.patch({ phase: 'disconnected', writable: false }) }) const action = container.querySelector('button')! act(() => { action.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) @@ -548,7 +548,7 @@ describe('terminal-bottom: degradation and recovery', () => { const { container, unmount } = render(ctx, bottomTab()) await flush() - const view = terminals.views.get('s1\u0000' + bottomTerminalKey(0))! + const view = terminals.views.get('s1\u0000' + bottomTerminalContentId(0))! act(() => { view.patch({ phase: 'failed', writable: false, issue: 'missingTerminal' }) }) const action = container.querySelector('button')! @@ -583,8 +583,6 @@ describe('terminal-bottom: degradation and recovery', () => { describe('terminal-bottom: identity helpers', () => { it('keeps run 0 stable and namespaces every later run', () => { expect(bottomTerminalContentId(0)).toBe('dsh-better-sidebar:terminal-bottom') - expect(bottomTerminalKey(0)).toBe(bottomTerminalContentId(0)) - expect(bottomTerminalContentId(1)).toBe(bottomTerminalKey(1)) expect(bottomTerminalContentId(1)).toContain('#1') // Distinct per run — the whole point of the generation. expect(bottomTerminalContentId(1)).not.toBe(bottomTerminalContentId(0)) @@ -614,7 +612,7 @@ describe('terminal-bottom: the descriptor close hook', () => { descriptor?.onClose?.(bottomTab({ terminalRun: 2 }), scope) expect(terminals.closeCalls).toEqual([ - { sessionId: 's1', key: bottomTerminalKey(2), contentId: bottomTerminalContentId(2) }, + { sessionId: 's1', key: bottomTerminalContentId(2), contentId: bottomTerminalContentId(2) }, ]) }) }) diff --git a/tests/text-encoding.spec.ts b/tests/text-encoding.spec.ts index 5be0328c..682ce3ac 100644 --- a/tests/text-encoding.spec.ts +++ b/tests/text-encoding.spec.ts @@ -50,6 +50,23 @@ describe('text encoding', () => { expect(decodeTextBytes(Buffer.from([0x89, 0x50, 0x00, 0x01, 0x02, 0x03]))).toBeNull() }) + it('keeps 16-bit little-endian data binary instead of reading it as UTF-16 text', () => { + // A raw uint16 table leaves the high byte 0 for every value below 256 — + // exactly the NUL lane BOM-less UTF-16 has — but its code units are C0/C1 + // control runs, not text. Read as text it opened a binary file in the + // editor, and a save rewrote it as UTF-16 (an odd length also lost its + // trailing byte). + const samples = Buffer.alloc(4096) + for (let index = 0; index < 2048; index += 1) samples.writeUInt16LE(100 + (index % 100), index * 2) + expect(decodeTextBytes(samples)).toBeNull() + expect(decodeTextBytes(Buffer.concat([samples, Buffer.from([0x7f])]))).toBeNull() + expect(decodeTextBytes(Buffer.concat([Buffer.from('RIFF....WAVEfmt data'), samples.subarray(0, 4000)]))).toBeNull() + // The same NUL lane spelled as text still reads as UTF-16: the lane vote + // alone must not decide. + expect(decodeTextBytes(Buffer.from('echo off\n', 'utf16le'))) + .toEqual({ content: 'echo off\n', encoding: 'utf16le' }) + }) + it('keeps a capped UTF-8 read UTF-8 when the cap cuts a character', () => { // A read cap stops wherever it lands, and the partial tail of a CJK // character is exactly what the GBK probe accepts: two of the three bytes