跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

提交记录
修改docs/guide/guest-systems.md+15 −0看文件
@@ -108,6 +108,21 @@ Cage 会撤销临时管理员并关闭这台客机的首次设置入口。以后
108108
109109Windows 客机的系统账户和应用登录独立保存。管理助手未连接或原客机配置变化时,Cage 会提示核对原环境;恢复助手或更新 Cage 不应重建账户、替换原系统盘或初始化个人目录。
110110
111新增:### 使用 Windows 本机 ISO
112新增:
113新增:选择 Microsoft 官方 Windows 11 x64 ISO 后,在系统授权打开的安装窗口中设置客机初始本地管理员。默认名称为 `CageAdmin`,可以修改。请保存这个账户的密码,后续登录客机和继续安装时都需要使用。
114新增:
115新增:Cage 将账户信息写入具有私有权限的安装应答盘,Windows 首次设置据此创建本地管理员并跳过联网账户引导。客机保持零常规 Hyper-V 网卡,完成组件置备后使用 Cage 网络通道。应答盘在确认客机已完成首次设置、可以通过管理员账户连接后清理。
116新增:
117新增:1. 在“虚拟机连接”(VMConnect)窗口选择 Windows 版本、目标磁盘,确认许可并完成区域设置。本轮 PowerShell 创建窗口会自动关闭。
118新增:2. 使用安装前设置的本地管理员登录客机桌面,回到 Cage 点击“已进入桌面,继续安装”。
119新增:3. 确认系统授权,在 PowerShell 安装窗口再次输入客机管理员账户。保持该窗口开启,等待组件下载、安装和配置结束。Cage 会创建用于工作台的专用普通账户,并重启客机完成首次登录。
120新增:4. 回到 Cage 完成网络检查,再进入工作台。
121新增:
122新增:已有客机继续使用原账户和系统盘。若安装由旧版本创建,使用当时创建的客机管理员继续。若仍停在 Windows 首次设置的强制联网页面,可以在 VMConnect 中按 `Shift+F10`,先检查 `%WINDIR%\System32\OOBE\BypassNRO.cmd` 是否存在。仅在该脚本存在时运行它,重启后选择离线继续并创建本地账户。各 Windows 构建提供的入口不同,缺少该脚本时应保留虚拟磁盘并记录 Windows 构建号,进一步核查该版本的离线设置方式。
123新增:
124新增:安装卡片区分等待 Windows 首次设置、组件下载和组件配置。原用户注册助手失败时,操作详情会保留 `enrollment_pipe_listen_failed` 或 `enrollment_pipe_accept_failed` 及 Win32 错误码,便于定位继续安装的问题。
125新增:
111126## 下载量与磁盘空间
112127
113128系统镜像的下载大小和虚拟磁盘容量是两件事。Debian 基础镜像约 320–325 MiB,初始虚拟磁盘容量上限为 24 GiB;macOS 和 Windows 的安装介质与系统占用更大,具体以所选版本为准。创建前请为镜像、系统盘、开发工具、项目产物和更新备份留足空间。
修改docs/windows.md+2 −0看文件
@@ -8,6 +8,8 @@ Cage 的 Windows 版本面向 Windows 10 22H2(内部版本 19045)和 Windows
88
99“自动匹配本机系统版本”匹配 Windows 发行版本、版本类型和语言,展示主机与客机补丁构建差异;安装中断后继续原记录与系统盘。当前已实测建机、首次启动与冷启动,修复后的最终工作台登记仍待复验。完整条件和流程见[客机系统指南](guide/guest-systems.md#自动匹配本机系统版本)。
1010
11新增:使用本机 ISO 时,安装窗口会先收集客机本地管理员账户,用安装应答完成离线账户创建。进入客机桌面后回 Cage 继续安装,组件置备期间保持 PowerShell 安装窗口开启。具体步骤及旧安装接续见[使用 Windows 本机 ISO](guide/guest-systems.md#使用-windows-本机-iso)。
12新增:
1113| 项目 | 要求 |
1214|---|---|
1315| 系统 | x64 Windows 10 22H2 或 Windows 11;不包含 Windows ARM64 与 32 位系统 |
修改internal/workbench/setup_progress.go+13 −0看文件
@@ -76,9 +76,22 @@ func parseSetupProgress(line string) *SetupProgress {
7676 return nil
7777 }
7878 p := &SetupProgress{System: fields[1]}
79新增: if fields[1] == "windows-11" {
80新增: p.Operation = fields[2]
81新增: }
7982 switch fields[2] {
8083 case "restore":
8184 p.Phase, p.Label = "packages", "正在安装 "+guestProgressName(fields[1])+" 系统"
85新增: case "account", "oobe", "credentials":
86新增: if fields[1] != "windows-11" {
87新增: return nil
88新增: }
89新增: p.Phase = "packages"
90新增: p.Label = map[string]string{
91新增: "account": "请在安装窗口设置客机本地管理员",
92新增: "oobe": "请在虚拟机连接窗口完成 Windows 首次设置",
93新增: "credentials": "请在安装窗口输入客机管理员账户",
94新增: }[fields[2]]
8295 case "media":
8396 p.Phase, p.Label = "image", "正在下载并校验客机开发组件"
8497 case "tools":
修改internal/workbench/setup_progress_test.go+14 −0看文件
@@ -6,6 +6,20 @@ import (
66 "time"
77)
88
9新增:func TestWindowsInstallationInteractionStages(t *testing.T) {
10新增: for _, stage := range []string{"account", "oobe", "credentials", "media", "tools", "services"} {
11新增: progress := parseSetupProgress("CAGE_GUEST_STAGE windows-11 " + stage)
12新增: if progress == nil || progress.System != "windows-11" || progress.Operation != stage || progress.Label == "" {
13新增: t.Fatalf("Windows installation stage was lost: %s %+v", stage, progress)
14新增: }
15新增: }
16新增: for _, system := range []string{"macos", "debian-13", "ubuntu-22.04"} {
17新增: if parseSetupProgress("CAGE_GUEST_STAGE "+system+" oobe") != nil {
18新增: t.Fatalf("Windows interaction stage accepted for %s", system)
19新增: }
20新增: }
21新增:}
22新增:
923// Child pipes may split a progress line across writes. A fallback mirror may
1024// restart from zero, and an absent Content-Length must stay indeterminate.
1125func TestSetupProgressFromChildOutput(t *testing.T) {
修改scripts/ci-windows-build.ps1+3 −0看文件
@@ -62,6 +62,9 @@ try {
6262 }
6363 & (Join-Path $PSScriptRoot 'build-windows.ps1') -Release:$Release
6464 Invoke-BuildTool $windowsPowerShell @('-NoProfile', '-NonInteractive', '-File', 'scripts/guest-os/windows-host-enrollment.tests.ps1')
65新增: foreach ($test in @('windows-iso-setup.tests.ps1', 'windows-host-image.tests.ps1', 'new-windows-test-vm.tests.ps1')) {
66新增: Invoke-BuildTool $windowsPowerShell @('-NoProfile', '-NonInteractive', '-File', "scripts/guest-os/$test")
67新增: }
6568 Invoke-BuildTool 'go' @('test', './internal/guestos', '-run', '^TestWindowsHostEnrollment', '-count=1')
6669 if (-not $Release) {
6770 $windowsPowerShell = Join-Path ([Environment]::SystemDirectory) 'WindowsPowerShell/v1.0/powershell.exe'
修改scripts/guest-os/complete-windows-guest.ps1+9 −1看文件
@@ -199,9 +199,14 @@ try {
199199 Publish-ReadyBinding
200200 return
201201 }
202删除: if (!$GuestAdministrator) { $GuestAdministrator=Get-Credential -Message 'Cage: enter an administrator account of the selected virtual Windows machine.' }
202新增: if (!$GuestAdministrator) {
203新增: Write-Output 'CAGE_GUEST_STAGE windows-11 credentials'
204新增: $GuestAdministrator=Get-Credential -Message '先在虚拟机连接窗口完成 Windows 设置并登录桌面,再输入客机管理员账户。新建 ISO 安装请使用安装前设置的本地账户。请保持此 PowerShell 安装窗口开启。'
205新增: } else { Write-Output 'CAGE_GUEST_STAGE windows-11 services' }
203206 if (!$GuestAdministrator) { throw 'Windows guest setup canceled.' }
204207 $session=New-PSSession -VMId $VMId -Credential $GuestAdministrator
208新增: if ($choice.source.host.system -cne 'windows-11') { Remove-CageISOAnswer $vm $session $instance }
209新增: Write-Output 'CAGE_GUEST_STAGE windows-11 services'
205210 $target=Invoke-Command -Session $session -FilePath (Join-Path $PSScriptRoot 'initialize-windows-workbench-user.ps1') -ArgumentList $VMId
206211 $firstBoot=Join-Path $pairDirectory 'first-account-boot'
207212 if (!$target.AlreadySignedIn -and (Test-Path -LiteralPath $firstBoot) -and [IO.File]::ReadAllText($firstBoot) -ne $target.BootID) {
@@ -218,10 +223,12 @@ try {
218223 $packages=Get-Content -LiteralPath (Join-Path $payload 'windows-workbench-packages.json') -Raw | ConvertFrom-Json
219224 $cli=Get-Content -LiteralPath (Join-Path $payload 'cli-dependencies.json') -Raw | ConvertFrom-Json
220225 $files=@{}
226新增: Write-Output 'CAGE_GUEST_STAGE windows-11 media'
221227 foreach ($spec in @($packages.PSObject.Properties)+@($cli.PSObject.Properties)) {
222228 $files[$spec.Name]=Get-PinnedPackage $spec.Value $cache
223229 }
224230
231新增: Write-Output 'CAGE_GUEST_STAGE windows-11 tools'
225232 $scratch=Join-Path $workRoot ('stage-'+[guid]::NewGuid())
226233 $null=New-Item -ItemType Directory $scratch
227234 $core=Join-Path $scratch 'core'
@@ -314,6 +321,7 @@ try {
314321 }
315322
316323 [IO.File]::WriteAllText($completionMarker,$target.SID)
324新增: Write-Output 'CAGE_GUEST_STAGE windows-11 services'
317325 Publish-ReadyBinding
318326} finally {
319327 if ($session) { Remove-PSSession $session }
修改scripts/guest-os/new-windows-test-vm.ps1+16 −6看文件
@@ -1,4 +1,4 @@
1删除:#requires -Version 5.1
1新增:#requires -Version 5.1
22<#
33.SYNOPSIS
44Create an offline Windows 11 x64 test VM on a local Hyper-V host.
@@ -10,6 +10,9 @@ disk and guest TPM state stay together after shutdown. Use the returned VMId
1010as -ExpectedVMId for claude-desktop-windows.ps1. -Start boots only this VM.
1111Windows Setup installs PowerShell 7 for all guest users. Supply -PowerShellZip
1212to use an existing copy of the pinned Microsoft archive on an offline host.
13新增:Manual ISO setup prompts for the guest's initial local administrator. Supply
14新增:-GuestAdministrator to provide it directly. Windows Setup uses the protected
15新增:answer DVD to create that account without a network connection.
1316#>
1417[CmdletBinding(SupportsShouldProcess)]
1518param(
@@ -29,8 +32,8 @@ param(
2932)
3033$ErrorActionPreference = 'Stop'
3134. (Join-Path $PSScriptRoot 'windows-guest-media.ps1')
35新增:. (Join-Path $PSScriptRoot 'windows-host-image.ps1')
3236$fromHost = ![string]::IsNullOrEmpty($ImageEdition)
33删除:if ($fromHost) { . (Join-Path $PSScriptRoot 'windows-host-image.ps1') }
3437
3538function Set-TestVMResources($VM, [int]$Processors, [long]$MemoryBytes) {
3639 # New-VM can inherit Dynamic Memory with a 1 TiB maximum on a client host.
@@ -80,6 +83,15 @@ if ([IO.DriveInfo]::new($parent.Root.FullName).AvailableFreeSpace -lt $requiredF
8083}
8184if (!$PSCmdlet.ShouldProcess($directory, "Create offline Hyper-V VM '$Name' (start: $([bool]$Start))")) { return }
8285
86新增:if ($fromHost) {
87新增: $answer = New-CageCloneAnswer $GuestAdministrator $ImageLanguage
88新增:} else {
89新增: if (!$GuestAdministrator) {
90新增: $GuestAdministrator = Get-Credential -UserName 'CageAdmin' -Message '设置虚拟 Windows 的初始本地管理员和密码。安装后用此账户登录客机,并在 Cage 继续安装时再次输入。'
91新增: }
92新增: $answer = New-CageISOAnswer $GuestAdministrator
93新增:}
94新增:
8395# Create with a protected ACL, then claim the requested name using a same-volume
8496# rename that fails atomically if another creation has already won.
8597$acl = [Security.AccessControl.DirectorySecurity]::new()
@@ -108,10 +120,8 @@ try {
108120 [IO.Directory]::Move($staging, $directory)
109121 $staged = $false
110122 $claimed = $true
111删除: # On a normal install Windows Setup still asks for edition, disk, license
112删除: # and account. The second DVD contributes only the guest development tools.
113删除: $answer = [xml]'<unattend xmlns="urn:schemas-microsoft-com:unattend"><settings pass="specialize"/></unattend>'
114删除: if ($fromHost) { $answer = New-CageCloneAnswer $GuestAdministrator $ImageLanguage }
123新增: # The protected second DVD supplies the chosen local account and tools.
124新增: # Windows Setup still asks for edition, disk, license and regional settings.
115125 New-WindowsGuestAnswerISO $toolsISO $answer $PowerShellZip
116126 $ownsToolsISO = $true
117127 $vm = New-VM -Name $Name -Generation 2 -MemoryStartupBytes ($MemoryGiB * 1GB) -NoVHD -Path $directory
修改scripts/guest-os/setup-windows-guest.ps1+59 −7看文件
@@ -1,4 +1,4 @@
1删除:#requires -Version 5.1
1新增:#requires -Version 5.1
22[CmdletBinding()]
33param(
44 [Parameter(Mandatory)][string]$Profile,
@@ -17,6 +17,25 @@ $ProgressPreference='SilentlyContinue'
1717$identity=[Security.Principal.WindowsIdentity]::GetCurrent()
1818$principal=[Security.Principal.WindowsPrincipal]::new($identity)
1919. (Join-Path $PSScriptRoot 'windows-host-image.ps1')
20新增:
21新增:function Wait-CageWindowsInstaller($Process, [string]$ProgressFile) {
22新增: $lastStage = ''
23新增: do {
24新增: $exited = $Process.WaitForExit(250)
25新增: $stage = ''
26新增: $reader = $null
27新增: try {
28新增: $reader = [IO.StreamReader]::new([IO.File]::Open($ProgressFile, 'Open', 'Read', 'ReadWrite'))
29新增: $stage = $reader.ReadToEnd()
30新增: } catch [IO.IOException] { }
31新增: finally { if ($reader) { $reader.Dispose() } }
32新增: if ($stage -cmatch '^CAGE_GUEST_STAGE windows-11 (account|oobe|credentials|media|tools|services)$' -and $stage -cne $lastStage) {
33新增: Write-Output $stage
34新增: $lastStage = $stage
35新增: }
36新增: } while (!$exited)
37新增:}
38新增:
2039if(!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)){
2140 if($identity.User.Value -cne $HostUserSID){throw 'Continue setup with the already authorized host user.'}
2241 if($HostEnrollment){throw 'Original user enrollment must be created by this setup process.'}
@@ -34,20 +53,52 @@ if(!$principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator))
3453 }
3554 # Preserve every selected installation argument across the one-time UAC
3655 # boundary. Encoded data cannot become executable PowerShell syntax.
37删除: $parameters=@{Profile=$Profile;State=$State;InstallationID=$InstallationID.ToString('D');IsoPath=$IsoPath;ExpectedIsoSha256=$ExpectedIsoSha256;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;HostUserSID=$HostUserSID;HostEnrollment=$context}
56新增: $progressFile=Join-Path ([IO.Path]::GetTempPath()) ('cage-windows-setup-'+[guid]::NewGuid().ToString('N')+'.stage')
57新增: # Hold the new file without delete sharing across UAC. The elevated writer
58新增: # opens this existing file once, so its path cannot be replaced mid-install.
59新增: $progressHandle=[IO.File]::Open($progressFile,'CreateNew','ReadWrite','ReadWrite')
60新增: $parameters=@{Profile=$Profile;State=$State;InstallationID=$InstallationID.ToString('D');IsoPath=$IsoPath;ExpectedIsoSha256=$ExpectedIsoSha256;ManifestPath=$ManifestPath;ManifestSHA256=$ManifestSHA256;HostUserSID=$HostUserSID;HostEnrollment=$context;ProgressFile=$progressFile}
3861 $payload=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes(($parameters|ConvertTo-Json -Depth 6 -Compress)))
3962 $script=[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($PSCommandPath))
40删除: $command='$ErrorActionPreference=''Stop'';$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$payload+'''))|ConvertFrom-Json;$a=@{};$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value};$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('''+$script+'''));try{& $s @a;exit 0}catch{Write-Error $_;exit 1}'
63新增: $command=@'
64新增:$ErrorActionPreference='Stop'
65新增:$p=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__PARAMETERS__'))|ConvertFrom-Json
66新增:$a=@{}
67新增:$p.PSObject.Properties|ForEach-Object{$a[$_.Name]=$_.Value}
68新增:$progressFile=$a.ProgressFile
69新增:$a.Remove('ProgressFile')
70新增:$s=[Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('__SCRIPT__'))
71新增:$progressStream=$null
72新增:try {
73新增: $progressStream=[IO.File]::Open($progressFile,'Open','Write','ReadWrite')
74新增: & $s @a | ForEach-Object {
75新增: $line=[string]$_
76新增: if ($line -cmatch '^CAGE_GUEST_STAGE windows-11 (account|oobe|credentials|media|tools|services)$') {
77新增: $bytes=[Text.Encoding]::UTF8.GetBytes($line)
78新增: $progressStream.Position=0
79新增: $progressStream.SetLength(0)
80新增: $progressStream.Write($bytes,0,$bytes.Length)
81新增: $progressStream.Flush()
82新增: }
83新增: Write-Output $_
84新增: }
85新增: exit 0
86新增:} catch { Write-Error $_; exit 1 }
87新增:finally { if ($progressStream) { $progressStream.Dispose() } }
88新增:'@
89新增: $command=$command.Replace('__PARAMETERS__',$payload).Replace('__SCRIPT__',$script)
4190 $encoded=[Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
4291 try{
4392 if($context){Wait-CageHostEnrollment $context $worker}
4493 $process=Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'WindowsPowerShell/v1.0/powershell.exe') -ArgumentList @('-NoLogo','-NoProfile','-ExecutionPolicy','RemoteSigned','-EncodedCommand',$encoded) -Verb RunAs -PassThru
4594 if($context){Set-CageHostEnrollmentAdmin $context $process}
46删除: $process.WaitForExit()
95新增: Wait-CageWindowsInstaller $process $progressFile
4796 if($process.ExitCode -ne 0){throw 'Windows setup did not complete; existing VM and data were preserved.'}
4897 }finally{
4998 if($context){try{Stop-CageHostEnrollment $context}catch{}}
5099 if($worker){if(!$worker.WaitForExit(5000) -and [Cage.HostEnrollment.Native]::Started([uint32]$worker.Id) -eq [long]$context.WorkerStarted){$worker.Kill();$worker.WaitForExit()};$worker.Dispose()}
100新增: $progressHandle.Dispose()
101新增: try { [IO.File]::Delete($progressFile) } catch [IO.IOException] { }
51102 }
52103 return
53104}
@@ -100,6 +151,7 @@ if ($readyToProvision) {
100151 if (!$vm.Count) {
101152 $imageOptions = @{}
102153 if ($fromHost) { $imageOptions = @{ ImageEdition=$owner.source.host.edition; ImageLanguage=$owner.source.host.language; ImageBuild=$owner.source.build; GuestAdministrator=$setupCredential } }
154新增: else { Write-Output 'CAGE_GUEST_STAGE windows-11 account' }
103155 $created=& (Join-Path $PSScriptRoot 'new-windows-guest.ps1') -Name $name -IsoPath $IsoPath -ExpectedIsoSha256 $ExpectedIsoSha256 -InstanceDirectory $instance -Confirm:$false @imageOptions
104156 $vm=Hyper-V\Get-VM -Id $created.VMId
105157 } elseif ($vm.Count -eq 1) { $vm=$vm[0] }
@@ -116,13 +168,13 @@ if ($readyToProvision) {
116168if ($vm.State -eq 'Off') { Hyper-V\Start-VM -VM $vm; $vm=Hyper-V\Get-VM -Id $vm.Id }
117169if ($vm.State -ne 'Running') { throw 'The private Windows guest is not running yet. Retry after its current operation.' }
118170if (!$readyToProvision -and !$fromHost) {
119删除: & (Join-Path ([Environment]::GetFolderPath('System')) 'vmconnect.exe') localhost $name
120删除: Write-Output 'Complete Windows Setup, then continue installation in Cage and authenticate with the guest administrator.'
171新增: Start-Process -FilePath (Join-Path ([Environment]::GetFolderPath('System')) 'vmconnect.exe') -ArgumentList @('localhost',$name)
172新增: Write-Output 'CAGE_GUEST_STAGE windows-11 oobe'
173新增: Write-Output '在虚拟机连接窗口完成 Windows 安装,用安装前设置的本地管理员登录桌面,再回 Cage 点击「已进入桌面,继续安装」。本轮 PowerShell 创建窗口会自动关闭。'
121174 return
122175}
123176$componentsReady = (Test-Path -LiteralPath (Join-Path $instance 'cage-workbench/pair/workbench-components-ready')) -and
124177 (Test-Path -LiteralPath (Join-Path $instance 'cage-workbench/pair/windows-guest.json'))
125178if ($fromHost -and $setupCredential -and !$published -and !$componentsReady) { Wait-CageWindowsSetup $vm.Id $setupCredential }
126删除:Write-Output 'CAGE_GUEST_STAGE windows-11 tools'
127179& (Join-Path $PSScriptRoot 'complete-windows-guest.ps1') -VMId $vm.Id -InstanceDirectory $instance -HostProfileDirectory $Profile -HostUserSID $HostUserSID -StateDirectory $state -HostEnrollment $HostEnrollment -ManifestPath $ManifestPath -ManifestSHA256 $ManifestSHA256 -GuestAdministrator $setupCredential
128180Write-Output 'CAGE_GUEST_STAGE windows-11 services'
修改scripts/guest-os/windows-host-image.ps1+50 −0看文件
@@ -1,5 +1,55 @@
11#requires -Version 5.1
22# Functions used only for a new private Windows guest disk.
3新增:function New-CageISOAnswer([pscredential]$Administrator) {
4新增: if (!$Administrator -or $Administrator.UserName.Length -gt 20 -or
5新增: $Administrator.UserName -match '["/\\\[\]:;|=,+*?<>@\x00-\x1f]' -or
6新增: $Administrator.UserName.Trim() -cne $Administrator.UserName -or $Administrator.UserName.EndsWith('.') -or
7新增: $Administrator.UserName -in @('Administrator', 'Guest', 'DefaultAccount', 'WDAGUtilityAccount', 'cagesetup') -or
8新增: $Administrator.Password.Length -eq 0) {
9新增: throw '请输入新的客机本地管理员名称和非空密码。用户名最多 20 个字符,请使用普通本地名称。'
10新增: }
11新增: $answer = [xml]@'
12新增:<unattend xmlns="urn:schemas-microsoft-com:unattend" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State">
13新增: <settings pass="specialize"/>
14新增: <settings pass="oobeSystem">
15新增: <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS">
16新增: <OOBE><HideOnlineAccountScreens>true</HideOnlineAccountScreens><HideWirelessSetupInOOBE>true</HideWirelessSetupInOOBE></OOBE>
17新增: <UserAccounts><LocalAccounts><LocalAccount wcm:action="add"><Name/><Description>Cage ISO initial administrator</Description><Group>Administrators</Group><Password><Value/><PlainText>true</PlainText></Password></LocalAccount></LocalAccounts></UserAccounts>
18新增: </component>
19新增: </settings>
20新增:</unattend>
21新增:'@
22新增: $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable)
23新增: $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend')
24新增: $answer.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText = $Administrator.UserName
25新增: $answer.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText = $Administrator.GetNetworkCredential().Password
26新增: return $answer
27新增:}
28新增:
29新增:function Remove-CageISOAnswer($VM, $Session, [string]$InstanceDirectory) {
30新增: Invoke-Command -Session $Session -ArgumentList $VM.Id -ScriptBlock {
31新增: param($expected)
32新增: if ([guid](Get-ItemProperty 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineId -ne $expected) { throw 'wrong guest' }
33新增: $setup = Get-ItemProperty 'HKLM:\SYSTEM\Setup'
34新增: if ($setup.SystemSetupInProgress -ne 0 -or $setup.OOBEInProgress -ne 0 -or !(Test-Path 'C:\Program Files\PowerShell\7\pwsh.exe')) {
35新增: throw '请在虚拟机连接窗口完成 Windows 首次设置并登录桌面,然后回 Cage 继续安装。'
36新增: }
37新增: foreach ($path in @('C:\Windows\Panther\Unattend.xml', 'C:\Windows\Panther\Unattend\Unattend.xml')) {
38新增: if (!(Test-Path -LiteralPath $path -PathType Leaf)) { continue }
39新增: try { $answer = [xml][IO.File]::ReadAllText($path) }
40新增: catch { continue } # Preserve an unrecognized answer without logging its contents.
41新增: $ns = [Xml.XmlNamespaceManager]::new($answer.NameTable)
42新增: $ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend')
43新增: if ($answer.SelectSingleNode('//u:LocalAccount[u:Description="Cage ISO initial administrator"]', $ns)) {
44新增: Remove-Item -LiteralPath $path -Force
45新增: }
46新增: }
47新增: }
48新增: $answerPath = Join-Path $InstanceDirectory 'windows-guest-tools.iso'
49新增: $VM | Hyper-V\Get-VMDvdDrive | Where-Object Path -eq $answerPath | Hyper-V\Remove-VMDvdDrive
50新增: [IO.File]::Delete($answerPath)
51新增:}
52新增:
353function New-CageCloneAnswer([pscredential]$Administrator, [string]$Language) {
454 if (!$Administrator -or $Administrator.UserName -cne 'cagesetup' -or $Language -notmatch '^[a-zA-Z]{2,3}-[a-zA-Z0-9-]{2,12}$') {
555 throw 'The new guest setup identity or language is invalid.'
新增scripts/guest-os/windows-iso-setup.tests.ps1+119 −0看文件
@@ -0,0 +1,119 @@
1新增:#requires -Version 5.1
2新增:$ErrorActionPreference = 'Stop'
3新增:. (Join-Path $PSScriptRoot 'windows-host-image.ps1')
4新增:function Assert-Check([bool]$Condition, [string]$Message) { if (!$Condition) { throw $Message } }
5新增:$credential = [pscredential]::new('CageAdmin', (ConvertTo-SecureString 'Test-only<&>"Account!123' -AsPlainText -Force))
6新增:$answer = New-CageISOAnswer $credential
7新增:$ns = [Xml.XmlNamespaceManager]::new($answer.NameTable)
8新增:$ns.AddNamespace('u', 'urn:schemas-microsoft-com:unattend')
9新增:$roundtrip = [xml]$answer.OuterXml
10新增:Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'CageAdmin') 'Initial account name changed.'
11新增:Assert-Check ($roundtrip.SelectSingleNode('//u:LocalAccount/u:Password/u:Value', $ns).InnerText -ceq $credential.GetNetworkCredential().Password) 'Password XML escaping changed the credential.'
12新增:Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Group', $ns).InnerText -ceq 'Administrators') 'PowerShell Direct needs the initial administrator.'
13新增:foreach ($setting in @('HideOnlineAccountScreens', 'HideWirelessSetupInOOBE')) {
14新增: Assert-Check ($answer.SelectSingleNode('//u:OOBE/u:'+$setting, $ns).InnerText -ceq 'true') 'Offline OOBE settings are missing.'
15新增:}
16新增:Assert-Check ($answer.SelectNodes('//u:DiskConfiguration | //u:ImageInstall | //u:HideEULAPage | //u:AcceptEula | //u:ProductKey | //u:AutoLogon | //u:UILanguage | //u:SkipMachineOOBE', $ns).Count -eq 0) 'Manual ISO choices or administrator sign-in were overridden.'
17新增:foreach ($name in @('Administrator', 'cagesetup', 'host\user', '[email protected]', 'abcdefghijklmnopqrstu')) {
18新增: try {
19新增: $null = New-CageISOAnswer ([pscredential]::new($name, $credential.Password))
20新增: throw 'Invalid account accepted'
21新增: } catch { if ($_.Exception.Message -eq 'Invalid account accepted') { throw } }
22新增:}
23新增:
24新增:# Execute the production branch which chooses the answer before creating a disk.
25新增:$errors = $null
26新增:$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'new-windows-test-vm.ps1'), [ref]$null, [ref]$errors)
27新增:Assert-Check ($errors.Count -eq 0) 'VM creation script failed to parse.'
28新增:$selection = @($ast.EndBlock.Statements | Where-Object { $_.Extent.Text.StartsWith('if ($fromHost) {') })[0]
29新增:Assert-Check ($null -ne $selection) 'Missing production answer selection.'
30新增:$createAnswer = [scriptblock]::Create($selection.Extent.Text)
31新增:$script:prompts = 0
32新增:function Get-Credential { param($UserName, $Message); $script:prompts++; return $credential }
33新增:$fromHost = $false
34新增:$GuestAdministrator = $null
35新增:. $createAnswer
36新增:Assert-Check ($script:prompts -eq 1 -and $answer.SelectNodes('//u:LocalAccount', $ns).Count -eq 1) 'The manual route did not collect an offline account.'
37新增:. $createAnswer
38新增:Assert-Check ($script:prompts -eq 1) 'An explicit credential prompted again.'
39新增:$fromHost = $true
40新增:$GuestAdministrator = [pscredential]::new('cagesetup', $credential.Password)
41新增:$ImageLanguage = 'zh-CN'
42新增:. $createAnswer
43新增:Assert-Check ($answer.SelectSingleNode('//u:LocalAccount/u:Name', $ns).InnerText -ceq 'cagesetup') 'Clone setup account changed.'
44新增:Assert-Check ($answer.SelectSingleNode('//u:UILanguage', $ns).InnerText -ceq 'zh-CN') 'Clone locale changed.'
45新增:
46新增:# The owner's progress reader accepts only known stages and reads the final
47新增:# stage after process exit. Arbitrary child output never becomes UI content.
48新增:$ast = [Management.Automation.Language.Parser]::ParseFile((Join-Path $PSScriptRoot 'setup-windows-guest.ps1'), [ref]$null, [ref]$errors)
49新增:Assert-Check ($errors.Count -eq 0) 'Setup orchestration failed to parse.'
50新增:$wait = $ast.Find({ param($node) $node -is [Management.Automation.Language.FunctionDefinitionAst] -and $node.Name -eq 'Wait-CageWindowsInstaller' }, $true)
51新增:. ([scriptblock]::Create($wait.Extent.Text))
52新增:$progressFile = [IO.Path]::GetTempFileName()
53新增:$heldProgress = [IO.File]::Open($progressFile, 'Open', 'ReadWrite', 'ReadWrite')
54新增:$writer = [IO.File]::Open($progressFile, 'Open', 'Write', 'ReadWrite')
55新增:try {
56新增: $process = [pscustomobject]@{ Position = 0; Writer = $writer; Stages = @('CAGE_GUEST_STAGE windows-11 account', 'private diagnostic fixture', 'CAGE_GUEST_STAGE windows-11 media', 'CAGE_GUEST_STAGE windows-11 tools', 'CAGE_GUEST_STAGE windows-11 services', 'CAGE_GUEST_STAGE windows-11 oobe') }
57新增: $process | Add-Member -MemberType ScriptMethod -Name WaitForExit -Value {
58新增: param($Timeout)
59新增: $bytes = [Text.Encoding]::UTF8.GetBytes($this.Stages[$this.Position])
60新增: $this.Writer.Position = 0
61新增: $this.Writer.SetLength(0)
62新增: $this.Writer.Write($bytes, 0, $bytes.Length)
63新增: $this.Writer.Flush()
64新增: $this.Position++
65新增: return $this.Position -eq $this.Stages.Count
66新增: }
67新增: $stages = @(Wait-CageWindowsInstaller $process $progressFile)
68新增: Assert-Check ($stages.Count -eq 5 -and $stages[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'Final progress or stage filtering failed.'
69新增: $writer.Dispose()
70新增:
71新增: # Execute the exact encoded wrapper in a real child PowerShell process.
72新增: # UAC itself is covered by native acceptance, while file sharing is exercised here.
73新增: $wrapper = $ast.Find({ param($node) $node -is [Management.Automation.Language.AssignmentStatementAst] -and $node.Left.Extent.Text -eq '$command' -and $node.Right.Extent.Text.StartsWith("@'") }, $true)
74新增: $literal = $wrapper.Right.Find({ param($node) $node -is [Management.Automation.Language.StringConstantExpressionAst] }, $true)
75新增: $command = $literal.Value
76新增: $fixtureScript = $progressFile+'.ps1'
77新增: $stdout = $progressFile+'.stdout'
78新增: $stderr = $progressFile+'.stderr'
79新增: try {
80新增: [IO.File]::WriteAllText($fixtureScript, "Write-Output 'CAGE_GUEST_STAGE windows-11 account'`nWrite-Output 'private diagnostic fixture'`nWrite-Output 'CAGE_GUEST_STAGE windows-11 oobe'")
81新增: $payload = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes((@{ProgressFile=$progressFile}|ConvertTo-Json -Compress)))
82新增: $scriptPath = [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes($fixtureScript))
83新增: $command = $command.Replace('__PARAMETERS__', $payload).Replace('__SCRIPT__', $scriptPath)
84新增: $encoded = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($command))
85新增: $child = Start-Process -FilePath (Get-Process -Id $PID).Path -ArgumentList @('-NoLogo','-NoProfile','-NonInteractive','-EncodedCommand',$encoded) -RedirectStandardOutput $stdout -RedirectStandardError $stderr -PassThru
86新增: try {
87新增: $forwarded = @(Wait-CageWindowsInstaller $child $progressFile)
88新增: Assert-Check ($child.ExitCode -eq 0) ('Encoded installer wrapper failed. '+[IO.File]::ReadAllText($stderr))
89新增: Assert-Check ($forwarded[-1] -ceq 'CAGE_GUEST_STAGE windows-11 oobe') 'The actual child could not publish its final stage.'
90新增: } finally { $child.Dispose() }
91新增: } finally {
92新增: foreach ($path in @($fixtureScript,$stdout,$stderr)) { [IO.File]::Delete($path) }
93新增: }
94新增:} finally { $writer.Dispose(); $heldProgress.Dispose(); [IO.File]::Delete($progressFile) }
95新增:
96新增:# An interrupted or unauthenticated guest retains its answer media. Successful
97新增:# cleanup only removes the fixed tools ISO and preserves the original disk.
98新增:$directory = Join-Path ([IO.Path]::GetTempPath()) ('cage-iso-answer-'+[guid]::NewGuid().ToString('N'))
99新增:$null = [IO.Directory]::CreateDirectory($directory)
100新增:try {
101新增: $iso = Join-Path $directory 'windows-guest-tools.iso'
102新增: $disk = Join-Path $directory 'system.vhdx'
103新增: [IO.File]::WriteAllText($iso, 'private answer fixture')
104新增: [IO.File]::WriteAllText($disk, 'existing personal disk fixture')
105新增: $vm = [pscustomobject]@{ Id = [guid]::NewGuid() }
106新增: $script:guestReady = $false
107新增: $script:removedDVDs = @()
108新增: function Invoke-Command { param($Session, $ArgumentList, $ScriptBlock); if (!$script:guestReady) { throw 'Guest setup incomplete' } }
109新增: function Hyper-V\Get-VMDvdDrive { process { @([pscustomobject]@{Path=$iso}, [pscustomobject]@{Path='original-windows.iso'}) } }
110新增: function Hyper-V\Remove-VMDvdDrive { process { $script:removedDVDs += $_.Path } }
111新增: try { Remove-CageISOAnswer $vm 'session' $directory; throw 'Incomplete setup was accepted' }
112新增: catch { if ($_.Exception.Message -cne 'Guest setup incomplete') { throw } }
113新增: Assert-Check ((Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 0) 'Unfinished setup lost its answer media.'
114新增: $script:guestReady = $true
115新增: Remove-CageISOAnswer $vm 'session' $directory
116新增: Assert-Check (!(Test-Path -LiteralPath $iso) -and $script:removedDVDs.Count -eq 1 -and $script:removedDVDs[0] -eq $iso) 'Cleanup touched the wrong DVD.'
117新增: Assert-Check ([IO.File]::ReadAllText($disk) -ceq 'existing personal disk fixture') 'Cleanup changed the retained disk.'
118新增:} finally { [IO.Directory]::Delete($directory, $true) }
119新增:Write-Output 'Passed manual ISO account/OOBE XML, retained manual choices, clone parity and elevated installer progress forwarding.'
修改ui/scripts/setup-progress-smoke.mjs+43 −0看文件
@@ -94,3 +94,46 @@ try {
9494 console.log("PASS: native image bytes, percent, measured rate, refresh, separate verification, install stage, 375px layout and native retry.");
9595 } finally {await browser.close();}
9696}
97新增:
98新增:{
99新增: const { browser, page, state, errors } = await createWorkbench({
100新增: initialization: { required: true, tracked: true, started: true },
101新增: clientContext: { mode: "local", connection_id: "local", client_platform: "windows", server_platform: "windows" },
102新增: beforeNavigate: async (page, state) => {
103新增: state.status.job = { id: "windows-install", kind: "guest-install", running: false,
104新增: setup_progress: { system: "windows-11", phase: "packages", operation: "oobe", label: "请在虚拟机连接窗口完成 Windows 首次设置" } };
105新增: },
106新增: });
107新增: try {
108新增: const panel = page.getByRole("region", { name: "环境安装进度" });
109新增: await panel.getByText(/虚拟机连接(VMConnect)窗口/).waitFor();
110新增: assert.equal(await panel.getByRole("progressbar").count(), 0);
111新增: assert.equal(await panel.getByRole("button", { name: "停止安装" }).count(), 0);
112新增: await page.reload();
113新增: const resume = panel.getByRole("button", { name: "已进入桌面,继续安装" });
114新增: await resume.waitFor();
115新增: let submitted;
116新增: await page.route("**/api/start", route => {
117新增: submitted = route.request().postDataJSON();
118新增: state.status.job = { ...state.status.job, running: true,
119新增: setup_progress: { system: "windows-11", phase: "packages", operation: "credentials", label: "请在安装窗口输入客机管理员账户" } };
120新增: return route.fulfill({ json: state.status.job });
121新增: });
122新增: await resume.click();
123新增: await panel.getByText(/请保持该窗口开启/).waitFor();
124新增: assert.equal(submitted.guest_system, "windows-11");
125新增: assert.equal(await resume.count(), 0);
126新增: for (const [operation, phase, label] of [["media", "image", "正在下载并校验客机开发组件"], ["tools", "tools", "正在安装客机应用和开发工具"], ["services", "services", "正在完成客机配置"]]) {
127新增: state.status.job.setup_progress = { system: "windows-11", phase, operation, label };
128新增: await panel.getByRole("heading", { name: label }).waitFor();
129新增: await panel.getByText(/请保持 PowerShell 安装窗口开启/).waitFor();
130新增: }
131新增: await page.setViewportSize({ width: 600, height: 650 });
132新增: assert.equal(await page.evaluate(() => document.documentElement.scrollWidth > innerWidth), false);
133新增: if (process.env.CAGE_SETUP_WINDOWS_SCREENSHOT) await page.screenshot({ path: process.env.CAGE_SETUP_WINDOWS_SCREENSHOT, animations: "disabled" });
134新增: state.status.job.setup_progress = { system: "macos", phase: "tools", label: "正在安装客机应用和开发工具" };
135新增: await panel.getByText(/请保持 PowerShell 安装窗口开启/).waitFor({ state: "hidden" });
136新增: assert.deepEqual(errors, []);
137新增: console.log("PASS: Windows OOBE resume, refresh, guest credentials, component phases and platform-specific guidance.");
138新增: } finally { await browser.close(); }
139新增:}
修改ui/src/guest-system-picker.jsx+1 −1看文件
@@ -114,7 +114,7 @@ export function GuestSystemPicker({ system, onChange, preserveOnUnmount = false,
114114 </div>}
115115 <small>客机账户和独立密码由 Cage 自动准备并加密保管,启动时自动登录。</small>
116116 </> : <>
117删除: <small>Windows 11 x64 需要 Hyper-V 和至少 64 GiB 可用磁盘空间。宿主安装开发组件时需要同一 Windows 账户的管理员权限。完成 Windows 安装后,通过客机管理员确认一次,Cage 会创建专用普通账户并重启客机。</small>
117新增: <small>Windows 11 x64 需要 Hyper-V 和至少 64 GiB 可用磁盘空间。安装前在授权窗口设置客机本地管理员,Cage 会生成离线账户应答。进入客机桌面后回 Cage 继续,使用该账户确认组件安装。Cage 随后创建专用普通账户并重启客机。</small>
118118 {!system.pending && <div>
119119 <button type="button" onClick={() => reference("windows-media")}>从微软下载 ISO</button>
120120 <button type="button" onClick={choose}>选择本机 ISO</button>
修改ui/src/setup-progress.jsx+10 −3看文件
@@ -20,12 +20,15 @@ function bytes(value) {
2020export function SetupProgress({ job, onDetails, onStop, onRetry, disconnected }) {
2121 const { phase, label, received, total, bytes_per_second, operation } = job.setup_progress;
2222 const native = job.kind === "guest-install";
23新增: const windows = native && job.setup_progress.system === "windows-11";
2324 const stage = stages.find(([key]) => key === phase);
2425 const Icon = stage?.[2] || Box;
2526 const hasBytes = Number.isFinite(received) && received >= 0;
2627 const knownSize = hasBytes && Number.isFinite(total) && total > 0 && received <= total;
2728 const percent = knownSize ? Math.floor(received / total * 100) : null;
2829 const failed = Boolean(job.error);
30新增: const waitingForWindows = windows && operation === "oobe";
31新增: const canContinue = failed || (waitingForWindows && !job.running);
2932 const meter = knownSize ? `${bytes(received)} / ${bytes(total)}` : hasBytes ? `已接收 ${bytes(received)}` : "";
3033 return <section className={`setup-progress${failed ? " setup-progress-failed" : ""}`} aria-label="环境安装进度">
3134 <ol className="setup-stages" aria-label="安装阶段">
@@ -41,12 +44,16 @@ export function SetupProgress({ job, onDetails, onStop, onRetry, disconnected })
4144 </div>
4245 {knownSize && <strong className="setup-transfer-number">{percent}<small>%</small></strong>}
4346 </div>
44删除: {!failed && <div role="progressbar" aria-label={label || stage?.[1] || "当前操作"}
47新增: {!failed && !waitingForWindows && <div role="progressbar" aria-label={label || stage?.[1] || "当前操作"}
4548 aria-valuemin={0} aria-valuemax={100} aria-valuenow={percent ?? undefined}
4649 aria-valuetext={knownSize ? `${percent}%,${meter}` : meter || undefined}
4750 className={knownSize ? "setup-meter" : "setup-meter setup-meter-active"}>
4851 <span style={knownSize ? { width: `${received / total * 100}%` } : undefined} />
4952 </div>}
53新增: {windows && operation === "account" && <p className="setup-transfer-hint">为虚拟 Windows 设置新的本地管理员名称和密码。安装后用此账户登录客机,并在继续安装时再次输入。</p>}
54新增: {waitingForWindows && <p className="setup-transfer-hint">在虚拟机连接(VMConnect)窗口选择 Windows 版本、磁盘和区域,使用安装前设置的本地管理员登录桌面,再回到 Cage 继续。本轮 PowerShell 创建窗口会自动关闭。</p>}
55新增: {windows && operation === "credentials" && <p className="setup-transfer-hint">确认客机已登录桌面,在 PowerShell 安装窗口输入客机管理员账户。请保持该窗口开启,等待组件安装结束。</p>}
56新增: {windows && ["media", "tools", "services"].includes(operation) && <p className="setup-transfer-hint">请保持 PowerShell 安装窗口开启,Cage 完成组件安装后会自动关闭。</p>}
5057 {failed && <>
5158 <p className="setup-transfer-error" role="alert"><SafetyMessage message={job.error} /></p>
5259 <p className="setup-transfer-hint">可手动继续安装,已保存的下载会尝试续传。</p>
@@ -54,8 +61,8 @@ export function SetupProgress({ job, onDetails, onStop, onRetry, disconnected })
5461 </div>
5562 <div className="setup-transfer-actions">
5663 <button className="text-button" type="button" onClick={onDetails}>操作详情</button>
57删除: {failed
58删除: ? <button type="button" className="primary" onClick={onRetry} disabled={disconnected}>继续安装</button>
64新增: {canContinue
65新增: ? <button type="button" className="primary" onClick={onRetry} disabled={disconnected}>{waitingForWindows && !failed ? "已进入桌面,继续安装" : "继续安装"}</button>
5966 : <button type="button" onClick={onStop} disabled={disconnected}>停止安装</button>}
6067 </div>
6168 </section>;