diff --git a/.playwright/scripts/__tests__/task-archive.e2e.mjs b/.playwright/scripts/__tests__/task-archive.e2e.mjs index a5fbd86b5..e31853aa4 100644 --- a/.playwright/scripts/__tests__/task-archive.e2e.mjs +++ b/.playwright/scripts/__tests__/task-archive.e2e.mjs @@ -160,7 +160,7 @@ test('active task deletion requires confirmation and permanently removes only ta await capture(page, testInfo, 'active-task-deleted') }) -test('official legacy cleanup plugin requires host confirmation and preserves external files', async ({ buddy }, testInfo) => { +test('official legacy cleanup plugin owns confirmation and preserves external files', async ({ buddy }, testInfo) => { test.skip(!process.env.LEXORA_TEST_LEGACY_CLEANUP_ARCHIVE, 'Provide the separately built legacy cleanup plugin archive') test.setTimeout(180000) const instance = await buddy.createInstance('legacy-task-cleanup') @@ -186,7 +186,7 @@ test('official legacy cleanup plugin requires host confirmation and preserves ex await card.getByTestId('extension-card-more').click() await page.getByTestId('extension-actions').hover() const action = page.locator(`[data-extension-action="${pluginId}.action"]`) - await expect(action).toHaveText('清理旧版任务…') + await expect(action).toHaveText('清理任务残留…') await action.click() } const pluginFrame = async () => { @@ -211,13 +211,13 @@ test('official legacy cleanup plugin requires host confirmation and preserves ex const lifecycleWindow = await app.browserWindow(page) await lifecycleWindow.evaluate(window => window.focus()) await runCleanup() - const confirmation = page.getByTestId('extension-task-cleanup-dialog') - await expect(confirmation).toBeVisible() - await expect(confirmation.getByTestId('extension-task-cleanup-scope')).toContainText('32') - await expect(confirmation).toContainText('删除后无法恢复') - await expect(confirmation).toContainText('不处理活动或已归档任务') - await expect(confirmation).toContainText('不影响用户工作区及外部文件') let frame = await pluginFrame() + const confirmation = () => frame.getByTestId('cleanup-preview') + await expect(confirmation()).toBeVisible() + await expect(frame.getByTestId('cleanup-preview-total')).toHaveText('32') + await expect(confirmation()).toContainText('不可恢复') + await expect(confirmation()).toContainText('不处理活动或已归档任务') + await expect(confirmation()).toContainText('不删除用户工作区及外部文件') await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'confirming') for (const appearance of ['light', 'dark']) { await page.evaluate(() => window.lexoraDesktop.themes.request({ action: 'preference', preference: { id: 'system' } })) @@ -231,31 +231,30 @@ test('official legacy cleanup plugin requires host confirmation and preserves ex const originalBounds = await lifecycleWindow.evaluate(window => window.getBounds()) await lifecycleWindow.evaluate(window => window.setBounds({ width: 980, height: 640 })) await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(980) - await expect(confirmation.getByRole('button', { name: '删除', exact: true })).toBeInViewport() + await expect(frame.getByTestId('cleanup-confirm-delete')).toBeInViewport() await capture(page, testInfo, 'legacy-cleanup-confirm-minimum') await lifecycleWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds) - await confirmation.getByRole('button', { name: '取消', exact: true }).click() - await expect(confirmation).toBeHidden() + await frame.getByTestId('cleanup-cancel').click() + await expect(confirmation()).toBeHidden() await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'cancelled') expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true) expect(await fs.readFile(path.join(fixture.owned, 'owned.txt'), 'utf8')).toBe('Task-owned fixture') await frame.getByRole('button', { name: '关闭', exact: true }).click() await runCleanup() - await expect(confirmation).toBeVisible() + frame = await pluginFrame() + await expect(confirmation()).toBeVisible() await lifecycleWindow.evaluate(window => window.hide()) - await expect.poll(() => page.evaluate(() => window.lexoraDesktop.extensions.taskCleanupConfirmations())).toEqual([]) + await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'cancelled') await lifecycleWindow.evaluate((window) => { window.show() window.focus() }) - await expect(confirmation).toBeHidden() - frame = await pluginFrame() - await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'cancelled') + await expect(confirmation()).toBeHidden() expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true) await frame.getByRole('button', { name: '关闭', exact: true }).click() await runCleanup() - await expect(confirmation).toBeVisible() frame = await pluginFrame() + await expect(confirmation()).toBeVisible() await frame.evaluate(() => { window.cleanupProgressSnapshots = [] const panel = document.querySelector('[data-testid="legacy-task-cleanup-panel"]') @@ -264,8 +263,8 @@ test('official legacy cleanup plugin requires host confirmation and preserves ex window.cleanupProgressSnapshots.push(Number(panel.querySelector('[data-testid="cleanup-processed"]').textContent)) }).observe(panel, { subtree: true, attributes: true, childList: true, characterData: true }) }) - await confirmation.getByRole('button', { name: '删除', exact: true }).click() - await expect(confirmation).toBeHidden() + await frame.getByTestId('cleanup-confirm-delete').click() + await expect(confirmation()).toBeHidden() await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'running') await expect.poll(() => frame.evaluate(() => window.cleanupProgressSnapshots.some(count => count > 0 && count < 32))).toBe(true) await capture(page, testInfo, 'legacy-cleanup-plugin-progress') @@ -316,33 +315,3 @@ test('official legacy cleanup plugin requires host confirmation and preserves ex await card.getByTestId('extension-card-more').click() await expect(page.getByTestId('extension-actions')).toHaveCount(0) }) - -test('legacy cleanup 1.0.1 remains compatible with host-only safety confirmation', async ({ buddy }, testInfo) => { - test.skip(!process.env.LEXORA_TEST_LEGACY_CLEANUP_COMPAT_ARCHIVE, 'Provide the original 1.0.1 package') - const instance = await buddy.createInstance('legacy-cleanup-compatibility') - const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation')) - const { app, page } = await launchArchiveInstance(instance) - await page.locator('.desktop-app-sidebar').getByRole('button', { name: '插件', exact: true }).click() - await app.evaluate(({ dialog }, archive) => { - dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [archive] }) - }, process.env.LEXORA_TEST_LEGACY_CLEANUP_COMPAT_ARCHIVE) - await page.getByTestId('extension-install-options').click() - await page.getByTestId('extension-install').click() - await page.getByTestId('extension-install-review').getByTestId('extension-confirm-install').click() - const card = page.locator(`article[data-extension-id="${pluginId}"]`) - await expect(card).toContainText('1.0.1') - await expect.poll(() => page.evaluate(async id => (await window.lexoraDesktop.extensions.list()).find(item => item.manifest.id === id)?.state, pluginId)).toBe('active') - await card.getByTestId('extension-card-more').click() - await page.getByTestId('extension-actions').hover() - await page.locator(`[data-extension-action="${pluginId}.action"]`).click() - const confirmation = page.getByTestId('extension-task-cleanup-dialog') - await expect(confirmation.getByTestId('extension-task-cleanup-scope')).toContainText('1') - expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true) - await confirmation.getByRole('button', { name: '删除', exact: true }).click() - await expect(confirmation).toBeHidden() - await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(false) - await expect.poll(() => fs.access(fixture.owned).then(() => true, () => false)).toBe(false) - expect(await fs.readFile(path.join(fixture.external, 'keep.txt'), 'utf8')).toBe('External fixture must survive') - expect(await taskExists(app, fixture.databasePath, 'archive-active')).toBe(true) - await expectStorage(app, fixture.databasePath) -}) diff --git a/apps/buddy/electron/main/extensions/ExtensionTaskCleanup.ts b/apps/buddy/electron/main/extensions/ExtensionTaskCleanup.ts deleted file mode 100644 index a8e32865f..000000000 --- a/apps/buddy/electron/main/extensions/ExtensionTaskCleanup.ts +++ /dev/null @@ -1,38 +0,0 @@ -import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' -import type { ExtensionServicePorts } from '../../../platform/extensions/ExtensionService' -import { dialog } from 'electron' - -export function assertTaskCleanupConfirmationSender(event: Pick, owner: BrowserWindow | null): void { - if (!owner || owner.isDestroyed() || !owner.isVisible() || owner.isMinimized() || !owner.isFocused() || owner.webContents.isDestroyed() || event.sender !== owner.webContents || event.senderFrame !== owner.webContents.mainFrame || owner.webContents.focusedFrame !== owner.webContents.mainFrame) - throw new Error('EXTENSION_TASK_CLEANUP_UNAVAILABLE') -} - -export function createExtensionTaskCleanupConfirmation(getWindow: () => BrowserWindow | null): NonNullable['confirmDelete'] { - let confirming = false - return async (session, input, assertCurrent) => { - assertCurrent() - const owner = getWindow() - if (confirming || !owner || owner.isDestroyed() || !owner.isVisible() || owner.isMinimized() || !owner.isFocused() || owner.webContents.isDestroyed() || owner.webContents.focusedFrame?.url !== session.url) - throw new Error('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - confirming = true - try { - const result = await dialog.showMessageBox(owner, { - type: 'warning', - title: '永久清理旧版已移除任务', - message: '永久删除此旧版已移除任务?', - detail: `任务标识:${input.conversationId}\n\n将删除该任务的本地历史和宿主管理的数据,无法撤销。不会删除用户工作区的原文件。任务状态已变化时会拒绝删除。`, - buttons: ['取消', '删除'], - defaultId: 0, - cancelId: 0, - noLink: true, - }) - assertCurrent() - if (getWindow() !== owner || owner.isDestroyed() || !owner.isVisible() || owner.isMinimized()) - throw new Error('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - return result.response === 1 - } - finally { - confirming = false - } - } -} diff --git a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanup.spec.ts b/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanup.spec.ts deleted file mode 100644 index 7fef5a5b8..000000000 --- a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanup.spec.ts +++ /dev/null @@ -1,75 +0,0 @@ -import type { BrowserWindow, IpcMainInvokeEvent } from 'electron' -import type { ExtensionViewSession } from '../../../../shared/extensions/extensionApi' -import { deferred } from '@buddy-tests/deferred' -import { beforeEach, expect, it, vi } from 'vitest' -import { assertTaskCleanupConfirmationSender, createExtensionTaskCleanupConfirmation } from '../ExtensionTaskCleanup' - -const showMessageBox = vi.hoisted(() => vi.fn()) -vi.mock('electron', () => ({ dialog: { showMessageBox } })) -beforeEach(() => showMessageBox.mockReset()) -const session: ExtensionViewSession = { id: 'view', extensionId: 'test.cleanup', generation: 'generation', token: 'token', url: 'lexora-extension://token/__view.html' } -const target = { conversationId: 'legacy-task', expectedRevision: 4 } -function fixture() { - const state = { visible: true, focused: true, minimized: false, destroyed: false, frame: session.url } - const owner = { isDestroyed: () => state.destroyed, isVisible: () => state.visible, isMinimized: () => state.minimized, isFocused: () => state.focused, webContents: { isDestroyed: () => state.destroyed, get focusedFrame() { - return { url: state.frame } - } } } - return { state, confirm: createExtensionTaskCleanupConfirmation(() => owner as unknown as BrowserWindow) } -} - -it('accepts only the current focused main window frame for host confirmation', () => { - const mainFrame = { url: 'lexora://desktop' } - const pluginFrame = { url: session.url } - const state = { focusedFrame: mainFrame, visible: true, focused: true, minimized: false, destroyed: false } - const owner = { isDestroyed: () => state.destroyed, isVisible: () => state.visible, isMinimized: () => state.minimized, isFocused: () => state.focused, webContents: { isDestroyed: () => false, mainFrame, get focusedFrame() { - return state.focusedFrame - } } } - const confirm = (sender: unknown = owner.webContents, senderFrame: unknown = mainFrame) => assertTaskCleanupConfirmationSender({ sender, senderFrame } as IpcMainInvokeEvent, owner as unknown as BrowserWindow) - expect(() => confirm()).not.toThrow() - expect(() => confirm(owner.webContents, pluginFrame)).toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - expect(() => confirm({}, mainFrame)).toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - expect(() => confirm(owner.webContents, { ...mainFrame })).toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - state.focusedFrame = pluginFrame - expect(() => confirm()).toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - state.focusedFrame = mainFrame - for (const key of ['visible', 'focused', 'minimized', 'destroyed'] as const) { - state[key] = !state[key] - expect(() => confirm()).toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - state[key] = !state[key] - } -}) - -it.each(['visible', 'focused', 'minimized', 'destroyed', 'frame'] as const)('rejects untrusted native presentation: %s', async (key) => { - const f = fixture() - if (key === 'frame') - f.state.frame = 'lexora-extension://another/__view.html' - else f.state[key] = !f.state[key] - await expect(f.confirm(session, target, () => {})).rejects.toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') -}) - -it('requires affirmative native confirmation with a safe default and exact target', async () => { - const f = fixture() - showMessageBox.mockResolvedValueOnce({ response: 0 }).mockResolvedValueOnce({ response: 1 }) - expect(await f.confirm(session, target, () => {})).toBe(false) - expect(await f.confirm(session, target, () => {})).toBe(true) - const options = showMessageBox.mock.calls[0]![1] - expect(options).toMatchObject({ defaultId: 0, cancelId: 0, buttons: ['取消', '删除'] }) - expect(options.detail).toContain(target.conversationId) - expect(options.detail).toContain('无法撤销') -}) - -it('rejects concurrent dialogs and a late answer after view revocation', async () => { - const f = fixture() - const answer = deferred<{ response: number }>() - let current = true - showMessageBox.mockReturnValue(answer.promise) - const pending = f.confirm(session, target, () => { - if (!current) - throw new Error('EXPIRED') - }) - const rejected = expect(pending).rejects.toThrow('EXPIRED') - await expect(f.confirm(session, target, () => {})).rejects.toThrow('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - current = false - answer.resolve({ response: 1 }) - await rejected -}) diff --git a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts b/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts index 80ce24645..c2988e44f 100644 --- a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts +++ b/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts @@ -1,11 +1,11 @@ -import type { ExtensionTaskCleanupProgress } from '../../../../shared/extensions/extensionTaskCleanup' +import type { ExtensionTaskCleanupPreview, ExtensionTaskCleanupProgress } from '../../../../shared/extensions/extensionTaskCleanup' import { readFile } from 'node:fs/promises' import { runInNewContext } from 'node:vm' import { deferred } from '@buddy-tests/deferred' import { expect, it } from 'vitest' interface CleanupCommand { - run: (options?: { onProgress?: (progress: ExtensionTaskCleanupProgress) => unknown }) => Promise + run: (options: { confirm: (preview: ExtensionTaskCleanupPreview, signal: AbortSignal) => boolean | Promise, onProgress?: (progress: ExtensionTaskCleanupProgress) => unknown }) => Promise } const progress: ExtensionTaskCleanupProgress = { phase: 'running', total: 2, processed: 1, deleted: 0, pending: 1, failed: 0, skipped: 0, errorCode: null } @@ -43,12 +43,12 @@ async function runtime(execute: (context: { taskCleanup?: CleanupCommand }) => P await receive({ id, method, params }) return replies.get(id)! } - return { pending, pagehide: () => pagehide(), command: (token: string | null) => message('command', { command: 'cleanup', cleanupToken: token }), progress: (token: string, value = progress) => message('taskCleanup.progress', { token, progress: value }) } + return { pending, pagehide: () => pagehide(), command: (token: string | null) => message('command', { command: 'cleanup', cleanupToken: token }), progress: (token: string, value = progress) => message('taskCleanup.progress', { token, progress: value }), confirm: (token: string) => message('taskCleanup.confirm', { token, preview: { total: 2, skipped: 1 } }), cancel: (token: string) => message('taskCleanup.cancel', { token }) } } it('routes by command token, isolates callback failures and releases listeners before final return', async () => { const received: ExtensionTaskCleanupProgress[] = [] - const f = await runtime(async ({ taskCleanup }) => taskCleanup!.run({ onProgress: (value) => { + const f = await runtime(async ({ taskCleanup }) => taskCleanup!.run({ confirm: () => true, onProgress: (value) => { received.push(value) if (received.length === 1) throw new Error('PLUGIN_CALLBACK_FAILED') @@ -74,7 +74,7 @@ it('keeps concurrent command callbacks isolated and removes rejected and unloade let index = 0 const f = await runtime(async ({ taskCleanup }) => { const id = ++index - return taskCleanup!.run({ onProgress: () => { + return taskCleanup!.run({ confirm: () => true, onProgress: () => { received.push(id) } }) }) @@ -95,17 +95,102 @@ it('keeps concurrent command callbacks isolated and removes rejected and unloade await second }) -it('preserves run() without options and does not expose cleanup outside a trusted invocation', async () => { +it('requires confirm before sending a request and does not expose cleanup outside a trusted invocation', async () => { let captured: CleanupCommand | undefined const f = await runtime(async ({ taskCleanup }) => { captured = taskCleanup - return taskCleanup ? taskCleanup.run() : null + return taskCleanup ? (taskCleanup.run as (options?: unknown) => Promise)() : null }) expect(await f.command(null)).toEqual({ success: true, result: null }) expect(captured).toBeUndefined() - const run = f.command('legacy') - await expect(captured!.run()).rejects.toThrow('EXTENSION_METHOD_DENIED') - expect((await f.progress('legacy')).success).toBe(true) - f.pending.get('legacy')!.resolve({ status: 'cancelled', results: [], summary: { ...progress, phase: 'cancelled' } }) - expect(await run).toMatchObject({ success: true, result: { status: 'cancelled', summary: { phase: 'cancelled' } } }) + expect(await f.command('missing')).toEqual({ success: false, result: 'EXTENSION_TASK_CLEANUP_CONFIRMATION_REQUIRED' }) + expect(f.pending.size).toBe(0) + await expect(captured!.run({ confirm: () => true })).rejects.toThrow('EXTENSION_METHOD_DENIED') +}) + +it.each([true, false, 'true', 1, null, 'throw'] as const)('requires a boolean confirmation response: %s', async (response) => { + const f = await runtime(async ({ taskCleanup }) => taskCleanup!.run({ confirm: (preview, signal) => { + expect(preview).toEqual({ total: 2, skipped: 1 }) + expect(Object.isFrozen(preview)).toBe(true) + expect(signal).toBeInstanceOf(AbortSignal) + expect(signal.aborted).toBe(false) + if (response === 'throw') + throw new Error('EXTENSION_OPERATION_FAILED') + return response as boolean + } })) + const run = f.command('current') + expect(await f.confirm('other')).toEqual({ success: false, result: 'EXTENSION_TASK_CLEANUP_EXPIRED' }) + expect(await f.confirm('current')).toEqual(typeof response === 'boolean' ? { success: true, result: response } : { success: false, result: response === 'throw' ? 'EXTENSION_OPERATION_FAILED' : 'EXTENSION_INVALID_ARGUMENT' }) + expect(await f.confirm('current')).toEqual({ success: false, result: 'EXTENSION_TASK_CLEANUP_EXPIRED' }) + f.pending.get('current')!.resolve(null) + await run +}) + +it.each(['cancel', 'pagehide', 'command-end'] as const)('aborts the local callback signal on %s and ignores late true', async (action) => { + const started = deferred() + const answer = deferred() + const commandEnd = deferred() + let cleanupRun: Promise | undefined + const f = await runtime(async ({ taskCleanup }) => { + cleanupRun = taskCleanup!.run({ confirm: (_preview, signal) => { + started.resolve(signal) + return answer.promise + } }) + if (action === 'command-end') { + await commandEnd.promise + return null + } + return cleanupRun + }) + const run = f.command('current') + const confirmation = f.confirm('current') + const signal = await started.promise + if (action === 'cancel') { + await f.cancel('current') + } + else if (action === 'pagehide') { + f.pagehide() + } + else { + commandEnd.resolve() + await run + } + expect(signal.aborted).toBe(true) + expect(await confirmation).toEqual({ success: false, result: 'EXTENSION_TASK_CLEANUP_EXPIRED' }) + answer.resolve(true) + expect(await f.confirm('current')).toEqual({ success: false, result: 'EXTENSION_TASK_CLEANUP_EXPIRED' }) + f.pending.get('current')!.resolve(null) + await cleanupRun + await run +}) + +it('consumes the command once and isolates in-flight confirmations by token', async () => { + const answers = [deferred(), deferred()] + const entered = [deferred(), deferred()] + let index = 0 + const f = await runtime(async ({ taskCleanup }) => { + const id = index++ + const run = taskCleanup!.run({ confirm: (_preview, signal) => { + entered[id]!.resolve(signal) + return answers[id]!.promise + } }) + await expect(taskCleanup!.run({ confirm: () => true })).rejects.toThrow('EXTENSION_METHOD_DENIED') + return run + }) + const first = f.command('first') + const second = f.command('second') + const firstConfirm = f.confirm('first') + const secondConfirm = f.confirm('second') + const firstSignal = await entered[0]!.promise + const secondSignal = await entered[1]!.promise + await f.cancel('first') + expect(firstSignal.aborted).toBe(true) + expect(secondSignal.aborted).toBe(false) + expect((await firstConfirm).success).toBe(false) + answers[0]!.resolve(true) + answers[1]!.resolve(true) + expect(await secondConfirm).toEqual({ success: true, result: true }) + f.pending.get('first')!.resolve(null) + f.pending.get('second')!.resolve(null) + await Promise.all([first, second]) }) diff --git a/apps/buddy/electron/main/extensions/registerExtensionIpc.ts b/apps/buddy/electron/main/extensions/registerExtensionIpc.ts index 09136573d..c3544a5f7 100644 --- a/apps/buddy/electron/main/extensions/registerExtensionIpc.ts +++ b/apps/buddy/electron/main/extensions/registerExtensionIpc.ts @@ -41,7 +41,6 @@ import { createExtensionSpeechBackend } from './createExtensionSpeechBackend' import { createExtensionClipboard } from './ExtensionClipboard' import { processExtensionPackageInBackground } from './ExtensionPackageWorker' import { ExtensionProtocol } from './ExtensionProtocol' -import { assertTaskCleanupConfirmationSender, createExtensionTaskCleanupConfirmation } from './ExtensionTaskCleanup' import { createInferenceHardwareProvider } from './inferenceHardware' import { SandboxedExtensionHost } from './SandboxedExtensionHost' @@ -108,7 +107,7 @@ export function registerExtensionIpc(options: { const service = new ExtensionService(store, { documents: options.documents, clipboard: createExtensionClipboard(options.getWindow), - taskCleanup: options.conversationCleanup ? { ...createExtensionTaskCleanup(options.conversationCleanup), confirmDelete: createExtensionTaskCleanupConfirmation(options.getWindow) } : undefined, + taskCleanup: options.conversationCleanup ? createExtensionTaskCleanup(options.conversationCleanup) : undefined, shellsChanged: options.shellsChanged, skillsChanged: options.skillsChanged, capabilitiesChanged: options.capabilitiesChanged, @@ -244,7 +243,7 @@ export function registerExtensionIpc(options: { const current = window() if (current && !current.isDestroyed()) current.webContents.send(change.kind === 'installation-progress' ? EXTENSION_IPC.installationsChanged : EXTENSION_IPC.changed) - if (change.kind !== 'installation-progress' && change.kind !== 'task-cleanup') { + if (change.kind !== 'installation-progress') { for (const listener of speechListeners) listener() } }), @@ -317,11 +316,6 @@ export function registerExtensionIpc(options: { case 'taskActions': return await options.taskActions() case 'invokeTaskAction': return await options.invokeTaskAction(input.input) case 'list': return await service.list() - case 'taskCleanupConfirmations': return service.taskCleanupConfirmations() - case 'confirmTaskCleanup': { - assertTaskCleanupConfirmationSender(event, window()) - return await service.confirmTaskCleanup(input.id, input.operationId, input.confirmed) - } case 'fileOpeners': return await service.fileOpeners() case 'setFileOpener': return await service.setFileOpener(input.choice) case 'prepareFileOpening': return await service.prepareFileOpening(input.input) diff --git a/apps/buddy/electron/main/extensions/runtime/host.js b/apps/buddy/electron/main/extensions/runtime/host.js index a1cd501f4..320dab8a7 100644 --- a/apps/buddy/electron/main/extensions/runtime/host.js +++ b/apps/buddy/electron/main/extensions/runtime/host.js @@ -10,8 +10,11 @@ const lifetime = new AbortController() const workers = createExtensionWorkers(new URL('/__package/', location.href), lifetime.signal, Worker) addEventListener('pagehide', () => lifetime.abort(), { once: true }) const commands = new Map() -const cleanupProgressListeners = new Map() -lifetime.signal.addEventListener('abort', () => cleanupProgressListeners.clear(), { once: true }) +const cleanupCallbacks = new Map() +lifetime.signal.addEventListener('abort', () => { + for (const callbacks of cleanupCallbacks.values()) callbacks.controller.abort() + cleanupCallbacks.clear() +}, { once: true }) const agentTools = new Map() const agentActions = new Map() const conditions = new Map() @@ -29,24 +32,62 @@ let activated = false const interactions = new Map() const code = (error, method) => /^EXTENSION_[A-Z_]+$/.test(error?.message) ? error.message : method === 'activate' ? 'EXTENSION_ACTIVATION_FAILED' : 'EXTENSION_OPERATION_FAILED' const request = (method, params = null) => bridge.request(method, params) -function cleanupCommand(token) { +function cleanupCommand(token, signal) { let used = false - return Object.freeze({ run: async (options = {}) => { - if (used) + return Object.freeze({ run: async (options) => { + if (used || signal.aborted || lifetime.signal.aborted) throw new Error('EXTENSION_METHOD_DENIED') + if (typeof options?.confirm !== 'function') + throw new Error('EXTENSION_TASK_CLEANUP_CONFIRMATION_REQUIRED') if (options.onProgress !== undefined && typeof options.onProgress !== 'function') throw new Error('EXTENSION_INVALID_ARGUMENT') used = true - if (options.onProgress) - cleanupProgressListeners.set(token, options.onProgress) + const callbacks = { confirm: options.confirm, onProgress: options.onProgress, controller: new AbortController(), used: false } + const cancel = () => { + cleanupCallbacks.delete(token) + callbacks.controller.abort() + } + cleanupCallbacks.set(token, callbacks) + signal.addEventListener('abort', cancel, { once: true }) try { return await request('taskCleanup.run', { token }) } finally { - cleanupProgressListeners.delete(token) + signal.removeEventListener('abort', cancel) + cancel() } } }) } + +async function confirmCleanup(token, preview) { + const callbacks = cleanupCallbacks.get(token) + if (!callbacks || callbacks.used || callbacks.controller.signal.aborted) + throw new Error('EXTENSION_TASK_CLEANUP_EXPIRED') + callbacks.used = true + const { signal } = callbacks.controller + let cancel + try { + const confirmed = await Promise.race([ + Promise.resolve().then(() => { + signal.throwIfAborted() + return callbacks.confirm(Object.freeze({ total: preview.total, skipped: preview.skipped }), signal) + }), + new Promise((resolve, reject) => { + cancel = () => reject(new Error('EXTENSION_TASK_CLEANUP_EXPIRED')) + signal.addEventListener('abort', cancel, { once: true }) + }), + ]) + if (signal.aborted || cleanupCallbacks.get(token) !== callbacks) + throw new Error('EXTENSION_TASK_CLEANUP_EXPIRED') + if (typeof confirmed !== 'boolean') + throw new Error('EXTENSION_INVALID_ARGUMENT') + return confirmed + } + finally { + signal.removeEventListener('abort', cancel) + } +} + function disposable(cleanup) { let disposed = false const value = { dispose() { @@ -258,10 +299,22 @@ bridge.subscribe(async ({ id, method, params }) => { else if (method === 'command') { if (!activated || !commands.has(params.command)) throw new Error('EXTENSION_COMMAND_UNAVAILABLE') - result = await commands.get(params.command)(Object.freeze({ resource: params.resource, arguments: params.arguments ?? null, invocation: params.invocation ?? null, taskCleanup: params.cleanupToken ? cleanupCommand(params.cleanupToken) : undefined })) ?? null + const controller = new AbortController() + try { + result = await commands.get(params.command)(Object.freeze({ resource: params.resource, arguments: params.arguments ?? null, invocation: params.invocation ?? null, taskCleanup: params.cleanupToken ? cleanupCommand(params.cleanupToken, controller.signal) : undefined })) ?? null + } + finally { controller.abort() } + } + else if (method === 'taskCleanup.confirm') { + result = await confirmCleanup(params.token, params.preview) + } + else if (method === 'taskCleanup.cancel') { + const callbacks = cleanupCallbacks.get(params.token) + cleanupCallbacks.delete(params.token) + callbacks?.controller.abort() } else if (method === 'taskCleanup.progress') { - const listener = cleanupProgressListeners.get(params.token) + const listener = cleanupCallbacks.get(params.token)?.onProgress if (listener) { try { void Promise.resolve(listener(Object.freeze({ ...params.progress }))).catch(() => {}) diff --git a/apps/buddy/electron/main/extensions/runtime/view.js b/apps/buddy/electron/main/extensions/runtime/view.js index 852db094e..ee21b08e8 100644 --- a/apps/buddy/electron/main/extensions/runtime/view.js +++ b/apps/buddy/electron/main/extensions/runtime/view.js @@ -120,7 +120,6 @@ async function initialize() { const api = Object.freeze({ workers, clipboard: Object.freeze({ read: () => request('clipboard.read'), write: data => request('clipboard.write', data) }), - taskCleanup: Object.freeze({ list: (input = {}) => request('taskCleanup.list', input), delete: input => request('taskCleanup.delete', input) }), setDocumentInfo: info => request('view.setDocumentInfo', info), setSettingsHeaderActions: actions => request('view.setSettingsHeaderActions', actions), onSettingsHeaderAction: listener => events.on('view:settings-header-action:activated', event => listener(event.data.id)), diff --git a/apps/buddy/electron/preload/extensions.ts b/apps/buddy/electron/preload/extensions.ts index 890bfe0f5..24255be34 100644 --- a/apps/buddy/electron/preload/extensions.ts +++ b/apps/buddy/electron/preload/extensions.ts @@ -9,8 +9,6 @@ export function createExtensionApi(): ExtensionApi { taskActions: () => request({ action: 'taskActions' }), invokeTaskAction: input => request({ action: 'invokeTaskAction', input }), list: () => request({ action: 'list' }), - taskCleanupConfirmations: () => request({ action: 'taskCleanupConfirmations' }), - confirmTaskCleanup: (id, operationId, confirmed) => request({ action: 'confirmTaskCleanup', id, operationId, confirmed }), fileOpeners: () => request({ action: 'fileOpeners' }), setFileOpener: choice => request({ action: 'setFileOpener', choice }), prepareFileOpening: input => request({ action: 'prepareFileOpening', input }), diff --git a/apps/buddy/platform/extensions/ExtensionService.ts b/apps/buddy/platform/extensions/ExtensionService.ts index 21eeb4302..45e836839 100644 --- a/apps/buddy/platform/extensions/ExtensionService.ts +++ b/apps/buddy/platform/extensions/ExtensionService.ts @@ -14,7 +14,7 @@ import type { ExtensionFileSource, ExtensionResourceSelection } from '../../shar import type { ExtensionConfiguration, ExtensionConfigurationSnapshot } from '../../shared/extensions/extensionSettings' import type { ExtensionShellDescriptor } from '../../shared/extensions/extensionShell' import type { ExtensionSkillDescriptor } from '../../shared/extensions/extensionSkills' -import type { ExtensionTaskCleanup, ExtensionTaskCleanupConfirmation, ExtensionTaskCleanupDelete } from '../../shared/extensions/extensionTaskCleanup' +import type { ExtensionTaskCleanup } from '../../shared/extensions/extensionTaskCleanup' import type { FileOpeningChoice, FileOpeningSnapshot } from '../../shared/files/fileOpening' import type { TaskFileTarget } from '../../shared/files/taskFileApi' import type { ShellCandidate, ShellCandidateId } from '../../shared/shell/shellProgram' @@ -61,7 +61,6 @@ import { extensionConfigurationAppliedSchema, resolveExtensionConfiguration, val import { extensionSettingsHeaderActionsSchema } from '../../shared/extensions/extensionSettingsHeaderActions' import { extensionSkillRoots } from '../../shared/extensions/extensionSkills' import { EXTENSION_UNO_STYLESHEET } from '../../shared/extensions/extensionStyles' -import { extensionTaskCleanupDeleteSchema, extensionTaskCleanupListSchema, extensionTaskCleanupPageSchema, extensionTaskCleanupResultSchema } from '../../shared/extensions/extensionTaskCleanup' import { windowStyleIdSchema, windowStyleSchema } from '../../shared/extensions/extensionWindowStyles' import { resolveInferenceEnvironment } from '../../shared/extensions/inferencePlatform' import { fileOpeningExtension } from '../../shared/files/fileOpening' @@ -95,10 +94,7 @@ export interface ExtensionServicePorts { read: (session: ExtensionViewSession, assertCurrent: () => void) => Promise write: (session: ExtensionViewSession, data: ExtensionClipboardData, assertCurrent: () => void) => Promise } - taskCleanup?: ExtensionTaskCleanup & { - confirmDelete: (session: ExtensionViewSession, input: ExtensionTaskCleanupDelete, assertCurrent: () => void) => Promise - confirmBatch?: (count: number, assertCurrent: () => void) => Promise - } + taskCleanup?: ExtensionTaskCleanup inference?: ExtensionInferencePorts themes?: ThemeService createHost: (pkg: ExtensionPackage, broker: (method: string, params: unknown) => Promise, failed: (failure?: ExtensionHostFailure) => void) => ExtensionHost @@ -169,7 +165,7 @@ export class ExtensionService { readonly #ports: ExtensionServicePorts readonly #running = new Map() #taskCleanupVisibilityGeneration = 0 - readonly #taskCleanup = new ExtensionTaskCleanupController(extensionId => this.#publish({ kind: 'task-cleanup', extensionId })) + readonly #taskCleanup = new ExtensionTaskCleanupController() readonly #cleanupInvocations = new Map() readonly #pendingStops = new Map() readonly #viewOpenings = new Map() @@ -1380,23 +1376,19 @@ export class ExtensionService { cancelUnconfirmedTaskCleanup(): void { this.#taskCleanupVisibilityGeneration++ - this.#taskCleanup.cancelUnconfirmed() + this.#cancelUnconfirmedTaskCleanup() + } + + #cancelUnconfirmedTaskCleanup(running?: RunningExtension): void { + this.#taskCleanup.cancelUnconfirmed(running?.package.manifest.id) for (const [token, invocation] of this.#cleanupInvocations) { - if (!invocation.used) { + if (!invocation.used && (!running || invocation.running === running)) { this.#cleanupInvocations.delete(token) invocation.abort.abort() } } } - taskCleanupConfirmations(): ExtensionTaskCleanupConfirmation[] { - return this.#taskCleanup.confirmations() - } - - async confirmTaskCleanup(id: string, operationId: string, confirmed: boolean): Promise { - this.#taskCleanup.confirm(id, operationId, confirmed) - } - async #executeCommand(running: RunningExtension, command: string, target: SpaceFileTarget | null, invocation: JsonValue = null, argumentsValue: JsonValue = null, cleanupToken: string | null = null): Promise { if (!running.package.manifest.contributes.commands.some(item => item.id === command)) throw new Error('EXTENSION_COMMAND_UNAVAILABLE') @@ -1520,29 +1512,6 @@ export class ExtensionService { if (method === 'bootstrap') { result = { apiVersion: view.running.package.manifest.apiVersion, instanceId: view.input.instanceId ?? null, interactionId: view.input.interactionId ?? null, interactionMode: placement?.kind === 'view' ? placement.interaction ?? null : null, entry: contribution.entry, styles: view.running.package.manifest.styles?.uno ? [EXTENSION_UNO_STYLESHEET] : [], location: placement?.kind === 'view' ? 'mount' : contribution.location, presentation: placement?.kind ?? (contribution.location === 'window-overlay' ? 'decoration' : 'view'), resource: view.input.resource, state: view.input.state, stateVersion: view.input.stateVersion, expectedStateVersion: contribution.stateVersion } } - else if (method === 'taskCleanup.list' || method === 'taskCleanup.delete') { - if (!view.running.package.manifest.permissions.legacyTaskCleanup || contribution.location === 'window-overlay' || (placement && placement.kind !== 'view')) - throw new Error('EXTENSION_METHOD_DENIED') - const cleanup = this.#ports.taskCleanup - if (!cleanup) - throw new Error('EXTENSION_TASK_CLEANUP_UNAVAILABLE') - const assertCurrent = () => { - this.#assertCurrent(view.running) - if (view.abort.signal.aborted || this.#views.get(id) !== view) - throw new Error('EXTENSION_VIEW_EXPIRED') - } - if (method === 'taskCleanup.list') { - result = extensionTaskCleanupPageSchema.parse(await cleanup.list(extensionTaskCleanupListSchema.parse(params))) - } - else { - const input = extensionTaskCleanupDeleteSchema.parse(params) - const confirmed = await cleanup.confirmDelete(view.session, input, assertCurrent) - assertCurrent() - if (!confirmed) - throw new Error('EXTENSION_TASK_CLEANUP_CANCELLED') - result = extensionTaskCleanupResultSchema.parse(await cleanup.delete(input)) - } - } else if (method === 'clipboard.read' || method === 'clipboard.write') { const permission = method === 'clipboard.read' ? 'clipboardRead' : 'clipboardWrite' if (!view.running.package.manifest.permissions[permission] || contribution.location === 'window-overlay' || (placement && placement.kind !== 'view')) @@ -2099,10 +2068,25 @@ export class ExtensionService { let progressUnavailable = false const cleanupResult = await this.#taskCleanup.run({ extensionId: id, - menuId: invocation.menuId, signal: AbortSignal.any([running.abort.signal, invocation.abort.signal]), cleanup, - confirm: cleanup.confirmBatch, + confirm: async (preview, signal) => { + const cancel = () => { + void running.host.call('taskCleanup.cancel', { token: input.token }, AbortSignal.timeout(5000)).catch(() => {}) + } + signal.addEventListener('abort', cancel, { once: true }) + try { + if (signal.aborted) + throw new Error('EXTENSION_TASK_CLEANUP_EXPIRED') + const confirmed = await running.host.call('taskCleanup.confirm', { token: input.token, preview: { ...preview } }, signal) + if (typeof confirmed !== 'boolean') + throw new Error('EXTENSION_INVALID_ARGUMENT') + return confirmed + } + finally { + signal.removeEventListener('abort', cancel) + } + }, progress: async (progress) => { if (progressUnavailable || running.abort.signal.aborted || invocation.abort.signal.aborted || this.#cleanupInvocations.get(input.token) !== invocation) return @@ -2773,6 +2757,7 @@ export class ExtensionService { if (resourceId && resourceId !== retainResource && ![...this.#views.values()].some(current => current.input.resource?.id === resourceId)) this.#fileSnapshots.delete(resourceId) this.#ports.themes?.releaseOwner(`${view.running.package.manifest.id}:${view.running.generation}:${view.input.viewId}`) + this.#cancelUnconfirmedTaskCleanup(view.running) view.abort.abort() const cleanups: Promise[] = [this.#cancelUploads(view.running, view.session.id)] if (this.#documents) diff --git a/apps/buddy/platform/extensions/ExtensionServiceEvents.ts b/apps/buddy/platform/extensions/ExtensionServiceEvents.ts index 0b7a25cc7..bab27b3a3 100644 --- a/apps/buddy/platform/extensions/ExtensionServiceEvents.ts +++ b/apps/buddy/platform/extensions/ExtensionServiceEvents.ts @@ -21,7 +21,6 @@ export type ExtensionServiceFact | { readonly kind: 'view', readonly extensionId: string, readonly generation: string, readonly viewId: string, readonly status: 'opened' | 'ready' | 'failed' | 'closed' | 'cleanup-failed', readonly errorCode?: string } | { readonly kind: 'contributions', readonly initial: boolean, readonly descriptors: EventSnapshot } | { readonly kind: 'installation-progress' } - | { readonly kind: 'task-cleanup', readonly extensionId: string } | { readonly kind: 'file-associations' } | { readonly kind: 'diagnostic', readonly extensionId: string, readonly event: string, readonly errorCode?: string, readonly durationMs?: number, readonly diagnostic?: ExtensionDiagnostic } diff --git a/apps/buddy/platform/extensions/ExtensionTaskCleanupBatch.ts b/apps/buddy/platform/extensions/ExtensionTaskCleanupBatch.ts index a912151c6..782bb5733 100644 --- a/apps/buddy/platform/extensions/ExtensionTaskCleanupBatch.ts +++ b/apps/buddy/platform/extensions/ExtensionTaskCleanupBatch.ts @@ -1,4 +1,4 @@ -import type { ExtensionTaskCleanup, ExtensionTaskCleanupDelete, ExtensionTaskCleanupProgress, ExtensionTaskCleanupResult } from '../../shared/extensions/extensionTaskCleanup' +import type { ExtensionTaskCleanup, ExtensionTaskCleanupDelete, ExtensionTaskCleanupPreview, ExtensionTaskCleanupProgress, ExtensionTaskCleanupResult } from '../../shared/extensions/extensionTaskCleanup' import { extensionError } from '../../shared/extensions/extensionApi' import { extensionTaskCleanupPageSchema, extensionTaskCleanupResultSchema } from '../../shared/extensions/extensionTaskCleanup' @@ -12,7 +12,7 @@ export type { ExtensionTaskCleanupProgress } from '../../shared/extensions/exten export async function runExtensionTaskCleanupBatch(options: { cleanup: ExtensionTaskCleanup - confirm: (count: number, assertCurrent: () => void) => Promise + confirm: (preview: ExtensionTaskCleanupPreview) => Promise assertCurrent: () => void progress?: (progress: ExtensionTaskCleanupProgress) => unknown }): Promise { @@ -56,9 +56,11 @@ export async function runExtensionTaskCleanupBatch(options: { progress.phase = 'confirming' await publish() options.assertCurrent() - const confirmed = await options.confirm(targets.length, options.assertCurrent) + const confirmed = await options.confirm(Object.freeze({ total: targets.length, skipped: progress.skipped })) options.assertCurrent() - if (!confirmed) { + if (typeof confirmed !== 'boolean') + throw new Error('EXTENSION_INVALID_ARGUMENT') + if (confirmed !== true) { progress.phase = 'cancelled' await publish() return { status: 'cancelled', results, summary: { ...progress } } diff --git a/apps/buddy/platform/extensions/ExtensionTaskCleanupController.ts b/apps/buddy/platform/extensions/ExtensionTaskCleanupController.ts index fed8dc89f..62a4fe9ba 100644 --- a/apps/buddy/platform/extensions/ExtensionTaskCleanupController.ts +++ b/apps/buddy/platform/extensions/ExtensionTaskCleanupController.ts @@ -1,69 +1,35 @@ -import type { ExtensionTaskCleanupConfirmation, ExtensionTaskCleanupOperation, ExtensionTaskCleanupProgress } from '../../shared/extensions/extensionTaskCleanup' +import type { ExtensionTaskCleanupPreview, ExtensionTaskCleanupProgress } from '../../shared/extensions/extensionTaskCleanup' import type { ExtensionTaskCleanupBatchResult } from './ExtensionTaskCleanupBatch' -import { randomUUID } from 'node:crypto' import { runExtensionTaskCleanupBatch } from './ExtensionTaskCleanupBatch' interface ActiveCleanup { - operation: ExtensionTaskCleanupOperation - assertCurrent: () => void + extensionId: string confirmed: boolean - cancel: () => void - decide?: (confirmed: boolean) => void + cancel: (expired?: boolean) => void } export class ExtensionTaskCleanupController { - readonly #operations = new Map() #active?: ActiveCleanup - private readonly changed: (extensionId: string) => void - - constructor(changed: (extensionId: string) => void) { - this.changed = changed - } - - snapshot(extensionId: string): ExtensionTaskCleanupOperation | undefined { - const operation = this.#operations.get(extensionId) - return operation ? { ...operation } : undefined - } - - confirmations(): ExtensionTaskCleanupConfirmation[] { - const active = this.#active - if (!active?.decide || active.operation.phase !== 'confirming' || active.operation.total === null) - return [] - const { id, extensionId, total, skipped } = active.operation - return [{ id, extensionId, total, skipped }] - } - - confirm(extensionId: string, operationId: string, confirmed: boolean): void { - const active = this.#active - if (!active || active.operation.extensionId !== extensionId || active.operation.id !== operationId || active.operation.phase !== 'confirming' || !active.decide) - throw new Error('EXTENSION_TASK_CLEANUP_EXPIRED') - active.assertCurrent() - active.decide(confirmed) - } - - cancelUnconfirmed(): void { - const active = this.#active - if (active && !active.confirmed && (active.operation.phase === 'scanning' || active.operation.phase === 'confirming')) - active.cancel() + cancelUnconfirmed(extensionId?: string): void { + if (this.#active && !this.#active.confirmed && (!extensionId || this.#active.extensionId === extensionId)) + this.#active.cancel() } async run(options: Omit[0], 'confirm'> & { extensionId: string - menuId: string signal: AbortSignal - confirm?: Parameters[0]['confirm'] + confirm: (preview: ExtensionTaskCleanupPreview, signal: AbortSignal) => Promise }): Promise { if (this.#active) throw new Error('EXTENSION_TASK_CLEANUP_BUSY') options.assertCurrent() - const operation: ExtensionTaskCleanupOperation = { id: randomUUID(), extensionId: options.extensionId, menuId: options.menuId, phase: 'scanning', total: null, processed: 0, deleted: 0, pending: 0, failed: 0, skipped: 0, errorCode: null } - this.#operations.set(options.extensionId, { ...operation }) const hidden = new AbortController() const signal = AbortSignal.any([options.signal, hidden.signal]) + let progress: ExtensionTaskCleanupProgress = { phase: 'scanning', total: null, processed: 0, deleted: 0, pending: 0, failed: 0, skipped: 0, errorCode: null } let delivery = Promise.resolve() - const publish = (progress: ExtensionTaskCleanupProgress) => { - delivery = Promise.resolve().then(() => options.progress?.(progress)).then(() => {}, () => {}) + const publish = (value: ExtensionTaskCleanupProgress) => { + delivery = Promise.resolve().then(() => options.progress?.(value)).then(() => {}, () => {}) return delivery } let finishHidden!: (result: ExtensionTaskCleanupBatchResult) => void @@ -76,75 +42,82 @@ export class ExtensionTaskCleanupController { throw new Error('EXTENSION_TASK_CLEANUP_EXPIRED') } const active: ActiveCleanup = { - operation, - assertCurrent, + extensionId: options.extensionId, confirmed: false, - cancel: () => { - operation.phase = 'cancelled' - operation.errorCode = null - this.#operations.set(options.extensionId, { ...operation }) - this.#active = undefined + cancel: (expired = false) => { + if (active.confirmed || hidden.signal.aborted) + return + progress = { ...progress, phase: expired ? 'failed' : 'cancelled', errorCode: expired ? 'EXTENSION_TASK_CLEANUP_EXPIRED' : null } + if (this.#active === active) + this.#active = undefined hidden.abort() - const { id: _id, extensionId: _extensionId, menuId: _menuId, ...summary } = operation - finishHidden({ status: 'cancelled', results: [], summary }) + finishHidden({ status: expired ? 'completed' : 'cancelled', results: [], summary: { ...progress } }) }, } this.#active = active + let finishExpired!: () => void + const expired = new Promise((resolve) => { + finishExpired = resolve + }) + const expire = () => { + active.cancel(true) + finishExpired() + } + options.signal.addEventListener('abort', expire, { once: true }) + if (options.signal.aborted) + expire() try { const result = await Promise.race([hiddenResult, runExtensionTaskCleanupBatch({ cleanup: options.cleanup, assertCurrent, - progress: (progress) => { + progress: (value) => { if (hidden.signal.aborted) return - Object.assign(operation, progress) - this.#operations.set(options.extensionId, { ...operation }) - return publish(progress) + progress = { ...value } + return publish(value) }, - confirm: (count, check) => new Promise((resolve, reject) => { - const notify = () => this.changed(options.extensionId) - const abort = () => { - try { - assertCurrent() - } - catch (error) { - finish(false, error) - } - } + confirm: preview => new Promise((resolve, reject) => { let settled = false - let announced = false + const abort = () => finish(false, new Error('EXTENSION_TASK_CLEANUP_EXPIRED')) function finish(confirmed: boolean, error?: unknown) { if (settled) return settled = true - active.decide = undefined signal.removeEventListener('abort', abort) - active.confirmed = !error && confirmed - if (announced) - notify() - if (error) + if (error) { reject(error) - else resolve(confirmed) + return + } + try { + assertCurrent() + if (typeof confirmed !== 'boolean') + throw new Error('EXTENSION_INVALID_ARGUMENT') + active.confirmed = confirmed === true + resolve(confirmed) + } + catch (error) { reject(error) } } - active.decide = confirmed => finish(confirmed) signal.addEventListener('abort', abort, { once: true }) if (signal.aborted) { abort() return } - announced = true - this.changed(options.extensionId) - if (options.confirm) - void options.confirm(count, check).then(value => finish(value), error => finish(false, error)) + Promise.resolve().then(() => { + assertCurrent() + return options.confirm(preview, signal) + }).then(value => finish(value), error => finish(false, error)) }), })]) - if (hidden.signal.aborted) { - await delivery - await publish(result.summary) + if (hidden.signal.aborted && !options.signal.aborted) { + await Promise.race([expired, delivery.then(() => { + if (!options.signal.aborted) + return publish(result.summary) + })]) } return result } finally { + options.signal.removeEventListener('abort', expire) if (this.#active === active) this.#active = undefined } diff --git a/apps/buddy/platform/extensions/__tests__/ExtensionCardActions.spec.ts b/apps/buddy/platform/extensions/__tests__/ExtensionCardActions.spec.ts index 64f06e4f1..96d67f1ab 100644 --- a/apps/buddy/platform/extensions/__tests__/ExtensionCardActions.spec.ts +++ b/apps/buddy/platform/extensions/__tests__/ExtensionCardActions.spec.ts @@ -1,8 +1,9 @@ +import type { ExtensionTaskCleanupPreview } from '../../../shared/extensions/extensionTaskCleanup' import type { JsonValue } from '../../../shared/workbench/workbenchState' -import type { ExtensionServicePorts } from '../ExtensionService' +import { randomUUID } from 'node:crypto' import { rm } from 'node:fs/promises' import { deferred } from '@buddy-tests/deferred' -import { afterEach, expect, it } from 'vitest' +import { afterEach, expect, it, vi } from 'vitest' import { EXTENSION_API_VERSION } from '../../../shared/extensions/extensionManifest' import { ExtensionService } from '../ExtensionService' import { createStore, manifest, reviewPackage } from './fixtures' @@ -12,21 +13,26 @@ afterEach(async () => { for (const dispose of disposers.splice(0).reverse()) await dispose() }) -async function fixture(confirmBatch: NonNullable['confirmBatch']> | null = async () => true) { +async function fixture(confirm: (preview: ExtensionTaskCleanupPreview, signal: AbortSignal) => Promise = async () => true) { const { root, store } = await createStore() disposers.push(() => rm(root, { recursive: true, force: true })) const definition = manifest({ apiVersion: EXTENSION_API_VERSION, permissions: { legacyTaskCleanup: true }, contributes: { commands: [{ id: 'tests.reader.cleanup', title: 'Cleanup' }], + views: [{ id: 'tests.reader.page', title: 'Cleanup', entry: 'view.js', location: 'page', resource: 'none' }], menus: [{ id: 'tests.reader.action', command: 'tests.reader.cleanup', target: 'extension.actions' }], } }) await store.install((await reviewPackage(root, store, definition)).token) - await store.install((await reviewPackage(root, store, manifest({ id: 'tests.peer', contributes: { commands: [{ id: 'tests.peer.noop', title: 'Peer' }] } }))).token) + await store.install((await reviewPackage(root, store, manifest({ id: 'tests.peer', contributes: { + commands: [{ id: 'tests.peer.noop', title: 'Peer' }], + views: [{ id: 'tests.peer.page', title: 'Peer', entry: 'view.js', location: 'page', resource: 'none' }], + } }))).token) let broker!: (method: string, params: unknown) => Promise const deleted: { conversationId: string, expectedRevision: number }[] = [] let genericChanges = 0 let hostGeneration = 0 const progressMessages: { extensionId: string, generation: number, params: Record }[] = [] - let onProgress = async (_params: Record) => {} + const cancelledTokens: JsonValue[] = [] + let onProgress = async (_params: Record, _signal: AbortSignal) => {} let capturedToken: string | null = null let onCommand = async (params: Record): Promise => { capturedToken = typeof params.cleanupToken === 'string' ? params.cleanupToken : null @@ -39,21 +45,25 @@ async function fixture(confirmBatch: NonNullable { + return { call: async (method, params, signal) => { if (method === 'activate') return { commands: pkg.manifest.contributes.commands.map(item => item.id) } if (method === 'command') return pkg.manifest.id === definition.id ? onCommand(params as Record) : null + if (method === 'taskCleanup.confirm') + return confirm((params as unknown as { preview: ExtensionTaskCleanupPreview }).preview, signal!) + if (method === 'taskCleanup.cancel') + cancelledTokens.push((params as Record).token!) if (method === 'taskCleanup.progress') { const input = params as Record progressMessages.push({ extensionId: pkg.manifest.id, generation, params: input }) - await onProgress(input) + await onProgress(input, signal!) } return null }, dispose: async () => {}, devtools: () => {} } }, changed: () => { genericChanges++ }, - createView: () => { throw new Error('NO_VIEW') }, + createView: () => ({ token: randomUUID(), url: 'lexora-extension://fixture/__view.html', dispose: () => {} }), workbench: async () => null, readText: async () => '', get: async () => new Response(''), @@ -63,14 +73,12 @@ async function fixture(confirmBatch: NonNullable { throw new Error('NO_VIEW') }, - ...(confirmBatch ? { confirmBatch } : {}), }, }) disposers.push(() => service.dispose()) await service.restart(definition.id) await service.execute(definition.id, 'tests.reader.cleanup', null) - return { service, deleted, progressMessages, onProgress: (handler: typeof onProgress) => { + return { service, deleted, progressMessages, cancelledTokens, onProgress: (handler: typeof onProgress) => { onProgress = handler }, genericChanges: () => genericChanges, broker: (method: string, params: unknown) => broker(method, params), token: () => capturedToken, onCommand: (handler: typeof onCommand) => { onCommand = handler @@ -78,14 +86,14 @@ async function fixture(confirmBatch: NonNullable { - const counts: number[] = [] - const f = await fixture(async (count) => { - counts.push(count) + const previews: ExtensionTaskCleanupPreview[] = [] + const f = await fixture(async (preview) => { + previews.push(preview) return true }) expect((await f.service.list())[0]?.registeredCommands).toEqual(['tests.reader.cleanup']) expect(await f.run()).toMatchObject({ taskCleanup: { status: 'completed', results: [{ conversationId: 'legacy', expectedRevision: 8, status: 'deleted' }], summary: { phase: 'completed', total: 1, processed: 1, deleted: 1, pending: 0 } } }) - expect(counts).toEqual([1]) + expect(previews).toEqual([{ total: 1, skipped: 0 }]) expect(f.deleted).toEqual([{ conversationId: 'legacy', expectedRevision: 8 }]) await expect(f.broker('taskCleanup.run', { token: f.token() })).rejects.toThrow('EXTENSION_METHOD_DENIED') }) @@ -148,114 +156,114 @@ it('revokes confirmation when the plugin is disabled and hides disposed commands await expect(second.run()).rejects.toThrow('EXTENSION_COMMAND_UNAVAILABLE') }) -it('publishes host confirmation and durable summaries independently of plugin return values', async () => { - const f = await fixture(null) - const started = deferred() - const subscription = f.service.onDidChange((change) => { - if (change.kind === 'task-cleanup') - started.resolve() - }) - const initialChanges = f.genericChanges() - const result = f.run() - await started.promise - const operation = f.service.taskCleanupConfirmations()[0]! - expect(operation).toEqual({ id: expect.any(String), total: 1, skipped: 0, extensionId: 'tests.reader' }) - expect((await f.service.list())[0]).not.toHaveProperty('taskCleanup') - expect(f.deleted).toEqual([]) - await expect(f.service.confirmTaskCleanup('tests.reader', 'old-operation', true)).rejects.toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - await f.service.confirmTaskCleanup('tests.reader', operation.id, true) - expect(await result).toMatchObject({ taskCleanup: { summary: { phase: 'completed', processed: 1, total: 1, deleted: 1, pending: 0 } } }) - expect(f.service.taskCleanupConfirmations()).toEqual([]) - expect(f.genericChanges()).toBe(initialChanges + 2) - subscription.dispose() -}) - -it.each(['disable', 'dispose', 'reset'] as const)('releases deferred host confirmation on %s with no late approval', async (action) => { - const f = await fixture(null) - const started = deferred() - const subscription = f.service.onDidChange((change) => { - if (change.kind === 'task-cleanup') - started.resolve() +it.each(['disable', 'dispose', 'reset'] as const)('releases plugin confirmation on %s with no late approval', async (action) => { + const answer = deferred() + const started = deferred() + const f = await fixture(async (_preview, signal) => { + started.resolve(signal) + return answer.promise }) const run = f.run() const rejected = expect(run).rejects.toThrow('EXTENSION_HOST_STOPPED') - await started.promise - const operation = f.service.taskCleanupConfirmations()[0]! + const signal = await started.promise if (action === 'disable') await f.service.enable('tests.reader', false) else if (action === 'dispose') await f.service.dispose() else await f.service.resetHosts() await rejected + expect(signal.aborted).toBe(true) + expect(f.cancelledTokens).toEqual([f.token()]) + answer.resolve(true) + await Promise.resolve() + expect(f.deleted).toEqual([]) +}) + +it.each([false, 'true', 1, null] as const)('fails closed for confirmation response %s', async (response) => { + const f = await fixture(async () => response) + expect(await f.run()).toMatchObject({ taskCleanup: { results: [], summary: { phase: response === false ? 'cancelled' : 'failed', processed: 0 } } }) + expect(f.deleted).toEqual([]) +}) + +it('fails closed when confirmation throws', async () => { + const f = await fixture(async () => { + throw new Error('EXTENSION_OPERATION_FAILED') + }) + expect(await f.run()).toMatchObject({ taskCleanup: { results: [], summary: { phase: 'failed', processed: 0 } } }) expect(f.deleted).toEqual([]) - await expect(f.service.confirmTaskCleanup('tests.reader', operation.id, true)).rejects.toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - expect(f.service.taskCleanupConfirmations()).toEqual([]) - subscription.dispose() }) it('does not mint a cleanup token when the window hides during command activation', async () => { - const f = await fixture(null) + const f = await fixture() const run = f.run() f.service.cancelUnconfirmedTaskCleanup() expect(await run).toBeNull() expect(f.token()).toBeNull() expect(f.deleted).toEqual([]) - expect(f.service.taskCleanupConfirmations()).toEqual([]) }) -it('revokes an unused token on hide before a delayed plugin starts cleanup', async () => { - const f = await fixture(null) +it.each(['hide', 'close-view', 'close-other-view'] as const)('scopes unused token revocation on %s before a delayed plugin starts cleanup', async (action) => { + const f = await fixture() + const extensionId = action === 'close-other-view' ? 'tests.peer' : 'tests.reader' + const view = await f.service.openView({ viewId: randomUUID(), extensionId, viewType: `${extensionId}.page`, resource: null, state: null, stateVersion: 1 }) const entered = deferred() const resume = deferred() f.onCommand(async (params) => { expect(typeof params.cleanupToken).toBe('string') entered.resolve() await resume.promise - await expect(f.broker('taskCleanup.run', { token: params.cleanupToken })).rejects.toThrow('EXTENSION_METHOD_DENIED') + const cleanup = f.broker('taskCleanup.run', { token: params.cleanupToken }) + if (action === 'close-other-view') + await expect(cleanup).resolves.toMatchObject({ summary: { phase: 'completed', deleted: 1 } }) + else await expect(cleanup).rejects.toThrow('EXTENSION_METHOD_DENIED') return null }) const run = f.run() await entered.promise - f.service.cancelUnconfirmedTaskCleanup() + if (action === 'hide') + f.service.cancelUnconfirmedTaskCleanup() + else f.service.closeView(view.id, view.generation, view.token) resume.resolve() - expect(await run).toBeNull() - expect(f.deleted).toEqual([]) - expect(f.service.taskCleanupConfirmations()).toEqual([]) + if (action === 'close-other-view') + expect(await run).toMatchObject({ taskCleanup: { summary: { phase: 'completed', deleted: 1 } } }) + else expect(await run).toBeNull() + expect(f.deleted).toEqual(action === 'close-other-view' ? [{ conversationId: 'legacy', expectedRevision: 8 }] : []) }) -it('returns a cancelled host result on hide and accepts a fresh explicitly confirmed invocation', async () => { - const f = await fixture(null) - let started = deferred() - const subscription = f.service.onDidChange((change) => { - if (change.kind === 'task-cleanup') - started.resolve() +it.each(['hide', 'close-view'] as const)('cancels on %s and accepts a fresh invocation without reviving late confirmation', async (action) => { + const started = deferred() + const answer = deferred() + let calls = 0 + const f = await fixture(async (_preview, signal) => { + if (++calls > 1) + return true + started.resolve(signal) + return answer.promise }) + const view = await f.service.openView({ viewId: randomUUID(), extensionId: 'tests.reader', viewType: 'tests.reader.page', resource: null, state: null, stateVersion: 1 }) const first = f.run() - await started.promise - const previous = f.service.taskCleanupConfirmations()[0]! - expect(previous.total).toBe(1) - f.service.cancelUnconfirmedTaskCleanup() + const signal = await started.promise + const previous = f.token() + if (action === 'hide') + f.service.cancelUnconfirmedTaskCleanup() + else f.service.closeView(view.id, view.generation, view.token) expect(await first).toMatchObject({ taskCleanup: { status: 'cancelled', results: [], summary: { phase: 'cancelled', processed: 0 } } }) - expect(f.service.taskCleanupConfirmations()).toEqual([]) + expect(signal.aborted).toBe(true) + expect(f.cancelledTokens).toEqual([previous]) expect(f.deleted).toEqual([]) - started = deferred() - const second = f.run() - await started.promise - const current = f.service.taskCleanupConfirmations()[0]! - expect(current.id).not.toBe(previous.id) - await expect(f.service.confirmTaskCleanup('tests.reader', previous.id, true)).rejects.toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - await f.service.confirmTaskCleanup('tests.reader', current.id, true) - await second + answer.resolve(true) + await expect(f.broker('taskCleanup.run', { token: previous })).rejects.toThrow('EXTENSION_METHOD_DENIED') + await f.run() + expect(f.token()).not.toBe(previous) expect(f.deleted).toEqual([{ conversationId: 'legacy', expectedRevision: 8 }]) - subscription.dispose() }) it('invalidates a confirmation if the plugin stops awaiting its invocation', async () => { - const f = await fixture(null) - const started = deferred() - const subscription = f.service.onDidChange((change) => { - if (change.kind === 'task-cleanup') - started.resolve() + const started = deferred() + const answer = deferred() + const f = await fixture(async (_preview, signal) => { + started.resolve(signal) + return answer.promise }) let cleanupResult: Promise | undefined f.onCommand(async (params) => { @@ -266,12 +274,12 @@ it('invalidates a confirmation if the plugin stops awaiting its invocation', asy }) await f.run() await expect(cleanupResult).resolves.toMatchObject({ summary: { phase: 'failed', errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED', processed: 0, deleted: 0 } }) - expect(f.service.taskCleanupConfirmations()).toEqual([]) + expect((await started.promise).aborted).toBe(true) + answer.resolve(true) expect(f.deleted).toEqual([]) - subscription.dispose() }) -it('pushes ordered bounded progress only to the initiating token and generation, without catalog progress refreshes', async () => { +it('pushes bounded progress only to the initiating token and generation', async () => { const f = await fixture() await f.service.execute('tests.peer', 'tests.peer.noop', null) const before = f.genericChanges() @@ -287,11 +295,10 @@ it('pushes ordered bounded progress only to the initiating token and generation, await entered.promise expect(f.progressMessages).toHaveLength(1) expect(f.deleted).toEqual([]) - expect(f.genericChanges()).toBe(before) release.resolve() const result = await run as { taskCleanup: { summary: JsonValue } } expect(f.progressMessages.at(-1)!.params.progress).toEqual(result.taskCleanup.summary) - expect(f.genericChanges()).toBe(before + 2) + expect(f.genericChanges()).toBe(before) expect(new Set(f.progressMessages.map(item => item.generation)).size).toBe(1) const previous = f.progressMessages[0]! for (const message of f.progressMessages) { @@ -318,5 +325,61 @@ it('does not submit deletion after progress delivery becomes unavailable', async expect(await f.run()).toMatchObject({ taskCleanup: { results: [], summary: { phase: 'failed', total: null, processed: 0, errorCode: 'EXTENSION_TASK_CLEANUP_UNAVAILABLE' } } }) expect(f.progressMessages).toHaveLength(1) expect(f.deleted).toEqual([]) - expect(f.service.taskCleanupConfirmations()).toEqual([]) +}) + +it('does not impose the progress ACK timeout on confirmation', async () => { + const started = deferred() + const answer = deferred() + const f = await fixture(async (_preview, signal) => { + started.resolve(signal) + return answer.promise + }) + vi.useFakeTimers() + const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => { + const abort = new AbortController() + setTimeout(() => abort.abort(), ms) + return abort.signal + }) + try { + const run = f.run() + const signal = await started.promise + await vi.advanceTimersByTimeAsync(6000) + expect(signal.aborted).toBe(false) + expect(f.deleted).toEqual([]) + answer.resolve(true) + expect(await run).toMatchObject({ taskCleanup: { summary: { phase: 'completed', deleted: 1 } } }) + } + finally { + timeout.mockRestore() + vi.useRealTimers() + } +}) + +it('stops before deletion when a progress ACK exceeds five seconds', async () => { + const entered = deferred() + const f = await fixture() + f.onProgress(async (_params, signal) => { + entered.resolve() + return new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => reject(new Error('EXTENSION_REQUEST_TIMEOUT')), { once: true }) + }) + }) + vi.useFakeTimers() + const timeout = vi.spyOn(AbortSignal, 'timeout').mockImplementation((ms) => { + const abort = new AbortController() + setTimeout(() => abort.abort(), ms) + return abort.signal + }) + try { + const run = f.run() + await entered.promise + expect(timeout).toHaveBeenCalledWith(5000) + await vi.advanceTimersByTimeAsync(5000) + expect(await run).toMatchObject({ taskCleanup: { results: [], summary: { phase: 'failed', errorCode: 'EXTENSION_TASK_CLEANUP_UNAVAILABLE' } } }) + expect(f.deleted).toEqual([]) + } + finally { + timeout.mockRestore() + vi.useRealTimers() + } }) diff --git a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanup.spec.ts b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanup.spec.ts index e25e93061..61880e3e2 100644 --- a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanup.spec.ts +++ b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanup.spec.ts @@ -1,9 +1,6 @@ -import type { ExtensionTaskCleanupDelete, ExtensionTaskCleanupResult } from '../../../shared/extensions/extensionTaskCleanup' import type { JsonValue } from '../../../shared/workbench/workbenchState' -import type { ExtensionServicePorts } from '../ExtensionService' import { randomUUID } from 'node:crypto' import { rm } from 'node:fs/promises' -import { deferred } from '@buddy-tests/deferred' import { afterEach, expect, it } from 'vitest' import { addedExtensionPermissions, extensionManifestSchema, extensionPermissionsSchema } from '../../../shared/extensions/extensionManifest' import { ExtensionService } from '../ExtensionService' @@ -16,7 +13,7 @@ afterEach(async () => { const target = { conversationId: 'legacy-task', expectedRevision: 4 } const item = { ...target, title: 'Legacy task', removedAt: '2026-01-01T00:00:00Z', estimatedBytes: null, canDelete: true, blockedReason: null } -async function fixture(permission = true, confirmation: NonNullable['confirmDelete'] = async () => true, execute?: (input: ExtensionTaskCleanupDelete) => Promise) { +async function fixture(permission = true) { const { root, store } = await createStore() cleanups.push(() => rm(root, { recursive: true, force: true })) const definition = manifest({ apiVersion: 4, permissions: { legacyTaskCleanup: permission }, contributes: { views: [{ id: 'tests.reader.page', title: 'Cleanup', entry: 'view.js', location: 'page', resource: 'none' }] } }) @@ -34,13 +31,12 @@ async function fixture(permission = true, confirmation: NonNullable new Response(''), taskCleanup: { list: async () => ({ items: records, nextCursor: null }), - delete: execute ?? (async (input) => { + delete: async (input) => { if (input.expectedRevision !== item.expectedRevision) throw new Error('CONVERSATION_REVISION_CONFLICT') records.splice(0) return { status: 'deleted' } - }), - confirmDelete: confirmation, + }, }, }) cleanups.push(() => service.dispose()) @@ -69,40 +65,10 @@ it('requires an explicitly reviewed permission and denies background access', as expect(allowed.records).toEqual([item]) }) -it('exposes only the bounded metadata page and accepts exact confirmed targets', async () => { +it('denies legacy view list and delete even with permission and a valid revision', async () => { const f = await fixture() - expect(await f.request('taskCleanup.list', { limit: 50 })).toEqual({ items: [item], nextCursor: null }) - for (const input of [{ kind: 'archived' }, { limit: 101 }, { path: '/tmp' }]) - await expect(f.request('taskCleanup.list', input)).rejects.toThrow('EXTENSION_INVALID_ARGUMENT') - for (const input of [{ conversationId: 'legacy-task' }, { ...target, kind: 'archived' }, { ...target, path: '/tmp' }]) - await expect(f.request('taskCleanup.delete', input)).rejects.toThrow('EXTENSION_INVALID_ARGUMENT') - expect(f.records).toEqual([item]) - expect(await f.request('taskCleanup.delete', target)).toEqual({ status: 'deleted' }) - expect(f.records).toEqual([]) -}) - -it('does not delete after cancellation or a stale revision', async () => { - const cancelled = await fixture(true, async () => false) - await expect(cancelled.request('taskCleanup.delete', target)).rejects.toThrow('EXTENSION_TASK_CLEANUP_CANCELLED') - expect(cancelled.records).toEqual([item]) - const stale = await fixture() - await expect(stale.request('taskCleanup.delete', { ...target, expectedRevision: 3 })).rejects.toThrow('CONVERSATION_REVISION_CONFLICT') - expect(stale.records).toEqual([item]) -}) - -it('revokes a pending confirmation when its view closes', async () => { - const confirmed = deferred() - const started = deferred() - const f = await fixture(true, async () => { - started.resolve() - return confirmed.promise - }) - const result = f.request('taskCleanup.delete', target) - const rejected = expect(result).rejects.toThrow('EXTENSION_VIEW_EXPIRED') - await started.promise - f.service.closeView(f.view.id, f.view.generation, f.view.token) - confirmed.resolve(true) - await rejected + await expect(f.request('taskCleanup.list', { limit: 50 })).rejects.toThrow('EXTENSION_METHOD_DENIED') + await expect(f.request('taskCleanup.delete', target)).rejects.toThrow('EXTENSION_METHOD_DENIED') expect(f.records).toEqual([item]) }) @@ -113,22 +79,3 @@ it('revokes the old session after uninstall', async () => { await expect(f.request('taskCleanup.delete', target)).rejects.toThrow('EXTENSION_VIEW_EXPIRED') expect(f.records).toEqual([item]) }) - -it('does not cancel a core deletion already accepted when the view closes', async () => { - const accepted = deferred() - const complete = deferred() - const deleted: string[] = [] - const f = await fixture(true, async () => true, async (input) => { - accepted.resolve() - await complete.promise - deleted.push(input.conversationId) - return { status: 'deleted' } - }) - const result = f.request('taskCleanup.delete', target) - const rejected = expect(result).rejects.toThrow('EXTENSION_VIEW_EXPIRED') - await accepted.promise - f.service.closeView(f.view.id, f.view.generation, f.view.token) - complete.resolve() - await rejected - expect(deleted).toEqual(['legacy-task']) -}) diff --git a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupBatch.spec.ts b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupBatch.spec.ts index 978844836..df664860c 100644 --- a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupBatch.spec.ts +++ b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupBatch.spec.ts @@ -24,8 +24,8 @@ it('reads all pages before one confirmation and freezes every target and revisio return { status: records.find(item => item.conversationId === input.conversationId)?.expectedRevision === input.expectedRevision ? 'deleted' : 'failed' } }, }, - confirm: async (count) => { - expect(count).toBe(205) + confirm: async (preview) => { + expect(preview).toEqual({ total: 205, skipped: 0 }) expect(reads).toEqual([0, 100, 200]) records[0]!.expectedRevision = 8 records.push(item('late-task')) @@ -38,56 +38,20 @@ it('reads all pages before one confirmation and freezes every target and revisio expect(deletes.some(item => item.conversationId === 'late-task')).toBe(false) }) -it('does not submit jobs on cancellation or incomplete reads', async () => { - const deleted: string[] = [] - const result = await runExtensionTaskCleanupBatch({ assertCurrent: () => {}, confirm: async () => false, cleanup: { - list: async () => ({ items: [item('cancelled')], nextCursor: null }), - delete: async (target) => { - deleted.push(target.conversationId) - return { status: 'deleted' } - }, - } }) - expect(result).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled', total: 1, processed: 0 } }) - await expect(runExtensionTaskCleanupBatch({ assertCurrent: () => {}, confirm: async () => { - throw new Error('MUST_NOT_CONFIRM') - }, cleanup: { - list: async ({ cursor }) => { - if (cursor) - throw new Error('READ_FAILED') - return { items: [item('partial')], nextCursor: 'next' } - }, - delete: async (target) => { - deleted.push(target.conversationId) - return { status: 'deleted' } - }, - } })).resolves.toMatchObject({ status: 'completed', results: [], summary: { phase: 'failed', total: null, processed: 0 } }) - expect(deleted).toEqual([]) -}) - -it('reports failed and pending items separately without refreshing CAS or retrying', async () => { - const calls: string[] = [] - const result = await runExtensionTaskCleanupBatch({ assertCurrent: () => {}, confirm: async () => true, cleanup: { - list: async () => ({ items: [item('failed'), item('pending'), item('deleted'), { ...item('busy'), canDelete: false }], nextCursor: null }), - delete: async ({ conversationId }) => { - calls.push(conversationId) - if (conversationId === 'failed') - throw new Error('SOURCE_CHANGED') - return { status: conversationId === 'pending' ? 'pending' : 'deleted' } - }, - } }) - expect(calls).toEqual(['failed', 'pending', 'deleted']) - expect(result.results.map(item => item.status)).toEqual(['failed', 'pending', 'deleted']) -}) - -it('publishes unknown totals while scanning and real processed counts including failures', async () => { +it('publishes real progress and distinct outcomes without retrying failed or blocked targets', async () => { const snapshots: ExtensionTaskCleanupProgress[] = [] + const calls: string[] = [] const result = await runExtensionTaskCleanupBatch({ assertCurrent: () => {}, progress: progress => snapshots.push(progress), - confirm: async () => true, + confirm: async (preview) => { + expect(preview).toEqual({ total: 3, skipped: 1 }) + return true + }, cleanup: { list: async ({ cursor }) => ({ items: cursor ? [item('deleted'), item('failed'), item('pending')] : [{ ...item('blocked'), canDelete: false }], nextCursor: cursor ? null : 'next' }), delete: async ({ conversationId }) => { + calls.push(conversationId) if (conversationId === 'failed') throw new Error('EXTENSION_TASK_CLEANUP_SOURCE_CHANGED') return { status: conversationId === 'pending' ? 'pending' : 'deleted' } @@ -97,7 +61,8 @@ it('publishes unknown totals while scanning and real processed counts including expect(snapshots.filter(item => item.phase === 'scanning').every(item => item.total === null && item.processed === 0)).toBe(true) expect(snapshots.filter(item => item.phase === 'running').map(item => item.processed)).toEqual([0, 1, 2, 3]) expect(snapshots.at(-1)).toEqual({ phase: 'failed', total: 3, processed: 3, deleted: 1, pending: 1, failed: 1, skipped: 1, errorCode: 'EXTENSION_TASK_CLEANUP_SOURCE_CHANGED' }) - expect(result.results).toHaveLength(3) + expect(calls).toEqual(['deleted', 'failed', 'pending']) + expect(result.results.map(item => item.status)).toEqual(['deleted', 'failed', 'pending']) }) it('keeps an incomplete scan unknown and never confirms a partial target set', async () => { diff --git a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupController.spec.ts b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupController.spec.ts index 3c1d9f5dd..4d63c4cf3 100644 --- a/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupController.spec.ts +++ b/apps/buddy/platform/extensions/__tests__/ExtensionTaskCleanupController.spec.ts @@ -1,23 +1,19 @@ -import type { ExtensionTaskCleanupOperation } from '../../../shared/extensions/extensionTaskCleanup' +import type { ExtensionTaskCleanupPreview } from '../../../shared/extensions/extensionTaskCleanup' import { deferred } from '@buddy-tests/deferred' -import { expect, it, vi } from 'vitest' +import { expect, it } from 'vitest' import { ExtensionTaskCleanupController } from '../ExtensionTaskCleanupController' const item = { conversationId: 'legacy', expectedRevision: 1, title: null, removedAt: '2026-01-01', estimatedBytes: null, canDelete: true, blockedReason: null } function fixture() { - const snapshots: ExtensionTaskCleanupOperation[] = [] - const confirming = deferred() - const changes: number[] = [] - const controller = new ExtensionTaskCleanupController(() => { - changes.push(controller.confirmations().length) - if (controller.confirmations().length) - confirming.resolve() - }) + const confirming = deferred<{ preview: ExtensionTaskCleanupPreview, signal: AbortSignal }>() + const answer = deferred() + const controller = new ExtensionTaskCleanupController() const abort = new AbortController() const deleted: string[] = [] - const options = { extensionId: 'test.cleanup', menuId: 'test.cleanup.menu', signal: abort.signal, assertCurrent: () => {}, progress: () => { - snapshots.push(controller.snapshot('test.cleanup')!) + const options = { extensionId: 'test.cleanup', signal: abort.signal, assertCurrent: () => {}, confirm: async (preview: ExtensionTaskCleanupPreview, signal: AbortSignal) => { + confirming.resolve({ preview, signal }) + return answer.promise }, cleanup: { list: async () => ({ items: [item], nextCursor: null }), delete: async ({ conversationId }: { conversationId: string }) => { @@ -25,65 +21,47 @@ function fixture() { return { status: 'pending' as const } }, } } - return { controller, snapshots, changes, confirming, abort, deleted, options } + return { controller, confirming, answer, abort, deleted, options } } -it('requires the exact current operation and rejects duplicate batches across extensions', async () => { +it('allows only one batch and returns real pending receipts after plugin confirmation', async () => { const f = fixture() const run = f.controller.run(f.options) - await f.confirming.promise - const operation = f.controller.snapshot('test.cleanup')! - expect(operation).toMatchObject({ phase: 'confirming', total: 1, processed: 0, menuId: 'test.cleanup.menu' }) + expect((await f.confirming.promise).preview).toEqual({ total: 1, skipped: 0 }) await expect(f.controller.run(f.options)).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') - await expect(f.controller.run({ ...f.options, extensionId: 'other.cleanup' })).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') - expect(() => f.controller.confirm('other.cleanup', operation.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - expect(() => f.controller.confirm('test.cleanup', 'old-operation', true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - f.controller.confirm('test.cleanup', operation.id, true) - expect(() => f.controller.confirm('test.cleanup', operation.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - await run - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'completed', total: 1, processed: 1, pending: 1, deleted: 0 }) - expect(f.snapshots.filter(item => item.phase === 'running').map(item => item.processed)).toEqual([0, 1]) - expect(f.deleted).toEqual(['legacy']) - expect(f.changes).toEqual([1, 0]) - expect(f.controller.confirmations()).toEqual([]) - expect(() => f.controller.confirm('test.cleanup', operation.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - const next = f.controller.run(f.options) - await vi.waitFor(() => expect(f.controller.confirmations()).toHaveLength(1)) - const latest = f.controller.snapshot('test.cleanup')! - expect(latest.id).not.toBe(operation.id) - expect(() => f.controller.confirm('test.cleanup', operation.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - f.controller.confirm('test.cleanup', latest.id, false) - await next - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'cancelled', processed: 0, pending: 0, deleted: 0 }) + f.controller.cancelUnconfirmed('other.plugin') + expect((await f.confirming.promise).signal.aborted).toBe(false) + f.answer.resolve(true) + expect(await run).toMatchObject({ summary: { phase: 'completed', total: 1, processed: 1, pending: 1, deleted: 0 } }) expect(f.deleted).toEqual(['legacy']) + expect(await f.controller.run({ ...f.options, confirm: async () => false })).toMatchObject({ status: 'cancelled', results: [] }) }) -it('cancels with zero submissions and snapshots cannot mutate host state', async () => { - const f = fixture() - const run = f.controller.run(f.options) - await f.confirming.promise - const snapshot = f.controller.snapshot('test.cleanup')! - snapshot.total = 2000 - f.controller.confirm('test.cleanup', snapshot.id, false) - expect(await run).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled', total: 1, processed: 0 } }) - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'cancelled', total: 1, processed: 0 }) - expect(f.deleted).toEqual([]) -}) - -it('releases unanswered confirmation on invalidation without submitting anything', async () => { +it.each(['hide', 'abort'] as const)('releases unanswered confirmation on %s and ignores late true', async (action) => { const f = fixture() const run = f.controller.run(f.options) - const rejected = expect(run).resolves.toMatchObject({ summary: { phase: 'failed', errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' } }) - await f.confirming.promise - const operation = f.controller.snapshot('test.cleanup')! - f.abort.abort() - await rejected - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'failed', total: 1, processed: 0, errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' }) - expect(() => f.controller.confirm('test.cleanup', operation.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') + const { signal } = await f.confirming.promise + if (action === 'hide') + f.controller.cancelUnconfirmed() + else f.abort.abort() + expect(signal.aborted).toBe(true) + expect(await run).toMatchObject({ results: [], summary: { phase: action === 'hide' ? 'cancelled' : 'failed', processed: 0 } }) + const nextAnswer = deferred() + const nextStarted = deferred() + const next = f.controller.run({ ...f.options, signal: new AbortController().signal, confirm: async () => { + nextStarted.resolve() + return nextAnswer.promise + } }) + await nextStarted.promise + f.answer.resolve(true) + await Promise.resolve() + await expect(f.controller.run(f.options)).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') + nextAnswer.resolve(false) + await next expect(f.deleted).toEqual([]) }) -it('retains accepted job receipts after invalidation without submitting the remaining targets', async () => { +it('retains accepted receipts on invalidation without submitting remaining targets', async () => { const f = fixture() const accepted = deferred() const receipt = deferred<{ status: 'pending' }>() @@ -95,62 +73,98 @@ it('retains accepted job receipts after invalidation without submitting the rema return receipt.promise }, } }) - const rejected = expect(run).resolves.toMatchObject({ summary: { phase: 'failed', total: 2, processed: 1, pending: 1, deleted: 0, errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' }, results: [{ conversationId: 'legacy', status: 'pending' }] }) await f.confirming.promise - f.controller.confirm('test.cleanup', f.controller.snapshot('test.cleanup')!.id, true) + f.answer.resolve(true) await accepted.promise + f.controller.cancelUnconfirmed() f.abort.abort() await expect(f.controller.run({ ...f.options, signal: new AbortController().signal })).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') receipt.resolve({ status: 'pending' }) - await rejected + expect(await run).toMatchObject({ summary: { phase: 'failed', total: 2, processed: 1, pending: 1, deleted: 0, errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' }, results: [{ conversationId: 'legacy', status: 'pending' }] }) expect(f.deleted).toEqual(['legacy']) - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'failed', total: 2, processed: 1, pending: 1, deleted: 0, failed: 0, skipped: 0 }) }) -it('cancels a hidden scan immediately and late reads cannot replace the next operation or release its lock', async () => { +it.each(['hide', 'abort'] as const)('releases a pending scan on %s and late reads cannot release the next operation lock', async (action) => { const f = fixture() + const phases: string[] = [] + const entered = deferred() const page = deferred<{ items: typeof item[], nextCursor: null }>() - const run = f.controller.run({ ...f.options, cleanup: { ...f.options.cleanup, list: () => page.promise } }) - const previous = f.controller.snapshot('test.cleanup')! - expect(previous.phase).toBe('scanning') - f.controller.cancelUnconfirmed() - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ id: previous.id, phase: 'cancelled', total: null, processed: 0 }) - const next = f.controller.run(f.options) - expect(await run).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled' } }) + const run = f.controller.run({ ...f.options, progress: value => phases.push(value.phase), cleanup: { ...f.options.cleanup, list: () => { + entered.resolve() + return page.promise + } } }) + await entered.promise + if (action === 'hide') + f.controller.cancelUnconfirmed() + else f.abort.abort() + const next = f.controller.run({ ...f.options, signal: new AbortController().signal }) + expect(await run).toMatchObject({ status: action === 'hide' ? 'cancelled' : 'completed', results: [], summary: { phase: action === 'hide' ? 'cancelled' : 'failed', total: null, processed: 0, errorCode: action === 'hide' ? null : 'EXTENSION_TASK_CLEANUP_EXPIRED' } }) await f.confirming.promise - const current = f.controller.snapshot('test.cleanup')! - expect(current.id).not.toBe(previous.id) + const previousPhases = [...phases] page.resolve({ items: [item], nextCursor: null }) await Promise.resolve() await Promise.resolve() - expect(f.controller.snapshot('test.cleanup')).toEqual(current) await expect(f.controller.run(f.options)).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') - expect(() => f.controller.confirm('test.cleanup', previous.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - f.controller.confirm('test.cleanup', current.id, false) + f.answer.resolve(false) await next + expect(phases).toEqual(previousPhases) expect(f.deleted).toEqual([]) }) -it('cancels hidden confirmation with zero submissions and permits another batch', async () => { +it.each([false, true])('releases an invalidated scan with pending progress, already hidden: %s', async (hidden) => { const f = fixture() - const run = f.controller.run(f.options) - await f.confirming.promise - const previous = f.controller.snapshot('test.cleanup')! - f.controller.cancelUnconfirmed() - const next = f.controller.run({ ...f.options, confirm: async () => false }) - expect(await run).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled' } }) - expect(() => f.controller.confirm('test.cleanup', previous.id, true)).toThrow('EXTENSION_TASK_CLEANUP_EXPIRED') - expect(await next).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled' } }) - expect(f.controller.snapshot('test.cleanup')!.id).not.toBe(previous.id) + const entered = deferred() + const delivery = deferred() + const phases: string[] = [] + const run = f.controller.run({ ...f.options, progress: async (value) => { + phases.push(value.phase) + entered.resolve() + return delivery.promise + }, cleanup: { ...f.options.cleanup, list: async () => { + throw new Error('MUST_NOT_SCAN') + } } }) + await entered.promise + if (hidden) { + f.controller.cancelUnconfirmed() + await Promise.resolve() + await Promise.resolve() + } + f.abort.abort() + const next = f.controller.run({ ...f.options, signal: new AbortController().signal, confirm: async () => false }) + expect(await run).toMatchObject({ results: [], summary: { phase: hidden ? 'cancelled' : 'failed', processed: 0, errorCode: hidden ? null : 'EXTENSION_TASK_CLEANUP_EXPIRED' } }) + expect(await next).toMatchObject({ status: 'cancelled' }) + delivery.resolve() + await Promise.resolve() + await Promise.resolve() + expect(phases).toEqual(['scanning']) expect(f.deleted).toEqual([]) }) -it.each(['immediately-after-confirmation', 'running'] as const)('continues only the frozen confirmed batch when hidden %s', async (when) => { +it('does not scan or confirm when the original invocation is already aborted', async () => { + const f = fixture() + f.abort.abort() + const calls: string[] = [] + expect(await f.controller.run({ ...f.options, confirm: async () => { + calls.push('confirm') + return true + }, cleanup: { ...f.options.cleanup, list: async () => { + calls.push('list') + return { items: [item], nextCursor: null } + } } })).toMatchObject({ results: [], summary: { phase: 'failed', total: null, processed: 0, errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' } }) + expect(calls).toEqual([]) + expect(f.deleted).toEqual([]) + expect(await f.controller.run({ ...f.options, signal: new AbortController().signal, confirm: async () => false })).toMatchObject({ status: 'cancelled' }) +}) + +it.each(['before-first-delete', 'running'] as const)('continues only frozen confirmed targets when hidden %s', async (when) => { const f = fixture() const accepted = deferred() const receipt = deferred<{ status: 'pending' }>() const records = [item, { ...item, conversationId: 'frozen' }] - const run = f.controller.run({ ...f.options, cleanup: { + const run = f.controller.run({ ...f.options, progress: (progress) => { + if (when === 'before-first-delete' && progress.phase === 'running') + f.controller.cancelUnconfirmed() + }, cleanup: { list: async () => ({ items: records, nextCursor: null }), delete: async ({ conversationId }) => { f.deleted.push(conversationId) @@ -162,43 +176,17 @@ it.each(['immediately-after-confirmation', 'running'] as const)('continues only }, } }) await f.confirming.promise - f.controller.confirm('test.cleanup', f.controller.snapshot('test.cleanup')!.id, true) - if (when === 'running') - await accepted.promise + f.answer.resolve(true) + await accepted.promise f.controller.cancelUnconfirmed() records.push({ ...item, conversationId: 'late-unapproved' }) await expect(f.controller.run(f.options)).rejects.toThrow('EXTENSION_TASK_CLEANUP_BUSY') receipt.resolve({ status: 'pending' }) - await run + expect(await run).toMatchObject({ summary: { phase: 'completed', total: 2, processed: 2, pending: 1, deleted: 1 } }) expect(f.deleted).toEqual(['legacy', 'frozen']) - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'completed', total: 2, processed: 2, pending: 1, deleted: 1 }) -}) - -it('still stops subsequent targets on actual invalidation after hiding an accepted batch', async () => { - const f = fixture() - const accepted = deferred() - const receipt = deferred<{ status: 'pending' }>() - const run = f.controller.run({ ...f.options, cleanup: { - list: async () => ({ items: [item, { ...item, conversationId: 'remaining' }], nextCursor: null }), - delete: async ({ conversationId }) => { - f.deleted.push(conversationId) - accepted.resolve() - return receipt.promise - }, - } }) - const rejected = expect(run).resolves.toMatchObject({ summary: { phase: 'failed', total: 2, processed: 1, pending: 1, deleted: 0, errorCode: 'EXTENSION_TASK_CLEANUP_EXPIRED' } }) - await f.confirming.promise - f.controller.confirm('test.cleanup', f.controller.snapshot('test.cleanup')!.id, true) - await accepted.promise - f.controller.cancelUnconfirmed() - f.abort.abort() - receipt.resolve({ status: 'pending' }) - await rejected - expect(f.deleted).toEqual(['legacy']) - expect(f.controller.snapshot('test.cleanup')).toMatchObject({ phase: 'failed', total: 2, processed: 1, pending: 1, deleted: 0 }) }) -it('finishes hidden progress in order without publishing late scan state over the next operation', async () => { +it('finishes hidden progress in order without late scan notifications', async () => { const f = fixture() const entered = deferred() const release = deferred() @@ -212,12 +200,9 @@ it('finishes hidden progress in order without publishing late scan state over th } }) await entered.promise f.controller.cancelUnconfirmed() - const next = await f.controller.run({ ...f.options, confirm: async () => false }) - const current = f.controller.snapshot('test.cleanup')! - expect(next.summary.phase).toBe('cancelled') + expect((await f.controller.run({ ...f.options, confirm: async () => false })).summary.phase).toBe('cancelled') release.resolve() expect(await run).toMatchObject({ status: 'cancelled', results: [], summary: { phase: 'cancelled', total: null, processed: 0 } }) expect(phases).toEqual(['scanning', 'cancelled']) - expect(f.controller.snapshot('test.cleanup')).toEqual(current) expect(f.deleted).toEqual([]) }) diff --git a/apps/buddy/service/resources/skills/plugin-creator/references/api.d.ts b/apps/buddy/service/resources/skills/plugin-creator/references/api.d.ts index 1865f6db0..3d35b37eb 100644 --- a/apps/buddy/service/resources/skills/plugin-creator/references/api.d.ts +++ b/apps/buddy/service/resources/skills/plugin-creator/references/api.d.ts @@ -429,14 +429,9 @@ export interface SettingsHeaderAction { readonly disabled?: boolean readonly progress?: number | null } -export interface LegacyTaskCleanupItem { - readonly conversationId: string - readonly title: string | null - readonly removedAt: string - readonly expectedRevision: number - readonly estimatedBytes: number | null - readonly canDelete: boolean - readonly blockedReason: string | null +export interface LegacyTaskCleanupPreview { + readonly total: number + readonly skipped: number } export interface LegacyTaskCleanupProgress { readonly phase: 'scanning' | 'confirming' | 'running' | 'completed' | 'cancelled' | 'failed' @@ -451,7 +446,10 @@ export interface LegacyTaskCleanupProgress { readonly errorCode: string | null } export interface LegacyTaskCleanupCommandApi { - run: (options?: { onProgress?: (progress: LegacyTaskCleanupProgress) => void }) => Promise<{ + run: (options: { + confirm: (preview: LegacyTaskCleanupPreview, signal: AbortSignal) => boolean | Promise + onProgress?: (progress: LegacyTaskCleanupProgress) => void + }) => Promise<{ /** @description completed 表示调用结束;成功与否以 summary.phase 为准。进入批次前的授权或不可用错误仍 reject。 */ status: 'cancelled' | 'completed' results: { conversationId: string, expectedRevision: number, status: 'deleted' | 'pending' | 'failed', errorCode?: string }[] @@ -459,12 +457,7 @@ export interface LegacyTaskCleanupCommandApi { summary: LegacyTaskCleanupProgress }> } -export interface LegacyTaskCleanupApi { - list: (input?: { cursor?: string, limit?: number }) => Promise<{ items: LegacyTaskCleanupItem[], nextCursor: string | null }> - delete: (input: { conversationId: string, expectedRevision: number }) => Promise<{ status: 'deleted' | 'pending' | 'failed', errorCode?: string }> -} export interface ViewContext { - readonly taskCleanup: LegacyTaskCleanupApi readonly documents: DocumentApi readonly clipboard: { read: () => Promise<{ text?: string, html?: string }> diff --git a/apps/buddy/service/resources/skills/plugin-creator/references/commands.md b/apps/buddy/service/resources/skills/plugin-creator/references/commands.md index 91ee52e23..f9bebacde 100644 --- a/apps/buddy/service/resources/skills/plugin-creator/references/commands.md +++ b/apps/buddy/service/resources/skills/plugin-creator/references/commands.md @@ -25,7 +25,7 @@ export function activate(context: ExtensionContext) { 每个声明必须在 `activate` 完成前注册一次。未知 ID、重复注册、非函数处理器或缺少注册都会使该插件启动失败;捕获注册错误也不能使错误插件启动。修正后显式重启。 -API 4 插件可通过 `contributes.menus` 的 `extension.actions` 在自身卡片的「插件操作」二级菜单提供命令,无需视图或导航。仅启用、激活成功且仍注册的本插件命令显示;空菜单不显示。点击直接调用,不打开页面;敏感操作仍需宿主确认。依赖分屏、文件或输入内容的命令应在声明中用 `when` 限定对应场景,并在处理函数中校验需要的上下文。候选按前缀显示;选中只插入命令,确认发送才执行。执行严格匹配完整名称和大小写,参数保持为字符串,不自动解析引号、JSON 或自然语言。插件本地命令不依赖模型配置,可以在任务流式输出时执行。只传命令参数与发起分屏,不传输入框附件、引用、会话身份或历史;带这些内容时拒绝执行并保留草稿。命令不可用或失败时也保留草稿,不降级为模型提示。 +API 4 插件可通过 `contributes.menus` 的 `extension.actions` 在自身卡片的「插件操作」二级菜单提供命令,无需视图或导航。仅启用、激活成功且仍注册的本插件命令显示;空菜单不显示。点击直接调用,不自动打开页面;不扩大命令的数据或操作权限。依赖分屏、文件或输入内容的命令应在声明中用 `when` 限定对应场景,并在处理函数中校验需要的上下文。候选按前缀显示;选中只插入命令,确认发送才执行。执行严格匹配完整名称和大小写,参数保持为字符串,不自动解析引号、JSON 或自然语言。插件本地命令不依赖模型配置,可以在任务流式输出时执行。只传命令参数与发起分屏,不传输入框附件、引用、会话身份或历史;带这些内容时拒绝执行并保留草稿。命令不可用或失败时也保留草稿,不降级为模型提示。 `invocation.target` 为 `slash`,`resource` 为 null,`arguments` 为最多 8192 字符的参数字符串。命令面板调用仍提供既有资源语义且参数为空;视图调用的参数仍为 JSON。插件应按实际调用入口验证自己的参数。 diff --git a/apps/buddy/service/src/conversations/__tests__/ConversationCleanupService.spec.ts b/apps/buddy/service/src/conversations/__tests__/ConversationCleanupService.spec.ts index 76f06a6f9..4da02eed4 100644 --- a/apps/buddy/service/src/conversations/__tests__/ConversationCleanupService.spec.ts +++ b/apps/buddy/service/src/conversations/__tests__/ConversationCleanupService.spec.ts @@ -64,11 +64,11 @@ it('cancellation creates no jobs and confirmation uses frozen CAS against a real f.seed('archived', 'archived') const external = join(f.home, 'external.txt') writeFileSync(external, 'external fixture') - const run = (confirm: (count: number) => Promise) => runExtensionTaskCleanupBatch({ cleanup: { list: async input => f.cleanup.list(input), delete: input => f.cleanup.delete(input) }, assertCurrent: () => {}, confirm }) - expect(await run(async count => count !== 1)).toEqual({ status: 'cancelled', results: [], summary: { phase: 'cancelled', total: 1, processed: 0, deleted: 0, pending: 0, failed: 0, skipped: 0, errorCode: null } }) + const run = (confirm: Parameters[0]['confirm']) => runExtensionTaskCleanupBatch({ cleanup: { list: async input => f.cleanup.list(input), delete: input => f.cleanup.delete(input) }, assertCurrent: () => {}, confirm }) + expect(await run(async ({ total }) => total !== 1)).toEqual({ status: 'cancelled', results: [], summary: { phase: 'cancelled', total: 1, processed: 0, deleted: 0, pending: 0, failed: 0, skipped: 0, errorCode: null } }) expect(f.database.prepare('SELECT * FROM conversation_deletion_jobs').all()).toEqual([]) - const changed = await run(async (count) => { - expect(count).toBe(1) + const changed = await run(async (preview) => { + expect(preview).toEqual({ total: 1, skipped: 0 }) f.database.prepare('UPDATE conversations SET metadata_revision = metadata_revision + 1 WHERE id = ?').run(target.conversationId) return true }) diff --git a/apps/buddy/shared/extensions/__tests__/extensionRequestLifecycle.spec.ts b/apps/buddy/shared/extensions/__tests__/extensionRequestLifecycle.spec.ts index 19fc21d21..ec2d047fb 100644 --- a/apps/buddy/shared/extensions/__tests__/extensionRequestLifecycle.spec.ts +++ b/apps/buddy/shared/extensions/__tests__/extensionRequestLifecycle.spec.ts @@ -1,7 +1,7 @@ import { expect, it } from 'vitest' import { waitsForExtensionIo } from '../extensionRequestLifecycle' -it.each(['resources.readBytes', 'resources.scanDirectory', 'taskCleanup.delete'])('does not impose a short view RPC deadline on %s', (method) => { +it.each(['resources.readBytes', 'resources.scanDirectory'])('does not impose a short view RPC deadline on %s', (method) => { expect(waitsForExtensionIo(method)).toBe(true) }) diff --git a/apps/buddy/shared/extensions/extensionApi.ts b/apps/buddy/shared/extensions/extensionApi.ts index 509a57c90..115d7b175 100644 --- a/apps/buddy/shared/extensions/extensionApi.ts +++ b/apps/buddy/shared/extensions/extensionApi.ts @@ -15,7 +15,6 @@ import type { ExtensionManifest } from './extensionManifest' import type { ExtensionReferenceCapture, ExtensionReferenceChoice, ExtensionReferenceMaterial, ExtensionReferenceOpening } from './extensionReferences' import type { ExtensionConfiguration, ExtensionConfigurationSnapshot } from './extensionSettings' import type { ExtensionSettingsHeaderAction } from './extensionSettingsHeaderActions' -import type { ExtensionTaskCleanupConfirmation } from './extensionTaskCleanup' import type { ExtensionWindowStyle } from './extensionWindowStyles' import { z } from 'zod' import { fileOpeningChoiceSchema, fileOpeningLocationSchema } from '../files/fileOpening' @@ -161,8 +160,6 @@ export type ExtensionWorkbenchEvent export const extensionManagementSchema = z.discriminatedUnion('action', [ z.object({ action: z.literal('list') }).strict(), - z.object({ action: z.literal('taskCleanupConfirmations') }).strict(), - z.object({ action: z.literal('confirmTaskCleanup'), id: extensionIdSchema, operationId: z.string().uuid(), confirmed: z.boolean() }).strict(), z.object({ action: z.literal('fileOpeners') }).strict(), z.object({ action: z.literal('setFileOpener'), choice: fileOpeningChoiceSchema }).strict(), z.object({ action: z.literal('prepareFileOpening'), input: extensionFileOpeningInputSchema }).strict(), @@ -212,8 +209,6 @@ export interface ExtensionApi { taskActions: () => Promise invokeTaskAction: (input: ExtensionTaskActionInput) => Promise list: () => Promise - taskCleanupConfirmations: () => Promise - confirmTaskCleanup: (id: string, operationId: string, confirmed: boolean) => Promise unavailable: () => Promise configuration: (id: string) => Promise configurationSnapshot: (id: string) => Promise diff --git a/apps/buddy/shared/extensions/extensionRequestLifecycle.ts b/apps/buddy/shared/extensions/extensionRequestLifecycle.ts index 2b5474df3..440efb555 100644 --- a/apps/buddy/shared/extensions/extensionRequestLifecycle.ts +++ b/apps/buddy/shared/extensions/extensionRequestLifecycle.ts @@ -17,7 +17,6 @@ const ioMethods = new Set([ 'resources.commitSave', 'resources.cancelSave', 'themes.request', - 'taskCleanup.delete', 'documents.pick', 'documents.open', 'documents.resume', diff --git a/apps/buddy/shared/extensions/extensionTaskCleanup.ts b/apps/buddy/shared/extensions/extensionTaskCleanup.ts index 5f0fb5334..6015ed376 100644 --- a/apps/buddy/shared/extensions/extensionTaskCleanup.ts +++ b/apps/buddy/shared/extensions/extensionTaskCleanup.ts @@ -35,19 +35,11 @@ export type ExtensionTaskCleanupDelete = z.infer export type ExtensionTaskCleanupPage = z.infer export type ExtensionTaskCleanupResult = z.infer -export interface ExtensionTaskCleanupConfirmation { - id: string - extensionId: string +export interface ExtensionTaskCleanupPreview { total: number skipped: number } -export interface ExtensionTaskCleanupOperation extends ExtensionTaskCleanupProgress { - id: string - extensionId: string - menuId: string -} - export interface ExtensionTaskCleanupProgress { phase: 'scanning' | 'confirming' | 'running' | 'completed' | 'cancelled' | 'failed' /** @description 完整扫描后冻结的可清理目标数;扫描未完成为 null,不含 skipped。 */ diff --git a/apps/buddy/shared/workbench/workbenchContributionCatalog.ts b/apps/buddy/shared/workbench/workbenchContributionCatalog.ts index b085fccf3..fb5521877 100644 --- a/apps/buddy/shared/workbench/workbenchContributionCatalog.ts +++ b/apps/buddy/shared/workbench/workbenchContributionCatalog.ts @@ -31,7 +31,7 @@ export const workbenchMounts = { } as const satisfies Record export const workbenchMenus = { - 'extension.actions': { title: { 'zh-CN': '插件操作', 'en-US': 'Plugin actions' }, scope: 'application', description: 'API 4 commands in the owning plugin card submenu. Only enabled, active, registered commands appear. Executes immediately without opening a view; sensitive operations still require host confirmation.' }, + 'extension.actions': { title: { 'zh-CN': '插件操作', 'en-US': 'Plugin actions' }, scope: 'application', description: 'API 4 commands in the owning plugin card submenu. Only enabled, active, registered commands appear. Executes without automatically opening a view; command invocation does not expand data or operation permissions.' }, 'composer.actions': { title: { 'zh-CN': '输入操作', 'en-US': 'Composer actions' }, scope: 'composer', description: 'Commands next to composer tools. A click may share draft text with selectedContent permission. Returning {insertText:string} inserts plain text only if the captured draft is unchanged; it never sends.' }, 'task.actions': { title: { 'zh-CN': '任务操作', 'en-US': 'Task actions' }, scope: 'pane', description: 'Commands in the task header. Receives the originating pane instanceId, without task identity or history.' }, 'resource.actions': { title: { 'zh-CN': '文件操作', 'en-US': 'File actions' }, scope: 'resource', description: 'Commands for the selected file. selectedResource:read grants an opaque handle through existing directory authorization.' }, @@ -41,7 +41,7 @@ export const workbenchMenus = { export const workbenchDecorations = workbenchRegions satisfies Record export const workbenchRuntimeCapabilities = { - 'taskCleanup': { title: { 'zh-CN': '旧版已移除任务清理', 'en-US': 'Legacy removed task cleanup' }, scope: 'application', description: 'Lexora >=0.21.0, API 4: extension.actions commands receive a single-use taskCleanup.run() only from a trusted user menu invocation with legacyTaskCleanup permission. Host determines all targets and freezes revisions, confirms the total once, then Core validates each legacy tombstone and CAS. Returns per-item results; cancellation creates no jobs. No arbitrary task, file, SQLite, timer or background deletion. Existing interactive ViewContext list/delete remains supported with per-item confirmation. Accepted Core jobs continue after plugin shutdown. See task-cleanup.md.' }, + 'taskCleanup': { title: { 'zh-CN': '旧版已移除任务清理', 'en-US': 'Legacy removed task cleanup' }, scope: 'application', description: 'Lexora >=0.22.0: extension.actions commands receive a single-use taskCleanup.run() only from a trusted user menu invocation with legacyTaskCleanup permission. One-time maintenance capability, not a general plugin API. Host freezes eligible targets and revisions; run requires a confirm(preview, signal) callback bound to the original command and only accepts true before Core validates each target and CAS. Plugins own all preview, confirmation, progress and result UI. No View cleanup API, arbitrary task/file/SQLite access, timers or background initiation. Cancellation before confirmation creates no jobs; accepted Core jobs continue after plugin shutdown.' }, 'inference': { title: { 'zh-CN': '后台模型推理', 'en-US': 'Background model inference' }, scope: 'application', description: 'contributes.inference provides chat, speech, image reading, generation and editing through declared Linux x64 native runtimes. Requires permissions.inference and a background entry; GPU and inference network origins have separate permissions. Plugins own optional resource preparation and management pages; the host owns task routing, cancellation and credential storage. No arbitrary host file access. See inference.md.' }, 'shells': { title: { 'zh-CN': '本机命令解释器', 'en-US': 'Local command interpreters' }, scope: 'application', description: 'API 4 contributes.shells declares fixed candidate IDs and native enabled/executable/priority setting keys. Requires permissions.shells. Host context.shells.detect() takes no arguments and reads bounded detection results, including unavailable candidates. Only user-enabled candidates reach core command execution under existing permissions; no plugin spawn, command input, configuration writes, installers, WSL or PTY. Defaults must leave candidates disabled, paths empty and priorities zero. See shells.md.' }, 'clipboard': { title: { 'zh-CN': '系统剪贴板', 'en-US': 'System clipboard' }, scope: 'application', description: 'Interactive ViewContext.clipboard.read()/write({text?,html?}) require independent clipboardRead/clipboardWrite manifest permissions and a visible focused view in the foreground window. Total UTF-8 content is limited to 4 MiB. Text and HTML writes are atomic. This is installation authorization plus focus, not per-call user activation. Background hosts, Workers, decorations, slots and controls are excluded; browser clipboard permissions remain denied. See views.md.' }, diff --git a/apps/buddy/src/modules/extensions/state/extensionTaskCleanupLabels.ts b/apps/buddy/src/modules/extensions/state/extensionTaskCleanupLabels.ts deleted file mode 100644 index af0f54089..000000000 --- a/apps/buddy/src/modules/extensions/state/extensionTaskCleanupLabels.ts +++ /dev/null @@ -1,16 +0,0 @@ -export function extensionTaskCleanupLabels(language: string) { - const english = language === 'en-US' - return { - title: english ? 'Clean up legacy tasks' : '清理旧版任务', - plugin: english ? 'Plugin' : '插件', - scope: english ? 'legacy removed tasks' : '个旧版已移除任务', - irreversible: english ? 'Deletion is permanent' : '删除后无法恢复', - risk: english ? 'This deletes their local history and host-managed data. Active and archived tasks, user workspaces and external files are not affected.' : '将删除这些任务的本地历史和宿主管理的数据。不处理活动或已归档任务,不影响用户工作区及外部文件。', - changed: english ? 'Tasks changed after this check will not be deleted without a new check.' : '检查后状态发生变化的任务将拒绝清理。', - cancel: english ? 'Cancel' : '取消', - delete: english ? 'Delete' : '删除', - skipped: (count: number) => english ? `${count} tasks are not currently eligible and were excluded.` : `${count} 项暂不可清理,本次未包含。`, - responseFailed: english ? 'The confirmation could not be updated. Please try again.' : '未能更新确认信息,请重试。', - expired: english ? 'This confirmation has expired. Check again before deleting.' : '本次确认已失效,请重新检查后再删除。', - } -} diff --git a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionFrameHost.vue b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionFrameHost.vue index 0e0bf568f..f514b612c 100644 --- a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionFrameHost.vue +++ b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionFrameHost.vue @@ -205,8 +205,6 @@ async function receive(event: MessageEvent) { try { if (data.method === 'clipboard.read' || data.method === 'clipboard.write') assertFocusedView(frame, 'EXTENSION_CLIPBOARD_UNAVAILABLE') - if (data.method === 'taskCleanup.delete') - assertFocusedView(frame, 'EXTENSION_TASK_CLEANUP_UNAVAILABLE') if ((['resources.pickFiles', 'resources.pickDirectory', 'resources.beginSave', 'documents.pick', 'references.add', 'references.capture', 'references.commit'].includes(data.method) || (data.method === 'documents.beginWrite' && data.params?.mode === 'saveAs')) && (!frame.visible || document.visibilityState !== 'visible' || !document.hasFocus())) throw new Error('EXTENSION_RESOURCE_PICKER_UNAVAILABLE') if (data.method === 'events.snapshot') { diff --git a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionReviewHost.vue b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionReviewHost.vue index 1387e844a..ddd1f2da6 100644 --- a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionReviewHost.vue +++ b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionReviewHost.vue @@ -9,7 +9,6 @@ import { extensionLabels, extensionVerificationError } from '../extensionLabels' import { extensionErrorCode } from '../state/useExtensionState' import DesktopExtensionIncompatibleReview from './DesktopExtensionIncompatibleReview.vue' import DesktopExtensionInstallReview from './DesktopExtensionInstallReview.vue' -import DesktopExtensionTaskCleanupHost from './DesktopExtensionTaskCleanupHost.vue' const { state, language } = useExtensionContext() const message = useMessage() @@ -44,7 +43,6 @@ async function install(applyUpdate: boolean, choices: FileOpeningChoice[], accep diff --git a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupDialog.vue b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupDialog.vue deleted file mode 100644 index 0589a3de5..000000000 --- a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupDialog.vue +++ /dev/null @@ -1,60 +0,0 @@ - - - diff --git a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupHost.vue b/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupHost.vue deleted file mode 100644 index 73174456c..000000000 --- a/apps/buddy/src/modules/extensions/widgets/DesktopExtensionTaskCleanupHost.vue +++ /dev/null @@ -1,73 +0,0 @@ - - - diff --git a/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionFrameHost.spec.ts b/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionFrameHost.spec.ts index 272315d78..8c881fc64 100644 --- a/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionFrameHost.spec.ts +++ b/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionFrameHost.spec.ts @@ -101,9 +101,9 @@ it('scopes broadcasts by extension and generation and header actions by exact vi expect(frames[0]!.actions).toHaveLength(1) }) -it('allows legacy deletion only from a focused visible ready frame and preserves accepted results after focus changes', async () => { +it('allows clipboard writes only from a focused visible ready frame and preserves accepted results after focus changes', async () => { const installed = shallowRef([{ manifest: extensionManifestSchema.parse({ schemaVersion: 1, id: 'tests.cleanup', name: 'Cleanup', version: '1.0.0', apiVersion: 4, engines: { lexora: '*' }, contributes: {} }), revision: 'first', enabled: true, compatible: true, development: false, pending: null, state: 'active', generation: crypto.randomUUID(), error: null, activationMs: null, logs: [] }]) - const viewRequest = vi.fn().mockResolvedValue({ status: 'deleted' }) + const viewRequest = vi.fn().mockResolvedValue(null) const api: Partial = { openView: async input => ({ id: input.viewId, extensionId: input.extensionId, generation: installed.value[0]!.generation!, token: crypto.randomUUID(), url: 'about:blank' }), closeView: async () => {}, @@ -143,25 +143,25 @@ it('allows legacy deletion only from a focused visible ready frame and preserves } } target.addEventListener('message', receive) - window.dispatchEvent(new MessageEvent('message', { source: target, data: { channel: 'lexora-extension', token: session.token, id, method: 'taskCleanup.delete', params: { conversationId: 'removed-task' } } })) + window.dispatchEvent(new MessageEvent('message', { source: target, data: { channel: 'lexora-extension', token: session.token, id, method: 'clipboard.write', params: { text: 'Clipboard fixture' } } })) }) vi.spyOn(document, 'visibilityState', 'get').mockReturnValue('visible') vi.spyOn(document, 'hasFocus').mockReturnValue(true) layoutChanged() frame.focus() - expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_TASK_CLEANUP_UNAVAILABLE' }) + expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_CLIPBOARD_UNAVAILABLE' }) surface.ready = true surface.visible = false - expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_TASK_CLEANUP_UNAVAILABLE' }) + expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_CLIPBOARD_UNAVAILABLE' }) surface.visible = true document.body.tabIndex = -1 document.body.focus() - expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_TASK_CLEANUP_UNAVAILABLE' }) + expect(await request()).toMatchObject({ ok: false, value: 'EXTENSION_CLIPBOARD_UNAVAILABLE' }) expect(viewRequest).not.toHaveBeenCalled() frame.focus() viewRequest.mockImplementationOnce(async () => { document.body.focus() - return { status: 'deleted' } + return null }) - expect(await request()).toMatchObject({ ok: true, value: { status: 'deleted' } }) + expect(await request()).toMatchObject({ ok: true, value: null }) }) diff --git a/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionTaskCleanupHost.spec.ts b/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionTaskCleanupHost.spec.ts deleted file mode 100644 index 8ee73a3d5..000000000 --- a/apps/buddy/src/modules/extensions/widgets/__tests__/DesktopExtensionTaskCleanupHost.spec.ts +++ /dev/null @@ -1,119 +0,0 @@ -// @vitest-environment jsdom -import type { ExtensionApi, ExtensionStatus } from '@buddy-shared/extensions/extensionApi' -import type { ExtensionTaskCleanupConfirmation } from '@buddy-shared/extensions/extensionTaskCleanup' -import type { ExtensionContext } from '../../extensionContext' -import { extensionManifestSchema } from '@buddy-shared/extensions/extensionManifest' -import { deferred } from '@buddy-tests/deferred' -import { NMessageProvider } from 'naive-ui' -import { afterEach, beforeEach, expect, it, vi } from 'vitest' -import { createApp, h, shallowRef } from 'vue' -import { useProvideExtensionContext } from '../../extensionContext' -import { useExtensionState } from '../../state/useExtensionState' -import DesktopExtensionTaskCleanupHost from '../DesktopExtensionTaskCleanupHost.vue' - -const cleanups: (() => void)[] = [] -beforeEach(() => { - vi.stubGlobal('matchMedia', (media: string) => ({ matches: false, media, onchange: null, addListener() {}, removeListener() {}, addEventListener() {}, removeEventListener() {}, dispatchEvent: () => true })) -}) -afterEach(() => { - cleanups.splice(0).forEach(cleanup => cleanup()) - document.body.innerHTML = '' - vi.unstubAllGlobals() -}) -const confirmation: ExtensionTaskCleanupConfirmation = { id: 'confirmation-1', extensionId: 'test.cleanup', total: 3, skipped: 2 } -async function mount() { - let requests = [confirmation] - const listeners = new Set<() => void>() - const decisions: { id: string, operationId: string, confirmed: boolean }[] = [] - const snapshot: ExtensionStatus = { - manifest: extensionManifestSchema.parse({ schemaVersion: 1, id: 'test.cleanup', name: '旧版任务清理', version: '1.0.2', apiVersion: 4, engines: { lexora: '*' }, contributes: {} }), - revision: 'revision', - enabled: true, - development: false, - compatible: true, - pending: null, - state: 'active', - generation: 'generation', - error: null, - activationMs: null, - logs: [], - } - const api: Partial = { - list: async () => [snapshot], - unavailable: async () => [], - taskActions: async () => [], - installations: async () => [], - onInstallationsChanged: () => () => {}, - onChanged: (listener) => { - listeners.add(listener) - return () => listeners.delete(listener) - }, - taskCleanupConfirmations: async () => requests, - confirmTaskCleanup: async (id, operationId, confirmed) => { - decisions.push({ id, operationId, confirmed }) - requests = [] - }, - } - const root = document.createElement('div') - document.body.append(root) - const app = createApp({ setup() { - const state = useExtensionState(api as ExtensionApi) - void state.refresh() - useProvideExtensionContext({ state, language: shallowRef('zh-CN') } as ExtensionContext) - return () => h(NMessageProvider, null, { default: () => h(DesktopExtensionTaskCleanupHost) }) - } }) - app.mount(root) - cleanups.push(() => app.unmount()) - await vi.waitFor(() => expect(dialog()).not.toBeNull()) - return { api, decisions, update(next: ExtensionTaskCleanupConfirmation[]) { - requests = next - listeners.forEach(listener => listener()) - } } -} -function dialog() { - return document.querySelector('[data-testid="extension-task-cleanup-dialog"]') -} -function button(label: string) { - const found = [...dialog()!.querySelectorAll('button')].find(button => button.textContent?.trim() === label) - expect(found, label).toBeDefined() - return found! -} - -it.each([['取消', false], ['删除', true]] as const)('binds %s to the frozen request and withdraws the confirmation afterwards', async (label, confirmed) => { - const f = await mount() - expect(dialog()!.textContent).toContain('删除后无法恢复') - expect(dialog()!.textContent).toContain('不处理活动或已归档任务') - expect(dialog()!.textContent).toContain('不影响用户工作区及外部文件') - expect(dialog()!.querySelector('[data-testid="extension-task-cleanup-scope"]')?.textContent).toContain('3') - expect(dialog()!.textContent).toContain('2 项暂不可清理') - button(label).click() - await vi.waitFor(() => expect(dialog()).toBeNull()) - expect(f.decisions).toEqual([{ id: 'test.cleanup', operationId: 'confirmation-1', confirmed }]) -}) - -it('ignores a late response from an old confirmation without disabling its replacement', async () => { - const f = await mount() - const old = deferred() - f.api.confirmTaskCleanup = () => old.promise - button('删除').click() - await vi.waitFor(() => expect(button('取消').disabled).toBe(true)) - f.update([{ ...confirmation, id: 'confirmation-2', total: 7 }]) - await vi.waitFor(() => expect(dialog()!.querySelector('[data-testid="extension-task-cleanup-scope"]')?.textContent).toContain('7')) - old.reject(new Error('EXTENSION_TASK_CLEANUP_EXPIRED')) - await vi.waitFor(() => expect(button('取消').disabled).toBe(false)) - expect(dialog()!.textContent).not.toContain('本次确认已失效') -}) - -it('preserves a known confirmation when refresh fails, without treating failure as no pending request', async () => { - const f = await mount() - f.api.taskCleanupConfirmations = async () => { - throw new Error('PRIVATE_PATH') - } - f.update([]) - await vi.waitFor(() => expect(dialog()!.textContent).toContain('未能更新确认信息')) - expect(dialog()!.querySelector('[data-testid="extension-task-cleanup-scope"]')?.textContent).toContain('3') - f.api.taskCleanupConfirmations = async () => [] - button('取消').click() - await vi.waitFor(() => expect(dialog()).toBeNull()) - expect(f.decisions[0]?.confirmed).toBe(false) -})