refactor: 精简 dev 相对 main 新增代码里的重复与白干(行为不变)

dev 分支的新增代码过了一轮「代码精简」审查(复用 / 简化 / 效率 / 修在哪一层四个角度,
分宿主侧、客户端外壳、客户端功能面板三片,另加测试与脚本),这里只落地行为完全不变的那批:

- `runGitRaw` 是 `runGit` 的纯转发别名(三个角度都点到):导出 `runGit`、删掉别名,
  `active-worktree.ts` 与它的 `vi.mock` 键同步改名。
- `open-external.ts` 的 `messageOf` 与 `fs-tree.ts` 的导出逐字相同:删本地实现改 import。
- `fs-operations.ts` 的单段名校验抄了三遍(注释却自称 shared rule):提成
  `assertSingleSegmentName`,rename / mkdir / 新建文件三处共用。
- `fs-tree.ts` 两个探测函数各抄一遍有界并发池:提成 `forEachRow`。
- `index.ts` 自己复刻了一遍 `request/header` 的 provider/model 读取:改调
  `collectModelRoutes(events, 1)[0]`;`lowestReasoningEffortOf` 的三态循环收成
  best/bestRank;`formatModelRoute` 零调用点,删掉(连带自测)。
- `state.ts`:`markUnread` / `clearUnread` 的当前会话路径改走已有的 `reduce`
  (「归约器返回同引用即 no-op」本来就在 reduce 里),删掉私有的 `replaceCurrent`;
  非当前会话那条仍只写内存不落盘,行为未动。
- `editor-dirty.ts`:`DirtyEntry.sessionId` 只服务一个没有生产调用者的
  `dirtyCountForSession`,会话隔离已由 `sessionId::tabId` 这个键承载,两个一起删,
  用例改断 `isEditorDirty(tabId, sessionId)`。
- `FileTree.tsx`:同一批行原先 `renderLevel` 与 `visibleRows` 各排一次,收进按
  `(data, sort)` 记忆的 `entriesFor`(照 `chainFor` 的形状)。
- `dock-fallback.tsx`:500ms 重测出的坐标没变就不换 state 对象(省掉一次无意义重渲染)。
- 其余同形收口:`DiffPane` 的死分支、`terminal-client` 的 `bottomTerminalKey`
  (与 `bottomTerminalContentId` 同值,调用点复用同一个 id)、`SideChatView` 的
  O(线程×目录) 排序扫描降为 Map、`conversation-draft` 的末段路径复用 `paths.baseName`、
  `TreePanel` 的目录命中集按 results 记忆。

验证:`tsc --noEmit` 只剩改动前那 3 条缺 `@xterm/*` 的既有报错;eslint 干净;
全套 vitest 与改动前的失败集合逐条一致(13 条,均为环境原因:缺 xterm 的构建/转换类
3 条、Windows 符号链接权限 3 条、语言字典串味 4 条、真起 git 的冒烟 1 条、文件级 1 条)。
This commit is contained in:
unsc9 committed 2026-10-09 16:04:24 +08:00
1 parent 9021d1094e
commit ebc5d0b6b7
21 files changed
+116 -158

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 !== '') {
+23 -5
View File
@@ -1800,6 +1800,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,
@@ -1809,7 +1828,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
@@ -1822,7 +1841,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
/**
@@ -1988,9 +2007,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
@@ -511,7 +511,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
+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) }
}
/**
+2 -12
View File
@@ -21,9 +21,8 @@
* 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
}
@@ -56,7 +55,7 @@ export function setEditorDirty(tabId: string, dirty: boolean, sessionId: string,
}
const previous = dirtyTabs.get(key)
if (previous !== undefined && previous.path === path) return
dirtyTabs.set(key, { sessionId, tabId, path })
dirtyTabs.set(key, { tabId, path })
notify()
}
@@ -94,15 +93,6 @@ export function isEditorDirty(tabId: string, sessionId?: string): boolean {
return false
}
/** 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
}
return count
}
/** How many tabs hold unsaved drafts across every session (the unload guard). */
export function dirtyCount(): number {
return dirtyTabs.size
+3 -1
View File
@@ -54,7 +54,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
@@ -971,7 +971,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
}
@@ -997,7 +997,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)
@@ -1006,19 +1006,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)
}
+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
@@ -29,6 +29,17 @@ import { invalidateDirectoryCache, requireAbsolute } from './fs-tree.ts'
import { ensureWorkspaceWritePath, resolveTarget } from './path-security.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). */
@@ -208,9 +219,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)
@@ -253,9 +262,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)) {
@@ -305,8 +312,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.
@@ -314,9 +321,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
@@ -252,19 +252,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
+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')
+3 -6
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 { closePathTabs } from '../src/client/tree-mutations.ts'
@@ -162,8 +162,7 @@ describe('editor-dirty registry', () => {
setEditorDirty('t1', true, 's1', '/tmp/a.ts')
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()
@@ -184,8 +183,7 @@ describe('editor-dirty registry', () => {
// 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(1)
expect(dirtyCountForSession('s2')).toBe(1)
expect(dirtyCount()).toBe(2)
expect(isEditorDirty('t2', 's1')).toBe(true)
expect(isEditorDirty('t2', 's2')).toBe(true)
})
@@ -200,7 +198,6 @@ describe('editor-dirty registry', () => {
setEditorDirty('tab1', false, 's2', '/tmp/b.ts')
clearEditorDirty('tab1', 's2')
expect(isEditorDirty('tab1', 's1')).toBe(true)
expect(dirtyCountForSession('s1')).toBe(1)
expect(dirtyCount()).toBe(1)
// Without a session the read is the conservative one: any session matches.
expect(isEditorDirty('tab1')).toBe(true)
+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) },
])
})
})