feat(extensions): add ZIP installation and unify action dialogs

This commit is contained in:
2026-09-06 00:52:59 +08:00
parent ba66b182af
commit 99a92e9eb1
29 changed files with 554 additions and 50 deletions
@@ -0,0 +1,53 @@
// @vitest-environment happy-dom
import { defineComponent } from 'vue'
import { flushPromises, mount } from '@vue/test-utils'
import { afterEach, expect, it, vi } from 'vitest'
import ActionDialog from './ActionDialog.vue'
import { useActionDialog } from '@/composables/useActionDialog'
let wrapper: ReturnType<typeof mount>
afterEach(() => wrapper?.unmount())
function setup() {
let api!: ReturnType<typeof useActionDialog>
wrapper = mount(defineComponent({
components: { ActionDialog },
setup() { api = useActionDialog(); return api },
template: '<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />',
}), { attachTo: document.body })
return api
}
it('requires explicit confirmation and treats Escape as cancellation', async () => {
const api = setup()
const action = vi.fn()
const result = api.askConfirm('删除所有配置?').then(ok => { if (ok) action() })
await flushPromises()
expect(document.activeElement?.textContent).toBe('取消')
await wrapper.get('dialog').trigger('cancel')
await result
expect(action).not.toHaveBeenCalled()
const confirmed = api.askConfirm('继续?')
await flushPromises()
await wrapper.get('form').trigger('submit')
expect(await confirmed).toBe(true)
})
it('preserves the default input and distinguishes empty submission from cancel', async () => {
const api = setup()
const input = api.askPrompt('新名称', '旧名称')
await flushPromises()
expect((wrapper.get('input').element as HTMLInputElement).value).toBe('旧名称')
await wrapper.get('input').setValue('')
await wrapper.get('form').trigger('submit')
expect(await input).toBe('')
const cancelled = api.askPrompt('名称')
await flushPromises()
await wrapper.get('button[type="button"]').trigger('click')
expect(await cancelled).toBeNull()
})
it('cancels duplicate requests and pending operations when their view unmounts', async () => {
const api = setup()
const first = api.askConfirm('继续?')
expect(await api.askConfirm('重复')).toBe(false)
wrapper.unmount()
expect(await first).toBe(false)
expect(await api.askPrompt('已离开')).toBeNull()
})
@@ -0,0 +1,32 @@
<script setup lang="ts">
import { ref } from 'vue'
import AppDialog from './AppDialog.vue'
import type { ActionDialogRequest } from '@/composables/useActionDialog'
import { t } from '@/i18n'
const props = defineProps<ActionDialogRequest>()
const emit = defineEmits<{ resolve: [value: string | null] }>()
const value = ref(props.initialValue)
</script>
<template>
<AppDialog :label="mode === 'confirm' ? t('确认操作', 'Confirm action') : message" @close="emit('resolve', null)">
<form class="modal action-dialog" @submit.prevent="emit('resolve', mode === 'prompt' ? value : '')">
<span class="badge info">{{ mode === 'confirm' ? t('操作确认', 'Confirmation') : t('填写信息', 'Enter information') }}</span>
<h2>{{ mode === 'confirm' ? t('确认操作', 'Confirm action') : t('请输入', 'Enter a value') }}</h2>
<label v-if="mode === 'prompt'" class="action-field"><span>{{ message }}</span><input v-model="value" class="input" autofocus /></label>
<p v-else class="action-message">{{ message }}</p>
<footer>
<button type="button" class="button-secondary" :autofocus="mode === 'confirm'" @click="emit('resolve', null)">{{ t('取消', 'Cancel') }}</button>
<button type="submit" class="button-primary">{{ t('确定', 'Confirm') }}</button>
</footer>
</form>
</AppDialog>
</template>
<style scoped>
.action-dialog { width: min(520px, 100%); }
h2 { margin: var(--space-sm) 0 var(--space-lg); }
.action-field { display: grid; gap: var(--space-md); }
.action-message, .action-field span { white-space: pre-wrap; overflow-wrap: anywhere; line-height: var(--line-height-relaxed); }
footer { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: var(--space-sm); margin-top: var(--space-xl); }
</style>
@@ -1,5 +1,5 @@
// @vitest-environment happy-dom
import { afterEach, expect, it } from 'vitest'
import { afterEach, expect, it, vi } from 'vitest'
import { mount, type VueWrapper } from '@vue/test-utils'
import AppDialog from './AppDialog.vue'
const mounted: VueWrapper[] = []
@@ -34,3 +34,17 @@ it('does not dismiss permission or busy dialogs through Escape or backdrop', asy
await w.get('dialog').trigger('click')
expect(w.emitted('close')).toBeUndefined()
})
it('cycles Tab between the first and last visible controls', async () => {
const w = mount(AppDialog, {props:{label:'键盘'}, slots:{default:'<section class="modal"><input /><button>取消</button><button disabled>禁用</button></section>'},attachTo:document.body}); mounted.push(w)
const input = w.get('input').element
const button = w.get('button').element
const rects = [new DOMRect(0, 0, 50, 30)] as unknown as DOMRectList
const spies = [input, button].map(element => vi.spyOn(element, 'getClientRects').mockReturnValue(rects))
input.focus()
await w.get('dialog').trigger('keydown', {key:'Tab', shiftKey:true})
expect(document.activeElement).toBe(button)
await w.get('dialog').trigger('keydown', {key:'Tab'})
expect(document.activeElement).toBe(input)
spies.forEach(spy => spy.mockRestore())
})
@@ -9,6 +9,18 @@ let previousFocus: HTMLElement | null = null
function dismiss() { if (props.dismissible) emit('close') }
function keydown(event: KeyboardEvent) {
if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); dismiss() }
if (event.key === 'Tab' && dialog.value) {
const items = Array.from(dialog.value.querySelectorAll<HTMLElement>('button:not(:disabled), input:not(:disabled):not([type="hidden"]), textarea:not(:disabled), select:not(:disabled), a[href], [tabindex]'))
.filter(element => element.tabIndex >= 0 && element.getClientRects().length > 0)
const first = items[0]
const last = items.at(-1)
if (!first) { event.preventDefault(); dialog.value.focus(); return }
if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog.value)) {
event.preventDefault(); last?.focus()
} else if (!event.shiftKey && document.activeElement === last) {
event.preventDefault(); first.focus()
}
}
}
onMounted(() => {
previousFocus = document.activeElement as HTMLElement | null
@@ -1,4 +1,8 @@
<script setup lang="ts">
import AppDialog from './AppDialog.vue'
import ActionDialog from '@/components/common/ActionDialog.vue'
import { useActionDialog } from '@/composables/useActionDialog'
const { actionDialog, resolveAction, askPrompt } = useActionDialog()
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useEditorStore } from '@/stores/editor'
@@ -79,6 +83,7 @@ function hide() { open.value = false }
async function execute(command: Command | undefined) {
if (!command) return
hide()
await nextTick()
try {
await command.run()
} catch (error) {
@@ -87,7 +92,7 @@ async function execute(command: Command | undefined) {
}
async function createNote() {
const rawName = window.prompt(t('笔记名称', 'Note name'))?.trim()
const rawName = (await askPrompt(t('笔记名称', 'Note name')))?.trim()
if (!rawName) return
const name = rawName.endsWith('.md') ? rawName : `${rawName}.md`
const file = await workspaceService.createFile('/', name, `# ${rawName}\n\n`)
@@ -148,6 +153,7 @@ async function applyPluginEffect(effect: PluginCommandEffect) {
function handleKeydown(event: KeyboardEvent) {
if ((event.ctrlKey || event.metaKey) && event.key.toLocaleLowerCase() === 'p') {
if (!open.value && document.querySelector('dialog[open]')) return
event.preventDefault()
open.value ? hide() : show()
} else if (event.key === 'Escape' && open.value) {
@@ -160,12 +166,13 @@ onBeforeUnmount(() => window.removeEventListener('keydown', handleKeydown))
</script>
<template>
<ActionDialog v-if="actionDialog" v-bind="actionDialog" @resolve="resolveAction" />
<div v-if="commandNotice" class="command-toast" role="status">
<span>{{ commandNotice }}</span><button :aria-label="t('关闭通知', 'Close notification')" @click="commandNotice = ''">×</button>
</div>
<Teleport to="body">
<div v-if="open" class="command-backdrop" @click.self="hide">
<section class="command-palette" role="dialog" aria-modal="true" :aria-label="t('命令面板', 'Command palette')">
<AppDialog v-if="open" :label="t('命令面板', 'Command palette')" @close="hide">
<section class="modal command-palette">
<input ref="input" v-model="query" class="command-input" :placeholder="t('输入命令…', 'Enter a command…')" @keydown.enter.prevent="execute(filteredCommands[0])" />
<p v-if="commandError" class="command-error">{{ commandError }}</p>
<div class="command-list">
@@ -176,15 +183,14 @@ onBeforeUnmount(() => window.removeEventListener('keydown', handleKeydown))
</div>
<footer><span>Enter · {{ t('执行', 'Run') }}</span><span>Esc · {{ t('关闭', 'Close') }}</span></footer>
</section>
</div>
</AppDialog>
</Teleport>
</template>
<style scoped>
.command-backdrop { position: fixed; inset: 0; z-index: var(--z-modal); display: flex; justify-content: center; align-items: flex-start; padding-top: 12vh; background: var(--color-background-overlay); animation: command-backdrop-in var(--motion-fast) both; }
.command-palette { width: min(620px, calc(100vw - 32px)); overflow: hidden; border: 1px solid var(--color-border-default); border-radius: var(--radius-xl); background: var(--color-surface-elevated); box-shadow: var(--shadow-xl); animation: command-palette-in var(--motion-normal) both; }
.command-palette { padding: 0; display: flex; flex-direction: column; width: min(620px, calc(100vw - 32px)); overflow: hidden; border: 1px solid var(--color-border-default); border-radius: var(--radius-xl); background: var(--color-surface-elevated); box-shadow: var(--shadow-xl); animation: command-palette-in var(--motion-normal) both; }
.command-input { width: 100%; padding: var(--space-xl); border: 0; border-bottom: 1px solid var(--color-border-default); outline: 0; background: transparent; color: var(--color-text-primary); font-size: var(--font-size-xl); }
.command-list { max-height: 360px; overflow: auto; padding: var(--space-sm); }
.command-list { min-height: 0; max-height: 360px; overflow: auto; padding: var(--space-sm); }
.command-list button { display: flex; justify-content: space-between; width: 100%; padding: var(--space-md) var(--space-lg); border-radius: var(--radius-md); text-align: left; transition: color var(--motion-fast), background-color var(--motion-fast), transform var(--motion-fast); }
.command-list button:hover, .command-list button:focus { outline: 0; background: var(--color-accent-soft); color: var(--color-accent-primary); }
.command-list button:hover { transform: translateX(2px); }
@@ -6,12 +6,39 @@ import ExtensionInstallDialog from './ExtensionInstallDialog.vue'
let wrapper: VueWrapper
afterEach(() => { wrapper?.unmount() })
it.each(['Skill', 'Plugin'] as const)('uploads a selected %s ZIP only on confirmation', async kind => {
const install = vi.fn().mockResolvedValue(undefined)
wrapper = mount(ExtensionInstallDialog, { props: { kind, install } })
const file = new File(['zip fixture'], 'package.zip', {type:'application/zip'})
Object.defineProperty(wrapper.get('input[type="file"]').element, 'files', {value:[file], configurable:true})
await wrapper.get('input[type="file"]').trigger('change')
expect(wrapper.text()).toContain('package.zip')
expect(install).not.toHaveBeenCalled()
await wrapper.get('form').trigger('submit')
await flushPromises()
expect(install).toHaveBeenCalledExactlyOnceWith(file)
expect(wrapper.emitted('installed')).toHaveLength(1)
})
it('rejects oversized ZIP files before upload', async () => {
const install = vi.fn()
wrapper = mount(ExtensionInstallDialog, {props:{kind:'Skill',install}})
const file = new File(['zip'], 'large.zip')
Object.defineProperty(file, 'size', {value:10 * 1024 * 1024 + 1})
Object.defineProperty(wrapper.get('input[type="file"]').element, 'files', {value:[file]})
await wrapper.get('input[type="file"]').trigger('change')
expect(wrapper.get('[role="alert"]').text()).toContain('10 MiB')
await wrapper.get('form').trigger('submit')
expect(install).not.toHaveBeenCalled()
})
it.each(['Skill', 'Plugin'] as const)('installs %s from a trimmed directory and prevents duplicate submissions', async kind => {
let complete!: () => void
const install = vi.fn(() => new Promise<void>(resolve => { complete = resolve }))
wrapper = mount(ExtensionInstallDialog, { props: { kind, install } })
expect(wrapper.text()).toContain(`${kind.toLowerCase()}.yaml`)
expect(wrapper.get('button[type="submit"]').attributes('disabled')).toBeDefined()
await wrapper.findAll('button').find(button => button.text() === '本地目录')!.trigger('click')
await wrapper.get('input').setValue(' G:\\packages\\example ')
await wrapper.get('form').trigger('submit')
await wrapper.get('form').trigger('submit')
@@ -27,6 +54,7 @@ it.each(['Skill', 'Plugin'] as const)('installs %s from a trimmed directory and
it('keeps the path and displays validation errors for retry', async () => {
const install = vi.fn().mockRejectedValueOnce(new Error('Manifest does not exist')).mockResolvedValueOnce(undefined)
wrapper = mount(ExtensionInstallDialog, { props: { kind: 'Plugin', install } })
await wrapper.findAll('button').find(button => button.text() === '本地目录')!.trigger('click')
await wrapper.get('input').setValue('G:\\packages\\example')
await wrapper.get('form').trigger('submit')
await flushPromises()
@@ -5,20 +5,38 @@ import AppDialog from './AppDialog.vue'
import AppIcon from './AppIcon.vue'
import { t } from '@/i18n'
const props = defineProps<{ kind: 'Skill' | 'Plugin'; install: (path: string) => Promise<unknown> }>()
const props = defineProps<{ kind: 'Skill' | 'Plugin'; install: (source: string | File) => Promise<unknown> }>()
const emit = defineEmits<{ close: []; installed: [] }>()
const path = ref('')
const mode = ref<'path' | 'zip'>('zip')
const fileInput = ref<HTMLInputElement>()
const file = ref<File | null>(null)
const busy = ref(false)
const error = ref('')
const title = computed(() => t(`安装 ${props.kind}`, `Install ${props.kind}`))
const manifest = computed(() => `${props.kind.toLowerCase()}.yaml`)
const ready = computed(() => mode.value === 'zip' ? Boolean(file.value) : Boolean(path.value.trim()))
function chooseFile(event: Event) {
const input = event.target as HTMLInputElement
file.value = null
error.value = ''
const selected = input.files?.[0]
input.value = ''
if (!selected) return
if (!selected.name.toLowerCase().endsWith('.zip') || !selected.size || selected.size > 10 * 1024 * 1024) {
error.value = t('请选择非空 ZIP 文件,大小不超过 10 MiB。', 'Choose a nonempty ZIP file up to 10 MiB.')
return
}
file.value = selected
}
async function submit() {
if (busy.value || !path.value.trim()) return
if (busy.value || !ready.value) return
error.value = ''
busy.value = true
try {
await props.install(path.value.trim())
await props.install(mode.value === 'zip' ? file.value! : path.value.trim())
emit('installed')
} catch (reason) {
error.value = reason instanceof Error ? reason.message : t('安装失败,请检查包目录后重试。', 'Installation failed. Check the package directory and retry.')
@@ -33,8 +51,19 @@ async function submit() {
<form class="modal extension-install-modal" :aria-busy="busy" @submit.prevent="submit">
<span class="badge info">{{ t('扩展安装', 'Extension installation') }}</span>
<h2>{{ title }}</h2>
<p class="muted">{{ t('本地包目录安装,安装时会校验清单与依赖。', 'Install from a local package directory. The manifest and dependencies are checked during installation.') }}</p>
<div class="package-source">
<p class="muted">{{ t('导入 ZIP 或使用本地包目录,安装时会校验清单与依赖。', 'Import a ZIP or use a local directory. The manifest and dependencies are checked during installation.') }}</p>
<div class="source-tabs" :aria-label="t('安装来源', 'Installation source')">
<button v-for="item in (['zip', 'path'] as const)" :key="item" type="button" class="button-secondary" :aria-pressed="mode === item" :disabled="busy" @click="mode = item; error = ''">{{ item === 'zip' ? t('ZIP 文件', 'ZIP file') : t('本地目录', 'Local directory') }}</button>
</div>
<div v-if="mode === 'zip'" class="package-source">
<AppIcon :icon="FolderOpened" :size="30" />
<input ref="fileInput" class="zip-input" type="file" accept=".zip,application/zip" :disabled="busy" :aria-label="t('选择 ZIP 扩展包', 'Choose a ZIP extension package')" @change="chooseFile" />
<button type="button" class="button-secondary" :disabled="busy" @click="fileInput?.click()">{{ file ? t('重新选择 ZIP', 'Choose another ZIP') : t('选择 ZIP 文件', 'Choose ZIP file') }}</button>
<strong v-if="file" class="package-name">{{ file.name }} · {{ (file.size / 1024).toFixed(1) }} KiB</strong>
<p class="muted">{{ t('根目录或唯一顶层文件夹中须包含', 'The root or single top-level folder must contain') }} <code>{{ manifest }}</code></p>
<p class="subtle">{{ t('ZIP 最大 10 MiB,解压后最大 50 MiB,最多 2048 个条目。', 'Up to 10 MiB compressed, 50 MiB extracted, and 2048 entries.') }}</p>
</div>
<div v-else class="package-source">
<AppIcon :icon="FolderOpened" :size="30" />
<strong>{{ t('本地包目录', 'Local package directory') }}</strong>
<p class="muted">{{ t('选择包含以下清单的完整解压目录:', 'Use the extracted directory containing:') }} <code>{{ manifest }}</code></p>
@@ -42,13 +71,13 @@ async function submit() {
<span>{{ t('目录路径', 'Directory path') }}</span>
<input v-model="path" class="input" autofocus required :disabled="busy" :placeholder="t('粘贴本地包目录的完整路径', 'Paste the full package directory path')" aria-describedby="extension-path-help" />
</label>
<p id="extension-path-help" class="subtle">{{ t('路径须位于 AI Core 所在电脑。ZIP 请先解压,再填写目录路径。', 'The directory must be on the AI Core computer. Extract ZIP packages before entering the directory path.') }}</p>
<p id="extension-path-help" class="subtle">{{ t('路径须位于 AI Core 所在电脑。', 'The directory must be on the AI Core computer.') }}</p>
</div>
<div v-if="error" class="error-banner" role="alert">{{ error }}</div>
<p v-if="busy" class="muted" role="status">{{ t('正在校验并安装请稍候', 'Validating and installing') }}</p>
<footer class="install-actions">
<button type="button" class="button-secondary" :disabled="busy" @click="emit('close')">{{ t('取消', 'Cancel') }}</button>
<button type="submit" class="button-primary" :disabled="busy || !path.trim()">{{ busy ? t('安装中…', 'Installing…') : title }}</button>
<button type="submit" class="button-primary" :disabled="busy || !ready">{{ busy ? t('安装中…', 'Installing…') : title }}</button>
</footer>
</form>
</AppDialog>
@@ -63,4 +92,8 @@ h2 { margin: var(--space-sm) 0 var(--space-md); }
.package-field input { min-width: 0; }
.install-actions { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: var(--space-sm); margin-top: var(--space-lg); }
.error-banner { overflow-wrap: anywhere; }
.source-tabs { display: flex; gap: var(--space-sm); margin-top: var(--space-lg); }
.source-tabs [aria-pressed="true"] { border-color: var(--color-accent-primary); color: var(--color-accent-primary); background: var(--color-accent-soft); }
.zip-input { display: none; }
.package-name { overflow-wrap: anywhere; max-width: 100%; }
</style>