mirror of
https://ghproxy.cflmy.top/https://github.com/deepseek-ai/deepseek-harness.git
synced 2026-12-01 17:49:35 +08:00
* feat(desktop): add shared texture transport and native presentation layers * fix(desktop): keep split fixtures and generated notices self-contained * refactor(theme): defer presentation stage token to Office layer * refactor(desktop): move frame integration into its consumer layer * refactor(sidebar-right): move native-layer visibility support to frame layer The fullscreen tab-body background and the tab visibility test only serve the frame integration that hides native layers through tab.visible, so they belong with that consumer layer. * refactor(desktop): keep shared textures on the renderer path * fix(desktop): settle shared textures across GPU loss and teardown * fix(desktop): correlate late texture arrivals and settlements by request * test(desktop): exercise late ingress delivery after presenter reset * fix(desktop): bound unsettled textures before handle export * fix(desktop): retain probe handles and invalidate unsynchronized imports * refactor(desktop): leave the fullscreen caption rule to frame forwarding The caption-menu fullscreen rule, its test, and the README sentences describe fullscreen that frame forwarding offers to plugins. They belong with frame forwarding, not the texture transport. * refactor(desktop): validate Host texture limits in the channel only The Host channel already shortens deadlines to 30 seconds and refuses dimensions above 8192 before Main's presenter sees a request, and it is the presenter's only caller. Remove the repeated checks from the presenter and assert the limits where they are enforced. * fix(desktop): drop only the surface that finds the ingress queue full A full delivery queue ended the macOS ingress reader, so a Main JavaScript thread that stalled for 16 surfaces failed every waiting presentation and left the Host without an endpoint until its next capability query. Release that one surface and keep reading; its presentation fails at the delivery deadline. A closing delivery function still ends the reader. * fix(desktop): reach Main through one process handle for Windows texture handles The Windows adapter opened Main by process identifier for every export, import, and reclamation. After Main exited, the Host's disconnect cleanup reclaimed each unsettled handle with DUPLICATE_CLOSE_SOURCE, which closes the source handle even when the call fails; an identifier reassigned by then named an unrelated process. Keep one handle to Main's process until the endpoint closes, refuse to reclaim without it, and leave duplicates to Main's exit after a disconnect. * feat(desktop): carry shared-texture frames on a native Host-Main channel Each frame was a Node IPC request from the Host's JavaScript thread, answered by a reply and a later notification on the same channel, with the macOS surface sent separately and paired in Main by token, and the Windows handle duplicated into Main by the Host through Koffi. The hop and ingress addons now form a two-way native channel on both platforms: a Mach port pair on macOS and a duplex message pipe on Windows. A frame's handle and description reach Main in one message, and Main returns the delivery reply and the settlement on the same channel. On Windows, Main verifies the pipe client's process and duplicates the Host's handle into its own process, so the Host opens no process and closes no remote handle. The Host IPC channel keeps only the capability and probe controls. A frame that finds Main's 32-frame delivery queue full is refused at once and stays reusable. When the channel is lost, the hop settles every unsettled frame as invalidated. The hop also exposes its connection to other Host addons as a C function table, which the sharedTexture claim returns from nativeSink, so a native producer can submit frames without the Host's JavaScript event loop. * refactor(desktop): drop unused parts of the shared-texture ingress Main never closed a handle inside the Host, never read a frame's delivery deadline, and waited for the Host's pipe connection only to cover the instant before the ingress registers it. Remove reclaimFromPeer, the timeoutMs field of the frame event, and the peer event with the probe's wait for it: a probe that arrives in that instant now fails with the export error. With frames as the only queued deliveries, the delivery function's own queue limit bounds them again. * refactor(desktop): submit shared-texture frames through the native sink only The Host had two entries for submitting a frame: the hop's JavaScript present, wrapped as SharedTextureService.present with promises fed by per-frame events, and the C sink for native addons. Frame forwarding, the only consumer, submits through the sink. Remove the JavaScript entry: the hop's present function and its delivered and settled events, the service's present with its frame, presented, and settlement types, and the wrapper's request table. The hop reports only the loss of a connection to JavaScript. The sink ABI and the wire format are unchanged. * feat(desktop): tell a refused shared-texture frame from a lost connection Every sink refusal returned 1, so a native consumer could not tell whether to keep its sink or replace it: a frame refused at the 128-request limit and a present after Main disappeared looked the same. present now returns DSH_SHARED_TEXTURE_PRESENT_OK (0) when the request left the Host, DSH_SHARED_TEXTURE_PRESENT_REJECTED (1) when only that frame was refused (invalid arguments or fields, the request limit, an identifier in use, or a failed send on a live connection), and DSH_SHARED_TEXTURE_PRESENT_DISCONNECTED (2) when the connection was closed or lost, including a send that found Main gone before the reader did. A sent request still returns 0 and settles through the reader when the connection ends during its send. * refactor(desktop)!: drop frame identifiers and the wire deadline from shared-texture presentation Each frame carried a Host-chosen identifier that the hop and Main both kept unique among unsettled frames, and a delivery deadline that Main never read. Frame forwarding tracks its own deliveries, so the identifiers only cost a string copy, a set lookup on each side, and an extra refusal reason. The sink ABI becomes version 2: dsh_shared_texture_frame_v2 drops id and id_len, and a consumer built for version 1 refuses the version 2 sink. DSTX becomes version 3: its present header drops timeout_ms and id_length and is followed by the metadata alone, and both sides refuse other versions and nonzero reserved fields. The hop still enforces each request's delivery deadline locally and still admits at most 128 unsettled requests; Main bounds admitted frames with a count instead of an identifier set. The native e2e labels frames through their metadata, proves that a timed-out request keeps its slot through the request limit, and forges version 2 and malformed version 3 headers. * refactor(desktop)!: read the Windows compositor adapter in Main To learn which adapter Chromium's compositor renders on, the Host asked Main for a probe texture, Main duplicated it into the Host and kept its own handle and hidden window until the Host released the probe, and the Host closed its duplicate after reading the adapter. The exchange needed the native connection to be open first, a probe table and late-reply cleanup on both sides, and two handle-transfer operations that nothing else used. Main now reads the adapter itself: the ingress addon reports the LUID of a Main-local shared texture through DXGI, formatted as "<HighPart>:<LowPart>" in unpadded lowercase hexadecimal, the text Host addons derive from an adapter LUID. Main exports one compositor texture, reads its adapter, and releases the texture and its window at once. The answer is kept for the GPU process generation, which a GPU process exit or Host teardown advances; concurrent queries share one probe, a probe that finds nothing or fails is not kept, a cleanup cancels a pending probe, and a probe that a GPU process exit overtook records nothing. SharedTextureService.probe becomes adapterLuid(timeoutMs), which resolves to that text or null, returns null outside Windows without asking Main, rejects when Desktop does not present shared textures, and no longer opens the native connection. The Host control requests are capabilities and adapter-luid; the probe and release-probe requests, the ingress exportToPeer, and the hop closeHandle are removed. * perf(desktop): block the macOS shared-texture ingress reader until a request or stop The macOS ingress reader woke every 100 ms to check for a stop request, so an idle Desktop woke the reader ten times a second and a close waited for the next wake-up. The reader now waits without a timeout. stop sets the flag and then sends an empty message to the ingress port through the send right Main already holds; a full queue already wakes the reader, so a wake-up that does not fit is dropped. Once stopped, the reader destroys whatever it receives, including its own wake-up, and Host requests still pass the audit-token check unchanged. * perf(desktop): trim per-frame work on the shared-texture path Every frame repeated work that only the first frame of a connection or no frame needs. On macOS each request carried a new send right to the Host's reply port, which Main merged and deallocated under a lock; the hop allocated and cleared a 4 KB message per request and the ingress cleared its whole receive buffer per message; the hop copied each frame's metadata into a string, and the Windows hop allocated a message vector; Main parsed every frame's metadata as JSON only to have Electron serialize the value again; and the product preload imported textures that no consumer would read. The first request of a macOS connection that reaches Main carries the reply port, and Main keeps it for that connection. Main drops the right when a reply cannot be delivered, as the Windows ingress disconnects the pipe, and the hop then receives a no-senders notification and settles every request as invalidated; Main discards requests that arrive on the dropped connection, and the endpoint serves the Host's next connection. Sends reuse a buffer per connection under the send lock and clear only the header fields and alignment padding, the ingress clears only the fixed message fields, and the hop passes metadata to the transport as a view of the caller's bytes. Main forwards the metadata text, and the product preload parses it before importing the texture. A transfer with metadata that is not JSON, or one that arrives while no consumer is registered, is refused before import, so the Host sees a failed delivery and a released settlement once Main drops its own reference. * fix(desktop): never import a handle from a closed Windows shared-texture connection A Windows request names its texture only by a handle value inside the Host, and Main duplicates it when its reader reaches the request. When the Host closed a connection itself, it settled every unsettled request as invalidated right after closing its pipe end, and the owner could then close the handle. A request still queued in the pipe stays readable after that close, so Main could duplicate a value that already named another object and present that texture as the settled frame. After duplicating, Main now checks that the Host's end of the pipe is still connected. The Host closes its end before it reports any settlement, so a duplicate taken while the end is open names the texture the request was sent with. Otherwise Main closes the duplicate and ends the connection, which discards the requests still queued; the endpoint then serves the Host's next connection. macOS needs no check because each request carries the IOSurface port itself. A Windows e2e suspends Main, presents a frame, closes the connection, and replaces the texture with one that takes over its handle value before resuming Main. Without the check Main delivered that frame with the replacement texture; with it Main delivers only the frames of open connections. * chore(desktop): state how long an ingress reply can block, and end a build script with a newline SharedTextureIngress.reply described a non-blocking queue, but it writes the reply on the calling thread and waits up to the 100 ms reply timeout while the Host is not reading. The comment now says so, together with the connection drop that follows a reply that cannot be written in time. native-package-builds.mjs ended without a newline. * fix(desktop): accept every enabled GPU compositing status in the adapter probe The probe required gpu_compositing to be exactly 'enabled', while support() accepts any 'enabled*' status, so adapterLuid returned null where capabilities reported support. Also type the e2e frame tuple to satisfy no-unsafe-return. * chore(desktop): end native-package-builds.d.mts with a newline * refactor(desktop)!: provide shared textures through the dsh-shared-texture plugin Desktop Host imported its shared-texture types from the private Electron application package, frame forwarding publishes declarations that referenced it, so an installed consumer could not resolve them, and renderer plugins read the texture bridge from globalThis.dshDesktop. @deepseek-ai/dsh-shared-texture (packages/shared-texture/shared-texture) is a Host and Client plugin package that owns the contract: - its Host root exports the abstract Cordis service SharedTexture, registered as ctx.sharedTexture and declaring only claim(), with the claim, capability, and native-sink types; its apply does nothing, because the Loader mounts the package only to deliver the Client half; - ./client is the Client plugin: where Desktop's product preload exposes dshDesktop.textures, it provides that bridge as the Client ctx.sharedTexture, typed SharedTextureBridge, and otherwise provides nothing; - ./bridge carries the type-only renderer SharedTextureBridge and SharedTextureLease; - ./protocol carries the type-only private control protocol between Desktop Main and the Desktop Host, including the hop addon types; it is not a plugin API. web-app mounts the package, so plugins inject ctx.sharedTexture instead of reading host globals. Desktop Host's SharedTexture extends the abstract Host service. Desktop Main and the Desktop Host take the low-frequency control message types from ./protocol and each still validates every message it receives at runtime, so Desktop Host no longer depends on Desktop. Desktop drops its ./shared-texture/host, ./shared-texture/client, and ./shared-texture/internal exports. The shared-texture subsystem page describes the entry points, and the capability-seam graph lists the service. * refactor(desktop): keep the shared-texture protocol in Desktop Host Main and the Desktop Host now share the child-process message types from `apps/desktop-host/src/types.ts`, imported as `@deepseek-ai/dsh-desktop-host/types`, so the published package no longer carries a private protocol subpath. The hop addon interfaces return to the Host module that is their only user. The renderer vocabulary keeps one Cordis-free module, renamed from `bridge` to `types`: `SharedTextureClientExport`, `SharedTextureHostExport`, and `SharedTextureLease`, imported by preload and IPC modules from `@deepseek-ai/dsh-shared-texture/types`. The module is required because the two compiler faces declare `ctx.sharedTexture` with different types: one program holding `src/index.ts` and `src/client/index.ts` fails with TS2717. --------- Co-authored-by: imccyu <276526105+imccyu@users.noreply.github.com>
572 lines
28 KiB
TypeScript
572 lines
28 KiB
TypeScript
/** Build one release target with matching Electron and dsh architecture. */
|
|
|
|
import { spawn } from 'node:child_process'
|
|
import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
|
|
import { parseArgs } from 'node:util'
|
|
import { join, resolve } from 'node:path'
|
|
import {
|
|
desktopBuildRecordFilename,
|
|
resolveDesktopAutoUpdateConfig,
|
|
} from '@deepseek-ai/dsh-desktop-publisher/desktop-auto-update-environment.mjs'
|
|
import { desktopArtifactOutput, desktopTargetBuildPaths } from './desktop-build-paths.mjs'
|
|
import { packageMacOSArtifacts, type DesktopPrepackagedArtifact } from './package-macos.ts'
|
|
import { loadDesktopPackageEnvironment, localMacOSPackageEnvironment, validateDesktopPackageEnvironment } from './desktop-package-environment.mjs'
|
|
import { createPackagingRun, recordPackagingEvent } from './packaging-run.mjs'
|
|
import { withWindowsSigningStage } from './windows-signing-stage.mjs'
|
|
import { prepareWindowsSignatureCacheDirectory, resolveWindowsSignatureCacheDirectory } from './windows-signature-cache-directory.mjs'
|
|
import { withMacOSSigningKeychain } from './macos-signing-keychain.mjs'
|
|
import { macOSDownloadEnvironment, resolveMacOSPackageSettings } from './macos-package-settings.mjs'
|
|
import { resolveWindowsPackageSettings } from './windows-package-settings.mjs'
|
|
import { packagingErrorDetails, packagingStep } from './packaging-step.mjs'
|
|
import { notarizeMacOS } from './notarize-macos.mjs'
|
|
import { resolveMacOSNotarizationEnvironment } from './desktop-release-environment.mjs'
|
|
import { DESKTOP_BUILD_VERSION_ENV, resolveDesktopBuildVersion, validateDesktopBuildVersion } from './desktop-build-version.mjs'
|
|
import { suggestDesktopBuildVersion } from './desktop-build-version-discovery.ts'
|
|
import { desktopBuildCommitEnvironment, readDesktopBuildCommit, resolveDesktopBuildCommit } from './desktop-build-commit.mjs'
|
|
import { requireDesktopToolchain } from './desktop-toolchain-preflight.ts'
|
|
import { withMacOSNotarizationProxy } from './macos-notarization-proxy.ts'
|
|
|
|
const APP_ROOT = resolve(import.meta.dirname, '..')
|
|
const REPOSITORY_ROOT = resolve(APP_ROOT, '..', '..')
|
|
const WINDOWS_SIGNING_ENV_PREFIX = 'DSH_DESKTOP_WINDOWS_'
|
|
const WINDOWS_SIGNING_ENV_NAMES = [
|
|
'DSH_DESKTOP_WINDOWS_CER_FILE',
|
|
'DSH_DESKTOP_WINDOWS_KEY_CONTAINER',
|
|
'DSH_DESKTOP_WINDOWS_SIGNTOOL',
|
|
'DSH_DESKTOP_WINDOWS_TOKEN_PIN',
|
|
'DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_DIR',
|
|
'DSH_DESKTOP_WINDOWS_SIGNATURE_CACHE_CONCURRENCY',
|
|
] as const
|
|
const DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES = new Set([
|
|
'DOWNLOAD_TEST_COS_SECRET_ID',
|
|
'DOWNLOAD_TEST_COS_SECRET_KEY',
|
|
'DOWNLOAD_PROD_COS_SECRET_ID',
|
|
'DOWNLOAD_PROD_COS_SECRET_KEY',
|
|
])
|
|
|
|
/** `--build-version` value that numbers a build after the ones already taken. */
|
|
const AUTOMATIC_BUILD_VERSION = 'auto'
|
|
|
|
/** Fixed platform and architecture identifiers exposed by package scripts. */
|
|
export type DesktopPackageTargetName = 'mac-arm64' | 'mac-x64' | 'win-x64'
|
|
|
|
/** One supported release target and its electron-builder selectors. */
|
|
export interface DesktopPackageTarget {
|
|
readonly name: DesktopPackageTargetName
|
|
readonly platform: 'darwin' | 'win32'
|
|
readonly arch: 'arm64' | 'x64'
|
|
readonly builderPlatform: '--mac' | '--win'
|
|
readonly builderArch: '--arm64' | '--x64'
|
|
}
|
|
|
|
const TARGETS: Record<DesktopPackageTargetName, DesktopPackageTarget> = {
|
|
'mac-arm64': {
|
|
name: 'mac-arm64',
|
|
platform: 'darwin',
|
|
arch: 'arm64',
|
|
builderPlatform: '--mac',
|
|
builderArch: '--arm64',
|
|
},
|
|
'mac-x64': {
|
|
name: 'mac-x64',
|
|
platform: 'darwin',
|
|
arch: 'x64',
|
|
builderPlatform: '--mac',
|
|
builderArch: '--x64',
|
|
},
|
|
'win-x64': {
|
|
name: 'win-x64',
|
|
platform: 'win32',
|
|
arch: 'x64',
|
|
builderPlatform: '--win',
|
|
builderArch: '--x64',
|
|
},
|
|
}
|
|
|
|
/**
|
|
* Remove Windows signing configuration from package preparation subprocesses.
|
|
* @param environment - Packaging command environment.
|
|
* @returns A copy without Windows signing fields.
|
|
*/
|
|
export function withoutWindowsSigningEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
return Object.fromEntries(Object.entries(environment)
|
|
.filter(([name]) => !name.startsWith(WINDOWS_SIGNING_ENV_PREFIX)))
|
|
}
|
|
|
|
/**
|
|
* Select signing mode and strip unsigned-build credentials for packaging subprocesses.
|
|
* @param environment - Target packaging environment.
|
|
* @param unsigned - Whether to create a local artifact without release signing or notarization.
|
|
* @returns Packaging environment without certificate inputs for unsigned builds.
|
|
*/
|
|
export function desktopElectronBuilderEnvironment(environment: NodeJS.ProcessEnv, unsigned: boolean): NodeJS.ProcessEnv {
|
|
const selected: NodeJS.ProcessEnv = { ...environment, DSH_DESKTOP_UNSIGNED: unsigned ? '1' : '0' }
|
|
// The bundled NSIS decoder cannot extract 7-Zip's automatic ARM64-filtered entries.
|
|
if (environment.DSH_DESKTOP_TARGET_PLATFORM === 'win32') selected.ELECTRON_BUILDER_7Z_FILTER = 'BCJ'
|
|
if (!unsigned) return selected
|
|
return {
|
|
...Object.fromEntries(Object.entries(withoutWindowsSigningEnvironment(selected))
|
|
.filter(([name]) => !/^(?:(?:WIN_)?CSC_|APPLE_|DSH_DESKTOP_MACOS_(?:SIGNING_|TEAM_ID$))/iu.test(name))),
|
|
CSC_IDENTITY_AUTO_DISCOVERY: 'false',
|
|
DSH_DESKTOP_UNSIGNED: '1',
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Remove upload-only COS credentials from every packaging subprocess.
|
|
* @param environment - Packaging command environment.
|
|
* @returns A copy without Desktop upload credentials.
|
|
*/
|
|
export function withoutDesktopUploadCredentials(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
|
return Object.fromEntries(Object.entries(environment)
|
|
.filter(([name]) => !DESKTOP_UPLOAD_CREDENTIAL_ENV_NAMES.has(name)))
|
|
}
|
|
|
|
function isTargetName(value: string): value is DesktopPackageTargetName {
|
|
return Object.hasOwn(TARGETS, value)
|
|
}
|
|
|
|
function packageVersion(path: string, label: string): string {
|
|
const manifest = JSON.parse(readFileSync(path, 'utf8')) as { version?: unknown }
|
|
if (typeof manifest.version !== 'string' || manifest.version === '') {
|
|
throw new Error(`desktop package: ${label} has no version`)
|
|
}
|
|
return manifest.version
|
|
}
|
|
|
|
function writeReleaseRecord(
|
|
target: DesktopPackageTarget,
|
|
environment: NodeJS.ProcessEnv,
|
|
artifactsRoot: string,
|
|
): void {
|
|
const desktopVersion = packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')
|
|
const dshVersion = packageVersion(join(REPOSITORY_ROOT, 'package.json'), 'dsh package')
|
|
if (desktopVersion !== dshVersion) {
|
|
throw new Error(`desktop package: desktop version ${desktopVersion} does not match dsh version ${dshVersion}`)
|
|
}
|
|
const buildVersion = resolveDesktopBuildVersion(environment, dshVersion)
|
|
const packaged = resolveDesktopBuildCommit(environment)
|
|
const update = resolveDesktopAutoUpdateConfig(environment, target.platform, target.arch)
|
|
const recordPath = join(artifactsRoot, desktopBuildRecordFilename(target.name))
|
|
const temporaryPath = `${recordPath}.tmp`
|
|
writeFileSync(temporaryPath, `${JSON.stringify({
|
|
schemaVersion: 1,
|
|
target: target.name,
|
|
version: buildVersion,
|
|
environment: update.environment,
|
|
channel: update.channel,
|
|
publicUrl: update.publicUrl,
|
|
// Upload reads this to tag the commit a production release was packaged from.
|
|
...packaged === undefined ? {} : { commit: packaged.commit, dirty: packaged.dirty },
|
|
}, null, 2)}\n`)
|
|
renameSync(temporaryPath, recordPath)
|
|
}
|
|
|
|
/**
|
|
* Resolve a named release target and reject hosts that cannot execute its packaged runtime.
|
|
* @param name - One of the fixed Desktop release target names.
|
|
* @param hostPlatform - Build-host Node.js platform.
|
|
* @param hostArch - Build-host Node.js architecture.
|
|
* @returns The target selectors shared by runtime preparation and electron-builder.
|
|
*/
|
|
export function resolveDesktopPackageTarget(
|
|
name: string,
|
|
hostPlatform: NodeJS.Platform = process.platform,
|
|
hostArch: string = process.arch,
|
|
): DesktopPackageTarget {
|
|
if (!isTargetName(name)) {
|
|
throw new Error(`desktop package: unsupported target ${JSON.stringify(name)}; expected ${Object.keys(TARGETS).join(', ')}`)
|
|
}
|
|
const target = TARGETS[name]
|
|
if (target.platform === 'win32' && (hostPlatform !== 'win32' || hostArch !== 'x64')) {
|
|
throw new Error('desktop package: win-x64 requires a Windows x64 build host')
|
|
}
|
|
if (target.platform === 'darwin' && hostPlatform !== 'darwin') {
|
|
throw new Error(`desktop package: ${name} requires a macOS build host`)
|
|
}
|
|
if (name === 'mac-arm64' && hostArch !== 'arm64') {
|
|
throw new Error('desktop package: mac-arm64 requires an Apple Silicon build host')
|
|
}
|
|
if (name === 'mac-x64' && hostArch !== 'arm64' && hostArch !== 'x64') {
|
|
throw new Error('desktop package: mac-x64 requires an Intel Mac or Apple Silicon with Rosetta')
|
|
}
|
|
return target
|
|
}
|
|
|
|
interface DesktopPackageInvocation {
|
|
readonly target: DesktopPackageTarget
|
|
readonly directory: boolean
|
|
readonly prepareOnly: boolean
|
|
readonly unsigned: boolean
|
|
readonly skipNotarization: boolean
|
|
readonly check: boolean
|
|
/** Build identifier to publish under, when this build does not publish the product version. */
|
|
readonly requestedBuildVersion: string | undefined
|
|
}
|
|
|
|
function hostTargetName(platform: NodeJS.Platform, arch: string): DesktopPackageTargetName {
|
|
const name = `${platform === 'darwin' ? 'mac' : platform === 'win32' ? 'win' : platform}-${arch}`
|
|
if (!isTargetName(name)) throw new Error(`desktop package: unsupported build host ${platform}-${arch}`)
|
|
return name
|
|
}
|
|
|
|
/**
|
|
* Parse the fixed-target packaging command line.
|
|
* @param argv - Arguments after the script entry point.
|
|
* @param hostPlatform - Build-host Node.js platform.
|
|
* @param hostArch - Build-host Node.js architecture.
|
|
* @returns The validated target and whether to emit an unpacked directory.
|
|
*/
|
|
export function parseDesktopPackageInvocation(
|
|
argv: readonly string[],
|
|
hostPlatform: NodeJS.Platform = process.platform,
|
|
hostArch: string = process.arch,
|
|
): DesktopPackageInvocation {
|
|
const { values, positionals } = parseArgs({
|
|
// `pnpm run <script> -- --build-version x` forwards the separator itself, and the script's own
|
|
// preset arguments come first, so it can land anywhere; parseArgs would read the rest as targets.
|
|
args: argv.filter(argument => argument !== '--'),
|
|
allowPositionals: true,
|
|
options: {
|
|
dir: { type: 'boolean', default: false },
|
|
'prepare-only': { type: 'boolean', default: false },
|
|
unsigned: { type: 'boolean', default: false },
|
|
'skip-notarization': { type: 'boolean', default: false },
|
|
check: { type: 'boolean', default: false },
|
|
'build-version': { type: 'string' },
|
|
},
|
|
})
|
|
if (positionals.length > 1) throw new Error('desktop package: expected at most one target')
|
|
const name = positionals[0] ?? hostTargetName(hostPlatform, hostArch)
|
|
if (values.unsigned && values['prepare-only']) throw new Error('desktop package: --unsigned cannot use --prepare-only')
|
|
if (values['skip-notarization'] && (name === 'win-x64' || values.unsigned || values['prepare-only'])) {
|
|
throw new Error('desktop package: --skip-notarization requires a signed macOS build, without --prepare-only')
|
|
}
|
|
const requestedBuildVersion = values['build-version']?.trim()
|
|
if (values['build-version'] !== undefined && (requestedBuildVersion === undefined || requestedBuildVersion === '')) {
|
|
throw new Error('desktop package: --build-version requires a value')
|
|
}
|
|
return {
|
|
target: resolveDesktopPackageTarget(name, hostPlatform, hostArch),
|
|
directory: values.dir,
|
|
prepareOnly: values['prepare-only'],
|
|
unsigned: values.unsigned,
|
|
skipNotarization: values['skip-notarization'],
|
|
check: values.check,
|
|
requestedBuildVersion,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Build the electron-builder command arguments for one validated target.
|
|
* @param target - Supported release target.
|
|
* @param directory - Whether to stop at an unpacked application directory.
|
|
* @param artifact - Optional single artifact built from an existing signed application.
|
|
* @returns Arguments that keep publishing under the separate validated upload command.
|
|
*/
|
|
export function desktopElectronBuilderArguments(
|
|
target: DesktopPackageTarget,
|
|
directory: boolean,
|
|
artifact?: DesktopPrepackagedArtifact,
|
|
): readonly string[] {
|
|
return [
|
|
'exec',
|
|
'electron-builder',
|
|
'--config',
|
|
'electron-builder.config.mjs',
|
|
target.builderPlatform,
|
|
...(artifact === undefined ? [] : [artifact.format]),
|
|
target.builderArch,
|
|
'--publish',
|
|
'never',
|
|
...(directory ? ['--dir'] : []),
|
|
...(artifact === undefined ? [] : [
|
|
...(target.platform === 'darwin' ? ['--config.mac.notarize=false'] : []),
|
|
'--prepackaged', artifact.appPath,
|
|
'--config.directories.output', artifact.output,
|
|
]),
|
|
]
|
|
}
|
|
|
|
function runPnpm(
|
|
args: readonly string[],
|
|
env: NodeJS.ProcessEnv = process.env,
|
|
cwd: string = APP_ROOT,
|
|
run?: ReturnType<typeof createPackagingRun>,
|
|
): Promise<void> {
|
|
const pnpmEntry = process.env.npm_execpath
|
|
if (pnpmEntry === undefined || pnpmEntry === '') {
|
|
throw new Error('desktop package: invoke this script through a pnpm package command')
|
|
}
|
|
if (run !== undefined) return run.run(args.join(' '), process.execPath, [pnpmEntry, ...args], { cwd, env })
|
|
return new Promise((resolvePromise, reject) => {
|
|
const child = spawn(process.execPath, [pnpmEntry, ...args], {
|
|
cwd,
|
|
env,
|
|
stdio: 'inherit',
|
|
})
|
|
child.once('error', reject)
|
|
child.once('close', (code, signal) => {
|
|
if (code === 0) resolvePromise()
|
|
else reject(new Error(`desktop package: pnpm ${args.join(' ')} exited with ${String(code ?? signal)}`))
|
|
})
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Resolve the version one run publishes from what its command line asked for.
|
|
* @param invocation - Validated packaging request.
|
|
* @param productVersion - Version the manifests declare.
|
|
* @param environment - Release settings, which name the bucket automatic numbering reads.
|
|
* @returns The product version, the requested version, or the next free index for today.
|
|
*/
|
|
async function resolveRequestedBuildVersion(
|
|
invocation: DesktopPackageInvocation,
|
|
productVersion: string,
|
|
environment: NodeJS.ProcessEnv,
|
|
): Promise<string> {
|
|
const requested = invocation.requestedBuildVersion
|
|
if (requested === undefined) return productVersion
|
|
if (requested !== AUTOMATIC_BUILD_VERSION) return validateDesktopBuildVersion(requested, productVersion)
|
|
const paths = desktopTargetBuildPaths(invocation.target.name, environment)
|
|
return suggestDesktopBuildVersion({
|
|
productVersion, target: invocation.target.name,
|
|
// Machine presets own packaging, not upload credentials; local auto numbering uses existing artifacts.
|
|
environment: environment.DSH_PACKAGING_PRESET === undefined ? environment : {},
|
|
// Unsigned builds land beside the signed output, so numbering has to read the directory this run writes.
|
|
artifactsRoot: desktopArtifactOutput(paths, invocation).directory,
|
|
})
|
|
}
|
|
|
|
async function main(): Promise<void> {
|
|
const invocation = parseDesktopPackageInvocation(process.argv.slice(2))
|
|
const { target } = invocation
|
|
if (invocation.skipNotarization) {
|
|
process.stdout.write('desktop package: skipping notarization and stapling; internal debugging only, not qualified for distribution or update publishing\n')
|
|
}
|
|
const environment = target.platform === 'darwin' && invocation.unsigned
|
|
? localMacOSPackageEnvironment()
|
|
: loadDesktopPackageEnvironment(target.platform, process.env, APP_ROOT, {
|
|
unsigned: invocation.unsigned, prepareOnly: invocation.prepareOnly,
|
|
})
|
|
const productVersion = packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')
|
|
// Release settings come from the selected configuration files, so the version this run publishes is an
|
|
// argument; the environment variable below only carries it to the child processes that build.
|
|
const buildVersion = await resolveRequestedBuildVersion(invocation, productVersion, environment)
|
|
environment[DESKTOP_BUILD_VERSION_ENV] = buildVersion
|
|
if (invocation.check) {
|
|
validateDesktopPackageEnvironment(environment, target, invocation)
|
|
await requireDesktopToolchain(target.platform, environment)
|
|
process.stdout.write(`desktop package: ${target.name} would publish ${buildVersion}; local configuration and toolchain valid, signing and notarization were not attempted\n`)
|
|
return
|
|
}
|
|
process.stdout.write(`desktop package: ${target.name} publishes ${buildVersion}${buildVersion === productVersion ? '' : ` for product version ${productVersion}`}\n`)
|
|
const packaged = readDesktopBuildCommit(REPOSITORY_ROOT)
|
|
Object.assign(environment, desktopBuildCommitEnvironment(packaged))
|
|
const secrets = Object.entries(environment).filter(([name]) => /KEY|SECRET|TOKEN|PASSWORD|APPLE_ID/iu.test(name)).map(([, value]) => value ?? '')
|
|
const run = createPackagingRun(join(APP_ROOT, '.desktop-build', 'packaging-runs'), {
|
|
target: target.name, unsigned: invocation.unsigned, skipNotarization: invocation.skipNotarization,
|
|
directory: invocation.directory, prepareOnly: invocation.prepareOnly,
|
|
version: buildVersion, productVersion, node: process.version,
|
|
commit: packaged.commit,
|
|
dirty: packaged.dirty,
|
|
}, { parallel: true, secrets })
|
|
console.log(`DESKTOP_PACKAGING_RECORD ${run.directory}`)
|
|
const previousDirectory = process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
|
|
process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = run.directory
|
|
let success = false
|
|
try {
|
|
await packagingStep(run.directory, 'configuration', async () => { validateDesktopPackageEnvironment(environment, target, invocation) }, secrets)
|
|
await packagingStep(run.directory, 'toolchain', () => requireDesktopToolchain(target.platform, environment), secrets)
|
|
if (target.platform === 'darwin') {
|
|
const settings = resolveMacOSPackageSettings(environment)
|
|
recordPackagingEvent(run.directory, { type: 'macos-settings', packConcurrency: settings.packConcurrency, zipCompressionLevel: settings.zipCompressionLevel,
|
|
downloadProxyConfigured: settings.downloadProxy !== undefined,
|
|
notarizationProxyConfigured: settings.notarizationProxy !== undefined })
|
|
await packagingStep(run.directory, 'macos-package', () => invocation.unsigned
|
|
? packageTarget(invocation, environment, run)
|
|
: withMacOSSigningKeychain(environment, signingEnvironment => packageTarget(invocation, signingEnvironment, run)), secrets)
|
|
} else {
|
|
await packagingStep(run.directory, 'windows-package', () => packageTarget(invocation, environment, run), secrets)
|
|
}
|
|
success = true
|
|
} catch (error) {
|
|
process.stderr.write(`${packagingErrorDetails(error, secrets)}\n`)
|
|
process.stderr.write(`desktop package: failed; see ${run.directory}/events.jsonl\n`)
|
|
process.exitCode = 1
|
|
} finally {
|
|
if (previousDirectory === undefined) delete process.env.DSH_DESKTOP_PACKAGING_RUN_DIR
|
|
else process.env.DSH_DESKTOP_PACKAGING_RUN_DIR = previousDirectory
|
|
run.finish(success)
|
|
}
|
|
if (success && target.platform === 'darwin' && !invocation.directory && !invocation.prepareOnly) {
|
|
const paths = desktopTargetBuildPaths(target.name, environment)
|
|
const output = desktopArtifactOutput(paths, invocation)
|
|
const filename = `deepseek-harness-${buildVersion}-mac-${target.arch}${output.suffix}.dmg`
|
|
console.log(`DMG: ${join(output.directory, filename)}`)
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Prepare one release only after its signing preflight, without publishing from the builder.
|
|
* @param invocation Validated host, target and packaging mode.
|
|
* @param environment File-owned release configuration.
|
|
* @param run Persistent stage supervisor; required for signed Windows packaging and enabled for all release commands.
|
|
* @returns Resolves after preparation or complete packaging; any failed stage prevents a release record.
|
|
*/
|
|
export async function packageTarget(
|
|
invocation: DesktopPackageInvocation,
|
|
environment: NodeJS.ProcessEnv,
|
|
run: ReturnType<typeof createPackagingRun> | undefined,
|
|
): Promise<void> {
|
|
const { target } = invocation
|
|
const execute = (args: readonly string[], env: NodeJS.ProcessEnv, cwd: string = APP_ROOT) => runPnpm(args, env, cwd, run)
|
|
const journal = target.platform === 'darwin' ? process.env.DSH_DESKTOP_PACKAGING_RUN_DIR : undefined
|
|
const proxyEvent = (status: string) => { if (journal) recordPackagingEvent(journal, { type: 'notarization-proxy', status }) }
|
|
const mac = target.platform === 'darwin' ? resolveMacOSPackageSettings(environment) : undefined
|
|
const packConcurrency = mac?.packConcurrency ?? resolveWindowsPackageSettings(environment).packConcurrency
|
|
const packArguments = ['--concurrency', String(packConcurrency)]
|
|
const buildPaths = desktopTargetBuildPaths(target.name, environment)
|
|
const releaseRecordPath = join(buildPaths.artifacts, desktopBuildRecordFilename(target.name))
|
|
if (!invocation.prepareOnly && !invocation.unsigned && !invocation.skipNotarization) {
|
|
rmSync(releaseRecordPath, { force: true })
|
|
rmSync(`${releaseRecordPath}.tmp`, { force: true })
|
|
}
|
|
const artifactsRoot = desktopArtifactOutput(buildPaths, invocation).directory
|
|
const buildEnv = withoutWindowsSigningEnvironment(withoutDesktopUploadCredentials(
|
|
desktopElectronBuilderEnvironment(environment, invocation.unsigned)))
|
|
const targetEnv: NodeJS.ProcessEnv = {
|
|
...buildEnv,
|
|
DSH_DESKTOP_MACOS_SKIP_NOTARIZATION: invocation.skipNotarization ? '1' : '0',
|
|
DSH_DESKTOP_TARGET_PLATFORM: target.platform,
|
|
DSH_DESKTOP_TARGET_ARCH: target.arch,
|
|
}
|
|
const downloadEnv = macOSDownloadEnvironment(targetEnv, mac?.downloadProxy)
|
|
const electronBuilderEnv = desktopElectronBuilderEnvironment(downloadEnv, invocation.unsigned)
|
|
if (target.platform === 'win32') {
|
|
electronBuilderEnv.ELECTRON_BUILDER_COMPRESSION_LEVEL = String(resolveWindowsPackageSettings(environment).compressionLevel)
|
|
}
|
|
for (const name of WINDOWS_SIGNING_ENV_NAMES) {
|
|
if (!invocation.unsigned && environment[name] !== undefined) electronBuilderEnv[name] = environment[name]
|
|
}
|
|
const signPrimaryRuntime = target.platform === 'win32' && !invocation.unsigned && !invocation.prepareOnly
|
|
const signedStage = async (stage: string, operation: () => Promise<void>): Promise<void> => {
|
|
if (!signPrimaryRuntime) return operation()
|
|
if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run')
|
|
const controller = new AbortController()
|
|
const interrupted = (): void => controller.abort()
|
|
const detach = (): void => {
|
|
process.removeListener('SIGINT', interrupted)
|
|
process.removeListener('SIGTERM', interrupted)
|
|
}
|
|
process.once('SIGINT', interrupted)
|
|
process.once('SIGTERM', interrupted)
|
|
try {
|
|
const options = { stage, signal: controller.signal, record: (event: object): void => recordPackagingEvent(run.directory, event) }
|
|
await withWindowsSigningStage(options, async () => {
|
|
detach()
|
|
await operation()
|
|
})
|
|
} finally { detach() }
|
|
}
|
|
if (signPrimaryRuntime) {
|
|
if (run === undefined) throw new Error('desktop package: signed Windows packaging requires a supervised run')
|
|
await signedStage('preflight', async () => {
|
|
await prepareWindowsSignatureCacheDirectory(resolveWindowsSignatureCacheDirectory(environment))
|
|
await run.run('preflight:windows-signing', process.execPath,
|
|
['--import', 'tsx/esm', join(APP_ROOT, 'scripts/windows-signing-preflight.ts')],
|
|
{ cwd: APP_ROOT, env: electronBuilderEnv, timeoutMs: 60_000 })
|
|
})
|
|
}
|
|
await execute(invocation.unsigned ? ['run', 'build', '--profile', 'local'] : ['run', 'build:official'], buildEnv, REPOSITORY_ROOT)
|
|
if (target.platform === 'darwin' || target.platform === 'win32') await execute(['run', 'build:native', '--arch', target.arch], buildEnv)
|
|
let preparationFailure: { error: unknown } | undefined
|
|
const executePreparation = async (args: readonly string[], env: NodeJS.ProcessEnv, cwd?: string): Promise<void> => {
|
|
if (preparationFailure !== undefined) throw preparationFailure.error
|
|
try { await execute(args, env, cwd) }
|
|
catch (error) { preparationFailure ??= { error }; throw error }
|
|
}
|
|
const pack = async (): Promise<void> => {
|
|
await executePreparation([
|
|
...(invocation.unsigned
|
|
? ['exec', 'tsx', 'apps/desktop/scripts/pack-local-packages.ts']
|
|
: ['run', 'release:pack', '--family', 'dsh']),
|
|
'--out', buildPaths.packedDsh, ...packArguments,
|
|
], buildEnv, REPOSITORY_ROOT)
|
|
await executePreparation([
|
|
'--dir',
|
|
'apps/desktop-host',
|
|
'pack',
|
|
'--pack-destination',
|
|
buildPaths.packedDsh,
|
|
], buildEnv, REPOSITORY_ROOT)
|
|
await executePreparation(['run', 'release:pack', '--family', 'vendor', '--out', buildPaths.packedVendor, ...packArguments], buildEnv, REPOSITORY_ROOT)
|
|
rmSync(buildPaths.packedLandlock, { recursive: true, force: true })
|
|
mkdirSync(buildPaths.packedLandlock, { recursive: true })
|
|
await executePreparation(['--dir', 'native/system', 'run', 'build:ts'], buildEnv, REPOSITORY_ROOT)
|
|
await executePreparation([
|
|
'--dir',
|
|
'native/system/packages/entry',
|
|
'pack',
|
|
'--pack-destination',
|
|
buildPaths.packedLandlock,
|
|
], buildEnv, REPOSITORY_ROOT)
|
|
}
|
|
const prepareRuntime = () => executePreparation(
|
|
['run', 'prepare:runtime', ...(signPrimaryRuntime ? ['--defer-primary-runtime-smoke'] : [])], downloadEnv)
|
|
if (target.platform === 'win32') {
|
|
const results = await Promise.allSettled([pack(), prepareRuntime()])
|
|
for (const result of results) if (result.status === 'rejected') throw result.reason
|
|
} else {
|
|
await pack()
|
|
await prepareRuntime()
|
|
}
|
|
if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime'], electronBuilderEnv)
|
|
await execute(['run', 'prepare:packages'], targetEnv)
|
|
await execute(['run', 'prepare:dsh', ...(signPrimaryRuntime ? ['--defer-runtime-smoke'] : [])], downloadEnv)
|
|
if (signPrimaryRuntime) await execute(['run', 'sign:primary-runtime', '--dsh'], electronBuilderEnv)
|
|
if (invocation.prepareOnly) return
|
|
const buildMacArtifact = (artifact: DesktopPrepackagedArtifact) => execute(
|
|
desktopElectronBuilderArguments(target, false, artifact), artifact.format === 'zip'
|
|
? { ...electronBuilderEnv, ELECTRON_BUILDER_COMPRESSION_LEVEL: String(mac?.zipCompressionLevel) }
|
|
: electronBuilderEnv)
|
|
if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization && !invocation.directory) {
|
|
await execute([
|
|
...desktopElectronBuilderArguments(target, true),
|
|
'--config.mac.notarize=false',
|
|
], electronBuilderEnv)
|
|
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
|
|
await withMacOSNotarizationProxy(mac?.notarizationProxy, () => packageMacOSArtifacts({
|
|
arch: target.arch,
|
|
// electron-builder named these artifacts after the published version, so locating them uses the same identifier.
|
|
version: resolveDesktopBuildVersion(environment, packageVersion(join(APP_ROOT, 'package.json'), 'desktop package')),
|
|
artifactsRoot: buildPaths.artifacts,
|
|
environment: electronBuilderEnv,
|
|
}, buildMacArtifact), undefined, undefined, proxyEvent)
|
|
} else if (target.platform === 'darwin' && !invocation.unsigned && !invocation.skipNotarization) {
|
|
await execute([...desktopElectronBuilderArguments(target, true), '--config.mac.notarize=false'], electronBuilderEnv)
|
|
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts'], targetEnv)
|
|
const appPath = join(buildPaths.artifacts, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app')
|
|
await withMacOSNotarizationProxy(mac?.notarizationProxy,
|
|
() => notarizeMacOS({ appPath, ...resolveMacOSNotarizationEnvironment(environment) }), undefined, undefined, proxyEvent)
|
|
} else {
|
|
if (target.platform === 'darwin' && invocation.skipNotarization && !invocation.directory) {
|
|
await execute(desktopElectronBuilderArguments(target, true), electronBuilderEnv)
|
|
const appPath = join(artifactsRoot, target.arch === 'arm64' ? 'mac-arm64' : 'mac', 'DeepSeek Harness.app')
|
|
for (const format of ['dmg', 'zip'] as const) {
|
|
await buildMacArtifact({ format, appPath, output: artifactsRoot })
|
|
}
|
|
} else {
|
|
await signedStage('artifacts', () => execute(desktopElectronBuilderArguments(target, invocation.directory), electronBuilderEnv))
|
|
}
|
|
await execute(['exec', 'tsx', 'scripts/smoke-packaged-runtime.ts',
|
|
...(invocation.unsigned ? ['--unsigned'] : []), ...(invocation.skipNotarization ? ['--skip-notarization'] : [])], targetEnv)
|
|
}
|
|
if (!invocation.directory && !invocation.unsigned && !invocation.skipNotarization) {
|
|
writeReleaseRecord(target, electronBuilderEnv, buildPaths.artifacts)
|
|
}
|
|
if (journal) recordPackagingEvent(journal, { type: 'artifacts', directory: artifactsRoot })
|
|
}
|
|
|
|
if (process.argv[1] !== undefined && import.meta.filename === resolve(process.argv[1])) await main()
|