Files
deepseek-harness/scripts/windows-package-workflow.spec.ts
T
涂轶翔 101f26de4e fix(system-prompt): 保留 section API 的增量系统指令 (#6941)
* feat(system-prompt): admit section updates incrementally

* docs(system-prompt): accept retirement restart gap

* test(system-prompt): cover retirement and reentry before admission

* test(system-prompt): align rebase fixtures and persistence history

* fix: align section prompt consumers and CI fixtures

* test: pin credentials for section snapshot fixtures

* test: align remaining snapshots with section admission

* test: preserve section metadata in Web and PowerShell replays

* refactor(system-prompt): retire sections through Cordis cleanup

* chore: refresh section admission history after rebase

* fix(system-prompt): advance admission head after compaction

* fix(system-prompt): trim sections before admission hashing

* docs: move system upgrade guides to current version

* docs: add system message contribution cookbook

* perf(system-prompt): avoid indexing history for admission

* refactor(system-prompt): derive admission from logged sections

* test(system-prompt): update lifecycle and compaction consumers

* test(system-prompt): refresh CLI section event expectations

* test(system-prompt): refresh question composer section metadata

* feat(system-prompt): resolve same-name sections by scope

* refactor(persona): use ordinary section registrations

* refactor(system-prompt): clarify assembly and related control flow

* test(system-prompt): reconcile rebased section snapshots

* test(python): use current system text helper after rebase

* test(system-prompt): refresh CLI expected section blocks

* test(system-prompt): reconcile latest master integration

* test(agent-loop): seed tools before deferred addition assertion

* refactor(compaction): replace system heads when compacting prefixes

* refactor(system-prompt): separate source text and notice attribution

* fix(system-prompt): preserve legacy instructions in compaction snapshots

* refactor(compaction): build system snapshots while reading the summary prefix

* refactor(compaction): rebuild current system instructions

* refactor(system-prompt): defer compaction rebuild to admission

* refactor(system-prompt): remove redundant fixtures and setup

* fix(plan-mode): announce committed user transitions

* docs(system-prompt): reconcile section lifecycle and compaction design

* refactor(system-prompt): consolidate projection version increments

* fix(system-prompt): reconcile master integration and replay fixtures

* docs(system-prompt): align upgrade guide with current release

* refactor(system-prompt): make admission operations explicit

* fix(system-prompt): reconcile master API and release changes

* docs(system-prompt): regenerate catalogs after master refresh

* refactor(llm-pi-ai): delegate text rendering to pi-ai

* fix(llm-pi-ai): preserve blank lines between system text parts

* refactor(system-prompt): remove redundant retirement metadata

* refactor(system-prompt): own admission and use canonical surface targets

* refactor(system-prompt): compare captured sections at commitment

Assembly fixes section text and lifecycle; PromptAssembly.systemUpdates() compares them with the committed projection when the loop commits. This replaces SystemPrompt.admit(), needsRebuild() and isCurrent(), the SystemAdmission export, the loop's reassembly after compaction, and SessionSurface.systemHeadResetSeq. The projection records a pending rebuild as a boolean that an attributed reset clears.

After a compaction inside a step, the rebuilt head uses the sections captured for that step; later source changes arrive as ordinary updates at the next step.

* test: await the session read fixture and type a matcher for lint

* test(tool-executor-ptc): describe same-name section override on executor replacement

Duplicate section names no longer reject a scoped executor; the earlier registration is overridden and returns as an ordinary update when the executor leaves.

* docs(upgrade-guide): move system-prompt integrations to v0.2.2-rc.3

The root version on master is 0.2.2-rc.3; verify-upgrade-guides rejects a guide added under an earlier version directory.

* refactor(system-prompt): rebuild over system messages without sections

A system message without source.sections now marks rebuilding pending, like a compaction summary. The next model attempt replaces the head with current sections and clears later system messages. This removes the separate legacy flag and its appended whole-prompt replacement and notice.

Sessions written by earlier releases, migrated logs, and imported DeepSeek conversations take the same path, so the importer and its tests return to their master versions.

* test(web): refresh the imported-conversation recording and drop a stray bytecode file

The Web recording for a resumed DeepSeek import was recorded while the prompt was appended after the imported history; the head is replaced again, as on master. The .pyc under the macOS signing skill was staged by accident in an earlier merge.

* refactor(session): scan system nodes on read

surface.systemNodes is read only when a system rebuild is written. Scanning the current surface nodes on each read restores the surface fold's plan types and state to their master definitions, which no longer carry the system message.

* refactor(session): rename SystemSurfaceNode.hasContent to isEmpty

The flag reports that the logged content array has no blocks. isEmpty matches the documented "empty head" wording and covers a head that was written empty without ever being cleared.

* refactor(llm): join system text through extractTextContent

extractTextContent gains a trim option that trims each text block and omits blocks left empty. The DeepSeek serializer, the pi-ai converter, and the prompt inspector use it with a blank-line separator in place of three hand-written joins.

The pi-ai converter now trims system and developer text like the other two, so whitespace-only blocks are omitted there as well.

* test(snapshots): refresh the PowerShell and cordis-inspect recordings

The two PowerShell scenarios still held the initial system message as one unattributed block; replay now writes one block per section with its attribution. The cordis-inspect-jsdoc recording embeds the API catalog, which names SystemSurfaceNode.isEmpty since the rename.

* test(plan-mode,harness-dev-context): cover a rejected pre-step and a repeated legacy prompt

A rejected pre-step must leave a queued plan-mode switch pending and unannounced until the next accepted step. A second unattributed system message with the same legacy paragraphs must keep the admitted paragraphs.

* test(web): refresh Web recordings for section-attributed system messages

Twenty-seven Web recordings still held the initial system message as one unattributed block. Replay now writes one text block per section with its attribution; twenty-six recordings differ only in that line.

plan-review also records the plan-mode switch notice before the first prompt and appends a plan:status update on exit in place of a head replacement and a series header, so its expanded golden gains the notice row.

The Creator persona test joins the system text blocks with blank lines, as the adapters do, before matching the persona line.

* refactor(system-prompt): require the retry argument of systemUpdates

The agent loop passes it on every attempt. A custom loop that omitted it on a retry received a full comparison in place of the pending rebuild, with no diagnostic; the type now makes each caller state which attempt it is.

* docs(upgrade-guide): move the system prompt integrations guide to v0.2.2-rc.5

The root version is 0.2.2-rc.5 after the master merge, and verify-upgrade-guides rejects a guide added under an earlier version directory.

* test(web): refresh the mention path presence recording for section-attributed system messages

* test: align two specs that master left failing

The DeepSeek settings spec waited for a saved notice carrying the provider label from before the rename to DeepSeek API. The Windows packaging workflow spec seeded one of the two helpers that the Stage workflow helpers step copies.

* chore: remove a Python cache file committed by mistake
2026-11-19 21:11:38 +08:00

224 lines
13 KiB
TypeScript

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'
import { parse, resolve } from 'node:path'
import yaml from 'js-yaml'
import { expect, it } from 'vitest'
const root = resolve(import.meta.dirname, '..')
const workflow = yaml.load(readFileSync(resolve(root, '.github/workflows/windows-package.yml'), 'utf8')) as {
on: Record<string, { inputs: Record<string, { type?: string; required?: boolean; default?: string; description?: string }> }>
permissions: Record<string, string>
concurrency: { group: string; 'cancel-in-progress': boolean }
jobs: Record<string, {
defaults?: { run: { shell: string } }
'runs-on': string | string[]
env: Record<string, string>
steps: Array<{
id?: string
name?: string
uses?: string
run?: string
if?: string
'working-directory'?: string
env?: Record<string, string>
with?: Record<string, unknown>
}>
}>
}
const job = workflow.jobs.package!
it.skipIf(process.platform !== 'win32')('resets only the allocated checkout without following dependency junctions', () => {
const directory = mkdtempSync(resolve(tmpdir(), 'windows-checkout-'))
try {
const parent = resolve(directory, 'runner-workspace')
const workspace = resolve(parent, 'repository')
const external = resolve(directory, 'external')
mkdirSync(workspace, { recursive: true })
mkdirSync(external)
writeFileSync(resolve(external, 'keep.txt'), 'keep')
symlinkSync(external, resolve(workspace, 'node_modules'), 'junction')
const script = resolve(directory, 'reset.ps1')
writeFileSync(script, job.steps.find(step => step.name === 'Reset packaging checkout')!.run!)
const run = (target: string) => execFileSync('pwsh', ['-NoProfile', '-File', script], {
cwd: directory,
env: { ...process.env, RUNNER_WORKSPACE: parent, GITHUB_WORKSPACE: target },
stdio: 'pipe',
})
run(workspace)
expect(existsSync(workspace)).toBe(true)
expect(existsSync(resolve(workspace, 'node_modules'))).toBe(false)
expect(readFileSync(resolve(external, 'keep.txt'), 'utf8')).toBe('keep')
expect(() => run(external)).toThrow()
rmSync(workspace, { recursive: true })
symlinkSync(external, workspace, 'junction')
expect(() => run(workspace)).toThrow()
expect(readFileSync(resolve(external, 'keep.txt'), 'utf8')).toBe('keep')
} finally {
rmSync(directory, { recursive: true, force: true, maxRetries: 3 })
}
})
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.')
expect(job.steps.find(step => step.name === 'Configure persistent pnpm store')?.env?.DSH_DESKTOP_PACKAGE_CACHE_DIR)
.toBe('${{ runner.tool_cache }}/dsh-desktop-package-cache')
expect(workflow.concurrency).toEqual({ group: 'windows-desktop-package', 'cancel-in-progress': false })
expect(workflow.permissions).toEqual({ contents: 'read' })
expect(Object.keys(workflow.on.workflow_dispatch!.inputs).sort()).toEqual([
'build_version', 'cache_namespace', 'compression_level', 'preset', 'signing', 'source_ref', 'test_release_id', 'update_channel', 'version_mode',
])
expect(workflow.on.workflow_dispatch!.inputs.signing!.default).toBe('signed')
expect(workflow.on.workflow_dispatch!.inputs.compression_level).toMatchObject({ type: 'choice', options: ['3', '7'], default: '3', required: true })
expect(job.env.PACKAGE_WINDOWS_COMPRESSION_LEVEL).toBe('${{ inputs.compression_level }}')
expect(workflow.on.workflow_dispatch!.inputs.build_version!.required).toBe(false)
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 == '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 }}')
expect(job.env.PACKAGE_SIGNING).toBe('${{ inputs.signing }}')
expect(job.steps.find(step => step.id === 'checkout')!.with).toMatchObject({ clean: true, 'persist-credentials': false, ref: '${{ inputs.source_ref }}' })
expect(job.steps.find(step => step.uses?.startsWith('pnpm/action-setup@'))?.with?.dest)
.toBe('${{ runner.temp }}/setup-pnpm-${{ github.run_id }}-${{ github.run_attempt }}')
})
it('validates before building and passes the same mode and version to checks and packaging', () => {
const settings = job.steps.find(step => step.id === 'settings')!
expect(settings.env).toEqual({ PACKAGE_BUILD_VERSION: '${{ inputs.build_version }}' })
const commands = job.steps.filter(step => step.run?.includes('package:desktop:win:x64'))
expect(commands).toHaveLength(2)
expect(commands[0]!.run).toContain("'--check'")
for (const step of commands) {
expect(step.env?.PACKAGE_VERSION).toBe('${{ steps.settings.outputs.version }}')
expect(step.run).toContain("if ($env:PACKAGE_SIGNING -eq 'unsigned') { $packageArgs += '--unsigned' }")
expect(step.run).toContain('exit $LASTEXITCODE')
}
for (const step of job.steps) expect(step.run ?? '').not.toContain('${{ inputs.')
expect(job.steps.indexOf(settings)).toBeLessThan(job.steps.indexOf(commands[0]!))
expect(job.steps.some(step => step.run?.includes('.env.windows'))).toBe(false)
})
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(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,
})
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', () => {
const command = '& "$env:PACKAGE_CI_HELPERS/windows-packaging-priority.ps1" -BestEffort'
expect(job.steps.find(entry => entry.name === 'Validate selected source and adapter support')!.run)
.not.toContain('windows-packaging-priority.ps1')
for (const name of ['Install locked dependencies', 'Build installer and verify packaged runtime']) {
const step = job.steps.find(entry => entry.name === name)!
expect(step.run!.trimStart().startsWith(command + '\n')).toBe(true)
}
})
it.skipIf(process.platform !== 'win32')('keeps the dependency store stable across run-specific pnpm homes', () => {
const directory = mkdtempSync(resolve(tmpdir(), 'windows-package-store-'))
try {
const workspace = resolve(directory, 'runner', 'repo')
const packageCache = resolve(directory, 'tool-cache', 'desktop')
const store = resolve(parse(directory).root, '.pnpm-store')
const step = job.steps.find(entry => entry.name === 'Configure persistent pnpm store')!
expect(job.steps.indexOf(step)).toBeLessThan(job.steps.findIndex(entry => entry.name === 'Install locked dependencies'))
const script = resolve(directory, 'store.ps1')
writeFileSync(script, "$ErrorActionPreference = 'Stop'\n" + step.run!)
const outputs = ['first', 'second'].map((run) => {
const environmentFile = resolve(directory, run + '.env')
execFileSync('pwsh', ['-NoProfile', '-File', script], {
env: { ...process.env, GITHUB_WORKSPACE: workspace,
PACKAGE_CACHE_NAMESPACE: '', DSH_DESKTOP_PACKAGE_CACHE_DIR: packageCache,
PNPM_HOME: resolve(directory, run, 'pnpm'), GITHUB_ENV: environmentFile },
stdio: 'pipe',
})
return readFileSync(environmentFile, 'utf8').trim()
})
expect(outputs.map(output => output.split(/\r?\n/u))).toEqual(Array.from({ length: 2 }, () => [
`DSH_DESKTOP_PACKAGE_CACHE_DIR=${packageCache}`, `PNPM_CONFIG_STORE_DIR=${store}`,
]))
const runNamespace = (namespace: string) => {
const output = resolve(directory, 'namespace.env')
rmSync(output, { force: true })
execFileSync('pwsh', ['-NoProfile', '-File', script], {
env: { ...process.env, GITHUB_WORKSPACE: workspace,
PACKAGE_CACHE_NAMESPACE: namespace, DSH_DESKTOP_PACKAGE_CACHE_DIR: packageCache, GITHUB_ENV: output },
stdio: 'pipe',
})
return readFileSync(output, 'utf8').trim().split(/\r?\n/u)
}
expect(runNamespace('perf-1')).toEqual([
`DSH_DESKTOP_PACKAGE_CACHE_DIR=${resolve(packageCache, 'perf-1')}`, `PNPM_CONFIG_STORE_DIR=${resolve(store, 'perf-1')}`,
])
for (const invalid of ['../escape', 'Upper', 'has space', 'con', 'perf\n', 'a'.repeat(65)]) {
expect(() => runNamespace(invalid)).toThrow()
}
} finally {
rmSync(directory, { recursive: true, force: true, maxRetries: 3 })
}
})
it('pins environment helpers to the workflow commit before selecting product source', () => {
const helper = job.steps.find(step => step.name === 'Checkout workflow helpers')!
const stage = job.steps.find(step => step.name === 'Stage workflow helpers')!
const source = job.steps.find(step => step.id === 'checkout')!
expect(helper.with).toMatchObject({ ref: '${{ github.workflow_sha }}', 'persist-credentials': false })
expect(job.steps.indexOf(helper)).toBeLessThan(job.steps.indexOf(stage))
expect(job.steps.indexOf(stage)).toBeLessThan(job.steps.indexOf(source))
expect(stage.run).toContain('RUNNER_TEMP')
expect(stage.run).toContain('windows-packaging-priority.ps1')
for (const step of job.steps.filter(step => step.name !== 'Stage workflow helpers')) {
expect(step.run ?? '').not.toContain('./apps/desktop/scripts/windows-packaging-priority.ps1')
}
})
it.skipIf(process.platform !== 'win32')('stages helpers that remain usable when product source lacks them', () => {
const directory = mkdtempSync(resolve(tmpdir(), 'workflow-helpers-'))
try {
const source = resolve(directory, 'source')
const scripts = resolve(source, 'apps/desktop/scripts')
const temporary = resolve(directory, 'temporary')
mkdirSync(scripts, { recursive: true })
mkdirSync(temporary)
for (const name of ['windows-packaging-priority.ps1', 'windows-packaging-summary.mjs']) {
writeFileSync(resolve(scripts, name), readFileSync(resolve(root, 'apps/desktop/scripts', name)))
}
const stage = resolve(directory, 'stage.ps1')
writeFileSync(stage, job.steps.find(step => step.name === 'Stage workflow helpers')!.run!)
const env = { ...process.env, RUNNER_TEMP: temporary, GITHUB_RUN_ID: '123', GITHUB_RUN_ATTEMPT: '1', GITHUB_ENV: resolve(directory, 'env') }
execFileSync('pwsh', ['-NoProfile', '-File', stage], { cwd: source, env, stdio: 'pipe' })
rmSync(scripts, { recursive: true })
const helper = resolve(temporary, 'packaging-helpers-123-1/windows-packaging-priority.ps1')
expect(execFileSync('pwsh', ['-NoProfile', '-File', helper, '-InspectOnly'], { cwd: source, stdio: 'pipe' }).toString())
.toContain('packaging-process-priority')
expect(() => execFileSync('pwsh', ['-NoProfile', '-File', stage], {
cwd: source, env: { ...env, GITHUB_RUN_ATTEMPT: '2' }, stdio: 'pipe',
})).toThrow()
} finally {
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)
})