Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

feat(desktop): align View menu with core shortcuts (#840)

云游君a7a416dee927
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.test.ts b/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
index 73f671be..32aac911 100644
--- a/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.test.ts
@@ -2,7 +2,8 @@ import type { AddressInfo } from 'node:net'
import type { MachineProfile, SshExecOptions, SshExecResult, SshMachineEvent, SshSession, SshTunnelHandle } from '../types/index'
import type { SshTransport, SshTransportOptions } from './transport.types'
import { Buffer } from 'node:buffer'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
+import { execFileSync } from 'node:child_process'
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { createServer } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'pathe'
@@ -300,6 +301,7 @@ afterEach(async () => {
else
process.env.DSH_HOME = harnessHomeBefore
vi.unstubAllGlobals()
+ vi.restoreAllMocks()
clearHostRuntime()
}
}
@@ -345,8 +347,12 @@ function boot(overrides: Partial<{
process.env.DSH_HOME = harnessHomeWith(overrides.envCredentials())
setHostConfig({ ...(overrides.config ?? config), sshDir: tempRoot() })
setKnownHostsPath(join(tempRoot(), 'known-hosts.json'))
+ const bundledPluginsRoot = tempRoot()
+ mkdirSync(join(bundledPluginsRoot, 'dsh-tauri-ssh'))
+ writeFileSync(join(bundledPluginsRoot, 'dsh-tauri-ssh', 'package.json'), JSON.stringify({ name: 'dsh-tauri-ssh', dsh: { bundle: {} } }))
setMachineDeps({
transport,
+ bundledPluginsTree: { root: bundledPluginsRoot, pluginNames: ['dsh-tauri-ssh'] },
localAllowlist: overrides.localAllowlist ?? (() => EMPTY_ALLOWLIST),
emitStatus: (id, status) => {
emits.push({ id, state: status.state, ...status.progress === undefined ? {} : { progress: status.progress } })
@@ -895,9 +901,6 @@ describe('sshManager', () => {
describe('sshManager install', () => {
it('installs dsh end-to-end, copies credentials, and auto-connects', async () => {
- // Session 1 = install (platform probe, missing check, install script,
- // entry check, credentials copy); session 2 = the automatic connect
- // (root probe refused, platform probe, missing check, launch, healthy).
let sessions = 0
const factory = () => {
sessions += 1
@@ -1287,8 +1290,6 @@ describe('sshManager install', () => {
const factory = () => {
sessions += 1
const session = new FakeSession(index => sessions >= 2 && index >= 1)
- // The first (failed) connect finds the runtime incomplete; the install
- // and the auto-connect see it whole.
if (sessions === 1)
session.startNotInstalled = true
return session
@@ -1303,7 +1304,6 @@ describe('sshManager install', () => {
expect(result.dshPath).toBe(ENTRY)
expect(manager.status(MachineId('m1')).dshMissing).toBeUndefined()
await until(() => manager.status(MachineId('m1')).state === 'connected', 'auto-connect after install')
- // First (failed) connect + install + auto-connect.
expect(transport.connectCalls, JSON.stringify(events.since(MachineId('m1')))).toBe(3)
})
@@ -1574,13 +1574,17 @@ describe('sshManager reconnect', () => {
expect(manager.status(MachineId('m1')).tunnelBaseUrl).toBe('http://127.0.0.1:49152/?token=tok-abc-123')
})
- it('syncs bundled plugins before ensuring the instance (failure degrades, never blocks)', async () => {
+ it('syncs the supplied plugin tree before ensuring the instance', async () => {
const session = new FakeSession(() => true)
const { manager, events } = boot({ sessionFactory: () => session })
const link = await manager.connect(MachineId('m1'))
expect(link.tunnelBaseUrl).toContain('http://127.0.0.1:')
expect(session.commands.some(command => command.startsWith('cat "$HOME/.dsh-desktop/plugins'))).toBe(true)
expect(session.commands.some(command => command.includes('PLUGINS_SYNCED'))).toBe(true)
+ const upload = session.options[session.commands.findIndex(command => command.includes('PLUGINS_SYNCED'))]?.stdinData
+ expect(upload).toBeInstanceOf(Buffer)
+ const manifest = execFileSync('tar', ['-xOzf', '-', './dsh-tauri-ssh/package.json'], { input: upload, encoding: 'utf8' })
+ expect(JSON.parse(manifest)).toEqual({ name: 'dsh-tauri-ssh', dsh: { bundle: {} } })
expect(events.since(MachineId('m1')).events.map(event => event.line).some(line => line.includes('捆绑插件已同步'))).toBe(true)
})
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.ts b/packages/dsh-tauri-ssh/src/host/service/machine.ts
index aca4cb34..62a685fa 100644
--- a/packages/dsh-tauri-ssh/src/host/service/machine.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.ts
@@ -382,6 +382,7 @@ async function performConnect(machineId: MachineId, profile: MachineProfile, sig
const session = await openSessionOrFail(machineId, profile, signal)
try {
await syncBundledPlugins(session, safeProfileName(profile.profileName), profile.remotePort, {
+ tree: machineRuntimeDeps().bundledPluginsTree,
onEvent: (stage, line) => {
if (generation === target.generation)
events.append(machineId, stage, line)
diff --git a/packages/dsh-tauri-ssh/src/host/service/machine.types.ts b/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
index fbd402e8..40d99440 100644
--- a/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
+++ b/packages/dsh-tauri-ssh/src/host/service/machine.types.ts
@@ -9,6 +9,7 @@ import type {
SshTunnelHandle,
} from '../types/index'
import type { WorkspaceAllowlist } from '../utils/allowlist'
+import type { BundledPluginsTree } from '../utils/plugins-sync'
import type { SshTransport } from './transport.types'
export interface MachineState {
@@ -39,4 +40,5 @@ export interface MachineDeps {
transport: SshTransport
emitStatus: (machineId: MachineId, status: SshMachineStatus) => void
localAllowlist: () => WorkspaceAllowlist
+ bundledPluginsTree?: BundledPluginsTree
}
diff --git a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
index 0567c659..9e73053c 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.test.ts
@@ -6,18 +6,32 @@ import { afterEach, describe, expect, it } from 'vitest'
import { buildPluginsBundle, findBundledPluginsTree, pluginSyncApplyCommand, pluginSyncMarkerCommand, WIRE_SCRIPT } from './plugins-sync'
describe('findBundledPluginsTree', () => {
- it('locates the deployed tree from the repo dev layout (packages/ → src-tauri/resources/node_modules)', () => {
- // 本测试运行于包源码树内:ownPkgDir=packages/dsh-tauri-ssh,候选一应被
- // 「ssh2 依赖不在」拒绝,候选二命中 build:plugins 的部署树
- const tree = findBundledPluginsTree()
- expect(tree).toBeDefined()
- expect(tree!.root).toContain('src-tauri/resources/node_modules')
- expect(tree!.pluginNames).toContain('dsh-tauri-ssh')
- expect(tree!.pluginNames).toContain('dsh-tauri-ui')
- // 第三方依赖不挂 dsh 字段,不得混入插件清单;上游 panel 包与 tailwind 样式包并入后为 10 个
- expect(tree!.pluginNames).not.toContain('ssh2')
- expect(tree!.pluginNames).not.toContain('dsh-tauri-panel')
- expect(tree!.pluginNames.length).toBeGreaterThanOrEqual(10)
+ it('locates deployed plugins from the dev layout and excludes ordinary dependencies', () => {
+ const root = mkdtempSync(join(tmpdir(), 'dsh-plugins-discovery-'))
+ try {
+ const source = join(root, 'packages', 'dsh-tauri-ssh')
+ const deployed = join(root, 'src-tauri', 'resources', 'node_modules')
+ mkdirSync(source, { recursive: true })
+ writeFileSync(join(source, 'package.json'), '{"name":"dsh-tauri-ssh"}')
+ for (const name of ['dsh-tauri-ssh', 'dsh-tauri-ui', 'ssh2', 'dsh-tauri-panel']) {
+ mkdirSync(join(deployed, name), { recursive: true })
+ writeFileSync(join(deployed, name, 'package.json'), JSON.stringify({
+ name,
+ ...name === 'dsh-tauri-ssh' || name === 'dsh-tauri-ui' ? { dsh: { bundle: {} } } : {},
+ }))
+ }
+ expect(findBundledPluginsTree(source)).toEqual({
+ root: deployed,
+ pluginNames: ['dsh-tauri-ssh', 'dsh-tauri-ui'],
+ })
+ expect(findBundledPluginsTree(join(deployed, 'dsh-tauri-ssh'))).toEqual({
+ root: deployed,
+ pluginNames: ['dsh-tauri-ssh', 'dsh-tauri-ui'],
+ })
+ }
+ finally {
+ rmSync(root, { recursive: true, force: true })
+ }
})
})
diff --git a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
index aaf099e2..58a042ef 100644
--- a/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
+++ b/packages/dsh-tauri-ssh/src/host/utils/plugins-sync.ts
@@ -53,8 +53,7 @@ export interface BundledPluginsTree {
pluginNames: string[]
}
-export function findBundledPluginsTree(): BundledPluginsTree | undefined {
- let ownPkgDir = dirname(realpathSync(fileURLToPath(import.meta.url)))
+export function findBundledPluginsTree(ownPkgDir = dirname(realpathSync(fileURLToPath(import.meta.url)))): BundledPluginsTree | undefined {
for (let depth = 0; depth < 6; depth += 1) {
try {
const manifest = JSON.parse(readFileSync(join(ownPkgDir, 'package.json'), 'utf8')) as { name?: string }
@@ -139,9 +138,9 @@ export async function syncBundledPlugins(
session: SshSession,
profileName: string,
remotePort: number,
- hooks: { onEvent?: (stage: SshMachineStage, line: string) => void } = {},
+ hooks: { onEvent?: (stage: SshMachineStage, line: string) => void, tree?: BundledPluginsTree | undefined } = {},
): Promise<boolean> {
- const tree = findBundledPluginsTree()
+ const tree = hooks.tree ?? findBundledPluginsTree()
if (tree === undefined) {
hooks.onEvent?.('install', '未找到本地捆绑插件树(dev 环境需先 build:plugins),跳过远端同步')
return false
diff --git a/packages/dsh-tauri/src/client/register/shortcuts.test.ts b/packages/dsh-tauri/src/client/register/shortcuts.test.ts
index d7986873..c2da6dc1 100644
--- a/packages/dsh-tauri/src/client/register/shortcuts.test.ts
+++ b/packages/dsh-tauri/src/client/register/shortcuts.test.ts
@@ -1,13 +1,3 @@
-/**
- * register/shortcuts.test.ts — 快捷键桥的两条契约。
- *
- * 1. iframe → 宿主:核心 `ctx.shortcuts.catalog` 的目录投影后经 `dsh://shortcuts` 回报
- * (壳层菜单右侧的按键提示都读它),配置变更后重发;
- * 2. 宿主 → iframe:`dsh://shortcuts:open` 按官方 `shortcuts.open` 的**生效**绑定补一次
- * 合成 keydown,弹出官方弹层与官方蒙版(壳层不自建对话框)。
- *
- * 核心没有 `shortcuts` 服务(老核心)时全部保持沉默,不得抛错。
- */
import type { ClientContext, ParentMessage } from '../types'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { CMD_SHORTCUTS_OPEN, EVENT_SHORTCUTS, shortcutsFeature } from './shortcuts'
@@ -59,14 +49,13 @@ function stubEnv(): Harness {
const disposers: (() => void)[] = []
function fakeCtx(service: unknown): ClientContext {
- return {
- get: () => service,
- effect(callback: (this: unknown) => () => void) {
- const dispose = callback.call({ ctx: this })
- disposers.push(dispose)
- return dispose
- },
- } as unknown as ClientContext
+ return { get: () => service } as unknown as ClientContext
+}
+
+function runFeature(ctx: ClientContext): () => void {
+ const dispose = shortcutsFeature.call(ctx)
+ disposers.push(dispose)
+ return dispose
}
function catalogService(rows: unknown[], subscribe?: (listener: () => void) => () => void) {
@@ -77,6 +66,7 @@ afterEach(() => {
for (const dispose of disposers.splice(0))
dispose()
vi.unstubAllGlobals()
+ vi.restoreAllMocks()
})
describe('shortcutsFeature', () => {
@@ -86,6 +76,7 @@ describe('shortcutsFeature', () => {
const ctx = fakeCtx(catalogService([
{ id: 'session.new', label: 'New chat', keys: ['Ctrl+N'], aria: 'Control+N', modified: false },
{ id: 'workspace.add', label: 'Open folder', keys: ['Ctrl+O'] },
+ { id: 'sidebar.left.toggle', label: 'Toggle sidebar', keys: ['⌥', '⌘', 'B'], binding: { code: 'KeyB', modifiers: ['alt', 'meta'] }, issue: null, conflicts: [] },
{ id: 42, label: 'broken' },
{ id: 'no.label' },
], (listener) => {
@@ -93,13 +84,14 @@ describe('shortcutsFeature', () => {
return () => {}
}))
- shortcutsFeature.call(ctx)
+ runFeature(ctx)
expect(env.sent).toEqual([{
type: EVENT_SHORTCUTS,
rows: [
- { id: 'session.new', label: 'New chat', keys: ['Ctrl+N'], aria: 'Control+N' },
- { id: 'workspace.add', label: 'Open folder', keys: ['Ctrl+O'] },
+ { id: 'session.new', label: 'New chat', keys: ['Ctrl+N'], aria: 'Control+N', available: false },
+ { id: 'workspace.add', label: 'Open folder', keys: ['Ctrl+O'], available: false },
+ { id: 'sidebar.left.toggle', label: 'Toggle sidebar', keys: ['⌥', '⌘', 'B'], available: true },
],
}])
expect(env.listeners()).toBe(1)
@@ -111,12 +103,11 @@ describe('shortcutsFeature', () => {
it('stays inert when the core has no shortcuts service', () => {
const env = stubEnv()
- expect(() => shortcutsFeature.call(fakeCtx(undefined))).not.toThrow()
+ expect(() => runFeature(fakeCtx(undefined))).not.toThrow()
expect(env.sent).toEqual([])
expect(env.listeners()).toBe(0)
})
- /** 官方弹层:用目录里的生效绑定合成 keydown(官方适配器只看 code + 修饰键)。 */
it('opens the official reference with the effective binding', () => {
const env = stubEnv()
class FakeKeyboardEvent {
@@ -140,7 +131,7 @@ describe('shortcutsFeature', () => {
}
dispatchers.add(handler as unknown as (event: KeyboardEvent) => void)
- shortcutsFeature.call(fakeCtx(catalogService([
+ runFeature(fakeCtx(catalogService([
{ id: 'shortcuts.open', label: 'Shortcuts', keys: ['Ctrl+/'], binding: { code: 'Slash', modifiers: ['control'] } },
])))
env.dispatch({ type: CMD_SHORTCUTS_OPEN })
@@ -150,4 +141,86 @@ describe('shortcutsFeature', () => {
expect(seen?.metaKey).toBe(false)
dispatchers.delete(handler as unknown as (event: KeyboardEvent) => void)
})
+
+ it.each(['sidebar.left.toggle', 'sidebar.right.toggle', 'terminal.new', 'session.search'])('invokes %s once with its current binding', (id) => {
+ const env = stubEnv()
+ class FakeKeyboardEvent {
+ constructor(readonly type: string, readonly init: KeyboardEventInit) {}
+ }
+ vi.stubGlobal('KeyboardEvent', FakeKeyboardEvent)
+ const received = vi.fn()
+ dispatchers.add(received)
+ const rows = [{ id, label: id, keys: ['⌘', 'T'], binding: { code: 'KeyT', modifiers: ['meta'] } }]
+ runFeature(fakeCtx(catalogService(rows)))
+
+ env.dispatch({ type: 'dsh://view:command', command: id })
+ expect(received).toHaveBeenCalledExactlyOnceWith(new FakeKeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ code: 'KeyT',
+ ctrlKey: false,
+ metaKey: true,
+ altKey: false,
+ shiftKey: false,
+ }))
+
+ rows[0].binding = { code: 'KeyU', modifiers: ['control', 'shift'] }
+ env.dispatch({ type: 'dsh://view:command', command: id })
+ expect(received).toHaveBeenCalledTimes(2)
+ expect(received).toHaveBeenLastCalledWith(new FakeKeyboardEvent('keydown', {
+ bubbles: true,
+ cancelable: true,
+ code: 'KeyU',
+ ctrlKey: true,
+ metaKey: false,
+ altKey: false,
+ shiftKey: true,
+ }))
+ })
+
+ it.each([
+ { binding: null },
+ { binding: { code: 'KeyB', modifiers: ['meta'] }, conflicts: ['other.command'] },
+ { binding: { code: 'KeyB', modifiers: ['meta'] }, issue: 'reserved' },
+ { binding: { code: 'KeyB', secondCode: 'KeyC', modifiers: ['meta'] } },
+ ])('disables unavailable bindings without dispatching a fallback: %j', (input) => {
+ const env = stubEnv()
+ vi.stubGlobal('KeyboardEvent', vi.fn())
+ runFeature(fakeCtx(catalogService([
+ { id: 'sidebar.left.toggle', label: 'Sidebar', keys: ['⌘', 'B'], ...input },
+ { id: 'shortcuts.open', label: 'Shortcuts', keys: [], binding: null },
+ ])))
+
+ expect(env.sent[0].rows).toEqual([
+ { id: 'sidebar.left.toggle', label: 'Sidebar', keys: ['⌘', 'B'], available: false },
+ { id: 'shortcuts.open', label: 'Shortcuts', keys: [], available: false },
+ ])
+ env.dispatch({ type: 'dsh://view:command', command: 'sidebar.left.toggle' })
+ env.dispatch({ type: CMD_SHORTCUTS_OPEN })
+ expect(KeyboardEvent).not.toHaveBeenCalled()
+ })
+
+ it('rejects commands outside the View whitelist', () => {
+ const env = stubEnv()
+ vi.stubGlobal('KeyboardEvent', vi.fn())
+ runFeature(fakeCtx(catalogService([
+ { id: 'session.archive', label: 'Archive', keys: ['⌘', 'A'], binding: { code: 'KeyA', modifiers: ['meta'] } },
+ ])))
+ env.dispatch({ type: 'dsh://view:command', command: 'session.archive' })
+ env.dispatch({ type: 'dsh://view:command', command: 42 })
+ expect(KeyboardEvent).not.toHaveBeenCalled()
+ })
+
+ it('clears the shell catalog when the bridge is disposed', () => {
+ const env = stubEnv()
+ const dispose = runFeature(fakeCtx(catalogService([
+ { id: 'terminal.new', label: 'Terminal', keys: ['Ctrl+`'], binding: { code: 'Backquote', modifiers: ['control'] } },
+ ])))
+ dispose()
+ expect(env.sent).toEqual([
+ { type: EVENT_SHORTCUTS, rows: [{ id: 'terminal.new', label: 'Terminal', keys: ['Ctrl+`'], available: true }] },
+ { type: EVENT_SHORTCUTS, rows: [] },
+ ])
+ expect(env.listeners()).toBe(0)
+ })
})
diff --git a/packages/dsh-tauri/src/client/register/shortcuts.ts b/packages/dsh-tauri/src/client/register/shortcuts.ts
index a932853c..da3a3014 100644
--- a/packages/dsh-tauri/src/client/register/shortcuts.ts
+++ b/packages/dsh-tauri/src/client/register/shortcuts.ts
@@ -1,31 +1,21 @@
-/**
- * register/shortcuts.ts — 快捷键目录桥(iframe ↔ 宿主导航栏)。
- *
- * iframe → 宿主:把核心 `ctx.shortcuts` 的目录投影成 `{ id, label, keys, aria }`,经
- * `dsh://shortcuts` 送达壳层;壳层的「文件」「帮助」菜单右侧按键提示与「显示键盘快捷键」
- * 清单都读这一份(配置变更后重发,用户改键即时生效)。
- *
- * 宿主 → iframe:`dsh://shortcuts:open` 打开官方「键盘快捷键」弹层。
- *
- * 协议字面量与宿主侧 `src/layout/components/webview.tsx` / `navbar.tsx` 逐字一致。
- */
import type { ParentMessage } from '../types'
import { invokeParent } from '../service/invoke-parent'
import { listenParent } from '../service/listen-parent'
import { defineRegister } from './index'
-/** iframe → 宿主:快捷键目录回报。 */
export const EVENT_SHORTCUTS = 'dsh://shortcuts'
-/** 宿主 → iframe:打开官方「键盘快捷键」弹层(官方 `shortcuts.open` 命令,含官方蒙版)。 */
export const CMD_SHORTCUTS_OPEN = 'dsh://shortcuts:open'
-/** 上报给壳层的一行目录(官方 `ShortcutCatalogEntry` 的投影)。 */
+const CMD_VIEW_COMMAND = 'dsh://view:command'
+const VIEW_COMMANDS = new Set(['sidebar.left.toggle', 'sidebar.right.toggle', 'terminal.new', 'session.search'])
+
export interface ShortcutRowReport {
id: string
label: string
keys: readonly string[]
aria?: string
+ available: boolean
}
interface CatalogLike {
@@ -45,21 +35,24 @@ export const shortcutsFeature = defineRegister((controller, ctx) => {
const snapshot = catalog?.getSnapshot
if (typeof snapshot !== 'function')
return
+ const readCatalog = snapshot.bind(catalog)
- const report = (): void => {
- invokeParent({ type: EVENT_SHORTCUTS, rows: project(snapshot.call(catalog)) })
+ function report(): void {
+ invokeParent({ type: EVENT_SHORTCUTS, rows: project(readCatalog()) })
}
report()
+ controller.add(() => invokeParent({ type: EVENT_SHORTCUTS, rows: [] }))
if (typeof catalog?.subscribe === 'function')
controller.add(catalog.subscribe(report))
controller.add(listenParent<ParentMessage>((data) => {
if (data.type === CMD_SHORTCUTS_OPEN)
- openReference(snapshot.call(catalog))
- }, [CMD_SHORTCUTS_OPEN]))
+ dispatchShortcut(readCatalog(), 'shortcuts.open')
+ else if (data.type === CMD_VIEW_COMMAND && typeof data.command === 'string' && VIEW_COMMANDS.has(data.command))
+ dispatchShortcut(readCatalog(), data.command)
+ }, [CMD_SHORTCUTS_OPEN, CMD_VIEW_COMMAND]))
})
-/** 目录投影:只保留有 id 与文案的行,`keys` 逐项取字符串。 */
function project(rows: unknown): ShortcutRowReport[] {
if (!Array.isArray(rows))
return []
@@ -76,6 +69,7 @@ function project(rows: unknown): ShortcutRowReport[] {
label: entry.label,
keys,
...typeof entry.aria === 'string' ? { aria: entry.aria } : {},
+ available: bindingOf(rows, entry.id) !== undefined,
})
if (out.length >= ROW_MAX)
break
@@ -83,38 +77,36 @@ function project(rows: unknown): ShortcutRowReport[] {
return out
}
-/**
- * 打开官方「键盘快捷键」弹层:官方命令没有公开的调用口,按其**生效**绑定补一次合成
- * keydown(官方键盘适配器只读 `event.code` 与修饰键,不校验 `isTrusted`),
- * 走的仍是官方 `shortcuts.open` 命令与其 `shell.overlay` 弹层(含官方蒙版)。
- */
-function openReference(rows: unknown): void {
+function dispatchShortcut(rows: unknown, id: string): void {
if (typeof window === 'undefined' || typeof KeyboardEvent !== 'function')
return
- const binding = bindingOf(rows, 'shortcuts.open')
+ const binding = bindingOf(rows, id)
+ if (binding === undefined)
+ return
const event = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
- ...binding ?? { code: 'Slash', ctrlKey: true, metaKey: false, altKey: false, shiftKey: false },
+ ...binding,
})
window.dispatchEvent(event)
}
-/** 目录里取某命令的生效绑定,翻成 KeyboardEvent 的物理键 + 修饰键字段。 */
function bindingOf(rows: unknown, id: string): KeyboardEventInit | undefined {
if (!Array.isArray(rows))
return undefined
for (const row of rows) {
if (typeof row !== 'object' || row === null)
continue
- const entry = row as { id?: unknown, binding?: unknown }
+ const entry = row as { id?: unknown, binding?: unknown, conflicts?: unknown, issue?: unknown }
if (entry.id !== id)
continue
+ if (entry.issue != null || (Array.isArray(entry.conflicts) && entry.conflicts.length > 0))
+ return undefined
const binding = entry.binding
if (typeof binding !== 'object' || binding === null)
return undefined
- const { code, modifiers } = binding as { code?: unknown, modifiers?: unknown }
- if (typeof code !== 'string')
+ const { code, modifiers, secondCode } = binding as { code?: unknown, modifiers?: unknown, secondCode?: unknown }
+ if (typeof code !== 'string' || code.length === 0 || secondCode != null)
return undefined
const list = Array.isArray(modifiers) ? modifiers.filter((value): value is string => typeof value === 'string') : []
return {
diff --git a/src-tauri/Info.plist b/src-tauri/Info.plist
index 9dea8c50..f9b2044e 100644
--- a/src-tauri/Info.plist
+++ b/src-tauri/Info.plist
@@ -1,19 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
-<!--
- 合并进 macOS .app 的 Info.plist(issue #214)。
-
- WKWebView 里 dsh 页面(dsh-ears / dsh-voice-scribe)调用 getUserMedia 时,
- macOS 的 TCC 只读取宿主 .app 的用途说明:缺少 NSMicrophoneUsageDescription
- 时不会弹授权框,而是直接终止进程("attempted to access privacy-sensitive
- data without a usage description")。浏览器里正常、桌面端必现就是这个原因。
-
- 相机是同类问题:壳层的 iframe allow 与 WebView2 授权都放行 camera,
- macOS 侧若缺 NSCameraUsageDescription 同样会在采集时被杀进程。
-
- Tauri 会自动合并 tauri.conf.json 同目录下的 Info.plist,
- 这里仍在 bundle.macOS.infoPlist 里显式声明,便于定位与回归。
--->
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
diff --git a/src-tauri/src/config/i18n.rs b/src-tauri/src/config/i18n.rs
index cdd42401..f2632940 100644
--- a/src-tauri/src/config/i18n.rs
+++ b/src-tauri/src/config/i18n.rs
@@ -50,6 +50,13 @@ pub fn t(key: &str) -> String {
"menu.hide_others" => ("隐藏其他", "Hide Others"),
"menu.show_all" => ("显示全部", "Show All"),
"menu.view" => ("视图", "View"),
+ "menu.toggle_sidebar" => ("显示/隐藏侧边栏", "Toggle Sidebar"),
+ "menu.toggle_right_panel" => ("显示/隐藏右侧面板", "Toggle Right Panel"),
+ "menu.open_terminal" => ("打开终端", "Open Terminal"),
+ "menu.search_chats" => ("查找聊天", "Search Chats"),
+ "menu.zoom_in" => ("放大", "Zoom In"),
+ "menu.zoom_out" => ("缩小", "Zoom Out"),
+ "menu.actual_size" => ("实际大小", "Actual Size"),
"menu.window" => ("窗口", "Window"),
"menu.minimize" => ("最小化", "Minimize"),
"menu.zoom" => ("缩放", "Zoom"),
diff --git a/src-tauri/src/desktop/builder.rs b/src-tauri/src/desktop/builder.rs
index acb6ae37..48b36184 100644
--- a/src-tauri/src/desktop/builder.rs
+++ b/src-tauri/src/desktop/builder.rs
@@ -33,6 +33,14 @@ use tauri::menu::{PredefinedMenuItem, Submenu};
#[cfg(target_os = "macos")]
static MACOS_FULLSCREEN_MENU_ITEM: OnceLock<Mutex<Option<MenuItem<Wry>>>> = OnceLock::new();
+#[cfg(target_os = "macos")]
+const MACOS_VIEW_COMMANDS: [(&str, &str); 4] = [
+ ("desktop-toggle-sidebar", "menu.toggle_sidebar"),
+ ("desktop-toggle-right-panel", "menu.toggle_right_panel"),
+ ("desktop-open-terminal", "menu.open_terminal"),
+ ("desktop-search-chats", "menu.search_chats"),
+];
+
#[cfg(windows)]
use crate::desktop::window::on_page_load;
use crate::desktop::window::{on_download, on_new_window};
@@ -308,12 +316,52 @@ pub fn install_macos_menu(app: &tauri::AppHandle<Wry>) -> tauri::Result<()> {
true,
&[&profiles, &plugins, &harness, &run_separator, &restart],
)?;
+ let view_commands = MACOS_VIEW_COMMANDS
+ .iter()
+ .map(|(id, key)| {
+ MenuItem::with_id(app, *id, crate::config::i18n::t(key), false, None::<&str>)
+ })
+ .collect::<tauri::Result<Vec<_>>>()?;
+ let view_separator = PredefinedMenuItem::separator(app)?;
+ let zoom_in = MenuItem::with_id(
+ app,
+ "desktop-zoom-in",
+ crate::config::i18n::t("menu.zoom_in"),
+ true,
+ Some("CmdOrCtrl+Equal"),
+ )?;
+ let zoom_out = MenuItem::with_id(
+ app,
+ "desktop-zoom-out",
+ crate::config::i18n::t("menu.zoom_out"),
+ true,
+ Some("CmdOrCtrl+-"),
+ )?;
+ let zoom_reset = MenuItem::with_id(
+ app,
+ "desktop-zoom-reset",
+ crate::config::i18n::t("menu.actual_size"),
+ true,
+ Some("CmdOrCtrl+0"),
+ )?;
+ let fullscreen_separator = PredefinedMenuItem::separator(app)?;
let view_menu = Submenu::with_id_and_items(
app,
"desktop-view-menu",
crate::config::i18n::t("menu.view"),
true,
- &[&fullscreen],
+ &[
+ &view_commands[0],
+ &view_commands[1],
+ &view_commands[2],
+ &view_commands[3],
+ &view_separator,
+ &zoom_in,
+ &zoom_out,
+ &zoom_reset,
+ &fullscreen_separator,
+ &fullscreen,
+ ],
)?;
let about = MenuItem::with_id(
@@ -501,6 +549,7 @@ pub fn install_macos_menu(app: &tauri::AppHandle<Wry>) -> tauri::Result<()> {
.get_or_init(|| Mutex::new(None))
.lock()
.unwrap_or_else(|error| error.into_inner()) = Some(fullscreen);
+ app.emit("macos-menu-rebuilt", ())?;
Ok(())
}
@@ -513,6 +562,63 @@ fn fullscreen_menu_label_key(is_fullscreen: bool) -> &'static str {
}
}
+#[derive(serde::Deserialize)]
+pub struct ViewMenuEntry {
+ id: String,
+ enabled: bool,
+ shortcut: Option<String>,
+}
+
+#[tauri::command]
+pub fn sync_view_menu(
+ window: tauri::WebviewWindow<Wry>,
+ entries: Vec<ViewMenuEntry>,
+) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ {
+ if window.label() == crate::desktop::pet::PET_WINDOW_LABEL
+ || !window.is_focused().unwrap_or(false)
+ {
+ return Ok(());
+ }
+ let Some(menu) = window.app_handle().menu() else {
+ return Ok(());
+ };
+ let Some(view) = menu.get("desktop-view-menu") else {
+ return Ok(());
+ };
+ let Some(view) = view.as_submenu() else {
+ return Ok(());
+ };
+ for (id, key) in MACOS_VIEW_COMMANDS {
+ let Some(item) = view.get(id) else {
+ continue;
+ };
+ let Some(item) = item.as_menuitem() else {
+ continue;
+ };
+ let entry = entries.iter().find(|entry| entry.id == id);
+ let enabled = entry.is_some_and(|entry| entry.enabled);
+ let mut label = crate::config::i18n::t(key);
+ if enabled {
+ if let Some(shortcut) = entry
+ .and_then(|entry| entry.shortcut.as_deref())
+ .filter(|shortcut| shortcut.len() <= 80)
+ {
+ label.push_str(" ");
+ label.push_str(shortcut);
+ }
+ }
+ item.set_text(label)
+ .and_then(|_| item.set_enabled(enabled))
+ .map_err(|error| format!("VIEW_MENU_SYNC_FAILED: {error}"))?;
+ }
+ }
+ #[cfg(not(target_os = "macos"))]
+ let _ = (window, entries);
+ Ok(())
+}
+
/// 原生全屏动画会连续触发 Resize;只在状态真正变化时刷新菜单文案。
#[cfg(target_os = "macos")]
fn sync_macos_fullscreen_menu(window: &tauri::Window<Wry>) {
@@ -1200,6 +1306,7 @@ pub fn handler() -> impl Fn(Invoke<Wry>) -> bool + Send + Sync + 'static {
crate::bridge::read_clipboard_image,
crate::bridge::write_clipboard_text,
crate::desktop::window::create_app_window,
+ crate::desktop::builder::sync_view_menu,
crate::desktop::window::quit_app,
crate::bridge::log_frontend,
crate::bridge::get_pet_status,
@@ -1266,6 +1373,24 @@ pub fn builder() -> tauri::Builder<tauri::Wry> {
Ok(())
})
.on_menu_event(|app, event| match event.id().as_ref() {
+ "desktop-toggle-sidebar"
+ | "desktop-toggle-right-panel"
+ | "desktop-open-terminal"
+ | "desktop-search-chats"
+ | "desktop-zoom-in"
+ | "desktop-zoom-out"
+ | "desktop-zoom-reset" => {
+ if let Some(window) = app.webview_windows().into_values().find(|window| {
+ window.label() != crate::desktop::pet::PET_WINDOW_LABEL
+ && window.is_focused().unwrap_or(false)
+ }) {
+ if let Err(error) =
+ app.emit_to(window.label(), "macos-menu-action", event.id().as_ref())
+ {
+ log::warn!("[menu] failed to emit View action: {error}");
+ }
+ }
+ }
#[cfg(target_os = "macos")]
"desktop-fullscreen" => {
if let Some(window) = app.webview_windows().into_values().find(|window| {
diff --git a/src/hooks/use-dsh-shortcuts.ts b/src/hooks/use-dsh-shortcuts.ts
index 5ab96978..45f7cbbf 100644
--- a/src/hooks/use-dsh-shortcuts.ts
+++ b/src/hooks/use-dsh-shortcuts.ts
@@ -6,8 +6,18 @@ export interface DshShortcutRow {
label: string
keys: readonly string[]
aria?: string
+ available?: boolean
}
+export const DSH_VIEW_COMMANDS = [
+ { action: 'desktop-toggle-sidebar', command: 'sidebar.left.toggle', label: 'menu.toggle_sidebar' },
+ { action: 'desktop-toggle-right-panel', command: 'sidebar.right.toggle', label: 'menu.toggle_right_panel' },
+ { action: 'desktop-open-terminal', command: 'terminal.new', label: 'menu.open_terminal' },
+ { action: 'desktop-search-chats', command: 'session.search', label: 'menu.search_chats' },
+] as const
+
+export type DshViewCommand = typeof DSH_VIEW_COMMANDS[number]['command']
+
export const useDshShortcuts = createGlobalState<{ rows: readonly DshShortcutRow[] }>({ rows: [] })
/**
diff --git a/src/i18n/locales/en-US.json b/src/i18n/locales/en-US.json
index 51b58e74..c205f436 100644
--- a/src/i18n/locales/en-US.json
+++ b/src/i18n/locales/en-US.json
@@ -79,6 +79,13 @@
"menu.hide_others": "Hide Others",
"menu.show_all": "Show All",
"menu.view": "View",
+ "menu.toggle_sidebar": "Toggle Sidebar",
+ "menu.toggle_right_panel": "Toggle Right Panel",
+ "menu.open_terminal": "Open Terminal",
+ "menu.search_chats": "Search Chats",
+ "menu.zoom_in": "Zoom In",
+ "menu.zoom_out": "Zoom Out",
+ "menu.actual_size": "Actual Size",
"menu.window": "Window",
"menu.minimize": "Minimize",
"menu.zoom": "Zoom",
diff --git a/src/i18n/locales/zh-CN.json b/src/i18n/locales/zh-CN.json
index 0e466326..d6e9a40b 100644
--- a/src/i18n/locales/zh-CN.json
+++ b/src/i18n/locales/zh-CN.json
@@ -79,6 +79,13 @@
"menu.hide_others": "隐藏其他",
"menu.show_all": "显示全部",
"menu.view": "视图",
+ "menu.toggle_sidebar": "显示/隐藏侧边栏",
+ "menu.toggle_right_panel": "显示/隐藏右侧面板",
+ "menu.open_terminal": "打开终端",
+ "menu.search_chats": "查找聊天",
+ "menu.zoom_in": "放大",
+ "menu.zoom_out": "缩小",
+ "menu.actual_size": "实际大小",
"menu.window": "窗口",
"menu.minimize": "最小化",
"menu.zoom": "缩放",
diff --git a/src/layout/components/navbar.tsx b/src/layout/components/navbar.tsx
index 45e795be..0523978e 100644
--- a/src/layout/components/navbar.tsx
+++ b/src/layout/components/navbar.tsx
@@ -1,3 +1,4 @@
+import type { DshViewCommand } from '@/hooks/use-dsh-shortcuts'
import type { DshPlugin } from '@/types'
import type { ConfigTab } from '@/ui/dialog/config'
import {
@@ -20,7 +21,7 @@ import { If } from 'react-if-lite'
import { cn } from 'tailwind-variants'
import { useStore } from 'valtio-define'
import { queryKeys } from '@/config/query-keys'
-import { shortcutHint, useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
+import { DSH_VIEW_COMMANDS, shortcutHint, useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
import { useDshStyle } from '@/hooks/use-dsh-style'
import { useListen } from '@/hooks/use-listen'
import { store } from '@/store'
@@ -225,9 +226,10 @@ export interface NavbarProps {
onOpenFolder?: () => void
/** 显示键盘快捷键:向 iframe 发 `dsh://shortcuts:open`,弹官方 `shortcuts.open` 弹层(官方蒙版);传入时该项可用 */
onOpenShortcuts?: () => void
+ onViewCommand?: (command: DshViewCommand) => void
}
-export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onOpenMachineManager, onOpenSyncToRemote }: NavbarProps) {
+export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSidebar, onNewChat, onOpenFolder, onOpenShortcuts, onViewCommand, onOpenMachineManager, onOpenSyncToRemote }: NavbarProps) {
const { t } = useTranslation()
const isFullscreen = useMacOSFullscreen()
const isMaximized = useMaximized()
@@ -386,12 +388,24 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb
}
}
- // macOS 原生菜单 → 复用壳层已有操作;非 macOS 无原生菜单,直接忽略事件。
- // (useListen 内部把回调放在 ref 转发,这里读到的始终是最新的处理函数。)
useListen<string>('macos-menu-action', (event) => {
if (!IS_MACOS)
return
+ const viewCommand = DSH_VIEW_COMMANDS.find(item => item.action === event.payload)
+ if (viewCommand) {
+ onViewCommand?.(viewCommand.command)
+ return
+ }
switch (event.payload) {
+ case 'desktop-zoom-in':
+ store.setting.zoom('increase')
+ break
+ case 'desktop-zoom-out':
+ store.setting.zoom('decrease')
+ break
+ case 'desktop-zoom-reset':
+ store.setting.zoom('reset')
+ break
case 'desktop-config':
handleOpenConfig('application')
break
@@ -432,7 +446,7 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb
onOpenFolder?.()
break
}
- })
+ }, { target: getCurrentWindow().label })
return (
<div
@@ -531,6 +545,46 @@ export function Navbar({ onRemoteChange, sidebarCollapsed = false, onToggleSideb
</Dropdown.Menu>
</Dropdown.Popover>
</Dropdown>
+ <Dropdown>
+ <Button
+ className="rounded-lg h-6 text-[12.5px] px-1.5"
+ size="sm"
+ variant="ghost"
+ aria-label={t('menu.view')}
+ data-testid="dsh-navbar-menu-view"
+ >
+ {t('menu.view')}
+ </Button>
+ <Dropdown.Popover className="rounded-md min-w-55" data-testid="dsh-navbar-menu-popover">
+ <Dropdown.Menu>
+ <Dropdown.Section>
+ {DSH_VIEW_COMMANDS.map(item => (
+ <Dropdown.Item
+ key={item.command}
+ id={item.command}
+ className="rounded-md"
+ isDisabled={onViewCommand == null || !shortcutRows.some(row => row.id === item.command && row.available === true)}
+ textValue={t(item.label)}
+ onAction={() => onViewCommand?.(item.command)}
+ >
+ <ShortcutLabel label={t(item.label)} hint={shortcutHint(shortcutRows, item.command)} />
+ </Dropdown.Item>
+ ))}
+ </Dropdown.Section>
+ <Dropdown.Section>
+ <Dropdown.Item id="zoom-in" className="rounded-md" textValue={t('menu.zoom_in')} onAction={() => store.setting.zoom('increase')}>
+ <ShortcutLabel label={t('menu.zoom_in')} hint="Ctrl + +" />
+ </Dropdown.Item>
+ <Dropdown.Item id="zoom-out" className="rounded-md" textValue={t('menu.zoom_out')} onAction={() => store.setting.zoom('decrease')}>
+ <ShortcutLabel label={t('menu.zoom_out')} hint="Ctrl + -" />
+ </Dropdown.Item>
+ <Dropdown.Item id="zoom-reset" className="rounded-md" textValue={t('menu.actual_size')} onAction={() => store.setting.zoom('reset')}>
+ <ShortcutLabel label={t('menu.actual_size')} hint="Ctrl + 0" />
+ </Dropdown.Item>
+ </Dropdown.Section>
+ </Dropdown.Menu>
+ </Dropdown.Popover>
+ </Dropdown>
<Dropdown isOpen={runMenuOpen} onOpenChange={setRunMenuOpen}>
{' '}
<Button
diff --git a/src/layout/components/view-menu.test.tsx b/src/layout/components/view-menu.test.tsx
new file mode 100644
index 00000000..16ff1794
--- /dev/null
+++ b/src/layout/components/view-menu.test.tsx
@@ -0,0 +1,237 @@
+// @vitest-environment jsdom
+import type { EventTarget } from '@tauri-apps/api/event'
+import type { ComponentProps, RefObject } from 'react'
+import { mockIPC, mockWindows } from '@tauri-apps/api/mocks'
+import { act, cleanup, fireEvent, render, renderHook, screen, waitFor } from '@testing-library/react'
+import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
+import { Navbar } from './navbar'
+import { Webview } from './webview'
+
+const { store, userAgent } = vi.hoisted(() => {
+ const userAgent = navigator.userAgent
+ Object.defineProperty(navigator, 'userAgent', { configurable: true, value: 'Macintosh' })
+ return {
+ userAgent,
+ store: {
+ harness: { status: 'ready', serviceHealthy: true },
+ recovery: { recovery: { required: false } },
+ desktopUpdater: { updateInfo: null },
+ setting: { zoom: vi.fn() },
+ },
+ }
+})
+
+vi.mock('@/store', () => ({ store }))
+vi.mock('valtio-define', () => ({ useStore: (value: unknown) => value }))
+vi.mock('@tauri-apps/plugin-os', () => ({ type: () => 'macos' }))
+vi.mock('@tanstack/react-query', () => ({ useQuery: () => ({ data: [] }) }))
+vi.mock('@overlastic/react', () => ({ useOverlay: () => vi.fn() }))
+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }))
+vi.mock('@/hooks/use-dsh-style', () => ({ useDshStyle: () => [{}] }))
+vi.mock('@/ui/dialog/about', () => ({ DesktopAboutDialog: () => null }))
+vi.mock('@/ui/dialog/config', () => ({ ConfigDialog: () => null }))
+vi.mock('@/ui/dialog/update', () => ({ DesktopUpdateDialog: () => null }))
+vi.mock('@/utils/clipboard', () => ({ writeClipboardText: vi.fn() }))
+vi.mock('@/utils/toast', () => ({ toast: vi.fn() }))
+vi.mock('@/ui/plugin/recovery', () => ({ Recovery: () => null }))
+vi.mock('./setup', () => ({ Setup: () => null }))
+vi.mock('./setup-preinstall', () => ({ PreinstallSetup: () => null }))
+vi.mock('./iframe', () => ({
+ Iframe: ({ iframeRef, srcOverride }: { iframeRef: RefObject<HTMLIFrameElement | null>, srcOverride: string | null }) => (
+ <iframe ref={iframeRef} title="Harness" src={srcOverride ?? 'http://127.0.0.1:3081'} />
+ ),
+}))
+vi.mock('./remote-switcher', () => ({
+ RemoteSwitcher: ({ onChange }: { onChange: (url: string, tint: string | null) => void }) => (
+ <>
+ <button onClick={() => onChange('http://127.0.0.1:4001', null)}>Remote alpha</button>
+ <button onClick={() => onChange('http://127.0.0.1:4002', null)}>Remote beta</button>
+ <button onClick={() => onChange('', null)}>Local</button>
+ </>
+ ),
+}))
+
+interface Listener {
+ event: string
+ target: EventTarget
+ handler: number
+}
+
+interface MenuEntry {
+ id: string
+ enabled: boolean
+ shortcut: string | null
+}
+
+const listeners = new Map<number, Listener>()
+let menuEntries: MenuEntry[]
+
+function nativeEvent(event: string, payload?: unknown, label?: string) {
+ const runtime = window as unknown as { __TAURI_INTERNALS__: { runCallback: (id: number, data: unknown) => void } }
+ for (const [id, listener] of listeners) {
+ if (listener.event !== event)
+ continue
+ if (label !== undefined && listener.target.kind !== 'Any' && (!('label' in listener.target) || listener.target.label !== label))
+ continue
+ runtime.__TAURI_INTERNALS__.runCallback(listener.handler, { event, id, payload })
+ }
+}
+
+function iframe() {
+ return screen.getByTitle<HTMLIFrameElement>('Harness')
+}
+
+function reportShortcuts() {
+ const frame = iframe()
+ act(() => {
+ window.dispatchEvent(new MessageEvent('message', {
+ source: frame.contentWindow,
+ origin: new URL(frame.src).origin,
+ data: {
+ type: 'dsh://shortcuts',
+ rows: [{ id: 'sidebar.left.toggle', label: 'Sidebar', keys: ['⌥', '⌘', 'B'], available: true }],
+ },
+ }))
+ })
+}
+
+beforeEach(() => {
+ listeners.clear()
+ menuEntries = []
+ store.harness.status = 'ready'
+ store.harness.serviceHealthy = true
+ store.setting.zoom.mockClear()
+ mockWindows('main')
+ mockIPC((command, args) => {
+ switch (command) {
+ case 'plugin:event|listen': {
+ const listener = args as unknown as Listener
+ listeners.set(listener.handler, listener)
+ return listener.handler
+ }
+ case 'plugin:event|unlisten':
+ listeners.delete((args as { eventId: number }).eventId)
+ return
+ case 'sync_view_menu':
+ menuEntries = structuredClone((args as { entries: MenuEntry[] }).entries)
+ return
+ case 'plugin:window|is_fullscreen':
+ case 'plugin:window|is_maximized':
+ return false
+ default:
+ throw new Error(`Unexpected native command: ${command}`)
+ }
+ })
+ const { result, unmount } = renderHook(useDshShortcuts)
+ act(() => result.current[1]({ rows: [] }))
+ unmount()
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+afterAll(() => {
+ Object.defineProperty(navigator, 'userAgent', { configurable: true, value: userAgent })
+})
+
+describe('native View menu state', () => {
+ it('restores enabled commands and hints after the language change rebuilds the native menu', async () => {
+ render(<Webview />)
+ reportShortcuts()
+ await waitFor(() => expect(menuEntries[0]).toEqual({ id: 'desktop-toggle-sidebar', enabled: true, shortcut: '⌥ ⌘ B' }))
+ menuEntries = menuEntries.map(entry => ({ ...entry, enabled: false, shortcut: null }))
+ act(() => nativeEvent('macos-menu-rebuilt'))
+ await waitFor(() => expect(menuEntries[0]).toEqual({ id: 'desktop-toggle-sidebar', enabled: true, shortcut: '⌥ ⌘ B' }))
+ expect(menuEntries.slice(1).map(entry => entry.enabled)).toEqual([false, false, false])
+ })
+
+ it('keeps the remote catalog and command bridge during a local service restart', async () => {
+ const view = render(<Webview />)
+ fireEvent.click(screen.getByRole('button', { name: 'Remote alpha' }))
+ reportShortcuts()
+ const frame = iframe()
+ const post = vi.spyOn(frame.contentWindow!, 'postMessage')
+ store.harness.serviceHealthy = false
+ view.rerender(<Webview />)
+ act(() => nativeEvent('tauri://focus', null, 'main'))
+ await waitFor(() => expect(menuEntries[0].enabled).toBe(true))
+ act(() => nativeEvent('macos-menu-action', 'desktop-toggle-sidebar', 'main'))
+ expect(post).toHaveBeenCalledExactlyOnceWith({ source: 'dsh-desktop', type: 'dsh://view:command', command: 'sidebar.left.toggle' }, 'http://127.0.0.1:4001')
+ expect(iframe()).toBe(frame)
+ store.harness.serviceHealthy = true
+ view.rerender(<Webview />)
+ await waitFor(() => expect(menuEntries[0].enabled).toBe(true))
+ })
+
+ it('clears the local catalog when the local service becomes unavailable', async () => {
+ const view = render(<Webview />)
+ reportShortcuts()
+ store.harness.serviceHealthy = false
+ view.rerender(<Webview />)
+ await waitFor(() => expect(menuEntries.map(entry => entry.enabled)).toEqual([false, false, false, false]))
+ store.harness.serviceHealthy = true
+ view.rerender(<Webview />)
+ expect(menuEntries[0]).toEqual({ id: 'desktop-toggle-sidebar', enabled: false, shortcut: null })
+ })
+
+ it.each(['Remote beta', 'Local'])('clears the previous remote catalog when switching to %s', async (destination) => {
+ render(<Webview />)
+ fireEvent.click(screen.getByRole('button', { name: 'Remote alpha' }))
+ reportShortcuts()
+ fireEvent.click(screen.getByRole('button', { name: destination }))
+ await waitFor(() => expect(menuEntries[0]).toEqual({ id: 'desktop-toggle-sidebar', enabled: false, shortcut: null }))
+ reportShortcuts()
+ await waitFor(() => expect(menuEntries[0].enabled).toBe(true))
+ })
+
+ it('clears the remote catalog when the shell removes the iframe', async () => {
+ const view = render(<Webview />)
+ fireEvent.click(screen.getByRole('button', { name: 'Remote alpha' }))
+ reportShortcuts()
+ store.harness.status = 'error'
+ view.rerender(<Webview />)
+ expect(screen.queryByTitle('Harness')).toBeNull()
+ await waitFor(() => expect(menuEntries[0].enabled).toBe(false))
+ store.harness.status = 'ready'
+ view.rerender(<Webview />)
+ expect(menuEntries[0].shortcut).toBeNull()
+ })
+})
+
+describe('native View menu recipients', () => {
+ function mountWindow(label: string, props: Partial<ComponentProps<typeof Navbar>> = {}) {
+ mockWindows(label)
+ return render(<Navbar onRemoteChange={vi.fn()} {...props} />)
+ }
+
+ it.each(['main', 'remote-alpha'])('delivers a targeted core command only to %s', async (label) => {
+ const main = vi.fn()
+ const remote = vi.fn()
+ mountWindow('main', { onViewCommand: main })
+ mountWindow('remote-alpha', { onViewCommand: remote })
+ await waitFor(() => expect([...listeners.values()].filter(listener => listener.event === 'macos-menu-action')).toHaveLength(2))
+ act(() => nativeEvent('macos-menu-action', 'desktop-open-terminal', label))
+ expect(main.mock.calls).toEqual(label === 'main' ? [['terminal.new']] : [])
+ expect(remote.mock.calls).toEqual(label === 'remote-alpha' ? [['terminal.new']] : [])
+ })
+
+ it('applies a targeted zoom action once when two shell windows are open', async () => {
+ mountWindow('main')
+ mountWindow('remote-alpha')
+ act(() => nativeEvent('macos-menu-action', 'desktop-zoom-in', 'remote-alpha'))
+ expect(store.setting.zoom).toHaveBeenCalledExactlyOnceWith('increase')
+ })
+
+ it('unsubscribes the recipient when its shell window closes', async () => {
+ const command = vi.fn()
+ const view = mountWindow('remote-alpha', { onViewCommand: command })
+ await waitFor(() => expect([...listeners.values()].filter(listener => listener.event === 'macos-menu-action')).toHaveLength(1))
+ view.unmount()
+ await waitFor(() => expect([...listeners.values()].filter(listener => listener.event === 'macos-menu-action')).toEqual([]))
+ act(() => nativeEvent('macos-menu-action', 'desktop-open-terminal', 'remote-alpha'))
+ expect(command).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/layout/components/webview.tsx b/src/layout/components/webview.tsx
index 5de2fb31..c80c92ff 100644
--- a/src/layout/components/webview.tsx
+++ b/src/layout/components/webview.tsx
@@ -1,11 +1,16 @@
-import type { DshShortcutRow } from '@/hooks/use-dsh-shortcuts'
+import type { DshShortcutRow, DshViewCommand } from '@/hooks/use-dsh-shortcuts'
+import { useWatch } from '@reause/core'
+import { invoke } from '@tauri-apps/api/core'
+import { getCurrentWindow } from '@tauri-apps/api/window'
+import { type } from '@tauri-apps/plugin-os'
import { useRef, useState } from 'react'
import { If } from 'react-if-lite'
import { useStore } from 'valtio-define'
-import { useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
+import { DSH_VIEW_COMMANDS, shortcutHint, useDshShortcuts } from '@/hooks/use-dsh-shortcuts'
import { useDshStyle } from '@/hooks/use-dsh-style'
import { useIframeMessage } from '@/hooks/use-iframe-message'
import { useIframePost } from '@/hooks/use-iframe-post'
+import { useListen } from '@/hooks/use-listen'
import { store } from '@/store'
import { Recovery } from '@/ui/plugin/recovery'
import { Iframe } from './iframe'
@@ -13,41 +18,52 @@ import { Navbar } from './navbar'
import { Setup } from './setup'
import { PreinstallSetup } from './setup-preinstall'
-/** 导航桥回报消息类型(iframe → 宿主) */
interface NavBridgeMessage {
type?: string
collapsed?: boolean
rows?: unknown
}
-/**
- * 主区域视图(Webview)
- *
- * 壳层导航栏(Navbar)常驻顶部,根据 harness 状态动态渲染主内容区:
- * - error: 错误页 / 插件全屏恢复页
- * - preinstall: 预装插件引导页
- * - ready: 渲染标准 iframe 界面
- * - other: 通用初始化 Setup 页
- */
export function Webview() {
- // 1. 状态与引用声明
const [sidebarCollapsed, setSidebarCollapsed] = useState(false)
const iframeRef = useRef<HTMLIFrameElement>(null)
const post = useIframePost(iframeRef)
const [dshStyle] = useDshStyle()
- const [, setDshShortcuts] = useDshShortcuts()
+ const [{ rows: shortcutRows }, setDshShortcuts] = useDshShortcuts()
const { status, serviceHealthy } = useStore(store.harness)
const { recovery } = useStore(store.recovery)
- const [{ url: activeTunnelUrl, tint: borderTint }, setRemoteView] = useState({ url: '', tint: null as string | null })
+ const [remoteView, setRemoteView] = useState({ url: '', tint: null as string | null })
+ const { url: activeTunnelUrl, tint: borderTint } = remoteView
const remoteMode = activeTunnelUrl !== ''
+ const live = status === 'ready' && (remoteMode || serviceHealthy)
+
+ function syncViewMenu() {
+ if (type() !== 'macos')
+ return
+ void invoke('sync_view_menu', {
+ entries: DSH_VIEW_COMMANDS.map(item => ({
+ id: item.action,
+ enabled: live && shortcutRows.some(row => row.id === item.command && row.available === true),
+ shortcut: shortcutHint(shortcutRows, item.command) ?? null,
+ })),
+ }).catch(error => console.error('[Webview] failed to sync View menu:', error))
+ }
+
+ useWatch([shortcutRows, live], syncViewMenu, { immediate: true })
+ useWatch(activeTunnelUrl, () => setDshShortcuts({ rows: [] }))
+ useWatch(live, (ready) => {
+ if (!ready)
+ setDshShortcuts({ rows: [] })
+ })
+ useListen('tauri://focus', syncViewMenu, { target: getCurrentWindow().label })
+ useListen('macos-menu-rebuilt', syncViewMenu, { target: getCurrentWindow().label })
function handleRemoteChange(url: string, tint: string | null) {
setRemoteView({ url, tint })
}
- // 2. Iframe 消息通信监听
useIframeMessage<NavBridgeMessage>(iframeRef, (data) => {
if (data.type === 'dsh://sidebar:collapsed') {
setSidebarCollapsed(Boolean(data.collapsed))
@@ -57,7 +73,6 @@ export function Webview() {
}
})
- // 4. 根据当前状态决定中间区域渲染内容
const renderContent = () => {
switch (status) {
case 'error':
@@ -81,21 +96,16 @@ export function Webview() {
}
}
- // iframe 缺席时没有协议接收方,不下发依赖它的回调:导航栏据此隐藏侧边栏开关、
- // 禁用「新聊天」「打开文件夹」「管理机器」,而不是留死按钮。
- // 判定必须与 `renderContent()` 的 iframe 条件完全一致:`status` 回到 `error`
- // (shutdown / 客户端 boot 失败)时 iframe 已卸载,但 `serviceHealthy` 可能仍为
- // true——只看后者会把回调发给已摘除的接收方,按钮点了没反应。
- const bridge = status === 'ready' && serviceHealthy
+ const bridge = live
? {
onToggleSidebar: () => post({ type: 'dsh://sidebar:toggle' }),
onNewChat: () => post({ type: 'dsh://session:new' }),
onOpenFolder: () => post({ type: 'dsh://workspace:add' }),
onOpenShortcuts: () => post({ type: 'dsh://shortcuts:open' }),
+ onViewCommand: (command: DshViewCommand) => post({ type: 'dsh://view:command', command }),
}
: {}
- // 5. 统一布局输出
return (
<main className="relative flex flex-col min-h-0 flex-1" style={dshStyle.frame || {}}>
<Navbar onRemoteChange={handleRemoteChange} sidebarCollapsed={sidebarCollapsed} {...bridge} />
@@ -106,7 +116,6 @@ export function Webview() {
)
}
-/** 目录行校验:只接受有 id 与文案的行,键位逐项取字符串(桥消息按不可信输入处理)。 */
function parseShortcutRows(rows: unknown): DshShortcutRow[] {
if (!Array.isArray(rows))
return []
@@ -114,7 +123,7 @@ function parseShortcutRows(rows: unknown): DshShortcutRow[] {
for (const row of rows) {
if (typeof row !== 'object' || row === null)
continue
- const entry = row as { id?: unknown, label?: unknown, keys?: unknown, aria?: unknown }
+ const entry = row as { id?: unknown, label?: unknown, keys?: unknown, aria?: unknown, available?: unknown }
if (typeof entry.id !== 'string' || typeof entry.label !== 'string')
continue
out.push({
@@ -122,6 +131,7 @@ function parseShortcutRows(rows: unknown): DshShortcutRow[] {
label: entry.label,
keys: Array.isArray(entry.keys) ? entry.keys.filter((key): key is string => typeof key === 'string') : [],
...typeof entry.aria === 'string' ? { aria: entry.aria } : {},
+ available: entry.available === true,
})
}
return out
diff --git a/test/macos-run-menu.test.ts b/test/macos-run-menu.test.ts
index d170682f..10412442 100644
--- a/test/macos-run-menu.test.ts
+++ b/test/macos-run-menu.test.ts
@@ -6,9 +6,9 @@ const navbarSource = readFileSync(new URL('../src/layout/components/navbar.tsx',
const i18nSource = readFileSync(new URL('../src-tauri/src/config/i18n.rs', import.meta.url), 'utf8')
function submenuItems(id: string) {
- const match = builderSource.match(new RegExp(`"${id}",\\s*crate::config::i18n::t\\("[^"]+"\\),\\s*true,\\s*&\\[([^\\]]+)\\]`))
+ const match = builderSource.match(new RegExp(`"${id}",\\s*crate::config::i18n::t\\("[^"]+"\\),\\s*true,\\s*&\\[([\\s\\S]*?)\\],?\\s*\\)`))
expect(match, `${id} must be installed with native menu items`).not.toBeNull()
- return match![1].match(/&\w+/g)
+ return match![1].match(/&\w+(?:\[\d+\])?/g)
}
describe('macOS native menu', () => {
@@ -78,7 +78,18 @@ describe('macOS native menu', () => {
})
it('toggles the focused shell window from View without suppressing AppKit fullscreen in Window', () => {
- expect(submenuItems('desktop-view-menu')).toEqual(['&fullscreen'])
+ expect(submenuItems('desktop-view-menu')).toEqual([
+ '&view_commands[0]',
+ '&view_commands[1]',
+ '&view_commands[2]',
+ '&view_commands[3]',
+ '&view_separator',
+ '&zoom_in',
+ '&zoom_out',
+ '&zoom_reset',
+ '&fullscreen_separator',
+ '&fullscreen',
+ ])
expect(builderSource).not.toContain('PredefinedMenuItem::fullscreen(')
expect(builderSource).toMatch(/MenuItem::with_id\(\s*app,\s*"desktop-fullscreen",\s*&fullscreen_label,\s*true,\s*Some\("Ctrl\+Super\+F"\)/)
const handler = builderSource.slice(builderSource.indexOf('"desktop-fullscreen" =>'))
@@ -92,4 +103,16 @@ describe('macOS native menu', () => {
expect(builderSource).toContain('Some(fullscreen)')
expect(builderSource).toContain('sync_macos_fullscreen_menu(window)')
})
+
+ it('routes View actions only to the focused shell window', () => {
+ const handler = builderSource.slice(builderSource.indexOf('"desktop-toggle-sidebar"\n'))
+ expect(handler).toContain('window.label() != crate::desktop::pet::PET_WINDOW_LABEL')
+ expect(handler).toContain('window.is_focused().unwrap_or(false)')
+ expect(handler).toMatch(/app\.emit_to\(\s*window.label\(\),\s*"macos-menu-action",\s*event.id\(\).as_ref\(\),?\s*\)/)
+ })
+
+ it('requests current window state only after the rebuilt native menu is installed', () => {
+ const install = builderSource.slice(builderSource.indexOf('pub fn install_macos_menu('), builderSource.indexOf('fn fullscreen_menu_label_key'))
+ expect(install).toMatch(/app\.set_menu\(menu\)\?[\s\S]*window_menu\.set_as_windows_menu_for_nsapp\(\)\?[\s\S]*app\.emit\("macos-menu-rebuilt", \(\)\)\?/)
+ })
})