diff --git a/integrations/dsh/plugins/dsh-pet/tests/desktop-host.mjs b/integrations/dsh/plugins/dsh-pet/tests/desktop-host.mjs index 0ecdf616ac..e05893e664 100644 --- a/integrations/dsh/plugins/dsh-pet/tests/desktop-host.mjs +++ b/integrations/dsh/plugins/dsh-pet/tests/desktop-host.mjs @@ -90,8 +90,8 @@ export async function startDesktop(app, root, env) { child.stderr.destroy() } } - const evaluate = async (expression) => { - const target = await appRenderer() + const evaluate = async (expression, webview) => { + const target = webview ?? await appRenderer() if (!target) throw new Error('DSH Desktop renderer is not ready') const result = await rendererCommand(target, 'Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true, @@ -99,5 +99,5 @@ export async function startDesktop(app, root, env) { if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text) return result.result.value } - return { stop, appRenderer, evaluate } + return { stop, appRenderer, evaluate, targets } } diff --git a/integrations/dsh/plugins/dsh-pet/tests/runtime.test.mjs b/integrations/dsh/plugins/dsh-pet/tests/runtime.test.mjs index 27f76b47c2..87331468d5 100644 --- a/integrations/dsh/plugins/dsh-pet/tests/runtime.test.mjs +++ b/integrations/dsh/plugins/dsh-pet/tests/runtime.test.mjs @@ -134,6 +134,79 @@ async function fixtureModel() { } } +async function assertDashboardMemory(desktop, root, baseUrl, scope) { + const workspace = join(root, 'pet-dashboard-workspace') + await mkdir(workspace) + // The renderer appears before the host has mounted its plugin routes. + // A GET verifies the POST-only fixture is ready without creating a session. + await until(() => desktop.evaluate(`fetch('/__powercontext_test/sessions') + .then(response => response.status === 405 && response.headers.get('allow') === 'POST')`).catch(() => false), + 'Desktop session fixture route') + const created = await desktop.evaluate(`(async () => { + const response = await fetch('/__powercontext_test/sessions', { + method: 'POST', headers: {'content-type': 'application/json'}, + body: JSON.stringify({cwd: ${JSON.stringify(workspace)}}), + }) + return { status: response.status, body: response.ok ? await response.json() : undefined } + })()`) + assert.equal(created.status, 200) + assert.ok(created.body.id) + await desktop.evaluate(`localStorage.setItem('dsh.sessions.current', JSON.stringify({sessionId:${JSON.stringify(created.body.id)}})); true`) + try { await desktop.evaluate('location.reload(); true') } catch { /* old renderer may detach */ } + await until(async () => { + try { + return await desktop.evaluate(`(() => { + for (const dialog of document.querySelectorAll('[role="dialog"][aria-modal="true"]')) { + if (!/开始使用|预览版说明|Get started|Preview/.test(dialog.innerText)) continue + const button = [...dialog.querySelectorAll('button')].find(node => /关闭|Close/.test(node.getAttribute('aria-label') || '')) + ?? dialog.querySelector('button') + button?.click() + } + return !!document.querySelector('.pc-trigger') + })()`) + } catch { return false } + }, 'PowerContext entry in the Desktop renderer') + const bridgePath = '/powercontext/dashboard?session_id=' + encodeURIComponent(created.body.id) + const bridge = await desktop.evaluate(`fetch(${JSON.stringify(bridgePath)}).then(response => response.json())`) + assert.equal(bridge.state, 'available', JSON.stringify(bridge)) + assert.equal(bridge.scope_id, scope) + assert.equal(new URL(bridge.url).searchParams.get('scope'), scope) + assert.ok(!new URL(bridge.url).searchParams.has('token')) + await desktop.evaluate("document.querySelector('.pc-trigger').click(); true") + await until(() => desktop.evaluate("!!document.querySelector('.pc-dashboard-button')"), 'Desktop Dashboard button') + await desktop.evaluate("document.querySelector('.pc-dashboard-button').click(); true") + const findPanel = async (page) => (await desktop.targets()).find(target => { + if (!target.url.startsWith(baseUrl + '/dashboard/' + page)) return false + return new URL(target.url).searchParams.get('scope') === scope + }) + let panel + await until(async () => { + panel = await findPanel('home') + if (!panel) return false + const heading = await desktop.evaluate("document.querySelector('h1')?.textContent || ''", panel) + return heading.includes('Synthetic pet one') + }, 'scoped Dashboard rendered inside Desktop Browser') + const notesLink = 'a[href^="/dashboard/notes"]' + assert.equal(await desktop.evaluate(`(() => { + const link = document.querySelector(${JSON.stringify(notesLink)}) + link?.click() + return !!link + })()`, panel), true, 'notes navigation exists in the embedded Dashboard') + await until(async () => { + panel = await findPanel('notes') + if (!panel) return false + return desktop.evaluate(`(() => { + if (document.body?.innerText.includes(${JSON.stringify(fact)})) return true + const entry = [...document.querySelectorAll('.memory-directory a, .memory-directory button')] + .find(node => node.getClientRects().length && node.innerText.includes(${JSON.stringify(fact.slice(0, 30))})) + entry?.click() + return !!entry + })()`, panel) + }, 'extracted pet memory listed in Notes') + await until(() => desktop.evaluate(`document.body?.innerText.includes(${JSON.stringify(fact)})`, panel), + 'full pet memory visible in the embedded Dashboard') +} + test('packaged pet adapter captures, extracts and recalls in real DSH ' + profile, { skip: !dsh && 'Set DSH_PET_TEST_BIN or DSH_PET_TEST_DESKTOP_APP for DSH 0.2.2-rc.1', timeout: 300_000, @@ -180,6 +253,7 @@ test('packaged pet adapter captures, extracts and recalls in real DSH ' + profil } const server = await startPowerContextServer({ env: { OPENAI_API_KEY: 'pet-' + 'test-fixture', + POWERCONTEXT_SERVER_DASHBOARD_ENABLED: desktopApp ? 'true' : 'false', POWERCONTEXT_SERVER_INFERENCE: JSON.stringify({ generation_model: 'openai-chat:fixture', generation_base_url: model.url + '/v1', }), @@ -283,9 +357,10 @@ test('packaged pet adapter captures, extracts and recalls in real DSH ' + profil JSON.stringify({ ...petConfig, chatMemoryRounds: rounds })) await configurePet(1) const patch = desktopApp ? join(profileDir, 'cordis.patch.yml') : join(root, 'model-patch.json') - await writeFile(patch, JSON.stringify([ - { id: 'llm-deepseek', config: { baseURL: model.url + '/v1', apiKeyEnv: 'DEEPSEEK_API_KEY', thinking: 'disabled' } }, - ])) + const modelOverride = { id: 'llm-deepseek', config: { + baseURL: model.url + '/v1', apiKeyEnv: 'DEEPSEEK_API_KEY', thinking: 'disabled', + } } + await writeFile(patch, JSON.stringify([modelOverride])) const statusFile = join(profileDir, '.powercontext-dsh-pet/status.json') const status = async () => JSON.parse(await readFile(statusFile, 'utf8').catch(() => '{}')) @@ -311,6 +386,10 @@ test('packaged pet adapter captures, extracts and recalls in real DSH ' + profil desktop = await startDesktop(desktopApp, root, env) await until(desktop.appRenderer, 'packaged Desktop renderer') await until(async () => (await status()).provider === 'registered', 'Desktop memory provider registration') + // Provider registration can precede the renderer's HTTP bridge after a restart. + await until(() => desktop.evaluate(`fetch('/dsh-pet-7340/config') + .then(response => response.ok && response.headers.get('content-type')?.includes('application/json'))`) + .catch(() => false), 'Desktop pet routes') return } const port = await unusedPort() @@ -429,4 +508,21 @@ test('packaged pet adapter captures, extracts and recalls in real DSH ' + profil full_history: { ...full, target_check: true }, model_provider_usage_and_cost: 'unknown (deterministic local fixture; no provider billing)', })) + + if (desktopApp) { + await stopHost() + const mainPackage = join(repo, 'integrations/dsh/plugins/powercontext') + const packed = await run('npm', ['pack', mainPackage, '--pack-destination', root, '--ignore-scripts', '--json']) + await run(dsh, ['plugin', '--profile', profile, 'add', join(root, JSON.parse(packed.stdout)[0].filename)]) + const fixture = join(mainPackage, 'tests/runtime/session-fixture') + await run(dsh, ['plugin', '--profile', profile, 'add', fixture]) + // The Dashboard connects to the same Server directly. The pet proxy above + // remains dedicated to observing the anonymous adapter's requests. + await writeFile(patch, JSON.stringify([ + modelOverride, { id: 'powercontext-dsh', config: { baseUrl: server.baseUrl, scopeId: scope } }, + ])) + desktop = await startDesktop(desktopApp, root, env) + await until(desktop.appRenderer, 'packaged Desktop renderer') + await assertDashboardMemory(desktop, root, server.baseUrl, scope) + } })