Merge remote-tracking branch 'origin/dev' into fix/826-file-link-line-jump

# Conflicts:
#	CHANGELOG.md
#	src/client/FileTree.tsx
#	src/client/desktop-env.ts
This commit is contained in:
ymac committed 2026-10-05 22:20:24 +08:00
commit 5f90f1d466
42 files changed
+1130 -81

No files matched your search

+2
View File
@@ -4,6 +4,8 @@
### Unreleased
- 📑 **Tab 右键菜单补两项**([#109](https://github.com/omdsh-dev/DSH-better-sidebar/issues/109)):「**关闭全部页签**」与「**在资源管理器中定位**」。前者作用域与相邻三项一致——**右键所在的那个标签组**(分栏各管各的),含右键的那个页签本身(这是它与「关闭其他页签」的区别),逐条走既有单页签关闭路径(descriptor `onClose` 生命周期 + 终端 pty 释放 + 会话作用域),页签在滚动视口外也能关;菜单只从页签上打开,所以该项恒可用。后者对页签关联的文件(`tab.path`,即编辑器/文件夹窗口)调用宿主 **open-in-app** 的 reveal——与资源管理器行右键「在文件管理器中显示」**同一个适配器**(`createOpenInApp` → `ctx.remote.session.openWorkspacePath({ action: 'reveal' })`),不新增任何宿主调用;变更 / 任务 / 侧边对话 / diff 页签没有可定位的文件(diff 的 ref 是仓库相对路径,不是宿主能定位的路径),该项置灰,无 resolver 时同样置灰。词条 `closeAllTabs` / `revealTabInFileManager` 同批进入 `locales.ts` 的 zh/en 与 19 份第三语言词典。
- 🧪 测试:`tests/tab-bar-context-menu.spec.tsx` 把菜单整份钉到 **6 项**(标签序 + 每行 disabled 数组),新增「关闭全部」「定位」「无关联文件置灰」「无 resolver 置灰」用例,并新增一条 Workbench 用例钉住 reveal resolver 穿到**分栏后每个 pane 的** tab 条(回退任一层传递即红)。
- 🔍 **文件搜索优先走本机原生引擎(fd / ripgrep),缺失或失败自动回退 JS 遍历**([#203](https://github.com/omdsh-dev/DSH-better-sidebar/issues/203),PR [#303](https://github.com/omdsh-dev/DSH-better-sidebar/pull/303) 重写落地):`fs.search` 之前是纯 JS 递归遍历,十万级目录秒级、10 万条访问预算一顶就静默截断。现在启动后惰性探测一次(每个候选二进制 `--version` 500ms 内验证通过才用,进程内缓存),探到就用引擎,探不到/运行失败回退原遍历;rg 优先用 DSH 自己捆绑的 `@vscode/ripgrep`(agent 侧搜索工具同一个二进制,从 CLI 入口的依赖树推导候选路径),fd 走 `--fixed-strings` 字面量匹配。噪声目录排除名单单源化到 `SKIP_DIR_NAMES`(18 项,walk 与两条 argv 共用),引擎输出统一归一化成 walk 契约(根相对、`/` 分隔、大小写不敏感),**路由与客户端零改动**。**目录命中按 #801 的契约同时产出 `dirs`**:fd 用 `--type d` 直接列目录,rg 由文件路径倒推匹配的目录段(`deriveRgMatches`)——唯一残留差异是**空目录在 rg 下不可见**(已记录)。运行失败禁用该引擎(坏二进制不该拖慢后续搜索),**超时只降级本次**(树太大不等于二进制坏)。调试插桩 `DSH_SEARCH_DEBUG=1` 写 `$DSH_HOME/search-debug.log`,默认完全静默。Windows 侧由 `ci-windows` lane 承载:`choco install fd ripgrep` + `pnpm check:engines` 对插件自己的 argv 做字节级断言(不得含 `\`/CR、非 ASCII 文件名必须命中)。
- 🧪 测试:`tests/search-engines.spec.ts`(探测缓存 / 失败禁用 / 超时不禁用 / argv 对称性 / `deriveRgMatches` / 捆绑 rg 候选路径推导 / 真引擎在场时的端到端),`tests/fs-search.spec.ts` 的 dispatch 组(引擎优先、`dirs` 透传、预算透传、运行失败回退并禁用)。
+1 -1
View File
@@ -246,7 +246,7 @@ dsh registry enable dsh-external/dsh-better-sidebar
| 选中下一个相同片段 | `Ctrl/Cmd + D` |
| Git 提交 | `Ctrl + Enter` |
| 关闭 Tab | 鼠标中键 |
| Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签(当前标签组) |
| Tab 右键菜单 | 关闭 / 关闭其他页签 / 关闭左侧页签 / 关闭右侧页签 / 关闭全部页签(均限当前标签组);在资源管理器中定位(该页签对应一个文件时可用) |
| 拆分/合并分栏 | 拖 Tab 到分栏边缘 / 中间 |
| 引用文件到输入框 | 悬浮行尾 `@文件` 按钮 |
| 复制文件路径 | 右键行 → 复制相对/绝对地址 |
+1 -1
View File
@@ -255,7 +255,7 @@ WeChat / QQ group QR codes will live here. After uploading the QR images (drag t
| Select next occurrence | `Ctrl/Cmd + D` |
| Git commit | `Ctrl + Enter` |
| Close tab | Middle mouse button |
| Tab context menu (right-click) | Close / Close Other Tabs / Close Tabs to the Left / Close Tabs to the Right (current pane) |
| Tab context menu (right-click) | Close / Close Other Tabs / Close Tabs to the Left / Close Tabs to the Right / Close All Tabs (all scoped to the current pane); Reveal in File Manager (for a tab that has a file) |
| Split / merge panes | Drag tab to pane edge / middle |
| Reference file to input | Hover the `@file` button at end of line |
| Copy file path | Right-click row → copy relative/absolute path |
+3 -3
View File
@@ -1071,9 +1071,9 @@ interface SettingsDescriptor {
- **根锚点**:宿主 div 带 `data-dsh-better-sidebar`(append 到 body);其内**面板宿主层** `[data-dsh-panel-host]`(`fixed; inset:0; z-25; pointer-events:none; overflow:hidden+clip`,v0.13.1+),面板/开关簇 absolute 定位,免疫中间层 transform 劫持;页面级 transform 触发 `data-dsh-panel-host-degraded` 降级。`overflow` 级联是**契约**(`hidden` 兜底 + `clip` 收尾,`tests/panel-host-css.spec.ts` 守护):`hidden` 盒子仍是滚动容器,脚本滚动或浏览器 scroll-into-view 修正(焦点移入视口外区域、嵌套 iframe/工作台加载时抢焦点、面板滑出动画中 focus() 落点)会沿最近可滚祖先滚走整层——面板与开关簇集体偏离视口角(computed left/right 仍"正确",偏移藏在盒子自身 scroll offset 里);`clip` 裁剪语义相同但不产生滚动盒,任何路径都滚不动这层。皮肤作用域覆盖限定在 `[data-dsh-better-sidebar]` 内。
- **布局变量**(`<html>` 上,面板打开时有效):`--dsh-sidebar-width` / `--dsh-sidebar-height`。右面板宽度 = AppFrame 的 `padding-right` 预留(新版 `#root [data-dsh-frame]` / rc.8 `#root > [data-slot="root"] > div` 双锚点),AppFrame border box 保持完整桌面视口宽度(Harness 以此判定桌面/窄屏布局,避免插件面板展开误入窄屏);AppFrame 的 details 拖拽手柄按同一变量向左平移贴合列边缘。底部面板仍走 centerCol `margin-bottom`;centerCol 锚点 = **JS 标注**(禁止 `nth-child`):侧栏 shell 的定位器给测得的 centerCol 节点打 `[data-dsh-center-col]` 标签(`Sidebar.tsx` locate,节点更换/HMR 时随 ref 迁移),`layout.css` 用 `#root [data-dsh-center-col]` 选中(`drag-layout.e2e.ts` 断言恰一节点且为对话槽宿主的父级——alpha.2 起 shell 把 `#root [data-slot="main.conversation"]` 解析进列并跳过 `display: contents` 祖先(`center-column.ts` 的 `CENTER_COLUMN_SELECTOR` 同时认 `main.conversation` 与 alpha.1 的 `conversation`),定位器从槽宿主向上取第一个非 `contents` 的祖先;frame 宽度与桌面 Session Log 由 `desktop-layout.e2e.ts` 断言)。
- **桌面信号与标题栏**(v0.14.1+ 四方案模型 `SidebarPrefs.titleBarScheme`,唯一决策点 `src/client/titlebar-strip.ts` 纯函数):
- 壳信号(只读,不自动触发修改):URL `dsh-desktop-mode` / `dsh-desktop-platform` / 可选 `dsh-desktop-titlebar-inset`(0–120 clamp)。
- **strip 取值链**:⓪ `web` 方案强制 0;① `navigator.windowControlsOverlay` 真实几何(`wco.ts` 订阅 `geometrychange`,**为 0 也权威**,`visible=false` 幽灵 API 视为缺失);② URL inset;③ 壳预设 `stripFor`(仅 `preset`);④ 手动 `titleBarStripPx`(仅 `custom`);⑤ 0。驱动 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip`。
- **四方案**:`auto`(默认,只信 WCO——"为某壳做的兼容在另一个壳会再坏",核心不做壳专属分支)/ `web`(强制 0)/ `preset`(`src/client/shell-presets.ts`,准入:issue/PR 提及且 GitHub ⭐>100;命中环境显示「已检测」后缀,绝不自动启用)/ `custom`(用户 CSS + 手动 px,齿轮弹窗)。
- 壳信号(只读,不自动触发修改):URL `dsh-desktop-mode`(`compatibility` / `extended` / `advanced`)/ `dsh-desktop-platform` / 可选 `dsh-desktop-titlebar-inset`(0–120 clamp);官方 Electron 壳还会提供**客户端服务** `ctx.desktopWindow`(`mode` / `platform` / `material` / `safeAreaInsets` / `dragRegion`,见 anywhere-labs/dsh-desktop 的 `plugin-services` 文档)。插件侧以结构化镜像探测它(`src/context-types.ts` 的 `SidebarDesktopWindowService` + `src/client/desktop-env.ts` 的 `probeDesktopWindow`),**绝不写进 `dsh.client.inject`**——普通浏览器没有该服务,注入它会让整个插件 pending。
- **strip 取值链**:⓪ `web` 方案强制 0;① **壳自带窗口契约**(`ctx.desktopWindow` 存在时以 `safeAreaInsets.top` 为权威:compatibility / extended 报 0——壳已把整个页面放在自己的 36px frame 之下,插件**不得**再让位一次;advanced 报它画进内容里的 caption 行高度,macOS 20 / win32 32);② `navigator.windowControlsOverlay` 真实几何(`wco.ts` 订阅 `geometrychange`,**为 0 也权威**,`visible=false` 幽灵 API 视为缺失);③ URL inset(**只在壳没提供上面的服务时生效**,即旧壳);④ 壳预设 `stripFor`(仅 `preset`);⑤ 手动 `titleBarStripPx`(仅 `custom`);⑥ 0。驱动 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip`。
- **四方案**:`auto`(默认,保守:壳提供了 `ctx.desktopWindow` 就用壳的真实几何,否则只信 WCO——"为某壳做的兼容在另一个壳会再坏",核心不做壳专属分支)/ `web`(强制 0)/ `preset`(`src/client/shell-presets.ts`,准入:issue/PR 提及且 GitHub ⭐>100;命中环境显示「已检测」后缀,绝不自动启用)/ `custom`(用户 CSS + 手动 px,齿轮弹窗)。
- **迁移**:`titleBarScheme` 无默认值;旧文档已有值(`titleBarCompat === true` 或 `titleBarStripPx` 非 40)→ 迁 `custom`;干净文档 → `auto`。
- **用户空间 CSS**:预设/自定义 css 注入 `<style data-dsh-preset-css|data-dsh-custom-css>` 到 head 末尾(后写胜出;覆盖 JS 内联需 `!important`),fiber 卸载即移除。稳定寻址面:`[data-dsh-toggle-cluster]` / `[data-dsh-panel]` / `[data-dsh-bottom-panel]`。
- **拖拽区退出**:交互 chrome(`.toggleCluster` / `.toggleButton` / `.tabBar`)统一 `-webkit-app-region: no-drag`(无边框壳拖拽带吞点击,#103/#111)。
@@ -34,7 +34,7 @@ better-sidebar 的桌面端适配历史上是"每壳一条补丁":右上角开
### 标准件(`src/client/wco.ts` + `src/client/titlebar-strip.ts`)
- `wco.ts`:模块级反应式 store(subscribe/getSnapshot,`useSyncExternalStore` 消费),特性检测 `navigator.windowControlsOverlay`,订阅 `geometrychange` 重读矩形(最大化/还原实时更新);最后订阅者退订时解绑原生监听;`setWcoSourceForTests` 注入测试源。API 抛错视为 present+0(绝不崩布局)。
- `titlebar-strip.ts`(唯一决策点,纯函数):**⓪ `web` 方案强制 0 → ① WCO 真实高度(权威,0 也权威;`visible=false` 幽灵 API 视为缺失)→ ② URL `dsh-desktop-titlebar-inset`(0–120 clamp)→ ③ 预设 `stripFor`(仅 preset 方案)→ ④ 手动 `titleBarStripPx`(仅 custom 方案)→ ⑤ 0**。结果驱动 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip`(CSS 契约不变)。
- `titlebar-strip.ts`(唯一决策点,纯函数):**⓪ `web` 方案强制 0 → ① WCO 真实高度(权威,0 也权威;`visible=false` 幽灵 API 视为缺失)→ ② URL `dsh-desktop-titlebar-inset`(0–120 clamp)→ ③ 预设 `stripFor`(仅 preset 方案)→ ④ 手动 `titleBarStripPx`(仅 custom 方案)→ ⑤ 0**。结果驱动 `body[data-dsh-title-bar-compat]` + `--dsh-title-bar-strip`(CSS 契约不变)。(2026-10-05 起 ⓪ 与 ① 之间插入「壳自带窗口契约」,见文末实施偏差记录。)
- `desktop-env.ts`:只做环境报告(desktop/mode/platform/titlebarInset),SSR 安全;移除旧 `win32OverlayTop` 硬编码。
### 预设与用户 CSS(`src/client/shell-presets.ts` + `Sidebar.tsx` effect)
@@ -71,6 +71,7 @@ better-sidebar 的桌面端适配历史上是"每壳一条补丁":右上角开
## 实施偏差记录
- 无。计划与实施一致;仅补充:schema 新字段必须无 default 才能让旧文档迁移(否则 settings 服务会把 default 填进解析结果、吞掉迁移),`plugin-shape.spec.ts` 断言了这一点。
- **2026-10-05(issue #864,分支 `fix/864-desktop-window-contract`)**:取值链在 ⓪ 与 ① 之间插入**壳自带窗口契约**——官方 Electron 壳(DSH Desktop 2.x)通过客户端服务 `ctx.desktopWindow` 公布 `safeAreaInsets.top`,插件以结构化镜像探测(`src/context-types.ts` 的 `SidebarDesktopWindowService`、`src/client/desktop-env.ts` 的 `probeDesktopWindow`),**不写进 `dsh.client.inject`**(普通浏览器没有该服务,注入会让插件永远 pending)。壳存在时该值权威:compatibility / extended 报 0(壳已把整个页面放在自己的 36px frame 之下),advanced 报它画进内容的 caption 行(macOS 20 / win32 32);壳不存在时 ②–⑤ 原样保留。`desktop-env.ts` 的 mode 同时接受第三种取值 `extended`(与 compatibility 同几何的独立 frame,**不套用 advanced 的预设顶部值**)。
## 存量 PR/issue 处置(合并后执行,均含哲学声明)
+8 -1
View File
@@ -336,7 +336,11 @@ const DirRow = memo(function DirRow(props: DirRowProps): ReactNode {
style={{ paddingLeft: depth * 22 + 6 }}
// A folded row renders the whole chain (`a/b/c`) and a plain click
// toggles every link at once, so the breadcrumb opens and closes as one.
title={chain.length > 1 ? target.path : undefined}
// EVERY directory row carries its full path here — a single-segment row
// is truncated by the label's ellipsis exactly like the breadcrumb, and
// the body never scrolls horizontally, so the tooltip is the only way to
// read a deep path (the same affordance `FileRow` gives a file).
title={target.path}
onClick={(event) => { actions.activate(event, entry.path, true, chain) }}
onKeyDown={(event: KeyboardEvent<HTMLDivElement>) => {
if (event.key === 'Enter' || event.key === ' ') {
@@ -398,6 +402,9 @@ const RootRow = memo(function RootRow(props: RootRowProps): ReactNode {
<div
className={clsx(css.explorerRow, dropTarget && css.explorerRowDropTarget)}
style={{ paddingLeft: 6 }}
// The root row prints only the workspace folder's BASENAME, so it needs
// the full path on hover like every other row.
title={path}
onDragOver={(event) => { actions.dragOver(event, path) }}
onDrop={(event) => { actions.drop(event, path, true) }}
onContextMenu={(event) => { actions.contextMenu(event, path, true) }}
+34 -6
View File
@@ -41,12 +41,13 @@ import { IconPanelBottomOutline16 } from './icons.tsx'
import { Workbench, type WorkbenchActions } from './split-pane.tsx'
import { useViewportSize } from './breakpoints.ts'
import { bottomPushHeight } from './layout-push.ts'
import { parseDesktopEnv } from './desktop-env.ts'
import { parseDesktopEnv, probeDesktopWindow } from './desktop-env.ts'
import { getWcoSnapshot, subscribeWco } from './wco.ts'
import { getShellPreset } from './shell-presets.ts'
import { computeTitleBarStrip } from './titlebar-strip.ts'
import { TabContent, buildNewTabOptions } from './sidebar/TabContent.tsx'
import { confirmDiscardDraft, dirtyCount, editorDirtyRevision, subscribeEditorDirty } from './editor-dirty.ts'
import { createOpenInApp } from './open-in-app.ts'
import { useCenterColumn } from './sidebar/use-center-column.ts'
import { useHostFeeds } from './sidebar/use-host-feeds.ts'
import { mountedSessions } from './native/surface.ts'
@@ -240,10 +241,11 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
}, [dirtyRevision])
// Title-bar / shell compatibility (the "位置兼容模式" scheme):
// auto — CONSERVATIVE: only the standard Window Controls Overlay
// geometry contributes (the real caption-overlay height,
// reactive to maximize/restore). No URL stamp, no preset, no
// guess — plain browsers see zero modification.
// auto — CONSERVATIVE: the desktop shell's own window contract when it
// publishes one, otherwise only the standard Window Controls
// Overlay geometry contributes (the real caption-overlay
// height, reactive to maximize/restore). No URL stamp, no
// preset, no guess — plain browsers see zero modification.
// preset — an opt-in built-in shell preset (shell-presets.ts) adds its
// per-shell strip as the no-WCO fallback.
// custom — the user's own CSS (injected below) + the legacy manual
@@ -254,6 +256,11 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
// both on unmount/boundary swap so a crashed sidebar never leaves them
// behind.
const desktopEnv = parseDesktopEnv()
// The shell's own geometry contract (absent on a plain browser page and on
// shells that only stamp the URL — see desktop-env.ts). Probed per render:
// it is a plain read of an immutable service, and the sidebar re-renders on
// every session / prefs / viewport change anyway.
const desktopWindow = probeDesktopWindow(ctx)
const wco = useSyncExternalStore(
useMemo(() => subscribeWco, []),
getWcoSnapshot,
@@ -261,7 +268,7 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
const scheme = snapshot.prefs.titleBarScheme
const preset = scheme === 'preset' ? getShellPreset(snapshot.prefs.titleBarPresetId) : undefined
const titleBarStrip = computeTitleBarStrip(
desktopEnv, wco, scheme, preset, snapshot.prefs.titleBarStripPx,
desktopEnv, wco, scheme, preset, snapshot.prefs.titleBarStripPx, desktopWindow,
)
const titleBarCompat = titleBarStrip > 0
useEffect(() => {
@@ -569,6 +576,26 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
referenceInChatShared(ctx, sessionId, path, isDir)
}, [ctx, sessionId])
/**
* The tab context menu's "reveal in the file manager" row. The host's
* open-in-app capability is the ONLY path this plugin reveals through
* (`ctx.remote.session.openWorkspacePath({action:'reveal'})`, shared with
* the explorer's own reveal row via `createOpenInApp`); a deployment
* without a desktop (plain web) answers false, which is logged and
* otherwise a no-op — the bottom panel has no error strip to write to, and
* a failed reveal must never take the strip down. Defined above the
* no-session early return — a hook must never sit behind a conditional
* return (React counts hooks per render).
*/
const openInApp = useMemo(() => createOpenInApp(ctx), [ctx])
const revealTabFile = useCallback((path: string): void => {
void openInApp.reveal(path).then((ok) => {
if (!ok) console.error(`[dsh-better-sidebar] reveal in file manager failed: ${path}`)
}).catch((error: unknown) => {
console.error('[dsh-better-sidebar] reveal in file manager error:', error)
})
}, [openInApp])
if (state === undefined || sessionId === undefined) {
// No conversation yet: the host stays mounted (the drag shield keeps
// covering the region) but nothing is rendered — the toggle button lives
@@ -769,6 +796,7 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) {
getTabIcon={tabIconOf}
getTabBadge={tabBadgeOf}
getTabRightActions={tabRightActionsOf}
onRevealInFileManager={revealTabFile}
/>
</div>
</div>
+33 -5
View File
@@ -5,7 +5,8 @@
* are draggable; dropping onto another tab inserts before it, dropping on the
* strip background appends to this pane. Right-clicking a tab opens the tab
* context menu (close / close others / close to the left / close to the
* right, the close ones scoped to this pane).
* right / close all — every close scoped to this pane — plus reveal the
* right-clicked tab's file in the OS file manager).
*/
import { useEffect, useRef, useState, type ReactNode } from 'react'
import clsx from 'clsx'
@@ -79,9 +80,18 @@ export function TabBar(props: {
* render their own).
*/
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/**
* Reveal one tab's associated file in the OS file manager — the tab
* context menu's reveal row, fed by the shell with the host's open-in-app
* capability. The row is disabled for a tab with no associated file (no
* `path`, e.g. the changes / tasks / side-chat / diff pages) and when the
* shell passes no resolver at all.
*/
onRevealInFileManager?: (path: string) => void
}) {
const {
paneId, tabs, active, onActivate, onClose, onNewTab, newTabOptions, onDropTab, getTabIcon, getTabBadge, getTabRightActions,
onRevealInFileManager,
} = props
const [menuOpen, setMenuOpen] = useState(false)
// The tab right-click context menu: the target tab plus the cursor
@@ -92,6 +102,12 @@ export function TabBar(props: {
// The context target's index in the render-time tab snapshot; -1 when the
// tab disappeared since the menu opened (the menu hides then).
const tabMenuIndex = tabMenu === null ? -1 : tabs.findIndex(tab => tab.id === tabMenu.tabId)
// The context target's associated file: `path` carries it for file tabs
// (editor windows, folder windows included). The changes / tasks /
// side-chat / diff pages have none — a diff's repo-relative ref is not a
// path the host could reveal — so the reveal row greys out for them.
const tabMenuPath = tabs[tabMenuIndex]?.path
const canReveal = onRevealInFileManager !== undefined && tabMenuPath !== undefined && tabMenuPath !== ''
// The active tab's right-actions node, resolved up front so the render
// below can skip the wrapper entirely when there is nothing to show (an
@@ -284,10 +300,12 @@ export function TabBar(props: {
{/*
The tab context menu, positioned at the right-click cursor (portal
so the panel's overflow clip cannot crop it). Close operations are
scoped to THIS pane: "close others/left/right" walk the render-time
tab snapshot and reuse the per-tab onClose path (which routes
through the service), so the target tab is never closed and the
pane never empties mid-loop.
scoped to THIS pane: "close others/left/right/all" walk the
render-time tab snapshot and reuse the per-tab onClose path (which
routes through the service), so every closed tab runs its own
lifecycle and the target tab is only closed by the operations that
mean it (close / close all). "Close all" is always available: the
menu only opens from a tab, so the pane always holds at least one.
*/}
<Menu
open={tabMenu !== null && tabMenuIndex >= 0}
@@ -297,6 +315,8 @@ export function TabBar(props: {
{ id: 'closeOthers', label: t('closeOtherTabs'), ...(tabs.length <= 1 ? { disabled: true } : {}) },
{ id: 'closeLeft', label: t('closeLeftTabs'), ...(tabMenuIndex <= 0 ? { disabled: true } : {}) },
{ id: 'closeRight', label: t('closeRightTabs'), ...(tabMenuIndex >= tabs.length - 1 ? { disabled: true } : {}) },
{ id: 'closeAll', label: t('closeAllTabs') },
{ id: 'revealInFileManager', label: t('revealTabInFileManager'), ...(canReveal ? {} : { disabled: true }) },
]}
onSelect={(id) => {
const target = tabMenu
@@ -314,6 +334,14 @@ export function TabBar(props: {
for (const tab of tabs.slice(0, index)) onClose(tab.id)
} else if (id === 'closeRight') {
for (const tab of tabs.slice(index + 1)) onClose(tab.id)
} else if (id === 'closeAll') {
// EVERY tab in this pane, the right-clicked one included (that
// is what separates it from "close others") and the ones
// scrolled out of the strip's viewport included.
for (const tab of tabs) onClose(tab.id)
} else if (id === 'revealInFileManager') {
const path = tabs[index]?.path
if (path !== undefined && path !== '') onRevealInFileManager?.(path)
}
}}
portal
+62 -10
View File
@@ -6,19 +6,33 @@
* mid-session); `resetDesktopEnvForTests` clears the memo for unit tests.
*
* GEOMETRY POLICY: this module only REPORTS shell facts — it never decides
* how to adapt. The strip height comes from standard signals first (the
* Window Controls Overlay API, see wco.ts), then the documented contract
* parameter `dsh-desktop-titlebar-inset` (a shell may stamp the real pixels
* it reserves at the top), then the user's chosen scheme (preset / custom).
* The legacy win32-advanced 32px constant is gone from the core: it lives
* in the opt-in shell preset (shell-presets.ts) as a fallback for shells
* without the WCO API.
* how to adapt. The strip height comes from the shell's own window contract
* when the shell publishes one (`ctx.desktopWindow` — see
* {@link probeDesktopWindow}), then from standard signals (the Window
* Controls Overlay API, see wco.ts), then the documented contract parameter
* `dsh-desktop-titlebar-inset` (a shell may stamp the real pixels it reserves
* at the top), then the user's chosen scheme (preset / custom). The legacy
* win32-advanced 32px constant is gone from the core: it lives in the opt-in
* shell preset (shell-presets.ts) as a fallback for shells without the WCO
* API.
*/
import type { Context, SidebarDesktopWindowService } from '../context-types.ts'
/** The three presentation modes the official desktop shell documents. */
export type DesktopMode = 'compatibility' | 'extended' | 'advanced'
export interface DesktopEnv {
/** Running inside a desktop shell (any URL stamp or preload marker). */
readonly desktop: boolean
/** `advanced` = frameless/custom-titlebar shell; `compatibility` = native frame. */
readonly mode: 'compatibility' | 'advanced' | null
/**
* `advanced` = the shell draws a compact caption row INTO the web content
* (so the page itself has to yield those pixels);
* `compatibility` / `extended` = the shell keeps a native/framed title bar
* ABOVE the content (compatibility ships the complete upstream frame below
* it, extended hosts the same surfaces itself) — both report a zero content
* inset, i.e. the page starts below chrome the shell already owns.
*/
readonly mode: DesktopMode | null
/** Shell platform stamp ('darwin' | 'win32' | …), lowercased, or null. */
readonly platform: string | null
/**
@@ -45,7 +59,9 @@ export function parseDesktopEnv(): DesktopEnv {
? new URLSearchParams(window.location.search.replace(/^\?/, ''))
: new URLSearchParams()
const modeParam = params.get('dsh-desktop-mode')
const mode = modeParam === 'compatibility' || modeParam === 'advanced' ? modeParam : null
const mode = modeParam === 'compatibility' || modeParam === 'extended' || modeParam === 'advanced'
? modeParam
: null
const platformParam = params.get('dsh-desktop-platform')
const platform = platformParam !== null && platformParam !== '' ? platformParam.toLowerCase() : null
const desktop = mode !== null || hasPreloadMarker
@@ -66,6 +82,42 @@ function parseTitlebarInset(raw: string | null): number {
return Math.min(120, Math.max(0, Math.round(parsed)))
}
/**
* The desktop shell's own window contract (`ctx.desktopWindow`, a CLIENT
* cordis service provided by the official Electron shell — see
* docs/plugin-services of anywhere-labs/dsh-desktop), or undefined on a
* plain browser page.
*
* This is the authority the whole geometry question belongs to: the shell
* reports where IT starts placing the upstream content surface, so a shell
* that already moved the page below its own title bar reports
* `safeAreaInsets.top = 0` there and must NOT be compensated again by the
* plugin's strip (which is what the `dsh-desktop-titlebar-inset` URL stamp
* used to cause — a second 36px of blank space, issue #864).
*
* PROBED, never injected: `dsh.client.inject` treats a missing service as
* "keep this plugin pending", and a plain browser never provides this one —
* listing it would stop the whole plugin from ever mounting. Read at CALL
* time rather than memoized like the URL stamps above: the service is
* published by the shell's own client plugin fiber, so it can legitimately
* be absent on the first read and present later.
*
* @param ctx - client context (any context without a `get` face — a minimal
* test double — resolves to undefined).
* @returns the shell's window service, or undefined when there is none.
*/
export function probeDesktopWindow(ctx: Context): SidebarDesktopWindowService | undefined {
try {
if (typeof ctx.get !== 'function') return undefined
return ctx.get('desktopWindow') as SidebarDesktopWindowService | undefined
} catch (error) {
// Probing is best-effort by contract: an incompatible host leaves the
// caller on the standard-signal chain instead of crashing the render.
console.error('[dsh-better-sidebar] desktop-window probe failed', error)
return undefined
}
}
/**
* Absolute base for the plugin's own host transports — the HTTP routes
* (`/sidebar/api/*`, `/sidebar/file`, `/sidebar/bundle/*`, …) and the
+2
View File
@@ -119,6 +119,8 @@ export const ar: Record<string, string> = {
closeOtherTabs: 'إغلاق التبويبات الأخرى',
closeLeftTabs: 'إغلاق التبويبات على اليسار',
closeRightTabs: 'إغلاق التبويبات على اليمين',
closeAllTabs: 'إغلاق كل التبويبات',
revealTabInFileManager: 'إظهار الملف في مدير الملفات',
pinTerminal: 'تثبيت الطرفية',
pinAgentTerminal: 'تثبيت طرفية Agent',
pinToWorkspace: 'تثبيت إلى مساحة العمل',
+2
View File
@@ -104,6 +104,8 @@ export const de: Record<string, string> = {
closeOtherTabs: 'Andere Tabs schließen',
closeLeftTabs: 'Tabs links schließen',
closeRightTabs: 'Tabs rechts schließen',
closeAllTabs: 'Alle Tabs schließen',
revealTabInFileManager: 'Datei im Dateimanager anzeigen',
pinTerminal: 'Terminal anheften',
pinAgentTerminal: 'Agent-Terminal anheften',
pinToWorkspace: 'An Arbeitsbereich anheften',
+2
View File
@@ -111,6 +111,8 @@ export const fr: Record<string, string> = {
closeOtherTabs: 'Fermer les autres onglets',
closeLeftTabs: 'Fermer les onglets à gauche',
closeRightTabs: 'Fermer les onglets à droite',
closeAllTabs: 'Fermer tous les onglets',
revealTabInFileManager: 'Afficher le fichier dans le gestionnaire de fichiers',
pinTerminal: 'Épingler le terminal',
pinAgentTerminal: 'Épingler le terminal Agent',
pinToWorkspace: 'Épingler à l\'espace de travail',
+2
View File
@@ -118,6 +118,8 @@ export const hi: Record<string, string> = {
closeOtherTabs: 'अन्य टैब बंद करें',
closeLeftTabs: 'बाएँ टैब बंद करें',
closeRightTabs: 'दाएँ टैब बंद करें',
closeAllTabs: 'सभी टैब बंद करें',
revealTabInFileManager: 'फ़ाइल को फ़ाइल मैनेजर में दिखाएँ',
pinTerminal: 'टर्मिनल पिन करें',
pinAgentTerminal: 'Agent टर्मिनल पिन करें',
pinToWorkspace: 'वर्कस्पेस पर पिन करें',
+2
View File
@@ -116,6 +116,8 @@ export const id: Record<string, string> = {
closeOtherTabs: 'Tutup Tab Lain',
closeLeftTabs: 'Tutup Tab di Kiri',
closeRightTabs: 'Tutup Tab di Kanan',
closeAllTabs: 'Tutup Semua Tab',
revealTabInFileManager: 'Tampilkan Berkas di Pengelola Berkas',
pinTerminal: 'Sematkan Terminal',
pinAgentTerminal: 'Sematkan Terminal Agent',
pinToWorkspace: 'Sematkan ke Workspace',
+2
View File
@@ -109,6 +109,8 @@ export const it: Record<string, string> = {
closeOtherTabs: 'Chiudi le altre schede',
closeLeftTabs: 'Chiudi le schede a sinistra',
closeRightTabs: 'Chiudi le schede a destra',
closeAllTabs: 'Chiudi tutte le schede',
revealTabInFileManager: 'Mostra il file nel gestore file',
pinTerminal: 'Blocca Terminale',
pinAgentTerminal: 'Blocca Terminale Agent',
pinToWorkspace: 'Blocca in Workspace',
+2
View File
@@ -118,6 +118,8 @@ export const ja: Record<string, string> = {
closeOtherTabs: '他のタブを閉じる',
closeLeftTabs: '左のタブを閉じる',
closeRightTabs: '右のタブを閉じる',
closeAllTabs: 'すべてのタブを閉じる',
revealTabInFileManager: 'ファイルの場所を開く',
pinTerminal: 'ターミナルを固定',
pinAgentTerminal: 'Agent ターミナルを固定',
pinToWorkspace: 'ワークスペースに固定',
+2
View File
@@ -110,6 +110,8 @@ export const ko: Record<string, string> = {
closeOtherTabs: '다른 탭 닫기',
closeLeftTabs: '왼쪽 탭 닫기',
closeRightTabs: '오른쪽 탭 닫기',
closeAllTabs: '모든 탭 닫기',
revealTabInFileManager: '파일 위치 열기',
pinTerminal: '터미널 고정',
pinAgentTerminal: 'Agent 터미널 고정',
pinToWorkspace: '워크스페이스에 고정',
+2
View File
@@ -116,6 +116,8 @@ export const nl: Record<string, string> = {
closeOtherTabs: 'Andere tabbladen sluiten',
closeLeftTabs: 'Tabbladen links sluiten',
closeRightTabs: 'Tabbladen rechts sluiten',
closeAllTabs: 'Alle tabbladen sluiten',
revealTabInFileManager: 'Bestand tonen in bestandsbeheerder',
pinTerminal: 'Terminal vastmaken',
pinAgentTerminal: 'Agent-terminal vastmaken',
pinToWorkspace: 'Vastmaken aan werkruimte',
+2
View File
@@ -120,6 +120,8 @@ export const pl: Record<string, string> = {
closeOtherTabs: 'Zamknij inne karty',
closeLeftTabs: 'Zamknij karty po lewej',
closeRightTabs: 'Zamknij karty po prawej',
closeAllTabs: 'Zamknij wszystkie karty',
revealTabInFileManager: 'Pokaż plik w menedżerze plików',
pinTerminal: 'Przypnij Terminal',
pinAgentTerminal: 'Przypnij Terminal Agent',
pinToWorkspace: 'Przypnij do obszaru roboczego',
+2
View File
@@ -101,6 +101,8 @@ export const pt: Record<string, string> = {
closeOtherTabs: 'Fechar outras abas',
closeLeftTabs: 'Fechar abas à esquerda',
closeRightTabs: 'Fechar abas à direita',
closeAllTabs: 'Fechar todas as abas',
revealTabInFileManager: 'Mostrar arquivo no gerenciador de arquivos',
pinTerminal: 'Fixar Terminal',
pinAgentTerminal: 'Fixar Terminal do Agent',
pinToWorkspace: 'Fixar no Workspace',
+2
View File
@@ -114,6 +114,8 @@ export const ru: Record<string, string> = {
closeOtherTabs: 'Закрыть остальные вкладки',
closeLeftTabs: 'Закрыть вкладки слева',
closeRightTabs: 'Закрыть вкладки справа',
closeAllTabs: 'Закрыть все вкладки',
revealTabInFileManager: 'Показать файл в файловом менеджере',
pinTerminal: 'Закрепить терминал',
pinAgentTerminal: 'Закрепить терминал Agent',
pinToWorkspace: 'Закрепить в рабочей области',
+2
View File
@@ -101,6 +101,8 @@ export const sv: Record<string, string> = {
closeOtherTabs: 'Stäng andra flikar',
closeLeftTabs: 'Stäng flikar till vänster',
closeRightTabs: 'Stäng flikar till höger',
closeAllTabs: 'Stäng alla flikar',
revealTabInFileManager: 'Visa filen i filhanteraren',
pinTerminal: 'Fäst Terminal',
pinAgentTerminal: 'Fäst Agent-terminal',
pinToWorkspace: 'Fäst på arbetsyta',
+2
View File
@@ -118,6 +118,8 @@ export const th: Record<string, string> = {
closeOtherTabs: 'ปิด Tab อื่น',
closeLeftTabs: 'ปิด Tab ด้านซ้าย',
closeRightTabs: 'ปิด Tab ด้านขวา',
closeAllTabs: 'ปิด Tab ทั้งหมด',
revealTabInFileManager: 'แสดงไฟล์ในตัวจัดการไฟล์',
pinTerminal: 'ปักหมุดเทอร์มินัล',
pinAgentTerminal: 'ปักหมุดเทอร์มินัล Agent',
pinToWorkspace: 'ปักหมุดไปยังพื้นที่ทำงาน',
+2
View File
@@ -118,6 +118,8 @@ export const tr: Record<string, string> = {
closeOtherTabs: 'Diğer sekmeleri kapat',
closeLeftTabs: 'Soldaki sekmeleri kapat',
closeRightTabs: 'Sağdaki sekmeleri kapat',
closeAllTabs: 'Tüm sekmeleri kapat',
revealTabInFileManager: 'Dosyayı dosya yöneticisinde göster',
pinTerminal: 'Terminali Sabitle',
pinAgentTerminal: 'Agent Terminalini Sabitle',
pinToWorkspace: 'Çalışma Alanına Sabitle',
+2
View File
@@ -118,6 +118,8 @@ export const vi: Record<string, string> = {
closeOtherTabs: 'Đóng các tab khác',
closeLeftTabs: 'Đóng tab bên trái',
closeRightTabs: 'Đóng tab bên phải',
closeAllTabs: 'Đóng tất cả tab',
revealTabInFileManager: 'Hiển thị tệp trong trình quản lý tệp',
pinTerminal: 'Ghim Terminal',
pinAgentTerminal: 'Ghim Terminal Agent',
pinToWorkspace: 'Ghim vào Workspace',
+2
View File
@@ -133,6 +133,8 @@ export const zhHK: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+2
View File
@@ -133,6 +133,8 @@ export const zhMO: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+2
View File
@@ -133,6 +133,8 @@ export const zhTW: Record<string, string> = {
closeOtherTabs: '關閉其他標籤',
closeLeftTabs: '關閉左側標籤',
closeRightTabs: '關閉右側標籤',
closeAllTabs: '關閉全部標籤',
revealTabInFileManager: '在檔案總管中定位',
pinTerminal: '固定終端',
pinAgentTerminal: '固定 Agent 終端',
pinToWorkspace: '固定到工作區',
+4
View File
@@ -130,6 +130,8 @@ export const zh = {
closeOtherTabs: '关闭其他页签',
closeLeftTabs: '关闭左侧页签',
closeRightTabs: '关闭右侧页签',
closeAllTabs: '关闭全部页签',
revealTabInFileManager: '在资源管理器中定位',
pinTerminal: '固定终端',
pinAgentTerminal: '固定 Agent 终端',
pinToWorkspace: '固定到工作区',
@@ -696,6 +698,8 @@ export const en: Record<keyof typeof zh, string> = {
closeOtherTabs: 'Close Other Tabs',
closeLeftTabs: 'Close Tabs to the Left',
closeRightTabs: 'Close Tabs to the Right',
closeAllTabs: 'Close All Tabs',
revealTabInFileManager: 'Reveal in File Manager',
pinTerminal: 'Pin Terminal',
pinAgentTerminal: 'Pin Agent Terminal',
pinToWorkspace: 'Pin to Workspace',
+10 -3
View File
@@ -24,8 +24,9 @@ export interface ShellPreset {
readonly desc: string | (() => string)
/**
* The top strip (px) this shell reserves over web content, per
* environment — the fallback used when neither the standard WCO API nor
* the `dsh-desktop-titlebar-inset` contract parameter is available.
* environment — the fallback used when neither the shell's own
* `ctx.desktopWindow` contract, nor the standard WCO API, nor the
* `dsh-desktop-titlebar-inset` contract parameter is available.
* Return undefined when the shell needs no strip in that environment.
* MUST be pure (called during render).
*/
@@ -51,13 +52,19 @@ export interface ShellPreset {
* a 20px caption row (traffic lights top-left), win32 draws the native
* window controls in a ~32px overlay (WCO reports the real height when
* available, which the auto scheme already consumes; the 32 is the
* no-WCO fallback). Compatibility mode keeps the native frame — nothing.
* no-WCO fallback). Compatibility and extended modes keep the shell's own
* frame ABOVE the web content — the shell has already pushed the page below
* it (and, on shells new enough to publish `ctx.desktopWindow`, reports
* `safeAreaInsets.top = 0`), so nothing is due here: the
* `env.mode !== 'advanced'` guard below is what keeps an extended shell from
* inheriting advanced's caption-row value.
*/
const DSH_DESKTOP: ShellPreset = {
id: 'dsh-desktop',
title: 'DeepSeek Harness Desktop',
desc: () => t('presetDshDesktopDesc'),
stripFor: (env) => {
// Advanced only — compatibility / extended own the region themselves.
if (env.mode !== 'advanced') return undefined
if (env.platform === 'darwin') return 20
if (env.platform === 'win32') return 32
+15 -1
View File
@@ -35,6 +35,19 @@
:global([data-dsh-panel-host]) {
position: fixed;
inset: 0;
/* Explicit viewport height — NOT a containing-block derivation (issue
#616). `inset: 0` alone sizes a fixed box from its containing block, and
a page-level `filter` / `backdrop-filter` / `transform` — exactly what a
glass skin puts on the shell wrapper or on <body> itself — REPLACES that
containing block with the ancestor's own padding box. The shell's content
is itself fixed/viewport-sized, so that box is zero-height: the host
collapses to 0px and the whole native right sidebar goes invisible while
its DOM (and every panel in it) is fully present. `vh` is measured
against the viewport instead, so the height survives any ancestor's
containing-block games; the over-constrained triple (top: 0 + height +
bottom: 0) resolves by ignoring `bottom`, keeping this a top-anchored
viewport-height layer. */
height: 100vh;
z-index: 25;
pointer-events: none;
/* Clip at the viewport edge: collapsed panels slide off-screen with
@@ -42,7 +55,8 @@
contributes to its ancestors' scrollable overflow — without this the
hidden panels extended the document's scrollable area, making the whole
page draggable left-right and up-down while any panel was collapsed.
The host is exactly viewport-sized (inset: 0), so the clip is invisible
The host is exactly viewport-sized (inset: 0 + the explicit 100vh
height above), so the clip is invisible
until a panel slides in from the edge; internal scroll containers and
the app's fixed overlay stack are unaffected. `clip`, not `hidden`: a
hidden box stays a PROGRAMMATICALLY scrollable container, and a
+16 -3
View File
@@ -148,8 +148,13 @@ function LeafView(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/**
* Reveal a tab's file in the OS file manager (the tab context menu's
* reveal row; see TabBar). Absent → that row stays disabled.
*/
onRevealInFileManager?: (path: string) => void
}) {
const { leaf, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { leaf, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
const [dropZone, setDropZone] = useState<DropZone | null>(null)
const activeTab = leaf.tabs.find(tab => tab.id === leaf.active) ?? leaf.tabs[leaf.tabs.length - 1]
@@ -206,6 +211,7 @@ function LeafView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
onDropTab={(payload, before) => {
if (before === null) actions.moveTabToEdge(payload, leaf.id, 'center')
else actions.moveTabBefore(payload, leaf.id, before)
@@ -246,8 +252,9 @@ function NodeView(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
onRevealInFileManager?: (path: string) => void
}) {
const { node, state, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { node, state, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
if (node.kind === 'leaf') {
return (
<LeafView
@@ -259,6 +266,7 @@ function NodeView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
)
}
@@ -287,6 +295,7 @@ function NodeView(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
</div>
</Fragment>
@@ -309,8 +318,11 @@ export function Workbench(props: {
getTabIcon?: (tab: SidebarTab) => ReactNode
getTabBadge?: (tab: SidebarTab) => ReactNode
getTabRightActions?: (tab: SidebarTab, paneId: string) => ReactNode
/** Reveal a tab's file in the OS file manager (see TabBar); absent → the
* tab context menu's reveal row is disabled. */
onRevealInFileManager?: (path: string) => void
}) {
const { state, tree, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions } = props
const { state, tree, newTabOptions, actions, onNewTab, renderTab, getTabIcon, getTabBadge, getTabRightActions, onRevealInFileManager } = props
return (
<div className={css.workbench}>
<NodeView
@@ -323,6 +335,7 @@ export function Workbench(props: {
getTabIcon={getTabIcon}
getTabBadge={getTabBadge}
getTabRightActions={getTabRightActions}
onRevealInFileManager={onRevealInFileManager}
/>
</div>
)
+22 -6
View File
@@ -5,13 +5,20 @@
*
* 0. `web` scheme — EXPLICIT "DSH official web": never adapt, not even
* standard WCO geometry (the user declares the plain web UI).
* 1. Window Controls Overlay real geometry (standard API, authoritative
* 1. The desktop shell's own window contract (`ctx.desktopWindow`, see
* desktop-env.ts) — authoritative when present: `safeAreaInsets.top` is
* where the SHELL starts placing the content, so it already accounts for
* everything the shell reserved. This is what keeps a shell that moved
* the page below its own title bar (compatibility / extended, inset 0)
* from being compensated a second time by the URL stamp below.
* 2. Window Controls Overlay real geometry (standard API, authoritative
* when present — even 0, e.g. the overlay is hidden while maximized).
* 2. The `dsh-desktop-titlebar-inset` URL contract parameter (a shell
* declares the exact pixels it reserves).
* 3. The active shell preset's strip (scheme `preset` — opt-in data).
* 4. The legacy manual `titleBarStripPx` (scheme `custom`).
* 5. 0 — plain-browser semantics, nothing modified.
* 3. The `dsh-desktop-titlebar-inset` URL contract parameter (a shell
* declares the exact pixels it reserves) — only for shells old enough
* not to publish the service above.
* 4. The active shell preset's strip (scheme `preset` — opt-in data).
* 5. The legacy manual `titleBarStripPx` (scheme `custom`).
* 6. 0 — plain-browser semantics, nothing modified.
*
* The result drives `--dsh-title-bar-strip` + `body[data-dsh-title-bar-compat]`
* exactly like the legacy boolean did; only the VALUE source changed.
@@ -19,6 +26,7 @@
import type { DesktopEnv } from './desktop-env.ts'
import type { TitleBarScheme } from '../prefs-shared.ts'
import type { WcoSnapshot } from './wco.ts'
import type { SidebarDesktopWindowService } from '../context-types.ts'
import { presetStripFor, type ShellPreset } from './shell-presets.ts'
export function computeTitleBarStrip(
@@ -27,8 +35,16 @@ export function computeTitleBarStrip(
scheme: TitleBarScheme,
preset: ShellPreset | undefined,
customStripPx: number,
desktopWindow?: SidebarDesktopWindowService | undefined,
): number {
if (scheme === 'web') return 0
// The shell's own contract outranks every signal below, including a URL
// stamp the shell itself published: the stamp is the shell's OWN reserve,
// and the shell's `safeAreaInsets.top` is that reserve already applied.
// A service without a usable `top` (an older/incompatible host) falls
// through to the standard chain instead of throwing mid-render.
const shellTop = desktopWindow?.safeAreaInsets?.top
if (typeof shellTop === 'number' && Number.isFinite(shellTop)) return shellTop
if (wco.present) return wco.height
if (env.titlebarInset > 0) return env.titlebarInset
if (scheme === 'preset') return presetStripFor(preset, env) ?? 0
+45
View File
@@ -626,6 +626,51 @@ export interface SidebarConversation {
}
}
/** Insets (CSS px) the desktop shell reserved for its own native chrome. */
export interface SidebarDesktopWindowInsets {
readonly top: number
readonly right: number
readonly bottom: number
readonly left: number
}
/** The shell's top caption hit-region (drag band + excluded native controls). */
export interface SidebarDesktopWindowDragRegion {
readonly height: number
readonly leftInset: number
readonly rightInset: number
}
/**
* The desktop shell's native-window geometry contract (`ctx.desktopWindow`,
* a CLIENT cordis service of the official Electron shell; see its
* docs/plugin-services). Mirrored structurally — like every other service
* face here — because the plugin must not value-import `dsh-plugin-desktop`
* (and the package is dev-time absent anyway).
*
* The service is OPTIONAL: a plain browser never provides it, so it is
* probed through {@link ./client/desktop-env.ts} rather than listed in
* `dsh.client.inject` (a missing inject dependency would keep the whole
* client plugin pending forever). Only `safeAreaInsets.top` is consumed
* today (the strip the sidebar yields at the top); the remaining fields are
* mirrored to keep the contract legible at the probe site.
*/
export interface SidebarDesktopWindowService {
/**
* `compatibility` / `extended` = the shell owns a frame ABOVE the content
* (both report a zero content inset); `advanced` = a compact caption row
* is drawn INTO the content (as of upstream master both darwin and win32 report 32; Linux 0 — always trust the shell's reported value).
*/
readonly mode: 'compatibility' | 'extended' | 'advanced'
readonly platform: 'darwin' | 'win32' | 'linux'
/** Capability-gated native material behind the renderer. */
readonly material: 'off' | 'transparent'
/** Where the shell starts placing the upstream content surface. */
readonly safeAreaInsets: SidebarDesktopWindowInsets
/** Native caption hit region; interactive children must opt out of dragging. */
readonly dragRegion: SidebarDesktopWindowDragRegion
}
/** Read-only subset of api-workspace-controller's public IWorkspaces.list. */
export interface SidebarWorkspacesService {
readonly list: {
+62 -6
View File
@@ -1,14 +1,17 @@
/**
* Desktop-shell detection tests: URL stamps (dsh-desktop-mode/platform)
* from the official Electron shell, the preload marker
* (__DSH_DESKTOP_FILE_PATH__), and the `dsh-desktop-titlebar-inset`
* contract parameter. Geometry ADAPTATION is deliberately NOT here — the
* strip resolution chain lives in titlebar-strip.ts (standard WCO first,
* see wco.spec.ts), keeping this module a pure environment reporter.
* (__DSH_DESKTOP_FILE_PATH__), the `dsh-desktop-titlebar-inset` contract
* parameter, and the shell's own window service probe
* (`ctx.desktopWindow` — see titlebar-strip.spec.ts for how the chain
* consumes it). Geometry ADAPTATION is deliberately NOT here — the strip
* resolution chain lives in titlebar-strip.ts (standard WCO first, see
* wco.spec.ts), keeping this module a pure environment reporter.
*/
import { beforeEach, describe, expect, it } from 'vitest'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import './browser-globals.ts'
import { parseDesktopEnv, resetDesktopEnvForTests } from '../src/client/desktop-env.ts'
import { parseDesktopEnv, probeDesktopWindow, resetDesktopEnvForTests } from '../src/client/desktop-env.ts'
import type { Context, SidebarDesktopWindowService } from '../src/context-types.ts'
function setSearch(search: string): void {
;(window.location as { search: string }).search = search
@@ -50,6 +53,21 @@ describe('parseDesktopEnv', () => {
expect(env.titlebarInset).toBe(0)
})
it('parses extended mode — the shell-owned 36px frame with compatibility geometry', () => {
// Extended window (DSH Desktop 2.x): the shell hosts the upstream
// surfaces below its OWN frame, exactly like compatibility — the mode is
// not an unknown value, and must not be read as `advanced` (whose preset
// strip would reserve the caption row a second time).
setSearch('?dsh-desktop-mode=extended&dsh-desktop-platform=darwin&dsh-desktop-titlebar-inset=36')
const env = parseDesktopEnv()
expect(env.desktop).toBe(true)
expect(env.mode).toBe('extended')
expect(env.platform).toBe('darwin')
// The stamp is still REPORTED verbatim: it is the shell's own reserve
// (the strip chain ignores it only because the window service exists).
expect(env.titlebarInset).toBe(36)
})
it('detects the desktop preload marker even without URL stamps', () => {
;(window as unknown as Record<string, unknown>).__DSH_DESKTOP_FILE_PATH__ = { getPathForFile: () => '' }
const env = parseDesktopEnv()
@@ -87,3 +105,41 @@ describe('parseDesktopEnv', () => {
expect(parseDesktopEnv().desktop).toBe(false)
})
})
describe('probeDesktopWindow', () => {
const service: SidebarDesktopWindowService = {
mode: 'extended',
platform: 'win32',
material: 'off',
safeAreaInsets: { top: 0, right: 0, bottom: 0, left: 0 },
dragRegion: { height: 0, leftInset: 0, rightInset: 0 },
}
/** A client context whose `get` answers one service name. */
const ctxWith = (name: string, value: unknown): Context => ({
get: (asked: string): unknown => asked === name ? value : undefined,
}) as unknown as Context
it('returns the shell service the client context publishes', () => {
expect(probeDesktopWindow(ctxWith('desktopWindow', service))).toBe(service)
})
it('returns undefined on a plain browser page (the service is never injected)', () => {
expect(probeDesktopWindow(ctxWith('desktopWindow', undefined))).toBeUndefined()
expect(probeDesktopWindow({} as Context)).toBeUndefined()
})
it('stays best-effort when the context getter throws', () => {
const ctx: Context = {
get: (): never => { throw new Error('cannot get property without inject') },
} as unknown as Context
const logged = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
expect(probeDesktopWindow(ctx)).toBeUndefined()
// Assert inside the spy's lifetime: mockRestore also clears the calls.
expect(logged).toHaveBeenCalledTimes(1)
} finally {
logged.mockRestore()
}
})
})
+139
View File
@@ -0,0 +1,139 @@
/**
* The desktop shell's window contract must reach the DOM, not just the pure
* chain (issue #430).
*
* `computeTitleBarStrip` is covered field by field in titlebar-strip.spec.ts;
* what this file adds is the WIRING, which is where the regression actually
* lived: the shell places the whole page below its own 36px frame and
* publishes `safeAreaInsets.top = 0` through `ctx.desktopWindow`, yet still
* stamps the render URL with `dsh-desktop-titlebar-inset=36`. If the Sidebar
* never hands the service to the chain, that stamp wins and every panel gets
* a second 36px blank strip at the top (`body[data-dsh-title-bar-compat]` +
* `--dsh-title-bar-strip: 36px`).
*
* Rendered with the REAL Sidebar + real store/service against a minimal fake
* context (the repo's jsdom mount pattern), so the assertion is on the
* document state the CSS actually consumes.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { Sidebar } from '../src/client/Sidebar.tsx'
import { createSidebarStore } from '../src/client/state.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
import { resetDesktopEnvForTests } from '../src/client/desktop-env.ts'
import type { Context, SidebarDesktopWindowService } from '../src/context-types.ts'
const shell = (mode: SidebarDesktopWindowService['mode'], top: number): SidebarDesktopWindowService => ({
mode,
platform: 'win32',
material: 'off',
safeAreaInsets: { top, right: 0, bottom: 0, left: 0 },
dragRegion: { height: top, leftInset: 0, rightInset: 0 },
})
/**
* Mount the real sidebar on a desktop-shell URL.
* @param search - the render URL's query (the shell's own stamps).
* @param desktopWindow - the service `ctx.get('desktopWindow')` answers, or
* undefined for a shell that does not publish one.
*/
function mount(search: string, desktopWindow: SidebarDesktopWindowService | undefined): { unmount: () => void } {
window.history.replaceState({}, '', `/${search}`)
resetDesktopEnvForTests()
// jsdom has no WebSocket; the panel's host feeds construct one on mount.
vi.stubGlobal('WebSocket', class { close(): void {} })
const store = createSidebarStore()
store.setSession('s1')
const service = createBetterSidebarService(store)
// useSyncExternalStore requires STABLE snapshots across calls (the real DSH
// services return stable objects) — a fresh object per call loops forever.
const locale = { active: 'en' }
const sessions = { byId: { s1: { id: 's1', cwd: '/ws' } } }
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => locale },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessions } },
get: (name: string) => name === 'betterSidebar' ? service : name === 'desktopWindow' ? desktopWindow : undefined,
}
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as unknown as Context, store })) })
return {
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
}
}
/** The strip the plugin applied to the page, as the CSS reads it. */
function appliedStrip(): { compat: boolean; px: string } {
return {
compat: document.body.hasAttribute('data-dsh-title-bar-compat'),
px: document.documentElement.style.getPropertyValue('--dsh-title-bar-strip'),
}
}
afterEach(() => {
document.body.innerHTML = ''
document.body.removeAttribute('data-dsh-title-bar-compat')
document.documentElement.style.removeProperty('--dsh-title-bar-strip')
vi.unstubAllGlobals()
resetDesktopEnvForTests()
})
describe('the shell window contract drives the applied strip', () => {
it('compatibility + URL inset 36 + contract top 0 → no strip at all', () => {
const view = mount(
'?dsh-desktop-mode=compatibility&dsh-desktop-platform=win32&dsh-desktop-titlebar-inset=36',
shell('compatibility', 0),
)
try {
expect(appliedStrip()).toEqual({ compat: false, px: '' })
} finally {
view.unmount()
}
})
it('extended + URL inset 36 + contract top 0 → no strip at all', () => {
const view = mount(
'?dsh-desktop-mode=extended&dsh-desktop-platform=darwin&dsh-desktop-titlebar-inset=36',
shell('extended', 0),
)
try {
expect(appliedStrip()).toEqual({ compat: false, px: '' })
} finally {
view.unmount()
}
})
it('advanced + contract top 32 → the caption row is yielded', () => {
const view = mount(
'?dsh-desktop-mode=advanced&dsh-desktop-platform=win32',
shell('advanced', 32),
)
try {
expect(appliedStrip()).toEqual({ compat: true, px: '32px' })
} finally {
view.unmount()
}
})
it('no service (plain browser / older shell) → the URL stamp chain is unchanged', () => {
const view = mount(
'?dsh-desktop-mode=compatibility&dsh-desktop-platform=win32&dsh-desktop-titlebar-inset=36',
undefined,
)
try {
expect(appliedStrip()).toEqual({ compat: true, px: '36px' })
} finally {
view.unmount()
}
})
})
+233
View File
@@ -0,0 +1,233 @@
/**
* Explorer row hover titles (#186): a deep path must stay readable.
*
* The tree body never scrolls horizontally on purpose (`.explorerBody` is
* `overflow-x: hidden`) and every label is ellipsised, so a row's `title` is
* the ONLY way to read where it really points. File rows always had one; the
* directory rows did not — the ordinary (single-segment) directory row and the
* workspace root row rendered no `title` at all, and the folded breadcrumb row
* only got one when it had more than one link. This spec drives the real tree
* through the jsdom harness the other file-tree specs use and pins the tooltip
* of EVERY render path, so no row can silently regress to `undefined`.
*/
// @vitest-environment jsdom
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import { createElement } from 'react'
import { createRoot, type Root } from 'react-dom/client'
import { act } from 'react-dom/test-utils'
import { FileTree } from '../src/client/FileTree.tsx'
import css from '../src/client/sidebar.module.css'
import { setupReactAct } from './test-utils.ts'
setupReactAct()
// vitest 4.1.11+ follows the OS locale; pin en-US so the copy is English.
beforeAll(() => {
Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true })
})
const ROOT = '/tmp/ws'
const fsTrees = vi.hoisted(() => vi.fn())
vi.mock('../src/client/api.ts', () => ({
api: {
fsTree: vi.fn(),
fsTrees: (...args: unknown[]) => fsTrees(...args),
gitStatus: async () => ({ isRepo: false, entries: [] }),
},
downloadUrl: () => '/sidebar/file',
isOutsideWorkspaceMessage: () => false,
}))
interface Row {
name: string
path: string
isDir: boolean
hidden: boolean
isSymlink: boolean
broken: boolean
compact?: boolean
}
/** A directory row; `compact` is the host's singleton mark (fold chains). */
function dir(path: string, compact = false): Row {
const name = path.slice(path.lastIndexOf('/') + 1)
return {
name,
path,
isDir: true,
hidden: name.startsWith('.'),
isSymlink: false,
broken: false,
...(compact ? { compact: true } : {}),
}
}
/** A file row. */
function file(path: string, broken = false): Row {
const name = path.slice(path.lastIndexOf('/') + 1)
return { name, path, isDir: false, hidden: name.startsWith('.'), isSymlink: broken, broken }
}
/**
* `ws/` holds a PLAIN directory (chain of one — the row that used to render no
* title), a singleton chain `a` → `a/b` (folded into one breadcrumb row), a
* regular file and a broken symlink (the file row's conditional wording).
*/
function levelOf(path: string): { path: string; entries: Row[]; truncated: boolean } {
switch (path) {
case ROOT:
return { path, entries: [
dir('/tmp/ws/plain'),
dir('/tmp/ws/a', true),
file('/tmp/ws/readme.md'),
file('/tmp/ws/dangling', true),
], truncated: false }
case '/tmp/ws/a':
return { path, entries: [dir('/tmp/ws/a/b', true)], truncated: false }
default:
return { path, entries: [file(`${path}/leaf.txt`)], truncated: false }
}
}
/** The smallest WebSocket the directory watcher talks to. */
class FakeSocket {
static readonly OPEN = 1
static readonly CONNECTING = 0
readyState = FakeSocket.CONNECTING
onopen: (() => void) | null = null
onmessage: ((event: { data: string }) => void) | null = null
onclose: (() => void) | null = null
constructor(readonly url: string) {}
send(): void {}
close(): void { this.readyState = 3 }
}
interface Harness {
container: HTMLDivElement
unmount: () => void
}
function mountTree(): Harness {
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => {
root.render(createElement(FileTree, {
sessionId: 's1',
cwd: ROOT,
expanded: [],
revealed: [],
onToggle: () => {},
onOpenFile: () => {},
onReferenceFile: () => {},
refreshTick: 0,
onUploadRequest: () => {},
busy: false,
}))
})
return { container, unmount: () => { act(() => { root.unmount() }); container.remove() } }
}
/** Flush the batch promise chain (the level cache fill + fold preload). */
async function flush(): Promise<void> {
await act(async () => {
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
await Promise.resolve()
})
}
/** Every tree row in document order — root row first, then the level's rows. */
function rows(container: HTMLElement): HTMLElement[] {
return [...container.querySelectorAll<HTMLElement>(`.${css.explorerRow}`)]
}
/** A row's own LABEL (the name span), never the trailing "Reference file" button. */
function labelOf(row: HTMLElement): string {
return row.querySelector(`.${css.explorerName}`)?.textContent ?? ''
}
/** The row rendering `label` (labels are unique in this fixture). */
function rowByLabel(container: HTMLElement, label: string): HTMLElement {
const row = rows(container).find(candidate => labelOf(candidate) === label)
if (row === undefined) throw new Error(`no row "${label}" in ${JSON.stringify(rows(container).map(labelOf))}`)
return row
}
/** One row's tooltip (`null` when the row carries none — the old bug). */
function titleOf(container: HTMLElement, label: string): string | null {
return rowByLabel(container, label).getAttribute('title')
}
let harness: Harness
beforeEach(() => {
vi.stubGlobal('WebSocket', FakeSocket)
fsTrees.mockReset()
fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({
levels: paths.map(path => levelOf(path)),
}))
})
afterEach(() => {
harness.unmount()
document.body.innerHTML = ''
vi.unstubAllGlobals()
})
describe('FileTree row hover titles', () => {
it('titles a plain directory row with its full path, not the truncated label', async () => {
harness = mountTree()
await flush()
// The row only PRINTS the basename (ellipsised when long)…
expect(labelOf(rowByLabel(harness.container, 'plain'))).toBe('plain')
// …so the tooltip carries the whole path (this was `undefined`).
expect(titleOf(harness.container, 'plain')).toBe('/tmp/ws/plain')
})
it('titles a folded breadcrumb row with the chain tail it renders', async () => {
harness = mountTree()
await flush()
// `a` folds through its singleton dir child: one `a/b` row.
expect(labelOf(rowByLabel(harness.container, 'a/b'))).toBe('a/b')
expect(titleOf(harness.container, 'a/b')).toBe('/tmp/ws/a/b')
})
it('titles the workspace root row with the full workspace path', async () => {
harness = mountTree()
await flush()
// The root row prints only the folder's basename (`ws`)…
expect(labelOf(rowByLabel(harness.container, 'ws'))).toBe('ws')
// …and now names the whole path like every other row.
expect(titleOf(harness.container, 'ws')).toBe(ROOT)
})
it('leaves file rows as they were: full path, broken symlink wording kept', async () => {
harness = mountTree()
await flush()
expect(titleOf(harness.container, 'readme.md')).toBe('/tmp/ws/readme.md')
// The file row's existing conditional wording survives untouched.
expect(titleOf(harness.container, 'dangling')).toBe('/tmp/ws/dangling — Broken symlink')
})
it('leaves no rendered row without a title', async () => {
harness = mountTree()
await flush()
const titled = rows(harness.container)
.map(row => `${labelOf(row)} → ${row.getAttribute('title') ?? '<none>'}`)
expect(titled).toEqual([
'ws → /tmp/ws',
'plain → /tmp/ws/plain',
'a/b → /tmp/ws/a/b',
'readme.md → /tmp/ws/readme.md',
'dangling → /tmp/ws/dangling — Broken symlink',
])
})
})
+20
View File
@@ -37,6 +37,26 @@ describe('panel host layer css', () => {
expect(hostRule).toMatch(/inset:\s*0/)
})
it('pins an explicit viewport height, never a containing-block derivation (#616)', () => {
// `inset: 0` alone sizes a fixed box from its CONTAINING BLOCK, and a
// page-level `filter` / `backdrop-filter` / `transform` — exactly what a
// glass skin puts on the shell wrapper or on <body> itself — REPLACES
// that containing block with the ancestor's own padding box. The shell's
// content is itself fixed/viewport-sized, so that box is zero-height: the
// host collapses to 0px and the entire native right sidebar goes
// invisible while its DOM (and every panel inside) is fully present.
// `vh` resolves against the viewport, so the explicit height survives the
// swap; `auto` / `100%` do not, which is what this pin rejects.
expect(hostRule, 'the [data-dsh-panel-host] rule must exist').toBeDefined()
const heights = stripComments(hostRule!).match(/(?:^|[;{])\s*height\s*:\s*[^;}]+/g) ?? []
// Pin the WHOLE list, not the first hit: a second, later `height`
// (`auto` / `100%`) would win the cascade and silently restore the
// collapse. Sub-properties (`max-height`, `line-height`) do not match.
expect(
heights.map((declaration) => declaration.replace(/^[;{]\s*/, '').replace(/\s+/g, ' ').trim()),
).toEqual(['height: 100vh'])
})
it('does not reintroduce overflow on the degraded (absolute) layer', () => {
const degraded = css.match(
/:global\(\[data-dsh-panel-host\]\[data-dsh-panel-host-degraded\]\) \{([\s\S]*?)\n\}/,
+14 -2
View File
@@ -2,8 +2,8 @@
* Built-in shell-preset data tests: registry integrity (unique ids, non-empty
* titles, non-empty localized descs, pure strip/detect functions) and the
* anywhere-labs DSH Desktop entry's strip values (darwin advanced 20px,
* win32 advanced 32px as the no-WCO fallback, compatibility/plain browser
* nothing).
* win32 advanced 32px as the no-WCO fallback, compatibility / extended /
* plain browser nothing).
*/
import { describe, expect, it } from 'vitest'
import { getShellPreset, getShellPresets, presetStripFor } from '../src/client/shell-presets.ts'
@@ -65,6 +65,18 @@ describe('shell presets', () => {
expect(presetStripFor(preset, env({ desktop: false, mode: null, platform: null }))).toBeUndefined()
})
it('reserves nothing in EXTENDED mode either — the caption row is advanced-only', () => {
// Extended is a third presentation mode (DSH Desktop 2.x): the shell
// hosts the surfaces below its own 36px frame, exactly like
// compatibility, and reports a zero content inset through
// `ctx.desktopWindow`. Inheriting advanced's caption-row values here
// would be the very double reservation issue #430 is about.
expect(presetStripFor(preset, env({ desktop: true, mode: 'extended', platform: 'darwin' }))).toBeUndefined()
expect(presetStripFor(preset, env({ desktop: true, mode: 'extended', platform: 'win32' }))).toBeUndefined()
// ... and the settings badge must not SUGGEST the preset there either.
expect(preset.detect?.(env({ desktop: true, mode: 'extended', platform: 'win32' }))).toBe(false)
})
it('detects advanced shells only as a SUGGESTION signal (never auto-applies)', () => {
expect(preset.detect?.(env({ desktop: true, mode: 'advanced', platform: 'darwin' }))).toBe(true)
expect(preset.detect?.(env({ desktop: true, mode: 'advanced', platform: 'win32' }))).toBe(true)
+63 -8
View File
@@ -57,12 +57,37 @@ interface MountedSidebar {
unmount: () => void
}
/** Roots still mounted when a test ends. `afterEach` unmounts them: wiping the
* DOM without unmounting leaves every effect cleanup un-run, and the 1s
* `session.phase` poller in `session-phase.ts` then outlives the test — it
* fires after jsdom is gone, React reads a missing `window` and the whole run
* is red on `Errors 1` even though every test passed. */
const mountedRoots: Array<() => void> = []
/** Intervals created while a test runs. `session-phase.ts` polls through
* `setInterval`; a live id here after the roots are unmounted means some
* effect leaked a timer (see `mountedRoots`). */
const liveIntervals = new Set<ReturnType<typeof setInterval>>()
/** Mount the real Sidebar shell against a minimal context (real store + service). */
/** Unique per-test session ids (see the comment inside). */
let sessionSeq = 0
function mountSidebar(): MountedSidebar {
vi.stubGlobal('WebSocket', FakeWebSocket)
// The real timers, wrapped so `afterEach` can prove nothing outlived the
// test (vi.unstubAllGlobals restores both).
const realSetInterval = globalThis.setInterval
const realClearInterval = globalThis.clearInterval
vi.stubGlobal('setInterval', ((handler: never, timeout?: number) => {
const id = realSetInterval(handler, timeout)
liveIntervals.add(id)
return id
}) as never)
vi.stubGlobal('clearInterval', ((id: never) => {
liveIntervals.delete(id)
realClearInterval(id)
}) as never)
const container = document.createElement('div')
document.body.append(container)
const store = createSidebarStore()
@@ -96,18 +121,30 @@ function mountSidebar(): MountedSidebar {
}
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
return {
container,
store,
service,
unmount: () => {
act(() => { root.unmount() })
container.remove()
},
// Idempotent: a test may unmount explicitly, and afterEach unmounts whatever
// is left (calling React's unmount twice throws).
let unmounted = false
const unmount = (): void => {
if (unmounted) return
unmounted = true
act(() => { root.unmount() })
container.remove()
}
mountedRoots.push(unmount)
return { container, store, service, unmount }
}
afterEach(() => {
// Unmount FIRST: that is what runs the effects' cleanups, and the cleanups
// are what clear the pollers. Wiping the DOM instead (the old harness) left
// them armed and reddened CI with `window is not defined`.
for (const unmount of mountedRoots.splice(0).reverse()) unmount()
const leaked = liveIntervals.size
liveIntervals.clear()
expect(
leaked,
'every interval started by a test must be cleared before it ends — an armed one fires after jsdom is torn down',
).toBe(0)
document.body.innerHTML = ''
// Belt and braces: drop any persisted layout a pending 200ms debounce
// write left behind between tests (unique session ids already isolate).
@@ -115,6 +152,24 @@ afterEach(() => {
vi.unstubAllGlobals()
})
describe('test harness', () => {
// The leak guard itself lives in `afterEach` (no interval may outlive a
// test). A poll that never settles keeps the 1s `session.phase` interval
// armed from mount to the end of the test — which is exactly the state the
// old harness (wipe the DOM, never unmount) leaked past teardown: the timer
// fired after jsdom was gone, React read a missing `window`, and an
// all-green run went red on `Errors 1`. The assertion below proves the
// armed state was really reached, so this test cannot pass vacuously.
it('arms the session-phase poller, so afterEach has something to clear', () => {
vi.stubGlobal('fetch', () => new Promise(() => {}))
mountSidebar()
expect(
liveIntervals.size,
'the hanging route must leave the poller armed',
).toBeGreaterThan(0)
})
})
describe('layout-push variable cleanup', () => {
it('clears --dsh-sidebar-height when the sidebar unmounts (and never pushes a width)', () => {
const { unmount } = mountSidebar()
+231 -20
View File
@@ -1,13 +1,17 @@
/**
* Tab-strip right-click context-menu tests. Right-clicking a tab takes over
* the browser menu (preventDefault) and shows the tab context menu with
* exactly five items: move to free window / close / close others / close to
* the left / close to the right. All bulk operations are scoped to the
* CURRENT pane (the render time tab snapshot) and reuse the per-tab onClose
* path, so the target tab is never closed and the pane never empties
* mid-loop. The menu items gray out when there is nothing to close (single
* tab → close others; leftmost → close left; rightmost → close right).
* Opening the menu must not activate the right-clicked tab.
* exactly six items: close / close others / close to the left / close to the
* right / close all / reveal in the file manager. All close operations are
* scoped to the CURRENT pane (the render-time tab snapshot) and reuse the
* per-tab onClose path, so every closed tab keeps its own lifecycle and the
* pane never empties mid-loop; "close all" is the one that closes the
* right-clicked tab too. The reveal row hands the tab's associated file
* (`path`, i.e. an editor window) to the shell's reveal resolver and is
* disabled for a tab that has none. Menu rows gray out when there is nothing
* to do (single tab → close others; leftmost → close left; rightmost → close
* right; no file → reveal). Opening the menu must not activate the
* right-clicked tab.
*/
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -20,7 +24,10 @@ import { setupReactAct } from './test-utils.ts'
setupReactAct()
import { TabBar } from '../src/client/TabBar.tsx'
import type { SidebarTab } from '../src/client/state.ts'
import { Sidebar } from '../src/client/Sidebar.tsx'
import { Workbench } from '../src/client/split-pane.tsx'
import { createSidebarStore, makeDefaultState, type SidebarState, type SidebarTab } from '../src/client/state.ts'
import { createBetterSidebarService } from '../src/client/service.ts'
/** Point the browser-language fallback at Chinese so the menu labels assert. */
function stubZh(): void {
@@ -30,20 +37,27 @@ function stubZh(): void {
})
}
const MENU_LABELS = ['关闭', '关闭其他页签', '关闭左侧页签', '关闭右侧页签']
const MENU_LABELS = [
'关闭', '关闭其他页签', '关闭左侧页签', '关闭右侧页签', '关闭全部页签', '在资源管理器中定位',
]
function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope: 'workspace' | 'global' | null) => void } = {}): {
function mountBar(tabs: SidebarTab[], opts: {
/** Omit the reveal resolver (the shell always passes one; this pins the
* disabled-without-resolver half of the contract). */
noRevealResolver?: boolean
} = {}): {
tabEls: HTMLElement[]
onClose: ReturnType<typeof vi.fn>
onActivate: ReturnType<typeof vi.fn>
onPinTab?: (tabId: string, scope: 'workspace' | 'global' | null) => void
/** The reveal resolver the strip was given (undefined when omitted). */
onRevealInFileManager?: ReturnType<typeof vi.fn>
unmount: () => void
} {
const container = document.createElement('div')
document.body.append(container)
const onClose = vi.fn()
const onActivate = vi.fn()
const onPinTab = opts.onPinTab
const onRevealInFileManager = opts.noRevealResolver === true ? undefined : vi.fn()
const root: Root = createRoot(container)
act(() => {
root.render(createElement(TabBar, {
@@ -54,7 +68,7 @@ function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope:
onClose,
onNewTab: () => {},
newTabOptions: [],
...(onPinTab !== undefined ? { onPinTab } : {}),
...(onRevealInFileManager === undefined ? {} : { onRevealInFileManager }),
onDropTab: () => {},
}))
})
@@ -63,7 +77,7 @@ function mountBar(tabs: SidebarTab[], opts: { onPinTab?: (tabId: string, scope:
tabEls,
onClose,
onActivate,
...(onPinTab !== undefined ? { onPinTab } : {}),
...(onRevealInFileManager === undefined ? {} : { onRevealInFileManager }),
unmount: () => {
act(() => { root.unmount() })
container.remove()
@@ -80,6 +94,14 @@ function fourTabs(): SidebarTab[] {
]
}
/** Two tabs where only the first carries a file (an editor window). */
function fileTabs(): SidebarTab[] {
return [
{ id: 'f1', type: 'editor', title: 'a.ts', path: '/repo/src/a.ts' },
{ id: 'f2', type: 'git', title: 'Changes' },
]
}
/** Dispatch a native right-click (contextmenu) and return the event. */
function rightClick(target: EventTarget): MouseEvent {
const event = new MouseEvent('contextmenu', { bubbles: true, cancelable: true, clientX: 120, clientY: 40 })
@@ -92,13 +114,20 @@ function menuItems(): HTMLElement[] {
return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')]
}
/** The disabled flags of the portaled rows, in menu order. */
function menuDisabled(): boolean[] {
return menuItems().map(item => (item as HTMLButtonElement).disabled)
}
afterEach(() => {
document.body.innerHTML = ''
vi.restoreAllMocks()
vi.unstubAllGlobals()
localStorage.clear()
})
describe('TabBar right-click context menu', () => {
it('opens the five-item menu at the cursor, prevents the browser menu, and does not activate', () => {
it('opens the six-item menu at the cursor, prevents the browser menu, and does not activate', () => {
stubZh()
const { tabEls, onActivate, unmount } = mountBar(fourTabs())
try {
@@ -180,6 +209,37 @@ describe('TabBar right-click context menu', () => {
}
})
it('close all closes every tab in the pane, the right-clicked one included', () => {
stubZh()
const { tabEls, onClose, unmount } = mountBar(fourTabs())
try {
act(() => { rightClick(tabEls[1]!) })
act(() => { menuItems()[4]!.click() })
expect(onClose.mock.calls.map(call => call[0])).toEqual(['t1', 't2', 't3', 't4'])
expect(menuItems()).toHaveLength(0)
} finally {
unmount()
}
})
it('reveals the right-clicked tab file through the shell resolver', () => {
stubZh()
const { tabEls, onRevealInFileManager, onClose, unmount } = mountBar(fileTabs())
try {
act(() => { rightClick(tabEls[0]!) })
// The file tab's row is live; the pane's other tab has no file.
expect(menuDisabled()).toEqual([false, false, true, false, false, false])
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenCalledTimes(1)
expect(onRevealInFileManager).toHaveBeenCalledWith('/repo/src/a.ts')
// Revealing is not a close: no tab may go away.
expect(onClose).not.toHaveBeenCalled()
expect(menuItems()).toHaveLength(0)
} finally {
unmount()
}
})
it('grays out close others on a single tab and close left/right at the strip ends', () => {
stubZh()
const single = mountBar([
@@ -187,11 +247,11 @@ describe('TabBar right-click context menu', () => {
])
try {
act(() => { rightClick(single.tabEls[0]!) })
const items = menuItems()
// The Menu renders each row as a disabled <button role="menuitem">.
expect(items.map(item => (item as HTMLButtonElement).disabled)).toEqual([false, true, true, true])
// Close all stays live (it always has at least the right-clicked tab).
expect(menuDisabled()).toEqual([false, true, true, true, false, true])
// Clicking the disabled row must not close anything.
act(() => { items[1]!.click() })
act(() => { menuItems()[1]!.click() })
expect(single.onClose).not.toHaveBeenCalled()
} finally {
single.unmount()
@@ -200,11 +260,162 @@ describe('TabBar right-click context menu', () => {
const four = mountBar(fourTabs())
try {
act(() => { rightClick(four.tabEls[0]!) })
expect(menuItems().map(item => (item as HTMLButtonElement).disabled)).toEqual([false, false, true, false])
expect(menuDisabled()).toEqual([false, false, true, false, false, true])
act(() => { rightClick(four.tabEls[3]!) })
expect(menuItems().map(item => (item as HTMLButtonElement).disabled)).toEqual([false, false, false, true])
expect(menuDisabled()).toEqual([false, false, false, true, false, true])
} finally {
four.unmount()
}
})
it('grays out the reveal row for a tab with no associated file', () => {
stubZh()
const tabs = fileTabs()
const { tabEls, onRevealInFileManager, onClose, unmount } = mountBar(tabs)
try {
act(() => { rightClick(tabEls[1]!) })
// The changes tab carries no file of its own (its diff ref is
// repo-relative, not a path the host could reveal).
expect(menuDisabled()).toEqual([false, false, false, true, false, true])
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).not.toHaveBeenCalled()
expect(onClose).not.toHaveBeenCalled()
} finally {
unmount()
}
})
it('grays out the reveal row when the shell passes no resolver', () => {
stubZh()
const { tabEls, onRevealInFileManager, unmount } = mountBar(fileTabs(), { noRevealResolver: true })
try {
act(() => { rightClick(tabEls[0]!) })
expect(onRevealInFileManager).toBeUndefined()
expect(menuDisabled()[5]).toBe(true)
} finally {
unmount()
}
})
})
describe('Workbench tab context menu', () => {
/** Two panes side by side, each with one file tab (the recursive render
* path a split workbench takes to its strips). */
function splitState(): SidebarState {
return {
...makeDefaultState(),
bottomSplits: {
kind: 'split',
id: 'split:1',
dir: 'row',
sizes: [0.5, 0.5],
children: [
{ kind: 'leaf', id: 'pane:1', tabs: [{ id: 't1', type: 'editor', title: 'a.ts', path: '/repo/a.ts' }], active: 't1' },
{ kind: 'leaf', id: 'pane:2', tabs: [{ id: 't2', type: 'editor', title: 'b.ts', path: '/repo/b.ts' }], active: 't2' },
],
},
}
}
it('hands every pane strip the shell reveal resolver', () => {
stubZh()
const state = splitState()
const onRevealInFileManager = vi.fn()
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => {
root.render(createElement(Workbench, {
state,
tree: state.bottomSplits,
newTabOptions: [],
actions: {
closeTab: () => {},
activateTab: () => {},
focusPane: () => {},
moveTabToEdge: () => {},
moveTabBefore: () => {},
resizeSplit: () => {},
},
onNewTab: () => {},
// The strip is what this spec is about: the panes' bodies stay empty.
renderTab: () => null,
onRevealInFileManager,
}))
})
try {
const paneTabs = [...container.querySelectorAll<HTMLElement>('[class*="tabList"] > [class*="tab"]')]
expect(paneTabs).toHaveLength(2)
// Each strip's reveal row must reach the resolver with ITS tab's file.
act(() => { rightClick(paneTabs[0]!) })
expect(menuDisabled()[5]).toBe(false)
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenLastCalledWith('/repo/a.ts')
act(() => { rightClick(paneTabs[1]!) })
act(() => { menuItems()[5]!.click() })
expect(onRevealInFileManager).toHaveBeenLastCalledWith('/repo/b.ts')
expect(onRevealInFileManager).toHaveBeenCalledTimes(2)
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
describe('Sidebar tab context menu reveal', () => {
/**
* The whole shell on a fake host: the bottom workbench holds one file tab,
* and the reveal row must reach the host's open-in-app remote — the same
* call the explorer's own reveal row makes (`ctx.remote.session.
* openWorkspacePath({ path, action: 'reveal' })`). This is the only
* coverage of the shell's own wiring between the strip resolver and the
* open-in-app adapter; `tests/open-in-app.spec.ts` covers the adapter.
*/
it('reveals the tab file through the host open-in-app remote', async () => {
vi.stubGlobal('WebSocket', class { close(): void {} })
const store = createSidebarStore()
store.setSession('s1')
store.reduce(state => ({ ...state, bottomOpen: true }))
const service = createBetterSidebarService(store)
service.registerTab({ id: 'probe', title: 'Probe', component: () => null })
service.openTab({ type: 'probe', title: 'probe.ts', path: '/repo/src/probe.ts' })
const reveal = vi.fn(async () => ({ ok: true }))
// Both snapshots are stable references (useSyncExternalStore re-reads
// them on every render: a fresh object here is an infinite loop). The
// shell follows the host's MOUNTED seat (`ctx.sidebarRight.mounted`) for
// its per-session state, so the fake column has to report one — without
// it the shell unbinds the store and renders nothing.
const localeSnapshot = { active: 'en' }
const sessionsSnapshot = { byId: { s1: { id: 's1', cwd: '/repo' } } }
const ctx = {
locale: { subscribe: () => () => {}, getSnapshot: () => localeSnapshot },
sessions: { list: { subscribe: () => () => {}, getSnapshot: () => sessionsSnapshot } },
get: (name: string) => ({
betterSidebar: service,
remote: { session: { openWorkspacePath: reveal } },
sidebarRight: { mounted: { subscribe: () => () => {}, getSnapshot: () => 's1' } },
})[name],
}
const container = document.createElement('div')
document.body.append(container)
const root: Root = createRoot(container)
act(() => { root.render(createElement(Sidebar, { ctx: ctx as never, store })) })
try {
const tab = container.querySelector<HTMLElement>('[class*="bottomPanel"] [class*="tabList"] > [class*="tab"]')
expect(tab).not.toBeNull()
act(() => { rightClick(tab!) })
// The copy is pinned by the TabBar block above (against zh); here the
// shape and the row's live state are what matter (the shell runs on the
// default locale).
expect(menuItems()).toHaveLength(MENU_LABELS.length)
expect(menuDisabled()[5]).toBe(false)
await act(async () => { menuItems()[5]!.click() })
expect(reveal).toHaveBeenCalledTimes(1)
expect(reveal).toHaveBeenCalledWith({ path: '/repo/src/probe.ts', action: 'reveal' })
} finally {
act(() => { root.unmount() })
container.remove()
}
})
})
+72 -4
View File
@@ -1,14 +1,17 @@
/**
* The title-bar strip resolution chain: standard WCO geometry first
* (authoritative even when 0), then the documented URL inset contract
* parameter, then the opt-in preset / custom scheme — and 0 (plain web,
* nothing modified) otherwise. No per-shell branch lives in the core.
* The title-bar strip resolution chain: the desktop shell's own window
* contract first (present → its `safeAreaInsets.top` is authoritative),
* then standard WCO geometry (authoritative even when 0), then the
* documented URL inset contract parameter, then the opt-in preset / custom
* scheme — and 0 (plain web, nothing modified) otherwise. No per-shell
* branch lives in the core.
*/
import { describe, expect, it } from 'vitest'
import { computeTitleBarStrip } from '../src/client/titlebar-strip.ts'
import type { DesktopEnv } from '../src/client/desktop-env.ts'
import type { WcoSnapshot } from '../src/client/wco.ts'
import type { ShellPreset } from '../src/client/shell-presets.ts'
import type { SidebarDesktopWindowService } from '../src/context-types.ts'
const env = (partial: Partial<DesktopEnv>): DesktopEnv => ({
desktop: false,
@@ -22,6 +25,18 @@ const wco = (present: boolean, height = 0): WcoSnapshot => ({ present, height })
const noPreset: ShellPreset | undefined = undefined
/** One desktop-shell window contract snapshot (only the read field varies). */
const shell = (
mode: SidebarDesktopWindowService['mode'],
top: number,
): SidebarDesktopWindowService => ({
mode,
platform: mode === 'advanced' ? 'win32' : 'darwin',
material: 'off',
safeAreaInsets: { top, right: 0, bottom: 0, left: 0 },
dragRegion: { height: top, leftInset: 0, rightInset: 0 },
})
describe('computeTitleBarStrip', () => {
it('keeps plain web untouched: no WCO, no inset, no scheme → 0', () => {
expect(computeTitleBarStrip(env({}), wco(false), 'auto', noPreset, 40)).toBe(0)
@@ -37,6 +52,8 @@ describe('computeTitleBarStrip', () => {
expect(computeTitleBarStrip(desktop, wco(false), 'web', {
id: 't', title: 't', desc: '', stripFor: () => 20,
}, 40)).toBe(0)
// ... and the shell contract does not override that explicit choice.
expect(computeTitleBarStrip(desktop, wco(false), 'web', noPreset, 40, shell('advanced', 32))).toBe(0)
})
it('trusts the standard WCO geometry first in every scheme (even 0 — e.g. maximized)', () => {
@@ -72,4 +89,55 @@ describe('computeTitleBarStrip', () => {
expect(computeTitleBarStrip(env({}), wco(false), 'auto', noPreset, 56)).toBe(0)
expect(computeTitleBarStrip(env({}), wco(false), 'preset', noPreset, 56)).toBe(0)
})
// The desktop shell's own window contract (`ctx.desktopWindow`) — issue
// #430. The shell reserves its title bar by placing the WHOLE page below it
// (compatibility / extended) yet still publishes the
// `dsh-desktop-titlebar-inset=36` URL stamp describing that same reserve;
// reading the stamp as "pixels the page must additionally yield" left a
// second 36px blank strip at the top of every panel. `safeAreaInsets.top`
// is that reserve ALREADY APPLIED, so it outranks the stamp.
describe('the shell window contract (ctx.desktopWindow)', () => {
it('(a) compatibility / extended report a zero inset → nothing is reserved', () => {
const stamped = env({ desktop: true, mode: 'compatibility', platform: 'win32', titlebarInset: 36 })
expect(computeTitleBarStrip(stamped, wco(false), 'auto', noPreset, 0, shell('compatibility', 0))).toBe(0)
const extended = env({ desktop: true, mode: 'extended', platform: 'win32', titlebarInset: 36 })
expect(computeTitleBarStrip(extended, wco(false), 'auto', noPreset, 0, shell('extended', 0))).toBe(0)
})
it('(b) advanced reports the caption row it draws INTO the content → that height', () => {
const advanced = env({ desktop: true, mode: 'advanced', platform: 'win32' })
expect(computeTitleBarStrip(advanced, wco(false), 'auto', noPreset, 0, shell('advanced', 32))).toBe(32)
// The value is the SHELL's, not a constant: macOS advanced reports 20.
expect(computeTitleBarStrip(advanced, wco(false), 'auto', noPreset, 0, shell('advanced', 20))).toBe(20)
})
it('(c) without the service the existing chain is untouched (older shells, plain pages)', () => {
const stamped = env({ desktop: true, mode: 'compatibility', platform: 'win32', titlebarInset: 36 })
expect(computeTitleBarStrip(stamped, wco(false), 'auto', noPreset, 0)).toBe(36)
expect(computeTitleBarStrip(stamped, wco(false), 'preset', noPreset, 0)).toBe(36)
})
it('(d) with the service the URL stamp is IGNORED, whatever it says', () => {
const stamped = env({ desktop: true, mode: 'extended', platform: 'darwin', titlebarInset: 36 })
expect(computeTitleBarStrip(stamped, wco(false), 'auto', noPreset, 40, shell('extended', 0))).toBe(0)
// ... including the custom scheme's manual px, which the shell's real
// geometry outranks exactly like WCO always did.
expect(computeTitleBarStrip(stamped, wco(false), 'custom', noPreset, 40, shell('extended', 0))).toBe(0)
// Even a present WCO overlay does not outrank the shell's own contract.
expect(computeTitleBarStrip(stamped, wco(true, 36), 'auto', noPreset, 0, shell('extended', 0))).toBe(0)
})
it('falls through to the standard chain for a service without a usable top', () => {
const stamped = env({ desktop: true, mode: 'compatibility', platform: 'win32', titlebarInset: 36 })
const broken = {
...shell('compatibility', 0),
safeAreaInsets: undefined,
} as unknown as SidebarDesktopWindowService
expect(computeTitleBarStrip(stamped, wco(false), 'auto', noPreset, 0, broken)).toBe(36)
const nan = { ...shell('compatibility', 0), safeAreaInsets: { top: Number.NaN, right: 0, bottom: 0, left: 0 } }
expect(computeTitleBarStrip(stamped, wco(true, 24), 'auto', noPreset, 0, nan)).toBe(24)
})
})
})