Merge pull request #901 from UNscientific-9/fix/p1-draft-rename-encoding

fix: 草稿守卫按会话记账 / 折叠行重命名落链尾 / 16 位小端数据不再当文本(另附 dev 新增代码精简)
This commit is contained in:
Atlas Zeng authored and GitHub committed 2026-10-12 01:49:42 +08:00
commit b01f51fd62
27 files changed
+373 -209

No files matched your search

+3 -3
View File
@@ -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<string | undefined> {
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<boolean> {
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 !== '') {
+1 -1
View File
@@ -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
+27 -7
View File
@@ -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<string, readonly FsEntry[]>()
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 ?? '') }}
/>
</div>
)
@@ -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}
+2 -1
View File
@@ -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
+1 -1
View File
@@ -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.
+4 -3
View File
@@ -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]),
+2 -2
View File
@@ -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
+1 -1
View File
@@ -437,7 +437,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose,
</div>
)
: target.kind === 'op' && mdOp && reading && readingText !== ''
? <MdReadingView text={readingText} ctx={ctx} scope={scope} path={target.kind === 'op' ? target.path : ''} />
? <MdReadingView text={readingText} ctx={ctx} scope={scope} path={target.path} />
: target.kind === 'op' && op !== null && op.isError
? (
<div className={css.paneBody}>
+2 -4
View File
@@ -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) }
}
/**
+62 -38
View File
@@ -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:<path>` 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
}
+3 -1
View File
@@ -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)
+2 -15
View File
@@ -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
}
+6 -13
View File
@@ -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<string, unknow
export function closeBottomTerminal(ctx: Context, tab: { meta?: unknown }, sessionId: string): void {
const service = webTerminals(ctx)
if (service === undefined) return
const run = terminalRunOf(tab)
service.close(sessionId, bottomTerminalKey(run), bottomTerminalContentId(run))
const id = bottomTerminalContentId(terminalRunOf(tab))
service.close(sessionId, id, id)
}
+26 -3
View File
@@ -34,6 +34,12 @@ interface PathTab {
* ABSOLUTE paths while a tab opened from a chat link carries the address's
* workspace-relative spelling, so every comparison runs here. */
absolute: string
/** The session this tab's EDITOR reads and writes in — the `scope.sessionId`
* its host registers the unsaved draft under, so it is the one the close
* guard has to name. Absent only for a bottom-workbench tab whose store has
* no session yet (the guard then reads conservatively rather than missing
* the record and closing a live draft without asking). */
scopeSessionId: string | undefined
/** The native tab's seat session; absent for a bottom-workbench tab, whose
* updates resolve against the store's current session. */
sessionId?: string
@@ -109,13 +115,22 @@ function pathTabsOf(snapshot: SidebarSnapshot, native: readonly NativePathTab[])
const tabs: PathTab[] = []
const state = snapshot.state
if (state !== undefined) {
// A bottom-workbench row resolves its scope against the store's session, so
// that same session is the one its editor registered its draft under — the
// key's `?? ''` is only the marker's spelling for "no session".
const session = snapshot.sessionId ?? ''
for (const leaf of allLeaves(state.bottomSplits)) {
for (const tab of leaf.tabs) {
// A bottom-workbench row carries an absolute path already, and it is the
// same string the tree hands this module — one spelling, both fields.
if (tab.path !== undefined) {
tabs.push({ key: pathTabKey(session, tab.id), id: tab.id, path: tab.path, absolute: tab.path })
tabs.push({
key: pathTabKey(session, tab.id),
id: tab.id,
path: tab.path,
absolute: tab.path,
scopeSessionId: snapshot.sessionId,
})
}
}
}
@@ -130,6 +145,10 @@ function pathTabsOf(snapshot: SidebarSnapshot, native: readonly NativePathTab[])
// raw against the tree's absolute paths skipped exactly those tabs, so the
// comparison runs on the resolved form while the tab keeps its spelling.
absolute: resolveSidebarPath(tab.cwd, tab.path),
// The SEAT session (below) keys the record; THIS one is the namespace the
// editor behind it runs in, and a file address may name a session other
// than the column it is drawn in.
scopeSessionId: tab.scopeSessionId,
sessionId: tab.sessionId,
})
}
@@ -177,7 +196,11 @@ export function retargetPathTabs(ctx: Context, store: SidebarStore, oldPath: str
* subtree of open files with it). A tab holding an unsaved draft asks first
* (the same guard + copy as the sidebar's tab close); declining keeps the
* tab — which is the user's call for the bottom workbench, and stays a
* conflict-gated save on the native side, never a silent re-create. */
* conflict-gated save on the native side, never a silent re-create.
*
* The question is asked in the tab's OWN session: the draft registry is keyed
* by `sessionId::tabId`, so a bare id read would look up a same-numbered tab in
* some other session (or nothing at all) and close a live draft unprompted. */
export function closePathTabs(ctx: Context, store: SidebarStore, target: string, unsavedMessage: string): void {
const service = ctx.get('betterSidebar')
if (service === undefined) return
@@ -185,7 +208,7 @@ export function closePathTabs(ctx: Context, store: SidebarStore, target: string,
// `isWithinWorkspace` is true for the target itself too, so one test covers
// both "this exact file" and "anything under this directory".
if (!isWithinWorkspace(target, tab.absolute)) continue
if (!confirmDiscardDraft(tab.id, unsavedMessage)) continue
if (!confirmDiscardDraft(tab.id, unsavedMessage, tab.scopeSessionId)) continue
// The tab is going away: a move announced for it can never be claimed.
clearRetargetedPath(tab.key)
service.closeTab(tab.id, tab.sessionId === undefined ? undefined : { sessionId: tab.sessionId })
+5 -12
View File
@@ -58,11 +58,6 @@ export function parseModelRoute(value: unknown): CommitModelRoute | undefined {
return { provider, model }
}
/** Render one route back into its stored form (the select value). */
export function formatModelRoute(route: CommitModelRoute): string {
return `${route.provider}/${route.model}`
}
/** Cap of the conversation-derived route list (the adapter catalog is
* capped separately, host-side). */
export const MODEL_ROUTE_HISTORY_LIMIT = 20
@@ -136,19 +131,17 @@ export function lowestReasoningEffortOf(efforts: unknown): string | undefined {
const id = entry !== null && typeof entry === 'object' ? (entry as { id?: unknown }).id : undefined
if (typeof id === 'string' && id !== '') ids.push(id)
}
const first = ids[0]
if (first === undefined) return undefined
let best = first
let bestRank = (REASONING_LEVEL_ORDER as readonly string[]).indexOf(best)
for (const id of ids.slice(1)) {
let best: string | undefined
let bestRank = Number.POSITIVE_INFINITY
for (const id of ids) {
const rank = (REASONING_LEVEL_ORDER as readonly string[]).indexOf(id)
if (rank < 0) continue
if (bestRank < 0 || rank < bestRank) {
if (rank < bestRank) {
best = id
bestRank = rank
}
}
return best
return best ?? ids[0]
}
/**
+16 -11
View File
@@ -30,6 +30,17 @@ import { ensureWorkspaceWritePath, resolveTarget } from './path-security.ts'
import { encodeText, fileFormatOf, restoreEol } from './text-encoding.ts'
import { SidebarError } from './wire.ts'
/**
* The name SHAPE every file mutation shares: one path segment, no separators,
* no `.`/`..`. Shared by rename, mkdir and the new-file rule so the three
* entries refuse the same inputs with the same sentence.
*/
function assertSingleSegmentName(name: string): void {
if (name === '' || name === '.' || name === '..' || name.includes('/') || name.includes('\\')) {
throw new SidebarError('bad-request', 'name must be a single path segment', 400)
}
}
/** Inputs of one upload: the session scope plus the request body stream. */
export interface WorkspaceUploadInput {
/** The session workspace root (the base of session-relative targets). */
@@ -289,9 +300,7 @@ async function pathExists(target: string): Promise<boolean> {
*/
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)
+23 -20
View File
@@ -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<void> {
/**
* 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<void>): Promise<void> {
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<void> {
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<void> {
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)
}
/**
+1 -7
View File
@@ -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<string> {
export function runGit(cwd: string, args: string[], timeoutMs = 30_000): Promise<string> {
// `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<string
})
}
/** Raw stdout of one git command. Callers that only need text (no status
* parsing) should use this instead of re-implementing the spawn. */
export function runGitRaw(cwd: string, args: string[], timeoutMs = 30_000): Promise<string> {
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. */
+3 -13
View File
@@ -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]
}
/**
+1 -5
View File
@@ -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
+50 -3
View File
@@ -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
}
+2 -2
View File
@@ -15,9 +15,9 @@ vi.mock('../src/git.ts', async (importOriginal) => {
const actual = await importOriginal<typeof import('../src/git.ts')>()
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)
},
}
})
-8
View File
@@ -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')
+43 -20
View File
@@ -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:<path>` 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')
+58 -1
View File
@@ -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<HTMLElement>('[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<HTMLElement>('[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<HTMLInputElement>('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()
+12 -14
View File
@@ -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) },
])
})
})
+17
View File
@@ -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