Merge remote-tracking branch 'origin/feat/agent-terminal-panel-host' into feat/agent-terminal-panel-tools

This commit is contained in:
Yichen Jiang committed 2026-11-04 16:33:14 +08:00
commit cc8e860a34
2270 files changed
+49570 -14442

No files matched your search

+29 -10
View File
@@ -8,6 +8,7 @@ import {
isPublicExperimentalPackageDirectory,
PRIVATE_EXPERIMENTAL_PACKAGE_DIRECTORIES,
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS,
LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES,
} from './experimental-package-policy.ts'
import {
checkDshFamilyVersion,
@@ -22,8 +23,11 @@ import {
type WorkspaceManifest,
} from './check-workspace-constraints.ts'
const legacyManifests = LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES
.map(dir => ({ dir, manifest: { name: dir.replace('packages/experimental/', '@deepseek-ai/dsh-experimental-') } }))
const experimental = {
dir: 'packages/experimental/prototype',
dir: LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES[0]!,
manifest: {
name: '@deepseek-ai/dsh-experimental-prototype',
publishConfig: { access: 'public' },
@@ -118,36 +122,51 @@ describe('workspace manifest discovery', () => {
})
describe('experimental workspace constraints', () => {
it('requires the experimental package-name prefix', () => {
it('requires an unprefixed name to have a directory entry', () => {
expect(checkExperimentalManifest({
...experimental,
manifest: { ...experimental.manifest, name: '@deepseek-ai/dsh-prototype' },
})).toEqual([
'@deepseek-ai/dsh-prototype: experimental package name must start with "@deepseek-ai/dsh-experimental-" or match its declared directory exception',
'@deepseek-ai/dsh-prototype: experimental package name must be declared for this directory in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)',
])
})
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('retains %s only at its declared directory', (dir, name) => {
expect(checkExperimentalManifest({ dir, manifest: { name, publishConfig: { access: 'public' } } })).toEqual([])
expect(checkExperimentalManifest({ ...experimental, manifest: { ...experimental.manifest, name } }))
.toEqual([expect.stringContaining('declared directory exception')])
.toEqual([expect.stringContaining('declared for this directory')])
})
it('rejects a missing manifest name even when the directory has no exception', () => {
expect(checkExperimentalManifest({ ...experimental, manifest: { publishConfig: { access: 'public' } } }))
.toEqual([expect.stringContaining('experimental package name must start')])
it('rejects the legacy prefix outside the legacy directory list', () => {
expect(checkExperimentalManifest({ ...experimental, dir: 'packages/experimental/prototype' })).toEqual([
'@deepseek-ai/dsh-experimental-prototype: new experimental packages must not use the "@deepseek-ai/dsh-experimental-" prefix; name it @deepseek-ai/dsh-<name> and declare it in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)',
])
})
it('rejects stale, moved and duplicated retained-name declarations', () => {
it('rejects a missing manifest name', () => {
expect(checkExperimentalManifest({ dir: 'packages/experimental/prototype', manifest: { publishConfig: { access: 'public' } } }))
.toEqual(['packages/experimental/prototype: experimental package must declare a name'])
})
it('rejects stale, moved and duplicated unprefixed-name declarations', () => {
const manifests = Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS).map(([dir, name]) => ({ dir, manifest: { name } }))
expect(checkExperimentalNameExceptions(manifests)).toEqual([])
expect(checkExperimentalNameExceptions([...manifests, ...legacyManifests])).toEqual([])
const [first, ...rest] = manifests
for (const invalid of [
rest,
[{ ...first!, manifest: { name: '@deepseek-ai/dsh-experimental-replacement' } }, ...rest],
[{ ...first!, dir: 'packages/core/replacement' }, ...rest],
[...manifests, { ...first!, dir: 'packages/experimental/duplicate' }],
]) expect(checkExperimentalNameExceptions(invalid)).toEqual([expect.stringContaining(first!.manifest.name)])
]) expect(checkExperimentalNameExceptions([...invalid, ...legacyManifests])).toEqual([expect.stringContaining(first!.manifest.name)])
})
it('rejects a legacy directory without a prefixed package', () => {
const unprefixed = Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS).map(([dir, name]) => ({ dir, manifest: { name } }))
const others = legacyManifests.filter(entry => entry.dir !== experimental.dir)
for (const invalid of [others, [...others, { dir: experimental.dir, manifest: { name: '@deepseek-ai/dsh-renamed' } }]]) {
expect(checkExperimentalNameExceptions([...unprefixed, ...invalid]))
.toEqual([`${experimental.dir}: remove this directory from LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES; no package with the legacy prefix lives here`])
}
})
it.each(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('rejects retained runtime names and aliases: %s', (name) => {
+16 -5
View File
@@ -15,6 +15,7 @@ import {
hasExperimentalPackageReference,
EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS,
EXPERIMENTAL_PACKAGE_NAME_PREFIX,
LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES,
PRIVATE_EXPERIMENTAL_PACKAGE_DIRECTORIES,
} from './experimental-package-policy.ts'
import { hasTypertRemoteNavigation, isForbiddenPublicationFile } from './publication-payload.ts'
@@ -423,9 +424,14 @@ export function checkExperimentalManifest(
if (!experimentalPackageDirectory.test(dir)) return []
const label = manifest.name ?? dir
const errors: string[] = []
if (manifest.name === undefined || !manifest.name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX)
&& manifest.name !== EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS[dir]) {
errors.push(`${label}: experimental package name must start with ${JSON.stringify(EXPERIMENTAL_PACKAGE_NAME_PREFIX)} or match its declared directory exception`)
if (manifest.name === undefined) {
errors.push(`${label}: experimental package must declare a name`)
} else if (manifest.name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX)) {
if (!LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES.includes(dir)) {
errors.push(`${label}: new experimental packages must not use the ${JSON.stringify(EXPERIMENTAL_PACKAGE_NAME_PREFIX)} prefix; name it @deepseek-ai/dsh-<name> and declare it in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)`)
}
} else if (manifest.name !== EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS[dir]) {
errors.push(`${label}: experimental package name must be declared for this directory in EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS (scripts/experimental-package-policy.ts)`)
}
if (isPublicExperimentalPackageDirectory(dir, privateDirectories)) {
if (manifest.private === true) errors.push(`${label}: public experimental package must not set "private": true`)
@@ -440,7 +446,7 @@ export function checkExperimentalManifest(
}
/**
* Reject missing, renamed, moved, or duplicated retained-name exceptions.
* Reject missing, renamed, moved, or duplicated unprefixed-name declarations and stale legacy prefixed directories.
* @param manifests - every workspace manifest, with repository-relative directories.
* @returns Violations of the exact directory/name ownership declarations.
*/
@@ -449,7 +455,12 @@ export function checkExperimentalNameExceptions(manifests: readonly WorkspaceMan
for (const [dir, name] of Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS)) {
const owners = manifests.filter(entry => entry.manifest.name === name)
if (owners.length !== 1 || owners[0]?.dir !== dir) {
errors.push(`${dir}: retained experimental name ${name} must have exactly one workspace owner at this directory`)
errors.push(`${dir}: unprefixed experimental name ${name} must have exactly one workspace owner at this directory`)
}
}
for (const dir of LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES) {
if (!manifests.some(entry => entry.dir === dir && entry.manifest.name?.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) === true)) {
errors.push(`${dir}: remove this directory from LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES; no package with the legacy prefix lives here`)
}
}
return errors
+6
View File
@@ -481,6 +481,12 @@ describe('CI workflow', () => {
expect(windowsWorkflow.jobs['windows-observational']).toBeUndefined()
expect(windowsBuild['continue-on-error']).not.toBe(true)
const channelCheck = buildCommands.find(step => step.name === 'Verify Desktop updater dependency versions')
expect(channelCheck).toMatchObject({ shell: 'pwsh' })
expect(channelCheck?.['continue-on-error']).not.toBe(true)
expect(channelCheck?.run).toContain('node apps/desktop/tests/updates/electron-updater/check-versions.mjs')
expect(buildCommands.indexOf(channelCheck!))
.toBeGreaterThan(buildCommands.findIndex(step => step.run === 'pnpm run check:ci:windows-blocking'))
const observational = buildCommands.find(step => step.id === 'observational')
expect(observational).toMatchObject({
run: 'pnpm run check:ci:windows-observational-ready',
+119
View File
@@ -0,0 +1,119 @@
/** Tree mutation reports and detached patch inputs across the Loader/Include upgrade. */
import { Context, FiberState } from '@deepseek-ai/cordis'
import Loader, { Group, type EntryChange, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
import { applyEntryPatches } from '@deepseek-ai/cordis-plugin-include'
import { describe, expect, it, onTestFinished, vi } from 'vitest'
async function fixture() {
const ctx = new Context()
onTestFinished(() => ctx.fiber.dispose())
await ctx.plugin(Loader)
ctx.loader.builtins.group = Group
ctx.loader.builtins.example = () => {}
const changes: EntryChange[] = []
vi.spyOn(ctx.loader, 'commit').mockImplementation((change) => { changes.push(change) })
return { ctx, loader: ctx.loader, changes }
}
describe('Loader tree mutation reports', () => {
it('reports assigned ids and applied options for create, update, move and remove', async () => {
const { loader, changes } = await fixture()
const id = await loader.create({ name: 'cordis:example', config: { value: 1 } })
await loader.await()
expect(changes).toHaveLength(1)
expect(changes[0]).toEqual({ id, group: loader.root, options: loader.resolve(id).options })
expect(id).not.toBe('')
const groupId = await loader.create({ name: 'cordis:group', group: true, config: [] })
await loader.await()
changes.length = 0
await loader.update(id, { config: { value: 2 } }, groupId)
expect(changes).toHaveLength(1)
expect(changes[0]).toMatchObject({ id, from: loader.root, group: loader.resolveGroup(groupId),
legacy: { config: { value: 1 } }, options: { config: { value: 2 } } })
expect(changes[0]!.options).toBe(loader.resolve(id).options)
changes.length = 0
await loader.update(id, { config: { value: 3 } })
expect(changes).toHaveLength(1)
expect(changes[0]!.from).toBeUndefined()
changes.length = 0
const legacy = loader.resolve(id).options
loader.remove(id)
await loader.await()
expect(changes).toEqual([{ id, group: loader.resolveGroup(groupId), legacy }])
expect(legacy.disabled).toBeUndefined()
})
it('reports explicit Fiber saves and self-disposal but ignores child disposal', async () => {
const { loader, changes } = await fixture()
const id = await loader.create({ name: 'cordis:example', config: { value: 1 } })
await loader.await()
const fiber = loader.resolve(id).fiber!
changes.length = 0
await fiber.update({ value: 2 })
expect(changes).toHaveLength(1)
expect(changes[0]).toMatchObject({ legacy: { config: { value: 1 } }, options: { config: { value: 2 } } })
changes.length = 0
const child = fiber.ctx.plugin(() => {})
await child
await child.dispose()
expect(changes).toEqual([])
await fiber.dispose()
expect(changes).toHaveLength(1)
expect(changes[0]!.options!.disabled).toBe(true)
expect(changes[0]!.legacy!.disabled).toBeUndefined()
})
it('keeps adopted entries and does not report file-driven removal or owner teardown', async () => {
const { ctx, loader, changes } = await fixture()
await loader.root.update([
{ id: 'g', name: 'cordis:group', group: true, config: [] },
{ id: 'x', name: 'cordis:example' },
])
await loader.await()
const target = loader.resolveGroup('g')
const options = loader.resolve('x').options
target.data.push(options)
await target.create(options)
loader.root.remove('x')
expect(loader.resolve('x').parent).toBe(target)
expect(loader.resolve('x').fiber!.state).toBe(FiberState.ACTIVE)
await target.update([])
await loader.await()
expect(loader.store.x).toBeUndefined()
expect(changes).toEqual([])
await ctx.fiber.dispose()
expect(changes).toEqual([])
})
it('mounts explicit ids containing the separator without nested-path resolution', async () => {
const { loader, changes } = await fixture()
const options: EntryOptions = { id: 'a:b', name: 'cordis:example' }
await expect(loader.create(options)).resolves.toBe('a:b')
await loader.await()
expect(loader.store['a:b']!.fiber!.state).toBe(FiberState.ACTIVE)
expect(changes).toEqual([{ id: 'a:b', group: loader.root, options }])
expect(() => loader.resolve('a:b')).toThrow('cannot resolve entry a:b')
})
})
describe('Include patch data ownership', () => {
it('detaches file entries even with no patches', () => {
const data: EntryOptions[] = [{ id: 'x', name: 'example', config: { value: 1 } }]
const result = applyEntryPatches(data, undefined, vi.fn())
result[0]!.disabled = true
;(result[0]!.config as { value: number }).value = 2
expect(data).toEqual([{ id: 'x', name: 'example', config: { value: 1 } }])
})
it('clones inserted groups and lets later patches address their descendants', () => {
const insert: EntryOptions[] = [{ id: 'g', name: 'group', group: true,
config: [{ id: 'x', name: 'example', config: { value: 1 } }] }]
const warn = vi.fn()
const result = applyEntryPatches([], [{ insert }, { id: 'x', disabled: true }], warn)
const children = result[0]!.config as Array<{ disabled?: boolean; config: { value: number } }>
expect(children[0]!.disabled).toBe(true)
children[0]!.config.value = 2
expect(insert[0]!.config).toEqual([{ id: 'x', name: 'example', config: { value: 1 } }])
expect(warn).not.toHaveBeenCalled()
})
})
+204
View File
@@ -0,0 +1,204 @@
/** File reconciliation and persistence results through real Loader entries. */
import { chmod, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Context, FiberState } from '@deepseek-ai/cordis'
import Loader, { Group, type EntryOptions } from '@deepseek-ai/cordis-plugin-loader'
import Include from '@deepseek-ai/cordis-plugin-include'
import { expect, it, onTestFinished, vi } from 'vitest'
const row = (id: string, value: number): EntryOptions => ({ id, name: 'cordis:example', config: { value } })
// File rows may omit ids; Include assigns them.
async function fixture(data: Array<Omit<EntryOptions, 'id'> & { id?: string }>) {
const dir = await mkdtemp(join(tmpdir(), 'dsh-include-journal-'))
const ctx = new Context()
onTestFinished(async () => {
await ctx.fiber.dispose()
await rm(dir, { recursive: true, force: true, maxRetries: 3 })
})
ctx.baseUrl = pathToFileURL(dir).href + '/'
await ctx.plugin(Loader)
ctx.loader.builtins.include = Include
ctx.loader.builtins.group = Group
ctx.loader.builtins.example = () => {}
const filename = join(dir, 'root.json')
await writeFile(filename, JSON.stringify(data))
const id = await ctx.loader.create({ name: 'cordis:include', config: { path: './root.json' } })
await ctx.loader.await()
const include = ctx.loader.resolve(id).subtree as Include
const read = async () => JSON.parse(await readFile(filename, 'utf8')) as EntryOptions[]
const edit = (entries: EntryOptions[]) => writeFile(filename, JSON.stringify(entries))
const update = (id: string, value: number) => include.update(id, { config: { value } })
const value = (id: string) => (include.store[id]!.fiber!.effectiveConfig as { value: number }).value
return { ctx, dir, filename, id, include, read, edit, update, value }
}
it.each(['refresh-first', 'update-first'] as const)('merges independent file and runtime edits with %s ordering', async (order) => {
const app = await fixture([row('a', 1), row('b', 1)])
await app.edit([row('a', 1), row('b', 3)])
if (order === 'refresh-first') await Promise.all([app.include.refresh(), app.update('a', 2)])
else await Promise.all([app.update('a', 2), app.include.refresh()])
await app.include.flush()
expect(app.value('a')).toBe(2)
expect(app.value('b')).toBe(3)
expect(await app.read()).toEqual([row('a', 2), row('b', 3)])
})
it('lets the file win a conflicting config edit and reports the conflict', async () => {
const app = await fixture([row('a', 1)])
const error = vi.spyOn(app.include.ctx.logger, 'error')
await app.edit([row('a', 3)])
await app.update('a', 2)
await app.include.flush()
expect(app.value('a')).toBe(3)
expect(await app.read()).toEqual([row('a', 3)])
expect(error.mock.calls.some(([message]) => String(message).includes('config conflict'))).toBe(true)
})
it('retains unsaved edits across a missing or invalid file and clears failure after recovery', async () => {
const app = await fixture([row('a', 1)])
await rm(app.filename)
await app.update('a', 2)
await expect(app.include.flush()).rejects.toThrow('unsaved change')
await expect(readFile(app.filename)).rejects.toMatchObject({ code: 'ENOENT' })
expect(app.value('a')).toBe(2)
await writeFile(app.filename, '{')
await expect(app.include.refresh()).rejects.toThrow('failed to parse')
expect(await readFile(app.filename, 'utf8')).toBe('{')
await app.edit([row('a', 1), row('b', 1)])
await app.include.refresh()
await expect(app.include.flush()).resolves.toBeUndefined()
expect(await app.read()).toEqual([row('a', 2), row('b', 1)])
})
it('routes patch-owned fields and inserted rows into the parent file', async () => {
const app = await fixture([])
const inner = join(app.dir, 'inner.json')
const original = JSON.stringify([row('a', 1)])
await writeFile(inner, original)
const id = await app.include.create({ name: 'cordis:include', config: {
path: './inner.json', patches: [{ id: 'a', disabled: true }, { insert: [row('b', 1)] }],
} })
await app.ctx.loader.await()
const child = app.ctx.loader.resolve(id).subtree as Include
await child.update('a', { disabled: false })
await child.update('b', { config: { value: 2 } })
await child.flush()
await app.include.flush()
expect(await readFile(inner, 'utf8')).toBe(original)
expect((await app.read())[0]!.config).toEqual({ path: './inner.json', patches: [
{ id: 'a', disabled: false }, { insert: [row('b', 2)] },
] })
expect(child.store.a!.fiber!.effectiveConfig).toEqual({ value: 1 })
expect(child.store.b!.fiber!.effectiveConfig).toEqual({ value: 2 })
})
// Windows does not implement POSIX write permission bits.
it.skipIf(process.platform === 'win32')('retains read-only file changes until a writable retry succeeds', async () => {
const app = await fixture([row('a', 1)])
try {
await chmod(app.filename, 0o444)
await app.update('a', 2)
await expect(app.include.flush()).rejects.toThrow('unsaved change')
expect(await app.read()).toEqual([row('a', 1)])
expect(app.value('a')).toBe(2)
} finally {
await chmod(app.filename, 0o644)
}
await app.include.flush()
expect(await app.read()).toEqual([row('a', 2)])
})
it('preserves file text on file-driven removal and drains runtime edits before shutdown', async () => {
const app = await fixture([row('a', 1), row('b', 1)])
const edited = JSON.stringify([row('a', 1)], null, 4) + '\n'
await writeFile(app.filename, edited)
await app.include.refresh()
expect(app.include.store.b).toBeUndefined()
expect(await readFile(app.filename, 'utf8')).toBe(edited)
await app.update('a', 2)
await app.include.stop()
expect(await app.read()).toEqual([row('a', 2)])
})
it('keeps persisted runtime edits when the Include config changes', async () => {
const app = await fixture([row('a', 1)])
await app.include.update('a', { disabled: true })
await app.include.flush()
await app.ctx.loader.update(app.id, { config: { path: './root.json', enableLogs: true } })
await app.include.flush()
expect(app.include.store.a!.fiber?.state).not.toBe(FiberState.ACTIVE)
expect(await app.read()).toEqual([{ ...row('a', 1), disabled: true }])
})
it('keeps generated ids and fibers for anonymous file and inserted rows across updates', async () => {
const app = await fixture([{ name: 'cordis:example', config: { value: 1 } }])
const config = { path: './root.json', patches: [{ insert: [{ name: 'cordis:example', config: { value: 2 } }] }] }
await app.ctx.loader.update(app.id, { config })
await app.include.flush()
const fibers = () => Object.values(app.include.store).map(entry => entry.fiber)
const before = fibers()
expect(before).toHaveLength(2)
await app.ctx.loader.update(app.id, { config: { ...config, enableLogs: true } })
await app.include.flush()
await app.include.refresh()
expect(fibers()).toEqual(before)
expect(fibers().every((fiber, index) => fiber === before[index])).toBe(true)
})
it('persists a row moved into the Include from another tree as a complete creation', async () => {
const app = await fixture([{ id: 'g', name: 'cordis:group', group: true, config: [] }])
const apply = vi.fn()
app.ctx.loader.builtins.counted = apply
const id = await app.ctx.loader.create({ name: 'cordis:counted', config: { value: 1 } })
await app.ctx.loader.await()
const entry = app.ctx.loader.store[id]!
await app.ctx.loader.update(id, { config: { value: 2 } }, `${app.id}:g`)
await app.include.flush()
await app.ctx.loader.await()
expect(app.include.store[id] === entry).toBe(true)
expect(id in app.ctx.loader.store).toBe(false)
expect(apply).toHaveBeenCalledTimes(2)
expect(entry.fiber!.state).toBe(FiberState.ACTIVE)
expect(await app.read()).toEqual([{ id: 'g', name: 'cordis:group', group: true, config: [
{ id, name: 'cordis:counted', config: { value: 2 } },
] }])
})
it('rejects a cross-tree move onto an id the destination already holds', async () => {
const app = await fixture([{ id: 'g', name: 'cordis:group', group: true, config: [row('x', 1)] }])
await app.ctx.loader.create({ id: 'x', name: 'cordis:example', config: { value: 2 } } as EntryOptions)
await app.ctx.loader.await()
await expect(app.ctx.loader.update('x', {}, `${app.id}:g`)).rejects.toThrow('already exists in the target tree')
expect(app.ctx.loader.root.data.map(options => options.id)).toContain('x')
expect(app.value('x')).toBe(1)
await app.include.flush()
expect(await app.read()).toEqual([{ id: 'g', name: 'cordis:group', group: true, config: [row('x', 1)] }])
})
it('transfers the members of a group moved into the Include', async () => {
const app = await fixture([{ id: 'g', name: 'cordis:group', group: true, config: [] }])
const apply = vi.fn()
app.ctx.loader.builtins.counted = apply
const outer = await app.ctx.loader.create({ name: 'cordis:group', group: true, config: [] })
await app.ctx.loader.await()
const inner = await app.ctx.loader.create({ name: 'cordis:counted', config: { value: 1 } }, outer)
await app.ctx.loader.await()
const [group, member] = [app.ctx.loader.store[outer]!, app.ctx.loader.store[inner]!]
await app.ctx.loader.update(outer, {}, `${app.id}:g`)
await app.include.flush()
await app.ctx.loader.await()
expect(app.include.store[outer] === group && app.include.store[inner] === member).toBe(true)
expect(outer in app.ctx.loader.store || inner in app.ctx.loader.store).toBe(false)
expect(group.subgroup!.tree === app.include).toBe(true)
expect(apply).toHaveBeenCalledOnce()
expect(await app.read()).toEqual([{ id: 'g', name: 'cordis:group', group: true, config: [
{ id: outer, name: 'cordis:group', group: true, config: [{ id: inner, name: 'cordis:counted', config: { value: 1 } }] },
] }])
app.ctx.loader.remove(`${app.id}:${outer}`)
await app.include.flush()
await app.ctx.loader.await()
expect(member.fiber?.state).not.toBe(FiberState.ACTIVE)
})
+44
View File
@@ -0,0 +1,44 @@
/** Vendor HMR containment of Include refresh rejections. */
import { mkdtempSync, realpathSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
import { Context, type Plugin } from '@deepseek-ai/cordis'
import Loader from '@deepseek-ai/cordis-plugin-loader'
import Include from '@deepseek-ai/cordis-plugin-include'
import Timer from '@deepseek-ai/cordis-plugin-timer'
import { expect, it, onTestFinished, vi } from 'vitest'
// A literal import would add vendor HMR's `Context.hmr` declaration to the
// repository type program, where DSH HMR declares the same property.
const vendorHmr: string = '@deepseek-ai/cordis-plugin-hmr'
it('logs a rejected Include refresh instead of leaving it unhandled', async () => {
const dir = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-vendor-hmr-include-')))
const ctx = new Context()
ctx.baseUrl = pathToFileURL(dir).href + '/'
onTestFinished(async () => { await ctx.fiber.dispose(); rmSync(dir, { recursive: true, force: true }) })
await ctx.plugin(Loader)
await ctx.plugin(Timer)
ctx.loader.builtins.include = Include
const file = join(dir, 'nested.yml')
writeFileSync(file, '[]\n')
const id = await ctx.loader.create({ name: 'cordis:include', config: { path: './nested.yml' } })
await ctx.loader.await()
const { default: Hmr } = await import(vendorHmr) as { default: Plugin }
await ctx.plugin(Hmr, { root: [], ignored: [], debounce: 0 })
// The service keeps its chokidar watcher private; the test drives its change listener directly.
const watcher = Reflect.get(ctx.get('hmr') as object, 'watcher') as { emit(event: 'change', path: string): boolean }
const include = ctx.loader.resolve(id).subtree as Include
const failure = new Error('config file has 1 unsaved change(s)')
const refresh = vi.spyOn(include, 'refresh').mockRejectedValue(failure)
const warn = vi.spyOn(ctx.logger, 'warn')
const unhandled = vi.fn()
process.on('unhandledRejection', unhandled)
onTestFinished(() => { process.off('unhandledRejection', unhandled) })
watcher.emit('change', file)
await vi.waitFor(() => { expect(warn).toHaveBeenCalledWith(failure) })
await new Promise(resolve => setImmediate(resolve))
expect(refresh).toHaveBeenCalledOnce()
expect(unhandled).not.toHaveBeenCalled()
})
+295
View File
@@ -0,0 +1,295 @@
/** Byte-level source reuse survives unrelated releases and invalidates changed build inputs. */
import { execFileSync, spawnSync } from 'node:child_process'
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, symlinkSync, utimesSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { expect, it, onTestFinished } from 'vitest'
import { loadDesktopPackageEnvironment } from '../../apps/desktop/scripts/desktop-package-environment.mjs'
import { cuaHelperBuildKey, cuaHelperSourceDigest, cuaHelperSourceMatches, readCuaSigningSettings } from './build-inputs.ts'
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'cua-inputs-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
const git = (...args: string[]): void => { execFileSync('git', args, { cwd: root, stdio: 'pipe' }) }
const files = {
'package.json': JSON.stringify({ version: '1.0.0', packageManager: '[email protected]' }),
'pnpm-lock.yaml': 'lockfileVersion: 9.0\n',
'packages/experimental/cua-macos/native/Package.swift': '// swift package\n',
'packages/experimental/cua-macos/native/Sources/Main.swift': 'print("one")\n',
'packages/experimental/cua-macos/native/Info.plist': 'application identity',
'scripts/cua-helper/package.ts': 'build helper',
'apps/desktop/scripts/notarize-macos.mjs': 'notarize helper',
'.github/workflows/cua-helper-package.yml': 'build configuration',
'.github/workflows/release-publish.yml': 'publish configuration',
'packages/client/unrelated/src/index.ts': 'unrelated feature',
}
for (const [path, bytes] of Object.entries(files)) {
mkdirSync(dirname(join(root, path)), { recursive: true })
writeFileSync(join(root, path), bytes)
}
git('init', '--quiet')
git('add', '.')
return { root, git, source: join(root, 'packages/experimental/cua-macos/native/Sources/Main.swift') }
}
function copyHelperScripts(root: string): void {
for (const file of ['scripts/cua-helper/build-inputs.ts', 'scripts/cua-helper/select-artifact.ts',
'apps/desktop/scripts/desktop-file-settings.mjs', 'apps/desktop/scripts/desktop-release-environment.mjs', 'scripts/release/process.ts']) {
mkdirSync(dirname(join(root, file)), { recursive: true })
copyFileSync(resolve(file), join(root, file))
}
}
it('keeps identical source bytes across product versions and unrelated package edits', () => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
writeFileSync(join(f.root, 'package.json'), JSON.stringify({ version: '2.0.0', packageManager: '[email protected]' }))
writeFileSync(join(f.root, 'packages/client/unrelated/src/index.ts'), 'another unrelated feature')
utimesSync(f.source, new Date('2001-01-01'), new Date('2001-01-01'))
expect(cuaHelperSourceDigest(f.root)).toBe(before)
writeFileSync(f.source, readFileSync(f.source).toString().replace('one', 'two'))
utimesSync(f.source, new Date('2001-01-01'), new Date('2001-01-01'))
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
})
it.each(['add', 'delete', 'rename', 'resource', 'dependency', 'script', 'workflow', 'package manager'])(
'invalidates %s changes', (change) => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
if (change === 'add') writeFileSync(join(dirname(f.source), 'Added.swift'), 'new source')
if (change === 'delete') rmSync(f.source)
if (change === 'rename') renameSync(f.source, join(dirname(f.source), 'Renamed.swift'))
if (change === 'resource') writeFileSync(join(f.root, 'packages/experimental/cua-macos/native/Info.plist'), 'changed identity')
if (change === 'dependency') writeFileSync(join(f.root, 'pnpm-lock.yaml'), 'changed dependency')
if (change === 'script') writeFileSync(join(f.root, 'apps/desktop/scripts/notarize-macos.mjs'), 'changed notarization')
if (change === 'workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'changed build configuration')
if (change === 'package manager') writeFileSync(join(f.root, 'package.json'), JSON.stringify({ packageManager: '[email protected]' }))
f.git('add', '-A')
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
},
)
it.skipIf(process.platform === 'win32')('includes executable mode and rejects source links', () => {
const f = fixture()
const before = cuaHelperSourceDigest(f.root)
chmodSync(f.source, 0o755)
expect(cuaHelperSourceDigest(f.root)).not.toBe(before)
rmSync(f.source)
symlinkSync(join(f.root, 'pnpm-lock.yaml'), f.source)
expect(() => cuaHelperSourceDigest(f.root)).toThrow('regular file')
})
it('fails on missing required tracked build inputs', () => {
const f = fixture()
f.git('rm', '--cached', 'scripts/cua-helper/package.ts')
expect(() => cuaHelperSourceDigest(f.root)).toThrow('missing tracked build input')
})
it.each(['preset', 'identity', 'team', 'certificate', 'toolchain', 'source'])(
'invalidates changed %s while credentials stay outside the build key', (change) => {
const f = fixture()
const certificate = join(f.root, 'signing.p12')
writeFileSync(certificate, 'fixture encrypted certificate')
const environment = { CSC_LINK: certificate, DSH_PACKAGING_PRESET: 'production',
DSH_DESKTOP_MACOS_SIGNING_IDENTITY: 'Fixture (ABCDEFGHIJ)', DSH_DESKTOP_MACOS_TEAM_ID: 'ABCDEFGHIJ',
APPLE_APP_SPECIFIC_PASSWORD: 'private-password' }
const source = cuaHelperSourceDigest(f.root)
const run = (_command: string, args: string[]): string => args.join(' ')
const before = cuaHelperBuildKey(source, environment, run)
environment.APPLE_APP_SPECIFIC_PASSWORD = 'new-private-password'
expect(cuaHelperBuildKey(source, environment, run)).toBe(before)
if (change === 'preset') environment.DSH_PACKAGING_PRESET = 'test'
if (change === 'identity') environment.DSH_DESKTOP_MACOS_SIGNING_IDENTITY = 'Other (ABCDEFGHIJ)'
if (change === 'team') environment.DSH_DESKTOP_MACOS_TEAM_ID = '1234567890'
if (change === 'certificate') writeFileSync(certificate, 'another certificate')
const after = cuaHelperBuildKey(change === 'source' ? 'b'.repeat(64) : source, environment,
change === 'toolchain' ? () => 'another toolchain' : run)
expect(after).not.toBe(before)
},
)
it('resolves the configured signing file without installing desktop dependencies or exposing parser errors', () => {
const f = fixture()
const config = join(f.root, 'config')
mkdirSync(join(config, 'secrets'), { recursive: true })
writeFileSync(join(config, 'secrets/macos-signing.env'), 'CSC_LINK=./signing.p12\nDSH_DESKTOP_MACOS_TEAM_ID=ABCDEFGHIJ\n')
const environment = { DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: 'production' }
expect(readCuaSigningSettings(environment)).toMatchObject({ CSC_LINK: join(config, 'secrets/signing.p12'), DSH_PACKAGING_PRESET: 'production' })
expect(() => readCuaSigningSettings({ ...environment, DSH_PACKAGING_PRESET: 'invalid' })).toThrow('preset')
expect(() => readCuaSigningSettings({ ...environment, DSH_PACKAGING_CONFIG_DIR: 'relative' })).toThrow('CONFIG_DIR')
})
it('loads fingerprinting and selection under plain Node with no node_modules directory', () => {
const f = fixture()
copyHelperScripts(f.root)
const output = execFileSync(process.execPath, ['--input-type=module', '-e',
"const a = await import('./scripts/cua-helper/select-artifact.ts'); const b = await import('./scripts/cua-helper/build-inputs.ts'); console.log(typeof a.selectCuaHelperArtifact, typeof b.cuaHelperSourceDigest)"],
{ cwd: f.root, encoding: 'utf8', timeout: 30_000, stdio: 'pipe' })
expect(output.trim()).toBe('function function')
})
const repository = 'deepseek-harness/deepseek-harness'
function producerSnapshot(root: string) {
const git = (...args: string[]): string => execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: 'pipe' })
git('add', '-A')
git('-c', `core.hooksPath=${join(root, 'no-hooks')}`, '-c', 'commit.gpgsign=false', '-c', 'user.name=Fixture',
'-c', '[email protected]', 'commit', '--quiet', '-m', 'fixture')
const commit = git('rev-parse', 'HEAD').trim()
const tree = git('ls-tree', '-r', '-z', 'HEAD').split('\0').filter(Boolean).map((entry) => {
const [metadata, path] = entry.split('\t')
const [mode, type, sha] = (metadata ?? '').split(' ')
if (!path || !mode || !type || !sha) throw new Error('Invalid Git fixture tree entry')
return { path, mode, type, sha }
})
const response = { truncated: false, tree }
const responses: Record<string, unknown> = { [`repos/${repository}/git/trees/${commit}?recursive=1`]: response }
for (const entry of tree.filter(entry => entry.path === 'package.json')) {
const bytes = execFileSync('git', ['cat-file', 'blob', entry.sha], { cwd: root, stdio: 'pipe' })
responses[`repos/${repository}/git/blobs/${entry.sha}`] = { sha: entry.sha, encoding: 'base64', content: bytes.toString('base64') }
}
return { commit, response, responses, api: async (path: string): Promise<unknown> => {
if (!(path in responses)) throw new Error(`Unexpected GitHub fixture request ${path}`)
return responses[path]
} }
}
it('compares GitHub commit objects independently of artifact claims while allowing a root version bump', async () => {
const f = fixture()
const previous = producerSnapshot(f.root)
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(join(f.root, 'package.json'), JSON.stringify({ version: '2.0.0', packageManager: '[email protected]' }))
writeFileSync(join(f.root, 'packages/client/unrelated/src/index.ts'), 'another unrelated feature')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(f.source, 'changed native code')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
})
it.each(['helper workflow', 'publish workflow', 'packaging script', 'manifest lifecycle', 'npm config', 'patch', 'tracked dependency', 'deleted file'])(
'rejects independent producer source proof after a changed %s', async (change) => {
const f = fixture()
const previous = producerSnapshot(f.root)
const digest = cuaHelperSourceDigest(f.root)
if (change === 'helper workflow') writeFileSync(join(f.root, '.github/workflows/cua-helper-package.yml'), 'forged uploader')
if (change === 'publish workflow') writeFileSync(join(f.root, '.github/workflows/release-publish.yml'), 'forged caller')
if (change === 'packaging script') writeFileSync(join(f.root, 'scripts/cua-helper/package.ts'), 'forged metadata')
if (change === 'manifest lifecycle') writeFileSync(join(f.root, 'package.json'), JSON.stringify({
version: '1.0.0', packageManager: '[email protected]', scripts: { postinstall: 'unexpected code' },
}))
if (change === 'npm config') writeFileSync(join(f.root, '.npmrc'), 'node-options=--require=./unexpected.cjs')
if (change === 'patch') {
mkdirSync(join(f.root, 'patches'))
writeFileSync(join(f.root, 'patches/dependency.patch'), 'changed package code')
}
if (change === 'tracked dependency') {
mkdirSync(join(f.root, 'apps/desktop/node_modules/unexpected'), { recursive: true })
writeFileSync(join(f.root, 'apps/desktop/node_modules/unexpected/index.js'), 'unexpected dependency code')
f.git('add', '--force', 'apps/desktop/node_modules')
}
if (change === 'deleted file') rmSync(f.source)
f.git('add', '-A')
expect(cuaHelperSourceDigest(f.root)).not.toBe(digest)
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
},
)
it('stops source comparison when GitHub returns an incomplete tree', async () => {
const f = fixture()
const previous = producerSnapshot(f.root)
previous.response.truncated = true
await expect(cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).rejects.toThrow('incomplete commit tree')
})
it.each(['test', 'production'])('computes the same %s build key through selection and packaging configuration readers', (preset) => {
const f = fixture()
const config = join(f.root, 'config')
mkdirSync(join(config, 'presets'), { recursive: true })
mkdirSync(join(config, 'secrets'))
writeFileSync(join(config, 'presets', `${preset}.env`), `DSH_DESKTOP_AUTO_UPDATE_ENV=${preset}\n`)
writeFileSync(join(config, 'secrets/signing.p12'), 'fixture certificate')
writeFileSync(join(config, 'secrets/macos-signing.env'), [
'CSC_LINK=./signing.p12', 'CSC_KEY_PASSWORD=fixture-password', 'DSH_DESKTOP_MACOS_TEAM_ID=ABCDEFGHIJ',
'DSH_DESKTOP_MACOS_SIGNING_IDENTITY=Fixture (ABCDEFGHIJ)',
].join('\n'))
const environment = { DSH_PACKAGING_CONFIG_DIR: config, DSH_PACKAGING_PRESET: preset }
const source = cuaHelperSourceDigest(f.root)
const run = (_command: string, args: string[]): string => args.join(' ')
expect(cuaHelperBuildKey(source, readCuaSigningSettings(environment), run))
.toBe(cuaHelperBuildKey(source, loadDesktopPackageEnvironment('darwin', environment), run))
})
// A private POSIX PATH exposes only Git, so successful CLI execution cannot depend on gh.
it.skipIf(process.platform === 'win32').each(['match', 'miss', 'api failure', 'missing token'])(
'runs the plain-Node selector entry with %s and without gh or node_modules', (scenario) => {
const f = fixture()
copyHelperScripts(f.root)
const snapshot = producerSnapshot(f.root)
const key = 'a'.repeat(64)
const base = `repos/${repository}/actions/runs/123`
Object.assign(snapshot.responses, {
[base]: { run_attempt: 2 },
[`${base}/attempts/2`]: { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success',
event: 'workflow_dispatch', path: '.github/workflows/cua-helper-package.yml', head_sha: snapshot.commit,
repository: { full_name: repository }, head_repository: { full_name: repository } },
[`${base}/jobs?filter=all&per_page=100`]: { jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] },
[`${base}/artifacts?per_page=100`]: { artifacts: scenario === 'match'
? [{ id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }] : [] },
})
const data = join(f.root, 'responses.json')
writeFileSync(data, JSON.stringify(snapshot.responses))
const bin = join(f.root, 'git-only-bin')
mkdirSync(bin)
const git = execFileSync('/usr/bin/which', ['git'], { encoding: 'utf8' }).trim()
symlinkSync(git, join(bin, 'git'))
const preload = join(f.root, 'mock-github.mjs')
writeFileSync(preload, `import { readFileSync } from 'node:fs';
const data = JSON.parse(readFileSync(process.env.FIXTURE_API_DATA, 'utf8'));
globalThis.fetch = async (input, options) => {
const url = new URL(input);
if (url.origin !== 'https://api.github.com' || new Headers(options.headers).get('authorization') !== 'Bearer fixture-token') {
throw new Error('unexpected GitHub request');
}
if (process.env.FIXTURE_API_FAILURE === '1') return new Response('fixture API failure', { status: 503 });
const path = url.pathname.slice(1) + url.search;
if (path.includes('/workflows/')) return Response.json({ workflow_runs: path.includes('cua-helper-package.yml') ? [{ id: 123 }] : [] });
if (!(path in data)) throw new Error('unexpected GitHub path');
return Response.json(data[path]);
};
`)
const output = join(f.root, 'outputs')
const summary = join(f.root, 'summary')
const result = spawnSync(process.execPath, ['--import', preload, join(f.root, 'scripts/cua-helper/select-artifact.ts')], {
cwd: f.root, encoding: 'utf8', timeout: 60_000,
env: { ...process.env, NODE_OPTIONS: '', PATH: bin, GH_TOKEN: scenario === 'missing token' ? '' : 'fixture-token',
GITHUB_API_URL: 'https://api.github.com', GITHUB_REPOSITORY: repository, GITHUB_OUTPUT: output,
GITHUB_STEP_SUMMARY: summary, CUA_RUN_ID: '', CUA_BUILD_KEY: key,
FIXTURE_API_DATA: data, FIXTURE_API_FAILURE: scenario === 'api failure' ? '1' : '0' },
})
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(existsSync(join(bin, 'gh'))).toBe(false)
expect(existsSync(join(f.root, 'node_modules'))).toBe(false)
if (scenario === 'api failure' || scenario === 'missing token') {
expect(result.status).toBe(1)
expect(result.stderr).toContain(scenario === 'missing token' ? 'GH_TOKEN is required' : 'HTTP 503')
expect(existsSync(output)).toBe(false)
expect(existsSync(summary)).toBe(false)
} else {
expect(result.status, result.stderr).toBe(0)
expect(readFileSync(output, 'utf8')).toBe(scenario === 'match' ? 'artifact-id=456\nrun-id=123\n' : 'artifact-id=\nrun-id=\n')
expect(readFileSync(summary, 'utf8')).toContain(scenario === 'match' ? '跳过依赖安装' : '未找到')
}
},
)
it('matches Git blobs when tracked attributes require CRLF checkout bytes', async () => {
const f = fixture()
const path = join(f.root, 'apps/desktop/scripts/fixture.cmd')
writeFileSync(join(f.root, '.gitattributes'), '*.cmd text eol=crlf\n')
writeFileSync(path, '@echo off\necho fixture\n')
const previous = producerSnapshot(f.root)
writeFileSync(path, '@echo off\r\necho fixture\r\n')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(true)
writeFileSync(join(f.root, '.gitattributes'), '*.cmd text eol=lf\n')
expect(await cuaHelperSourceMatches(f.root, repository, previous.commit, previous.api)).toBe(false)
})
+169
View File
@@ -0,0 +1,169 @@
/** Content and machine identity for reusing a signed helper before installing dependencies. */
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { appendFileSync, lstatSync, readFileSync } from 'node:fs'
import { isAbsolute, join, resolve } from 'node:path'
import { isEntry } from '../release/process.ts'
import { readDesktopPackageSettings } from '../../apps/desktop/scripts/desktop-file-settings.mjs'
import { resolveMacOSSigningEnvironment } from '../../apps/desktop/scripts/desktop-release-environment.mjs'
const sourceDirectories = [
'packages/experimental/cua-macos/native', 'scripts/cua-helper', 'apps/desktop/scripts', 'patches',
]
const sourceFiles = new Set([
'.github/workflows/cua-helper-package.yml', '.github/workflows/release-publish.yml',
'package.json', 'scripts/package.json', 'apps/package.json', 'apps/desktop/package.json', 'scripts/release/process.ts',
'pnpm-lock.yaml', 'pnpm-workspace.yaml', '.npmrc', '.pnpmfile.cjs', '.pnpmfile.mjs',
])
function isSourceFile(path: string): boolean {
return sourceFiles.has(path) || path === '.gitattributes' || path.endsWith('/.gitattributes') || /^(?:(?:apps|apps\/desktop|scripts)\/)?tsconfig[^/]*\.json$/u.test(path)
|| path.split('/').includes('node_modules')
|| sourceDirectories.some(directory => path.startsWith(`${directory}/`))
}
function trackedSources(root: string): string[] {
const files = execFileSync('git', ['ls-files', '-z'], { cwd: root, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 })
.split('\0').filter(isSourceFile).sort()
for (const required of ['packages/experimental/cua-macos/native/Package.swift', 'scripts/cua-helper/package.ts',
'package.json', 'pnpm-lock.yaml']) {
if (!files.includes(required)) throw new Error(`CUA source: missing tracked build input ${required}`)
}
return files
}
function manifestConfiguration(bytes: Buffer, root: boolean): Buffer {
const manifest: unknown = JSON.parse(bytes.toString('utf8'))
assert(manifest && typeof manifest === 'object' && !Array.isArray(manifest), 'CUA source: invalid package manifest')
assert(!root || ('packageManager' in manifest && typeof manifest.packageManager === 'string'),
'CUA source: package.json must declare packageManager')
return Buffer.from(JSON.stringify(Object.fromEntries(Object.entries(manifest).filter(([name]) => name !== 'version'))))
}
function sourceFile(root: string, file: string): { bytes: Buffer; executable: boolean } {
const path = join(root, file)
const stat = lstatSync(path)
if (!stat.isFile()) throw new Error(`CUA source: build input must be a regular file: ${file}`)
return { bytes: readFileSync(path), executable: (stat.mode & 0o111) !== 0 }
}
function gitBlobHash(bytes: Buffer): string {
return createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex')
}
/**
* Hash tracked build inputs by path, bytes and executable mode; only package manifest version fields is excluded.
* Missing tracked files and links fail; build outputs and untracked files never enter the digest.
* @param root - Clean repository root containing all helper build inputs.
* @returns SHA-256 of sources, resources, workflows, package configuration, patches and locked dependencies.
*/
export function cuaHelperSourceDigest(root: string): string {
const hash = createHash('sha256')
for (const file of trackedSources(root)) {
const { bytes, executable } = sourceFile(root, file)
const input = file === 'package.json' || file.endsWith('/package.json') ? manifestConfiguration(bytes, file === 'package.json') : bytes
hash.update(`${file}\0`).update(createHash('sha256').update(input).digest()).update(Buffer.from([Number(executable)]))
}
return hash.digest('hex')
}
/**
* Compare a producer's immutable GitHub commit tree with local build inputs independently of artifact metadata.
* Incomplete trees, unreadable blobs and API failures stop selection; content differences return false.
* @param root - Consumer repository root, before dependency installation.
* @param repository - GitHub repository containing the authenticated producer run.
* @param commit - Producer head SHA returned by GitHub, never an artifact-supplied revision.
* @param api - Read-only GitHub JSON reader.
* @returns Resolves to whether selected paths, bytes and executable modes match, excluding package manifest version fields.
*/
export async function cuaHelperSourceMatches(root: string, repository: string, commit: string,
api: (path: string) => Promise<unknown>): Promise<boolean> {
assert(/^[a-f0-9]{40}$/u.test(commit), 'CUA source: invalid producer commit')
const response = await api(`repos/${repository}/git/trees/${commit}?recursive=1`)
assert(response && typeof response === 'object' && 'truncated' in response && response.truncated === false
&& 'tree' in response && Array.isArray(response.tree), 'CUA source: GitHub returned an incomplete commit tree')
const tree = new Map<string, { sha: string; mode: string }>()
const entries: unknown[] = response.tree
for (const value of entries) {
assert(value && typeof value === 'object' && 'path' in value && typeof value.path === 'string', 'CUA source: invalid tree entry')
if (!isSourceFile(value.path) || ('type' in value && value.type === 'tree')) continue
assert('sha' in value && typeof value.sha === 'string' && /^[a-f0-9]{40}$/u.test(value.sha)
&& 'mode' in value && typeof value.mode === 'string' && 'type' in value, 'CUA source: invalid source entry')
if (value.type !== 'blob' || !['100644', '100755'].includes(value.mode)) return false
assert(!tree.has(value.path), 'CUA source: duplicate source entry')
tree.set(value.path, { sha: value.sha, mode: value.mode })
}
const files = trackedSources(root)
if (tree.size !== files.length) return false
for (const file of files) {
const remote = tree.get(file)
if (!remote) return false
const local = sourceFile(root, file)
if (remote.mode !== (local.executable ? '100755' : '100644')) return false
if (gitBlobHash(local.bytes) === remote.sha) continue
const canonical = execFileSync('git', ['hash-object', `--path=${file}`, '--stdin'],
{ cwd: root, input: local.bytes, encoding: 'utf8' }).trim()
if (canonical === remote.sha) continue
if (file !== 'package.json' && !file.endsWith('/package.json')) return false
const blob = await api(`repos/${repository}/git/blobs/${remote.sha}`)
assert(blob && typeof blob === 'object' && 'sha' in blob && blob.sha === remote.sha
&& 'encoding' in blob && blob.encoding === 'base64' && 'content' in blob && typeof blob.content === 'string',
'CUA source: invalid package manifest blob')
const bytes = Buffer.from(blob.content, 'base64')
assert(gitBlobHash(bytes) === remote.sha, 'CUA source: package manifest blob digest mismatch')
if (!manifestConfiguration(local.bytes, file === 'package.json').equals(manifestConfiguration(bytes, file === 'package.json'))) return false
}
return true
}
/**
* Read the signing preset's public identity and certificate location without installing desktop dependencies.
* @param environment - Actions environment with the machine configuration directory and selected preset.
* @returns File-owned signing settings and the selected preset; no values are logged.
*/
export function readCuaSigningSettings(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
const root = environment.DSH_PACKAGING_CONFIG_DIR
const preset = environment.DSH_PACKAGING_PRESET
if (!root || !isAbsolute(root) || !['test', 'production'].includes(preset ?? '')) {
throw new Error('CUA reuse: DSH_PACKAGING_CONFIG_DIR and a test or production preset are required')
}
const settings = readDesktopPackageSettings(join(root, 'secrets/macos-signing.env'), () => true)
return { ...settings, DSH_PACKAGING_PRESET: preset }
}
/**
* Bind source bytes to the active toolchain, preset and signing certificate container.
* @param source - Current source digest.
* @param environment - File-owned signing settings including CSC_LINK and the selected preset.
* @param run - Synchronous query returning the active compiler, SDK and Python version strings.
* @returns SHA-256 build key; credential values and certificate bytes are not recorded.
*/
export function cuaHelperBuildKey(source: string, environment: NodeJS.ProcessEnv,
run: (command: string, args: string[]) => string = (command, args) =>
execFileSync(command, args, { encoding: 'utf8', timeout: 60_000, stdio: 'pipe' }).trim()): string {
const signing = resolveMacOSSigningEnvironment(environment)
const certificate = environment.CSC_LINK
if (!certificate || !isAbsolute(certificate)) throw new Error('CUA reuse: CSC_LINK must identify the signing certificate file')
const configuration = {
source, preset: environment.DSH_PACKAGING_PRESET ?? 'local', ...signing,
certificate: createHash('sha256').update(readFileSync(certificate)).digest('hex'),
node: process.version,
swift: run('/usr/bin/xcrun', ['swift', '--version']),
clang: run('/usr/bin/xcrun', ['clang', '--version']),
sdk: run('/usr/bin/xcrun', ['--sdk', 'macosx', '--show-sdk-build-version']),
python: run('/usr/bin/xcrun', ['python3', '--version']),
}
return createHash('sha256').update(JSON.stringify(configuration)).digest('hex')
}
if (isEntry(import.meta.url)) {
const env = process.env
if (!env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY) throw new Error('CUA build inputs: Actions context required')
const root = resolve(import.meta.dirname, '../..')
const sourceDigest = cuaHelperSourceDigest(root)
const buildKey = cuaHelperBuildKey(sourceDigest, readCuaSigningSettings(env))
appendFileSync(env.GITHUB_OUTPUT, `build-key=${buildKey}\n`)
appendFileSync(env.GITHUB_STEP_SUMMARY, `CUA helper 源码摘要:\`${sourceDigest}\`。\n\n`)
console.log(`CUA helper source digest: ${sourceDigest}`)
}
+1
View File
@@ -48,6 +48,7 @@ vi.mock('tar', () => ({
create: async ({ file }: { file: string }) => writeFile(file, 'fixture archive'),
extract: async () => {},
}))
vi.mock('./build-inputs.ts', () => ({ cuaHelperSourceDigest: () => 'a'.repeat(64), cuaHelperBuildKey: () => 'b'.repeat(64) }))
vi.mock('./payload.ts', async importOriginal => ({
...await importOriginal<typeof import('./payload.ts')>(),
readCuaApplication: (directory: string) => ({ application: join(directory, 'fixture/DSH Computer Use.app') }),
+11 -4
View File
@@ -3,6 +3,7 @@ import { execFileSync } from 'node:child_process'
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join, resolve } from 'node:path'
import { isEntry } from '../release/process.ts'
import { parseArgs } from 'node:util'
import { execa } from 'execa'
import { create, extract } from 'tar'
@@ -15,6 +16,7 @@ import { notarizeMacOS } from '../../apps/desktop/scripts/notarize-macos.mjs'
import { createPackagingRun } from '../../apps/desktop/scripts/packaging-run.mjs'
import { packagingErrorDetails, packagingStep } from '../../apps/desktop/scripts/packaging-step.mjs'
import { verifyMacOSRuntimeCode } from '../../apps/desktop/scripts/verify-macos-signature.mjs'
import { cuaHelperBuildKey, cuaHelperSourceDigest } from './build-inputs.ts'
import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, readCuaApplication, sealCuaApplication, verifyCuaHelperPayload, type CuaHelperManifest } from './payload.ts'
async function main(): Promise<void> {
@@ -23,6 +25,11 @@ async function main(): Promise<void> {
const root = resolve(import.meta.dirname, '../..')
const output = resolve(values.out)
const environment = loadDesktopPackageEnvironment('darwin')
const sourceDigest = cuaHelperSourceDigest(root)
const buildKey = cuaHelperBuildKey(sourceDigest, environment)
if (process.env.CUA_EXPECTED_BUILD_KEY !== undefined && process.env.CUA_EXPECTED_BUILD_KEY !== buildKey) {
throw new Error('CUA build inputs changed after artifact selection; restart the helper workflow')
}
const signing = resolveMacOSSigningEnvironment(environment)
const notary = resolveMacOSNotarizationEnvironment(environment)
const settings = resolveMacOSPackageSettings(environment)
@@ -68,15 +75,15 @@ async function main(): Promise<void> {
applications.push({ architecture, bundle: sealCuaApplication(directory, application) })
}
})
const manifest: CuaHelperManifest = { schemaVersion: 1, version, commit, teamId: signing.teamId, applications }
const manifest: CuaHelperManifest = { schemaVersion: 2, sourceDigest, buildKey, version, commit, teamId: signing.teamId, applications }
writeFileSync(join(payload, CUA_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`)
verifyCuaHelperPayload(payload, { version, commit })
verifyCuaHelperPayload(payload, { sourceDigest, buildKey })
const archive = join(output, 'cua-helper.tgz')
await create({ cwd: payload, file: archive, gzip: true, portable: true }, [CUA_MANIFEST, 'native'])
const extracted = join(scratch, 'extracted')
mkdirSync(extracted)
await extract({ cwd: extracted, file: archive, strict: true })
verifyCuaHelperPayload(extracted, { version, commit })
verifyCuaHelperPayload(extracted, { sourceDigest, buildKey })
for (const { architecture, bundle } of applications) {
const application = join(extracted, 'native/bin', `darwin-${architecture}`, bundle, CUA_APPLICATION)
await verify(application, architecture)
@@ -98,4 +105,4 @@ async function main(): Promise<void> {
journal.finish(true)
}
await main()
if (isEntry(import.meta.url)) await main()
+16 -6
View File
@@ -10,7 +10,7 @@ import { expect, it, onTestFinished } from 'vitest'
import { CUA_APPLICATION, CUA_ARCHITECTURES, CUA_MANIFEST, cuaApplicationDigest, readCuaApplication, sealCuaApplication, stageCuaHelperPayload, verifyCuaHelperPayload } from './payload.ts'
import { verifyCuaHelperTarball } from './verify-tarball.ts'
const identity = { version: '1.0.0', commit: 'a'.repeat(40) }
const identity = { sourceDigest: 'a'.repeat(64), buildKey: 'b'.repeat(64) }
function fixture() {
const root = mkdtempSync(join(tmpdir(), 'cua-payload-test-'))
onTestFinished(() => { rmSync(root, { recursive: true, force: true }) })
@@ -28,7 +28,7 @@ function fixture() {
chmodSync(join(application, 'Contents/MacOS/dsh-cua-native'), 0o755)
return { architecture, bundle: sealCuaApplication(directory, application) }
})
const manifest = { schemaVersion: 1, ...identity, teamId: 'ABCDEFGHIJ', applications }
const manifest = { schemaVersion: 2, ...identity, version: '1.0.0', commit: 'a'.repeat(40), teamId: 'ABCDEFGHIJ', applications }
writeFileSync(join(payload, CUA_MANIFEST), JSON.stringify(manifest))
return { root, payload, manifest, directory: join(payload, 'native/bin/darwin-arm64') }
}
@@ -72,7 +72,7 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
mkdirSync(output)
stageCuaHelperPayload(f.payload, packageRoot, identity)
writeFileSync(join(packageRoot, 'package.json'), JSON.stringify({
name: '@deepseek-ai/dsh-experimental-cua-macos', version: identity.version, type: 'module',
name: '@deepseek-ai/dsh-experimental-cua-macos', version: f.manifest.version, type: 'module',
files: ['lib/index.js', 'native/bin', CUA_MANIFEST],
}))
writeFileSync(join(packageRoot, 'lib/index.js'), 'export const provider = "fixture";\n')
@@ -103,11 +103,11 @@ it.skipIf(process.platform === 'win32')('keeps npm tarball bytes when reusing a
expect(rebuilt.equals(first)).toBe(false)
})
it.skipIf(process.platform === 'win32').each(['version', 'commit', 'architecture', 'missing', 'extra', 'permissions', 'symlink'] as const)('rejects %s damage before staging', (damage) => {
it.skipIf(process.platform === 'win32').each(['source', 'configuration', 'architecture', 'missing', 'extra', 'permissions', 'symlink'] as const)('rejects %s damage before staging', (damage) => {
const f = fixture()
const before = readCuaApplication(f.directory)
if (damage === 'version') f.manifest.version = '2.0.0'
if (damage === 'commit') f.manifest.commit = 'b'.repeat(40)
if (damage === 'source') f.manifest.sourceDigest = 'c'.repeat(64)
if (damage === 'configuration') f.manifest.buildKey = 'd'.repeat(64)
if (damage === 'architecture') f.manifest.applications[1] = f.manifest.applications[0]!
if (damage === 'missing') rmSync(join(before.application, 'Contents/Info.plist'))
if (damage === 'extra') cpSync(before.application, join(f.directory, 'old-generation', CUA_APPLICATION), { recursive: true })
@@ -128,3 +128,13 @@ it('keeps company signing outside pull-request release rehearsals', () => {
expect(release).toContain('scripts/cua-helper/stage.ts')
expect(readFileSync(resolve('.github/workflows/release.yml'), 'utf8')).not.toContain('cua-helper-package.yml')
})
it.skipIf(process.platform === 'win32')('retains the original build commit and version when consuming identical helper sources', () => {
const f = fixture()
f.manifest.version = '0.9.0'
f.manifest.commit = 'c'.repeat(40)
writeFileSync(join(f.payload, CUA_MANIFEST), JSON.stringify(f.manifest))
const consumer = join(f.root, 'consumer')
stageCuaHelperPayload(f.payload, consumer, identity)
expect(JSON.parse(readFileSync(join(consumer, CUA_MANIFEST), 'utf8'))).toEqual(f.manifest)
})
+7 -5
View File
@@ -12,7 +12,8 @@ export const CUA_APPLICATION = 'DSH Computer Use.app'
export const CUA_MANIFEST = 'cua-helper.json'
const Digest = z.string().regex(/^[a-f0-9]{64}$/u)
const Manifest = z.object({
schemaVersion: z.literal(1), version: z.string().min(1), commit: z.string().regex(/^[a-f0-9]{40}$/u),
schemaVersion: z.literal(2), sourceDigest: Digest, buildKey: Digest,
version: z.string().min(1), commit: z.string().regex(/^[a-f0-9]{40}$/u),
teamId: z.string().regex(/^[A-Z0-9]{10}$/u),
applications: z.array(z.object({ architecture: z.enum(CUA_ARCHITECTURES), bundle: Digest }).strict()).length(2),
}).strict()
@@ -90,12 +91,13 @@ export function sealCuaApplication(directory: string, application: string): stri
/**
* Verify the producer record and every final application before copying or packing.
* @param root - Extracted helper artifact containing native/bin and cua-helper.json.
* @param expected - Source commit and product version of the consuming checkout.
* @param expected - Source digest and, on the Mac-to-pack transfer, the selected build key.
* @returns Validated producer metadata.
*/
export function verifyCuaHelperPayload(root: string, expected: { version: string; commit: string }): CuaHelperManifest {
export function verifyCuaHelperPayload(root: string, expected: { sourceDigest: string; buildKey?: string }): CuaHelperManifest {
const manifest = Manifest.parse(JSON.parse(readFileSync(join(root, CUA_MANIFEST), 'utf8')))
if (manifest.version !== expected.version || manifest.commit !== expected.commit) throw new Error('CUA artifact does not match the release source and version')
if (manifest.sourceDigest !== expected.sourceDigest) throw new Error('CUA artifact does not match the current helper source bytes')
if (expected.buildKey !== undefined && manifest.buildKey !== expected.buildKey) throw new Error('CUA artifact does not match the selected build configuration')
if (new Set(manifest.applications.map(entry => entry.architecture)).size !== 2) throw new Error('CUA artifact must contain arm64 and x64')
const bin = join(root, 'native/bin')
if (readdirSync(bin).sort().join(',') !== 'darwin-arm64,darwin-x64') throw new Error('CUA artifact has unexpected architecture directories')
@@ -112,7 +114,7 @@ export function verifyCuaHelperPayload(root: string, expected: { version: string
* @param packageRoot - Provider package to receive native/bin.
* @param expected - Source identity required by the release.
*/
export function stageCuaHelperPayload(root: string, packageRoot: string, expected: { version: string; commit: string }): void {
export function stageCuaHelperPayload(root: string, packageRoot: string, expected: { sourceDigest: string; buildKey?: string }): void {
verifyCuaHelperPayload(root, expected)
const destination = join(packageRoot, 'native/bin')
if (existsSync(destination)) throw new Error('CUA staging requires an empty native/bin; use a clean release checkout')
+248 -52
View File
@@ -1,94 +1,290 @@
/** Retained CUA selection stays within one producer, attempt and immutable artifact. */
import { expect, it, vi } from 'vitest'
import { selectCuaHelperArtifact } from './select-artifact.ts'
/** Discovery and explicit selection require matching inputs and successful producer evidence. */
import { expect, it, onTestFinished, vi } from 'vitest'
import { createGitHubJsonReader, selectCuaHelperArtifact } from './select-artifact.ts'
const repository = 'deepseek-harness/deepseek-harness'
const base = `repos/${repository}/actions/runs/123`
const key = 'a'.repeat(64)
function fixture() {
const run = { id: 123, run_attempt: 2, status: 'completed', conclusion: 'success', event: 'workflow_dispatch',
path: '.github/workflows/cua-helper-package.yml', repository: { full_name: repository } }
const jobs = [{ jobs: [{ name: 'package', conclusion: 'success' }] }]
const artifact = { id: 456, name: 'cua-helper-123-2', expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: 'cua-helper-123-1' }] }, { artifacts: [artifact] }]
const api = vi.fn((path: string, paginate?: boolean) => {
path: '.github/workflows/cua-helper-package.yml', head_sha: 'c'.repeat(40), repository: { full_name: repository }, head_repository: { full_name: repository } }
const jobs = [{ jobs: [{ name: 'package', conclusion: 'success', run_attempt: 2 }] }]
const matchesSource = vi.fn(async (_commit: string) => true)
const artifact = { id: 456, name: `cua-helper-123-2-${key}`, expired: false, size_in_bytes: 4096 }
const artifacts = [{ artifacts: [{ ...artifact, id: 455, name: `cua-helper-123-1-${key}` }] }, { artifacts: [artifact] }]
const api = vi.fn(async (path: string, paginate?: boolean) => {
if (path === base) { expect(paginate).toBeUndefined(); return { run_attempt: 2 } }
if (path === `${base}/attempts/2`) { expect(paginate).toBeUndefined(); return run }
expect(paginate).toBe(true)
if (path === `${base}/attempts/2/jobs?per_page=100`) return jobs
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [{ id: 123 }] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [] }]
if (path === `${base}/jobs?filter=all&per_page=100`) return jobs
if (path === `${base}/artifacts?per_page=100`) return artifacts
throw new Error(`Unexpected GitHub request ${path}`)
})
return { run, jobs, artifact, artifacts, api }
return { run, jobs, artifact, artifacts, api, matchesSource }
}
it.each([undefined, '', '2'])('pins attempt %s and finds its artifact across pages', (attempt) => {
it.each(['123', ''])('selects a matching artifact with run ID %j and pins the latest attempt', async (runId) => {
const f = fixture()
expect(selectCuaHelperArtifact(repository, { cua_run_id: '123', cua_run_attempt: attempt }, f.api))
expect(await selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource))
.toEqual({ runId: '123', attempt: '2', artifactId: '456' })
expect(f.api.mock.calls.some(([path]) => path === base)).toBe(attempt !== '2')
expect(f.api.mock.calls.filter(([path]) => path === base)).toHaveLength(1)
expect(f.api.mock.calls.some(([path]) => path.includes('/workflows/'))).toBe(runId === '')
})
it('allows successful CUA packaging when later publication jobs failed', () => {
it('allows successful helper packaging when later npm publication failed', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success' }, { name: 'Publish to npm', conclusion: 'failure' }]
expect(selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api).artifactId).toBe('456')
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'Publish to npm', conclusion: 'failure', run_attempt: 2 }]
expect((await selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource))?.artifactId).toBe('456')
})
it.each([
{}, { cua_run_attempt: '2' }, { cua_run_id: '' }, { cua_run_id: '123/other' }, { cua_run_id: ' 123' },
{ cua_run_id: '0' }, { cua_run_id: '123', cua_run_attempt: '-1' }, { cua_run_id: '123', cua_run_attempt: '2\nartifact-id=9' },
])('rejects invalid selection fields before reading GitHub: %j', (inputs) => {
it.each(['123/other', ' 123', '0', '-1', '2\nartifact-id=9', 'https://github.com/owner/repo/actions/runs/123'])(
'rejects invalid run ID %j before reading GitHub', async (runId) => {
const f = fixture()
await expect(selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource)).rejects.toThrow('numeric run ID')
expect(f.api).not.toHaveBeenCalled()
},
)
it.each(['wrong/repo/extra', '../repo', 'owner/..', 'owner/.'])('rejects invalid repository %s before reading GitHub', async (repo) => {
const f = fixture()
expect(() => selectCuaHelperArtifact(repository, inputs, f.api)).toThrow()
await expect(selectCuaHelperArtifact(repo, '123', key, f.api, f.matchesSource)).rejects.toThrow('invalid repository')
expect(f.api).not.toHaveBeenCalled()
})
it.each(['wrong/repo/extra', '../repo', 'owner/..', 'owner/.'])('rejects invalid repository %s before reading GitHub', (repo) => {
const f = fixture()
expect(() => selectCuaHelperArtifact(repo, { cua_run_id: '123' }, f.api)).toThrow('invalid repository')
expect(f.api).not.toHaveBeenCalled()
})
it.each(['workflow', 'event', 'repository', 'id', 'attempt', 'running', 'failed'] as const)('rejects %s run evidence', (change) => {
const f = fixture()
if (change === 'workflow') f.run.path = '.github/workflows/ci.yml'
if (change === 'event') f.run.event = 'pull_request'
if (change === 'repository') f.run.repository.full_name = 'outsider/fork'
if (change === 'id') f.run.id = 124
if (change === 'attempt') f.run.run_attempt = 1
if (change === 'running') f.run.status = 'in_progress'
if (change === 'failed') f.run.conclusion = 'failure'
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow()
expect(f.api.mock.calls.some(([path]) => path.includes('/artifacts'))).toBe(false)
})
it.each(['workflow', 'event', 'repository', 'head_repository', 'id', 'attempt', 'running', 'failed'] as const)(
'rejects explicit %s run evidence', async (change) => {
const f = fixture()
if (change === 'workflow') f.run.path = '.github/workflows/ci.yml'
if (change === 'event') f.run.event = 'pull_request'
if (change === 'repository') f.run.repository.full_name = 'outsider/fork'
if (change === 'head_repository') f.run.head_repository.full_name = 'outsider/fork'
if (change === 'id') f.run.id = 124
if (change === 'attempt') f.run.run_attempt = 1
if (change === 'running') f.run.status = 'in_progress'
if (change === 'failed') f.run.conclusion = 'failure'
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow()
expect(f.api.mock.calls.some(([path]) => path.includes('/artifacts'))).toBe(false)
},
)
it.each(['failure', 'cancelled', 'skipped', 'missing', 'duplicate'])(
'rejects %s helper jobs without falling back to attempt 1', (status) => {
'rejects %s helper jobs without falling back to attempt 1', async (status) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.run.conclusion = 'failure'
f.jobs[0]!.jobs = status === 'missing' ? [] : status === 'duplicate'
? [{ name: 'cua-helper / package', conclusion: 'success' }, { name: 'cua-helper / package', conclusion: 'success' }]
: [{ name: 'cua-helper / package', conclusion: status }]
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow('successful cua-helper / package job')
? [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }, { name: 'cua-helper / package', conclusion: 'success', run_attempt: 2 }]
: [{ name: 'cua-helper / package', conclusion: status, run_attempt: 2 }]
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('last executed cua-helper / package job did not succeed')
expect(f.api.mock.calls.some(([path]) => path.includes('/attempts/1') || path.includes('/artifacts'))).toBe(false)
},
)
it.each(['missing', 'expired', 'empty', 'duplicate'] as const)('rejects %s artifacts instead of another attempt', (change) => {
it.each(['missing', 'expired', 'empty', 'mismatch', 'legacy'] as const)(
'rebuilds on automatic %s but rejects the same explicit selection', async (change) => {
const f = fixture()
if (change === 'missing') f.artifacts.pop()
if (change === 'expired') f.artifact.expired = true
if (change === 'empty') f.artifact.size_in_bytes = 0
if (change === 'mismatch') f.artifact.name = `cua-helper-123-2-${'b'.repeat(64)}`
if (change === 'legacy') f.artifact.name = 'cua-helper-123-2'
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('CUA reuse: run 123:')
},
)
it('selects a match across workflows and pages after a newer failed producer', async () => {
const f = fixture()
if (change === 'missing') f.artifacts.pop()
if (change === 'expired') f.artifact.expired = true
if (change === 'empty') f.artifact.size_in_bytes = 0
if (change === 'duplicate') f.artifacts.push({ artifacts: [{ ...f.artifact, id: 457 }] })
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, f.api)).toThrow('select an available build or rebuild')
const api = vi.fn(async (path: string, paginate?: boolean): Promise<unknown> => {
if (path.includes('/workflows/cua-helper-package.yml/runs?')) return [{ workflow_runs: [] }]
if (path.includes('/workflows/release-publish.yml/runs?')) return [{ workflow_runs: [{ id: 124 }] }, { workflow_runs: [{ id: 123 }] }]
if (path.endsWith('/runs/124/artifacts?per_page=100')) return [{ artifacts: [{ ...f.artifact, name: `cua-helper-124-1-${key}` }] }]
if (path.endsWith('/runs/124')) return { run_attempt: 1 }
if (path.endsWith('/runs/124/attempts/1')) return { ...f.run, id: 124, run_attempt: 1, conclusion: 'failure' }
return f.api(path, paginate)
})
expect((await selectCuaHelperArtifact(repository, '', key, api, f.matchesSource, new Date('2026-11-03T00:00:00Z')))?.runId).toBe('123')
const paths = api.mock.calls.map(([path]) => path)
expect(paths.find(path => path.includes('/workflows/'))).toContain(encodeURIComponent('>=2026-10-20T00:00:00.000Z'))
expect(paths.indexOf(`${base.replace('123', '124')}/attempts/1`)).toBeLessThan(paths.indexOf(base))
})
it('propagates unavailable GitHub evidence without returning a selection', () => {
const api = vi.fn(() => { throw new Error('HTTP 404') })
expect(() => selectCuaHelperArtifact(repository, { cua_run_id: '123' }, api)).toThrow('HTTP 404')
it.each(['duplicate', 'invalid metadata'] as const)('stops automatic discovery on %s evidence', async (change) => {
const f = fixture()
if (change === 'duplicate') f.artifacts.push({ artifacts: [{ ...f.artifact, id: 457 }] })
const api = async (path: string, paginate?: boolean): Promise<unknown> => change === 'invalid metadata' && path.endsWith('/artifacts?per_page=100')
? [{ artifacts: [{ ...f.artifact, expired: 'false' }] }] : f.api(path, paginate)
await expect(selectCuaHelperArtifact(repository, '', key, api, f.matchesSource)).rejects.toThrow()
})
it.each(['', '123'])('propagates unavailable GitHub evidence with selection %j', async (runId) => {
const api = vi.fn(async () => { throw new Error('HTTP 403') })
await expect(selectCuaHelperArtifact(repository, runId, key, api, async () => true)).rejects.toThrow('HTTP 403')
expect(api).toHaveBeenCalledTimes(1)
})
it('does not query job or attempt details when artifact names exclude the requested build key', async () => {
const f = fixture()
f.artifact.name = 'cua-helper-123-2-legacy'
f.artifacts.shift()
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
expect(f.api.mock.calls.map(([path]) => path).filter(path => !path.includes('/workflows/')))
.toEqual([`${base}/artifacts?per_page=100`])
})
it.each(['123', ''])('retains the original helper after a publish-only rerun with selection %j', async (runId) => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
{ name: 'Publish to npm', conclusion: 'success', run_attempt: 2 }]
f.artifacts.pop()
expect(await selectCuaHelperArtifact(repository, runId, key, f.api, f.matchesSource))
.toEqual({ runId: '123', attempt: '1', artifactId: '455' })
expect(f.matchesSource).toHaveBeenCalledExactlyOnceWith(f.run.head_sha)
})
it('does not reuse an older successful helper after a newer helper execution failed', async () => {
const f = fixture()
f.run.path = '.github/workflows/release-publish.yml'
f.jobs[0]!.jobs = [{ name: 'cua-helper / package', conclusion: 'success', run_attempt: 1 },
{ name: 'cua-helper / package', conclusion: 'failure', run_attempt: 2 }]
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('did not succeed')
expect(f.matchesSource).not.toHaveBeenCalled()
})
it('rejects forged artifact keys when independent producer source evidence differs', async () => {
const f = fixture()
f.matchesSource.mockResolvedValue(false)
expect(await selectCuaHelperArtifact(repository, '', key, f.api, f.matchesSource)).toBeUndefined()
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('producer commit')
})
it('stops when a new attempt appears during selection', async () => {
const f = fixture()
f.jobs[0]!.jobs[0]!.run_attempt = 3
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('run advanced')
})
it('authenticates native HTTP requests and follows canonical GitHub pagination links', async () => {
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 1 }] }, {
headers: { link: '<https://api.github.com/repositories/42/actions/jobs?page=2>; rel="next"' },
}))
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 2 }] }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo/actions/jobs?page=1', true)).resolves.toEqual([
{ jobs: [{ id: 1 }] }, { jobs: [{ id: 2 }] },
])
expect(request).toHaveBeenCalledTimes(2)
expect(request.mock.calls[1]![1]?.signal).toBe(request.mock.calls[0]![1]?.signal)
expect(request.mock.calls[1]![0]).toHaveProperty('href', 'https://api.github.com/repositories/42/actions/jobs?page=2')
for (const [, options] of request.mock.calls) {
const headers = new Headers(options?.headers)
expect(headers.get('authorization')).toBe('Bearer fixture-token')
expect(headers.get('accept')).toBe('application/vnd.github+json')
expect(options?.signal).toBeInstanceOf(AbortSignal)
expect(options?.redirect).toBe('error')
}
})
it('uses the configured GitHub API base path and leaves non-paginated JSON unwrapped', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ run_attempt: 2 }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token', GITHUB_API_URL: 'https://github.example.test/api/v3' }, request)
await expect(api('repos/owner/repo/actions/runs/123')).resolves.toEqual({ run_attempt: 2 })
expect(request.mock.calls[0]![0]).toHaveProperty('href', 'https://github.example.test/api/v3/repos/owner/repo/actions/runs/123')
})
it.each([401, 403, 429, 500, 503])('rejects HTTP %s without returning a partial page list or response credentials', async (status) => {
const request = vi.fn<typeof fetch>()
.mockResolvedValueOnce(Response.json({ jobs: [{ id: 1 }] }, {
headers: { link: '<https://api.github.com/repos/owner/repo/jobs?page=2>; rel="next"' },
}))
.mockResolvedValueOnce(new Response('private-response-value', { status }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
const result = api('repos/owner/repo/jobs?page=1', true)
await expect(result).rejects.toThrow(`HTTP ${status}`)
await expect(result).rejects.not.toThrow('private-response-value')
await expect(result).rejects.not.toThrow('fixture-token')
})
it.each(['connection reset', 'request timeout'])('reports %s as a failed query', async (failure) => {
const request = vi.fn<typeof fetch>().mockRejectedValue(new Error(failure))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo')).rejects.toThrow('failed or timed out')
})
it('rejects invalid JSON without exposing its content', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response('private-response-value'))
const result = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo')
await expect(result).rejects.toThrow('invalid JSON')
await expect(result).rejects.not.toThrow('private-response-value')
})
it.each([
'https://outside.example.test/page/2',
'https://[email protected]/repos/owner/repo/jobs?page=2',
'https://api.github.com/repos/owner/repo/jobs?page=1',
])('rejects unsafe or cyclic pagination %s before sending another request', async (next) => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({ jobs: [] }, { headers: { link: `<${next}>; rel="next"` } }))
const api = createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)
await expect(api('repos/owner/repo/jobs?page=1', true)).rejects.toThrow('CUA reuse: GitHub')
expect(request).toHaveBeenCalledTimes(1)
})
it('rejects a malformed next-page header', async () => {
const request = vi.fn<typeof fetch>().mockResolvedValue(Response.json({}, { headers: { link: 'missing-url; rel="next"' } }))
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo/jobs', true))
.rejects.toThrow('invalid pagination link')
})
it('stops reading an oversized response and cancels its stream', async () => {
let cancelled = false
const body = new ReadableStream<Uint8Array>({
start(controller) { controller.enqueue(new Uint8Array(32 * 1024 * 1024 + 1)) },
cancel() { cancelled = true },
})
const request = vi.fn<typeof fetch>().mockResolvedValue(new Response(body))
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo/git/trees/fixture'))
.rejects.toThrow('exceeds 32 MiB')
expect(cancelled).toBe(true)
})
it.each(['', 'not-a-url', 'http://api.github.com', 'https://user:[email protected]', 'https://api.github.com?token=private'])(
'rejects invalid API configuration %j before requesting data', (url) => {
const request = vi.fn<typeof fetch>()
expect(() => createGitHubJsonReader({ GH_TOKEN: 'fixture-token', GITHUB_API_URL: url }, request)).toThrow('GITHUB_API_URL')
expect(request).not.toHaveBeenCalled()
},
)
it('requires an explicit Actions token instead of relying on gh credentials', () => {
const request = vi.fn<typeof fetch>()
expect(() => createGitHubJsonReader({}, request)).toThrow('GH_TOKEN is required')
expect(request).not.toHaveBeenCalled()
})
it('propagates an asynchronous source verification failure', async () => {
const f = fixture()
f.matchesSource.mockRejectedValue(new Error('source evidence unavailable'))
await expect(selectCuaHelperArtifact(repository, '123', key, f.api, f.matchesSource)).rejects.toThrow('source evidence unavailable')
})
it('passes the 60-second abort signal to the HTTP transport', async () => {
const controller = new AbortController()
const timeout = vi.spyOn(AbortSignal, 'timeout').mockReturnValue(controller.signal)
onTestFinished(() => { timeout.mockRestore() })
const request: typeof fetch = async (_url, options) => {
expect(options?.signal).toBe(controller.signal)
controller.abort(new DOMException('fixture timeout', 'TimeoutError'))
options?.signal?.throwIfAborted()
throw new Error('Expected an aborted request')
}
await expect(createGitHubJsonReader({ GH_TOKEN: 'fixture-token' }, request)('repos/owner/repo')).rejects.toThrow('timed out')
expect(timeout).toHaveBeenCalledExactlyOnceWith(60_000)
})
+197 -61
View File
@@ -1,74 +1,210 @@
/** Select one retained, successful CUA packaging attempt without contacting the Mac runner. */
import { execFileSync } from 'node:child_process'
import { appendFileSync, readFileSync } from 'node:fs'
/** Find a matching retained helper on the Mac runner before installing dependencies. */
import assert from 'node:assert/strict'
import { appendFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { z } from 'zod'
import { isEntry } from '../release/process.ts'
import { cuaHelperSourceMatches } from './build-inputs.ts'
const positiveId = z.string().regex(/^[1-9]\d*$/u)
const inputsSchema = z.object({
cua_run_id: positiveId,
cua_run_attempt: z.union([positiveId, z.literal('')]).optional(),
})
const runSchema = z.object({
id: z.number().int().positive(), run_attempt: z.number().int().positive(),
status: z.literal('completed'), conclusion: z.string().nullable(), event: z.literal('workflow_dispatch'),
path: z.enum(['.github/workflows/cua-helper-package.yml', '.github/workflows/release-publish.yml']),
repository: z.object({ full_name: z.string() }),
})
const jobsSchema = z.array(z.object({ jobs: z.array(z.object({ name: z.string(), conclusion: z.string().nullable() })) }))
const artifactsSchema = z.array(z.object({ artifacts: z.array(z.object({
id: z.number().int().positive(), name: z.string(), expired: z.boolean(), size_in_bytes: z.number().int().nonnegative(),
})) }))
const workflows = ['cua-helper-package.yml', 'release-publish.yml'] as const
function record(value: unknown): Record<string, unknown> {
assert(value !== null && typeof value === 'object' && !Array.isArray(value), 'CUA reuse: invalid GitHub object')
return value as Record<string, unknown>
}
function id(value: unknown): string {
assert(typeof value === 'number' && Number.isSafeInteger(value) && value > 0, 'CUA reuse: invalid GitHub identifier')
return String(value)
}
function rows(value: unknown, key: string): Record<string, unknown>[] {
assert(Array.isArray(value), 'CUA reuse: expected paginated GitHub response')
return value.flatMap((page: unknown) => {
const entries = record(page)[key]
assert(Array.isArray(entries), `CUA reuse: invalid GitHub ${key}`)
return entries.map(record)
})
}
/** Exact producer attempt and immutable artifact selected by the Mac workflow. */
export interface CuaHelperSelection {
readonly runId: string
readonly attempt: string
readonly artifactId: string
}
/**
* Pin an explicit attempt or the latest attempt once, then select its immutable artifact ID.
* A successful helper job in a completed publication run is reusable even if later npm jobs failed.
* Failure returns no selection; there is no fallback to another attempt. Payload validation remains with stage.ts.
* @param repository - Repository containing the producer and consuming release.
* @param inputsValue - Untrusted dispatch fields cua_run_id and optional cua_run_attempt.
* @param api - Read-only GitHub JSON reader; paginated responses must be arrays of pages.
* @returns Exact run, attempt and artifact to download before source/version and application validation.
* Select the last executed helper job, preserving its producer attempt across pack/publish-only reruns.
* Automatic misses rebuild; explicit misses and unreadable GitHub evidence fail without selecting another run.
* @param repository - Same repository that owns the producer and consumer.
* @param runId - Optional decimal run ID; empty selects automatic discovery.
* @param buildKey - Source and machine configuration digest required by the consumer.
* @param api - Read-only GitHub JSON reader; paginated responses are arrays of pages.
* @param matchesSource - Independent comparison of the producer head SHA with the consuming build inputs.
* @param now - Discovery time; automatic search covers the artifact's 14-day retention window.
* @returns Resolves to the matching producer artifact, or undefined when automatic discovery has no match.
*/
export function selectCuaHelperArtifact(repository: string, inputsValue: unknown,
api: (path: string, paginate?: boolean) => unknown): { runId: string; attempt: string; artifactId: string } {
if (!/^[\w.-]+\/[\w.-]+$/u.test(repository) || repository.split('/').some(part => part === '.' || part === '..')) {
throw new Error('CUA reuse: invalid repository')
export async function selectCuaHelperArtifact(repository: string, runId: string, buildKey: string,
api: (path: string, paginate?: boolean) => Promise<unknown>, matchesSource: (commit: string) => Promise<boolean>,
now = new Date()): Promise<CuaHelperSelection | undefined> {
assert(/^[\w.-]+\/[\w.-]+$/u.test(repository) && !repository.split('/').some(part => part === '.' || part === '..'),
'CUA reuse: invalid repository')
assert(runId === '' || /^[1-9]\d*$/u.test(runId), 'CUA reuse: enter the numeric run ID after /actions/runs/ in the run URL')
assert(/^[a-f0-9]{64}$/u.test(buildKey), 'CUA reuse: invalid build key')
const base = `repos/${repository}/actions`
const selectRun = async (candidate: string, retained?: Record<string, unknown>[]): Promise<CuaHelperSelection | string> => {
const attempt = id(record(await api(`${base}/runs/${candidate}`)).run_attempt)
const run = record(await api(`${base}/runs/${candidate}/attempts/${attempt}`))
assert(id(run.id) === candidate && id(run.run_attempt) === attempt
&& record(run.repository).full_name === repository && record(run.head_repository).full_name === repository,
'CUA reuse: selected run, attempt or repository does not match GitHub evidence')
const workflow = workflows.find(name => run.path === `.github/workflows/${name}`)
assert(workflow && run.event === 'workflow_dispatch', 'CUA reuse: select a supported repository packaging or release run')
if (run.status !== 'completed') return 'the latest attempt has not completed'
if (workflow === 'cua-helper-package.yml' && run.conclusion !== 'success') return 'the latest packaging attempt did not succeed'
const jobName = workflow === 'cua-helper-package.yml' ? 'package' : 'cua-helper / package'
const jobs = rows(await api(`${base}/runs/${candidate}/jobs?filter=all&per_page=100`, true), 'jobs')
.filter(job => job.name === jobName)
const attempts = jobs.map(job => Number(id(job.run_attempt)))
assert(attempts.every(value => value <= Number(attempt)), 'CUA reuse: run advanced during selection; retry with the same run ID')
const producerAttempt = Math.max(0, ...attempts)
const producers = jobs.filter(job => job.run_attempt === producerAttempt)
if (producers.length !== 1 || producers[0]?.conclusion !== 'success') return `the last executed ${jobName} job did not succeed`
const name = `cua-helper-${candidate}-${producerAttempt}-${buildKey}`
const artifacts = (retained ?? rows(await api(`${base}/runs/${candidate}/artifacts?per_page=100`, true), 'artifacts'))
.filter(artifact => artifact.name === name)
if (artifacts.length === 0) return 'no artifact matches the current source bytes and build configuration; use the producer run linked in its summary or rebuild'
const [artifact] = artifacts
assert(artifacts.length === 1 && artifact !== undefined, 'CUA reuse: matching artifact is ambiguous')
assert(typeof artifact.expired === 'boolean' && typeof artifact.size_in_bytes === 'number', 'CUA reuse: invalid artifact metadata')
if (artifact.expired || artifact.size_in_bytes <= 0) return 'the matching artifact is expired or empty'
assert(typeof run.head_sha === 'string' && /^[a-f0-9]{40}$/u.test(run.head_sha), 'CUA reuse: invalid producer head SHA')
if (!await matchesSource(run.head_sha)) return 'the producer commit has different helper build inputs'
return { runId: candidate, attempt: String(producerAttempt), artifactId: id(artifact.id) }
}
const inputs = inputsSchema.parse(inputsValue)
const base = `repos/${repository}/actions/runs/${inputs.cua_run_id}`
const attempt = inputs.cua_run_attempt
|| String(z.object({ run_attempt: z.number().int().positive() }).parse(api(base)).run_attempt)
const run = runSchema.parse(api(`${base}/attempts/${attempt}`))
if (String(run.id) !== inputs.cua_run_id || String(run.run_attempt) !== attempt || run.repository.full_name !== repository) {
throw new Error('CUA reuse: selected run, attempt or repository does not match GitHub evidence')
if (runId !== '') {
const selected = await selectRun(runId)
if (typeof selected === 'string') throw new Error(`CUA reuse: run ${runId}: ${selected}`)
return selected
}
const jobName = run.path === '.github/workflows/cua-helper-package.yml' ? 'package' : 'cua-helper / package'
if (jobName === 'package' && run.conclusion !== 'success') {
throw new Error('CUA reuse: standalone packaging did not succeed; select a successful attempt')
const since = new Date(now.getTime() - 14 * 24 * 60 * 60 * 1000).toISOString()
const candidates: Record<string, unknown>[] = []
for (const workflow of workflows) {
candidates.push(...rows(await api(
`${base}/workflows/${workflow}/runs?event=workflow_dispatch&status=completed&created=${encodeURIComponent(`>=${since}`)}&per_page=100`,
true), 'workflow_runs'))
}
const jobs = jobsSchema.parse(api(`${base}/attempts/${attempt}/jobs?per_page=100`, true))
.flatMap(page => page.jobs).filter(job => job.name === jobName)
if (jobs.length !== 1 || jobs[0]?.conclusion !== 'success') {
throw new Error(`CUA reuse: run ${inputs.cua_run_id}, attempt ${attempt} requires one successful ${jobName} job;`
+ ' select a successful attempt')
candidates.sort((left, right) => Number(id(right.id)) - Number(id(left.id)))
for (const candidate of candidates) {
const candidateId = id(candidate.id)
const artifacts = rows(await api(`${base}/runs/${candidateId}/artifacts?per_page=100`, true), 'artifacts')
if (!artifacts.some(artifact => typeof artifact.name === 'string'
&& artifact.name.startsWith(`cua-helper-${candidateId}-`) && artifact.name.endsWith(`-${buildKey}`))) continue
const selected = await selectRun(candidateId, artifacts)
if (typeof selected !== 'string') return selected
}
const name = `cua-helper-${inputs.cua_run_id}-${attempt}`
const artifacts = artifactsSchema.parse(api(`${base}/artifacts?per_page=100`, true))
.flatMap(page => page.artifacts).filter(artifact => artifact.name === name)
const [artifact] = artifacts
if (artifacts.length !== 1 || artifact === undefined || artifact.expired || artifact.size_in_bytes === 0) {
throw new Error(`CUA reuse: ${name} is missing, expired, empty or ambiguous; select an available build or rebuild`)
}
return { runId: inputs.cua_run_id, attempt, artifactId: String(artifact.id) }
return undefined
}
if (process.argv[1] !== undefined && resolve(process.argv[1]) === import.meta.filename) {
/**
* Create authenticated, read-only GitHub requests using Node's built-in fetch.
* Each call, including pagination, has a 60-second deadline and a 32 MiB response limit.
* Pagination stays on the configured API origin. Request or parsing failures never return partial pages.
* @param environment - GH_TOKEN and optional GITHUB_API_URL supplied by Actions.
* @param request - HTTP transport receiving the authenticated URL and request options.
* @returns JSON reader; paginated calls resolve to an array of page objects.
*/
export function createGitHubJsonReader(environment: NodeJS.ProcessEnv, request: typeof fetch = fetch):
(path: string, paginate?: boolean) => Promise<unknown> {
const token = environment.GH_TOKEN?.trim()
if (!token) throw new Error('CUA reuse: GH_TOKEN is required for GitHub API access')
const configured = environment.GITHUB_API_URL ?? 'https://api.github.com'
let base: URL
try { base = new URL(configured.endsWith('/') ? configured : `${configured}/`) } catch (_error) {
// URL parser errors may include credential-bearing configuration.
throw new Error('CUA reuse: GITHUB_API_URL must be a valid HTTPS API URL')
}
assert(base.protocol === 'https:' && !base.username && !base.password && !base.search && !base.hash,
'CUA reuse: GITHUB_API_URL must be HTTPS without credentials, query or fragment')
return async (path, paginate = false) => {
let target = new URL(path, base)
const visited = new Set<string>()
const pages: unknown[] = []
let bytes = 0
const signal = AbortSignal.timeout(60_000)
while (true) {
assert(target.origin === base.origin && target.pathname.startsWith(base.pathname)
&& !target.username && !target.password && !target.hash, 'CUA reuse: GitHub pagination left the configured API')
assert(!visited.has(target.href), 'CUA reuse: GitHub returned a pagination cycle')
visited.add(target.href)
let response: Response
try {
response = await request(target, {
headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json',
'X-GitHub-Api-Version': '2026-03-10', 'User-Agent': 'deepseek-harness-cua-helper' },
redirect: 'error', signal,
})
} catch (error) {
throw new Error('CUA reuse: GitHub request failed or timed out; check connectivity and retry this workflow', { cause: error })
}
if (!response.ok) {
try { await response.body?.cancel() } catch (_error) {
// A failed body stream must not hide the HTTP failure already received.
}
throw new Error(`CUA reuse: GitHub request failed (HTTP ${response.status}); check token permissions, rate limits or service availability, then retry`)
}
const reader = response.body?.getReader()
if (!reader) throw new Error('CUA reuse: GitHub returned an empty response')
const chunks: Uint8Array[] = []
try {
while (true) {
const chunk = await reader.read()
if (chunk.done) break
bytes += chunk.value.byteLength
if (bytes > 32 * 1024 * 1024) {
await reader.cancel()
throw new Error('CUA reuse: GitHub response exceeds 32 MiB')
}
chunks.push(chunk.value)
}
} finally { reader.releaseLock() }
let value: unknown
try { value = JSON.parse(Buffer.concat(chunks).toString('utf8')) } catch (_error) {
// JSON parser errors may include response bytes.
throw new Error('CUA reuse: GitHub returned invalid JSON; retry this workflow')
}
if (!paginate) return value
pages.push(value)
const link = response.headers.get('link') ?? ''
const next = /<([^>]+)>\s*;\s*rel="next"/u.exec(link)?.[1]
assert(next || !link.includes('rel="next"'), 'CUA reuse: GitHub returned an invalid pagination link')
if (!next) return pages
target = new URL(next, target)
}
}
}
if (isEntry(import.meta.url)) {
const env = process.env
if (!env.GITHUB_EVENT_PATH || !env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT) throw new Error('CUA reuse: Actions context required')
const event = z.object({ inputs: inputsSchema }).parse(JSON.parse(readFileSync(env.GITHUB_EVENT_PATH, 'utf8')))
const selection = selectCuaHelperArtifact(env.GITHUB_REPOSITORY, event.inputs, (path, paginate) =>
JSON.parse(execFileSync('gh', ['api', ...(paginate ? ['--paginate', '--slurp'] : []), path],
{ encoding: 'utf8', timeout: 60_000, maxBuffer: 8 * 1024 * 1024 })))
appendFileSync(env.GITHUB_OUTPUT, `artifact-id=${selection.artifactId}\nattempt=${selection.attempt}\n`)
console.log(`CUA helper: run ${selection.runId}, attempt ${selection.attempt}, artifact ${selection.artifactId}`)
if (!env.GITHUB_REPOSITORY || !env.GITHUB_OUTPUT || !env.GITHUB_STEP_SUMMARY || !env.CUA_BUILD_KEY) {
throw new Error('CUA reuse: Actions context and CUA_BUILD_KEY are required')
}
const githubJson = createGitHubJsonReader(env)
const repository = env.GITHUB_REPOSITORY
const root = resolve(import.meta.dirname, '../..')
const sourceMatches = new Map<string, boolean>()
const selection = await selectCuaHelperArtifact(repository, env.CUA_RUN_ID ?? '', env.CUA_BUILD_KEY, githubJson, async (commit) => {
let matches = sourceMatches.get(commit)
if (matches === undefined) {
matches = await cuaHelperSourceMatches(root, repository, commit, githubJson)
sourceMatches.set(commit, matches)
}
return matches
})
appendFileSync(env.GITHUB_OUTPUT, `artifact-id=${selection?.artifactId ?? ''}\nrun-id=${selection?.runId ?? ''}\n`)
const summary = selection
? `复用 [CUA helper 构建](https://github.com/${repository}/actions/runs/${selection.runId}/attempts/${selection.attempt}),run ID \`${selection.runId}\`,artifact ID \`${selection.artifactId}\`。跳过依赖安装、编译、签名和公证。`
: '未找到源码逐字节一致且构建配置匹配的可用 CUA helper 产物,执行依赖安装和重新构建。'
appendFileSync(env.GITHUB_STEP_SUMMARY, `${summary}\n`)
console.log(summary)
}
+5 -6
View File
@@ -1,14 +1,13 @@
/** Stage the signed helper artifact selected by the credential-free npm pack job. */
import { execFileSync } from 'node:child_process'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { parseArgs } from 'node:util'
import { cuaHelperSourceDigest } from './build-inputs.ts'
import { stageCuaHelperPayload } from './payload.ts'
const { values } = parseArgs({ options: { from: { type: 'string' } }, allowPositionals: false })
if (!values.from) throw new Error('Usage: stage.ts --from <extracted-helper-artifact>')
const root = resolve(import.meta.dirname, '../..')
const { version } = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as { version: string }
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim()
stageCuaHelperPayload(resolve(values.from), resolve(root, 'packages/experimental/cua-macos'), { version, commit })
console.log(`CUA helper staged for ${version} (${commit})`)
const expected = { sourceDigest: cuaHelperSourceDigest(root),
...(process.env.CUA_EXPECTED_BUILD_KEY === undefined ? {} : { buildKey: process.env.CUA_EXPECTED_BUILD_KEY }) }
stageCuaHelperPayload(resolve(values.from), resolve(root, 'packages/experimental/cua-macos'), expected)
console.log(`CUA helper staged for source digest ${expected.sourceDigest}`)
+2 -2
View File
@@ -8,10 +8,10 @@ import { verifyCuaHelperPayload } from './payload.ts'
/**
* Verify both helper applications in the exact provider tarball being published.
* @param tarball - pnpm-produced provider package archive.
* @param expected - Product version and source commit of the publishing checkout.
* @param expected - Helper source digest of the publishing checkout.
* @returns Resolves only when the archive has complete, digest-verified application generations.
*/
export async function verifyCuaHelperTarball(tarball: string, expected: { version: string; commit: string }): Promise<void> {
export async function verifyCuaHelperTarball(tarball: string, expected: { sourceDigest: string }): Promise<void> {
const root = mkdtempSync(join(tmpdir(), 'cua-publish-verify-'))
try {
await extract({ file: tarball, cwd: root, strict: true, filter: (path, entry) => {
+28
View File
@@ -0,0 +1,28 @@
/** Shared assertions for original-build routing and artifact identity in packaging workflows. */
import { expect } from 'vitest'
/**
* Require archival steps to retain the original machine, directory and build identity.
* @param job Parsed archival job from a packaging workflow.
* @param count Expected number of artifact upload steps.
* @returns The checked upload steps, preserving platform-specific fields.
*/
export function expectDesktopArchive<S extends { uses?: string; with?: Record<string, unknown> }>(
job: { 'runs-on': string | string[]; env: Record<string, string>; steps: S[] }, count: number,
): S[] {
expect(job['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
expect(job.env).toMatchObject({
DESKTOP_RETAINED_DIRECTORY: '${{ needs.package.outputs.directory }}',
DESKTOP_PACKAGE_ATTEMPT: '${{ needs.package.outputs.attempt }}',
DESKTOP_PACKAGE_RUNNER: '${{ needs.package.outputs.runner-name }}',
})
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(count)
for (const step of uploads) {
expect(step.with?.name).toBe('${{ env.DESKTOP_ARCHIVE_NAME }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.version }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).toContain('${{ needs.package.outputs.attempt }}')
expect(job.env.DESKTOP_ARCHIVE_NAME).not.toContain('github.run_attempt')
}
return uploads
}
+4
View File
@@ -23,6 +23,7 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
mkdirSync(join(root, 'apps/desktop/scripts'), { recursive: true })
writeFileSync(join(root, 'package.json'), '{"version":"1.0.0"}')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'PACKAGE_VERSION_MODE')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
git('add', '.')
git('-c', 'user.name=Fixture', '-c', '[email protected]', '-c', 'commit.gpgsign=false', 'commit', '-m', 'fixture')
const sha = git('rev-parse', 'HEAD')
@@ -51,6 +52,9 @@ it.each(['macos', 'windows'])('%s packaging accepts test branches but preserves
}
for (const preset of ['test', 'production']) expect(run(preset, 'dsh-v1.0.0').status).toBe(0)
expect(run('test', 'dsh-v2.0.0').status).not.toBe(0)
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), 'old archival adapter')
expect(run('test', 'dsh-v1.0.0').stderr).toContain('independent Desktop artifact archival support')
writeFileSync(join(root, 'apps/desktop/scripts/retain-desktop-ci.ts'), '--check-runner')
writeFileSync(join(root, 'apps/desktop/scripts/desktop-ci-version.mjs'), 'old adapter')
expect(run('test', 'dsh-v1.0.0').status).not.toBe(0)
} finally { rmSync(root, { recursive: true, force: true, maxRetries: 3 }) }
+23
View File
@@ -9,6 +9,7 @@ const workflow = yaml.load(readFileSync(resolve(import.meta.dirname, '../.github
permissions: Record<string, string>
jobs: Record<string, {
defaults?: unknown
concurrency?: { group: string; 'cancel-in-progress': boolean }
needs?: string | string[]
env?: Record<string, string>
if?: string
@@ -78,3 +79,25 @@ it('rejects non-master dispatch before scheduling a self-hosted job', () => {
if (result.status !== 0) expect(result.stderr).toContain('must be dispatched from master')
}
})
it('defaults to production website upload and separates cache-only recovery', () => {
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { upload_website: { type: 'boolean', default: true } } })
expect(workflow.jobs.prepare!.env?.DESKTOP_UPLOAD_WEBSITE).toBe('${{ inputs.upload_website }}')
expect(workflow.jobs.prepare!.env?.DOWNLOAD_PROD_EO_ZONE_ID).toBe('${{ vars.DOWNLOAD_PROD_EO_ZONE_ID }}')
const upload = workflow.jobs['upload-website-installer']!
const purge = workflow.jobs['purge-website-installer']!
expect(purge.needs).toEqual(['route', 'prepare', 'upload-website-installer'])
expect(upload.concurrency).toEqual({ group: 'desktop-website-upload-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
expect(purge.concurrency).toEqual({ group: 'desktop-website-purge-${{ needs.prepare.outputs.website-destination }}', 'cancel-in-progress': false })
for (const job of [upload, purge]) {
expect(job.if).toBe("inputs.upload_website && needs.prepare.outputs.preset != 'test'")
expect(job.environment).toBe('desktop-production')
const preflight = job.steps.findIndex(step => step.run === 'node apps/desktop/scripts/preflight-desktop-publish-local.mjs')
expect(preflight).toBeGreaterThan(-1)
expect(preflight).toBeLessThan(job.steps.findIndex(step => step.run === 'pnpm install --frozen-lockfile'))
expect(job.env?.DESKTOP_WEBSITE_APPROVAL).toBe('${{ needs.prepare.outputs.website-approval }}')
}
expect(upload.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts upload')
expect(purge.steps.find(step => step.id === 'website')?.run).toBe('node --import tsx apps/desktop/scripts/publish-website-ci.ts purge')
expect(purge.steps.some(step => step.run?.includes('publish-desktop-ci.ts'))).toBe(false)
})
+4 -4
View File
@@ -1,4 +1,4 @@
/** Retained package names keep experimental isolation and persisted record namespaces. */
/** Unprefixed and legacy prefixed package names keep experimental isolation and persisted record namespaces. */
import { describe, expect, it } from 'vitest'
import {
@@ -19,7 +19,7 @@ describe('experimental package identities', () => {
}
})
it.each(names)('does not extend the retained-name exception %s to another package', (name) => {
it.each(names)('does not extend the unprefixed name %s to another package', (name) => {
for (const reference of [`${name}-unrelated`, `other-${name}`, name.replace('@deepseek-ai/', '@other/')]) {
expect(isExperimentalPackageName(reference)).toBe(false)
expect(hasExperimentalPackageReference(reference)).toBe(false)
@@ -27,12 +27,12 @@ describe('experimental package identities', () => {
}
})
it('keeps new experimental packages under their prefixed namespaces', () => {
it('derives the record namespace from a legacy prefixed name', () => {
expect(experimentalPackageRecordNamespace('@deepseek-ai/dsh-experimental-bridge')).toBe('bridge')
expect(hasExperimentalPackageReference('@deepseek-ai/dsh-core')).toBe(false)
})
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('keeps %s record names independent of the retained npm name', (directory, name) => {
it.each(Object.entries(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))('keeps %s record names independent of the unprefixed npm name', (directory, name) => {
expect(experimentalPackageRecordNamespace(name)).toBe(directory.split('/').at(-1))
})
})
+54 -8
View File
@@ -1,9 +1,9 @@
/** Experimental package identities, publication policy, and retained npm names. */
/** Experimental package identities, publication policy, and npm names. */
/**
* Experimental packages whose npm names omit the experimental prefix, by directory: identities retained across
* experimental classification and package-role moves, and packages named without the prefix so that leaving
* experimental status keeps their names.
* Experimental packages whose npm names omit the experimental prefix, by directory. Every new experimental package
* belongs here so that promotion keeps its name; isolation checks and plugin-record ownership recognize an unprefixed
* experimental name only through this map.
*/
export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, string>> = {
'packages/experimental/cua': '@deepseek-ai/dsh-cua',
@@ -27,17 +27,63 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, strin
'packages/experimental/personalized-recommendations': '@deepseek-ai/dsh-personalized-recommendations',
} satisfies Record<`packages/experimental/${string}`, `@deepseek-ai/dsh-${string}`>
/** npm namespace for experimental packages without retained-name exceptions. */
/** Legacy npm namespace, allowed only in `LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES`. */
export const EXPERIMENTAL_PACKAGE_NAME_PREFIX = '@deepseek-ai/dsh-experimental-'
const retainedNames = new Set(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))
/** Existing experimental packages that keep the legacy prefix until a rename; this list must not grow. */
export const LEGACY_PREFIXED_EXPERIMENTAL_PACKAGE_DIRECTORIES: readonly string[] = [
'packages/experimental/api-speech-to-text',
'packages/experimental/auto-review',
'packages/experimental/badge-skill-bundle',
'packages/experimental/browser-use-chrome-devtools-mcp',
'packages/experimental/browser-use-playwright-mcp',
'packages/experimental/browser-use-runtime',
'packages/experimental/browser-use-stagehand-native',
'packages/experimental/claude-code-mods',
'packages/experimental/client-ui-claude-code-mods',
'packages/experimental/client-ui-cot-translation',
'packages/experimental/client-ui-forge',
'packages/experimental/client-ui-stats',
'packages/experimental/client-ui-voice-input',
'packages/experimental/computer-use-cua-driver-mcp',
'packages/experimental/computer-use-cua-driver-native',
'packages/experimental/cot-translation-bundle',
'packages/experimental/cua-macos',
'packages/experimental/forge',
'packages/experimental/forge-bundle',
'packages/experimental/forge-github',
'packages/experimental/forge-session',
'packages/experimental/inspector',
'packages/experimental/inspector-profile',
'packages/experimental/liveshare',
'packages/experimental/liveshare-protocol',
'packages/experimental/plugin-market-bundle',
'packages/experimental/ptc-runtime-python',
'packages/experimental/ralph-bundle',
'packages/experimental/session-inspector',
'packages/experimental/session-search',
'packages/experimental/session-titles-bundle',
'packages/experimental/speech-to-text',
'packages/experimental/speech-to-text-sensevoice',
'packages/experimental/subagent-oar',
'packages/experimental/terminal-bundle',
'packages/experimental/tool-subagent-oar',
'packages/experimental/tool-worktree',
'packages/experimental/translator',
'packages/experimental/voice-input-bundle',
'packages/experimental/webworker-packer',
'packages/experimental/webworker-runtime',
'packages/experimental/worktree',
]
const unprefixedNames = new Set(Object.values(EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS))
/**
* Identify an experimental npm package independently of its installed directory.
* @param name - complete npm package name, without a version or subpath.
* @returns Whether the name uses the experimental prefix or a retained name.
* @returns Whether the name uses the legacy prefix or appears in `EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS`.
*/
export function isExperimentalPackageName(name: string): boolean {
return name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) || retainedNames.has(name)
return name.startsWith(EXPERIMENTAL_PACKAGE_NAME_PREFIX) || unprefixedNames.has(name)
}
/**
+5 -1
View File
@@ -241,13 +241,17 @@ describe('the real workspace surface', () => {
expect(entries.length).toBeGreaterThan(30)
for (const entry of entries) {
expect(entry.summary, `${entry.key} has no summary`).not.toBe('')
expect(['single', 'list', 'keyed', 'chain']).toContain(entry.kind)
expect(['single', 'list', 'keyed', 'chain', 'hoc']).toContain(entry.kind)
expect(['root', 'session', 'session-maybe']).toContain(entry.scope)
}
// The frame root is the canonical trap: occupied by the shipped app frame,
// so a dynamic package registering there replaces the whole UI.
const root = entries.find(entry => entry.key === 'root')
expect(root?.replaceRisk).toBe('shadows-shipped-ui')
// A hoc layer wraps the owner content; its example must keep rendering it.
const frame = entries.find(entry => entry.key === 'conversation.hero.frame')
expect(frame?.replaceRisk).toBe('wraps-owner-content')
expect(frame?.example).toContain('({ children }) => React.createElement(\'div\', null, children)')
expect(root?.occupants.join(' ')).toContain('AppFrame')
expect(entries.find(entry => entry.key === 'conversation.session')?.declaredBy)
.toContain("factory 'conversation.content' (client-ui-conversation)")
+19 -7
View File
@@ -33,7 +33,7 @@ const OUT = 'packages/extensions/cordis-client-runner/src/client/slot-catalog.ts
const SOURCE_GLOBS = ['packages/*/*/src/**/*.ts', 'packages/*/*/src/**/*.tsx']
/** Slot cardinalities the contract allows. */
const KINDS = ['single', 'list', 'keyed', 'chain'] as const
const KINDS = ['single', 'list', 'keyed', 'chain', 'hoc'] as const
/** Slot data scopes the contract allows. */
const SCOPES = ['root', 'session', 'session-maybe'] as const
@@ -82,6 +82,10 @@ const REGISTER_OPTIONS: Readonly<Record<(typeof KINDS)[number], readonly OptionD
chain: [
{ name: 'select', requirement: 'required', type: '(owner) => unknown | null', doc: 'Pure routing selector. Entries are tried in ascending order; the first non-null result wins and arrives as the component\'s `matched` prop. All-null falls through to the owner\'s fallback.' },
],
hoc: [
{ name: 'id', requirement: 'required', type: 'string', doc: 'Your layer key. A fresh id adds a layer; reusing a shipped id replaces that layer. Your component must render its `children` prop: a layer that omits it hides the owner content, such as the whole conversation and its composer.' },
{ name: 'order', requirement: 'optional', type: 'number', doc: 'Nesting position, ascending (default 0); the lowest order is the outermost layer. Render the `children` prop exactly once.' },
],
}
/** The one register option a dynamic package must NOT pass, and why. */
@@ -301,9 +305,11 @@ function entryOf(
...occupant.id === undefined ? [] : [`id '${occupant.id}'`],
...occupant.entryKey === undefined ? [] : [`key '${occupant.entryKey}'`],
].join(' ')),
replaceRisk: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
? 'shadows-shipped-ui'
: 'none',
replaceRisk: declaration.kind === 'hoc'
? 'wraps-owner-content'
: cellOccupied && (declaration.kind === 'single' || declaration.kind === 'keyed')
? 'shadows-shipped-ui'
: 'none',
example: exampleOf(declaration),
source: declaration.source,
}
@@ -365,7 +371,9 @@ function exampleOf(declaration: SlotDeclaration): string {
' apply(ctx) {',
` ctx.slots.inject('${declaration.key}', () => ctx.slots.register(`,
` { ${options} },`,
" () => React.createElement('div', null, 'hello'),",
declaration.kind === 'hoc'
? " ({ children }) => React.createElement('div', null, children),"
: " () => React.createElement('div', null, 'hello'),",
' ))',
' },',
'}',
@@ -393,6 +401,7 @@ const KIND_EXAMPLE: Readonly<Record<string, readonly string[]>> = {
list: ["id: 'my-entry'", 'order: 100', "label: 'My entry'"],
keyed: ["key: '<one key the owner dispatches>'"],
chain: ['select: owner => null'],
hoc: ["id: 'my-layer'", 'order: 100'],
}
/** Drop the `@deepseek-ai/dsh-` prefix so rows stay readable. */
@@ -476,7 +485,7 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
'export interface ClientSlotEntry {',
' /** SlotMap key passed as the register call\'s `name`. */',
' key: string',
' /** Cardinality: `single`, `list`, `keyed`, or `chain`. */',
' /** Cardinality: `single`, `list`, `keyed`, `chain`, or `hoc`. */',
' kind: string',
' /** Data scope: `root`, `session`, or `session-maybe`. */',
' scope: string',
@@ -502,7 +511,10 @@ export function renderClientCatalog(entries: readonly SlotEntry[]): string {
' declaredBy: string',
' /** Entries the shipped composition already registered here. */',
' occupants: readonly string[]',
' /** `shadows-shipped-ui` when registering here replaces shipped UI; `none` when additive. */',
' /**',
' * `shadows-shipped-ui` when registering here replaces shipped UI; `wraps-owner-content` when your',
' * component wraps the owner content and must render `children`; `none` when additive.',
' */',
' replaceRisk: string',
' /** A minimal browser half that registers into this slot. */',
' example: string',
+12
View File
@@ -69,6 +69,7 @@ export const SERVICE_PAGE: Record<string, string> = {
hmr: 'boot.md',
mcpResources: 'mcp.md',
agentLoop: 'core.md',
mcpManager: 'mcp.md',
agentDefaultModel: 'core.md',
agentPresets: 'core.md',
agents: 'core.md',
@@ -254,6 +255,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
'schedule': 'schedule.md',
'llm': 'llm-streaming.md',
'llm-pi-ai': 'llm-streaming.md',
'mcp-manager': 'mcp.md',
'permission-presets': 'permission-presets.md',
'session': 'session.md',
'settings': 'settings.md',
@@ -264,6 +266,7 @@ export const EVENT_SCOPE_PAGE: Record<string, string> = {
'feedback': 'feedback.md',
'tools': 'tools.md',
'user-questions': 'user-questions.md',
'web': 'web.md',
'webserver': 'web-server.md',
'workflow': 'workflow.md',
'workspace': 'workspace.md',
@@ -403,6 +406,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
ForgeLineComment: 'forge.md',
ForgeReviewRequest: 'forge.md',
ForgeReviewResult: 'forge.md',
ForgeBaseBranches: 'forge.md',
ForgeBranches: 'forge.md',
ForgeChangeRequestDiff: 'forge.md',
ForgeChangeRequestStatesFrame: 'forge.md',
@@ -739,6 +743,7 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
SubagentInterruptAuthority: 'subagent.md',
SubagentInterruptReceipt: 'subagent.md',
SubagentListEntry: 'subagent.md',
SubagentMemberNames: 'subagent.md',
SubagentPromptReceipt: 'subagent.md',
SubagentPromptRequest: 'subagent.md',
SubagentProvider: 'subagent.md',
@@ -882,6 +887,8 @@ export const LINK_MAP: Readonly<Record<string, string>> = {
WebFetchProvider: 'web.md',
WebFetchRequest: 'web.md',
WebFetchResult: 'web.md',
WebProviderInfo: 'web.md',
WebProviderList: 'web.md',
WebSearchProvider: 'web.md',
WebSearchRequest: 'web.md',
WebSearchResult: 'web.md',
@@ -1010,6 +1017,11 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
ConsumeTokenRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
InsertTextRequest: 'event-local request contract is owned by packages/client/ui-input-trigger/src/types.ts',
AgentHandle: 'agent ownership handle is owned by packages/core/agent/README.md',
McpManagedServerStatus: 'managed-server status union is owned by packages/mcp/mcp-manager/README.md',
McpManagedServerView: 'managed-server list view is owned by packages/mcp/mcp-manager/README.md',
McpServerRegistration: 'plugin-registered server entry is owned by packages/mcp/mcp-manager/README.md',
McpProbeOptions: 'probe options are owned by packages/mcp/mcp-client/README.md',
McpProbeResult: 'probe outcome union is owned by packages/mcp/mcp-client/README.md',
AgentPreset: 'discovered preset record is owned by packages/preset/agent-preset-registry/README.md',
AgentPresetRoster: 'path-free preset roster is owned by packages/preset/agent-preset-registry/README.md',
PresetDefinition: 'declarative configuration is owned by packages/preset/agent-preset/README.md',
+9 -2
View File
@@ -487,7 +487,7 @@ const SERVICE_ROLES: ServiceRole[] = [
mode: 'seam',
implementations: ['credentials-local'],
consumers: ['api-settings-controller', 'llm-deepseek', 'llm-pi-ai'],
note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free metadata, writes, and owner-only reads of stored keys.',
note: 'Configuration carries references to secrets; providers own the values. Consumers resolve per operation, so a rotated credential reaches the very next request; the settings controller exposes value-free views and write-only storage.',
},
{
key: 'deepseekAccount',
@@ -705,6 +705,13 @@ const SERVICE_ROLES: ServiceRole[] = [
consumers: ['base', 'sdk-minimal'],
note: 'The one concrete loop plugin; extension packages depend on dsh-agent events and services, not on this package.',
},
{
key: 'mcpManager',
pkg: 'mcp-manager',
title: 'Settings-driven MCP server fleet',
mode: 'core',
note: 'Reconciles mcp-client instances against its volatile servers configuration, aggregates their connection statuses, and serves restart and probe to management surfaces.',
},
{
key: 'schedule',
pkg: 'schedule',
@@ -879,7 +886,7 @@ const SERVICE_ROLES: ServiceRole[] = [
pkg: 'web',
title: 'Web access provider registry',
mode: 'seam',
implementations: ['web-search-exa', 'web-search-perplexity', 'web-search-deepseek', 'web-deepseek-api', 'web-fetch-http'],
implementations: ['web-search-deepseek', 'web-deepseek-api', 'web-fetch-http'],
consumers: ['tool-web'],
note: 'Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names.',
},
+5 -5
View File
@@ -38,7 +38,7 @@ import type { ImageAttachmentLimits, ImageAttachmentRef, SaveImageAttachment, St
import UserQuestionService from '@deepseek-ai/dsh-user-questions'
import PlanModeController from '@deepseek-ai/dsh-plan-mode'
import WebRuntime from '@deepseek-ai/dsh-web'
import * as WebSearchExa from '@deepseek-ai/dsh-web-search-exa'
import * as WebDeepSeekApi from '@deepseek-ai/dsh-web-deepseek-api'
import * as WebFetchLocal from '@deepseek-ai/dsh-web-fetch-http'
import SubagentRuntime from '@deepseek-ai/dsh-subagent'
import type { SubagentProvider } from '@deepseek-ai/dsh-subagent'
@@ -297,7 +297,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
await ctx.plugin(NodePtcRuntime)
},
note:
'The PTC executor exposes only run_code to the model and declares other visible capabilities in a generated SDK in the runtime’s language. Program bindings enter the shared guarded tool pipeline in submission order; concurrency-safe bodies overlap up to maxParallelSubCalls, and nested results remain linked to the outer program.',
'The PTC executor exposes only run_code to the model and declares other visible capabilities in a generated SDK in the runtime’s language. Program bindings enter the shared guarded tool pipeline in submission order; concurrency-safe bodies overlap up to maxParallelSubCalls, and nested results remain linked to the outer program. The resolved timeout and maxSubCallsPerMinute set the total call allowance; exceeding it terminates the program.',
},
{
pkg: '@deepseek-ai/dsh-plan-mode',
@@ -600,7 +600,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
await ctx.plugin(ToolSubagent, { provider: 'mock', modelDiscovery: true })
},
note:
'The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns a child id promptly; local children accept follow-ups, while external backends report their single execution automatically.',
'The load-time `toolName` selects the delegation name (default `subagent`); `modelSelection` adds optional route fields. `modelDiscovery` defaults off and registers shared discovery on one instance per scope. Web and Desktop presets enable spawn discovery and route fields and leave `subagent_fork` route fields disabled. The Host settings service records authorization for each new top-level Session; child Sessions inherit it. Without a recorded policy, discovery and explicit selection permit only the current parent route. Every delegation returns the child\'s name promptly; local children accept follow-ups, while external backends report their single execution automatically.',
},
{
pkg: '@deepseek-ai/dsh-tool-subagent-control',
@@ -703,7 +703,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
})
await ctx.plugin(ToolWorktree)
},
note: 'Explicit experimental composition only. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout.',
note: 'Enabled through the Change requests & worktrees bundle on Web and Desktop; other profiles can select the standalone bundle. Creates a new branch and checkout from a pinned local commit under existing write permissions, then changes the Session directory. Leaving retains the branch and checkout.',
},
{
pkg: '@deepseek-ai/dsh-tool-workflow',
@@ -739,7 +739,7 @@ const TOOL_PACKAGES: ToolPackage[] = [
// Mount search and fetch providers so both tools register. Their schemas
// do not depend on provider identity or availability.
await ctx.plugin(WebRuntime)
await ctx.plugin(WebSearchExa)
await ctx.plugin(WebDeepSeekApi)
await ctx.plugin(WebFetchLocal)
await ctx.plugin(ToolWeb)
},
+1
View File
@@ -304,6 +304,7 @@ it('updates volatile children through Group and Include custom updates and saves
expect(initial.title.get()).toBe('group-update')
expect(group.options.config).toEqual([child('group-update')])
await includeEntry.fiber!.update({ path: includePath, patches: [{ id: 'consumer', config: { title: 'include-update' } }] })
await include.flush()
await ctx.loader.await()
expect(initial.title.get()).toBe('include-update')
expect(includeEntry.fiber).toBe(originalInclude)
+19 -6
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import yaml from 'js-yaml'
@@ -24,8 +25,16 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
}>
}
it('archives using the same persistent pnpm store as packaging', () => {
const cache = (job: string) => workflow.jobs[job]!.steps.find(step => step.name === 'Configure persistent package caches')
expect(cache('upload-artifact')).toEqual(cache('package'))
expect(cache('upload-artifact')?.run).toContain('PNPM_CONFIG_STORE_DIR=')
})
it('confines signed Mac packaging to manual dispatch and a dedicated Apple Silicon runner', () => {
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
expect(workflow.jobs.package!.env.PACKAGE_VERSION_MODE).toBe("${{ inputs.version_mode == 'follow-dsh' && 'product' || inputs.version_mode == 'build-number' && 'auto' || inputs.version_mode }}")
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { version_mode: { default: 'default', options: ['default', 'follow-dsh', 'build-number', 'manual'] } } })
expect(workflow.jobs.package).not.toHaveProperty('name')
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { test_release_id: { type: 'string', default: '', required: false } } })
expect(workflow.on.workflow_dispatch).not.toHaveProperty('inputs.publish')
@@ -36,11 +45,14 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
expect(steps.find(step => step.id === 'checkout')?.with).toMatchObject({ 'persist-credentials': false, clean: true })
for (const step of steps) expect(step.run ?? '').not.toContain('${{ inputs.')
const uploads = steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(2)
expect(uploads).toHaveLength(1)
const archive = workflow.jobs['upload-artifact']!
expect(archive['runs-on']).toEqual(['self-hosted', '${{ needs.package.outputs.runner }}'])
const installer = archive.steps.find(step => step.uses?.startsWith('actions/upload-artifact@'))!
expect(uploads[0]?.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[1]?.if).toBe('success()')
expect(uploads[1]?.with?.path).toBe('${{ steps.retained.outputs.directory }}/*')
expect(uploads[1]?.with?.['compression-level']).toBe(0)
expect(installer.if).toBe('success()')
expect(installer.with?.path).toBe('${{ steps.archive.outputs.path }}')
expect(installer.with).toMatchObject({ archive: false, overwrite: true, name: '${{ env.DESKTOP_ARCHIVE_NAME }}' })
})
it('defaults to notarization and labels the explicit debugging option', () => {
@@ -50,7 +62,6 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
} } })
const steps = workflow.jobs.package!.steps
expect(steps.filter(step => step.run?.includes('args+=(--skip-notarization)'))).toHaveLength(2)
expect(steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain('${{ steps.settings.outputs.mode }}')
})
it('retains build inputs outside checkout and run-specific pnpm installations', () => {
@@ -85,13 +96,15 @@ describe.each(['arm64', 'x64'])('macOS %s packaging', (arch) => {
})
it('passes the same target to preparation, packaging and retention', () => {
const archive = workflow.jobs['upload-artifact']!
expectDesktopArchive(archive, 1)
const job = workflow.jobs.package!
expect(job.env.DSH_DESKTOP_TARGET_PLATFORM).toBe('darwin')
expect(job.env.DSH_DESKTOP_TARGET_ARCH).toBe(arch)
const builds = job.steps.filter(step => step.run?.includes('pnpm run package:desktop:mac:'))
expect(builds).toHaveLength(2)
for (const step of builds) expect(step.run).toContain(`package:desktop:mac:${arch}`)
expect(job.steps.find(step => step.name === 'Retain installers for the selected mode')?.with?.name).toContain(`macos-${arch}-`)
expect(archive.env.DESKTOP_ARCHIVE_NAME).toBe('macos-' + arch + '-${{ needs.package.outputs.mode }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}.zip')
if (arch === 'x64') {
const rosetta = job.steps.findIndex(step => step.run === 'arch -x86_64 /usr/bin/true')
expect(rosetta).toBeGreaterThan(-1)
-16
View File
@@ -1449,9 +1449,6 @@
"746ebc5aade01a50cc9a74fc07b1023addf021aef80b62c069a437ac140c9e64": 1,
"c920d88f6eb309ef5991608642a1ab0fd972690538b33c34d86c68d07ddd6edf": 1
},
"packages/session-query/session-log-export/tests/dialog.client.spec.tsx": {
"a9b1969d76db0b05f87c862956f8ff45c52f1f4a5b32a206339de0c9fee99a77": 1
},
"packages/session-query/session-log-export/tests/loader-composition.host.spec.ts": {
"59c63f734e8bba862325f776e3fcbebd78a84cfb4161f8df41c216950d9bf351": 1,
"e12d49327a6708ae3ace371e28ed0deb471dc8895c584ba94a86af344c15cec3": 1
@@ -1958,19 +1955,6 @@
"packages/web/tool-web/tests/spill.spec.ts": {
"ecf3420d023d28e1cbc687d438bb66ee49d55a4ae4cb0828dd0f59b926363903": 1
},
"packages/web/web-search-deepseek/tests/deepseek.spec.ts": {
"37c9617ff75d6a383f58dd63f939a88803e4ff5e1676bfe7e1c0cc340fc65014": 5,
"598014dcfe77101781e3c6a02709097e3b0151a335e909c44719fac08fdea433": 2
},
"packages/web/web-search-exa/tests/exa.spec.ts": {
"37c9617ff75d6a383f58dd63f939a88803e4ff5e1676bfe7e1c0cc340fc65014": 7,
"598014dcfe77101781e3c6a02709097e3b0151a335e909c44719fac08fdea433": 2
},
"packages/web/web-search-perplexity/tests/perplexity.spec.ts": {
"37c9617ff75d6a383f58dd63f939a88803e4ff5e1676bfe7e1c0cc340fc65014": 5,
"598014dcfe77101781e3c6a02709097e3b0151a335e909c44719fac08fdea433": 2,
"ed2fec09418bc1a78fde5097fd01d5aabf903166ed1bf480a5e38bccdd3948a6": 1
},
"packages/workflow/tool-workflow/tests/tool-workflow.spec.ts": {
"061944ebda38f8da144d88cfa668e6336efc68c33441a9fe3215d8c001124526": 2
},
+16 -12
View File
@@ -133,7 +133,7 @@ describe('optional bundles', () => {
}
})
it('offers Git Worktrees as one disabled bundle with its runtime and tool', () => {
it('retains the standalone worktree bundle for explicit profiles', () => {
const name = '@deepseek-ai/dsh-experimental-tool-worktree'
expect(OPTIONAL_BUNDLES).toContain(name)
for (const template of Object.values(PROFILE_TEMPLATES)) expect(template.bundles).not.toContain(name)
@@ -144,7 +144,7 @@ describe('optional bundles', () => {
}
})
it('offers the forge panel as one disabled bundle with its registry, provider, bindings, panel, and isolated worktree service', () => {
it('offers the forge panel and model worktree tool together with their separate worktree services', () => {
const name = '@deepseek-ai/dsh-experimental-forge-bundle'
expect(OPTIONAL_BUNDLES).toContain(name)
for (const template of Object.values(PROFILE_TEMPLATES)) expect(template.bundles).not.toContain(name)
@@ -154,24 +154,28 @@ describe('optional bundles', () => {
'@deepseek-ai/dsh-experimental-forge-github',
'@deepseek-ai/dsh-experimental-forge-session',
'@deepseek-ai/dsh-experimental-client-ui-forge',
'@deepseek-ai/dsh-experimental-worktree',
'@deepseek-ai/dsh-experimental-tool-worktree',
]) {
expect(flattenRows(composeEntries(shipped)).some(row => row.name === moduleName)).toBe(false)
expect(rows.filter(row => row.name === moduleName && row.disabled !== true)).toHaveLength(1)
}
const group = composeEntries([...shipped, bundle(name).patches]).find(row => row.id === 'optional-forge-panel')
expect(group?.isolate).toEqual({ worktrees: true })
expect(rows.filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(2)
})
it('composes the forge panel beside Git Worktrees with one worktree service each', () => {
const composed = composeEntries([
...shipped,
bundle('@deepseek-ai/dsh-experimental-tool-worktree').patches,
bundle('@deepseek-ai/dsh-experimental-forge-bundle').patches,
], (message) => { throw new Error(message) })
const topLevelIds = composed.flatMap(entry => typeof entry.id === 'string' ? [entry.id] : [])
expect(topLevelIds).toHaveLength(new Set(topLevelIds).size)
expect(flattenRows(composed).filter(row => row.name === '@deepseek-ai/dsh-experimental-worktree')).toHaveLength(2)
it('keeps the existing tool and panel row overrides addressable in the unified bundle', () => {
const config = { directory: '.agents/custom-worktrees' }
const warnings: string[] = []
const composed = composeEntries([...shipped, bundle('@deepseek-ai/dsh-experimental-forge-bundle').patches, [
{ id: 'worktree', config },
{ id: 'tool-worktree', disabled: true },
{ id: 'optional-forge-panel', disabled: true },
]], message => warnings.push(message))
expect(warnings).toEqual([])
expect(composed.find(row => row.id === 'worktree')?.config).toEqual(config)
expect(composed.find(row => row.id === 'tool-worktree')?.disabled).toBe(true)
expect(composed.find(row => row.id === 'optional-forge-panel')?.disabled).toBe(true)
})
it('ships all five lightweight bundles without selecting them in a default template', () => {
-2
View File
@@ -32,8 +32,6 @@ export const PRODUCT_PACKAGE_POLICY: Readonly<Record<string, ProductPackagePolic
'packages/subagent/subagent-claude-code': { category: 'optional', reason: 'Separately installed native Claude Code agent integration.' },
'packages/subagent/subagent-codex': { category: 'optional', reason: 'Separately installed native Codex agent integration.' },
'packages/subagent/subagent-dsh-sdk': { category: 'optional', reason: 'Requires an explicitly configured external DSH home.' },
'packages/web/web-search-exa': { category: 'optional', reason: 'Alternative search provider requiring its own API credentials.' },
'packages/web/web-search-perplexity': { category: 'optional', reason: 'Alternative search provider requiring its own API credentials.' },
'packages/context/tmux-context': { category: 'optional', reason: 'Context contribution requiring a tmux pane.' },
'packages/fs/tool-str-replace-editor': { category: 'optional', reason: 'Explicit alternative to the default filesystem editing tools.' },
'packages/fs/fs-observation-policy': { category: 'optional', reason: 'Read-before-mutation guard that a deployment enables on the disabled dsh-base row.' },
+20 -1
View File
@@ -3,11 +3,13 @@
import { createHash } from 'node:crypto'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { join, resolve } from 'node:path'
import { setTimeout as sleep } from 'node:timers/promises'
import { afterEach, beforeEach, describe, expect, it, onTestFinished, vi } from 'vitest'
import { attempt, attemptEchoed, type CommandResult } from './process.ts'
import { publishRelease } from './publish.ts'
import { cuaHelperSourceDigest } from '../cua-helper/build-inputs.ts'
import { verifyCuaHelperTarball } from '../cua-helper/verify-tarball.ts'
import { packedIdentity, readPublishOrder } from './tarball.ts'
vi.mock('./process.ts', async importOriginal => ({
@@ -23,6 +25,8 @@ vi.mock('./tarball.ts', async importOriginal => ({
readPublishOrder: vi.fn(),
}))
vi.mock('../cua-helper/verify-tarball.ts', () => ({ verifyCuaHelperTarball: vi.fn() }))
vi.mock('node:timers/promises', async importOriginal => ({
...await importOriginal<typeof import('node:timers/promises')>(),
setTimeout: vi.fn(),
@@ -310,3 +314,18 @@ describe('release publication channels', () => {
expect(attemptEchoed).not.toHaveBeenCalled()
})
})
it('verifies helper sources from the repository root when publication is invoked from a subdirectory', async () => {
const fixture = packedRelease(['1.0.0'])
vi.mocked(packedIdentity).mockReturnValue({ name: '@deepseek-ai/dsh-experimental-cua-macos', version: '1.0.0' })
vi.mocked(verifyCuaHelperTarball).mockResolvedValue(undefined)
registry()
const root = resolve(import.meta.dirname, '../..')
const sourceDigest = cuaHelperSourceDigest(root)
const cwd = vi.spyOn(process, 'cwd').mockReturnValue(join(root, 'scripts'))
try {
await publishRelease('dsh', fixture.directory)
expect(verifyCuaHelperTarball).toHaveBeenCalledExactlyOnceWith(fixture.packages[0]!.path, { sourceDigest })
expect(attemptEchoed).toHaveBeenCalledOnce()
} finally { cwd.mockRestore() }
})
+2 -3
View File
@@ -12,7 +12,7 @@
* the same artifact safe.
*/
import { execFileSync } from 'node:child_process'
import { cuaHelperSourceDigest } from '../cua-helper/build-inputs.ts'
import { verifyCuaHelperTarball } from '../cua-helper/verify-tarball.ts'
import { createHash } from 'node:crypto'
import { readFileSync } from 'node:fs'
@@ -188,8 +188,7 @@ export async function publishRelease(familyId: string, directory: string, distTa
})
for (const member of order) {
if (member.name !== '@deepseek-ai/dsh-experimental-cua-macos') continue
const commit = execFileSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' }).trim()
await verifyCuaHelperTarball(member.tarball, { version: member.version, commit })
await verifyCuaHelperTarball(member.tarball, { sourceDigest: cuaHelperSourceDigest(resolve(import.meta.dirname, '../..')) })
}
if (distTag !== undefined) {
for (const member of order) verifyDistTag(member, distTag)
+1 -1
View File
@@ -24,7 +24,7 @@ const REGISTER_HEAD = /\.(?:register|registerFactory)\(/
export interface SlotDeclaration {
/** SlotMap key, e.g. `settings.section`. */
key: string
/** Cardinality literal (`single` / `list` / `keyed` / `chain`), or '' when not a literal. */
/** Cardinality literal (`single` / `list` / `keyed` / `chain` / `hoc`), or '' when not a literal. */
kind: string
/** Data-scope literal (`root` / `session` / `session-maybe`), or '' when not a literal. */
scope: string
+1
View File
@@ -1522,6 +1522,7 @@ def smoke_sdk_dynamic_tools(base_url: str, executable: Path, update_snapshots: b
task = root / "dynamic-tool-task.txt"
task.write_text("Call snapshot_ping once.\n", encoding="utf-8")
patch = write_profile_patch(root, "dynamic-tools.patch.yml", sessions, [
{"id": "tool-fs", "config": {"applyPatch": True}},
{"id": "llm-deepseek", "config": {"models": [
{"id": "smoke-model", "toolUpdate": "addition-only"},
]}},
+4 -4
View File
@@ -12,7 +12,7 @@ import * as searchFixtureModule from '../snapshots/session/web-search-endpoint-g
// @ts-expect-error The fixture intentionally has no declaration artifact.
import * as loopbackFixtureModule from '../snapshots/session/loopback-fixture-server.mjs'
const RECORDED_ENDPOINT = 'http://127.0.0.1:43118/anthropic/v1/messages'
const RECORDED_ENDPOINT = 'http://127.0.0.1:43118/api/v1/tools/search'
interface FixturePlugin {
readonly name: string
@@ -152,17 +152,17 @@ describe('snapshot HTTP fixture lifecycle', () => {
try {
await globalThis.fetch(RECORDED_ENDPOINT)
expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://127.0.0.1:54322/anthropic/v1/messages')
expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://127.0.0.1:54322/api/v1/tools/search')
await globalThis.fetch(new URL(RECORDED_ENDPOINT))
expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://127.0.0.1:54322/anthropic/v1/messages')
expect(fetchMock.mock.calls.at(-1)?.[0]).toBe('http://127.0.0.1:54322/api/v1/tools/search')
const request = new Request(RECORDED_ENDPOINT, { method: 'POST', headers: { 'x-fixture': 'request' } })
await globalThis.fetch(request)
const mappedRequest = fetchMock.mock.calls.at(-1)?.[0]
expect(mappedRequest).toBeInstanceOf(Request)
if (!(mappedRequest instanceof Request)) throw new TypeError('mapped fetch input must be a Request')
expect(mappedRequest.url).toBe('http://127.0.0.1:54322/anthropic/v1/messages')
expect(mappedRequest.url).toBe('http://127.0.0.1:54322/api/v1/tools/search')
expect(mappedRequest.method).toBe('POST')
expect(mappedRequest.headers.get('x-fixture')).toBe('request')
@@ -890,11 +890,12 @@
"seq": 37,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-1}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "Check direct child"
"label": "Check direct child",
"name": "agent-1"
}
},
{
@@ -914,7 +915,7 @@
"content": [
{
"type": "text",
"text": "started subagent {{child-1}}"
"text": "started subagent agent-1"
}
],
"isError": false,
@@ -922,7 +923,7 @@
},
"meta": {
"kind": "activation",
"subagentId": "{{child-1}}"
"name": "agent-1"
}
},
"sourceEventSeqs": [
@@ -970,7 +971,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -984,7 +985,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -1144,11 +1145,12 @@
"seq": 46,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-2}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "advanced-exe-snapshot child 1"
"label": "advanced-exe-snapshot child 1",
"name": "agent-2"
}
},
{
@@ -1248,7 +1250,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -1262,7 +1264,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -2778,11 +2780,12 @@
"seq": 37,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-1}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "Check direct child"
"label": "Check direct child",
"name": "agent-1"
}
}
}
@@ -2808,7 +2811,7 @@
"content": [
{
"type": "text",
"text": "started subagent {{child-1}}"
"text": "started subagent agent-1"
}
],
"isError": false,
@@ -2816,7 +2819,7 @@
},
"meta": {
"kind": "activation",
"subagentId": "{{child-1}}"
"name": "agent-1"
}
},
"sourceEventSeqs": [
@@ -3275,7 +3278,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -3289,7 +3292,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -3676,11 +3679,12 @@
"seq": 46,
"time": 0,
"data": {
"version": 0,
"version": 3,
"childId": "{{child-2}}",
"childCreatedAt": 0,
"mode": "continuable",
"label": "advanced-exe-snapshot child 1"
"label": "advanced-exe-snapshot child 1",
"name": "agent-2"
}
}
}
@@ -4228,7 +4232,7 @@
"content": [
{
"type": "text",
"text": "Background subagent {{child-1}} finished and will do no further work unless you send it more."
"text": "Background subagent agent-1 finished and will do no further work unless you send it more."
},
{
"type": "text",
@@ -4242,7 +4246,7 @@
"source": {
"kind": "subagent-settled",
"form": "notice",
"summary": "Background subagent {{child-1}} finished and will do no further work unless you send it more.",
"summary": "Background subagent agent-1 finished and will do no further work unless you send it more.",
"stopReason": "completed",
"senderSessionId": "{{child-1}}"
},
@@ -36,16 +36,16 @@
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":33}}
{"type":"assistant/message","data":{"turn":1,"step":3,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-direct-child","name":"subagent","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-direct-child","args":["{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":3,"callId":"advanced-direct-child","name":"subagent","arguments":"{\"description\": \"Check direct child\", \"prompt\": \"Reply with exactly DIRECT_CHILD_OK and nothing else.\"}"}}
{"type":"subagent/catalog","data":{"version":0,"childId":"{{child-1}}","childCreatedAt":0,"mode":"continuable","label":"Check direct child"}}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-direct-child"},"toolCallId":"advanced-direct-child","content":[{"type":"text","text":"started subagent {{child-1}}"}],"isError":false,"id":"{{messageId}}"},"meta":{"kind":"activation","subagentId":"{{child-1}}"}},"sourceEventSeqs":[36],"surfaceOp":"append"}
{"type":"subagent/catalog","data":{"version":3,"childId":"{{child-1}}","childCreatedAt":0,"mode":"continuable","label":"Check direct child","name":"agent-1"}}
{"type":"tool/result","data":{"turn":1,"step":3,"message":{"role":"tool","source":{"kind":"tool","callId":"advanced-direct-child"},"toolCallId":"advanced-direct-child","content":[{"type":"text","text":"started subagent agent-1"}],"isError":false,"id":"{{messageId}}"},"meta":{"kind":"activation","name":"agent-1"}},"sourceEventSeqs":[36],"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":3}}
{"type":"step/start","data":{"turn":1,"step":4}}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":40}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent {{child-1}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{child-1}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"}]}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"inserted":[{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"}]}}
{"type":"assistant/message","data":{"turn":1,"step":4,"message":{"role":"assistant","content":[{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}},"id":"{{messageId}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-workflow","name":"workflow","args":[""]},{"type":"tool-call-chunks","time0":0,"index":0,"dt":[],"id":"advanced-workflow","args":["{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"tool-calls"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"tool-call"}]}}}]},"surfaceOp":"append"}
{"type":"tool/call","data":{"turn":1,"step":4,"callId":"advanced-workflow","name":"workflow","arguments":"{\"script\": \"phase('Delegate')\\nconst reply = await agent('Reply with exactly WORKFLOW_CHILD_OK and nothing else.', { label: 'workflow-child' })\\nreturn { reply }\", \"meta\": {\"name\": \"advanced-exe-snapshot\", \"description\": \"exercise one packaged workflow child\"}}"}}
{"type":"tool-workflow/run-start","data":{"runId":"{{workflow-run}}","name":"advanced-exe-snapshot"}}
{"type":"subagent/catalog","data":{"version":0,"childId":"{{child-2}}","childCreatedAt":0,"mode":"continuable","label":"advanced-exe-snapshot child 1"}}
{"type":"subagent/catalog","data":{"version":3,"childId":"{{child-2}}","childCreatedAt":0,"mode":"continuable","label":"advanced-exe-snapshot child 1","name":"agent-2"}}
{"type":"tool-workflow/agent-start","data":{"runId":"{{workflow-run}}","seq":1,"label":"workflow-child","phase":"Delegate","childId":"{{child-2}}"}}
{"type":"tool-workflow/agent-end","data":{"runId":"{{workflow-run}}","seq":1,"outcome":"completed"}}
{"type":"tool-workflow/run-end","data":{"runId":"{{workflow-run}}","stopReason":"completed"}}
@@ -53,7 +53,7 @@
{"type":"step/end","data":{"turn":1,"step":4}}
{"type":"agent/inbox/spliced","data":{"target":"next-step","start":0,"removedCount":1,"inserted":[]}}
{"type":"step/start","data":{"turn":1,"step":5}}
{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent {{child-1}} finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent {{child-1}} finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"user/message","data":{"content":[{"type":"text","text":"Background subagent agent-1 finished and will do no further work unless you send it more."},{"type":"text","text":"Its closing message:"},{"type":"text","text":"DIRECT_CHILD_OK"}],"source":{"kind":"subagent-settled","form":"notice","summary":"Background subagent agent-1 finished and will do no further work unless you send it more.","stopReason":"completed","senderSessionId":"{{child-1}}"},"role":"user","id":"{{messageId}}"},"surfaceOp":"append"}
{"type":"session-log-deepseek/delivery-accepted","data":{"sessionId":"{{parent}}","sessionFormatVersion":4,"throughSeq":54}}
{"type":"assistant/message","data":{"turn":1,"step":5,"message":{"role":"assistant","content":[{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}],"source":{"kind":"model","provider":"deepseek-official","model":"smoke-model","replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}},"id":"{{message:1}}"},"usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6},"stream":[{"type":"chunk","time":0,"chunk":{"type":"block-start","index":0,"blockType":"text"}},{"type":"text-chunks","time0":0,"index":0,"dt":[],"texts":["ADVANCED_EXECUTABLE_OK"]},{"type":"chunk","time":0,"chunk":{"type":"block-end","index":0,"block":{"type":"text","text":"ADVANCED_EXECUTABLE_OK"}}},{"type":"chunk","time":0,"chunk":{"type":"usage","usage":{"inputTokens":3,"outputTokens":3,"totalTokens":6}}},{"type":"chunk","time":0,"chunk":{"type":"finish","reason":{"kind":"stop"},"replayState":{"response":{"kind":"deepseek-messages","version":1,"model":"smoke-model"},"blocks":[{"type":"text"}]}}}]},"surfaceOp":"append"}
{"type":"step/end","data":{"turn":1,"step":5}}
@@ -8,7 +8,7 @@
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 the root agent. Your agent id is \"authoring\".\n\nTo message other agents, use send_message({ agent_id: \"<agent-id>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 the root agent. Your name 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.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",
@@ -8,7 +8,7 @@
}
},
"catalogs": [
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 the root agent. Your agent id is \"authoring\".\n\nTo message other agents, use send_message({ agent_id: \"<agent-id>\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their ids.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
"Query the packaged Python environment for Office authoring.Current runtime context. This snapshot supersedes earlier runtime-context snapshots.\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: danger-full-access. The DSH file sandbox does not restrict file modifications by available operations.\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 the root agent. Your name 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.<system-reminder>\nA skill is a reusable set of task-specific instructions. The following skills are available in this session:\n\n<available_skills>\n- `diagnose-windows-sandbox-acl`: Use on Windows for unexpected DSH sandbox access denials: workspace writes or listing fail, or an ordinarily readable path cannot be read. One bundled command inspects the path and every ancestor and repairs the ACL problems it proves in that same run. Expected confinement denials need no ACL repair.\n- `office`: Create, edit, inspect, or convert Office documents, spreadsheets, presentations, and PDFs. Load to choose the relevant workflow.\n- `office-docx`: Create, read, edit, and validate Word documents (.docx).\n- `office-export-pdf`: Convert an Office document to a requested PDF with LibreOffice Kit.\n- `office-pptx`: Create, read, edit, and validate PowerPoint presentations (.pptx).\n- `office-recalculate`: Refresh spreadsheet formula caches and verify calculated values with LibreOffice Kit.\n- `office-render`: Render requested document images or inspect visual layout with LibreOffice Kit.\n- `office-xlsx`: Read, create, edit, and validate Excel workbooks, data, and formulas (.xlsx).\n</available_skills>\n\nIf the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded.\nA user may also invoke a skill directly; its <skill_content> block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.\n</system-reminder>Time sampled while preparing turn 1, step 1: 2026-10-16T00:00:00+00:00[UTC]\nBrowser time zone for this request: unavailable. Ask the user to clarify otherwise-unqualified dates and times.\nElapsed since the preceding model-visible message: unavailable."
],
"result": {
"python": "{{python}}",
+126 -55
View File
@@ -1,9 +1,11 @@
/** Release rehearsal routing and persistent-runner isolation, without executing release builds. */
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { spawnSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, resolve } from 'node:path'
import { runInNewContext } from 'node:vm'
import { load } from 'js-yaml'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, onTestFinished } from 'vitest'
const root = resolve(import.meta.dirname, '../..')
const repository = 'deepseek-harness/deepseek-harness'
@@ -11,6 +13,7 @@ const selfhosted = ['self-hosted', 'linux', 'x64', 'vm-backup']
const hosted = 'ubuntu-24.04'
interface Step {
env?: Record<string, string>
name?: string
uses?: string
run?: string
@@ -30,6 +33,8 @@ interface Workflow {
with?: Record<string, unknown>
needs?: string
permissions?: Record<string, string>
outputs?: Record<string, string>
env?: Record<string, string>
}>
}
@@ -42,7 +47,7 @@ function workflow(file: string): Workflow {
// Missing context properties use the Actions empty-string value.
function evaluate(expression: string, context: Record<string, string | boolean>): unknown {
const source = expression.trim().replace(/^\$\{\{|\}\}$/g, '')
.replace(/\b(?:github|vars|runner|inputs|needs)(?:\.[a-zA-Z_][a-zA-Z_0-9-]*)+/g,
.replace(/\b(?:github|vars|runner|inputs|needs|steps)(?:\.[a-zA-Z_][a-zA-Z_0-9-]*)+/g,
key => JSON.stringify(context[key] ?? ''))
return runInNewContext(source, {
fromJSON: JSON.parse, startsWith: (value: string, prefix: string) => value.startsWith(prefix),
@@ -180,75 +185,141 @@ it('keeps vendor publication manual and entirely hosted', () => {
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
for (const job of Object.values(publish.jobs)) expect(job['runs-on']).toBe(hosted)
})
it('keeps DSH publication manual with hosted npm jobs and an explicit signed-helper producer', () => {
it('keeps DSH publication manual and delegates all helper selections to the Mac workflow', () => {
const publish = workflow('release-publish.yml')
expect(Object.keys(publish.on)).toEqual(['workflow_dispatch'])
const helper = publish.jobs['cua-helper']!
expect(helper).toEqual({
if: "startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check",
uses: './.github/workflows/cua-helper-package.yml',
with: { reuse: true, preset: 'production', cua_run_id: '${{ inputs.cua_run_id }}' },
})
for (const [name, job] of Object.entries(publish.jobs)) {
if (name === 'cua-helper') {
expect(job).toEqual({
if: "(startsWith(github.ref, 'refs/tags/dsh-v') || inputs.skip-tag-check) && inputs.cua_run_id == '' && inputs.cua_run_attempt == ''",
uses: './.github/workflows/cua-helper-package.yml',
with: { source_ref: '${{ github.ref }}', preset: 'production' },
})
} else expect(job['runs-on']).toBe(hosted)
if (name !== 'cua-helper') expect(job['runs-on']).toBe(hosted)
}
expect(JSON.stringify(publish)).not.toContain('cua_run_attempt')
expect(publish.on['workflow_dispatch']).toMatchObject({ inputs: { 'skip-tag-check': {
description: 'Skip release tag validation for the selected ref; other publication checks still apply.',
} } })
expect(publish.jobs['pack']!.needs).toBe('cua-helper')
expect(publish.jobs['pack']!.if).toBeUndefined()
})
it.each([
['refs/tags/dsh-v0.2.1-rc.4', false, '', '', true],
['refs/heads/master', false, '', '', false],
['refs/heads/master', true, '', '', true],
['refs/tags/dsh-v0.2.1-rc.4', false, '123', '', false],
['refs/heads/master', true, '123', '2', false],
['refs/tags/dsh-v0.2.1-rc.4', false, '', '2', false],
] as const)('selects the helper producer for ref %s, skip=%s, run=%s, attempt=%s', (ref, skip, runId, attempt, expected) => {
['refs/tags/dsh-v0.2.1-rc.4', false, true],
['refs/heads/master', false, false],
['refs/heads/master', true, true],
] as const)('gates helper selection for ref %s, skip=%s', (ref, skip, expected) => {
const expression = workflow('release-publish.yml').jobs['cua-helper']!.if!
expect(evaluate(expression, { 'github.ref': ref, 'inputs.skip-tag-check': skip,
'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt })).toBe(expected)
expect(evaluate(expression, { 'github.ref': ref, 'inputs.skip-tag-check': skip })).toBe(expected)
})
it.each([
['success', '', '', false, true],
['failure', '', '', false, false],
['failure', '123', '', false, false],
['cancelled', '', '', false, false],
['skipped', '', '', false, false],
['skipped', '123', '', false, true],
['skipped', '123', '2', false, true],
['skipped', '', '2', false, true],
['skipped', '123', '2', true, false],
] as const)('gates npm packing with helper=%s, run=%s, attempt=%s, cancelled=%s', (result, runId, attempt, cancelled, expected) => {
const pack = workflow('release-publish.yml').jobs['pack']!
expect(pack.needs).toBe('cua-helper')
expect(evaluate(pack.if!, { 'needs.cua-helper.result': result,
'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt, cancelled })).toBe(expected)
it('skips installation and signing on a helper match and exports the original producer identifiers', () => {
const helper = workflow('cua-helper-package.yml')
expect(helper.permissions).toEqual({ contents: 'read', actions: 'read' })
const job = helper.jobs['package']!
const select = job.steps.find(step => step.name === 'Find reusable CUA helper')!
expect(select.run).toBe('node scripts/cua-helper/select-artifact.ts')
expect(Boolean(evaluate(select.if!, {}))).toBe(false)
expect(evaluate(select.if!, { 'inputs.reuse': true })).toBe(true)
expect(select.env?.['CUA_BUILD_KEY']).toBe('${{ steps.build-inputs.outputs.build-key }}')
const inputs = job.steps.find(step => step.name === 'Record CUA helper build inputs')!
expect(inputs.run).toBe('node scripts/cua-helper/build-inputs.ts')
expect(inputs.if).toBeUndefined()
expect(job.steps.indexOf(inputs)).toBeLessThan(job.steps.indexOf(select))
const expensive = job.steps.filter(step => step.uses === 'pnpm/[email protected]'
|| step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications'
|| step.uses === 'actions/[email protected]')
expect(expensive).toHaveLength(4)
expect(job.steps.find(step => step.name === 'Install locked dependencies')?.run)
.toBe('pnpm install --frozen-lockfile --ignore-scripts --ignore-pnpmfile')
const build = job.steps.find(step => step.name === 'Build and verify notarized applications')!
expect(build.run).toContain('node --import tsx/esm scripts/cua-helper/package.ts --out dist/cua-helper')
expect(build.run).not.toContain('pnpm exec')
for (const step of expensive) {
expect(job.steps.indexOf(select)).toBeLessThan(job.steps.indexOf(step))
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': '456' })).toBe(false)
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': '' })).toBe(true)
}
expect(job.outputs).toMatchObject({
'artifact-id': '${{ steps.retained.outputs.artifact-id || steps.upload.outputs.artifact-id }}',
'run-id': '${{ steps.retained.outputs.run-id || github.run_id }}',
'build-key': '${{ steps.build-inputs.outputs.build-key }}',
})
})
it('validates retained attempts before downloading exactly one artifact with read-only Actions access', () => {
it('downloads the selected producer artifact and verifies its build key before packing', () => {
const publish = workflow('release-publish.yml')
expect(publish.permissions).toEqual({ contents: 'read' })
expect(publish.permissions).toEqual({ contents: 'read', actions: 'read' })
const pack = publish.jobs['pack']!
expect(pack.permissions).toEqual({ contents: 'read', actions: 'read' })
const select = pack.steps.find(step => step.name === 'Select retained CUA helper')!
const retained = pack.steps.find(step => step.name === 'Download retained CUA helper')!
const fresh = pack.steps.find(step => step.name === 'Download freshly built CUA helper')!
expect(select.run).toBe('pnpm exec tsx scripts/cua-helper/select-artifact.ts')
expect(pack.steps.indexOf(select)).toBeLessThan(pack.steps.indexOf(retained))
expect(retained).toMatchObject({ uses: 'actions/[email protected]', with: {
'artifact-ids': '${{ steps.retained-cua.outputs.artifact-id }}', 'run-id': '${{ inputs.cua_run_id }}',
const download = pack.steps.find(step => step.name === 'Download selected CUA helper')!
expect(download).toMatchObject({ uses: 'actions/[email protected]', with: {
'artifact-ids': '${{ needs.cua-helper.outputs.artifact-id }}', 'run-id': '${{ needs.cua-helper.outputs.run-id }}',
'github-token': '${{ github.token }}', path: 'dist/cua-helper',
} })
expect(retained.with?.name).toBeUndefined()
expect(fresh.with).toEqual({ name: '${{ needs.cua-helper.outputs.artifact }}', path: 'dist/cua-helper' })
for (const [runId, attempt, reuse] of [['', '', false], ['123', '', true], ['123', '2', true], ['', '2', true]] as const) {
const context = { 'inputs.cua_run_id': runId, 'inputs.cua_run_attempt': attempt }
expect(evaluate(select.if!, context)).toBe(reuse)
expect(evaluate(retained.if!, context)).toBe(reuse)
expect(evaluate(fresh.if!, context)).toBe(!reuse)
}
expect(download.if).toBeUndefined()
expect(download.with?.name).toBeUndefined()
const stage = pack.steps.find(step => step.name === 'Stage verified native helper applications')!
expect(stage.if).toBeUndefined()
expect(stage.env).toEqual({ CUA_EXPECTED_BUILD_KEY: '${{ needs.cua-helper.outputs.build-key }}' })
expect(stage.run).toContain('scripts/cua-helper/stage.ts --from dist/cua-helper/extracted')
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(retained))
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(fresh))
expect(pack.steps.indexOf(stage)).toBeGreaterThan(pack.steps.indexOf(download))
expect(pack.steps.indexOf(stage)).toBeLessThan(pack.steps.findIndex(step => step.name === 'Pack release tarballs'))
})
it('checks out the Actions run commit and exposes only the preset on the manual helper form', () => {
const helper = workflow('cua-helper-package.yml')
const dispatch = helper.on['workflow_dispatch'] as { inputs: Record<string, unknown> }
const called = helper.on['workflow_call'] as { inputs: Record<string, unknown> }
expect(Object.keys(dispatch.inputs)).toEqual(['preset'])
expect(called.inputs).toEqual({ reuse: { type: 'boolean', default: false },
cua_run_id: { type: 'string', default: '' }, preset: { type: 'string', default: 'production' } })
const job = helper.jobs['package']!
const checkout = job.steps.find(step => step.uses === 'actions/[email protected]')!
expect(checkout.with).toEqual({ 'persist-credentials': false, clean: true })
expect(job.env).not.toHaveProperty('PACKAGE_SOURCE_REF')
expect(JSON.stringify(helper)).not.toContain('source_ref')
expect(workflow('release-publish.yml').jobs['cua-helper']!.with).not.toHaveProperty('source_ref')
})
it.each([
['refs/heads/release-candidate', 'test', true, ''],
['refs/tags/dsh-v1.2.3', 'production', true, ''],
['refs/tags/dsh-v1.2.4', 'production', false, 'Release tag must match product version'],
['refs/heads/master', 'invalid', false, 'Invalid preset'],
['refs/pull/42/merge', 'test', false, 'Select a trusted repository branch or release tag'],
['', 'test', false, 'Select a trusted repository branch or release tag'],
] as const)('validates the run ref %s and preset %s before dependency installation', (ref, preset, accepted, diagnostic) => {
const directory = mkdtempSync(join(tmpdir(), 'cua-workflow-ref-'))
onTestFinished(() => { rmSync(directory, { recursive: true, force: true }) })
writeFileSync(join(directory, 'package.json'), JSON.stringify({ version: '1.2.3' }))
const job = workflow('cua-helper-package.yml').jobs['package']!
const validation = job.steps.find(step => step.name === 'Validate run ref and preset')!
const source = /^node -e '([\s\S]+)'$/u.exec(validation.run!.trim())?.[1]
expect(source).toBeDefined()
const result = spawnSync(process.execPath, ['-e', source!], {
cwd: directory, encoding: 'utf8', timeout: 60_000,
env: { ...process.env, GITHUB_REF: ref, DSH_PACKAGING_PRESET: preset, PACKAGE_SOURCE_REF: 'refs/tags/dsh-v0.0.0' },
})
expect(result.error).toBeUndefined()
expect(result.signal).toBeNull()
expect(result.status, result.stderr).toBe(accepted ? 0 : 1)
if (!accepted) expect(result.stderr).toContain(diagnostic)
expect(job.steps.indexOf(validation)).toBeLessThan(job.steps.findIndex(step => step.name === 'Record CUA helper build inputs'))
})
it.each([
[false, '', true],
[true, '', true],
[true, '456', false],
] as const)('builds for reuse=%s and selected artifact=%s only when required', (reuse, artifactId, build) => {
const steps = workflow('cua-helper-package.yml').jobs['package']!.steps
const selection = steps.find(step => step.name === 'Find reusable CUA helper')!
expect(Boolean(evaluate(selection.if!, reuse ? { 'inputs.reuse': true } : {}))).toBe(reuse)
for (const step of steps.filter(step => step.uses === 'pnpm/[email protected]'
|| step.name === 'Install locked dependencies' || step.name === 'Build and verify notarized applications'
|| step.uses === 'actions/[email protected]')) {
expect(evaluate(step.if!, { 'steps.retained.outputs.artifact-id': artifactId })).toBe(build)
}
})
+20
View File
@@ -2382,6 +2382,11 @@
"symbol": "SubagentActivation",
"source": "packages/subagent/subagent/src/types.ts"
},
{
"doc": "docs/subsystems/subagent.md",
"symbol": "SubagentMemberNames",
"source": "packages/subagent/subagent/src/types.ts"
},
{
"doc": "docs/subsystems/product-telemetry.md",
"symbol": "ProductTelemetryScalar",
@@ -2697,6 +2702,21 @@
"symbol": "ForgeBranches",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeBaseBranch",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeAutomaticBase",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeBaseBranches",
"source": "packages/experimental/client-ui-forge/src/types.ts"
},
{
"doc": "docs/subsystems/forge.md",
"symbol": "ForgeChangeRequestListState",
@@ -31,6 +31,7 @@ const MANIFEST_BIN_ALLOWLIST = new Map<string, ManifestBin>([
/** Every JavaScript executable in an application or packaging workspace has one explicit role. */
const EXECUTABLE_SOURCE_ALLOWLIST = new Map<string, string>([
['apps/cli/src/installed-bin.ts', 'installed dsh command entry'],
['apps/cli/src/bin.ts', 'supported dsh application launcher'],
['apps/desktop/scripts/logged-notarytool.mjs', 'build-only notarization logging wrapper'],
['packages/context/time-context/tests/fixtures/driver.ts', 'test-only subprocess driver'],
@@ -74,7 +74,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/experimental/forge': { kind: 'none', reason: 'Providers and watchers exchange code host status without contributing model context.' },
'packages/experimental/forge-github': { kind: 'none', reason: 'The provider reads pull request status for host-side watchers without contributing model context.' },
'packages/experimental/client-ui-forge': { kind: 'indirect', reason: 'Switching a Session directory from the panel reaches the model through the working-directory notice; inspection and status stay on the host.' },
'packages/experimental/forge-bundle': { kind: 'none', reason: 'Composes the forge packages and panel without adding a model tool or prompt.' },
'packages/experimental/forge-bundle': { kind: 'indirect', reason: 'The worktree tool and panel own the model-visible schemas, results, and directory notices selected by the bundle.' },
'packages/experimental/forge-session': { kind: 'none', reason: 'Bindings, discovery records, and polled status stay on the host; binding records never enter model requests.' },
'packages/experimental/worktree': { kind: 'indirect', reason: 'The worktree tool renders creation results; the working-directory service owns model-visible directory context.' },
'packages/experimental/client-ui-stats': { kind: 'none', reason: 'The panel reads Session events and renders them in the browser; it registers no tool, prompt section, or model input.' },
@@ -94,6 +94,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/attachment/attachment': { kind: 'indirect', reason: 'The storage seam delegates model request rendering to provider adapters.' },
'packages/attachment/attachment-local': { kind: 'indirect', reason: 'The local backend delegates model request rendering to provider adapters.' },
'packages/mcp/mcp-manager': { kind: 'indirect', reason: 'The manager only mounts and disposes dsh-mcp-client instances; those instances own every model-facing tool and schema.' },
'packages/client/ui-jobs': { kind: 'none', reason: 'Browser-side presentation of host-observed output; touches no prompt, message, schema, stream, or tool result.' },
'packages/shell/shell': { kind: 'indirect', reason: 'The service interface delegates all model rendering to dsh-tool-bash.' },
'packages/shell/shell-env': { kind: 'indirect', reason: 'The env service exposes managed DSH_* facts through the shell tools (dsh-tool-bash/dsh-tool-pwsh); it registers no prompt or schema of its own.' },
@@ -147,7 +148,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/client/ui-sidebar-right': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-sidebar': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-brand-official': { kind: 'none', reason: 'Browser-side presentation occupants; registers nothing model-facing.' },
'packages/client/ui-conversation': { kind: 'none', reason: 'Browser-side UI plugin layer; registers nothing model-facing.' },
'packages/client/ui-approval': { kind: 'none', reason: 'Browser-side approval presentation; registers nothing model-facing.' },
'packages/client/ui-chat': { kind: 'none', reason: 'Browser-side Chat presentation; registers nothing model-facing.' },
'packages/client/ui-message-feedback': { kind: 'none', reason: 'Browser-side controls over log-only message feedback; ratings and notes never enter model context or change model-input tokens.' },
@@ -265,7 +265,6 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly<Record<string, SentenceContract>> = {
'packages/util/native-command': { kind: 'none', reason: 'The host-side subprocess runner registers nothing model-facing.' },
'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' },
'packages/web/web-fetch-http': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' },
'packages/workflow/workflow': { kind: 'indirect', reason: 'The service delegates parent and child model rendering to its consumer and engine.' },
}
+17 -7
View File
@@ -1,3 +1,4 @@
import { expectDesktopArchive } from './desktop-archive-workflow-test.ts'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
@@ -11,7 +12,8 @@ const workflow = yaml.load(readFileSync(resolve(root, '.github/workflows/windows
permissions: Record<string, string>
concurrency: { group: string; 'cancel-in-progress': boolean }
jobs: Record<string, {
'runs-on': string
defaults?: { run: { shell: string } }
'runs-on': string | string[]
env: Record<string, string>
steps: Array<{
id?: string
@@ -60,6 +62,7 @@ it.skipIf(process.platform !== 'win32')('resets only the allocated checkout with
it('routes manual packaging to the dedicated runner with explicit preset and signing selection', () => {
expect(Object.keys(workflow.on)).toEqual(['workflow_dispatch'])
expect(workflow.on.workflow_dispatch).toMatchObject({ inputs: { version_mode: { default: 'default', options: ['default', 'follow-dsh', 'build-number', 'manual'] } } })
expect(workflow.jobs.package).not.toHaveProperty('name')
expect(job['runs-on']).toBe('dsh-win-package-trial')
expect(JSON.stringify(job.env)).not.toContain('runner.')
@@ -77,7 +80,7 @@ it('routes manual packaging to the dedicated runner with explicit preset and sig
expect(workflow.on.workflow_dispatch!.inputs.version_mode!.default).toBe('default')
expect(workflow.on.workflow_dispatch!.inputs.source_ref!.default).toBe('master')
expect(workflow.on.workflow_dispatch!.inputs.update_channel!.default).toBe('nightly')
expect(job.env.PACKAGE_VERSION_MODE).toBe('${{ inputs.version_mode }}')
expect(job.env.PACKAGE_VERSION_MODE).toBe("${{ inputs.version_mode == 'follow-dsh' && 'product' || inputs.version_mode == 'build-number' && 'auto' || inputs.version_mode }}")
expect(job.env.PACKAGE_SOURCE_REF).toBe('${{ inputs.source_ref }}')
expect(job.env.DSH_DESKTOP_UPDATE_CHANNEL).toBe('${{ inputs.update_channel }}')
expect(job.env.DSH_PACKAGING_PRESET).toBe('${{ inputs.preset }}')
@@ -105,16 +108,16 @@ it('validates before building and passes the same mode and version to checks and
it('retains failure diagnostics and uploads only the selected successful installer', () => {
const uploads = job.steps.filter(step => step.uses?.startsWith('actions/upload-artifact@'))
expect(uploads).toHaveLength(3)
expect(uploads).toHaveLength(1)
const archive = workflow.jobs['upload-artifact']!
const archival = expectDesktopArchive(archive, 1)
expect(uploads[0]!.if).toBe("always() && steps.checkout.outcome == 'success'")
expect(uploads[0]!.with).toMatchObject({
path: '${{ github.workspace }}/apps/desktop/.desktop-build/packaging-runs/',
'include-hidden-files': true,
})
for (const mode of ['unsigned', 'signed']) {
const upload = uploads.find(step => step.if === `success() && inputs.signing == '${mode}'`)!
expect(upload.with).toMatchObject({ path: '${{ steps.retained.outputs.directory }}/*', 'if-no-files-found': 'error', 'compression-level': 0 })
}
expect(archive.env.DESKTOP_ARCHIVE_NAME).toBe('windows-x64-${{ inputs.signing }}-${{ needs.package.outputs.version }}-${{ github.run_id }}-${{ needs.package.outputs.attempt }}.zip')
expect(archival[0]!.with).toMatchObject({ path: '${{ steps.archive.outputs.path }}', 'if-no-files-found': 'error', archive: false, overwrite: true, name: '${{ env.DESKTOP_ARCHIVE_NAME }}' })
})
it('normalizes priority in the dependency and packaging shells before launching their children', () => {
@@ -211,3 +214,10 @@ it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when
rmSync(directory, { recursive: true, force: true, maxRetries: 3 })
}
})
it('archives with native PowerShell and the persistent packaging store', () => {
const archival = workflow.jobs['upload-artifact']!
expect(archival.defaults?.run.shell).toBe('pwsh')
expect(archival.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
.toBe(job.steps.find(step => step.name === 'Configure persistent pnpm store')?.run)
})