Merge branch 'feat/upstream-skills' into feat/wecom-plugin

This commit is contained in:
gengruilin committed 2026-11-17 15:06:35 +08:00
commit 4c7c1933bd
3267 files changed
+118001 -29842

No files matched your search

+2 -2
View File
@@ -12,8 +12,8 @@
en: cc03e6b75206661b
zh: 99e41f4143198352
/deepseek-ai-dsh/profiles:
en: 523477a093beb0c2
zh: f88ea21e5fbea969
en: 85171337ac2fb2ff
zh: 705a4eef97d9b519
/deepseek-ai-dsh/optional-overlays:
en: 3a40ddc44e55f79c
zh: 8d3949132e1ef93c
+1 -1
View File
@@ -34,7 +34,7 @@ dsh --help # the launcher's own help
<a id="profiles"></a>
## Profiles
A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest and both profile and home patch files, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics.
A profile directory holds a `package.json` (out-of-tree plugin dependencies plus the profile manifest `dsh.profile` with its ordered `bundles` list) and a `cordis.patch.yml` (the user's own patch layer). `dsh-hmr`, when enabled in YAML, watches the profile manifest, the profile and home patch files, and every `--patch` overlay file, then recomposes all layers through one serialized reload. Without HMR, changes apply on restart, except that a Config Editor save applies the current contents of every patch and overlay file. Edits arriving during watcher registration use the same nonfatal reload reporting as later edits. [Plugin Manager](../../packages/boot/plugin-manager/README.md) shares package operations and the profile write lock with `dsh plugin`; package updates retain disabled bundle selections. CLI package commands inherit authentication variables and terminal descriptors, including interactive build approval; service calls retain their scrubbed environment and captured diagnostics.
Installation and profile startup enforce the declared `engines.dsh` range, or DSH peer ranges when it is absent, against the same runtime version shown by `dsh --version`. Incompatible plugins require an explicitly acknowledged exact-version exemption. The [plugin manager's compatibility reference](../../packages/boot/plugin-manager/README.md#version-compatibility-and-exemptions) documents `version-exemptions`, `allow-version`, `revoke-version`, persistence, and risks.
+1 -1
View File
@@ -34,7 +34,7 @@ dsh --help # the launcher's own help
<a id="profiles"></a>
## Profile
profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。
profile 目录包含一个 `package.json`,其中记录树外插件依赖,以及 profile manifest(元数据清单)`dsh.profile`、其中按顺序排列的 `bundles` 列表;还包含一个 `cordis.patch.yml`,其中保存用户自己的 patch 层。在 YAML 中启用的 `dsh-hmr` 监视 profile manifest、profile 与 home 级 patch 文件以及每个 `--patch` overlay 文件,再通过统一串行重载重新组合所有层。未启用 HMR 时,更改在重启后生效;例外是 Config Editor 保存时会应用所有 patch 与 overlay 文件的当前内容。监听器注册期间发生的编辑与后续编辑使用相同的非致命重载错误报告。[插件管理器](../../packages/boot/plugin-manager/README.zh.md) 与 `dsh plugin` 共享包操作和 profile 写锁;更新依赖会保留已停用的组合包选择。CLI 包操作继承认证环境和终端描述符,支持交互式构建批准;service 调用保留清理后的环境并捕获诊断。
安装和 profile 启动会按声明的 `engines.dsh` 范围(未声明时按 DSH peer 范围),检查与 `dsh --version` 显示值相同的运行时版本。不兼容插件需要用户明确确认精确版本豁免。[插件管理器的兼容性参考](../../packages/boot/plugin-manager/README.zh.md#version-compatibility-and-exemptions)说明 `version-exemptions`、`allow-version`、`revoke-version`、持久化规则与风险。
+6
View File
@@ -86,6 +86,8 @@ flowchart LR
cfg --> plugin_dsh_base_session_telemetry_otel
plugin_dsh_base_subprocess["subprocess<br/>@deepseek-ai/dsh-subprocess-local"]
cfg --> plugin_dsh_base_subprocess
plugin_dsh_base_cli_account["cli-account<br/>@deepseek-ai/dsh-cli-account"]
cfg --> plugin_dsh_base_cli_account
plugin_dsh_base_sandbox["sandbox<br/>@deepseek-ai/dsh-sandbox-local"]
cfg --> plugin_dsh_base_sandbox
plugin_dsh_base_sandbox_policy["sandbox-policy<br/>@deepseek-ai/dsh-sandbox-policy"]
@@ -120,6 +122,8 @@ flowchart LR
cfg --> plugin_dsh_base_skill_filesystem
plugin_dsh_base_tool_skill["tool-skill<br/>@deepseek-ai/dsh-tool-skill"]
cfg --> plugin_dsh_base_tool_skill
plugin_dsh_base_upstream_skills["upstream-skills<br/>@deepseek-ai/dsh-upstream-skills"]
cfg --> plugin_dsh_base_upstream_skills
plugin_dsh_base_commands["commands<br/>@deepseek-ai/dsh-commands"]
cfg --> plugin_dsh_base_commands
plugin_dsh_base_command_feedback["command-feedback<br/>@deepseek-ai/dsh-command-feedback"]
@@ -249,6 +253,7 @@ flowchart LR
| `otel` | `@deepseek-ai/dsh-otel` |
| `session-telemetry-otel` | `@deepseek-ai/dsh-session-telemetry-otel` |
| `subprocess` | `@deepseek-ai/dsh-subprocess-local` |
| `cli-account` | `@deepseek-ai/dsh-cli-account` |
| `sandbox` | `@deepseek-ai/dsh-sandbox-local` |
| `sandbox-policy` | `@deepseek-ai/dsh-sandbox-policy` |
| `bash-sandbox` | `@deepseek-ai/dsh-bash-sandbox` |
@@ -266,6 +271,7 @@ flowchart LR
| `skill` | `@deepseek-ai/dsh-skill` |
| `skill-filesystem` | `@deepseek-ai/dsh-skill-filesystem` |
| `tool-skill` | `@deepseek-ai/dsh-tool-skill` |
| `upstream-skills` | `@deepseek-ai/dsh-upstream-skills` |
| `commands` | `@deepseek-ai/dsh-commands` |
| `command-feedback` | `@deepseek-ai/dsh-command-feedback` |
| `goal` | `@deepseek-ai/dsh-goal` |
+5 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh",
"description": "dsh CLI: profile launch, plugin management, and configuration inspection",
"version": "0.2.2-rc.2",
"version": "0.2.2-rc.3",
"publishConfig": {
"access": "public"
},
@@ -115,9 +115,12 @@
"@deepseek-ai/dsh-experimental-session-search": "workspace:*",
"@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*",
"@deepseek-ai/dsh-cua-bundle": "workspace:*",
"@deepseek-ai/dsh-cua-mcp": "workspace:*",
"@deepseek-ai/dsh-timeline": "workspace:*",
"@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*",
"@deepseek-ai/dsh-personalized-recommendations": "workspace:*",
"@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*"
"@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*",
"@deepseek-ai/dsh-deepseek-chat-import": "workspace:*"
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:*",
+2 -2
View File
@@ -21,8 +21,8 @@
en: 8d2cfff9bab7327f
zh: 21515ab6e6798504
/dsh-cli-behavior-reference/web-profile:
en: 149c5571acd51baf
zh: 300e3c2425273a92
en: afc6ddcd63f24664
zh: ed11d2ad6d7a9852
/dsh-cli-behavior-reference/shared-deployment-behavior:
en: f02219118dcec531
zh: fe2977628d7340da
+1 -1
View File
@@ -128,7 +128,7 @@ The production Web runner needs built package and frontend artifacts (`pnpm run
Process shutdown gives the plugin tree up to five seconds to dispose. The first `SIGINT`/`SIGTERM` starts that graceful drain — `SIGTERM` is a supervisor's ordinary stop request and exits 0 on every surface, `SIGINT` reports 130; a second signal forces immediate exit. If one-shot normal completion is already stuck in disposal, the first `Ctrl+C` is the escalation and exits immediately instead of being swallowed.
The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers.
The base-backed modes treat the invoking directory as the default workspace root, load applicable `AGENTS.md` or `CLAUDE.md` instructions with a 65,536-byte render budget for each instruction chain, and use an in-memory SQLite session content index. The standalone `sdk-minimal` profile uses the invoking directory as its sandbox-policy root and includes `read_image`, but omits text filesystem tools, instruction discovery, and SQLite. An enabled HMR plugin watches both `cordis.patch.yml` layers (profile and home) and every `--patch` overlay file, and reapplies valid edits transactionally; without HMR, the process applies them once. A one-shot surface exits through its bounded shutdown, which disposes any live watchers.
New sessions in base-backed profiles default to the `workspace-write` permission preset. Bash and filesystem mutations are restricted to the session workspace and platform temporary roots; reads and network access are not confined, while process visibility depends on the selected sandbox backend — bwrap runs commands in a private PID namespace that hides host processes, and Landlock and Seatbelt leave host process visibility unchanged. `DSH_PERMISSION_MODE` changes the process fallback. Stored General-settings permissions affect later Web sessions, not an already-open one. The standalone `sdk-minimal` tree instead pins `danger-full-access` and mounts no approval or permission-settings service.
+1 -1
View File
@@ -128,7 +128,7 @@ dsh web --help
进程关闭时,插件树最多有 5 秒完成 dispose。首次收到 `SIGINT` 或 `SIGTERM` 时会开始优雅排空:`SIGTERM` 是监督进程发出的常规停止请求,在所有运行模式下都以 0 退出;`SIGINT` 则报告 130。第二次收到信号时会立即强制退出。如果一次性运行在正常结束时已经卡在 dispose 阶段,第一次按下 `Ctrl+C` 就会直接升级为强制退出,而不会被忽略。
基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。
基于 base 的模式都将运行命令时所在的目录作为默认 workspace 根目录,以每条指令链 65,536 字节的渲染预算加载适用的 `AGENTS.md` 或 `CLAUDE.md` 指令,并使用内存 SQLite 会话内容索引。独立的 `sdk-minimal` profile 把运行命令时所在的目录作为沙箱策略根目录并包含 `read_image`,但省略文本文件系统工具、指令发现与 SQLite。启用的 HMR 插件会监视 profile 与 home 两个 `cordis.patch.yml` 配置层以及每个 `--patch` overlay 文件的有效变更,并以事务方式重新应用;未启用 HMR 时只应用一次。一次性运行模式通过有界关闭流程退出,该流程会 dispose 所有实时监视器。
基于 base 的 profile 中,新会话默认使用 `workspace-write` 权限预设。Bash 和文件系统修改仅限于会话 workspace 与平台临时根目录;读取和网络访问不受限制,进程可见性则取决于所选沙箱后端——bwrap 在私有 PID 命名空间中运行命令并隐藏宿主进程,Landlock 与 Seatbelt 保持宿主进程可见性不变。`DSH_PERMISSION_MODE` 更改进程后备值。General settings 中存储的权限影响后续 Web 会话,不改变已打开的会话。独立的 `sdk-minimal` 配置树则固定为 `danger-full-access`,且不挂载 approval 或权限 settings 服务。
+4 -7
View File
@@ -14,14 +14,12 @@ import { existsSync, mkdirSync, mkdtempSync, renameSync, rmSync, writeFileSync }
import { dirname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { FiberState, type Context } from '@deepseek-ai/cordis'
import type { PatchOptions } from '@deepseek-ai/cordis-plugin-include'
import {
boot,
readProfilePatches,
createRuntimeResolution,
initProfile,
installFailLoud,
loadOverlayPatches,
loadProfile,
reportSkippedBundles,
PluginPackages,
@@ -204,8 +202,8 @@ interface ComposedProfile {
profile: Profile
/** Immutable runtime resolution computed before any plugin imports. */
resolution: RuntimeResolution
/** Command-line overlay contents, frozen for this invocation. */
overlays: PatchOptions[]
/** Absolute command-line overlay files, in argv order. */
overlayPaths: string[]
}
/**
@@ -231,8 +229,7 @@ async function composeProfile(
if (resolvedProfile !== undefined) writeFileSync(join(profile.dir, PROFILE_ROOT_FILENAME), PROFILE_ROOT_CONFIG)
const resolutionOptions = { installAnchor: resolvedProfile?.installAnchor ?? INSTALL_ANCHOR, profile }
const resolution = await createRuntimeResolution(resolutionOptions)
const overlays = patchFiles.flatMap(file => loadOverlayPatches(NAME, resolve(file)))
return { profile, resolution, overlays }
return { profile, resolution, overlayPaths: patchFiles.map(file => resolve(file)) }
}
/** An application-owned profile and its independent installation fallback. */
@@ -331,7 +328,7 @@ export async function runProfile(options: RunProfileOptions): Promise<{ ctx: Con
installAnchor: options.resolvedProfile?.installAnchor ?? INSTALL_ANCHOR,
startedBundles: composed.profile.layers.map(layer => layer.packageName),
cwd: process.cwd(), home: resolveDshHome(),
overlays: composed.overlays, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED,
overlayPaths: composed.overlayPaths, telemetryDisabledEnv: process.env.DSH_TELEMETRY_DISABLED,
}
const ctx = await boot(NAME, rootConfig, readProfilePatches(NAME, profileContext, composed.profile), async (hostCtx) => {
app.current = hostCtx
+3 -6
View File
@@ -13,9 +13,8 @@ import {
} from '@agentclientprotocol/sdk'
import { withFileLock, writeFileAtomic } from '@deepseek-ai/dsh-atomic-write'
import { startMockLlmServer } from '@deepseek-ai/dsh-llm-mock-server'
import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import { execa } from 'execa'
import * as yaml from 'js-yaml'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { testProfileResolution } from './profiles/headless/tests/profile-resolution.ts'
@@ -144,9 +143,7 @@ function createProfileLifecycleFixture(): ProfileLifecycleFixture {
writeFileSync(join(profileDir, 'cordis.patch.yml'), '[]\n')
const linkTarget = join(profileDir, 'node_modules', 'dsh-lifecycle-bundle')
mkdirSync(join(profileDir, 'node_modules'), { recursive: true })
try {
rmSync(linkTarget, { recursive: true, force: true })
} catch { /* fresh dir */ }
rmSync(linkTarget, { recursive: true, force: true })
// Copy-free: a package.json redirecting via a relative main is enough for require.resolve.
mkdirSync(linkTarget, { recursive: true })
for (const file of ['package.json', 'cordis.patch.yml', 'plugin.mjs']) {
@@ -1259,7 +1256,7 @@ describe.skipIf(!existsSync(dshBin))('dsh BUILT bin (node lib/bin.js, no tsx)',
)
expect(code).toBe(0)
expect(stderr).toBe('')
const rows = yaml.load(stdout, { schema: entryListSchema }) as Array<{ id?: string; name?: string }>
const rows = parseEntryYaml(stdout) as Array<{ id?: string; name?: string }>
expect(rows.map(row => [row.id, row.name])).toEqual([
['sdk-app-startup', '@deepseek-ai/dsh-sdk-app'],
['sdk-jsonrpc-server', '@deepseek-ai/dsh-sdk-jsonrpc-server'],
+69 -19
View File
@@ -1,14 +1,23 @@
/** Built Desktop Host lifecycle with Electron disconnecting before profile startup settles. */
/** Built Desktop Host credential receipt and shutdown before profile startup settles. */
import { fork } from 'node:child_process'
import { copyFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { randomBytes } from 'node:crypto'
import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { delimiter, dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { finished } from 'node:stream/promises'
import { expect, it, onTestFinished } from 'vitest'
it.each([false, true])('settles startup after parent IPC disconnect (boot failure: %s)', async (fail) => {
it.each([
{ event: 'disconnect', phase: 'credentials', fail: false },
{ event: 'shutdown', phase: 'credentials', fail: false },
{ event: 'invalid-credential', phase: 'credentials', fail: true },
{ event: 'disconnect', phase: 'startup', fail: false },
{ event: 'disconnect', phase: 'startup', fail: true },
{ event: 'shutdown', phase: 'startup', fail: false },
{ event: 'shutdown', phase: 'startup', fail: true },
] as const)('settles $event while waiting for $phase (failure: $fail)', async ({ event, phase, fail }) => {
const root = mkdtempSync(join(tmpdir(), 'desktop-disconnect-'))
const modules = join(root, 'node_modules', '@deepseek-ai')
const hostDirectory = fileURLToPath(new URL('../../desktop-host/', import.meta.url))
@@ -23,8 +32,12 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
writeFileSync(join(root, 'package.json'), '{"type":"module"}')
writeFileSync(join(modules, 'dsh-app-boot', 'package.json'), '{"type":"module","exports":"./index.js"}')
writeFileSync(join(modules, 'dsh-app-boot', 'index.js'), `
import { writeFileSync } from 'node:fs';
export class StartupError extends Error {}
export const loadProfileDirectory = () => ({ skippedBundles: [] });
export const loadProfileDirectory = () => {
writeFileSync(${JSON.stringify(join(root, 'profile-loaded'))}, 'loaded');
return { skippedBundles: [] };
};
export const reportSkippedBundles = () => {};
export const loadLayeredEnv = () => ({});
`)
@@ -33,12 +46,19 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
import { writeFileSync } from 'node:fs';
export function runProfile(options) {
process.send({ type: 'booting', packageManager: options.packageManager });
return new Promise((resolve, reject) => process.once('disconnect', () => {
if (${String(fail)}) { reject(new Error('fixture boot failure')); return; }
resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {}, inject: () => {},
connection: { authenticatedUrl: value => value }, webServer: { port: 19387 } },
shutdown: { shutdown: async () => writeFileSync(${JSON.stringify(join(root, 'stopped'))}, 'stopped') } });
}));
return new Promise((resolve, reject) => {
const settle = () => {
process.off('disconnect', settle);
process.off('message', onMessage);
if (${String(fail)}) { reject(new Error('fixture boot failure')); return; }
resolve({ ctx: { plugin: async () => {}, effect: () => {}, on: () => {}, inject: () => {},
connection: { authenticatedUrl: value => value }, webServer: { port: 19387 } },
shutdown: { shutdown: async () => writeFileSync(${JSON.stringify(join(root, 'stopped'))}, 'stopped') } });
};
const onMessage = message => { if (message.type === 'shutdown') settle(); };
process.once('disconnect', settle);
process.on('message', onMessage);
});
}
`)
const entry = join(root, 'index.js')
@@ -50,6 +70,8 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
child.stderr!.setEncoding('utf8').on('data', (chunk: string) => { stderr += chunk })
const exited = new Promise<number | null>(resolve => child.once('exit', resolve))
const drained = finished(child.stderr!, { cleanup: true })
const messages: unknown[] = []
child.on('message', (message) => { messages.push(message) })
onTestFinished(async () => {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
await Promise.all([exited, drained])
@@ -58,28 +80,56 @@ it.each([false, true])('settles startup after parent IPC disconnect (boot failur
try {
const boot = await new Promise<{
packageManager: { command: string; args: string[]; env: Record<string, string> }
}>((resolve, reject) => {
} | undefined>((resolve, reject) => {
child.on('message', (message) => {
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'starting') {
if (phase === 'credentials') { resolve(undefined); return }
child.send({ type: 'desktop-auth', secret: randomBytes(32).toString('base64url') }, (error) => {
if (error !== null) reject(error)
})
}
if (typeof message === 'object' && message !== null && 'type' in message && message.type === 'booting' && 'packageManager' in message) {
resolve(message as { packageManager: { command: string; args: string[]; env: Record<string, string> } })
}
})
child.once('error', reject)
child.once('exit', (code) => { reject(new Error(`Host exited before booting: ${String(code)} ${stderr}`)) })
child.once('exit', (code) => { reject(new Error(`Host exited before ${phase}: ${String(code)} ${stderr}`)) })
})
if (phase === 'startup') {
expect(boot?.packageManager.command).toBe(process.execPath)
expect(boot?.packageManager.args).toEqual(['--expose-internals', pnpm])
expect(boot?.packageManager.env.ELECTRON_RUN_AS_NODE).toBe('1')
expect(boot?.packageManager.env.PATH).toBe(`${nodeBin}${delimiter}${process.env.PATH ?? ''}`)
}
if (event === 'disconnect') child.disconnect()
else await new Promise<void>((resolve, reject) => {
child.send(event === 'shutdown' ? { type: 'shutdown' } : { type: 'desktop-auth', secret: 'bad-secret' }, (error) => {
if (error === null) resolve()
else reject(error)
})
})
expect(boot.packageManager.command).toBe(process.execPath)
expect(boot.packageManager.args).toEqual(['--expose-internals', pnpm])
expect(boot.packageManager.env.ELECTRON_RUN_AS_NODE).toBe('1')
expect(boot.packageManager.env.PATH).toBe(`${nodeBin}${delimiter}${process.env.PATH ?? ''}`)
child.disconnect()
const exitCode = await exited
await drained
expect(child.signalCode).toBeNull()
expect(exitCode, stderr).toBe(fail ? 1 : 0)
expect(stderr).not.toContain('ERR_IPC_CHANNEL_CLOSED')
expect(stderr).not.toContain('Unhandled')
if (fail) expect(stderr).toContain('fixture boot failure')
else expect(readFileSync(join(root, 'stopped'), 'utf8')).toBe('stopped')
expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'ready' })]))
if (event === 'shutdown' && !fail) {
expect(messages.filter(message => typeof message === 'object' && message !== null && 'type' in message
&& message.type === 'shutdown-complete')).toHaveLength(1)
}
if (fail) {
expect(stderr).toContain(event === 'invalid-credential' ? 'Desktop authentication message is invalid' : 'fixture boot failure')
} else {
expect(stderr).toBe('')
expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'fatal' })]))
}
if (phase === 'credentials') {
expect(existsSync(join(root, 'profile-loaded'))).toBe(false)
expect(existsSync(join(root, 'stopped'))).toBe(false)
expect(messages).not.toEqual(expect.arrayContaining([expect.objectContaining({ type: 'booting' })]))
} else if (!fail) expect(readFileSync(join(root, 'stopped'), 'utf8')).toBe('stopped')
} finally {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
await Promise.all([exited, drained])
@@ -3,8 +3,7 @@
import { existsSync, mkdtempSync, realpathSync } from 'node:fs'
import { copyFile, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { Ajv2020 } from 'ajv/dist/2020.js'
import * as yaml from 'js-yaml'
import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import type { ConfigSchemaDump } from '@deepseek-ai/dsh-app-boot'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -162,7 +161,7 @@ describe.skipIf(!builtArtifactsExist)('dsh --dump-config-schema assembled output
const composed = await dump(fixture, [], '--dump-config')
const validator = new Ajv2020({ strict: false, validateFormats: false })
const validate = validator.compile(document)
expect(validate(yaml.load(composed.stdout, { schema: entryListSchema })), JSON.stringify(validate.errors)).toBe(true)
expect(validate(parseEntryYaml(composed.stdout)), JSON.stringify(validate.errors)).toBe(true)
expect(validate([{ name: `${packageName}/namespace`, config: { attempts: 'wrong' } }])).toBe(false)
const patch = validator.compile({ $schema: document.$schema, $defs: document.$defs, $ref: '#/$defs/patchList' })
expect(patch([{ id: 'schema-class', config: { enabled: 'wrong' } }])).toBe(false)
@@ -37,7 +37,7 @@
"boolean",
"null"
],
"description": "Allows patch indexing and insertion into an entry-list config; does not select the plugin implementation."
"description": "Allows patch indexing and insertion into an entry-list config, which a group: true entry requires; does not select the plugin implementation."
},
"disabled": {
"anyOf": [
@@ -249,6 +249,28 @@
{
"$ref": "#/$defs/entryMetadata"
},
{
"if": {
"properties": {
"group": {
"const": true
}
},
"required": [
"group"
]
},
"then": {
"properties": {
"config": {
"$ref": "#/$defs/entryList"
}
},
"required": [
"config"
]
}
},
{
"if": {
"properties": {
@@ -15,7 +15,7 @@ import { mkdtemp, readFile, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import yaml from 'js-yaml'
import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import { describe, expect, it } from 'vitest'
const repoRoot = fileURLToPath(new URL('../../../', import.meta.url))
@@ -37,12 +37,6 @@ interface PatchEntry extends ConfigRow {
insert?: ConfigRow[]
}
const jsExprType = new yaml.Type('tag:yaml.org,2002:js', {
kind: 'scalar',
construct: value => String(value),
})
const configSchema = yaml.JSON_SCHEMA.extend(jsExprType)
/** Boot the built Web CLI, wait for its settled URL, then dispose through SIGTERM. */
function runBuiltWeb(cwd: string): Promise<{ stdout: string; stderr: string; code: number }> {
return new Promise((resolveRun, rejectRun) => {
@@ -103,9 +97,9 @@ describe.skipIf(!requireBuiltArtifacts)('built CLI lazy-search startup', () => {
it('boots and disposes the shipped composition with full-text search off by default', async () => {
expect(existsSync(builtBin), `missing built CLI ${resolve(builtBin)}; run pnpm build`).toBe(true)
expect(existsSync(webDist), `missing Web dist ${resolve(webDist)}; run pnpm run build:web`).toBe(true)
const baseRows = (yaml.load(await readFile(baseConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[])
const baseRows = (parseEntryYaml(await readFile(baseConfigPath, 'utf8')) as PatchEntry[])
.flatMap(entry => entry.insert ?? [entry])
const webRows = (yaml.load(await readFile(webConfigPath, 'utf8'), { schema: configSchema }) as PatchEntry[])
const webRows = (parseEntryYaml(await readFile(webConfigPath, 'utf8')) as PatchEntry[])
.flatMap(entry => entry.insert ?? [entry])
const baseRow = baseRows.find(row => row.id === 'session-query-sqlite')
const webRow = webRows.find(row => row.id === 'session-query-sqlite')
@@ -95,7 +95,7 @@ describe.skipIf(!existsSync(join(root, 'apps/cli/lib/bin.js')))('Official option
const profile = app.loadProfileDirectory('bundle-test', directory, installAnchor)
const profileContext: ProfileContext = {
name: 'web', dir: directory, patchPath: profile.patchPath, installAnchor, cwd: workspace, home,
startedBundles: profile.layers.map(layer => layer.packageName), overlays: [], telemetryDisabledEnv: '1',
startedBundles: profile.layers.map(layer => layer.packageName), overlayPaths: [], telemetryDisabledEnv: '1',
}
const resolution = await app.createRuntimeResolution({ installAnchor, home, profile })
const listeners = new Set<() => void>()
@@ -0,0 +1,109 @@
/** The shipped cua-mcp bundle: the real CLI loads a profile that selects only this bundle and serves Computer Use programs over stdio. */
import { execFile } from 'node:child_process'
import { existsSync } from 'node:fs'
import { mkdir, mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { describe, expect, it, onTestFinished } from 'vitest'
import { clearAmbientProxyEnv } from '../../../../../scripts/test-proxy-environment.ts'
import { startProbe, type McpProbe } from './probe.ts'
const root = fileURLToPath(new URL('../../../../../', import.meta.url))
const bin = join(root, 'apps/cli/lib/bin.js')
const fixturePatch = fileURLToPath(new URL('./fixture.patch.yml', import.meta.url))
const execFileAsync = promisify(execFile)
interface CallResult {
content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>
isError?: boolean
}
function textOf(block: CallResult['content'][number] | undefined): string {
if (block?.type !== 'text') throw new Error(`expected a text block, got ${JSON.stringify(block)}`)
return block.text
}
describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => {
it('serves programs over stdio from a profile that selects only this bundle, and exits on EOF', async () => {
const temporary = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-profile-'))
const home = join(temporary, 'home')
// The directory the client launches the server from; programs must not start there.
const launch = join(temporary, 'launch')
const owned: { probe?: McpProbe } = {}
onTestFinished(async () => {
try { await owned.probe?.terminate() } finally { await rm(temporary, { recursive: true, force: true }) }
})
const env: NodeJS.ProcessEnv = {
...process.env, DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1', DSH_PERMISSION_MODE: 'danger-full-access', DSH_CUA_CONSENT: 'allow',
}
clearAmbientProxyEnv(env)
// The default workspace is under test, whatever the developer's shell exports.
delete env.DSH_CUA_WORKSPACE
await execFileAsync(process.execPath, ['-e', 'require("node:fs").mkdirSync(process.argv[1], { recursive: true })', launch])
// The profile manifest the README documents: the installation's shipped bundle as the only layer, no pnpm step.
const profileDir = join(home, 'profiles', 'cua-mcp')
await mkdir(profileDir, { recursive: true })
await writeFile(join(profileDir, 'package.json'), `${JSON.stringify({
name: 'dsh-profile-cua-mcp', private: true, dependencies: {}, dsh: { profile: { bundles: ['@deepseek-ai/dsh-cua-mcp'] } },
}, null, 2)}\n`)
const probe = owned.probe = startProbe({ args: [bin, '--profile', 'cua-mcp', '--patch', fixturePatch], cwd: launch, env })
const initialized = await probe.request('initialize', {
protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'cua-mcp-e2e', version: '1' },
}) as { serverInfo: { name: string; version: string }; instructions: string; capabilities: object }
probe.notify('notifications/initialized')
expect(initialized.serverInfo.name).toBe('dsh_cua')
expect(initialized.capabilities).toMatchObject({ tools: { listChanged: false } })
await expect(`${initialized.instructions}\n`).toMatchFileSnapshot('./expected/instructions.txt')
const listed = await probe.request('tools/list') as { tools: { name: string }[] }
await expect(`${JSON.stringify(listed.tools, null, 2)}\n`).toMatchFileSnapshot('./expected/tools.json')
const reference = await probe.request('tools/call', { name: 'cua_get_api_reference', arguments: {} }) as CallResult
expect(reference.isError).toBeUndefined()
expect(reference.content).toHaveLength(1)
await expect(`${textOf(reference.content[0])}\n`).toMatchFileSnapshot('./expected/reference.md')
const first = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
code: 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); '
+ 'await win.getAccessibilityTree(); await win.click("0"); '
+ 'inspect(JSON.stringify({ visits, window: win.windowId, pid: process.pid, cwd: process.cwd() }), await win.getScreenshot())',
description: 'Open the fixture window',
} }) as CallResult
expect(first.isError).toBeUndefined()
expect(first.content.map(block => block.type)).toEqual(['text', 'image'])
const state = JSON.parse(textOf(first.content[0])) as { visits: number; window: string; pid: number; cwd: string }
expect(state).toMatchObject({ visits: 1, window: '7' })
// Without DSH_CUA_WORKSPACE the profile creates its workspace inside the Harness home and starts programs there.
// Both spellings are resolved: the temporary directory is a symlink on macOS and an 8.3 short name on Windows.
const programDirectory = await realpath(state.cwd)
expect(programDirectory).toBe(await realpath(join(home, 'cua-mcp', 'workspace')))
expect(programDirectory).not.toBe(await realpath(launch))
const image = first.content[1]
if (image?.type !== 'image') throw new Error('expected an image block')
expect(image.mimeType).toMatch(/^image\//)
expect(Buffer.from(image.data, 'base64').length).toBeGreaterThan(0)
const second = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
code: 'globalThis.visits++; inspect(JSON.stringify({ visits, sameWindow: win.windowId === "7", pid: process.pid }))', description: 'Count another visit',
} }) as CallResult
expect(second.content).toHaveLength(1)
expect(JSON.parse(textOf(second.content[0]))).toEqual({ visits: 2, sameWindow: true, pid: state.pid })
const reset = await probe.request('tools/call', { name: 'cua_reset', arguments: {} }) as CallResult
expect(reset.isError).toBeUndefined()
expect(textOf(reset.content[0])).toContain('Program environment cleared')
const third = await probe.request('tools/call', { name: 'cua_run_code', arguments: {
code: 'inspect(JSON.stringify({ visits: globalThis.visits ?? null, hasWindow: typeof win !== "undefined", pid: process.pid }))', description: 'Inspect the fresh environment',
} }) as CallResult
expect(third.content).toHaveLength(1)
const afterReset = JSON.parse(textOf(third.content[0])) as { visits: null; hasWindow: boolean; pid: number }
expect(afterReset).toMatchObject({ visits: null, hasWindow: false })
expect(afterReset.pid).not.toBe(state.pid)
expect(await probe.close()).toEqual({ code: 0, signal: null })
expect(probe.stderr()).not.toContain('MCP startup failed')
expect(() => process.kill(afterReset.pid, 0)).toThrow()
})
})
@@ -0,0 +1 @@
DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state.
@@ -0,0 +1,61 @@
## cua API reference
Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation.
Call inspect(...values) to display selected observation results.
Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: string and the methods listed below for window level. Window IDs are opaque provider-issued strings; preserve them verbatim.
Supported modifier names depend on the platform and the operation; see the platform guidance.
Setup and discovery:
- cua.getCapabilities() -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions.
- cua.listApps() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app.
- app.getWindows() -> { windowId: string, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership.
- app.getWindow(windowId: string) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them.
- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required.
- app.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
## Accessibility tree
Available at app or window level depending on the platform.
Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing.
- getAccessibilityTree(options?: { includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names.
- listActions(elementId: string) -> string[] — list the actions an element advertises.
- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none.
- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument.
- setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value.
- selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate.
## Screenshots
Use an explicit window for screenshots.
- getScreenshot() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId.
## Simulated mouse
Use an explicit window for pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot.
- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration.
- toggleMouse(mouseButton: 'left' | 'right' | 'middle', direction: 'down' | 'up') -> ActionResult — press or release the specified mouse button at the current pointer position without moving it. No coordinates are accepted. Release held buttons explicitly with 'up'; the opposite event is not sent automatically.
- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: Modifier[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press.
- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left.
- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: Modifier[], relative?: boolean }) -> ActionResult — drag between two points of one window.
A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry.
## Simulated keyboard
Available at app or window level depending on the platform.
- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab.
- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry.
- pressKey(key: string, modifiers?: Modifier[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string.
- sendKeyEvent(key: string, direction: 'down' | 'up') -> ActionResult — send one key-down or key-up event; key accepts a single key name, including a modifier.
click, drag, and pressKey are convenience operations; sendKeyEvent, mouseMove, and toggleMouse are primitive operations. For complex action combinations, decompose convenience operations into sequences of primitive operations supported by the current platform.
Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name.
AX read defaults: maxElements=2000, maxDepth=25.
Maximum click holdMs: 5000 ms.
@@ -0,0 +1,64 @@
[
{
"name": "cua_get_api_reference",
"title": "Computer use API reference",
"description": "Return the complete `cua` API reference that every cua_run_code program must follow: methods, signatures, and operating rules. Call it before the first cua_run_code program of a conversation, and again whenever the reference is no longer in your context or a program fails on an unknown `cua` method. It only reads: nothing on the desktop or in the program environment changes.",
"inputSchema": {
"type": "object",
"properties": {}
},
"annotations": {
"readOnlyHint": true,
"destructiveHint": false,
"idempotentHint": true,
"openWorldHint": false
}
},
{
"name": "cua_run_code",
"title": "Computer use program",
"description": "Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Use inspect(...values) to display selected text and images. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Use inspect(...values) to display output. Do not use console. Use the raw form of a template literal only for short text whose backslashes must stay exactly as written, such as a regular expression; write other text, in particular file contents and commands, as ordinary strings. Write file contents as an array of quoted strings, one line each, joined with newlines; never as one template literal. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call runs one program in its own top-level scope. Its top-level let, const, var, class, and function declarations, and the names it received from earlier programs, are copied into the top-level scope of later programs: later programs receive copies of these variables, not references to them, so an object they hold is still shared. In one program, either use a copied name or declare it again; do not declare a name and also use its copied value. Assigning to a copied name, even one declared with const, changes only this program's copy, which later programs receive. Do not declare var inside blocks; a block-level var changes which value later programs copy. Functions and still-running code from earlier programs keep the values they captured, and assignments they make later are not copied; keep shared mutable state in objects. If a program fails before a declaration of an existing name finishes, later programs keep that name's earlier value. Use await import(...) for modules; require and module are unavailable. Relative import specifiers resolve from the working directory of this environment's first program, while process.cwd() and relative file paths follow each program's working directory. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Await tools and cleanup before the program ends; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before the program ends; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically.",
"inputSchema": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The TypeScript program to execute, following this tool's execution instructions."
},
"description": {
"type": "string",
"description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"."
},
"timeoutMs": {
"type": "number",
"description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline."
}
},
"required": [
"code",
"description"
]
},
"annotations": {
"readOnlyHint": false,
"destructiveHint": true,
"idempotentHint": false,
"openWorldHint": true
}
},
{
"name": "cua_reset",
"title": "Reset computer use program state",
"description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. A running cua_run_code program is cancelled. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment. Use it when the environment has become unusable or its retained state must not carry into the next task.",
"inputSchema": {
"type": "object",
"properties": {}
},
"annotations": {
"readOnlyHint": false,
"destructiveHint": false,
"idempotentHint": true,
"openWorldHint": false
}
}
]
@@ -0,0 +1,18 @@
# Replace both native providers with the recorded desktop fixture so the profile serves on every Host.
- id: cua-mcp-provider
disabled: true
- id: cua-mcp-provider-windows
disabled: true
- insert:
- id: cua-mcp-fixture-provider
name: '../../../../../snapshots/session/cua-run-code/provider.mjs'
config:
screenshotTarget:
longEdge: 1
maxBytes: 100000
allowedApps:
- id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
name: Fixture
executablePath: /fixture/app
+102
View File
@@ -0,0 +1,102 @@
/** Raw JSON-RPC probe over the profile's stdio: every stdout line must be a protocol frame. */
import { spawn } from 'node:child_process'
import { createInterface } from 'node:readline'
/** One observed child exit; a graceful EOF exit carries code zero and no signal. */
export interface ProbeExit {
readonly code: number | null
readonly signal: NodeJS.Signals | null
}
/** Test-side requests and explicit process ownership. */
export interface McpProbe {
/**
* @param method - JSON-RPC method.
* @param params - JSON params.
* @returns The matching result; a protocol error or a non-protocol stdout line rejects pending and later requests.
*/
request(method: string, params?: object): Promise<unknown>
/** @param method - Notification method. @param params - JSON params. */
notify(method: string, params?: object): void
/** @returns Captured stderr, which the protocol never uses. */
stderr(): string
/** @returns The exit observed after stdin EOF. */
close(): Promise<ProbeExit>
/** Stop a failed fixture and await its exit. */
terminate(): Promise<void>
}
/**
* Start the built CLI with the given arguments and hold its stdio.
* @param options - Executable arguments, working directory, and environment.
* @returns The probe; `terminate` must run even after a failed assertion.
*/
export function startProbe(options: { readonly args: readonly string[]; readonly cwd: string; readonly env: NodeJS.ProcessEnv }): McpProbe {
const child = spawn(process.execPath, [...options.args], { cwd: options.cwd, env: options.env, stdio: 'pipe' })
let stderr = ''
child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') })
let nextId = 0
let ended = false
let failure: Error | undefined
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>()
const fail = (error: Error): void => {
failure ??= error
for (const request of pending.values()) request.reject(error)
pending.clear()
}
child.on('error', fail)
child.stdin.on('error', fail)
const closed = new Promise<ProbeExit>((resolve) => {
child.once('close', (code, signal) => {
ended = true
fail(new Error(`cua-mcp exited before replying (${String(code)}, ${String(signal)}): ${stderr}`))
resolve({ code, signal })
})
})
const reading = (async () => {
for await (const line of createInterface({ input: child.stdout })) {
let parsed: unknown
try { parsed = JSON.parse(line) } catch { parsed = undefined }
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) || Reflect.get(parsed, 'jsonrpc') !== '2.0') {
throw new Error(`cua-mcp wrote a non-protocol line to stdout: ${line}`)
}
const frame = parsed as { id?: number; method?: string; result?: unknown; error?: unknown }
if (frame.id === undefined) continue
const request = pending.get(frame.id)
if (request === undefined) throw new Error(`cua-mcp replied to an unknown request ${String(frame.id)}`)
pending.delete(frame.id)
if (frame.error === undefined) request.resolve(frame.result)
else request.reject(new Error(`MCP request failed: ${JSON.stringify(frame.error)}`))
}
})().catch((error: unknown) => { fail(error instanceof Error ? error : new Error(String(error))) })
const write = (message: object): void => { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`) }
return {
async request(method, params) {
if (failure !== undefined) throw failure
if (ended) throw new Error('cua-mcp is closed')
const id = ++nextId
const response = Promise.withResolvers<unknown>()
const timer = setTimeout(() => {
pending.delete(id)
response.reject(new Error(`MCP ${method} did not reply: ${stderr}`))
}, 90_000)
pending.set(id, { resolve: response.resolve, reject: response.reject })
write({ id, method, ...params === undefined ? {} : { params } })
try { return await response.promise } finally { clearTimeout(timer) }
},
notify(method, params) { write({ method, ...params === undefined ? {} : { params } }) },
stderr: () => stderr,
async close() {
child.stdin.end()
const exit = await closed
await reading
if (failure !== undefined && !failure.message.startsWith('cua-mcp exited before replying')) throw failure
return exit
},
async terminate() {
if (!ended) child.kill('SIGKILL')
await closed
await reading
},
}
}
@@ -9,7 +9,7 @@
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"request/context","seq":11,"time":0,"data":{"provider":"deepseek-official","model":"deepseek-v4-flash","contextWindow":1000000}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title","seq":12,"time":0,"data":{"title":"say pong","messageSeqs":[8],"source":{"kind":"fallback"}}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"session/title-llm-request","seq":13,"time":0,"data":{"titleProvider":"session-title-first-prompt-llm","messageSeqs":[8],"route":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"system":"Create a concise title for an AI coding-assistant session from the supplied human messages.\nReturn only the title on one line, **in plain text of natural language**, with no quotes, prefix, explanation, Markdown, XML, or terminal control codes. No code is allowed.\nUse the language of the messages.\nAim for about 5 words in non-CJK languages or 10 CJK characters.\nIf the messages give little to name, still return a short best-effort title, such as Greeting, instead of explaining.","messages":[{"content":[{"type":"text","text":"Generate the session title from this JSON array of human messages:\n[{\"seq\":8,\"text\":\"say pong\"}]"}],"source":{"kind":"dsh-session-title-llm"},"role":"user","id":"{{sessionId}}"}],"maxTokens":4096,"reasoningEffort":"off"}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"assistant/attempt","seq":14,"time":0,"data":{"turn":1,"step":1,"stream":[{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"error","failure":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}]}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"step/end","seq":15,"time":0,"data":{"turn":1,"step":1}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}}
{"type":"session_event","sessionId":"{{sessionId}}","event":{"type":"turn/end","seq":16,"time":0,"data":{"turn":1,"reason":{"kind":"error","error":{"message":"llm-deepseek-keyless: the API key resolved from DEEPSEEK_API_KEY contains characters no HTTP header can carry; set DEEPSEEK_API_KEY to the raw key alone (the web Models page writes it)","code":"INVALID_CREDENTIAL"}}}}}
{"type":"result","sessionId":"{{sessionId}}","output":""}
@@ -8,7 +8,7 @@
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Use the write tool exactly once with file_path set to exactly the relative path inherited.txt and content escaped. If the write is denied, reply with the single word CHILD_DENIED and the denial marker line; do not retry and do not request escalation. If it succeeds, reply CHILD_WROTE."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: read-only. Any available operation enforced by the DSH file sandbox cannot modify files in the standing mode. Do not refuse a required modification from this policy alone: try an available tool normally and follow any denial and escalation guidance it returns."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash","reasoningEffort":"low"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Use the write tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}}
@@ -8,7 +8,7 @@
{"type":"step/start","data":{"turn":1,"step":1}}
{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{sessionId}}"}},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Reply with exactly CHILD_RESULT and nothing else. Do not call send_message."},{"type":"text","text":"Your final answer is delivered automatically if your parent is still online. Include the result and relevant evidence in that answer; the parent does not receive your full transcript, tool output, or reasoning. If your last action is a message to your parent, the completion notice omits your final answer; include the result and relevant evidence in that message."}],"source":{"kind":"user"},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"<system-reminder>\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`).\n\nYou are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names.\n\nDelegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly.\n\nDelegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly.\n\nYou are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it.\n</system-reminder>"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are disabled in this session: actions that require approval are rejected automatically — do not request sandbox escalation (do not set `sandbox_permissions`)."},{"name":"subagent:identity","text":"You are a subagent delegated by agent \"lead\".\nYour name is \"agent-1\".\nThe root agent of your collaboration tree is \"lead\".\n\nTo message other agents, use send_message({ agent: \"<agent-name>\", message: \"...\" }).\nWhen you finish, use send_message to send a self-contained result to the agent that delegated you. Message any agent as soon as a finding changes what it should do next; sending a message does not end your turn.\nUse list_agents({}) to find your collaborator agents and their names."},{"name":"tool:subagent:depth","text":"Delegation depth for `subagent`: current 1, maximum 1, remaining levels 0. Do not call `subagent` at this depth; carry out the work directly."},{"name":"tool:subagent_fork:depth","text":"Delegation depth for `subagent_fork`: current 1, maximum 1, remaining levels 0. Do not call `subagent_fork` at this depth; carry out the work directly."},{"name":"subagent:delegation","text":"You are a delegated subagent: your permission scope was fixed when you were started and cannot be widened from inside this session — operations that require approval are rejected automatically. When the task needs access beyond that scope, do not retry the denied operation; state the limitation in your reply so the delegating agent can handle it."}]},"role":"user","id":"{{sessionId}}"},"surfaceOp":"append"}
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":"{{tools}}"},"reason":"initial"}}
{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-flash"}}
{"type":"session/title","data":{"title":"Reply with exactly CHILD_RESULT and","messageSeqs":[8],"source":{"kind":"fallback"}}}
@@ -3,7 +3,7 @@
* @module subagent-settlement-fence
*/
import type { Context } from '@deepseek-ai/cordis'
import { Context } from '@deepseek-ai/cordis'
import type {} from '@deepseek-ai/dsh-agent-loop'
import type {} from '@deepseek-ai/dsh-subagent'
@@ -24,12 +24,12 @@ export function apply(ctx: Context): void {
let hasDelivered = false
ctx.effect(() => {
const disposeInbox = ctx.root.on('agent/inbox/inserted', ({ agent, message }) => {
const disposeInbox = ctx[Context.root].on('agent/inbox/inserted', ({ agent, message }) => {
if (agent.session.header.parentSession !== undefined || message.source.kind !== 'subagent-settled') return
hasDelivered = true
delivered.resolve(undefined)
})
const disposeStep = ctx.root.on('agent/pre-step', async ({ agent, turn, step }, next) => {
const disposeStep = ctx[Context.root].on('agent/pre-step', async ({ agent, turn, step }, next) => {
if (agent.session.header.parentSession === undefined && turn === 1 && step === 2 && !hasDelivered) {
await delivered.promise
}
@@ -1,5 +1,5 @@
import { executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { executeToolFixture, executeModelToolFixture } from '@deepseek-ai/dsh-tool-testkit'
import { mkdtemp, mkdir, readFile, realpath, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'
@@ -152,6 +152,50 @@ async function backgroundPtcModeHarness(cwd: string): Promise<Context> {
}
describe('PTC mode typed values: keyless real-process contracts', () => {
it('returns formatted read content from inspect through the real outer run_code result', async () => {
workdir = await realpath(await mkdtemp(join(tmpdir(), 'dsh-ptc-inspect-read-')))
const path = join(workdir, 'a.txt')
await writeFile(path, 'alpha\nbeta\n')
ctx = await typedPtcModeHarness()
await ctx.plugin(ToolFs)
const formatted = `<path>${path}</path>\n<type>file</type>\n<content>\n1: alpha\n2: beta\n\n(End of file - total 2 lines)\n</content>`
const native = await executeToolFixture(ctx, {
callId: brandString<ToolCallId>('inspect-read-reference'), name: 'read',
arguments: { file_path: path }, signal: testToolSignal,
})
expect(native.isError).toBe(false)
expect(native.content).toEqual([{ type: 'text', text: formatted }])
const result = await runCode(ctx, `inspect(await tools.read({ file_path: ${JSON.stringify(path)} }));`)
expect(result.isError).toBe(false)
expect(result.content).toEqual([{ type: 'text', text: formatted + '\n' }])
expect(result.value).toEqual({
logs: [formatted + '\n'], sandbox: { mode: 'danger-full-access', denied: false },
})
})
it.each(['renderer', 'policy'])('keeps an empty %s output silent while preserving program data', async (source) => {
ctx = await typedPtcModeHarness()
ctx.tools.register(defineTool({
name: 'silent_result', description: 'Return data without display text.', parameters: {},
output: {
schema: { type: 'object', properties: { answer: { type: 'number', required: true } }, additionalProperties: false },
render: () => source === 'renderer' ? [] : [{ type: 'text', text: 'original rendering' }],
},
execute: async () => ({ answer: 42 }),
...source === 'policy' ? { finalizeContent: () => [] } : {},
}))
const result = await runCode(ctx, `
const value = await tools.silent_result({});
if (value.answer !== 42) throw new Error('program data changed');
inspect(value);
`)
expect(result.isError).toBe(false)
expect(result.content).toEqual([{ type: 'text', text: '(run_code completed with no output)' }])
expect(result.value).toEqual({ logs: [], sandbox: { mode: 'danger-full-access', denied: false } })
})
it('crosses a large intermediate value intact and exposes only typed tool failure fields', async () => {
ctx = await typedPtcModeHarness()
ctx.tools.register(defineTool({
@@ -305,15 +349,15 @@ describe('PTC mode typed values: keyless real-process contracts', () => {
} as Agent
const value = completion(await runCode(ctx, `
const listed = await tools.cordis_inspect_list({});
const listed = await tools.cordis_inspect({});
const provider = listed.providers.find(item => item.id === 'Tool');
const inspected = await tools.cordis_inspect_query({
const inspected = await tools.cordis_inspect({ query: {
platform: provider.platform, provider: provider.id, method: provider.methods[0].name,
});
} });
inspect(JSON.stringify({ provider: provider.id, names: inspected.data.tools.map(tool => tool.name) }));
`, testToolSignal, agent))
expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect_list', 'cordis_inspect_query'] })
expect(value).toEqual({ provider: 'Tool', names: ['cordis_inspect'] })
})
})
@@ -5,8 +5,8 @@ import { join } from 'node:path'
import { createInterface } from 'node:readline'
import { fileURLToPath } from 'node:url'
import { execa } from 'execa'
import yaml from 'js-yaml'
import { expect, it, onTestFinished } from 'vitest'
import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import type { BundleInfo, ChangeResult } from '@deepseek-ai/dsh-plugin-manager'
import { getDshRuntimeVersion } from '../../../../packages/boot/app-boot/src/plugin-compatibility.ts'
import { generateOfficialBundleCatalog } from '../../../../scripts/gen-official-bundle-catalog.ts'
@@ -118,7 +118,7 @@ it.skipIf(!built)('installs the exported registry\'s local closure and switches
const observer = join(temporary, 'official-installer-observer.mjs')
await writeFile(observer, await readFile(new URL('./fixtures/official-installer-observer.mjs', import.meta.url), 'utf8'))
const patch = join(temporary, 'official-installer.patch.yml')
await writeFile(patch, yaml.dump([{ insert: [{ id: 'official-installer-observer', name: observer,
await writeFile(patch, stringifyEntryYaml([{ insert: [{ id: 'official-installer-observer', name: observer,
config: {
registry: registry.url,
profile,
@@ -2,7 +2,7 @@
* Keyless comparison of actual SDK and Desktop/Web step-admitted tool sets.
* Keep intentional differences in tool-parity.ts; unused exceptions fail.
* Team mode is excluded while its known composition mismatch is tracked in #7172.
* SDK minimal, Creator-only tools, graphical context and optional runtime payloads
* SDK minimal, other presets, graphical context and optional runtime payloads
* are outside this fixed standard/PTC, top-level-session comparison.
*/
import { createServer } from 'node:http'
+6 -2
View File
@@ -9,8 +9,12 @@ interface Exception {
/** Intentional product differences; obsolete entries fail alongside undeclared differences. */
export const toolParityExceptions: Record<ToolMode, readonly Exception[]> = {
standard: [{ tool: 'list_subagent_models', side: 'desktop',
reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' }],
standard: [
{ tool: 'list_subagent_models', side: 'desktop',
reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' },
{ tool: 'cordis_inspect', side: 'desktop',
reason: 'Web exposes inspection of its Host and connected Client runtime; the SDK profile does not compose the Cordis inspection providers.' },
],
ptc: [
{ tool: 'list_subagent_models', side: 'desktop',
reason: 'Desktop enables subagent model discovery; SDK delegation inherits the caller model by default.' },
@@ -64,13 +64,15 @@ function fixture() {
// A recovery URL is a readiness signal; sibling HMR work must settle first.
' void scope.get("loader").await().then(() => {',
' if (disposed || !scope.get("webServer") || !scope.get("connection")) return',
' writeFileSync(config.url, scope.connection.authenticatedUrl(`http://127.0.0.1:${scope.webServer.port}`))',
' writeFileSync(config.url, `http://127.0.0.1:${scope.webServer.port}`)',
' })',
' })',
'}',
'',
].join('\n'))
const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: { path: diagnostics, url: serverUrl, states } }
const observer = { id: 'matrix-log-observer', name: pathToFileURL(observerPath).href, config: {
path: diagnostics, url: serverUrl, states,
} }
const plugin = join(root, 'probe.mjs')
writeFileSync(plugin, [
"import { appendFileSync, existsSync } from 'node:fs'",
@@ -134,8 +136,11 @@ function start(f: ReturnType<typeof fixture>, extra: string[] = [], nodeArgs: st
}
async function serves(currentServer = false) {
await wait(() => /dsh web: http:\/\//u.test(stdout))
const url = currentServer ? readFileSync(f.serverUrl, 'utf8') : /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1]
if (!url) throw new Error('Missing Web URL')
const publishedUrl = /dsh web: (http:\/\/[^\s]+)/u.exec(stdout)?.[1]
if (!publishedUrl) throw new Error('Missing Web URL')
const url = new URL(currentServer ? readFileSync(f.serverUrl, 'utf8') : publishedUrl)
// The real token plugin publishes once per process; HMR can replace the listener.
url.search = new URL(publishedUrl).search
const auth = await fetch(url, { redirect: 'manual', signal: AbortSignal.timeout(10_000) })
const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0]
if (!cookie) throw new Error('Missing Web authentication cookie')
@@ -7,6 +7,7 @@ import { fileURLToPath } from 'node:url'
import { execa } from 'execa'
import yaml from 'js-yaml'
import { expect, it } from 'vitest'
import { stringifyEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import { assertInstalledTree, createPackedInstallation } from './packed-installation.ts'
const root = fileURLToPath(new URL('../../../..', import.meta.url))
@@ -64,7 +65,7 @@ export function apply(ctx) {
}
`)
const patch = join(temporary, 'test.patch.yml')
await writeFile(patch, yaml.dump([
await writeFile(patch, stringifyEntryYaml([
{ id: 'session-telemetry-otel', disabled: true },
{ id: 'github-webhook-ingress', insert: [{ id: 'observe-packed-ingress', name: observer }] },
]))
+5 -3
View File
@@ -2,7 +2,7 @@
import { lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { join, relative } from 'node:path'
import { Context } from '@deepseek-ai/cordis'
import { createLaunchEnvironmentSnapshot } from '@deepseek-ai/dsh-launch-environment'
import {
@@ -139,7 +139,7 @@ describe('runProfile with an application-owned profile', () => {
try {
const { shutdown } = await runProfile({
environment, profile: 'desktop', resolvedProfile: runtime,
patchFiles: [overlay], args: ['--port', '0', '--no-open'],
patchFiles: [relative(process.cwd(), overlay)], args: ['--port', '0', '--no-open'],
})
expect(installProxyFromEnvironment).toHaveBeenCalledWith(environment, expect.any(Function))
const resolution = vi.mocked(createRuntimeResolution).mock.settledResults
@@ -165,7 +165,9 @@ describe('runProfile with an application-owned profile', () => {
])
expect(rows.find(row => row.id === 'target')?.config).toEqual({ overlay: true, priority: 'overlay' })
expect(rows.find(row => row.id === 'session-telemetry-otel')?.disabled).toBe(true)
expect(ctx.profileContext).toMatchObject({ dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor })
expect(ctx.profileContext).toMatchObject({
dir: home, patchPath: profilePatch, installAnchor: runtime.installAnchor, overlayPaths: [overlay],
})
await shutdown.shutdown(0)
expect(dispose).toHaveBeenCalledOnce()
expect(disposeProxy).toHaveBeenCalledOnce()
+25 -14
View File
@@ -221,7 +221,7 @@ async function bootWeb(
bootCtx.provide('profileContext', { name: surface, dir: profileDir, patchPath: profile.patchPath,
installAnchor: INSTALL_ANCHOR, home, cwd: home,
startedBundles: profileBundles ?? ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-web-app'],
overlays: [], telemetryDisabledEnv: '1' })
overlayPaths: [], telemetryDisabledEnv: '1' })
await bootCtx.plugin(PluginPackages, { resolution })
bootCtx.provide('connection', {
fetch: { register: () => () => {} },
@@ -351,7 +351,7 @@ describe('the shipped Web composition', () => {
// excluded for the reason the TUI composition e2e excludes them — they
// depend on ripgrep being present on the machine.
expect(toolNames(ctx, handle.agent).filter(name => name !== 'glob' && name !== 'grep')).toEqual([
'ask_user_question', 'bash', 'create_goal', 'edit', 'exit_plan_mode',
'ask_user_question', 'bash', 'cordis_inspect', 'create_goal', 'edit', 'exit_plan_mode',
'get_goal', 'job_kill', 'job_list', 'job_output', 'list_agents', 'list_subagent_models', 'office_convert', 'office_recalculate', 'office_render', 'plugin_manager', 'present', 'read', 'read_image',
'schedule_create', 'schedule_edit', 'schedule_list', 'schedule_view',
'send_message', 'skill',
@@ -359,6 +359,18 @@ describe('the shipped Web composition', () => {
'workflow', 'working_directory', 'write',
])
expect(ctx.commands.find(handle.agent, 'goal')).toBeDefined()
for (const query of [undefined, { platform: 'host', provider: 'Config', method: 'listConfigs', input: { name: '@deepseek-ai/dsh-agent-loop' } }] as const) {
const inspected = await executeToolFixture(ctx, {
agent: handle.agent, callId: brandString<ToolCallId>(`standard-inspect-${query === undefined ? 'list' : 'query'}`), name: 'cordis_inspect',
arguments: query === undefined ? {} : { query }, signal: new AbortController().signal,
})
expect(inspected.isError).toBe(false)
const text = inspected.content.flatMap(block => block.type === 'text' ? [block.text] : []).join('')
const value: unknown = JSON.parse(text)
const path = query === undefined ? 'providers' : 'data.entries'
const entry = query === undefined ? { platform: 'host', id: 'Config' } : { name: '@deepseek-ai/dsh-agent-loop' }
expect(value).toHaveProperty(path, expect.arrayContaining([expect.objectContaining(entry)]))
}
} finally {
await handle.dispose()
}
@@ -603,7 +615,7 @@ describe('the shipped Web composition', () => {
try {
const tools = toolNames(ctx, handle.agent)
expect(tools).toEqual(expect.arrayContaining([
'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager',
'cordis_inspect', 'plugin_manager',
]))
for (const removed of ['cordis_define', 'cordis_run', 'cordis_stop', 'cordis_undefine', 'cordis_inspect_self']) {
expect(tools).not.toContain(removed)
@@ -985,8 +997,7 @@ describe('the standard preset documentation skill', () => {
expect((await testCtx.skills.get('dsh-doc', { cwd: root, scope: creator.agent }))?.path).toBe(definition.path)
const schemas = testCtx.tools.schemas(standardAgent.agent)
expect(schemas).toEqual(testCtx.tools.schemas(baseline.agent))
expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_list')
expect(schemas.map(tool => tool.name)).not.toContain('cordis_inspect_query')
expect(schemas.map(tool => tool.name)).toContain('cordis_inspect')
for (const handle of [baseline, standardAgent]) {
handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'Reply ready.' }], source: { kind: 'user' } }))
await handle.agent.whenIdle()
@@ -1116,13 +1127,13 @@ describe('a user preset declared from the shipped cordis rows', () => {
try {
for (const handle of [shipped, copied]) {
expect(toolNames(copyCtx, handle.agent)).toEqual(expect.arrayContaining([
'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager',
'cordis_inspect', 'plugin_manager',
]))
}
const signal = new AbortController().signal
const listed = await executeToolFixture(copyCtx, {
callId: brandString<ToolCallId>('copied-preset-inspect-list'),
name: 'cordis_inspect_list',
name: 'cordis_inspect',
arguments: {},
signal,
agent: copied.agent,
@@ -1139,15 +1150,15 @@ describe('a user preset declared from the shipped cordis rows', () => {
onTestFinished(() => { spills.mockRestore() })
const queried = await executeToolFixture(copyCtx, {
callId: brandString<ToolCallId>('copied-preset-inspect-tools'),
name: 'cordis_inspect_query',
arguments: { platform: 'host', provider: 'Tool', method: 'listTools' },
name: 'cordis_inspect',
arguments: { query: { platform: 'host', provider: 'Tool', method: 'listTools' } },
signal,
agent: copied.agent,
})
expect(queried.isError).toBe(false)
// The tool catalog may exceed the inline budget; assert its complete stored text.
const queriedText = spills.mock.calls.at(-1)?.[0].content ?? resultText(queried)
for (const toolName of ['bash', 'cordis_inspect_list', 'cordis_inspect_query', 'plugin_manager']) {
for (const toolName of ['bash', 'cordis_inspect', 'plugin_manager']) {
expect(queriedText).toContain(`"name": "${toolName}"`)
}
@@ -1158,8 +1169,8 @@ describe('a user preset declared from the shipped cordis rows', () => {
const listConfigs = async (input: Record<string, string | number>, callId: string): Promise<ConfigPage['data']> => {
const page = await executeToolFixture(copyCtx, {
callId: brandString<ToolCallId>(callId),
name: 'cordis_inspect_query',
arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input },
name: 'cordis_inspect',
arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input } },
signal,
agent: copied.agent,
})
@@ -1177,8 +1188,8 @@ describe('a user preset declared from the shipped cordis rows', () => {
expect(firstPage.nextOffset).toBe(5)
const projected = await executeToolFixture(copyCtx, {
callId: brandString<ToolCallId>('copied-preset-inspect-config'),
name: 'cordis_inspect_query',
arguments: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } },
name: 'cordis_inspect',
arguments: { query: { platform: 'host', provider: 'Config', method: 'listConfigs', input: { entry: toolsRow!.id } } },
signal,
agent: copied.agent,
})
+2 -3
View File
@@ -15,8 +15,7 @@ import { mkdtempSync, rmSync, readFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import yaml from 'js-yaml'
import { entryListSchema } from '@deepseek-ai/cordis-plugin-include'
import { parseEntryYaml } from '@deepseek-ai/cordis-plugin-include'
import { evaluate } from '@deepseek-ai/cordis-plugin-loader'
import { bundlePatchPaths, composeEntries, initProfile, loadProfile, PROFILES_DIR } from '@deepseek-ai/dsh-app-boot'
@@ -104,7 +103,7 @@ describe('shipped agent presets gate both shell tools by platform', () => {
const webBundle = fileURLToPath(new URL('../../../packages/bundle/web-app/', import.meta.url))
const webManifest = JSON.parse(readFileSync(join(webBundle, 'package.json'), 'utf8')) as { dsh: { bundle: { patch: string[] } } }
const presetRows = composeEntries([bundlePatchPaths(webBundle, webManifest.dsh.bundle).flatMap(file =>
yaml.load(readFileSync(file, 'utf8'), { schema: entryListSchema }) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])])
parseEntryYaml(readFileSync(file, 'utf8')) as import('@deepseek-ai/cordis-plugin-include').PatchOptions[])])
const definitions = presetRows.filter(row => row.name === '@deepseek-ai/dsh-agent-preset').map(row => row.config as import('@deepseek-ai/dsh-agent-preset-registry').PresetDefinition)
+7 -1
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-desktop-host",
"description": "Private Node-mode host process for the Electron desktop application",
"version": "0.2.2-rc.2",
"version": "0.2.2-rc.3",
"private": true,
"license": "MIT",
"type": "module",
@@ -18,6 +18,7 @@
"@deepseek-ai/dsh-app-boot": "workspace:*",
"@deepseek-ai/dsh-client-connection": "workspace:*",
"@deepseek-ai/dsh-host-webserver": "workspace:*",
"@deepseek-ai/dsh-host-authentication-desktop": "workspace:*",
"@deepseek-ai/dsh-jobs": "workspace:*",
"@deepseek-ai/dsh-schedule": "workspace:*",
"@deepseek-ai/dsh-deepseek-account": "workspace:*",
@@ -25,6 +26,11 @@
"@deepseek-ai/dsh-plugin-manager": "workspace:*"
},
"devDependencies": {
"ws": "^8.21.3",
"@types/ws": "^8.18.1",
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-api-remote-access": "workspace:*",
"@deepseek-ai/dsh-typert-registry": "workspace:*",
"@deepseek-ai/dsh-fs": "workspace:*",
"@deepseek-ai/dsh-fs-local": "workspace:*",
"@deepseek-ai/dsh-session": "workspace:*",
+70
View File
@@ -0,0 +1,70 @@
/** Receive the Desktop startup credential over the private parent IPC channel. */
interface AuthenticationChannel {
readonly connected: boolean
on(event: 'message', listener: (message: unknown) => void): unknown
on(event: 'disconnect', listener: () => void): unknown
off(event: 'message', listener: (message: unknown) => void): unknown
off(event: 'disconnect', listener: () => void): unknown
}
/** Normal parent termination before or after private credential delivery. */
export class DesktopAuthenticationEnd extends Error {
constructor(readonly kind: 'shutdown' | 'disconnected') {
super(kind === 'shutdown' ? 'Desktop authentication cancelled by shutdown' : 'Desktop authentication channel disconnected')
this.name = 'DesktopAuthenticationEnd'
}
}
/** One private credential receipt and the lifetime of its parent channel. */
export interface DesktopSecretReceipt {
readonly secret: Promise<string>
readonly signal: AbortSignal
/** Remove private IPC listeners and end any pending receipt. */
dispose(): void
}
/**
* Install credential receipt before publishing the Host's starting message.
* @param channel - owned parent IPC connection.
* @returns one credential and a signal ended by disconnect, shutdown, invalid input, or duplicate delivery.
* Pending receipt rejects with DesktopAuthenticationEnd for normal parent termination; malformed or repeated credentials remain failures.
*/
export function receiveDesktopSecret(channel: AuthenticationChannel): DesktopSecretReceipt {
const delivered = Promise.withResolvers<string>()
const lifetime = new AbortController()
let received = false
const detach = (): void => {
channel.off('message', onMessage)
channel.off('disconnect', onDisconnect)
}
const end = (error: Error): void => {
if (lifetime.signal.aborted) return
detach()
lifetime.abort(error)
delivered.reject(error)
}
const onDisconnect = (): void => { end(new DesktopAuthenticationEnd('disconnected')) }
const onMessage = (message: unknown): void => {
if (typeof message !== 'object' || message === null || !('type' in message)) return
if (message.type === 'shutdown') { end(new DesktopAuthenticationEnd('shutdown')); return }
if (message.type !== 'desktop-auth') return
if (received) { end(new Error('Desktop authentication credential already received')); return }
if (Array.isArray(message) || Object.keys(message).length !== 2 || !('secret' in message) || typeof message.secret !== 'string'
|| !/^[A-Za-z0-9_-]{43}$/u.test(message.secret)
|| Buffer.from(message.secret, 'base64url').toString('base64url') !== message.secret) {
end(new Error('Desktop authentication message is invalid'))
return
}
received = true
delivered.resolve(message.secret)
}
channel.on('message', onMessage)
channel.on('disconnect', onDisconnect)
if (!channel.connected) onDisconnect()
return {
secret: delivered.promise,
signal: lifetime.signal,
dispose() { end(new Error('Desktop authentication receiver disposed')) },
}
}
+39 -7
View File
@@ -15,10 +15,29 @@ import { installDesktopUpdateTaskControl } from './update-tasks.ts'
import { installDesktopQuitInspection } from './quit-inspection.ts'
import { installPlatformSessionPublisher } from './platform-session.ts'
import { installOperationDiagnostics } from './operation-diagnostics.ts'
import { DesktopAuthenticationEnd, receiveDesktopSecret } from './authentication.ts'
import * as DesktopAuthentication from '@deepseek-ai/dsh-host-authentication-desktop'
async function main(): Promise<void> {
const runId = randomUUID() as PluginOperationRunId
if (process.connected) process.send?.({ type: 'starting', runId }, (error) => { if (error !== null) console.error(error) })
const authentication = receiveDesktopSecret(process)
if (process.connected) process.send?.({ type: 'starting', runId }, (error) => {
if (error !== null) authentication.dispose()
})
const send = (message: object): Promise<void> => new Promise((resolve, reject) => {
if (!process.connected || process.send === undefined) { resolve(); return }
process.send(message, (error) => { if (error === null) resolve(); else reject(error) })
})
let secret: string
try {
secret = await authentication.secret
authentication.signal.throwIfAborted()
} catch (error) {
if (!(error instanceof DesktopAuthenticationEnd)) throw error
if (error.kind === 'shutdown') await send({ type: 'shutdown-complete' })
if (process.connected) process.disconnect()
return
}
const runtimeDir = process.argv[2] as string
const projectDir = process.argv[3] as string
// Set before the launch-environment snapshot and profile evaluation; empty means the payload sits beside the runtime directory.
@@ -51,10 +70,6 @@ async function main(): Promise<void> {
updateTasks?: ReturnType<typeof installDesktopUpdateTaskControl>
quitInspection?: ReturnType<typeof installDesktopQuitInspection>
} = {}
const send = (message: object): Promise<void> => new Promise((resolve, reject) => {
if (!process.connected || process.send === undefined) { resolve(); return }
process.send(message, (error) => { if (error === null) resolve(); else reject(error) })
})
const stop = (): Promise<void> => stopping ??= (async () => {
for (const abort of dragReads.values()) abort.abort()
await Promise.allSettled(dragTasks)
@@ -124,16 +139,33 @@ async function main(): Promise<void> {
}
})().catch((error: unknown) => { console.error(error) })
})
const onAuthenticationEnd = (): void => { void stop() }
authentication.signal.addEventListener('abort', onAuthenticationEnd, { once: true })
if (authentication.signal.aborted) onAuthenticationEnd()
process.once('disconnect', () => { void stop() })
const { ctx } = await application
const canPublish = (): boolean => stopping === undefined && process.connected && !authentication.signal.aborted
if (!canPublish()) return
ctx.effect(() => () => {
authentication.signal.removeEventListener('abort', onAuthenticationEnd)
authentication.dispose()
}, 'desktop-host: authentication channel')
installOperationDiagnostics(ctx, record => send({ type: 'plugin-operation', record }), 32, runId)
control.updateTasks = installDesktopUpdateTaskControl(ctx)
control.quitInspection = installDesktopQuitInspection(ctx)
installPlatformSessionPublisher(ctx, (session) => {
if (process.connected) process.send?.({ type: 'platform-session', session })
})
const url = ctx.connection.authenticatedUrl(`${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}`)
if (process.connected) process.send?.({ type: 'ready', url, injections: ctx.webServer.collectIndexInjections(ctx.connection.browserPeer) }, (error) => { if (error !== null) console.error(error) })
await ctx.plugin(DesktopAuthentication, { readSecret: () => secret }).await()
if (!canPublish()) return
const admission = ctx.connection.authentication.authenticate({
headers: { cookie: `dsh-desktop-session=${secret}` },
})
if ('rejection' in admission) throw new Error('Desktop authentication provider did not accept its startup credential')
const url = `${ctx.webServer.protocol}//127.0.0.1:${String(ctx.webServer.port)}/`
const injections = ctx.webServer.collectIndexInjections(admission.peer)
if (!canPublish()) return
process.send?.({ type: 'ready', url, injections }, (error) => { if (error !== null) console.error(error) })
}
if (import.meta.main) {
@@ -0,0 +1,175 @@
/** Desktop credential delivery and provider lifetime through the private IPC channel. */
import { EventEmitter, once } from 'node:events'
import { randomBytes } from 'node:crypto'
import { Context } from '@deepseek-ai/cordis'
import * as Connection from '@deepseek-ai/dsh-client-connection'
import WebServer from '@deepseek-ai/dsh-host-webserver'
import TypertRegistry from '@deepseek-ai/dsh-typert-registry'
import TypertGateway from '@deepseek-ai/dsh-api-gateway'
import RemoteAccess from '@deepseek-ai/dsh-api-remote-access'
import WebSocket from 'ws'
import OperatorFixture from '../../../packages/api/gateway/tests/operator-connect-fixture.ts'
import { expect, it, onTestFinished, vi } from 'vitest'
import { DesktopAuthenticationEnd, receiveDesktopSecret } from '../src/authentication.ts'
import * as DesktopAuthentication from '@deepseek-ai/dsh-host-authentication-desktop'
class Channel extends EventEmitter {
connected = true
}
const secret = (): string => randomBytes(32).toString('base64url')
it('listens before delivery and accepts one exact desktop credential message', async () => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
onTestFinished(() => { received.dispose() })
const value = secret()
channel.emit('message', { type: 'unrelated' })
channel.emit('message', { type: 'desktop-auth', secret: value })
expect(await received.secret).toBe(value)
expect(received.signal.aborted).toBe(false)
expect(channel.listenerCount('message')).toBe(1)
received.dispose()
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
})
it.each([
{ type: 'desktop-auth' },
{ type: 'desktop-auth', secret: 'bad-secret' },
{ type: 'desktop-auth', secret: 'A'.repeat(42) + 'B' },
{ type: 'desktop-auth', secret: 'A'.repeat(43), extra: true },
])('rejects malformed desktop authentication without echoing input', async (message) => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
channel.emit('message', message)
await expect(received.secret).rejects.toThrow('Desktop authentication message is invalid')
expect(received.signal.aborted).toBe(true)
expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd)
expect(String(received.signal.reason)).not.toContain('bad-secret')
expect(channel.listenerCount('message')).toBe(0)
})
it.each(['disconnected', 'shutdown'] as const)('distinguishes pending authentication ending on %s', async (kind) => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
if (kind === 'disconnected') channel.emit('disconnect')
else channel.emit('message', { type: 'shutdown' })
await expect(received.secret).rejects.toBeInstanceOf(DesktopAuthenticationEnd)
expect(received.signal.reason).toMatchObject({ kind })
expect(received.signal.aborted).toBe(true)
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
channel.emit('message', { type: 'desktop-auth', secret: secret() })
await expect(received.secret).rejects.toBe(received.signal.reason)
})
it.each(['disconnected', 'shutdown'] as const)('retains %s after credentials arrive before the receiver resumes', async (kind) => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
const value = secret()
channel.emit('message', { type: 'desktop-auth', secret: value })
if (kind === 'disconnected') channel.emit('disconnect')
else channel.emit('message', { type: 'shutdown' })
expect(await received.secret).toBe(value)
expect(() => { received.signal.throwIfAborted() }).toThrow(DesktopAuthenticationEnd)
expect(received.signal.reason).toMatchObject({ kind })
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
})
it('rejects disposal while waiting without treating it as parent shutdown', async () => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
received.dispose()
await expect(received.secret).rejects.toThrow('Desktop authentication receiver disposed')
expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd)
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
})
it('refuses a channel already disconnected before waiting', async () => {
const channel = new Channel()
channel.connected = false
const received = receiveDesktopSecret(channel)
await expect(received.secret).rejects.toBeInstanceOf(DesktopAuthenticationEnd)
expect(received.signal.reason).toMatchObject({ kind: 'disconnected' })
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
})
it.each([true, false])('rejects duplicate credentials before the receiver resumes (same: %s)', async (same) => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
const value = secret()
channel.emit('message', { type: 'desktop-auth', secret: value })
channel.emit('message', { type: 'desktop-auth', secret: same ? value : secret() })
expect(await received.secret).toBe(value)
expect(() => { received.signal.throwIfAborted() }).toThrow('Desktop authentication credential already received')
expect(received.signal.reason).not.toBeInstanceOf(DesktopAuthenticationEnd)
expect(channel.listenerCount('message')).toBe(0)
expect(channel.listenerCount('disconnect')).toBe(0)
})
it.each([true, false])('ends the channel on duplicate credentials (same: %s)', async (same) => {
const channel = new Channel()
const received = receiveDesktopSecret(channel)
const value = secret()
channel.emit('message', { type: 'desktop-auth', secret: value })
await received.secret
channel.emit('message', { type: 'desktop-auth', secret: same ? value : secret() })
expect(received.signal.aborted).toBe(true)
expect(String(received.signal.reason)).toContain('already received')
expect(String(received.signal.reason)).not.toContain(value)
expect(channel.listenerCount('message')).toBe(0)
})
it('authenticates real HTTP requests using its own Peer and withdraws with its owner', async () => {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
await ctx.plugin(WebServer, { host: '127.0.0.1', port: 0 }).await()
await ctx.plugin(Connection).await()
await ctx.plugin(TypertRegistry).await()
await ctx.plugin(RemoteAccess).await()
await ctx.plugin(TypertGateway).await()
await ctx.plugin(OperatorFixture).await()
const value = secret()
const desktop = ctx.plugin(DesktopAuthentication, { readSecret: () => value })
await desktop.await()
const admitted = ctx.connection.authentication.authenticate({ headers: { cookie: `dsh-desktop-session=${value}` } })
if ('rejection' in admitted) throw new Error('Desktop fixture did not register its provider')
const desktopPeer = admitted.peer
expect(desktopPeer).not.toBe(ctx.connection.browserPeer)
ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/identity', handler(req, res) {
const admitted = ctx.connection.admit(req)
if ('rejection' in admitted) { res.writeHead(admitted.rejection).end(); return }
res.end(admitted.peer.id)
} }))
const origin = ctx.webServer.getOrigin()
const request = async (cookie?: string): Promise<{ status: number; body: string }> => {
const response = await fetch(`${origin}/identity`, { headers: cookie === undefined ? {} : { cookie } })
return { status: response.status, body: await response.text() }
}
expect((await request()).status).toBe(401)
expect((await request(`dsh-desktop-session=${secret()}`)).status).toBe(401)
expect((await request(`dsh-desktop-session=${value}; dsh-desktop-session=${value}`)).status).toBe(401)
expect(await request(`other=1; dsh-desktop-session=${value}`)).toEqual({ status: 200, body: desktopPeer.id })
expect(await request(`dsh-desktop-session=${value}`)).toEqual({ status: 200, body: desktopPeer.id })
const socket = new WebSocket(`${origin.replace('http:', 'ws:')}/api/remote.mux`, {
headers: { cookie: `dsh-desktop-session=${value}` },
})
const closed = once(socket, 'close')
onTestFinished(async () => {
if (socket.readyState !== WebSocket.CLOSED) socket.terminate()
await closed
})
await once(socket, 'open')
const ready = once(socket, 'message')
socket.send(JSON.stringify({ type: 'open', streamId: 'desktop', endpoint: 'fixture/follow', payload: { args: { label: 'desktop' } } }))
await ready
expect(ctx.operatorConnectFixture.calls.get('desktop')?.peer).toBe(desktopPeer)
await desktop.dispose()
await closed
await vi.waitFor(() => { expect(ctx.operatorConnectFixture.calls.get('desktop')?.finished).toBe(true) })
expect(desktopPeer.signal.aborted).toBe(true)
expect((await request(`dsh-desktop-session=${value}`)).status).toBe(401)
})
+2 -1
View File
@@ -8,6 +8,7 @@
"src"
],
"references": [
{ "path": "../../packages/host/authentication-desktop" },
{ "path": "../../vendor/cordis" },
{ "path": "../../packages/core/agent" },
{ "path": "../../packages/jobs/jobs" },
@@ -26,7 +27,7 @@
"path": "../../packages/host/webserver"
},
{
"path": "../../packages/credentials/deepseek-account"
"path": "../../packages/account/deepseek-account"
},
{
"path": "../../packages/boot/plugin-manager"
+28
View File
@@ -0,0 +1,28 @@
# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write apps/desktop-publisher/README.md
/:
en: b6cea27035a6acd8
zh: c8484ea772e48b76
/desktop-publisher:
en: 2f3214a4c5f468bd
zh: 0344414f601ce5da
/desktop-publisher/summary:
en: 96e01061bb58ef81
zh: 34e3e9da3adbdfef
/desktop-publisher/table-of-contents:
en: c910eb62c99ebaae
zh: a39d3e1344eb1b3d
/desktop-publisher/use-this-package:
en: 9678d489d32b9e7b
zh: 6d0ddae4cf96db94
/desktop-publisher/implementation:
en: 62a7d718a25d4ea4
zh: 10c8e93749810a15
/desktop-publisher/limitations:
en: cc71e293492ce240
zh: 1b9388bf9b108274
/desktop-publisher/limitations/dev-note:
en: 0a1253c6f7b5e8b9
zh: 9f56528562c7c914
+49
View File
@@ -0,0 +1,49 @@
---
description: "Run Desktop publication and staged rollout from retained packages without installing Desktop build dependencies."
kind: "package-library"
---
# Desktop publisher
English | [中文](README.zh.md)
## Summary
Publish retained Desktop packages, change an existing release's rollout percentage, and refresh website installers. The manual GitHub workflows select the original packaging machine and require the configured environment approvals. This private workspace shares the repository lockfile and runs TypeScript source directly with Node 24 and tsx.
## Table of Contents
- [Use this package](#use-this-package)
- [Implementation](#implementation)
- [Limitations](#limitations)
## Use this package
Use [Publish Desktop](../../.github/workflows/desktop-publish.yml) for initial publication and [Rollout & Website](../../.github/workflows/desktop-rollout.yml) for an already published version. The workflows own operator inputs, runner routing, credentials, and approval steps. Rollout installs only this workspace's production dependencies with lifecycle scripts disabled; invoke its entrypoints with Node from this package directory to avoid pnpm's automatic dependency repair.
The dependency-free preflights run before installation. Their executable regression check is:
```sh
node apps/desktop-publisher/tests/preinstall.mjs
```
## Implementation
<details>
<summary>Maintainer details</summary>
Desktop build and signing scripts stay in `apps/desktop`; publishing code imports no Desktop implementation. Desktop consumes publisher helpers through the workspace package exports. Runtime dependencies belong in this package's `dependencies`; tests and type checking use repository development tools. The root host TypeScript project checks this source, so there is no separate emitted package or package-local tsconfig.
Full-install publication and filtered-install rollout use different checkout directories. Changing install modes in one checkout removes development dependency links and can retain stale Desktop directories. Release records live outside these checkouts and remain owned by the existing retained-release configuration.
Tests under `apps/desktop` may reuse the publisher's loopback COS fixture. Publisher failure tests also exercise the Desktop rollback and archival CLIs as repository integration tests; these test-only paths are not runtime dependencies. The isolated-install CI checks load publisher source without Desktop or root development dependencies on Linux, macOS, and Windows, and contribute to required CI verdicts.
</details>
## Limitations
- This private tool is not published to npm and does not generate a standalone artifact. Workflow checkouts must contain the shared lockfile and workspace metadata.
- Isolated-install and preflight tests do not authorize a production write or prove that an installer upgrades a real client.
### Dev Note
None.
+49
View File
@@ -0,0 +1,49 @@
---
description: "从保留的安装包执行 Desktop 发布和灰度放量,无需安装 Desktop 构建依赖。"
kind: "package-library"
---
# Desktop 发布工具
[English](README.md) | 中文
## 概述
发布保留的 Desktop 安装包、调整已发布版本的放量比例,以及刷新官网安装包。手动 GitHub 工作流选择原始打包机器,并要求通过配置的环境审批。此私有 workspace 共用仓库锁文件,通过 Node 24 和 tsx 直接执行 TypeScript 源码。
## 目录
- [使用此包](#use-this-package)
- [实现](#implementation)
- [限制](#limitations)
## 使用此包
首次发布使用 [Publish Desktop](../../.github/workflows/desktop-publish.yml),已发布版本使用 [Rollout & Website](../../.github/workflows/desktop-rollout.yml)。工作流负责操作输入、运行器路由、凭据和审批步骤。放量仅安装此 workspace 的生产依赖,并禁用生命周期脚本;从此包目录使用 Node 调用入口,避免 pnpm 自动修复依赖。
无依赖预检在安装之前运行,其可执行回归检查为:
```sh
node apps/desktop-publisher/tests/preinstall.mjs
```
## 实现
<details>
<summary>维护者说明</summary>
Desktop 构建和签名脚本保留在 `apps/desktop`;发布代码不导入 Desktop 实现。Desktop 通过 workspace 包导出使用发布辅助函数。运行时依赖归此包的 `dependencies` 所有;测试和类型检查使用仓库开发工具。根目录的 host TypeScript 项目检查这些源码,因此没有独立的编译产物或包级 tsconfig。
完整安装的发布与筛选安装的放量使用不同 checkout 目录。在同一 checkout 切换安装模式会移除开发依赖链接,也可能保留旧 Desktop 目录。发布记录位于这些 checkout 之外,仍由现有保留版本配置管理。
`apps/desktop` 下的测试可以复用发布工具的 loopback COS fixture。发布失败测试还将 Desktop 回滚和归档 CLI 作为仓库集成测试执行;这些测试路径不是运行时依赖。隔离安装 CI 在 Linux、macOS 和 Windows 上验证发布源码无需 Desktop 或根目录开发依赖即可加载,结果纳入必需的 CI 汇总检查。
</details>
## 限制
- 此私有工具不发布到 npm,也不生成独立产物。工作流 checkout 必须包含共用锁文件和 workspace 元数据。
- 隔离安装和预检测试不授权生产写入,也不能证明安装包能升级真实客户端。
### 开发备注
无。
+19
View File
@@ -0,0 +1,19 @@
{
"name": "@deepseek-ai/dsh-desktop-publisher",
"version": "0.2.2-rc.3",
"description": "Private Desktop release metadata, rollout and website publisher",
"private": true,
"type": "module",
"license": "MIT",
"exports": {
"./*": "./src/*"
},
"dependencies": {
"zod": "4.6.6",
"js-yaml": "^4.3.2",
"semver": "^7.8.5",
"cos-nodejs-sdk-v5": "3.0.0",
"tencentcloud-sdk-nodejs-teo": "4.1.330",
"tsx": "^4.23.13"
}
}
@@ -47,7 +47,7 @@ export function createDesktopCos(credentials: DesktopCosCredentials, timeoutMs:
})
cos.on('before-send', (options: CosRequestOptions) => {
for (const name of Object.keys(options.headers)) {
if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') delete options.headers[name]
if (name.toLowerCase() === 'cache-control' && options.headers[name] === '') Reflect.deleteProperty(options.headers, name)
}
})
return cos
@@ -9,6 +9,7 @@ const schema = z.strictObject({
bucket: z.string().regex(/^[a-z0-9-]+-\d+$/u),
origin: z.url().refine((value) => { const url = new URL(value); return url.protocol === 'https:' && !url.username && !url.password && url.pathname === '/' && !url.search && !url.hash }, 'expected an HTTPS origin'),
credentialsFile: absolutePath,
edgeOneZoneId: z.string().regex(/^zone-[a-z0-9]+$/u).optional(),
macOS: z.strictObject({ signingIdentity: z.string().min(1), teamId: z.string().regex(/^[A-Z0-9]{10}$/u) }).optional(),
windows: z.strictObject({ certificateThumbprint: z.string().regex(/^[A-Fa-f0-9]{40}$/u) }).optional(),
githubApp: z.strictObject({ clientId: singleLine, privateKeyFile: absolutePath }).optional(),
@@ -44,3 +45,13 @@ export async function readDesktopUploadCredentials(config: DesktopPublishConfig)
throw new Error('desktop publish: cannot read valid upload credentials from the configured file')
}
}
/**
* Require the configured EdgeOne destination before website upload or cache recovery.
* @param config Validated machine publication settings.
* @returns Configured EdgeOne zone identifier.
*/
export function requireDesktopEdgeOneZoneId(config: DesktopPublishConfig): string {
if (!config.edgeOneZoneId) throw new Error('website publication: configure edgeOneZoneId in publishing/production.json before uploading')
return config.edgeOneZoneId
}
@@ -5,7 +5,7 @@ import { Readable, Writable } from 'node:stream'
import type COS from 'cos-nodejs-sdk-v5'
import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from './desktop-cos.ts'
import { cosOperation } from './cos-operation.ts'
import type { DesktopUploadPlan } from './desktop-upload-plan.ts'
import type { DesktopUploadPlan } from './desktop-upload-types.ts'
import { desktopArtifactDigest, type DesktopPublishTransport } from './desktop-publish.ts'
import { DesktopCosOperationError } from './desktop-publication-failure.ts'
@@ -66,7 +66,8 @@ export function desktopPublishCos(
if (actual.size !== digest.size || actual.sha512 !== digest.sha512) throw new Error('desktop publish: local input changed')
const cos = client()
const md5 = createHash('md5')
const bytes = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)]
const bytes = artifact.contents === undefined
? createReadStream(artifact.path) as AsyncIterable<Buffer> : [Buffer.from(artifact.contents)]
for await (const chunk of bytes) md5.update(chunk)
const body = artifact.contents === undefined ? createReadStream(artifact.path) : Readable.from([Buffer.from(artifact.contents)])
try {
@@ -108,7 +108,7 @@ export async function findDesktopPublication(root: string, expected: {
for (const entry of entries) {
if (!entry.isDirectory() || !entry.name.startsWith('publish-')) continue
const directory = join(root, entry.name)
let operation
let operation: unknown
try { operation = JSON.parse(await readFile(join(directory, 'operation.json'), 'utf8')) } catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') continue
throw error
@@ -4,7 +4,7 @@ import { createReadStream } from 'node:fs'
import { load } from 'js-yaml'
import { gt, valid } from 'semver'
import { z } from 'zod'
import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-plan.ts'
import type { DesktopUploadArtifact, DesktopUploadPlan } from './desktop-upload-types.ts'
/** File identity computed from bytes, never inferred from COS ETags. */
export interface DesktopObjectDigest { readonly size: number; readonly sha512: string }
@@ -51,7 +51,8 @@ export class DesktopPublishError extends Error {
export async function desktopArtifactDigest(artifact: DesktopUploadArtifact): Promise<DesktopObjectDigest> {
const hash = createHash('sha512')
let size = 0
const stream = artifact.contents === undefined ? createReadStream(artifact.path) : [Buffer.from(artifact.contents)]
const stream = artifact.contents === undefined
? createReadStream(artifact.path) as AsyncIterable<Buffer> : [Buffer.from(artifact.contents)]
for await (const bytes of stream) { hash.update(bytes); size += bytes.length }
return { size, sha512: hash.digest('base64') }
}
@@ -61,10 +62,11 @@ function same(left: DesktopObjectDigest | null, right: DesktopObjectDigest | nul
}
function version(contents: string, remote = false): string {
let parsed: { version: string } | undefined
try {
const parsed = z.object({ version: z.string() }).parse(load(contents))
if (valid(parsed.version) !== null) return parsed.version
} catch (error) { /* Discard parser error details, which may include raw remote YAML. */ }
parsed = z.object({ version: z.string() }).parse(load(contents))
} catch (_parseError) { /* Discard parser error details, which may include raw remote YAML. */ }
if (parsed !== undefined && valid(parsed.version) !== null) return parsed.version
throw new DesktopPublishError(remote ? 'verification-failed' : 'invalid-plan',
`desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`)
}
@@ -1,6 +1,6 @@
/** Resume a fixed-URL purge without repeating ambiguous submissions. */
import type { teo } from 'tencentcloud-sdk-nodejs-teo'
import type { DesktopPurgeConfig } from './desktop-edgeone.ts'
import type { DesktopPurgeConfig } from './desktop-purge-types.ts'
/** Non-secret evidence saved before submission and after every observation. */
export interface DesktopPurgeRecord {
@@ -65,12 +65,12 @@ async function observe(record: DesktopPurgeRecord, client: DesktopPurgeRecoveryC
if (offset >= response.TotalCount) break
if (response.Tasks.length === 0 || offset >= 10_000) return unknown('task history could not be fully inspected')
} while (true)
} catch (error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') }
} catch (_error) { return unknown('task query failed; check EdgeOne history and DescribePurgeTasks permission') }
if (matches.length === 0) return unknown(record.jobId
? 'accepted task not found in query history; execution result unconfirmed'
: 'no matching submission found; purge may not have been submitted; inspect EdgeOne history before manual recovery')
if (matches.length !== 1) return unknown('multiple matching submissions found; cannot identify this submission')
const task = matches[0]!
const task = matches[0]
if (matches.length !== 1 || !task) return unknown('multiple matching submissions found; cannot identify this submission')
if (!task.JobId || !/^[\w.-]{1,128}$/u.test(task.JobId)
|| task.JobId.includes(config.secretId) || task.JobId.includes(config.secretKey)) return unknown('query returned no usable task ID')
const status = task.Status
@@ -115,7 +115,7 @@ export async function recoverDesktopPurge(config: DesktopPurgeConfig, previous:
await options.save(record)
let response: Awaited<ReturnType<DesktopPurgeRecoveryClient['CreatePurgeTask']>> | undefined
try { response = await client.CreatePurgeTask({ ZoneId: config.zoneId, Type: 'purge_url', Targets: [config.publicUrl] }) }
catch (error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ }
catch (_error) { /* Submission may have reached EdgeOne; reconcile history without repeating the request. */ }
const jobId = response?.JobId
if (response?.FailedList?.length) {
record = { ...record, status: 'failed' }
@@ -0,0 +1,7 @@
/** Validated production destination and credentials; never serialize this value. */
export interface DesktopPurgeConfig {
readonly zoneId: string
readonly publicUrl: string
readonly secretId: string
readonly secretKey: string
}
@@ -44,7 +44,7 @@ async function fingerprint(path: string) {
if (!info.isFile() || info.isSymbolicLink()) throw new Error('desktop release store: expected a regular file')
const hash = createHash('sha512')
let size = 0
for await (const bytes of createReadStream(path)) { size += bytes.length; hash.update(bytes) }
for await (const bytes of createReadStream(path) as AsyncIterable<Buffer>) { size += bytes.length; hash.update(bytes) }
if (size === 0) throw new Error('desktop release store: empty artifact')
return { size, sha512: hash.digest('base64') }
}
@@ -0,0 +1,15 @@
/** Resolve retained Desktop storage independently of packaging and signing. */
import { dirname, isAbsolute, join } from 'node:path'
/**
* Resolve the persistent release root without assuming a particular user's home directory.
* @param env Machine packaging configuration; an explicit releases directory overrides its sibling default.
* @returns Absolute directory outside the disposable checkout.
*/
export function desktopReleasesRoot(env: NodeJS.ProcessEnv): string {
const configured = env.DSH_PACKAGING_CONFIG_DIR
if (!configured) throw new Error('desktop retention: DSH_PACKAGING_CONFIG_DIR is required')
const root = env.DSH_DESKTOP_RELEASES_DIR || join(dirname(configured), 'releases')
if (!isAbsolute(configured) || !isAbsolute(root)) throw new Error('desktop retention: machine directories must be absolute')
return root
}
@@ -7,15 +7,15 @@ import { dump, load } from 'js-yaml'
import { z } from 'zod'
import { desktopUpdateMetadataFilename, resolveDesktopUploadConfig } from './desktop-auto-update-environment.mjs'
import type { DesktopRetainedManifest } from './desktop-release-store.ts'
import type { DesktopUploadPlan } from './desktop-upload-plan.ts'
import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts'
import { desktopArtifactDigest, type DesktopPublishOperations, type DesktopRemoteObject } from './desktop-publish.ts'
const percentage = z.number().int().min(0).max(100)
const metadataSchema = z.object({
version: z.string(),
files: z.array(z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).passthrough()).length(1),
files: z.tuple([z.object({ url: z.string(), size: z.number().int().positive(), sha512: z.string() }).loose()]),
path: z.string().optional(), sha512: z.string().optional(), stagingPercentage: percentage.optional(),
}).passthrough()
}).loose()
function metadata(contents: string) {
if (Buffer.byteLength(contents) > 1024 * 1024) throw new Error('desktop rollout: metadata exceeds 1 MiB')
@@ -26,7 +26,7 @@ function metadata(contents: string) {
/** Validated immutable update identity; no installer bytes are read. */
export interface DesktopRolloutPlan {
readonly upload: DesktopUploadPlan
readonly upload: DesktopSingleUploadPlan
readonly expected: string
}
@@ -56,7 +56,7 @@ export async function prepareDesktopRollout(directory: string, manifest: Desktop
const parsed = metadata(contents)
const payload = `deepseek-harness-${source.version}-${source.target}.${windows ? 'exe' : 'zip'}`
const file = manifest.files.find(entry => entry.name === payload)
const entry = parsed.files[0]!
const entry = parsed.files[0]
if (parsed.version !== source.version || entry.url !== payload || !file
|| entry.size !== file.size || entry.sha512 !== file.sha512
|| (parsed.path !== undefined && parsed.path !== payload)
@@ -103,8 +103,9 @@ export function verifyDesktopRolloutFeed(plan: DesktopRolloutPlan, remote: Deskt
export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: number | undefined,
operations: Pick<DesktopPublishOperations, 'transport' | 'record'>) {
if (target !== undefined) percentage.parse(target)
const artifact = plan.upload.artifacts[0]!
const artifact = plan.upload.artifacts[0]
const before = await operations.transport.read(artifact.key, true)
if (!before?.contents) throw new Error('desktop rollout: published update feed is missing')
const current = verifyDesktopRolloutFeed(plan, before)
const next = target ?? current.percentage
if (next < current.percentage) throw new Error('desktop rollout: percentage cannot decrease; inspect the current rollout')
@@ -115,8 +116,8 @@ export async function rolloutDesktopRelease(plan: DesktopRolloutPlan, target: nu
const updated = { ...artifact, contents: dump({ ...current.metadata, stagingPercentage: next }) }
const digest = await desktopArtifactDigest(updated)
const confirmed = await operations.transport.read(artifact.key, true)
if (confirmed?.contents !== before?.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry')
await operations.record({ type: 'put-intent', key: artifact.key, before: before!.contents!, after: updated.contents })
if (confirmed?.contents !== before.contents) throw new Error('desktop rollout: feed changed before write; inspect and retry')
await operations.record({ type: 'put-intent', key: artifact.key, before: before.contents, after: updated.contents })
await operations.transport.put(updated, digest, false)
const actual = await operations.transport.read(artifact.key, true)
if (actual?.size !== digest.size || actual.sha512 !== digest.sha512) {
@@ -0,0 +1,37 @@
/** Shared upload contracts for Desktop packaging and publication. */
import type { DesktopAutoUpdateTarget } from './desktop-auto-update-environment.mjs'
/** One local file and its final object metadata. */
export interface DesktopUploadArtifact {
readonly path: string
readonly filename: string
readonly key: string
readonly contentType: string
/** Browser save name for fixed website downloads, preserving the validated installer basename. */
readonly contentDisposition?: string
readonly channelMetadata: boolean
/** Published YAML with normalized artifact URLs; binary bytes remain file-backed. */
readonly contents?: string
}
/** A validated installer or update upload, with any channel metadata ordered last. */
export interface DesktopUploadPlan {
readonly environment: 'test' | 'production'
readonly target: DesktopAutoUpdateTarget
readonly version: string
/** Update feed directory URL, or the single installer URL for a fixed download. */
readonly publicUrl: string
readonly bucket: string
readonly secretIdEnvName: string
readonly secretKeyEnvName: string
readonly artifacts: readonly DesktopUploadArtifact[]
/** Commit the artifacts were packaged from, absent for a package built before builds recorded it. */
readonly commit?: string
/** Whether that checkout carried uncommitted changes. */
readonly dirty?: boolean
}
/** A publication operation targeting exactly one metadata object or installer. */
export type DesktopSingleUploadPlan = Omit<DesktopUploadPlan, 'artifacts'> & {
readonly artifacts: readonly [DesktopUploadArtifact]
}
@@ -9,11 +9,11 @@ import { createDesktopCos, DESKTOP_COS_REGION, type DesktopCosCredentials } from
import { cosOperation } from './cos-operation.ts'
import type { DesktopObjectDigest, DesktopPublishTransport } from './desktop-publish.ts'
import { DesktopCosOperationError } from './desktop-publication-failure.ts'
import type { DesktopUploadPlan } from './desktop-upload-plan.ts'
import type { DesktopSingleUploadPlan } from './desktop-upload-types.ts'
/** Verified file and destination; the caller closes the handle after publication. */
export interface DesktopWebsiteInstaller {
readonly plan: DesktopUploadPlan
readonly plan: DesktopSingleUploadPlan
readonly digest: DesktopObjectDigest
readonly md5: string
readonly contentDisposition: string
@@ -52,7 +52,7 @@ export async function prepareWebsiteInstaller(directory: string, manifest: Deskt
const sha512 = createHash('sha512')
const md5 = createHash('md5')
let size = 0
for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 })) {
for await (const bytes of handle.createReadStream({ autoClose: false, start: 0 }) as AsyncIterable<Buffer>) {
size += bytes.length
sha512.update(bytes)
md5.update(bytes)
@@ -89,7 +89,7 @@ export async function uploadWebsiteInstaller(installer: DesktopWebsiteInstaller,
record: (event: 'upload-intent' | 'uploaded') => Promise<void>,
options: { createClient?: typeof createDesktopCos; previouslyUploaded?: boolean } = {},
): Promise<'uploaded' | 'present'> {
const artifact = installer.plan.artifacts[0]!
const artifact = installer.plan.artifacts[0]
const matches = (remote: DesktopObjectDigest | null) =>
remote?.size === installer.digest.size && remote.sha512 === installer.digest.sha512
const remote = await transport.read(artifact.key, false)
@@ -27,7 +27,7 @@ export function preflightDesktopPublish(repository, inputs, api) {
throw new Error('desktop publish: GitHub returned invalid artifact metadata')
}
for (const { name } of pages.flatMap(page => page.artifacts)) {
if (!name.replace(/\.zip$/u, '').endsWith(`-${inputs.package_run_id}-${attempt}`)) continue
if (!name.replace(/\.(?:zip|dmg)$/u, '').replace(/-(?:metadata|update)$/u, '').endsWith(`-${inputs.package_run_id}-${attempt}`)) continue
const qualification = name.startsWith('windows-x64-unsigned-') ? 'unsigned'
: /^macos-(?:arm64|x64)-unnotarized-debug-/u.test(name) ? 'unnotarized' : ''
const diagnostic = desktopPublishQualificationError(qualification)
@@ -3,8 +3,8 @@ import { createHash } from 'node:crypto'
import { appendFile } from 'node:fs/promises'
import { dirname, join, resolve } from 'node:path'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './desktop-releases-root.ts'
import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts'
import { resolveRetainedDesktopPublication, retainedDesktopPublishApi } from './resolve-retained-desktop-publish-ci.ts'
import { createDesktopPublicationRecord, findDesktopPublication, withDesktopChannelLock } from './desktop-publish-record.ts'
@@ -36,8 +36,8 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
const target = input === '' ? undefined : Number(input)
const website = env.DESKTOP_UPLOAD_WEBSITE === 'true'
if (target === undefined && !website) throw new Error('desktop rollout: select a percentage or website publication')
if (website && (route.preset !== 'production' || !/^zone-[a-z0-9]+$/u.test(env.DOWNLOAD_PROD_EO_ZONE_ID || ''))) {
throw new Error('desktop rollout: website publication requires production and DOWNLOAD_PROD_EO_ZONE_ID')
if (website && route.preset !== 'production') {
throw new Error('desktop rollout: website publication requires production')
}
const root = desktopReleasesRoot(env)
const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt)
@@ -49,7 +49,8 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
|| source.qualification !== (source.target === 'win-x64' ? 'signed' : 'notarized')) {
throw new Error('desktop rollout: repository or release qualification mismatch')
}
const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, source.preset)
const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), source.preset)
const zoneId = website ? requireDesktopEdgeOneZoneId(config) : undefined
const environment = source.preset === 'test'
? { DSH_DESKTOP_AUTO_UPDATE_ENV: 'test', DOWNLOAD_TEST_ORIGIN: config.origin,
DOWNLOAD_TEST_RELEASE_ID: source.testReleaseId ?? '', DOWNLOAD_TEST_COS_BUCKET: config.bucket }
@@ -62,7 +63,7 @@ export async function prepareDesktopRolloutCi(env: NodeJS.ProcessEnv) {
throw new Error('desktop rollout: initial COS feed publication is not confirmed for this package')
}
const approval = createHash('sha256').update(JSON.stringify({ manifest, plan, target, website,
zoneId: website ? env.DOWNLOAD_PROD_EO_ZONE_ID : undefined })).digest('hex')
zoneId })).digest('hex')
return { route, root, recordsRoot, config, manifest, plan, target, website, destination, approval }
}
@@ -84,7 +85,7 @@ export async function publishDesktopRolloutCi(mode: 'check' | 'apply' | 'website
const { route, root, recordsRoot, config, manifest, plan, target, website, destination, approval } = context
if (mode === 'check') {
if (env.GITHUB_OUTPUT) await appendFile(env.GITHUB_OUTPUT,
`approval=${approval}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\nwebsite-destination=${createHash('sha256').update(`${config.bucket}/${route.target}`).digest('hex')}\nlabel=${manifest.source.version} / ${route.channel} / ${route.target} → ${target === undefined ? 'website only' : `${target}%`}\n`)
`rollout-requested=${target !== undefined}\napproval=${approval}\nwebsite-approval=${websiteApproval(manifest, config.bucket)}\nwebsite-destination=${createHash('sha256').update(`${config.bucket}/${route.target}`).digest('hex')}\nlabel=${manifest.source.version} / ${route.channel} / ${route.target} → ${target === undefined ? 'website only' : `${target}%`}\n`)
if (env.GITHUB_STEP_SUMMARY && !env.DESKTOP_ROLLOUT_APPROVAL) await appendFile(env.GITHUB_STEP_SUMMARY,
`## 桌面放量与官网发布确认\n\n打包运行:${route.runId} / 第 ${route.attempt} 次;版本:${manifest.source.version};平台:${route.target};环境 / 渠道:${route.preset} / ${route.channel}。\n\n目标放量比例:${target === undefined ? '保持当前比例' : `${target}%`}。执行时从 COS 核对当前比例,不允许降低比例。\n\n官网:${website ? desktopWebsiteInstallerUrl(route.target) + '(上传安装包并刷新缓存)' : '不变'}。${website ? '官网安装包面向所有下载用户,不受自动更新放量比例限制,也不要求放量达到 100%。固定下载地址无防降级保护,发布较早版本会替换较新安装包。' : ''}\n\n已确认首次 COS 发布记录;不重新计算全部安装包哈希或校验签名。\n`)
return
@@ -4,8 +4,8 @@ import { appendFile, mkdir, readFile, rename, writeFile } from 'node:fs/promises
import { dirname, join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { z } from 'zod'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from './desktop-publish-config.ts'
import { desktopReleasesRoot } from './desktop-releases-root.ts'
import { readRetainedDesktopManifest, retainedDesktopPath } from './desktop-release-store.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from './desktop-website-installer.ts'
import { desktopPublishCos } from './desktop-publish-cos.ts'
@@ -45,11 +45,10 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro
|| !/^[1-9]\d*$/u.test(env.GITHUB_RUN_ATTEMPT || '')) throw new Error('website publication: invalid Actions identity or original machine')
const root = desktopReleasesRoot(env)
const manifest = await readRetainedDesktopManifest(root, route.runId, route.attempt)
const config = await readDesktopPublishConfig(env.DSH_PACKAGING_CONFIG_DIR!, 'production')
const config = await readDesktopPublishConfig(z.string().parse(env.DSH_PACKAGING_CONFIG_DIR), 'production')
const approval = websiteApproval(manifest, config.bucket)
if (!env.DESKTOP_WEBSITE_APPROVAL || env.DESKTOP_WEBSITE_APPROVAL !== approval) throw new Error('website publication: approved build or destination changed')
const zoneId = env.DOWNLOAD_PROD_EO_ZONE_ID
if (!zoneId || !/^zone-[a-z0-9]+$/u.test(zoneId)) throw new Error('website publication: configure DOWNLOAD_PROD_EO_ZONE_ID before uploading')
const zoneId = requireDesktopEdgeOneZoneId(config)
const directory = join(dirname(root), 'upload-records', `website-${env.GITHUB_RUN_ID}-${route.target}`)
await mkdir(directory, { recursive: true, mode: 0o700 })
const stateFile = join(directory, 'state.json')
@@ -68,7 +67,7 @@ export async function publishWebsiteCi(mode: 'upload' | 'purge', env: NodeJS.Pro
const installer = await prepareWebsiteInstaller(retainedDesktopPath(root, route.runId, route.attempt), manifest, route,
env.GITHUB_REPOSITORY || '', config.bucket)
try {
const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0]!.key}`, async () => {
const outcome = await withDesktopChannelLock(join(dirname(root), 'publish-locks'), `${config.bucket}/${installer.plan.artifacts[0].key}`, async () => {
const previouslyUploaded = state.uploadConfirmed === true || state.upload === 'uploaded'
return uploadWebsiteInstaller(installer, credentials, desktopPublishCos(installer.plan, credentials), async (event) => {
state = event === 'upload-intent'
@@ -53,12 +53,12 @@ export function selectDesktopPackage(repository: string, inputsValue: unknown, r
}
packages = packages.filter(job => job.run_attempt === run.run_attempt && job.conclusion === 'success' && job.runner_name)
if (packages.length !== 1) throw new Error('desktop publish: expected one successful package job')
const runnerName = packages[0]!.runner_name!
const runnerName = z.string().parse(packages[0]?.runner_name)
const routes = desktopPublishRunnersSchema.parse(routesValue)
const route = routes[runnerName]
const target = (Object.keys(desktopPackageWorkflows) as Array<keyof typeof desktopPackageWorkflows>)
.find(name => desktopPackageWorkflows[name] === run.path)!
if (!route || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route')
.find(name => desktopPackageWorkflows[name] === run.path)
if (!route || target === undefined || !route.target.includes(target)) throw new Error('desktop publish: original machine has no configured publishing route')
if (new Set(Object.values(routes).map(value => value.label)).size !== Object.keys(routes).length) {
throw new Error('desktop publish: each configured machine needs its own unique runner label')
}
@@ -2,7 +2,7 @@
import { appendFile } from 'node:fs/promises'
import { resolve } from 'node:path'
import { z } from 'zod'
import { desktopReleasesRoot } from './retain-desktop-ci.ts'
import { desktopReleasesRoot } from './desktop-releases-root.ts'
import { verifyRetainedDesktopRelease } from './desktop-release-store.ts'
import { resolveDesktopPublishRoute } from './desktop-publish-route.ts'
@@ -15,7 +15,7 @@ import { resolveDesktopPublishRoute } from './desktop-publish-route.ts'
*/
export async function resolveRetainedDesktopPublication(env: NodeJS.ProcessEnv, api: (path: string) => unknown,
readManifest = verifyRetainedDesktopRelease) {
const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).passthrough(),
const selection = z.object({ run: z.object({ id: z.number().int().positive(), run_attempt: z.number().int().positive() }).loose(),
jobs: z.array(z.unknown()), routes: z.unknown(), runnerName: z.string() }).parse(JSON.parse(env.DESKTOP_PACKAGE_SELECTION || '{}'))
if (!env.GITHUB_REPOSITORY || env.RUNNER_NAME !== selection.runnerName) throw new Error('desktop publish: task was dispatched to a different machine')
const manifest = await readManifest(desktopReleasesRoot(env), String(selection.run.id), String(selection.run.run_attempt))
@@ -52,7 +52,7 @@ export function retainedDesktopPublishApi(env: NodeJS.ProcessEnv): (path: string
signal: AbortSignal.timeout(60_000),
})
if (!response.ok) throw new Error(`desktop publish: GitHub verification request failed (HTTP ${response.status})`)
return response.json()
return response.json() as Promise<unknown>
}
}
@@ -1,8 +1,8 @@
import { Readable, Writable } from 'node:stream'
import type { ServerResponse } from 'node:http'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cosOperation } from '../scripts/cos-operation.ts'
import { createDesktopCos } from '../scripts/desktop-cos.ts'
import { cosOperation } from '@deepseek-ai/dsh-desktop-publisher/cos-operation.ts'
import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts'
import { answer, cosError, startCosLoopback, type CosLoopback } from './cos-loopback.ts'
const loopbacks: CosLoopback[] = []
@@ -7,7 +7,7 @@ import {
resolveDesktopAutoUpdateEnvironment,
resolveDesktopAutoUpdateTarget,
resolveDesktopUploadConfig,
} from '../scripts/desktop-auto-update-environment.mjs'
} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs'
const RELEASE_ID = '0123456789abcdef0123456789abcdef'
@@ -2,9 +2,9 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vitest'
import { selectDesktopPackage } from '../scripts/resolve-desktop-publish-ci.ts'
import { resolveRetainedDesktopPublication } from '../scripts/resolve-retained-desktop-publish-ci.ts'
import { retainDesktopRelease, verifyRetainedDesktopRelease } from '../scripts/desktop-release-store.ts'
import { selectDesktopPackage } from '../src/resolve-desktop-publish-ci.ts'
import { resolveRetainedDesktopPublication } from '@deepseek-ai/dsh-desktop-publisher/resolve-retained-desktop-publish-ci.ts'
import { retainDesktopRelease, verifyRetainedDesktopRelease } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts'
function fixture() {
const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), status: 'completed', conclusion: 'success',
@@ -2,8 +2,8 @@ import { spawnSync } from 'node:child_process'
import { fileURLToPath } from 'node:url'
import { expect, it } from 'vitest'
import { z } from 'zod'
import { DesktopCosOperationError, desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts'
import { DesktopPublishError } from '../scripts/desktop-publish.ts'
import { DesktopCosOperationError, desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts'
import { DesktopPublishError } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts'
it('preserves actionable validation and filesystem diagnostics', () => {
expect(desktopPublicationFailure(new DesktopPublishError('conflict', 'desktop publish: object differs: bin/app.exe'), 'upload'))
@@ -24,9 +24,10 @@ it('does not retain provider bodies, unknown messages, JSON input or invalid fie
expect(desktopPublicationFailure({ code: 'AccessDenied', statusCode: 403 }, 'upload').message).toContain('HTTP 403')
})
// These repository integration tests execute Desktop CLIs; the publisher runtime never imports them.
it('prints rollback usage through the real CLI before any audit or remote operation', () => {
const result = spawnSync(process.execPath, ['--import', 'tsx/esm',
fileURLToPath(new URL('../scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 })
fileURLToPath(new URL('../../desktop/scripts/rollback-desktop-channel.ts', import.meta.url))], { encoding: 'utf8', timeout: 30_000 })
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status).toBe(1)
@@ -47,7 +48,7 @@ it('omits malformed provider receipt fields and never copies raw errors into COS
it('prints structured archival failure through the real CLI', () => {
const result = spawnSync(process.execPath, ['--import', 'tsx/esm',
fileURLToPath(new URL('../scripts/archive-desktop-ci.ts', import.meta.url))], {
fileURLToPath(new URL('../../desktop/scripts/archive-desktop-ci.ts', import.meta.url))], {
encoding: 'utf8', timeout: 30_000, env: { ...process.env, DESKTOP_ARCHIVE_NAME: '', GITHUB_OUTPUT: '' },
})
expect(result.error).toBeUndefined()
@@ -57,7 +58,6 @@ it('prints structured archival failure through the real CLI', () => {
message: 'desktop archival: invalid ZIP output settings' })
})
it.each(['percentage cannot decrease; inspect the current rollout', 'feed changed before write; inspect and retry',
'written feed is unconfirmed; inspect before retrying'])('retains rollout recovery instructions: %s', (message) => {
expect(desktopPublicationFailure(new Error(`desktop rollout: ${message}`), 'desktop rollout'))
@@ -66,7 +66,7 @@ it.each(['percentage cannot decrease; inspect the current rollout', 'feed change
it.each([['check', 'extra'], ['route']])('prints actionable rollout CLI failures for %s', (...args) => {
const result = spawnSync(process.execPath, ['--import', 'tsx/esm',
fileURLToPath(new URL('../scripts/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], {
fileURLToPath(new URL('../src/publish-desktop-rollout-ci.ts', import.meta.url)), ...args], {
encoding: 'utf8', timeout: 30_000, env: { ...process.env, GITHUB_OUTPUT: '', GH_TOKEN: '' },
})
expect(result.error).toBeUndefined()
@@ -2,7 +2,7 @@ import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it } from 'vitest'
import { readDesktopPublishConfig, readDesktopUploadCredentials } from '../scripts/desktop-publish-config.ts'
import { readDesktopPublishConfig, readDesktopUploadCredentials, requireDesktopEdgeOneZoneId } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-config.ts'
it('reads public settings without opening the absent credential file and requires production App settings', async () => {
const root = await mkdtemp(join(tmpdir(), 'publish-config-'))
@@ -45,3 +45,21 @@ it('rejects multiline App outputs before writing Actions output fields', async (
}
} finally { await rm(root, { recursive: true, force: true }) }
})
it('validates optional EdgeOne settings and requires them only for website operations', async () => {
const root = await mkdtemp(join(tmpdir(), 'publish-zone-'))
try {
await mkdir(join(root, 'publishing'))
const config = { bucket: 'test-123', origin: 'https://example.com', credentialsFile: join(root, 'absent.json') }
const file = join(root, 'publishing/test.json')
await writeFile(file, JSON.stringify(config))
const selected = await readDesktopPublishConfig(root, 'test')
expect(() => requireDesktopEdgeOneZoneId(selected)).toThrow('edgeOneZoneId in publishing/production.json')
await writeFile(file, JSON.stringify({ ...config, edgeOneZoneId: 'zone-fixture' }))
expect(requireDesktopEdgeOneZoneId(await readDesktopPublishConfig(root, 'test'))).toBe('zone-fixture')
for (const edgeOneZoneId of ['', 'invalid', 'zone-example\n', 123]) {
await writeFile(file, JSON.stringify({ ...config, edgeOneZoneId }))
await expect(readDesktopPublishConfig(root, 'test')).rejects.toHaveProperty('issues.0.path', ['edgeOneZoneId'])
}
} finally { await rm(root, { recursive: true, force: true }) }
})
@@ -1,10 +1,10 @@
import { expect, it } from 'vitest'
import { createDesktopCos } from '../scripts/desktop-cos.ts'
import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts'
import { desktopArtifactDigest } from '../scripts/desktop-publish.ts'
import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts'
import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts'
import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts'
import { desktopArtifactDigest } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts'
import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts'
import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts'
it.each([true, false])('preserves download headers and verified bytes with overwrite prevention %s', async (forbidOverwrite) => {
const objects = new Map<string, Buffer>()
@@ -4,7 +4,7 @@ import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
import { expect, it } from 'vitest'
import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '../scripts/desktop-publish-record.ts'
import { createDesktopPublicationRecord, wasDesktopAttemptPublished, withDesktopChannelLock } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-record.ts'
it('excludes another process while a channel lock is held and admits it after release', async () => {
const root = await mkdtemp(join(tmpdir(), 'desktop-process-lock-'))
@@ -18,7 +18,7 @@ it('excludes another process while a channel lock is held and admits it after re
}
`
const contender = () => promisify(execFile)(process.execPath, ['--import', 'tsx/esm', '--input-type=module', '-e', script,
new URL('../scripts/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' })
new URL('../src/desktop-publish-record.ts', import.meta.url).href, root], { encoding: 'utf8' })
try {
await withDesktopChannelLock(root, 'bucket/mac', async () => {
expect((await contender()).stdout).toBe('locked')
@@ -1,5 +1,5 @@
import { expect, it } from 'vitest'
import { resolveDesktopPublishRoute } from '../scripts/desktop-publish-route.ts'
import { resolveDesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts'
function fixture() {
const run = { id: 42, run_attempt: 2, head_sha: 'a'.repeat(40), path: '.github/workflows/macos-package.yml',
@@ -1,7 +1,7 @@
import { createHash } from 'node:crypto'
import { expect, it } from 'vitest'
import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '../scripts/desktop-publish.ts'
import type { DesktopUploadPlan } from '../scripts/desktop-upload-plan.ts'
import { publishDesktopRelease, type DesktopPublishEvent, type DesktopPublishOperations, type DesktopRemoteObject } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish.ts'
import type { DesktopUploadPlan } from '../src/desktop-upload-types.ts'
function observed(contents: string): DesktopRemoteObject {
return { contents, size: Buffer.byteLength(contents), sha512: createHash('sha512').update(contents).digest('base64') }
@@ -127,3 +127,22 @@ it('classifies corrupted remote channel metadata separately from an invalid loca
await expect(publishDesktopRelease(f.plan, f.operations)).rejects.toMatchObject({ code: 'verification-failed' })
expect(f.writes).toEqual([])
})
it.each(['version: [private-feed', 'version: 42\n', 'version: invalid-private-version\n'])(
'rejects invalid channel metadata without exposing its contents: %s', async (contents) => {
for (const remote of [false, true]) {
const f = fixture()
const plan: DesktopUploadPlan = remote ? f.plan : {
...f.plan,
artifacts: f.plan.artifacts.map(artifact => artifact.channelMetadata ? { ...artifact, contents } : artifact),
}
if (remote) f.objects.set('feed/nightly.yml', observed(contents))
await expect(publishDesktopRelease(plan, f.operations)).rejects.toMatchObject({
code: remote ? 'verification-failed' : 'invalid-plan',
message: `desktop publish: invalid ${remote ? 'remote' : 'planned'} channel version`,
})
expect(f.writes).toEqual([])
expect(f.tags()).toBe(0)
}
},
)
@@ -1,6 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { desktopPublicationFailure } from '../scripts/desktop-publication-failure.ts'
import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '../scripts/desktop-purge-recovery.ts'
import { desktopPublicationFailure } from '@deepseek-ai/dsh-desktop-publisher/desktop-publication-failure.ts'
import { recoverDesktopPurge, type DesktopPurgeRecord, type DesktopPurgeRecoveryOptions } from '@deepseek-ai/dsh-desktop-publisher/desktop-purge-recovery.ts'
const config = { zoneId: 'zone-test', publicUrl: 'https://download.deepseek.com/desktop/test.dmg', secretId: 'secret-id', secretKey: 'secret-key' }
const submittedAt = '2026-10-30T00:00:00.000Z'
@@ -2,7 +2,7 @@ import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '../scripts/desktop-release-store.ts'
import { retainDesktopRelease, retainedDesktopPath, verifyRetainedDesktopRelease, type DesktopRetainedSource } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts'
const roots: string[] = []
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) })
@@ -3,12 +3,12 @@ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it } from 'vitest'
import { createDesktopCos } from '../scripts/desktop-cos.ts'
import { desktopPublishCos } from '../scripts/desktop-publish-cos.ts'
import { createDesktopCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts'
import { desktopPublishCos } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-cos.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '../scripts/desktop-website-installer.ts'
import type { DesktopRetainedManifest } from '../scripts/desktop-release-store.ts'
import type { DesktopPublishRoute } from '../scripts/desktop-publish-route.ts'
import { prepareWebsiteInstaller, uploadWebsiteInstaller } from '@deepseek-ai/dsh-desktop-publisher/desktop-website-installer.ts'
import type { DesktopRetainedManifest } from '@deepseek-ai/dsh-desktop-publisher/desktop-release-store.ts'
import type { DesktopPublishRoute } from '@deepseek-ai/dsh-desktop-publisher/desktop-publish-route.ts'
const roots: string[] = []
afterEach(async () => { await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true }))) })
@@ -0,0 +1,18 @@
/** Run only in a clean checkout after installing this workspace's production dependencies. */
import assert from 'node:assert/strict'
import { existsSync } from 'node:fs'
import { createRequire } from 'node:module'
import '../src/resolve-desktop-publish-ci.ts'
import { prepareDesktopRolloutCi } from '../src/publish-desktop-rollout-ci.ts'
import { desktopReleasesRoot } from '../src/desktop-releases-root.ts'
import { teo } from 'tencentcloud-sdk-nodejs-teo'
const require = createRequire(import.meta.url)
for (const dependency of ['electron', 'electron-builder', 'app-builder-lib', 'react', 'vite', 'typescript']) {
assert.throws(() => require.resolve(dependency), { code: 'MODULE_NOT_FOUND' }, `${dependency} must not be installed`)
}
assert.equal(existsSync(new URL('../../desktop/node_modules', import.meta.url)), false)
assert.equal(typeof teo.v20220901.Client, 'function')
assert.throws(() => desktopReleasesRoot({}), /DSH_PACKAGING_CONFIG_DIR is required/)
await assert.rejects(prepareDesktopRolloutCi({}), /runId/)
console.log('Desktop publisher isolated install: OK (no package build, credentials or remote operations)')
@@ -0,0 +1,32 @@
/** Exercise the pre-install entrypoints in a fixture with no workspace dependency links. */
import assert from 'node:assert/strict'
import { spawnSync } from 'node:child_process'
import { copyFile, mkdtemp, realpath, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
const directory = await realpath(await mkdtemp(join(tmpdir(), 'publisher-preinstall-')))
try {
for (const filename of ['preflight-desktop-publish.mjs', 'preflight-desktop-publish-local.mjs', 'desktop-publish-qualification.mjs']) {
await copyFile(new URL(`../src/${filename}`, import.meta.url), join(directory, filename))
}
const { preflightDesktopPublish } = await import(pathToFileURL(join(directory, 'preflight-desktop-publish.mjs')).href)
assert.equal(preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [] }]), '2')
assert.throws(() => preflightDesktopPublish('owner/repo', { package_run_id: '123', package_run_attempt: '2' }, () => [{ artifacts: [{ name: 'windows-x64-unsigned-123-2' }] }]), /unsigned/)
const env = { ...process.env }
for (const key of ['GITHUB_EVENT_PATH', 'GITHUB_REPOSITORY', 'GITHUB_OUTPUT', 'DSH_PACKAGING_CONFIG_DIR', 'NODE_OPTIONS']) Reflect.deleteProperty(env, key)
for (const [filename, diagnostic] of [
['preflight-desktop-publish.mjs', 'Actions context required'],
['preflight-desktop-publish-local.mjs', 'set DSH_PACKAGING_CONFIG_DIR'],
]) {
const result = spawnSync(process.execPath, [join(directory, filename)], { env, encoding: 'utf8', timeout: 10_000 })
assert.equal(result.error, undefined)
assert.equal(result.status, 1)
assert.ok(result.stderr.includes(diagnostic), result.stderr)
assert.ok(!result.stderr.includes('ERR_MODULE_NOT_FOUND'), result.stderr)
}
console.log('Desktop publisher pre-install entrypoints: OK')
} finally {
await rm(directory, { recursive: true, force: true })
}
@@ -3,15 +3,15 @@ import { mkdtemp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, expect, it, vi } from 'vitest'
import * as desktopCos from '../scripts/desktop-cos.ts'
import * as desktopCos from '@deepseek-ai/dsh-desktop-publisher/desktop-cos.ts'
import { answer, cosError, startCosLoopback } from './cos-loopback.ts'
import { teo } from 'tencentcloud-sdk-nodejs-teo'
import { publishWebsiteCi, websiteApproval } from '../scripts/publish-website-ci.ts'
import { publishWebsiteCi, websiteApproval } from '@deepseek-ai/dsh-desktop-publisher/publish-website-ci.ts'
vi.mock('node:timers/promises', () => ({ setTimeout: async () => {} }))
afterEach(() => vi.restoreAllMocks())
it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'put', 'uploaded', 'metadata', 'metadata-retry', 'stable', 'approval'] as const)('preserves publication recovery for %s', async (scenario) => {
it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'put', 'uploaded', 'metadata', 'metadata-retry', 'stable', 'approval', 'missing-zone'] as const)('preserves publication recovery for %s', async (scenario) => {
const root = await mkdtemp(join(tmpdir(), 'website-ci-'))
try {
const config = join(root, 'packaging')
@@ -22,7 +22,7 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
const credentialsFile = join(root, 'credentials.json')
await writeFile(credentialsFile, JSON.stringify({ secretId: 'fixture-id', secretKey: 'fixture-key' }))
await writeFile(join(config, 'publishing', 'production.json'), JSON.stringify({
bucket: 'production-123', origin: 'https://download.deepseek.com', credentialsFile,
edgeOneZoneId: scenario === 'missing-zone' ? undefined : 'zone-fixture', bucket: 'production-123', origin: 'https://download.deepseek.com', credentialsFile,
githubApp: { clientId: 'app', privateKeyFile: join(root, 'app.pem') },
}))
const route = { runId: '12', attempt: '1', commit: 'a'.repeat(40), sourceRef: 'master', channel: scenario === 'stable' ? 'stable' : 'nightly',
@@ -38,7 +38,15 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
if (scenario === 'metadata-retry') await writeFile(join(records, 'state.json'), JSON.stringify({ approval, upload: 'upload-intent', uploadConfirmed: true }))
const env = { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_OUTPUT: join(root, 'output') }
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-ignored', GITHUB_OUTPUT: join(root, 'output') }
if (scenario === 'missing-zone') {
await rm(credentialsFile)
for (const mode of ['upload', 'purge'] as const) {
await expect(publishWebsiteCi(mode, { ...env, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-legacy' }))
.rejects.toThrow('edgeOneZoneId in publishing/production.json')
}
return
}
if (scenario === 'upload' || scenario === 'put' || scenario === 'uploaded' || scenario === 'metadata' || scenario === 'metadata-retry' || scenario === 'stable' || scenario === 'approval') {
await writeFile(join(root, 'releases', '12', '1', manifest.files[0]!.name), 'x')
if (scenario === 'upload' || scenario === 'put') await rm(join(records, 'state.json'))
@@ -89,6 +97,7 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
vi.spyOn(teo.v20220901.Client.prototype, 'DescribePurgeTasks').mockRejectedValue(new Error('unavailable'))
await publishWebsiteCi('purge', env)
expect(submit).toHaveBeenCalledOnce()
expect(submit.mock.calls[0]?.[0]).toMatchObject({ ZoneId: 'zone-fixture' })
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ purge: { jobId: 'new-job' } })
}
}
@@ -111,8 +120,9 @@ it.each(['accepted', 'unconfirmed', 'incomplete', 'wrong-journal', 'upload', 'pu
const summary = join(root, 'summary.md')
await publishWebsiteCi('purge', { RUNNER_NAME: 'mini', GITHUB_REPOSITORY: 'owner/repo', GITHUB_RUN_ID: '99',
GITHUB_RUN_ATTEMPT: '1', DSH_PACKAGING_CONFIG_DIR: config, DESKTOP_PUBLISH_ROUTE: JSON.stringify(route),
DESKTOP_WEBSITE_APPROVAL: approval, DOWNLOAD_PROD_EO_ZONE_ID: 'zone-fixture', GITHUB_STEP_SUMMARY: summary })
DESKTOP_WEBSITE_APPROVAL: approval, GITHUB_STEP_SUMMARY: summary })
expect(submit).toHaveBeenCalledOnce()
expect(submit.mock.calls[0]?.[0]).toMatchObject({ ZoneId: 'zone-fixture' })
expect(query).toHaveBeenCalledTimes(2)
expect(output.mock.calls.map(call => String(call[0])).join('')).toContain('::warning title=官网缓存刷新结果未确认::')
expect(JSON.parse(await readFile(join(records, 'state.json'), 'utf8'))).toMatchObject({ upload: 'uploaded', purge: { status: 'unknown' } })
@@ -0,0 +1,56 @@
import { existsSync, readFileSync } from 'node:fs'
import { join, resolve, relative } from 'node:path'
import { load } from 'js-yaml'
import { z } from 'zod'
import { expect, it } from 'vitest'
const root = resolve(import.meta.dirname, '../../..')
const step = z.object({
uses: z.string().optional(), run: z.string().optional(),
'working-directory': z.string().optional(),
with: z.object({ path: z.string().optional() }).loose().optional(),
}).loose()
const workflowSchema = z.object({ jobs: z.record(z.string(), z.object({ steps: z.array(step) }).loose()) })
it('loads every rollout entry from its own installed package and the correct job checkout', () => {
const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows/desktop-rollout.yml'), 'utf8')))
for (const job of Object.values(workflow.jobs)) {
const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@'))
const checkoutRoot = resolve(root, checkout?.with?.path ?? '.')
const install = job.steps.find(entry => entry.run?.includes(' install '))
expect(install?.run).toContain('--filter @deepseek-ai/dsh-desktop-publisher --fail-if-no-match install --prod --frozen-lockfile --ignore-scripts')
for (const entry of job.steps) {
if (!entry.run?.startsWith('node --import tsx ')) continue
const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.'))
expect(directory).toBe(join('apps', 'desktop-publisher'))
const script = entry.run.split(' ')[3]!
expect(existsSync(resolve(root, directory, script))).toBe(true)
}
expect(job.steps.some(entry => entry.run?.includes('pnpm exec'))).toBe(false)
}
})
it.each(['desktop-rollout.yml', 'desktop-publish.yml'])('keeps %s preflights executable before install', (filename) => {
const workflow = workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8')))
let preflights = 0
for (const job of Object.values(workflow.jobs)) {
const checkout = job.steps.find(entry => entry.uses?.startsWith('actions/checkout@'))
const checkoutRoot = resolve(root, checkout?.with?.path ?? '.')
for (const [index, entry] of job.steps.entries()) {
if (!entry.run?.startsWith('node apps/desktop-publisher/src/preflight-')) continue
preflights++
const directory = relative(checkoutRoot, resolve(root, entry['working-directory'] ?? '.'))
expect(directory).toBe('')
expect(existsSync(resolve(root, entry.run.split(' ')[1]!))).toBe(true)
expect(index).toBeLessThan(job.steps.findIndex(candidate => candidate.run?.includes(' install ')))
}
}
expect(preflights).toBe(5)
})
it('separates rollout checkouts from full-workspace publication checkouts', () => {
const read = (filename: string) => workflowSchema.parse(load(readFileSync(resolve(root, '.github/workflows', filename), 'utf8')))
const paths = (filename: string) => Object.values(read(filename).jobs).flatMap(job => job.steps.flatMap(entry => entry.uses?.startsWith('actions/checkout@') && entry.with?.path ? [entry.with.path] : []))
const full = new Set(paths('desktop-publish.yml'))
for (const path of paths('desktop-rollout.yml')) expect(full.has(path)).toBe(false)
})
+8 -8
View File
@@ -15,8 +15,8 @@
en: 127ea90553cb6af7
zh: 7b1c5aec8558c684
/deepseek-harness-desktop/application-overview:
en: 37d36f8d57214336
zh: ceb50c0fa866eb24
en: 7414f87908fbffaf
zh: 8ff4fc1d83879c25
/deepseek-harness-desktop/terminal-command:
en: 5f2d25a1d8472647
zh: 2acb5c5d7d1917e2
@@ -27,8 +27,8 @@
en: 3724c53da4f7647b
zh: 76ae549d43c99bb4
/deepseek-harness-desktop/key-technical-decisions/bundled-workspace-dependencies:
en: 9eb34500d71cbc0a
zh: 90e6a98d4c2c0f14
en: 764bdc09fa8f5701
zh: da7897e14434b43c
/deepseek-harness-desktop/bundled-command-runtime:
en: 372297005b57a08b
zh: 074a635ac17e4362
@@ -51,11 +51,11 @@
en: 617a89aeb28131b9
zh: 4d84bd5d86501c86
/deepseek-harness-desktop/package:
en: ac31ebdd9de54f34
zh: 921e534d5c4b3a16
en: 7200a35dbed997c3
zh: 511d6961530757f1
/deepseek-harness-desktop/windows-installer-interface:
en: f1302ed4a3ab58bb
zh: cb53b9b349815028
en: 3a70021830865253
zh: 0467be8b505446cb
/deepseek-harness-desktop/updates:
en: 8b0b9efeb83727ef
zh: 5ee95de48ceab392
+9 -4
View File
@@ -37,7 +37,9 @@ Electron caches the last confirmed UI language in `userData/desktop/locale-cache
Desktop analytics follows the [product collection policy](../../packages/client/product-analytics/README.md), including its live application setting. Web usage is excluded. Update installation waits for its local analytics intake before locking API admission and stopping the Host. Intake has a one-second deadline; failure does not prevent installation, and collector delivery is not awaited.
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. Native Host requests send the current Host's authentication cookie explicitly, and no Electron session stores it; each Host start removes `dsh-auth-*` cookies that earlier releases left in the default session, because cookies ignore ports and would otherwise accompany every request to `127.0.0.1`.
The desktop application is an Electron shell around the complete dsh Web application. An Electron RunAsNode child starts the shared profile runner, and Electron immediately loads the packaged Web entry at `dsh-app://app/`. Its shared loading page waits for Host boot injections, then starts the client without navigating to another document. Electron forwards application HTTP requests to the authenticated Web Host, dropping connection-level response headers (`transfer-encoding`, `connection`, `keep-alive`) that describe the Node fetch rather than the resource, and marking plugin bundle responses `no-store` because their per-launch revisions would only accumulate in Chromium's disk cache; WebSocket streams connect to that Host with credentials attached only for the owned application window. Node IPC carries boot injections, readiness, and shutdown. Desktop listens on an OS-assigned port by default, so it cannot collide with Web’s `3080` or a reserved port; a `webserver.config.port` patch can override it. Native Host requests explicitly send the Desktop credential as a `dsh-desktop-session` Cookie header, and no Electron session stores it; each Host start removes `dsh-auth-*` cookies that earlier releases left in the default session, because cookies ignore ports and would otherwise accompany every request to `127.0.0.1`.
Electron generates a fresh random credential for each owned Host process. After the child's `starting` message, the main process sends it in a private `desktop-auth` IPC message. The Host creates an owner Peer and registers a Desktop authentication Provider before publishing its single `ready` message with the ordinary Host URL and that Peer's startup injections. Electron keeps the credential in main-process memory and attaches it to HTTP and WebSocket requests for that Host; the renderer receives boot data rather than the credential. Desktop proceeds directly after readiness, without the browser Token URL-to-Cookie exchange. While awaiting the credential, a shutdown request receives `shutdown-complete` and exits with status 0; parent disconnection exits with status 0 without starting the profile. Invalid or duplicate credential delivery remains an authentication failure.
Desktop binds `127.0.0.1`, the address Electron dials for the ready URL and the WebSocket credential filter. WebSocket streams use `ws:` or `wss:` according to the Host listener; credentials require matching authority and scheme.
@@ -49,7 +51,7 @@ Desktop ships one pnpm distribution at `resources/runtime/primary-runtime/depend
Embedded Platform documents use a persistent WebContentsView partition keyed by a hash of the Platform origin and stable account ID. localStorage preferences, including dismissed notices, survive view closure and application restart; different accounts and origins use separate storage. The Host supplies the account ID from its latest successful profile read; while no ID is known, the document opens in a disposable partition that keeps no preference across opens. Opening a persistent partition clears cookies, filesystem, IndexedDB, Cache Storage, the HTTP and shader caches, service workers, and HTTP authentication before the document loads; a disposable partition clears all of its storage. Closing a view destroys the document, removes its request interceptors, and schedules the same cleanup, so authentication left by an unclean exit is cleared before the next document loads. The next open and application shutdown await that cleanup, and an update install waits for it before the installer takes over the exit. A failed cleanup rejects that open and blocks the same account until a later cleanup succeeds; other accounts keep opening. Sign-out destroys the document but retains account-scoped preferences for the next sign-in. A document already open in a disposable partition stays mounted when the account ID arrives for the same credential; the next open uses the account-scoped partition. The [storage decision](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.md) describes the retention policy. Host sends account credentials through private Node IPC; account RPC and the Harness renderer receive no token. Before page scripts execute, the Platform preload performs one synchronous IPC to read the prepared main-process credential. It exposes displayMode, synchronous getAuthToken() and getLocale() getters, and onLocaleChange(listener), which returns an unsubscribe function. Both getters read preload memory without further IPC. The bootstrap includes the resolved Desktop language (`zh_CN` or `en_US`); Settings language changes update the preload cache and notify the open Platform document without reloading. Platform applies this language before its first render and does not persist it as a browser preference. The main-process handler performs only sender validation and an in-memory read; it never waits for Host, disk, or network. Trusted-page initialization failures retain embedded mode and make the getter throw, preventing browser-credential fallback. Only the owned Platform main frame on the configured issuer origin can initialize. Sign-out, credential replacement, Host shutdown, and view closure destroy the document. Cross-origin document navigation is blocked. HTTPS links requesting a new window open in the system browser without the embedded session or token; other schemes and URL credentials are rejected. Native views occupy the viewport below the Account feature’s return bar.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/credentials/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
Desktop Host Platform API requests and update-policy requests identify the installed client with the same Platform client headers: platform, client version, locale, timezone offset in seconds, and a bundle id that is intentionally empty. Account operations take the calling UI's identity per call; the account provider owns [API-only header configuration](../../packages/account/deepseek-account/README.md#use-this-package). Update policy additionally reports architecture, update channel, and bundled runtime version. The native account-state decoder accepts `no-response` sign-in failures and preserves the error code in the UI-safe projection.
A server-expired account credential returns to Welcome when no official API key is configured; an available API key keeps the workspace open. Explicit sign-out follows the same rule. Both Welcome and the workspace display the localized expiry notice.
@@ -101,6 +103,8 @@ The macOS PNG uses an inset rounded background for legacy ICNS packaging, with r
electron-builder copies only the manifest's `dependencies` into `app.asar/node_modules`, so the Electron main bundle `lib/main.js` inlines its workspace devDependencies and leaves `electron`, Node builtins, and those `dependencies` as its only bare imports; a sandboxed preload may leave only `electron`, `events`, `timers`, and `url`, the modules its `require` polyfill resolves. The main bundle resolves the inlined packages from their `lib/` output, so the root `build:lib:host` bundles `apps/desktop` after the concurrent workspace tsdown pass, and [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) fails any Desktop bundle whose static, dynamic, or `require()` import the packaged application cannot resolve. Without that check an import rolldown could not resolve ships as an external specifier and fails at launch with `ERR_MODULE_NOT_FOUND`. The [archived bundle-order decision](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md) records the alternatives.
The Electron main process declares `@deepseek-ai/dsh-error` as a production dependency to supply the required peer of `@deepseek-ai/dsh-typert-protocol`. The standalone command-management worker at `resources/runtime/cli/command-manager.js` has no adjacent `node_modules`, so its bundle inlines `@deepseek-ai/dsh-atomic-write` and `@deepseek-ai/dsh-error`.
Signed Windows packaging scans the primary runtime and application production dependencies for PE content, including files without a conventional extension. The final scan covers the entire unpacked application. Directory links, malformed `MZ` files and non-PE `.exe`, `.dll` or `.pyd` files stop packaging; data files beginning with `MZ` are also rejected unless they contain a valid PE header. It preserves valid vendor signatures and signs unsigned code before sealing runtime hashes or executing smoke checks. Public-key inspection uses batches of 32 files with at most four processes; hardware-token signing remains serial, and each new signature must match the configured certificate and carry a timestamp. Hardware signing and verification failures stop the run; isolated timestamp requests follow the [bounded retry policy](windows-signing/README.md#windows-ev-signing). Electron-builder preserves copied runtime executables only after signature and exact-byte verification. A final PE-signature audit and a fresh-cache ASAR payload and Host smoke must pass before the release completion record is written. Development, preparation-only and unsigned builds do not use the hardware token and can be blocked by Windows code-integrity policy; no build mode disables that policy. Passing smoke checks does not establish compatibility with every enterprise policy.
Desktop carries independent Python, Node.js and pnpm distributions. Python includes numpy, pandas, python-docx, python-pptx, openpyxl, Pillow, lxml and XlsxWriter with their complete dependencies. The `load_workspace_dependencies` tool installs this payload offline on first use under `$DSH_HOME/dsh-runtimes/dsh-primary-runtime` (normally `~/.dsh/dsh-runtimes/dsh-primary-runtime`) and returns absolute interpreter, pnpm script and library paths plus `pythonDistributions`, the bundled distribution names and versions. The version report excludes user-installed additions. Office tasks prefer these libraries unless user or workspace instructions select another environment. Execute the pnpm script with the returned Node executable. The returned Node library directory is reserved for bundled libraries, not pnpm's global installation directory.
@@ -121,7 +125,7 @@ The shared Desktop/SDK runtime builder omits directories named `tests` beneath N
| Runtime | The application must run without a system Node.js or pnpm installation. | dsh runs under Electron with `ELECTRON_RUN_AS_NODE=1` and `--expose-internals` and every package operation uses the bundled pnpm. Package-manager configuration and the Host environment follow the user's settings. Package scripts use a `node` shell launcher that forwards to Electron. |
| Package sources | Core installation at startup adds work even when offline. | `app.asar/dsh` carries a complete production dependency tree; the profile installs only external plugins. |
| State ownership | Sharing executable dependency graphs would let CLI and Desktop change each other's dsh, Cordis, plugin, or native-module versions, while two desktop processes could race on the same profile. | Electron acquires its process-lifetime single-instance lock before any profile access and exclusively owns `$DSH_HOME/profiles/desktop` plus its package-manager state. CLI and Desktop share supported product data under `$DSH_HOME`, but never executable packages, plugin activation, lockfiles, or `node_modules`. |
| Transport | Web serving and authentication share one implementation. | Electron loads packaged Web assets; the Host supplies boot injections and authenticated APIs. |
| Transport | Web and Desktop share request admission and Peer-based authorization. | Electron loads packaged Web assets; its private Desktop Provider authenticates native Host requests, and the Host supplies startup injections for that Peer. |
| Plugin changes | Desktop and Web need the same installation and activation behavior. | The main application uses the shared Web Plugin Manager and bundled pnpm. |
| Updates | Independent shell and dsh updates would recreate version splits, while unchanged shell blocks should not require a complete transfer. | The Electron shell, matching dsh runtime and pnpm form one signed update unit. Platform update artifacts may reuse unchanged blocks, but runtime version selection never splits from the Desktop release. |
@@ -245,6 +249,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner
- [Desktop packaging](packaging/README.md): local and Actions builds, versions, deployment settings, artifacts, logs and verification.
- [Windows signing and runner operations](windows-signing/README.md): machine setup, accepted isolation risks, signing credentials, token failures and cache maintenance.
- [Desktop publication](publishing/README.md): upload credentials, release identity, fixed downloads, update feeds and upload recovery.
- [Publisher workspace](../desktop-publisher/README.md): dependency ownership and isolated rollout installation.
<a id="windows-uninstall-rules"></a>
@@ -252,7 +257,7 @@ Use the dedicated guides for build and release operations. Shared Windows runner
## Windows installer interface
During a confirmed Windows update restart, a separate process displays a draggable status notice until the installation stage ends. The installer does not wait for this window; installation and relaunch continue if it cannot start or stops responding. A gap can remain before the new application window appears. Optional DPI APIs are resolved at runtime, with 96 DPI layout when unavailable.
During a confirmed Windows update restart, a separate process displays a draggable status notice until the installation stage ends. The status process starts in the Windows system directory so it cannot pin the installation directory during replacement. The installer does not wait for this window; installation and relaunch continue if it cannot start or stops responding. A gap can remain before the new application window appears. Optional DPI APIs are resolved at runtime, with 96 DPI layout when unavailable.
The Windows installer uses native NSIS pages with light and dark palettes, system shadows, an editable installation directory, and a finish page whose launch checkbox is selected by default. Installation is restricted to the current user. Clicking Install or pressing Enter validates the current path; drive roots remain invalid after normalization, including repeated trailing separators. New destinations must be empty, and nonempty destinations must be registered installations. Running executables at the affected installation path produce a native prompt and remain running; same-named applications in other directories do not block installation. Silent updates wait up to ten seconds for the affected application to exit, then stop with exit code 2 if it is still running.
+9 -4
View File
@@ -37,7 +37,9 @@ Electron 在 `userData/desktop/locale-cache` 缓存最近确认的界面语言
桌面埋点遵循[产品采集策略](../../packages/client/product-analytics/README.zh.md)及其动态应用配置,不包含 Web 使用情况。安装更新会等待该操作的本地埋点接收请求结束,再锁定 API 准入并停止 Host。接收请求的时限为一秒,失败不会阻止安装,也不等待收集端完成发送。
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。原生 Host 请求会显式发送当前 Host 的认证 Cookie,任何 Electron session 都不保存该 Cookie;每次启动 Host 时都会移除早期版本遗留在默认 session 中的 `dsh-auth-*` Cookie,因为 Cookie 不区分端口,否则这些 Cookie 会随每个发往 `127.0.0.1` 的请求一并发送。
桌面应用是完整 dsh Web 应用外的一层 Electron 壳。Electron RunAsNode 子进程启动共享 profile runner,Electron 立即从 `dsh-app://app/` 加载打包内的 Web 入口。共享加载页等待 Host 启动注入,然后在同一文档中启动客户端。Electron 将应用 HTTP 请求转发给已认证的 Web Host,转发时丢弃描述 Node fetch 连接而非资源本身的响应头(`transfer-encoding`、`connection`、`keep-alive`),并把插件 bundle 响应标记为 `no-store`,因为其每次启动都变化的 revision 只会在 Chromium 磁盘缓存中累积;WebSocket 流连接到该 Host,仅为归属的应用窗口附加凭据。Node IPC 承载启动注入、就绪与关闭。Desktop 默认监听系统分配的端口,因此不会与 Web 的 `3080` 或系统保留端口冲突;可通过 `webserver.config.port` patch 覆盖。原生 Host 请求通过 `dsh-desktop-session` Cookie 头显式发送 Desktop 凭据,任何 Electron session 都不保存它;每次启动 Host 时都会移除早期版本遗留在默认 session 中的 `dsh-auth-*` Cookie,因为 Cookie 不区分端口,否则这些 Cookie 会随每个发往 `127.0.0.1` 的请求一并发送。
Electron 为每个自行启动的 Host 进程生成新的随机凭据。收到子进程的 `starting` 消息后,主进程通过私有 `desktop-auth` IPC 消息交付凭据。Host 创建 owner Peer 并注册 Desktop 认证 Provider,然后发送唯一的 `ready` 消息,携带普通 Host URL 和该 Peer 的启动注入。Electron 将凭据保存在主进程内存中,为发往该 Host 的 HTTP 和 WebSocket 请求附加凭据;渲染进程只接收启动数据。Desktop 在就绪后直接继续启动,无需浏览器 Token URL 换 Cookie 的步骤。等待凭据期间收到 shutdown 时,Host 回复 `shutdown-complete` 并以状态0退出;父通道断开时以状态0退出,不启动 profile。非法或重复凭据交付仍作为认证失败处理。
Desktop 绑定 `127.0.0.1`,即 Electron 为就绪 URL 与 WebSocket 凭据过滤器拨号的地址。WebSocket 流按 Host 监听器使用 `ws:` 或 `wss:`;附加凭据要求 authority 与 scheme 均匹配。
@@ -49,7 +51,7 @@ Desktop 在 `resources/runtime/primary-runtime/dependencies/pnpm` 中携带一
Platform 内嵌文档使用持久化 WebContentsView 分区,分区名由 Platform 来源和稳定账号 ID 的哈希决定。localStorage 中的页面偏好(包括已关闭的通知)在关闭视图和重启应用后保留;不同账号和来源使用独立存储。账号 ID 来自 Host 最近一次成功的资料读取;尚无该 ID 时,文档在一次性分区中打开,该分区不跨次保留偏好。打开持久分区会先清理 Cookie、文件系统、IndexedDB、Cache Storage、HTTP 与着色器缓存、Service Worker 及 HTTP 认证状态;一次性分区则清理其全部存储。关闭视图会销毁文档、移除请求拦截器并安排相同的清理,因此异常退出遗留的认证会在下一个文档加载前被清除。下次打开和应用退出都会等待该清理完成,更新安装也会在安装器接管退出前等待。清理失败会使该次打开失败,并在后续清理成功前阻止同一账号打开;其他账号不受影响。退出登录会销毁文档,但保留账号偏好供下次登录使用。同一凭证下账号 ID 迟到时,已以一次性分区打开的文档保持挂载;下次打开使用账号分区。[存储决策](../../.agents/notes/implemented/architecture/2026-09-22-platform-browser-storage.zh.md)说明保留策略。Host 通过私有 Node IPC 发送账号凭证;账号 RPC 和 Harness 渲染进程不接收 token。Platform preload 在页面脚本执行前通过一次同步 IPC 读取主进程中已准备的凭证。它暴露 displayMode、同步的 getAuthToken() 和 getLocale() getter,以及返回取消订阅函数的 onLocaleChange(listener)。两个 getter 都只读取 preload 内存,不再调用 IPC。bootstrap 包含 Desktop 已解析的语言(`zh_CN` 或 `en_US`);Settings 语言变更会更新 preload 缓存并通知已打开的 Platform 文档,无需重载。Platform 在首屏渲染前应用该语言,且不将其持久化为浏览器偏好。主进程处理器仅校验调用来源并读取内存,不等待 Host、磁盘或网络。可信页面初始化失败时保留内嵌模式,由 getter 抛错,避免回退到浏览器凭证。只有受控 Platform 页面中、位于所配置签发来源的主 frame 能完成初始化。退登、凭证替换、Host 关闭及视图关闭都会销毁文档。跨来源文档导航被阻止。请求新窗口的 HTTPS 链接在系统浏览器中打开,不携带内嵌会话或 token;其他协议及带 URL 凭证的链接被拒绝。原生视图占据 Account 功能返回栏下方的视口。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/credentials/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
Desktop Host 的 Platform API 请求与更新策略请求用相同的 Platform 客户端请求头标识已安装客户端:平台、客户端版本、语言、以秒为单位的时区偏移,以及有意保持为空的 bundle id。账号操作按调用逐次传入调用界面的身份;账号 provider 管理[仅 API 使用的请求头配置](../../packages/account/deepseek-account/README.zh.md#use-this-package)。更新策略额外上报架构、更新通道和内置运行时版本。 原生账号状态解析器接受 `no-response` 登录失败,并在供 UI 使用的安全投影中保留该错误码。
账号凭据被服务端判定失效后,未配置官方 API key 时返回 Welcome;有可用 API key 时保持工作区打开。主动退出登录遵循相同规则。Welcome 和工作区均显示本地化的登录失效提示。
@@ -101,6 +103,8 @@ macOS PNG 使用带留白的圆角底板,供传统 ICNS 打包使用,包含
electron-builder 只把清单中的 `dependencies` 复制进 `app.asar/node_modules`,因此 Electron 主进程 bundle `lib/main.js` 内联其工作区 devDependencies,裸导入只剩 `electron`、Node 内置模块与这些 `dependencies`;沙箱 preload 只能留下 `electron`、`events`、`timers` 与 `url`,即其 `require` polyfill 能解析的模块。主进程 bundle 从被内联包的 `lib/` 产物解析它们,所以根 `build:lib:host` 在并发的工作区 tsdown 阶段之后才为 `apps/desktop` 打 bundle,并由 [`desktop-bundle-imports`](scripts/desktop-bundle-imports.mjs) 让任何静态、动态或 `require()` 导入无法在打包应用内解析的 Desktop bundle 直接失败。没有这项检查时,rolldown 无法解析的导入会作为外部说明符进入产物,并在启动时以 `ERR_MODULE_NOT_FOUND` 失败。[已归档的bundle 顺序决策](../../.agents/notes/archived/process/2026-09-22-desktop-main-bundle-after-workspace-tsdown.md)记录了备选方案。
Electron 主进程将 `@deepseek-ai/dsh-error` 声明为生产依赖,满足 `@deepseek-ai/dsh-typert-protocol` 必需的对等依赖(peer dependency)。独立命令管理 worker 位于 `resources/runtime/cli/command-manager.js`,其相邻位置没有 `node_modules`,因此 bundle 内联 `@deepseek-ai/dsh-atomic-write` 和 `@deepseek-ai/dsh-error`。
Windows 签名打包按 PE 文件内容扫描第一方运行时和应用生产依赖,包括没有常规扩展名的文件。最终扫描覆盖整个解包应用。目录链接、格式错误的 `MZ` 文件以及非 PE 的 `.exe`、`.dll` 或 `.pyd` 文件会使打包停止;以 `MZ` 开头的数据文件也会被拒绝,除非包含有效 PE 头。它保留有效的上游签名,并在记录运行时哈希或执行冒烟检查前为未签名代码补签。公钥验签每个进程处理最多 32 个文件,同时最多运行四个进程;硬件令牌签名仍串行执行,每个新签名必须匹配配置的证书且带时间戳。硬件签名或验签失败会停止本轮执行;独立的时间戳请求遵循[有界重试规则](windows-signing/README.zh.md#windows-ev-signing)。electron-builder 只有在验签和逐字节比对通过后,才保留复制后运行时可执行文件的签名。写入发布完成记录前,必须通过最终 PE 签名检查,以及使用全新缓存的 ASAR 载荷和 Host 冒烟检查。开发、仅准备和未签名构建不使用硬件令牌,可能被 Windows 代码完整性策略阻止;任何构建模式都不会关闭该策略。冒烟检查通过不代表兼容所有企业策略。
Desktop 携带独立的 Python、Node.js 和 pnpm 分发包。Python 包含 numpy、pandas、python-docx、python-pptx、openpyxl、Pillow、lxml、XlsxWriter 及其完整依赖。`load_workspace_dependencies` 工具首次使用时,将该产物离线安装到 `$DSH_HOME/dsh-runtimes/dsh-primary-runtime`(通常为 `~/.dsh/dsh-runtimes/dsh-primary-runtime`),并返回解释器、pnpm 脚本和库目录的绝对路径,以及记录内置分发包名称与版本的 `pythonDistributions`。版本报告不包含用户自行安装的包。Office 任务默认使用这些库,用户或工作区指令指定其他环境时遵循其要求。pnpm 脚本通过返回的 Node 可执行文件运行。返回的 Node 库目录为随包交付的库预留,不是 pnpm 的全局安装目录。
@@ -121,7 +125,7 @@ Desktop/SDK 共享运行时构建器在复制或签名产物前,裁剪 NumPy
| 运行时 | 应用必须能够在没有系统 Node.js 或 pnpm 的机器上运行。 | dsh 通过设置 `ELECTRON_RUN_AS_NODE=1` 和 `--expose-internals` 的 Electron 运行,所有包操作都使用内置 pnpm。包管理器配置和 Host 环境遵循用户设置。包脚本通过 `node` shell 启动器转发给 Electron。 |
| 包来源 | 即使离线,启动时安装核心依赖也会增加开销。 | `app.asar/dsh` 携带完整生产依赖树;profile 只安装外部插件。 |
| 状态归属 | 共享可执行依赖图会让 CLI(命令行界面)与 Desktop 相互改变 dsh、Cordis、插件或原生模块版本,而两个桌面进程还可能争用同一个 profile。 | Electron 在访问任何 profile 前获取进程生命周期单实例锁,并独占 `$DSH_HOME/profiles/desktop` 及其包管理器状态。CLI 与 Desktop 共享 `$DSH_HOME` 下受支持的产品数据,但绝不共享可执行包、插件激活、锁文件或 `node_modules`。 |
| 传输 | Web 服务与认证共享一套实现。 | Electron 加载打包的 Web 资源;Host 提供启动注入和经过认证的 API。 |
| 传输 | Web 与 Desktop 共享请求准入和基于 Peer 的授权。 | Electron 加载打包的 Web 资源;私有 Desktop Provider 认证原生 Host 请求,Host 提供该 Peer 的启动注入。 |
| 插件变更 | Desktop 与 Web 需要一致的安装和激活行为。 | 主应用使用共享 Web 插件管理器和内置 pnpm。 |
| 更新 | 桌面壳与 dsh 独立更新会重新产生版本分裂,而桌面壳未变化的数据块不应强制完整传输。 | Electron 壳、匹配的 dsh 运行时与 pnpm 组成一个已签名更新单元。平台更新产物可以复用未变化的数据块,但运行时版本选择绝不脱离 Desktop 发布。 |
@@ -245,6 +249,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否
- [Desktop 打包](packaging/README.zh.md):本地与 Actions 构建、版本、部署配置、产物、日志和验收。
- [Windows 签名与 runner 运维](windows-signing/README.zh.md):机器部署、已接受的隔离风险、签名凭据、Token 失败与缓存维护。
- [Desktop 发布](publishing/README.zh.md):上传凭据、发布标识、固定下载、更新清单和上传恢复。
- [发布工具 workspace](../desktop-publisher/README.zh.md):依赖归属与放量隔离安装。
<a id="windows-uninstall-rules"></a>
@@ -252,7 +257,7 @@ Desktop 在 Host 启动后、打开工作区前检查模型 API Key 引用是否
## Windows 安装界面
Windows 更新确认重启后,独立进程显示可拖动的状态提示,直到安装阶段结束。安装器不等待提示窗;提示窗无法启动或失去响应时,安装和重新启动仍会继续。新版应用窗口出现前仍可能有一段空白。可选的 DPI API 在运行时解析,不可用时采用 96 DPI 布局。
Windows 更新确认重启后,独立进程显示可拖动的状态提示,直到安装阶段结束。状态进程以 Windows 系统目录为工作目录,避免在替换期间占用安装目录。安装器不等待提示窗;提示窗无法启动或失去响应时,安装和重新启动仍会继续。新版应用窗口出现前仍可能有一段空白。可选的 DPI API 在运行时解析,不可用时采用 96 DPI 布局。
Windows 安装程序使用原生 NSIS 页面,提供亮暗配色、系统阴影、可编辑的安装目录,以及默认勾选立即启动的完成页。安装仅面向当前用户。点击安装或按 Enter 均校验当前路径;路径规范化后仍拒绝磁盘根目录,包括带重复末尾分隔符的写法。新安装位置必须为空,非空位置必须是已登记的安装目录。受影响安装路径中的程序运行时显示系统提示,并保持应用运行;其他目录中的同名应用不阻止安装。静默更新最多等待受影响应用退出十秒,若仍在运行则以退出码 2 结束。
@@ -1,5 +1,6 @@
{
"bucket": "replace-with-bucket-1250000000",
"edgeOneZoneId": "zone-replacewithproductionzone",
"origin": "https://download.deepseek.com",
"credentialsFile": "/absolute/path/to/packaging/secrets/cos-production.json",
"macOS": {
@@ -1,5 +1,6 @@
{
"bucket": "replace-with-bucket-1250000000",
"edgeOneZoneId": "zone-replacewithproductionzone",
"origin": "https://download.deepseek.com",
"credentialsFile": "C:/absolute/path/to/packaging/secrets/cos-production.json",
"windows": {
+4 -1
View File
@@ -8,6 +8,7 @@ namespace restart_status {
struct Launch {
std::wstring command;
std::wstring program;
std::wstring directory;
HANDLE job;
};
@@ -28,7 +29,7 @@ static DWORD WINAPI LaunchWorker(void* data) {
startup.lpAttributeList = attributes;
PROCESS_INFORMATION process{};
started = CreateProcessW(launch->program.c_str(), &launch->command[0], nullptr, nullptr, FALSE,
EXTENDED_STARTUPINFO_PRESENT, nullptr, nullptr, &startup.StartupInfo, &process) != FALSE;
EXTENDED_STARTUPINFO_PRESENT, nullptr, launch->directory.c_str(), &startup.StartupInfo, &process) != FALSE;
if (started) {
CloseHandle(process.hThread);
CloseHandle(process.hProcess);
@@ -61,6 +62,8 @@ extern "C" __declspec(dllexport) HANDLE __cdecl InstallerStartRestartStatus(LPCW
const UINT sysLength = GetSystemDirectoryW(system, ARRAYSIZE(system));
if (!length || length >= ARRAYSIZE(dll) || !sysLength || sysLength >= ARRAYSIZE(system)) return nullptr;
auto launch = std::make_unique<restart_status::Launch>();
// An inherited installation directory would prevent its rename while the status window is alive.
launch->directory = system;
launch->program = std::wstring(system) + L"\\rundll32.exe";
launch->command = L"\"" + launch->program + L"\" \"" + dll + L"\",ShowRestartStatus \"" +
installer + L"\" " + std::to_wstring(language) + L" " + theme + L" " + text;
+7 -2
View File
@@ -1,7 +1,7 @@
{
"name": "@deepseek-ai/dsh-desktop",
"description": "Electron desktop shell for a bundled dsh runtime and external plugins",
"version": "0.2.2-rc.2",
"version": "0.2.2-rc.3",
"private": true,
"license": "MIT",
"author": {
@@ -52,11 +52,15 @@
"semver": "^7.8.5",
"ws": "^8.21.3",
"@deepseek-ai/dsh-api-gateway": "workspace:*",
"@deepseek-ai/dsh-error": "workspace:*",
"@deepseek-ai/cordis": "workspace:~"
},
"devDependencies": {
"@deepseek-ai/dsh-brand": "workspace:*",
"@deepseek-ai/dsh-app-boot": "workspace:*",
"@deepseek-ai/dsh-client-connection": "workspace:*",
"@deepseek-ai/dsh-host-authentication-desktop": "workspace:*",
"@deepseek-ai/dsh-host-webserver": "workspace:*",
"@deepseek-ai/dsh-client-ui-settings-general": "workspace:*",
"@deepseek-ai/dsh-client-ui-sidebar-browser": "workspace:*",
"@deepseek-ai/dsh-home-paths": "workspace:*",
@@ -91,6 +95,7 @@
"zod": "4.6.6",
"@deepseek-ai/dsh-util-file-drag": "workspace:*",
"@deepseek-ai/dsh-client-ui-file-actions": "workspace:*",
"tencentcloud-sdk-nodejs-teo": "4.1.330"
"tencentcloud-sdk-nodejs-teo": "4.1.330",
"@deepseek-ai/dsh-desktop-publisher": "workspace:*"
}
}
+2 -2
View File
@@ -27,8 +27,8 @@
en: b39449c2f945cab9
zh: a742ba9efa282be8
/desktop-packaging/macos-self-hosted-packaging:
en: 08619f0e26782636
zh: 7c236cbe46be4a47
en: b7c6668f451d2e16
zh: d3125c2bb6cf8e7b
/desktop-packaging/unsigned-windows-test-installer:
en: f429bc0c280e2dfa
zh: 4adbcc9e906bdf80
Loaded 100 of 3267 files, more files were not shown because too many files have changed in this diff. Show more