Merge pull request #169 from Nwflower/feat/ui-polish
feat(ui,app,host): polish update UX, relocate moved VM registry, dedupe GPUs, and fix clone MCP flow
This commit is contained in:
48 files changed
+1368
-309
No files matched your search
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复克隆虚拟机没有主机 SSH 端口转发的问题。源虚拟机开启端口转发时,克隆出的虚拟机现在会占用源端口之后的一个空闲端口,因此 MCP 临时会话与克隆上的 SSH 相关工具(`guest_exec`、`guest_wait_ready`、`test_run` 等)可以正常连接客体。源虚拟机未开启转发时克隆仍不开启。",
|
||||
"en": "Fix cloned VMs having no host SSH port forward. When the source VM forwards SSH, a clone now takes the next free port after the source port, so SSH-based guest tools such as `guest_exec`, `guest_wait_ready`, and `test_run` work on MCP temporary sessions and other clones. A source without forwarding still yields a clone without one."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复 MCP 临时克隆无法自动输入登录密码、SSH 用户名常为空的问题。克隆不保存自己的虚拟机设置,现在它读取 `login_password` 和 `username` 时会回退到来源虚拟机,且仅在来源虚拟机仍开启「允许 AI 访问」时生效;撤销来源的授权后克隆立即失去回退。密码不会复制进克隆,克隆销毁后不留存副本。虚拟机未保存登录密码时,解锁会提示去 MCP 服务设置里填写,而不是返回内部错误。",
|
||||
"en": "Fix MCP temporary clones failing to type the login password and often reporting an empty SSH username. A clone keeps no VM settings of its own, so reads of `login_password` and `username` now fall back to the source VM, and only while the source still allows AI access; revoking access on the source removes the fallback immediately. The password is never copied into the clone, so disposing it leaves no copy behind. When a VM has no saved login password, unlock now asks you to set it in the MCP Service settings instead of returning an internal error."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复宿主机存在多份 Vulkan ICD 驱动清单时,内核页重复显示同一块显卡且缺失驱动版本号的问题。",
|
||||
"en": "Deduplicate repeated Vulkan physical device entries on the Runtime page when multiple ICD manifests are registered for the same GPU."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "fixes",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "修复手动移动数据目录并在设置或首启界面重新选择新目录后,因虚拟机注册表保留旧路径导致无法启动虚拟机的问题。",
|
||||
"en": "Fix VMs failing to start after moving the data folder and reselecting its new location by updating stale paths in the VM registry."
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"group": "improvements",
|
||||
"order": 0,
|
||||
"authors": ["Nwflower"],
|
||||
"zh": "下载速度低于 1 MB/s 时改以 KB/s 显示,精简关于页与更新通道文案,默认同步宿主机内存规格并将外观与语言设置分组置顶,更新检查按通道缓存 5 分钟且切换通道时不再禁用控件。",
|
||||
"en": "Display download speeds below 1 MB/s in KB/s, tighten About page and update channel copy, sync host memory SMBIOS specs by default and move Appearance & language to the top of Settings, cache update checks per channel for 5 minutes, and keep the update channel selector interactive while switching."
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { loadTestModule } from './load-test-module.mjs'
|
||||
|
||||
const { currentTask, findActiveOfflineTask, pruneFinishedTasks, upsertTask } =
|
||||
const { currentTask, findActiveOfflineTask, pruneFinishedTasks, taskDetail, upsertTask } =
|
||||
await loadTestModule(`export * from './lib/tasks'`)
|
||||
|
||||
const task = (id, overrides = {}) => ({
|
||||
@@ -33,3 +33,10 @@ test('one installer download represents the VM creations waiting for it', () =>
|
||||
primary: download, waitingVMs: ['vm one'], matchedIDs: ['download', 'vm'],
|
||||
})
|
||||
})
|
||||
|
||||
test('taskDetail formats download speeds under 1 MB/s in KB/s', () => {
|
||||
assert.equal(taskDetail(task('slow', { done: 5e6, total: 50e6, rate: 512e3 })), '5 MB / 50 MB · 512 KB/s')
|
||||
assert.equal(taskDetail(task('tiny', { done: 1e6, total: 10e6, rate: 200 })), '1 MB / 10 MB · 1 KB/s')
|
||||
assert.equal(taskDetail(task('fast', { done: 2e9, total: 10e9, rate: 12.5e6 })), '2.0 GB / 10.0 GB · 12.5 MB/s')
|
||||
assert.equal(taskDetail(task('gig', { done: 2e9, total: 10e9, rate: 1.2e9 })), '2.0 GB / 10.0 GB · 1.2 GB/s')
|
||||
})
|
||||
+30
-3
@@ -516,13 +516,40 @@ export const App: React.FC = () => {
|
||||
const setChannel = (alpha: boolean) => {
|
||||
api.SetRuntimeChannel(alpha ? 'alpha' : 'stable').then(() => refresh()).catch((e) => fail(tr('failGeneric'), e))
|
||||
}
|
||||
const appChannelSeqRef = useRef(0)
|
||||
const appChannelPendingRef = useRef<'stable' | 'alpha' | 'dev' | null>(null)
|
||||
const appChannelFlushRef = useRef<Promise<void> | null>(null)
|
||||
const appUpdateChannel = state?.config.app_update_channel === 'alpha' || state?.config.app_update_channel === 'dev'
|
||||
? state.config.app_update_channel
|
||||
: 'stable'
|
||||
const setAppUpdateChannel = async (ch: 'stable' | 'alpha' | 'dev') => {
|
||||
await api.SetAppUpdateChannel(ch)
|
||||
await refresh()
|
||||
await update.recheck()
|
||||
const seq = ++appChannelSeqRef.current
|
||||
setState((prev) => (prev ? { ...prev, config: { ...prev.config, app_update_channel: ch } } : prev))
|
||||
appChannelPendingRef.current = ch
|
||||
if (!appChannelFlushRef.current) {
|
||||
appChannelFlushRef.current = (async () => {
|
||||
while (appChannelPendingRef.current !== null) {
|
||||
const target = appChannelPendingRef.current
|
||||
appChannelPendingRef.current = null
|
||||
await api.SetAppUpdateChannel(target)
|
||||
}
|
||||
})().finally(() => {
|
||||
appChannelFlushRef.current = null
|
||||
})
|
||||
}
|
||||
try {
|
||||
await appChannelFlushRef.current
|
||||
} catch (e) {
|
||||
if (appChannelSeqRef.current === seq) {
|
||||
appChannelPendingRef.current = null
|
||||
void refresh()
|
||||
throw e
|
||||
}
|
||||
return
|
||||
}
|
||||
if (appChannelSeqRef.current !== seq) return
|
||||
await update.recheck(false)
|
||||
if (appChannelSeqRef.current === seq) void refresh()
|
||||
}
|
||||
const cancelTask = (id: string) => { api.CancelTask(id).catch((e) => fail(tr('failGeneric'), e)) }
|
||||
|
||||
|
||||
@@ -43,7 +43,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
}) => {
|
||||
const tr = (k: I18nKey, v?: Record<string, string | number>) => t(locale, k, v)
|
||||
const [checkingUpdate, setCheckingUpdate] = useState(false)
|
||||
const [switchingChannel, setSwitchingChannel] = useState(false)
|
||||
const [updateErr, setUpdateErr] = useState('')
|
||||
const [qqInstalled, setQQInstalled] = useState<boolean | null>(null)
|
||||
const [openingQQ, setOpeningQQ] = useState(false)
|
||||
@@ -128,54 +127,53 @@ export const AboutPage: React.FC<Props> = ({
|
||||
}
|
||||
|
||||
const handleChannelChange = async (next: AppUpdateChannel) => {
|
||||
if (next === appUpdateChannel || switchingChannel) return
|
||||
setSwitchingChannel(true)
|
||||
if (next === appUpdateChannel) return
|
||||
setUpdateErr('')
|
||||
try {
|
||||
await onAppUpdateChannel(next)
|
||||
} catch (e) {
|
||||
setUpdateErr(String(e).replace(/^Error:\s*/, ''))
|
||||
} finally {
|
||||
setSwitchingChannel(false)
|
||||
}
|
||||
}
|
||||
|
||||
const version = appVersion ?? appUpdate?.current ?? ''
|
||||
const visibleUpdate = appUpdate && (!appUpdate.channel || appUpdate.channel === appUpdateChannel) ? appUpdate : null
|
||||
const visiblePhase: UpdatePhase = visibleUpdate ? updatePhase : 'none'
|
||||
const version = appVersion ?? visibleUpdate?.current ?? ''
|
||||
const pct = updateTask && updateTask.percent >= 0 ? Math.round(updateTask.percent) : null
|
||||
const updateAvailableKey: I18nKey = appUpdate?.channel === 'dev'
|
||||
const updateAvailableKey: I18nKey = visibleUpdate?.channel === 'dev'
|
||||
? 'appUpdateAvailableDev'
|
||||
: appUpdate?.channel === 'alpha'
|
||||
: visibleUpdate?.channel === 'alpha'
|
||||
? 'appUpdateAvailableAlpha'
|
||||
: 'appUpdateAvailable'
|
||||
|
||||
let updateSub: React.ReactNode = null
|
||||
if (updatePhase === 'downloading') {
|
||||
if (visiblePhase === 'downloading') {
|
||||
updateSub = (
|
||||
<>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: appUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<div className="row-sub">{tr('updateDownloadingSub', { v: visibleUpdate?.latest ?? '' })}{updateTask && taskDetail(updateTask) ? ` · ${taskDetail(updateTask)}` : ''}</div>
|
||||
<span className="progress rg-p-progress about-update-progress" aria-hidden="true">
|
||||
<span className="progress-fill" style={{ transform: `scaleX(${(pct ?? 0) / 100})` }} />
|
||||
</span>
|
||||
</>
|
||||
)
|
||||
} else if (updatePhase === 'ready') {
|
||||
updateSub = <div className="row-sub">{tr('updateReadySub', { v: appUpdate?.latest ?? '' })}</div>
|
||||
} else if (updatePhase === 'failed') {
|
||||
} else if (visiblePhase === 'ready') {
|
||||
updateSub = <div className="row-sub">{tr('updateReadySub', { v: visibleUpdate?.latest ?? '' })}</div>
|
||||
} else if (visiblePhase === 'failed') {
|
||||
updateSub = <div className="row-sub warn-text" title={updateTask?.error}>{tr('updateFailedSub')}</div>
|
||||
} else if (appUpdate?.has_update) {
|
||||
updateSub = <div className="row-sub">{tr(updateAvailableKey, { v: appUpdate.latest })}</div>
|
||||
} else if (visibleUpdate?.has_update) {
|
||||
updateSub = <div className="row-sub">{tr(updateAvailableKey, { v: visibleUpdate.latest })}</div>
|
||||
} else if (updateErr) {
|
||||
updateSub = <div className="row-sub" title={updateErr}>{tr('appUpdateLookupFailed')}</div>
|
||||
}
|
||||
|
||||
let updateAction: React.ReactNode
|
||||
if (updatePhase === 'downloading') {
|
||||
if (visiblePhase === 'downloading') {
|
||||
updateAction = <Button onClick={onCancelUpdate}>{tr('updateCancel')}</Button>
|
||||
} else if (updatePhase === 'ready') {
|
||||
} else if (visiblePhase === 'ready') {
|
||||
updateAction = <Button variant="primary" busy={installing} onClick={onInstallUpdate}>{tr('updateRestart')}</Button>
|
||||
} else if (updatePhase === 'failed') {
|
||||
} else if (visiblePhase === 'failed') {
|
||||
updateAction = <Button variant="primary" icon={<RotateCw size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateRetry')}</Button>
|
||||
} else if (updatePhase === 'available') {
|
||||
} else if (visiblePhase === 'available') {
|
||||
updateAction = <Button variant="primary" icon={<Download size={14} aria-hidden="true" />} onClick={onDownloadUpdate}>{tr('updateDownloadInstall')}</Button>
|
||||
} else {
|
||||
updateAction = <Button busy={checkingUpdate} onClick={() => void runUpdateCheck(true)}>{tr('appCheckUpdate')}</Button>
|
||||
@@ -197,15 +195,15 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-main">
|
||||
<div className="row-title">
|
||||
{tr('appVersionTitle')} <span className="mono">{version}</span>
|
||||
{appUpdate && !appUpdate.has_update && (
|
||||
{visibleUpdate && !visibleUpdate.has_update && (
|
||||
<span className="badge rg-p-badge badge-ok">{tr('appUpToDate')}</span>
|
||||
)}
|
||||
</div>
|
||||
{updateSub}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{appUpdate?.has_update && appUpdate.page_url && (
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(appUpdate.page_url!)}>
|
||||
{visibleUpdate?.has_update && visibleUpdate.page_url && (
|
||||
<Button variant="ghost" icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(visibleUpdate.page_url!)}>
|
||||
{tr('updateReleaseNotes')}
|
||||
</Button>
|
||||
)}
|
||||
@@ -229,9 +227,9 @@ export const AboutPage: React.FC<Props> = ({
|
||||
value={appUpdateChannel}
|
||||
onChange={(v) => void handleChannelChange(v)}
|
||||
options={[
|
||||
{ value: 'stable' as AppUpdateChannel, label: tr('appUpdateChannelStable'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'alpha' as AppUpdateChannel, label: tr('appUpdateChannelAlpha'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'dev' as AppUpdateChannel, label: tr('appUpdateChannelDev'), disabled: switchingChannel || checkingUpdate || updatePhase === 'downloading' || installing },
|
||||
{ value: 'stable' as AppUpdateChannel, label: tr('appUpdateChannelStable'), disabled: updatePhase === 'downloading' || installing },
|
||||
{ value: 'alpha' as AppUpdateChannel, label: tr('appUpdateChannelAlpha'), disabled: updatePhase === 'downloading' || installing },
|
||||
{ value: 'dev' as AppUpdateChannel, label: tr('appUpdateChannelDev'), disabled: updatePhase === 'downloading' || installing },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
@@ -245,7 +243,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpWebsite')}</div>
|
||||
<div className="row-sub">{tr('aboutWebsiteSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(siteURL(locale))}>
|
||||
@@ -256,7 +253,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpProjectPage')}</div>
|
||||
<div className="row-sub">{tr('aboutProjectSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(REPO_URL)}>
|
||||
@@ -267,7 +263,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('helpReportIssue')}</div>
|
||||
<div className="row-sub">{tr('aboutIssueSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<ExternalLink size={14} aria-hidden="true" />} onClick={() => openURL(`${REPO_URL}/issues`)}>
|
||||
@@ -278,7 +273,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutLicensesTitle')}</div>
|
||||
<div className="row-sub">{tr('aboutLicensesSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Button icon={<Scale size={14} aria-hidden="true" />} onClick={() => void openLicenses()}>
|
||||
@@ -292,7 +286,6 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('aboutDiscord')}</div>
|
||||
<div className="row-sub">{tr('aboutDiscordSub')}</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{onCopy && (
|
||||
@@ -320,9 +313,7 @@ export const AboutPage: React.FC<Props> = ({
|
||||
<div className="row-sub">{tr('aboutQQNotInstalledSub')}</div>
|
||||
) : qqLaunchErr ? (
|
||||
<div className="row-sub" title={qqLaunchErr}>{tr('aboutQQLaunchFailed')}</div>
|
||||
) : (
|
||||
<div className="row-sub">{tr('aboutQQGroupSub')}</div>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
{qqInstalled && !qqLaunchErr ? (
|
||||
|
||||
@@ -123,9 +123,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
|
||||
const pcoreOpt = findOptimization(optimizations, 'pcore_pin')
|
||||
const missingFontScript = state.missing_font_hint || ''
|
||||
const memSpecLabel = host.memory_spec?.speed_mhz
|
||||
? `${host.memory_spec.speed_mhz} MHz${host.memory_spec.type_name ? ` ${host.memory_spec.type_name}` : ''}`
|
||||
: ''
|
||||
|
||||
const guard = (fn: () => Promise<unknown>) => async () => {
|
||||
try {
|
||||
@@ -491,6 +488,49 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
<div className="page-title"><h1>{tr('sidebarSettings')}</h1></div>
|
||||
</header>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('themeLabel')}</div>
|
||||
{(!canDark || !canLight) && (
|
||||
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
|
||||
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
|
||||
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsGeneral')}</div>
|
||||
<div className="list">
|
||||
@@ -524,24 +564,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('syncHostMemorySMBIOS')}</div>
|
||||
<div className="row-sub">
|
||||
{memSpecLabel
|
||||
? tr('syncHostMemorySMBIOSSub', { spec: memSpecLabel })
|
||||
: tr('syncHostMemorySMBIOSUnavailable')}
|
||||
</div>
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Switch
|
||||
label={tr('syncHostMemorySMBIOS')}
|
||||
disabled={!memSpecLabel}
|
||||
checked={!!memSpecLabel && !!config.sync_host_memory_smbios}
|
||||
onChange={(checked) => guard(() => api.SetSyncHostMemorySMBIOS(checked))()}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('minimizeToTray')}</div>
|
||||
@@ -826,49 +848,6 @@ export const AppSettingsPage: React.FC<Props> = ({
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('settingsAppearance')}</div>
|
||||
<div className="list">
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('themeLabel')}</div>
|
||||
{(!canDark || !canLight) && (
|
||||
<div className="row-sub">{tr(!canDark ? 'themePluginDarkDisabled' : 'themePluginLightDisabled')}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<Segmented
|
||||
label={tr('themeLabel')}
|
||||
value={themeMode}
|
||||
onChange={onThemeMode}
|
||||
options={[
|
||||
{ value: 'light', label: tr('themeLight'), disabled: !canLight },
|
||||
{ value: 'dark', label: tr('themeDark'), disabled: !canDark },
|
||||
{ value: 'system', label: tr('themeSystem'), disabled: !canLight || !canDark },
|
||||
]}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div className="row">
|
||||
<div className="row-main">
|
||||
<div className="row-title">{tr('language')}</div>
|
||||
<div className="row-sub">{tr('languageSub')}</div>
|
||||
{missingFontScript && (
|
||||
<div className="row-sub warn-text">{tr('fontMissingFoDHint', { script: missingFontScript })}</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="row-right">
|
||||
<PopupSelect
|
||||
label={tr('language')}
|
||||
value={config.locale || 'auto'}
|
||||
onChange={onSetLocale}
|
||||
options={getLocaleOptions(locales, locale, state.detected_locale)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{pluginViews.length > 0 && (
|
||||
<section className="section">
|
||||
<div className="section-title">{tr('sidebarPlugins')}</div>
|
||||
|
||||
@@ -6,8 +6,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"aboutCopyDiscord": "复制邀请链接",
|
||||
"aboutCopyQQGroup": "复制群号",
|
||||
"aboutDiscord": "Discord 社区",
|
||||
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutJoinDiscord": "加入服务器",
|
||||
"aboutJoinQQGroup": "加入群聊",
|
||||
"aboutLicensesOpenGitHub": "在 GitHub 查看",
|
||||
@@ -16,14 +14,11 @@ export const settingsZh: Record<string, string> = {
|
||||
"aboutLicensesTabNotice": "第三方声明",
|
||||
"aboutLicensesTitle": "开源许可与声明",
|
||||
"aboutLicensesView": "查看",
|
||||
"aboutProjectSub": "GitHub 上的源码与发布版本",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"aboutWebsiteSub": "reims.dev 上的下载、使用文档、插件市场与兼容性列表",
|
||||
"activate": "使用",
|
||||
"affinityApplyNow": "立即应用",
|
||||
"affinityAvoidLPE": "避开 LP-E",
|
||||
@@ -61,12 +56,12 @@ export const settingsZh: Record<string, string> = {
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(Dev 滚动版)",
|
||||
"appUpdateChannelAlpha": "Alpha",
|
||||
"appUpdateChannelDev": "Dev",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(开发版)",
|
||||
"appUpdateChannelAlpha": "测试版",
|
||||
"appUpdateChannelDev": "开发版",
|
||||
"appUpdateChannelStable": "稳定版",
|
||||
"appUpdateChannelSubKeepOld": "接收 {channel} 预发布版本;启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubKeepOld": "接收{channel};启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubStable": "仅接收经过验证的正式稳定版本",
|
||||
"appUpdateChannelTitle": "更新通道",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
@@ -116,7 +111,7 @@ export const settingsZh: Record<string, string> = {
|
||||
"catNetwork": "网络",
|
||||
"catStorage": "存储",
|
||||
"catStorageNet": "存储与网络",
|
||||
"choose": "浏览…",
|
||||
"choose": "选择…",
|
||||
"configured": "已配置",
|
||||
"coresUnit": "核",
|
||||
"cpuOverHint": "留给 Windows 的线程不足 2 个,电脑可能变卡",
|
||||
@@ -496,9 +491,6 @@ export const settingsZh: Record<string, string> = {
|
||||
"storageInstallers": "镜像",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "虚拟机文件",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
|
||||
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
|
||||
"targetDisplayDisconnectedOption": "已断开 · 回退至主显示器",
|
||||
"targetDisplayFallbackHint": "已保存的「{name}」当前未连接,将回退至主显示器",
|
||||
"targetDisplayHint": "目标显示器:{name}({w}×{h},{scale}% 缩放)",
|
||||
@@ -550,8 +542,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"aboutCopyDiscord": "Copy invite link",
|
||||
"aboutCopyQQGroup": "Copy group ID",
|
||||
"aboutDiscord": "Discord community",
|
||||
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutJoinDiscord": "Join server",
|
||||
"aboutJoinQQGroup": "Join group",
|
||||
"aboutLicensesOpenGitHub": "View on GitHub",
|
||||
@@ -560,14 +550,11 @@ export const settingsEn: Record<string, string> = {
|
||||
"aboutLicensesTabNotice": "Third-party notices",
|
||||
"aboutLicensesTitle": "Open-source licenses",
|
||||
"aboutLicensesView": "View",
|
||||
"aboutProjectSub": "Source code and releases on GitHub",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"aboutWebsiteSub": "Downloads, docs, plugin market and compatibility list on reims.dev",
|
||||
"activate": "Use",
|
||||
"affinityApplyNow": "Apply Now",
|
||||
"affinityAvoidLPE": "Exclude LP-E",
|
||||
@@ -660,7 +647,7 @@ export const settingsEn: Record<string, string> = {
|
||||
"catNetwork": "Network",
|
||||
"catStorage": "Storage",
|
||||
"catStorageNet": "Storage \u0026 Network",
|
||||
"choose": "Browse…",
|
||||
"choose": "Choose…",
|
||||
"configured": "Configured",
|
||||
"coresUnit": "cores",
|
||||
"cpuOverHint": "Leaves Windows fewer than 2 threads; your PC may slow down",
|
||||
@@ -1040,9 +1027,6 @@ export const settingsEn: Record<string, string> = {
|
||||
"storageInstallers": "Images",
|
||||
"storageRuntimes": "Reims-Go",
|
||||
"storageVMs": "VM files",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
|
||||
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
|
||||
"targetDisplayDisconnectedOption": "Disconnected · using primary",
|
||||
"targetDisplayFallbackHint": "Saved {name} is disconnected; falling back to the primary display",
|
||||
"targetDisplayHint": "Target display: {name} ({w}×{h} at {scale}%)",
|
||||
|
||||
@@ -5,8 +5,6 @@ export type I18nKey =
|
||||
| "aboutCopyDiscord"
|
||||
| "aboutCopyQQGroup"
|
||||
| "aboutDiscord"
|
||||
| "aboutDiscordSub"
|
||||
| "aboutIssueSub"
|
||||
| "aboutJoinDiscord"
|
||||
| "aboutJoinQQGroup"
|
||||
| "aboutLicensesOpenGitHub"
|
||||
@@ -15,14 +13,11 @@ export type I18nKey =
|
||||
| "aboutLicensesTabNotice"
|
||||
| "aboutLicensesTitle"
|
||||
| "aboutLicensesView"
|
||||
| "aboutProjectSub"
|
||||
| "aboutQQGroup"
|
||||
| "aboutQQGroupSub"
|
||||
| "aboutQQLaunchFailed"
|
||||
| "aboutQQNotInstalled"
|
||||
| "aboutQQNotInstalledSub"
|
||||
| "aboutTagline"
|
||||
| "aboutWebsiteSub"
|
||||
| "activate"
|
||||
| "affinityApplyNow"
|
||||
| "affinityAvoidLPE"
|
||||
@@ -1068,9 +1063,6 @@ export type I18nKey =
|
||||
| "suspendedNoticeDescWithTime"
|
||||
| "suspendedNoticeTitle"
|
||||
| "suspendedSettingsHint"
|
||||
| "syncHostMemorySMBIOS"
|
||||
| "syncHostMemorySMBIOSSub"
|
||||
| "syncHostMemorySMBIOSUnavailable"
|
||||
| "targetDisplayDisconnectedOption"
|
||||
| "targetDisplayFallbackHint"
|
||||
| "targetDisplayHint"
|
||||
|
||||
@@ -46,12 +46,12 @@ export function taskTitle(locale: Locale, task: Task): string {
|
||||
}
|
||||
}
|
||||
|
||||
/** "8.3 / 18.4 GB · 42 MB/s" */
|
||||
/** "8.3 / 18.4 GB · 42 MB/s" or "12 / 50 MB · 512 KB/s" */
|
||||
export function taskDetail(task: Task): string {
|
||||
const parts: string[] = []
|
||||
if (task.total > 0) parts.push(`${bytes(task.done)} / ${bytes(task.total)}`)
|
||||
else if (task.done > 0) parts.push(bytes(task.done))
|
||||
if (task.rate > 0) parts.push(`${bytes(task.rate)}/s`)
|
||||
if (task.rate > 0) parts.push(rate(task.rate))
|
||||
return parts.join(' · ')
|
||||
}
|
||||
|
||||
@@ -187,3 +187,9 @@ function bytes(b: number): string {
|
||||
if (b >= 1e9) return `${(b / 1e9).toFixed(1)} GB`
|
||||
return `${Math.max(1, Math.ceil(b / 1e6))} MB`
|
||||
}
|
||||
|
||||
function rate(b: number): string {
|
||||
if (b >= 1e9) return `${(b / 1e9).toFixed(1)} GB/s`
|
||||
if (b >= 1e6) return `${(b / 1e6).toFixed(1)} MB/s`
|
||||
return `${Math.max(1, Math.round(b / 1e3))} KB/s`
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { AppUpdateInfo, Task } from '../types'
|
||||
import { api } from '../wails'
|
||||
|
||||
@@ -26,12 +26,18 @@ export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options)
|
||||
})
|
||||
const [confirming, setConfirming] = useState(false)
|
||||
const [installing, setInstalling] = useState(false)
|
||||
const reqSeqRef = useRef(0)
|
||||
|
||||
// Check once the app is up, then every 6 hours, so the sidebar's update
|
||||
// button shows up without opening the About page.
|
||||
useEffect(() => {
|
||||
if (!ready) return
|
||||
const check = () => { api.CheckAppUpdate(false).then(setInfo).catch((e) => console.warn('[app] CheckAppUpdate failed:', e)) }
|
||||
const check = () => {
|
||||
const seq = ++reqSeqRef.current
|
||||
api.CheckAppUpdate(false)
|
||||
.then((next) => { if (reqSeqRef.current === seq) setInfo(next) })
|
||||
.catch((e) => console.warn('[app] CheckAppUpdate failed:', e))
|
||||
}
|
||||
check()
|
||||
const id = window.setInterval(check, CHECK_EVERY_MS)
|
||||
return () => window.clearInterval(id)
|
||||
@@ -55,14 +61,18 @@ export function useAppUpdate({ ready, tasks, runningVMCount, onError }: Options)
|
||||
}
|
||||
|
||||
/** Forgets a dismissed release and asks again, e.g. after the update channel changed. */
|
||||
const recheck = async () => {
|
||||
const recheck = async (force = false) => {
|
||||
const seq = ++reqSeqRef.current
|
||||
setDismissed('')
|
||||
try { localStorage.removeItem(DISMISSED_KEY) } catch (e) { console.warn('[app] clear dismissed update failed:', e) }
|
||||
try {
|
||||
setInfo(await api.CheckAppUpdate(true))
|
||||
const next = await api.CheckAppUpdate(force)
|
||||
if (reqSeqRef.current === seq) setInfo(next)
|
||||
} catch (e) {
|
||||
setInfo(null)
|
||||
throw e
|
||||
if (reqSeqRef.current === seq) {
|
||||
setInfo(null)
|
||||
throw e
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Vendored
-2
@@ -272,8 +272,6 @@ export function SetQEMUASLR(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetRuntimeChannel(arg1:string):Promise<void>;
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1:boolean):Promise<void>;
|
||||
|
||||
export function SetVMAffinity(arg1:string,arg2:string,arg3:app.VMAffinityUpdate):Promise<app.VMAffinityStatus>;
|
||||
|
||||
export function SetVMDisplay(arg1:string,arg2:string,arg3:string):Promise<app.VMDisplayStatus>;
|
||||
|
||||
@@ -522,10 +522,6 @@ export function SetRuntimeChannel(arg1) {
|
||||
return window['go']['app']['App']['SetRuntimeChannel'](arg1);
|
||||
}
|
||||
|
||||
export function SetSyncHostMemorySMBIOS(arg1) {
|
||||
return window['go']['app']['App']['SetSyncHostMemorySMBIOS'](arg1);
|
||||
}
|
||||
|
||||
export function SetVMAffinity(arg1, arg2, arg3) {
|
||||
return window['go']['app']['App']['SetVMAffinity'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
@@ -812,7 +812,6 @@ export namespace config {
|
||||
qemu_aslr?: boolean;
|
||||
app_update_channel?: string;
|
||||
minimize_to_tray?: boolean;
|
||||
sync_host_memory_smbios?: boolean;
|
||||
host_dns_mode?: string;
|
||||
host_dns_doh_url?: string;
|
||||
enable_hypervisor_switch?: boolean;
|
||||
@@ -834,7 +833,6 @@ export namespace config {
|
||||
this.qemu_aslr = source["qemu_aslr"];
|
||||
this.app_update_channel = source["app_update_channel"];
|
||||
this.minimize_to_tray = source["minimize_to_tray"];
|
||||
this.sync_host_memory_smbios = source["sync_host_memory_smbios"];
|
||||
this.host_dns_mode = source["host_dns_mode"];
|
||||
this.host_dns_doh_url = source["host_dns_doh_url"];
|
||||
this.enable_hypervisor_switch = source["enable_hypervisor_switch"];
|
||||
|
||||
+19
-10
@@ -116,8 +116,9 @@ type App struct {
|
||||
resolveFolderVolume func(string) (host.DirectoryVolume, error)
|
||||
imeBridge *host.IMEBridge
|
||||
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
trayMgr *tray.Manager
|
||||
allowQuit bool
|
||||
launchPrevDataRoot string
|
||||
quitMode string
|
||||
vmStarts sync.WaitGroup
|
||||
lastVMs []driver.VMListItem
|
||||
@@ -182,10 +183,13 @@ type Lifecycle struct {
|
||||
func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
i18n.SetDetailRedactor(host.RedactText)
|
||||
cfg, needsSetup, err := config.Resolve()
|
||||
launchPrevDataRoot := ""
|
||||
if launch.DataRoot != "" {
|
||||
cfg, err = config.Load(filepath.Join(launch.DataRoot, "reims-go.json"))
|
||||
if err != nil {
|
||||
cfg = config.Default()
|
||||
} else if cfg.DataRoot != "" && !sameDataFolder(cfg.DataRoot, launch.DataRoot) {
|
||||
launchPrevDataRoot = cfg.DataRoot
|
||||
}
|
||||
cfg.DataRoot = launch.DataRoot
|
||||
needsSetup = false
|
||||
@@ -193,9 +197,10 @@ func New(trayIcon []byte, launch cli.WindowArgs) (*App, Lifecycle) {
|
||||
cfg = config.Default()
|
||||
}
|
||||
a := &App{
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
cfg: cfg,
|
||||
needsSetup: needsSetup,
|
||||
launch: launch,
|
||||
launchPrevDataRoot: launchPrevDataRoot,
|
||||
trayIcon: trayIcon,
|
||||
transitions: make(map[string]string),
|
||||
pendingChanges: make(map[string][]PendingChange),
|
||||
@@ -471,10 +476,6 @@ func (a *App) SetMinimizeToTray(enabled bool) error {
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.MinimizeToTray = &enabled })
|
||||
}
|
||||
|
||||
func (a *App) SetSyncHostMemorySMBIOS(enabled bool) error {
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.SyncHostMemorySMBIOS = enabled })
|
||||
}
|
||||
|
||||
// showMainWindow restores and focuses the Wails window from the system tray.
|
||||
func (a *App) showMainWindow() {
|
||||
if a.ctx == nil {
|
||||
@@ -704,12 +705,18 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
nextCfg, err := config.LoadExisting(cfgPath)
|
||||
fresh := errors.Is(err, os.ErrNotExist)
|
||||
recordedOldRoot := ""
|
||||
if fresh {
|
||||
nextCfg = config.Default()
|
||||
nextCfg.Locale = prev.Locale
|
||||
nextCfg.QEMUASLR = prev.QEMUASLR
|
||||
} else if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
} else {
|
||||
recordedOldRoot = nextCfg.DataRoot
|
||||
}
|
||||
if recordedOldRoot == "" || sameDataFolder(recordedOldRoot, dir) {
|
||||
recordedOldRoot = prev.DataRoot
|
||||
}
|
||||
nextCfg.DataRoot = dir
|
||||
if changed && !setup {
|
||||
@@ -738,7 +745,6 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
nextCfg.RuntimeChannel = cur.RuntimeChannel
|
||||
nextCfg.AppUpdateChannel = cur.AppUpdateChannel
|
||||
nextCfg.MinimizeToTray = cur.MinimizeToTray
|
||||
nextCfg.SyncHostMemorySMBIOS = cur.SyncHostMemorySMBIOS
|
||||
nextCfg.EnableHypervisorSwitch = cur.EnableHypervisorSwitch
|
||||
nextCfg.HostDNSMode, nextCfg.HostDNSDoHURL = cur.HostDNSMode, cur.HostDNSDoHURL
|
||||
nextCfg.FullscreenHotkeyEnabled = cur.FullscreenHotkeyEnabled
|
||||
@@ -766,6 +772,9 @@ func (a *App) setDataRoot(dir string, syncPolicy func(context.Context, string, s
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() {
|
||||
a.relocateRegisteredVMs(dir, recordedOldRoot)
|
||||
}
|
||||
|
||||
// Leaving a read-only folder starts the plugins and polling it held back,
|
||||
// even when the user picked the same folder again after fixing it.
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/driver"
|
||||
"github.com/Nwflower/reims-go/internal/host"
|
||||
"github.com/Nwflower/reims-go/internal/i18n"
|
||||
"github.com/Nwflower/reims-go/internal/lifecycle"
|
||||
"github.com/Nwflower/reims-go/internal/plugin"
|
||||
"github.com/Nwflower/reims-go/internal/testutil/fakedriver"
|
||||
)
|
||||
|
||||
const cloneSourceSettingPlugin = "test.clone.agent"
|
||||
|
||||
// newCloneSettingsEnv builds a host whose MCP clone reads its settings from a
|
||||
// source VM. The plugin declares the same login_password/username/
|
||||
// allow_ai_access schema as reims.agent, scoped to the VM.
|
||||
func newCloneSettingsEnv(t *testing.T) (*App, *plugin.Manager, driver.Driver) {
|
||||
t.Helper()
|
||||
cfg := config.Default()
|
||||
cfg.DataRoot = t.TempDir()
|
||||
mgr, err := plugin.NewManager(plugin.ManagerOptions{DataRoot: cfg.DataRoot, HostVersion: "0.0.0"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(mgr.Close)
|
||||
if err := mgr.Registry().Register(plugin.PluginDef{
|
||||
Manifest: plugin.Manifest{
|
||||
ID: cloneSourceSettingPlugin,
|
||||
Version: "1.0.0",
|
||||
Name: plugin.LocalizedText{EnUS: cloneSourceSettingPlugin},
|
||||
Settings: &plugin.SettingsSchema{
|
||||
Scope: "vm",
|
||||
Properties: map[string]plugin.SettingProperty{
|
||||
"allow_ai_access": {Type: "boolean"},
|
||||
"username": {Type: "string"},
|
||||
"login_password": {Type: "string", Secret: true},
|
||||
},
|
||||
},
|
||||
},
|
||||
Source: plugin.SourceBuiltin,
|
||||
Desired: true,
|
||||
Activate: func(_ context.Context, _ *plugin.Scope) error {
|
||||
return nil
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mgr.Registry().Reconcile(context.Background())
|
||||
|
||||
h := fakedriver.NewHarness(t)
|
||||
drv := h.Add("hosted", "test.clone.driver", "test.driver.clone")
|
||||
|
||||
app := &App{
|
||||
cfg: cfg,
|
||||
pluginMgr: mgr,
|
||||
transitions: map[string]string{},
|
||||
pendingChanges: map[string][]PendingChange{},
|
||||
pollWake: make(chan struct{}, 1),
|
||||
diskPaths: map[string]cachedDiskPath{},
|
||||
procSamples: map[string]host.ProcessSample{},
|
||||
driverRouter: h.Router,
|
||||
vmStateTable: h.States,
|
||||
lifecycleSvc: lifecycle.New(h.Registry, h.Router, nil),
|
||||
}
|
||||
return app, mgr, drv
|
||||
}
|
||||
|
||||
func createVMs(t *testing.T, drv driver.Driver, names ...string) {
|
||||
t.Helper()
|
||||
for _, name := range names {
|
||||
if err := drv.Create(context.Background(), driver.CreateRequest{DriverID: drv.ID(), Name: name}, io.Discard, io.Discard); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneSecretFallsBackToAuthorizedSource(t *testing.T) {
|
||||
app, mgr, drv := newCloneSettingsEnv(t)
|
||||
createVMs(t, drv, "source", "__agent-clone")
|
||||
sourceKey := driver.NewVMRef(drv.ID(), "source").Key()
|
||||
cloneKey := driver.NewVMRef(drv.ID(), "__agent-clone").Key()
|
||||
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{
|
||||
"allow_ai_access": true,
|
||||
"username": "macuser",
|
||||
"login_password": "secret-from-source",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-clone")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneKey, sourceKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password")
|
||||
if err != nil {
|
||||
t.Fatalf("clone should borrow the source password: %v", err)
|
||||
}
|
||||
if got != "secret-from-source" {
|
||||
t.Fatalf("clone secret = %q, want the source value", got)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "macuser" {
|
||||
t.Fatalf("clone SSH user = %q, want the source user", user)
|
||||
}
|
||||
|
||||
// The clone's own value wins over the source.
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{
|
||||
"allow_ai_access": true,
|
||||
"username": "cloneuser",
|
||||
"login_password": "clone-own-password",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err = app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password")
|
||||
if err != nil || got != "clone-own-password" {
|
||||
t.Fatalf("clone own secret = %q (%v), want its own value", got, err)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" {
|
||||
t.Fatalf("clone SSH user = %q, want its own value", user)
|
||||
}
|
||||
|
||||
// Clearing the clone's own password and revoking access on the source
|
||||
// removes the fallback again.
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, cloneKey, map[string]any{"login_password": ""}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := mgr.SetSettings(cloneSourceSettingPlugin, sourceKey, map[string]any{"allow_ai_access": false}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
t.Fatalf("revoked source should leave no fallback, got %v", err)
|
||||
}
|
||||
if user := app.computerUseSSHUser(mgr, cloneSourceSettingPlugin, cloneVM); user != "cloneuser" {
|
||||
t.Fatalf("clone keeps its own SSH user after source revoke, got %q", user)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneSecretWithoutSourceStaysEmpty(t *testing.T) {
|
||||
app, mgr, drv := newCloneSettingsEnv(t)
|
||||
createVMs(t, drv, "__agent-orphan")
|
||||
cloneVM, err := app.resolveVMInfo(drv.ID(), "__agent-orphan")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// A marker with no source (the lost-marker repair path) has no fallback.
|
||||
if err := writeComputerUseOwnership(cloneVM.Directory, cloneSourceSettingPlugin, cloneVM.Ref().Key(), ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := app.computerUseSecretSetting(mgr, cloneSourceSettingPlugin, cloneVM, "login_password"); !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
t.Fatalf("clone without a source should have no fallback, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretMissingMessageLocalized(t *testing.T) {
|
||||
const key = "err.computer_use.secret_missing"
|
||||
for _, loc := range []i18n.Locale{i18n.ZhCN, i18n.EnUS} {
|
||||
msg := strings.TrimSpace(i18n.M(loc, key, nil))
|
||||
if msg == "" || msg == key {
|
||||
t.Fatalf("%s %q did not resolve", loc, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,11 @@ type computerUseOwnership struct {
|
||||
Version int `json:"version"`
|
||||
PluginID string `json:"plugin_id"`
|
||||
VMKey string `json:"vm_key"`
|
||||
// SourceVM is the driver-qualified key of the VM the clone was taken from.
|
||||
// A clone has no vm settings of its own (login password, SSH user), so
|
||||
// secret and username lookups fall back to the source while it is still
|
||||
// authorized. Older markers omit it and simply have no fallback.
|
||||
SourceVM string `json:"source_vm,omitempty"`
|
||||
}
|
||||
|
||||
func (a *App) computerUseHostHandlers(mgr *plugin.Manager, pluginID string) map[string]plugin.RPCRequestHandler {
|
||||
@@ -94,8 +99,11 @@ func (a *App) handleComputerUseTypeSecret(ctx context.Context, raw json.RawMessa
|
||||
if mgr == nil {
|
||||
return nil, errors.New("plugin manager is unavailable")
|
||||
}
|
||||
secret, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), req.Setting)
|
||||
secret, err := a.computerUseSecretSetting(mgr, pluginID, vm, req.Setting)
|
||||
if err != nil {
|
||||
if errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
return nil, a.computerUseHostError("secret_missing", "err.computer_use.secret_missing", i18n.Vars{"name": vm.Name})
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
defer func() { secret = "" }()
|
||||
@@ -175,14 +183,7 @@ func (a *App) computerUseVMView(vm driver.VMInfo, mgr *plugin.Manager, pluginID
|
||||
view["capabilities"] = append([]string(nil), vm.Capabilities...)
|
||||
}
|
||||
if accessEnabled {
|
||||
username := a.GetVMSSHUser(vm.DriverID, vm.Name)
|
||||
if mgr != nil {
|
||||
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
|
||||
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||
username = strings.TrimSpace(configured)
|
||||
}
|
||||
}
|
||||
if username != "" {
|
||||
if username := a.computerUseSSHUser(mgr, pluginID, vm); username != "" {
|
||||
view["ssh_username"] = username
|
||||
}
|
||||
}
|
||||
@@ -278,7 +279,7 @@ func (a *App) handleComputerUseVMClone(ctx context.Context, raw json.RawMessage,
|
||||
return nil, err
|
||||
}
|
||||
cloneRef := cloned.Ref()
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key())
|
||||
err = persistComputerUseOwnership(cloned, pluginID, cloneRef.Key(), vm.Ref().Key())
|
||||
if err != nil {
|
||||
if cleanupErr := a.DeleteVM(vm.DriverID, cloneName, false); cleanupErr != nil {
|
||||
return nil, errors.Join(err, fmt.Errorf("clean up unregistered clone %q: %w", cloneName, cleanupErr))
|
||||
@@ -513,14 +514,15 @@ func (a *App) forgetComputerUseOwnedVM(vmKey string) {
|
||||
}
|
||||
}
|
||||
|
||||
func writeComputerUseOwnership(vmDir, pluginID, vmKey string) error {
|
||||
func writeComputerUseOwnership(vmDir, pluginID, vmKey, sourceVM string) error {
|
||||
vmDir = strings.TrimSpace(vmDir)
|
||||
pluginID = strings.TrimSpace(pluginID)
|
||||
vmKey = strings.TrimSpace(vmKey)
|
||||
sourceVM = strings.TrimSpace(sourceVM)
|
||||
if vmDir == "" || pluginID == "" || vmKey == "" {
|
||||
return errors.New("temporary VM ownership metadata is incomplete")
|
||||
}
|
||||
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey})
|
||||
data, err := json.Marshal(computerUseOwnership{Version: 1, PluginID: pluginID, VMKey: vmKey, SourceVM: sourceVM})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -612,15 +614,15 @@ func (a *App) restoreComputerUseOwnedVMs(ctx context.Context) error {
|
||||
return errors.Join(cleanupErrors...)
|
||||
}
|
||||
|
||||
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey string) error {
|
||||
func persistComputerUseOwnership(vm driver.VMInfo, pluginID, vmKey, sourceVM string) error {
|
||||
if vm.Directory == "" {
|
||||
return errors.New("temporary clone directory is unavailable")
|
||||
}
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey); err != nil {
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, vmKey, sourceVM); err != nil {
|
||||
return err
|
||||
}
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok || marker.PluginID != pluginID {
|
||||
if !ok || marker.PluginID != pluginID || marker.SourceVM != strings.TrimSpace(sourceVM) {
|
||||
return errors.New("temporary VM ownership marker could not be verified")
|
||||
}
|
||||
return nil
|
||||
@@ -647,7 +649,9 @@ func (a *App) syncComputerUseOwnership(vms []driver.VMListItem) {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
for _, pluginID := range pluginIDs {
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, key); err == nil {
|
||||
// The source VM is no longer known on this repair path (the marker
|
||||
// was lost), so write an empty source: no fallback, same as before.
|
||||
if err := writeComputerUseOwnership(vm.Directory, pluginID, key, ""); err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -685,6 +689,90 @@ func computerUseVMAccessEnabled(mgr *plugin.Manager, pluginID, vmKey string) boo
|
||||
return mgr.SavedBoolSetting(pluginID, vmKey, computerUseAccessSetting)
|
||||
}
|
||||
|
||||
// computerUseSourceVM returns the driver-qualified key of the VM a temporary
|
||||
// clone was taken from, or "" when the clone records no usable source. Only
|
||||
// MCP-owned clones carry an ownership marker, so any other VM has no fallback.
|
||||
func (a *App) computerUseSourceVM(vm driver.VMInfo) string {
|
||||
marker, ok := readComputerUseOwnership(vm)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
source := strings.TrimSpace(marker.SourceVM)
|
||||
if source == "" || source == vm.Ref().Key() {
|
||||
return ""
|
||||
}
|
||||
normalized, ok := driver.ParseVMRef(source)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return normalized.Key()
|
||||
}
|
||||
|
||||
// computerUseSecretSetting reads one secret for a VM. A temporary clone owns no
|
||||
// vm settings, so a value it does not have falls back to the source VM's copy
|
||||
// while that source still allows MCP access. The fallback reads the single
|
||||
// stored secret instead of copying it, so revoking access to the source also
|
||||
// revokes it for its clones and no secret is left behind when a clone is
|
||||
// disposed. A source that no longer exists resolves to nothing.
|
||||
func (a *App) computerUseSecretSetting(mgr *plugin.Manager, pluginID string, vm driver.VMInfo, key string) (string, error) {
|
||||
value, err := mgr.SecretSetting(pluginID, vm.Ref().Key(), key)
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
if !errors.Is(err, plugin.ErrSecretEmpty) {
|
||||
return "", err
|
||||
}
|
||||
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
|
||||
if !ok {
|
||||
return "", err
|
||||
}
|
||||
return mgr.SecretSetting(pluginID, sourceVM.Ref().Key(), key)
|
||||
}
|
||||
|
||||
// computerUseAuthorizedSource resolves a clone's source VM and confirms the
|
||||
// source still grants MCP access. It reports false when the clone has no
|
||||
// recorded source, the source is gone, or access to the source was revoked.
|
||||
func (a *App) computerUseAuthorizedSource(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) (driver.VMInfo, bool) {
|
||||
source := a.computerUseSourceVM(vm)
|
||||
if source == "" || !computerUseVMAccessEnabled(mgr, pluginID, source) {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
ref, ok := driver.ParseVMRef(source)
|
||||
if !ok {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
sourceVM, err := a.resolveVMInfo(ref.DriverID, ref.Name)
|
||||
if err != nil {
|
||||
return driver.VMInfo{}, false
|
||||
}
|
||||
return sourceVM, true
|
||||
}
|
||||
|
||||
// computerUseSSHUser resolves the SSH login name for a VM. A temporary clone
|
||||
// has neither its own settings nor a copied .reims-go-ssh-user file, so it
|
||||
// borrows the source's user while the source still allows MCP access.
|
||||
func (a *App) computerUseSSHUser(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
|
||||
if username := a.sshUserForVM(mgr, pluginID, vm); username != "" {
|
||||
return username
|
||||
}
|
||||
sourceVM, ok := a.computerUseAuthorizedSource(mgr, pluginID, vm)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return a.sshUserForVM(mgr, pluginID, sourceVM)
|
||||
}
|
||||
|
||||
func (a *App) sshUserForVM(mgr *plugin.Manager, pluginID string, vm driver.VMInfo) string {
|
||||
username := a.GetVMSSHUser(vm.DriverID, vm.Name)
|
||||
if mgr != nil {
|
||||
settings := mgr.GetSettings(pluginID, vm.Ref().Key(), false)
|
||||
if configured, ok := settings["username"].(string); ok && strings.TrimSpace(configured) != "" {
|
||||
username = strings.TrimSpace(configured)
|
||||
}
|
||||
}
|
||||
return strings.TrimSpace(username)
|
||||
}
|
||||
|
||||
// resolveComputerUseVMInfo accepts the bare VM name used by the UI and the
|
||||
// canonical driverID:name reference returned by the VM list and resource APIs.
|
||||
func (a *App) resolveComputerUseVMInfo(ref string) (driver.VMInfo, error) {
|
||||
|
||||
@@ -35,13 +35,13 @@ func TestDataRootSwitchCarriesASLRAndCleansSource(t *testing.T) {
|
||||
if _, err := a.SetFullscreenHotkey(FullscreenHotkeyConfig{Enabled: true, Hotkey: "F9"}); err != nil {
|
||||
return err
|
||||
}
|
||||
return a.SetSyncHostMemorySMBIOS(true)
|
||||
return a.SetMinimizeToTray(false)
|
||||
})
|
||||
if err != nil || calls != 1 {
|
||||
t.Fatalf("switch: calls=%d err=%v", calls, err)
|
||||
}
|
||||
stored, err := config.LoadExisting(filepath.Join(target, "reims-go.json"))
|
||||
if err != nil || !stored.QEMUASLR || !stored.SyncHostMemorySMBIOS || a.cfg.DataRoot != target {
|
||||
if err != nil || !stored.QEMUASLR || stored.MinimizeToTray == nil || *stored.MinimizeToTray || a.cfg.DataRoot != target {
|
||||
t.Fatalf("new config: %+v, %v", stored, err)
|
||||
}
|
||||
if !stored.FullscreenHotkeyEnabled || stored.FullscreenHotkey != "F9" {
|
||||
|
||||
@@ -17,6 +17,9 @@ import (
|
||||
func (a *App) openDataRoot() dataroot.Status {
|
||||
a.mu.Lock()
|
||||
dir := a.cfg.DataRoot
|
||||
explicitLaunch := a.launch.DataRoot != ""
|
||||
prevRoot := a.launchPrevDataRoot
|
||||
a.launchPrevDataRoot = ""
|
||||
a.mu.Unlock()
|
||||
st := dataroot.Open(dir, version.Version)
|
||||
a.mu.Lock()
|
||||
@@ -24,6 +27,9 @@ func (a *App) openDataRoot() dataroot.Status {
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() && explicitLaunch {
|
||||
a.relocateRegisteredVMs(dir, prevRoot)
|
||||
}
|
||||
return st
|
||||
}
|
||||
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/datamigrate"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/macos/reims"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -88,3 +91,62 @@ func TestReadOnlyFolderRefusesWrites(t *testing.T) {
|
||||
t.Fatalf("read-only folder changed: before %v, after %v", before, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetDataRoot_RelocatesMovedVMRegistry(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
base := t.TempDir()
|
||||
t.Setenv("REIMS_GO_LOCATION_FILE", filepath.Join(base, "location.json"))
|
||||
|
||||
oldRoot := filepath.Join(base, "old-root")
|
||||
newRoot := filepath.Join(base, "new-root")
|
||||
if err := (&config.Config{DataRoot: oldRoot}).EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Simulate moving the entire data folder from oldRoot to newRoot:
|
||||
// reims-go.json and vms.toml inside newRoot still reference oldRoot.
|
||||
if err := (&config.Config{DataRoot: newRoot}).EnsureDirs(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldCfg := config.Default()
|
||||
oldCfg.DataRoot = oldRoot
|
||||
if err := config.Save(filepath.Join(newRoot, "reims-go.json"), oldCfg); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
if err := os.MkdirAll(newVMDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(newVMDir, "vm.toml"), []byte("disk = \"disk.qcow2\"\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldVMDir := filepath.Join((&config.Config{DataRoot: oldRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
regDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(regDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
vmsToml := "[[vm]]\nname = 'macos-tahoe'\ndir = '" + strings.ReplaceAll(oldVMDir, "'", "''") + "'\n"
|
||||
if err := os.WriteFile(filepath.Join(regDir, "vms.toml"), []byte(vmsToml), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: oldRoot, Locale: "zh-CN"},
|
||||
root: dataroot.Open(oldRoot, version.Version),
|
||||
}
|
||||
noopASLR := func(context.Context, string, string) error { return nil }
|
||||
if err := a.setDataRoot(newRoot, noopASLR); err != nil {
|
||||
t.Fatalf("setDataRoot: %v", err)
|
||||
}
|
||||
|
||||
vms, err := reims.ListRegisteredVMs(newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 1 {
|
||||
t.Fatalf("got %d vms, want 1", len(vms))
|
||||
}
|
||||
if !strings.EqualFold(filepath.Clean(vms[0].Directory), filepath.Clean(newVMDir)) {
|
||||
t.Fatalf("vm dir = %q, want %q", vms[0].Directory, newVMDir)
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,17 @@ func (a *App) client() (*reims.Client, error) {
|
||||
return reims.NewClient(&cfg, *active), nil
|
||||
}
|
||||
|
||||
func (a *App) relocateRegisteredVMs(dataRoot, previousDataRoot string) {
|
||||
updated, err := reims.RelocateRegisteredVMs(dataRoot, previousDataRoot)
|
||||
if err != nil {
|
||||
a.emitLog("app", "Relocate VM registry paths failed: "+err.Error())
|
||||
return
|
||||
}
|
||||
if updated > 0 {
|
||||
a.emitLog("app", fmt.Sprintf("Updated %d VM registry path(s) for data folder %s", updated, dataRoot))
|
||||
}
|
||||
}
|
||||
|
||||
func enrichMacOSVMListStates(vms []driver.VMListItem) {
|
||||
for i := range vms {
|
||||
if vms[i].State == "stopped" && reims.HasSuspendState(vms[i].Dir) {
|
||||
|
||||
@@ -33,39 +33,43 @@ func (a *App) includeAlpha() bool {
|
||||
return rt.NormalizeChannel(a.cfg.RuntimeChannel) == rt.ChannelAlpha
|
||||
}
|
||||
|
||||
// remoteCache keeps the release list for a while: GitHub allows 60
|
||||
// remoteCache keeps the release list per channel for a while: GitHub allows 60
|
||||
// unauthenticated API requests an hour, and the host page, first launch and
|
||||
// the CLI all ask for it.
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
alpha bool
|
||||
list []rt.Remote
|
||||
type remoteCacheEntry struct {
|
||||
at time.Time
|
||||
list []rt.Remote
|
||||
}
|
||||
|
||||
const remoteCacheTTL = 10 * time.Minute
|
||||
var remoteCache struct {
|
||||
sync.Mutex
|
||||
entries map[bool]remoteCacheEntry
|
||||
}
|
||||
|
||||
const updateCacheTTL = 5 * time.Minute
|
||||
|
||||
// ListRemoteRuntimes lists published runtimes for the configured channel.
|
||||
func (a *App) ListRemoteRuntimes() ([]rt.Remote, error) {
|
||||
alpha := a.includeAlpha()
|
||||
remoteCache.Lock()
|
||||
defer remoteCache.Unlock()
|
||||
if remoteCache.list != nil && remoteCache.alpha == alpha && time.Since(remoteCache.at) < remoteCacheTTL {
|
||||
return remoteCache.list, nil
|
||||
if entry, ok := remoteCache.entries[alpha]; ok && entry.list != nil && time.Since(entry.at) < updateCacheTTL {
|
||||
list := entry.list
|
||||
remoteCache.Unlock()
|
||||
return list, nil
|
||||
}
|
||||
remoteCache.Unlock()
|
||||
|
||||
list, err := rt.DefaultSource().ListRemote(a.baseCtx(), alpha)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
remoteCache.at, remoteCache.alpha, remoteCache.list = time.Now(), alpha, list
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// forgetRemoteRuntimes drops the cached list (after an install or a channel change).
|
||||
func forgetRemoteRuntimes() {
|
||||
remoteCache.Lock()
|
||||
remoteCache.list = nil
|
||||
if remoteCache.entries == nil {
|
||||
remoteCache.entries = make(map[bool]remoteCacheEntry)
|
||||
}
|
||||
remoteCache.entries[alpha] = remoteCacheEntry{at: time.Now(), list: list}
|
||||
remoteCache.Unlock()
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// SetRuntimeChannel picks "stable" or "alpha" for online installs
|
||||
@@ -77,11 +81,7 @@ func (a *App) SetRuntimeChannel(channel string) error {
|
||||
default:
|
||||
return fmt.Errorf("unknown channel %q", channel)
|
||||
}
|
||||
if err := a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel }); err != nil {
|
||||
return err
|
||||
}
|
||||
forgetRemoteRuntimes()
|
||||
return nil
|
||||
return a.setPreference(func(cfg *config.Config) { cfg.RuntimeChannel = channel })
|
||||
}
|
||||
|
||||
// InstallRuntimeOnline downloads, verifies and installs a published runtime
|
||||
@@ -179,11 +179,14 @@ func percent(done, total int64) float64 {
|
||||
return float64(done) * 100 / float64(total)
|
||||
}
|
||||
|
||||
type appUpdateCacheEntry struct {
|
||||
at time.Time
|
||||
info version.UpdateInfo
|
||||
}
|
||||
|
||||
var appUpdateCache struct {
|
||||
sync.Mutex
|
||||
at time.Time
|
||||
channel string
|
||||
info *version.UpdateInfo
|
||||
entries map[string]appUpdateCacheEntry
|
||||
}
|
||||
|
||||
// SetAppUpdateChannel picks "stable", "alpha", or "dev" for Reims-Go client
|
||||
@@ -199,10 +202,6 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
if err := a.setPreference(func(cfg *config.Config) { cfg.AppUpdateChannel = channel }); err != nil {
|
||||
return err
|
||||
}
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.info = nil
|
||||
appUpdateCache.channel = ""
|
||||
appUpdateCache.Unlock()
|
||||
appUpdateReady.Lock()
|
||||
appUpdateReady.version, appUpdateReady.path, appUpdateReady.sha256 = "", "", ""
|
||||
appUpdateReady.Unlock()
|
||||
@@ -210,7 +209,8 @@ func (a *App) SetAppUpdateChannel(channel string) error {
|
||||
}
|
||||
|
||||
// CheckAppUpdate checks GitHub Releases for a newer Reims-Go version on the
|
||||
// configured app update channel. Results are cached for 10 minutes unless force is true.
|
||||
// configured app update channel. Results are cached per channel for 5 minutes
|
||||
// unless force is true.
|
||||
func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
a.mu.Lock()
|
||||
ch := version.ChannelStable
|
||||
@@ -219,19 +219,26 @@ func (a *App) CheckAppUpdate(force bool) (version.UpdateInfo, error) {
|
||||
}
|
||||
a.mu.Unlock()
|
||||
|
||||
appUpdateCache.Lock()
|
||||
defer appUpdateCache.Unlock()
|
||||
if !force && appUpdateCache.info != nil && appUpdateCache.channel == ch && time.Since(appUpdateCache.at) < remoteCacheTTL {
|
||||
return *appUpdateCache.info, nil
|
||||
if !force {
|
||||
appUpdateCache.Lock()
|
||||
if entry, ok := appUpdateCache.entries[ch]; ok && time.Since(entry.at) < updateCacheTTL {
|
||||
info := entry.info
|
||||
appUpdateCache.Unlock()
|
||||
return info, nil
|
||||
}
|
||||
appUpdateCache.Unlock()
|
||||
}
|
||||
|
||||
info, err := version.DefaultSource().CheckUpdate(a.baseCtx(), version.Version, ch)
|
||||
if err != nil {
|
||||
return info, err
|
||||
}
|
||||
copyInfo := info
|
||||
appUpdateCache.at = time.Now()
|
||||
appUpdateCache.channel = ch
|
||||
appUpdateCache.info = ©Info
|
||||
appUpdateCache.Lock()
|
||||
if appUpdateCache.entries == nil {
|
||||
appUpdateCache.entries = make(map[string]appUpdateCacheEntry)
|
||||
}
|
||||
appUpdateCache.entries[ch] = appUpdateCacheEntry{at: time.Now(), info: info}
|
||||
appUpdateCache.Unlock()
|
||||
return info, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -66,14 +66,14 @@ func TestRuntimeConfigFollowsExternalSelection(t *testing.T) {
|
||||
if got.ActiveRuntime != "backup" || !got.QEMUASLR {
|
||||
t.Fatalf("desktop reads stale selection: %+v", got)
|
||||
}
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
|
||||
if err := a.SetMinimizeToTray(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
|
||||
if saved.ActiveRuntime != "backup" || !saved.QEMUASLR || saved.MinimizeToTray == nil || *saved.MinimizeToTray {
|
||||
t.Fatalf("saving an unrelated setting lost the selection: %+v", saved)
|
||||
}
|
||||
}
|
||||
@@ -85,7 +85,7 @@ func TestPreferencesDoNotOverwriteDamagedConfig(t *testing.T) {
|
||||
if err := os.WriteFile(path, []byte("{"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err == nil {
|
||||
if err := a.SetQEMUASLR(true); err == nil {
|
||||
t.Fatal("saved preferences over an unreadable selection")
|
||||
}
|
||||
if data, err := os.ReadFile(path); err != nil || string(data) != "{" {
|
||||
@@ -100,7 +100,7 @@ func TestConfigWaitDoesNotBlockApp(t *testing.T) {
|
||||
}{
|
||||
{"ASLR", func(a *App) error { return a.SetQEMUASLR(true) }},
|
||||
{"runtime", func(a *App) error { return a.UseRuntime("backup") }},
|
||||
{"preference", func(a *App) error { return a.SetSyncHostMemorySMBIOS(true) }},
|
||||
{"preference", func(a *App) error { return a.SetMinimizeToTray(false) }},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cfg := &config.Config{DataRoot: t.TempDir()}
|
||||
@@ -129,7 +129,7 @@ func TestConfigWaitDoesNotBlockApp(t *testing.T) {
|
||||
if err := <-done; err == nil || !available {
|
||||
t.Fatalf("global lock available = %v, save error = %v", available, err)
|
||||
}
|
||||
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || a.cfg.SyncHostMemorySMBIOS {
|
||||
if a.cfg.QEMUASLR || a.cfg.ActiveRuntime != "" || (a.cfg.MinimizeToTray != nil && !*a.cfg.MinimizeToTray) {
|
||||
t.Fatalf("failed save published %+v", a.cfg)
|
||||
}
|
||||
})
|
||||
@@ -158,7 +158,7 @@ func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
|
||||
})
|
||||
}()
|
||||
synctest.Wait()
|
||||
if err := a.SetSyncHostMemorySMBIOS(true); err != nil {
|
||||
if err := a.SetMinimizeToTray(false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
close(resume)
|
||||
@@ -166,10 +166,10 @@ func TestConcurrentSelectionAndPreferenceSurvive(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(dir, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || !saved.SyncHostMemorySMBIOS {
|
||||
if err != nil || saved.ActiveRuntime != "backup" || !saved.QEMUASLR || saved.MinimizeToTray == nil || *saved.MinimizeToTray {
|
||||
t.Fatalf("concurrent updates lost: %+v, %v", saved, err)
|
||||
}
|
||||
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || !a.cfg.SyncHostMemorySMBIOS {
|
||||
if a.cfg.ActiveRuntime != saved.ActiveRuntime || !a.cfg.QEMUASLR || a.cfg.MinimizeToTray == nil || *a.cfg.MinimizeToTray {
|
||||
t.Fatalf("in-memory settings diverged: %+v", a.cfg)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -120,12 +120,17 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
}
|
||||
|
||||
cfgPath := filepath.Join(dir, "reims-go.json")
|
||||
_, existingCfgErr := os.Stat(cfgPath)
|
||||
cfg, err := config.Load(cfgPath)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read %s: %w", cfgPath, err)
|
||||
}
|
||||
recordedOldRoot := ""
|
||||
if existingCfgErr == nil {
|
||||
recordedOldRoot = cfg.DataRoot
|
||||
}
|
||||
cfg.DataRoot = dir
|
||||
if _, statErr := os.Stat(cfgPath); statErr != nil {
|
||||
if existingCfgErr != nil {
|
||||
cfg.Locale = locale // a new folder keeps the language picked on this screen
|
||||
}
|
||||
if err := cfg.EnsureDirs(); err != nil {
|
||||
@@ -149,6 +154,9 @@ func (a *App) CompleteSetup(dir string) error {
|
||||
a.syncClipboardStagingLocked()
|
||||
a.mu.Unlock()
|
||||
a.logDataRoot(st)
|
||||
if st.Writable() {
|
||||
a.relocateRegisteredVMs(dir, recordedOldRoot)
|
||||
}
|
||||
// Nothing touching the data folder ran before setup (startup), so plugins
|
||||
// start now whichever folder was chosen.
|
||||
a.resetDataRootCaches()
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/Nwflower/reims-go/internal/dataroot"
|
||||
"github.com/Nwflower/reims-go/internal/version"
|
||||
)
|
||||
|
||||
func TestAppUpdateCache_PerChannelFiveMinuteTTL(t *testing.T) {
|
||||
if updateCacheTTL != 5*time.Minute {
|
||||
t.Fatalf("updateCacheTTL = %v, want 5m", updateCacheTTL)
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
a := &App{
|
||||
cfg: &config.Config{DataRoot: dir, AppUpdateChannel: version.ChannelStable},
|
||||
root: dataroot.Status{Dir: dir},
|
||||
}
|
||||
|
||||
appUpdateCache.Lock()
|
||||
orig := appUpdateCache.entries
|
||||
appUpdateCache.entries = map[string]appUpdateCacheEntry{
|
||||
version.ChannelStable: {
|
||||
at: time.Now(),
|
||||
info: version.UpdateInfo{Channel: version.ChannelStable, Current: "v0.2.13", Latest: "v0.2.13", HasUpdate: false},
|
||||
},
|
||||
version.ChannelAlpha: {
|
||||
at: time.Now(),
|
||||
info: version.UpdateInfo{Channel: version.ChannelAlpha, Current: "v0.2.13", Latest: "v0.2.14-alpha.1", HasUpdate: true},
|
||||
},
|
||||
}
|
||||
appUpdateCache.Unlock()
|
||||
t.Cleanup(func() {
|
||||
appUpdateCache.Lock()
|
||||
appUpdateCache.entries = orig
|
||||
appUpdateCache.Unlock()
|
||||
})
|
||||
|
||||
// Stable channel returns cached result immediately.
|
||||
got, err := a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(stable): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelStable || got.HasUpdate {
|
||||
t.Fatalf("stable got = %+v, want cached no-update", got)
|
||||
}
|
||||
|
||||
// Switching to alpha must preserve per-channel cache and return cached alpha result.
|
||||
if err := a.SetAppUpdateChannel(version.ChannelAlpha); err != nil {
|
||||
t.Fatalf("SetAppUpdateChannel(alpha): %v", err)
|
||||
}
|
||||
got, err = a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(alpha): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelAlpha || !got.HasUpdate || got.Latest != "v0.2.14-alpha.1" {
|
||||
t.Fatalf("alpha got = %+v, want cached alpha update", got)
|
||||
}
|
||||
|
||||
// Switching back to stable still hits the stable cache.
|
||||
if err := a.SetAppUpdateChannel(version.ChannelStable); err != nil {
|
||||
t.Fatalf("SetAppUpdateChannel(stable): %v", err)
|
||||
}
|
||||
got, err = a.CheckAppUpdate(false)
|
||||
if err != nil {
|
||||
t.Fatalf("CheckAppUpdate(stable again): %v", err)
|
||||
}
|
||||
if got.Channel != version.ChannelStable || got.HasUpdate {
|
||||
t.Fatalf("stable again got = %+v, want cached no-update", got)
|
||||
}
|
||||
}
|
||||
@@ -27,12 +27,8 @@ type Config struct {
|
||||
AppUpdateChannel string `json:"app_update_channel,omitempty"`
|
||||
// MinimizeToTray keeps Reims-Go running in the Windows system tray when the
|
||||
// main window is closed so Guest Tools bridges stay alive. Defaults to true.
|
||||
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
|
||||
// SyncHostMemorySMBIOS overrides QEMU's default SMBIOS Type 17 memory spec
|
||||
// (2666 MHz DDR4) with the host's physical memory speed and generation so
|
||||
// macOS About This Mac reports the host's real RAM frequency. Defaults to false.
|
||||
SyncHostMemorySMBIOS bool `json:"sync_host_memory_smbios,omitempty"`
|
||||
HostDNSMode string `json:"host_dns_mode,omitempty"`
|
||||
MinimizeToTray *bool `json:"minimize_to_tray,omitempty"`
|
||||
HostDNSMode string `json:"host_dns_mode,omitempty"`
|
||||
HostDNSDoHURL string `json:"host_dns_doh_url,omitempty"`
|
||||
// EnableHypervisorSwitch unlocks the Hyper-V / WHPX boot launch switch in
|
||||
// Settings for users who alternate with exclusive-mode VMware. Off by
|
||||
|
||||
+117
-10
@@ -24,6 +24,7 @@ type VulkanDeviceProbe struct {
|
||||
DeviceType uint32 // VkPhysicalDeviceType: 1=integrated, 2=discrete, 3=virtual, 4=cpu
|
||||
APIVersion uint32
|
||||
Extensions map[string]bool
|
||||
DeviceLUID string // optional adapter LUID:nodeMask from VkPhysicalDeviceIDProperties
|
||||
}
|
||||
|
||||
var (
|
||||
@@ -200,33 +201,111 @@ func EvaluateGPUCompat(g GPUInfo, probe *VulkanDeviceProbe) GPUInfo {
|
||||
return g
|
||||
}
|
||||
|
||||
func probeRank(p VulkanDeviceProbe) (int, uint32, int) {
|
||||
reqCount := 0
|
||||
for _, ext := range RequiredVulkanExtensions {
|
||||
if p.Extensions[ext] {
|
||||
reqCount++
|
||||
}
|
||||
}
|
||||
return reqCount, p.APIVersion, len(p.Extensions)
|
||||
}
|
||||
|
||||
func betterVulkanProbe(a, b VulkanDeviceProbe) bool {
|
||||
ar, av, ae := probeRank(a)
|
||||
br, bv, be := probeRank(b)
|
||||
if ar != br {
|
||||
return ar > br
|
||||
}
|
||||
if av != bv {
|
||||
return av > bv
|
||||
}
|
||||
return ae > be
|
||||
}
|
||||
|
||||
func sameVulkanDuplicate(a, b VulkanDeviceProbe) bool {
|
||||
if a.DeviceLUID != "" && b.DeviceLUID != "" {
|
||||
return a.DeviceLUID == b.DeviceLUID
|
||||
}
|
||||
if a.DeviceLUID != "" || b.DeviceLUID != "" {
|
||||
return false
|
||||
}
|
||||
return a.VendorID != 0 && a.DeviceID != 0 &&
|
||||
a.VendorID == b.VendorID && a.DeviceID == b.DeviceID &&
|
||||
strings.EqualFold(strings.TrimSpace(a.Name), strings.TrimSpace(b.Name))
|
||||
}
|
||||
|
||||
func probeMatchesExistingGPU(p VulkanDeviceProbe, out []GPUInfo, outLUIDs []string) bool {
|
||||
pVen, pDev := "", ""
|
||||
if p.VendorID != 0 {
|
||||
pVen = fmt.Sprintf("%04x", p.VendorID)
|
||||
}
|
||||
if p.DeviceID != 0 {
|
||||
pDev = fmt.Sprintf("%04x", p.DeviceID)
|
||||
}
|
||||
pName := strings.ToLower(strings.TrimSpace(p.Name))
|
||||
for i, existing := range out {
|
||||
if p.DeviceLUID != "" && outLUIDs[i] != "" {
|
||||
if p.DeviceLUID == outLUIDs[i] {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
eVen := strings.ToLower(strings.TrimSpace(existing.VendorID))
|
||||
eDev := strings.ToLower(strings.TrimSpace(existing.DeviceID))
|
||||
if pVen != "" && pDev != "" && eVen != "" && eDev != "" {
|
||||
if pVen == eVen && pDev == eDev {
|
||||
return true
|
||||
}
|
||||
continue
|
||||
}
|
||||
if pName != "" && strings.ToLower(strings.TrimSpace(existing.Name)) == pName {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MergeRegistryAndVulkanGPUs reconciles Windows display-class registry entries
|
||||
// with live Vulkan physical devices from vulkan-1.dll, preserving ICD paths and
|
||||
// driver versions while enriching each GPU with real Vulkan 1.3 capability and
|
||||
// compatibility grades.
|
||||
func MergeRegistryAndVulkanGPUs(regGPUs []GPUInfo, vkProbes []VulkanDeviceProbe) []GPUInfo {
|
||||
used := make([]bool, len(vkProbes))
|
||||
markUsed := func(idx int) {
|
||||
used[idx] = true
|
||||
if luid := vkProbes[idx].DeviceLUID; luid != "" {
|
||||
for j := range vkProbes {
|
||||
if vkProbes[j].DeviceLUID == luid {
|
||||
used[j] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
matchProbe := func(g GPUInfo) *VulkanDeviceProbe {
|
||||
// 1. Exact PCI vendor:device match.
|
||||
if g.VendorID != "" && g.DeviceID != "" {
|
||||
wantVen := strings.ToLower(g.VendorID)
|
||||
wantDev := strings.ToLower(g.DeviceID)
|
||||
best := -1
|
||||
for i := range vkProbes {
|
||||
if used[i] {
|
||||
continue
|
||||
}
|
||||
if fmt.Sprintf("%04x", vkProbes[i].VendorID) == wantVen &&
|
||||
fmt.Sprintf("%04x", vkProbes[i].DeviceID) == wantDev {
|
||||
used[i] = true
|
||||
return &vkProbes[i]
|
||||
if best < 0 || betterVulkanProbe(vkProbes[i], vkProbes[best]) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if best >= 0 {
|
||||
markUsed(best)
|
||||
return &vkProbes[best]
|
||||
}
|
||||
}
|
||||
// 2. Case-insensitive name fallback only when PCI IDs are absent on either side;
|
||||
// never cross-match two different PCI devices that share a generic marketing name
|
||||
// (e.g. "AMD Radeon(TM) Graphics").
|
||||
lowName := strings.ToLower(strings.TrimSpace(g.Name))
|
||||
if lowName != "" {
|
||||
best := -1
|
||||
for i := range vkProbes {
|
||||
if used[i] {
|
||||
continue
|
||||
@@ -237,32 +316,60 @@ func MergeRegistryAndVulkanGPUs(regGPUs []GPUInfo, vkProbes []VulkanDeviceProbe)
|
||||
}
|
||||
pName := strings.ToLower(strings.TrimSpace(vkProbes[i].Name))
|
||||
if pName == lowName || strings.Contains(pName, lowName) || strings.Contains(lowName, pName) {
|
||||
used[i] = true
|
||||
return &vkProbes[i]
|
||||
if best < 0 || betterVulkanProbe(vkProbes[i], vkProbes[best]) {
|
||||
best = i
|
||||
}
|
||||
}
|
||||
}
|
||||
if best >= 0 {
|
||||
markUsed(best)
|
||||
return &vkProbes[best]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
out := make([]GPUInfo, 0, len(regGPUs)+len(vkProbes))
|
||||
outLUIDs := make([]string, 0, len(regGPUs)+len(vkProbes))
|
||||
for _, g := range regGPUs {
|
||||
p := matchProbe(g)
|
||||
out = append(out, EvaluateGPUCompat(g, p))
|
||||
if p != nil {
|
||||
outLUIDs = append(outLUIDs, p.DeviceLUID)
|
||||
} else {
|
||||
outLUIDs = append(outLUIDs, "")
|
||||
}
|
||||
}
|
||||
|
||||
// Include any non-CPU Vulkan GPU enumerated by vulkan-1.dll that wasn't
|
||||
// listed under the display-class registry (e.g. registered only under
|
||||
// HKLM\SOFTWARE\Khronos\Vulkan\Drivers).
|
||||
// listed under the display-class registry, skipping duplicate ICD entries
|
||||
// for a physical device already present in out while keeping distinct
|
||||
// identical-model GPUs (different DeviceLUIDs) separate.
|
||||
for i := range vkProbes {
|
||||
if used[i] || vkProbes[i].DeviceType == 4 {
|
||||
continue
|
||||
}
|
||||
p := vkProbes[i]
|
||||
if probeMatchesExistingGPU(p, out, outLUIDs) {
|
||||
continue
|
||||
}
|
||||
for j := i + 1; j < len(vkProbes); j++ {
|
||||
if used[j] || vkProbes[j].DeviceType == 4 {
|
||||
continue
|
||||
}
|
||||
if sameVulkanDuplicate(p, vkProbes[j]) {
|
||||
used[j] = true
|
||||
if betterVulkanProbe(vkProbes[j], p) {
|
||||
p = vkProbes[j]
|
||||
}
|
||||
}
|
||||
}
|
||||
base := GPUInfo{
|
||||
Name: p.Name,
|
||||
Kind: ClassifyGPU(p.Name),
|
||||
}
|
||||
out = append(out, EvaluateGPUCompat(base, &p))
|
||||
outLUIDs = append(outLUIDs, p.DeviceLUID)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -165,6 +165,72 @@ func TestGPUCompatibilityGradingAndRecommendation(t *testing.T) {
|
||||
if noCross[3].DeviceID != "13c0" || noCross[3].Compat != GPUCompatSupported || noCross[3].VulkanICD != "" {
|
||||
t.Fatalf("13c0 probe should remain separate with no stale ICD: %+v", noCross[3])
|
||||
}
|
||||
|
||||
// 11. Duplicate Vulkan ICD enumerations for the same physical GPU are deduplicated,
|
||||
// preferring the highest Vulkan version while preserving real multi-GPU setups.
|
||||
v14 := uint32((1 << 22) | (4 << 12) | 303)
|
||||
deduped := MergeRegistryAndVulkanGPUs(
|
||||
[]GPUInfo{
|
||||
{Name: "NVIDIA GeForce RTX 5070 Laptop GPU", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2d18", DriverVersion: "32.0.15.9174"},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VulkanICD: `C:\igvk64.json`, VendorID: "8086", DeviceID: "7d51", DriverVersion: "32.0.101.6554"},
|
||||
},
|
||||
[]VulkanDeviceProbe{
|
||||
{Name: "NVIDIA GeForce RTX 5070 Laptop GPU", VendorID: 0x10de, DeviceID: 0x2d18, DeviceType: 2, APIVersion: v14, Extensions: allReqExts},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VendorID: 0x8086, DeviceID: 0x7d51, DeviceType: 1, APIVersion: v13, Extensions: allReqExts},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VendorID: 0x8086, DeviceID: 0x7d51, DeviceType: 1, APIVersion: v14, Extensions: allReqExts},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VendorID: 0x8086, DeviceID: 0x7d51, DeviceType: 1, APIVersion: v14, Extensions: allReqExts},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VendorID: 0x8086, DeviceID: 0x7d51, DeviceType: 1, APIVersion: v14, Extensions: allReqExts},
|
||||
{Name: "Intel(R) Arc(TM) 140T GPU (16GB)", VendorID: 0x8086, DeviceID: 0x7d51, DeviceType: 1, APIVersion: v14, Extensions: allReqExts},
|
||||
// Duplicate Vulkan-only GPU should also appear only once.
|
||||
{Name: "AMD Radeon RX 7900 XTX", VendorID: 0x1002, DeviceID: 0x744c, DeviceType: 2, APIVersion: v13, Extensions: allReqExts},
|
||||
{Name: "AMD Radeon RX 7900 XTX", VendorID: 0x1002, DeviceID: 0x744c, DeviceType: 2, APIVersion: v14, Extensions: allReqExts},
|
||||
},
|
||||
)
|
||||
if len(deduped) != 3 {
|
||||
t.Fatalf("expected 3 deduplicated GPUs, got %d: %+v", len(deduped), deduped)
|
||||
}
|
||||
if deduped[1].DriverVersion != "32.0.101.6554" || deduped[1].VulkanVersion != "1.4.303" {
|
||||
t.Fatalf("expected Intel GPU to keep driver version and best Vulkan version, got %+v", deduped[1])
|
||||
}
|
||||
if deduped[2].DeviceID != "744c" || deduped[2].VulkanVersion != "1.4.303" {
|
||||
t.Fatalf("expected Vulkan-only duplicate to pick best version, got %+v", deduped[2])
|
||||
}
|
||||
|
||||
// Real dual identical discrete GPUs (two distinct registry adapters) must both remain.
|
||||
dualIdentical := MergeRegistryAndVulkanGPUs(
|
||||
[]GPUInfo{
|
||||
{Name: "NVIDIA GeForce RTX 4090", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2684", DriverVersion: "32.0.15.9174"},
|
||||
{Name: "NVIDIA GeForce RTX 4090", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2684", DriverVersion: "32.0.15.9174"},
|
||||
},
|
||||
[]VulkanDeviceProbe{
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v14, Extensions: allReqExts},
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v14, Extensions: allReqExts},
|
||||
},
|
||||
)
|
||||
if len(dualIdentical) != 2 {
|
||||
t.Fatalf("expected both physical identical GPUs to be kept, got %+v", dualIdentical)
|
||||
}
|
||||
|
||||
// Dual identical GPUs with distinct DeviceLUIDs must stay separate even when
|
||||
// only one (or neither) is in the display-class registry, while duplicate ICDs
|
||||
// sharing the same DeviceLUID still collapse to one entry.
|
||||
dualLUID := MergeRegistryAndVulkanGPUs(
|
||||
[]GPUInfo{
|
||||
{Name: "NVIDIA GeForce RTX 4090", VulkanICD: `C:\nv-vk64.json`, VendorID: "10de", DeviceID: "2684", DriverVersion: "32.0.15.9174"},
|
||||
},
|
||||
[]VulkanDeviceProbe{
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v13, Extensions: allReqExts, DeviceLUID: "0000000000000001:1"},
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v14, Extensions: allReqExts, DeviceLUID: "0000000000000001:1"},
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v13, Extensions: allReqExts, DeviceLUID: "0000000000000002:1"},
|
||||
{Name: "NVIDIA GeForce RTX 4090", VendorID: 0x10de, DeviceID: 0x2684, DeviceType: 2, APIVersion: v14, Extensions: allReqExts, DeviceLUID: "0000000000000002:1"},
|
||||
},
|
||||
)
|
||||
if len(dualLUID) != 2 {
|
||||
t.Fatalf("expected 2 distinct physical RTX 4090s with LUIDs, got %d: %+v", len(dualLUID), dualLUID)
|
||||
}
|
||||
if dualLUID[0].VulkanVersion != "1.4.303" || dualLUID[1].VulkanVersion != "1.4.303" {
|
||||
t.Fatalf("expected both LUID-distinct GPUs to pick best Vulkan version, got %+v", dualLUID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAffinityMaskHelpers(t *testing.T) {
|
||||
|
||||
@@ -11,13 +11,16 @@ import (
|
||||
)
|
||||
|
||||
const (
|
||||
vkSuccess = 0
|
||||
vkIncomplete = 5
|
||||
vkErrorIncompatibleDriver = -9
|
||||
vkStructureTypeAppInfo = 0
|
||||
vkStructureTypeInstCreate = 1
|
||||
vkAPIVersion10 = (1 << 22)
|
||||
vkAPIVersion13 = (1 << 22) | (3 << 12)
|
||||
vkSuccess = 0
|
||||
vkIncomplete = 5
|
||||
vkErrorIncompatibleDriver = -9
|
||||
vkStructureTypeAppInfo = 0
|
||||
vkStructureTypeInstCreate = 1
|
||||
vkStructureTypePhysicalDeviceProps2 = 1000059001
|
||||
vkStructureTypePhysicalDeviceIDProps = 1000071004
|
||||
vkAPIVersion10 = (1 << 22)
|
||||
vkAPIVersion11 = (1 << 22) | (1 << 12)
|
||||
vkAPIVersion13 = (1 << 22) | (3 << 12)
|
||||
)
|
||||
|
||||
// vkApplicationInfo matches VkApplicationInfo on x86-64 Windows (48 bytes).
|
||||
@@ -49,6 +52,18 @@ type vkExtensionProperties struct {
|
||||
SpecVersion uint32
|
||||
}
|
||||
|
||||
// vkPhysicalDeviceIDProperties matches VkPhysicalDeviceIDProperties on x86-64 Windows (64 bytes).
|
||||
type vkPhysicalDeviceIDProperties struct {
|
||||
sType uint32
|
||||
_ uint32
|
||||
pNext uintptr
|
||||
deviceUUID [16]byte
|
||||
driverUUID [16]byte
|
||||
deviceLUID [8]byte
|
||||
deviceNodeMask uint32
|
||||
deviceLUIDValid uint32
|
||||
}
|
||||
|
||||
// probeVulkanDevices loads vulkan-1.dll and enumerates all visible Vulkan
|
||||
// physical devices along with their API version, PCI IDs, device type, and
|
||||
// advertised device extensions. An empty list with no error means enumeration succeeded.
|
||||
@@ -61,12 +76,16 @@ func probeVulkanDevices() ([]VulkanDeviceProbe, error) {
|
||||
pDestroyInst := dll.NewProc("vkDestroyInstance")
|
||||
pEnumPhys := dll.NewProc("vkEnumeratePhysicalDevices")
|
||||
pGetProps := dll.NewProc("vkGetPhysicalDeviceProperties")
|
||||
pGetProps2 := dll.NewProc("vkGetPhysicalDeviceProperties2")
|
||||
pEnumExts := dll.NewProc("vkEnumerateDeviceExtensionProperties")
|
||||
for _, proc := range []*syscall.LazyProc{pCreateInst, pDestroyInst, pEnumPhys, pGetProps, pEnumExts} {
|
||||
if err := proc.Find(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if err := pGetProps2.Find(); err != nil {
|
||||
pGetProps2 = nil
|
||||
}
|
||||
|
||||
appName := append([]byte("reims-go"), 0)
|
||||
appInfo := vkApplicationInfo{
|
||||
@@ -133,13 +152,15 @@ func probeVulkanDevices() ([]VulkanDeviceProbe, error) {
|
||||
var propsBuf [2048]byte
|
||||
pGetProps.Call(pd, uintptr(unsafe.Pointer(&propsBuf[0])))
|
||||
|
||||
apiVersion := binary.LittleEndian.Uint32(propsBuf[0:4])
|
||||
probe := VulkanDeviceProbe{
|
||||
APIVersion: binary.LittleEndian.Uint32(propsBuf[0:4]),
|
||||
APIVersion: apiVersion,
|
||||
VendorID: binary.LittleEndian.Uint32(propsBuf[8:12]),
|
||||
DeviceID: binary.LittleEndian.Uint32(propsBuf[12:16]),
|
||||
DeviceType: binary.LittleEndian.Uint32(propsBuf[16:20]),
|
||||
Name: cstrFromBytes(propsBuf[20:276]),
|
||||
Extensions: probeVulkanDeviceExtensions(pEnumExts, pd),
|
||||
DeviceLUID: probeVulkanDeviceLUID(pGetProps2, pd, appInfo.apiVersion, apiVersion),
|
||||
}
|
||||
out = append(out, probe)
|
||||
}
|
||||
@@ -153,6 +174,23 @@ func vulkanResultError(call string, result int32) error {
|
||||
return fmt.Errorf("%s: VkResult %d", call, result)
|
||||
}
|
||||
|
||||
func probeVulkanDeviceLUID(pGetProps2 *syscall.LazyProc, pd uintptr, instanceAPIVersion, deviceAPIVersion uint32) string {
|
||||
if pGetProps2 == nil || instanceAPIVersion < vkAPIVersion11 || deviceAPIVersion < vkAPIVersion11 {
|
||||
return ""
|
||||
}
|
||||
idProps := vkPhysicalDeviceIDProperties{
|
||||
sType: vkStructureTypePhysicalDeviceIDProps,
|
||||
}
|
||||
var props2Buf [2048]byte
|
||||
binary.LittleEndian.PutUint32(props2Buf[0:4], vkStructureTypePhysicalDeviceProps2)
|
||||
binary.LittleEndian.PutUint64(props2Buf[8:16], uint64(uintptr(unsafe.Pointer(&idProps))))
|
||||
pGetProps2.Call(pd, uintptr(unsafe.Pointer(&props2Buf[0])))
|
||||
if idProps.deviceLUIDValid == 0 {
|
||||
return ""
|
||||
}
|
||||
return fmt.Sprintf("%x:%x", idProps.deviceLUID, idProps.deviceNodeMask)
|
||||
}
|
||||
|
||||
func probeVulkanDeviceExtensions(pEnumExts *syscall.LazyProc, pd uintptr) map[string]bool {
|
||||
var extCount uint32
|
||||
res, _, _ := pEnumExts.Call(pd, 0, uintptr(unsafe.Pointer(&extCount)), 0)
|
||||
|
||||
@@ -162,6 +162,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.computer_use.phase.recovery": "恢复模式",
|
||||
"err.computer_use.phase_confirmation": "虚拟机 {name} 处于 {phase} 阶段,操作需要先在 Reims-Go 中确认",
|
||||
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
|
||||
"err.computer_use.secret_missing": "该虚拟机未保存登录密码,无法自动输入。请在 Reims-Go 的 MCP 服务设置中填写 macOS 登录密码后重试。",
|
||||
"err.computer_use.unavailable": "虚拟机交互服务当前不可用",
|
||||
"err.computer_use.unsupported_driver": "当前虚拟机驱动不支持虚拟机交互",
|
||||
"err.computer_use.vm_not_running": "虚拟机 {name} 未运行",
|
||||
@@ -864,6 +865,7 @@ var catalog = map[Locale]map[string]string{
|
||||
"err.computer_use.phase.recovery": "Recovery mode",
|
||||
"err.computer_use.phase_confirmation": "VM {name} is in the {phase} phase and requires confirmation in Reims-Go",
|
||||
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
|
||||
"err.computer_use.secret_missing": "This VM has no saved login password, so it cannot be typed automatically. Set the macOS login password in the Reims-Go MCP Service settings and try again.",
|
||||
"err.computer_use.unavailable": "The virtual machine interaction service is currently unavailable",
|
||||
"err.computer_use.unsupported_driver": "The selected VM driver does not support computer use",
|
||||
"err.computer_use.vm_not_running": "VM {name} is not running",
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -22,6 +23,51 @@ import (
|
||||
var _ driver.CloneDriver = (*ReimsMacOSDriver)(nil)
|
||||
var _ driver.CloneResultDriver = (*ReimsMacOSDriver)(nil)
|
||||
|
||||
// portInUse reports whether a TCP port is already bound on the loopback
|
||||
// interface, so a clone picks a forward that will not collide.
|
||||
func portInUse(port int) bool {
|
||||
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if err != nil {
|
||||
return true
|
||||
}
|
||||
_ = l.Close()
|
||||
return false
|
||||
}
|
||||
|
||||
// cloneSSHPort gives a clone a host SSH forward of its own. It skips ports
|
||||
// already configured on other registered VMs (including powered-off ones) as
|
||||
// well as ports currently bound on loopback, and returns an error if no port
|
||||
// is available above sourcePort. A source without forwarding stays without one.
|
||||
func cloneSSHPort(sourcePort int, reserved map[int]bool, inUse func(int) bool) (int, error) {
|
||||
if sourcePort <= 0 {
|
||||
return 0, nil
|
||||
}
|
||||
for port := sourcePort + 1; port <= 65535; port++ {
|
||||
if reserved[port] || inUse(port) {
|
||||
continue
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
return 0, fmt.Errorf("no free SSH port available above %d", sourcePort)
|
||||
}
|
||||
|
||||
func reservedSSHPorts(ctx context.Context, c *reims.Client, registered []reims.VMListItem, excludeName string) (map[int]bool, error) {
|
||||
reserved := make(map[int]bool, len(registered))
|
||||
for _, item := range registered {
|
||||
if strings.EqualFold(item.Name, excludeName) {
|
||||
continue
|
||||
}
|
||||
det, err := c.Show(ctx, item.Name)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("inspect SSH port of registered VM %q: %w", item.Name, err)
|
||||
}
|
||||
if det.SSHPort > 0 {
|
||||
reserved[det.SSHPort] = true
|
||||
}
|
||||
}
|
||||
return reserved, nil
|
||||
}
|
||||
|
||||
func (d *ReimsMacOSDriver) CloneCoWWithInfo(ctx context.Context, sourceName, cloneName string, stdout, stderr io.Writer) (driver.VMInfo, error) {
|
||||
cloneName = strings.TrimSpace(cloneName)
|
||||
if err := d.CloneCoW(ctx, sourceName, cloneName, stdout, stderr); err != nil {
|
||||
@@ -111,6 +157,17 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
} else if !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
var clonePort int
|
||||
if src.SSHPort > 0 {
|
||||
reserved, err := reservedSSHPorts(ctx, c, registered, sourceName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
clonePort, err = cloneSSHPort(src.SSHPort, reserved, portInUse)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
env := rt.BuildChildEnv(&cfg, active)
|
||||
_, _ = fmt.Fprintf(stdout, "Creating CoW overlay for %s backed by %s...\n", cloneName, filepath.Base(srcDisk))
|
||||
if err := reims.CreateCoWOverlay(ctx, active.QemuImgPath(), env, srcDisk, overlayPath, stdout, stderr); err != nil {
|
||||
@@ -121,7 +178,7 @@ func (d *ReimsMacOSDriver) CloneCoW(ctx context.Context, sourceName, cloneName s
|
||||
if src.NetworkMode == "bridge" {
|
||||
network = true
|
||||
}
|
||||
createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &capture, Audio: &audio, Network: &network, Logs: &logs, Start: false}
|
||||
createOpts := reims.CreateOpts{Name: cloneName, SourceMode: "disk", Disk: overlayPath, DiskMode: "in-place", DiskController: src.DiskController, CPUs: src.CPUs, Memory: src.Memory, Graphics: src.Graphics, GPU: src.GPU, Resolution: src.Resolution, Displays: src.Displays, Capture: &capture, Audio: &audio, Network: &network, SSHPort: clonePort, Logs: &logs, Start: false}
|
||||
if err := c.RegisterCoWClone(ctx, createOpts, stdout, stderr); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package macosdriver
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCloneSSHPort(t *testing.T) {
|
||||
never := func(int) bool { return false }
|
||||
all := func(int) bool { return true }
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
sourcePort int
|
||||
reserved map[int]bool
|
||||
inUse func(int) bool
|
||||
want int
|
||||
wantErr bool
|
||||
}{
|
||||
{"source without forwarding stays off", 0, nil, never, 0, false},
|
||||
{"next free port after the source", 2222, nil, never, 2223, false},
|
||||
{"skips ports that are already bound", 2222, nil, func(p int) bool { return p <= 2225 }, 2226, false},
|
||||
{"skips ports reserved by stopped registered VMs", 2222, map[int]bool{2223: true, 2224: true}, never, 2225, false},
|
||||
{"skips both reserved and bound ports", 2222, map[int]bool{2223: true}, func(p int) bool { return p == 2224 }, 2225, false},
|
||||
{"returns an error when the range is exhausted", 65533, nil, all, 0, true},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := cloneSSHPort(tt.sourcePort, tt.reserved, tt.inUse)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("cloneSSHPort(%d) = %d, nil; want error", tt.sourcePort, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("cloneSSHPort(%d) unexpected error: %v", tt.sourcePort, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("cloneSSHPort(%d) = %d, want %d", tt.sourcePort, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -293,10 +293,10 @@ func AppendNestedVirtIntent(in *plugin.StartIntent, locale i18n.Locale, vmDir, u
|
||||
}
|
||||
|
||||
// prepareHostMemorySMBIOS appends `-smbios type=17,speed=...,memory_type=...`
|
||||
// when SyncHostMemorySMBIOS is enabled in app config, overriding reims-ctl's
|
||||
// hardcoded 2666 MHz DDR4 default with the host's probed RAM spec.
|
||||
func (d *ReimsMacOSDriver) prepareHostMemorySMBIOS(cfg config.Config, rep host.Report, userExtraArgs string, supportsMemType func() bool, in *plugin.StartIntent) {
|
||||
if !cfg.SyncHostMemorySMBIOS || rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 {
|
||||
// by default whenever the host's RAM spec is available, overriding reims-ctl's
|
||||
// hardcoded 2666 MHz DDR4 default unless the user supplies a manual type=17 arg.
|
||||
func (d *ReimsMacOSDriver) prepareHostMemorySMBIOS(_ config.Config, rep host.Report, userExtraArgs string, supportsMemType func() bool, in *plugin.StartIntent) {
|
||||
if rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 {
|
||||
in.ClearKeys = append(in.ClearKeys, keyHostMemorySMBIOS)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -15,18 +15,11 @@ func TestPrepareHostMemorySMBIOS(t *testing.T) {
|
||||
MemorySpec: &host.HostMemorySpec{SpeedMHz: 6400, MemoryType: 34, TypeName: "DDR5"},
|
||||
}
|
||||
|
||||
// Disabled by default: clears keyHostMemorySMBIOS.
|
||||
var inOff plugin.StartIntent
|
||||
drv.prepareHostMemorySMBIOS(config.Config{}, rep, "", func() bool { return true }, &inOff)
|
||||
if len(inOff.Args) != 0 || !slices.Contains(inOff.ClearKeys, keyHostMemorySMBIOS) {
|
||||
t.Fatalf("default off: got args=%v clear=%v", inOff.Args, inOff.ClearKeys)
|
||||
}
|
||||
|
||||
// Enabled with memory_type support: emits speed + memory_type.
|
||||
// Enabled by default with memory_type support: emits speed + memory_type.
|
||||
var inOn plugin.StartIntent
|
||||
drv.prepareHostMemorySMBIOS(config.Config{SyncHostMemorySMBIOS: true}, rep, "", func() bool { return true }, &inOn)
|
||||
drv.prepareHostMemorySMBIOS(config.Config{}, rep, "", func() bool { return true }, &inOn)
|
||||
if len(inOn.Args) != 1 || !slices.Equal(inOn.Args[0].Tokens, []string{"-smbios", "type=17,speed=6400,memory_type=34"}) {
|
||||
t.Fatalf("enabled with memory_type: got %+v", inOn.Args)
|
||||
t.Fatalf("default with memory_type: got %+v", inOn.Args)
|
||||
}
|
||||
if err := plugin.ValidateArgFragment(inOn.Args[0]); err != nil {
|
||||
t.Fatalf("ValidateArgFragment rejected fragment: %v", err)
|
||||
@@ -34,21 +27,21 @@ func TestPrepareHostMemorySMBIOS(t *testing.T) {
|
||||
|
||||
// Enabled without memory_type support: emits speed only.
|
||||
var inNoType plugin.StartIntent
|
||||
drv.prepareHostMemorySMBIOS(config.Config{SyncHostMemorySMBIOS: true}, rep, "", func() bool { return false }, &inNoType)
|
||||
drv.prepareHostMemorySMBIOS(config.Config{}, rep, "", func() bool { return false }, &inNoType)
|
||||
if len(inNoType.Args) != 1 || !slices.Equal(inNoType.Args[0].Tokens, []string{"-smbios", "type=17,speed=6400"}) {
|
||||
t.Fatalf("enabled without memory_type: got %+v", inNoType.Args)
|
||||
t.Fatalf("without memory_type: got %+v", inNoType.Args)
|
||||
}
|
||||
|
||||
// Enabled when host speed unavailable: clears key.
|
||||
// Host speed unavailable: clears key.
|
||||
var inUnknown plugin.StartIntent
|
||||
drv.prepareHostMemorySMBIOS(config.Config{SyncHostMemorySMBIOS: true}, host.Report{}, "", func() bool { return true }, &inUnknown)
|
||||
drv.prepareHostMemorySMBIOS(config.Config{}, host.Report{}, "", func() bool { return true }, &inUnknown)
|
||||
if len(inUnknown.Args) != 0 || !slices.Contains(inUnknown.ClearKeys, keyHostMemorySMBIOS) {
|
||||
t.Fatalf("unknown speed: got args=%v clear=%v", inUnknown.Args, inUnknown.ClearKeys)
|
||||
}
|
||||
|
||||
// User already supplied a manual -smbios type=17: respect it and clear ours.
|
||||
var inManual plugin.StartIntent
|
||||
drv.prepareHostMemorySMBIOS(config.Config{SyncHostMemorySMBIOS: true}, rep, "-smbios type=17,speed=5200", func() bool { return true }, &inManual)
|
||||
drv.prepareHostMemorySMBIOS(config.Config{}, rep, "-smbios type=17,speed=5200", func() bool { return true }, &inManual)
|
||||
if len(inManual.Args) != 0 || !slices.Contains(inManual.ClearKeys, keyHostMemorySMBIOS) {
|
||||
t.Fatalf("user manual type=17: got args=%v clear=%v", inManual.Args, inManual.ClearKeys)
|
||||
}
|
||||
|
||||
@@ -64,17 +64,23 @@ func SaveNetworkRecord(dir string, record NetworkRecord) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
f, err := os.CreateTemp(dir, ".reims-network-*.tmp")
|
||||
return writeFileAtomic(filepath.Join(dir, NetworkRecordFile), raw, 0o600)
|
||||
}
|
||||
|
||||
// writeFileAtomic replaces path via a same-directory temp file and rename.
|
||||
// Package reims cannot import internal/atomicfile (see archtest macosHostImports).
|
||||
func writeFileAtomic(path string, data []byte, perm os.FileMode) error {
|
||||
f, err := os.CreateTemp(filepath.Dir(path), "."+filepath.Base(path)+".*.tmp")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
tmp := f.Name()
|
||||
defer os.Remove(tmp)
|
||||
if err := f.Chmod(0o600); err != nil {
|
||||
if _, err := f.Write(data); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
if _, err := f.Write(raw); err != nil {
|
||||
if err := f.Chmod(perm); err != nil {
|
||||
_ = f.Close()
|
||||
return err
|
||||
}
|
||||
@@ -85,7 +91,7 @@ func SaveNetworkRecord(dir string, record NetworkRecord) error {
|
||||
if err := f.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.Rename(tmp, filepath.Join(dir, NetworkRecordFile))
|
||||
return os.Rename(tmp, path)
|
||||
}
|
||||
|
||||
// RemoveNetworkRecord 删除网络记录文件(不存在视为成功)。
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
@@ -16,11 +17,23 @@ import (
|
||||
// directories, without loading a runtime or changing the registry.
|
||||
// Format: reims-vgpu 3731afd, crates/reims-ctl/src/vm.rs:974-1002.
|
||||
func ListRegisteredVMs(dataRoot string) ([]driver.VMInfo, error) {
|
||||
dir, overridden := os.LookupEnv("REIMS_CTL_CONFIG_DIR")
|
||||
if !overridden {
|
||||
dir = filepath.Join((&config.Config{DataRoot: dataRoot}).XDGConfigDir(), "reims-ctl")
|
||||
return readRegisteredVMs(registryDirForDataRoot(dataRoot))
|
||||
}
|
||||
|
||||
func registryDirForDataRoot(dataRoot string) string {
|
||||
if dir := strings.TrimSpace(os.Getenv("REIMS_CTL_CONFIG_DIR")); dir != "" {
|
||||
return dir
|
||||
}
|
||||
return readRegisteredVMs(dir)
|
||||
return filepath.Join((&config.Config{DataRoot: dataRoot}).XDGConfigDir(), "reims-ctl")
|
||||
}
|
||||
|
||||
type registeredVMEntry struct {
|
||||
Name string `toml:"name"`
|
||||
Dir string `toml:"dir"`
|
||||
}
|
||||
|
||||
type registeredVMRegistry struct {
|
||||
VMs []registeredVMEntry `toml:"vm"`
|
||||
}
|
||||
|
||||
func readRegisteredVMs(dir string) ([]driver.VMInfo, error) {
|
||||
@@ -32,12 +45,7 @@ func readRegisteredVMs(dir string) ([]driver.VMInfo, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var registry struct {
|
||||
VMs []struct {
|
||||
Name string `toml:"name"`
|
||||
Dir string `toml:"dir"`
|
||||
} `toml:"vm"`
|
||||
}
|
||||
var registry registeredVMRegistry
|
||||
if err := toml.Unmarshal(raw, ®istry); err != nil {
|
||||
return nil, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
@@ -54,6 +62,151 @@ func readRegisteredVMs(dir string) ([]driver.VMInfo, error) {
|
||||
return vms, nil
|
||||
}
|
||||
|
||||
// RelocateRegisteredVMs rewrites stale absolute VM directories in reims-ctl's
|
||||
// vms.toml after a data folder has been moved to a new location.
|
||||
func RelocateRegisteredVMs(dataRoot, previousDataRoot string) (int, error) {
|
||||
return relocateRegisteredVMsInDir(registryDirForDataRoot(dataRoot), dataRoot, previousDataRoot)
|
||||
}
|
||||
|
||||
func relocateRegisteredVMsInDir(registryDir, dataRoot, previousDataRoot string) (int, error) {
|
||||
dataRoot = strings.TrimSpace(dataRoot)
|
||||
if dataRoot == "" || registryDir == "" {
|
||||
return 0, nil
|
||||
}
|
||||
dataRoot = filepath.Clean(dataRoot)
|
||||
previousDataRoot = strings.TrimSpace(previousDataRoot)
|
||||
if previousDataRoot != "" {
|
||||
previousDataRoot = filepath.Clean(previousDataRoot)
|
||||
}
|
||||
|
||||
path := filepath.Join(registryDir, "vms.toml")
|
||||
raw, err := readVMMetadata(path)
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return 0, nil
|
||||
}
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
var registry registeredVMRegistry
|
||||
if err := toml.Unmarshal(raw, ®istry); err != nil {
|
||||
return 0, fmt.Errorf("parse %s: %w", path, err)
|
||||
}
|
||||
|
||||
defaultVMsDir := filepath.Join((&config.Config{DataRoot: dataRoot}).XDGDataDir(), "reims-ctl", "vms")
|
||||
updated := 0
|
||||
for i := range registry.VMs {
|
||||
entry := ®istry.VMs[i]
|
||||
if entry.Name == "" || strings.TrimSpace(entry.Dir) == "" {
|
||||
continue
|
||||
}
|
||||
cleanDir := filepath.Clean(entry.Dir)
|
||||
nextDir, ok := relocatedVMDir(cleanDir, dataRoot, previousDataRoot, defaultVMsDir)
|
||||
if !ok || samePathString(cleanDir, nextDir) {
|
||||
continue
|
||||
}
|
||||
entry.Dir = nextDir
|
||||
updated++
|
||||
}
|
||||
if updated == 0 {
|
||||
return 0, nil
|
||||
}
|
||||
encoded, err := toml.Marshal(registry)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode %s: %w", path, err)
|
||||
}
|
||||
if err := writeFileAtomic(path, encoded, 0o644); err != nil {
|
||||
return 0, fmt.Errorf("write %s: %w", path, err)
|
||||
}
|
||||
return updated, nil
|
||||
}
|
||||
|
||||
func relocatedVMDir(cleanDir, dataRoot, previousDataRoot, defaultVMsDir string) (string, bool) {
|
||||
if previousDataRoot != "" && !samePathString(previousDataRoot, dataRoot) {
|
||||
rel, ok := relativeSubpath(previousDataRoot, cleanDir)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
candidate := filepath.Join(dataRoot, rel)
|
||||
if hasVMConfig(candidate) || (!hasVMConfig(cleanDir) && isExistingDir(candidate)) {
|
||||
return candidate, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
if hasVMConfig(cleanDir) {
|
||||
return "", false
|
||||
}
|
||||
leaf, ok := managedDefaultVMLeaf(cleanDir)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
candidate := filepath.Join(defaultVMsDir, leaf)
|
||||
if hasVMConfig(candidate) {
|
||||
return candidate, true
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// managedDefaultVMLeaf extracts the VM directory name only when cleanDir has
|
||||
// the managed default layout (<root>/data/reims-ctl/vms/<leaf>), so an
|
||||
// unmounted external or custom VM path is never mistaken for a moved default VM.
|
||||
func managedDefaultVMLeaf(cleanDir string) (string, bool) {
|
||||
leaf := strings.TrimSpace(filepath.Base(cleanDir))
|
||||
if leaf == "" || leaf == "." || leaf == ".." || leaf == string(filepath.Separator) {
|
||||
return "", false
|
||||
}
|
||||
vmsDir := filepath.Dir(cleanDir)
|
||||
ctlDir := filepath.Dir(vmsDir)
|
||||
dataDir := filepath.Dir(ctlDir)
|
||||
if !strings.EqualFold(filepath.Base(vmsDir), "vms") ||
|
||||
!strings.EqualFold(filepath.Base(ctlDir), "reims-ctl") ||
|
||||
!strings.EqualFold(filepath.Base(dataDir), "data") {
|
||||
return "", false
|
||||
}
|
||||
return leaf, true
|
||||
}
|
||||
|
||||
func relativeSubpath(root, target string) (string, bool) {
|
||||
normRoot := filepath.Clean(root)
|
||||
normTarget := filepath.Clean(target)
|
||||
if runtime.GOOS == "windows" {
|
||||
lowRoot := strings.ToLower(normRoot)
|
||||
lowTarget := strings.ToLower(normTarget)
|
||||
if lowTarget == lowRoot {
|
||||
return ".", true
|
||||
}
|
||||
prefix := lowRoot
|
||||
if !strings.HasSuffix(prefix, string(filepath.Separator)) {
|
||||
prefix += string(filepath.Separator)
|
||||
}
|
||||
if !strings.HasPrefix(lowTarget, prefix) {
|
||||
return "", false
|
||||
}
|
||||
return normTarget[len(prefix):], true
|
||||
}
|
||||
rel, err := filepath.Rel(normRoot, normTarget)
|
||||
if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {
|
||||
return "", false
|
||||
}
|
||||
return rel, true
|
||||
}
|
||||
|
||||
func samePathString(a, b string) bool {
|
||||
if runtime.GOOS == "windows" {
|
||||
return strings.EqualFold(filepath.Clean(a), filepath.Clean(b))
|
||||
}
|
||||
return filepath.Clean(a) == filepath.Clean(b)
|
||||
}
|
||||
|
||||
func hasVMConfig(dir string) bool {
|
||||
info, err := os.Stat(filepath.Join(dir, "vm.toml"))
|
||||
return err == nil && !info.IsDir()
|
||||
}
|
||||
|
||||
func isExistingDir(dir string) bool {
|
||||
info, err := os.Stat(dir)
|
||||
return err == nil && info.IsDir()
|
||||
}
|
||||
|
||||
// vmSystemDisk mirrors reims-ctl's Vm::disk, which resolves relative paths
|
||||
// against the registered VM directory.
|
||||
func vmSystemDisk(dir string) (string, error) {
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
package reims
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/Nwflower/reims-go/internal/config"
|
||||
"github.com/pelletier/go-toml/v2"
|
||||
)
|
||||
|
||||
func writeTestVMConfig(t *testing.T, dir string) {
|
||||
t.Helper()
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir %s: %v", dir, err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(dir, "vm.toml"), []byte("disk = \"disk.qcow2\"\n"), 0o644); err != nil {
|
||||
t.Fatalf("write vm.toml: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func writeTestRegistry(t *testing.T, dataRoot string, entries []registeredVMEntry) string {
|
||||
t.Helper()
|
||||
regDir := filepath.Join((&config.Config{DataRoot: dataRoot}).XDGConfigDir(), "reims-ctl")
|
||||
if err := os.MkdirAll(regDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir registry: %v", err)
|
||||
}
|
||||
raw, err := toml.Marshal(registeredVMRegistry{VMs: entries})
|
||||
if err != nil {
|
||||
t.Fatalf("marshal registry: %v", err)
|
||||
}
|
||||
path := filepath.Join(regDir, "vms.toml")
|
||||
if err := os.WriteFile(path, raw, 0o644); err != nil {
|
||||
t.Fatalf("write registry: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
func TestRelocateRegisteredVMs_WithPreviousRootAndExternalVM(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
base := t.TempDir()
|
||||
oldRoot := filepath.Join(base, "old-data")
|
||||
newRoot := filepath.Join(base, "new-data")
|
||||
externalDir := filepath.Join(base, "external-vm")
|
||||
|
||||
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
writeTestVMConfig(t, newVMDir)
|
||||
writeTestVMConfig(t, externalDir)
|
||||
|
||||
oldVMDir := filepath.Join((&config.Config{DataRoot: oldRoot}).XDGDataDir(), "reims-ctl", "vms", "macos-tahoe")
|
||||
writeTestRegistry(t, newRoot, []registeredVMEntry{
|
||||
{Name: "macos-tahoe", Dir: oldVMDir},
|
||||
{Name: "external", Dir: externalDir},
|
||||
})
|
||||
|
||||
updated, err := RelocateRegisteredVMs(newRoot, oldRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("RelocateRegisteredVMs: %v", err)
|
||||
}
|
||||
if updated != 1 {
|
||||
t.Fatalf("updated = %d, want 1", updated)
|
||||
}
|
||||
|
||||
vms, err := ListRegisteredVMs(newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 2 {
|
||||
t.Fatalf("got %d vms, want 2", len(vms))
|
||||
}
|
||||
if !samePathString(vms[0].Directory, newVMDir) {
|
||||
t.Fatalf("relocated dir = %q, want %q", vms[0].Directory, newVMDir)
|
||||
}
|
||||
if !samePathString(vms[1].Directory, externalDir) {
|
||||
t.Fatalf("external dir = %q, want %q", vms[1].Directory, externalDir)
|
||||
}
|
||||
|
||||
// Second call must be a no-op.
|
||||
updated, err = RelocateRegisteredVMs(newRoot, oldRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("second RelocateRegisteredVMs: %v", err)
|
||||
}
|
||||
if updated != 0 {
|
||||
t.Fatalf("second updated = %d, want 0", updated)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelocateRegisteredVMs_FallbackWithoutPreviousRoot(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
base := t.TempDir()
|
||||
missingOldRoot := filepath.Join(base, "gone-data")
|
||||
newRoot := filepath.Join(base, "moved-data")
|
||||
|
||||
newVMDir := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "mac-dev")
|
||||
writeTestVMConfig(t, newVMDir)
|
||||
|
||||
oldVMDir := filepath.Join((&config.Config{DataRoot: missingOldRoot}).XDGDataDir(), "reims-ctl", "vms", "mac-dev")
|
||||
writeTestRegistry(t, newRoot, []registeredVMEntry{
|
||||
{Name: "mac-dev", Dir: oldVMDir},
|
||||
})
|
||||
|
||||
updated, err := RelocateRegisteredVMs(newRoot, "")
|
||||
if err != nil {
|
||||
t.Fatalf("RelocateRegisteredVMs: %v", err)
|
||||
}
|
||||
if updated != 1 {
|
||||
t.Fatalf("updated = %d, want 1", updated)
|
||||
}
|
||||
|
||||
vms, err := ListRegisteredVMs(newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 1 || !samePathString(vms[0].Directory, newVMDir) {
|
||||
t.Fatalf("vms = %+v, want dir %q", vms, newVMDir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRelocateRegisteredVMs_PreservesUnmountedExternalVM(t *testing.T) {
|
||||
t.Setenv("REIMS_CTL_CONFIG_DIR", "")
|
||||
base := t.TempDir()
|
||||
oldRoot := filepath.Join(base, "old-data")
|
||||
newRoot := filepath.Join(base, "new-data")
|
||||
|
||||
// A leftover default VM folder shares the same name as an unmounted external VM.
|
||||
leftoverDefault := filepath.Join((&config.Config{DataRoot: newRoot}).XDGDataDir(), "reims-ctl", "vms", "work-mac")
|
||||
writeTestVMConfig(t, leftoverDefault)
|
||||
|
||||
unmountedExternal := filepath.Join(base, "offline-drive", "work-mac")
|
||||
writeTestRegistry(t, newRoot, []registeredVMEntry{
|
||||
{Name: "work-mac", Dir: unmountedExternal},
|
||||
})
|
||||
|
||||
for _, prev := range []string{oldRoot, ""} {
|
||||
updated, err := RelocateRegisteredVMs(newRoot, prev)
|
||||
if err != nil {
|
||||
t.Fatalf("RelocateRegisteredVMs(prev=%q): %v", prev, err)
|
||||
}
|
||||
if updated != 0 {
|
||||
t.Fatalf("RelocateRegisteredVMs(prev=%q) updated = %d, want 0", prev, updated)
|
||||
}
|
||||
vms, err := ListRegisteredVMs(newRoot)
|
||||
if err != nil {
|
||||
t.Fatalf("ListRegisteredVMs: %v", err)
|
||||
}
|
||||
if len(vms) != 1 || !samePathString(vms[0].Directory, unmountedExternal) {
|
||||
t.Fatalf("prev=%q overwrote external VM dir: got %+v, want %q", prev, vms, unmountedExternal)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -97,7 +97,7 @@ func (p *Prep) Prepare(ctx context.Context, name string, rep host.Report, cur *r
|
||||
}
|
||||
|
||||
func (p *Prep) syncHostMemorySMBIOS(ctx context.Context, name string, rep host.Report, cur *reims.VMDetail) {
|
||||
if !p.cfg.SyncHostMemorySMBIOS || rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 {
|
||||
if rep.MemorySpec == nil || rep.MemorySpec.SpeedMHz <= 0 {
|
||||
return
|
||||
}
|
||||
if reims.HasSMBIOSType17Arg(cur.ExtraArgs) {
|
||||
|
||||
@@ -1153,7 +1153,7 @@ func (m *Manager) SecretSetting(pluginID, vmName, key string) (string, error) {
|
||||
text, _ := values[key].(string)
|
||||
m.mu.RUnlock()
|
||||
if text == "" {
|
||||
return "", errors.New("secret setting is empty")
|
||||
return "", ErrSecretEmpty
|
||||
}
|
||||
if strings.HasPrefix(text, protectedSecretPrefix) {
|
||||
return unprotectSettingSecret(text)
|
||||
|
||||
@@ -39,7 +39,7 @@ const (
|
||||
// primary GitHub raw endpoint is unreachable or blocked.
|
||||
DefaultMarketMirrorURL = "https://cdn.jsdelivr.net/gh/reims-go/plugins@dist/index.json"
|
||||
|
||||
defaultMarketCacheTTL = 10 * time.Minute
|
||||
defaultMarketCacheTTL = 5 * time.Minute
|
||||
defaultMarketStallTimeout = 45 * time.Second
|
||||
maxMarketIndexBytes = 4 << 20 // 4 MiB ceiling for lightweight index.json
|
||||
)
|
||||
|
||||
@@ -10,6 +10,11 @@ const protectedSecretPrefix = "dpapi:v1:"
|
||||
|
||||
var ErrSecretNotProtected = errors.New("stored secret is not protected")
|
||||
|
||||
// ErrSecretEmpty marks a secret setting that was never saved for the requested
|
||||
// scope. Callers that may fall back to another VM (a temporary clone reading
|
||||
// its source) match it with errors.Is instead of comparing text.
|
||||
var ErrSecretEmpty = errors.New("secret setting is empty")
|
||||
|
||||
func protectSettingSecret(value string) (string, error) {
|
||||
if value == "" || strings.HasPrefix(value, protectedSecretPrefix) {
|
||||
return value, nil
|
||||
|
||||
@@ -102,7 +102,7 @@ func TestSelectionRevalidatesAfterConsent(t *testing.T) {
|
||||
paths = append(paths, path)
|
||||
if len(paths) == 1 {
|
||||
prefs := cfg
|
||||
prefs.SyncHostMemorySMBIOS = true
|
||||
prefs.AutoPinPCores = false
|
||||
if err := SavePreferences(&prefs); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestSelectionRevalidatesAfterConsent(t *testing.T) {
|
||||
t.Fatalf("removed during consent: paths = %q, err = %v", paths, err)
|
||||
}
|
||||
saved, err := config.LoadExisting(filepath.Join(cfg.DataRoot, "reims-go.json"))
|
||||
if err != nil || saved.ActiveRuntime != "old" || !saved.SyncHostMemorySMBIOS {
|
||||
if err != nil || saved.ActiveRuntime != "old" || saved.AutoPinPCores {
|
||||
t.Fatalf("lost settings while awaiting consent: %+v, %v", saved, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -309,6 +309,7 @@
|
||||
"err.computer_use.phase.recovery": "Recovery mode",
|
||||
"err.computer_use.access_disabled": "MCP access to VM {name} is disabled in plugin settings",
|
||||
"err.computer_use.not_owned": "VM {name} is not an MCP-created temporary clone",
|
||||
"err.computer_use.secret_missing": "This VM has no saved login password, so it cannot be typed automatically. Set the macOS login password in the Reims-Go MCP Service settings and try again.",
|
||||
"err.computer_use.restore_confirmation": "Confirm in Reims-Go before restoring a snapshot for VM {name}",
|
||||
"err.fullscreen_vmware_svga": "Press Ctrl+Alt+F in the QEMU window for {name} to toggle full screen",
|
||||
"err.app_window_unavailable": "Separate app windows require a macOS VM running on Windows",
|
||||
|
||||
@@ -95,9 +95,6 @@
|
||||
"updateFailedSub": "Download or verification failed; try again",
|
||||
"aboutTagline": "Run a GPU-accelerated macOS virtual machine on Windows — prebuilt, ready out of the box.",
|
||||
"aboutCommunity": "Community & support",
|
||||
"aboutWebsiteSub": "Downloads, docs, plugin market and compatibility list on reims.dev",
|
||||
"aboutProjectSub": "Source code and releases on GitHub",
|
||||
"aboutIssueSub": "Report a problem or suggest a feature on GitHub",
|
||||
"aboutLicensesTitle": "Open-source licenses",
|
||||
"aboutLicensesSub": "Apache-2.0 license and third-party notices (available offline)",
|
||||
"aboutLicensesView": "View",
|
||||
@@ -115,7 +112,7 @@
|
||||
"welcomeSub": "Pick an installer, assign cores and GPU, and launch in minutes",
|
||||
"back": "Back",
|
||||
"next": "Next",
|
||||
"choose": "Browse…",
|
||||
"choose": "Choose…",
|
||||
"hostRuntime": "Runtime",
|
||||
"qemuASLR": "Automatically enable ASLR for QEMU",
|
||||
"qemuASLRHint": "Applies to the selected runtime and may restore blank macOS Dock icons after you shut down and start the VM again",
|
||||
@@ -136,11 +133,9 @@
|
||||
"appCheckUpdate": "Check for updates",
|
||||
"appUpdateLookupFailed": "Couldn’t check GitHub for updates",
|
||||
"aboutDiscord": "Discord community",
|
||||
"aboutDiscordSub": "Chat with users, share hardware compatibility, test alphas and build plugins",
|
||||
"aboutCopyDiscord": "Copy invite link",
|
||||
"aboutJoinDiscord": "Join server",
|
||||
"aboutQQGroup": "QQ Group",
|
||||
"aboutQQGroupSub": "Launch QQ directly to join for community support and feedback",
|
||||
"aboutQQNotInstalled": "QQ not installed",
|
||||
"aboutQQNotInstalledSub": "Local QQ wasn’t detected — copy the group ID to join manually",
|
||||
"aboutQQLaunchFailed": "Couldn’t launch QQ — copy the group ID to join manually",
|
||||
@@ -444,9 +439,6 @@
|
||||
"smbiosCheckHint": "Tip: check the serial at checkcoverage.apple.com and verify it reports invalid (not registered to a real Mac) before writing.",
|
||||
"smbiosStopRequired": "Shut down the VM completely first (not running or suspended)",
|
||||
"smbiosLoadFailed": "Could not read OpenCore SMBIOS",
|
||||
"syncHostMemorySMBIOS": "Sync host memory specs",
|
||||
"syncHostMemorySMBIOSSub": "Show the host's actual memory speed and generation ({spec}) in macOS About This Mac; applies on next start",
|
||||
"syncHostMemorySMBIOSUnavailable": "Could not read host SMBIOS memory speed; VMs keep the default 2666 MHz DDR4",
|
||||
"targetDisplayTitle": "Launch display",
|
||||
"targetDisplayPrimaryDefault": "Primary display (default)",
|
||||
"targetDisplayNumbered": "Display {n}",
|
||||
|
||||
@@ -309,6 +309,7 @@
|
||||
"err.computer_use.phase.recovery": "恢复模式",
|
||||
"err.computer_use.access_disabled": "MCP 插件在设置中无权访问虚拟机 {name}",
|
||||
"err.computer_use.not_owned": "虚拟机 {name} 不是 MCP 创建的临时克隆",
|
||||
"err.computer_use.secret_missing": "该虚拟机未保存登录密码,无法自动输入。请在 Reims-Go 的 MCP 服务设置中填写 macOS 登录密码后重试。",
|
||||
"err.computer_use.restore_confirmation": "在 Reims-Go 中确认后才能还原虚拟机 {name} 的快照",
|
||||
"err.fullscreen_vmware_svga": "在 {name} 的 QEMU 窗口中按 Ctrl+Alt+F 切换全屏",
|
||||
"err.app_window_unavailable": "独立窗口仅支持 Windows 上运行的 macOS 虚拟机",
|
||||
|
||||
@@ -95,9 +95,6 @@
|
||||
"updateFailedSub": "下载或校验失败,可以重试",
|
||||
"aboutTagline": "在 Windows 上开一台带 GPU 加速的 macOS 虚拟机——免编译,开箱即用。",
|
||||
"aboutCommunity": "社区与支持",
|
||||
"aboutWebsiteSub": "reims.dev 上的下载、使用文档、插件市场与兼容性列表",
|
||||
"aboutProjectSub": "GitHub 上的源码与发布版本",
|
||||
"aboutIssueSub": "遇到问题或有功能建议,在 GitHub 提交 Issue",
|
||||
"aboutLicensesTitle": "开源许可与声明",
|
||||
"aboutLicensesSub": "Apache-2.0 协议与第三方开源组件声明(离线可查)",
|
||||
"aboutLicensesView": "查看",
|
||||
@@ -115,7 +112,7 @@
|
||||
"welcomeSub": "选择系统来源、分配核数与显卡,几步完成配置",
|
||||
"back": "上一步",
|
||||
"next": "下一步",
|
||||
"choose": "浏览…",
|
||||
"choose": "选择…",
|
||||
"hostRuntime": "运行时",
|
||||
"qemuASLR": "自动为 QEMU 启用 ASLR",
|
||||
"qemuASLRHint": "设置随运行时版本切换,虚拟机关机后再启动时生效,可能解决 macOS Dock 图标空白的问题",
|
||||
@@ -125,22 +122,20 @@
|
||||
"appVersionTitle": "客户端版本",
|
||||
"appUpToDate": "已是最新",
|
||||
"appUpdateAvailable": "发现新版本 {v}(稳定版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(Alpha 测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(Dev 滚动版)",
|
||||
"appUpdateAvailableAlpha": "发现新版本 {v}(测试版)",
|
||||
"appUpdateAvailableDev": "发现新版本 {v}(开发版)",
|
||||
"appUpdateChannelTitle": "更新通道",
|
||||
"appUpdateChannelSubStable": "仅接收经过验证的正式稳定版本",
|
||||
"appUpdateChannelSubKeepOld": "接收 {channel} 预发布版本;启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelSubKeepOld": "接收{channel};启动时不删除旧版程序与已下载安装包,方便随时回退",
|
||||
"appUpdateChannelStable": "稳定版",
|
||||
"appUpdateChannelAlpha": "Alpha",
|
||||
"appUpdateChannelDev": "Dev",
|
||||
"appUpdateChannelAlpha": "测试版",
|
||||
"appUpdateChannelDev": "开发版",
|
||||
"appCheckUpdate": "检查更新",
|
||||
"appUpdateLookupFailed": "暂时无法连接 GitHub 检查更新",
|
||||
"aboutDiscord": "Discord 社区",
|
||||
"aboutDiscordSub": "交流使用体验、硬件兼容反馈、Alpha 测试与插件开发",
|
||||
"aboutCopyDiscord": "复制邀请链接",
|
||||
"aboutJoinDiscord": "加入服务器",
|
||||
"aboutQQGroup": "QQ 交流群",
|
||||
"aboutQQGroupSub": "点击直接拉起 QQ 加群,交流使用与问题反馈",
|
||||
"aboutQQNotInstalled": "未安装 QQ",
|
||||
"aboutQQNotInstalledSub": "未检测到本地 QQ,可复制群号手动搜索加入",
|
||||
"aboutQQLaunchFailed": "未能拉起 QQ,可复制群号手动搜索加入",
|
||||
@@ -444,9 +439,6 @@
|
||||
"smbiosCheckHint": "建议将序列号复制到 checkcoverage.apple.com 确认显示「无效序列号」(未被真机占用)后再写入。",
|
||||
"smbiosStopRequired": "请先彻底关机(不能处于运行或休眠状态)",
|
||||
"smbiosLoadFailed": "无法读取 OpenCore 设备码",
|
||||
"syncHostMemorySMBIOS": "同步宿主机内存规格",
|
||||
"syncHostMemorySMBIOSSub": "在 macOS「关于本机」中显示宿主机真实内存频率与代数(当前:{spec}),下次启动生效",
|
||||
"syncHostMemorySMBIOSUnavailable": "未能从宿主机 SMBIOS 读取物理内存频率,虚拟机将保持默认的 2666 MHz DDR4",
|
||||
"targetDisplayTitle": "启动显示器",
|
||||
"targetDisplayPrimaryDefault": "主显示器(默认)",
|
||||
"targetDisplayNumbered": "显示器 {n}",
|
||||
|
||||
Reference in new issue
Block a user