From ebc5d0b6b735e3ed76e587ad120aa353ef9017ac Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Fri, 9 Oct 2026 16:04:24 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E7=B2=BE=E7=AE=80=20dev=20?= =?UTF-8?q?=E7=9B=B8=E5=AF=B9=20main=20=E6=96=B0=E5=A2=9E=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E9=87=8C=E7=9A=84=E9=87=8D=E5=A4=8D=E4=B8=8E=E7=99=BD?= =?UTF-8?q?=E5=B9=B2=EF=BC=88=E8=A1=8C=E4=B8=BA=E4=B8=8D=E5=8F=98=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 条)。 --- src/active-worktree.ts | 6 ++-- src/client/FileTree.tsx | 28 ++++++++++++++---- src/client/SideChatView.tsx | 3 +- src/client/TerminalView.tsx | 7 +++-- src/client/TreePanel.tsx | 4 +-- src/client/changes/DiffPane.tsx | 2 +- src/client/conversation-draft.ts | 6 ++-- src/client/editor-dirty.ts | 14 ++------- src/client/sidebar/dock-fallback.tsx | 4 ++- src/client/state.ts | 17 ++--------- src/client/terminal-client.ts | 19 ++++-------- src/commit-message.ts | 17 ++++------- src/fs-operations.ts | 27 ++++++++++------- src/fs-tree.ts | 43 +++++++++++++++------------- src/git.ts | 8 +----- src/index.ts | 16 ++--------- src/open-external.ts | 6 +--- tests/active-worktree.spec.ts | 4 +-- tests/commit-message.spec.ts | 8 ------ tests/editor-unsaved-guard.spec.tsx | 9 ++---- tests/terminal-tab.spec.tsx | 26 ++++++++--------- 21 files changed, 116 insertions(+), 158 deletions(-) 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/FileTree.tsx b/src/client/FileTree.tsx index 80751fbf..c6642750 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -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() + 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} diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 1bba5d99..f17dc2c3 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -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 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 6a3959a8..286d7f77 100644 --- a/src/client/editor-dirty.ts +++ b/src/client/editor-dirty.ts @@ -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 diff --git a/src/client/sidebar/dock-fallback.tsx b/src/client/sidebar/dock-fallback.tsx index baad4146..9d3e07a1 100644 --- a/src/client/sidebar/dock-fallback.tsx +++ b/src/client/sidebar/dock-fallback.tsx @@ -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) diff --git a/src/client/state.ts b/src/client/state.ts index 4c6ec327..f016f3cf 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -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 } 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) @@ -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) 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 78258d09..74ebb197 100644 --- a/src/index.ts +++ b/src/index.ts @@ -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] } /** 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/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 411080f5..a7e92c0f 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 { 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) 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) }, ]) }) })