Merge pull request #9132 from deepseek-harness/fix/cua-copy

fix(cua): 完善自动电脑操作相关界面文案与实验性提示
This commit is contained in:
涂轶翔 authored and GitHub committed 2026-11-27 13:08:57 +08:00
commit 1e1f19dddb
34 files changed
+688 -444

No files matched your search

+8 -7
View File
@@ -19,7 +19,7 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
})
const name = 'host-platform-only'
await writeFile(join(root, 'package.json'), JSON.stringify({ name, version: '1.0.0', dsh: { bundle: {
patch: './cordis.patch.yml', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'],
patch: './cordis.patch.yml', platforms: ['freebsd'],
} } }))
await writeFile(join(root, 'cordis.patch.yml'), '- id: ptc-runtime\n config:\n executionMode: persistent-in-memory\n replScoped: false\n')
const scaffold = owned.scaffold = await launchWebScaffold({ profile: { packages: [{ dir: root }] } })
@@ -28,7 +28,8 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
await page.goto(scaffold.authenticatedUrl)
await connectFreshWorkspaceZh(page, scaffold.workspaceCwd)
await page.getByRole('navigation', { name: '全局面板' }).getByRole('button', { name: '插件', exact: true }).click()
const reason = '此插件不支持运行 DSH 的主机操作系统'
// No CI runner is FreeBSD, so one golden covers every Host; the id has no localized label and renders verbatim.
const reason = '此插件仅支持 freebsd'
const card = page.locator(`[data-plugin-package="${name}"]`)
await card.getByText(reason, { exact: true }).waitFor()
expect(await card.getByRole('switch').isEnabled()).toBe(false)
@@ -41,19 +42,19 @@ it('disables unsupported bundles, shows the Host restriction, and refuses direct
const beforeRuntime = runtimeId()
expect(beforeRuntime).toBeTypeOf('number')
expect(scaffold.ctx.ptcRuntime.programFormat).toBe('scoped-repl')
const names = [name]
const refusals: [string, string[]][] = [[name, ['freebsd']]]
await page.locator('[data-plugin-panel]').getByRole('button', { name: '更多', exact: true }).click()
const cua = page.locator('[data-plugin-package="@deepseek-ai/dsh-cua-bundle"]')
const cuaSupported = process.platform === 'darwin' || process.platform === 'win32'
expect(await cua.count()).toBe(cuaSupported ? 1 : 0)
if (!cuaSupported) {
expect((await scaffold.ctx.pluginManager.listBundles()).find(bundle => bundle.name === '@deepseek-ai/dsh-cua-bundle'))
.toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform' } })
names.push('@deepseek-ai/dsh-cua-bundle')
.toMatchObject({ listedByDefault: false, enabled: false, error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] } })
refusals.push(['@deepseek-ai/dsh-cua-bundle', ['darwin', 'win32']])
}
for (const bundle of names) {
for (const [bundle, platforms] of refusals) {
expect(await scaffold.ctx.pluginManager.setBundleEnabled(bundle, true)).toMatchObject({
changed: false, application: 'failed', error: { code: 'unsupported-platform' },
changed: false, application: 'failed', error: { code: 'unsupported-platform', platforms },
})
}
expect(await readFile(manifest, 'utf8')).toBe(before)
+5 -5
View File
@@ -112,7 +112,7 @@ it.skipIf(process.platform !== 'darwin').each([
await card.getByRole('status').getByText('正在应用 自动电脑操作 的更改', { exact: true }).waitFor({ state: 'hidden' })
const setup = page.getByRole('dialog', { name: '配置自动电脑操作', exact: true })
await setup.waitFor()
expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1)
expect(await setup.getByText('“自动电脑操作”已开启,但暂时无法检查系统权限。请前往插件详情页查看详情并重试。', { exact: true }).count()).toBe(1)
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/cua-permissions/setup.expected.md', import.meta.url)),
await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd), webSnapshotMode())
expect(await setup.getByRole('group', { name: '新会话默认模式', exact: true }).count()).toBe(0)
@@ -158,7 +158,7 @@ it.skipIf(process.platform !== 'darwin').each([
expect(runtimeFiber() === originalRuntimeFiber).toBe(true)
expect(scaffold.ctx.ptcRuntime.programFormat).toBe(script ? 'script' : 'function-body')
await setup.waitFor()
expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1)
expect(await setup.getByText('“自动电脑操作”已开启,但暂时无法检查系统权限。请前往插件详情页查看详情并重试。', { exact: true }).count()).toBe(1)
await setup.getByRole('button', { name: '稍后', exact: true }).click()
await setup.waitFor({ state: 'hidden' })
const saved = await readFile(settingsPath, 'utf8')
@@ -189,7 +189,7 @@ it.skipIf(process.platform !== 'darwin').each([
const detail = plugins.locator('[data-detail-document]')
await detail.getByRole('img', { name: '在多窗口桌面中自动操作选定任务看板窗口的示意图' }).waitFor()
const guidance = plugins.locator('[data-cua-guidance]')
await guidance.getByText(/请谨慎在生产环境中使用/).waitFor()
await guidance.getByText(/请谨慎在重要或生产环境中使用/).waitFor()
expect(await guidance.textContent()).not.toContain('helperPath')
expect(await detail.textContent()).not.toContain('PTC')
toggle = page.locator('[data-plugin-panel]').getByRole('switch', { name: '启用 自动电脑操作', exact: true })
@@ -232,11 +232,11 @@ it.skipIf(process.platform !== 'darwin').each([
await toggle.click()
await toggle.and(page.locator('[aria-checked="true"]')).waitFor({ state: 'visible' })
await setup.waitFor()
expect(await setup.getByText('“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。', { exact: true }).count()).toBe(1)
expect(await setup.getByText('“自动电脑操作”已开启,但暂时无法检查系统权限。请前往插件详情页查看详情并重试。', { exact: true }).count()).toBe(1)
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
await setup.getByRole('button', { name: '前往设置', exact: true }).click()
await setup.waitFor({ state: 'hidden' })
await page.getByRole('region', { name: '系统权限与设置', exact: true }).getByRole('alert').waitFor()
await page.getByRole('region', { name: '系统权限', exact: true }).getByRole('alert').waitFor()
expect(await readFile(settingsPath, 'utf8')).toBe(saved)
expect(scaffold.ctx.settings.describe().find(row => row.ns === 'ui-settings')?.value).toMatchObject({ enabled: codingTools })
expect(scaffold.ctx.agentPresets.defaultId).toBe(initialDefault)
+9 -13
View File
@@ -159,13 +159,13 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
const panel = page.locator('[data-cua-settings]')
const accessibility = panel.getByRole('group', { name: 'Accessibility', exact: true })
await accessibility.getByRole('button', { name: 'Request permission', exact: true }).waitFor()
expect(await panel.getByRole('region', { name: 'Authorize computer use', exact: true }).getByRole('group').count()).toBe(2)
expect(await panel.getByRole('region', { name: 'System permissions', exact: true }).getByRole('group').count()).toBe(2)
expect(await panel.getByRole('region', { name: 'Manage applications computer use can access', exact: true }).count()).toBe(1)
await expect.poll(() => panel.locator('li img').evaluate((image: HTMLImageElement) => image.naturalWidth)).toBe(1)
expect(await panel.getByText('/fixture/app', { exact: true }).count()).toBe(0)
expect(await accessibility.getByText('DSH Computer Use.app', { exact: true }).count()).toBe(1)
expect(await accessibility.textContent()).toContain('In System Settings, allow')
expect(await accessibility.textContent()).toContain('to read interface controls, click, and type.')
expect(await accessibility.textContent()).toContain('Allow')
expect(await accessibility.textContent()).toContain('to read interface content, click, and type.')
expect(await panel.getByRole('group', { name: 'Screen Recording', exact: true }).getByText('DSH Computer Use.app', { exact: true }).count()).toBe(1)
await expect.poll(() => accessibility.locator('img').evaluate((image: HTMLImageElement) => image.naturalWidth)).toBe(1)
await expect.poll(() => panel.getAttribute('aria-busy')).toBe('false')
@@ -334,7 +334,7 @@ it.skipIf(process.platform !== 'darwin')('keeps system requests pending until fr
expect(tripwire.pageErrors).toEqual([])
})
it.skipIf(process.platform !== 'darwin' && process.platform !== 'win32')('shows Windows setup when the helper is missing', async () => {
it.skipIf(process.platform !== 'darwin' && process.platform !== 'win32')('shows guidance without manual helper build instructions when the helper is missing', async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-cua-missing-helper-'))
const resources: { scaffold?: WebScaffold; browser?: Browser } = {}
onTestFinished(async () => {
@@ -348,12 +348,6 @@ it.skipIf(process.platform !== 'darwin' && process.platform !== 'win32')('shows
const scaffold = resources.scaffold = await launchWebScaffold({
profile: { packages: [{ dir: bundle, enabled: true }] }, extraOverlayPath: patch,
})
if (process.platform === 'darwin') {
// The Host inventory reads this Loader flag; only the platform-specific input is substituted on macOS.
const windows = [...scaffold.ctx.loader.entries()].find(entry => entry.options.id === 'cua-windows')
if (!windows) throw new Error('CUA bundle has no Windows provider row')
vi.spyOn(windows, 'disabled', 'get').mockReturnValue(false)
}
const browser = resources.browser = await chromium.launch()
const page = await newEnglishPage(browser)
await page.goto(scaffold.authenticatedUrl)
@@ -361,11 +355,13 @@ it.skipIf(process.platform !== 'darwin' && process.platform !== 'win32')('shows
await page.getByRole('button', { name: 'View Computer use', exact: true }).click()
const panel = page.locator('[data-cua-settings]')
const guidance = panel.locator('[data-cua-guidance]')
await guidance.getByText(/pnpm run build:native:x64/).waitFor()
await guidance.getByText(/helperPath/).waitFor()
await guidance.getByRole('note').getByText('Experimental feature', { exact: true }).waitFor()
await guidance.getByText(/We recommend using PTC mode/).waitFor()
expect(await guidance.textContent()).not.toContain('pnpm run build:native')
expect(await guidance.textContent()).not.toContain('helperPath')
const preview = page.locator('[data-detail-document] img')
await preview.evaluate(async (image) => { await (image as HTMLImageElement).decode() })
const firstSetting = panel.getByRole('heading', { name: 'Authorize computer use', exact: true })
const firstSetting = panel.getByRole('heading', { name: process.platform === 'win32' ? 'Manage applications computer use can access' : 'System permissions', exact: true })
const previewBox = await preview.boundingBox(), guidanceBox = await guidance.boundingBox(), settingBox = await firstSetting.boundingBox()
expect(previewBox!.y + previewBox!.height).toBeLessThanOrEqual(guidanceBox!.y)
expect(guidanceBox!.y + guidanceBox!.height).toBeLessThanOrEqual(settingBox!.y)
@@ -1 +1 @@
- status: 此插件不支持运行 DSH 的主机操作系统
- status: 此插件仅支持 freebsd
@@ -3,7 +3,7 @@
- strong: Fixture
- text: Allow agent to control this application via computer use?
- button "Risks"
- paragraph: Manage app permissions for all sessions on the plugin page.
- paragraph: Once allowed, the agent can view and operate this app. You can manage app permissions anytime in plugin settings.
- button "Reject"
- button "Allow for this session"
- button "Always allow"
@@ -1,15 +1,18 @@
- region "Authorize computer use":
- paragraph: Computer use is an experimental preview. The agent may click the wrong button or type in the wrong window. Use caution in production environments. We recommend native PTC mode so the agent can operate apps and call other tools in the same program.
- heading "Authorize computer use" [level=3]
- region "System permissions":
- note:
- paragraph: Experimental feature
- paragraph: Computer use is experimental and results are not guaranteed. The agent may click the wrong button or type in the wrong window. Use caution in important or production environments.
- paragraph: We recommend using PTC mode so the agent can operate apps and call other tools in the same program. You can set it as the default in Settings → Agent presets.
- heading "System permissions" [level=3]
- paragraph: "Computer use requires the following system permissions to run:"
- group "Accessibility":
- strong: Accessibility
- paragraph: In System Settings, allow DSH Computer Use.app to read interface controls, click, and type.
- paragraph: Allow DSH Computer Use.app to read interface content, click, and type.
- button "Request permission"
- group "Screen Recording":
- strong: Screen Recording
- paragraph: In System Settings, allow DSH Computer Use.app to capture application windows.
- paragraph: Allow DSH Computer Use.app to capture the selected application window.
- button "Request permission"
- paragraph: Manage Accessibility and Screen Recording permissions in System Settings.
- region "Manage applications computer use can access":
- heading "Manage applications computer use can access" [level=3]
- heading "Always-allowed applications" [level=4]
@@ -1,6 +1,6 @@
- dialog "配置自动电脑操作":
- heading "配置自动电脑操作" [level=2]
- button "关闭"
- paragraph: “自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。
- paragraph: “自动电脑操作”已开启,但暂时无法检查系统权限。请前往插件详情页查看详情并重试。
- button "稍后"
- button "前往设置"
+1 -1
View File
@@ -730,7 +730,7 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
expect(result.toggles.map(toggle => toggle.name).filter(name => standalone.includes(name))).toEqual([])
expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([])
expect(result.optional.filter(entry => entry.error !== null)).toEqual([
expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform' } }),
expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] } }),
])
// Metadata resolves through the Worker's Node internal modules: every optional bundle shows its title and icon.
expect(result.optional.filter(entry => entry.metaError !== null || entry.title !== 'object' || entry.icon !== 'string')).toEqual([])
+5 -5
View File
@@ -74,11 +74,11 @@ Application listeners are outside this package matrix. Desktop Host subscribes t
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:78`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | [`mcp-account`](../packages/mcp/mcp-account) |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:460`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | [`plugin-recommendations`](../packages/extensions/plugin-recommendations), `remotes` |
| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:466`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:473`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:480`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:462`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | [`plugin-recommendations`](../packages/extensions/plugin-recommendations), `remotes` |
| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:454`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:482`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:640`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:78`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
+5 -5
View File
@@ -76,11 +76,11 @@
| `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:78`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`llm-replay`](../packages/test-support/llm-replay), [`session-checkpoint-policy`](../packages/session/session-checkpoint-policy), [`session-title`](../packages/session/session-title), [`timeline`](../packages/experimental/timeline) |
| `mcp-manager/status` | `parallel` | [`packages/mcp/mcp-manager/src/types.ts:49`](../packages/mcp/mcp-manager/src/types.ts) | [`mcp-manager`](../packages/mcp/mcp-manager) (`parallel`) | [`mcp-account`](../packages/mcp/mcp-account) |
| `permission-presets/catalog-changed` | `emit` | [`packages/interaction/permission-presets/src/types.ts:62`](../packages/interaction/permission-presets/src/types.ts) | [`permission-presets`](../packages/interaction/permission-presets) (`events.dispatch`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:460`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | [`plugin-recommendations`](../packages/extensions/plugin-recommendations), `remotes` |
| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:466`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:473`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:452`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:480`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/changed` | `emit` | [`packages/boot/plugin-manager/src/types.ts:462`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | [`plugin-recommendations`](../packages/extensions/plugin-recommendations), `remotes` |
| `plugin-manager/install-log` | `emit` | [`packages/boot/plugin-manager/src/types.ts:468`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/install-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:475`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-manager/operation` | `parallel` | [`packages/boot/plugin-manager/src/types.ts:454`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`parallel`) | - |
| `plugin-manager/update-state` | `emit` | [`packages/boot/plugin-manager/src/types.ts:482`](../packages/boot/plugin-manager/src/types.ts) | [`plugin-manager`](../packages/boot/plugin-manager) (`emit`) | `remotes` |
| `plugin-market/changed` | `emit` | [`packages/boot/plugin-market/src/types.ts:174`](../packages/boot/plugin-market/src/types.ts) | [`plugin-market`](../packages/boot/plugin-market) (`emit`) | `remotes` |
| `schedule/changed` | `emit` | [`packages/schedule/schedule/src/types.ts:640`](../packages/schedule/schedule/src/types.ts) | [`schedule`](../packages/schedule/schedule) (`emit`) | `remotes` |
| `schedule/resolve-agent` | `waterfall` | [`packages/schedule/schedule/src/index.ts:78`](../packages/schedule/schedule/src/index.ts) | [`schedule`](../packages/schedule/schedule) (`waterfall`) | `server` |
@@ -11,7 +11,7 @@ export class UnsupportedBundlePlatformError extends Error {
* @param platforms Node platform names or `wsl` supported by the bundle.
* @param platform Operating system of the DSH Host.
*/
constructor(platforms: readonly string[], platform: string) {
constructor(readonly platforms: readonly string[], platform: string) {
super(`Bundle supports Host platforms ${platforms.join(', ')}; the DSH Host is running ${platform}`)
this.name = 'UnsupportedBundlePlatformError'
}
@@ -21,6 +21,8 @@ it.each(['darwin', 'win32', 'linux'])('allows undeclared platforms and an explic
it.each(['win32', 'linux'])('rejects macOS-only bundles on %s Hosts', (platform) => {
expect(() => { assertBundlePlatform(['darwin'], platform) }).toThrow(UnsupportedBundlePlatformError)
expect(() => { assertBundlePlatform(['darwin'], platform) }).toThrow(`the DSH Host is running ${platform}`)
expect(() => { assertBundlePlatform(['darwin', 'wsl'], platform) })
.toThrow(expect.objectContaining({ platforms: ['darwin', 'wsl'] }))
})
it.each([null, true, 'darwin', [], [1], [''], ['Darwin'], [' darwin'], ['macos'], ['darwin', 'linxu'], ['darwin', false]].map(platforms => ({ platforms })))('rejects malformed platform metadata $platforms', ({ platforms }) => {
+1 -1
View File
@@ -111,7 +111,7 @@ function messageOf(error: unknown): string { return error instanceof Error ? err
/** An expected refusal keeps its code; anything else becomes an operation error carrying its exact diagnostic. */
function managementError(error: unknown): ManagementError {
if (error instanceof UnsupportedBundlePlatformError) return { code: 'unsupported-platform' }
if (error instanceof UnsupportedBundlePlatformError) return { code: 'unsupported-platform', platforms: [...error.platforms] }
if (!(error instanceof ManagementFailure)) return { code: 'operation-error', diagnostic: messageOf(error) }
return { code: error.code, ...error.incompatible === undefined ? {} : { incompatible: error.incompatible } }
}
@@ -40,6 +40,8 @@ export interface ManagementError {
diagnostic?: string
/** Present with `incompatible-version`: the packages the running DSH version rejects. */
incompatible?: IncompatiblePlugin[]
/** Present with `unsupported-platform`: the Host platforms the bundle supports. */
platforms?: string[]
}
/**
@@ -110,9 +110,12 @@ it.each(['live', 'startup'] as const)('refuses an unsupported bundle before savi
const before = readFileSync(join(dir, 'package.json'), 'utf8')
const patchBefore = readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')
expect((await manager.listBundles()).find(row => row.name === 'extra')).toMatchObject({
enabled: false, installed: true, listedByDefault: false, description: 'Platform-limited bundle', error: { code: 'unsupported-platform' },
enabled: false, installed: true, listedByDefault: false, description: 'Platform-limited bundle',
error: { code: 'unsupported-platform', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'] },
})
expect(await manager.setBundleEnabled('extra', true)).toMatchObject({
changed: false, application: 'failed', error: { code: 'unsupported-platform', platforms: [process.platform === 'darwin' ? 'win32' : 'darwin'] },
})
expect(await manager.setBundleEnabled('extra', true)).toMatchObject({ changed: false, application: 'failed', error: { code: 'unsupported-platform' } })
expect(readFileSync(join(dir, 'package.json'), 'utf8')).toBe(before)
expect(ctx.get('managedProbe')).toBeUndefined()
expect(readFileSync(join(dir, 'cordis.patch.yml'), 'utf8')).toBe(patchBefore)
@@ -1836,7 +1839,7 @@ it('lists absent Official entries offline without resolving their packages or co
name: entry.packageName, official: true, availability: 'missing', enabled: false, installed: false, optional: false,
removable: false, rows: [], overrides: [], meta: entry.meta,
...entry.platforms !== undefined && !entry.platforms.includes(process.platform)
? { listedByDefault: false, error: { code: 'unsupported-platform' } } : {},
? { listedByDefault: false, error: { code: 'unsupported-platform', platforms: [...entry.platforms] } } : {},
installTarget: { spec: `${entry.packageName}@${getDshRuntimeVersion()}`, version: getDshRuntimeVersion() },
}])
expect(resolve.mock.calls.some(([name]) => name === entry.packageName)).toBe(false)
@@ -1860,7 +1863,7 @@ it.each([false, true])('applies offline platform admission to an uninstalled Off
}
expect((await manager.listBundles()).find(bundle => bundle.name === entry.packageName)).toMatchObject({
installed: false, availability: 'missing', enabled: selected, listedByDefault: false,
error: { code: 'unsupported-platform' },
error: { code: 'unsupported-platform', platforms: [process.platform === 'darwin' ? 'linux' : 'darwin'] },
})
if (selected) {
expect(await manager.setBundleEnabled(entry.packageName, false)).toMatchObject({ changed: true, enabled: false })
@@ -995,10 +995,7 @@ function registryOption(registry: Registry, t: Translate, resolved: string | nul
function failureText(failure: InstallState['failure'], t: Translate, install?: Pick<InstallState, 'attempts' | 'subject' | 'registries'>): string {
if (failure === null) return t('installFailureGeneric')
// A compatibility refusal is the package's own answer, whatever pnpm's exit classified the run as.
if (failure.code === 'incompatible-version') {
const incompatible = failure.incompatible === undefined ? {} : { incompatible: failure.incompatible }
return managementText({ code: failure.code, installing: true, ...incompatible }, t)
}
if (failure.error?.code === 'incompatible-version') return managementText({ ...failure.error, installing: true }, t)
// Blocked scripts the Host could not name leave the person to allow them in the profile's pnpm settings by hand.
if (failure.kind === 'build-blocked' && !failure.pendingBuilds?.length) return t('installFailureBuildBlockedManual')
const host = install?.subject?.host
@@ -1008,7 +1005,7 @@ function failureText(failure: InstallState['failure'], t: Translate, install?: P
return t('installFailureNetworkAll', { registries: registryList(asked, t, install?.registries?.resolved ?? null) })
}
if (failure.kind !== undefined) return t(FAILURE_KIND_KEYS[failure.kind])
if (failure.code !== undefined) return managementText({ code: failure.code, diagnostic: failure.reason }, t)
if (failure.error !== undefined) return managementText(failure.error, t)
if (failure.reason !== '') return failure.reason
// An enabled install that failed applying the bundle names that step, never the install command it already finished.
return failure.stage === 'enable' && failure.enabled === true ? t('installFailedEnabling') : t('installFailureGeneric')
@@ -1450,7 +1447,7 @@ function InstallDialog({
{phase === 'done' && subject?.bundled ? <p className={css.wizardSub}>{t('installBundledDescription')}</p> : null}
{phase === 'failed' ? <p className={css.wizardSub}>{failureText(install.failure, t, install)}</p> : null}
{phase === 'failed' && failure?.stage === 'enable' && failure.enabled === true
&& (failure.code !== undefined || failure.reason !== '')
&& (failure.error !== undefined || failure.reason !== '')
? <p className={css.wizardSub}>{t('installFailedEnabling')}</p>
: null}
{attemptLine === null ? null : <p className={css.wizardSub}>{attemptLine}</p>}
@@ -294,7 +294,14 @@ export const zh = {
reasonStaleApproval: '待允许的安装脚本列表已变化,请重新安装以刷新',
reasonIncompatibleVersion: '{plugin} 与 DSH {runtime} 不兼容(要求 {requirements}),运行它可能导致崩溃或数据丢失。',
reasonIncompatibleVersionUnnamed: '这个插件与当前 DSH 版本不兼容,运行它可能导致崩溃或数据丢失。',
reasonUnsupportedPlatform: '此插件不支持运行 DSH 的主机操作系统',
reasonUnsupportedPlatform: '此插件不支持当前操作系统',
reasonUnsupportedPlatformList: '此插件仅支持 {platforms}',
platformListSeparator: '、',
platformListLastSeparator: ' 和 ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
reasonIncompatibleInstall: '请安装与当前 DSH 兼容的插件版本。',
reasonIncompatibleInstalled: '请卸载后重新安装与当前 DSH 兼容的版本。',
reasonUnexpectedPackage: '插件来源安装了与所请求不同的包或版本,已撤销这次安装。请向插件发布者或插件索引维护者报告此问题。',
@@ -601,7 +608,14 @@ export const en = {
reasonStaleApproval: 'The pending script approvals changed; install again to refresh them.',
reasonIncompatibleVersion: '{plugin} is incompatible with DSH {runtime} (requires {requirements}); running it may cause crashes or data loss.',
reasonIncompatibleVersionUnnamed: 'This plugin is incompatible with the running DSH version; running it may cause crashes or data loss.',
reasonUnsupportedPlatform: 'This plugin does not support the operating system running DSH.',
reasonUnsupportedPlatform: 'This plugin does not support this operating system.',
reasonUnsupportedPlatformList: 'This plugin only supports {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' and ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
reasonIncompatibleInstall: 'Install a plugin version compatible with this DSH.',
reasonIncompatibleInstalled: 'Uninstall it and install a version compatible with this DSH.',
reasonUnexpectedPackage: 'The plugin source installed another package or version than requested; the installation was undone. Report it to the plugin\'s publisher or the index maintainer.',
@@ -618,7 +632,14 @@ export const en = {
/** Japanese copy, checked against the English keys. */
export const ja = {
'reasonUnsupportedPlatform': 'このプラグインはDSHを実行しているホストOSに対応していません。',
'reasonUnsupportedPlatform': 'このプラグインは現在の OS に対応していません。',
'reasonUnsupportedPlatformList': 'このプラグインは {platforms} にのみ対応しています。',
'platformListSeparator': '、',
'platformListLastSeparator': ' と ',
'platformDarwin': 'macOS',
'platformWin32': 'Windows',
'platformLinux': 'Linux',
'platformWsl': 'WSL',
'panel': 'プラグイン',
'settingsEntry': 'プラグイン管理',
'clientSyncing': 'このページでプラグインを同期中…',
@@ -922,7 +943,14 @@ export const ja = {
/** Spanish dictionary, checked against the English keys. */
export const es = {
reasonUnsupportedPlatform: 'Este complemento no es compatible con el sistema operativo que ejecuta DSH.',
reasonUnsupportedPlatform: 'Este complemento no es compatible con este sistema operativo.',
reasonUnsupportedPlatformList: 'Este complemento solo es compatible con {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' y ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
panel: 'Complementos',
settingsEntry: 'Complementos',
clientSyncing: 'Sincronizando complementos en esta página…',
@@ -1226,7 +1254,14 @@ export const es = {
/** French dictionary, checked against the English keys. */
export const fr = {
reasonUnsupportedPlatform: 'Ce plugin ne prend pas en charge le système d’exploitation sur lequel DSH s’exécute.',
reasonUnsupportedPlatform: 'Ce plugin n’est pas compatible avec ce système d’exploitation.',
reasonUnsupportedPlatformList: 'Ce plugin est uniquement compatible avec {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' et ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
panel: 'Plugins',
settingsEntry: 'Plugins',
clientSyncing: 'Synchronisation des plugins sur cette page…',
@@ -1530,7 +1565,14 @@ export const fr = {
/** German dictionary, checked against the English keys. */
export const de = {
reasonUnsupportedPlatform: 'Dieses Plugin unterstützt das Betriebssystem, auf dem DSH läuft, nicht.',
reasonUnsupportedPlatform: 'Dieses Plugin unterstützt dieses Betriebssystem nicht.',
reasonUnsupportedPlatformList: 'Dieses Plugin unterstützt nur {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' und ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
panel: 'Plugins',
settingsEntry: 'Plugins',
clientSyncing: 'Plugins auf dieser Seite werden synchronisiert…',
@@ -1834,7 +1876,14 @@ export const de = {
/** Russian dictionary, checked against the English keys. */
export const ru = {
reasonUnsupportedPlatform: 'Этот плагин не поддерживает операционную систему, в которой работает DSH.',
reasonUnsupportedPlatform: 'Этот плагин не поддерживает текущую операционную систему.',
reasonUnsupportedPlatformList: 'Этот плагин поддерживает только {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' и ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
panel: 'Плагины',
settingsEntry: 'Плагины',
clientSyncing: 'Синхронизация плагинов на этой странице…',
@@ -2138,7 +2187,14 @@ export const ru = {
/** Portuguese dictionary, checked against the English keys. */
export const pt = {
reasonUnsupportedPlatform: 'Este plugin não oferece suporte ao sistema operacional em que o DSH está sendo executado.',
reasonUnsupportedPlatform: 'Este plugin não é compatível com este sistema operacional.',
reasonUnsupportedPlatformList: 'Este plugin é compatível apenas com {platforms}.',
platformListSeparator: ', ',
platformListLastSeparator: ' e ',
platformDarwin: 'macOS',
platformWin32: 'Windows',
platformLinux: 'Linux',
platformWsl: 'WSL',
panel: 'Plug-ins',
settingsEntry: 'Plug-ins',
clientSyncing: 'Sincronizando plug-ins nesta página…',
@@ -12,7 +12,6 @@ import type { Context as ClientContext } from '@deepseek-ai/cordis'
import type {
BundleInfo,
ChangeResult,
IncompatiblePlugin,
ManagementError,
PluginEntryId,
PluginInfo,
@@ -71,11 +70,9 @@ export type ManagerNotice =
/** What was being done when it failed. */
readonly action: FailedAction
/** The Host's refusal, when the Host refused; absent when the transport failed. */
readonly code?: ManagementError['code']
readonly error?: ManagementError
/** The Host's diagnostic or the transport's words, shown verbatim; empty when the code says it all. */
readonly reason: string
/** The packages an `incompatible-version` refusal names. */
readonly incompatible?: readonly IncompatiblePlugin[]
readonly packageName?: string
readonly seq: number
}
@@ -267,8 +264,8 @@ export interface InstallState {
/** Why it waits, when the Host says. */
readonly restartReason?: RestartReason
/**
* The run's failure, once one settled the dialog: the Host's refusal
* `code` with its diagnostic as `reason`, or the transport's words alone;
* The run's failure, once one settled the dialog: the Host's refusal as
* `error` with its diagnostic as `reason`, or the transport's words alone;
* `kind` classifies a pnpm failure, and `pendingBuilds` names the packages
* whose install scripts pnpm left undecided, offered for approval.
* `uncertainty` distinguishes a lost installation reply, an unconfirmed
@@ -276,9 +273,8 @@ export interface InstallState {
*/
readonly failure: {
readonly reason: string
readonly code?: ManagementError['code']
/** The packages an `incompatible-version` refusal names. */
readonly incompatible?: readonly IncompatiblePlugin[]
/** The Host's refusal, when the Host refused. */
readonly error?: ManagementError
readonly kind?: PluginInstallFailureKind
/** The step the failed change reached; `enable` means the installation finished and applying the bundle failed. */
readonly stage?: ChangeResult['stage']
@@ -539,11 +535,9 @@ type Answer<T> =
| { readonly ok: true; readonly value: T }
| { readonly ok: false; readonly error: { readonly code: string; readonly message: string; readonly details?: unknown } }
/** A refused answer or a change the Host could not apply, carrying what it said and, for a refusal, its code. */
/** A refused answer or a change the Host could not apply, carrying what it said and, for a refusal, the Host's error. */
class RemoteAnswerError extends Error {
constructor(
readonly reason: string, readonly code?: ManagementError['code'], readonly incompatible?: readonly IncompatiblePlugin[],
) {
constructor(readonly reason: string, readonly error?: ManagementError) {
super(reason)
this.name = 'RemoteAnswerError'
}
@@ -556,8 +550,7 @@ function failureOf(
): NonNullable<InstallState['failure']> {
return {
reason: error?.diagnostic ?? '',
...error === undefined ? {} : { code: error.code },
...error?.incompatible === undefined ? {} : { incompatible: error.incompatible },
...error === undefined ? {} : { error },
...kind === undefined ? {} : { kind },
stage,
...enabled === undefined ? {} : { enabled },
@@ -566,14 +559,10 @@ function failureOf(
}
}
/** The notice a thrown failure becomes: a refusal keeps its code, anything else its words. */
/** The notice a thrown failure becomes: a refusal keeps the Host's error, anything else its words. */
function failedNotice(error: unknown, subject: { action: FailedAction; packageName?: string }, seq: number): ManagerNotice {
const code = error instanceof RemoteAnswerError ? error.code : undefined
const incompatible = error instanceof RemoteAnswerError ? error.incompatible : undefined
return {
kind: 'failed', reason: reasonOf(error), ...code === undefined ? {} : { code },
...incompatible === undefined ? {} : { incompatible }, ...subject, seq,
}
const refusal = error instanceof RemoteAnswerError ? error.error : undefined
return { kind: 'failed', reason: reasonOf(error), ...refusal === undefined ? {} : { error: refusal }, ...subject, seq }
}
/** The runs with every one still open settled at `exitCode`. */
@@ -1593,7 +1582,7 @@ export class PluginManagerController {
const result = answer.value
switch (result.application) {
case 'failed':
throw new RemoteAnswerError(result.error?.diagnostic ?? '', result.error?.code, result.error?.incompatible)
throw new RemoteAnswerError(result.error?.diagnostic ?? '', result.error)
case 'cancelled':
this.patch({ notice: { kind: 'cancelled', seq: ++this.noticeSeq } })
return
@@ -1,7 +1,7 @@
/** Display labels and toast sentences for global plugin management. */
import { EXPERIMENTAL_BUNDLES } from '@deepseek-ai/dsh-official-bundles'
import type { IncompatiblePlugin, ManagementError, Registry, RestartReason } from '@deepseek-ai/dsh-api-remotes/client'
import type { ManagementError, Registry, RestartReason } from '@deepseek-ai/dsh-api-remotes/client'
import type { PropsLocale } from '@deepseek-ai/dsh-client-ui-slots'
import type { PluginManagerLocaleKey } from './locales.ts'
import type { FailedAction, ManagerNotice, PackageRow, PackageView, PluginManagerFace } from './manager-store.ts'
@@ -45,6 +45,23 @@ function registryHost(registry: string): string {
}
}
/** Display names for the Node platform ids and `wsl` that bundle metadata declares; other ids render verbatim. */
const PLATFORM_KEYS = new Map<string, PluginManagerLocaleKey>([
['darwin', 'platformDarwin'],
['win32', 'platformWin32'],
['linux', 'platformLinux'],
['wsl', 'platformWsl'],
])
function platformList(platforms: readonly string[], t: Translate): string {
const labels = platforms.map((name) => {
const key = PLATFORM_KEYS.get(name)
return key === undefined ? name : t(key)
})
if (labels.length === 1) return labels.join('')
return `${labels.slice(0, -1).join(t('platformListSeparator'))}${t('platformListLastSeparator')}${labels.at(-1)}`
}
/** The sentence each of the Host's refusal codes reads as. */
const CODE_KEYS = {
'management-required': 'reasonManagementRequired',
@@ -75,15 +92,13 @@ const FAILED_KEYS = {
/**
* What a management error reads as: the code's sentence; for an incompatibility, one sentence per
* package it names, then the remedy for an install or for an installed plugin; or, for an operation error, the Host's diagnostic as it is.
* @param error - the Host's code, its diagnostic, and the packages an incompatibility names.
* package it names, then the remedy for an install or for an installed plugin; for a platform refusal, the supported
* platforms it names; or, for an operation error, the Host's diagnostic as it is.
* @param error - the Host's error.
* @param t - the manager's translate seat.
* @returns the sentence.
*/
export function managementText(error: {
readonly code: ManagementError['code']
readonly diagnostic?: string
readonly incompatible?: readonly IncompatiblePlugin[]
export function managementText(error: ManagementError & {
/** Set when the refused package is being installed rather than already installed; selects the incompatibility remedy. */
readonly installing?: true
}, t: Translate): string {
@@ -97,6 +112,12 @@ export function managementText(error: {
}))
return [...sentences, t(error.installing ? 'reasonIncompatibleInstall' : 'reasonIncompatibleInstalled')].join(t('sentenceSeparator'))
}
if (error.code === 'unsupported-platform') {
const platforms = error.platforms ?? []
return platforms.length === 0
? t('reasonUnsupportedPlatform')
: t('reasonUnsupportedPlatformList', { platforms: platformList(platforms, t) })
}
if (error.code !== 'operation-error') return t(CODE_KEYS[error.code])
return error.diagnostic === undefined || error.diagnostic === '' ? t('reasonOperationError') : error.diagnostic
}
@@ -180,9 +201,7 @@ export function noticeText(notice: ManagerNotice, t: Translate): string {
unconfirmed: 'installBackgroundUnconfirmed', applying: 'installBackgroundApplying', unknown: 'installBackgroundUnknown',
} as const)[notice.outcome])
case 'failed': {
const reason = notice.code === undefined ? notice.reason : managementText({
code: notice.code, diagnostic: notice.reason, ...notice.incompatible === undefined ? {} : { incompatible: notice.incompatible },
}, t)
const reason = notice.error === undefined ? notice.reason : managementText(notice.error, t)
return t(FAILED_KEYS[notice.action], { reason: reason === '' ? t('reasonOperationError') : reason })
}
}
@@ -1819,8 +1819,16 @@ describe('PluginManagerPage', () => {
set({ packages: [pkg({ enabled: false, error: { code: 'unsupported-platform' } })] })
expect(screen.getByText(en.reasonUnsupportedPlatform)).toBeTruthy()
expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })).toHaveProperty('disabled', true)
set({ packages: [pkg({ enabled: true, error: { code: 'unsupported-platform' } })] })
set({ packages: [pkg({ enabled: true, error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] } })] })
expect(screen.getByText('This plugin only supports macOS and Windows.')).toBeTruthy()
expect(screen.getByRole('switch', { name: en.enableToggle.replace('{name}', 'dsh-better-sidebar') })).toHaveProperty('disabled', false)
set({ packages: [pkg({ enabled: false, error: { code: 'unsupported-platform', platforms: ['freebsd'] } })] })
expect(screen.getByText('This plugin only supports freebsd.')).toBeTruthy()
set({ notice: { kind: 'failed', action: 'enable', error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] }, reason: '', packageName: 'dsh-better-sidebar', seq: 1 } })
expect(screen.getByRole('alert').textContent).toContain('This plugin only supports macOS and Windows.')
set({ notice: null, install: { ...IDLE_INSTALL, open: true, spec: 'dsh-cua', phase: 'failed', failure: { error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] }, reason: '' } } })
expect(screen.getByText('This plugin only supports macOS and Windows.')).toBeTruthy()
set({ install: IDLE_INSTALL })
// A bundle that leaves the list drops back to the cards.
const { version: _version, ...unversioned } = pkg()
set({ packages: [unversioned] })
@@ -2239,15 +2247,15 @@ describe('PluginManagerPage', () => {
expect(screen.getByText(sentence)).toBeTruthy()
}
// A failure without a kind reads by its code, else in the Host's words; without words, or without a failure at all, generically.
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: '', code: 'not-bundle' } } })
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: '', error: { code: 'not-bundle' } } } })
expect(screen.getByText(en.reasonNotBundle)).toBeTruthy()
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: 'ERR_PNPM_ADDING_TO_ROOT', code: 'operation-error' } } })
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: 'ERR_PNPM_ADDING_TO_ROOT', error: { code: 'operation-error', diagnostic: 'ERR_PNPM_ADDING_TO_ROOT' } } } })
expect(screen.getByText('ERR_PNPM_ADDING_TO_ROOT')).toBeTruthy()
// A compatibility refusal outranks the kind pnpm's exit was classified as.
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed',
failure: { reason: '', code: 'incompatible-version', incompatible: [INCOMPATIBLE], kind: 'unknown' } } })
failure: { reason: '', error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] }, kind: 'unknown' } } })
expect(screen.getByText(`${incompatibleText()} ${en.reasonIncompatibleInstall}`)).toBeTruthy()
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: '', code: 'incompatible-version' } } })
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: '', error: { code: 'incompatible-version' } } } })
expect(screen.getByText(`${en.reasonIncompatibleVersionUnnamed} ${en.reasonIncompatibleInstall}`)).toBeTruthy()
set({ install: { ...IDLE_INSTALL, open: true, spec: 'x', phase: 'failed', failure: { reason: 'the transport said so' } } })
expect(screen.getByText('the transport said so')).toBeTruthy()
@@ -2708,11 +2716,11 @@ describe('PluginManagerPage', () => {
// A failure names what was being done; a refusal is worded by its code, a silent one generically.
set({ notice: { kind: 'failed', action: 'enable', reason: 'the tree rejected it', packageName: 'pkg-1', seq: 4 } })
expect(screen.getByRole('alert').textContent).toContain(en.failedEnable.replace('{reason}', 'the tree rejected it'))
set({ notice: { kind: 'failed', action: 'uninstall', code: 'bundle-in-use', reason: '', packageName: 'pkg-1', seq: 5 } })
set({ notice: { kind: 'failed', action: 'uninstall', error: { code: 'bundle-in-use' }, reason: '', packageName: 'pkg-1', seq: 5 } })
expect(screen.getByRole('alert').textContent).toContain(en.failedUninstall.replace('{reason}', en.reasonBundleInUse))
set({ notice: { kind: 'failed', action: 'enable', code: 'incompatible-version', incompatible: [INCOMPATIBLE], reason: '', packageName: 'pkg-1', seq: 5 } })
set({ notice: { kind: 'failed', action: 'enable', error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] }, reason: '', packageName: 'pkg-1', seq: 5 } })
expect(screen.getByRole('alert').textContent).toContain(en.failedEnable.replace('{reason}', `${incompatibleText()} ${en.reasonIncompatibleInstalled}`))
set({ notice: { kind: 'failed', action: 'rowDisable', code: 'operation-error', reason: 'EACCES', packageName: 'pkg-1', seq: 6 } })
set({ notice: { kind: 'failed', action: 'rowDisable', error: { code: 'operation-error', diagnostic: 'EACCES' }, reason: 'EACCES', packageName: 'pkg-1', seq: 6 } })
expect(screen.getByRole('alert').textContent).toContain(en.failedRowDisable.replace('{reason}', 'EACCES'))
set({ notice: { kind: 'failed', action: 'disable', reason: '', packageName: 'pkg-1', seq: 7 } })
expect(screen.getByRole('alert').textContent).toContain(en.failedDisable.replace('{reason}', en.reasonOperationError))
@@ -536,11 +536,12 @@ describe('PluginManagerController', () => {
.mockResolvedValueOnce(ok(failed({ code: 'bundle-in-use' })))
.mockResolvedValueOnce(ok(failed()))
.mockResolvedValueOnce(ok({ ...failed(), application: 'cancelled' }))
.mockResolvedValueOnce(ok(failed({ code: 'incompatible-version', incompatible: [INCOMPATIBLE] }))),
.mockResolvedValueOnce(ok(failed({ code: 'incompatible-version', incompatible: [INCOMPATIBLE] })))
.mockResolvedValueOnce(ok(failed({ code: 'unsupported-platform', platforms: ['darwin', 'win32'] }))),
})
await controller.load()
face.setEnabled(BUNDLE.name, true)
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', code: 'operation-error', reason: 'the tree rejected it', packageName: BUNDLE.name, seq: 1 }) })
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', error: { code: 'operation-error', diagnostic: 'the tree rejected it' }, reason: 'the tree rejected it', packageName: BUNDLE.name, seq: 1 }) })
face.setEnabled(BUNDLE.name, false)
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'disable', reason: 'offline', packageName: BUNDLE.name, seq: 2 }) })
face.setEnabled(BUNDLE.name, true)
@@ -549,7 +550,7 @@ describe('PluginManagerController', () => {
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', reason: 'odd', packageName: BUNDLE.name, seq: 4 }) })
// A refusal keeps its code with no words of its own; a failure without a code has neither.
face.setEnabled(BUNDLE.name, true)
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', code: 'bundle-in-use', reason: '', packageName: BUNDLE.name, seq: 5 }) })
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', error: { code: 'bundle-in-use' }, reason: '', packageName: BUNDLE.name, seq: 5 }) })
face.setEnabled(BUNDLE.name, true)
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'enable', reason: '', packageName: BUNDLE.name, seq: 6 }) })
// A change the Host stopped is said in passing.
@@ -559,7 +560,13 @@ describe('PluginManagerController', () => {
face.setEnabled(BUNDLE.name, true)
await vi.waitFor(() => {
expect(state().notice).toEqual({
kind: 'failed', action: 'enable', code: 'incompatible-version', incompatible: [INCOMPATIBLE], reason: '', packageName: BUNDLE.name, seq: 8,
kind: 'failed', action: 'enable', error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] }, reason: '', packageName: BUNDLE.name, seq: 8,
})
})
face.setEnabled(BUNDLE.name, true)
await vi.waitFor(() => {
expect(state().notice).toEqual({
kind: 'failed', action: 'enable', error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] }, reason: '', packageName: BUNDLE.name, seq: 9,
})
})
face.dismissNotice()
@@ -586,7 +593,7 @@ describe('PluginManagerController', () => {
plugins.removeBundle.mockResolvedValueOnce(ok({ ...failed(), stage: 'remove', error: { code: 'not-removable' } }) as never)
face.uninstall(BUNDLE.name)
face.confirm()
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'uninstall', code: 'not-removable', reason: '', packageName: BUNDLE.name, seq: 1 }) })
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'uninstall', error: { code: 'not-removable' }, reason: '', packageName: BUNDLE.name, seq: 1 }) })
})
it('switches rows under their own busy keys and reports what the Host said', async () => {
@@ -603,7 +610,7 @@ describe('PluginManagerController', () => {
gate.resolve(ok(APPLIED))
await vi.waitFor(() => { expect(state().busy).toEqual([]) })
face.setRowEnabled(ROW_ENTRY, true)
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'rowEnable', code: 'unaddressable', reason: '', packageName: ROW_ENTRY, seq: 1 }) })
await vi.waitFor(() => { expect(state().notice).toEqual({ kind: 'failed', action: 'rowEnable', error: { code: 'unaddressable' }, reason: '', packageName: ROW_ENTRY, seq: 1 }) })
})
it('installs a Discover spec through the dialog, asking its registry first, and reopens a hidden installation instead', async () => {
@@ -831,7 +838,7 @@ describe('PluginManagerController', () => {
face.editInstallSpec('dsh-x')
face.runInstall()
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.failure).toEqual({ reason: 'ERR', code: 'operation-error', kind: 'network', stage: 'install' })
expect(state().install.failure).toEqual({ reason: 'ERR', error: { code: 'operation-error', diagnostic: 'ERR' }, kind: 'network', stage: 'install' })
face.cancelInstall()
expect(state().install).toMatchObject({ open: true, phase: 'idle', spec: 'dsh-x', failure: null, subject: null })
})
@@ -1206,7 +1213,7 @@ describe('PluginManagerController', () => {
face.enableInstalled()
await vi.waitFor(() => { expect(state().install.open).toBe(false) })
expect(plugins.setBundleEnabled).toHaveBeenCalledTimes(2)
expect(state().notice).toEqual({ kind: 'failed', action: 'enable', code: 'operation-error', reason: 'the tree rejected it', packageName: 'dsh-a', seq: 2 })
expect(state().notice).toEqual({ kind: 'failed', action: 'enable', error: { code: 'operation-error', diagnostic: 'the tree rejected it' }, reason: 'the tree rejected it', packageName: 'dsh-a', seq: 2 })
expect(state().highlight).toBe('dsh-a')
// An install that named no bundle has nothing to enable or mark: the screen just closes.
@@ -1243,7 +1250,7 @@ describe('PluginManagerController', () => {
pendingBuilds: ['native'],
}))
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.failure).toEqual({ reason: 'ERR_PNPM_IGNORED_BUILDS', code: 'operation-error', kind: 'build-blocked', pendingBuilds: ['native'], stage: 'install' })
expect(state().install.failure).toEqual({ reason: 'ERR_PNPM_IGNORED_BUILDS', error: { code: 'operation-error', diagnostic: 'ERR_PNPM_IGNORED_BUILDS' }, kind: 'build-blocked', pendingBuilds: ['native'], stage: 'install' })
// The retry keeps the subject the check produced and carries the approved names under a new request id.
face.approveBuildsAndRetry()
const second = await started()
@@ -1317,7 +1324,7 @@ describe('PluginManagerController', () => {
answer(ok(failed({ code: 'operation-error', diagnostic: 'ERR_PNPM' }, { exitCode: 1, output: 'ERR_PNPM', truncated: false, logPath: '/l', kind: 'network' })))
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.runs).toEqual([])
expect(state().install.failure).toEqual({ reason: 'ERR_PNPM', code: 'operation-error', kind: 'network', stage: 'install' })
expect(state().install.failure).toEqual({ reason: 'ERR_PNPM', error: { code: 'operation-error', diagnostic: 'ERR_PNPM' }, kind: 'network', stage: 'install' })
expect(state().install.subject).toEqual({ spec: 'x', ...INSPECTED })
// A lost answer cannot establish whether the Host stopped the process.
await installing()
@@ -1345,18 +1352,23 @@ describe('PluginManagerController', () => {
{ jobId: 'j', command: 'pnpm add x', cwd: '/p', output: 'partial', exitCode: 0 },
{ jobId: 'k', command: 'pnpm add x', cwd: '/p', output: 'open', exitCode: null },
])
expect(state().install.failure).toEqual({ reason: '', code: 'not-bundle', stage: 'install' })
expect(state().install.failure).toEqual({ reason: '', error: { code: 'not-bundle' }, stage: 'install' })
// An incompatibility keeps the packages it names.
await installing()
answer(ok(failed({ code: 'incompatible-version', incompatible: [INCOMPATIBLE] })))
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.failure).toEqual({ reason: '', code: 'incompatible-version', incompatible: [INCOMPATIBLE], stage: 'install' })
expect(state().install.failure).toEqual({ reason: '', error: { code: 'incompatible-version', incompatible: [INCOMPATIBLE] }, stage: 'install' })
// A platform refusal keeps the supported Host platforms it names.
await installing()
answer(ok(failed({ code: 'unsupported-platform', platforms: ['darwin', 'win32'] })))
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.failure).toEqual({ reason: '', error: { code: 'unsupported-platform', platforms: ['darwin', 'win32'] }, stage: 'install' })
// A failure the Host does not explain has neither code nor words.
await installing()
answer(ok(failed()))
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
expect(state().install.failure).toEqual({ reason: '', stage: 'install' })
expect(plugins.installBundle).toHaveBeenCalledTimes(6)
expect(plugins.installBundle).toHaveBeenCalledTimes(7)
// Editing the spec after a failure starts over too.
face.editInstallSpec('y')
expect(state().install).toMatchObject({ phase: 'idle', spec: 'y', runs: [], failure: null })
@@ -1404,7 +1416,7 @@ describe('PluginManagerController', () => {
face.runInstall()
await vi.waitFor(() => { expect(state().install.phase).toBe('failed') })
// The Host laid the failure at activation, and the details keep the run's complete log.
expect(state().install.failure).toEqual({ reason: 'activation refused', code: 'operation-error', stage: 'enable', enabled: true })
expect(state().install.failure).toEqual({ reason: 'activation refused', error: { code: 'operation-error', diagnostic: 'activation refused' }, stage: 'enable', enabled: true })
expect(state().install.logPath).toBe(failedLog)
// Retrying forgets the settled run's log until the next answer names its own.
face.runInstall()
+4 -4
View File
@@ -18,11 +18,11 @@
en: f04acee552aa1a44
zh: 38600adaf4cf7fa2
/deepseek-ai-dsh-cua/use-this-package/permission-controls:
en: 724e72c7dc35eb49
zh: aa99fa5d5eb400ba
en: 2061107eb1bb3ea9
zh: 14917f8fc4979992
/deepseek-ai-dsh-cua/understand-the-implementation:
en: 05dd7d67f596934a
zh: d8ce8406d288f17e
en: 9defaaf1e0113f11
zh: 752c7e02a8709eab
/deepseek-ai-dsh-cua/further-exploration:
en: c174fb5a00ea3681
zh: 039340042676881d
+4 -4
View File
@@ -68,11 +68,11 @@ The application approval card includes a **Risks** tag. Hover over it, focus it
On the Computer Use detail page, permission cards, component rows, and source facts use l3 borders, with 32px gaps between sections. Application badges retain their l1 borders.
The [Computer Use bundle](../cua-bundle/README.md) mounts this page with its native provider. On macOS, **Authorize computer use** groups Accessibility and Screen Recording inside one border. Each permission row shows the responsible application’s name and icon. **Request permission** delegates to the provider with the selected permission and current Client language; the [macOS provider](../cua-macos/README.md) owns the native drag guide. An outlined **Allowed** button opens settings for revocation; unknown status uses **Unknown**. Application grants remain in a separate group.
The [Computer Use bundle](../cua-bundle/README.md) mounts this page with its native provider. On macOS, **System permissions** introduces the required permissions and groups Accessibility and Screen Recording inside one border. Each permission row shows the responsible application’s name and icon. **Request permission** delegates to the provider with the selected permission and current Client language; the [macOS provider](../cua-macos/README.md) owns the native drag guide. An outlined **Allowed** button opens settings for revocation; unknown status uses **Unknown**. Application grants remain in a separate group.
The enabled bundle shows the preview notice above the system permission controls. The Windows page also gives the npm helper build and configuration steps. The macOS page offers Accessibility and Screen Recording controls.
The enabled bundle highlights the experimental notice and places the PTC recommendation, which points to **Settings → Agent presets** for making PTC mode the default, in a separate paragraph. On macOS, Accessibility and Screen Recording controls appear under **System permissions**. On Windows, the page omits the system permissions section, places active warnings (helper failure, locked or unavailable desktop, or unavailable window capture) above the experimental notice, and places desktop-unlock and standard-privilege guidance between the experimental notice and the PTC recommendation.
The page refreshes on entry, window focus, and completed actions. Query failures retain the last observation as unknown and offer **Retry**. Opening settings or requesting permission does not establish consent. The provider owns native guidance, its configuration, and localized recovery instructions.
The page refreshes on entry, window focus, and completed actions. System-permission query failures appear directly beneath the section heading with recovery guidance and **Retry**, while retaining the last observation as unknown. Opening settings or requesting permission does not establish consent. The provider owns native guidance, its configuration, and localized recovery instructions.
System-permission operations affect the computer running DSH. When accessing DSH remotely, complete authorization on that computer.
@@ -133,7 +133,7 @@ Check `methods` and `keyboard` in the result of `await cua.getCapabilities()` fo
Platform providers import `CuaConfigFields` from `@deepseek-ai/dsh-cua/config` to extend the shared configuration. The root Host entry exports `installCua`, `CuaConfig`, and the Typert-discovered `CuaAccess` service; its `apply()` only marks the optional Client contribution. `/client` loads the permission UI through the existing module loader. Separate Host and Client compiler projects keep React, CSS, and browser registrations out of headless imports. `/api` owns the app/window API and its types; `/bridge`, `/native-client`, and `/protocol` retain runtime and platform consumers. `/types` exports only the named types required by generated Remote declarations. The Client uses package-local types. `/typert` supplies Host reflection and `/remote` supplies generated browser descriptors and codecs; permission authority remains on the Host.
The optional browser contribution mounts the native provider's permission Remote and reuses the Plugins activation and configuration slots. The system permission rows remain visible while unknown fields use placeholders; platform-specific permission guidance remains visible during queries and after grants once the platform has been identified. System checks, application decisions, and application icons fill in as each query completes. Application names and actions do not wait for icons; icon positions retain their space. User actions run in order without waiting for pending observation queries. Disposal waits for both actions and queries to settle before releasing the separately owned Remote mount. Known query errors stay visible while management operations or retries run, with their actions disabled. Query errors stay with the affected section, and activation guidance depends only on system checks. The injection layer observes Plugin Manager operations independently of the page. Bundle and row changes pause permission queries and invalidate in-flight results; settlement refreshes observations even after the page closes. Last known errors remain until a successful read. Disposal discards late results. When no native system observation is available, the controller reads the Host plugin inventory to identify an enabled Windows provider, including one that failed during helper preparation. If both reads fail, the page reports both causes and offers a retry. It projects queries into the page and setup dialog; reconnects refresh it. Page entry, focus and completed actions read the current permission store. Operation notices live in the shell overlay, so closing the page does not remove them. The provider owns permission checks, persisted decisions, and cancellation; the browser owns no authorization state.
The optional browser contribution mounts the native provider's permission Remote and reuses the Plugins activation and configuration slots. The system permission rows remain visible while unknown fields use placeholders; platform-specific guidance updates once the platform is identified. System checks, application decisions, and application icons fill in as each query completes. Application names and actions do not wait for icons; icon positions retain their space. User actions run in order without waiting for pending observation queries. Disposal waits for both actions and queries to settle before releasing the separately owned Remote mount. Known query errors stay visible while management operations or retries run, with their actions disabled. Query errors stay with the affected section, and activation guidance depends only on system checks. The injection layer observes Plugin Manager operations independently of the page. Bundle and row changes pause permission queries and invalidate in-flight results; settlement refreshes observations even after the page closes. Last known errors remain until a successful read. Disposal discards late results. When no native system observation is available, the controller reads the Host plugin inventory to identify an enabled Windows provider so startup helper failures still render the Windows warning layout. If that lookup also fails, the page shows the lookup failure in place of the native query error and offers a retry. It projects queries into the page and setup dialog; reconnects refresh it. Page entry, focus and completed actions read the current permission store. Operation notices live in the shell overlay, so closing the page does not remove them. The provider owns permission checks, persisted decisions, and cancellation; the browser owns no authorization state.
</details>
-----
+4 -4
View File
@@ -68,11 +68,11 @@ kind: "package-reference"
Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边框,区块间距为 32px。应用名称徽标保留 l1 边框。
[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“系统权限与设置”把辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。
[Computer Use 组合](../cua-bundle/README.zh.md)将本页与原生 provider 一起挂载。在 macOS 上,“系统权限”先说明运行所需权限,再将辅助功能和屏幕录制放在同一个边框内。每条权限要求显示责任应用的名称和图标。“申请权限”将所选权限和当前界面语言交给 provider;原生拖动引导由 [macOS provider](../cua-macos/README.zh.md)负责。“已允许”描边按钮打开设置以撤销权限;未知状态使用“未确认”。应用访问授权保持独立分组。
启用组合包后,系统权限上方显示预览提示。Windows 页面还提供 npm 安装所需的辅助程序构建和配置步骤,macOS 页面提供辅助功能和屏幕录制授权操作。
启用组合包后,页面高亮显示实验性功能提示,并另起一段给出 PTC 模式建议,提示可在**设置 → Agent 预设**中将其设为默认。macOS 在“系统权限”下提供辅助功能和屏幕录制授权操作;Windows 不展示系统权限分区,改为在实验性提示上方展示当前异常警告(辅助程序连接失败、桌面锁定或不可用、窗口截图不可用),并在实验性提示与 PTC 建议之间说明保持桌面解锁与普通用户权限限制。
进入页面、返回窗口和操作结束后会刷新状态。查询失败保留上次观测但标为未确认,并提供“重试”。打开设置或申请权限不代表授权完成。原生引导、配置和本地化恢复提示由 provider 负责。
进入页面、返回窗口和操作结束后会刷新状态。系统权限检查失败直接显示在分组标题下方,附带排查建议与“重试”,同时将上次观测标为未确认。打开设置或申请权限不代表授权完成。原生引导、配置和本地化恢复提示由 provider 负责。
系统权限操作作用于运行 DSH 的电脑。远程访问时,请在该电脑上完成授权。
@@ -133,7 +133,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边
平台提供方从 `@deepseek-ai/dsh-cua/config` 导入 `CuaConfigFields` 来扩展共享配置。根 Host 入口导出 `installCua`、`CuaConfig` 和供 Typert 发现的 `CuaAccess` 服务,`apply()` 只标记可选 Client 贡献。`/client` 通过现有模块加载器加载权限界面。Host 和 Client 使用独立编译项目,headless 导入不会加载 React、CSS 或浏览器注册。`/api` 提供应用、窗口 API 及其类型;`/bridge`、`/native-client` 和 `/protocol` 保留运行时和平台消费者。`/types` 仅导出生成 Remote 声明所需的命名类型,Client 使用包内类型。`/typert` 提供 Host 反射,`/remote` 提供浏览器描述和编解码,权限判断仍由 Host 执行。
可选浏览器插件挂载原生 provider 的权限 Remote,复用插件页的启用引导和配置插槽。系统权限始终可见,未加载的字段保留占位;平台确认后,查询期间和权限已允许时均保留权限管理说明。系统权限、应用列表和应用图标分别查询,结果返回后各自显示。应用名称和操作按钮不等待图标,图标位置保留空位。用户操作按顺序执行,不等待尚未完成的查询;卸载时等待操作和查询全部结束,再释放独立持有的 Remote 挂载。已知查询错误在管理操作或重试期间保持可见,操作按钮禁用。查询错误只显示在对应部分,启用引导只等待系统权限结果。注入层独立于页面观察插件管理操作。组合包和组件行变更会暂停权限查询,并使进行中的结果失效;操作结束后即使页面已关闭,也会重新查询。已知错误保留至读取成功;卸载后的迟到结果会被丢弃。首次读取系统权限失败时,控制器会查询主机插件清单。已启用的 Windows 提供方即使因准备辅助程序而加载失败,页面仍会显示配置步骤。两项查询都失败时,页面显示两个错误并提供重试。重新连接后会刷新状态。进入页面、窗口聚焦或操作完成后读取当前授权存储。操作提示挂载到 shell overlay,关闭页面后仍可显示。provider 负责权限检查、持久授权和取消;浏览器不保存授权决定。
可选浏览器插件挂载原生 provider 的权限 Remote,复用插件页的启用引导和配置插槽。系统权限始终可见,未加载的字段保留占位;平台确认后按平台展示对应说明。系统权限、应用列表和应用图标分别查询,结果返回后各自显示。应用名称和操作按钮不等待图标,图标位置保留空位。用户操作按顺序执行,不等待尚未完成的查询;卸载时等待操作和查询全部结束,再释放独立持有的 Remote 挂载。已知查询错误在管理操作或重试期间保持可见,操作按钮禁用。查询错误只显示在对应部分,启用引导只等待系统权限结果。注入层独立于页面观察插件管理操作。组合包和组件行变更会暂停权限查询,并使进行中的结果失效;操作结束后即使页面已关闭,也会重新查询。已知错误保留至读取成功;卸载后的迟到结果会被丢弃。首次读取系统权限失败时,控制器会查询主机插件清单以识别已启用的 Windows 提供方,使启动失败仍按 Windows 警告布局展示。该查询也失败时,页面以查询失败原因替代原生查询错误,并提供重试。重新连接后会刷新状态。进入页面、窗口聚焦或操作完成后读取当前授权存储。操作提示挂载到 shell overlay,关闭页面后仍可显示。provider 负责权限检查、持久授权和取消;浏览器不保存授权决定。
</details>
-----
@@ -4,7 +4,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import { isDeepStrictEqual } from 'node:util'
import { UserQuestionError, type AskUserQuestionAnswer } from '@deepseek-ai/dsh-user-questions'
import { z } from 'zod'
import { applicationAccessDisplay } from './locales.ts'
import { applicationAccessDisplay, sessionApplicationAccessDisplay } from './locales.ts'
import { NativeError, type NativeClient } from './native-client.ts'
import type { CuaAppHandle } from './types.ts'
import type { CuaApplicationGrant, CuaApplicationId } from './application-types.ts'
@@ -203,17 +203,19 @@ export class ApplicationAccess {
const questions = this.ctx.get('userQuestions')
if (!questions) throw new NativeError('APP_APPROVAL_UNAVAILABLE', 'No human answerer is available for application access')
const options = [{ label: 'Allow for this session' }, { label: 'Deny' }]
if (identity.persistable && this.options.store.persistent) options.push({ label: 'Always allow' })
const persistable = identity.persistable && this.options.store.persistent
if (persistable) options.push({ label: 'Always allow' })
const display = persistable ? applicationAccessDisplay : sessionApplicationAccessDisplay
let result: AskUserQuestionAnswer
try {
result = await questions.ask({ agent, signal, questions: [{ id: 'cua-app-access',
question: `Allow computer use to launch if needed, read, capture, and control ${identity.name}?`,
detail: applicationAccessDisplay.detail.en,
detail: display.detail.en,
options, intent: {
kind: 'approval', approve: 'Allow for this session', reject: 'Deny',
...(identity.persistable && this.options.store.persistent ? { always: 'Always allow' } : {}),
...(persistable ? { always: 'Always allow' } : {}),
subject: { name: identity.name, ...(icon === undefined ? {} : { icon }) },
display: applicationAccessDisplay,
display,
} }] })
} catch (error) {
if (error instanceof UserQuestionError && error.code === 'ASK_CANCELLED') {
@@ -1,9 +1,51 @@
.panels { display: grid; gap: 32px; margin: 0; font-size: 13px; }
.panel { display: grid; gap: 12px; min-width: 0; }
.guidance { display: grid; gap: 8px; overflow-wrap: anywhere; }
.guidance { display: grid; gap: 12px; overflow-wrap: anywhere; }
.panelGuidance { margin-bottom: 12px; }
.guidance p, .panel p { margin: 0; color: var(--dsw-alias-label-secondary); line-height: 1.6; }
.caution, .dangerNotice {
display: flex;
flex-wrap: wrap;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
padding: 10px 12px;
border-radius: var(--dsw-radius-md);
}
.caution { background: var(--dsw-alias-state-warn-tertiary); }
.dangerNotice { background: color-mix(in srgb, var(--dsw-alias-state-error-primary) 8%, transparent); }
.noticeMain {
display: flex;
align-items: flex-start;
gap: 8px;
flex: 1;
min-width: 180px;
}
.cautionIcon {
display: inline-flex;
flex: none;
margin-top: 3px;
color: var(--dsw-alias-state-warn-primary);
}
.dangerIcon {
display: inline-flex;
flex: none;
margin-top: 3px;
color: var(--dsw-alias-state-error-primary);
}
.cautionBody {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
overflow-wrap: anywhere;
}
.cautionBody .cautionTitle {
color: var(--dsw-alias-label-primary);
font-weight: 500;
}
.card { min-width: 0; border: 0.5px solid var(--dsw-alias-border-l3); border-radius: var(--dsw-radius-md); }
.card > * + * { border-top: 0.5px solid var(--dsw-alias-border-l3); }
.panel p { margin: 0; color: var(--dsw-alias-label-secondary); line-height: 1.6; }
.panel h3 { margin: 0; font-size: 14px; font-weight: 500; }
.panel h4 { margin: 0; font-size: 13px; font-weight: 500; color: var(--dsw-alias-label-secondary); }
.permission, .apps li { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; }
@@ -16,7 +58,7 @@
.apps li { padding: 12px 0; }
.apps li:last-child { padding-bottom: 0; }
.panel strong { font-weight: 500; }
.panel .error { color: var(--dsw-alias-state-error-primary); overflow-wrap: anywhere; }
.panels .error { color: var(--dsw-alias-state-error-primary); overflow-wrap: anywhere; }
.application { display: flex; align-items: center; gap: 10px; }
.application strong { min-width: 0; overflow-wrap: anywhere; }
.application img { flex-shrink: 0; object-fit: contain; }
@@ -1,6 +1,6 @@
/** Native permission status and revocable application consent on the existing plugin page. */
import { useEffect } from 'react'
import { Button, IconLayersOutlineRegular, IconSettingsOutlineRegular, Modal, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import { useEffect, type ReactNode } from 'react'
import { Button, IconLayersOutlineRegular, IconSettingsOutlineRegular, IconWarningOutlineRegular, Modal, Toast } from '@deepseek-ai/dsh-client-ui-primitives'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import type { InjectFace, PropsLocale, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from '@deepseek-ai/dsh-client-ui-plugin-manager/client'
@@ -85,21 +85,49 @@ function UnknownStatus({ loading, t }: Pick<PermissionProps, 't'> & { loading: b
})
}
function WindowsStatus({ system, uncertain, t }: Pick<PermissionProps, 't'> & {
system: Extract<CuaSystemPermissionState, { platform: 'windows' }>
uncertain: boolean
function NoticeBox({ tone, role, title, body, action }: {
tone: 'warn' | 'danger'
role: 'note' | 'alert'
title: string
body: string
action?: ReactNode
}) {
const unlocked = system.sessionLocked === false
return <>
<div className={css.permission} role="group" aria-label={t('windowsDesktop')}>
<div><strong>{t('windowsDesktop')}</strong><p>{t('windowsDesktopUse')}</p></div>
<span>{uncertain || system.sessionLocked === null ? t('unknown') : t(unlocked ? 'available' : 'locked')}</span>
const danger = tone === 'danger'
return <div className={danger ? css.dangerNotice : css.caution} role={role}>
<div className={css.noticeMain}>
<span className={danger ? css.dangerIcon : css.cautionIcon} aria-hidden="true"><IconWarningOutlineRegular size={14} /></span>
<div className={css.cautionBody}>
<p className={css.cautionTitle}>{title}</p>
<p>{body}</p>
</div>
</div>
<div className={css.permission} role="group" aria-label={t('windowsCapture')}>
<div><strong>{t('windowsCapture')}</strong><p>{t('screenRecordingUse')}</p></div>
<span>{uncertain || system.sessionLocked === null ? t('unknown') : t(unlocked && system.captureAvailable ? 'available' : 'unavailable')}</span>
</div>
</>
{action}
</div>
}
function WindowsGuidance({ system, error, busy, refresh, t }: Pick<PermissionProps, 'refresh' | 't'> & {
system: Extract<CuaSystemPermissionState, { platform: 'windows' }> | null
error: string | null
busy: boolean
}) {
return <div className={css.guidance} data-cua-guidance>
{error !== null && <NoticeBox tone="danger" role="alert"
title={t('windowsHelperFailed', { message: error })} body={t('queryFailedHint')}
action={<Button size="sm" variant="outline" disabled={busy} onClick={refresh}>{t('retry')}</Button>} />}
{/* Standing desktop conditions are notes so that opening the page does not interrupt assistive technology. */}
{error === null && system !== null && <>
{system.sessionLocked === true && <NoticeBox tone="danger" role="note"
title={t('windowsLockedTitle')} body={t('windowsLockedBody')} />}
{system.sessionLocked === null && <NoticeBox tone="danger" role="note"
title={t('windowsSessionUnknownTitle')} body={t('windowsSessionUnknown')} />}
{system.sessionLocked === false && !system.captureAvailable && <NoticeBox tone="warn" role="note"
title={t('windowsCaptureUnavailableTitle')} body={t('windowsCaptureUnavailableNotice')} />}
</>}
<NoticeBox tone="warn" role="note" title={t('previewNoticeTitle')} body={t('previewNotice')} />
<p>{t('windowsInstructions')}</p>
{error === null && system !== null && !system.elevated && <p>{t('standardPrivileges')}</p>}
<p>{t('ptcRecommendation')}</p>
</div>
}
function systemReady(system: CuaSystemPermissionState): boolean {
@@ -121,39 +149,42 @@ export function PermissionPanel(props: PermissionProps) {
const transitioning = state.changing
const busy = transitioning || state.system.busy
const appsBusy = transitioning || state.applications.busy
const loading = observed === null && state.system.error === null
// A failed native query leaves the platform unknown until the Host inventory says whether a Windows provider is enabled.
const platformPending = observed === null && state.system.error !== null
&& state.windowsProvider.value === null && state.windowsProvider.error === null
const loading = observed === null && (state.system.error === null || platformPending)
const mac = observed?.platform === 'darwin' ? observed : null
const win = observed?.platform === 'windows' ? observed : null
const application = state.system.error !== null ? undefined : mac?.launchApplication
// An unidentified platform outranks the native query failure because the page cannot tell which guidance applies.
const providerError = observed === null ? state.windowsProvider.error : null
useEffect(() => {
refresh()
window.addEventListener('focus', refresh)
return () => { window.removeEventListener('focus', refresh) }
}, [refresh])
return <div className={css.panels} data-cua-settings aria-busy={transitioning || state.busy || loading}>
<section className={css.panel} aria-label={t('title')}>
<div className={css.guidance} data-cua-guidance>
<p>{t('previewNotice')}</p>
{windows && <>
<p>{t('windowsHelperBuild', {
directory: 'packages/experimental/cua-windows',
x64: 'pnpm run build:native:x64', arm64: 'pnpm run build:native:arm64',
})}</p>
<p>{t('windowsHelperPath', {
patch: 'cordis.patch.yml', entry: 'cua-windows', config: 'config', path: 'helperPath', exe: 'dsh-cua-windows.exe',
})}</p>
</>}
</div>
<h3>{t('title')}</h3>
<div className={css.card}>
{observed === null && state.windowsProvider.error !== null && <p role="alert" className={css.error}>
{t('providerLookupFailed', { message: state.windowsProvider.error })}
{windows ? <WindowsGuidance system={win} error={state.system.error} busy={busy} refresh={refresh} t={t} />
: <section className={css.panel} aria-label={t('title')}>
<div className={`${css.guidance} ${css.panelGuidance}`} data-cua-guidance>
<NoticeBox tone="warn" role="note" title={t('previewNoticeTitle')} body={t('previewNotice')} />
<p>{t('ptcRecommendation')}</p>
</div>
<h3>{t('title')}</h3>
{state.system.error !== null && !platformPending && <NoticeBox tone="danger" role="alert"
title={providerError === null
? t('queryFailed', { message: state.system.error })
: t('providerLookupFailed', { message: providerError })}
body={t('queryFailedHint')}
action={<Button size="sm" variant="outline" disabled={busy} onClick={refresh}>{t('retry')}</Button>} />}
{(observed !== null || loading) && <p
className={observed === null ? css.pendingHint : undefined}
aria-hidden={observed === null || undefined}
>
{t('permissionsIntro')}
</p>}
{state.system.error !== null && <div className={css.notice} role="alert">
<span className={css.error}>{t('queryFailed', { message: state.system.error })}</span>
<Button size="sm" variant="outline" disabled={busy} onClick={refresh}>{t('retry')}</Button>
</div>}
{observed === null ? <UnknownStatus loading={loading} t={t} />
: observed.platform === 'windows' ? <WindowsStatus system={observed} uncertain={state.system.error !== null} t={t} />
<div className={css.card}>
{mac === null ? <UnknownStatus loading={loading} t={t} />
: (['accessibility', 'screenRecording'] as const).map(permission => <div className={css.permission} key={permission}
role="group" aria-label={t(permission)}>
<div>
@@ -161,14 +192,11 @@ export function PermissionPanel(props: PermissionProps) {
<PermissionDescription application={application} permission={permission} t={t} />
</div>
<PermissionAction permission={permission}
granted={mac === null || state.system.error !== null ? null : mac[permission]}
granted={state.system.error !== null ? null : mac[permission]}
busy={busy} request={props.request} openSettings={props.openSettings} t={t} />
</div>)}
</div>
<p className={observed === null ? css.pendingHint : undefined} aria-hidden={observed === null || undefined}>{observed?.platform === 'windows'
? <>{t('windowsInstructions')} {t(observed.elevated ? 'elevated' : 'standardPrivileges')}</>
: t('permissionHint')}</p>
</section>
</div>
</section>}
<section className={css.panel} aria-label={t('applicationsTitle')}>
<h3>{t('applicationsTitle')}</h3>
<div className={css.card}>
@@ -120,7 +120,7 @@ export class PermissionController {
const latest = () => current() && this.sequence === sequence
const refresh = Promise.all([
this.read('system', this.remote.systemStatus, latest).then(async () => {
// The Windows helper can be missing before its first permission response.
// Identify an enabled Windows provider when native setup fails before reporting its platform.
if (latest() && this.state.getSnapshot().system.value === null) {
this.state.update((state) => { state.windowsProvider.busy = true })
await this.read('windowsProvider', this.windowsProvider, latest)
+195 -190
View File
@@ -2,33 +2,36 @@
export const NS = 'cuaPermissions'
/** English permission-page dictionary. */
export const en = {
previewNotice: 'Computer use is an experimental preview. The agent may click the wrong button or type in the wrong window. Use caution in production environments. We recommend native PTC mode so the agent can operate apps and call other tools in the same program.',
windowsHelperBuild: 'If you installed DSH through npm, build the Windows helper from the matching DSH source. In {directory}, run {x64} or {arm64} with the .NET 10 SDK for your architecture.',
previewNoticeTitle: 'Experimental feature',
previewNotice: 'Computer use is experimental and results are not guaranteed. The agent may click the wrong button or type in the wrong window. Use caution in important or production environments.',
ptcRecommendation: 'We recommend using PTC mode so the agent can operate apps and call other tools in the same program. You can set it as the default in Settings → Agent presets.',
providerLookupFailed: 'Could not identify the computer use provider: {message}',
windowsHelperPath: 'In the active profile’s {patch}, find or add the entry with ID {entry}. Set {path} under its {config} to the absolute path of {exe}.',
approvalRisks: 'Risks',
approvalRiskTitle: 'Computer use risks',
approvalRiskNotice: 'The agent can access only apps you approve, and can read and control them in the background.\n\nOnline games, messaging apps, and other apps may restrict automation. Violating their rules could result in your account with that app being suspended or banned.\n\nProceed at your own risk. To stop automated control at any time, press Stop in DeepSeek Harness.',
title: 'Authorize computer use',
title: 'System permissions',
permissionsIntro: 'Computer use requires the following system permissions to run:',
applicationsTitle: 'Manage applications computer use can access',
windowsSetupTitle: 'Check Windows desktop access',
windowsSetupBody: 'Unlock the Windows desktop, then check again. DSH asks before accessing each application.',
windowsSessionUnknown: 'No interactive Windows desktop was verified. Run DSH in a signed-in desktop session, then check again.',
windowsCaptureUnavailable: 'This Windows session does not support window capture. Check the Windows version and graphics driver, then check again.',
applicationInteraction: 'Application interaction',
windowsInstructions: 'Keep the Windows desktop unlocked. Some input needs the target application in front. Applications running with higher privileges can refuse access.',
windowsDesktop: 'Interactive desktop', windowsDesktopUse: 'An unlocked desktop is required for observation and input.',
windowsCapture: 'Window capture', available: 'Available', unavailable: 'Unavailable', locked: 'Locked or disconnected',
elevated: 'The native component is running with administrator privileges.', standardPrivileges: 'The native component is running with standard user privileges.',
windowsSetupTitle: 'Check desktop environment',
windowsSetupBody: 'The desktop is locked. Unlock it and try again.',
windowsSessionUnknownTitle: 'Desktop session unavailable',
windowsSessionUnknown: 'Could not detect an available desktop. Run DeepSeek Harness in a signed-in desktop session and try again.',
windowsLockedTitle: 'Desktop is locked',
windowsLockedBody: 'Unlock the desktop so the agent can view and operate apps.',
windowsCaptureUnavailableTitle: 'Window screenshots unavailable',
windowsCaptureUnavailable: 'This desktop environment does not support window capture. Check your OS version and graphics driver, then try again.',
windowsCaptureUnavailableNotice: 'Window capture is unavailable in this environment. Check or update your OS version and graphics driver, then try again. DeepSeek Harness can still operate apps through accessibility, with reduced capability.',
windowsHelperFailed: 'Could not connect to the computer use helper: {message}',
windowsInstructions: 'Keep the desktop unlocked while in use. Some actions require bringing the target app to the front.',
standardPrivileges: 'Currently running with standard user privileges. Apps running with higher privileges (such as as administrator) may not be controllable.',
setupTitle: 'Set up computer use before use',
setupBody: 'Computer use is enabled. Before using it, grant Accessibility and Screen Recording permissions. Open the plugin details to complete setup.',
setupQueryFailed: 'computer use is enabled, but system permissions could not be checked. Open the plugin details to see the error and retry.',
setupBody: 'Computer use is enabled and requires Accessibility and Screen Recording permissions to run. Open the plugin details to finish setup.',
setupQueryFailed: 'Computer use is enabled, but system permissions could not be checked. Open the plugin details to view the error and try again.',
openSetup: 'Open settings', later: 'Later', close: 'Close',
accessibility: 'Accessibility', screenRecording: 'Screen Recording',
accessibilityUse: 'Read interface controls, click, and type.', screenRecordingUse: 'Capture the selected application window.',
accessibilityPermission: 'In System Settings, allow {application} to read interface controls, click, and type.',
screenRecordingPermission: 'In System Settings, allow {application} to capture application windows.',
permissionHint: 'Manage Accessibility and Screen Recording permissions in System Settings.',
accessibilityUse: 'Read interface content, click, and type.', screenRecordingUse: 'Capture the selected application window.',
accessibilityPermission: 'Allow {application} to read interface content, click, and type.',
screenRecordingPermission: 'Allow {application} to capture the selected application window.',
granted: 'Allowed', unknown: 'Unknown', request: 'Request permission', settings: 'Open System Settings', retry: 'Retry',
allowedApps: 'Always-allowed applications',
blockedApps: 'Applications not allowed', retryApproval: 'Allow asking again',
@@ -36,37 +39,42 @@ export const en = {
noApps: 'No always-allowed or blocked applications.',
revoke: 'Revoke', revoked: 'Application access revoked', requested: 'Follow the guide at the bottom of System Settings', opened: 'System Settings opened',
applicationsFailed: 'Could not load application access: {message}', iconsFailed: 'Could not load application icons: {message}',
failed: 'Could not update permissions: {message}', queryFailed: 'Could not check permissions: {message}',
failed: 'Could not update permissions: {message}', queryFailed: 'Could not check system permissions: {message}',
queryFailedHint: 'Try disabling and re-enabling this plugin, or restarting DeepSeek Harness. If the issue persists, check whether security software blocked the helper or reinstall DeepSeek Harness.',
}
/** Keys shared by all supported locale dictionaries. */
export type CuaPermissionLocaleKey = keyof typeof en
/** Chinese permission-page dictionary. */
export const zh: Record<CuaPermissionLocaleKey, string> = {
previewNotice: '自动电脑操作目前为实验性预览功能。智能体可能点错按钮,或把内容输入错误的窗口,请谨慎在生产环境中使用。推荐使用原生 PTC 模式,让智能体在同一段代码中操作应用并调用其他工具。',
windowsHelperBuild: '通过 npm 安装 DSH 后,请使用对应版本的 DSH 源码构建 Windows 辅助程序。在 {directory} 中使用 .NET 10 SDK,按电脑架构运行 {x64} 或 {arm64}。',
previewNoticeTitle: '实验性功能提示',
previewNotice: '自动电脑操作仍处于实验阶段,不保证操作结果。智能体可能误点按钮或在错误的窗口中输入内容,请谨慎在重要或生产环境中使用。',
ptcRecommendation: '建议配合 PTC 模式使用,让智能体在同一段代码中完成应用操作并调用其他工具。可在“设置 → Agent 预设”中将其设为默认。',
providerLookupFailed: '无法识别自动电脑操作后端:{message}',
windowsHelperPath: '在当前 profile 的 {patch} 中,找到或添加 ID 为 {entry} 的条目,将其 {config} 下的 {path} 设为 {exe} 的绝对路径。',
approvalRisks: '风险提示',
approvalRiskTitle: '自动电脑操作风险提示',
approvalRiskNotice: '智能体只能访问你已授权的应用,并可在后台读取应用内容、操作应用。\n\n网络游戏、即时通讯等应用可能对自动化操作有所限制。违反相关规则可能导致你在该应用中的账号被暂停使用或封禁。\n\n请自行承担使用风险。如需停止自动化操作,可随时点击 DeepSeek Harness 中的停止按钮。',
title: '系统权限与设置', applicationsTitle: '管理可访问的应用', setupTitle: '配置自动电脑操作',
setupBody: '“自动电脑操作”插件已开启。使用前需授予辅助功能和屏幕录制权限,请前往插件详情页完成设置。',
setupQueryFailed: '“自动电脑操作”插件已开启,但暂时无法检测系统权限。请前往插件详情页查看原因并重试。',
windowsSetupTitle: '检查 Windows 桌面访问状态',
windowsSetupBody: '请解锁 Windows 桌面,然后重新检测。DSH 会在访问每个应用前询问授权。',
windowsSessionUnknown: '尚未确认可交互的 Windows 桌面。请在已登录的桌面会话中运行 DSH,然后重新检测。',
windowsCaptureUnavailable: '当前 Windows 会话不支持窗口截图。请检查 Windows 版本和显卡驱动,然后重新检测。',
applicationInteraction: '应用交互',
windowsInstructions: '请保持 Windows 桌面解锁。部分输入需要将目标应用切到前台,运行权限更高的应用可能拒绝访问。',
windowsDesktop: '交互桌面', windowsDesktopUse: '观察和输入需要已解锁的桌面。',
windowsCapture: '窗口截图', available: '可用', unavailable: '不可用', locked: '已锁定或断开连接',
elevated: '本机组件正以管理员权限运行。', standardPrivileges: '本机组件正以普通用户权限运行。',
title: '系统权限',
permissionsIntro: '自动电脑操作需要以下两项系统权限才能运行:',
applicationsTitle: '管理可访问的应用', setupTitle: '配置自动电脑操作',
setupBody: '“自动电脑操作”已开启,需要授予「辅助功能」和「屏幕录制」权限才能运行。请前往插件详情页完成设置。',
setupQueryFailed: '“自动电脑操作”已开启,但暂时无法检查系统权限。请前往插件详情页查看详情并重试。',
windowsSetupTitle: '检查桌面运行环境',
windowsSetupBody: '桌面已锁定,请解锁后重试。',
windowsSessionUnknownTitle: '无法检测到可用桌面',
windowsSessionUnknown: '无法检测到可用的桌面。请在已登录的桌面环境中运行 DeepSeek Harness,然后重试。',
windowsLockedTitle: '桌面已锁定',
windowsLockedBody: '请解锁桌面,以便智能体查看并操作应用。',
windowsCaptureUnavailableTitle: '窗口截图不可用',
windowsCaptureUnavailable: '当前桌面环境不支持窗口截图。请检查系统版本与显卡驱动后重试。',
windowsCaptureUnavailableNotice: '当前环境不支持窗口截图。请检查或更新系统版本与显卡驱动后重试。DeepSeek Harness 仍可通过辅助功能操作应用,但识别与操作能力会受限。',
windowsHelperFailed: '无法连接自动电脑操作辅助程序:{message}',
windowsInstructions: '使用时请保持桌面处于解锁状态。部分操作需要将目标应用切到前台。',
standardPrivileges: '当前以普通用户权限运行,以管理员等更高权限运行的应用可能无法操作。',
openSetup: '前往设置', later: '稍后', close: '关闭',
accessibility: '辅助功能', screenRecording: '屏幕录制',
accessibilityUse: '读取界面控件、点击和输入文字', screenRecordingUse: '截取所选应用的窗口',
accessibilityPermission: '在系统设置中允许 {application} 读取界面、点击和输入。',
screenRecordingPermission: '在系统设置中允许 {application} 截取应用窗口。',
permissionHint: '在系统设置中管理辅助功能和屏幕录制权限',
accessibilityUse: '读取界面内容,并执行点击和键盘输入。', screenRecordingUse: '截取所选应用窗口的画面。',
accessibilityPermission: '允许 {application} 读取界面内容,并执行点击和键盘输入。',
screenRecordingPermission: '允许 {application} 截取所选应用窗口的画面。',
granted: '已允许', unknown: '未确认', request: '申请权限', settings: '打开系统设置', retry: '重试',
allowedApps: '始终允许的应用',
blockedApps: '不允许访问的应用', retryApproval: '允许再次询问',
@@ -74,45 +82,46 @@ export const zh: Record<CuaPermissionLocaleKey, string> = {
noApps: '暂无始终允许或不允许访问的应用。',
revoke: '撤销', revoked: '已撤销应用访问权限', requested: '请按系统设置底部的引导完成授权', opened: '已打开系统设置',
applicationsFailed: '无法读取应用授权:{message}', iconsFailed: '无法读取应用图标:{message}',
failed: '无法更新权限:{message}', queryFailed: '无法检测权限:{message}',
failed: '无法更新权限:{message}', queryFailed: '无法检查系统权限:{message}',
queryFailedHint: '请尝试关闭并重新启用此插件,或重启 DeepSeek Harness。如仍未解决,请检查安全软件是否拦截了辅助程序,或重新安装。',
}
/** Japanese copy, checked against the English keys. */
export const ja = {
previewNotice: 'Computer Use は実験的なプレビュー機能です。エージェントが誤ったボタンをクリックしたり、別のウィンドウに入力したりする可能性があります。本番環境では慎重に使用してください。ネイティブ PTC モードでは、同じプログラムでアプリの操作と他のツールの呼び出しができるため、このモードを推奨します。',
windowsHelperBuild: 'npm で DSH をインストールした場合は、同じバージョンの DSH のソースから Windows 用ヘルパーをビルドしてください。{directory} で .NET 10 SDK を使い、アーキテクチャに応じて {x64} または {arm64} を実行します。',
previewNoticeTitle: '実験的機能について',
previewNotice: 'Computer Use は実験的な機能であり、操作結果は保証されません。エージェントが誤ったボタンをクリックしたり、別のウィンドウに入力したりする可能性があります。重要な環境や本番環境では慎重に使用してください。',
ptcRecommendation: '同じプログラム内でアプリの操作と他のツールの呼び出しを行えるよう、PTC モードの使用をおすすめします。「設定 → エージェントプリセット」でデフォルトに設定できます。',
providerLookupFailed: 'Computer Use のプロバイダーを特定できませんでした:{message}',
windowsHelperPath: '使用中のプロファイルの {patch} で、ID が {entry} の項目を探すか追加し、その {config} 内の {path} に {exe} の絶対パスを指定してください。',
windowsSetupTitle: 'Windows デスクトップへのアクセスを確認',
windowsSetupBody: 'Windows デスクトップのロックを解除して再確認してください。DSH は各アプリへのアクセス前に確認します。',
windowsSessionUnknown: '操作可能な Windows デスクトップを確認できませんでした。サインイン済みのデスクトップセッションで DSH を実行し、再確認してください。',
windowsCaptureUnavailable: 'この Windows セッションはウィンドウキャプチャに対応していません。Windows のバージョンとグラフィックスドライバーを確認して再試行してください。',
applicationInteraction: 'アプリの操作',
windowsInstructions: 'Windows デスクトップのロックを解除しておいてください。一部の入力では対象アプリを最前面にする必要があります。高い権限で実行中のアプリはアクセスを拒否する場合があります。',
windowsDesktop: '操作可能なデスクトップ',
windowsDesktopUse: '画面の確認と入力にはロック解除済みのデスクトップが必要です。',
windowsCapture: 'ウィンドウキャプチャ',
available: '利用可能', unavailable: '利用不可', locked: 'ロック中または切断済み',
elevated: 'ネイティブコンポーネントは管理者権限で実行中です。',
standardPrivileges: 'ネイティブコンポーネントは標準ユーザー権限で実行中です。',
windowsSetupTitle: 'デスクトップ実行環境を確認',
windowsSetupBody: 'デスクトップがロックされています。ロックを解除して再試行してください。',
windowsSessionUnknownTitle: 'デスクトップセッションを利用できません',
windowsSessionUnknown: '利用可能なデスクトップを検出できませんでした。サインイン済みのデスクトップ環境で DeepSeek Harness を実行して再試行してください。',
windowsLockedTitle: 'デスクトップがロックされています',
windowsLockedBody: 'エージェントがアプリを確認・操作できるよう、デスクトップのロックを解除してください。',
windowsCaptureUnavailableTitle: 'ウィンドウのスクリーンショットを利用できません',
windowsCaptureUnavailable: '現在のデスクトップ環境はウィンドウキャプチャに対応していません。OS のバージョンとグラフィックスドライバーを確認して再試行してください。',
windowsCaptureUnavailableNotice: 'この環境ではウィンドウキャプチャを利用できません。OS のバージョンやグラフィックスドライバーを確認・更新して再試行してください。アクセシビリティ機能による操作は引き続き可能ですが、性能や対応範囲が制限されます。',
windowsHelperFailed: 'Computer Use 補助プログラムに接続できませんでした:{message}',
windowsInstructions: '使用中はデスクトップのロックを解除しておいてください。一部の操作では対象アプリを最前面に表示する必要があります。',
standardPrivileges: '現在、標準ユーザー権限で実行中です。管理者などより高い権限で実行中のアプリは操作できない場合があります。',
approvalRisks: 'リスク',
approvalRiskTitle: 'コンピュータ操作のリスク',
approvalRiskNotice: 'エージェントがアクセスできるのは、あなたが許可したアプリだけです。許可したアプリの内容を読み取ったり、バックグラウンドで操作したりできます。\n\nオンラインゲームやメッセージアプリなどでは、自動操作が制限されている場合があります。規約に違反すると、そのアプリのアカウントが一時停止または永久停止になる可能性があります。\n\n自己責任でご利用ください。自動操作は、DeepSeek Harness の停止ボタンでいつでも止められます。',
'title': 'コンピュータ操作を承認',
'title': 'システム権限',
'permissionsIntro': 'Computer Use を実行するには、次の 2 つのシステム権限が必要です。',
'applicationsTitle': 'Computer Useがアクセスできるアプリを管理',
'setupTitle': '使用前にComputer Useを設定',
'setupBody': 'Computer Use は有効です。使用前にアクセシビリティと画面収録の権限を許可してください。プラグインの詳細を開いて設定を完了してください。',
'setupQueryFailed': 'Computer Useは有効ですが、システム権限を確認できませんでした。プラグインの詳細を開いてエラーを確認し、再試行してください。',
'setupBody': 'Computer Use が有効になりました。実行するには「アクセシビリティ」と「画面収録」の権限が必要です。プラグインの詳細ページで設定を完了してください。',
'setupQueryFailed': 'Computer Use は有効ですが、システム権限を確認できませんでした。プラグインの詳細ページで内容を確認して再試行してください。',
'openSetup': '設定を開く',
'later': '後で',
'close': '閉じる',
'accessibility': 'アクセシビリティ',
'screenRecording': '画面収録',
'accessibilityUse': 'インターフェースのコントロールを読み取り、クリックし、入力します。',
'screenRecordingUse': '選択したアプリケーションのウィンドウをキャプチャします。',
'accessibilityPermission': 'システム設定で、{application}にインターフェースのコントロールの読み取り、クリック、入力を許可してください。',
'screenRecordingPermission': 'システム設定で、{application}にアプリケーションウィンドウのキャプチャを許可してください。',
'permissionHint': 'システム設定でアクセシビリティと画面収録の権限を管理してください。',
'accessibilityUse': '画面の内容を読み取り、クリックやキーボード入力を行います。',
'screenRecordingUse': '選択したアプリのウィンドウ画面をキャプチャします。',
'accessibilityPermission': '{application} に画面内容の読み取り、クリック、キーボード入力を許可します。',
'screenRecordingPermission': '{application} に選択したアプリウィンドウの画面キャプチャを許可します。',
'granted': '許可済み',
'unknown': '不明',
'request': '権限をリクエスト',
@@ -130,43 +139,42 @@ export const ja = {
'applicationsFailed': 'アプリケーションのアクセスを読み込めませんでした: {message}',
'iconsFailed': 'アプリケーションのアイコンを読み込めませんでした: {message}',
'failed': '権限を更新できませんでした: {message}',
'queryFailed': '権限を確認できませんでした: {message}',
'queryFailed': 'システム権限を確認できませんでした:{message}',
'queryFailedHint': 'プラグインを一度オフにして再度有効にするか、DeepSeek Harness を再起動してください。解決しない場合は、セキュリティソフトが補助プログラムをブロックしていないか確認するか、再インストールしてください。',
} satisfies Record<keyof typeof en, string>
/** Spanish dictionary, checked against the English keys. */
export const es = {
previewNotice: 'Computer Use es una función experimental en fase de prueba. El agente puede pulsar el botón equivocado o escribir en otra ventana. Úsala con precaución en entornos de producción. Recomendamos el modo PTC nativo para que el agente pueda controlar aplicaciones y usar otras herramientas en el mismo programa.',
windowsHelperBuild: 'Si instalaste DSH con npm, compila el programa auxiliar de Windows desde las fuentes de la misma versión de DSH. En {directory}, usa el SDK de .NET 10 y ejecuta {x64} o {arm64} según la arquitectura del equipo.',
previewNoticeTitle: 'Función experimental',
previewNotice: 'Computer Use es experimental y sus resultados no están garantizados. El agente puede pulsar el botón equivocado o escribir en la ventana incorrecta. Úsala con precaución en entornos importantes o de producción.',
ptcRecommendation: 'Recomendamos usar el modo PTC para que el agente pueda controlar aplicaciones y llamar a otras herramientas en el mismo programa. Puedes establecerlo como predeterminado en Configuración → Ajustes preestablecidos del agente.',
providerLookupFailed: 'No se pudo identificar el proveedor de Computer Use: {message}',
windowsHelperPath: 'En el archivo {patch} del perfil activo, busca o añade la entrada con el ID {entry}. En su sección {config}, establece {path} en la ruta absoluta de {exe}.',
windowsSetupTitle: 'Comprobar el acceso al escritorio de Windows',
windowsSetupBody: 'Desbloquea el escritorio de Windows y vuelve a comprobarlo. DSH pide permiso antes de acceder a cada aplicación.',
windowsSessionUnknown: 'No se ha verificado un escritorio interactivo de Windows. Ejecuta DSH en una sesión de escritorio iniciada y vuelve a comprobarlo.',
windowsCaptureUnavailable: 'Esta sesión de Windows no admite la captura de ventanas. Comprueba la versión de Windows y el controlador gráfico, y vuelve a intentarlo.',
applicationInteraction: 'Interacción con aplicaciones',
windowsInstructions: 'Mantén desbloqueado el escritorio de Windows. Algunas entradas requieren que la aplicación esté en primer plano. Las aplicaciones con más privilegios pueden denegar el acceso.',
windowsDesktop: 'Escritorio interactivo',
windowsDesktopUse: 'La observación y la entrada requieren un escritorio desbloqueado.',
windowsCapture: 'Captura de ventanas',
available: 'Disponible',
unavailable: 'No disponible',
locked: 'Bloqueado o desconectado',
elevated: 'El componente nativo se ejecuta con privilegios de administrador.',
standardPrivileges: 'El componente nativo se ejecuta con privilegios de usuario estándar.',
windowsSetupTitle: 'Comprobar el entorno del escritorio',
windowsSetupBody: 'El escritorio está bloqueado. Desbloquéalo e inténtalo de nuevo.',
windowsSessionUnknownTitle: 'Sesión de escritorio no disponible',
windowsSessionUnknown: 'No se pudo detectar un escritorio disponible. Ejecuta DeepSeek Harness en una sesión de escritorio iniciada e inténtalo de nuevo.',
windowsLockedTitle: 'El escritorio está bloqueado',
windowsLockedBody: 'Desbloquea el escritorio para que el agente pueda ver y operar aplicaciones.',
windowsCaptureUnavailableTitle: 'Capturas de ventana no disponibles',
windowsCaptureUnavailable: 'Este entorno de escritorio no admite la captura de ventanas. Comprueba la versión del sistema operativo y el controlador gráfico, y vuelve a intentarlo.',
windowsCaptureUnavailableNotice: 'La captura de ventanas no está disponible en este entorno. Comprueba o actualiza la versión del sistema operativo y el controlador gráfico, y vuelve a intentarlo. DeepSeek Harness puede seguir operando aplicaciones mediante accesibilidad, pero con capacidad reducida.',
windowsHelperFailed: 'No se pudo conectar con el programa auxiliar de Computer Use: {message}',
windowsInstructions: 'Mantén el escritorio desbloqueado durante el uso. Algunas acciones requieren poner la aplicación en primer plano.',
standardPrivileges: 'Actualmente se ejecuta con privilegios de usuario estándar. Es posible que no se puedan controlar aplicaciones con mayores privilegios (como las ejecutadas como administrador).',
approvalRisks: 'Riesgos',
approvalRiskTitle: 'Riesgos del control del equipo',
approvalRiskNotice: 'El agente solo puede acceder a las aplicaciones que autorices, y puede leer su contenido y controlarlas en segundo plano.\n\nLos juegos en línea, las aplicaciones de mensajería y otras aplicaciones pueden restringir la automatización. Incumplir sus normas podría provocar la suspensión o el bloqueo permanente de tu cuenta en esa aplicación.\n\nContinúa bajo tu propia responsabilidad. Para detener el control automatizado en cualquier momento, pulsa Detener en DeepSeek Harness.',
title: 'Autorizar el uso de la computadora',
title: 'Permisos del sistema',
permissionsIntro: 'Computer Use necesita los siguientes permisos del sistema para funcionar:',
applicationsTitle: 'Administrar aplicaciones a las que puede acceder el uso de la computadora',
setupTitle: 'Configurar el uso de la computadora antes de usarla',
setupBody: 'El uso de la computadora está habilitado. Antes de usarlo, otorgue permisos de Accesibilidad y Grabación de pantalla. Abra los detalles del complemento para completar la configuración.',
setupQueryFailed: 'El uso de la computadora está habilitado, pero no se pudieron verificar los permisos del sistema. Abra los detalles del complemento para ver el error y vuelva a intentarlo.',
setupBody: 'Computer Use está activado y necesita permisos de Accesibilidad y Grabación de pantalla para funcionar. Abre los detalles del complemento para completar la configuración.',
setupQueryFailed: 'Computer Use está activado, pero no se pudieron comprobar los permisos del sistema. Abre los detalles del complemento para ver el error e inténtalo de nuevo.',
openSetup: 'Abrir configuración', later: 'Más tarde', close: 'Cerrar',
accessibility: 'Accesibilidad', screenRecording: 'Grabación de pantalla',
accessibilityUse: 'Lea los controles de la interfaz, haga clic y escriba.', screenRecordingUse: 'Capture la ventana de la aplicación seleccionada.',
accessibilityPermission: 'En Configuración del sistema, permita que {application} lea los controles de la interfaz, haga clic y escriba.',
screenRecordingPermission: 'En Configuración del sistema, permita que {application} capture ventanas de aplicaciones.',
permissionHint: 'Administre los permisos de accesibilidad y grabación de pantalla en Configuración del sistema.',
accessibilityUse: 'Leer el contenido de la interfaz, hacer clic y escribir.', screenRecordingUse: 'Capturar la ventana de la aplicación seleccionada.',
accessibilityPermission: 'Permite que {application} lea el contenido de la interfaz, haga clic y escriba.',
screenRecordingPermission: 'Permite que {application} capture la ventana de la aplicación seleccionada.',
granted: 'Permitido', unknown: 'Desconocido', request: 'Solicitar permiso', settings: 'Abrir configuración del sistema', retry: 'Reintentar',
allowedApps: 'Aplicaciones siempre permitidas',
blockedApps: 'Aplicaciones no permitidas', retryApproval: 'Permitir preguntar de nuevo',
@@ -174,43 +182,42 @@ export const es = {
noApps: 'No hay aplicaciones siempre permitidas o bloqueadas.',
revoke: 'Revocar', revoked: 'Acceso a la aplicación revocado', requested: 'Siga la guía en la parte inferior de Configuración del sistema', opened: 'Configuración del sistema abierta',
applicationsFailed: 'No se pudo cargar el acceso a la aplicación: {message}', iconsFailed: 'No se pudieron cargar los íconos de la aplicación: {message}',
failed: 'No se pudieron actualizar los permisos: {message}', queryFailed: 'No se pudieron verificar los permisos: {message}',
failed: 'No se pudieron actualizar los permisos: {message}', queryFailed: 'No se pudieron comprobar los permisos del sistema: {message}',
queryFailedHint: 'Intenta desactivar y volver a activar este complemento o reiniciar DeepSeek Harness. Si el problema persiste, comprueba si el software de seguridad bloqueó el programa auxiliar o vuelve a instalar DeepSeek Harness.',
} satisfies Record<keyof typeof en, string>
/** French dictionary, checked against the English keys. */
export const fr = {
previewNotice: 'Computer Use est proposé en aperçu expérimental. L’agent peut cliquer sur le mauvais bouton ou saisir du texte dans la mauvaise fenêtre. Soyez prudent en production. Nous recommandons le mode PTC natif pour que l’agent puisse piloter des applications et utiliser d’autres outils dans le même programme.',
windowsHelperBuild: 'Si vous avez installé DSH avec npm, compilez le programme auxiliaire Windows à partir des sources de la même version de DSH. Dans {directory}, utilisez le SDK .NET 10 et exécutez {x64} ou {arm64} selon votre architecture.',
previewNoticeTitle: 'Fonctionnalité expérimentale',
previewNotice: 'Computer Use est une fonctionnalité expérimentale dont les résultats ne sont pas garantis. L’agent peut cliquer sur le mauvais bouton ou saisir du texte dans la mauvaise fenêtre. Soyez prudent dans les environnements importants ou de production.',
ptcRecommendation: 'Nous recommandons d’utiliser le mode PTC afin que l’agent puisse piloter des applications et appeler d’autres outils dans le même programme. Vous pouvez le définir par défaut dans Paramètres → Préréglages d\'agent.',
providerLookupFailed: 'Impossible d’identifier le fournisseur de Computer Use : {message}',
windowsHelperPath: 'Dans le fichier {patch} du profil actif, trouvez ou ajoutez l’entrée d’identifiant {entry}. Dans sa section {config}, indiquez le chemin absolu de {exe} dans {path}.',
windowsSetupTitle: 'Vérifier l’accès au bureau Windows',
windowsSetupBody: 'Déverrouillez le bureau Windows, puis vérifiez à nouveau. DSH demande une autorisation avant d’accéder à chaque application.',
windowsSessionUnknown: 'Aucun bureau Windows interactif n’a été vérifié. Exécutez DSH dans une session de bureau ouverte, puis vérifiez à nouveau.',
windowsCaptureUnavailable: 'Cette session Windows ne prend pas en charge la capture de fenêtres. Vérifiez la version de Windows et le pilote graphique, puis réessayez.',
applicationInteraction: 'Interaction avec les applications',
windowsInstructions: 'Gardez le bureau Windows déverrouillé. Certaines saisies nécessitent que l’application soit au premier plan. Les applications disposant de privilèges supérieurs peuvent refuser l’accès.',
windowsDesktop: 'Bureau interactif',
windowsDesktopUse: 'L’observation et la saisie nécessitent un bureau déverrouillé.',
windowsCapture: 'Capture de fenêtres',
available: 'Disponible',
unavailable: 'Indisponible',
locked: 'Verrouillé ou déconnecté',
elevated: 'Le composant natif s’exécute avec des privilèges d’administrateur.',
standardPrivileges: 'Le composant natif s’exécute avec des privilèges d’utilisateur standard.',
windowsSetupTitle: 'Vérifier l’environnement de bureau',
windowsSetupBody: 'Le bureau est verrouillé. Déverrouillez-le puis réessayez.',
windowsSessionUnknownTitle: 'Session de bureau indisponible',
windowsSessionUnknown: 'Impossible de détecter un bureau disponible. Exécutez DeepSeek Harness dans une session de bureau ouverte puis réessayez.',
windowsLockedTitle: 'Le bureau est verrouillé',
windowsLockedBody: 'Déverrouillez le bureau pour permettre à l’agent de consulter et d’utiliser les applications.',
windowsCaptureUnavailableTitle: 'Captures de fenêtre indisponibles',
windowsCaptureUnavailable: 'Cet environnement de bureau ne prend pas en charge la capture de fenêtres. Vérifiez la version du système et le pilote graphique, puis réessayez.',
windowsCaptureUnavailableNotice: 'La capture de fenêtres n’est pas disponible dans cet environnement. Vérifiez ou mettez à jour la version du système et le pilote graphique, puis réessayez. DeepSeek Harness peut toujours contrôler les applications via l’accessibilité, avec des capacités réduites.',
windowsHelperFailed: 'Impossible de se connecter au programme auxiliaire Computer Use : {message}',
windowsInstructions: 'Gardez le bureau déverrouillé pendant l’utilisation. Certaines actions nécessitent de placer l’application au premier plan.',
standardPrivileges: 'Fonctionne actuellement avec des privilèges d’utilisateur standard. Les applications exécutées avec des privilèges supérieurs (comme en tant qu’administrateur) peuvent ne pas être contrôlables.',
approvalRisks: 'Risques',
approvalRiskTitle: 'Risques du contrôle de l’ordinateur',
approvalRiskNotice: 'L’agent ne peut accéder qu’aux applications que vous autorisez. Il peut en lire le contenu et les contrôler en arrière-plan.\n\nLes jeux en ligne, les messageries et d’autres applications peuvent limiter l’automatisation. Le non-respect de leurs règles pourrait entraîner la suspension ou le bannissement de votre compte dans l’application concernée.\n\nUtilisez cette fonction à vos risques et périls. Vous pouvez interrompre le contrôle automatisé à tout moment en cliquant sur Arrêter dans DeepSeek Harness.',
title: "Autoriser l'utilisation de l'ordinateur",
title: 'Autorisations système',
permissionsIntro: 'Computer Use a besoin des autorisations système suivantes pour fonctionner :',
applicationsTitle: "Gérer les applications auxquelles l'ordinateur peut accéder",
setupTitle: "Configurer l'utilisation de l'ordinateur avant utilisation",
setupBody: "L'utilisation de l'ordinateur est activée. Avant de l'utiliser, accordez les autorisations d'accessibilité et d'enregistrement d'écran. Ouvrez les détails du plugin pour terminer la configuration.",
setupQueryFailed: "L'utilisation de l'ordinateur est activée, mais les autorisations système n'ont pas pu être vérifiées. Ouvrez les détails du plugin pour voir l'erreur et réessayez.",
setupBody: 'Computer Use est activé et nécessite les autorisations Accessibilité et Enregistrement de l’écran pour fonctionner. Ouvrez les détails du plugin pour terminer la configuration.',
setupQueryFailed: 'Computer Use est activé, mais les autorisations système n’ont pas pu être vérifiées. Ouvrez les détails du plugin pour voir l’erreur et réessayer.',
openSetup: 'Ouvrir les paramètres', later: 'Plus tard', close: 'Fermer',
accessibility: 'Accessibilité', screenRecording: "Enregistrement d'écran",
accessibilityUse: 'Lisez les commandes de l’interface, cliquez et tapez.', screenRecordingUse: "Capturez la fenêtre de l'application sélectionnée.",
accessibilityPermission: "Dans Paramètres système, autorisez {application} à lire les commandes de l'interface, à cliquer et à taper.",
screenRecordingPermission: "Dans Paramètres système, autorisez {application} à capturer les fenêtres d'application.",
permissionHint: 'Gérez les autorisations d’accessibilité et d’enregistrement de l’écran dans les réglages système.',
accessibilityUse: 'Lire le contenu de l’interface, cliquer et saisir au clavier.', screenRecordingUse: 'Capturer la fenêtre de l’application sélectionnée.',
accessibilityPermission: 'Autorisez {application} à lire le contenu de l’interface, cliquer et saisir au clavier.',
screenRecordingPermission: 'Autorisez {application} à capturer la fenêtre de l’application sélectionnée.',
granted: 'Autorisé', unknown: 'Inconnu', request: "Demander l'autorisation", settings: 'Ouvrir les paramètres système', retry: 'Réessayer',
allowedApps: 'Applications toujours autorisées',
blockedApps: 'Applications non autorisées', retryApproval: 'Autoriser la demande à nouveau',
@@ -218,43 +225,42 @@ export const fr = {
noApps: 'Aucune application toujours autorisée ou bloquée.',
revoke: 'Révoquer', revoked: "Accès à l'application révoqué", requested: 'Suivez le guide en bas des réglages système.', opened: 'Paramètres système ouverts',
applicationsFailed: "Impossible de charger l'accès à l'application : {message}", iconsFailed: "Impossible de charger les icônes d'application : {message}",
failed: 'Impossible de mettre à jour les autorisations : {message}', queryFailed: 'Impossible de vérifier les autorisations : {message}',
failed: 'Impossible de mettre à jour les autorisations : {message}', queryFailed: 'Impossible de vérifier les autorisations système : {message}',
queryFailedHint: 'Essayez de désactiver puis de réactiver ce plugin, ou de redémarrer DeepSeek Harness. Si le problème persiste, vérifiez si un logiciel de sécurité bloque le programme auxiliaire ou réinstallez DeepSeek Harness.',
} satisfies Record<keyof typeof en, string>
/** German dictionary, checked against the English keys. */
export const de = {
previewNotice: 'Computer Use ist eine experimentelle Vorschau. Der Agent kann auf die falsche Schaltfläche klicken oder Text im falschen Fenster eingeben. Seien Sie in Produktionsumgebungen vorsichtig. Wir empfehlen den nativen PTC-Modus, damit der Agent Anwendungen bedienen und andere Werkzeuge im selben Programm aufrufen kann.',
windowsHelperBuild: 'Wenn Sie DSH über npm installiert haben, bauen Sie das Windows-Hilfsprogramm aus dem Quellcode der passenden DSH-Version. Führen Sie in {directory} mit dem .NET 10 SDK je nach Architektur {x64} oder {arm64} aus.',
previewNoticeTitle: 'Experimentelle Funktion',
previewNotice: 'Computer Use ist experimentell und Ergebnisse werden nicht garantiert. Der Agent kann auf die falsche Schaltfläche klicken oder im falschen Fenster tippen. Seien Sie in wichtigen oder produktiven Umgebungen vorsichtig.',
ptcRecommendation: 'Wir empfehlen den PTC-Modus, damit der Agent Anwendungen bedienen und andere Werkzeuge im selben Programm aufrufen kann. Sie können ihn unter Einstellungen → Agentenvoreinstellungen als Standard festlegen.',
providerLookupFailed: 'Der Computer-Use-Anbieter konnte nicht ermittelt werden: {message}',
windowsHelperPath: 'Suchen oder erstellen Sie in der Datei {patch} des aktiven Profils den Eintrag mit der ID {entry}. Setzen Sie dort unter {config} den Wert von {path} auf den absoluten Pfad zu {exe}.',
windowsSetupTitle: 'Windows-Desktopzugriff prüfen',
windowsSetupBody: 'Entsperren Sie den Windows-Desktop und prüfen Sie erneut. DSH fragt vor dem Zugriff auf jede Anwendung nach einer Erlaubnis.',
windowsSessionUnknown: 'Es wurde kein interaktiver Windows-Desktop bestätigt. Führen Sie DSH in einer angemeldeten Desktopsitzung aus und prüfen Sie erneut.',
windowsCaptureUnavailable: 'Diese Windows-Sitzung unterstützt keine Fensteraufnahme. Prüfen Sie die Windows-Version und den Grafiktreiber und versuchen Sie es erneut.',
applicationInteraction: 'Anwendungsinteraktion',
windowsInstructions: 'Lassen Sie den Windows-Desktop entsperrt. Manche Eingaben erfordern die Zielanwendung im Vordergrund. Anwendungen mit höheren Berechtigungen können den Zugriff verweigern.',
windowsDesktop: 'Interaktiver Desktop',
windowsDesktopUse: 'Für Beobachtung und Eingaben muss der Desktop entsperrt sein.',
windowsCapture: 'Fensteraufnahme',
available: 'Verfügbar',
unavailable: 'Nicht verfügbar',
locked: 'Gesperrt oder getrennt',
elevated: 'Die native Komponente wird mit Administratorrechten ausgeführt.',
standardPrivileges: 'Die native Komponente wird mit Standardbenutzerrechten ausgeführt.',
windowsSetupTitle: 'Desktopumgebung prüfen',
windowsSetupBody: 'Der Desktop ist gesperrt. Entsperren Sie ihn und versuchen Sie es erneut.',
windowsSessionUnknownTitle: 'Desktopsitzung nicht verfügbar',
windowsSessionUnknown: 'Es konnte kein verfügbarer Desktop erkannt werden. Führen Sie DeepSeek Harness in einer angemeldeten Desktopsitzung aus und versuchen Sie es erneut.',
windowsLockedTitle: 'Desktop ist gesperrt',
windowsLockedBody: 'Entsperren Sie den Desktop, damit der Agent Apps ansehen und bedienen kann.',
windowsCaptureUnavailableTitle: 'Fenster-Screenshots nicht verfügbar',
windowsCaptureUnavailable: 'Diese Desktopumgebung unterstützt keine Fensteraufnahme. Prüfen Sie die Betriebssystemversion und den Grafiktreiber und versuchen Sie es erneut.',
windowsCaptureUnavailableNotice: 'Die Fensteraufnahme ist in dieser Umgebung nicht verfügbar. Prüfen oder aktualisieren Sie Betriebssystemversion und Grafiktreiber und versuchen Sie es erneut. DeepSeek Harness kann Apps weiterhin über Bedienungshilfen steuern, jedoch mit eingeschränkter Leistungsfähigkeit.',
windowsHelperFailed: 'Verbindung zum Computer-Use-Hilfsprogramm fehlgeschlagen: {message}',
windowsInstructions: 'Lassen Sie den Desktop während der Nutzung entsperrt. Einige Aktionen erfordern die Zielanwendung im Vordergrund.',
standardPrivileges: 'Wird derzeit mit Standardbenutzerrechten ausgeführt. Apps mit höheren Berechtigungen (z. B. als Administrator) lassen sich möglicherweise nicht steuern.',
approvalRisks: 'Risiken',
approvalRiskTitle: 'Risiken der Computersteuerung',
approvalRiskNotice: 'Der Agent kann nur auf Apps zugreifen, die Sie freigeben. Er kann deren Inhalte lesen und die Apps im Hintergrund steuern.\n\nOnline-Spiele, Messenger und andere Apps können die Automatisierung einschränken. Bei Verstößen gegen ihre Regeln könnte Ihr Konto bei der jeweiligen App vorübergehend oder dauerhaft gesperrt werden.\n\nDie Nutzung erfolgt auf eigenes Risiko. Über Stopp in DeepSeek Harness können Sie die automatisierte Steuerung jederzeit beenden.',
title: 'Autorisieren Sie die Computernutzung',
title: 'Systemberechtigungen',
permissionsIntro: 'Computer Use benötigt die folgenden Systemberechtigungen:',
applicationsTitle: 'Verwalten Sie Anwendungen, auf die der Computer zugreifen kann',
setupTitle: 'Richten Sie die Computernutzung vor der Nutzung ein',
setupBody: 'Die Computernutzung ist aktiviert. Erteilen Sie vor der Verwendung die Berechtigungen für Barrierefreiheit und Bildschirmaufzeichnung. Öffnen Sie die Plugin-Details, um die Einrichtung abzuschließen.',
setupQueryFailed: 'Die Computernutzung ist aktiviert, aber die Systemberechtigungen konnten nicht überprüft werden. Öffnen Sie die Plugin-Details, um den Fehler anzuzeigen, und versuchen Sie es erneut.',
setupBody: 'Computer Use ist aktiviert und benötigt die Berechtigungen für Bedienungshilfen und Bildschirmaufnahme. Öffnen Sie die Plugin-Details, um die Einrichtung abzuschließen.',
setupQueryFailed: 'Computer Use ist aktiviert, aber die Systemberechtigungen konnten nicht geprüft werden. Öffnen Sie die Plugin-Details, um den Fehler anzuzeigen und es erneut zu versuchen.',
openSetup: 'Einstellungen öffnen', later: 'Später', close: 'Schließen',
accessibility: 'Barrierefreiheit', screenRecording: 'Bildschirmaufzeichnung',
accessibilityUse: 'Lesen Sie die Steuerelemente der Benutzeroberfläche, klicken Sie und geben Sie ein.', screenRecordingUse: 'Erfassen Sie das ausgewählte Anwendungsfenster.',
accessibilityPermission: 'Erlauben Sie {application} in den Systemeinstellungen, Schnittstellensteuerelemente zu lesen, zu klicken und zu tippen.',
screenRecordingPermission: 'Erlauben Sie {application} in den Systemeinstellungen, Anwendungsfenster zu erfassen.',
permissionHint: 'Verwalten Sie die Berechtigungen für Bedienungshilfen und Bildschirmaufnahme in den Systemeinstellungen.',
accessibility: 'Bedienungshilfen', screenRecording: 'Bildschirmaufnahme',
accessibilityUse: 'Oberflächeninhalte lesen, klicken und tippen.', screenRecordingUse: 'Das Fenster der ausgewählten Anwendung aufnehmen.',
accessibilityPermission: 'Erlauben Sie {application}, Oberflächeninhalte zu lesen, zu klicken und zu tippen.',
screenRecordingPermission: 'Erlauben Sie {application}, das Fenster der ausgewählten Anwendung aufzunehmen.',
granted: 'Erlaubt', unknown: 'Unbekannt', request: 'Bitte um Erlaubnis', settings: 'Öffnen Sie die Systemeinstellungen', retry: 'Erneut versuchen',
allowedApps: 'Immer zulässige Anwendungen',
blockedApps: 'Nicht erlaubte Anwendungen', retryApproval: 'Erlaube noch einmal nachzufragen',
@@ -262,43 +268,42 @@ export const de = {
noApps: 'Keine immer erlaubten oder blockierten Anwendungen.',
revoke: 'Widerrufen', revoked: 'Anwendungszugriff widerrufen', requested: 'Folgen Sie der Anleitung unten in den Systemeinstellungen', opened: 'Systemeinstellungen geöffnet',
applicationsFailed: 'Anwendungszugriff konnte nicht geladen werden: {message}', iconsFailed: 'Anwendungssymbole konnten nicht geladen werden: {message}',
failed: 'Berechtigungen konnten nicht aktualisiert werden: {message}', queryFailed: 'Berechtigungen konnten nicht überprüft werden: {message}',
failed: 'Berechtigungen konnten nicht aktualisiert werden: {message}', queryFailed: 'Systemberechtigungen konnten nicht geprüft werden: {message}',
queryFailedHint: 'Deaktivieren und aktivieren Sie dieses Plugin erneut oder starten Sie DeepSeek Harness neu. Besteht das Problem weiterhin, prüfen Sie, ob Sicherheitssoftware das Hilfsprogramm blockiert, oder installieren Sie DeepSeek Harness neu.',
} satisfies Record<keyof typeof en, string>
/** Russian dictionary, checked against the English keys. */
export const ru = {
previewNotice: 'Управление компьютером доступно в режиме экспериментального предпросмотра. Агент может нажать не ту кнопку или ввести текст не в то окно. Используйте эту функцию в рабочей среде с осторожностью. Рекомендуем нативный режим PTC: в нём агент может управлять приложениями и вызывать другие инструменты в одной программе.',
windowsHelperBuild: 'Если DSH установлен через npm, соберите вспомогательную программу для Windows из исходного кода той же версии DSH. В каталоге {directory} выполните {x64} или {arm64} с помощью .NET 10 SDK в зависимости от архитектуры компьютера.',
previewNoticeTitle: 'Экспериментальная функция',
previewNotice: 'Управление компьютером находится на экспериментальной стадии, и результат не гарантируется. Агент может нажать не ту кнопку или ввести текст не в то окно. Будьте осторожны в важных и рабочих средах.',
ptcRecommendation: 'Рекомендуем использовать режим PTC, чтобы агент мог управлять приложениями и вызывать другие инструменты в одной программе. Его можно сделать режимом по умолчанию в разделе «Настройки → Настройки агента».',
providerLookupFailed: 'Не удалось определить поставщика Computer Use: {message}',
windowsHelperPath: 'В файле {patch} активного профиля найдите или добавьте запись с идентификатором {entry}. В её разделе {config} задайте для {path} абсолютный путь к {exe}.',
windowsSetupTitle: 'Проверить доступ к рабочему столу Windows',
windowsSetupBody: 'Разблокируйте рабочий стол Windows и повторите проверку. DSH запрашивает разрешение перед доступом к каждому приложению.',
windowsSessionUnknown: 'Интерактивный рабочий стол Windows не подтверждён. Запустите DSH в сеансе вошедшего в систему пользователя и повторите проверку.',
windowsCaptureUnavailable: 'Этот сеанс Windows не поддерживает захват окон. Проверьте версию Windows и графический драйвер, затем повторите проверку.',
applicationInteraction: 'Взаимодействие с приложениями',
windowsInstructions: 'Не блокируйте рабочий стол Windows. Для некоторых действий требуется вывести целевое приложение на передний план. Приложения с повышенными привилегиями могут отказать в доступе.',
windowsDesktop: 'Интерактивный рабочий стол',
windowsDesktopUse: 'Для наблюдения и ввода требуется разблокированный рабочий стол.',
windowsCapture: 'Захват окон',
available: 'Доступно',
unavailable: 'Недоступно',
locked: 'Заблокирован или отключён',
elevated: 'Нативный компонент работает с правами администратора.',
standardPrivileges: 'Нативный компонент работает с обычными правами пользователя.',
windowsSetupTitle: 'Проверить среду рабочего стола',
windowsSetupBody: 'Рабочий стол заблокирован. Разблокируйте его и повторите попытку.',
windowsSessionUnknownTitle: 'Сеанс рабочего стола недоступен',
windowsSessionUnknown: 'Не удалось обнаружить доступный рабочий стол. Запустите DeepSeek Harness в активной сессии рабочего стола и повторите попытку.',
windowsLockedTitle: 'Рабочий стол заблокирован',
windowsLockedBody: 'Разблокируйте рабочий стол, чтобы агент мог видеть приложения и управлять ими.',
windowsCaptureUnavailableTitle: 'Снимки окон недоступны',
windowsCaptureUnavailable: 'Текущая среда рабочего стола не поддерживает захват окон. Проверьте версию ОС и графический драйвер, затем повторите попытку.',
windowsCaptureUnavailableNotice: 'Захват окон недоступен в этой среде. Проверьте или обновите версию ОС и графический драйвер, затем повторите попытку. DeepSeek Harness по-прежнему может управлять приложениями через средства доступности, но с ограниченными возможностями.',
windowsHelperFailed: 'Не удалось подключиться к вспомогательному компоненту управления компьютером: {message}',
windowsInstructions: 'Во время работы держите рабочий стол разблокированным. Для некоторых действий нужно вывести приложение на передний план.',
standardPrivileges: 'Сейчас запущено с обычными правами пользователя. Приложения с повышенными привилегиями (например, от имени администратора) могут не поддаваться управлению.',
approvalRisks: 'Риски',
approvalRiskTitle: 'Риски управления компьютером',
approvalRiskNotice: 'Агент получает доступ только к приложениям, которые вы разрешили, и может читать их содержимое и управлять ими в фоновом режиме.\n\nВ онлайн-играх, мессенджерах и других приложениях могут действовать ограничения на автоматизацию. Нарушение их правил может привести к временной или постоянной блокировке вашей учётной записи в соответствующем приложении.\n\nВы пользуетесь этой возможностью на свой страх и риск. Чтобы в любой момент остановить автоматизированное управление, нажмите «Остановить» в DeepSeek Harness.',
title: 'Разрешить использование компьютера',
title: 'Системные разрешения',
permissionsIntro: 'Для работы управления компьютером требуются следующие системные разрешения:',
applicationsTitle: 'Управление приложениями, к которым может иметь доступ компьютер',
setupTitle: 'Настройте использование компьютера перед использованием',
setupBody: 'Использование компьютера включено. Перед использованием предоставьте разрешения на универсальный доступ и запись экрана. Откройте сведения о плагине, чтобы завершить настройку.',
setupQueryFailed: 'Использование компьютера разрешено, но системные разрешения проверить не удалось. Откройте сведения о плагине, чтобы увидеть ошибку, и повторите попытку.',
setupBody: 'Управление компьютером включено. Для работы требуются разрешения на универсальный доступ и запись экрана. Откройте сведения о плагине, чтобы завершить настройку.',
setupQueryFailed: 'Управление компьютером включено, но не удалось проверить системные разрешения. Откройте сведения о плагине, чтобы посмотреть ошибку и повторить попытку.',
openSetup: 'Открыть настройки', later: 'Позже', close: 'Закрыть',
accessibility: 'Доступность', screenRecording: 'Запись экрана',
accessibilityUse: 'Прочтите элементы управления интерфейсом, щелкните и введите текст.', screenRecordingUse: 'Захват выбранного окна приложения.',
accessibilityPermission: 'В настройках системы разрешите {application} читать элементы управления интерфейсом, щелкать и печатать.',
screenRecordingPermission: 'В настройках системы разрешите {application} захватывать окна приложений.',
permissionHint: 'Управляйте разрешениями на универсальный доступ и запись экрана в системных настройках.',
accessibilityUse: 'Читать элементы интерфейса, нажимать и вводить текст.', screenRecordingUse: 'Захватывать окно выбранного приложения.',
accessibilityPermission: 'Разрешите {application} читать элементы интерфейса, нажимать и вводить текст.',
screenRecordingPermission: 'Разрешите {application} захватывать окно выбранного приложения.',
granted: 'Разрешено', unknown: 'Неизвестно', request: 'Запросить разрешение', settings: 'Открыть настройки системы', retry: 'Повторить',
allowedApps: 'Всегда разрешенные приложения',
blockedApps: 'Приложения не разрешены', retryApproval: 'Разрешить спросить еще раз',
@@ -306,43 +311,42 @@ export const ru = {
noApps: 'Никаких всегда разрешенных или заблокированных приложений.',
revoke: 'Отозвать', revoked: 'Доступ к приложению отозван', requested: 'Следуйте инструкциям внизу окна «Системные настройки».', opened: 'Системные настройки открыты',
applicationsFailed: 'Не удалось загрузить доступ к приложению: {message}.', iconsFailed: 'Не удалось загрузить значки приложений: {message}.',
failed: 'Не удалось обновить разрешения: {message}.', queryFailed: 'Не удалось проверить разрешения: {message}',
failed: 'Не удалось обновить разрешения: {message}.', queryFailed: 'Не удалось проверить системные разрешения: {message}',
queryFailedHint: 'Попробуйте отключить и снова включить этот плагин или перезапустить DeepSeek Harness. Если проблема сохраняется, проверьте, не блокирует ли вспомогательный компонент защитное ПО, или переустановите DeepSeek Harness.',
} satisfies Record<keyof typeof en, string>
/** Portuguese dictionary, checked against the English keys. */
export const pt = {
previewNotice: 'Computer Use é um recurso experimental em prévia. O agente pode clicar no botão errado ou digitar na janela errada. Use com cautela em ambientes de produção. Recomendamos o modo PTC nativo para que o agente possa controlar aplicativos e usar outras ferramentas no mesmo programa.',
windowsHelperBuild: 'Se você instalou o DSH pelo npm, compile o auxiliar do Windows a partir do código-fonte da mesma versão do DSH. Em {directory}, use o SDK do .NET 10 e execute {x64} ou {arm64} conforme a arquitetura do computador.',
previewNoticeTitle: 'Recurso experimental',
previewNotice: 'Computer Use é experimental e os resultados não são garantidos. O agente pode clicar no botão errado ou digitar na janela errada. Use com cautela em ambientes importantes ou de produção.',
ptcRecommendation: 'Recomendamos usar o modo PTC para que o agente possa operar aplicativos e chamar outras ferramentas no mesmo programa. Você pode defini-lo como padrão em Configurações → Predefinições de agente.',
providerLookupFailed: 'Não foi possível identificar o provedor do Computer Use: {message}',
windowsHelperPath: 'No arquivo {patch} do perfil ativo, localize ou adicione a entrada com o ID {entry}. Em {config}, defina {path} como o caminho absoluto de {exe}.',
windowsSetupTitle: 'Verificar acesso à área de trabalho do Windows',
windowsSetupBody: 'Desbloqueie a área de trabalho do Windows e verifique novamente. O DSH pede permissão antes de acessar cada aplicativo.',
windowsSessionUnknown: 'Nenhuma área de trabalho interativa do Windows foi confirmada. Execute o DSH em uma sessão com login e verifique novamente.',
windowsCaptureUnavailable: 'Esta sessão do Windows não oferece suporte à captura de janelas. Verifique a versão do Windows e o driver gráfico e tente novamente.',
applicationInteraction: 'Interação com aplicativos',
windowsInstructions: 'Mantenha a área de trabalho do Windows desbloqueada. Algumas entradas exigem que o aplicativo de destino esteja em primeiro plano. Aplicativos com privilégios mais altos podem recusar o acesso.',
windowsDesktop: 'Área de trabalho interativa',
windowsDesktopUse: 'A observação e a entrada exigem uma área de trabalho desbloqueada.',
windowsCapture: 'Captura de janelas',
available: 'Disponível',
unavailable: 'Indisponível',
locked: 'Bloqueada ou desconectada',
elevated: 'O componente nativo está sendo executado com privilégios de administrador.',
standardPrivileges: 'O componente nativo está sendo executado com privilégios de usuário padrão.',
windowsSetupTitle: 'Verificar ambiente da área de trabalho',
windowsSetupBody: 'A área de trabalho está bloqueada. Desbloqueie-a e tente novamente.',
windowsSessionUnknownTitle: 'Sessão de área de trabalho indisponível',
windowsSessionUnknown: 'Não foi possível detectar uma área de trabalho disponível. Execute o DeepSeek Harness em uma sessão de área de trabalho conectada e tente novamente.',
windowsLockedTitle: 'A área de trabalho está bloqueada',
windowsLockedBody: 'Desbloqueie a área de trabalho para que o agente possa ver e operar aplicativos.',
windowsCaptureUnavailableTitle: 'Capturas de janela indisponíveis',
windowsCaptureUnavailable: 'Este ambiente de área de trabalho não oferece suporte à captura de janelas. Verifique a versão do sistema operacional e o driver gráfico e tente novamente.',
windowsCaptureUnavailableNotice: 'A captura de janelas não está disponível neste ambiente. Verifique ou atualize a versão do sistema operacional e o driver gráfico e tente novamente. O DeepSeek Harness ainda pode operar aplicativos por acessibilidade, com capacidade reduzida.',
windowsHelperFailed: 'Não foi possível conectar ao auxiliar do Computer Use: {message}',
windowsInstructions: 'Mantenha a área de trabalho desbloqueada durante o uso. Algumas ações exigem colocar o aplicativo em primeiro plano.',
standardPrivileges: 'Atualmente em execução com privilégios de usuário padrão. Aplicativos executados com privilégios mais altos (como administrador) podem não ser controláveis.',
approvalRisks: 'Riscos',
approvalRiskTitle: 'Riscos do controle do computador',
approvalRiskNotice: 'O agente só pode acessar os aplicativos que você autorizar e pode ler seu conteúdo e controlá-los em segundo plano.\n\nJogos on-line, aplicativos de mensagens e outros aplicativos podem restringir a automação. Violar essas regras pode levar à suspensão ou ao banimento da sua conta no aplicativo em questão.\n\nUse por sua conta e risco. Para interromper o controle automatizado a qualquer momento, clique em Parar no DeepSeek Harness.',
title: 'Autorizar o uso do computador',
title: 'Permissões do sistema',
permissionsIntro: 'O Computer Use precisa das seguintes permissões do sistema para funcionar:',
applicationsTitle: 'Gerenciar aplicativos que o computador pode acessar',
setupTitle: 'Configure o uso do computador antes de usar',
setupBody: 'O uso do computador está ativado. Antes de usá-lo, conceda permissões de Acessibilidade e Gravação de tela. Abra os detalhes do plugin para concluir a configuração.',
setupQueryFailed: 'O uso do computador está ativado, mas não foi possível verificar as permissões do sistema. Abra os detalhes do plugin para ver o erro e tente novamente.',
setupBody: 'O Computer Use está ativado e precisa das permissões de Acessibilidade e Gravação de tela para funcionar. Abra os detalhes do plugin para concluir a configuração.',
setupQueryFailed: 'O Computer Use está ativado, mas não foi possível verificar as permissões do sistema. Abra os detalhes do plugin para ver o erro e tentar novamente.',
openSetup: 'Abrir configurações', later: 'Mais tarde', close: 'Fechar',
accessibility: 'Acessibilidade', screenRecording: 'Gravação de tela',
accessibilityUse: 'Leia os controles da interface, clique e digite.', screenRecordingUse: 'Capture a janela do aplicativo selecionado.',
accessibilityPermission: 'Nas configurações do sistema, permita que {application} leia os controles da interface, clique e digite.',
screenRecordingPermission: 'Nas configurações do sistema, permita que {application} capture janelas de aplicativos.',
permissionHint: 'Gerencie as permissões de acessibilidade e gravação de tela nas Configurações do sistema.',
accessibilityUse: 'Ler o conteúdo da interface, clicar e digitar.', screenRecordingUse: 'Capturar a janela do aplicativo selecionado.',
accessibilityPermission: 'Permita que {application} leia o conteúdo da interface, clique e digite.',
screenRecordingPermission: 'Permita que {application} capture a janela do aplicativo selecionado.',
granted: 'Permitido', unknown: 'Desconhecido', request: 'Solicitar permissão', settings: 'Abra as configurações do sistema', retry: 'Tentar novamente',
allowedApps: 'Aplicativos sempre permitidos',
blockedApps: 'Aplicativos não permitidos', retryApproval: 'Permitir perguntar novamente',
@@ -350,5 +354,6 @@ export const pt = {
noApps: 'Nenhum aplicativo sempre permitido ou bloqueado.',
revoke: 'Revogar', revoked: 'Acesso ao aplicativo revogado', requested: 'Siga o guia na parte inferior das Configurações do sistema', opened: 'Configurações do sistema abertas',
applicationsFailed: 'Não foi possível carregar o acesso ao aplicativo: {message}', iconsFailed: 'Não foi possível carregar os ícones do aplicativo: {message}',
failed: 'Não foi possível atualizar as permissões: {message}', queryFailed: 'Não foi possível verificar as permissões: {message}',
failed: 'Não foi possível atualizar as permissões: {message}', queryFailed: 'Não foi possível verificar as permissões do sistema: {message}',
queryFailedHint: 'Tente desativar e reativar este plugin ou reiniciar o DeepSeek Harness. Se o problema persistir, verifique se algum software de segurança bloqueou o auxiliar ou reinstale o DeepSeek Harness.',
} satisfies Record<keyof typeof en, string>
+24 -8
View File
@@ -3,56 +3,64 @@
/** English application-access messages. */
export const en = {
question: 'Allow agent to control this application via computer use?',
detail: 'Manage app permissions for all sessions on the plugin page.',
detail: 'Once allowed, the agent can view and operate this app. You can manage app permissions anytime in plugin settings.',
sessionDetail: 'Once allowed, the agent can view and operate this app for this session.',
approve: 'Allow for this session',
}
/** Chinese application-access messages. */
export const zh = {
question: '允许智能体自动操作此应用吗?',
detail: '在插件页面管理所有会话的应用权限。',
detail: '允许后,智能体将能够查看并操作此应用。你可随时在插件设置中管理应用权限。',
sessionDetail: '允许后,智能体将能在本会话内查看并操作此应用。',
approve: '本会话允许',
} satisfies Record<keyof typeof en, string>
/** Japanese application-access messages. */
export const ja = {
question: 'エージェントが Computer Use でこのアプリを操作することを許可しますか?',
detail: 'プラグインページで、すべてのセッションのアプリ権限を管理できます。',
detail: '許可すると、エージェントはこのアプリの内容を確認して操作できます。アプリの権限はプラグイン設定からいつでも管理できます。',
sessionDetail: '許可すると、エージェントはこのセッション中にこのアプリの内容を確認して操作できます。',
approve: 'このセッションで許可',
} satisfies Record<keyof typeof en, string>
/** Spanish dictionary, checked against the English keys. */
export const es = {
question: '¿Permitir que el agente controle esta aplicación mediante Computer Use?',
detail: 'Gestiona los permisos de las aplicaciones para todas las sesiones en la página del plugin.',
detail: 'Si lo permites, el agente podrá ver y controlar esta aplicación. Puedes gestionar los permisos de las aplicaciones en cualquier momento en la configuración del complemento.',
sessionDetail: 'Si lo permites, el agente podrá ver y controlar esta aplicación durante esta sesión.',
approve: 'Permitir durante esta sesión',
} satisfies Record<keyof typeof en, string>
/** French dictionary, checked against the English keys. */
export const fr = {
question: 'Autoriser l’agent à contrôler cette application via Computer Use ?',
detail: 'Gérez les autorisations des applications pour toutes les sessions sur la page du plugin.',
detail: 'Une fois autorisé, l’agent peut consulter et utiliser cette application. Vous pouvez gérer les autorisations des applications à tout moment dans les paramètres du plugin.',
sessionDetail: 'Une fois autorisé, l’agent peut consulter et utiliser cette application pendant cette session.',
approve: 'Autoriser pour cette session',
} satisfies Record<keyof typeof en, string>
/** German dictionary, checked against the English keys. */
export const de = {
question: 'Darf der Agent diese Anwendung über Computer Use steuern?',
detail: 'Verwalten Sie App-Berechtigungen für alle Sitzungen auf der Plugin-Seite.',
detail: 'Nach der Freigabe kann der Agent diese App einsehen und bedienen. Sie können App-Berechtigungen jederzeit in den Plugin-Einstellungen verwalten.',
sessionDetail: 'Nach der Freigabe kann der Agent diese App für diese Sitzung einsehen und bedienen.',
approve: 'Für diese Sitzung zulassen',
} satisfies Record<keyof typeof en, string>
/** Russian dictionary, checked against the English keys. */
export const ru = {
question: 'Разрешить агенту управлять этим приложением через Computer Use?',
detail: 'Управляйте разрешениями приложений для всех сеансов на странице плагина.',
detail: 'После разрешения агент сможет просматривать это приложение и управлять им. Управлять разрешениями приложений можно в любое время в настройках плагина.',
sessionDetail: 'После разрешения агент сможет просматривать это приложение и управлять им в этом сеансе.',
approve: 'Разрешить для этого сеанса',
} satisfies Record<keyof typeof en, string>
/** Portuguese dictionary, checked against the English keys. */
export const pt = {
question: 'Permitir que o agente controle este aplicativo via Computer Use?',
detail: 'Gerencie as permissões dos aplicativos para todas as sessões na página do plugin.',
detail: 'Depois de permitido, o agente poderá visualizar e operar este aplicativo. Você pode gerenciar as permissões de aplicativos a qualquer momento nas configurações do plugin.',
sessionDetail: 'Depois de permitido, o agente poderá visualizar e operar este aplicativo nesta sessão.',
approve: 'Permitir nesta sessão',
} satisfies Record<keyof typeof en, string>
@@ -80,6 +88,14 @@ export const applicationAccessDisplay = {
pt: pt.approve,
},
}
/** Session-only application-access display translations when persistent grants are unavailable. */
export const sessionApplicationAccessDisplay = {
...applicationAccessDisplay,
detail: {
en: en.sessionDetail, zh: zh.sessionDetail, ja: ja.sessionDetail, es: es.sessionDetail,
fr: fr.sessionDetail, de: de.sessionDetail, ru: ru.sessionDetail, pt: pt.sessionDetail,
},
}
/** Window consent never grants access to sibling windows or application launch. */
export const windowAccessQuestion = {
@@ -1,23 +1,23 @@
/** Scope and interruption shown before the user grants system input. */
export const systemInputControlPrompt = {
question: {
en: 'Allow the agent to control your keyboard and mouse?',
zh: '允许智能体控制你的键盘和鼠标吗?',
ja: 'エージェントにキーボードとマウスの操作を許可しますか?',
es: '¿Permitir que el agente controle tu teclado y ratón?',
fr: 'Autoriser l’agent à contrôler votre clavier et votre souris ?',
de: 'Darf der Agent Ihre Tastatur und Maus steuern?',
ru: 'Разрешить агенту управлять клавиатурой и мышью?',
pt: 'Permitir que o agente controle seu teclado e mouse?',
en: 'Allow the agent to directly control your keyboard and mouse?',
zh: '允许智能体直接控制你的键盘和鼠标吗?',
ja: 'エージェントにキーボードとマウスの直接操作を許可しますか?',
es: '¿Permitir que el agente controle directamente tu teclado y ratón?',
fr: 'Autoriser l’agent à contrôler directement votre clavier et votre souris ?',
de: 'Darf der Agent Ihre Tastatur und Maus direkt steuern?',
ru: 'Разрешить агенту напрямую управлять вашей клавиатурой и мышью?',
pt: 'Permitir que o agente controle diretamente seu teclado e mouse?',
},
detail: {
en: 'The agent can send system keystrokes, move your pointer, and hold or release keys and mouse buttons. This can interrupt your input. Your choice lasts until you close this session or restart DSH.',
zh: '智能体可以发送系统键盘输入、移动指针,以及按住或松开键盘键和鼠标按钮,可能打断你的操作。此选择在关闭会话或重启 DSH 前有效。',
ja: 'エージェントはシステムへのキー入力、ポインタ移動、キーやマウスボタンの押下と解放を行えます。操作が中断される場合があります。この選択はセッションを閉じるか DSH を再起動するまで有効です。',
es: 'El agente puede enviar pulsaciones al sistema, mover el puntero y mantener pulsadas o soltar teclas y botones del ratón. Esto puede interrumpir tu interacción. Tu elección se mantiene hasta cerrar la sesión o reiniciar DSH.',
fr: 'L’agent peut envoyer des frappes au système, déplacer le pointeur et maintenir ou relâcher les touches et boutons. Cela peut interrompre vos actions. Votre choix reste valable jusqu’à la fermeture de la session ou au redémarrage de DSH.',
de: 'Der Agent kann Systemtastatureingaben senden, den Zeiger bewegen sowie Tasten und Maustasten gedrückt halten oder loslassen. Dies kann Ihre Eingabe unterbrechen. Ihre Entscheidung gilt bis zum Schließen der Sitzung oder Neustart von DSH.',
ru: 'Агент может отправлять системные нажатия клавиш, перемещать указатель, удерживать и отпускать клавиши и кнопки мыши. Это может прервать ваши действия. Выбор сохраняется до закрытия сеанса или перезапуска DSH.',
pt: 'O agente pode enviar teclas ao sistema, mover o ponteiro e manter teclas e botões pressionados ou soltá-los. Isso pode interromper sua interação. Sua escolha vale até encerrar a sessão ou reiniciar o DSH.',
en: 'Once allowed, the agent can send keystrokes and move or click the mouse, which may interrupt what you are doing. This permission applies only to this session and expires when you close the session or restart DeepSeek Harness.',
zh: '允许后,智能体可直接输入按键、移动和点击鼠标,可能会打断你当前的操作。授权仅在当前会话内有效,关闭会话或重启 DeepSeek Harness 后自动失效。',
ja: '許可すると、エージェントがキー入力やマウスの移動・クリックを直接行えるようになり、作業が中断される場合があります。この許可は現在のセッション中のみ有効で、セッションを閉じるか DeepSeek Harness を再起動すると自動的に失効します。',
es: 'Si lo permites, el agente podrá pulsar teclas y mover o hacer clic con el ratón, lo que puede interrumpir tu actividad actual. Este permiso solo es válido en esta sesión y caduca al cerrarla o reiniciar DeepSeek Harness.',
fr: 'Une fois autorisé, l’agent peut saisir des touches, déplacer la souris et cliquer, ce qui peut interrompre votre activité en cours. Cette autorisation ne s’applique qu’à cette session et expire lorsque vous la fermez ou redémarrez DeepSeek Harness.',
de: 'Nach der Freigabe kann der Agent Tasten drücken sowie die Maus bewegen und klicken, was Ihre laufende Arbeit unterbrechen kann. Diese Erlaubnis gilt nur für diese Sitzung und endet beim Schließen der Sitzung oder Neustart von DeepSeek Harness.',
ru: 'После разрешения агент сможет нажимать клавиши, перемещать курсор и кликать мышью, что может прервать ваши текущие действия. Разрешение действует только в этом сеансе и сбрасывается при его закрытии или перезапуске DeepSeek Harness.',
pt: 'Depois de permitido, o agente poderá digitar teclas e mover ou clicar com o mouse, o que pode interromper o que você está fazendo. Esta permissão vale apenas para esta sessão e expira ao encerrá-la ou reiniciar o DeepSeek Harness.',
},
}
@@ -236,15 +236,21 @@ it.each([
expect(question).toMatchObject({
id: 'cua-app-access',
question: 'Allow computer use to launch if needed, read, capture, and control Test application?',
detail: 'Manage app permissions for all sessions on the plugin page.',
detail: offeredAlways
? 'Once allowed, the agent can view and operate this app. You can manage app permissions anytime in plugin settings.'
: 'Once allowed, the agent can view and operate this app for this session.',
intent: { kind: 'approval', approve: 'Allow for this session', reject: 'Deny',
subject: { name: 'Test application' }, display: {
question: { en: 'Allow agent to control this application via computer use?',
zh: '允许智能体自动操作此应用吗?',
ja: 'エージェントが Computer Use でこのアプリを操作することを許可しますか?' },
detail: { en: 'Manage app permissions for all sessions on the plugin page.',
zh: '在插件页面管理所有会话的应用权限。',
ja: 'プラグインページで、すべてのセッションのアプリ権限を管理できます。' },
detail: offeredAlways
? { en: 'Once allowed, the agent can view and operate this app. You can manage app permissions anytime in plugin settings.',
zh: '允许后,智能体将能够查看并操作此应用。你可随时在插件设置中管理应用权限。',
ja: '許可すると、エージェントはこのアプリの内容を確認して操作できます。アプリの権限はプラグイン設定からいつでも管理できます。' }
: { en: 'Once allowed, the agent can view and operate this app for this session.',
zh: '允许后,智能体将能在本会话内查看并操作此应用。',
ja: '許可すると、エージェントはこのセッション中にこのアプリの内容を確認して操作できます。' },
approve: { en: 'Allow for this session', zh: '本会话允许', ja: 'このセッションで許可',
es: 'Permitir durante esta sesión', fr: 'Autoriser pour cette session', de: 'Für diese Sitzung zulassen',
ru: 'Разрешить для этого сеанса', pt: 'Permitir nesta sessão' },
@@ -88,13 +88,23 @@ it.each([en, zh])('waits for platform identification before offering system perm
const f = fixture()
render(<PermissionPanel {...f.props} t={makeTranslate(dictionary)} />)
expect(screen.queryByRole('group', { name: dictionary.accessibility })).toBeNull()
expect(screen.getByText(dictionary.permissionHint).getAttribute('aria-hidden')).toBe('true')
expect(screen.getByText(dictionary.permissionsIntro).getAttribute('aria-hidden')).toBe('true')
f.publish({ system: { ...f.state.getSnapshot().system, busy: false, error: 'connection lost' }, busy: false })
// The provider lookup has not answered yet, so neither platform's layout or failure appears.
expect(screen.queryByRole('alert')).toBeNull()
expect(screen.queryAllByText(dictionary.unknown)).toHaveLength(0)
expect(screen.getByText(dictionary.permissionsIntro).getAttribute('aria-hidden')).toBe('true')
f.publish({ windowsProvider: { value: false, error: null, busy: false } })
expect(screen.getAllByText(dictionary.unknown)).toHaveLength(2)
expect(screen.queryByText(dictionary.granted)).toBeNull()
expect(screen.queryByRole('button', { name: dictionary.request })).toBeNull()
expect(screen.queryByRole('button', { name: dictionary.unknown })).toBeNull()
expect(screen.getByText(dictionary.permissionHint).getAttribute('aria-hidden')).toBe('true')
expect(screen.queryByText(dictionary.permissionsIntro)).toBeNull()
const alert = screen.getByRole('alert')
expect(within(alert).getByText(dictionary.queryFailedHint)).toBeTruthy()
const heading = screen.getByRole('heading', { name: dictionary.title })
expect(heading.compareDocumentPosition(alert) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(alert.compareDocumentPosition(screen.getByRole('group', { name: dictionary.accessibilityUse })) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
f.publish({ ...observe({ ...value, system: { ...value.system, accessibility: true, screenRecording: false } }) })
fireEvent.click(screen.getByRole('button', { name: dictionary.request }))
expect(f.props.request).toHaveBeenCalledWith('screenRecording')
@@ -106,7 +116,7 @@ it('offers setup after inspection, permits dismissal, and dismisses once both pr
expect(screen.queryByRole('dialog')).toBeNull()
f.publish({ ...observe(value) })
const dialog = screen.getByRole('dialog', { name: en.setupTitle })
expect(within(dialog).getByText('Computer use is enabled. Before using it, grant Accessibility and Screen Recording permissions. Open the plugin details to complete setup.')).toBeTruthy()
expect(within(dialog).getByText(en.setupBody)).toBeTruthy()
fireEvent.click(within(dialog).getByRole('button', { name: en.openSetup }))
expect(onOpenDetails).toHaveBeenCalledOnce()
fireEvent.click(within(dialog).getByRole('button', { name: en.later }))
@@ -213,10 +223,10 @@ it.each([en, zh])('shows system permissions with the target application beside e
const recording = within(requirements).getByRole('group', { name: dictionary.screenRecording })
expect(within(recording).getByText(application.name)).toBeTruthy()
expect(recording.textContent).toContain(dictionary.screenRecordingPermission.replace('{application}', application.name))
expect(within(requirements).getByText(dictionary.permissionHint)).toBeTruthy()
expect(within(requirements).getByText(dictionary.permissionsIntro)).toBeTruthy()
f.publish({ system: { ...f.state.getSnapshot().system, error: 'offline' } })
expect(screen.queryByText(application.name)).toBeNull()
expect(within(requirements).getByText(dictionary.permissionHint)).toBeTruthy()
expect(within(requirements).getByText(dictionary.permissionsIntro)).toBeTruthy()
})
it('names the authorization target even when its icon is unavailable', () => {
@@ -240,12 +250,12 @@ it('waits for the first current observation instead of opening setup with a stal
})
it('keeps permission management guidance after both permissions are granted', () => {
it('shows both permissions as allowed without a redundant macOS footer', () => {
const f = fixture()
render(<PermissionPanel {...f.props} />)
f.publish({ ...observe({ ...value, system: { ...value.system, accessibility: true, screenRecording: true } }) })
expect(screen.getAllByText(en.granted)).toHaveLength(2)
expect(screen.getByText(en.permissionHint)).toBeTruthy()
expect(screen.getByText(en.permissionsIntro)).toBeTruthy()
})
@@ -385,51 +395,98 @@ it('retains a known query failure throughout management and refresh', () => {
expect(f.state.getSnapshot().changing).toBe(true)
})
it('shows Windows setup above the controls even when the helper is missing', () => {
it.each([en, zh])('highlights the experimental notice and keeps the PTC recommendation separate', (dictionary) => {
const f = fixture()
f.publish({ system: { value: null, error: 'helper missing', busy: false }, windowsProvider: { value: true, error: null, busy: false } })
render(<PermissionPanel {...f.props} />)
const instructions = screen.getByText(/pnpm run build:native:x64/)
const firstSetting = screen.getByRole('heading', { name: en.title })
expect(instructions.compareDocumentPosition(firstSetting) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(screen.getByText(/helperPath/)).toBeTruthy()
expect(screen.queryByRole('button', { name: en.request })).toBeNull()
f.publish({ ...observe(value) })
render(<PermissionPanel {...f.props} t={makeTranslate(dictionary)} />)
const note = screen.getByRole('note')
expect(within(note).getByText(dictionary.previewNoticeTitle)).toBeTruthy()
expect(within(note).getByText(dictionary.previewNotice)).toBeTruthy()
expect(within(note).queryByText(dictionary.ptcRecommendation)).toBeNull()
const ptc = screen.getByText(dictionary.ptcRecommendation)
const heading = screen.getByRole('heading', { name: dictionary.title })
expect(note.compareDocumentPosition(ptc) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(ptc.compareDocumentPosition(heading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
})
it('keeps the provider lookup diagnostic beside the native error until the platform is known', () => {
const f = fixture()
f.publish({ system: { value: null, error: 'helper missing', busy: false }, windowsProvider: { value: null, error: 'offline', busy: false } })
render(<PermissionPanel {...f.props} />)
const diagnostic = en.providerLookupFailed.replace('{message}', 'offline')
expect(screen.getByText(diagnostic)).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: en.retry }))
expect(f.props.refresh).toHaveBeenCalledTimes(2)
f.publish({ system: { value: value.system, error: null, busy: false } })
expect(screen.queryByText(diagnostic)).toBeNull()
})
it.each([true, false, null] as const)('shows Windows desktop access for lock state %s without macOS permission actions', (sessionLocked) => {
it.each([true, false, null] as const)('omits system permissions on Windows and places warnings above the experimental notice for lock=%s', (sessionLocked) => {
const f = fixture()
f.publish({ ...observe(value), system: { value: { platform: 'windows', sessionLocked, captureAvailable: true,
elevated: false, helper: { path: 'C:\\helper.exe' } }, error: null, busy: false } })
render(<PermissionPanel {...f.props} />)
expect(screen.getByText(en.previewNotice)).toBeTruthy()
expect(screen.getByText(/helperPath/)).toBeTruthy()
const desktop = screen.getByRole('group', { name: en.windowsDesktop })
const capture = screen.getByRole('group', { name: en.windowsCapture })
expect(within(desktop).getByText(sessionLocked === null ? en.unknown : sessionLocked ? en.locked : en.available)).toBeTruthy()
expect(within(capture).getByText(sessionLocked === null ? en.unknown : sessionLocked ? en.unavailable : en.available)).toBeTruthy()
expect(screen.getByText(en.standardPrivileges, { exact: false })).toBeTruthy()
expect(screen.queryByRole('group', { name: en.accessibility })).toBeNull()
expect(screen.queryByRole('heading', { name: en.title })).toBeNull()
expect(screen.queryByRole('region', { name: en.title })).toBeNull()
expect(screen.queryByRole('group')).toBeNull()
expect(screen.queryByRole('button', { name: en.request })).toBeNull()
expect(screen.queryByRole('button', { name: en.granted })).toBeNull()
expect(screen.queryByText('C:\\helper.exe')).toBeNull()
expect(screen.queryByText(/helperPath/)).toBeNull()
expect(screen.queryByText(/pnpm run build:native/)).toBeNull()
const experimental = screen.getByText(en.previewNoticeTitle)
const instructions = screen.getByText(en.windowsInstructions)
const privileges = screen.getByText(en.standardPrivileges)
const ptc = screen.getByText(en.ptcRecommendation)
expect(experimental.compareDocumentPosition(instructions) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(instructions.compareDocumentPosition(privileges) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(privileges.compareDocumentPosition(ptc) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
if (sessionLocked === true) {
const note = screen.getByText(en.windowsLockedTitle).closest('[role="note"]')!
expect(within(note as HTMLElement).getByText(en.windowsLockedBody)).toBeTruthy()
expect(note.compareDocumentPosition(experimental) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
} else if (sessionLocked === null) {
const note = screen.getByText(en.windowsSessionUnknownTitle).closest('[role="note"]')!
expect(within(note as HTMLElement).getByText(en.windowsSessionUnknown)).toBeTruthy()
expect(note.compareDocumentPosition(experimental) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
}
// Standing desktop conditions never interrupt assistive technology.
expect(screen.queryByRole('alert')).toBeNull()
f.publish({ system: { value: { platform: 'windows', sessionLocked: false, captureAvailable: false,
elevated: true, helper: {} }, error: null, busy: false } })
expect(within(capture).getByText(en.unavailable)).toBeTruthy()
expect(screen.getByText(en.elevated, { exact: false })).toBeTruthy()
expect(screen.queryByRole('alert')).toBeNull()
// Administrator privileges add no warning; they only withhold the standard-privilege limitation.
expect(screen.queryAllByRole('note').filter(note => note.textContent?.includes('administrator'))).toEqual([])
const captureNotice = screen.getByText(en.windowsCaptureUnavailableTitle)
expect(screen.getByText(en.windowsCaptureUnavailableNotice)).toBeTruthy()
expect(captureNotice.compareDocumentPosition(experimental) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(screen.queryByText(en.standardPrivileges)).toBeNull()
f.publish({ system: { ...f.state.getSnapshot().system, error: 'offline' } })
expect(screen.getAllByText(en.unknown)).toHaveLength(2)
const helperAlert = screen.getByRole('alert')
expect(within(helperAlert).getByText(en.windowsHelperFailed.replace('{message}', 'offline'))).toBeTruthy()
expect(within(helperAlert).getByText(en.queryFailedHint)).toBeTruthy()
expect(helperAlert.compareDocumentPosition(experimental) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
expect(screen.queryByText(en.windowsCaptureUnavailableTitle)).toBeNull()
fireEvent.click(within(helperAlert).getByRole('button', { name: en.retry }))
expect(f.props.refresh).toHaveBeenCalledTimes(2)
})
it('shows the Windows helper warning above the experimental notice when startup fails before reporting platform', () => {
const f = fixture()
f.publish({ system: { value: null, error: 'Native helper not found', busy: false },
windowsProvider: { value: true, error: null, busy: false } })
render(<PermissionPanel {...f.props} />)
expect(screen.queryByRole('heading', { name: en.title })).toBeNull()
expect(screen.queryByRole('group')).toBeNull()
const alert = screen.getByRole('alert')
expect(within(alert).getByText(en.windowsHelperFailed.replace('{message}', 'Native helper not found'))).toBeTruthy()
expect(within(alert).getByText(en.queryFailedHint)).toBeTruthy()
const experimental = screen.getByText(en.previewNoticeTitle)
expect(alert.compareDocumentPosition(experimental) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
})
it('reports a failed provider lookup instead of the native error until the platform is known', () => {
const f = fixture()
f.publish({ system: { value: null, error: 'helper missing', busy: false }, windowsProvider: { value: null, error: 'offline', busy: false } })
render(<PermissionPanel {...f.props} />)
const alert = screen.getByRole('alert')
expect(within(alert).getByText(en.providerLookupFailed.replace('{message}', 'offline'))).toBeTruthy()
expect(within(alert).getByText(en.queryFailedHint)).toBeTruthy()
expect(screen.queryByText(en.queryFailed.replace('{message}', 'helper missing'))).toBeNull()
fireEvent.click(within(alert).getByRole('button', { name: en.retry }))
expect(f.props.refresh).toHaveBeenCalledTimes(2)
f.publish({ system: { value: null, error: 'helper missing', busy: false }, windowsProvider: { value: false, error: null, busy: false } })
expect(within(screen.getByRole('alert')).getByText(en.queryFailed.replace('{message}', 'helper missing'))).toBeTruthy()
f.publish({ system: { value: value.system, error: null, busy: false } })
expect(screen.queryByRole('alert')).toBeNull()
})
it.each([[true, true], [false, true], [false, false], [null, true]] as const)('offers Windows setup for lock=%s and capture=%s', (sessionLocked, captureAvailable) => {
@@ -9286,7 +9286,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'ManagementError',
declaration: 'export interface ManagementError {\n code: ReadOnlyReason | \'unknown-plugin\' | \'invalid-spec\' | \'already-installed\' | \'ambiguous-install\' | \'not-bundle\' | \'not-removable\' | \'stop-profile\' | \'bundle-in-use\' | \'stale-approval\' | \'incompatible-version\' | \'unsupported-platform\' | \'unexpected-package\' | \'operation-error\';\n diagnostic?: string;\n incompatible?: IncompatiblePlugin[];\n}',
declaration: 'export interface ManagementError {\n code: ReadOnlyReason | \'unknown-plugin\' | \'invalid-spec\' | \'already-installed\' | \'ambiguous-install\' | \'not-bundle\' | \'not-removable\' | \'stop-profile\' | \'bundle-in-use\' | \'stale-approval\' | \'incompatible-version\' | \'unsupported-platform\' | \'unexpected-package\' | \'operation-error\';\n diagnostic?: string;\n incompatible?: IncompatiblePlugin[];\n platforms?: string[];\n}',
},
{
name: 'ManualCompactAgentContext',