diff --git a/.github/workflows/mobile-build.yml b/.github/workflows/mobile-build.yml
new file mode 100644
index 000000000..fc9836328
--- /dev/null
+++ b/.github/workflows/mobile-build.yml
@@ -0,0 +1,91 @@
+name: Android package
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: android-package-${{ github.ref }}
+ cancel-in-progress: false
+
+jobs:
+ build:
+ name: Signed Android APK
+ runs-on: ubuntu-24.04
+ environment: android-signing
+ timeout-minutes: 30
+ steps:
+ - name: Checkout
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - name: Setup pnpm
+ uses: pnpm/action-setup@0977fd99725f1db4007ccb2928dbb4e90d06cc86 # v6.0.10
+
+ - name: Setup Node
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version-file: .node-version
+
+ - name: Setup Java
+ uses: actions/setup-java@b6effb05e454b25005698d916606bdc6ffcbf961 # v5
+ with:
+ distribution: temurin
+ java-version: '21'
+
+ - name: Install workspace dependencies
+ uses: ./.github/actions/install-workspace-dependencies
+ with:
+ packages: '@uselexora/lexora @uselexora/lexora-buddy...'
+
+ - name: Prepare Android SDK
+ run: sdkmanager 'platforms;android-36' 'build-tools;36.0.0'
+
+ - name: Verify Android client
+ working-directory: apps/mobile
+ run: ./gradlew --no-daemon :android:testDebugUnitTest :android:lintRelease
+
+ - name: Build signed APK
+ working-directory: apps/mobile
+ env:
+ LEXORA_ANDROID_KEYSTORE_BASE64: ${{ secrets.LEXORA_ANDROID_KEYSTORE_BASE64 }}
+ LEXORA_ANDROID_STORE_PASSWORD: ${{ secrets.LEXORA_ANDROID_STORE_PASSWORD }}
+ LEXORA_ANDROID_KEY_ALIAS: ${{ secrets.LEXORA_ANDROID_KEY_ALIAS }}
+ LEXORA_ANDROID_KEY_PASSWORD: ${{ secrets.LEXORA_ANDROID_KEY_PASSWORD }}
+ shell: bash
+ run: |
+ set -euo pipefail
+ : "${LEXORA_ANDROID_KEYSTORE_BASE64:?Missing signing keystore}"
+ : "${LEXORA_ANDROID_STORE_PASSWORD:?Missing keystore password}"
+ : "${LEXORA_ANDROID_KEY_ALIAS:?Missing signing alias}"
+ : "${LEXORA_ANDROID_KEY_PASSWORD:?Missing key password}"
+ umask 077
+ export LEXORA_ANDROID_KEYSTORE="$RUNNER_TEMP/lexora-android-release.p12"
+ trap 'rm -f "$LEXORA_ANDROID_KEYSTORE"' EXIT
+ printf '%s' "$LEXORA_ANDROID_KEYSTORE_BASE64" | base64 --decode > "$LEXORA_ANDROID_KEYSTORE"
+ unset LEXORA_ANDROID_KEYSTORE_BASE64
+ ./gradlew --no-daemon :android:assembleRelease
+ "$ANDROID_HOME/build-tools/36.0.0/apksigner" verify --verbose --print-certs android/build/outputs/apk/release/android-release.apk | tee android/build/outputs/apk/release/signature.txt
+ expected="$(cat android/release-certificate.sha256)"
+ grep -Fx "Signer #1 certificate SHA-256 digest: $expected" android/build/outputs/apk/release/signature.txt
+ cd android/build/outputs/apk/release
+ sha256sum android-release.apk > android-release.apk.sha256
+
+ - name: Remove signing material
+ if: always()
+ run: rm -f "$RUNNER_TEMP/lexora-android-release.p12"
+
+ - name: Upload signed package
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: lexora-android-apk
+ path: |
+ apps/mobile/android/build/outputs/apk/release/android-release.apk
+ apps/mobile/android/build/outputs/apk/release/android-release.apk.sha256
+ apps/mobile/android/build/outputs/apk/release/output-metadata.json
+ apps/mobile/android/build/outputs/apk/release/signature.txt
+ if-no-files-found: error
+ retention-days: 14
diff --git a/.playwright/scripts/README.md b/.playwright/scripts/README.md
index 20375acbc..f5331e1d3 100644
--- a/.playwright/scripts/README.md
+++ b/.playwright/scripts/README.md
@@ -11,3 +11,12 @@ pnpm test:e2e
`pnpm test` 执行无 GUI 的 Vitest 测试。`pnpm test:e2e` 构建当前 Electron 应用并执行 Playwright Test;可追加测试文件名或 `--grep` 筛选场景。Linux 需要 `Xvfb`,Electron 必须能启用 Chromium sandbox。
Electron 测试位于 `__tests__/*.e2e.mjs`,复用 `fixtures/electron.mjs` 的 `test`、`expect`;辅助逻辑测试使用 `__tests__/*.spec.mjs`。
+
+Android 已安装调试 APK 和测试 APK、并通过 `adb` 连接后,可运行双端审批、草稿、附件、历史、进程恢复与任务控制联测:
+
+```sh
+LEXORA_TEST_ANDROID_SERIAL=emulator-5554 pnpm test:e2e mobile-desktop.e2e.mjs mobile-approvals.e2e.mjs mobile-task-controls.e2e.mjs mobile-history.e2e.mjs mobile-recovery.e2e.mjs mobile-content.e2e.mjs mobile-interruption.e2e.mjs
+# 普通 Node Core 与 Electron Host 联测需先构建配套服务
+pnpm --filter @uselexora/lexora-buddy build:desktop
+LEXORA_TEST_MOBILE_SERVICE_MODE=daemon LEXORA_TEST_ANDROID_SERIAL=emulator-5554 pnpm exec playwright test --config .playwright/scripts/playwright.config.mjs mobile-desktop.e2e.mjs mobile-approvals.e2e.mjs mobile-task-controls.e2e.mjs mobile-history.e2e.mjs mobile-recovery.e2e.mjs mobile-content.e2e.mjs mobile-interruption.e2e.mjs
+```
diff --git a/.playwright/scripts/__tests__/attachment-publication.e2e.mjs b/.playwright/scripts/__tests__/attachment-publication.e2e.mjs
new file mode 100644
index 000000000..a16d61d94
--- /dev/null
+++ b/.playwright/scripts/__tests__/attachment-publication.e2e.mjs
@@ -0,0 +1,62 @@
+import { execFile } from 'node:child_process'
+import fs from 'node:fs/promises'
+import { createRequire, isBuiltin } from 'node:module'
+import os from 'node:os'
+import path from 'node:path'
+import process from 'node:process'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+import { expect, test } from '@playwright/test'
+
+const execute = promisify(execFile)
+const root = fileURLToPath(new URL('../../../', import.meta.url))
+const requireBuddy = createRequire(path.join(root, 'apps/buddy/package.json'))
+const checkpoints = ['prepared', 'file-synced', 'renamed', 'directory-synced', 'published', 'bound']
+
+test('interrupted file publication recovers only durable attachment ownership', async () => {
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'lexora-attachment-publication-'))
+ const report = []
+ try {
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: {
+ ssr: path.join(root, '.playwright/scripts/fixtures/attachment-publication-crash.ts'),
+ outDir: path.join(directory, 'harness'),
+ target: 'node26',
+ rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'publication.mjs', format: 'es' } },
+ } })
+ const entry = path.join(directory, 'harness/publication.mjs')
+ for (const checkpoint of checkpoints) {
+ const profile = path.join(directory, checkpoint)
+ const unknown = path.join(profile, 'profile/drafts/unknown/keep.txt')
+ await fs.mkdir(path.dirname(unknown), { recursive: true })
+ await fs.writeFile(unknown, 'unknown files are preserved')
+ let interrupted
+ try {
+ await execute(process.execPath, [entry, 'publish', profile, checkpoint], { timeout: 30000 })
+ }
+ catch (error) { interrupted = error }
+ expect(interrupted, checkpoint).toBeTruthy()
+ expect(JSON.parse(interrupted.stdout.trim())).toEqual({ checkpoint })
+ const result = await execute(process.execPath, [entry, 'recover', profile], { timeout: 30000 })
+ const recovery = JSON.parse(result.stdout.trim())
+ const bound = checkpoint === 'bound'
+ expect(recovery.files).toHaveLength(1)
+ expect(recovery.files[0].state).toBe(bound ? 'ready' : 'deleted')
+ expect(recovery.references).toEqual(bound ? [{ kind: 'draft', owner_id: 'crash-draft' }] : [])
+ expect(recovery.bytes).toEqual(bound ? ['durable attachment bytes'] : [])
+ expect(recovery.preparations).toEqual([{ state: bound ? 'settled' : 'aborted', reserved_bytes: 0 }])
+ expect(await fs.readFile(unknown, 'utf8')).toBe('unknown files are preserved')
+ const repeat = JSON.parse((await execute(process.execPath, [entry, 'recover', profile], { timeout: 30000 })).stdout.trim())
+ expect(repeat.files).toEqual(recovery.files)
+ expect(repeat.references).toEqual(recovery.references)
+ expect(repeat.recovered.removedOrphanFiles).toBe(0)
+ report.push({ checkpoint, ...recovery })
+ }
+ }
+ finally {
+ const reportPath = test.info().outputPath('attachment-publication.json')
+ await fs.writeFile(reportPath, JSON.stringify(report, null, 2))
+ await test.info().attach('attachment-publication.json', { path: reportPath, contentType: 'application/json' })
+ await fs.rm(directory, { recursive: true, force: true })
+ }
+})
diff --git a/.playwright/scripts/__tests__/browser-platform-lifetime.e2e.mjs b/.playwright/scripts/__tests__/browser-platform-lifetime.e2e.mjs
new file mode 100644
index 000000000..3f97e30d1
--- /dev/null
+++ b/.playwright/scripts/__tests__/browser-platform-lifetime.e2e.mjs
@@ -0,0 +1,88 @@
+import { Buffer } from 'node:buffer'
+import { createServer } from 'node:http'
+import { expect, test } from '../fixtures/electron.mjs'
+
+test('platform browser survives workbench destruction, rejects stale presentation and reattaches the same interactive page', async ({ buddy }, testInfo) => {
+ const server = createServer((_request, response) => {
+ response.setHeader('Content-Type', 'text/html; charset=utf-8')
+ response.end('
Background browser fixture')
+ })
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
+ try {
+ const url = `http://127.0.0.1:${server.address().port}/`
+ const instance = await buddy.createInstance('browser-background')
+ const { app, page } = await instance.launch()
+ const state = await page.evaluate(async (url) => {
+ const state = await window.lexoraDesktop.browser.ensureSession(null, 'lifetime-test')
+ return window.lexoraDesktop.browser.navigate(state.sessionId, url)
+ }, url)
+ const pageId = await app.evaluate(({ webContents }, url) => webContents.getAllWebContents().find(contents => contents.getURL() === url)?.id, url)
+ expect(typeof pageId).toBe('number')
+ const bounds = { x: 40, y: 100, width: 620, height: 300 }
+ const oldToken = await page.evaluate(() => window.lexoraDesktop.browser.acquirePresentation())
+ const presentation = { presentationId: oldToken, sessionId: state.sessionId, pageId: state.pageId, visible: true, bounds, clip: bounds }
+ await page.evaluate(input => window.lexoraDesktop.browser.present(input), presentation)
+ const initial = await app.evaluate(async ({ webContents }, id) => {
+ const contents = webContents.fromId(id)
+ contents.focus()
+ await contents.executeJavaScript('document.querySelector("#text").focus()')
+ contents.insertText(' retained')
+ return { text: await contents.executeJavaScript('document.querySelector("#text").value'), ticks: await contents.executeJavaScript('window.ticks'), zoom: contents.getZoomFactor(), size: (await contents.capturePage()).getSize() }
+ }, pageId)
+ expect(initial.text).toContain('retained')
+ expect(initial.size.width).toBeGreaterThan(0)
+ await page.evaluate(async sessionId => window.lexoraDesktop.browser.setZoomFactor(sessionId, 1.25), state.sessionId)
+ await page.evaluate(input => window.lexoraDesktop.browser.present(input), { ...presentation, visible: false })
+ await app.evaluate(({ BrowserWindow }) => {
+ const window = BrowserWindow.getAllWindows().find(window => window.webContents.getURL().startsWith('lexora-app:'))
+ if (!window)
+ throw new Error('Workbench is missing')
+ setImmediate(() => window.destroy())
+ })
+ await expect.poll(() => app.evaluate(async ({ webContents }, id) => (await webContents.fromId(id)?.debugger.sendCommand('Runtime.evaluate', { expression: 'window.ticks', returnByValue: true }))?.result?.value, pageId)).toBeGreaterThan(initial.ticks + 2)
+ const offline = await app.evaluate(async ({ webContents }, id) => {
+ const contents = webContents.fromId(id)
+ await contents.debugger.sendCommand('Runtime.evaluate', { expression: 'document.querySelector("button").click()' })
+ const snapshot = await contents.capturePage(undefined, { stayHidden: true })
+ return { clicks: await contents.executeJavaScript('window.clicks'), text: await contents.executeJavaScript('document.querySelector("#text").value'), screenshotBytes: snapshot.toPNG().length }
+ }, pageId)
+ expect(offline).toMatchObject({ clicks: 1, text: initial.text })
+ expect(offline.screenshotBytes).toBeGreaterThan(100)
+ const newWindow = app.waitForEvent('window')
+ await app.evaluate(({ app }) => app.emit('activate'))
+ const reopened = await newWindow
+ await expect(reopened.locator('.desktop-workbench-area__tasks .tiptap:visible').first()).toBeVisible()
+ const stale = await reopened.evaluate(async (input) => {
+ try {
+ await window.lexoraDesktop.browser.present(input)
+ return false
+ }
+ catch { return true }
+ }, presentation)
+ expect(stale).toBe(true)
+ const guests = await reopened.evaluate(() => window.lexoraDesktop.browser.listGuests())
+ expect(guests).toContainEqual(expect.objectContaining({ sessionId: state.sessionId, pageId: state.pageId }))
+ const nextToken = await reopened.evaluate(() => window.lexoraDesktop.browser.acquirePresentation())
+ await reopened.evaluate(input => window.lexoraDesktop.browser.present(input), { ...presentation, presentationId: nextToken })
+ const resumed = await app.evaluate(async ({ webContents }, id) => {
+ const contents = webContents.fromId(id)
+ const button = await contents.executeJavaScript('(()=>{const r=document.querySelector("button").getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}})()')
+ const point = { x: Math.round(button.x * contents.getZoomFactor()), y: Math.round(button.y * contents.getZoomFactor()) }
+ contents.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point })
+ contents.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point })
+ return { id: contents.id, zoom: contents.getZoomFactor(), text: await contents.executeJavaScript('document.querySelector("#text").value') }
+ }, pageId)
+ expect(resumed).toEqual({ id: pageId, zoom: 1.25, text: initial.text })
+ await expect.poll(() => app.evaluate(({ webContents }, id) => webContents.fromId(id).executeJavaScript('window.clicks'), pageId)).toBe(2)
+ await expect.poll(() => app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows().filter(window => window.webContents.getURL().startsWith('lexora-app:')).length)).toBe(1)
+ const image = await app.evaluate(async ({ desktopCapturer }) => {
+ const [screen] = await desktopCapturer.getSources({ types: ['screen'], thumbnailSize: { width: 1500, height: 950 } })
+ return screen.thumbnail.toPNG().toString('base64')
+ })
+ await testInfo.attach('reattached-browser', { body: Buffer.from(image, 'base64'), contentType: 'image/png' })
+ }
+ finally {
+ server.closeAllConnections()
+ await new Promise(resolve => server.close(resolve))
+ }
+})
diff --git a/.playwright/scripts/__tests__/browser-selection-references.e2e.mjs b/.playwright/scripts/__tests__/browser-selection-references.e2e.mjs
index 3a7ed7349..121fde881 100644
--- a/.playwright/scripts/__tests__/browser-selection-references.e2e.mjs
+++ b/.playwright/scripts/__tests__/browser-selection-references.e2e.mjs
@@ -26,7 +26,7 @@ test('browser button picks a typed element without clicking the page, cancels sa
const cards = page.locator('.desktop-chat-composer-wrap .resource-quote-card')
async function nativePoint(selector, click = true) {
return app.evaluate(async ({ webContents }, { url, selector, click }) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
if (!guest)
throw new Error('Fixture guest missing')
const rect = await guest.executeJavaScript(`(() => { const r = document.querySelector(${JSON.stringify(selector)}).getBoundingClientRect(); return { x:r.x+r.width/2, y:r.y+r.height/2, width:innerWidth, height:innerHeight }; })()`)
@@ -36,7 +36,6 @@ test('browser button picks a typed element without clicking the page, cancels sa
guest.sendInputEvent({ type: 'mouseDown', button: 'left', clickCount: 1, ...point })
guest.sendInputEvent({ type: 'mouseUp', button: 'left', clickCount: 1, ...point })
}
- return { x: point.x / guest.getZoomFactor() / rect.width, y: point.y / guest.getZoomFactor() / rect.height }
}, { url, selector, click })
}
async function waitPicker() {
@@ -49,7 +48,7 @@ test('browser button picks a typed element without clicking the page, cancels sa
await expect(cards.first()).toContainText('Frozen link excerpt')
await expect(input).toContainText('Keep my latest question.')
await expect(address).toHaveValue(url)
- expect(await app.evaluate(async ({ webContents }, url) => webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url).executeJavaScript('Boolean(window.clicked)'), url)).toBe(false)
+ expect(await app.evaluate(async ({ webContents }, url) => webContents.getAllWebContents().find(contents => contents.getURL() === url).executeJavaScript('Boolean(window.clicked)'), url)).toBe(false)
await cards.first().locator('.chat-reference-card__link').click()
await expect(page.locator('.resource-quote-preview:visible')).toContainText('Frozen link excerpt')
await page.getByRole('button', { name: '定位来源', exact: true }).click()
@@ -73,7 +72,7 @@ test('browser button picks a typed element without clicking the page, cancels sa
await waitPicker()
await nativePoint('button')
await expect(cards).toHaveCount(2)
- expect(await app.evaluate(async ({ webContents }, url) => webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url).executeJavaScript('Boolean(window.submitted)'), url)).toBe(false)
+ expect(await app.evaluate(async ({ webContents }, url) => webContents.getAllWebContents().find(contents => contents.getURL() === url).executeJavaScript('Boolean(window.submitted)'), url)).toBe(false)
await page.evaluate(async () => {
const [guest] = await window.lexoraDesktop.browser.listGuests()
await window.lexoraDesktop.browser.setZoomFactor(guest.sessionId, 1)
@@ -84,7 +83,7 @@ test('browser button picks a typed element without clicking the page, cancels sa
await expect(cards).toHaveCount(3)
await expect(cards.last()).not.toContainText('must-not-capture')
await app.evaluate(async ({ webContents }, url) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
await guest.executeJavaScript('document.querySelector("#large").textContent="x".repeat(32769); document.querySelector("#large").style="height:24px;overflow:hidden"')
}, url)
await pick.click()
@@ -103,63 +102,19 @@ test('browser button picks a typed element without clicking the page, cancels sa
await input.click()
await expect(pick).toBeVisible()
await app.evaluate(async ({ webContents }, url) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
await guest.executeJavaScript('document.querySelector("#target").textContent="New snapshot for one target"')
}, url)
await pick.click()
await waitPicker()
- const anchor = await nativePoint('#target')
+ await nativePoint('#target')
const menu = page.locator('.resource-selection-menu.n-dropdown:visible')
- const surface = page.getByTestId('browser-guest-surface')
- async function checkMenuPosition(point) {
- const viewport = await surface.boundingBox()
- const box = await menu.boundingBox()
- const windowSize = await page.evaluate(() => ({ width: innerWidth, height: innerHeight }))
- const x = viewport.x + point.x * viewport.width
- const y = viewport.y + point.y * viewport.height
- expect(box.x).toBeGreaterThanOrEqual(0)
- expect(box.y).toBeGreaterThanOrEqual(0)
- expect(box.x + box.width).toBeLessThanOrEqual(windowSize.width + 1)
- expect(box.y + box.height).toBeLessThanOrEqual(windowSize.height + 1)
- if (x + box.width + 8 < windowSize.width) {
- expect(Math.abs(box.x - x)).toBeLessThan(8)
- }
- else {
- expect(box.x).toBeLessThanOrEqual(x + 8)
- expect(box.x + box.width).toBeGreaterThanOrEqual(x - 8)
- }
- expect(Math.min(Math.abs(box.y - y), Math.abs(box.y + box.height - y))).toBeLessThan(16)
- }
await expect(menu).toBeVisible()
- await checkMenuPosition(anchor)
await menu.getByRole('menuitem', { name: '引用到其他对话', exact: true }).hover()
const targets = page.locator('.resource-selection-menu:visible').filter({ has: page.locator('.resource-selection-menu-option__label').filter({ hasText: /^分屏 2/ }) })
await targets.getByRole('menuitem').filter({ hasText: /^分屏 2/ }).click()
await expect(page.locator('.resource-quote-card').filter({ hasText: 'New snapshot for one target' })).toHaveCount(1)
await expect(inputs.first()).toContainText('Keep my latest question.')
- await page.evaluate(async () => {
- const [guest] = await window.lexoraDesktop.browser.listGuests()
- await window.lexoraDesktop.browser.setZoomFactor(guest.sessionId, 1.5)
- })
- await pick.click()
- await waitPicker()
- const zoomAnchor = await nativePoint('#target')
- await expect(menu).toBeVisible()
- await checkMenuPosition(zoomAnchor)
- await page.keyboard.press('Escape')
- await expect(menu).not.toBeVisible()
- await app.evaluate(async ({ webContents }, url) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
- await guest.executeJavaScript('document.querySelector("#target").style="position:fixed;bottom:12px;right:12px;width:80px;height:32px;padding:0;margin:0;overflow:hidden"')
- }, url)
- await pick.click()
- await waitPicker()
- const edgeAnchor = await nativePoint('#target')
- await expect(menu).toBeVisible()
- await checkMenuPosition(edgeAnchor)
- await page.keyboard.press('Escape')
- await expect(menu).not.toBeVisible()
- await expect(page.locator('.resource-quote-card').filter({ hasText: 'New snapshot for one target' })).toHaveCount(1)
await pick.click()
await waitPicker()
await address.fill(`${url}?next`)
@@ -194,7 +149,7 @@ test('native element identity survives scrolling and shadow roots, rejects repla
await address.press('Enter')
await expect(page.getByTestId('browser-pick-element')).toBeEnabled()
const guestEval = expression => app.evaluate(async ({ webContents }, { url, expression }) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
return guest.executeJavaScript(expression)
}, { url, expression })
await expect.poll(() => guestEval('Boolean(document.querySelector("iframe")?.contentDocument?.querySelector("button"))')).toBe(true)
@@ -207,7 +162,7 @@ test('native element identity survives scrolling and shadow roots, rejects repla
}
async function point(target, click = false) {
await app.evaluate(async ({ webContents }, { url, target, click }) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
const point = await guest.executeJavaScript(`(() => {
const target = ${JSON.stringify(target)};
const frame = document.querySelector('iframe');
diff --git a/.playwright/scripts/__tests__/commandCapacity.ts b/.playwright/scripts/__tests__/commandCapacity.ts
new file mode 100644
index 000000000..31f3a3d37
--- /dev/null
+++ b/.playwright/scripts/__tests__/commandCapacity.ts
@@ -0,0 +1,93 @@
+import assert from 'node:assert/strict'
+import { stat, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import { performance } from 'node:perf_hooks'
+import process from 'node:process'
+import { setImmediate as yieldLoop } from 'node:timers/promises'
+import { ComposerDraftCommandService } from '../../../apps/buddy/service/src/chat/ComposerDraftCommandService'
+import { ComposerDraftService } from '../../../apps/buddy/service/src/chat/ComposerDraftService'
+import { CommandAdmissionService, createLocalCommandPrincipal } from '../../../apps/buddy/service/src/commands/CommandAdmissionService'
+import { createComposerDraftRepository } from '../../../apps/buddy/service/src/storage/composerDraftRepository'
+import { openBuddyMigrationCandidate } from '../../../apps/buddy/service/src/storage/database'
+import { createBuddyUserContent } from '../../../apps/buddy/shared/conversation/buddyUserContent'
+
+export async function runCommandCapacity(root: string, bundleSha256: string) {
+ const path = join(root, 'capacity.sqlite3')
+ const database = openBuddyMigrationCandidate({ databasePath: path })
+ database.exec('UPDATE storage_profile SET authority = \'sqlite\', migration_state = \'ready\'')
+ const repository = createComposerDraftRepository(database)
+ const executionConfig = { approvalPolicy: 'policy', executionProfile: 'read_only' } as const
+ repository.open({ draftId: 'capacity', scope: { kind: 'task', draftId: 'capacity', spaceId: null }, initialContent: createBuddyUserContent(), initialExecutionConfig: executionConfig, initialModelSelection: null, now: new Date().toISOString() })
+ const drafts = new ComposerDraftService(repository, async () => {})
+ const principal = createLocalCommandPrincipal(database)
+ const admission = new CommandAdmissionService({ database, principal, sourceInstanceId: 'capacity-instance' })
+ const commands = new ComposerDraftCommandService({
+ database,
+ actorId: principal.actorId,
+ admission,
+ drafts,
+ prepareAttachments: async () => { throw new Error('This workload does not copy files') },
+ releaseResources: async () => {},
+ onCleanupError: (error) => { throw error },
+ })
+ const samples: number[] = []
+ const dataGeneration = String(database.prepare('SELECT data_generation FROM storage_profile').get()!.data_generation)
+ const count = 6000
+ const report = {
+ platform: process.platform,
+ node: process.version,
+ bundleSha256,
+ commands: count,
+ inputCharacters: 16_384,
+ continuousTypingEquivalentSeconds: count * 1.5,
+ intermittentTypingEquivalentSeconds: count * 0.3,
+ limits: { commitP99Ms: 25, bytesPerCommand: 2048, receiptPayloadBytes: 1024 },
+ commitP99Ms: 0,
+ databaseBytes: 0,
+ bytesPerCommand: 0,
+ maxReceiptPayloadBytes: 0,
+ backupBytes: 0,
+ passed: false,
+ }
+ try {
+ const baseline = Number(database.prepare('PRAGMA page_count').get()!.page_count) * Number(database.prepare('PRAGMA page_size').get()!.page_size)
+ for (let index = 0; index < count; index++) {
+ const started = performance.now()
+ const result = await commands.execute('composerDrafts.save', {
+ dataGeneration,
+ commandId: `save-${index}`,
+ expectedServiceInstanceId: 'capacity-instance',
+ intent: { draftId: 'capacity', expectedRevision: index, content: createBuddyUserContent(`${index}:`.padEnd(report.inputCharacters, 'x')), executionConfig, modelSelection: null },
+ })
+ assert.equal(result.receipt.decision, 'accepted')
+ samples.push(performance.now() - started)
+ if (index % 32 === 0)
+ await yieldLoop()
+ }
+ const sorted = samples.toSorted((a, b) => a - b)
+ report.commitP99Ms = sorted[Math.ceil(sorted.length * 0.99) - 1]!
+ assert.equal(database.prepare('SELECT COUNT(*) AS count FROM command_receipts').get()!.count, count)
+ report.maxReceiptPayloadBytes = Number(database.prepare('SELECT MAX(length(CAST(target_json AS BLOB)) + length(CAST(result_json AS BLOB))) AS value FROM command_receipts').get()!.value)
+ database.exec('PRAGMA wal_checkpoint(TRUNCATE)')
+ report.databaseBytes = (await stat(path)).size
+ report.bytesPerCommand = (report.databaseBytes - baseline) / count
+ const backup = join(root, 'capacity-backup.sqlite3')
+ database.prepare('VACUUM INTO ?').run(backup)
+ report.backupBytes = (await stat(backup)).size
+ repository.discard({ draftId: 'capacity', expectedRevision: count })
+ assert.equal(admission.lookup({ dataGeneration, commandId: 'save-0' }).lookup, 'decided')
+ assert.equal(admission.lookup({ dataGeneration, commandId: `save-${count - 1}` }).lookup, 'decided')
+ assert(report.commitP99Ms <= report.limits.commitP99Ms)
+ assert(report.bytesPerCommand <= report.limits.bytesPerCommand)
+ assert(report.maxReceiptPayloadBytes <= report.limits.receiptPayloadBytes)
+ report.passed = true
+ process.stdout.write(`Command capacity: ${count} decisions, ${report.bytesPerCommand.toFixed(1)} bytes/command, commit P99 ${report.commitP99Ms.toFixed(2)}ms\n`)
+ }
+ finally {
+ await commands.dispose()
+ await admission.dispose()
+ await drafts.dispose()
+ database.close()
+ await writeFile(join(root, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
+ }
+}
diff --git a/.playwright/scripts/__tests__/connections.e2e.mjs b/.playwright/scripts/__tests__/connections.e2e.mjs
new file mode 100644
index 000000000..c50052673
--- /dev/null
+++ b/.playwright/scripts/__tests__/connections.e2e.mjs
@@ -0,0 +1,99 @@
+import { Buffer } from 'node:buffer'
+import { createHash, X509Certificate } from 'node:crypto'
+import { once } from 'node:events'
+import { request } from 'node:https'
+import { createServer } from 'node:net'
+import { connect } from 'node:tls'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+
+test('mobile connections start without manual addressing and show centered empty or paired devices', async ({ buddy }, testInfo) => {
+ const instance = await buddy.createInstance('connections-settings')
+ const desktop = await instance.launch({ storageAuthority: 'sqlite' })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const reservation = createServer().listen(0, '127.0.0.1')
+ await once(reservation, 'listening')
+ const port = reservation.address().port
+ await new Promise(resolve => reservation.close(resolve))
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false, port }), port)
+ expect(await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.status({}))).toMatchObject({ enabled: false, bindAddress: null })
+ await page.locator('.desktop-app-sidebar').getByRole('button', { name: '设置', exact: true }).click()
+ await page.getByRole('link', { name: '连接', exact: true }).click()
+ const settings = page.getByTestId('private-network-settings')
+ const toggle = settings.getByRole('switch', { name: '允许移动设备连接' })
+ await expect(toggle).toBeEnabled()
+ await expect(settings.getByRole('textbox')).toHaveCount(0)
+ await expect(settings.getByRole('spinbutton')).toHaveCount(0)
+ const area = page.getByTestId('paired-devices-empty-area')
+ const empty = page.getByTestId('paired-devices-empty')
+ await expect(empty).toBeVisible()
+ async function assertCentered() {
+ const outer = await area.boundingBox()
+ const inner = await empty.boundingBox()
+ expect(Math.abs(outer.x + outer.width / 2 - inner.x - inner.width / 2)).toBeLessThanOrEqual(2)
+ expect(Math.abs(outer.y + outer.height / 2 - inner.y - inner.height / 2)).toBeLessThanOrEqual(2)
+ }
+ await assertCentered()
+ await page.screenshot({ path: testInfo.outputPath('connections-empty-light.png') })
+ await page.evaluate(() => window.lexoraDesktop.themes.request({ action: 'preference', preference: { id: 'lexora.themes.classic-dark' } }))
+ await assertCentered()
+ await page.screenshot({ path: testInfo.outputPath('connections-empty-dark.png') })
+ const browserWindow = await desktop.app.browserWindow(page)
+ await browserWindow.evaluate(window => window.setSize(900, 650))
+ await assertCentered()
+ await page.screenshot({ path: testInfo.outputPath('connections-empty-narrow.png') })
+ expect(await settings.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
+ await browserWindow.evaluate(window => window.setSize(1440, 900))
+ await page.evaluate(() => window.lexoraDesktop.themes.request({ action: 'preference', preference: { id: 'lexora.themes.classic-light' } }))
+ await toggle.click()
+ await expect(toggle).toBeChecked()
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.status({}))).toMatchObject({ state: 'listening', port })
+ await settings.getByRole('button', { name: '配对新设备', exact: true }).click()
+ await expect(page.getByTestId('device-pairing-code').locator('canvas')).toBeVisible()
+ await page.screenshot({ path: testInfo.outputPath('connections-pairing.png') })
+ await page.keyboard.press('Escape')
+ await expect(page.getByTestId('device-pairing-code')).toBeHidden()
+ const qr = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ const { serviceId, profileId, issuerInstanceId, ticketId, ticketSecret } = qr
+ const context = { serviceId, profileId, issuerInstanceId, ticketId, ticketSecret }
+ const call = await pairedTransport(qr)
+ const prepared = await call('/v1/pairing/prepare', { ...context, deviceName: '测试手机' })
+ const credentials = await call('/v1/pairing/redeem', { ...context, attemptId: prepared.attemptId, recoverySecret: prepared.recoverySecret })
+ await call('/v1/pairing/confirm', {}, `${credentials.credentialId}.${credentials.credentialSecret}`)
+ const list = page.getByTestId('paired-devices-list')
+ await expect(list.getByText('测试手机', { exact: true })).toBeVisible({ timeout: 15000 })
+ await expect(list).toContainText('已授权')
+ await expect(empty).toBeHidden()
+ await page.screenshot({ path: testInfo.outputPath('connections-paired.png') })
+ await list.getByRole('button', { name: '撤销访问' }).click()
+ await page.getByRole('button', { name: '确认', exact: true }).click()
+ await expect(list).toContainText('已撤销')
+ await toggle.click()
+ await expect(toggle).not.toBeChecked()
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.status({}))).toMatchObject({ enabled: false, state: 'disabled', endpoint: null })
+ expect(desktop.diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
+})
+
+async function pairedTransport(qr) {
+ const url = new URL(qr.endpoint)
+ const socket = connect({ host: url.hostname, port: Number(url.port), rejectUnauthorized: false })
+ await once(socket, 'secureConnect')
+ const certificate = new X509Certificate(socket.getPeerCertificate().raw)
+ socket.destroy()
+ const pin = `sha256/${createHash('sha256').update(certificate.publicKey.export({ type: 'spki', format: 'der' })).digest('base64')}`
+ expect(pin).toBe(qr.spkiPin)
+ return (path, body, bearer) => new Promise((resolve, reject) => {
+ const payload = JSON.stringify(body)
+ const req = request(`${qr.endpoint}${path}`, { method: 'POST', ca: certificate.toString(), headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(payload), ...(bearer ? { Authorization: `Bearer ${bearer}` } : {}) } }, (response) => {
+ const chunks = []
+ response.on('data', chunk => chunks.push(chunk))
+ response.on('end', () => {
+ if (response.statusCode !== 200)
+ reject(new Error(`Pairing failed: ${response.statusCode}`))
+ else resolve(JSON.parse(Buffer.concat(chunks).toString()))
+ })
+ })
+ req.on('error', reject)
+ req.end(payload)
+ })
+}
diff --git a/.playwright/scripts/__tests__/context-panel-draft-adoption.e2e.mjs b/.playwright/scripts/__tests__/context-panel-draft-adoption.e2e.mjs
index d0ce8626a..7c0038f05 100644
--- a/.playwright/scripts/__tests__/context-panel-draft-adoption.e2e.mjs
+++ b/.playwright/scripts/__tests__/context-panel-draft-adoption.e2e.mjs
@@ -80,7 +80,7 @@ test('first send with a browser reference preserves the open resource panel and
await pick.click()
await expect(pick).toHaveAttribute('aria-pressed', 'true')
await app.evaluate(async ({ webContents }, url) => {
- const guest = webContents.getAllWebContents().find(contents => contents.getType() === 'webview' && contents.getURL() === url)
+ const guest = webContents.getAllWebContents().find(contents => contents.getURL() === url)
const point = await guest.executeJavaScript('(() => { const r = document.querySelector("#picked").getBoundingClientRect(); return { x:r.x+r.width/2, y:r.y+r.height/2 }; })()')
const x = Math.round(point.x * guest.getZoomFactor())
const y = Math.round(point.y * guest.getZoomFactor())
diff --git a/.playwright/scripts/__tests__/extension-contributions.e2e.mjs b/.playwright/scripts/__tests__/extension-contributions.e2e.mjs
index 49a6e3211..e4cec717c 100644
--- a/.playwright/scripts/__tests__/extension-contributions.e2e.mjs
+++ b/.playwright/scripts/__tests__/extension-contributions.e2e.mjs
@@ -51,26 +51,6 @@ test('plugin-owned preferences activate contributions, yield native content and
const alpha = await pluginFrame('alpha', 'footer')
await expect(alpha.getByText('tests.alpha content')).toBeVisible()
await expect(nativeFooter()).toHaveCount(0)
- const identity = await alpha.evaluate(() => window.fixture.instance)
- const hostColor = name => page.evaluate((name) => {
- const style = document.createElement('span').style
- style.color = getComputedStyle(document.documentElement).getPropertyValue(`--buddy-${name}`)
- return style.color
- }, name)
- await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { theme: { id: 'lexora.themes.violet-dark' } } }))
- await expect(page.locator('html')).toHaveAttribute('data-buddy-theme-id', 'lexora.themes.violet-dark')
- await expect.poll(() => alpha.evaluate(() => getComputedStyle(document.querySelector('main')).backgroundColor)).toBe(await hostColor('accent-solid'))
- await page.getByTestId('context-panel-toggle').click()
- await page.getByTestId('context-panel-more').click()
- await page.getByRole('menuitem', { name: '移到左侧', exact: true }).click()
- await page.getByTestId('context-panel-maximize').click()
- await expect.poll(() => visible('alpha')).toBe(false)
- await page.getByTestId('context-panel-maximize').click()
- await expect.poll(() => visible('alpha')).toBe(true)
- await page.getByTestId('context-panel-more').click()
- await page.getByRole('menuitem', { name: '移到右侧', exact: true }).click()
- await page.getByTestId('context-panel-more').click()
- await page.getByRole('menuitem', { name: '关闭', exact: true }).click()
const alphaActions = await pluginFrame('alpha', 'actions')
const actionFrame = await alphaActions.frameElement()
await actionFrame.waitForElementState('stable')
@@ -79,7 +59,6 @@ test('plugin-owned preferences activate contributions, yield native content and
await expect(nativeFooter()).toBeVisible()
await alphaActions.getByRole('checkbox', { name: 'Content tests.alpha' }).check()
await expect(alpha.getByText('tests.alpha content')).toBeVisible()
- expect(await alpha.evaluate(() => window.fixture.instance)).toBe(identity)
await installPlugin(instance, app, page, 'beta')
await preference('beta', true)
await expect.poll(() => visible('alpha')).toBe(true)
@@ -103,7 +82,7 @@ test('plugin-owned preferences activate contributions, yield native content and
await expect(nativeFooter()).toBeVisible()
})
-test('command failures distinguish execution, malformed replies and timeouts in the real plugin host', async ({ buddy }) => {
+test('command failures preserve diagnostics and responsive pending calls settle when the plugin is disabled', async ({ buddy }) => {
const instance = await buddy.createInstance('plugin-failures')
const { app, page } = await instance.launch()
const id = await installPlugin(instance, app, page, 'failures')
@@ -123,10 +102,17 @@ test('command failures distinguish execution, malformed replies and timeouts in
expect(await status()).toMatchObject({ state: 'active', error: null, logs: expect.arrayContaining([
expect.objectContaining({ code: 'EXTENSION_INVALID_RESULT', diagnostic: expect.objectContaining({ method: 'command', stage: 'result' }) }),
]) })
- expect(await execute('timeout')).toContain('EXTENSION_REQUEST_TIMEOUT')
- await expect.poll(status).toMatchObject({ state: 'failed', generation: null, error: 'EXTENSION_REQUEST_TIMEOUT', logs: expect.arrayContaining([
- expect.objectContaining({ event: 'host.failed', code: 'EXTENSION_REQUEST_TIMEOUT', diagnostic: { method: 'command', stage: 'timeout' } }),
- ]) })
+ let settled = false
+ const pending = execute('wait').then((error) => {
+ settled = true
+ return error
+ })
+ expect(await execute('read')).toBeNull()
+ expect(settled).toBe(false)
+ expect(await status()).toMatchObject({ state: 'active', error: null })
+ await page.evaluate(id => window.lexoraDesktop.extensions.enable(id, false), id)
+ expect(await pending).toContain('EXTENSION_AGENT_CANCELLED')
+ await expect.poll(status).toMatchObject({ state: 'disabled', generation: null, error: null })
expect(JSON.stringify(await status())).not.toContain('Private plugin error')
})
diff --git a/.playwright/scripts/__tests__/local-service-lifecycle.e2e.mjs b/.playwright/scripts/__tests__/local-service-lifecycle.e2e.mjs
new file mode 100644
index 000000000..2297ad758
--- /dev/null
+++ b/.playwright/scripts/__tests__/local-service-lifecycle.e2e.mjs
@@ -0,0 +1,328 @@
+import { execFile, spawn } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createRequire, isBuiltin } from 'node:module'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+import { chromium } from '@playwright/test'
+import { startDisplay } from '../buddy-test.mjs'
+import { expect, test } from '../fixtures/electron.mjs'
+import { processAlive as live, connectLocalService as management, readJson } from '../fixtures/local-service.mjs'
+import { ROOT } from '../shared.mjs'
+
+const buddyRoot = path.join(ROOT, 'apps/buddy')
+const require = createRequire(path.join(buddyRoot, 'package.json'))
+
+const execute = promisify(execFile)
+const cases = [{ storageAuthority: 'legacy_jsonl' }, { storageAuthority: 'sqlite' }]
+if (process.env.LEXORA_TEST_SESSION_SERVICE === '1')
+ cases.push({ storageAuthority: 'sqlite', sessionService: true })
+
+for (const { storageAuthority, sessionService } of cases) {
+ test(`independent Core maintains ${storageAuthority} storage${sessionService ? ', registered by systemd' : ''}, survives Desktop exit, and fully stops its host`, async ({ buddy }, testInfo) => {
+ test.skip(process.platform !== 'linux', 'The POSIX process-group acceptance runs on Linux')
+ test.setTimeout(180000)
+ const instance = await buddy.createInstance('independent-service')
+ let preparationModule
+ if (storageAuthority === 'sqlite') {
+ const preparation = testInfo.outputPath('profile-preparation')
+ const { build } = await import(pathToFileURL(require.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: {
+ ssr: path.join(ROOT, '.playwright/scripts/__tests__/prepareProductProfile.ts'),
+ outDir: preparation,
+ target: 'node26',
+ rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'prepare.mjs', format: 'es' } },
+ } })
+ preparationModule = await import(pathToFileURL(path.join(preparation, 'prepare.mjs')).href)
+ }
+ const display = await startDisplay()
+ const output = path.join(buddyRoot, '.output')
+ const release = JSON.parse(await fs.readFile(path.join(output, 'release-set.json'), 'utf8'))
+ const boot = (await fs.readFile('/proc/sys/kernel/random/boot_id', 'utf8')).trim()
+ let runtimeDirectory = path.join(instance.home, '.runtime')
+ await fs.mkdir(runtimeDirectory, { mode: 0o700 })
+ const config = {
+ version: 1,
+ profile: 'test',
+ profileRoot: instance.home,
+ resourcesRoot: path.join(output, path.dirname(release.core.entry), 'resources'),
+ nodeExecutable: path.join(output, release.node.entry),
+ coreEntry: path.join(output, release.core.entry),
+ hostExecutable: require('electron'),
+ hostArguments: ['--ozone-platform=x11', '--disable-setuid-sandbox', '--disable-gpu', '--remote-debugging-port=0', buddyRoot],
+ releaseSetPath: path.join(output, 'release-set.json'),
+ buildId: release.buildId,
+ sessionId: `${boot}:${process.env.XDG_SESSION_ID}`,
+ userId: String(process.getuid()),
+ leaseDirectory: path.join(path.dirname(instance.home), '.leases'),
+ storageAuthority,
+ }
+ const launchFile = path.join(runtimeDirectory, 'launch.json')
+ await fs.writeFile(launchFile, JSON.stringify(config), { mode: 0o600 })
+ let stderr = ''
+ const core = sessionService ? null : spawn(config.nodeExecutable, [config.coreEntry, '--config', launchFile], { cwd: ROOT, env: { ...process.env, DISPLAY: display.address, WAYLAND_DISPLAY: '', LEXORA_BUDDY_PROFILE: 'test', LEXORA_HOME: instance.home }, stdio: ['ignore', 'pipe', 'pipe'] })
+ core?.stderr.on('data', (value) => {
+ stderr += value
+ })
+ core?.stdout.on('data', (value) => {
+ stderr += value
+ })
+ let browser
+ let client
+ let product
+ let hostPid
+ let corePid = core?.pid
+ let unit
+ try {
+ if (sessionService) {
+ const launcher = preparationModule.resolveBuddyProcessControl({ appPath: config.resourcesRoot, resourcesPath: config.resourcesRoot, isPackaged: true })
+ expect(launcher).toBeTruthy()
+ const registration = new preparationModule.SessionServiceRegistration(config, launchFile, launcher)
+ unit = `${registration.name}.service`
+ const previousDisplay = process.env.DISPLAY
+ const previousWayland = process.env.WAYLAND_DISPLAY
+ process.env.DISPLAY = display.address
+ process.env.WAYLAND_DISPLAY = ''
+ try {
+ await registration.start()
+ }
+ finally {
+ if (previousDisplay === undefined)
+ delete process.env.DISPLAY
+ else process.env.DISPLAY = previousDisplay
+ if (previousWayland === undefined)
+ delete process.env.WAYLAND_DISPLAY
+ else process.env.WAYLAND_DISPLAY = previousWayland
+ }
+ }
+ await expect.poll(async () => {
+ const discovery = await readJson(path.join(runtimeDirectory, 'service.json'))
+ return discovery?.phase
+ }, { timeout: 120000 }).toBe('ready')
+ let discovery = await readJson(path.join(runtimeDirectory, 'service.json'))
+ if (unit) {
+ corePid = Number((await execute('/usr/bin/systemctl', ['--user', 'show', unit, '--property=MainPID', '--value'])).stdout.trim())
+ stderr = (await execute('/usr/bin/journalctl', ['--user', '-u', unit, '-o', 'cat', '--no-pager'], { maxBuffer: 4 * 1024 * 1024 })).stdout
+ }
+ expect(discovery.process.pid).toBe(corePid)
+ let credentials = await readJson(path.join(runtimeDirectory, 'local-client.json'))
+ client = await management(discovery, credentials.managementSecret)
+ await expect.poll(() => stderr.match(/DevTools listening on (ws:\/\/\S+)/)?.[1]).toBeTruthy()
+ browser = await chromium.connectOverCDP(stderr.match(/DevTools listening on (ws:\/\/\S+)/)[1])
+ expect(browser.contexts().flatMap(context => context.pages()).filter(page => page.url().startsWith('lexora-app:'))).toHaveLength(0)
+ const children = (await fs.readFile(`/proc/${corePid}/task/${corePid}/children`, 'utf8')).trim().split(/\s+/).filter(Boolean).map(Number)
+ const executable = await fs.realpath(config.hostExecutable)
+ const hosts = []
+ for (const pid of children) {
+ if (await fs.readlink(`/proc/${pid}/exe`).catch(() => null) === executable)
+ hosts.push(pid)
+ }
+ expect(hosts).toHaveLength(1)
+ hostPid = hosts[0]
+ const opened = await client.request('service.openDesktop', { expectedServiceInstanceId: discovery.serviceInstanceId, intent: { kind: 'tasks' } })
+ expect(opened).toMatchObject({ accepted: true, uiReady: true, targetVisible: true, visible: true })
+ let page = browser.contexts().flatMap(context => context.pages()).find(page => page.url().startsWith('lexora-app:'))
+ expect(page).toBeTruthy()
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready' })
+ const info = await page.evaluate(() => window.lexoraDesktop.app.getInfo())
+ expect(path.dirname(info.configPath)).toBe(instance.home)
+ const firstGeneration = await page.evaluate(async () => (await window.lexoraDesktop.app.startup.getState()).generation)
+ const snapshot = await page.evaluate(() => window.lexoraDesktop.storage.snapshot({ scopes: ['tasks', 'settings'], credentials: false }))
+ expect(snapshot.id).toBeTruthy()
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready', maintenance: null })
+ const backupGeneration = await page.evaluate(async () => (await window.lexoraDesktop.app.startup.getState()).generation)
+ expect(backupGeneration).not.toBe(firstGeneration)
+ expect((await client.request('service.status', {})).process.pid).toBe(corePid)
+ await page.evaluate(() => window.lexoraDesktop.localChat.runtime.restart())
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready', maintenance: null })
+ expect(await page.evaluate(async () => (await window.lexoraDesktop.app.startup.getState()).generation)).not.toBe(backupGeneration)
+ expect((await client.request('service.status', {})).process.pid).toBe(corePid)
+ await expect(client.request('service.beginMaintenance', { expectedServiceInstanceId: discovery.serviceInstanceId, kind: 'backup' })).rejects.toThrow()
+ const restart = async (expectedRoot = instance.home) => {
+ const previousHost = hostPid
+ const previousService = discovery.serviceInstanceId
+ await page.evaluate(() => window.lexoraDesktop.storage.restart())
+ runtimeDirectory = path.join(expectedRoot, '.runtime')
+ await expect.poll(async () => {
+ const next = await readJson(path.join(runtimeDirectory, 'service.json'))
+ return next?.phase === 'ready' && next.serviceInstanceId !== previousService
+ }, { timeout: 120000 }).toBe(true)
+ expect(await live(previousHost)).toBe(false)
+ discovery = await readJson(path.join(runtimeDirectory, 'service.json'))
+ credentials = await readJson(path.join(runtimeDirectory, 'local-client.json'))
+ client.close()
+ client = await management(discovery, credentials.managementSecret)
+ expect(discovery.process.pid).toBe(corePid)
+ if (unit)
+ stderr = (await execute('/usr/bin/journalctl', ['--user', '-u', unit, '-o', 'cat', '--no-pager'], { maxBuffer: 4 * 1024 * 1024 })).stdout
+ await browser.close().catch(() => {})
+ const endpoint = [...stderr.matchAll(/DevTools listening on (ws:\/\/\S+)/g)].at(-1)?.[1]
+ browser = await chromium.connectOverCDP(endpoint)
+ page = browser.contexts().flatMap(context => context.pages()).find(candidate => candidate.url().startsWith('lexora-app:'))
+ await expect.poll(() => page?.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready' })
+ expect(path.dirname((await page.evaluate(() => window.lexoraDesktop.app.getInfo())).configPath)).toBe(expectedRoot)
+ const children = (await fs.readFile(`/proc/${corePid}/task/${corePid}/children`, 'utf8')).trim().split(/\s+/).filter(Boolean).map(Number)
+ const nextHosts = []
+ for (const pid of children) {
+ if (await fs.readlink(`/proc/${pid}/exe`).catch(() => null) === executable)
+ nextHosts.push(pid)
+ }
+ expect(nextHosts).toHaveLength(1)
+ hostPid = nextHosts[0]
+ }
+ await restart()
+ if (storageAuthority === 'sqlite') {
+ if (sessionService) {
+ await page.evaluate(id => window.lexoraDesktop.storage.restore(id, { scopes: ['tasks', 'settings'], credentials: false }), snapshot.id)
+ await restart()
+ }
+ else {
+ const moved = `${instance.home}-moved`
+ await page.evaluate(target => window.lexoraDesktop.storage.relocate(target), moved)
+ await restart(moved)
+ }
+ }
+ await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { exitBehavior: 'keep_service' } }))
+ await page.screenshot({ path: testInfo.outputPath('independent-workbench.png'), animations: 'disabled', timeout: 10000 })
+ const closed = page.waitForEvent('close')
+ await page.evaluate(() => window.lexoraDesktop.commands.execute('app.quit'))
+ await closed
+ expect((await client.request('service.status', {})).process.pid).toBe(corePid)
+ expect(await live(hostPid)).toBe(true)
+ if (storageAuthority === 'sqlite') {
+ product = await management(discovery, credentials.productSecret, 'product')
+ const initialized = await product.request('initialize', { protocol: { major: 1, minMinor: 0, maxMinor: 0 }, client: { kind: 'mobile', version: 'test' }, supportedContentKinds: ['buddy-user-content-v1'], supportedReviewKinds: [] })
+ const command = { dataGeneration: initialized.dataGeneration, commandId: randomUUID(), expectedServiceInstanceId: initialized.serviceInstanceId, intent: { kind: 'settings' } }
+ const result = await product.request('desktop.open', command)
+ expect(result.receipt).toMatchObject({ decision: 'accepted', result: { desktop: { uiReady: true, targetVisible: true, visible: true } } })
+ expect(await product.request('desktop.open', command)).toEqual(result)
+ expect(await product.request('commands.get', { dataGeneration: command.dataGeneration, commandId: command.commandId })).toEqual({ lookup: 'decided', receipt: result.receipt })
+ }
+ else {
+ expect(await client.request('service.openDesktop', { expectedServiceInstanceId: discovery.serviceInstanceId, intent: { kind: 'settings' } })).toMatchObject({ targetVisible: true })
+ }
+ const reopened = browser.contexts().flatMap(context => context.pages()).find(page => page.url().startsWith('lexora-app:'))
+ expect(reopened).not.toBe(page)
+ expect(reopened.url()).toContain('#/settings/general')
+ await expect.poll(() => reopened.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready' })
+ expect((await reopened.evaluate(() => window.lexoraDesktop.settings.get())).desktop.exitBehavior).toBe('keep_service')
+ const exited = core ? once(core, 'exit') : null
+ if (storageAuthority === 'sqlite' && !sessionService) {
+ await reopened.evaluate(async () => {
+ await window.lexoraDesktop.settings.update({ desktop: { exitBehavior: 'stop_service' } })
+ void window.lexoraDesktop.commands.execute('app.quit')
+ })
+ }
+ else {
+ expect(await client.request('service.stop', { expectedServiceInstanceId: discovery.serviceInstanceId, commandId: randomUUID(), reason: 'explicit' })).toEqual({ accepted: true })
+ }
+ if (exited)
+ await exited
+ else await expect.poll(() => live(corePid)).toBe(false)
+ expect(await live(hostPid)).toBe(false)
+ expect(await readJson(path.join(runtimeDirectory, 'service.json'))).toBeNull()
+ }
+ finally {
+ product?.close()
+ client?.close()
+ await browser?.close().catch(() => {})
+ if (core && core.exitCode === null && core.signalCode === null) {
+ const exited = once(core, 'exit')
+ core.kill('SIGTERM')
+ await Promise.race([exited, new Promise(resolve => setTimeout(resolve, 10000))])
+ }
+ if (unit) {
+ await execute('/usr/bin/systemctl', ['--user', 'stop', unit]).catch(() => {})
+ stderr = (await execute('/usr/bin/journalctl', ['--user', '-u', unit, '-o', 'cat', '--no-pager'], { maxBuffer: 4 * 1024 * 1024 })).stdout
+ }
+ await display.stop()
+ await fs.writeFile(testInfo.outputPath('service.log'), stderr)
+ await testInfo.attach('service-log', { path: testInfo.outputPath('service.log'), contentType: 'text/plain' })
+ }
+ })
+}
+
+for (const legacy of [false, true]) {
+ test(`desktop launcher ${legacy ? 'upgrades legacy data and' : 'initializes SQLite and'} starts one session service, reuses it and honors installer shutdown`, async ({ buddy }, testInfo) => {
+ test.skip(process.platform !== 'linux' || process.env.LEXORA_TEST_SESSION_SERVICE !== '1', 'Requires an explicit Linux user-session service acceptance')
+ test.setTimeout(180000)
+ const instance = await buddy.createInstance('service-launcher', { executablePath: legacy ? process.env.LEXORA_TEST_LEGACY_EXECUTABLE : undefined })
+ let original
+ let draftId
+ if (legacy) {
+ const { page } = await instance.launch()
+ const editor = page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await editor.fill('启动升级保留草稿 😀')
+ await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes('启动升级保留草稿 😀'))?.draftId)).toBeTruthy()
+ draftId = await page.evaluate(async () => (await window.lexoraDesktop.localChat.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes('启动升级保留草稿 😀')).draftId)
+ await instance.stop()
+ original = await fs.readFile(path.join(instance.home, 'buddy/buddy.sqlite3'))
+ }
+ const display = await startDisplay()
+ const environment = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:LEXORA_|ELECTRON_|PI_)/.test(key)))
+ Object.assign(environment, { DISPLAY: display.address, WAYLAND_DISPLAY: '', XDG_SESSION_TYPE: 'x11', LEXORA_BUDDY_PROFILE: 'test', LEXORA_HOME: instance.home, LEXORA_BUDDY_SERVICE_MODE: 'daemon' })
+ const packaged = process.env.LEXORA_TEST_SERVICE_EXECUTABLE
+ if (packaged)
+ delete environment.LEXORA_BUDDY_SERVICE_MODE
+ const launch = async (...args) => {
+ const result = await execute(packaged ?? require('electron'), ['--ozone-platform=x11', '--disable-setuid-sandbox', '--disable-gpu', ...(packaged ? [] : [buddyRoot]), ...args], { cwd: ROOT, env: environment, timeout: 130000, maxBuffer: 1024 * 1024 })
+ await fs.appendFile(testInfo.outputPath('launcher.log'), result.stderr)
+ }
+ const directory = path.join(instance.home, '.runtime')
+ const launchFile = path.join(path.dirname(instance.home), '.lexora-locations', createHash('sha256').update(instance.home).digest('hex').slice(0, 24), 'service', 'launch.json')
+ let unit
+ let client
+ let corePid
+ try {
+ await launch('--background')
+ await expect.poll(() => readJson(launchFile), { timeout: 120000 }).not.toBeNull()
+ const config = await readJson(launchFile)
+ unit = `lexora-core-${createHash('sha256').update(`${config.defaultRoot ?? config.profileRoot}\0${config.sessionId}`).digest('hex').slice(0, 24)}.service`
+ expect(config.hostArguments).toEqual(expect.arrayContaining(['--ozone-platform=x11', '--disable-gpu']))
+ await expect.poll(() => readJson(path.join(directory, 'service.json')), { timeout: 120000 }).toMatchObject({ phase: 'ready' })
+ const discovery = await readJson(path.join(directory, 'service.json'))
+ expect(discovery.phase).toBe('ready')
+ corePid = discovery.process.pid
+ const credentials = await readJson(path.join(directory, 'local-client.json'))
+ client = await management(discovery, credentials.managementSecret)
+ const opened = await client.request('service.openDesktop', { expectedServiceInstanceId: discovery.serviceInstanceId, intent: { kind: 'tasks' } })
+ expect(opened).toMatchObject({ accepted: true, uiReady: true, targetVisible: true, visible: true })
+ await launch()
+ expect((await readJson(path.join(directory, 'service.json'))).serviceInstanceId).toBe(discovery.serviceInstanceId)
+ expect((await client.request('service.status', {})).process.pid).toBe(corePid)
+ await launch('--quit-for-install')
+ expect(await live(corePid)).toBe(false)
+ await expect.poll(() => readJson(path.join(directory, 'service.json'))).toBeNull()
+ await launch('--quit-for-install')
+ const location = await readJson(path.join(path.dirname(path.dirname(launchFile)), 'location.json'))
+ expect(discovery.profileId).toBe(location.identity.dataId)
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ expect(database.prepare('SELECT authority, migration_state FROM storage_profile').get()).toMatchObject({ authority: 'sqlite', migration_state: 'ready' })
+ if (legacy) {
+ expect(database.prepare('SELECT content_json FROM composer_drafts WHERE id = ?').get(draftId).content_json).toContain('启动升级保留草稿 😀')
+ const upgrade = location.history.find(operation => operation.kind === 'upgrade')
+ expect(await fs.readFile(path.join(upgrade.retainedTarget, 'buddy/buddy.sqlite3'))).toEqual(original)
+ }
+ }
+ finally { database.close() }
+ expect(await readJson(path.join(directory, 'service.json'))).toBeNull()
+ }
+ finally {
+ client?.close()
+ const config = await readJson(launchFile)
+ if (!unit && config)
+ unit = `lexora-core-${createHash('sha256').update(`${config.defaultRoot ?? config.profileRoot}\0${config.sessionId}`).digest('hex').slice(0, 24)}.service`
+ if (unit) {
+ await execute('/usr/bin/systemctl', ['--user', 'stop', unit]).catch(() => {})
+ const log = await execute('/usr/bin/journalctl', ['--user', '-u', unit, '-o', 'cat', '--no-pager'], { maxBuffer: 4 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath('launcher-service.log'), log.stdout)
+ }
+ await display.stop()
+ }
+ })
+}
diff --git a/.playwright/scripts/__tests__/mobile-approvals.e2e.mjs b/.playwright/scripts/__tests__/mobile-approvals.e2e.mjs
new file mode 100644
index 000000000..50f27d149
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-approvals.e2e.mjs
@@ -0,0 +1,235 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createServer as createListener } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+import { selectComposerPermission } from '../fixtures/model-controls.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Desktop and Android converge on approval winners, original receipts and cancelled runs', async ({ buddy }) => {
+ test.skip(!serial, 'Requires an isolated Android device with the debug and instrumentation APKs installed')
+ test.setTimeout(240000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 210000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-approval-${token}.json`
+ const configuration = test.info().outputPath('pairing.json')
+ const requests = []
+ const provider = createServer((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ requests.push(body)
+ const user = body.messages.findLastIndex(message => message.role === 'user')
+ const phase = JSON.stringify(body.messages[user]?.content).match(/Approval competition (\d)/)?.[1] ?? '0'
+ const write = !body.messages.slice(user + 1).some(message => message.role === 'tool')
+ const delta = write
+ ? { role: 'assistant', tool_calls: [{ index: 0, id: `approval-write-${phase}`, type: 'function', function: { name: 'write', arguments: JSON.stringify({ path: `approval-${phase}.txt`, content: `Approved exactly once ${phase} 😀` }) } }] }
+ : { role: 'assistant', content: `双端审批完成 ${phase}` }
+ const common = { id: `approval-${requests.length}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: write ? 'tool_calls' : 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-approvals')
+ await prepareMobileDesktopProfile(instance.home, test.info().outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ let { page } = desktop
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally { database.close() }
+ }
+ const listener = createListener()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ let instrument
+ const files = [0, 1, 2, 3].flatMap(phase => ['ready', 'done', 'resume'].map(stage => `files/approval-${token}-${phase}-${stage}.json`))
+ files.push(...['0', '2', 'final'].map(phase => `files/approval-${token}-${phase}.png`))
+ const checkpoint = async (phase, stage) => {
+ const file = `files/approval-${token}-${phase}-${stage}.json`
+ files.push(file)
+ let value
+ await expect.poll(async () => {
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', file)).stdout)
+ return true
+ }
+ catch { return false }
+ }, { timeout: 60000 }).toBe(true)
+ return value
+ }
+ try {
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'approval-fixture', displayName: 'Approval fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Approval model', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'approval-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('approval-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'approval-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.reload()
+ await selectComposerPermission(page, '人工审批')
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ const evidence = []
+ for (let phase = 0; phase < 5; phase++) {
+ await page.locator('.desktop-chat-composer__prosemirror:visible').fill(`Approval competition ${phase}`)
+ await page.getByRole('button', { name: '发送消息', exact: true }).click()
+ const card = page.locator('.desktop-approval-card').filter({ has: page.getByRole('button', { name: '允许一次', exact: true }) })
+ await expect(card).toBeVisible({ timeout: 45000 })
+ const pending = read(db => db.prepare('SELECT a.id, a.run_id, r.conversation_id FROM approvals a JOIN runs r ON a.run_id = r.id WHERE a.status = ?').get('pending'))
+ if (phase === 0) {
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, conversationId: pending.conversation_id, desktopLifecycle: serviceMode === 'daemon' }), { mode: 0o600 })
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.DesktopApprovalInstrumentedTest', '-e', 'desktopApprovalToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`).then(result => ({ result }), error => ({ error }))
+ }
+ const ready = await checkpoint(phase, 'ready')
+ expect(ready.approvalId).toBe(pending.id)
+ await page.screenshot({ path: test.info().outputPath(`desktop-pending-${phase}.png`) })
+ if (phase === 0) {
+ await card.getByRole('button', { name: '拒绝', exact: true }).click()
+ }
+ else if (phase === 1) {
+ if (serviceMode === 'daemon') {
+ await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { exitBehavior: 'keep_service' } }))
+ const closed = page.waitForEvent('close')
+ await page.evaluate(() => window.lexoraDesktop.commands.execute('app.quit'))
+ await closed
+ expect(desktop.app.process().exitCode).toBeNull()
+ expect(desktop.app.context().pages().filter(candidate => candidate.url().startsWith('lexora-app:'))).toHaveLength(0)
+ }
+ const reopened = serviceMode === 'daemon' ? desktop.app.context().waitForEvent('page', { timeout: 60000 }) : null
+ const resume = `files/approval-${token}-${phase}-resume.json`
+ files.push(resume)
+ await adb('shell', 'run-as', appPackage, 'touch', resume)
+ if (reopened) {
+ page = await reopened
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.app.startup.getState())).toMatchObject({ status: 'ready' })
+ await expect(page.locator('.buddy-chat-message').filter({ hasText: '双端审批完成 1' })).toBeVisible()
+ }
+ }
+ else if (phase === 2) {
+ await page.getByRole('button', { name: '停止运行', exact: true }).click()
+ }
+ else if (phase === 3) {
+ await page.evaluate(() => window.lexoraDesktop.localChat.runtime.restart())
+ await expect.poll(async () => (await page.evaluate(() => window.lexoraDesktop.localChat.runtime.getStatus())).status, { timeout: 45000 }).toBe('ready')
+ await adb('shell', 'run-as', appPackage, 'touch', `files/approval-${token}-${phase}-resume.json`)
+ }
+ else {
+ const resume = `files/approval-${token}-${phase}-resume.json`
+ files.push(resume)
+ await adb('shell', 'run-as', appPackage, 'touch', resume)
+ }
+ const expected = ['denied', 'approved', 'cancelled', 'cancelled', 'denied'][phase]
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM approvals WHERE id = ?').get(pending.id).status)).toBe(expected)
+ await expect(page.locator('.desktop-approval-card').getByRole('button', { name: '允许一次', exact: true })).toHaveCount(0)
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(pending.run_id).status)).not.toMatch(/^(queued|running)$/)
+ if (phase < 2 || phase === 4)
+ await expect(page.locator('.buddy-chat-message').filter({ hasText: `双端审批完成 ${phase}` })).toBeVisible()
+ const receipts = await checkpoint(phase, 'done')
+ const decision = read(db => db.prepare('SELECT * FROM approval_decisions WHERE approval_id = ?').get(pending.id))
+ expect(decision.resolution).toBe(phase === 2 || phase === 3 ? 'cancelled' : phase === 1 ? 'approved' : 'denied')
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM run_events WHERE run_id = ? AND event_type = \'approval.resolved\'').get(pending.run_id).count)).toBe(1)
+ const review = JSON.parse(read(db => db.prepare('SELECT review_json FROM approval_reviews WHERE approval_id = ?').get(pending.id).review_json))
+ const output = path.resolve(review.body.cwd, review.body.arguments.path)
+ expect(output.startsWith(`${instance.home}${path.sep}`)).toBe(true)
+ if (phase === 1) {
+ expect(await fs.readFile(output, 'utf8')).toBe('Approved exactly once 1 😀')
+ const rejected = await page.evaluate(async ({ approvalId, runId, reviewVersion }) => {
+ try {
+ await window.lexoraDesktop.localChat.approvals.deny(approvalId, { runId, reviewVersion })
+ return null
+ }
+ catch (error) { return String(error) }
+ }, { approvalId: pending.id, runId: pending.run_id, reviewVersion: review.reviewVersion })
+ expect(rejected).toContain('APPROVAL_ALREADY_RESOLVED')
+ expect(read(db => db.prepare('SELECT * FROM approval_decisions WHERE approval_id = ?').get(pending.id))).toEqual(decision)
+ expect(decision.actor_id).not.toBe(read(db => db.prepare('SELECT local_actor_id FROM storage_profile WHERE id = 1').get().local_actor_id))
+ }
+ else {
+ await expect(fs.stat(output)).rejects.toMatchObject({ code: 'ENOENT' })
+ }
+ if (phase === 4) {
+ expect(receipts[phase].receipt.decision).toBe('accepted')
+ expect(decision.actor_id).not.toBe(read(db => db.prepare('SELECT local_actor_id FROM storage_profile WHERE id = 1').get().local_actor_id))
+ }
+ evidence.push({ phase, approvalId: pending.id, runId: pending.run_id, decision, receipt: receipts[phase].receipt })
+ }
+ if (serviceMode === 'daemon') {
+ await checkpoint('final', 'ready')
+ await page.screenshot({ path: test.info().outputPath('desktop-final.png') })
+ await desktop.app.detachMain()
+ await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { exitBehavior: 'stop_service' } }))
+ const closed = page.waitForEvent('close')
+ await page.evaluate(() => {
+ void window.lexoraDesktop.commands.execute('app.quit')
+ })
+ await closed
+ expect(await checkpoint('final', 'done')).toEqual({ disconnected: true, outboxUnchanged: true })
+ await expect.poll(() => desktop.app.process().exitCode).toBe(0)
+ }
+ const outcome = await instrument
+ await fs.writeFile(test.info().outputPath('android-instrumentation.txt'), outcome.result?.stdout ?? String(outcome.error))
+ expect(outcome.error).toBeUndefined()
+ expect(outcome.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(outcome.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ for (const phase of ['0', '2', 'final']) {
+ const file = `files/approval-${token}-${phase}.png`
+ files.push(file)
+ const capture = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', file], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(test.info().outputPath(`android-${phase}.png`), capture.stdout)
+ }
+ await fs.writeFile(test.info().outputPath('approval-evidence.json'), JSON.stringify({ evidence, modelRequests: requests.length, coreAdapter: serviceMode, syntheticProvider: true }, null, 2))
+ if (!page.isClosed())
+ await page.screenshot({ path: test.info().outputPath('desktop-final.png') })
+ }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const interrupted = await instrument
+ if (interrupted)
+ await fs.writeFile(test.info().outputPath('android-instrumentation.txt'), interrupted.result?.stdout ?? String(interrupted.error))
+ await adb('shell', 'rm', '-f', remoteConfig)
+ if (files.length)
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', ...files)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of page.isClosed() ? [] : await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ if (!page.isClosed())
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ provider.closeAllConnections()
+ await new Promise(resolve => provider.close(resolve))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-branches.e2e.mjs b/.playwright/scripts/__tests__/mobile-branches.e2e.mjs
new file mode 100644
index 000000000..b4c7d0010
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-branches.e2e.mjs
@@ -0,0 +1,360 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer as createProvider } from 'node:http'
+import { createServer } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+const bindAddress = process.env.LEXORA_TEST_MOBILE_BIND_ADDRESS ?? '127.0.0.1'
+
+test('Android and Desktop browse and run separate branches concurrently without mixing drafts, questions or queues', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an Android device with current debug and instrumentation APKs')
+ test.setTimeout(420000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 360000, maxBuffer: 8 * 1024 * 1024 })
+ const bytes = async (...args) => (await execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 15000, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })).stdout
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-branches-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const identityBackup = `no_backup/branch-parallel-${token}-identity`
+ const files = new Set()
+ const marker = stage => `files/branches-${token}-${stage}.json`
+ const gates = Object.fromEntries(['A-initial', 'B-initial', 'A-result', 'B-result'].map(key => [key, Promise.withResolvers()]))
+ const requests = []
+ const cleanupFailures = []
+ let desktop
+ let port
+ let reversed = false
+ let started = false
+ let instrument
+ let outcome
+ const provider = createProvider((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ const input = body.messages.filter(message => message.role === 'user').map(message => JSON.stringify(message.content)).join('\n')
+ const markers = [...input.matchAll(/Parallel (baseline [AB]|edited A|branch ([AB]) main)|Queue branch ([AB])/g)]
+ const selected = markers.at(-1)
+ const branch = selected?.[2]
+ const queueBranch = selected?.[3]
+ const agentRequest = body.tools?.some(tool => tool.function?.name === 'lexora_ask_user') === true
+ const calls = body.messages.flatMap(message => message.tool_calls ?? [])
+ const ask = calls.find(call => call.function?.name === 'lexora_ask_user')
+ const waited = calls.some(call => call.function?.name === 'lexora_wait_user')
+ const phase = branch && agentRequest ? !ask ? 'initial' : !waited ? 'wait' : 'result' : queueBranch ? 'queue' : 'baseline'
+ const record = { branch: branch ?? queueBranch ?? null, phase, receivedAt: Date.now(), closedAt: null, body }
+ requests.push(record)
+ response.once('close', () => {
+ record.closedAt = Date.now()
+ })
+ const common = { id: `branch-${requests.length}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ const emit = (delta, finish = null) => response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`)
+ const hold = async key => Promise.race([gates[key].promise.then(() => true), once(response, 'close').then(() => false)])
+ let tool
+ if (phase === 'initial') {
+ emit({ role: 'assistant', content: `${branch} 并行输出开始 ${token}\n` })
+ if (!await hold(`${branch}-initial`))
+ return
+ tool = { id: `branch-${branch}-ask`, name: 'lexora_ask_user', arguments: JSON.stringify({ questions: [{ id: `answer-${branch}`, question: `只回答分支 ${branch} 的问题`, kind: 'text', options: [] }] }) }
+ }
+ else if (phase === 'wait') {
+ const result = body.messages.find(message => message.role === 'tool' && message.tool_call_id === ask.id)
+ const content = typeof result?.content === 'string' ? result.content : result?.content?.map(item => item.text ?? '').join('') ?? ''
+ const requestId = content.match(/"requestId"\s*:\s*"([^"]+)"/)?.[1]
+ if (!requestId)
+ throw new Error('Actual ask_user receipt did not contain requestId')
+ tool = { id: `branch-${branch}-wait`, name: 'lexora_wait_user', arguments: JSON.stringify({ requestId }) }
+ }
+ else if (phase === 'result') {
+ if (!JSON.stringify(body.messages).includes(`分支 ${branch} 的回答 ${token}`))
+ throw new Error('Answer was delivered to the wrong branch')
+ emit({ role: 'assistant', content: `${branch} 已收到本分支回答 ${token}\n` })
+ if (!await hold(`${branch}-result`))
+ return
+ emit({ content: `${branch} 并行完成 ${token}` })
+ }
+ else {
+ const text = queueBranch ? `${queueBranch} 队列独立完成 ${token}` : selected?.[1] === 'edited A' ? `编辑 A 的新分支结果 ${token}` : `历史 ${selected?.[1]?.endsWith('B') ? 'B' : 'A'} 原文 ${token}`
+ emit({ role: 'assistant', content: text })
+ }
+ if (tool)
+ emit({ role: 'assistant', tool_calls: [{ index: 0, id: tool.id, type: 'function', function: { name: tool.name, arguments: tool.arguments } }] })
+ emit({}, tool ? 'tool_calls' : 'stop')
+ response.end('data: [DONE]\n\n')
+ })().catch(error => response.destroy(error))
+ })
+ const checkpoint = async (stage) => {
+ files.add(marker(stage))
+ let value
+ await expect.poll(async () => {
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', marker(stage))).stdout)
+ return true
+ }
+ catch {
+ if (outcome)
+ throw new Error(outcome.result?.stdout ?? String(outcome.error))
+ return false
+ }
+ }, { timeout: 90000 }).toBe(true)
+ return value
+ }
+ const signal = async (stage) => {
+ files.add(marker(stage))
+ await adb('shell', 'run-as', appPackage, 'touch', marker(stage))
+ }
+ const restorePhone = async () => {
+ if (!started)
+ return
+ await adb('shell', 'am', 'force-stop', appPackage)
+ let manifest
+ for (const suffix of ['.json', '.json.bak']) {
+ manifest = await adb('shell', 'run-as', appPackage, 'cat', `${identityBackup}${suffix}`).then(value => JSON.parse(value.stdout), () => null)
+ if (manifest)
+ break
+ }
+ if (!manifest)
+ return
+ let failure
+ try {
+ const result = await adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.BranchParallelInstrumentedTest', '-e', 'branchParallelToken', token, '-e', 'branchParallelRestoreOnly', 'true', `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ await fs.writeFile(testInfo.outputPath('android-restoration.txt'), result.stdout + result.stderr)
+ expect(result.stdout).toMatch(/OK \(1 test\)/)
+ expect(result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ }
+ catch (error) { failure = error }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const original = await bytes('exec-out', 'run-as', appPackage, 'cat', `${identityBackup}.bin`)
+ expect(createHash('sha256').update(original).digest('hex')).toBe(manifest.sha256)
+ if (manifest.present) {
+ await adb('shell', 'run-as', appPackage, 'cp', `${identityBackup}.bin`, `${identityBackup}.restore`)
+ await adb('shell', 'run-as', appPackage, 'mv', `${identityBackup}.restore`, 'no_backup/device-identity.bin')
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ expect(createHash('sha256').update(await bytes('exec-out', 'run-as', appPackage, 'cat', 'no_backup/device-identity.bin')).digest('hex')).toBe(manifest.sha256)
+ }
+ else {
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ }
+ }
+ if (failure)
+ throw failure
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', `${identityBackup}.bin`, `${identityBackup}.json`, `${identityBackup}.json.bak`)
+ }
+ try {
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-branches')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally { database.close() }
+ }
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 }, desktop: { chat: { followUpBehavior: 'queue' } } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'branches-fixture', displayName: 'Branch verification', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Branch verification', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'branches-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('branches-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'branches-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.reload()
+ const composer = page.locator('.desktop-chat-composer__prosemirror:visible')
+ await composer.fill(`Parallel baseline A ${token}`)
+ await page.getByRole('button', { name: '发送消息', exact: true }).click()
+ await expect.poll(() => read(db => db.prepare('SELECT COUNT(*) AS count FROM runs WHERE status = \'completed\'').get().count)).toBe(1)
+ const first = read(db => db.prepare('SELECT id, conversation_id, branch_id, triggering_message_id FROM runs ORDER BY rowid LIMIT 1').get())
+ const conversationId = first.conversation_id
+ const branchA = first.branch_id
+ const originalRecords = read(db => db.prepare('SELECT id, content_json FROM messages WHERE branch_id = ? ORDER BY rowid').all(branchA))
+ const title = `分支并行验收 ${token.slice(0, 8)}`
+ const fork = await page.evaluate(async ({ conversationId, branchId, userMessageId, token, title }) => {
+ const api = window.lexoraDesktop.localChat
+ const current = await api.conversations.get(conversationId)
+ await api.conversations.rename(conversationId, title, current.titleRevision)
+ const draft = await api.composerDrafts.open({ draftId: crypto.randomUUID(), scope: { kind: 'message_edit', conversationId, branchId, userMessageId }, initialContent: { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text: `Parallel baseline B ${token}` }] }], panelResourceIds: [] }, initialModelSelection: null, initialExecutionConfig: { executionProfile: current.executionProfile, approvalPolicy: current.approvalPolicy } })
+ return api.chat.editUserMessage({ conversationId, userMessageId, draftId: draft.draftId, expectedRevision: draft.revision, requestId: crypto.randomUUID() })
+ }, { conversationId, branchId: branchA, userMessageId: first.triggering_message_id, token, title })
+ const branchB = fork.branchId
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(fork.runId).status)).toBe('completed')
+ expect(branchB).not.toBe(branchA)
+ await page.locator('[data-testid="conversation-branches"]:visible').click()
+ await page.getByTestId(`conversation-branch-${branchB}`).click()
+ const branchView = page.locator('[data-testid="conversation-branches"]:visible')
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, bindAddress, resolve))
+ port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ await page.evaluate(value => window.lexoraDesktop.localChat.privateNetwork.configure(value), { enabled: true, bindAddress, port })
+ if (bindAddress === '127.0.0.1') {
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ }
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, title, conversationId, branchA, branchB }), { mode: 0o600 })
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ started = true
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.BranchParallelInstrumentedTest', '-e', 'branchParallelToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`).then(result => ({ result }), error => ({ error })).then((value) => {
+ outcome = value
+ return value
+ })
+ const phone = await checkpoint('phone-started')
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ await composer.fill(`Parallel branch B main ${token}`)
+ await page.getByRole('button', { name: '发送消息', exact: true }).click()
+ await expect.poll(() => requests.filter(value => value.phase === 'initial').map(value => value.branch).sort(), { timeout: 45000 }).toEqual(['A', 'B'])
+ const runB = read(db => db.prepare('SELECT id FROM runs WHERE branch_id = ? AND status = \'running\'').get(branchB)).id
+ const concurrent = read(db => db.prepare('SELECT id, branch_id, buddy_id FROM runs WHERE id IN (?, ?) AND status = \'running\'').all(phone.runId, runB))
+ expect(concurrent).toHaveLength(2)
+ expect(new Set(concurrent.map(run => run.buddy_id)).size).toBe(1)
+ expect(requests.filter(value => value.phase === 'initial').every(value => value.closedAt === null)).toBe(true)
+ await expect(page.getByText(`B 并行输出开始 ${token}`, { exact: false })).toBeVisible()
+ await expect(page.getByText(`A 并行输出开始 ${token}`, { exact: false })).toHaveCount(0)
+ await signal('both-running')
+ await expect(composer).toHaveText('')
+ const queueText = `Queue branch B ${token}`
+ await composer.fill(queueText)
+ await page.locator('.desktop-chat-composer__actions:visible').getByRole('button', { name: '加入队列', exact: true }).click()
+ await expect(composer).toHaveText('')
+ const queuedRow = page.locator('.chat-message-queue__row:visible').filter({ hasText: queueText })
+ await expect(queuedRow).toBeVisible()
+ const queuedBranchB = await page.evaluate(value => window.lexoraDesktop.localChat.chat.listQueue(value), { conversationId, branchId: branchB })
+ expect(queuedBranchB).toHaveLength(1)
+ const queueB = queuedBranchB[0].id
+ await expect(queuedRow).toHaveAttribute('data-queued-message', queueB)
+ expect(queuedBranchB[0]).toMatchObject({ conversationId, branchId: branchB, state: 'waiting', delivery: { mode: 'next' }, content: { userContent: { body: [{ type: 'paragraph', content: [{ type: 'text', text: queueText }] }] } } })
+ const queuedA = await checkpoint('queue-a')
+ const desktopDraft = `电脑 B 独立草稿 ${token}`
+ await composer.fill(desktopDraft)
+ for (const branch of ['A', 'B']) gates[`${branch}-initial`].resolve()
+ const questions = branchId => page.evaluate(value => window.lexoraDesktop.localChat.questions.list(value), { conversationId, branchId })
+ await expect.poll(() => questions(branchA), { timeout: 45000 }).toMatchObject([{ status: 'pending', branchId: branchA }])
+ await expect.poll(() => questions(branchB), { timeout: 45000 }).toMatchObject([{ status: 'pending', branchId: branchB }])
+ await signal('questions-ready')
+ expect(await checkpoint('views-isolated')).toMatchObject({ recreated: true })
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ await expect(composer).toHaveText(desktopDraft)
+ await page.reload()
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ await expect(composer).toHaveText(desktopDraft)
+ await signal('answer-a')
+ await checkpoint('answered-a')
+ await expect.poll(() => requests.some(value => value.phase === 'result' && value.branch === 'A'), { timeout: 45000 }).toBe(true)
+ await signal('stop-a')
+ await checkpoint('stopped-a')
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(runB).status)).toBe('running')
+ expect((await questions(branchB))[0].status).toBe('pending')
+ expect(read(db => db.prepare('SELECT state FROM chat_queue WHERE id = ?').get(queuedA.queueId).state)).toBe('paused')
+ const queuedB = await page.evaluate(value => window.lexoraDesktop.localChat.chat.listQueue(value), { conversationId, branchId: branchB })
+ expect(queuedB).toHaveLength(1)
+ expect(queuedB[0]).toMatchObject({ id: queueB, branchId: branchB, state: 'waiting' })
+ const questionB = (await questions(branchB))[0]
+ await page.evaluate(value => window.lexoraDesktop.localChat.questions.answer(value), { conversationId, branchId: branchB, requestId: questionB.id, answers: [{ questionId: 'answer-B', selectedOptionIds: [], text: `分支 B 的回答 ${token}` }] })
+ await expect.poll(() => requests.some(value => value.phase === 'result' && value.branch === 'B'), { timeout: 45000 }).toBe(true)
+ await signal('edit-a')
+ const edited = await checkpoint('edited-a')
+ expect(edited.branchId).not.toBe(branchA)
+ expect(edited.branchId).not.toBe(branchB)
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(runB).status)).toBe('running')
+ expect(read(db => db.prepare(`SELECT id, content_json FROM messages WHERE id IN (${originalRecords.map(() => '?').join(',')}) ORDER BY rowid`).all(...originalRecords.map(value => value.id)))).toEqual(originalRecords)
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ await expect(composer).toHaveText(desktopDraft)
+ await signal('restore-a')
+ expect(await checkpoint('reconnected-a')).toMatchObject({ draft: `手机 A 独立草稿😀 ${token}` })
+ await page.reload()
+ await expect(branchView).toHaveAttribute('data-branch-id', branchB)
+ await expect(composer).toHaveText(desktopDraft)
+ gates['B-result'].resolve()
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(runB).status)).toBe('completed')
+ await expect.poll(() => requests.some(value => value.phase === 'queue' && value.branch === 'B')).toBe(true)
+ await expect.poll(() => read(db => db.prepare('SELECT COUNT(*) AS count FROM runs WHERE branch_id = ? AND status IN (\'running\',\'queued\')').get(branchB).count)).toBe(0)
+ await signal('b-finished')
+ const done = await checkpoint('done')
+ const result = await instrument
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error))
+ expect(result.error).toBeUndefined()
+ expect(result.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(result.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ const evidence = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', marker('done'))).stdout)
+ expect(evidence).toMatchObject({ ...done, originalIdentityRestored: true, independentDrafts: true, noGlobalActivation: true, landscapeImeVisible: true })
+ const text = branch => read(db => db.prepare('SELECT content_json FROM messages WHERE branch_id = ? ORDER BY rowid').all(branch)).map(value => value.content_json).join('\n')
+ expect(text(branchA)).not.toContain('B 并行')
+ expect(text(branchB)).not.toContain('A 并行')
+ expect(text(edited.branchId)).not.toContain('B 并行')
+ expect(read(db => db.prepare('SELECT active_branch_id FROM conversations WHERE id = ?').get(conversationId).active_branch_id)).toBe(branchA)
+ expect((await questions(branchA))[0]).toMatchObject({ status: 'answered', response: { answers: [{ text: `分支 A 的回答 ${token}` }] } })
+ expect((await questions(branchB))[0]).toMatchObject({ status: 'answered', response: { answers: [{ text: `分支 B 的回答 ${token}` }] } })
+ await fs.writeFile(testInfo.outputPath('branch-evidence.json'), JSON.stringify({ ...evidence, concurrent, queueA: queuedA.queueId, queueB, runB, edited, simultaneousProviderRequests: true, desktopBranchRestored: branchB, syntheticProvider: true, coreAdapter: serviceMode }, null, 2))
+ await page.screenshot({ path: testInfo.outputPath('desktop-branch-b.png') })
+ }
+ finally {
+ for (const stage of ['isolated', 'restored', 'landscape-ime']) {
+ const file = `files/branches-${token}-${stage}.png`
+ files.add(file)
+ const image = await bytes('exec-out', 'run-as', appPackage, 'cat', file).catch(() => null)
+ if (image?.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])))
+ await fs.writeFile(testInfo.outputPath(`android-${stage}.png`), image)
+ }
+ const touchFile = `files/branches-${token}-landscape-touch.json`
+ files.add(touchFile)
+ const touch = await adb('shell', 'run-as', appPackage, 'cat', touchFile).then(result => JSON.parse(result.stdout)).catch(() => null)
+ if (touch)
+ await fs.writeFile(testInfo.outputPath('android-landscape-touch.json'), JSON.stringify(touch, null, 2))
+ await restorePhone().catch(error => cleanupFailures.push(error))
+ const result = await instrument
+ if (result)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error))
+ for (const gate of Object.values(gates)) gate.resolve()
+ provider.closeAllConnections()
+ const cleanup = await Promise.allSettled([
+ adb('shell', 'rm', '-f', remoteConfig),
+ adb('shell', 'run-as', appPackage, 'rm', '-f', ...files),
+ fs.rm(configuration, { force: true }),
+ new Promise((resolve, reject) => provider.close(error => error ? reject(error) : resolve())),
+ (async () => {
+ try {
+ if (desktop) {
+ for (const device of await desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await desktop.page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ }
+ }
+ finally {
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ }
+ })(),
+ ])
+ cleanupFailures.push(...cleanup.filter(value => value.status === 'rejected').map(value => value.reason))
+ }
+ if (cleanupFailures.length)
+ throw new AggregateError(cleanupFailures, 'Could not restore the isolated mobile branches test')
+})
diff --git a/.playwright/scripts/__tests__/mobile-content.e2e.mjs b/.playwright/scripts/__tests__/mobile-content.e2e.mjs
new file mode 100644
index 000000000..aea305757
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-content.e2e.mjs
@@ -0,0 +1,98 @@
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:net'
+import process from 'node:process'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Legacy local Android content remains intact and read only while unsupported actions remain blocked', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an isolated Android device with debug and instrumentation APKs')
+ test.setTimeout(180000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 120000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-content-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const instance = await buddy.createInstance('mobile-content')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ const { page } = desktop
+ const editor = page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await expect(editor).toBeVisible()
+ await useSyntheticCredentialStorage(desktop)
+ await expect(editor).toBeVisible()
+ const original = '跨端中文😀e\u0301'
+ await editor.fill(original)
+ const getDraft = () => page.evaluate(async text => (await window.lexoraDesktop.localChat.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes(text)), original)
+ await expect.poll(getDraft).toBeTruthy()
+ const draft = await getDraft()
+ const content = {
+ version: 1,
+ body: [{ type: 'paragraph', content: [
+ { type: 'text', text: original },
+ { type: 'hard_break' },
+ { type: 'actor_ref', actorId: 'fixture-reader', name: '阅读者' },
+ { type: 'quote_ref', quoteKind: 'message', quoteId: 'frozen-quote' },
+ { type: 'session_ref', sessionId: 'historical-session' },
+ { type: 'prompt_directive', directive: 'slash_command', commandMode: 'prompt', value: '/review' },
+ ] }],
+ panelResourceIds: [],
+ quotes: [{ id: 'frozen-quote', text: '引用原文😀', textOffset: 2, source: { conversationId: 'archived-task', branchId: 'archived-branch', messageId: 'archived-reply', role: 'assistant', runId: null } }],
+ sessionReferences: [{ id: 'historical-session', title: '原来的任务' }],
+ }
+ const saved = await page.evaluate(({ draft, content }) => window.lexoraDesktop.localChat.composerDrafts.save({ draftId: draft.draftId, expectedRevision: draft.revision, content, modelSelection: draft.modelSelection, executionConfig: draft.executionConfig, participants: draft.participants ?? null }), { draft, content })
+ const large = await page.evaluate(async (executionConfig) => {
+ const id = crypto.randomUUID()
+ return window.lexoraDesktop.localChat.composerDrafts.open({ draftId: id, scope: { kind: 'task', draftId: id, spaceId: null }, initialContent: { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text: '大段内容'.repeat(30000) }] }], panelResourceIds: [] }, initialModelSelection: null, initialExecutionConfig: executionConfig })
+ }, draft.executionConfig)
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ let reversed = false
+ let instrument
+ try {
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, draftId: draft.draftId, largeDraftId: large.draftId }), { mode: 0o600 })
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.ContentInstrumentedTest', '-e', 'contentWorkflowToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`).then(result => ({ result }), error => ({ error }))
+ const outcome = await instrument
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), outcome.result?.stdout ?? String(outcome.error))
+ expect(outcome.error).toBeUndefined()
+ expect(outcome.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(outcome.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ const result = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', `files/content-${token}-result.json`)).stdout)
+ expect(result).toMatchObject({ richInputReadOnly: true, unsupportedInputPreserved: true, forbiddenActionRejected: true, noImplicitSend: true })
+ expect(result.content).toEqual(saved.content)
+ expect((await page.evaluate(id => window.lexoraDesktop.localChat.composerDrafts.get(id), draft.draftId)).content).toEqual(saved.content)
+ const screenshot = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', `files/content-${token}.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath('android-content.png'), screenshot.stdout)
+ await fs.writeFile(testInfo.outputPath('roundtrip.json'), JSON.stringify({ ...result, originalDesktopPreserved: true, coreAdapter: serviceMode }, null, 2))
+ }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const outcome = await instrument
+ if (outcome)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), outcome.result?.stdout ?? String(outcome.error))
+ await adb('shell', 'rm', '-f', remoteConfig)
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', `files/content-${token}-result.json`, `files/content-${token}.png`)
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-desktop.e2e.mjs b/.playwright/scripts/__tests__/mobile-desktop.e2e.mjs
new file mode 100644
index 000000000..e1d63f3c7
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-desktop.e2e.mjs
@@ -0,0 +1,199 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer as createProvider } from 'node:http'
+import { createServer } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+const bindAddress = process.env.LEXORA_TEST_MOBILE_BIND_ADDRESS ?? '127.0.0.1'
+const useAdbReverse = bindAddress === '127.0.0.1'
+const networkRecovery = process.env.LEXORA_TEST_MOBILE_NETWORK_RECOVERY === '1'
+
+test('real Desktop and Android keep independent local input and submit one immutable input with attachments', async ({ buddy }) => {
+ test.skip(!serial, 'Requires an isolated Android device with the debug and instrumentation APKs installed')
+ test.setTimeout(180000)
+ expect(!networkRecovery || !useAdbReverse, 'Wi-Fi recovery requires a real private-network address').toBe(true)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 90000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-desktop-${token}.json`
+ const ready = `files/desktop-${token}-ready.json`
+ const resume = `files/desktop-${token}-resume.json`
+ const instance = await buddy.createInstance('mobile-desktop')
+ await prepareMobileDesktopProfile(instance.home, test.info().outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const avatar = await page.evaluate(async () => {
+ const buddies = window.lexoraDesktop.localChat.buddies
+ const buddy = await buddies.get('default')
+ const canvas = document.createElement('canvas')
+ canvas.width = canvas.height = 64
+ const context = canvas.getContext('2d')
+ context.fillStyle = '#1d9076'
+ context.fillRect(0, 0, 64, 64)
+ context.fillStyle = '#f2d97d'
+ context.fillRect(16, 16, 32, 32)
+ const avatar = canvas.toDataURL('image/png')
+ await buddies.update({ buddyId: buddy.id, expectedRevision: buddy.revision, avatar })
+ return avatar
+ })
+ const avatarHash = createHash('sha256').update(Buffer.from(avatar.split(',')[1], 'base64')).digest('hex')
+ const requests = []
+ const provider = createProvider((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ const common = { id: 'local-input', model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: '输入和附件已收到' }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'input-fixture', displayName: 'Input fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Input model', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'input-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('input-fixture', 'api_key')
+ }
+ finally {
+ stop()
+ }
+ await providers.setDefaultModel({ providerId: 'input-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.reload()
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally {
+ database.close()
+ }
+ }
+ const editor = page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await expect(editor).toBeVisible()
+ const originalText = 'Desktop 原始输入 😀'
+ await editor.fill(originalText)
+ const getDraft = () => page.evaluate(async text => (await window.lexoraDesktop.localChat.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes(text)), originalText)
+ await expect.poll(getDraft).toBeTruthy()
+ const draft = await getDraft()
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, bindAddress, resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ const configuration = test.info().outputPath('pairing.json')
+ let instrument
+ try {
+ await page.evaluate(({ bindAddress, port }) => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress, port }), { bindAddress, port })
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, networkRecovery, avatarHash, draftId: draft.draftId, originalText }), { mode: 0o600 })
+ if (useAdbReverse)
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.DesktopWorkflowInstrumentedTest', '-e', 'desktopWorkflowToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ .then(result => ({ result }), error => ({ error }))
+ let checkpoint
+ await expect.poll(async () => {
+ try {
+ checkpoint = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', ready)).stdout)
+ return checkpoint.attachmentCount
+ }
+ catch { return null }
+ }, { timeout: 45000 }).toBe(1)
+ await expect(editor).toContainText(originalText)
+ const updatedText = 'Desktop 并发编辑保留 😀'
+ await editor.fill(updatedText)
+ await expect.poll(() => page.evaluate(async id => JSON.stringify((await window.lexoraDesktop.localChat.composerDrafts.get(id)).content), draft.draftId)).toContain(updatedText)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM composer_drafts WHERE owner_actor_id = ?').get(checkpoint.ownerDeviceId).count)).toBe(0)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM remote_uploads WHERE actor_id = ? AND input_id = ? AND state = \'ready\'').get(checkpoint.ownerDeviceId, checkpoint.inputId).count)).toBe(1)
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'))
+ try {
+ database.prepare('UPDATE remote_uploads SET state = \'expired\' WHERE actor_id = ? AND input_id = ? AND state = \'ready\'').run(checkpoint.ownerDeviceId, checkpoint.inputId)
+ }
+ finally {
+ database.close()
+ }
+ const continuation = test.info().outputPath('resume.json')
+ await fs.writeFile(continuation, JSON.stringify({ text: updatedText }))
+ await adb('push', continuation, `/data/local/tmp/lexora-desktop-${token}-resume.json`)
+ await adb('shell', 'run-as', appPackage, 'cp', `/data/local/tmp/lexora-desktop-${token}-resume.json`, resume)
+ if (networkRecovery) {
+ const waitMarker = stage => expect.poll(async () => {
+ try {
+ return (await adb('shell', 'run-as', appPackage, 'cat', `files/desktop-${token}-${stage}.json`)).stdout.trim() === 'ready'
+ }
+ catch { return false }
+ }, { timeout: 45000 }).toBe(true)
+ expect((await adb('shell', 'settings', 'get', 'global', 'wifi_on')).stdout.trim()).toBe('1')
+ await waitMarker('network-ready')
+ await adb('shell', 'svc', 'wifi', 'disable')
+ try {
+ await waitMarker('offline')
+ }
+ finally { await adb('shell', 'svc', 'wifi', 'enable') }
+ }
+ const outcome = await instrument
+ await fs.writeFile(test.info().outputPath('android-instrumentation.txt'), outcome.result?.stdout ?? String(outcome.error))
+ expect(outcome.error).toBeUndefined()
+ expect(outcome.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(outcome.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ await expect(editor).toContainText(updatedText)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM composer_drafts WHERE owner_actor_id = ?').get(checkpoint.ownerDeviceId).count)).toBe(0)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM command_receipts WHERE actor_id = ? AND method = \'chat.submitInput\' AND decision = \'accepted\'').get(checkpoint.ownerDeviceId).count)).toBe(1)
+ expect(JSON.stringify(requests)).toContain('Android 本地输入与附件')
+ expect(JSON.stringify(requests)).toContain('附件内容完整保留')
+ const screenshot = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', `files/desktop-${token}.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(test.info().outputPath('android-draft.png'), screenshot.stdout)
+ await page.screenshot({ path: test.info().outputPath('desktop-draft.png') })
+ const target = read(db => JSON.parse(db.prepare('SELECT target_json FROM command_receipts WHERE actor_id = ? AND method = \'chat.submitInput\' AND decision = \'accepted\'').get(checkpoint.ownerDeviceId).target_json))
+ await page.locator(`[data-task-id="${target.conversationId}"]`).first().click()
+ await page.getByRole('button', { name: '分屏打开', exact: true }).click()
+ await expect(editor).toContainText(updatedText)
+ await expect(page.locator('.desktop-workbench-area__tasks').getByText('输入和附件已收到', { exact: true })).toBeVisible()
+ await expect(page.locator('.desktop-workbench-area__tasks img').filter({ visible: true }).and(page.locator(`img[src="${avatar}"]`)).first()).toBeVisible()
+ await page.screenshot({ path: test.info().outputPath('desktop-conversation.png') })
+
+ await fs.writeFile(test.info().outputPath('workflow.json'), JSON.stringify({ ...checkpoint, localDrafts: true, immutableInput: true, nativeAndroidUi: true, electronUi: true, coreAdapter: serviceMode, wifiInterruptionRecovery: networkRecovery, customAvatar: true, avatarHash, offlineAvatar: networkRecovery, transport: useAdbReverse ? 'adb-reverse' : 'private-network', serverAddress: bindAddress }, null, 2))
+ }
+ finally {
+ if (networkRecovery)
+ await adb('shell', 'svc', 'wifi', 'enable')
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const interrupted = await instrument
+ if (interrupted)
+ await fs.writeFile(test.info().outputPath('android-instrumentation.txt'), interrupted.result?.stdout ?? String(interrupted.error))
+ await adb('shell', 'rm', '-f', remoteConfig, `/data/local/tmp/lexora-desktop-${token}-resume.json`)
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', ready, resume, `files/desktop-${token}.png`, `files/desktop-${token}-network-ready.json`, `files/desktop-${token}-offline.json`)
+ if (useAdbReverse)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ provider.closeAllConnections()
+ await new Promise(resolve => provider.close(resolve))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-devices.e2e.mjs b/.playwright/scripts/__tests__/mobile-devices.e2e.mjs
new file mode 100644
index 000000000..ba628f4d1
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-devices.e2e.mjs
@@ -0,0 +1,209 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer as createProvider } from 'node:http'
+import { createServer } from 'node:net'
+import process from 'node:process'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+const bindAddress = process.env.LEXORA_TEST_MOBILE_BIND_ADDRESS ?? '127.0.0.1'
+const useAdbReverse = bindAddress === '127.0.0.1'
+
+test('Android switches between two real computers without mixing credentials, scopes or local input', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an Android device with the debug and instrumentation APKs installed')
+ test.setTimeout(360000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 300000, maxBuffer: 8 * 1024 * 1024 })
+ const bytes = async (...args) => (await execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 15000, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })).stdout
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-devices-${token}.json`
+ const resultFile = `files/devices-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const computers = []
+ const captures = ['computer-switch', 'workbench', 'spaces', 'unassigned', 'space-tasks', 'new-space-task', 'conversation', 'restored-second-input']
+ const identityBackup = `no_backup/device-switch-${token}-identity`
+ const requests = []
+ const provider = createProvider((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ const common = { id: `devices-${requests.length}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: '空间验收回复:已收到这台电脑的任务。' }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ const cleanupFailures = []
+ let instrumentStarted = false
+ const restorePhone = async () => {
+ if (!instrumentStarted)
+ return
+ await adb('shell', 'am', 'force-stop', appPackage)
+ let manifest
+ for (const suffix of ['.json', '.json.bak']) {
+ manifest = await adb('shell', 'run-as', appPackage, 'cat', `${identityBackup}${suffix}`).then(result => JSON.parse(result.stdout), () => null)
+ if (manifest)
+ break
+ }
+ if (!manifest)
+ return
+ let cleanupError
+ try {
+ const cleanup = await adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.DeviceSwitchInstrumentedTest', '-e', 'deviceSwitchToken', token, '-e', 'deviceSwitchRestoreOnly', 'true', `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ await fs.writeFile(testInfo.outputPath('android-restoration.txt'), cleanup.stdout + cleanup.stderr)
+ expect(cleanup.stdout).toMatch(/OK \(1 test\)/)
+ expect(cleanup.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ }
+ catch (error) { cleanupError = error }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const original = await bytes('exec-out', 'run-as', appPackage, 'cat', `${identityBackup}.bin`)
+ expect(createHash('sha256').update(original).digest('hex')).toBe(manifest.sha256)
+ if (manifest.present) {
+ await adb('shell', 'run-as', appPackage, 'cp', `${identityBackup}.bin`, `${identityBackup}.restore`)
+ await adb('shell', 'run-as', appPackage, 'mv', `${identityBackup}.restore`, 'no_backup/device-identity.bin')
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ const restored = await bytes('exec-out', 'run-as', appPackage, 'cat', 'no_backup/device-identity.bin')
+ expect(createHash('sha256').update(restored).digest('hex')).toBe(manifest.sha256)
+ }
+ else {
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ }
+ }
+ if (cleanupError)
+ throw cleanupError
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', `${identityBackup}.json`, `${identityBackup}.json.bak`, `${identityBackup}.json.new`, `${identityBackup}.bin`)
+ await fs.writeFile(testInfo.outputPath('phone-restoration.json'), JSON.stringify({ originalIdentityRestored: true, testPartitionsRemoved: manifest.partitions.length, originalKeystorePreserved: true }))
+ }
+ try {
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ for (const label of ['first', 'second']) {
+ const instance = await buddy.createInstance(`mobile-devices-${label}`)
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath(`profile-preparation-${label}`))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const computer = { label, desktop, reversed: false }
+ computers.push(computer)
+ const display = label === 'first' ? 'A' : 'B'
+ const spaceName = `验收空间 ${display}`
+ const space = await desktop.page.evaluate(name => window.lexoraDesktop.localChat.spaces.create({ name, memoryScope: 'space_only', primaryDirectory: null }), spaceName)
+ await desktop.page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'devices-fixture', displayName: 'Devices verification', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Devices verification', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'devices-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('devices-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'devices-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ computer.tasks = []
+ for (const assigned of [true, false]) {
+ const title = `电脑 ${display} ${assigned ? '空间任务' : '未分配任务'}`
+ const task = await desktop.page.evaluate(async ({ spaceId, title }) => {
+ const api = window.lexoraDesktop.localChat
+ const draftId = crypto.randomUUID()
+ const draft = await api.composerDrafts.open({ draftId, scope: { kind: 'task', draftId, spaceId }, initialContent: { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text: title }] }], panelResourceIds: [] }, initialModelSelection: null, initialExecutionConfig: { executionProfile: 'read_only', approvalPolicy: 'policy' } })
+ const turn = await api.chat.startTurn({ draftId, expectedRevision: draft.revision, requestId: crypto.randomUUID() })
+ return { conversationId: turn.conversationId, branchId: turn.branchId, runId: turn.runId }
+ }, { spaceId: assigned ? space.id : null, title })
+ await expect.poll(() => desktop.page.evaluate(id => window.lexoraDesktop.localChat.runs.get(id), task.runId), { timeout: 30000 }).toMatchObject({ status: 'completed' })
+ await desktop.page.evaluate(async ({ id, title }) => {
+ const api = window.lexoraDesktop.localChat.conversations
+ const current = await api.get(id)
+ return api.rename(id, title, current.titleRevision)
+ }, { id: task.conversationId, title })
+ computer.tasks.push({ ...task, title, assigned })
+ }
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, bindAddress, resolve))
+ computer.port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ await desktop.page.evaluate(({ bindAddress, port }) => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress, port }), { bindAddress, port: computer.port })
+ computer.spaceId = space.id
+ computer.spaceName = spaceName
+ if (useAdbReverse) {
+ await adb('reverse', `tcp:${computer.port}`, `tcp:${computer.port}`)
+ computer.reversed = true
+ }
+ }
+ const config = {}
+ for (const computer of computers) {
+ const pairing = await computer.desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ config[computer.label] = { pairing, spaceId: computer.spaceId, spaceName: computer.spaceName, assignedTitle: computer.tasks.find(task => task.assigned).title, unassignedTitle: computer.tasks.find(task => !task.assigned).title }
+ }
+ expect(config.first.pairing.serviceId).not.toBe(config.second.pairing.serviceId)
+ expect(config.first.pairing.profileId).not.toBe(config.second.pairing.profileId)
+ await fs.writeFile(configuration, JSON.stringify(config), { mode: 0o600 })
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrumentStarted = true
+ const outcome = await adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.DeviceSwitchInstrumentedTest', '-e', 'deviceSwitchToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), outcome.stdout + outcome.stderr)
+ expect(outcome.stdout).toMatch(/OK \(1 test\)/)
+ expect(outcome.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ const checkpoint = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', resultFile)).stdout)
+ expect(checkpoint).toMatchObject({ deviceCount: 2, separateScopes: true, localDraftIsolation: true, staleIdentityRejected: true, previousConnectionClosed: true, forgotSelectedWithoutFallback: true, remainingDeviceReconnects: true, originalIdentityRestored: true, ui: { topBarDeviceSwitch: true, spaceNavigation: true, allAndUnassignedFilters: true, newTaskInheritsSpace: true, localInputIsolation: true, inputSurvivesRecreation: true } })
+ expect(new Set(checkpoint.partitions).size).toBe(2)
+ expect(checkpoint.firstServiceId).toBe(config.first.pairing.serviceId)
+ expect(checkpoint.secondServiceId).toBe(config.second.pairing.serviceId)
+ expect(await computers[0].desktop.page.evaluate(id => window.lexoraDesktop.localChat.conversations.get(id), checkpoint.ui.createdConversationId)).toMatchObject({ spaceId: config.first.spaceId })
+ expect(await computers[1].desktop.page.evaluate(() => window.lexoraDesktop.localChat.conversations.list())).toHaveLength(2)
+ const userInputs = JSON.stringify(requests.flatMap(request => request.messages.filter(message => message.role === 'user')))
+ expect(userInputs).toContain(`服务 A 空间草稿😀 ${token}`)
+ expect(userInputs).not.toContain(`服务 B 空间草稿😀 ${token}`)
+ for (const computer of computers) {
+ const devices = await computer.desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))
+ expect(devices.filter(device => device.state === 'active').map(device => device.deviceId)).toEqual([checkpoint[`${computer.label}DeviceId`]])
+ await computer.desktop.page.screenshot({ path: testInfo.outputPath(`desktop-${computer.label}.png`) })
+ }
+ await fs.writeFile(testInfo.outputPath('devices.json'), JSON.stringify({ ...checkpoint, coreAdapter: serviceMode, transport: useAdbReverse ? 'adb-reverse' : 'private-network', syntheticProvider: true, productDataFromCore: true }, null, 2))
+ }
+ finally {
+ for (const capture of captures) {
+ const image = await bytes('exec-out', 'run-as', appPackage, 'cat', `files/devices-${token}-${capture}.png`).catch(() => null)
+ if (image)
+ await fs.writeFile(testInfo.outputPath(`android-${capture}.png`), image)
+ }
+ await restorePhone().catch(error => cleanupFailures.push(error))
+ const cleanup = await Promise.allSettled([
+ adb('shell', 'rm', '-f', remoteConfig),
+ adb('shell', 'run-as', appPackage, 'rm', '-f', resultFile, ...captures.map(capture => `files/devices-${token}-${capture}.png`)),
+ fs.rm(configuration, { force: true }),
+ (async () => {
+ provider.closeAllConnections()
+ await new Promise((resolve, reject) => provider.close(error => error ? reject(error) : resolve()))
+ })(),
+ ...computers.map(async (computer) => {
+ try {
+ for (const device of await computer.desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await computer.desktop.page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await computer.desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ }
+ finally {
+ if (computer.reversed)
+ await adb('reverse', '--remove', `tcp:${computer.port}`)
+ }
+ }),
+ ])
+ cleanupFailures.push(...cleanup.filter(result => result.status === 'rejected').map(result => result.reason))
+ }
+ if (cleanupFailures.length)
+ throw new AggregateError(cleanupFailures, 'Could not clean up the isolated mobile device-switch test')
+})
diff --git a/.playwright/scripts/__tests__/mobile-history.e2e.mjs b/.playwright/scripts/__tests__/mobile-history.e2e.mjs
new file mode 100644
index 000000000..103d1ddf5
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-history.e2e.mjs
@@ -0,0 +1,190 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createServer as createListener } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Android historical followup, edit and regeneration preserve branches, restored input and exact source targets', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an isolated Android device with debug and instrumentation APKs')
+ test.setTimeout(240000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 210000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-history-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const requests = []
+ const provider = createServer((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const number = requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ const common = { id: `history-${number}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: `历史回复 ${number} 😀` }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-history')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally { database.close() }
+ }
+ const listener = createListener()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ let instrument
+ let outcome
+ let reversed = false
+ const marker = stage => `files/history-${token}-${stage}.json`
+ const files = new Set([`files/history-${token}-branches.png`])
+ const signal = async (stage) => {
+ files.add(marker(stage))
+ await adb('shell', 'run-as', appPackage, 'touch', marker(stage))
+ }
+ const checkpoint = async (stage) => {
+ files.add(marker(stage))
+ let value
+ await expect.poll(async () => {
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', marker(stage))).stdout)
+ return true
+ }
+ catch {
+ if (outcome)
+ throw new Error(outcome.result?.stdout ?? String(outcome.error))
+ return false
+ }
+ }, { timeout: 60000 }).toBe(true)
+ return value
+ }
+ try {
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'history-fixture', displayName: 'History fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'History model', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'history-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('history-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'history-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.reload()
+ for (const [index, input] of ['历史基线输入', '后续输入不应进入历史续写'].entries()) {
+ await page.locator('.desktop-chat-composer__prosemirror:visible').fill(input)
+ await page.getByRole('button', { name: '发送消息', exact: true }).click()
+ await expect.poll(() => read(db => db.prepare('SELECT COUNT(*) AS count FROM runs WHERE status = \'completed\'').get().count)).toBe(index + 1)
+ }
+ const original = read(db => db.prepare('SELECT id, conversation_id, branch_id FROM runs ORDER BY started_at LIMIT 1').get())
+ await page.evaluate(() => {
+ location.hash = '/settings/general'
+ })
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, conversationId: original.conversation_id, originalBranchId: original.branch_id }), { mode: 0o600 })
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.HistoryInstrumentedTest', '-e', 'historyToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ .then(result => ({ result }), error => ({ error }))
+ .then((result) => {
+ outcome = result
+ return result
+ })
+ const regenerated = await checkpoint('regenerated')
+ expect(requests).toHaveLength(5)
+ for (const index of [2, 3, 4]) {
+ const input = JSON.stringify(requests[index].messages)
+ expect(input).toContain('历史回复 1')
+ expect(input).not.toContain('后续输入不应进入历史续写')
+ expect(input).not.toContain('历史回复 2')
+ }
+ expect(JSON.stringify(requests[2].messages)).toContain('从第一条回复继续')
+ expect(JSON.stringify(requests[3].messages)).toContain('编辑后的接续输入')
+ expect(JSON.stringify(requests[4].messages)).toContain('编辑后的接续输入')
+ const activate = branchId => page.evaluate(async ({ conversationId, branchId }) => {
+ const api = window.lexoraDesktop.localChat.conversations
+ const current = await api.get(conversationId)
+ await api.activateBranch({ conversationId, branchId, expectedRevision: current.metadataRevision })
+ }, { conversationId: original.conversation_id, branchId })
+ await activate(original.branch_id)
+ await signal('original-active')
+ await checkpoint('source-edit-ready')
+ await activate(regenerated.branchId)
+ await signal('branch-changed')
+ const independentEdit = await checkpoint('delete-ready')
+ expect(independentEdit.branchId).not.toBe(original.branch_id)
+ expect(independentEdit.branchId).not.toBe(regenerated.branchId)
+ expect(requests).toHaveLength(6)
+ expect(JSON.stringify(requests[5].messages)).toContain('默认分支改变仍从原来源编辑')
+ expect(JSON.stringify(requests[5].messages)).not.toContain('编辑后的接续输入')
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(6)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM messages WHERE branch_id = ?').get(original.branch_id).count)).toBe(4)
+ expect(read(db => db.prepare('SELECT active_branch_id FROM conversations WHERE id = ?').get(original.conversation_id).active_branch_id)).toBe(regenerated.branchId)
+ await page.evaluate(async (id) => {
+ const api = window.lexoraDesktop.localChat.conversations
+ const current = await api.get(id)
+ if (!await api.delete(id, current.metadataRevision))
+ throw new Error('Fixture task was not deleted')
+ }, original.conversation_id)
+ await signal('task-deleted')
+ const evidence = await checkpoint('done')
+ expect(evidence).toMatchObject({ independentBranchEditAccepted: true, deletedSourceRejection: { decision: 'rejected', errorCode: 'SOURCE_CHANGED' } })
+ const result = await instrument
+ expect(result.error).toBeUndefined()
+ expect(result.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(result.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ expect(requests).toHaveLength(6)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(0)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM messages').get().count)).toBe(0)
+ expect(read(db => db.prepare('SELECT id FROM conversations WHERE id = ?').get(original.conversation_id))).toBeUndefined()
+ const capture = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', `files/history-${token}-branches.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath('android-history-branches.png'), capture.stdout)
+ await fs.writeFile(testInfo.outputPath('history-evidence.json'), JSON.stringify({ ...evidence, coreAdapter: serviceMode, modelRequests: requests.length, syntheticProvider: true, originalBranchPreservedBeforeDeletion: true, deletedTaskPurged: true, laterContextExcluded: true }, null, 2))
+ }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const result = await instrument
+ if (result)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error))
+ await adb('shell', 'rm', '-f', remoteConfig)
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', ...files)
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ provider.closeAllConnections()
+ await new Promise(resolve => provider.close(resolve))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-interruption.e2e.mjs b/.playwright/scripts/__tests__/mobile-interruption.e2e.mjs
new file mode 100644
index 000000000..8701777ee
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-interruption.e2e.mjs
@@ -0,0 +1,166 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createServer as createListener } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Android recovers the original receipt after a Core runtime restart and explicitly starts a separate successor', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an isolated Android device with debug and instrumentation APKs')
+ test.setTimeout(180000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 150000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-interruption-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const requests = []
+ let pendingStream
+ const provider = createServer((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const number = requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ const common = { id: `interruption-${number}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: number === 1 ? '中断前的部分回复' : '中断后新回复' }, finish_reason: null }] })}\n\n`)
+ if (number === 1) {
+ pendingStream = response
+ return
+ }
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-interruption')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const read = (query) => {
+ const db = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(db)
+ }
+ finally { db.close() }
+ }
+ const listener = createListener()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ let instrument
+ let outcome
+ let reversed = false
+ const files = new Set(['live', 'completed'].map(stage => `files/interruption-${token}-${stage}.png`))
+ const marker = stage => `files/interruption-${token}-${stage}.json`
+ const signal = async (stage) => {
+ files.add(marker(stage))
+ await adb('shell', 'run-as', appPackage, 'touch', marker(stage))
+ }
+ const checkpoint = async (stage) => {
+ files.add(marker(stage))
+ let value
+ await expect.poll(async () => {
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', marker(stage))).stdout)
+ return true
+ }
+ catch {
+ if (outcome)
+ throw new Error(outcome.result?.stdout ?? String(outcome.error))
+ return false
+ }
+ }, { timeout: 60000 }).toBe(true)
+ return value
+ }
+ try {
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'interruption-fixture', displayName: 'Interruption fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Interruption model', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'interruption-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('interruption-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'interruption-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing }), { mode: 0o600 })
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.InterruptionInstrumentedTest', '-e', 'interruptionToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ .then(result => ({ result }), error => ({ error }))
+ .then((result) => {
+ outcome = result
+ return result
+ })
+ await checkpoint('stream-visible')
+ expect(pendingStream).toBeTruthy()
+ pendingStream.write(`data: ${JSON.stringify({ id: 'interruption-1', model: 'fixture-model', object: 'chat.completion.chunk', created: 1, choices: [{ index: 0, delta: { content: '接着输出' }, finish_reason: null }] })}\n\n`)
+ const original = await checkpoint('started')
+ expect(requests).toHaveLength(1)
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(original.runId).status)).toBe('running')
+ await page.evaluate(() => window.lexoraDesktop.localChat.runtime.restart())
+ await expect.poll(async () => (await page.evaluate(() => window.lexoraDesktop.localChat.runtime.getStatus())).status, { timeout: 45000 }).toBe('ready')
+ await signal('restarted')
+ const recovered = await checkpoint('reconciled')
+ expect(recovered).toMatchObject({ oldTarget: original, originalReceiptRecovered: true })
+ expect(['cancelled', 'failed']).toContain(recovered.oldStatus)
+ expect(requests).toHaveLength(1)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(1)
+ await signal('allow-new-intent')
+ const evidence = await checkpoint('done')
+ const result = await instrument
+ expect(result.error).toBeUndefined()
+ expect(result.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(result.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ expect(requests).toHaveLength(2)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(2)
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(original.runId).status)).toBe(recovered.oldStatus)
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(evidence.successor.runId).status)).toBe('completed')
+ expect(JSON.stringify(requests[1].messages)).toContain('服务中断后等待我明确重新生成')
+ for (const stage of ['live', 'completed']) {
+ const capture = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', `files/interruption-${token}-${stage}.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath(`android-${stage}.png`), capture.stdout)
+ }
+ await fs.writeFile(testInfo.outputPath('interruption-evidence.json'), JSON.stringify({ ...evidence, coreAdapter: serviceMode, controlledRuntimeRestart: true, liveAndRestoredPartialOutput: true, automaticSuccessors: 0, modelRequests: requests.length }, null, 2))
+ }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const result = await instrument
+ if (result)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error))
+ await adb('shell', 'rm', '-f', remoteConfig)
+ if (files.size)
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', ...files)
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ provider.closeAllConnections()
+ await new Promise(resolve => provider.close(resolve))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-questions.e2e.mjs b/.playwright/scripts/__tests__/mobile-questions.e2e.mjs
new file mode 100644
index 000000000..50f38c94a
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-questions.e2e.mjs
@@ -0,0 +1,320 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer as createProvider } from 'node:http'
+import { createServer } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { setTimeout as delay } from 'node:timers/promises'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+const bindAddress = process.env.LEXORA_TEST_MOBILE_BIND_ADDRESS ?? '127.0.0.1'
+const useAdbReverse = bindAddress === '127.0.0.1'
+const prompts = [
+ [{ id: 'coverage', question: '这次要验证哪些能力?', kind: 'multiple', options: [{ id: 'connection', label: '连接恢复', recommended: true }, { id: 'files', label: '文件操作' }, { id: 'source', label: '仅审查源码' }] }],
+ [{ id: 'winner', question: '本次以哪一端的实际回答为准?', kind: 'single', options: [{ id: 'desktop', label: '由电脑提交回答' }, { id: 'mobile', label: '手机先填但不提交' }] }],
+]
+
+test('real Agent questions accept native Android choices, retain unfinished answers and close a stale dialog after Desktop answers', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an Android device with the debug and instrumentation APKs installed')
+ test.setTimeout(360000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 300000, maxBuffer: 8 * 1024 * 1024 })
+ const bytes = async (...args) => (await execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 15000, encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })).stdout
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-questions-${token}.json`
+ const resultFile = `files/questions-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const identityBackup = `no_backup/question-answer-${token}-identity`
+ const captures = ['filled', 'restored-answer', 'delivered', 'awaiting-desktop', 'desktop-winner']
+ const requests = []
+ const cleanupFailures = []
+ let instrumentStarted = false
+ let instrument
+ let instrumentProcess
+ let instrumentOutcome
+ let desktop
+ let port
+ let reversed = false
+ const provider = createProvider((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ requests.push(body)
+ const serialized = JSON.stringify(body.messages)
+ const phase = Number(serialized.match(/Question mobile phase ([01])/)?.[1] ?? '0')
+ const calls = body.messages.flatMap(message => message.tool_calls ?? [])
+ const agentRequest = body.tools?.some(tool => tool.function?.name === 'lexora_ask_user') === true
+ const ask = calls.find(call => call.function?.name === 'lexora_ask_user')
+ const waited = calls.some(call => call.function?.name === 'lexora_wait_user')
+ let tool
+ if (agentRequest && !ask) {
+ tool = { name: 'lexora_ask_user', arguments: JSON.stringify({ questions: prompts[phase] }) }
+ }
+ else if (agentRequest && !waited) {
+ const result = body.messages.find(message => message.role === 'tool' && message.tool_call_id === ask.id)
+ const text = typeof result?.content === 'string' ? result.content : result?.content?.map(item => item.text ?? '').join('') ?? ''
+ const requestId = text.match(/"requestId"\s*:\s*"([^"]+)"/)?.[1]
+ if (!requestId)
+ throw new Error('The actual ask_user tool did not return a request receipt')
+ tool = { name: 'lexora_wait_user', arguments: JSON.stringify({ requestId }) }
+ }
+ const reply = phase === 0 ? `手机选择与补充😀 ${token}` : `桌面抢先回答 ${token}`
+ const delta = tool
+ ? { role: 'assistant', tool_calls: [{ index: 0, id: `question-${phase}-${tool.name}`, type: 'function', function: tool }] }
+ : { role: 'assistant', content: `问题验收完成 ${phase}:${serialized.includes(reply) ? reply : '未收到实际答案'}` }
+ const common = { id: `question-${requests.length}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: tool ? 'tool_calls' : 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(error => response.destroy(error))
+ })
+ const restorePhone = async () => {
+ if (!instrumentStarted)
+ return
+ await adb('shell', 'am', 'force-stop', appPackage)
+ let manifest
+ for (const suffix of ['.json', '.json.bak']) {
+ manifest = await adb('shell', 'run-as', appPackage, 'cat', `${identityBackup}${suffix}`).then(result => JSON.parse(result.stdout), () => null)
+ if (manifest)
+ break
+ }
+ if (!manifest)
+ return
+ let cleanupError
+ try {
+ const cleanup = await adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.QuestionAnswerInstrumentedTest', '-e', 'questionAnswerToken', token, '-e', 'questionAnswerRestoreOnly', 'true', `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ await fs.writeFile(testInfo.outputPath('android-restoration.txt'), cleanup.stdout + cleanup.stderr)
+ expect(cleanup.stdout).toMatch(/OK \(1 test\)/)
+ expect(cleanup.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ }
+ catch (error) { cleanupError = error }
+ finally {
+ await adb('shell', 'am', 'force-stop', appPackage)
+ const original = await bytes('exec-out', 'run-as', appPackage, 'cat', `${identityBackup}.bin`)
+ expect(createHash('sha256').update(original).digest('hex')).toBe(manifest.sha256)
+ if (manifest.present) {
+ await adb('shell', 'run-as', appPackage, 'cp', `${identityBackup}.bin`, `${identityBackup}.restore`)
+ await adb('shell', 'run-as', appPackage, 'mv', `${identityBackup}.restore`, 'no_backup/device-identity.bin')
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ const restored = await bytes('exec-out', 'run-as', appPackage, 'cat', 'no_backup/device-identity.bin')
+ expect(createHash('sha256').update(restored).digest('hex')).toBe(manifest.sha256)
+ }
+ else {
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', 'no_backup/device-identity.bin', 'no_backup/device-identity.bin.bak', 'no_backup/device-identity.bin.new')
+ }
+ }
+ if (cleanupError)
+ throw cleanupError
+ await adb('shell', 'run-as', appPackage, 'rm', '-f', `${identityBackup}.json`, `${identityBackup}.json.bak`, `${identityBackup}.json.new`, `${identityBackup}.bin`)
+ await fs.writeFile(testInfo.outputPath('phone-restoration.json'), JSON.stringify({ originalIdentityRestored: true, testPartitionsRemoved: manifest.partitions.length, originalKeystorePreserved: true }))
+ }
+ const checkpoints = []
+ const instrumentationText = outcome => [outcome?.result?.stdout ?? outcome?.error?.stdout, outcome?.result?.stderr ?? outcome?.error?.stderr, outcome?.error?.stack].filter(Boolean).join('\n')
+ const assertInstrumentation = (outcome) => {
+ const output = instrumentationText(outcome)
+ if (outcome.error || !/OK \(1 test\)/.test(output) || /INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/.test(output))
+ throw new Error(`Android question instrumentation failed:\n${output}`, { cause: outcome.error })
+ }
+ const checkpoint = async (phase, stage) => {
+ const file = `files/questions-${token}-${phase}-${stage}.json`
+ checkpoints.push(file)
+ const deadline = performance.now() + 75000
+ while (performance.now() < deadline) {
+ let value
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', file)).stdout)
+ }
+ catch {}
+ if (instrumentOutcome) {
+ assertInstrumentation(instrumentOutcome)
+ if (value === undefined)
+ throw new Error(`Android instrumentation completed before question checkpoint ${phase}/${stage}:\n${instrumentationText(instrumentOutcome)}`)
+ }
+ if (value !== undefined)
+ return value
+ await Promise.race([delay(250), instrument])
+ }
+ throw new Error(`Android question checkpoint ${phase}/${stage} was not reached within 75000 ms`)
+ }
+ const resume = async (phase) => {
+ const file = `files/questions-${token}-${phase}-resume.json`
+ checkpoints.push(file)
+ await adb('shell', 'run-as', appPackage, 'touch', file)
+ }
+ try {
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-questions')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const page = desktop.page
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally { database.close() }
+ }
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'questions-fixture', displayName: 'Question verification', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Question verification', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'questions-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('questions-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'questions-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ const cases = []
+ for (let phase = 0; phase < 2; phase++) {
+ const title = phase === 0 ? '手机问答与恢复验收' : '桌面抢先回答验收'
+ const turn = await page.evaluate(async (phase) => {
+ const api = window.lexoraDesktop.localChat
+ const draftId = crypto.randomUUID()
+ const draft = await api.composerDrafts.open({ draftId, scope: { kind: 'task', draftId, spaceId: null }, initialContent: { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text: `Question mobile phase ${phase}` }] }], panelResourceIds: [] }, initialModelSelection: null, initialExecutionConfig: { executionProfile: 'read_only', approvalPolicy: 'policy' } })
+ const turn = await api.chat.startTurn({ draftId, expectedRevision: draft.revision, requestId: crypto.randomUUID() })
+ return { conversationId: turn.conversationId, branchId: turn.branchId, runId: turn.runId }
+ }, phase)
+ const scope = { conversationId: turn.conversationId, branchId: turn.branchId }
+ await expect.poll(() => page.evaluate(scope => window.lexoraDesktop.localChat.questions.list(scope), scope), { timeout: 45000 }).toMatchObject([{ status: 'pending', questions: prompts[phase] }])
+ const request = (await page.evaluate(scope => window.lexoraDesktop.localChat.questions.list(scope), scope))[0]
+ await page.evaluate(async ({ id, title }) => {
+ const api = window.lexoraDesktop.localChat.conversations
+ const current = await api.get(id)
+ await api.rename(id, title, current.titleRevision)
+ }, { id: turn.conversationId, title })
+ cases.push({ ...turn, requestId: request.id, title })
+ }
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, bindAddress, resolve))
+ port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ await page.evaluate(({ bindAddress, port }) => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress, port }), { bindAddress, port })
+ if (useAdbReverse) {
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ }
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, cases }), { mode: 0o600 })
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ instrumentStarted = true
+ instrumentProcess = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.QuestionAnswerInstrumentedTest', '-e', 'questionAnswerToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ instrument = instrumentProcess.then(result => ({ result }), error => ({ error })).then((outcome) => {
+ instrumentOutcome = outcome
+ return outcome
+ })
+ const phone = await checkpoint(0, 'done')
+ expect(phone).toMatchObject({ requestId: cases[0].requestId, activityRecreated: true, selectedOptionIds: ['connection', 'files'], text: `手机选择与补充😀 ${token}` })
+ const scopeOf = item => ({ conversationId: item.conversationId, branchId: item.branchId })
+ const currentQuestion = item => page.evaluate(scope => window.lexoraDesktop.localChat.questions.list(scope), scopeOf(item))
+ await expect.poll(() => currentQuestion(cases[0])).toMatchObject([{ status: 'answered', response: { answers: [{ questionId: 'coverage', selectedOptionIds: ['connection', 'files'], text: phone.text }] }, delivery: { state: 'delivered' } }])
+ await expect.poll(() => page.evaluate(id => window.lexoraDesktop.localChat.runs.get(id), cases[0].runId)).toMatchObject({ status: 'completed' })
+ await resume(0)
+ const ready = await checkpoint(1, 'ready')
+ expect(ready).toMatchObject({ requestId: cases[1].requestId, dialogOpen: true })
+ await page.evaluate(async ({ scope, requestId, text }) => {
+ await window.lexoraDesktop.localChat.questions.answer({ ...scope, requestId, answers: [{ questionId: 'winner', selectedOptionIds: ['desktop'], text }] })
+ }, { scope: scopeOf(cases[1]), requestId: cases[1].requestId, text: `桌面抢先回答 ${token}` })
+ await expect.poll(() => currentQuestion(cases[1])).toMatchObject([{ status: 'answered', response: { answers: [{ selectedOptionIds: ['desktop'], text: `桌面抢先回答 ${token}` }] }, delivery: { state: 'delivered' } }])
+ await expect.poll(() => page.evaluate(id => window.lexoraDesktop.localChat.runs.get(id), cases[1].runId)).toMatchObject({ status: 'completed' })
+ await resume(1)
+ expect(await checkpoint(1, 'done')).toMatchObject({ staleDialogClosed: true, noStaleCommand: true })
+ const outcome = await instrument
+ assertInstrumentation(outcome)
+ const evidence = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', resultFile)).stdout)
+ expect(evidence).toMatchObject({ activityRecreated: true, multipleChoicesAndText: true, staleDialogClosed: true, noStaleCommand: true, originalIdentityRestored: true })
+ for (const [phase, item] of cases.entries()) {
+ const events = read(db => db.prepare('SELECT event_type, payload_json FROM run_events WHERE run_id = ? ORDER BY sequence').all(item.runId))
+ const toolNames = events.filter(event => event.event_type === 'tool.started').map(event => JSON.parse(event.payload_json).toolName)
+ expect(toolNames.filter(name => name === 'lexora_ask_user')).toHaveLength(1)
+ expect(toolNames.filter(name => name === 'lexora_wait_user')).toHaveLength(1)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM execution_mailbox_sources WHERE id = ?').get(`user-question:${item.requestId}`).count)).toBe(1)
+ const reply = read(db => db.prepare('SELECT content_json FROM messages WHERE run_id = ? AND role = \'assistant\'').all(item.runId)).map(row => JSON.parse(row.content_json).text ?? '').join('\n')
+ expect(reply).toContain(phase === 0 ? phone.text : `桌面抢先回答 ${token}`)
+ }
+ const receipts = read(db => db.prepare('SELECT decision, target_json FROM command_receipts WHERE method = \'questions.answer\'').all())
+ expect(receipts).toHaveLength(2)
+ expect(new Set(receipts.map(receipt => JSON.parse(receipt.target_json).questionId))).toEqual(new Set(cases.map(item => item.requestId)))
+ expect(receipts.every(receipt => receipt.decision === 'accepted')).toBe(true)
+ expect(JSON.stringify(requests)).not.toContain(`此手机旧回答不得投递 ${token}`)
+ await fs.writeFile(testInfo.outputPath('questions.json'), JSON.stringify({ ...evidence, cases, syntheticProvider: true, toolExecutionFromCore: true, mailboxInputs: 2, productAnswerReceipts: 2, desktopWinnerUsesProductGateway: true }, null, 2))
+ await page.screenshot({ path: testInfo.outputPath('desktop-questions.png') })
+ }
+ finally {
+ if (instrument && !instrumentOutcome) {
+ await adb('shell', 'am', 'force-stop', appPackage).catch(error => cleanupFailures.push(error))
+ await Promise.race([instrument, delay(10000)])
+ if (!instrumentOutcome) {
+ instrumentProcess.child.kill('SIGTERM')
+ await instrument
+ }
+ }
+ const output = instrumentationText(instrumentOutcome)
+ if (instrumentStarted)
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), output || 'Instrumentation did not return output').catch(error => cleanupFailures.push(error))
+ const pngHeader = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
+ for (const capture of captures) {
+ const image = await bytes('exec-out', 'run-as', appPackage, 'cat', `files/questions-${token}-${capture}.png`).catch(() => null)
+ if (image?.subarray(0, 8).equals(pngHeader))
+ await fs.writeFile(testInfo.outputPath(`android-${capture}.png`), image).catch(error => cleanupFailures.push(error))
+ }
+ for (const name of new Set(output.match(/mobile-ui-failure-\d+\.(?:json|png)/g) ?? [])) {
+ const file = `files/${name}`
+ checkpoints.push(file)
+ const value = await bytes('exec-out', 'run-as', appPackage, 'cat', file).catch(() => null)
+ if (!value)
+ continue
+ try {
+ if (name.endsWith('.png') ? !value.subarray(0, 8).equals(pngHeader) : !Array.isArray(JSON.parse(value.toString('utf8'))))
+ continue
+ }
+ catch { continue }
+ await fs.writeFile(testInfo.outputPath(name), value).catch(error => cleanupFailures.push(error))
+ }
+ await restorePhone().catch(error => cleanupFailures.push(error))
+ const cleanup = await Promise.allSettled([
+ adb('shell', 'rm', '-f', remoteConfig),
+ adb('shell', 'run-as', appPackage, 'rm', '-f', resultFile, ...checkpoints, ...captures.map(capture => `files/questions-${token}-${capture}.png`)),
+ fs.rm(configuration, { force: true }),
+ (async () => {
+ provider.closeAllConnections()
+ await new Promise((resolve, reject) => provider.close(error => error ? reject(error) : resolve()))
+ })(),
+ (async () => {
+ try {
+ if (desktop) {
+ for (const device of await desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await desktop.page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await desktop.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ }
+ }
+ finally {
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ }
+ })(),
+ ])
+ cleanupFailures.push(...cleanup.filter(result => result.status === 'rejected').map(result => result.reason))
+ }
+ if (cleanupFailures.length)
+ throw new AggregateError(cleanupFailures, 'Could not clean up the isolated mobile questions test')
+})
diff --git a/.playwright/scripts/__tests__/mobile-recovery.e2e.mjs b/.playwright/scripts/__tests__/mobile-recovery.e2e.mjs
new file mode 100644
index 000000000..75c6d4104
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-recovery.e2e.mjs
@@ -0,0 +1,52 @@
+import { execFile } from 'node:child_process'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:net'
+import process from 'node:process'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Android process termination preserves drafts, original receipts and resumable attachment uploads with real Core', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an isolated Android device with debug and instrumentation APKs')
+ test.setTimeout(180000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 60000 })
+ const instance = await buddy.createInstance('mobile-recovery')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const listener = createServer()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ const configuration = testInfo.outputPath('pairing.json')
+ let reversed = false
+ try {
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing }), { mode: 0o600 })
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ const result = await execute(process.execPath, ['.playwright/scripts/mobile/__tests__/process-recovery.e2e.mjs', '--serial', serial, '--adb', process.env.ADB ?? 'adb', '--pairing', configuration, '--output', testInfo.outputPath('recovery')], { timeout: 150000, maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath('runner.log'), result.stdout + result.stderr)
+ const recovered = JSON.parse(await fs.readFile(testInfo.outputPath('recovery/result.json'), 'utf8'))
+ expect(recovered).toMatchObject({ passed: true, nativeDraftRestored: true, currentInputPreserved: true, executionSettingsPreserved: true, duplicateAdoptionPrevented: true })
+ await expect(page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()).toBeVisible()
+ await page.screenshot({ path: testInfo.outputPath('desktop-after-recovery.png') })
+ }
+ finally {
+ await adb('shell', 'am', 'force-stop', 'app.uselexora.mobile.dev')
+ if (reversed)
+ await adb('reverse', '--remove', `tcp:${port}`)
+ await fs.rm(configuration, { force: true })
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ }
+})
diff --git a/.playwright/scripts/__tests__/mobile-task-controls.e2e.mjs b/.playwright/scripts/__tests__/mobile-task-controls.e2e.mjs
new file mode 100644
index 000000000..a70f4d4f3
--- /dev/null
+++ b/.playwright/scripts/__tests__/mobile-task-controls.e2e.mjs
@@ -0,0 +1,228 @@
+import { Buffer } from 'node:buffer'
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createServer as createListener } from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { promisify } from 'node:util'
+import { expect, test, useSyntheticCredentialStorage } from '../fixtures/electron.mjs'
+import { prepareMobileDesktopProfile } from '../fixtures/mobile-desktop.mjs'
+
+const execute = promisify(execFile)
+const serial = process.env.LEXORA_TEST_ANDROID_SERIAL
+const serviceMode = process.env.LEXORA_TEST_MOBILE_SERVICE_MODE ?? 'utility'
+
+test('Android direct stop, queue, branch switching and read state preserve exact targets and local input', async ({ buddy }, testInfo) => {
+ test.skip(!serial, 'Requires an isolated Android device with debug and instrumentation APKs')
+ test.setTimeout(300000)
+ const adb = (...args) => execute(process.env.ADB ?? 'adb', ['-s', serial, ...args], { timeout: 280000, maxBuffer: 8 * 1024 * 1024 })
+ const token = randomUUID()
+ const appPackage = 'app.uselexora.mobile.dev'
+ const remoteConfig = `/data/local/tmp/lexora-controls-${token}.json`
+ const configuration = testInfo.outputPath('pairing.json')
+ const gates = Array.from({ length: 3 }, () => Promise.withResolvers())
+ const requests = []
+ const provider = createServer((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ const index = requests.push(body) - 1
+ if (gates[index] && !await Promise.race([gates[index].promise.then(() => true), once(response, 'close').then(() => false)]))
+ return
+ const common = { id: `controls-${index}`, model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: index === 0 ? '首段输出结束' : index < 3 ? '恢复排队任务完成' : '历史分支验证回复' }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const instance = await buddy.createInstance('mobile-task-controls')
+ await prepareMobileDesktopProfile(instance.home, testInfo.outputPath('profile-preparation'))
+ const desktop = await instance.launch({ storageAuthority: 'sqlite', serviceMode })
+ await useSyntheticCredentialStorage(desktop)
+ const { page } = desktop
+ const read = (query) => {
+ const database = new DatabaseSync(path.join(instance.home, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return query(database)
+ }
+ finally { database.close() }
+ }
+ const listener = createListener()
+ await new Promise(resolve => listener.listen(0, '127.0.0.1', resolve))
+ const port = listener.address().port
+ await new Promise(resolve => listener.close(resolve))
+ let reversed = false
+ let started = false
+ let failure
+ let instrument
+ let outcome
+ const files = new Set(['stopped.png', 'final.png'].map(name => `files/controls-${token}-${name}`))
+ const marker = stage => `files/controls-${token}-${stage}.json`
+ const signal = async (stage) => {
+ files.add(marker(stage))
+ await adb('shell', 'run-as', appPackage, 'touch', marker(stage))
+ }
+ const checkpoint = async (stage) => {
+ files.add(marker(stage))
+ let value
+ await expect.poll(async () => {
+ try {
+ value = JSON.parse((await adb('shell', 'run-as', appPackage, 'cat', marker(stage))).stdout)
+ return true
+ }
+ catch {
+ if (outcome)
+ throw new Error(outcome.result?.stdout ?? String(outcome.error))
+ return false
+ }
+ }, { timeout: 60000 }).toBe(true)
+ return value
+ }
+ try {
+ await page.evaluate(async (baseUrl) => {
+ await window.lexoraDesktop.settings.update({ runtime: { codemode: 'off', modelRetryLimit: 0 } })
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'controls-fixture', displayName: 'Controls fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'fixture-model', name: 'Controls model', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'controls-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'offline-fixture-key')
+ })
+ try {
+ await providers.login('controls-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'controls-fixture', modelId: 'fixture-model', reasoning: null })
+ }, `http://127.0.0.1:${provider.address().port}/v1`)
+ await page.reload()
+ await page.locator('.desktop-chat-composer__prosemirror:visible').fill('Mobile controls baseline')
+ await page.getByRole('button', { name: '发送消息', exact: true }).click()
+ await expect.poll(() => requests.length).toBe(1)
+ const first = read(db => db.prepare('SELECT id, conversation_id, branch_id FROM runs WHERE status = \'running\'').get())
+ expect(first).toBeTruthy()
+ await page.evaluate(() => {
+ location.hash = '/settings/general'
+ })
+ await expect(page).toHaveURL(/#\/settings\/general/)
+ await page.evaluate(port => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress: '127.0.0.1', port }), port)
+ const pairing = await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.issuePairing({}))
+ await fs.writeFile(configuration, JSON.stringify({ pairing, conversationId: first.conversation_id }), { mode: 0o600 })
+ await adb('reverse', `tcp:${port}`, `tcp:${port}`)
+ reversed = true
+ await adb('push', configuration, remoteConfig)
+ await fs.rm(configuration)
+ started = true
+ instrument = adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.TaskControlsInstrumentedTest', '-e', 'taskControlsToken', token, `${appPackage}.test/androidx.test.runner.AndroidJUnitRunner`)
+ .then(result => ({ result }), error => ({ error }))
+ .then((result) => {
+ outcome = result
+ return result
+ })
+ const stale = await checkpoint('stale-ready')
+ expect(await page.evaluate(item => window.lexoraDesktop.localChat.chat.cancelQueued({ id: item.id, conversationId: item.conversationId, branchId: item.branchId, expectedRevision: Number(item.revision) }), stale)).toBe(true)
+ await signal('stale-removed')
+ expect((await checkpoint('steered')).runId).toBe(first.id)
+ gates[0].resolve()
+ await expect.poll(() => requests.length).toBe(2)
+ expect(JSON.stringify(requests[1].messages)).toContain('手机补充当前执行')
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(1)
+ await signal('steer-delivered')
+ const paused = await checkpoint('paused')
+ expect(read(db => db.prepare('SELECT state FROM chat_queue WHERE id = ?').get(paused.queueId).state)).toBe('paused')
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(first.id).status)).toBe('cancelled')
+ expect(requests).toHaveLength(2)
+ await signal('continue')
+ await expect.poll(() => requests.length).toBe(3)
+ await signal('next-running')
+ const replay = await checkpoint('old-stop-replayed')
+ expect(replay.nextRunId).not.toBe(first.id)
+ expect(read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(replay.nextRunId).status)).toBe('running')
+ gates[2].resolve()
+ const phoneRead = await checkpoint('phone-read')
+ expect(phoneRead.unread).toBe(false)
+ const states = () => page.evaluate(id => window.lexoraDesktop.localChat.taskMarks.states([id]), first.conversation_id)
+ await expect.poll(states).toMatchObject([{ unread: false, resultRunId: replay.nextRunId }])
+ const setRead = read => page.evaluate(async ({ id, read }) => {
+ const marks = window.lexoraDesktop.localChat.taskMarks
+ const [state] = await marks.states([id])
+ return marks.setRead({ conversationId: id, resultRunId: state.resultRunId, readRevision: state.readRevision, read })
+ }, { id: first.conversation_id, read })
+ expect(await setRead(false)).toMatchObject({ unread: true })
+ await signal('desktop-unread')
+ await checkpoint('background')
+ expect(await setRead(true)).toMatchObject({ unread: false })
+ await signal('desktop-read')
+ await checkpoint('branches-ready')
+ const fork = await page.evaluate(({ conversationId, sourceRunId, requestId }) => window.lexoraDesktop.localChat.chat.regenerateAssistant({ conversationId, sourceRunId, requestId }), { conversationId: first.conversation_id, sourceRunId: replay.nextRunId, requestId: randomUUID() })
+ expect(fork.branchId).not.toBe(first.branch_id)
+ await expect.poll(() => read(db => db.prepare('SELECT status FROM runs WHERE id = ?').get(fork.runId).status)).toBe('completed')
+ await page.evaluate(async ({ conversationId, branchId }) => {
+ const conversations = window.lexoraDesktop.localChat.conversations
+ const current = await conversations.get(conversationId)
+ await conversations.activateBranch({ conversationId, branchId, expectedRevision: current.metadataRevision })
+ }, { conversationId: first.conversation_id, branchId: first.branch_id })
+ await signal('branches-created')
+ const evidence = await checkpoint('done')
+ expect(evidence).toMatchObject({ directStopRetainedInput: true, branchDraftIsolation: true, forkBranchId: fork.branchId, originalBranchId: first.branch_id })
+ expect(read(db => db.prepare('SELECT active_branch_id FROM conversations WHERE id = ?').get(first.conversation_id).active_branch_id)).toBe(first.branch_id)
+ await expect(page).toHaveURL(/#\/settings\/general/)
+ const result = await instrument
+ await fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error))
+ expect(result.error).toBeUndefined()
+ expect(result.result.stdout).toMatch(/OK \(1 test\)/)
+ expect(result.result.stdout).not.toMatch(/INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ expect(read(db => db.prepare('SELECT COUNT(*) AS count FROM runs').get().count)).toBe(3)
+ expect(requests).toHaveLength(4)
+ for (const stage of ['stopped', 'final']) {
+ const capture = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'run-as', appPackage, 'cat', `files/controls-${token}-${stage}.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await fs.writeFile(testInfo.outputPath(`android-${stage}.png`), capture.stdout)
+ }
+ await fs.writeFile(testInfo.outputPath('task-control-evidence.json'), JSON.stringify({ ...evidence, coreAdapter: serviceMode, modelRequests: requests.length, syntheticProvider: true }, null, 2))
+ }
+ catch (error) { failure = error }
+ finally {
+ const cleanupErrors = []
+ const cleanup = async (action) => {
+ try {
+ await action()
+ }
+ catch (error) { cleanupErrors.push(error) }
+ }
+ if (started)
+ await cleanup(() => adb('shell', 'am', 'force-stop', appPackage))
+ const result = await instrument
+ if (result)
+ await cleanup(() => fs.writeFile(testInfo.outputPath('android-instrumentation.txt'), result.result?.stdout ?? String(result.error)))
+ await cleanup(() => adb('shell', 'rm', '-f', remoteConfig))
+ if (started)
+ await cleanup(() => adb('shell', 'run-as', appPackage, 'rm', '-f', ...files))
+ if (reversed)
+ await cleanup(() => adb('reverse', '--remove', `tcp:${port}`))
+ await cleanup(() => fs.rm(configuration, { force: true }))
+ await cleanup(async () => {
+ for (const device of await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.devices({}))) {
+ if (device.state === 'active')
+ await page.evaluate(deviceId => window.lexoraDesktop.localChat.privateNetwork.revoke({ deviceId }), device.deviceId)
+ }
+ await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
+ })
+ for (const gate of gates) gate.resolve()
+ provider.closeAllConnections()
+ await cleanup(() => new Promise(resolve => provider.close(resolve)))
+ if (cleanupErrors.length) {
+ if (!failure)
+ failure = new AggregateError(cleanupErrors, 'Mobile task control cleanup failed')
+ else
+ await cleanup(() => fs.writeFile(testInfo.outputPath('cleanup-errors.txt'), cleanupErrors.map(error => String(error)).join('\n')))
+ }
+ }
+ if (failure)
+ throw failure
+})
diff --git a/.playwright/scripts/__tests__/persistence-upgrade.e2e.mjs b/.playwright/scripts/__tests__/persistence-upgrade.e2e.mjs
new file mode 100644
index 000000000..87dab8898
--- /dev/null
+++ b/.playwright/scripts/__tests__/persistence-upgrade.e2e.mjs
@@ -0,0 +1,178 @@
+import { Buffer } from 'node:buffer'
+import { createHash, randomUUID } from 'node:crypto'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createRequire, isBuiltin } from 'node:module'
+import path from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { pathToFileURL } from 'node:url'
+import { expect, test } from '../fixtures/electron.mjs'
+import { ROOT } from '../shared.mjs'
+
+const requireBuddy = createRequire(path.join(ROOT, 'apps/buddy/package.json'))
+const contentText = '旧版迁移附件 😀 完整字节保留。\n'
+
+test.use({ passwordStore: process.env.LEXORA_TEST_PASSWORD_STORE })
+
+test('installed legacy data migrates with attachments and accepts new work without changing the source', async ({ buddy }, testInfo) => {
+ test.skip(!process.env.LEXORA_TEST_LEGACY_EXECUTABLE, 'Set the installed legacy executable to validate its actual data')
+ test.setTimeout(240000)
+ const requests = []
+ const server = createServer(async (request, response) => {
+ if (request.method !== 'POST' || request.url !== '/v1/chat/completions') {
+ response.writeHead(404).end()
+ return
+ }
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ requests.push(JSON.parse(Buffer.concat(chunks).toString('utf8')))
+ const common = { id: `migration-${requests.length}`, model: 'migration-fixture', object: 'chat.completion.chunk', created: 1 }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: { role: 'assistant', content: '迁移验收固定输出 😀' }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta: {}, finish_reason: 'stop' }], usage: { prompt_tokens: 32, completion_tokens: 8, total_tokens: 40 } })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })
+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
+ const source = await buddy.createInstance('installed-legacy', { executablePath: process.env.LEXORA_TEST_LEGACY_EXECUTABLE })
+ const candidate = await buddy.createInstance('migration-candidate')
+ let success = false
+ try {
+ const { page } = await source.launch()
+ const info = await page.evaluate(() => window.lexoraDesktop.app.getInfo())
+ await page.evaluate(async (baseUrl) => {
+ const providers = window.lexoraDesktop.localChat.providers
+ await providers.upsertCustom({ id: 'migration-fixture', displayName: 'Migration fixture', api: 'openai-completions', baseUrl, enabled: true, models: [{ id: 'migration-fixture', name: 'Migration fixture', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const stop = providers.onAuthChallenge((challenge) => {
+ if (challenge.providerId === 'migration-fixture' && challenge.type === 'secret')
+ void providers.respondToAuth(challenge.challengeId, 'isolated-migration-fixture-key')
+ })
+ try {
+ await providers.login('migration-fixture', 'api_key')
+ }
+ finally { stop() }
+ await providers.setDefaultModel({ providerId: 'migration-fixture', modelId: 'migration-fixture', reasoning: null })
+ await window.lexoraDesktop.settings.update({ desktop: { notificationsEnabled: false } })
+ }, `http://127.0.0.1:${server.address().port}/v1`)
+ await page.reload()
+ const editor = page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await expect(editor).toBeVisible()
+ await editor.fill('由已安装旧版创建的输入 😀')
+ await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.composerDrafts.list()).some(draft => JSON.stringify(draft.content).includes('由已安装旧版创建')))).toBe(true)
+ const editorDraftId = await page.evaluate(async () => (await window.lexoraDesktop.localChat.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes('由已安装旧版创建')).draftId)
+ const oldDraft = await createAttachmentDraft(page, '由已安装旧版创建的输入 😀', contentText, editorDraftId)
+ const turn = await page.evaluate(async (draftId) => {
+ const api = window.lexoraDesktop.localChat
+ const draft = await api.composerDrafts.get(draftId)
+ return api.chat.startTurn({ draftId, expectedRevision: draft.revision, requestId: crypto.randomUUID() })
+ }, (await createAttachmentDraft(page, '旧版带附件任务', contentText)).draftId)
+ await expect.poll(() => readRows(source.home, 'SELECT status FROM runs WHERE id = ?', turn.run.id)[0]?.status, { timeout: 45000 }).toBe('completed')
+ expect(JSON.stringify(requests)).toContain('旧版迁移附件')
+ const originalDraft = await page.evaluate(id => window.lexoraDesktop.localChat.composerDrafts.get(id), oldDraft.draftId)
+ await source.stop()
+ const reopened = await source.launch()
+ expect(await reopened.page.evaluate(id => window.lexoraDesktop.localChat.composerDrafts.get(id), oldDraft.draftId)).toEqual(originalDraft)
+ await source.stop()
+ await fs.writeFile(path.join(source.home, 'unknown-preserved.bin'), Buffer.from([0, 1, 127, 255]))
+ const sourceRows = readRows(source.home, 'SELECT id, conversation_id, branch_id, status, pi_session_file FROM runs ORDER BY id')
+ expect(sourceRows.some(row => row.pi_session_file)).toBe(true)
+ const original = await fingerprints(source.home)
+ const output = testInfo.outputPath('migration-module')
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: { ssr: path.join(ROOT, '.playwright/scripts/__tests__/prepareProductProfile.ts'), outDir: output, target: 'node26', rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'prepare.mjs', format: 'es' } } } })
+ const { activatePersistenceCandidate, importPersistenceCandidate, openBuddySqliteDatabase } = await import(pathToFileURL(path.join(output, 'prepare.mjs')).href)
+ expect(() => openBuddySqliteDatabase({ databasePath: path.join(source.home, 'buddy/buddy.sqlite3') })).toThrow('explicit persistence migration required')
+ expect(await fingerprints(source.home)).toEqual(original)
+ const input = { sourceRoot: source.home, candidateRoot: path.join(candidate.home, 'migration'), leaseDirectory: path.join(buddy.directory, 'leases'), signal: new AbortController().signal }
+ for (const point of ['copied', 'run', 'files', 'verified']) {
+ await expect(importPersistenceCandidate({ ...input, checkpoint: async (phase) => {
+ if (phase === point)
+ throw new Error(`Interrupted at ${point}`)
+ } })).rejects.toThrow(`Interrupted at ${point}`)
+ expect(await fingerprints(source.home)).toEqual(original)
+ }
+ const migrated = await activatePersistenceCandidate(input)
+ expect(await activatePersistenceCandidate(input)).toEqual(migrated)
+ expect(await fingerprints(source.home)).toEqual(original)
+ expect(readRows(migrated.profileRoot, 'SELECT authority, migration_state FROM storage_profile')).toEqual([{ authority: 'sqlite', migration_state: 'ready' }])
+ expect(readRows(migrated.profileRoot, 'SELECT id, conversation_id, branch_id, status, pi_session_file FROM runs ORDER BY id')).toEqual(sourceRows.map(row => ({ ...row, pi_session_file: row.pi_session_file?.replace(source.home, migrated.profileRoot) ?? null })))
+ expect(await fs.readFile(path.join(migrated.profileRoot, 'unknown-preserved.bin'))).toEqual(Buffer.from([0, 1, 127, 255]))
+ const migratedLaunch = await candidate.launch({ profileRoot: migrated.profileRoot, storageAuthority: 'sqlite' })
+ expect(await migratedLaunch.page.evaluate(id => window.lexoraDesktop.localChat.composerDrafts.get(id), oldDraft.draftId)).toMatchObject(originalDraft)
+ const attachment = await migratedLaunch.page.evaluate(async (id) => {
+ const api = window.lexoraDesktop.localChat
+ const resource = (await api.composerResources.list(id))[0]
+ return api.composerResources.readText({ draftId: id, resourceId: resource.resourceId })
+ }, oldDraft.draftId)
+ expect(attachment).toBe(contentText)
+ const nextDraft = await createAttachmentDraft(migratedLaunch.page, '迁移后新工作', contentText)
+ const next = await migratedLaunch.page.evaluate(async (draftId) => {
+ const api = window.lexoraDesktop.localChat
+ const draft = await api.composerDrafts.get(draftId)
+ const command = { draftId, expectedRevision: draft.revision, requestId: crypto.randomUUID() }
+ const first = await api.chat.startTurn(command)
+ const retry = await api.chat.startTurn(command)
+ return { first, retry }
+ }, nextDraft.draftId)
+ expect(next.retry.run.id).toBe(next.first.run.id)
+ await expect.poll(() => readRows(migrated.profileRoot, 'SELECT status FROM runs WHERE id = ?', next.first.run.id)[0]?.status, { timeout: 45000 }).toBe('completed')
+ await candidate.stop()
+ const databaseBytes = await fs.readFile(path.join(migrated.profileRoot, 'buddy/buddy.sqlite3'))
+ const rejected = await source.launch({ profileRoot: migrated.profileRoot, startupStatus: 'failed' })
+ let rejection
+ await expect.poll(async () => {
+ rejection = await rejected.page.evaluate(() => window.lexoraDesktop.app.startup.getState())
+ return rejection.status
+ }).toBe('failed')
+ expect(rejection.stages).toEqual(expect.arrayContaining([expect.objectContaining({ stage: 'runtime.database', status: 'failed' })]))
+ await source.stop()
+ expect(await fs.readFile(path.join(migrated.profileRoot, 'buddy/buddy.sqlite3'))).toEqual(databaseBytes)
+ expect(await fingerprints(source.home)).toEqual(original)
+ await fs.writeFile(testInfo.outputPath('migration-result.json'), JSON.stringify({ installedVersion: info.version, installedExecutable: process.env.LEXORA_TEST_LEGACY_EXECUTABLE, sourceRuns: sourceRows.length, migrated, oldRun: turn.run.id, newRun: next.first.run.id, sourceUnchanged: true, migrationCheckpoints: ['copied', 'run', 'files', 'verified'], oldBinaryRejection: rejection }, null, 2))
+ success = true
+ }
+ finally {
+ await source.stop()
+ await candidate.stop()
+ server.closeAllConnections()
+ await new Promise(resolve => server.close(resolve))
+ if (!success)
+ await fs.writeFile(testInfo.outputPath('provider-requests.json'), JSON.stringify(requests, null, 2))
+ }
+})
+
+async function createAttachmentDraft(page, text, attachment, draftId = randomUUID()) {
+ return page.evaluate(async ({ text, attachment, draftId, resourceId }) => {
+ const api = window.lexoraDesktop.localChat
+ const content = { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text }] }], panelResourceIds: [] }
+ let draft = await api.composerDrafts.open({ draftId, scope: { kind: 'task', draftId, spaceId: null }, initialContent: content, initialExecutionConfig: { approvalPolicy: 'policy', executionProfile: 'workspace_write' }, initialModelSelection: { providerId: 'migration-fixture', modelId: 'migration-fixture', reasoning: null, serviceTier: null } })
+ const bytes = new TextEncoder().encode(attachment)
+ await api.composerResources.accept({ draftId, resources: [{ resourceId, name: '迁移附件.txt', mimeType: 'text/plain', sizeBytes: bytes.length }] })
+ await api.composerResources.complete({ draftId, resourceId, bytes })
+ draft = await api.composerDrafts.get(draftId)
+ return api.composerDrafts.save({ draftId, expectedRevision: draft.revision, content: { ...content, panelResourceIds: [resourceId] }, modelSelection: draft.modelSelection, executionConfig: draft.executionConfig })
+ }, { text, attachment, draftId, resourceId: randomUUID() })
+}
+
+function readRows(profileRoot, sql, ...params) {
+ const database = new DatabaseSync(path.join(profileRoot, 'buddy/buddy.sqlite3'), { readOnly: true })
+ try {
+ return database.prepare(sql).all(...params).map(row => ({ ...row }))
+ }
+ finally { database.close() }
+}
+
+async function fingerprints(root) {
+ const result = {}
+ for (const entry of await fs.readdir(root, { withFileTypes: true, recursive: true })) {
+ const absolute = path.join(entry.parentPath, entry.name)
+ const relative = path.relative(root, absolute)
+ if (relative.startsWith('.runtime/') || relative === 'buddy/buddy.sqlite3-shm')
+ continue
+ if (entry.isFile())
+ result[relative] = createHash('sha256').update(await fs.readFile(absolute)).digest('hex')
+ else if (entry.isSymbolicLink())
+ result[relative] = await fs.readlink(absolute)
+ }
+ return result
+}
diff --git a/.playwright/scripts/__tests__/prepareProductProfile.ts b/.playwright/scripts/__tests__/prepareProductProfile.ts
new file mode 100644
index 000000000..1f4248aba
--- /dev/null
+++ b/.playwright/scripts/__tests__/prepareProductProfile.ts
@@ -0,0 +1,15 @@
+import { join } from 'node:path'
+import { openBuddySqliteDatabase } from '../../../apps/buddy/service/src/storage/database'
+
+export function prepareProductProfile(profileRoot: string) {
+ openBuddySqliteDatabase({ databasePath: join(profileRoot, 'buddy/buddy.sqlite3') }).close()
+}
+
+export { resolveBuddyProcessControl } from '../../../apps/buddy/platform/native/nativeHost'
+export { SessionServiceRegistration } from '../../../apps/buddy/platform/service/SessionServiceRegistration'
+
+export { openBuddySqliteDatabase } from '../../../apps/buddy/service/src/storage/database'
+
+export { activatePersistenceCandidate } from '../../../apps/buddy/service/src/storage/persistenceMigration/activatePersistenceCandidate'
+
+export { importPersistenceCandidate } from '../../../apps/buddy/service/src/storage/persistenceMigration/importPersistenceCandidate'
diff --git a/.playwright/scripts/__tests__/product-desktop.e2e.mjs b/.playwright/scripts/__tests__/product-desktop.e2e.mjs
new file mode 100644
index 000000000..40ef75dac
--- /dev/null
+++ b/.playwright/scripts/__tests__/product-desktop.e2e.mjs
@@ -0,0 +1,56 @@
+import fs from 'node:fs/promises'
+import { createRequire, isBuiltin } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { expect, test } from '../fixtures/electron.mjs'
+
+const root = fileURLToPath(new URL('../../../', import.meta.url))
+const requireBuddy = createRequire(path.join(root, 'apps/buddy/package.json'))
+
+test('candidate Desktop persists inputs and recovers stale saves through the product protocol', async ({ buddy }) => {
+ const instance = await buddy.createInstance('product-desktop')
+ const output = test.info().outputPath('profile-preparation')
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: {
+ ssr: path.join(root, '.playwright/scripts/__tests__/prepareProductProfile.ts'),
+ outDir: output,
+ target: 'node26',
+ rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'prepare.mjs', format: 'es' } },
+ } })
+ const { prepareProductProfile } = await import(pathToFileURL(path.join(output, 'prepare.mjs')).href)
+ prepareProductProfile(instance.home)
+ let { page } = await instance.launch({ storageAuthority: 'sqlite' })
+ const editor = page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await expect(editor).toBeVisible()
+ await editor.fill('Persist the candidate input 中文 🚀')
+ await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.composerDrafts.list()).map(draft => JSON.stringify(draft.content)).join('\n'))).toContain('Persist the candidate input')
+ const proof = await page.evaluate(async () => {
+ const api = window.lexoraDesktop.localChat
+ const draft = (await api.composerDrafts.list()).find(draft => JSON.stringify(draft.content).includes('Persist the candidate input'))
+ const content = { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text: 'Recover unconfirmed desktop input' }] }], panelResourceIds: [] }
+ let rejected = false
+ try {
+ await api.composerDrafts.save({ draftId: draft.draftId, expectedRevision: draft.revision + 9, content, modelSelection: draft.modelSelection, executionConfig: draft.executionConfig })
+ }
+ catch { rejected = true }
+ return { rejected, originalDraftId: draft.draftId }
+ })
+ expect(proof.rejected).toBe(true)
+ await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.runtime.listRecovery())).toMatchObject([expect.objectContaining({ state: 'rejected', canRestore: true })])
+ await instance.stop()
+ const reopened = await instance.launch({ storageAuthority: 'sqlite' })
+ page = reopened.page
+ await expect(page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()).toContainText('Persist the candidate input')
+ await page.getByRole('button', { name: '查看', exact: true }).click()
+ await expect(page.getByText('Recover unconfirmed desktop input', { exact: true })).toBeVisible()
+ await page.getByRole('button', { name: '保存为新草稿', exact: true }).click()
+ await expect(page.locator('.tiptap:visible').filter({ hasText: 'Recover unconfirmed desktop input' })).toBeVisible()
+ const result = await page.evaluate(async () => {
+ const api = window.lexoraDesktop.localChat
+ return { drafts: (await api.composerDrafts.list()).map(draft => ({ draftId: draft.draftId, content: draft.content })), recovery: await api.runtime.listRecovery() }
+ })
+ expect(result.recovery).toEqual([])
+ expect(result.drafts.find(draft => draft.draftId === proof.originalDraftId)?.content.body[0].content[0].text).toContain('Persist the candidate input')
+ await fs.writeFile(test.info().outputPath('product-desktop.json'), JSON.stringify({ ...proof, ...result }, null, 2))
+ await page.screenshot({ path: test.info().outputPath('product-desktop.png') })
+})
diff --git a/.playwright/scripts/__tests__/service-process.e2e.mjs b/.playwright/scripts/__tests__/service-process.e2e.mjs
new file mode 100644
index 000000000..54fbc83db
--- /dev/null
+++ b/.playwright/scripts/__tests__/service-process.e2e.mjs
@@ -0,0 +1,275 @@
+import assert from 'node:assert/strict'
+import { Buffer } from 'node:buffer'
+import { execFile, fork } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createRequire, isBuiltin } from 'node:module'
+import os from 'node:os'
+import path from 'node:path'
+import process from 'node:process'
+import { setTimeout as delay } from 'node:timers/promises'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { promisify } from 'node:util'
+import { expect, test } from '@playwright/test'
+
+const execute = promisify(execFile)
+const root = fileURLToPath(new URL('../../../', import.meta.url))
+const buddyRoot = path.join(root, 'apps/buddy')
+const requireBuddy = createRequire(path.join(buddyRoot, 'package.json'))
+
+test('standalone Node artifact keeps accepted work across client disconnect and service restart', async () => {
+ const testInfo = test.info()
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'lexora-service-process-'))
+ const candidate = path.join(directory, 'candidate')
+ const coreHome = path.join(directory, 'profile')
+ const work = path.join(directory, 'work')
+ const file = path.join(work, 'fixture.txt')
+ const report = { requests: [], results: {} }
+ const source = { PATH: process.env.PATH, HOME: directory, TMPDIR: directory, TEMP: directory, SystemRoot: process.env.SystemRoot, COMSPEC: process.env.COMSPEC }
+ const children = []
+ let finishStream
+ const server = createServer((request, response) => {
+ void (async () => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const payload = JSON.parse(Buffer.concat(chunks).toString())
+ assert.equal(request.headers.authorization, 'Bearer process-fixture-key')
+ const user = JSON.stringify(payload.messages.findLast(message => message.role === 'user'))
+ const toolResult = payload.messages.findLast(message => message.role === 'tool')
+ const mode = user.includes('FIXTURE_FILE') ? 'file' : user.includes('FIXTURE_STREAM') ? 'stream' : 'text'
+ report.requests.push({ mode, toolReadMatched: Boolean(toolResult && JSON.stringify(toolResult).includes('isolated-node-file')) })
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ const common = { id: randomUUID(), model: 'fixture-model', object: 'chat.completion.chunk', created: 1 }
+ const send = (delta, finishReason = null) => response.write(`data: ${JSON.stringify({ ...common, choices: [{ index: 0, delta, finish_reason: finishReason }] })}\n\n`)
+ send({ role: 'assistant', content: '' })
+ if (mode === 'stream') {
+ send({ content: 'fixture-stream-started' })
+ finishStream = () => {
+ send({}, 'stop')
+ response.end('data: [DONE]\n\n')
+ }
+ return
+ }
+ if (mode === 'file' && !toolResult) {
+ send({ tool_calls: [{ index: 0, id: 'fixture-read', type: 'function', function: { name: 'read', arguments: JSON.stringify({ path: file }) } }] })
+ send({}, 'tool_calls')
+ }
+ else {
+ send({ content: mode === 'file' ? 'fixture-file-ok' : 'fixture-text-ok' })
+ send({}, 'stop')
+ }
+ response.end('data: [DONE]\n\n')
+ })().catch((error) => {
+ report.serverError = error.message
+ response.writeHead(500)
+ response.end('Fixture failed')
+ })
+ })
+ try {
+ await fs.cp(path.join(buddyRoot, '.output/build/service'), candidate, { recursive: true, verbatimSymlinks: true })
+ await fs.mkdir(work)
+ await fs.writeFile(file, 'isolated-node-file\n')
+ server.listen(0, '127.0.0.1')
+ await once(server, 'listening')
+ const baseUrl = `http://127.0.0.1:${server.address().port}`
+ report.closure = await auditCandidate(candidate)
+ const manifest = JSON.parse(await fs.readFile(path.join(candidate, 'resources.json'), 'utf8'))
+ for (const resource of [...manifest.bundled, ...manifest.resources])
+ expect(await hashFile(path.join(candidate, resource.path)), resource.path).toBe(resource.sha256)
+ const runtime = path.join(directory, process.platform === 'win32' ? 'node.exe' : 'node')
+ await fs.copyFile(process.execPath, runtime)
+ await fs.chmod(runtime, 0o700)
+ const inventory = await execute(runtime, ['--input-type=module', '-e', `
+ import { createRequire } from 'node:module';
+ import { DatabaseSync } from 'node:sqlite';
+ const require = createRequire(import.meta.resolve('@earendil-works/pi-coding-agent'));
+ const photon = require('@silvia-odwyer/photon-node');
+ const image = new photon.PhotonImage(new Uint8Array([255, 0, 0, 255]), 1, 1);
+ const db = new DatabaseSync(':memory:');
+ console.log(JSON.stringify({ versions: process.versions, execPath: process.execPath, sqlite: db.prepare('select sqlite_version() as version').get(), wasm: { width: image.get_width(), height: image.get_height() }, modules: [require.resolve('@silvia-odwyer/photon-node'), import.meta.resolve('unpdf')] }));
+ image.free(); db.close(); await import('unpdf');
+ `], { cwd: candidate, env: source })
+ report.inventory = JSON.parse(inventory.stdout)
+ expect(report.inventory.versions.electron).toBeUndefined()
+ expect(report.inventory.execPath).toBe(runtime)
+ expect(report.inventory.wasm).toEqual({ width: 1, height: 1 })
+ for (const module of report.inventory.modules) {
+ const resolved = module.startsWith('file:') ? fileURLToPath(module) : module
+ expect(path.relative(candidate, resolved).startsWith('..'), module).toBe(false)
+ }
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: {
+ ssr: path.join(root, '.playwright/scripts/fixtures/service-process-harness.ts'),
+ outDir: path.join(directory, 'harness'),
+ target: 'node26',
+ rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'harness.mjs', format: 'es' } },
+ } })
+ const { RuntimeRpcPeer, createBuddyServiceEnvironment, BUDDY_SERVICE_PROTOCOL_VERSION, DEFAULT_RUNTIME_PREFERENCES, registerFixtureHost } = await import(pathToFileURL(path.join(directory, 'harness/harness.mjs')).href)
+ function startCore(resourcesRoot = path.join(candidate, 'resources')) {
+ const child = fork(path.join(candidate, 'service.mjs'), [], { execPath: runtime, execArgv: [], cwd: work, env: createBuddyServiceEnvironment(source, coreHome), stdio: ['ignore', 'pipe', 'pipe', 'ipc'] })
+ children.push(child)
+ let stderr = ''
+ child.stderr.on('data', (value) => {
+ stderr = `${stderr}${value}`.slice(-32768)
+ })
+ child.stdout.resume()
+ const messages = []
+ child.on('message', message => messages.push(message))
+ const peers = new Map()
+ function channel(id) {
+ const peer = new RuntimeRpcPeer({ transport: { postMessage: message => child.send({ type: 'rpc', channel: id, message }), subscribe(listener) {
+ const receive = (message) => {
+ if (message.type === 'rpc' && message.channel === id)
+ listener(message.message)
+ }
+ child.on('message', receive)
+ return () => child.off('message', receive)
+ } } })
+ peers.set(id, peer)
+ return peer
+ }
+ registerFixtureHost(channel('host'))
+ const exited = new Promise(resolve => child.once('exit', (code, signal) => {
+ for (const peer of peers.values()) peer.close(new Error('Service exited'))
+ resolve({ code, signal, stderr })
+ }))
+ const connect = (id, role) => {
+ const peer = channel(id)
+ child.send({ type: 'connect', channel: id, role })
+ return peer
+ }
+ child.send({ type: 'connect', channel: 'too-early', role: 'product' })
+ child.send({ type: 'start', protocolVersion: BUDDY_SERVICE_PROTOCOL_VERSION, config: { profile: 'test', buddyHome: coreHome, resourcesRoot, proxy: { httpProxy: '', httpsProxy: '', noProxy: '' }, preferences: { ...DEFAULT_RUNTIME_PREFERENCES, codemode: 'off', modelRetryLimit: 0 }, display: false } })
+ return {
+ child,
+ messages,
+ connect,
+ exited,
+ async ready() {
+ await expect.poll(() => messages.find(message => ['ready', 'failed'].includes(message.type)), { timeout: 30000 }).toBeTruthy()
+ expect(messages.find(message => ['ready', 'failed'].includes(message.type)), stderr).toEqual({ type: 'ready', protocolVersion: BUDDY_SERVICE_PROTOCOL_VERSION })
+ },
+ close(id) {
+ child.send({ type: 'disconnect', channel: id })
+ peers.get(id)?.close(new Error('Client disconnected'))
+ },
+ }
+ }
+ let core = startCore(path.join(candidate, 'missing'))
+ report.results.missingResources = await core.exited
+ expect(report.results.missingResources.code).toBe(1)
+ await expect(fs.stat(path.join(coreHome, 'buddy.sqlite3'))).rejects.toThrow()
+ core = startCore()
+ await core.ready()
+ expect(core.messages).toContainEqual({ type: 'rejected', channel: 'too-early', code: 'SERVICE_NOT_READY' })
+ const management = core.connect('management', 'management')
+ let product = core.connect('first', 'product')
+ const second = core.connect('second', 'product')
+ await expect(management.request('runtime.status', {})).resolves.toMatchObject({ ready: true })
+ await expect(product.request('runtime.shutdown', {})).rejects.toMatchObject({ code: -32601 })
+ await expect(product.request('extensions.agent.request', {})).rejects.toMatchObject({ code: -32601 })
+ await expect(product.request('providers.upsertCustom', {})).rejects.toMatchObject({ code: -32601 })
+ await management.request('providers.upsertCustom', { id: 'process-fixture', displayName: 'Isolated process fixture', api: 'openai-completions', baseUrl: `${baseUrl}/v1`, enabled: true, models: [{ id: 'fixture-model', name: 'Fixture', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const space = await management.request('spaces.create', { name: 'Isolated workspace', memoryScope: 'space_only', primaryDirectory: { id: null, root: work }, primaryDirectorySelectionVerified: true })
+ report.results.search = await product.request('spaces.searchFiles', { spaceId: space.id, query: 'fixture', deepSearch: true })
+ expect(report.results.search.some(entry => entry.path === 'fixture.txt' || entry.path === file)).toBe(true)
+ report.results.nativeRead = await management.request('spaceFiles.readDocument', { spaceId: space.id, directoryId: space.primaryDirectory.id, revision: space.primaryDirectory.revision, path: 'fixture.txt' })
+ expect(report.results.nativeRead.text).toBe('isolated-node-file\n')
+ async function startTask(text) {
+ const draftId = randomUUID()
+ const content = { version: 1, body: [{ type: 'paragraph', content: [{ type: 'text', text }] }], panelResourceIds: [] }
+ const executionConfig = { approvalPolicy: 'policy', executionProfile: 'workspace_write' }
+ const modelSelection = { providerId: 'process-fixture', modelId: 'fixture-model', reasoning: null, serviceTier: null }
+ const opened = await product.request('composerDrafts.open', { draftId, scope: { kind: 'task', draftId, spaceId: space.id }, initialContent: content, initialExecutionConfig: executionConfig, initialModelSelection: modelSelection })
+ const draft = await product.request('composerDrafts.save', { draftId: opened.draftId, expectedRevision: opened.revision, content, executionConfig, modelSelection })
+ return product.request('chat.startTurn', { draftId: draft.draftId, expectedRevision: draft.revision, requestId: randomUUID() })
+ }
+ async function terminal(runId) {
+ let result
+ await expect.poll(async () => {
+ result = await product.request('runs.get', { runId })
+ return result.status
+ }, { timeout: 30000 }).toMatch(/^(?:completed|cancelled|failed)$/)
+ expect(result.status, JSON.stringify(result)).toBe('completed')
+ return result
+ }
+ report.results.text = await terminal((await startTask('FIXTURE_TEXT')).runId)
+ report.results.file = await terminal((await startTask('FIXTURE_FILE')).runId)
+ expect(report.requests.some(value => value.toolReadMatched)).toBe(true)
+ const continued = await startTask('FIXTURE_STREAM')
+ await expect.poll(() => Boolean(finishStream)).toBe(true)
+ await expect(management.request('runtime.shutdown', { onlyIfIdle: true })).resolves.toEqual({ accepted: false })
+ core.close('first')
+ product = second
+ await expect(second.request('runs.get', { runId: continued.runId })).resolves.toMatchObject({ status: 'running' })
+ finishStream()
+ report.results.disconnected = await terminal(continued.runId)
+ const third = core.connect('third', 'product')
+ core.child.send({ type: 'rpc', channel: 'second', message: { invalid: true } })
+ await expect(third.request('runs.get', { runId: continued.runId })).resolves.toMatchObject({ status: 'completed' })
+ core.child.send({ type: 'connect', channel: 'first', role: 'product' })
+ await expect.poll(() => core.messages.find(message => message.type === 'rejected' && message.channel === 'first')).toEqual({ type: 'rejected', channel: 'first', code: 'SERVICE_CHANNEL_EXISTS' })
+ report.results.requestCount = report.requests.length
+ await expect(management.request('runtime.shutdown', {})).resolves.toEqual({ accepted: true })
+ report.results.stopped = await core.exited
+ expect(report.results.stopped.code).toBe(0)
+ core = startCore()
+ await core.ready()
+ const restored = core.connect('restored', 'product')
+ const admin = core.connect('admin', 'management')
+ await expect(restored.request('runs.list', {})).resolves.toHaveLength(3)
+ await expect(restored.request('runs.get', { runId: continued.runId })).resolves.toMatchObject({ status: 'completed' })
+ expect(report.requests.length).toBe(report.results.requestCount)
+ await expect(admin.request('runtime.shutdown', { onlyIfIdle: true })).resolves.toEqual({ accepted: true })
+ expect((await core.exited).code).toBe(0)
+ core = startCore()
+ await core.ready()
+ core.child.disconnect()
+ report.results.ownerDisconnected = await core.exited
+ expect(report.results.ownerDisconnected.code).toBe(1)
+ expect(report.serverError).toBeUndefined()
+ }
+ finally {
+ finishStream?.()
+ for (const child of children) {
+ if (child.exitCode !== null || child.signalCode !== null)
+ continue
+ child.kill('SIGTERM')
+ await Promise.race([once(child, 'exit'), delay(5000)])
+ if (child.exitCode === null && child.signalCode === null) {
+ child.kill('SIGKILL')
+ await once(child, 'exit')
+ }
+ }
+ server.closeAllConnections()
+ await new Promise(resolve => server.close(resolve))
+ const reportPath = testInfo.outputPath('service-process.json')
+ await fs.writeFile(reportPath, JSON.stringify(report, null, 2))
+ await testInfo.attach('service-process.json', { path: reportPath, contentType: 'application/json' })
+ await fs.rm(directory, { recursive: true, force: true })
+ }
+})
+
+async function hashFile(file) {
+ return createHash('sha256').update(await fs.readFile(file)).digest('hex')
+}
+
+async function auditCandidate(root) {
+ let files = 0
+ let symlinks = 0
+ for (const entry of await fs.readdir(root, { recursive: true, withFileTypes: true })) {
+ if (entry.isFile())
+ files++
+ if (!entry.isSymbolicLink())
+ continue
+ symlinks++
+ const resolved = await fs.realpath(path.join(entry.parentPath, entry.name))
+ const relative = path.relative(root, resolved)
+ assert(relative && relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative), 'Artifact symlink must stay inside the service package')
+ }
+ expect(files).toBeGreaterThan(0)
+ expect(symlinks).toBeGreaterThan(0)
+ return { files, symlinks }
+}
diff --git a/.playwright/scripts/__tests__/storage.e2e.mjs b/.playwright/scripts/__tests__/storage.e2e.mjs
index c2cdc821a..ad9c47bed 100644
--- a/.playwright/scripts/__tests__/storage.e2e.mjs
+++ b/.playwright/scripts/__tests__/storage.e2e.mjs
@@ -1,23 +1,6 @@
import { Buffer } from 'node:buffer'
import { expect, test } from '../fixtures/electron.mjs'
-test('legacy caches and diagnostic logs alone do not trigger a startup migration', async ({ buddy }) => {
- const { mkdir, readFile, writeFile } = await import('node:fs/promises')
- const { join, dirname } = await import('node:path')
- const instance = await buddy.createInstance('cache-only')
- const files = ['.runtime/cache/chromium/Cache/data', '.runtime/cache/chromium/Code Cache/data', '.runtime/state/logs/old.log', '.runtime/state/crashes/old-report']
- for (const file of files) {
- await mkdir(dirname(join(instance.home, file)), { recursive: true })
- await writeFile(join(instance.home, file), 'retained-fixture')
- }
- const desktop = await instance.launch()
- const summary = await desktop.page.evaluate(() => window.lexoraDesktop.storage.summary())
- expect(summary.pending).toBeNull()
- expect(summary.history).toEqual([])
- for (const file of files)
- expect(await readFile(join(instance.home, file), 'utf8')).toBe('retained-fixture')
-})
-
test('stopping initial consolidation exits with source data intact and offers retry on next launch', async ({ buddy }) => {
const { createHash } = await import('node:crypto')
const { mkdir, open, readFile, stat } = await import('node:fs/promises')
@@ -168,48 +151,50 @@ test('local backup limits defer deletion until confirmation or the next successf
await expect(page.getByRole('button', { name: '查看备份 (1)', exact: true })).toBeVisible()
})
-test('preboot migration is visible, keeps runtime stopped, and a second launch uses the verified root', async ({ buddy }) => {
- const { access, readFile, rename, writeFile } = await import('node:fs/promises')
- const { createHash } = await import('node:crypto')
- const { dirname, join } = await import('node:path')
- const instance = await buddy.createInstance('migration')
- const first = await instance.launch()
- const target = `${instance.home}-moved`
- await first.page.evaluate(target => window.lexoraDesktop.storage.relocate(target), target)
- await instance.stop()
- const locator = join(dirname(instance.home), '.lexora-locations', createHash('sha256').update(instance.home).digest('hex').slice(0, 24), 'location.json')
- const pending = JSON.parse(await readFile(locator, 'utf8'))
- pending.pending.phase = 'failed'
- pending.pending.error = 'STORAGE_WORKER_INTERRUPTED'
- await writeFile(locator, JSON.stringify(pending))
- const migration = await instance.launch({ maintenance: true })
- await expect(migration.page.getByRole('heading', { name: '正在搬迁数据' })).toBeVisible()
- expect(await migration.app.evaluate(({ app }) => app.getAppMetrics().some(metric => metric.name === 'Buddy Service'))).toBe(false)
- await migration.app.evaluate(({ app }) => {
- app.relaunch = () => {}
- })
- await migration.page.getByRole('link', { name: '重试', exact: true }).click()
- await expect.poll(async () => JSON.parse(await readFile(locator, 'utf8')).activeRoot).toBe(target)
- await instance.stop()
- const restarted = await instance.launch({ expectedRoot: target })
- await restarted.page.evaluate(() => {
- location.hash = '#/settings/storage'
+for (const storageAuthority of ['legacy_jsonl', 'sqlite']) {
+ test(`preboot migration is visible, keeps runtime stopped, and a second launch uses the verified root (${storageAuthority})`, async ({ buddy }) => {
+ const { access, readFile, rename, writeFile } = await import('node:fs/promises')
+ const { createHash } = await import('node:crypto')
+ const { dirname, join } = await import('node:path')
+ const instance = await buddy.createInstance('migration')
+ const first = await instance.launch({ storageAuthority })
+ const target = `${instance.home}-moved`
+ await first.page.evaluate(target => window.lexoraDesktop.storage.relocate(target), target)
+ await instance.stop()
+ const locator = join(dirname(instance.home), '.lexora-locations', createHash('sha256').update(instance.home).digest('hex').slice(0, 24), 'location.json')
+ const pending = JSON.parse(await readFile(locator, 'utf8'))
+ pending.pending.phase = 'failed'
+ pending.pending.error = 'STORAGE_WORKER_INTERRUPTED'
+ await writeFile(locator, JSON.stringify(pending))
+ const migration = await instance.launch({ storageAuthority, maintenance: true })
+ await expect(migration.page.getByRole('heading', { name: '正在搬迁数据' })).toBeVisible()
+ expect(await migration.app.evaluate(({ app }) => app.getAppMetrics().some(metric => metric.name === 'Buddy Service'))).toBe(false)
+ await migration.app.evaluate(({ app }) => {
+ app.relaunch = () => {}
+ })
+ await migration.page.getByRole('link', { name: '重试', exact: true }).click()
+ await expect.poll(async () => JSON.parse(await readFile(locator, 'utf8')).activeRoot).toBe(target)
+ await instance.stop()
+ const restarted = await instance.launch({ storageAuthority, expectedRoot: target })
+ await restarted.page.evaluate(() => {
+ location.hash = '#/settings/storage'
+ })
+ await expect(restarted.page.getByTestId('storage-current-root')).toHaveText(target)
+ expect(JSON.parse(await readFile(locator, 'utf8')).pending).toBeNull()
+ await instance.stop()
+ await instance.launch({ storageAuthority, expectedRoot: target })
+ expect(JSON.parse(await readFile(locator, 'utf8')).history).toHaveLength(1)
+ await instance.stop()
+ await rename(target, `${target}-offline`)
+ const unavailable = await instance.launch({ storageAuthority, maintenance: true })
+ await expect(unavailable.page.getByRole('heading', { name: '暂时无法打开原有数据' })).toBeVisible()
+ expect(await unavailable.app.evaluate(({ app }) => app.getAppMetrics().some(metric => metric.name === 'Buddy Service'))).toBe(false)
+ await expect(access(target)).rejects.toMatchObject({ code: 'ENOENT' })
+ await instance.stop()
+ await rename(`${target}-offline`, target)
+ await instance.launch({ storageAuthority, expectedRoot: target })
})
- await expect(restarted.page.getByTestId('storage-current-root')).toHaveText(target)
- expect(JSON.parse(await readFile(locator, 'utf8')).pending).toBeNull()
- await instance.stop()
- await instance.launch({ expectedRoot: target })
- expect(JSON.parse(await readFile(locator, 'utf8')).history).toHaveLength(1)
- await instance.stop()
- await rename(target, `${target}-offline`)
- const unavailable = await instance.launch({ maintenance: true })
- await expect(unavailable.page.getByRole('heading', { name: '暂时无法打开原有数据' })).toBeVisible()
- expect(await unavailable.app.evaluate(({ app }) => app.getAppMetrics().some(metric => metric.name === 'Buddy Service'))).toBe(false)
- await expect(access(target)).rejects.toMatchObject({ code: 'ENOENT' })
- await instance.stop()
- await rename(`${target}-offline`, target)
- await instance.launch({ expectedRoot: target })
-})
+}
test('a failed move can return to the original data without retrying', async ({ buddy }) => {
const { mkdir, writeFile } = await import('node:fs/promises')
@@ -430,78 +415,134 @@ test('a missing initial data root stays absent while recovery is shown', async (
await instance.launch()
})
-test('exports an encrypted selective backup and imports it into the configured root with unselected data preserved', async ({ buddy }) => {
+for (const storageAuthority of ['legacy_jsonl', 'sqlite']) {
+ test(`exports an encrypted selective backup and imports it into the configured root with unselected data preserved (${storageAuthority})`, async ({ buddy }) => {
+ const { createHash, randomUUID } = await import('node:crypto')
+ const { mkdir, readFile, writeFile } = await import('node:fs/promises')
+ const { dirname, join } = await import('node:path')
+ const { useSyntheticCredentialStorage } = await import('../fixtures/electron.mjs')
+ const source = await buddy.createInstance('backup-export')
+ const desktop = await source.launch({ storageAuthority })
+ await useSyntheticCredentialStorage(desktop)
+ const connection = { id: randomUUID(), credentialId: randomUUID(), adapter: 'webdav', name: 'Portable connection', endpoint: 'https://example.invalid/backup/', username: 'fixture' }
+ await mkdir(join(source.home, 'buddy/secrets/sync'), { recursive: true })
+ await writeFile(join(source.home, 'device/sync.json'), JSON.stringify({ version: 1, enabled: false, selectedAdapter: 'webdav', activeConnectionId: connection.id, connections: [connection] }))
+ await writeFile(join(source.home, 'buddy/secrets/sync', `${createHash('sha256').update(connection.credentialId).digest('hex')}.credential`), `offline-fixture:${JSON.stringify({ id: connection.credentialId, value: 'synthetic-key-only', version: 1 })}`)
+ const snapshot = await desktop.page.evaluate(() => window.lexoraDesktop.storage.snapshot({ scopes: ['connections'], credentials: true, password: 'fixture-password' }))
+ expect(snapshot).toMatchObject({ scopes: ['connections'], credentials: true })
+ const exportParent = join(source.home, 'exported')
+ await mkdir(exportParent, { recursive: true })
+ await desktop.app.evaluate(({ dialog }, selected) => {
+ dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selected] })
+ }, exportParent)
+ const exported = await desktop.page.evaluate(id => window.lexoraDesktop.storage.export(id), snapshot.id)
+ const destination = await buddy.createInstance('backup-import')
+ const receiving = await destination.launch({ storageAuthority })
+ await useSyntheticCredentialStorage(receiving)
+ const space = await receiving.page.evaluate(() => window.lexoraDesktop.localChat.spaces.create({ name: 'Keep my current space', memoryScope: 'space_only', primaryDirectory: null }))
+ await receiving.app.evaluate(({ dialog }, selected) => {
+ dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selected] })
+ }, exported)
+ expect(await receiving.page.evaluate(() => window.lexoraDesktop.storage.import())).toEqual(snapshot)
+ const wrong = await receiving.page.evaluate(async (id) => {
+ try {
+ await window.lexoraDesktop.storage.restore(id, { scopes: ['connections'], credentials: true, password: 'incorrect-password' })
+ }
+ catch (error) { return String(error) }
+ }, snapshot.id)
+ expect(wrong).toContain('SNAPSHOT_PASSWORD_INVALID')
+ expect((await receiving.page.evaluate(() => window.lexoraDesktop.storage.summary())).pending).toBeNull()
+ await receiving.page.getByRole('button', { name: '设置', exact: true }).click()
+ await receiving.page.getByRole('link', { name: '数据存储', exact: true }).click()
+ await receiving.page.getByRole('button', { name: /^查看备份/ }).click()
+ await receiving.page.getByRole('button', { name: '恢复备份', exact: true }).click()
+ await expect(receiving.page.getByRole('checkbox', { name: /^工具与连接配置/ })).toBeChecked()
+ await expect(receiving.page.getByRole('checkbox', { name: /^任务与空间/ })).toBeDisabled()
+ await expect(receiving.page.locator('.n-modal')).toHaveCount(1)
+ await receiving.page.keyboard.press('Escape')
+ await receiving.page.evaluate(id => window.lexoraDesktop.storage.restore(id, { scopes: ['connections'], credentials: true, password: 'fixture-password' }), snapshot.id)
+ await destination.stop()
+ const locator = join(dirname(destination.home), '.lexora-locations', createHash('sha256').update(destination.home).digest('hex').slice(0, 24), 'location.json')
+ const state = JSON.parse(await readFile(locator, 'utf8'))
+ state.pending.phase = 'failed'
+ state.pending.error = 'STORAGE_WORKER_INTERRUPTED'
+ await writeFile(locator, JSON.stringify(state))
+ const migration = await destination.launch({ storageAuthority, maintenance: true })
+ await migration.app.evaluate(({ app }) => {
+ app.relaunch = () => {}
+ })
+ await migration.page.getByRole('link', { name: '重试', exact: true }).click()
+ await expect.poll(async () => JSON.parse(await readFile(locator, 'utf8')).pending).toBeNull()
+ await destination.stop()
+ const restored = await destination.launch({ storageAuthority })
+ await useSyntheticCredentialStorage(restored)
+ const connections = (await restored.page.evaluate(() => window.lexoraDesktop.sync.state())).connections
+ expect(connections).toHaveLength(1)
+ expect(connections[0]).toMatchObject({ name: 'Portable connection' })
+ const credentialRestored = await restored.app.evaluate(({ safeStorage }, root) => {
+ const fs = process.getBuiltinModule('node:fs')
+ const path = process.getBuiltinModule('node:path')
+ const crypto = process.getBuiltinModule('node:crypto')
+ const connection = JSON.parse(fs.readFileSync(path.join(root, 'device/sync.json'), 'utf8')).connections[0]
+ const file = path.join(root, 'buddy/secrets/sync', `${crypto.createHash('sha256').update(connection.credentialId).digest('hex')}.credential`)
+ return JSON.parse(safeStorage.decryptString(fs.readFileSync(file))).value === 'synthetic-key-only'
+ }, destination.home)
+ expect(credentialRestored).toBe(true)
+ expect(await restored.page.evaluate(() => window.lexoraDesktop.localChat.spaces.list())).toEqual(expect.arrayContaining([expect.objectContaining({ id: space.id })]))
+ expect((await restored.page.evaluate(() => window.lexoraDesktop.storage.summary())).root).toBe(destination.home)
+ })
+}
+
+test('in-place persistence upgrade retries with visible progress and preserves independent stores', async ({ buddy }, testInfo) => {
const { createHash, randomUUID } = await import('node:crypto')
- const { mkdir, readFile, writeFile } = await import('node:fs/promises')
+ const { lstat, mkdir, readFile, writeFile } = await import('node:fs/promises')
const { dirname, join } = await import('node:path')
- const { useSyntheticCredentialStorage } = await import('../fixtures/electron.mjs')
- const source = await buddy.createInstance('backup-export')
- const desktop = await source.launch()
- await useSyntheticCredentialStorage(desktop)
- const connection = { id: randomUUID(), credentialId: randomUUID(), adapter: 'webdav', name: 'Portable connection', endpoint: 'https://example.invalid/backup/', username: 'fixture' }
- await mkdir(join(source.home, 'buddy/secrets/sync'), { recursive: true })
- await writeFile(join(source.home, 'device/sync.json'), JSON.stringify({ version: 1, enabled: false, selectedAdapter: 'webdav', activeConnectionId: connection.id, connections: [connection] }))
- await writeFile(join(source.home, 'buddy/secrets/sync', `${createHash('sha256').update(connection.credentialId).digest('hex')}.credential`), `offline-fixture:${JSON.stringify({ id: connection.credentialId, value: 'synthetic-key-only', version: 1 })}`)
- const snapshot = await desktop.page.evaluate(() => window.lexoraDesktop.storage.snapshot({ scopes: ['connections'], credentials: true, password: 'fixture-password' }))
- expect(snapshot).toMatchObject({ scopes: ['connections'], credentials: true })
- const exportParent = join(source.home, 'exported')
- await mkdir(exportParent, { recursive: true })
- await desktop.app.evaluate(({ dialog }, selected) => {
- dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selected] })
- }, exportParent)
- const exported = await desktop.page.evaluate(id => window.lexoraDesktop.storage.export(id), snapshot.id)
- const destination = await buddy.createInstance('backup-import')
- const receiving = await destination.launch()
- await useSyntheticCredentialStorage(receiving)
- const space = await receiving.page.evaluate(() => window.lexoraDesktop.localChat.spaces.create({ name: 'Keep my current space', memoryScope: 'space_only', primaryDirectory: null }))
- await receiving.app.evaluate(({ dialog }, selected) => {
- dialog.showOpenDialog = async () => ({ canceled: false, filePaths: [selected] })
- }, exported)
- expect(await receiving.page.evaluate(() => window.lexoraDesktop.storage.import())).toEqual(snapshot)
- const wrong = await receiving.page.evaluate(async (id) => {
- try {
- await window.lexoraDesktop.storage.restore(id, { scopes: ['connections'], credentials: true, password: 'incorrect-password' })
- }
- catch (error) { return String(error) }
- }, snapshot.id)
- expect(wrong).toContain('SNAPSHOT_PASSWORD_INVALID')
- expect((await receiving.page.evaluate(() => window.lexoraDesktop.storage.summary())).pending).toBeNull()
- await receiving.page.getByRole('button', { name: '设置', exact: true }).click()
- await receiving.page.getByRole('link', { name: '数据存储', exact: true }).click()
- await receiving.page.getByRole('button', { name: /^查看备份/ }).click()
- await receiving.page.getByRole('button', { name: '恢复备份', exact: true }).click()
- await expect(receiving.page.getByRole('checkbox', { name: /^工具与连接配置/ })).toBeChecked()
- await expect(receiving.page.getByRole('checkbox', { name: /^任务与空间/ })).toBeDisabled()
- await expect(receiving.page.locator('.n-modal')).toHaveCount(1)
- await receiving.page.keyboard.press('Escape')
- await receiving.page.evaluate(id => window.lexoraDesktop.storage.restore(id, { scopes: ['connections'], credentials: true, password: 'fixture-password' }), snapshot.id)
- await destination.stop()
- const locator = join(dirname(destination.home), '.lexora-locations', createHash('sha256').update(destination.home).digest('hex').slice(0, 24), 'location.json')
+ const instance = await buddy.createInstance('upgrade-scope')
+ const first = await instance.launch({ storageAuthority: 'legacy_jsonl' })
+ const editor = first.page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()
+ await editor.fill('升级前保留的草稿')
+ await expect.poll(() => first.page.evaluate(async () => JSON.stringify(await window.lexoraDesktop.localChat.composerDrafts.list()))).toContain('升级前保留的草稿')
+ await instance.stop()
+ const markers = ['buddy/extensions/inference/model.bin', 'buddy/backups/previous.bin', 'device/chromium/Cache/marker']
+ for (const path of markers) {
+ await mkdir(dirname(join(instance.home, path)), { recursive: true })
+ await writeFile(join(instance.home, path), 'independent data')
+ }
+ const identities = await Promise.all(markers.map(path => lstat(join(instance.home, path))))
+ const locator = join(dirname(instance.home), '.lexora-locations', createHash('sha256').update(instance.home).digest('hex').slice(0, 24), 'location.json')
const state = JSON.parse(await readFile(locator, 'utf8'))
- state.pending.phase = 'failed'
- state.pending.error = 'STORAGE_WORKER_INTERRUPTED'
+ state.pending = { id: randomUUID(), kind: 'upgrade', source: instance.home, target: instance.home, phase: 'copying', createdAt: new Date().toISOString(), error: null }
await writeFile(locator, JSON.stringify(state))
- const migration = await destination.launch({ maintenance: true })
+ const migration = await instance.launch({ storageAuthority: 'default', maintenance: true })
+ await expect(migration.page.getByRole('heading', { name: '正在升级本地数据' })).toBeVisible()
+ await expect(migration.page.locator('#detail')).toContainText('上次整理被中断')
await migration.app.evaluate(({ app }) => {
app.relaunch = () => {}
})
+ const progress = []
+ migration.page.on('console', (message) => {
+ const text = message.text()
+ if (text.startsWith('upgrade-progress:'))
+ progress.push(JSON.parse(text.slice('upgrade-progress:'.length)))
+ })
+ await migration.page.evaluate(() => {
+ new MutationObserver(() => console.info(`upgrade-progress:${JSON.stringify({ phase: document.body.dataset.phase, detail: document.getElementById('detail').textContent, amount: document.getElementById('amount').textContent })}`))
+ .observe(document.body, { subtree: true, childList: true, attributes: true })
+ })
+ const process = migration.app.process()
await migration.page.getByRole('link', { name: '重试', exact: true }).click()
- await expect.poll(async () => JSON.parse(await readFile(locator, 'utf8')).pending).toBeNull()
- await destination.stop()
- const restored = await destination.launch()
- await useSyntheticCredentialStorage(restored)
- const connections = (await restored.page.evaluate(() => window.lexoraDesktop.sync.state())).connections
- expect(connections).toHaveLength(1)
- expect(connections[0]).toMatchObject({ name: 'Portable connection' })
- const credentialRestored = await restored.app.evaluate(({ safeStorage }, root) => {
- const fs = process.getBuiltinModule('node:fs')
- const path = process.getBuiltinModule('node:path')
- const crypto = process.getBuiltinModule('node:crypto')
- const connection = JSON.parse(fs.readFileSync(path.join(root, 'device/sync.json'), 'utf8')).connections[0]
- const file = path.join(root, 'buddy/secrets/sync', `${crypto.createHash('sha256').update(connection.credentialId).digest('hex')}.credential`)
- return JSON.parse(safeStorage.decryptString(fs.readFileSync(file))).value === 'synthetic-key-only'
- }, destination.home)
- expect(credentialRestored).toBe(true)
- expect(await restored.page.evaluate(() => window.lexoraDesktop.localChat.spaces.list())).toEqual(expect.arrayContaining([expect.objectContaining({ id: space.id })]))
- expect((await restored.page.evaluate(() => window.lexoraDesktop.storage.summary())).root).toBe(destination.home)
+ await expect.poll(() => process.exitCode, { timeout: 45000 }).toBe(0)
+ await instance.stop()
+ await writeFile(testInfo.outputPath('upgrade-progress.json'), JSON.stringify(progress, null, 2))
+ expect(progress.some(update => update.phase === 'copying' && /已复制 [1-9]/.test(update.detail))).toBe(true)
+ expect(progress.some(update => update.phase === 'verifying' && /已校验 [1-9]/.test(update.detail))).toBe(true)
+ expect(JSON.parse(await readFile(locator, 'utf8')).pending).toBeNull()
+ for (const [index, path] of markers.entries()) {
+ expect(await lstat(join(instance.home, path))).toMatchObject({ ino: identities[index].ino, mtimeMs: identities[index].mtimeMs })
+ expect(await readFile(join(instance.home, path), 'utf8')).toBe('independent data')
+ }
+ const restarted = await instance.launch({ storageAuthority: 'default' })
+ await expect(restarted.page.locator('.desktop-workbench-area__tasks .tiptap:visible').first()).toContainText('升级前保留的草稿')
+ expect(await restarted.page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.status({}))).toMatchObject({ enabled: false })
+ await restarted.page.screenshot({ path: testInfo.outputPath('after-upgrade.png') })
})
diff --git a/.playwright/scripts/__tests__/storageCrash.ts b/.playwright/scripts/__tests__/storageCrash.ts
new file mode 100644
index 000000000..0da4249ae
--- /dev/null
+++ b/.playwright/scripts/__tests__/storageCrash.ts
@@ -0,0 +1,400 @@
+import type { ChildProcess } from 'node:child_process'
+import type { Readable } from 'node:stream'
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdirSync, readFileSync, rmSync, writeFileSync, writeSync } from 'node:fs'
+import { join } from 'node:path'
+import process from 'node:process'
+import { DatabaseSync } from 'node:sqlite'
+import { pathToFileURL } from 'node:url'
+import { PreparedRunCommandService } from '../../../apps/buddy/service/src/chat/PreparedRunCommandService'
+import { recoverSqliteRuns } from '../../../apps/buddy/service/src/runs/recoverSqliteRuns'
+import { createAttachmentRepository } from '../../../apps/buddy/service/src/storage/attachmentRepository'
+import { createComposerDraftRepository } from '../../../apps/buddy/service/src/storage/composerDraftRepository'
+import { openBuddyMigrationCandidate } from '../../../apps/buddy/service/src/storage/database'
+import { guardStorageDatabase } from '../../../apps/buddy/service/src/storage/StorageIsolation'
+import { verifyCommandReceipt } from '../../../apps/buddy/service/src/storage/verifyCommandReceipt'
+import { createBuddyUserContent } from '../../../apps/buddy/shared/conversation/buddyUserContent'
+
+export const STORAGE_CRASH_POINTS = [
+ 'before-begin',
+ 'after-input',
+ 'after-draft',
+ 'after-receipt',
+ 'before-commit',
+ 'after-commit',
+ 'before-ack',
+ 'partial-ack',
+ 'after-ack',
+] as const
+type CrashPoint = typeof STORAGE_CRASH_POINTS[number]
+const committedPoints = new Set(['after-commit', 'before-ack', 'partial-ack', 'after-ack'])
+const transactionPoints = new Set(['after-input', 'after-draft', 'after-receipt', 'before-commit'])
+const now = '2026-09-30T00:00:00.000Z'
+const resource = 'Synthetic attachment retained across process interruption.\n'
+const resourceHash = createHash('sha256').update(resource).digest('hex')
+
+export interface StorageCrashFixture {
+ directory: string
+ dataGeneration: string
+}
+
+interface Checkpoint {
+ point: CrashPoint
+ inTransaction: boolean
+}
+
+function command(fixture: StorageCrashFixture) {
+ return { dataGeneration: fixture.dataGeneration, actorId: 'desktop-local', commandId: 'command-1', fingerprintVersion: 1, fingerprint: 'fixture-intent-1' }
+}
+
+function input(fixture: StorageCrashFixture) {
+ return {
+ attachmentBindings: [{ id: 'file-1', sourceAttachmentId: 'file-1', sourceDraftId: 'draft-1', messageId: 'message-1', storedPath: join(fixture.directory, 'resource.txt'), createdAt: now }],
+ branchId: 'branch-1',
+ conversationId: 'conversation-1',
+ createdAt: now,
+ approvalPolicy: 'policy' as const,
+ executionProfile: 'workspace_write' as const,
+ draft: { draftId: 'draft-1', expectedRevision: 0 },
+ model: 'fixture',
+ provider: 'fixture',
+ spaceId: null,
+ runInput: { attachmentIds: ['file-1'], contextItems: [], prompt: 'Materialized fixture input', reasoning: null, serviceTier: null },
+ runId: 'run-1',
+ title: 'Fixture',
+ userMessageContent: { text: 'Keep original input' },
+ userMessageId: 'message-1',
+ }
+}
+
+export function createStorageCrashFixture(directory: string): StorageCrashFixture {
+ mkdirSync(directory)
+ writeFileSync(join(directory, 'resource.txt'), resource)
+ const database = openBuddyMigrationCandidate({ databasePath: join(directory, 'candidate.sqlite3') })
+ try {
+ guardStorageDatabase(database)
+ database.exec('UPDATE storage_profile SET authority = \'sqlite\', migration_state = \'ready\'')
+ createComposerDraftRepository(database).open({
+ draftId: 'draft-1',
+ scope: { kind: 'global' },
+ initialContent: createBuddyUserContent('Keep original input'),
+ initialExecutionConfig: { approvalPolicy: 'policy', executionProfile: 'workspace_write' },
+ initialModelSelection: { modelId: 'fixture', providerId: 'fixture', reasoning: null, serviceTier: null },
+ now,
+ })
+ const attachments = createAttachmentRepository(database)
+ attachments.persistence?.adopt({ path: join(directory, 'resource.txt'), sizeBytes: resource.length, sha256: resourceHash })
+ attachments.create({
+ id: 'file-1',
+ draftId: 'draft-1',
+ messageId: null,
+ conversationId: null,
+ name: 'resource.txt',
+ mimeType: 'text/plain',
+ sizeBytes: resource.length,
+ storedPath: join(directory, 'resource.txt'),
+ createdAt: now,
+ })
+ const fixture = { directory, dataGeneration: String(database.prepare('SELECT data_generation FROM storage_profile').get()!.data_generation) }
+ writeFileSync(join(directory, 'fixture.json'), `${JSON.stringify(fixture)}\n`)
+ return fixture
+ }
+ finally {
+ database.close()
+ }
+}
+
+export function acceptAtStorageCheckpoint(
+ fixture: StorageCrashFixture,
+ point: CrashPoint,
+ checkpoint: (value: Checkpoint) => void,
+ respond: (data: string) => void,
+): void {
+ const database = openBuddyMigrationCandidate({ databasePath: join(fixture.directory, 'candidate.sqlite3') })
+ guardStorageDatabase(database)
+ const owner = new PreparedRunCommandService({ database, sourceInstanceId: 'before-restart' })
+ const exec = database.exec.bind(database)
+ const stop = (candidate: CrashPoint) => {
+ if (candidate === point)
+ checkpoint({ point, inTransaction: database.isTransaction })
+ }
+ try {
+ assert.equal(database.prepare('PRAGMA synchronous').get()!.synchronous, 2)
+ assert.equal(database.prepare('PRAGMA journal_mode').get()!.journal_mode, 'wal')
+ database.function('fixture_checkpoint', (candidate) => {
+ stop(candidate as CrashPoint)
+ return null
+ })
+ database.exec(`
+ CREATE TEMP TRIGGER fixture_input AFTER INSERT ON run_inputs
+ BEGIN SELECT fixture_checkpoint('after-input'); END;
+ CREATE TEMP TRIGGER fixture_draft AFTER UPDATE ON composer_drafts
+ BEGIN SELECT fixture_checkpoint('after-draft'); END;
+ CREATE TEMP TRIGGER fixture_receipt AFTER INSERT ON command_receipts
+ BEGIN SELECT fixture_checkpoint('after-receipt'); END;
+ `)
+ database.exec = (sql) => {
+ if (sql === 'COMMIT')
+ stop('before-commit')
+ exec(sql)
+ if (sql === 'COMMIT')
+ stop('after-commit')
+ }
+ stop('before-begin')
+ const accepted = owner.start(command(fixture), input(fixture))
+ stop('before-ack')
+ const response = `${JSON.stringify({ commandId: 'command-1', receipt: accepted.receipt })}\n`
+ if (point === 'partial-ack') {
+ respond(response.slice(0, Math.floor(response.length / 2)))
+ stop('partial-ack')
+ }
+ else {
+ respond(response)
+ stop('after-ack')
+ }
+ throw new Error(`Storage checkpoint was not interrupted: ${point}`)
+ }
+ finally {
+ database.exec = exec
+ owner.dispose()
+ database.close()
+ }
+}
+
+export async function verifyStorageCrash(fixture: StorageCrashFixture, point: CrashPoint, response: string) {
+ const databasePath = join(fixture.directory, 'candidate.sqlite3')
+ const committed = committedPoints.has(point)
+ const originalReceipt = verifyCommandReceipt({ databasePath, identity: command(fixture) })
+ assert.equal(originalReceipt !== null, committed)
+ const reader = new DatabaseSync(databasePath, { readOnly: true })
+ try {
+ for (const table of ['conversations', 'conversation_branches', 'messages', 'runs', 'run_inputs', 'turn_requests', 'command_receipts', 'run_events'])
+ assert.equal(reader.prepare(`SELECT count(*) AS count FROM ${table}`).get()!.count, Number(committed), table)
+ assert.equal(reader.prepare('SELECT revision FROM composer_drafts').get()!.revision, committed ? 1 : 0)
+ assert.deepEqual({ ...reader.prepare('SELECT draft_id, message_id FROM attachments').get() }, committed
+ ? { draft_id: null, message_id: 'message-1' }
+ : { draft_id: 'draft-1', message_id: null })
+ if (committed) {
+ assert.deepEqual(JSON.parse(JSON.stringify(originalReceipt!.target)), { runId: 'run-1', conversationId: 'conversation-1', branchId: 'branch-1' })
+ assert.equal(originalReceipt!.sourceInstanceId, 'before-restart')
+ assert.equal(originalReceipt!.method, 'chat.startTurn')
+ assert.deepEqual(JSON.parse(JSON.stringify(originalReceipt!.result)), { draftReceipt: { draftId: 'draft-1', sourceRevision: 0, committedRevision: 1 } })
+ assert.deepEqual(JSON.parse(String(reader.prepare('SELECT content_json FROM messages').get()!.content_json)), { text: 'Keep original input' })
+ assert.deepEqual({ ...reader.prepare('SELECT prompt, attachment_ids_json FROM run_inputs').get() }, { prompt: 'Materialized fixture input', attachment_ids_json: '["file-1"]' })
+ assert.deepEqual({ ...reader.prepare('SELECT id, conversation_id, branch_id, status, next_event_sequence FROM runs').get() }, {
+ id: 'run-1',
+ conversation_id: 'conversation-1',
+ branch_id: 'branch-1',
+ status: 'queued',
+ next_event_sequence: 2,
+ })
+ }
+ assert.equal(reader.prepare('PRAGMA integrity_check').get()!.integrity_check, 'ok')
+ assert.deepEqual(reader.prepare('PRAGMA foreign_key_check').all(), [])
+ }
+ finally {
+ reader.close()
+ }
+ if (point === 'after-ack') {
+ assert.deepEqual(JSON.parse(response), JSON.parse(JSON.stringify({ commandId: 'command-1', receipt: originalReceipt })))
+ }
+ else if (point === 'partial-ack') {
+ assert(response.length > 0 && !response.endsWith('\n'))
+ assert.throws(() => JSON.parse(response))
+ }
+ else {
+ assert.equal(response, '')
+ }
+
+ const database = openBuddyMigrationCandidate({ databasePath })
+ guardStorageDatabase(database)
+ const owner = new PreparedRunCommandService({ database, sourceInstanceId: 'after-restart' })
+ try {
+ const accepted = owner.start(command(fixture), input(fixture))
+ assert.equal(accepted.created, !committed)
+ if (committed)
+ assert.deepEqual(accepted.receipt, originalReceipt)
+ assert.deepEqual(owner.start(command(fixture), input(fixture)), { created: false, receipt: accepted.receipt })
+ const conversationsDirectory = join(fixture.directory, 'conversations')
+ assert.equal(await recoverSqliteRuns({ database, conversationsDirectory }), 1)
+ assert.equal(await recoverSqliteRuns({ database, conversationsDirectory }), 0)
+ assert.deepEqual(owner.find(command(fixture)), accepted.receipt)
+ assert.equal(owner.start(command(fixture), input(fixture)).created, false)
+ assert.equal(database.prepare('SELECT count(*) AS count FROM runs').get()!.count, 1)
+ assert.deepEqual({ ...database.prepare('SELECT status, error_code FROM runs').get() }, { status: 'failed', error_code: 'RUNTIME_RESTARTED' })
+ assert.equal(database.prepare('SELECT count(*) AS count FROM command_receipts').get()!.count, 1)
+ assert.equal(database.prepare('SELECT revision FROM composer_drafts').get()!.revision, 1)
+ assert.equal(createHash('sha256').update(readFileSync(join(fixture.directory, 'resource.txt'))).digest('hex'), resourceHash)
+ return { point, committedBeforeRestart: committed, receipt: accepted.receipt, recoveredRuns: 1, finalRuns: 1, resourceHash }
+ }
+ finally {
+ owner.dispose()
+ database.close()
+ }
+}
+
+export function runStorageCrashChild(directory: string, point: CrashPoint, nonce: string): void {
+ assert(STORAGE_CRASH_POINTS.includes(point))
+ const fixture = JSON.parse(readFileSync(join(directory, 'fixture.json'), 'utf8')) as StorageCrashFixture
+ assert.equal(fixture.directory, directory)
+ acceptAtStorageCheckpoint(fixture, point, (value) => {
+ writeSync(3, `${JSON.stringify({ ...value, nonce })}\n`)
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 30000)
+ throw new Error('Storage crash parent did not terminate the paused child')
+ }, data => writeSync(1, data))
+}
+
+interface ChildResult {
+ stdout: string
+ stderr: string
+ code: number | null
+ signal: NodeJS.Signals | null
+ error: { message: string, code?: string } | null
+ checkpoint: Checkpoint | null
+}
+
+const children = new Set()
+
+function runChild(args: string[], expected?: { point: CrashPoint, nonce: string }): Promise {
+ return new Promise((resolve) => {
+ const result: ChildResult = { stdout: '', stderr: '', code: null, signal: null, error: null, checkpoint: null }
+ const child = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe', 'pipe'] })
+ children.add(child)
+ const fail = (error: unknown) => {
+ result.error ??= { message: String(error), ...((error as NodeJS.ErrnoException)?.code ? { code: (error as NodeJS.ErrnoException).code } : {}) }
+ child.kill('SIGKILL')
+ }
+ const timeout = setTimeout(() => fail(new Error('Storage child timed out before verified exit')), 10000)
+ for (const [name, stream] of [['stdout', child.stdout], ['stderr', child.stderr]] as const) {
+ stream!.setEncoding('utf8')
+ stream!.on('data', (chunk: string) => {
+ if (result[name].length + chunk.length > 65536) {
+ fail(new Error(`Storage child exceeded ${name} limit`))
+ return
+ }
+ result[name] += chunk
+ })
+ }
+ let control = ''
+ const channel = child.stdio[3] as Readable
+ channel.setEncoding('utf8')
+ channel.on('data', (chunk: string) => {
+ try {
+ assert(expected, 'Unexpected storage child checkpoint')
+ assert(control.length + chunk.length <= 4096, 'Storage child checkpoint exceeded limit')
+ control += chunk
+ if (!control.endsWith('\n'))
+ return
+ const message = JSON.parse(control) as Checkpoint & { nonce: string }
+ assert.deepEqual(message, { ...expected, inTransaction: transactionPoints.has(expected.point) })
+ assert.equal(result.checkpoint, null, 'Repeated storage child checkpoint')
+ result.checkpoint = { point: message.point, inTransaction: message.inTransaction }
+ assert(child.kill('SIGKILL'), 'Storage child could not be terminated')
+ }
+ catch (error) {
+ fail(error)
+ }
+ })
+ child.on('error', fail)
+ child.once('close', (code, signal) => {
+ clearTimeout(timeout)
+ children.delete(child)
+ result.code = code
+ result.signal = signal
+ resolve(result)
+ })
+ })
+}
+
+export async function runStorageCrashes(root: string, bundle: string, bundleSha256: string): Promise {
+ const cases: Array> & { child: ChildResult }> = []
+ const report: {
+ startedAt: string
+ node: string
+ platform: string
+ arch: string
+ bundleSha256: string
+ status: 'running' | 'blocked' | 'failed' | 'passed'
+ blockedReason?: string
+ retainedFixture?: string
+ preflight?: ChildResult
+ cases: typeof cases
+ error?: string
+ } = { startedAt: new Date().toISOString(), node: process.version, platform: process.platform, arch: process.arch, bundleSha256, status: 'running', cases }
+ const stopChildren = () => {
+ for (const child of children)
+ child.kill('SIGKILL')
+ }
+ let interrupted = false
+ const interrupt = () => {
+ interrupted = true
+ stopChildren()
+ }
+ process.once('SIGINT', interrupt)
+ process.once('SIGTERM', interrupt)
+ try {
+ const token = randomUUID()
+ report.preflight = await runChild(['--input-type=module', '-e', 'process.stdout.write(process.argv[1])', token])
+ assert(!interrupted, 'Storage process interruption acceptance was cancelled')
+ if (report.preflight.error || report.preflight.code !== 0 || report.preflight.stdout !== token || process.platform === 'win32') {
+ report.status = 'blocked'
+ report.blockedReason = process.platform === 'win32'
+ ? 'SIGKILL acceptance requires a POSIX host'
+ : report.preflight.error
+ ? `Child process error: ${report.preflight.error.message}`
+ : report.preflight.code !== 0
+ ? `Child process exited with code ${report.preflight.code}`
+ : 'Child process exited without the required nonce response'
+ process.exitCode = 1
+ return
+ }
+ for (const point of STORAGE_CRASH_POINTS) {
+ const directory = join(root, point)
+ let verified = false
+ report.retainedFixture = directory
+ try {
+ const fixture = createStorageCrashFixture(directory)
+ const nonce = randomUUID()
+ const child = await runChild([
+ '--input-type=module',
+ '-e',
+ 'const { runStorageCrashChild } = await import(process.argv[1]); runStorageCrashChild(process.argv[2], process.argv[3], process.argv[4]);',
+ pathToFileURL(bundle).href,
+ directory,
+ point,
+ nonce,
+ ], { point, nonce })
+ writeFileSync(join(root, `${point}.child.json`), `${JSON.stringify(child, null, 2)}\n`)
+ assert(!interrupted, 'Storage process interruption acceptance was cancelled')
+ assert.equal(child.error, null, JSON.stringify(child))
+ assert.equal(child.signal, 'SIGKILL', JSON.stringify(child))
+ assert.equal(child.checkpoint?.point, point, JSON.stringify(child))
+ cases.push({ ...await verifyStorageCrash(fixture, point, child.stdout), child })
+ assert(!interrupted, 'Storage process interruption acceptance was cancelled')
+ verified = true
+ process.stdout.write(`Storage process interruption verified: ${point}\n`)
+ }
+ finally {
+ if (verified) {
+ rmSync(directory, { recursive: true, force: true })
+ delete report.retainedFixture
+ }
+ }
+ }
+ report.status = 'passed'
+ }
+ catch (error) {
+ report.status = 'failed'
+ report.error = String(error)
+ throw error
+ }
+ finally {
+ stopChildren()
+ process.removeListener('SIGINT', interrupt)
+ process.removeListener('SIGTERM', interrupt)
+ writeFileSync(join(root, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
+ process.stdout.write(`Storage process interruption status: ${report.status}; verified ${cases.length}/${STORAGE_CRASH_POINTS.length}\n`)
+ }
+}
diff --git a/.playwright/scripts/__tests__/storageDurability.ts b/.playwright/scripts/__tests__/storageDurability.ts
new file mode 100644
index 000000000..bd9bc93ae
--- /dev/null
+++ b/.playwright/scripts/__tests__/storageDurability.ts
@@ -0,0 +1,244 @@
+import type { DatabaseSync } from 'node:sqlite'
+import type { AppendBuddyRunEventInput } from '../../../apps/buddy/service/src/events/BuddyRunEvent'
+import assert from 'node:assert/strict'
+import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { monitorEventLoopDelay, performance } from 'node:perf_hooks'
+import process from 'node:process'
+import { setTimeout as delay, setImmediate as yieldLoop } from 'node:timers/promises'
+import { BufferedRunEventWriter } from '../../../apps/buddy/service/src/agent/events/BufferedRunEventWriter'
+import { SqliteRunEventLog } from '../../../apps/buddy/service/src/events/SqliteRunEventLog'
+import { checkpointSqliteStorage } from '../../../apps/buddy/service/src/storage/checkpointSqliteStorage'
+import { CommandCommitter } from '../../../apps/buddy/service/src/storage/CommandCommitter'
+import { createComposerDraftRepository } from '../../../apps/buddy/service/src/storage/composerDraftRepository'
+import { createConversationRepository } from '../../../apps/buddy/service/src/storage/conversationRepository'
+import { openBuddyMigrationCandidate } from '../../../apps/buddy/service/src/storage/database'
+import { guardStorageDatabase } from '../../../apps/buddy/service/src/storage/StorageIsolation'
+import { withTransaction } from '../../../apps/buddy/service/src/storage/transaction'
+import { createBuddyUserContent } from '../../../apps/buddy/shared/conversation/buddyUserContent'
+import { seedSqliteRun } from './storageFixture'
+
+const time = '2026-09-29T00:00:00.000Z'
+const executionConfig = { approvalPolicy: 'policy', executionProfile: 'workspace_write' } as const
+const modes = ['full-1', 'full-20', 'buffered'] as const
+type Mode = typeof modes[number]
+
+function distribution(values: number[]) {
+ assert(values.length > 0)
+ const sorted = values.toSorted((a, b) => a - b)
+ return {
+ count: sorted.length,
+ p95: sorted[Math.ceil(sorted.length * 0.95) - 1]!,
+ p99: sorted[Math.ceil(sorted.length * 0.99) - 1]!,
+ max: sorted.at(-1)!,
+ }
+}
+
+function seed(database: DatabaseSync) {
+ withTransaction(database, () => {
+ const insert = database.prepare(`INSERT INTO messages (id, conversation_id, branch_id, run_id, role, content_json, created_at)
+ VALUES (?, 'task-1', 'branch-task-1', ?, 'assistant', ?, ?)`)
+ for (let run = 0; run < 1000; run++) {
+ seedSqliteRun(database, `history-${run}`)
+ for (let message = 0; message < 9; message++) {
+ insert.run(`history-${run}-${message}`, `history-${run}`, JSON.stringify({ text: 'x'.repeat(256) }), new Date(Date.parse(time) + run * 9 + message).toISOString())
+ }
+ }
+ database.exec('UPDATE runs SET status = \'completed\'')
+ seedSqliteRun(database, 'stream-run')
+ })
+ const drafts = createComposerDraftRepository(database)
+ drafts.open({
+ draftId: 'draft',
+ scope: { kind: 'global' },
+ initialContent: createBuddyUserContent('Draft'),
+ initialExecutionConfig: executionConfig,
+ initialModelSelection: null,
+ now: time,
+ })
+ return { drafts, commands: new CommandCommitter(database), conversations: createConversationRepository(database) }
+}
+
+function storageSize(databasePath: string) {
+ return {
+ database: statSync(databasePath).size,
+ wal: existsSync(`${databasePath}-wal`) ? statSync(`${databasePath}-wal`).size : 0,
+ }
+}
+
+async function sample(root: string, mode: Mode, repetition: number) {
+ const directory = join(root, `${mode}-${repetition}`)
+ mkdirSync(directory)
+ const databasePath = join(directory, 'candidate.sqlite3')
+ const database = openBuddyMigrationCandidate({ databasePath })
+ guardStorageDatabase(database)
+ database.exec('UPDATE storage_profile SET authority = \'sqlite\', migration_state = \'ready\'')
+ const log = new SqliteRunEventLog({ database })
+ const histogram = monitorEventLoopDelay({ resolution: 1 })
+ try {
+ assert.deepEqual({ ...database.prepare('PRAGMA synchronous').get() }, { synchronous: 2 })
+ assert.deepEqual({ ...database.prepare('PRAGMA journal_mode').get() }, { journal_mode: 'wal' })
+ const { drafts, commands, conversations } = seed(database)
+ const beforeSize = storageSize(databasePath)
+ const dataGeneration = String(database.prepare('SELECT data_generation FROM storage_profile').get()!.data_generation)
+ const commitTimes: number[] = []
+ const appendBatch = async (events: readonly AppendBuddyRunEventInput[]) => {
+ const started = performance.now()
+ const result = await log.appendBatch(events)
+ commitTimes.push(performance.now() - started)
+ return result
+ }
+ const buffered = new BufferedRunEventWriter({ appendBatch }, 'stream-run', () => time)
+ const batchSize = mode === 'full-1' ? 1 : 20
+ histogram.enable()
+ await delay(10)
+ const cpuBefore = process.cpuUsage()
+ const started = performance.now()
+ let peakRss = process.memoryUsage().rss
+ for (let index = 0; index < 4000; index += batchSize) {
+ const events = Array.from({ length: batchSize }, () => ({
+ runId: 'stream-run',
+ type: 'message.delta' as const,
+ payload: { messageId: 'stream', delta: 's'.repeat(128) },
+ createdAt: time,
+ }))
+ if (mode === 'buffered')
+ buffered.appendBatch(events)
+ else
+ await appendBatch(events)
+ peakRss = Math.max(peakRss, process.memoryUsage().rss)
+ await yieldLoop()
+ }
+ await buffered.drain()
+ const elapsedMs = performance.now() - started
+ const cpu = process.cpuUsage(cpuBefore)
+ await delay(10)
+ histogram.disable()
+ const eventLoopMs = { p95: histogram.percentile(95) / 1e6, p99: histogram.percentile(99) / 1e6, max: histogram.max / 1e6 }
+ const facts = await log.read('stream-run')
+ assert.equal(facts.map(event => (event.payload as { delta: string }).delta).join(''), 's'.repeat(4000 * 128))
+ const queries: Record = { legacyOffset: [], messageTail: [], messageOld: [], eventOld: [] }
+ const reads = {
+ legacyOffset: () => database.prepare('SELECT * FROM messages WHERE conversation_id = \'task-1\' AND branch_id = \'branch-task-1\' ORDER BY created_at DESC LIMIT 50 OFFSET 9000').all(),
+ messageTail: () => conversations.listMessagePage('task-1', 'branch-task-1', { limit: 50 }).items,
+ messageOld: () => conversations.listMessagePage('task-1', 'branch-task-1', { limit: 50, beforeMessageId: 'history-100-0' }).items,
+ eventOld: () => log.list('stream-run', { limit: 50, afterSequence: 0 }),
+ }
+ for (let index = 0; index < 200; index++) {
+ for (const [name, read] of Object.entries(reads)) {
+ const begin = performance.now()
+ const rows = await read()
+ queries[name]!.push(performance.now() - begin)
+ assert.equal(rows.length, 50)
+ }
+ await yieldLoop()
+ }
+ const terminalStart = performance.now()
+ await log.appendBatch([
+ { runId: 'stream-run', type: 'message.completed', payload: {
+ messageId: 'stream',
+ role: 'assistant',
+ content: { text: 's'.repeat(4000 * 128) },
+ stopReason: 'completed',
+ }, createdAt: time },
+ { runId: 'stream-run', type: 'run.completed', payload: null, createdAt: time },
+ ])
+ const terminalMs = performance.now() - terminalStart
+ const compactStart = performance.now()
+ const removedEvents = await log.compactTerminalRun('stream-run')
+ const compactionMs = performance.now() - compactStart
+ assert.equal(removedEvents, facts.length)
+ assert.equal((await log.read('stream-run')).length, 2)
+ assert.equal(database.prepare('SELECT next_event_sequence FROM runs WHERE id = \'stream-run\'').get()!.next_event_sequence, facts.length + 3)
+ const draftTimes: number[] = []
+ histogram.reset()
+ histogram.enable()
+ await delay(10)
+ for (let revision = 0; revision < 1000; revision++) {
+ const begin = performance.now()
+ const result = commands.accept({
+ dataGeneration,
+ actorId: 'desktop-local',
+ commandId: `save-${revision}`,
+ method: 'draft.save',
+ fingerprintVersion: 1,
+ fingerprint: `draft-${revision}`,
+ sourceInstanceId: 'cost-fixture',
+ }, () => {
+ const draft = drafts.save({ draftId: 'draft', expectedRevision: revision, content: createBuddyUserContent('d'.repeat(512)), executionConfig, modelSelection: null, now: time })
+ return { target: { draftId: draft.draftId }, result: { revision: draft.revision } }
+ })
+ draftTimes.push(performance.now() - begin)
+ assert.equal(result.receipt.result.revision, revision + 1)
+ await yieldLoop()
+ }
+ await delay(10)
+ histogram.disable()
+ const draftEventLoopMs = { p99: histogram.percentile(99) / 1e6, max: histogram.max / 1e6 }
+ assert.equal(drafts.findById('draft')?.revision, 1000)
+ assert.equal(database.prepare('SELECT count(*) AS count FROM command_receipts').get()!.count, 1000)
+ const beforeCheckpoint = storageSize(databasePath)
+ const checkpointStart = performance.now()
+ const checkpoint = { ...checkpointSqliteStorage(database), elapsedMs: performance.now() - checkpointStart }
+ const afterCheckpoint = storageSize(databasePath)
+ const result = {
+ mode,
+ repetition,
+ historyRuns: 1000,
+ historyMessages: 10000,
+ inputEvents: 4000,
+ inputCharacters: 128,
+ persistedEvents: facts.length,
+ elapsedMs,
+ cpu,
+ peakRss,
+ commitMs: distribution(commitTimes),
+ draftCommitMs: distribution(draftTimes),
+ eventLoopMs,
+ draftEventLoopMs,
+ queriesMs: Object.fromEntries(Object.entries(queries).map(([name, values]) => [name, distribution(values)])),
+ beforeSize,
+ beforeCheckpoint,
+ afterCheckpoint,
+ checkpoint,
+ terminalMs,
+ compactionMs,
+ removedEvents,
+ sqlite: database.prepare('SELECT sqlite_version() AS version').get()!.version,
+ }
+ writeFileSync(join(root, `${mode}-${repetition}.json`), `${JSON.stringify(result, null, 2)}\n`)
+ assert.equal(checkpoint.busy, 0)
+ assert.equal(afterCheckpoint.wal, 0)
+ for (const p99 of [result.commitMs.p99, result.draftCommitMs.p99, eventLoopMs.p99, draftEventLoopMs.p99, ...Object.values(result.queriesMs).map(query => query.p99)])
+ assert(p99 <= 25, `Storage cost P99 ${p99.toFixed(2)}ms exceeds 25ms`)
+ return result
+ }
+ finally {
+ histogram.disable()
+ try {
+ await log.close()
+ }
+ finally {
+ database.close()
+ rmSync(directory, { recursive: true })
+ }
+ }
+}
+
+export async function runStorageDurability(root: string, bundleSha256: string) {
+ const samples: Awaited>[] = []
+ const report = { startedAt: new Date().toISOString(), platform: process.platform, arch: process.arch, node: process.version, bundleSha256, samples, passed: false }
+ try {
+ for (let repetition = 1; repetition <= 3; repetition++) {
+ for (const mode of modes) {
+ const result = await sample(root, mode, repetition)
+ samples.push(result)
+ process.stdout.write(`${mode} ${repetition}/3: commit P99 ${result.commitMs.p99.toFixed(2)}ms, loop P99 ${result.eventLoopMs.p99.toFixed(2)}ms, old page P99 ${result.queriesMs.messageOld!.p99.toFixed(2)}ms\n`)
+ }
+ }
+ report.passed = true
+ }
+ finally {
+ writeFileSync(join(root, 'report.json'), `${JSON.stringify(report, null, 2)}\n`)
+ }
+}
diff --git a/.playwright/scripts/__tests__/storageFixture.ts b/.playwright/scripts/__tests__/storageFixture.ts
new file mode 100644
index 000000000..bd543cbc7
--- /dev/null
+++ b/.playwright/scripts/__tests__/storageFixture.ts
@@ -0,0 +1,15 @@
+import type { DatabaseSync } from 'node:sqlite'
+
+export const sqliteRunFixtureTime = '2026-09-29T00:00:00.000Z'
+
+export function seedSqliteRun(database: DatabaseSync, runId: string, options: { conversationId?: string, nextSequence?: number | null } = {}) {
+ const conversationId = options.conversationId ?? 'task-1'
+ const branchId = `branch-${conversationId}`
+ database.prepare('INSERT OR IGNORE INTO conversations (id, created_at, updated_at) VALUES (?, ?, ?)').run(conversationId, sqliteRunFixtureTime, sqliteRunFixtureTime)
+ database.prepare('INSERT OR IGNORE INTO conversation_branches (id, conversation_id, created_at) VALUES (?, ?, ?)').run(branchId, conversationId, sqliteRunFixtureTime)
+ database.prepare('UPDATE conversations SET active_branch_id = ? WHERE id = ?').run(branchId, conversationId)
+ database.prepare(`INSERT INTO messages (id, conversation_id, branch_id, role, content_json, created_at)
+ VALUES (?, ?, ?, 'user', ?, ?)`).run(`input-${runId}`, conversationId, branchId, '{"text":"Fixture input"}', sqliteRunFixtureTime)
+ database.prepare(`INSERT INTO runs (id, conversation_id, branch_id, triggering_message_id, provider, model, purpose, status, started_at, next_event_sequence)
+ VALUES (?, ?, ?, ?, 'fixture', 'fixture', 'chat', 'queued', ?, ?)`).run(runId, conversationId, branchId, `input-${runId}`, sqliteRunFixtureTime, options.nextSequence === undefined ? 1 : options.nextSequence)
+}
diff --git a/.playwright/scripts/__tests__/task-archive-profile.ts b/.playwright/scripts/__tests__/task-archive-profile.ts
index 50b88a820..53ea60bb4 100644
--- a/.playwright/scripts/__tests__/task-archive-profile.ts
+++ b/.playwright/scripts/__tests__/task-archive-profile.ts
@@ -1 +1 @@
-export { openBuddyDatabase } from '../../../apps/buddy/service/src/storage/database'
+export { openBuddyDatabase, openBuddySqliteDatabase } from '../../../apps/buddy/service/src/storage/database'
diff --git a/.playwright/scripts/__tests__/task-archive.e2e.mjs b/.playwright/scripts/__tests__/task-archive.e2e.mjs
index e31853aa4..607819682 100644
--- a/.playwright/scripts/__tests__/task-archive.e2e.mjs
+++ b/.playwright/scripts/__tests__/task-archive.e2e.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
import { expect, test } from '../fixtures/electron.mjs'
-import { prepareTaskArchiveProfile, readTaskArchiveStorage, taskExists } from '../fixtures/task-archive.mjs'
+import { prepareTaskArchiveProfile, taskExists } from '../fixtures/task-archive.mjs'
const pluginId = 'p95e8d9a8d120433d9ba2058e1c844ed0.legacy-task-cleanup'
@@ -22,7 +22,6 @@ async function archiveTask(page, id) {
async function openManager(page) {
await page.locator('.desktop-app-sidebar').getByRole('button', { name: '设置', exact: true }).click()
const link = page.locator('.desktop-settings-sidebar').getByRole('link', { name: '任务归档', exact: true })
- await expect(link.locator('..').getByRole('heading', { name: '个人', exact: true })).toBeVisible()
await link.click()
await expect(page.locator('.desktop-settings-page__title')).toHaveText('任务归档')
const manager = page.getByTestId('task-archive-manager')
@@ -30,12 +29,8 @@ async function openManager(page) {
return manager
}
-async function expectStorage(app, databasePath) {
- expect(await readTaskArchiveStorage(app, databasePath)).toEqual({ version: 42, tables: [] })
-}
-
-async function launchArchiveInstance(instance) {
- const session = await instance.launch()
+async function launchArchiveInstance(instance, authority) {
+ const session = await instance.launch({ storageAuthority: authority })
await expect.poll(() => session.page.evaluate(() => window.lexoraDesktop.localChat.runtime.getStatus())).toMatchObject({ status: 'ready' })
return session
}
@@ -46,272 +41,224 @@ async function capture(page, testInfo, name) {
await testInfo.attach(name, { path: screenshot, contentType: 'image/png' })
}
-test('archive manager preserves read-only history, explicit restoration and truthful cleanup results', async ({ buddy }, testInfo) => {
- test.setTimeout(180000)
- const instance = await buddy.createInstance('task-archive-legacy')
- const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'))
- const { app, page } = await launchArchiveInstance(instance)
- await expectStorage(app, fixture.databasePath)
- const row = page.locator('[data-task-id="archive-active"]')
- await expect(row).toBeVisible()
- await row.locator('.desktop-task-sidebar__task').click()
- await expect(page.locator('.desktop-chat-page:visible')).toBeVisible()
- await archiveTask(page, 'archive-active')
- await page.getByRole('button', { name: '撤销归档', exact: true }).click()
- await expect(row).toBeVisible()
- await archiveTask(page, 'archive-active')
- let manager = await openManager(page)
- const archived = manager.locator('[data-archive-id="archive-active"]')
- await expect(archived).toBeVisible()
- await archived.getByRole('button', { name: '可归档的历史任务', exact: true }).click()
- await expect(manager).toBeHidden()
- await expect(page.getByText('此任务已归档,仅可阅读历史。取消归档不会自动恢复执行或权限。')).toBeVisible()
- await expect(page.locator('.desktop-chat-page:visible .tiptap:visible')).toHaveCount(0)
- await expect(page.locator('.desktop-chat-page:visible')).toContainText('保留的历史内容 archive-active')
- await expect(row).toBeHidden()
- expect(await page.locator('.n-message--error-type').allTextContents()).toEqual([])
- await capture(page, testInfo, 'legacy-archived-read-only')
- await page.getByRole('button', { name: '取消归档', exact: true }).click()
- await expect(row).toBeVisible()
- await expect(page.locator('.desktop-chat-page:visible .tiptap:visible')).toBeVisible()
- expect(await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))).toMatchObject({ archivedAt: null })
- manager = await openManager(page)
- const select = async (label) => {
- await manager.locator('#archive-cleanup-policy .n-base-selection').click()
- const menu = page.locator('.n-base-select-menu:visible')
- await expect(menu.locator('.n-base-select-option')).toHaveText(['不清理', '3 天', '7 天', '30 天'])
- await menu.getByText(label, { exact: true }).click()
- }
- await expect(manager.locator('#archive-cleanup-policy')).toContainText('不清理')
- await select('3 天')
- let risk = page.getByTestId('task-archive-policy-confirm')
- await expect(risk).toContainText('不可恢复')
- await expect(risk).toContainText('旧版已移除的任务不自动清理')
- await risk.getByRole('button', { name: '取消', exact: true }).click()
- expect(await page.evaluate(() => window.lexoraDesktop.localChat.conversations.getArchivePolicy())).toEqual({ days: 0 })
- await select('7 天')
- risk = page.getByTestId('task-archive-policy-confirm')
- await risk.getByRole('button', { name: '保存', exact: true }).click()
- await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.conversations.getArchivePolicy())).toEqual({ days: 7 })
- await select('3 天')
- await expect(risk).toContainText('归档满 3 天')
- await risk.getByRole('button', { name: '取消', exact: true }).click()
- await select('30 天')
- await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.conversations.getArchivePolicy())).toEqual({ days: 30 })
- await select('不清理')
- await expect.poll(() => page.evaluate(() => window.lexoraDesktop.localChat.conversations.getArchivePolicy())).toEqual({ days: 0 })
- const failed = manager.locator('[data-archive-id="archive-failed"]')
- await failed.getByRole('button', { name: '清理失败', exact: true }).click()
- await expect(page.getByText('FILE_ACCESS_DENIED', { exact: true })).toBeVisible()
- await failed.getByRole('button', { name: '清理失败', exact: true }).click()
- await expect(failed).toContainText('清理失败')
- await failed.getByRole('button', { name: '删除', exact: true }).click()
- const deletion = page.getByTestId('task-archive-delete-confirm')
- await expect(deletion).toContainText('永久删除')
- await expect(deletion).toContainText('任务独占的 workspace 和附件副本')
- await expect(deletion).toContainText('外部目录及其中的文件不受影响')
- await deletion.getByRole('button', { name: '删除', exact: true }).click()
- await expect(deletion).toBeHidden()
- await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-failed')).toBe(false)
- await expect(failed).toHaveCount(0)
- expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true)
- await expectStorage(app, fixture.databasePath)
- await capture(page, testInfo, 'legacy-archive-cleanup-result')
-})
+for (const authority of ['legacy_jsonl', 'sqlite']) {
+ test.describe(authority, () => {
+ test('archived history stays read-only until explicit restoration', async ({ buddy }, testInfo) => {
+ test.setTimeout(180000)
+ const instance = await buddy.createInstance(`task-archive-legacy-${authority}`)
+ await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'), authority)
+ const { page } = await launchArchiveInstance(instance, authority)
+ const row = page.locator('[data-task-id="archive-active"]')
+ await expect(row).toBeVisible()
+ await row.locator('.desktop-task-sidebar__task').click()
+ await expect(page.locator('.desktop-chat-page:visible')).toBeVisible()
+ await archiveTask(page, 'archive-active')
+ await page.getByRole('button', { name: '撤销归档', exact: true }).click()
+ await expect(row).toBeVisible()
+ await archiveTask(page, 'archive-active')
+ const manager = await openManager(page)
+ const archived = manager.locator('[data-archive-id="archive-active"]')
+ await expect(archived).toBeVisible()
+ await archived.getByRole('button', { name: '可归档的历史任务', exact: true }).click()
+ await expect(manager).toBeHidden()
+ await expect(page.getByText('此任务已归档,仅可阅读历史。取消归档不会自动恢复执行或权限。')).toBeVisible()
+ await expect(page.locator('.desktop-chat-page:visible .tiptap:visible')).toHaveCount(0)
+ await expect(page.locator('.desktop-chat-page:visible')).toContainText('保留的历史内容 archive-active')
+ await expect(row).toBeHidden()
+ await page.getByRole('button', { name: '取消归档', exact: true }).click()
+ await expect(row).toBeVisible()
+ await expect(page.locator('.desktop-chat-page:visible .tiptap:visible')).toBeVisible()
+ expect(await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))).toMatchObject({ archivedAt: null })
+ })
-test('active task deletion requires confirmation and permanently removes only task-owned data', async ({ buddy }, testInfo) => {
- test.setTimeout(180000)
- const instance = await buddy.createInstance('active-task-delete')
- const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'))
- const { app, page } = await launchArchiveInstance(instance)
- await expectStorage(app, fixture.databasePath)
- const row = page.locator('[data-task-id="archive-active"]')
- await expect(row).toBeVisible()
- const before = await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))
- expect(before).toMatchObject({ archivedAt: null, deletedAt: null })
- expect(Number.isSafeInteger(before.metadataRevision)).toBe(true)
- const openDeletion = async () => {
- await row.click({ button: 'right' })
- await page.locator('.n-dropdown-menu:visible').getByText('删除', { exact: true }).click()
- const confirmation = page.getByRole('dialog').filter({ hasText: '删除任务?' })
- await expect(confirmation).toContainText('将永久删除“可归档的历史任务”')
- await expect(confirmation).toContainText('不可恢复')
- await expect(confirmation).toContainText('外部目录及其中的文件不受影响')
- return confirmation
- }
- let confirmation = await openDeletion()
- await confirmation.getByRole('button', { name: '取消', exact: true }).click()
- await expect(confirmation).toBeHidden()
- await expect(row).toBeVisible()
- expect(await taskExists(app, fixture.databasePath, 'archive-active')).toBe(true)
- expect(await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))).toMatchObject({ deletedAt: null, metadataRevision: before.metadataRevision })
- expect(await fs.readFile(path.join(fixture.activeOwned, 'owned.txt'), 'utf8')).toBe('Task-owned fixture')
- confirmation = await openDeletion()
- await capture(page, testInfo, 'active-task-delete-confirmation')
- await confirmation.getByRole('button', { name: '删除', exact: true }).click()
- await expect(confirmation).toBeHidden()
- await expect(row).toBeHidden()
- await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-active')).toBe(false)
- await expect.poll(() => fs.access(fixture.activeOwned).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-existing')).toBe(true)
- expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true)
- await expectStorage(app, fixture.databasePath)
- await capture(page, testInfo, 'active-task-deleted')
-})
+ test('active task deletion requires confirmation and permanently removes only task-owned data', async ({ buddy }, testInfo) => {
+ test.setTimeout(180000)
+ const instance = await buddy.createInstance(`active-task-delete-${authority}`)
+ const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'), authority)
+ const { app, page } = await launchArchiveInstance(instance, authority)
+ const row = page.locator('[data-task-id="archive-active"]')
+ await expect(row).toBeVisible()
+ const before = await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))
+ expect(before).toMatchObject({ archivedAt: null, deletedAt: null })
+ const openDeletion = async () => {
+ await row.click({ button: 'right' })
+ await page.locator('.n-dropdown-menu:visible').getByText('删除', { exact: true }).click()
+ const confirmation = page.getByRole('dialog').filter({ hasText: '删除任务?' })
+ await expect(confirmation).toContainText('将永久删除“可归档的历史任务”')
+ await expect(confirmation).toContainText('不可恢复')
+ await expect(confirmation).toContainText('外部目录及其中的文件不受影响')
+ return confirmation
+ }
+ let confirmation = await openDeletion()
+ await confirmation.getByRole('button', { name: '取消', exact: true }).click()
+ await expect(confirmation).toBeHidden()
+ await expect(row).toBeVisible()
+ expect(await taskExists(app, fixture.databasePath, 'archive-active')).toBe(true)
+ expect(await page.evaluate(() => window.lexoraDesktop.localChat.conversations.get('archive-active'))).toMatchObject({ deletedAt: null, metadataRevision: before.metadataRevision })
+ expect(await fs.readFile(path.join(fixture.activeOwned, 'owned.txt'), 'utf8')).toBe('Task-owned fixture')
+ confirmation = await openDeletion()
+ await confirmation.getByRole('button', { name: '删除', exact: true }).click()
+ await expect(confirmation).toBeHidden()
+ await expect(row).toBeHidden()
+ await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-active')).toBe(false)
+ await expect.poll(() => fs.access(fixture.activeOwned).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-existing')).toBe(true)
+ expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true)
+ })
-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')
- const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'), 'legacy_jsonl', { legacyTasks: 32, legacyFiles: 64 })
- const { app, page } = await launchArchiveInstance(instance)
- await expectStorage(app, fixture.databasePath)
- 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_ARCHIVE)
- await page.getByTestId('extension-install-options').click()
- await page.getByTestId('extension-install').click()
- const review = page.getByTestId('extension-install-review')
- await expect(review).toBeVisible()
- await expect(review.locator('[data-permission="legacyTaskCleanup"]')).toContainText('不允许删除活动任务或任意文件')
- await review.getByTestId('extension-confirm-install').click()
- await expect(review).toBeHidden()
- await expect.poll(() => page.evaluate(async id => (await window.lexoraDesktop.extensions.list()).find(item => item.manifest.id === id)?.enabled, pluginId)).toBe(true)
- const card = page.locator(`article[data-extension-id="${pluginId}"]`)
- await expect(card.getByRole('button', { name: '打开', exact: true })).toHaveCount(0)
- await expect(page.locator('.desktop-app-sidebar').getByRole('button', { name: '旧版任务清理', exact: true })).toHaveCount(0)
- const runCleanup = async () => {
- 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 action.click()
- }
- const pluginFrame = async () => {
- let frame
- await expect.poll(async () => {
- for (const candidate of page.frames()) {
- if (await candidate.getByTestId('legacy-task-cleanup-panel').count().catch(() => 0)) {
- frame = candidate
- return true
- }
+ 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-${authority}`)
+ const fixture = await prepareTaskArchiveProfile(instance.home, testInfo.outputPath('profile-preparation'), authority, { legacyTasks: 32, legacyFiles: 64 })
+ const { app, page } = await launchArchiveInstance(instance, authority)
+ 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_ARCHIVE)
+ await page.getByTestId('extension-install-options').click()
+ await page.getByTestId('extension-install').click()
+ const review = page.getByTestId('extension-install-review')
+ await expect(review).toBeVisible()
+ await expect(review.locator('[data-permission="legacyTaskCleanup"]')).toContainText('不允许删除活动任务或任意文件')
+ await review.getByTestId('extension-confirm-install').click()
+ await expect(review).toBeHidden()
+ await expect.poll(() => page.evaluate(async id => (await window.lexoraDesktop.extensions.list()).find(item => item.manifest.id === id)?.enabled, pluginId)).toBe(true)
+ const card = page.locator(`article[data-extension-id="${pluginId}"]`)
+ await expect(card.getByRole('button', { name: '打开', exact: true })).toHaveCount(0)
+ await expect(page.locator('.desktop-app-sidebar').getByRole('button', { name: '旧版任务清理', exact: true })).toHaveCount(0)
+ const runCleanup = async () => {
+ 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 action.click()
}
- return false
- }).toBe(true)
- return frame
- }
- const showResult = async () => {
- await card.getByTestId('extension-card-more').click()
- await page.getByTestId('extension-actions').hover()
- await page.locator(`[data-extension-action="${pluginId}.result-action"]`).click()
- return pluginFrame()
- }
- const lifecycleWindow = await app.browserWindow(page)
- await lifecycleWindow.evaluate(window => window.focus())
- await runCleanup()
- 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' } }))
- await app.evaluate(({ nativeTheme }, appearance) => {
- Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { configurable: true, get: () => appearance === 'dark' })
- nativeTheme.emit('updated')
- }, appearance)
- await expect(page.locator('html')).toHaveAttribute('data-buddy-theme', appearance)
- await capture(page, testInfo, `legacy-cleanup-confirm-${appearance}`)
- }
- 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(frame.getByTestId('cleanup-confirm-delete')).toBeInViewport()
- await capture(page, testInfo, 'legacy-cleanup-confirm-minimum')
- await lifecycleWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds)
- 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()
- frame = await pluginFrame()
- await expect(confirmation()).toBeVisible()
- await lifecycleWindow.evaluate(window => window.hide())
- await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'cancelled')
- await lifecycleWindow.evaluate((window) => {
- window.show()
- window.focus()
- })
- await expect(confirmation()).toBeHidden()
- expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true)
- await frame.getByRole('button', { name: '关闭', exact: true }).click()
- await runCleanup()
- frame = await pluginFrame()
- await expect(confirmation()).toBeVisible()
- await frame.evaluate(() => {
- window.cleanupProgressSnapshots = []
- const panel = document.querySelector('[data-testid="legacy-task-cleanup-panel"]')
- new MutationObserver(() => {
- if (panel.dataset.phase === 'running')
- window.cleanupProgressSnapshots.push(Number(panel.querySelector('[data-testid="cleanup-processed"]').textContent))
- }).observe(panel, { subtree: true, attributes: true, childList: true, characterData: true })
- })
- 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')
- await frame.getByRole('button', { name: /^(后台继续|关闭)$/ }).click()
- await expect(card.getByTestId('extension-card-more')).toBeEnabled()
- await page.locator('.desktop-app-sidebar').getByRole('button', { name: '设置', exact: true }).click()
- await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-legacy-31')).toBe(false)
- await page.locator('.desktop-app-sidebar').getByRole('button', { name: '插件', exact: true }).click()
- frame = await showResult()
- await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'completed')
- await expect(frame.getByTestId('cleanup-deleted')).toHaveText('32')
- await expect(frame.getByTestId('cleanup-pending')).toHaveText('0')
- await expect(frame.getByTestId('cleanup-failed')).toHaveText('0')
- await capture(page, testInfo, 'legacy-cleanup-plugin-result-dark')
- await app.evaluate(({ nativeTheme }) => {
- Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { configurable: true, get: () => false })
- nativeTheme.emit('updated')
+ const pluginFrame = async () => {
+ let frame
+ await expect.poll(async () => {
+ for (const candidate of page.frames()) {
+ if (await candidate.getByTestId('legacy-task-cleanup-panel').count().catch(() => 0)) {
+ frame = candidate
+ return true
+ }
+ }
+ return false
+ }).toBe(true)
+ return frame
+ }
+ const showResult = async () => {
+ await card.getByTestId('extension-card-more').click()
+ await page.getByTestId('extension-actions').hover()
+ await page.locator(`[data-extension-action="${pluginId}.result-action"]`).click()
+ return pluginFrame()
+ }
+ const lifecycleWindow = await app.browserWindow(page)
+ await lifecycleWindow.evaluate(window => window.focus())
+ await runCleanup()
+ 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' } }))
+ await app.evaluate(({ nativeTheme }, appearance) => {
+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { configurable: true, get: () => appearance === 'dark' })
+ nativeTheme.emit('updated')
+ }, appearance)
+ await expect(page.locator('html')).toHaveAttribute('data-buddy-theme', appearance)
+ await capture(page, testInfo, `legacy-cleanup-confirm-${appearance}`)
+ }
+ 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(frame.getByTestId('cleanup-confirm-delete')).toBeInViewport()
+ await capture(page, testInfo, 'legacy-cleanup-confirm-minimum')
+ await lifecycleWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds)
+ 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()
+ frame = await pluginFrame()
+ await expect(confirmation()).toBeVisible()
+ await lifecycleWindow.evaluate(window => window.hide())
+ await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'cancelled')
+ await lifecycleWindow.evaluate((window) => {
+ window.show()
+ window.focus()
+ })
+ await expect(confirmation()).toBeHidden()
+ expect(await taskExists(app, fixture.databasePath, 'archive-legacy')).toBe(true)
+ await frame.getByRole('button', { name: '关闭', exact: true }).click()
+ await runCleanup()
+ frame = await pluginFrame()
+ await expect(confirmation()).toBeVisible()
+ await frame.evaluate(() => {
+ window.cleanupProgressSnapshots = []
+ const panel = document.querySelector('[data-testid="legacy-task-cleanup-panel"]')
+ new MutationObserver(() => {
+ if (panel.dataset.phase === 'running')
+ window.cleanupProgressSnapshots.push(Number(panel.querySelector('[data-testid="cleanup-processed"]').textContent))
+ }).observe(panel, { subtree: true, attributes: true, childList: true, characterData: true })
+ })
+ 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')
+ await frame.getByRole('button', { name: /^(后台继续|关闭)$/ }).click()
+ await expect(card.getByTestId('extension-card-more')).toBeEnabled()
+ await page.locator('.desktop-app-sidebar').getByRole('button', { name: '设置', exact: true }).click()
+ await expect.poll(() => taskExists(app, fixture.databasePath, 'archive-legacy-31')).toBe(false)
+ await page.locator('.desktop-app-sidebar').getByRole('button', { name: '插件', exact: true }).click()
+ frame = await showResult()
+ await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'completed')
+ await expect(frame.getByTestId('cleanup-deleted')).toHaveText('32')
+ await expect(frame.getByTestId('cleanup-pending')).toHaveText('0')
+ await expect(frame.getByTestId('cleanup-failed')).toHaveText('0')
+ await capture(page, testInfo, 'legacy-cleanup-plugin-result-dark')
+ await app.evaluate(({ nativeTheme }) => {
+ Object.defineProperty(nativeTheme, 'shouldUseDarkColors', { configurable: true, get: () => false })
+ nativeTheme.emit('updated')
+ })
+ await expect(page.locator('html')).toHaveAttribute('data-buddy-theme', 'light')
+ await capture(page, testInfo, 'legacy-cleanup-plugin-result-light')
+ await lifecycleWindow.evaluate(window => window.setBounds({ width: 980, height: 640 }))
+ await expect(frame.getByRole('button', { name: '关闭', exact: true })).toBeInViewport()
+ await capture(page, testInfo, 'legacy-cleanup-plugin-result-minimum')
+ await lifecycleWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds)
+ await lifecycleWindow.dispose()
+ for (const id of fixture.legacyTaskIds)
+ expect(await taskExists(app, fixture.databasePath, id)).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)
+ expect(await taskExists(app, fixture.databasePath, 'archive-existing')).toBe(true)
+ await frame.getByRole('button', { name: '关闭', exact: true }).click()
+ await runCleanup()
+ frame = await pluginFrame()
+ await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'completed')
+ await expect(frame.getByTestId('cleanup-total')).toHaveText('0')
+ await expect(frame.getByTestId('legacy-task-cleanup-panel')).toContainText('没有可清理的旧版任务')
+ await capture(page, testInfo, 'legacy-cleanup-plugin-empty')
+ await frame.getByRole('button', { name: '关闭', exact: true }).click()
+ await expect(page.locator('.n-message')).toHaveCount(0, { timeout: 15000 })
+ await card.getByTestId('extension-card-more').click()
+ await page.getByTestId('extension-actions').hover()
+ await capture(page, testInfo, 'legacy-cleanup-plugin-menu')
+ await page.keyboard.press('Escape')
+ await card.getByTestId('extension-disable').click()
+ await expect(card.getByTestId('extension-enable')).toBeVisible()
+ await card.getByTestId('extension-card-more').click()
+ await expect(page.getByTestId('extension-actions')).toHaveCount(0)
+ })
})
- await expect(page.locator('html')).toHaveAttribute('data-buddy-theme', 'light')
- await capture(page, testInfo, 'legacy-cleanup-plugin-result-light')
- await lifecycleWindow.evaluate(window => window.setBounds({ width: 980, height: 640 }))
- await expect(frame.getByRole('button', { name: '关闭', exact: true })).toBeInViewport()
- await capture(page, testInfo, 'legacy-cleanup-plugin-result-minimum')
- await lifecycleWindow.evaluate((window, bounds) => window.setBounds(bounds), originalBounds)
- await lifecycleWindow.dispose()
- for (const id of fixture.legacyTaskIds)
- expect(await taskExists(app, fixture.databasePath, id)).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)
- expect(await taskExists(app, fixture.databasePath, 'archive-existing')).toBe(true)
- await expectStorage(app, fixture.databasePath)
- await frame.getByRole('button', { name: '关闭', exact: true }).click()
- await runCleanup()
- frame = await pluginFrame()
- await expect(frame.getByTestId('legacy-task-cleanup-panel')).toHaveAttribute('data-phase', 'completed')
- await expect(frame.getByTestId('cleanup-total')).toHaveText('0')
- await expect(frame.getByTestId('legacy-task-cleanup-panel')).toContainText('没有可清理的旧版任务')
- await capture(page, testInfo, 'legacy-cleanup-plugin-empty')
- await frame.getByRole('button', { name: '关闭', exact: true }).click()
- await expect(page.locator('.n-message')).toHaveCount(0, { timeout: 15000 })
- await card.getByTestId('extension-card-more').click()
- await page.getByTestId('extension-actions').hover()
- await capture(page, testInfo, 'legacy-cleanup-plugin-menu')
- await page.keyboard.press('Escape')
- await card.getByTestId('extension-disable').click()
- await expect(card.getByTestId('extension-enable')).toBeVisible()
- await card.getByTestId('extension-card-more').click()
- await expect(page.getByTestId('extension-actions')).toHaveCount(0)
-})
+}
diff --git a/.playwright/scripts/__tests__/workbench.e2e.mjs b/.playwright/scripts/__tests__/workbench.e2e.mjs
index 3e1f6c69b..093cdd0bd 100644
--- a/.playwright/scripts/__tests__/workbench.e2e.mjs
+++ b/.playwright/scripts/__tests__/workbench.e2e.mjs
@@ -2,7 +2,7 @@ import fs from 'node:fs/promises'
import path from 'node:path'
import { expect, test } from '../fixtures/electron.mjs'
-test('working copies and sidebar preserve drafts, veto unsaved closure and recover across restart', async ({ buddy }) => {
+test('working copies preserve drafts, veto unsaved closure and recover across restart', async ({ buddy }) => {
const instance = await buddy.createInstance('working-copy')
const directory = path.join(instance.home, 'documents')
const document = path.join(directory, 'README.md')
@@ -47,28 +47,6 @@ test('working copies and sidebar preserve drafts, veto unsaved closure and recov
await expect.poll(readBackup).toBe(beforeUndo)
await expect(editor.locator('.view-lines')).toContainText('Second edit while dirty.')
expect(await fs.readFile(document, 'utf8')).toBe('Original document.\n')
- const sidebar = page.locator('.desktop-workbench-layout__sidebar')
- const width = () => sidebar.evaluate(element => element.getBoundingClientRect().width)
- const initialWidth = await width()
- await page.getByTestId('workbench-sidebar-resizer').focus()
- await page.keyboard.press('ArrowRight')
- const savedWidth = () => page.evaluate(async () => (await window.lexoraDesktop.settings.get()).desktop.taskSidebar.width)
- await expect.poll(savedWidth).toBeGreaterThan(initialWidth)
- const expandedWidth = await savedWidth()
- await expect.poll(width).toBe(expandedWidth)
- const toggle = page.getByTestId('workbench-sidebar-toggle')
- await page.getByTestId('workbench-sidebar-resizer').hover()
- await toggle.click()
- await expect(toggle).toHaveAttribute('aria-expanded', 'false')
- await expect(sidebar).toHaveAttribute('inert', '')
- await expect.poll(width).toBe(0)
- await expect(composer).toHaveText(draft)
- await page.locator('.desktop-workbench-layout__sidebar-collapsed-boundary').hover()
- await toggle.click()
- await expect(toggle).toHaveAttribute('aria-expanded', 'true')
- await expect(sidebar).not.toHaveAttribute('inert')
- await expect.poll(width).toBe(expandedWidth)
- await expect(composer).toHaveText(draft)
await page.getByTestId('task-context-panel').getByRole('tab', { name: '文件', exact: true }).click({ button: 'right' })
await page.locator('.n-dropdown-menu:visible').getByText('关闭全部', { exact: true }).click()
const close = page.locator('.n-dialog').filter({ hasText: '关闭前保存更改?' })
@@ -77,8 +55,6 @@ test('working copies and sidebar preserve drafts, veto unsaved closure and recov
await expect(editor.locator('.view-lines')).toContainText('Second edit while dirty.')
await instance.stop()
;({ app, page, diagnostics } = await instance.launch())
- await expect.poll(savedWidth).toBe(expandedWidth)
- await expect.poll(() => page.locator('.desktop-workbench-layout__sidebar').evaluate(element => element.getBoundingClientRect().width)).toBe(expandedWidth)
await expect(page.locator('.desktop-chat-composer__prosemirror:visible')).toHaveText(draft)
const panelToggle = page.getByTestId('context-panel-toggle')
if (await panelToggle.getAttribute('aria-expanded') === 'false')
@@ -224,6 +200,17 @@ async function sendNotificationTarget(window) {
await window.evaluate(window => window.webContents.send('lexora:app:open-target', { conversationId: 'b', runId: 'notification-run' }))
}
+async function expectNotificationBranch(page, pane) {
+ await expect(pane.locator('[data-message-id="notification-message"]')).toBeAttached()
+ const viewId = await pane.locator('.workbench__view[data-resource-id="b"]').getAttribute('data-view-id')
+ await expect.poll(() => page.evaluate(async id => (await window.lexoraDesktop.workbench.read())?.layout.views[id]?.resource, viewId)).toMatchObject({
+ scheme: 'task',
+ id: 'b',
+ data: { branchId: 'notification-branch' },
+ })
+ expect(await page.evaluate(async () => (await window.lexoraDesktop.localChat.conversations.get('b')).activeBranchId)).toBe('branch-b')
+}
+
async function expectNotificationMessage(page, pane) {
const message = pane.locator('[data-message-id="notification-message"]')
await expect(message).toContainText('The notification points to this earlier message.')
@@ -231,7 +218,7 @@ async function expectNotificationMessage(page, pane) {
const laterMessages = await page.evaluate(() => window.lexoraDesktop.localChat.conversations.listMessages({ conversationId: 'b', branchId: 'notification-branch', limit: 100 }))
expect(laterMessages.items.map(item => item.id)).toContain('later-message-24')
await expect(pane.locator('[data-message-id="later-message-24"]')).not.toBeInViewport()
- await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.conversations.get('b')).activeBranchId)).toBe('notification-branch')
+ await expectNotificationBranch(page, pane)
await expect(pane.locator('[data-message-id="message-b"]')).toHaveCount(0)
}
@@ -285,7 +272,7 @@ test('notification navigation: app:open-target opens an unopened task while hidd
await expect.poll(() => window.evaluate(window => ({ visible: window.isVisible(), focused: window.isFocused() }))).toEqual({ visible: false, focused: false })
await sendNotificationTarget(window)
- await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.conversations.get('b')).activeBranchId)).toBe('notification-branch')
+ await expectNotificationBranch(page, notificationPane(page, 'b'))
await expect(notificationTask(page, 'b')).toHaveClass(/is-active/)
expect(await window.evaluate(window => window.isVisible())).toBe(false)
await window.evaluate(window => window.showInactive())
@@ -297,73 +284,3 @@ test('notification navigation: app:open-target opens an unopened task while hidd
await expect(notificationTask(page, 'b')).toHaveClass(/is-active/)
expect(diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
})
-
-test('resource tab menus pin, close by position and preserve pins across restart', async ({ buddy }) => {
- const instance = await buddy.createInstance('resource-tab-menu')
- let { page, diagnostics } = await instance.launch()
- await expect(page.getByRole('textbox', { name: '对话消息', exact: true })).toBeVisible()
- await page.keyboard.press('Control+Shift+P')
- await page.getByPlaceholder('输入命令名称').fill('浏览器')
- await page.getByPlaceholder('输入命令名称').press('Enter')
- const panel = () => page.getByTestId('task-context-panel')
- const tabs = () => panel().getByRole('tab')
- const menu = () => page.locator('.n-dropdown-menu:visible')
- async function add() {
- const count = await tabs().count()
- await page.getByTestId('context-add-tab').click()
- await page.getByRole('menuitem', { name: '浏览器', exact: true }).click()
- await expect(tabs()).toHaveCount(count + 1)
- }
- async function action(index, label) {
- await tabs().nth(index).click({ button: 'right' })
- await expect(menu().getByText(label, { exact: true }).locator('..')).not.toHaveClass(/disabled/)
- await menu().getByText(label, { exact: true }).click()
- }
- await expect(tabs()).toHaveCount(1)
- await add()
- await add()
- await add()
- const ids = await tabs().evaluateAll(elements => elements.map(element => element.id))
- await action(1, '固定')
- await expect(tabs().first()).toHaveAttribute('id', ids[1])
- await expect(panel().locator('[data-pinned="true"]')).toHaveCount(1)
- await expect(tabs().last()).toHaveAttribute('aria-selected', 'true')
- await tabs().nth(2).click({ button: 'right' })
- await expect(menu().getByText('关闭左侧', { exact: true }).locator('..')).not.toHaveClass(/disabled/)
- await menu().getByText('关闭左侧', { exact: true }).click()
- await expect(tabs()).toHaveCount(3)
- expect(await tabs().evaluateAll(elements => elements.map(element => element.id))).toEqual([ids[1], ids[2], ids[3]])
- await action(1, '关闭右侧')
- await expect(tabs()).toHaveCount(2)
- expect(await tabs().evaluateAll(elements => elements.map(element => element.id))).toEqual([ids[1], ids[2]])
- await add()
- await action(1, '关闭其他')
- await expect(tabs()).toHaveCount(2)
- await action(1, '关闭全部')
- await expect(tabs()).toHaveCount(1)
- await expect(tabs().first()).toHaveAttribute('id', ids[1])
- await tabs().first().focus()
- await page.keyboard.press('Shift+F10')
- await expect(menu().getByText('取消固定', { exact: true })).toBeVisible()
- for (const label of ['关闭其他', '关闭左侧', '关闭右侧', '关闭全部'])
- await expect(menu().getByText(label, { exact: true }).locator('..')).toHaveClass(/disabled/)
- await page.keyboard.press('Escape')
- await expect(menu()).toBeHidden()
- expect(diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
- await instance.stop()
- ;({ page, diagnostics } = await instance.launch())
- const toggle = page.getByTestId('context-panel-toggle')
- await expect(toggle).toBeVisible()
- if (await toggle.getAttribute('aria-expanded') === 'false')
- await toggle.click()
- await expect(panel().locator('[data-pinned="true"]')).toHaveCount(1)
- await action(0, '取消固定')
- await expect(panel().locator('[data-pinned="true"]')).toHaveCount(0)
- await action(0, '固定')
- await panel().getByRole('button', { name: '取消固定', exact: true }).click()
- await expect(tabs()).toHaveCount(1)
- await expect(panel().locator('[data-pinned="true"]')).toHaveCount(0)
- await panel().getByRole('button', { name: '关闭新标签页', exact: true }).click()
- await expect(tabs()).toHaveCount(0)
- expect(diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
-})
diff --git a/.playwright/scripts/buddy-test.mjs b/.playwright/scripts/buddy-test.mjs
index ed2f65fab..536568c6a 100644
--- a/.playwright/scripts/buddy-test.mjs
+++ b/.playwright/scripts/buddy-test.mjs
@@ -8,6 +8,7 @@ import { createServer } from 'node:net'
import { homedir } from 'node:os'
import path from 'node:path'
import process from 'node:process'
+import { launchDaemonDesktop } from './fixtures/local-service.mjs'
import { attachPageDiagnostics, ROOT, serializeError } from './shared.mjs'
const repoRoot = ROOT
@@ -38,7 +39,7 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
const pending = new Set()
const records = []
let disposed = false
- async function createInstance(label) {
+ async function createInstance(label, { executablePath: instanceExecutablePath = executablePath } = {}) {
assert(/^[\w-]{1,64}$/.test(label), 'Invalid test instance name')
const home = await fs.mkdtemp(path.join(instancesRoot, `${label}-`))
const identity = await fs.stat(home)
@@ -83,11 +84,17 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
instances.push(instance)
return instance
- async function launch({ maintenance = false, expectedRoot = home, startupStatus = 'ready' } = {}) {
+ async function launch({ maintenance = false, profileRoot = home, expectedRoot = profileRoot, startupStatus = 'ready', storageAuthority = 'legacy_jsonl', serviceMode = 'utility' } = {}) {
assert(['ready', 'failed'].includes(startupStatus), 'Unsupported startup expectation')
assert(contains(instancesRoot, await canonicalPath(expectedRoot)), 'Expected root must stay in this isolated test run')
- const { _electron: electron } = await import('@playwright/test')
- const environment = createTestEnvironment(home)
+ const { _electron: electron, expect } = await import('@playwright/test')
+ assert(['legacy_jsonl', 'sqlite', 'default'].includes(storageAuthority), 'Unsupported storage authority')
+ assert(contains(instancesRoot, await canonicalPath(profileRoot)), 'Profile must stay in this isolated test run')
+ assert(['utility', 'daemon'].includes(serviceMode), 'Unsupported service mode')
+ assert(serviceMode !== 'daemon' || (!maintenance && !instanceExecutablePath && !rendererUrl && storageAuthority === 'sqlite'), 'Daemon fixture requires the SQLite development application')
+ const environment = createTestEnvironment(profileRoot)
+ if (storageAuthority !== 'default')
+ environment.LEXORA_BUDDY_STORAGE_AUTHORITY = storageAuthority
if (rendererUrl)
environment.ELECTRON_RENDERER_URL = rendererUrl
if (process.platform === 'linux') {
@@ -99,9 +106,11 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
launchNumber += 1
try {
const args = [...(process.platform === 'linux' ? ['--ozone-platform=x11', '--disable-setuid-sandbox'] : []), ...(passwordStore ? [`--password-store=${passwordStore}`] : []), '--disable-gpu']
- application = executablePath
- ? await launchInstalled(executablePath, args, environment, { maintenance, artifactDirectory, launchNumber })
- : await electron.launch({ executablePath: require('electron'), args: [...args, path.resolve(appPath)], chromiumSandbox: true, cwd: repoRoot, env: environment, timeout: 45000 })
+ application = serviceMode === 'daemon'
+ ? await launchDaemonDesktop({ home: profileRoot, buddyRoot, hostExecutable: require('electron'), hostArguments: args, environment, artifactDirectory })
+ : instanceExecutablePath
+ ? await launchInstalled(instanceExecutablePath, args, environment, { maintenance, artifactDirectory, launchNumber })
+ : await electron.launch({ executablePath: require('electron'), args: [...args, path.resolve(appPath)], chromiumSandbox: true, cwd: repoRoot, env: environment, timeout: 45000 })
applicationProcess = application.process()
launchRecord.pid = applicationProcess.pid
applicationProcess.stderr?.on('data', (chunk) => {
@@ -117,10 +126,10 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
return { app: application, page, diagnostics: launchRecord.diagnostics }
}
assert.equal(rendererUrl ? new URL(page.url()).origin : new URL(page.url()).protocol, rendererUrl ? new URL(rendererUrl).origin : 'lexora-app:')
- await page.waitForFunction(async status => (await window.lexoraDesktop?.app.startup.getState())?.status === status, startupStatus, { timeout: 45000 })
+ await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop?.app.startup.getState())?.status), { timeout: 45000 }).toBe(startupStatus)
const info = await page.evaluate(() => window.lexoraDesktop.app.getInfo())
assert.equal(info.runtimeProfile, 'test')
- if (executablePath)
+ if (instanceExecutablePath)
assert.equal(info.isPackaged, true)
assert.equal(await fs.realpath(path.dirname(info.configPath)), await canonicalPath(expectedRoot))
const { runtimeProfile, isPackaged, version, platform, configPath } = info
@@ -137,7 +146,7 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
if (application) {
const current = application
const child = applicationProcess
- if (executablePath || (child.exitCode === null && child.signalCode === null)) {
+ if (instanceExecutablePath || current.serviceMode === 'daemon' || (child.exitCode === null && child.signalCode === null)) {
await page?.screenshot({ path: path.join(artifactDirectory, `launch-${launchNumber}.png`), animations: 'disabled', timeout: 5000 }).catch(() => {})
await withTimeout(current.context().tracing.stop({ path: path.join(artifactDirectory, `trace-${launchNumber}.zip`) }), 10000, 'Trace export timed out').catch(() => {})
try {
@@ -169,9 +178,9 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
artifacts,
runId,
records,
- async createInstance(label = 'desktop') {
+ async createInstance(label = 'desktop', options = {}) {
assert(!disposed, 'Test run has been disposed')
- const operation = createInstance(label)
+ const operation = createInstance(label, options)
pending.add(operation)
try {
return await operation
@@ -197,10 +206,10 @@ export async function createBuddyTestRun({ appPath = process.env.LEXORA_TEST_APP
}
}
-function createTestEnvironment(home) {
+export function createTestEnvironment(home) {
const environment = Object.fromEntries(Object.entries(process.env).filter(([key, value]) => value !== undefined
&& !/^(?:LEXORA_|ELECTRON_|PI_|XDG_|WAYLAND_DISPLAY$)/.test(key)))
- return { ...environment, LEXORA_BUDDY_PROFILE: 'test', LEXORA_HOME: home }
+ return { ...environment, LEXORA_BUDDY_PROFILE: 'test', LEXORA_HOME: home, LEXORA_BUDDY_SERVICE_MODE: 'utility' }
}
function contains(root, candidate) {
@@ -225,7 +234,7 @@ async function canonicalPath(value) {
}
}
-async function startDisplay() {
+export async function startDisplay() {
const child = spawn('Xvfb', ['-displayfd', '3', '-screen', '0', '1500x950x24', '-nolisten', 'tcp'], { stdio: ['ignore', 'ignore', 'pipe', 'pipe'] })
let stderr = ''
child.stderr.on('data', (chunk) => {
diff --git a/.playwright/scripts/fixtures/attachment-publication-crash.ts b/.playwright/scripts/fixtures/attachment-publication-crash.ts
new file mode 100644
index 000000000..ce7676b83
--- /dev/null
+++ b/.playwright/scripts/fixtures/attachment-publication-crash.ts
@@ -0,0 +1,68 @@
+import { Buffer } from 'node:buffer'
+import { writeSync } from 'node:fs'
+import { readFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import process from 'node:process'
+import { fileStorage } from '../../../apps/buddy/platform/filesystem/fileStorage'
+import { AttachmentService } from '../../../apps/buddy/service/src/attachments/AttachmentService'
+import { createAttachmentRepository } from '../../../apps/buddy/service/src/storage/attachmentRepository'
+import { BuddyDataPaths } from '../../../apps/buddy/service/src/storage/BuddyDataPaths'
+import { openBuddyMigrationCandidate } from '../../../apps/buddy/service/src/storage/database'
+
+const [mode, directory, point] = process.argv.slice(2)
+if (!directory || !['publish', 'recover'].includes(mode!))
+ throw new Error('Invalid attachment crash fixture arguments')
+const database = openBuddyMigrationCandidate({ databasePath: join(directory, 'data.sqlite3') })
+database.exec('UPDATE storage_profile SET authority = \'sqlite\', migration_state = \'ready\'')
+const repository = createAttachmentRepository(database)
+const service = new AttachmentService({ paths: new BuddyDataPaths(join(directory, 'profile')), repository })
+function checkpoint(name: string) {
+ if (name !== point)
+ return
+ writeSync(1, `${JSON.stringify({ checkpoint: name })}\n`)
+ process.kill(process.pid, 'SIGKILL')
+}
+if (mode === 'publish') {
+ const persistence = repository.persistence!
+ const prepare = persistence.prepare.bind(persistence)
+ persistence.prepare = (input) => {
+ const result = prepare(input)
+ checkpoint('prepared')
+ return result
+ }
+ const replace = fileStorage.replace
+ fileStorage.replace = async (...args) => {
+ checkpoint('file-synced')
+ await replace(...args)
+ checkpoint('renamed')
+ }
+ const syncDirectory = fileStorage.syncDirectory
+ fileStorage.syncDirectory = async (...args) => {
+ await syncDirectory(...args)
+ checkpoint('directory-synced')
+ }
+ const create = repository.create
+ repository.create = (record) => {
+ const result = create(record)
+ checkpoint('bound')
+ return result
+ }
+ service.onDidChange((event) => {
+ if (event.kind === 'file-published')
+ checkpoint('published')
+ })
+ await service.registerUploads('crash-draft', [{ name: 'source.txt', mimeType: 'text/plain', bytes: Buffer.from('durable attachment bytes') }])
+ throw new Error('Requested publication checkpoint was not reached')
+}
+else {
+ const before = database.prepare('SELECT state FROM managed_files').get()
+ const recovered = await service.reconcileStorage()
+ const records = repository.listAll()
+ const bytes = await Promise.all(records.map(record => readFile(record.storedPath, 'utf8')))
+ const files = database.prepare('SELECT state, sha256, durability FROM managed_files').all()
+ const references = database.prepare('SELECT kind, owner_id FROM file_references').all()
+ const preparations = database.prepare('SELECT state, reserved_bytes FROM file_preparations').all()
+ await service.dispose()
+ database.close()
+ writeSync(1, `${JSON.stringify({ before, recovered, files, references, preparations, bytes })}\n`)
+}
diff --git a/.playwright/scripts/fixtures/electron.mjs b/.playwright/scripts/fixtures/electron.mjs
index 9e154fd28..19f954ff5 100644
--- a/.playwright/scripts/fixtures/electron.mjs
+++ b/.playwright/scripts/fixtures/electron.mjs
@@ -62,7 +62,7 @@ export const test = base.extend({
for (const file of await fs.readdir(record.artifactDirectory)) {
await testInfo.attach(`${path.basename(record.home)}-${file}`, {
path: path.join(record.artifactDirectory, file),
- contentType: file.endsWith('.png') ? 'image/png' : 'application/zip',
+ contentType: file.endsWith('.png') ? 'image/png' : file.endsWith('.zip') ? 'application/zip' : file.endsWith('.json') ? 'application/json' : 'text/plain',
})
}
}
@@ -74,7 +74,8 @@ export const test = base.extend({
export { expect } from '@playwright/test'
export async function useSyntheticCredentialStorage({ app, page }) {
- await base.expect.poll(async () => (await page.evaluate(() => window.lexoraDesktop.localChat.runtime.getStatus())).status, { timeout: 45000 }).toBe('ready')
+ await base.expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.app.startup.getState()).status), { timeout: 45000 }).toBe('ready')
+ const generation = await page.evaluate(async () => (await window.lexoraDesktop.app.startup.getState()).generation)
await app.evaluate(({ app, safeStorage }) => {
if (app.getName() !== 'Lexora Buddy Test')
throw new Error('Synthetic credentials require an isolated test instance')
@@ -95,5 +96,8 @@ export async function useSyntheticCredentialStorage({ app, page }) {
})
})
await page.evaluate(() => window.lexoraDesktop.localChat.runtime.restart())
- await base.expect.poll(async () => (await page.evaluate(() => window.lexoraDesktop.localChat.runtime.getStatus())).status, { timeout: 45000 }).toBe('ready')
+ await base.expect.poll(async () => {
+ const state = await page.evaluate(() => window.lexoraDesktop.app.startup.getState())
+ return { ready: state.status === 'ready', restarted: state.generation !== generation }
+ }, { timeout: 45000 }).toEqual({ ready: true, restarted: true })
}
diff --git a/.playwright/scripts/fixtures/extension-contributions.mjs b/.playwright/scripts/fixtures/extension-contributions.mjs
index 9c7b4df97..fd27ad848 100644
--- a/.playwright/scripts/fixtures/extension-contributions.mjs
+++ b/.playwright/scripts/fixtures/extension-contributions.mjs
@@ -15,7 +15,7 @@ export async function writeContributionPlugin(directory, name, { uno = false, me
entry: 'host.js',
...(media ? { permissions: { network: ['https://media.example.com'], themeManagement: true } } : {}),
contributes: {
- commands: ['read', 'save', 'failure', 'invalid', 'timeout', ...(media ? ['download'] : [])].map(command => ({ id: `${id}.${command}`, title: command, hidden: true })),
+ commands: ['read', 'save', 'failure', 'invalid', 'wait', ...(media ? ['download'] : [])].map(command => ({ id: `${id}.${command}`, title: command, hidden: true })),
views: [
{ id: `${id}.settings`, title: `Settings ${name}`, entry: 'settings.js', resource: 'none', location: 'page' },
{ id: `${id}.footer`, title: `Footer ${name}`, entry: 'footer.js', resource: 'none' },
@@ -55,7 +55,7 @@ async function activate(media, context) {
throw new Error('Private plugin error')
}))
context.subscriptions.add(context.commands.register(`${id}.invalid`, () => Number.NaN))
- context.subscriptions.add(context.commands.register(`${id}.timeout`, () => new Promise(() => {})))
+ context.subscriptions.add(context.commands.register(`${id}.wait`, () => new Promise(() => {})))
context.subscriptions.add(context.commands.register(`${id}.save`, async ({ arguments: patch }) => {
state = { ...state, ...patch }
await context.storage.set(state)
@@ -78,7 +78,7 @@ async function settings(pluginId, context, container) {
async function footer(pluginId, uno, context, container) {
container.dataset.contributionFixture = `${pluginId}.footer`
- window.fixture = { instance: crypto.randomUUID(), visible: context.visible }
+ window.fixture = { visible: context.visible }
context.onVisibilityChange(visible => window.fixture.visible = visible)
if (uno)
container.className = 'h-full grid place-items-center rounded-control bg-accent text-on-accent text-[14px] font-sans transition-colors duration-[var(--lexora-motion-state-duration)]'
diff --git a/.playwright/scripts/fixtures/local-service.mjs b/.playwright/scripts/fixtures/local-service.mjs
new file mode 100644
index 000000000..da77d4782
--- /dev/null
+++ b/.playwright/scripts/fixtures/local-service.mjs
@@ -0,0 +1,213 @@
+import assert from 'node:assert/strict'
+import { spawn } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { once } from 'node:events'
+import fs from 'node:fs/promises'
+import net from 'node:net'
+import path from 'node:path'
+import process from 'node:process'
+import { chromium, expect } from '@playwright/test'
+
+export async function connectLocalService(discovery, secret, role = 'management') {
+ const socket = net.createConnection(role === 'product' ? discovery.productEndpoint : discovery.managementEndpoint)
+ const rpc = createRequests(frame => socket.write(`${JSON.stringify({ jsonrpc: '2.0', ...frame })}\n`), randomUUID)
+ let buffer = ''
+ let welcome
+ const ready = new Promise((resolve, reject) => {
+ welcome = { resolve, reject }
+ })
+ socket.on('error', (error) => {
+ welcome.reject(error)
+ rpc.reject(error)
+ })
+ socket.on('close', () => {
+ const error = new Error('SERVICE_CLOSED')
+ welcome.reject(error)
+ rpc.reject(error)
+ })
+ socket.on('data', (chunk) => {
+ buffer += chunk
+ while (buffer.includes('\n')) {
+ const end = buffer.indexOf('\n')
+ const frame = JSON.parse(buffer.slice(0, end))
+ buffer = buffer.slice(end + 1)
+ if (frame.type === 'welcome')
+ welcome.resolve(frame)
+ else rpc.receive(frame)
+ }
+ })
+ const { protocol, profileId, serviceInstanceId, buildId, sessionId, userId } = discovery
+ socket.write(`${JSON.stringify({ protocol, profileId, serviceInstanceId, buildId, sessionId, userId, type: 'hello', role, secret })}\n`)
+ try {
+ expect(await ready).toMatchObject({ serviceInstanceId, buildId, sessionId, userId })
+ return { request: rpc.request, close: () => socket.destroy() }
+ }
+ catch (error) {
+ socket.destroy()
+ throw error
+ }
+}
+
+export async function launchDaemonDesktop({ home, buddyRoot, hostExecutable, hostArguments, environment, artifactDirectory }) {
+ assert.equal(process.platform, 'linux', 'Daemon Desktop fixture currently requires Linux')
+ assert.equal(environment.LEXORA_BUDDY_PROFILE, 'test')
+ environment = { ...environment, XDG_SESSION_ID: process.env.XDG_SESSION_ID }
+ const output = path.join(buddyRoot, '.output')
+ const release = await readJson(path.join(output, 'release-set.json'))
+ const boot = (await fs.readFile('/proc/sys/kernel/random/boot_id', 'utf8')).trim()
+ const runtimeDirectory = path.join(home, '.runtime')
+ await fs.mkdir(runtimeDirectory, { recursive: true, mode: 0o700 })
+ const config = {
+ version: 1,
+ profile: 'test',
+ profileRoot: home,
+ resourcesRoot: path.join(output, path.dirname(release.core.entry), 'resources'),
+ nodeExecutable: path.join(output, release.node.entry),
+ coreEntry: path.join(output, release.core.entry),
+ hostExecutable,
+ hostArguments: [...hostArguments, '--inspect=127.0.0.1:0', '--remote-debugging-port=0', buddyRoot],
+ releaseSetPath: path.join(output, 'release-set.json'),
+ buildId: release.buildId,
+ sessionId: `${boot}:${process.env.XDG_SESSION_ID}`,
+ userId: String(process.getuid()),
+ leaseDirectory: path.join(path.dirname(home), '.leases'),
+ storageAuthority: 'sqlite',
+ }
+ const launchFile = path.join(runtimeDirectory, 'launch.json')
+ await fs.writeFile(launchFile, JSON.stringify(config), { mode: 0o600 })
+ const core = spawn(config.nodeExecutable, [config.coreEntry, '--config', launchFile], { cwd: buddyRoot, env: environment, stdio: ['ignore', 'pipe', 'pipe'] })
+ let log = ''
+ for (const stream of [core.stdout, core.stderr]) {
+ stream.on('data', (chunk) => {
+ log = `${log}${chunk}`.slice(-1024 * 1024)
+ })
+ }
+ let browser
+ let inspector
+ let client
+ let hostPid
+ const stopped = once(core, 'exit')
+ const close = async () => {
+ await inspector?.close()
+ await browser?.close().catch(() => {})
+ try {
+ if (core.exitCode === null && core.signalCode === null) {
+ const discovery = await readJson(path.join(runtimeDirectory, 'service.json'))
+ if (client && discovery)
+ await client.request('service.stop', { expectedServiceInstanceId: discovery.serviceInstanceId, commandId: randomUUID(), reason: 'explicit' }).catch(() => {})
+ else core.kill('SIGTERM')
+ await expect.poll(() => core.exitCode !== null || core.signalCode !== null, { timeout: 20000 }).toBe(true)
+ }
+ await stopped
+ if (hostPid)
+ await expect.poll(() => processAlive(hostPid)).toBe(false)
+ }
+ finally {
+ client?.close()
+ if (core.exitCode === null && core.signalCode === null)
+ core.kill('SIGTERM')
+ await fs.writeFile(path.join(artifactDirectory, 'daemon.log'), log, { mode: 0o600 })
+ }
+ }
+ try {
+ await expect.poll(async () => {
+ assert(core.exitCode === null && core.signalCode === null, `Node service exited: ${log}`)
+ return (await readJson(path.join(runtimeDirectory, 'service.json')))?.phase
+ }, { timeout: 120000 }).toBe('ready')
+ const discovery = await readJson(path.join(runtimeDirectory, 'service.json'))
+ expect(discovery.process.pid).toBe(core.pid)
+ expect(await fs.realpath(`/proc/${core.pid}/exe`)).toBe(await fs.realpath(config.nodeExecutable))
+ const credentials = await readJson(path.join(runtimeDirectory, 'local-client.json'))
+ client = await connectLocalService(discovery, credentials.managementSecret)
+ await expect.poll(() => /DevTools listening on ws:\/\/\S+/.test(log)).toBe(true)
+ browser = await chromium.connectOverCDP(log.match(/DevTools listening on (ws:\/\/\S+)/)[1])
+ await expect.poll(() => /Debugger listening on ws:\/\/\S+/.test(log)).toBe(true)
+ inspector = await connectInspector(log.match(/Debugger listening on (ws:\/\/\S+)/)[1])
+ hostPid = await inspector.evaluate(() => process.pid)
+ expect(hostPid).not.toBe(core.pid)
+ const opened = await client.request('service.openDesktop', { expectedServiceInstanceId: discovery.serviceInstanceId, intent: { kind: 'tasks' } })
+ expect(opened).toMatchObject({ accepted: true, uiReady: true, targetVisible: true, visible: true })
+ const page = browser.contexts().flatMap(context => context.pages()).find(page => page.url().startsWith('lexora-app:'))
+ assert(page, 'Service did not open Desktop')
+ await fs.writeFile(path.join(artifactDirectory, 'daemon.json'), JSON.stringify({ corePid: core.pid, hostPid, buildId: release.buildId, nodeExecutable: config.nodeExecutable }, null, 2))
+ return { serviceMode: 'daemon', context: () => page.context(), firstWindow: async () => page, process: () => core, evaluate: inspector.evaluate, detachMain: () => inspector.close(), close }
+ }
+ catch (error) {
+ await close()
+ throw error
+ }
+}
+
+async function connectInspector(endpoint) {
+ const socket = new WebSocket(endpoint)
+ const rpc = createRequests(frame => socket.send(JSON.stringify(frame)))
+ socket.addEventListener('message', event => rpc.receive(JSON.parse(event.data)))
+ socket.addEventListener('close', () => rpc.reject(new Error('INSPECTOR_CLOSED')))
+ await once(socket, 'open')
+ return {
+ async evaluate(callback, argument) {
+ const result = await rpc.request('Runtime.evaluate', { expression: `(${callback.toString()})(process.mainModule.require('electron'), ${JSON.stringify(argument) ?? 'undefined'})`, awaitPromise: true, returnByValue: true })
+ if (result.exceptionDetails)
+ throw new Error(result.exceptionDetails.exception?.description ?? result.exceptionDetails.text)
+ return result.result.value
+ },
+ async close() {
+ if (socket.readyState === WebSocket.OPEN) {
+ const closed = once(socket, 'close')
+ socket.close()
+ await closed
+ }
+ },
+ }
+}
+
+function createRequests(send, nextId) {
+ const pending = new Map()
+ let sequence = 0
+ return {
+ request(method, params) {
+ const id = nextId ? nextId() : ++sequence
+ return new Promise((resolve, reject) => {
+ const timeout = setTimeout(() => {
+ pending.delete(id)
+ reject(new Error(`Request timed out: ${method}`))
+ }, 45000)
+ pending.set(id, { resolve, reject, timeout })
+ send({ id, method, params })
+ })
+ },
+ receive(frame) {
+ const request = pending.get(frame.id)
+ if (!request)
+ return
+ pending.delete(frame.id)
+ clearTimeout(request.timeout)
+ if (frame.error)
+ request.reject(new Error(frame.error.message))
+ else request.resolve(frame.result)
+ },
+ reject(error) {
+ for (const request of pending.values()) {
+ clearTimeout(request.timeout)
+ request.reject(error)
+ }
+ pending.clear()
+ },
+ }
+}
+
+export async function readJson(file) {
+ try {
+ return JSON.parse(await fs.readFile(file, 'utf8'))
+ }
+ catch (error) {
+ if (error.code === 'ENOENT')
+ return null
+ throw error
+ }
+}
+
+export async function processAlive(pid) {
+ const stat = await fs.readFile(`/proc/${pid}/stat`, 'utf8').catch(() => null)
+ return stat !== null && !['Z', 'X'].includes(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[0])
+}
diff --git a/.playwright/scripts/fixtures/mobile-desktop.mjs b/.playwright/scripts/fixtures/mobile-desktop.mjs
new file mode 100644
index 000000000..d12d6ca22
--- /dev/null
+++ b/.playwright/scripts/fixtures/mobile-desktop.mjs
@@ -0,0 +1,18 @@
+import { createRequire, isBuiltin } from 'node:module'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+const root = fileURLToPath(new URL('../../../', import.meta.url))
+
+export async function prepareMobileDesktopProfile(home, output) {
+ const requireBuddy = createRequire(path.join(root, 'apps/buddy/package.json'))
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: {
+ ssr: path.join(root, '.playwright/scripts/__tests__/prepareProductProfile.ts'),
+ outDir: output,
+ target: 'node26',
+ rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'prepare.mjs', format: 'es' } },
+ } })
+ const { prepareProductProfile } = await import(pathToFileURL(path.join(output, 'prepare.mjs')).href)
+ prepareProductProfile(home)
+}
diff --git a/.playwright/scripts/fixtures/runtime-network-utility.mjs b/.playwright/scripts/fixtures/runtime-network-utility.mjs
index c9b757fe8..ca113f51f 100644
--- a/.playwright/scripts/fixtures/runtime-network-utility.mjs
+++ b/.playwright/scripts/fixtures/runtime-network-utility.mjs
@@ -1,9 +1,10 @@
import process from 'node:process'
import { setTimeout as delay } from 'node:timers/promises'
-import { startRuntimeNetwork } from '../../../apps/buddy/service/src/network/runtimeNetwork.ts'
+import { RuntimeNetwork } from '../../../apps/buddy/service/src/network/runtimeNetwork.ts'
async function run() {
- const stop = startRuntimeNetwork()
+ const network = new RuntimeNetwork()
+ await network.replace({ httpProxy: process.env.HTTP_PROXY, httpsProxy: process.env.HTTPS_PROXY, noProxy: '' })
const start = performance.now()
const before = process.cpuUsage()
let failure
@@ -49,7 +50,7 @@ async function run() {
catch (error) { cancelled = error.name === 'AbortError' }
return { versions: { electron: process.versions.electron, node: process.versions.node, undici: process.versions.undici }, failure, settleMs: settled - start, totalCpuMs: (total.user + total.system) / 1000, idleCpuMs: (idleUsage.user + idleUsage.system) / 1000, stream, responseCompatible: response instanceof Response, websocket, cancelled }
}
- finally { await stop() }
+ finally { await network.dispose() }
}
run().then(result => process.parentPort.postMessage(result), error => process.parentPort.postMessage({ error: error.message }))
diff --git a/.playwright/scripts/fixtures/service-process-harness.ts b/.playwright/scripts/fixtures/service-process-harness.ts
new file mode 100644
index 000000000..39fbfc2e3
--- /dev/null
+++ b/.playwright/scripts/fixtures/service-process-harness.ts
@@ -0,0 +1,62 @@
+import type { RuntimeRpcPeerContract } from '../../../apps/buddy/shared/runtime/rpcPeer'
+import { openBuddyMigrationCandidate } from '../../../apps/buddy/service/src/storage/database'
+import { extensionAgentRpc } from '../../../apps/buddy/shared/extensions/extensionAgent'
+import { extensionCapabilitiesRpc } from '../../../apps/buddy/shared/extensions/extensionCapabilities'
+import { extensionChatRpc } from '../../../apps/buddy/shared/extensions/extensionChat'
+import { extensionImageRpc } from '../../../apps/buddy/shared/extensions/extensionImage'
+import { extensionImageReadingRpc } from '../../../apps/buddy/shared/extensions/extensionImageReading'
+import { extensionShellRpc } from '../../../apps/buddy/shared/extensions/extensionShell'
+import { extensionSkillsRpc } from '../../../apps/buddy/shared/extensions/extensionSkills'
+import { imageRpc } from '../../../apps/buddy/shared/images/imagePreferences'
+import { DEFAULT_NETWORK_PERMISSIONS } from '../../../apps/buddy/shared/permissions/networkPermissions'
+import { networkPermissionsRpc } from '../../../apps/buddy/shared/permissions/networkPermissionsRpc'
+import { HOST_SPEECH_MODELS } from '../../../apps/buddy/shared/speech/speechApi'
+
+export { RuntimeRpcPeer } from '../../../apps/buddy/platform/ipc/runtimeRpcPeer'
+export { createBuddyServiceEnvironment } from '../../../apps/buddy/platform/process/serviceEnvironment'
+export { DEFAULT_RUNTIME_PREFERENCES } from '../../../apps/buddy/shared/runtime/runtimePreferences'
+export { BUDDY_SERVICE_PROTOCOL_VERSION } from '../../../apps/buddy/shared/runtime/runtimeProtocol'
+
+export function registerFixtureHost(peer: RuntimeRpcPeerContract, options: { secrets?: Map, persistSecrets?: () => Promise } = {}): void {
+ const credentials = new Map([['process-fixture', { type: 'api_key', key: 'process-fixture-key' }]])
+ peer.onRequest('host.credentials.list', () => ({ ok: true, providers: [...credentials.keys()].map(providerId => ({ providerId, type: 'api_key' })) }))
+ peer.onRequest('host.credentials.read', raw => ({ ok: true, value: credentials.get((raw as { providerId: string }).providerId) ?? null }))
+ peer.onRequest('host.credentials.write', (raw) => {
+ const { providerId, credential } = raw as { providerId: string, credential: unknown }
+ credentials.set(providerId, credential)
+ return { ok: true }
+ })
+ peer.onRequest('host.credentials.delete', (raw) => {
+ credentials.delete((raw as { providerId: string }).providerId)
+ return { ok: true }
+ })
+ const secrets = options.secrets ?? new Map()
+ peer.onRequest('host.secrets.read', (raw) => {
+ const { namespace, id } = raw as { namespace: string, id: string }
+ return { ok: true, value: secrets.get(`${namespace}:${id}`) ?? null }
+ })
+ peer.onRequest('host.secrets.write', async (raw) => {
+ const { namespace, id, value } = raw as { namespace: string, id: string, value: unknown }
+ secrets.set(`${namespace}:${id}`, value)
+ await options.persistSecrets?.()
+ return { ok: true }
+ })
+ peer.onRequest('host.secrets.delete', async (raw) => {
+ const { namespace, id } = raw as { namespace: string, id: string }
+ secrets.delete(`${namespace}:${id}`)
+ await options.persistSecrets?.()
+ return { ok: true }
+ })
+ for (const method of [extensionAgentRpc.list, extensionCapabilitiesRpc.list, extensionChatRpc.list, extensionImageRpc.list, extensionImageReadingRpc.list, extensionShellRpc.list, extensionSkillsRpc.list, HOST_SPEECH_MODELS])
+ peer.onRequest(method, () => [])
+ peer.onRequest(imageRpc.preferences, () => ({}))
+ peer.onRequest(networkPermissionsRpc.get, () => structuredClone(DEFAULT_NETWORK_PERMISSIONS))
+}
+
+export function createCandidateFixtureDatabase(path: string): void {
+ const database = openBuddyMigrationCandidate({ databasePath: path })
+ try {
+ database.exec('UPDATE storage_profile SET authority = \'sqlite\', migration_state = \'ready\'')
+ }
+ finally { database.close() }
+}
diff --git a/.playwright/scripts/fixtures/task-archive.mjs b/.playwright/scripts/fixtures/task-archive.mjs
index 091a76324..57edf8ea5 100644
--- a/.playwright/scripts/fixtures/task-archive.mjs
+++ b/.playwright/scripts/fixtures/task-archive.mjs
@@ -7,8 +7,8 @@ import { fileURLToPath, pathToFileURL } from 'node:url'
const root = fileURLToPath(new URL('../../../', import.meta.url))
-export async function prepareTaskArchiveProfile(home, output, authority = 'legacy_jsonl', { legacyTasks = 1, legacyFiles = 1 } = {}) {
- assert.equal(authority, 'legacy_jsonl')
+export async function prepareTaskArchiveProfile(home, output, authority, { legacyTasks = 1, legacyFiles = 1 } = {}) {
+ assert.ok(['legacy_jsonl', 'sqlite'].includes(authority), 'Archive fixture requires an explicit storage authority')
assert(Number.isInteger(legacyTasks) && legacyTasks >= 1 && legacyTasks <= 100)
assert(Number.isInteger(legacyFiles) && legacyFiles >= 1 && legacyFiles <= 64)
const legacyTaskIds = Array.from({ length: legacyTasks }, (_, index) => index ? `archive-legacy-${index}` : 'archive-legacy')
@@ -20,32 +20,28 @@ export async function prepareTaskArchiveProfile(home, output, authority = 'legac
target: 'node26',
rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'prepare.mjs', format: 'es' } },
} })
- const { openBuddyDatabase } = await import(pathToFileURL(path.join(output, 'prepare.mjs')).href)
+ const { openBuddyDatabase, openBuddySqliteDatabase } = await import(pathToFileURL(path.join(output, 'prepare.mjs')).href)
const databasePath = path.join(home, 'buddy/buddy.sqlite3')
- const database = openBuddyDatabase({ databasePath })
+ const open = authority === 'legacy_jsonl' ? openBuddyDatabase : openBuddySqliteDatabase
+ const database = open({ databasePath })
try {
- assert.equal(database.prepare('PRAGMA user_version').get().user_version, 42)
- assert.deepEqual(database.prepare('SELECT name FROM sqlite_master WHERE type = \'table\' AND name IN (\'storage_profile\', \'managed_files\') ORDER BY name').all().map(row => row.name), [])
+ assert.equal(database.prepare('PRAGMA user_version').get().user_version, authority === 'legacy_jsonl' ? 42 : 43)
+ assert.deepEqual(database.prepare('SELECT name FROM sqlite_master WHERE type = \'table\' AND name IN (\'storage_profile\', \'managed_files\') ORDER BY name').all().map(row => row.name), authority === 'legacy_jsonl' ? [] : ['managed_files', 'storage_profile'])
+ if (authority === 'sqlite')
+ assert.equal(database.prepare('SELECT authority FROM storage_profile WHERE id = 1').get().authority, 'sqlite')
const now = new Date().toISOString()
- for (const [id, name, revoked] of [['archive-space-design', '设计空间', null], ['archive-space-old', '历史研究空间', now]])
- database.prepare('INSERT INTO spaces (id, name, memory_scope, revoked_at, created_at, updated_at) VALUES (?, ?, ?, ?, ?, ?)').run(id, name, 'space_only', revoked, now, now)
const tasks = [
['archive-active', '可归档的历史任务', null, null],
['archive-existing', '已经归档的历史任务', now, null],
- ['archive-notes', '整理桌面工作台交互细节与后续改进记录,保留完整上下文供下次继续', now, null, 'archive-space-design'],
- ['archive-review', '检查本地数据的保留范围与恢复流程', now, null, 'archive-space-old'],
- ['archive-space-active', '设计空间中的活动任务', null, null, 'archive-space-design'],
- ['archive-failed', '清理失败的历史任务', now, now],
...legacyTaskIds.map((id, index) => [id, `模拟旧版已移除任务 ${index + 1}`, null, now]),
]
- for (const [id, title, archived, deleted, spaceId] of tasks) {
- database.prepare('INSERT INTO conversations (id, title, buddy_id, active_branch_id, created_at, updated_at, archived_at, deleted_at, space_id) VALUES (?, ?, (SELECT default_buddy_id FROM buddy_catalog WHERE id = 1), ?, ?, ?, ?, ?, ?)').run(id, title, `branch-${id}`, now, now, archived, deleted, spaceId ?? null)
+ for (const [id, title, archived, deleted] of tasks) {
+ database.prepare('INSERT INTO conversations (id, title, buddy_id, active_branch_id, created_at, updated_at, archived_at, deleted_at) VALUES (?, ?, (SELECT default_buddy_id FROM buddy_catalog WHERE id = 1), ?, ?, ?, ?, ?)').run(id, title, `branch-${id}`, now, now, archived, deleted)
database.prepare('INSERT INTO conversation_members (conversation_id, actor_id, joined_at) SELECT ?, default_buddy_id, ? FROM buddy_catalog WHERE id = 1').run(id, now)
database.prepare('INSERT INTO task_attention (conversation_id) VALUES (?)').run(id)
database.prepare('INSERT INTO conversation_branches (id, conversation_id, created_at) VALUES (?, ?, ?)').run(`branch-${id}`, id, now)
database.prepare('INSERT INTO messages (id, conversation_id, branch_id, role, content_json, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(`message-${id}`, id, `branch-${id}`, 'user', JSON.stringify({ text: `保留的历史内容 ${id}` }), now)
}
- database.prepare('INSERT INTO conversation_deletion_jobs (conversation_id, status, error_code, created_at, updated_at) VALUES (\'archive-failed\', \'failed\', \'FILE_ACCESS_DENIED\', ?, ?)').run(now, now)
}
finally { database.close() }
const owned = path.join(home, 'buddy/conversations/archive-legacy/workspace')
@@ -56,32 +52,13 @@ export async function prepareTaskArchiveProfile(home, output, authority = 'legac
await Promise.all(Array.from({ length: legacyFiles }, (_, index) => fs.writeFile(path.join(directory, index ? `owned-${index}.txt` : 'owned.txt'), 'Task-owned fixture')))
}
const external = path.join(home, 'external')
- for (const directory of [owned, activeOwned]) {
- await fs.mkdir(directory, { recursive: true })
- await fs.writeFile(path.join(directory, 'owned.txt'), 'Task-owned fixture')
- }
+ await fs.mkdir(activeOwned, { recursive: true })
await fs.mkdir(external, { recursive: true })
+ await fs.writeFile(path.join(activeOwned, 'owned.txt'), 'Task-owned fixture')
await fs.writeFile(path.join(external, 'keep.txt'), 'External fixture must survive')
return { databasePath, owned, activeOwned, external, legacyTaskIds }
}
-export async function readTaskArchiveStorage(app, databasePath) {
- return app.evaluate(({ app }, databasePath) => {
- if (app.getName() !== 'Lexora Buddy Test')
- throw new Error('Archive assertions require an isolated test profile')
- const { DatabaseSync } = process.getBuiltinModule('node:sqlite')
- const database = new DatabaseSync(databasePath, { readOnly: true })
- try {
- const tables = database.prepare('SELECT name FROM sqlite_master WHERE type = \'table\' AND name IN (\'storage_profile\', \'managed_files\') ORDER BY name').all().map(row => row.name)
- return {
- version: database.prepare('PRAGMA user_version').get().user_version,
- tables,
- }
- }
- finally { database.close() }
- }, databasePath)
-}
-
export async function taskExists(app, databasePath, id) {
return app.evaluate(({ app }, { databasePath, id }) => {
if (app.getName() !== 'Lexora Buddy Test')
diff --git a/.playwright/scripts/mobile/__tests__/process-recovery.e2e.mjs b/.playwright/scripts/mobile/__tests__/process-recovery.e2e.mjs
new file mode 100644
index 000000000..b0a46d72d
--- /dev/null
+++ b/.playwright/scripts/mobile/__tests__/process-recovery.e2e.mjs
@@ -0,0 +1,60 @@
+import assert from 'node:assert/strict'
+import { execFile } from 'node:child_process'
+import { randomUUID } from 'node:crypto'
+import { mkdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import process from 'node:process'
+import { setTimeout } from 'node:timers/promises'
+import { promisify } from 'node:util'
+
+const execute = promisify(execFile)
+const args = new Map(process.argv.slice(2).reduce((entries, value, index, values) => value.startsWith('--') ? [...entries, [value.slice(2), values[index + 1]]] : entries, []))
+for (const key of ['serial', 'output']) assert(args.get(key), `Missing --${key}`)
+const output = args.get('output')
+await mkdir(output, { recursive: true })
+const packageName = 'app.uselexora.mobile.dev'
+const token = randomUUID()
+const marker = `files/process-recovery-${token}.json`
+const adb = (...parameters) => execute(args.get('adb') ?? 'adb', ['-s', args.get('serial'), ...parameters], { timeout: 60000, maxBuffer: 4 * 1024 * 1024 })
+const instrument = phase => adb('shell', 'am', 'instrument', '-w', '-r', '-e', 'class', 'app.uselexora.mobile.ProcessRecoveryInstrumentedTest', '-e', 'processRecoveryToken', token, '-e', 'processRecoveryPhase', phase, '-e', 'processRecoveryPairing', String(Boolean(args.get('pairing'))), `${packageName}.test/androidx.test.runner.AndroidJUnitRunner`)
+let preparing
+try {
+ if (args.get('pairing'))
+ await adb('push', args.get('pairing'), `/data/local/tmp/lexora-recovery-${token}.json`)
+ let preparationFinished = false
+ preparing = instrument('prepare').then(result => ({ result }), error => ({ error })).then(async (outcome) => {
+ await writeFile(join(output, 'preparation.txt'), outcome.result?.stdout ?? String(outcome.error))
+ preparationFinished = true
+ return outcome
+ })
+ let checkpoint
+ const deadline = Date.now() + 30000
+ while (Date.now() < deadline) {
+ assert(!preparationFinished, 'Preparation ended before its checkpoint; see preparation.txt')
+ try {
+ checkpoint = JSON.parse((await adb('shell', 'run-as', packageName, 'cat', marker)).stdout)
+ break
+ }
+ catch {}
+ await setTimeout(200)
+ }
+ assert(checkpoint?.pid > 0, 'Preparation did not persist its checkpoint')
+ assert.equal((await adb('shell', 'pidof', packageName)).stdout.trim(), String(checkpoint.pid))
+ await adb('shell', 'am', 'force-stop', packageName)
+ const interrupted = await preparing
+ await writeFile(join(output, 'interrupted.txt'), interrupted.result?.stdout ?? String(interrupted.error))
+ assert.match(interrupted.result?.stdout ?? '', /Process crashed|INSTRUMENTATION_FAILED|shortMsg=Process crashed/, 'Instrumentation was not interrupted by process termination')
+ const recovered = await instrument('verify')
+ await writeFile(join(output, 'recovered.txt'), recovered.stdout)
+ assert.match(recovered.stdout, /OK \(1 test\)/)
+ assert.doesNotMatch(recovered.stdout, /INSTRUMENTATION_STATUS_CODE: -[234]|FAILURES/)
+ const screenshot = await execute(args.get('adb') ?? 'adb', ['-s', args.get('serial'), 'exec-out', 'run-as', packageName, 'cat', `files/process-recovery-${token}.png`], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+ await writeFile(join(output, 'android-recovered.png'), screenshot.stdout)
+ await writeFile(join(output, 'result.json'), JSON.stringify({ passed: true, action: 'am force-stop', terminatedPid: checkpoint.pid, inputPreserved: true, nativeDraftRestored: true, currentInputPreserved: true, executionSettingsPreserved: true, originalCommandReconciled: true, serverPrefixResumed: true, duplicateAdoptionPrevented: true }, null, 2))
+}
+finally {
+ await adb('shell', 'am', 'force-stop', packageName)
+ await preparing
+ await adb('shell', 'rm', '-f', `/data/local/tmp/lexora-recovery-${token}.json`)
+ await adb('shell', 'run-as', packageName, 'rm', '-f', marker, `files/process-recovery-${token}.png`)
+}
diff --git a/.playwright/scripts/mobile/capture-android-performance.mjs b/.playwright/scripts/mobile/capture-android-performance.mjs
new file mode 100644
index 000000000..37f119a38
--- /dev/null
+++ b/.playwright/scripts/mobile/capture-android-performance.mjs
@@ -0,0 +1,118 @@
+import assert from 'node:assert/strict'
+import { execFile } from 'node:child_process'
+import { createHash, randomUUID } from 'node:crypto'
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import process from 'node:process'
+import { promisify } from 'node:util'
+
+const execute = promisify(execFile)
+const args = new Map(process.argv.slice(2).reduce((entries, value, index, values) => value.startsWith('--') ? [...entries, [value.slice(2), values[index + 1]]] : entries, []))
+for (const key of ['serial', 'package', 'activity', 'apk', 'output']) assert(args.get(key), `Missing --${key}`)
+const output = args.get('output')
+const recoveryMarker = `Recovery${randomUUID().replaceAll('-', '')}`
+await mkdir(output, { recursive: true })
+const adb = args.get('adb') ?? 'adb'
+const invoke = async (...parameters) => (await execute(adb, ['-s', args.get('serial'), ...parameters], { maxBuffer: 8 * 1024 * 1024 })).stdout
+const shell = (...parameters) => invoke('shell', ...parameters)
+const start = () => shell('am', 'start', '-W', '-n', `${args.get('package')}/${args.get('activity')}`, ...(args.has('fixture') ? ['--ez', 'fixture', 'true'] : []))
+async function dump() {
+ await shell('uiautomator', 'dump', '/sdcard/lexora-acceptance.xml')
+ const xml = await shell('cat', '/sdcard/lexora-acceptance.xml')
+ assert(xml.includes(`package="${args.get('package')}"`), 'Another application owns the focused UI')
+ return xml
+}
+const bounds = node => [...node.matchAll(/bounds="\[(\d+),(\d+)\]\[(\d+),(\d+)\]"/g)][0]?.slice(1).map(Number)
+const center = value => [Math.round((value[0] + value[2]) / 2), Math.round((value[1] + value[3]) / 2)]
+const device = {
+ emulator: (await shell('getprop', 'ro.kernel.qemu')).trim() === '1',
+ model: (await shell('getprop', 'ro.product.model')).trim(),
+ android: (await shell('getprop', 'ro.build.version.release')).trim(),
+ api: Number((await shell('getprop', 'ro.build.version.sdk')).trim()),
+ abi: (await shell('getprop', 'ro.product.cpu.abi')).trim(),
+ display: (await shell('wm', 'size')).trim(),
+ density: (await shell('wm', 'density')).trim(),
+}
+const budgets = { environment: device.emulator ? 'emulator' : 'physical', coldStartP95Ms: 2500, frameP95Ms: 64, pssKiB: 262144, apkBytes: 40 * 1024 * 1024 }
+await writeFile(join(output, 'device.json'), JSON.stringify(device, null, 2))
+await writeFile(join(output, 'budgets.json'), JSON.stringify({ ...budgets, frozenAt: new Date().toISOString() }, null, 2))
+await invoke('install', '-r', args.get('apk'))
+const times = []
+for (let index = 0; index < 5; index++) {
+ await shell('am', 'force-stop', args.get('package'))
+ const result = await start()
+ await writeFile(join(output, `cold-start-${index + 1}.txt`), result)
+ const value = /TotalTime:\s*(\d+)/.exec(result)
+ assert(value, 'No successful Activity startup measurement')
+ times.push(Number(value[1]))
+ assert((await shell('pidof', args.get('package'))).trim(), 'Application exited during startup')
+ const xml = await dump()
+ assert(xml.includes('Lexora'), 'Application did not render its interface')
+}
+async function openTasks() {
+ let xml = await dump()
+ const search = xml.match(/]+content-desc="搜索任务"[^>]*>/)?.[0]
+ if (search) {
+ await shell('input', 'tap', ...center(bounds(search)).map(String))
+ xml = await dump()
+ }
+ return xml
+}
+async function openFixtureTask() {
+ const xml = await openTasks()
+ const task = xml.match(/]+(?:text|content-desc)="任务 1 ·[^>]*>/)?.[0]
+ assert(task, 'First fixture task unavailable')
+ await shell('input', 'tap', ...center(bounds(task)).map(String))
+ return dump()
+}
+await writeFile(join(output, 'initial.xml'), await openTasks())
+await shell('dumpsys', 'gfxinfo', args.get('package'), 'reset')
+const taskList = (await dump()).match(/]+scrollable="true"[^>]*>/)?.[0]
+assert(taskList, 'Task list unavailable')
+const [left, top, right, bottom] = bounds(taskList)
+const x = Math.round((left + right) / 2)
+const upper = Math.round(top + (bottom - top) * 0.2)
+const lower = Math.round(top + (bottom - top) * 0.8)
+for (let index = 0; index < 10; index++) await shell('input', 'swipe', String(x), String(index % 2 ? upper : lower), String(x), String(index % 2 ? lower : upper), '350')
+const frames = await shell('dumpsys', 'gfxinfo', args.get('package'), 'framestats')
+const memory = await shell('dumpsys', 'meminfo', args.get('package'))
+const flutterTimings = args.get('renderer') === 'flutter' ? await shell('cat', `/sdcard/Android/data/${args.get('package')}/files/frame-times.json`) : null
+await writeFile(join(output, 'frames.txt'), frames)
+await writeFile(join(output, 'memory.txt'), memory)
+const editing = await openFixtureTask()
+const input = editing.match(/]+class="android.widget.EditText"[^>]*>/)?.[0]
+assert(input, 'Native text input unavailable')
+await shell('input', 'tap', ...center(bounds(input)).map(String))
+await shell('input', 'keyevent', 'KEYCODE_MOVE_END')
+await shell('input', 'text', recoveryMarker)
+const keyboard = await shell('dumpsys', 'input_method')
+if (/mInputShown=true|mIsInputViewShown=true/.test(keyboard))
+ await shell('input', 'keyevent', 'KEYCODE_BACK')
+assert((await dump()).includes(recoveryMarker), 'Typed input missing')
+await shell('am', 'force-stop', args.get('package'))
+await start()
+let recovered = await dump()
+if (!recovered.includes(recoveryMarker))
+ recovered = await openFixtureTask()
+assert(recovered.includes(recoveryMarker), 'Process death lost the locally saved draft')
+await writeFile(join(output, 'recovered.xml'), recovered)
+const screenshot = await execute(adb, ['-s', args.get('serial'), 'exec-out', 'screencap', '-p'], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+await writeFile(join(output, '01-input-recovered.png'), screenshot.stdout)
+const apk = await readFile(args.get('apk'))
+const p95 = times.toSorted((a, b) => a - b).at(-1)
+let frameP95 = Number(/95th percentile:\s*(\d+)ms/.exec(frames)?.[1] ?? NaN)
+let frameMetric = 'Android HWUI'
+if (args.get('renderer') === 'flutter') {
+ const timings = flutterTimings
+ await writeFile(join(output, 'flutter-frame-times.json'), timings)
+ const values = JSON.parse(timings).map(value => value / 1000).sort((a, b) => a - b)
+ assert(values.length >= 30, 'Insufficient Flutter FrameTiming samples')
+ frameP95 = values[Math.ceil(values.length * 0.95) - 1]
+ frameMetric = 'Flutter FrameTiming totalSpan (separate renderer instrumentation)'
+}
+const pss = Number(/^\s*TOTAL(?: PSS)?:\s*(\d+)/m.exec(memory)?.[1] ?? NaN)
+const result = { package: args.get('package'), apkSha256: createHash('sha256').update(apk).digest('hex'), apkBytes: apk.length, coldStartMs: times, coldStartP95Ms: p95, frameP95Ms: frameP95, frameMetric, pssKiB: pss, recovery: 'passed', emulatorOnly: device.emulator, device, scope: 'Five cold starts, 1000-task list scrolling, main-process memory snapshot and draft recovery; excludes WebView process memory, sustained streaming, peak memory and energy', budgets, pass: p95 <= budgets.coldStartP95Ms && frameP95 <= budgets.frameP95Ms && pss <= budgets.pssKiB && apk.length <= budgets.apkBytes }
+await writeFile(join(output, 'measurements.json'), JSON.stringify(result, null, 2))
+await shell('rm', '-f', '/sdcard/lexora-acceptance.xml')
+process.stdout.write(`${JSON.stringify(result)}\n`)
+assert(result.pass, 'Android baseline performance budget exceeded')
diff --git a/.playwright/scripts/mobile/capture-android-streaming.mjs b/.playwright/scripts/mobile/capture-android-streaming.mjs
new file mode 100644
index 000000000..ebf52ded5
--- /dev/null
+++ b/.playwright/scripts/mobile/capture-android-streaming.mjs
@@ -0,0 +1,88 @@
+import assert from 'node:assert/strict'
+import { execFile } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import path from 'node:path'
+import process from 'node:process'
+import { setTimeout as delay } from 'node:timers/promises'
+import { promisify } from 'node:util'
+
+const execute = promisify(execFile)
+const args = new Map(process.argv.slice(2).reduce((entries, value, index, values) => value.startsWith('--') ? [...entries, [value.slice(2), values[index + 1]]] : entries, []))
+for (const key of ['serial', 'package', 'apk', 'output']) assert(args.get(key), `Missing --${key}`)
+const appPackage = args.get('package')
+assert(appPackage.endsWith('.benchmark'), 'Streaming measurement requires the isolated benchmark application')
+const seconds = Number(args.get('seconds') ?? 60)
+assert(Number.isInteger(seconds) && seconds >= 10 && seconds <= 180)
+const output = args.get('output')
+await mkdir(output, { recursive: true })
+const adb = (...parameters) => execute(args.get('adb') ?? 'adb', ['-s', args.get('serial'), ...parameters], { maxBuffer: 8 * 1024 * 1024, timeout: 20000 })
+const shell = async (...parameters) => (await adb('shell', ...parameters)).stdout
+const apkSha256 = createHash('sha256').update(await readFile(args.get('apk'))).digest('hex')
+const installed = (await shell('pm', 'path', appPackage)).trim().replace(/^package:/, '')
+assert((await shell('sha256sum', installed)).startsWith(apkSha256), 'Installed APK does not match the supplied artifact')
+const budgets = { rafFrameP95Ms: 64, totalPssKiB: 262144, minimumFrameSamples: 100 }
+await writeFile(path.join(output, 'budgets.json'), JSON.stringify({ ...budgets, frozenAt: new Date().toISOString() }, null, 2))
+const remoteResult = `/sdcard/Android/data/${appPackage}/files/reader-benchmark.json`
+await shell('am', 'force-stop', appPackage)
+await shell('rm', '-f', remoteResult)
+const start = await shell('am', 'start', '-W', '-n', `${appPackage}/app.uselexora.mobile.ui.MainActivity`, '--ez', 'fixture', 'true', '--ei', 'readerBenchmarkSeconds', String(seconds))
+await writeFile(path.join(output, 'start.txt'), start)
+const samples = []
+let metrics
+let completedAt
+const started = Date.now()
+while (Date.now() - started < (seconds * 2 + 40) * 1000) {
+ const main = (await shell('pidof', appPackage)).trim().split(/\s+/).filter(Boolean)
+ assert(main.length, 'Benchmark application exited')
+ const services = await shell('dumpsys', 'activity', 'services')
+ const processes = new Map(main.map(pid => [pid, appPackage]))
+ for (const block of services.split(/(?= {2}\* ServiceRecord\{)/)) {
+ if (!block.includes('SandboxedProcessService') || !block.includes(appPackage))
+ continue
+ const linked = /app=ProcessRecord\{[^ ]+ (\d+):([^/}]+)/.exec(block)
+ if (linked)
+ processes.set(linked[1], linked[2])
+ }
+ const memory = []
+ for (const [pid, name] of processes) {
+ const value = await shell('dumpsys', 'meminfo', pid)
+ const pssKiB = Number(/^\s*TOTAL(?: PSS)?:\s*(\d+)/m.exec(value)?.[1])
+ assert(Number.isFinite(pssKiB), `Missing process memory: ${name}`)
+ memory.push({ pid, name, pssKiB })
+ }
+ const battery = await shell('dumpsys', 'battery')
+ samples.push({ elapsedMs: Date.now() - started, processes: memory, totalPssKiB: memory.reduce((sum, item) => sum + item.pssKiB, 0), battery })
+ metrics ??= await shell('cat', remoteResult).then(value => JSON.parse(value), () => null)
+ if (metrics) {
+ completedAt ??= Date.now()
+ if (Date.now() - completedAt >= 10000)
+ break
+ }
+ await delay(2000)
+}
+const peakPssKiB = Math.max(...samples.map(sample => sample.totalPssKiB))
+const device = {
+ model: (await shell('getprop', 'ro.product.model')).trim(),
+ api: Number((await shell('getprop', 'ro.build.version.sdk')).trim()),
+ emulator: (await shell('getprop', 'ro.kernel.qemu')).trim() === '1',
+}
+const result = {
+ device,
+ package: appPackage,
+ apkSha256,
+ metrics,
+ peakPssKiB,
+ settledPssKiB: samples.at(-1)?.totalPssKiB,
+ budgets,
+ samples,
+ energy: { measured: false, reason: 'USB power and charge state are recorded; these are not a battery-discharge energy measurement' },
+ scope: 'Foreground 500-message history and sustained output; total PSS includes WebView processes explicitly bound to this application',
+ passed: Boolean(metrics?.completed && metrics.frameSamples >= budgets.minimumFrameSamples && metrics.rafFrameP95Ms <= budgets.rafFrameP95Ms && peakPssKiB <= budgets.totalPssKiB && samples.some(sample => sample.processes.length > 1)),
+}
+await writeFile(path.join(output, 'measurements.json'), JSON.stringify(result, null, 2))
+const image = await execute(args.get('adb') ?? 'adb', ['-s', args.get('serial'), 'exec-out', 'screencap', '-p'], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
+assert(image.stdout.length > 0, 'No visible device screenshot')
+await writeFile(path.join(output, 'stream-completed.png'), image.stdout)
+process.stdout.write(`${JSON.stringify({ ...result, samples: result.samples.length })}\n`)
+assert(result.passed, 'Streaming or complete process memory budget exceeded')
diff --git a/.playwright/scripts/private-network-fixture.mjs b/.playwright/scripts/private-network-fixture.mjs
new file mode 100644
index 000000000..2ad55776d
--- /dev/null
+++ b/.playwright/scripts/private-network-fixture.mjs
@@ -0,0 +1,135 @@
+import { Buffer } from 'node:buffer'
+import { fork } from 'node:child_process'
+import { once } from 'node:events'
+import * as fs from 'node:fs/promises'
+import { createServer } from 'node:http'
+import { createRequire, isBuiltin } from 'node:module'
+import os from 'node:os'
+import path from 'node:path'
+import process from 'node:process'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+export async function main() {
+ const root = fileURLToPath(new URL('../../', import.meta.url))
+ const buddy = path.join(root, 'apps/buddy')
+ const requireBuddy = createRequire(path.join(buddy, 'package.json'))
+ const keep = Boolean(process.env.LEXORA_FIXTURE_DIRECTORY)
+ const directory = keep ? path.resolve(process.env.LEXORA_FIXTURE_DIRECTORY) : await fs.mkdtemp(path.join(os.tmpdir(), 'lexora-native-network-'))
+ await fs.mkdir(directory, { recursive: true, mode: 0o700 })
+ const profile = path.join(directory, 'profile')
+ const qrPath = path.join(directory, 'pairing.json')
+ const endpointPath = path.join(directory, 'connection.json')
+ const port = Number(process.env.LEXORA_FIXTURE_PORT ?? 19443)
+ const candidate = process.env.LEXORA_FIXTURE_SERVICE ? path.resolve(process.env.LEXORA_FIXTURE_SERVICE) : path.join(buddy, '.output/build/service')
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')).href)
+ await build({ configFile: false, logLevel: 'error', build: { ssr: path.join(root, '.playwright/scripts/fixtures/service-process-harness.ts'), outDir: path.join(directory, 'harness'), target: 'node26', rolldownOptions: { external: isBuiltin, output: { entryFileNames: 'harness.mjs', format: 'es' } } } })
+ const { RuntimeRpcPeer, createBuddyServiceEnvironment, BUDDY_SERVICE_PROTOCOL_VERSION, DEFAULT_RUNTIME_PREFERENCES, registerFixtureHost, createCandidateFixtureDatabase } = await import(pathToFileURL(path.join(directory, 'harness/harness.mjs')).href)
+ await fs.mkdir(profile, { recursive: true, mode: 0o700 })
+ createCandidateFixtureDatabase(path.join(profile, 'buddy.sqlite3'))
+ const provider = createServer((request, response) => {
+ void (async () => {
+ let size = 0
+ const chunks = []
+ for await (const chunk of request) {
+ size += chunk.byteLength
+ chunks.push(chunk)
+ if (size > 1_048_576)
+ throw new Error('Fixture request exceeds limit')
+ }
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8'))
+ const approval = JSON.stringify(body.messages).includes('Android approval verification') && !body.messages.some(message => message.role === 'tool')
+ response.writeHead(200, { 'Content-Type': 'text/event-stream' })
+ response.write(`data: ${JSON.stringify({ id: 'native-fixture', model: 'fixture-model', object: 'chat.completion.chunk', created: 1, choices: [{ index: 0, delta: approval ? { role: 'assistant', tool_calls: [{ index: 0, id: 'mobile-approval-call', type: 'function', function: { name: 'write', arguments: JSON.stringify({ path: 'mobile-approval.txt', content: JSON.stringify(body.messages).includes('large approval document') ? '中😀'.repeat(30000) : 'Isolated Android approval fixture' }) } }] } : { role: 'assistant', content: '隔离服务已收到输入。你好,Android。😀' }, finish_reason: null }] })}\n\n`)
+ response.write(`data: ${JSON.stringify({ id: 'native-fixture', model: 'fixture-model', object: 'chat.completion.chunk', created: 1, choices: [{ index: 0, delta: {}, finish_reason: approval ? 'tool_calls' : 'stop' }] })}\n\n`)
+ response.end('data: [DONE]\n\n')
+ })().catch(() => response.destroy())
+ })
+ provider.listen(0, '127.0.0.1')
+ await once(provider, 'listening')
+ const child = fork(path.join(candidate, 'service.mjs'), [], { execArgv: [], cwd: directory, env: createBuddyServiceEnvironment({ PATH: process.env.PATH, HOME: directory, TMPDIR: directory, TEMP: directory, SystemRoot: process.env.SystemRoot, COMSPEC: process.env.COMSPEC }, profile), stdio: ['ignore', 'ignore', 'pipe', 'ipc'] })
+ const peers = new Map()
+ function channel(id) {
+ const peer = new RuntimeRpcPeer({ transport: { postMessage: message => child.send({ type: 'rpc', channel: id, message }), subscribe(listener) {
+ const receive = (message) => {
+ if (message.type === 'rpc' && message.channel === id)
+ listener(message.message)
+ }
+ child.on('message', receive)
+ return () => child.off('message', receive)
+ } } })
+ peers.set(id, peer)
+ return peer
+ }
+ const secretsPath = path.join(directory, 'synthetic-secrets.json')
+ let secrets
+ try {
+ secrets = new Map(JSON.parse(await fs.readFile(secretsPath, 'utf8')))
+ }
+ catch (error) {
+ if (error.code !== 'ENOENT')
+ throw error
+ secrets = new Map()
+ }
+ registerFixtureHost(channel('host'), { secrets, persistSecrets: async () => {
+ const temporary = `${secretsPath}.part`
+ await fs.writeFile(temporary, JSON.stringify([...secrets]), { mode: 0o600, flush: true })
+ await fs.rename(temporary, secretsPath)
+ } })
+ let stopped = false
+ async function stop() {
+ if (stopped)
+ return
+ stopped = true
+ const exited = child.exitCode === null && child.signalCode === null ? once(child, 'exit') : Promise.resolve()
+ child.kill('SIGTERM')
+ await exited
+ for (const peer of peers.values()) peer.close(new Error('Fixture stopped'))
+ provider.closeAllConnections()
+ provider.close()
+ if (!keep)
+ await fs.rm(directory, { recursive: true, force: true })
+ }
+ process.once('SIGINT', () => void stop())
+ process.once('SIGTERM', () => void stop())
+ child.once('exit', () => void stop())
+ child.stderr.on('data', value => process.stderr.write(value))
+ const ready = new Promise((resolve, reject) => {
+ child.on('message', (message) => {
+ if (message.type === 'ready')
+ resolve()
+ if (message.type === 'failed')
+ reject(new Error(message.code))
+ })
+ child.once('exit', () => reject(new Error('Fixture service exited before ready')))
+ })
+ child.send({ type: 'start', protocolVersion: BUDDY_SERVICE_PROTOCOL_VERSION, config: { profile: 'test', buddyHome: profile, resourcesRoot: path.join(candidate, 'resources'), storageAuthority: 'sqlite', proxy: { httpProxy: '', httpsProxy: '', noProxy: '' }, preferences: { ...DEFAULT_RUNTIME_PREFERENCES, cacheWarming: 'off', codemode: 'off', modelRetryLimit: 0 }, display: false } })
+ await ready
+ const management = channel('management')
+ child.send({ type: 'connect', channel: 'management', role: 'management' })
+ await management.request('providers.upsertCustom', { id: 'process-fixture', displayName: 'Isolated Android fixture', api: 'openai-completions', baseUrl: `http://127.0.0.1:${provider.address().port}/v1`, enabled: true, models: [{ id: 'fixture-model', name: 'Fixture', input: ['text'], reasoning: false, contextWindow: 128000, maxTokens: 1024 }] })
+ const product = channel('product')
+ child.send({ type: 'connect', channel: 'product', role: 'product' })
+ const spaces = await product.request('spaces.list', {})
+ if (!spaces.some(space => space.name === 'Android verification'))
+ await management.request('spaces.create', { name: 'Android verification', memoryScope: 'space_only', primaryDirectory: null, primaryDirectorySelectionVerified: false })
+ let status = await management.request('privateNetwork.configure', { enabled: true, bindAddress: '127.0.0.1', port })
+ if (process.env.LEXORA_FIXTURE_RESET_TLS === '1')
+ status = await management.request('privateNetwork.resetIdentity', {})
+ if (status.state !== 'listening')
+ throw new Error(`Fixture listener failed: ${status.errorCode}`)
+ await fs.writeFile(endpointPath, JSON.stringify(status), { mode: 0o600 })
+ async function issue() {
+ const qr = await management.request('privateNetwork.issuePairing', {})
+ await fs.writeFile(qrPath, JSON.stringify(qr), { mode: 0o600 })
+ process.stdout.write(`${JSON.stringify({ endpoint: status.endpoint, qrPath, endpointPath, fixture: directory })}\n`)
+ }
+ await issue()
+ process.on('SIGUSR1', () => void issue())
+}
+
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
+ main().catch((error) => {
+ process.stderr.write(`${error instanceof Error ? error.message : 'FIXTURE_FAILED'}\n`)
+ process.exitCode = 1
+ })
+}
diff --git a/.playwright/scripts/storage-durability.mjs b/.playwright/scripts/storage-durability.mjs
new file mode 100644
index 000000000..08a9c87ed
--- /dev/null
+++ b/.playwright/scripts/storage-durability.mjs
@@ -0,0 +1,47 @@
+import assert from 'node:assert/strict'
+import { createHash } from 'node:crypto'
+import fs from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import path from 'node:path'
+import process from 'node:process'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+
+const workspace = fileURLToPath(new URL('../../', import.meta.url))
+const buddy = path.join(workspace, 'apps/buddy')
+const requireBuddy = createRequire(path.join(buddy, 'package.json'))
+const mode = process.argv[2] ?? 'cost'
+assert(process.argv.length <= 3 && ['cost', 'crash', 'capacity'].includes(mode), 'Usage: node .playwright/scripts/storage-durability.mjs [cost|crash|capacity]')
+const root = path.join(workspace, '.playwright/runs', `storage-durability-${new Date().toISOString().replaceAll(/[:.]/g, '-')}`)
+await fs.mkdir(root, { recursive: true })
+await fs.symlink(path.join(buddy, 'node_modules'), path.join(root, 'node_modules'), 'junction')
+try {
+ const { build } = await import(pathToFileURL(requireBuddy.resolve('vite')))
+ await build({
+ configFile: false,
+ logLevel: 'error',
+ build: {
+ ssr: fileURLToPath(new URL(`./__tests__/${mode === 'crash' ? 'storageCrash' : mode === 'capacity' ? 'commandCapacity' : 'storageDurability'}.ts`, import.meta.url)),
+ outDir: root,
+ emptyOutDir: false,
+ target: 'node26',
+ minify: false,
+ rollupOptions: {
+ external: id => !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0'),
+ output: { entryFileNames: 'storage.mjs' },
+ },
+ },
+ })
+ const bundle = path.join(root, 'storage.mjs')
+ const bundleSha256 = createHash('sha256').update(await fs.readFile(bundle)).digest('hex')
+ const api = await import(pathToFileURL(bundle))
+ if (mode === 'crash')
+ await api.runStorageCrashes(root, bundle, bundleSha256)
+ else if (mode === 'capacity')
+ await api.runCommandCapacity(root, bundleSha256)
+ else
+ await api.runStorageDurability(root, bundleSha256)
+}
+finally {
+ await fs.unlink(path.join(root, 'node_modules'))
+ process.stdout.write(`Storage durability artifacts: ${root}\n`)
+}
diff --git a/apps/buddy/electron-builder.config.cjs b/apps/buddy/electron-builder.config.cjs
index c13116718..84f3b9227 100644
--- a/apps/buddy/electron-builder.config.cjs
+++ b/apps/buddy/electron-builder.config.cjs
@@ -10,7 +10,11 @@ const { resolveInferenceEnvironment } = require('./shared/extensions/inferencePl
const { OPERATING_SYSTEM } = require('./shared/platform/identifiers.ts')
const target = resolveBuildTarget()
-const resources = platformResources(target)
+const resources = [
+ ...platformResources(target),
+ { from: '.output/build/service', to: 'lexora-service' },
+ { from: `.output/resources/node-runtime/${target.id}`, to: 'lexora-runtime' },
+]
const packageFormat = process.env.LEXORA_BUDDY_PACKAGE_FORMAT ?? target.packageFormats[0]
const { version, sourceDateEpoch } = require('./buddy.version.json')
const { desktopName, productName: displayName } = require('./package.json')
@@ -29,6 +33,11 @@ const signedMacos = macosSigningMode() === 'developer-id'
module.exports = withDesktopNativeVersion({
appId: desktopName,
+ afterPack: async context => (await import('../../packaging/buddy/release/product-release-set.mjs')).writePackagedReleaseSet(context),
+ afterSign: async (context) => {
+ if (target.platform === OPERATING_SYSTEM.Windows)
+ await (await import('../../packaging/buddy/release/product-release-set.mjs')).writePackagedReleaseSet(context)
+ },
extraMetadata: {
desktopDistribution: { schemaVersion: 1, format: packageFormat === 'macos-zip' ? 'dmg' : packageFormat, architecture: target.architecture, signing: target.platform === OPERATING_SYSTEM.MacOS ? (signedMacos ? 'developer-id' : 'ad-hoc') : 'none' },
},
@@ -58,6 +67,7 @@ module.exports = withDesktopNativeVersion({
...excludedDependencyFiles(target),
],
mac: {
+ sign: async (options, packager) => (await import('../../packaging/buddy/release/product-release-set.mjs')).signMacosReleaseSet(options, packager),
extraResources: (target.platform === OPERATING_SYSTEM.MacOS ? resources : []),
target: [{ target: 'dmg', arch: ['arm64'] }, { target: 'zip', arch: ['arm64'] }],
artifactName: target.platform === OPERATING_SYSTEM.MacOS ? desktopArtifactName(target, 'dmg', macro('version')).replace(/\.dmg$/, `.${macro('ext')}`) : undefined,
@@ -73,7 +83,7 @@ module.exports = withDesktopNativeVersion({
binaries: (target.platform === OPERATING_SYSTEM.MacOS ? resources : [])
.filter(resource => resource.to.startsWith('native-'))
.map(resource => `Contents/Resources/${resource.to}`)
- .concat(['Contents/Resources/search-tools/fd', 'Contents/Resources/search-tools/rg']),
+ .concat(['Contents/Resources/search-tools/fd', 'Contents/Resources/search-tools/rg', 'Contents/Resources/lexora-runtime/node']),
},
dmg: {
sign: signedMacos,
diff --git a/apps/buddy/electron.vite.config.ts b/apps/buddy/electron.vite.config.ts
index 46829b1dc..ba8e67630 100644
--- a/apps/buddy/electron.vite.config.ts
+++ b/apps/buddy/electron.vite.config.ts
@@ -39,11 +39,11 @@ export default defineConfig({
externalizeDeps: { exclude: ['typescript'] },
outDir: join(electronOutputRoot, 'main'),
rollupOptions: {
- external: ['electron', '@silvia-odwyer/photon-node', 'fflate/node', /^@earendil-works\/pi-/],
+ external: ['electron', 'original-fs', '@silvia-odwyer/photon-node', 'fflate/node', /^@earendil-works\/pi-/],
input: {
'index': fileURLToPath(new URL('./electron/main/index.ts', import.meta.url)),
'storage-worker': fileURLToPath(new URL('./service/src/storage/storageWorker.ts', import.meta.url)),
- 'buddy-service': fileURLToPath(new URL('./service/src/index.ts', import.meta.url)),
+ 'buddy-service': fileURLToPath(new URL('./electron/main/runtime/serviceProcess.ts', import.meta.url)),
'extension-package-worker': fileURLToPath(new URL('./electron/main/extensions/packageWorker.ts', import.meta.url)),
},
output: {
diff --git a/apps/buddy/electron/dev.mjs b/apps/buddy/electron/dev.mjs
new file mode 100644
index 000000000..e491c02f9
--- /dev/null
+++ b/apps/buddy/electron/dev.mjs
@@ -0,0 +1,38 @@
+import { spawn } from 'node:child_process'
+import { dirname, join } from 'node:path'
+import process from 'node:process'
+import { fileURLToPath } from 'node:url'
+import { BUDDY_DEVELOPMENT_RESTART_EXIT_CODE } from '../shared/runtime/profile.ts'
+
+const cli = join(dirname(fileURLToPath(import.meta.resolve('electron-vite/package.json'))), 'bin/electron-vite.js')
+let child
+let stopping = false
+for (const signal of ['SIGINT', 'SIGTERM', ...(process.platform === 'win32' ? [] : ['SIGHUP'])]) {
+ process.on(signal, () => {
+ stopping = true
+ child?.kill(signal)
+ })
+}
+async function run() {
+ let restart = true
+ while (restart) {
+ if (stopping)
+ return
+ child = spawn(process.execPath, [cli, 'dev', ...process.argv.slice(2)], {
+ stdio: 'inherit',
+ env: { ...process.env, LEXORA_BUDDY_DEV_LAUNCHER: '1' },
+ })
+ const code = await new Promise((resolve, reject) => {
+ child.once('error', reject)
+ child.once('close', (code, signal) => resolve(code ?? (signal ? 1 : 0)))
+ })
+ child = undefined
+ restart = !stopping && code === BUDDY_DEVELOPMENT_RESTART_EXIT_CODE
+ if (!restart)
+ process.exitCode = code
+ }
+}
+void run().catch((error) => {
+ console.error(error)
+ process.exitCode = 1
+})
diff --git a/apps/buddy/electron/main/DesktopWindowManager.ts b/apps/buddy/electron/main/DesktopWindowManager.ts
index 651b129cd..78844f538 100644
--- a/apps/buddy/electron/main/DesktopWindowManager.ts
+++ b/apps/buddy/electron/main/DesktopWindowManager.ts
@@ -3,6 +3,7 @@ import type { DesktopWindowHandle } from './window'
export interface DesktopWindowManagerOptions {
createWindow: () => DesktopWindowHandle
+ onBeforeDestroy?: (window: BrowserWindow) => void
onRecoveryExhausted?: () => void
onRecoveryRebuilding?: () => void
onRecoveryStarted?: () => void
@@ -15,6 +16,7 @@ interface ManagedDesktopWindow {
}
export class DesktopWindowManager {
+ readonly #onBeforeDestroy?: (window: BrowserWindow) => void
readonly #createWindow: () => DesktopWindowHandle
readonly #onRecoveryExhausted?: () => void
readonly #onRecoveryRebuilding?: () => void
@@ -26,6 +28,7 @@ export class DesktopWindowManager {
#disposed = false
constructor(options: DesktopWindowManagerOptions) {
+ this.#onBeforeDestroy = options.onBeforeDestroy
this.#createWindow = options.createWindow
this.#onRecoveryExhausted = options.onRecoveryExhausted
this.#onRecoveryRebuilding = options.onRecoveryRebuilding
@@ -61,7 +64,7 @@ export class DesktopWindowManager {
if (this.#managedWindow === managedWindow) {
this.#managedWindow = null
if (!managedWindow.handle.window.isDestroyed())
- managedWindow.handle.window.destroy()
+ this.#destroy(managedWindow.handle.window)
}
throw error
})
@@ -96,14 +99,19 @@ export class DesktopWindowManager {
const managedWindow = this.#managedWindow
this.#managedWindow = null
if (managedWindow && !managedWindow.handle.window.isDestroyed())
- managedWindow.handle.window.destroy()
+ this.#destroy(managedWindow.handle.window)
+ }
+
+ #destroy(window: BrowserWindow): void {
+ this.#onBeforeDestroy?.(window)
+ window.destroy()
}
#replaceWindow(): ManagedDesktopWindow {
const previousWindow = this.#managedWindow
this.#managedWindow = null
if (previousWindow && !previousWindow.handle.window.isDestroyed())
- previousWindow.handle.window.destroy()
+ this.#destroy(previousWindow.handle.window)
const handle = this.#createWindow()
const managedWindow: ManagedDesktopWindow = {
@@ -188,7 +196,7 @@ export class DesktopWindowManager {
const managedWindow = this.#managedWindow
this.#managedWindow = null
if (managedWindow && !managedWindow.handle.window.isDestroyed())
- managedWindow.handle.window.destroy()
+ this.#destroy(managedWindow.handle.window)
this.#onRecoveryExhausted?.()
}
}
diff --git a/apps/buddy/electron/main/__tests__/conversationIpc.spec.ts b/apps/buddy/electron/main/__tests__/conversationIpc.spec.ts
new file mode 100644
index 000000000..07d481f3e
--- /dev/null
+++ b/apps/buddy/electron/main/__tests__/conversationIpc.spec.ts
@@ -0,0 +1,123 @@
+import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
+import { describe, expect, it, vi } from 'vitest'
+import { conversationsRpc } from '../../../shared/conversation/conversationApi'
+import { conversationArchiveRpc } from '../../../shared/conversation/conversationArchiveApi'
+import { createConversationApi } from '../../preload/local-chat/conversation'
+import { LOCAL_CHAT_IPC_CHANNELS } from '../../shared/localChatApi'
+import { registerConversationIpc } from '../local-chat/conversation'
+import { createLocalChatIpcContext } from '../local-chat/registrar'
+
+const electron = vi.hoisted(() => {
+ const handlers = new Map Promise>()
+ const webContents = { mainFrame: {} }
+ return {
+ handlers,
+ webContents,
+ invoke: async (channel: string, input: unknown) => {
+ const handler = handlers.get(channel)
+ if (!handler)
+ throw new Error('IPC handler is missing')
+ return handler({ sender: webContents, senderFrame: webContents.mainFrame } as unknown as IpcMainInvokeEvent, input)
+ },
+ }
+})
+
+vi.mock('electron', () => ({
+ ipcMain: {
+ handle: (channel: string, handler: (event: IpcMainInvokeEvent, input: unknown) => Promise) => electron.handlers.set(channel, handler),
+ removeHandler: (channel: string) => electron.handlers.delete(channel),
+ },
+ ipcRenderer: { invoke: electron.invoke },
+}))
+
+describe('conversation archive IPC contract', () => {
+ it.each([
+ ['archive', LOCAL_CHAT_IPC_CHANNELS.conversationsArchive],
+ ['restoreArchive', LOCAL_CHAT_IPC_CHANNELS.conversationsRestoreArchive],
+ ['deleteArchived', LOCAL_CHAT_IPC_CHANNELS.conversationsDeleteArchived],
+ ] as const)('preserves the fixed revision and refuses missing CAS for %s', async (method, channel) => {
+ const received: unknown[] = []
+ const context = createLocalChatIpcContext({
+ getLanguage: () => 'zh-CN',
+ getWindow: () => ({ webContents: electron.webContents } as unknown as BrowserWindow),
+ openModelSnapshotDirectory: async () => {},
+ readWebCredential: async () => null,
+ runtime: {
+ state: {},
+ onNotification: () => () => {},
+ onStateChange: () => () => {},
+ restart: async () => {},
+ request: async (name, input) => {
+ expect(name).toBe(conversationArchiveRpc[method].method)
+ received.push(conversationArchiveRpc[method].input.parse(input))
+ return true
+ },
+ },
+ })
+ registerConversationIpc(context)
+ const api = createConversationApi()
+ try {
+ await expect(api.conversations[method]('task-1', 0)).resolves.toBe(true)
+ await expect(api.conversations[method]('task-1', 7)).resolves.toBe(true)
+ for (const expectedRevision of [undefined, -1, 1.5, '7', Number.MAX_SAFE_INTEGER + 1]) {
+ await expect(electron.invoke(channel, { conversationId: 'task-1', expectedRevision })).rejects.toThrow('VALIDATION_FAILED')
+ }
+ expect(received).toEqual([
+ { conversationId: 'task-1', expectedRevision: 0 },
+ { conversationId: 'task-1', expectedRevision: 7 },
+ ])
+ }
+ finally { context.dispose() }
+ })
+})
+
+describe('conversation deletion IPC contract', () => {
+ it('preserves the preload revision condition through strict main validation', async () => {
+ const received: unknown[] = []
+ const context = createLocalChatIpcContext({
+ getLanguage: () => 'zh-CN',
+ getWindow: () => ({ webContents: electron.webContents } as unknown as BrowserWindow),
+ openModelSnapshotDirectory: async () => {},
+ readWebCredential: async () => null,
+ runtime: {
+ state: {},
+ onNotification: () => () => {},
+ onStateChange: () => () => {},
+ restart: async () => {},
+ request: async (method, input) => {
+ expect(method).toBe(conversationsRpc.delete.method)
+ received.push(conversationsRpc.delete.input.parse(input))
+ return true
+ },
+ },
+ })
+ registerConversationIpc(context)
+ const api = createConversationApi()
+ try {
+ await expect(api.conversations.delete('task-1', 0)).resolves.toBe(true)
+ await expect(api.conversations.delete('task-1', 7)).resolves.toBe(true)
+ await expect(api.conversations.delete('task-1')).resolves.toBe(true)
+ expect(received).toEqual([
+ { conversationId: 'task-1', expectedRevision: 0 },
+ { conversationId: 'task-1', expectedRevision: 7 },
+ { conversationId: 'task-1' },
+ ])
+
+ for (const revision of [-1, 1.5, '7']) {
+ await expect(electron.invoke(LOCAL_CHAT_IPC_CHANNELS.conversationsDelete, {
+ conversationId: 'task-1',
+ expectedRevision: revision,
+ })).rejects.toThrow('VALIDATION_FAILED')
+ }
+ await expect(electron.invoke(LOCAL_CHAT_IPC_CHANNELS.conversationsDelete, {
+ conversationId: 'task-1',
+ expectedRevision: 7,
+ unexpected: true,
+ })).rejects.toThrow('VALIDATION_FAILED')
+ expect(received).toHaveLength(3)
+ }
+ finally {
+ context.dispose()
+ }
+ })
+})
diff --git a/apps/buddy/electron/main/app/DesktopApplication.ts b/apps/buddy/electron/main/app/DesktopApplication.ts
index 39f1d175a..11adc57be 100644
--- a/apps/buddy/electron/main/app/DesktopApplication.ts
+++ b/apps/buddy/electron/main/app/DesktopApplication.ts
@@ -1,7 +1,10 @@
-import type { Event } from 'electron'
+import type { BrowserWindow, Event } from 'electron'
+import type { z } from 'zod'
+import type { desktopOpenIntentSchema } from '../../../shared/service/localServiceProtocol'
import type { DesktopEnvironment } from './typing'
import process from 'node:process'
-import { app, nativeTheme } from 'electron'
+import { app, nativeTheme, powerMonitor } from 'electron'
+import { z as schema } from 'zod'
import { currentPlatform } from '../../../platform/currentPlatform'
import { localTransports } from '../../../platform/ipc/localTransport'
import { DEFAULT_BROWSER_PREFERENCES } from '../../../shared/browser/browserPreferences'
@@ -11,6 +14,8 @@ import { ServiceLifecycleSource } from '../../../shared/lifecycle/ServiceLifecyc
import { observeLifecycleDiagnostics } from '../../../shared/observability/lifecycleDiagnostics'
import { runsRpc } from '../../../shared/runs/runApi'
import { BrowserIntegration } from '../browser/BrowserIntegration'
+import { connectPlatformHost } from '../runtime/platformHostBootstrap'
+import { RemoteServiceClient } from '../runtime/RemoteServiceClient'
import { INSTALLER_EXIT_ARGUMENT, isInstallerExitRequest, resolveDesktopLaunchIntent } from '../startupIntent'
import { showStorageMigration } from '../storage/StorageMigrationWindow'
import { showStorageUnavailable, StorageUnavailableError } from '../storage/storageUnavailable'
@@ -26,7 +31,8 @@ import { DesktopRuntimeHost } from './DesktopRuntimeHost'
import { checkDesktopSmokeBridge } from './desktopSmokeCheck'
import { checkDesktopDirectories, DesktopInstanceLockUnavailable } from './desktopStorage'
import { DesktopWindowHost } from './DesktopWindowHost'
-import { initializeDesktopEnvironment, prepareDesktopEnvironment, prepareDesktopReady } from './environment'
+import { initializeDesktopEnvironment, prepareDesktopEnvironment, prepareDesktopReady, registerDesktopSchemes } from './environment'
+import { requestDesktopTarget } from './requestDesktopTarget'
class DesktopApplication {
readonly #environment: DesktopEnvironment
@@ -39,6 +45,9 @@ class DesktopApplication {
readonly #quit: ReturnType
#disposePromise: Promise | null = null
#rendererRecoveryPrompt: Promise | null = null
+ #openingDesktop: Promise | undefined
+ #closingDesktop: Promise | undefined
+ #locked = false
constructor(environment: DesktopEnvironment) {
this.#environment = environment
@@ -52,13 +61,25 @@ class DesktopApplication {
report: event => environment.events.publish(event),
isTaskLinked: () => this.#runtime.config?.desktop.contextPanelMode === 'task',
onActivityError: () => environment.events.publish({ level: 'warn', event: 'browser.activity.failed', errorCode: 'BROWSER_ACTIVITY_FAILED' }),
- endpoint: localTransports[currentPlatform.transport](environment.paths.browserAdapterSocket),
+ endpoint: localTransports[currentPlatform.transport](environment.paths.browserAdapterSocket, { ownsProfileLease: () => true }),
getPreferences: () => this.#runtime.config?.browser ?? DEFAULT_BROWSER_PREFERENCES,
testBrokerSocketPath: environment.paths.profile === 'test' ? process.env.LEXORA_BUDDY_BROWSER_ADAPTER_TEST_BROKER_SOCKET : undefined,
})
this.#runtime = new DesktopRuntimeHost(environment, this.#windows, this.#browser)
+ this.#runtime.openDesktop = (intent, signal) => this.#openDesktopTarget(intent, signal)
this.#quit = createDesktopQuitLifecycle({
events: environment.events,
+ ...(environment.platformHost
+ ? {
+ getExitBehavior: () => this.#runtime.config?.desktop.exitBehavior ?? 'stop_service',
+ closeDesktop: () => this.#closeDesktop(),
+ restartDesktop: async () => {
+ if (!(this.#runtime.service instanceof RemoteServiceClient))
+ throw new Error('SERVICE_NOT_READY')
+ await this.#runtime.service.restartDesktop()
+ },
+ }
+ : {}),
confirm: options => confirmDesktopQuit({
getWindow: () => this.#windows.window,
getLanguage: () => this.#runtime.language,
@@ -70,9 +91,13 @@ class DesktopApplication {
}, options),
dispose: async () => {
try {
+ if (this.#runtime.service instanceof RemoteServiceClient)
+ await this.#runtime.service.stop()
await this.#dispose()
}
- finally { await closeDesktopDiagnostics(environment.diagnostics) }
+ finally {
+ await closeDesktopDiagnostics(environment.diagnostics)
+ }
},
quit: (restart) => {
if (restart)
@@ -126,8 +151,30 @@ class DesktopApplication {
if (resolveDesktopLaunchIntent(argv) === 'foreground')
this.#windows.show()
})
- app.on('activate', () => this.#windows.show())
+ app.on('activate', () => {
+ void this.#openDesktop().catch(() => {})
+ })
app.on('window-all-closed', () => {})
+ void app.whenReady().then(() => {
+ powerMonitor.on('lock-screen', () => {
+ this.#locked = true
+ })
+ powerMonitor.on('unlock-screen', () => {
+ this.#locked = false
+ })
+ })
+ const platformHost = this.#environment.platformHost
+ if (platformHost) {
+ platformHost.peer.onRequest('host.stop', async (raw) => {
+ schema.object({}).strict().parse(raw)
+ await this.#dispose()
+ setImmediate(() => app.exit(0))
+ return { stopped: true }
+ })
+ platformHost.peer.onDidClose(() => {
+ void this.#dispose().finally(() => app.exit(1))
+ })
+ }
}
async start(): Promise {
@@ -150,27 +197,103 @@ class DesktopApplication {
defer(() => this.#integrations.stopSubscriptions())
await this.#integrations.start()
}, ['desktop.runtime'])
+ await this.#runtime.publishHostReady()
+ if (this.#environment.platformHost)
+ return null
return host.start('desktop.window', ({ defer }) => {
defer(() => this.#windows.close())
defer(() => this.#browser.closeWindow())
- return this.#windows.initialize({
- onWindowCreated: window => this.#browser.bindWindow(window),
- isQuitting: () => this.#quit.quitting,
- onHidden: () => { void showBackgroundCloseNotice(this.#runtime.configStore) },
- onRecoveryExhausted: () => this.#presentRendererRecovery(),
- })
+ return this.#openDesktop()
}, ['desktop.integrations'])
})
- if (this.#runtime.windowsPowerShell?.endsWith('\\powershell.exe') && !this.#environment.isSmokeTest)
+ if (window && this.#runtime.windowsPowerShell?.endsWith('\\powershell.exe') && !this.#environment.isSmokeTest)
showLegacyPowerShellNotice(window, () => this.#runtime.language, this.#environment)
- if (this.#environment.isSmokeTest) {
+ if (this.#environment.isSmokeTest && window) {
await checkDesktopSmokeBridge(window)
await this.#runtime.verifyInstallation()
await this.#quit.request()
}
}
+ async #openDesktopTarget(intent: z.infer, signal?: AbortSignal) {
+ const available = () => !signal?.aborted && !this.#locked && powerMonitor.getSystemIdleState(1) !== 'locked' && !this.#quit.quitting && !this.#disposePromise && !this.#closingDesktop
+ const unavailable = { accepted: false, uiReady: false, targetVisible: false, visible: false, focused: false }
+ if (!available())
+ return unavailable
+ try {
+ const window = await this.#openDesktop(intent)
+ const targetVisible = await requestDesktopTarget(window, this.#environment.startup, intent, undefined, { signal, available })
+ if (!available() || window.isDestroyed())
+ return unavailable
+ return { accepted: true, uiReady: this.#environment.startup.state.status === 'ready', targetVisible, visible: window.isVisible(), focused: window.isFocused() }
+ }
+ catch {
+ return unavailable
+ }
+ }
+
+ async #openDesktop(intent?: z.infer): Promise {
+ if (this.#quit.quitting || this.#disposePromise || this.#closingDesktop || this.#locked)
+ throw new Error('DESKTOP_OPEN_UNAVAILABLE')
+ if (intent?.kind === 'tasks' && intent.conversationId) {
+ const task = await this.#runtime.service.request('conversations.get', { conversationId: intent.conversationId })
+ if (!task)
+ throw new Error('CONVERSATION_NOT_FOUND')
+ }
+ const window = await (this.#openingDesktop ??= (async () => {
+ await this.#runtime.setDesktopAvailable(true)
+ this.#integrations.attachDesktop()
+ if (this.#windows.window) {
+ this.#windows.show()
+ return this.#windows.window
+ }
+ const opened = await this.#windows.initialize({
+ onWindowCreated: (window) => {
+ this.#browser.bindWindow(window)
+ window.on('query-session-end', () => {
+ void this.#quit.request({ reason: 'session_end', discardDraftsOnFailure: true })
+ })
+ },
+ onWindowReleasing: () => {
+ this.#environment.startup.detachRenderer()
+ this.#browser.closeWindow()
+ },
+ isQuitting: () => this.#quit.quitting,
+ onHidden: () => {
+ void showBackgroundCloseNotice(this.#runtime.configStore)
+ },
+ onRecoveryExhausted: () => this.#presentRendererRecovery(),
+ })
+ if (this.#environment.platformHost)
+ this.#windows.show()
+ return opened
+ })().finally(() => {
+ this.#openingDesktop = undefined
+ }))
+ if (this.#quit.quitting || this.#closingDesktop || window.isDestroyed())
+ throw new Error('DESKTOP_OPEN_CANCELLED')
+ return window
+ }
+
+ #closeDesktop(): Promise {
+ return this.#closingDesktop ??= (async () => {
+ await this.#openingDesktop
+ await this.#integrations.detachDesktop()
+ this.#browser.closeWindow()
+ this.#windows.close()
+ })().finally(() => {
+ this.#closingDesktop = undefined
+ })
+ }
+
async handleStartupFailure(error: unknown): Promise {
+ if (this.#environment.platformHost) {
+ this.#environment.startup.failed(error)
+ await this.#dispose().catch(() => {})
+ await closeDesktopDiagnostics(this.#environment.diagnostics)
+ app.exit(1)
+ return
+ }
if (this.#environment.isSmokeTest)
process.stderr.write(`Desktop installation verification failed: ${error instanceof Error ? error.stack : String(error)}\n`)
this.#environment.startup.failed(error)
@@ -187,7 +310,9 @@ class DesktopApplication {
try {
await closeDesktopDiagnostics(this.#environment.diagnostics)
}
- finally { app.exit(1) }
+ finally {
+ app.exit(1)
+ }
}
}
}
@@ -231,6 +356,8 @@ class DesktopApplication {
this.#disposePromise ??= (async () => {
this.#environment.startup.stopping()
const failures: unknown[] = []
+ this.#browser.closeWindow()
+ this.#windows.close()
try {
await this.#host.stop()
}
@@ -252,15 +379,23 @@ export async function startDesktopApplication(): Promise {
let environment: DesktopEnvironment | undefined
let recoveryRecorded = false
try {
+ registerDesktopSchemes()
if (isDesktopInstallationActive()) {
app.quit()
return
}
- environment = prepareDesktopEnvironment()
+ const platformHost = process.argv.includes('--lexora-platform-host') ? await connectPlatformHost() : undefined
+ process.env.LEXORA_BUDDY_STORAGE_AUTHORITY ??= 'sqlite'
+ environment = await prepareDesktopEnvironment(platformHost)
if (environment.storage.state.pending) {
await showStorageMigration(environment.storage, environment.diagnostics)
return
}
+ if (process.argv.includes('--lexora-storage-maintenance')) {
+ await closeDesktopDiagnostics(environment.diagnostics)
+ app.exit(0)
+ return
+ }
initializeDesktopEnvironment(environment)
if (process.argv.includes(INSTALLER_EXIT_ARGUMENT)) {
await closeDesktopDiagnostics(environment.diagnostics)
@@ -278,6 +413,13 @@ export async function startDesktopApplication(): Promise {
void application.start().catch(error => application.handleStartupFailure(error))
}
catch (cause) {
+ if (process.argv.includes('--lexora-platform-host')) {
+ environment?.startup.failed(cause)
+ if (environment)
+ await closeDesktopDiagnostics(environment.diagnostics)
+ app.exit(1)
+ return
+ }
let error = cause
if (error instanceof StorageUnavailableError) {
await showStorageUnavailable(error)
diff --git a/apps/buddy/electron/main/app/DesktopIntegrations.ts b/apps/buddy/electron/main/app/DesktopIntegrations.ts
index 7fead5dd4..2b5f71663 100644
--- a/apps/buddy/electron/main/app/DesktopIntegrations.ts
+++ b/apps/buddy/electron/main/app/DesktopIntegrations.ts
@@ -7,7 +7,7 @@ import type { DesktopRuntimeHost } from './DesktopRuntimeHost'
import type { DesktopWindowHost } from './DesktopWindowHost'
import type { DesktopEnvironment } from './typing'
import { homedir } from 'node:os'
-import { basename } from 'node:path'
+import { basename, join } from 'node:path'
import process from 'node:process'
import { app, nativeTheme, Notification, shell } from 'electron'
import { z } from 'zod'
@@ -50,6 +50,8 @@ import { NotificationSoundLibrary } from '../notifications/NotificationSoundLibr
import { NotificationSoundService } from '../notifications/NotificationSoundService'
import { registerDesktopNotificationIpc } from '../notifications/registerDesktopNotificationIpc'
import { registerNotificationSoundIpc } from '../notifications/registerNotificationSoundIpc'
+import { ProductDesktopGateway } from '../productProtocol/ProductDesktopGateway'
+import { registerDraftRecoveryIpc } from '../productProtocol/registerDraftRecoveryIpc'
import { createProviderSpeechBackend } from '../speech/createProviderSpeechBackend'
import { registerSpeechIpc } from '../speech/registerSpeechIpc'
import { registerStorageIpc } from '../storage/registerStorageIpc'
@@ -81,6 +83,7 @@ export class DesktopIntegrations {
readonly #requestInstall: (prepare: () => Promise<(() => void) | void>) => Promise
readonly #subscriptions: Array<() => void | Promise> = []
#tray: DesktopTrayController | null = null
+ #detachDesktop: (() => Promise) | undefined
constructor(environment: DesktopEnvironment, runtime: DesktopRuntimeHost, windows: DesktopWindowHost, browser: BrowserIntegration, requestQuit: () => void, requestRestart: () => void, requestInstall: (prepare: () => Promise<(() => void) | void>) => Promise) {
this.#environment = environment
@@ -107,8 +110,31 @@ export class DesktopIntegrations {
await this.#browser.host?.updateActivity()
}
+ attachDesktop(): void {
+ if (this.#tray)
+ return
+ const { paths, trayIconPath } = this.#environment
+ const runtime = this.#runtime
+ const windows = this.#windows
+ this.#tray = createDesktopTray({
+ appName: paths.appName,
+ iconPath: trayIconPath,
+ profile: paths.profile,
+ language: runtime.language,
+ onOpenDesktop: () => windows.show(),
+ onQuit: this.#requestQuit,
+ onRestart: this.#requestRestart,
+ })
+ }
+
+ async detachDesktop(): Promise {
+ this.destroyTray()
+ await this.#detachDesktop?.()
+ await this.#runtime.setDesktopAvailable(false)
+ }
+
async start(): Promise {
- const { paths, trayIconPath, diagnostics } = this.#environment
+ const { paths, diagnostics } = this.#environment
const runtime = this.#runtime
const windows = this.#windows
const service = runtime.service
@@ -252,6 +278,7 @@ export class DesktopIntegrations {
await extensions.themesReady.catch(() => {})
this.#subscriptions.push(registerThemeIpc(themes, () => windows.window, (color, dark, system) => windows.setThemeAppearance(color, dark, system)))
this.#subscriptions.push(service.onStateChange(() => extensions.conditions.invalidate({ inputs: ['runtime.models', 'runtime.task'] })))
+ this.#detachDesktop = extensions.detachDesktop
runtime.inspectExtension = extensions.inspect
runtime.extensionAgent = extensions.agent
runtime.extensionStorage = extensions
@@ -283,15 +310,8 @@ export class DesktopIntegrations {
this.#subscriptions.push(registerStartupIpc(this.#environment.startup, () => windows.window))
this.#subscriptions.push(registerApplicationLogIpc(new ApplicationLogReader(paths.logs, diagnostics.launchId, homedir()), () => windows.window, event => diagnostics.record(event), () => diagnostics.flushWithin(1000)))
this.#subscriptions.push(registerPerformanceIpc(runtime, () => windows.window, this.#environment.events.publish))
- this.#tray = createDesktopTray({
- appName: paths.appName,
- iconPath: trayIconPath,
- profile: paths.profile,
- language: runtime.language,
- onOpenDesktop: () => windows.show(),
- onQuit: this.#requestQuit,
- onRestart: this.#requestRestart,
- })
+ if (!this.#environment.platformHost)
+ this.attachDesktop()
const player = new NotificationAudioPlayer()
const soundLibrary = new NotificationSoundLibrary({ home: paths.buddyHome, configStore: runtime.configStore, applyConfig: config => this.applyConfig(config) })
const sounds = new NotificationSoundService({ player, library: soundLibrary, getPreferences: () => runtime.config!.desktop.notificationSound })
@@ -388,6 +408,7 @@ export class DesktopIntegrations {
})
this.#subscriptions.push(() => configNotifications.dispose())
this.#subscriptions.push(registerBrowserDesktopIpc({
+ presentation: this.#browser,
data: this.#browser.data,
screenshots: this.#browser.screenshots,
getHost: () => this.#browser.host,
@@ -395,6 +416,16 @@ export class DesktopIntegrations {
resolveArtifactEntry: async input => browserArtifactEntrySchema.parse(await service.request('artifacts.resolveBrowserEntry', input)),
resolveFileEntry: async input => taskFilesRpc.resolveBrowser.response.parse(await service.request(taskFilesRpc.resolveBrowser.method, input)),
}))
+ const productGateway = process.env.LEXORA_BUDDY_STORAGE_AUTHORITY === 'sqlite'
+ ? new ProductDesktopGateway(service, join(paths.lexoraHome, 'device/product-outbox'), buddyVersion.version)
+ : null
+ if (productGateway)
+ this.#subscriptions.push(() => productGateway.dispose())
+ this.#subscriptions.push(registerDraftRecoveryIpc({
+ directory: join(paths.lexoraHome, 'device/renderer-drafts'),
+ getWindow: () => windows.window,
+ identity: async () => productGateway ? productGateway.getIdentity() : null,
+ }))
this.#subscriptions.push(registerLocalChatIpc({
recordDiagnostic: this.#environment.events.scope({ component: 'desktop.gateway' }).publish,
readWebCredential: () => runtime.readWebCredential(),
@@ -417,7 +448,7 @@ export class DesktopIntegrations {
throw error
}
},
- runtime: service,
+ runtime: productGateway ?? service,
}))
}
diff --git a/apps/buddy/electron/main/app/DesktopRuntimeHost.ts b/apps/buddy/electron/main/app/DesktopRuntimeHost.ts
index 57524a3b9..b1c72d931 100644
--- a/apps/buddy/electron/main/app/DesktopRuntimeHost.ts
+++ b/apps/buddy/electron/main/app/DesktopRuntimeHost.ts
@@ -1,4 +1,6 @@
import type { ExtensionInspection } from '../../../shared/extensions/extensionAuthoring'
+import type { RuntimeRpcPeerContract } from '../../../shared/runtime/rpcPeer'
+import type { DesktopOpenIntent, DesktopOpenResult } from '../../../shared/service/localServiceProtocol'
import type { SpeechProvider } from '../../../shared/speech/speechApi'
import type { LexoraConfig } from '../../shared/desktopApi'
import type { BrowserIntegration } from '../browser/BrowserIntegration'
@@ -10,6 +12,7 @@ import type { DesktopEnvironment } from './typing'
import { join } from 'node:path'
import process from 'node:process'
import { app, powerMonitor } from 'electron'
+import { z } from 'zod'
import { currentPlatform } from '../../../platform/currentPlatform'
import { createBuddyNativeEnvironment, resolveBuddyProcessControl, resolveBuddyShellSandbox } from '../../../platform/native/nativeHost'
import shellSandbox from '../../../platform/native/shellSandbox.json'
@@ -28,6 +31,7 @@ import { ocrRpc } from '../../../shared/images/ocrService'
import { networkPermissionGrantSchema, networkPermissionsRpc } from '../../../shared/permissions/networkPermissionsRpc'
import { isLinux } from '../../../shared/platform/identifiers'
import { runtimePreferencesRpc } from '../../../shared/runtime/runtimePreferences'
+import { desktopOpenIntentSchema } from '../../../shared/service/localServiceProtocol'
import { HOST_SPEECH_MODELS } from '../../../shared/speech/speechApi'
import { installAttachmentProtocol } from '../attachmentProtocol'
import { registerBrowserHostRpc } from '../browser/registerBrowserHostRpc'
@@ -49,12 +53,15 @@ import { installRendererProtocol } from '../rendererProtocol'
import { createBuddyServiceEnvironment, resolveBuddySearchToolsDirectory } from '../runtime/buddyServiceEnvironment'
import { forkBuddyServiceProcess } from '../runtime/buddyServiceProcess'
import { BuddyServiceSupervisor } from '../runtime/BuddyServiceSupervisor'
+import { RemoteServiceClient } from '../runtime/RemoteServiceClient'
import { registerSandboxHostRpc } from '../sandbox/registerSandboxHostRpc'
import { verifySandboxInstallation } from '../sandbox/verifySandboxInstallation'
import { createCredentialVault } from '../secrets/CredentialVault'
import { registerCredentialHostRpc } from '../secrets/registerCredentialHostRpc'
+import { withProfileWritesStopped } from '../storage/profileWrites'
export class DesktopRuntimeHost {
+ openDesktop: ((intent: DesktopOpenIntent, signal?: AbortSignal) => Promise) | null = null
readonly performance: DesktopPerformanceMonitor
inspectExtension: ((id: string) => Promise) | null = null
extensionAgent: ReturnType['agent'] | null = null
@@ -71,7 +78,8 @@ export class DesktopRuntimeHost {
#credentials: CredentialVault | null = null
#config: LexoraConfig | null = null
#features: DesktopFeature[] = []
- #service: BuddyServiceSupervisor | null = null
+ #service: Pick | null = null
+ #desktopAvailable = true
#network: DesktopNetwork | null = null
#webHost: HostWebService | null = null
#windowsPowerShell: string | undefined
@@ -83,6 +91,7 @@ export class DesktopRuntimeHost {
constructor(environment: DesktopEnvironment, windows: DesktopWindowHost, browser: BrowserIntegration) {
this.#environment = environment
+ this.#desktopAvailable = !environment.platformHost
this.#windows = windows
this.#browser = browser
this.performance = new DesktopPerformanceMonitor(() => ({ metrics: app.getAppMetrics(), proxy: this.network.activity }), environment.events.publish)
@@ -101,7 +110,8 @@ export class DesktopRuntimeHost {
}
withStoppedStorage(operation: () => Promise): Promise {
- return this.service.withStoppedStorage(() => this.extensionStorage ? this.extensionStorage.withStoppedStorage(operation) : operation())
+ const snapshot = () => withProfileWritesStopped(this.#environment.paths.lexoraHome, operation)
+ return this.service.withStoppedStorage(() => this.extensionStorage ? this.extensionStorage.withStoppedStorage(snapshot) : snapshot())
}
get language(): LexoraConfig['desktop']['language'] {
@@ -160,7 +170,7 @@ export class DesktopRuntimeHost {
}
}
- get service(): BuddyServiceSupervisor {
+ get service(): Pick {
if (!this.#service)
throw new Error('Desktop Runtime is not prepared')
return this.#service
@@ -217,91 +227,103 @@ export class DesktopRuntimeHost {
paths: environment.paths,
})
this.#features = composition.features
- this.#service = new BuddyServiceSupervisor({
- onDiagnostic: (event) => {
- environment.diagnostics.record({ ...event, scope: 'local-service' })
- },
- bindPeer: (peer) => {
- const sandbox = registerSandboxHostRpc(peer, {
- buddyHome: environment.paths.buddyHome,
- protectedRoots: environment.storage.protection.sandboxRoots,
- protectionScope: environment.storage.bootstrapRoot,
- proxyUrl: this.#network!.sandboxProxyUrl,
- ...this.#sandboxOptions(),
- })
- const prepareSandbox = () => {
- sandbox.prepare()
- peer.notify('host.sandbox.ready', {})
- }
- this.#prepareSandbox = prepareSandbox
- sandbox.onDidChange(event => environment.events.publish({
- event: `sandbox.supervisor.${event.kind}`,
- level: event.kind === 'cleanup_failed' ? 'warn' : 'info',
- requestId: event.requestId,
- sandboxProcess: { phase: event.kind, pid: event.pid, exitCode: event.exitCode },
- }))
- const stopAuthoring = registerExtensionAuthoringRpc(peer, (id) => {
- if (!this.inspectExtension)
+ const bindPeer = (peer: RuntimeRpcPeerContract) => {
+ const sandbox = registerSandboxHostRpc(peer, {
+ buddyHome: environment.paths.buddyHome,
+ protectedRoots: environment.storage.protection.sandboxRoots,
+ protectionScope: environment.storage.bootstrapRoot,
+ proxyUrl: this.#network!.sandboxProxyUrl,
+ ...this.#sandboxOptions(),
+ })
+ const prepareSandbox = () => {
+ sandbox.prepare()
+ peer.notify('host.sandbox.ready', {})
+ }
+ this.#prepareSandbox = prepareSandbox
+ sandbox.onDidChange(event => environment.events.publish({
+ event: `sandbox.supervisor.${event.kind}`,
+ level: event.kind === 'cleanup_failed' ? 'warn' : 'info',
+ requestId: event.requestId,
+ sandboxProcess: { phase: event.kind, pid: event.pid, exitCode: event.exitCode },
+ }))
+ const stopAuthoring = registerExtensionAuthoringRpc(peer, (id) => {
+ if (!this.inspectExtension)
+ throw new Error('EXTENSION_SERVICE_UNAVAILABLE')
+ return this.inspectExtension(id)
+ }, () => this.#config?.desktop.pluginAuthor ?? '')
+ const disposers = [
+ peer.onRequest('host.openDesktop', (raw, signal) => {
+ if (!this.openDesktop)
+ throw new Error('DESKTOP_UNAVAILABLE')
+ return this.openDesktop(desktopOpenIntentSchema.parse(raw), signal)
+ }),
+ peer.onRequest(imageRpc.preferences, async () => (await this.configStore.read()).desktop.images ?? {}),
+ peer.onRequest(ocrRpc.read, (raw, signal) => this.ocr.read(raw, signal ?? new AbortController().signal)),
+ peer.onRequest(HOST_SPEECH_MODELS, () => this.speechModels?.() ?? []),
+ registerExtensionImageReadingRpc(peer, () => this.extensionInference),
+ registerExtensionImageRpc(peer, () => this.extensionInference),
+ registerExtensionModelRpc(peer, () => this.extensionInference),
+ registerExtensionShellRpc(peer, () => this.extensionShells),
+ peer.onRequest(extensionAgentRpc.list, () => this.extensionAgent?.list() ?? []),
+ peer.onRequest(extensionAgentRpc.releaseRun, (input) => {
+ const { runId } = z.object({ runId: z.string().min(1).max(256) }).strict().parse(input)
+ this.extensionAgent?.releaseRun(runId)
+ return {}
+ }),
+ peer.onRequest(extensionSkillsRpc.list, () => this.extensionSkills?.list() ?? []),
+ peer.onRequest(extensionAgentRpc.resource, (input, signal) => {
+ if (!this.extensionAgent)
+ throw new Error('EXTENSION_AGENT_UNAVAILABLE')
+ return this.extensionAgent.readResource(extensionAgentResourceRequestSchema.parse(input), signal ?? new AbortController().signal)
+ }),
+ // Unlike skills, an empty answer here would read as "everything was uninstalled", so an unready service must fail instead.
+ peer.onRequest(extensionCapabilitiesRpc.list, () => {
+ if (!this.extensionCapabilities)
throw new Error('EXTENSION_SERVICE_UNAVAILABLE')
- return this.inspectExtension(id)
- }, () => this.#config?.desktop.pluginAuthor ?? '')
- const disposers = [
- peer.onRequest(imageRpc.preferences, async () => (await this.configStore.read()).desktop.images ?? {}),
- peer.onRequest(ocrRpc.read, (raw, signal) => this.ocr.read(raw, signal ?? new AbortController().signal)),
- peer.onRequest(HOST_SPEECH_MODELS, () => this.speechModels?.() ?? []),
- registerExtensionImageReadingRpc(peer, () => this.extensionInference),
- registerExtensionImageRpc(peer, () => this.extensionInference),
- registerExtensionModelRpc(peer, () => this.extensionInference),
- registerExtensionShellRpc(peer, () => this.extensionShells),
- peer.onRequest(extensionAgentRpc.list, () => this.extensionAgent?.list() ?? []),
- peer.onRequest(extensionSkillsRpc.list, () => this.extensionSkills?.list() ?? []),
- peer.onRequest(extensionAgentRpc.resource, (input, signal) => {
- if (!this.extensionAgent)
- throw new Error('EXTENSION_AGENT_UNAVAILABLE')
- return this.extensionAgent.readResource(extensionAgentResourceRequestSchema.parse(input), signal ?? new AbortController().signal)
- }),
- // Unlike skills, an empty answer here would read as "everything was uninstalled", so an unready service must fail instead.
- peer.onRequest(extensionCapabilitiesRpc.list, () => {
- if (!this.extensionCapabilities)
- throw new Error('EXTENSION_SERVICE_UNAVAILABLE')
- return this.extensionCapabilities.list()
- }),
- peer.onRequest(extensionAgentRpc.invoke, (input, signal) => {
- if (!this.extensionAgent)
- throw new Error('EXTENSION_AGENT_UNAVAILABLE')
- return this.extensionAgent.invoke(extensionAgentInvocationSchema.parse(input), signal ?? new AbortController().signal)
- }),
- peer.onRequest(runtimePreferencesRpc.get, () => this.#config!.runtime),
- peer.onRequest(networkPermissionsRpc.get, async () => (await this.configStore.read()).browser.networkPermissions),
- peer.onRequest(networkPermissionsRpc.allow, async (params, signal) => {
- const input = networkPermissionGrantSchema.parse(params)
- await this.configStore.allowNetworkPermission(input.host, input.operation, () => signal?.throwIfAborted())
- return {}
- }),
- peer.onRequest(contextPanelRpc.presentBrowser, (params) => {
- const source = contextPanelSourceSchema.parse(params)
- return this.contextPanel.execute({ action: 'open', target: { kind: 'browser', source } }, 'harness')
- }),
- registerWebHostRpc(peer, this.#webHost!),
- registerBrowserHostRpc(peer, {
- createAdapterLease: input => this.#browser.adapter.issueLease(input),
- getHost: () => this.#browser.host,
- }),
- registerCredentialHostRpc(peer, credentials),
- ...this.#features.map(feature => feature.bindPeer(peer)),
- ]
- return () => {
- if (this.#prepareSandbox === prepareSandbox)
- this.#prepareSandbox = undefined
- const cleanup = Promise.allSettled([sandbox.dispose(), stopAuthoring()]).then((results) => {
- const failures = results.filter(result => result.status === 'rejected').map(result => result.reason)
- if (failures.length)
- throw new AggregateError(failures, 'RUNTIME_CLEANUP_FAILED')
- }).finally(() => this.#sandboxCleanup.delete(cleanup))
- this.#sandboxCleanup.add(cleanup)
- disposers.forEach(dispose => dispose())
- }
+ return this.extensionCapabilities.list()
+ }),
+ peer.onRequest(extensionAgentRpc.invoke, (input, signal) => {
+ if (!this.extensionAgent)
+ throw new Error('EXTENSION_AGENT_UNAVAILABLE')
+ return this.extensionAgent.invoke(extensionAgentInvocationSchema.parse(input), signal ?? new AbortController().signal)
+ }),
+ peer.onRequest(runtimePreferencesRpc.get, () => this.#config!.runtime),
+ peer.onRequest(networkPermissionsRpc.get, async () => (await this.configStore.read()).browser.networkPermissions),
+ peer.onRequest(networkPermissionsRpc.allow, async (params, signal) => {
+ const input = networkPermissionGrantSchema.parse(params)
+ await this.configStore.allowNetworkPermission(input.host, input.operation, () => signal?.throwIfAborted())
+ return {}
+ }),
+ peer.onRequest(contextPanelRpc.presentBrowser, (params) => {
+ const source = contextPanelSourceSchema.parse(params)
+ return this.contextPanel.execute({ action: 'open', target: { kind: 'browser', source } }, 'harness')
+ }),
+ registerWebHostRpc(peer, this.#webHost!),
+ registerBrowserHostRpc(peer, {
+ createAdapterLease: input => this.#browser.adapter.issueLease(input),
+ getHost: () => this.#browser.host,
+ }),
+ registerCredentialHostRpc(peer, credentials),
+ ...this.#features.map(feature => feature.bindPeer(peer)),
+ ]
+ return () => {
+ this.extensionAgent?.releaseAllRuns()
+ if (this.#prepareSandbox === prepareSandbox)
+ this.#prepareSandbox = undefined
+ const cleanup = Promise.allSettled([sandbox.dispose(), stopAuthoring()]).then((results) => {
+ const failures = results.filter(result => result.status === 'rejected').map(result => result.reason)
+ if (failures.length)
+ throw new AggregateError(failures, 'RUNTIME_CLEANUP_FAILED')
+ }).finally(() => this.#sandboxCleanup.delete(cleanup))
+ this.#sandboxCleanup.add(cleanup)
+ disposers.forEach(dispose => dispose())
+ }
+ }
+ const supervisorOptions = {
+ onDiagnostic: (event: Parameters[0]['onDiagnostic']>>[0]) => {
+ environment.diagnostics.record({ ...event, scope: 'local-service' })
},
+ bindPeer,
diagnosticOutput: environment.diagnostics.createWritable('local-service', { event: 'runtime.supervisor', level: 'error' }),
spawnService: (onFatalError, sourceId) => forkBuddyServiceProcess({
env: {
@@ -314,20 +336,28 @@ export class DesktopRuntimeHost {
onFatalError,
captureStderr: output => environment.diagnostics.captureOutput('local-service', output, sourceId),
}),
- })
+ } satisfies ConstructorParameters[0]
+ if (environment.platformHost) {
+ this.#subscriptions.push(bindPeer(environment.platformHost.peer))
+ this.#service = new RemoteServiceClient(environment.platformHost.bootstrap, environment.platformHost.peer)
+ }
+ else {
+ this.#service = new BuddyServiceSupervisor(supervisorOptions)
+ }
this.#subscriptions.push(environment.startup.bindRuntime(this.#service))
return config
}
async applyConfig(config: LexoraConfig): Promise {
await this.#network?.apply(config.proxy)
+ const previousLaunchAtLogin = this.#config?.desktop.launchAtLogin
const previous = this.#config?.runtime
this.#config = config
if (previous?.cacheWarming !== config.runtime.cacheWarming || previous?.codemode !== config.runtime.codemode || previous?.modelRetryLimit !== config.runtime.modelRetryLimit || previous?.codemodeWorkerLimit !== config.runtime.codemodeWorkerLimit || previous?.codemodeOverflow !== config.runtime.codemodeOverflow)
this.#service?.notify(runtimePreferencesRpc.changed, config.runtime)
- const featureConfig = config.desktop.onboardingCompleted ? config : { ...config, pet: { ...config.pet, enabled: false } }
+ const featureConfig = this.#desktopAvailable && config.desktop.onboardingCompleted ? config : { ...config, pet: { ...config.pet, enabled: false } }
await Promise.all(this.#features.map(feature => feature.applyConfig(featureConfig)))
- if (app.isPackaged && this.#environment.paths.profile === 'stable')
+ if (app.isPackaged && this.#environment.paths.profile === 'stable' && previousLaunchAtLogin !== undefined && previousLaunchAtLogin !== config.desktop.launchAtLogin)
await this.#environment.setAutostart(config.desktop.launchAtLogin)
}
@@ -372,13 +402,26 @@ export class DesktopRuntimeHost {
return this.#credentials.read('web', 'tavily')
}
+ async setDesktopAvailable(value: boolean): Promise {
+ this.#desktopAvailable = value
+ if (this.#config)
+ await this.applyConfig(this.#config)
+ }
+
+ async publishHostReady(): Promise {
+ const host = this.#environment.platformHost
+ if (!host)
+ return
+ await host.peer.request('host.ready', { hostInstanceId: host.bootstrap.hostInstanceId, preferences: this.#config!.runtime, display: true, proxy: { httpProxy: this.network.proxyUrl, httpsProxy: this.network.proxyUrl, noProxy: '' } }, 120000)
+ }
+
async stop(): Promise {
this.performance.stop()
const failures: unknown[] = []
for (const cleanup of [
() => this.contextPanel.dispose(),
() => this.configStore.dispose(),
- () => this.#service?.stop(),
+ () => this.#service instanceof RemoteServiceClient ? this.#service.disconnect() : this.#service?.stop(),
() => Promise.all(this.#sandboxCleanup),
() => this.#webHost?.dispose(),
() => this.#network?.stop(),
diff --git a/apps/buddy/electron/main/app/DesktopStartup.ts b/apps/buddy/electron/main/app/DesktopStartup.ts
index d13f7fc3a..dd60e28d0 100644
--- a/apps/buddy/electron/main/app/DesktopStartup.ts
+++ b/apps/buddy/electron/main/app/DesktopStartup.ts
@@ -130,6 +130,13 @@ export class DesktopStartup {
return true
}
+ detachRenderer(): void {
+ if (this.#renderer)
+ this.#retiredRenderers.add(this.#renderer.sourceId)
+ this.#renderer = null
+ this.#update()
+ }
+
stopping(): void {
if (this.#terminalStatus)
return
diff --git a/apps/buddy/electron/main/app/DesktopWindowHost.ts b/apps/buddy/electron/main/app/DesktopWindowHost.ts
index 94cb9cda6..29c1ff060 100644
--- a/apps/buddy/electron/main/app/DesktopWindowHost.ts
+++ b/apps/buddy/electron/main/app/DesktopWindowHost.ts
@@ -15,6 +15,7 @@ interface WindowBindings {
onHidden: () => void
onRecoveryExhausted: () => void
onWindowCreated: (window: BrowserWindow) => void
+ onWindowReleasing?: (window: BrowserWindow) => void
}
export class DesktopWindowHost {
@@ -45,6 +46,7 @@ export class DesktopWindowHost {
screen.getAllDisplays().map(display => display.bounds),
)
const manager = new DesktopWindowManager({
+ onBeforeDestroy: bindings.onWindowReleasing,
onRecoveryStarted: () => environment.events.publish({ level: 'warn', event: 'renderer.recovery.started', attempt: 1 }),
onRecoveryRebuilding: () => environment.events.publish({ level: 'info', event: 'renderer.recovery.rebuilding', attempt: 1 }),
onRecoveryExhausted: () => {
diff --git a/apps/buddy/electron/main/app/__tests__/DesktopStartup.spec.ts b/apps/buddy/electron/main/app/__tests__/DesktopStartup.spec.ts
index d19ed755a..64345bc94 100644
--- a/apps/buddy/electron/main/app/__tests__/DesktopStartup.spec.ts
+++ b/apps/buddy/electron/main/app/__tests__/DesktopStartup.spec.ts
@@ -80,9 +80,6 @@ describe('application lifecycle snapshot', () => {
expect(startup.state.status).toBe('ready')
expect(startup.state.hasBeenReady).toBe(true)
expect(events.filter(event => event.event === 'app.ready')).toHaveLength(1)
- const snapshot = startup.state
- Object.assign(snapshot.stages[0]!, { status: 'failed' })
- expect(startup.state.stages[0]?.status).toBe('completed')
})
it('rejects delayed renderer reports after the Runtime generation changes while retaining their diagnostics', () => {
@@ -117,11 +114,17 @@ describe('application lifecycle snapshot', () => {
expect(startup.state.stages.some(stage => stage.progress)).toBe(false)
})
- it('reconstructs completed managed stages when subscribed after initialization', async () => {
- const host = new ServiceHost()
- await host.start('desktop', () => true)
- const startup = new DesktopStartup()
- startup.bindDesktop(host.lifecycle)
- expect(startup.state.stages).toContainEqual(expect.objectContaining({ stage: 'desktop', status: 'completed' }))
+ it('requires a fresh renderer after closing the desktop and rejects late reports from the old page', () => {
+ const { startup, complete, send, connect } = fixture()
+ complete('desktop')
+ connect('runtime-1')
+ complete('renderer')
+ expect(startup.state.status).toBe('ready')
+ startup.detachRenderer()
+ expect(startup.state.status).toBe('starting')
+ send('renderer', 'ready')
+ expect(startup.state.status).toBe('starting')
+ complete('renderer')
+ expect(startup.state.status).toBe('ready')
})
})
diff --git a/apps/buddy/electron/main/app/__tests__/desktopQuitLifecycle.spec.ts b/apps/buddy/electron/main/app/__tests__/desktopQuitLifecycle.spec.ts
index 3f1195581..dcd8b13c2 100644
--- a/apps/buddy/electron/main/app/__tests__/desktopQuitLifecycle.spec.ts
+++ b/apps/buddy/electron/main/app/__tests__/desktopQuitLifecycle.spec.ts
@@ -3,6 +3,57 @@ import { describe, expect, it } from 'vitest'
import { createDesktopQuitLifecycle } from '../desktopQuitLifecycle'
describe('desktop quit lifecycle', () => {
+ it('captures the committed exit preference once and keeps Core alive when only Desktop exits', async () => {
+ const saving = deferred()
+ const operations: string[] = []
+ let preference: 'keep_service' | 'stop_service' = 'keep_service'
+ const lifecycle = createDesktopQuitLifecycle({
+ getExitBehavior: () => preference,
+ closeDesktop: async () => { operations.push('desktop.closed') },
+ confirm: () => saving.promise,
+ dispose: async () => { operations.push('service.stopped') },
+ quit: () => { operations.push('host.quit') },
+ exit: () => { operations.push('host.forced') },
+ })
+ const first = lifecycle.request()
+ preference = 'stop_service'
+ expect(lifecycle.request()).toBe(first)
+ saving.resolve(true)
+ await first
+ expect(operations).toEqual(['desktop.closed'])
+ expect(lifecycle.committed).toBe(false)
+ await lifecycle.request({ reason: 'service_stop' })
+ expect(operations).toEqual(['desktop.closed', 'service.stopped', 'host.quit'])
+ })
+
+ it('hands a confirmed restart to Core and retries a rejected handoff without disposing Desktop', async () => {
+ const accepted = deferred()
+ let failure = true
+ let requests = 0
+ const lifecycle = createDesktopQuitLifecycle({
+ getExitBehavior: () => 'keep_service',
+ confirm: async () => true,
+ restartDesktop: async () => {
+ requests++
+ if (failure)
+ throw new Error('SERVICE_NOT_READY')
+ await accepted.promise
+ },
+ dispose: async () => { throw new Error('Core owns restart cleanup') },
+ quit: () => { throw new Error('Core owns the next Desktop') },
+ exit: () => { throw new Error('A rejected handoff must keep Desktop alive') },
+ })
+ await expect(lifecycle.request({ restart: true })).rejects.toThrow('SERVICE_NOT_READY')
+ expect(lifecycle.quitting).toBe(false)
+ failure = false
+ const request = lifecycle.request({ restart: true })
+ expect(lifecycle.request({ restart: true })).toBe(request)
+ accepted.resolve()
+ await request
+ expect(requests).toBe(2)
+ expect(lifecycle.committed).toBe(true)
+ })
+
it('shares concurrent requests and commits only after saving and cleanup', async () => {
const save = deferred()
const stopped = deferred()
@@ -59,20 +110,7 @@ describe('desktop quit lifecycle', () => {
expect(events).toEqual(['cleanup', 'restart'])
})
- it('preserves explicit discard-on-failure for signal shutdown', async () => {
- const events: string[] = []
- const lifecycle = createDesktopQuitLifecycle({
- exit: () => { throw new Error('Unexpected forced exit') },
- confirm: async options => options.discardDraftsOnFailure === true,
- dispose: async () => { events.push('cleanup') },
- quit: () => { events.push('quit') },
- })
- await lifecycle.request({ discardDraftsOnFailure: true })
- expect(events).toEqual(['cleanup', 'quit'])
- expect(lifecycle.committed).toBe(true)
- })
-
- it.each(['quit', 'installation'] as const)('exits after cleanup fails during %s without committing or running the completion action', async (reason) => {
+ it('exits after cleanup fails without committing or running the installation', async () => {
const operations: string[] = []
const lifecycle = createDesktopQuitLifecycle({
confirm: async () => true,
@@ -83,36 +121,15 @@ describe('desktop quit lifecycle', () => {
quit: () => { operations.push('quit') },
exit: () => { operations.push('exit') },
})
- const input = reason === 'quit' ? {} : { reason: 'installation' as const }
- const prepare = reason === 'installation'
- ? async () => () => { operations.push('install') }
- : undefined
- const pending = lifecycle.request(input, prepare)
+ const pending = lifecycle.request({ reason: 'installation' }, async () => () => {
+ operations.push('install')
+ })
await expect(pending).rejects.toThrow('Cleanup failed')
expect(operations).toEqual(['dispose', 'exit'])
expect(lifecycle.quitting).toBe(true)
expect(lifecycle.committed).toBe(false)
})
- it('hands installation off only after confirmation and before releasing application resources', async () => {
- const operations: string[] = []
- let allowed = false
- const lifecycle = createDesktopQuitLifecycle({
- exit: () => { throw new Error('Unexpected forced exit') },
- confirm: async () => allowed,
- dispose: async () => { operations.push('dispose') },
- quit: () => { operations.push('quit') },
- })
- const prepare = async () => {
- operations.push('installer')
- }
- await lifecycle.request({ reason: 'installation' }, prepare)
- expect(operations).toEqual([])
- allowed = true
- await lifecycle.request({ reason: 'installation' }, prepare)
- expect(operations).toEqual(['installer', 'dispose', 'quit'])
- })
-
it('leaves the application running if installer launch fails', async () => {
const operations: string[] = []
const lifecycle = createDesktopQuitLifecycle({
diff --git a/apps/buddy/electron/main/app/__tests__/requestDesktopTarget.spec.ts b/apps/buddy/electron/main/app/__tests__/requestDesktopTarget.spec.ts
new file mode 100644
index 000000000..1208b8ebb
--- /dev/null
+++ b/apps/buddy/electron/main/app/__tests__/requestDesktopTarget.spec.ts
@@ -0,0 +1,72 @@
+import type { BrowserWindow, IpcMain } from 'electron'
+import { EventEmitter } from 'node:events'
+import { afterEach, expect, it, vi } from 'vitest'
+import { DESKTOP_IPC_CHANNELS } from '../../../shared/desktopApi'
+import { requestDesktopTarget } from '../requestDesktopTarget'
+import { createStartupFixture } from './startupFixture'
+
+vi.mock('electron', () => ({ ipcMain: {} }))
+afterEach(() => vi.useRealTimers())
+
+function fixture() {
+ const { startup, complete, connect } = createStartupFixture()
+ complete('desktop')
+ connect('runtime-1')
+ complete('renderer')
+ const ipc = new EventEmitter()
+ let request!: { requestId: string }
+ const webContents = { mainFrame: {}, isDestroyed: () => false, send: (_channel: string, input: typeof request) => {
+ request = input
+ } }
+ const window = Object.assign(new EventEmitter(), { isDestroyed: () => false, webContents })
+ const open = (options = {}) => requestDesktopTarget(window as unknown as BrowserWindow, startup, { kind: 'tasks' }, ipc as unknown as IpcMain, options)
+ const ack = (sender = webContents, senderFrame = webContents.mainFrame, requestId = request.requestId) => ipc.emit(DESKTOP_IPC_CHANNELS.appOpenTargetAck, { sender, senderFrame }, { requestId, opened: true })
+ return { open, ack, window, webContents, ipc }
+}
+
+it('acknowledges only the requested target from the current main frame', async () => {
+ vi.useFakeTimers()
+ const f = fixture()
+ const opening = f.open()
+ let settled = false
+ void opening.then(() => settled = true)
+ await vi.advanceTimersByTimeAsync(0)
+ f.ack({ ...f.webContents })
+ f.ack(f.webContents, {})
+ f.ack(f.webContents, f.webContents.mainFrame, '00000000-0000-4000-8000-000000000000')
+ await vi.advanceTimersByTimeAsync(100)
+ expect(settled).toBe(false)
+ f.ack()
+ await expect(opening).resolves.toBe(true)
+ expect(f.ipc.listenerCount(DESKTOP_IPC_CHANNELS.appOpenTargetAck)).toBe(0)
+})
+
+it.each(['timeout', 'closed'])('does not report a visible target after %s', async (reason) => {
+ vi.useFakeTimers()
+ const f = fixture()
+ const opening = f.open()
+ await vi.advanceTimersByTimeAsync(0)
+ if (reason === 'closed')
+ f.window.emit('closed')
+ else
+ await vi.advanceTimersByTimeAsync(20000)
+ await expect(opening).resolves.toBe(false)
+ expect(f.ipc.listenerCount(DESKTOP_IPC_CHANNELS.appOpenTargetAck)).toBe(0)
+})
+
+it('does not accept a target acknowledgement after locking or cancellation', async () => {
+ vi.useFakeTimers()
+ const f = fixture()
+ let available = true
+ const opening = f.open({ available: () => available })
+ await vi.advanceTimersByTimeAsync(0)
+ available = false
+ f.ack()
+ await expect(opening).resolves.toBe(false)
+ const controller = new AbortController()
+ const cancelled = f.open({ signal: controller.signal })
+ await vi.advanceTimersByTimeAsync(0)
+ controller.abort()
+ await expect(cancelled).resolves.toBe(false)
+ expect(f.ipc.listenerCount(DESKTOP_IPC_CHANNELS.appOpenTargetAck)).toBe(0)
+})
diff --git a/apps/buddy/electron/main/app/desktopQuitLifecycle.ts b/apps/buddy/electron/main/app/desktopQuitLifecycle.ts
index 6f125b542..dfb4dcc1c 100644
--- a/apps/buddy/electron/main/app/desktopQuitLifecycle.ts
+++ b/apps/buddy/electron/main/app/desktopQuitLifecycle.ts
@@ -1,8 +1,12 @@
+import type { DesktopExitBehavior } from '../../../shared/lifecycle/exitBehavior'
import type { ApplicationEvents } from '../../../shared/observability/ApplicationEvents'
import type { DesktopQuitOptions } from './typing'
interface DesktopQuitLifecycleOptions {
events?: ApplicationEvents
+ getExitBehavior?: () => DesktopExitBehavior
+ closeDesktop?: () => Promise
+ restartDesktop?: () => Promise
confirm: (options: DesktopQuitOptions) => Promise
dispose: () => Promise
quit: (restart: boolean) => void
@@ -20,6 +24,7 @@ export function createDesktopQuitLifecycle(options: DesktopQuitLifecycleOptions)
request(input: DesktopQuitOptions = {}, prepare?: () => Promise<(() => void) | void>): Promise {
if (pending)
return pending
+ const behavior = input.reason || input.restart || prepare ? 'stop_service' : options.getExitBehavior?.() ?? 'stop_service'
pending = Promise.resolve().then(async () => {
options.events?.publish({ event: 'app.quit_requested', level: 'info' })
if (!(await options.confirm(input))) {
@@ -27,6 +32,18 @@ export function createDesktopQuitLifecycle(options: DesktopQuitLifecycleOptions)
return
}
options.events?.publish({ event: 'app.quit_confirmed', level: 'info' })
+ if (behavior === 'keep_service') {
+ if (!options.closeDesktop)
+ throw new Error('DESKTOP_EXIT_SCOPE_UNAVAILABLE')
+ await options.closeDesktop()
+ return
+ }
+ if (input.restart && options.restartDesktop && !prepare) {
+ await options.restartDesktop()
+ quitting = true
+ committed = true
+ return
+ }
const finish = prepare ? await prepare() : undefined
quitting = true
await options.dispose()
diff --git a/apps/buddy/electron/main/app/desktopServiceEntry.ts b/apps/buddy/electron/main/app/desktopServiceEntry.ts
new file mode 100644
index 000000000..17ea6a8b5
--- /dev/null
+++ b/apps/buddy/electron/main/app/desktopServiceEntry.ts
@@ -0,0 +1,105 @@
+import type { LocalServiceLaunchOptions } from '../../../platform/service/launchLocalService'
+import { randomUUID } from 'node:crypto'
+import { homedir, tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import process from 'node:process'
+import { app, dialog } from 'electron'
+import originalFs from 'original-fs'
+import buddyPackage from '../../../package.json'
+import { ensurePrivateDirectoriesSync } from '../../../platform/filesystem/privateDirectories'
+import { resolveBuddyPrivateDirectories } from '../../../platform/native/nativeHost'
+import { launchLocalService } from '../../../platform/service/launchLocalService'
+import { acquireStorageRootLease } from '../../../platform/storage/StorageRootLease'
+import { resolveBuddyRuntimePaths } from '../paths'
+import { INSTALLER_EXIT_ARGUMENT, resolveDesktopLaunchIntent } from '../startupIntent'
+import { requestPersistenceUpgrade } from '../storage/requestPersistenceUpgrade'
+import { prepareStorageBootstrap, readStorageBootstrap } from '../storage/storageBootstrap'
+
+export async function startDesktopServiceEntry(): Promise {
+ if (process.argv.includes('--lexora-platform-host') || process.argv.includes('--lexora-storage-maintenance') || process.env.LEXORA_BUDDY_SERVICE_MODE === 'utility' || (!app.isPackaged && process.env.LEXORA_BUDDY_SERVICE_MODE !== 'daemon'))
+ return false
+ try {
+ const paths = resolveBuddyRuntimePaths({
+ defaultUserData: app.getPath('userData'),
+ desktopName: buddyPackage.desktopName,
+ isPackaged: app.isPackaged,
+ localAppData: process.env.LOCALAPPDATA,
+ lexoraHomeOverride: process.env.LEXORA_HOME,
+ profileOverride: process.env.LEXORA_BUDDY_PROFILE,
+ smokeTest: process.env.LEXORA_DESKTOP_SMOKE_TEST === '1',
+ temporaryDirectory: tmpdir(),
+ userDataOverride: app.commandLine.hasSwitch('user-data-dir') ? app.commandLine.getSwitchValue('user-data-dir') : undefined,
+ userHome: homedir(),
+ userId: process.geteuid?.() ?? 0,
+ xdgCacheHome: process.env.XDG_CACHE_HOME,
+ xdgConfigHome: process.env.XDG_CONFIG_HOME,
+ xdgRuntimeDirectory: process.env.XDG_RUNTIME_DIR,
+ xdgStateHome: process.env.XDG_STATE_HOME,
+ })
+ const storage = readStorageBootstrap(paths.lexoraHome)
+ const previousUserData = app.getPath('userData')
+ const previousSessionData = app.getPath('sessionData')
+ const launcherData = join(storage.bootstrapRoot, 'launcher')
+ ensurePrivateDirectoriesSync([launcherData], resolveBuddyPrivateDirectories({ appPath: app.getAppPath(), resourcesPath: process.resourcesPath, isPackaged: app.isPackaged }))
+ app.setName(paths.appName)
+ app.setPath('userData', launcherData)
+ app.setPath('sessionData', launcherData)
+ const platformArguments = ['ozone-platform', 'password-store', 'user-data-dir', 'disable-gpu', 'disable-setuid-sandbox'].flatMap((name) => {
+ if (!app.commandLine.hasSwitch(name))
+ return []
+ const value = app.commandLine.getSwitchValue(name)
+ return [value ? `--${name}=${value}` : `--${name}`]
+ })
+ const options: LocalServiceLaunchOptions = {
+ releaseFileSystem: originalFs,
+ releaseSetPath: app.isPackaged ? join(process.resourcesPath, 'release-set.json') : join(app.getAppPath(), '.output/release-set.json'),
+ profileRoot: storage.state.activeRoot,
+ defaultRoot: paths.lexoraHome,
+ profile: paths.profile,
+ hostExecutable: process.execPath,
+ hostArguments: [...platformArguments, ...app.isPackaged ? [] : [app.getAppPath()]],
+ leaseDirectory: join(paths.profile === 'test' ? dirname(paths.lexoraHome) : homedir(), '.lexora-locations', 'locks'),
+ storageAuthority: 'sqlite',
+ }
+ let connection = await launchLocalService({ ...options, startIfMissing: false })
+ if (!connection && !process.argv.includes(INSTALLER_EXIT_ARGUMENT)) {
+ const release = acquireStorageRootLease(storage.state.activeRoot, options.leaseDirectory, resolveBuddyPrivateDirectories({ appPath: app.getAppPath(), resourcesPath: process.resourcesPath, isPackaged: app.isPackaged }))
+ let maintenance: boolean
+ try {
+ const prepared = prepareStorageBootstrap(paths, resolveBuddyPrivateDirectories({ appPath: app.getAppPath(), resourcesPath: process.resourcesPath, isPackaged: app.isPackaged }))
+ await requestPersistenceUpgrade(prepared)
+ maintenance = !!(await prepared.store.read()).pending
+ }
+ finally { release() }
+ if (maintenance) {
+ app.setPath('userData', previousUserData)
+ app.setPath('sessionData', previousSessionData)
+ return false
+ }
+ connection = await launchLocalService(options)
+ }
+ if (!connection) {
+ app.exit(0)
+ return true
+ }
+ try {
+ if (process.argv.includes(INSTALLER_EXIT_ARGUMENT)) {
+ await connection.peer.request('service.stop', { expectedServiceInstanceId: connection.discovery.serviceInstanceId, commandId: randomUUID(), reason: 'maintenance' })
+ await connection.waitForExit()
+ }
+ else if (resolveDesktopLaunchIntent(process.argv, process.platform === 'darwin' && app.getLoginItemSettings().wasOpenedAtLogin) === 'foreground') {
+ await connection.peer.request('service.openDesktop', { expectedServiceInstanceId: connection.discovery.serviceInstanceId, intent: { kind: 'tasks' } })
+ }
+ }
+ finally { connection.peer.close(new Error('SERVICE_LAUNCHER_FINISHED')) }
+ app.exit(0)
+ }
+ catch (error) {
+ await app.whenReady()
+ const code = error instanceof Error && /^[A-Z_]+$/.test(error.message) ? error.message : 'SERVICE_START_FAILED'
+ process.stderr.write(`${code}\n`)
+ dialog.showErrorBox('Lexora', `无法启动后台服务。请保留当前数据并重试。\n${code}`)
+ app.exit(1)
+ }
+ return true
+}
diff --git a/apps/buddy/electron/main/app/environment.ts b/apps/buddy/electron/main/app/environment.ts
index 481940000..8f1a5429e 100644
--- a/apps/buddy/electron/main/app/environment.ts
+++ b/apps/buddy/electron/main/app/environment.ts
@@ -1,5 +1,5 @@
import type { DesktopEnvironment } from './typing'
-import { mkdirSync } from 'node:fs'
+import { mkdirSync, realpathSync } from 'node:fs'
import { homedir, tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import process from 'node:process'
@@ -18,6 +18,7 @@ import { resolveBuddyRuntimePaths } from '../paths'
import { desktopHosts } from '../platform/desktopHost'
import { rendererSchemePrivileges } from '../rendererProtocol'
import { resolveDesktopLaunchIntent } from '../startupIntent'
+import { requestPersistenceUpgrade } from '../storage/requestPersistenceUpgrade'
import { prepareStorageBootstrap, readStorageBootstrap, unifiedStoragePaths } from '../storage/storageBootstrap'
import { fileIconSchemePrivileges } from '../themes/registerFileIconIpc'
import { themeSchemePrivileges } from '../themes/registerThemeIpc'
@@ -27,7 +28,7 @@ import { DesktopStartup } from './DesktopStartup'
import { checkDesktopDirectories, criticalDesktopDirectories, DesktopInstanceLockUnavailable, prepareDesktopPrivateStorage } from './desktopStorage'
import { observeStartupDiagnostics } from './startupDiagnostics'
-export function prepareDesktopEnvironment(): DesktopEnvironment {
+export async function prepareDesktopEnvironment(platformHost?: DesktopEnvironment['platformHost']): Promise {
if (currentPlatform.id === OPERATING_SYSTEM.Linux)
app.commandLine.appendSwitch('enable-speech-dispatcher')
const desktopHost = desktopHosts[currentPlatform.id]
@@ -63,8 +64,27 @@ export function prepareDesktopEnvironment(): DesktopEnvironment {
if (!app.requestSingleInstanceLock({ executablePath: process.execPath }))
throw new DesktopInstanceLockUnavailable(legacyPaths.userData)
const storage = prepareStorageBootstrap(legacyPaths, privateDirectoriesExecutable())
- const releaseStorage = acquireStorageRootLease(storage.state.activeRoot, storage.leaseDirectory, storage.privateDirectoriesExecutable)
- app.once('will-quit', releaseStorage)
+ if (platformHost) {
+ if (platformHost.peer.closed || storage.state.pending || realpathSync(storage.state.activeRoot) !== realpathSync(platformHost.bootstrap.profileRoot) || legacyPaths.profile !== platformHost.bootstrap.profile)
+ throw new Error('PLATFORM_HOST_PROFILE_CHANGED')
+ }
+ else if (!storage.state.pending) {
+ const releaseStorage = acquireStorageRootLease(storage.state.activeRoot, storage.leaseDirectory, storage.privateDirectoriesExecutable)
+ try {
+ if (!process.argv.includes('--lexora-storage-maintenance') && process.env.LEXORA_BUDDY_STORAGE_AUTHORITY === 'sqlite') {
+ await requestPersistenceUpgrade(storage)
+ storage.state = await storage.store.read()
+ }
+ }
+ catch (error) {
+ releaseStorage()
+ throw error
+ }
+ if (storage.state.pending)
+ releaseStorage()
+ else
+ app.once('will-quit', releaseStorage)
+ }
const paths = unifiedStoragePaths(legacyPaths, storage.state.activeRoot)
if (process.env.LEXORA_BUDDY_PET_STATE_PATH)
paths.nativePetState = legacyPaths.nativePetState
@@ -84,6 +104,7 @@ export function prepareDesktopEnvironment(): DesktopEnvironment {
events.subscribe(event => diagnostics.record({ ...event, scope: 'desktop' }))
observeStartupDiagnostics(startup, events)
return {
+ ...(platformHost ? { platformHost } : {}),
diagnostics,
events,
startup,
@@ -131,9 +152,7 @@ export function initializeDesktopEnvironment(environment: DesktopEnvironment): v
environment.diagnostics.record({ scope: 'desktop', level: 'warn', event: 'crash_reporter.unavailable', ...readDiagnosticError(error) })
}
}
- bootstrapStep('register_protocols', () => {
- protocol.registerSchemesAsPrivileged([...attachmentSchemePrivileges, rendererSchemePrivileges, extensionSchemePrivileges, fileIconSchemePrivileges, themeSchemePrivileges])
- })
+ registerDesktopSchemes()
bootstrapStep('desktop_identity', () => desktopHosts[currentPlatform.id].setIdentity?.(paths.desktopName))
}
@@ -163,3 +182,13 @@ export async function prepareDesktopReady(environment: DesktopEnvironment): Prom
app.setAppUserModelId(paths.desktopName)
Menu.setApplicationMenu(null)
}
+
+let desktopSchemesRegistered = false
+export function registerDesktopSchemes(): void {
+ if (desktopSchemesRegistered)
+ return
+ bootstrapStep('register_protocols', () => {
+ protocol.registerSchemesAsPrivileged([...attachmentSchemePrivileges, rendererSchemePrivileges, extensionSchemePrivileges, fileIconSchemePrivileges, themeSchemePrivileges])
+ })
+ desktopSchemesRegistered = true
+}
diff --git a/apps/buddy/electron/main/app/requestDesktopTarget.ts b/apps/buddy/electron/main/app/requestDesktopTarget.ts
new file mode 100644
index 000000000..0905a1afd
--- /dev/null
+++ b/apps/buddy/electron/main/app/requestDesktopTarget.ts
@@ -0,0 +1,78 @@
+import type { BrowserWindow, IpcMain, IpcMainEvent } from 'electron'
+import type { z } from 'zod'
+import type { desktopOpenIntentSchema } from '../../../shared/service/localServiceProtocol'
+import type { DesktopStartup } from './DesktopStartup'
+import { randomUUID } from 'node:crypto'
+import { ipcMain } from 'electron'
+import { desktopTargetAckSchema } from '../../../shared/service/localServiceProtocol'
+import { DESKTOP_IPC_CHANNELS } from '../../shared/desktopApi'
+
+export async function requestDesktopTarget(window: BrowserWindow, startup: DesktopStartup, intent: z.infer, ipc: Pick = ipcMain, options: { signal?: AbortSignal, available?: () => boolean } = {}): Promise {
+ const deadline = Date.now() + 20000
+ const available = () => !options.signal?.aborted && (options.available?.() ?? true)
+ if (!available())
+ return false
+ await new Promise((resolve, reject) => {
+ let stop = () => {}
+ let timeout: ReturnType
+ function close() {
+ finish(new Error('DESKTOP_CLOSED'))
+ }
+ function finish(error?: Error) {
+ clearTimeout(timeout)
+ stop()
+ window.off('closed', close)
+ options.signal?.removeEventListener('abort', close)
+ if (error)
+ reject(error)
+ else resolve()
+ }
+ timeout = setTimeout(() => finish(new Error('DESKTOP_RENDERER_NOT_READY')), 20000)
+ const check = () => {
+ const state = startup.state
+ if (window.isDestroyed())
+ close()
+ else if (state.status === 'ready')
+ finish()
+ else if (state.status === 'failed' || state.status === 'stopped')
+ finish(new Error('DESKTOP_RENDERER_NOT_READY'))
+ }
+ stop = startup.onStateChange(check)
+ window.once('closed', close)
+ options.signal?.addEventListener('abort', close, { once: true })
+ check()
+ })
+ if (!available() || window.isDestroyed() || window.webContents.isDestroyed())
+ return false
+ const requestId = randomUUID()
+ return new Promise((resolve) => {
+ let timeout: ReturnType
+ function finish(opened: boolean) {
+ clearTimeout(timeout)
+ ipc.off(DESKTOP_IPC_CHANNELS.appOpenTargetAck, receive)
+ window.off('closed', close)
+ options.signal?.removeEventListener('abort', close)
+ resolve(opened)
+ }
+ function close() {
+ finish(false)
+ }
+ function receive(event: IpcMainEvent, raw: unknown) {
+ if (window.isDestroyed() || event.sender !== window.webContents || event.senderFrame !== window.webContents.mainFrame)
+ return
+ const result = desktopTargetAckSchema.safeParse(raw)
+ if (result.success && result.data.requestId === requestId)
+ finish(available() && result.data.opened)
+ }
+ timeout = setTimeout(finish, Math.max(0, deadline - Date.now()), false)
+ ipc.on(DESKTOP_IPC_CHANNELS.appOpenTargetAck, receive)
+ window.once('closed', close)
+ options.signal?.addEventListener('abort', close, { once: true })
+ try {
+ window.webContents.send(DESKTOP_IPC_CHANNELS.appOpenTargetRequest, { requestId, intent })
+ }
+ catch {
+ finish(false)
+ }
+ })
+}
diff --git a/apps/buddy/electron/main/app/typing.ts b/apps/buddy/electron/main/app/typing.ts
index 2369ff12a..96b0e9c85 100644
--- a/apps/buddy/electron/main/app/typing.ts
+++ b/apps/buddy/electron/main/app/typing.ts
@@ -3,11 +3,13 @@ import type { ApplicationEvents } from '../../../shared/observability/Applicatio
import type { LexoraConfig } from '../../shared/desktopApi'
import type { DesktopDiagnosticLogger } from '../desktopDiagnostics'
import type { BuddyRuntimePaths } from '../paths'
+import type { PlatformHostConnection } from '../runtime/platformHostBootstrap'
import type { DesktopLaunchIntent } from '../startupIntent'
import type { DesktopStorage } from '../storage/storageBootstrap'
import type { DesktopStartup } from './DesktopStartup'
export interface DesktopEnvironment {
+ platformHost?: PlatformHostConnection
events: ApplicationEvents
startup: DesktopStartup
diagnostics: DesktopDiagnosticLogger
@@ -22,7 +24,7 @@ export interface DesktopEnvironment {
}
export interface DesktopQuitOptions {
- reason?: 'installation'
+ reason?: 'installation' | 'session_end' | 'service_stop'
discardDraftsOnFailure?: boolean
restart?: boolean
}
diff --git a/apps/buddy/electron/main/attachmentProtocol.ts b/apps/buddy/electron/main/attachmentProtocol.ts
index 4e221689d..f1f97f1de 100644
--- a/apps/buddy/electron/main/attachmentProtocol.ts
+++ b/apps/buddy/electron/main/attachmentProtocol.ts
@@ -1,4 +1,5 @@
import type { BuddyServiceSupervisor } from './runtime/BuddyServiceSupervisor'
+import { Buffer } from 'node:buffer'
import { readFile } from 'node:fs/promises'
import { dirname } from 'node:path'
import process from 'node:process'
@@ -8,6 +9,7 @@ import { resolveBuddyFileReader } from '../../platform/native/nativeHost'
import { artifactsRequestSchemas, artifactsResponseSchemas } from '../../shared/artifacts/artifactApi'
import { attachmentsRequestSchemas } from '../../shared/conversation/attachmentApi'
import { composerResourcesRpc } from '../../shared/conversation/composerApi'
+import { attachmentPreviewBytesSchema } from '../../shared/runtime/attachmentHostProtocol'
import { handleMediaRequest } from './mediaProtocol'
import { resolveDevelopmentRendererUrl } from './security/navigationPolicy'
@@ -20,7 +22,7 @@ export const attachmentSchemePrivileges: Electron.CustomScheme[] = [ATTACHMENT_P
privileges: { secure: true, standard: true, stream: true, supportFetchAPI: true, corsEnabled: scheme === ARTIFACT_PROTOCOL || scheme === ATTACHMENT_PROTOCOL },
}))
-export function installAttachmentProtocol(runtime: BuddyServiceSupervisor): () => void {
+export function installAttachmentProtocol(runtime: Pick): () => void {
const fileReader = resolveBuddyFileReader({ appPath: app.getAppPath(), isPackaged: app.isPackaged, resourcesPath: process.resourcesPath })
const developmentUrl = resolveDevelopmentRendererUrl(process.env.ELECTRON_RENDERER_URL, app.isPackaged)
const rendererOrigin = developmentUrl ? new URL(developmentUrl).origin : 'lexora-app://renderer'
@@ -70,6 +72,10 @@ export function installAttachmentProtocol(runtime: BuddyServiceSupervisor): () =
try {
const input = schema.parse({ [idKey]: id })
+ if (scheme === ATTACHMENT_PROTOCOL) {
+ const preview = attachmentPreviewBytesSchema.parse(await runtime.request('attachments.readPreview', input))
+ return new Response(Buffer.from(preview.data, 'base64'), { headers: { 'cache-control': 'private, max-age=300', 'content-type': preview.mimeType, 'x-content-type-options': 'nosniff' } })
+ }
const preview = artifactsResponseSchemas.artifactPreview.parse(
await runtime.request(method, input),
)
diff --git a/apps/buddy/electron/main/browser/BrowserHost.ts b/apps/buddy/electron/main/browser/BrowserHost.ts
index 66d23016e..934c31296 100644
--- a/apps/buddy/electron/main/browser/BrowserHost.ts
+++ b/apps/buddy/electron/main/browser/BrowserHost.ts
@@ -15,7 +15,6 @@ import type {
BrowserWaitSpec,
} from '../../../shared/browser'
import type {
- DesktopBrowserError,
DesktopBrowserGuestDescriptor,
DesktopBrowserProfileMode,
DesktopBrowserSetSurfaceInput,
@@ -24,6 +23,7 @@ import type {
import type { BrowserLocateElementInput, BrowserPickResult } from '../../../shared/browser/browserSelection'
import type { NetworkAuthorizer } from '../../../shared/network/networkAuthorization'
import type { BrowserHostChange, BrowserHostFact } from './BrowserHostEvents'
+import type { BrowserLocalFileGrant } from './BrowserNavigation'
import type { BrowserPage } from './BrowserPageSession'
import type { BrowserSessionTeardownReason } from './BrowserSessionRegistry'
import type { SemanticBrowserDriver, SemanticBrowserScreenshot, SemanticBrowserScreenshotReference } from './SemanticBrowserDriver'
@@ -32,11 +32,9 @@ import { BROWSER_WAIT_DEFAULT_QUIET_MS, browserAgentTabId } from '../../../share
import { Emitter } from '../../../shared/events/Emitter'
import { copyEventSnapshot } from '../../../shared/events/eventSnapshot'
import { BrowserHostError } from './BrowserHostError'
+import { BrowserNavigation } from './BrowserNavigation'
import { BrowserOperationGuard } from './BrowserOperationGuard'
import { BrowserPageSession, snapshot } from './BrowserPageSession'
-import {
- BrowserSecurityPolicyError,
-} from './BrowserSecurityPolicy'
import {
BrowserSessionRegistry,
BrowserSessionRegistryError,
@@ -47,8 +45,6 @@ import {
export const BROWSER_DEFAULT_PARTITION = 'persist:buddy-browser-default-v1'
const BROWSER_GUEST_ATTACH_TIMEOUT_MS = 10_000
-const BROWSER_NAVIGATION_WAIT_TIMEOUT_MS = 30_000
-const BROWSER_FAILED_NAVIGATION_SETTLE_MS = 200
const BROWSER_NAVIGATION_SETTLE_TIMEOUT_MS = 15_000
const BROWSER_ACTION_NAVIGATION_DETECTION_MS = 50
const BROWSER_WAIT_STATE_INTERVAL_MS = 50
@@ -64,17 +60,12 @@ interface BrowserHostOptions {
createPage?: (descriptor: DesktopBrowserGuestDescriptor) => BrowserPage
requestGuestAttachment?: () => void
revokeSession?: (sessionId: string) => void
- window: BrowserWindow
+ window?: BrowserWindow
}
type BrowserWaitAction = Extract
type BrowserWaitRequest = BrowserWaitAction | BrowserWaitSpec
-export interface BrowserLocalFileGrant {
- entryPath: string
- rootPath: string
-}
-
export interface BrowserScreenshotReadInput extends SemanticBrowserScreenshotReference {
owner?: BrowserPageOwner
pageId: string
@@ -103,11 +94,11 @@ export class BrowserHost {
readonly #createId: () => string
readonly #createPage: ((descriptor: DesktopBrowserGuestDescriptor) => BrowserPage) | null
readonly #evictedConversationIds = new Set()
- readonly #failedNavigationTargets = new WeakMap()
+ readonly #navigation: BrowserNavigation
readonly #requestGuestAttachment: () => void
readonly #revokeSession: (sessionId: string) => void
readonly #sessions: BrowserSessionRegistry
- readonly #window: BrowserWindow
+ readonly #window: BrowserWindow | undefined
readonly #windowClosedListener: () => void
readonly #willAttachWebviewListener: (
event: ElectronEvent,
@@ -133,13 +124,23 @@ export class BrowserHost {
createId: this.#createId,
maxSessions: options.maxSessions ?? 16,
})
+ this.#navigation = new BrowserNavigation({
+ sessions: this.#sessions,
+ operations: this.#operations,
+ requireSession: id => this.#requireSession(id),
+ waitForPage: session => this.#waitForPage(session),
+ assertCurrentPage: (session, pageId, operation) => this.#assertCurrentPage(session, pageId, operation),
+ notFound: id => this.#sessionNotFound(id),
+ onDidChange: this.onDidChange,
+ recordTiming: (session, phase, startedAt) => this.#recordTiming(session, phase, startedAt),
+ })
this.#window = options.window
this.#windowClosedListener = () => this.dispose()
this.#willAttachWebviewListener = (event, webPreferences, params) => {
this.#configureGuestAttachment(event, webPreferences, params)
}
- this.#window.once('closed', this.#windowClosedListener)
- this.#window.webContents.on('will-attach-webview', this.#willAttachWebviewListener)
+ this.#window?.once('closed', this.#windowClosedListener)
+ this.#window?.webContents.on('will-attach-webview', this.#willAttachWebviewListener)
}
get isDisposed(): boolean {
@@ -296,7 +297,7 @@ export class BrowserHost {
listGuests(): DesktopBrowserGuestDescriptor[] {
this.#assertActive()
- return this.#sessions.values().map(session => ({ ...session.descriptor }))
+ return this.#sessions.values().map(session => ({ ...session.descriptor, pageId: session.state.pageId }))
}
attachGuest(sessionId: string, page: BrowserPage): void {
@@ -493,6 +494,7 @@ export class BrowserHost {
this.#operations.assertCanMutate()
this.assertOwner(input.sessionId, input.owner)
const queuedSession = this.#requireSession(input.sessionId)
+ this.assertControl(input)
const predecessor = queuedSession.actionTail
let releaseQueue!: () => void
queuedSession.actionTail = new Promise((resolve) => {
@@ -639,376 +641,16 @@ export class BrowserHost {
}
}
- async navigate(sessionId: string, rawUrl: string, readiness: 'load' | 'document-ready' = 'load', assertControl: () => void = () => {}): Promise {
- assertControl()
- this.#operations.assertCanMutate()
- const session = this.#requireSession(sessionId)
- const startedAt = performance.now()
- const navigationSequence = this.#beginPageAction(session)
- let url: string
- try {
- await this.#waitForPage(session)
- this.#requireSession(sessionId)
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
- this.#recordTiming(session, 'guest_ready', startedAt)
- this.#assertNavigationControl(session, navigationSequence, assertControl)
- this.#operations.assertCanMutate()
- const authorizationStartedAt = performance.now()
- url = await session.securityPolicy?.authorizeNavigation(rawUrl) ?? ''
- this.#recordTiming(session, 'authorized', authorizationStartedAt)
- }
- catch (error) {
- this.#requireSession(sessionId)
- if (error instanceof BrowserHostError && error.code === 'BROWSER_CONTROL_REQUIRED')
- throw error
- if (session.state.error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
- throw new BrowserHostError('BROWSER_PAGE_UNRESPONSIVE', session.state.error.message)
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
- this.#failedNavigationTargets.set(session, rawUrl)
- const failure: DesktopBrowserError = error instanceof BrowserSecurityPolicyError
- ? { code: error.code, message: error.message, reason: error.reason }
- : { code: 'BROWSER_PAGE_FAILED', message: browserLoadErrorMessage(error) }
- session.state.error = failure
- session.state.status = 'error'
- this.#finishPageAction(session, navigationSequence)
- this.#publish(session)
- throw error instanceof BrowserHostError
- ? error
- : new BrowserHostError(failure.code, failure.message, failure.reason)
- }
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
-
- this.#assertNavigationControl(session, navigationSequence, assertControl)
- return this.#loadPage(sessionId, session, navigationSequence, url, readiness, assertControl)
+ navigate(sessionId: string, rawUrl: string, readiness: 'load' | 'document-ready' = 'load', assertControl: () => void = () => {}): Promise {
+ return this.#navigation.navigate(sessionId, rawUrl, readiness, assertControl)
}
- async #loadPage(
- sessionId: string,
- session: BrowserPageSession,
- navigationSequence: number,
- url: string,
- readiness: 'load' | 'document-ready',
- assertControl: () => void,
- ): Promise {
- return session.runWhileActive(async () => {
- const startedAt = performance.now()
- const page = session.requirePage()
- const pageId = session.state.pageId
- let hasCommittedDocument = false
- let resolveWait!: (state: DesktopBrowserState) => void
- let rejectWait!: (error: unknown) => void
- const waiting = new Promise((resolve, reject) => {
- resolveWait = resolve
- rejectWait = reject
- })
- const checkInterrupted = (): boolean => {
- try {
- this.#requireSession(sessionId)
- this.#assertCurrentPage(session, pageId, 'while waiting for navigation')
- assertControl()
- if (!this.#shouldContinuePageAction(session, navigationSequence)) {
- resolveWait(snapshot(session.state))
- return true
- }
- const error = session.state.error
- if (error?.code === 'BROWSER_PAGE_CRASHED' || error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
- throw new BrowserHostError(error.code, error.message, error.reason)
- return false
- }
- catch (error) {
- rejectWait(error)
- return true
- }
- }
- const onDocumentCommitted = () => {
- if (this.#shouldContinuePageAction(session, navigationSequence))
- hasCommittedDocument = true
- }
- const onDocumentReady = () => {
- if (checkInterrupted() || readiness !== 'document-ready' || session.mainFrameCommitSequence !== navigationSequence)
- return
- this.#recordTiming(session, 'document_ready', startedAt)
- resolveWait(snapshot(session.state))
- }
- const subscription = this.onDidChange((change) => {
- if ((change.kind === 'state' || change.kind === 'session') && change.state.sessionId === sessionId)
- checkInterrupted()
- })
- page.on('did-navigate', onDocumentCommitted)
- page.on('dom-ready', onDocumentReady)
- const timer = setTimeout(() => {
- if (checkInterrupted())
- return
- const failure = session.state.error
- if (failure) {
- rejectWait(new BrowserHostError(failure.code, failure.message, failure.reason))
- return
- }
- if (hasCommittedDocument && session.mainFrameCommitSequence === navigationSequence) {
- resolveWait(snapshot(session.state))
- return
- }
- const message = 'Browser navigation did not commit before its deadline'
- rejectWait(new BrowserHostError('BROWSER_PAGE_FAILED', message))
- session.navigationSequence += 1
- this.#finishPageAction(session, navigationSequence)
- this.#failedNavigationTargets.set(session, url)
- session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
- session.state.status = 'error'
- try {
- page.stop()
- }
- catch {}
- this.#publish(session)
- }, BROWSER_NAVIGATION_WAIT_TIMEOUT_MS)
- try {
- return await Promise.race([
- waiting,
- this.#loadPageToCompletion(sessionId, session, navigationSequence, url, assertControl),
- ])
- }
- finally {
- clearTimeout(timer)
- subscription.dispose()
- page.off('did-navigate', onDocumentCommitted)
- page.off('dom-ready', onDocumentReady)
- }
- }, { timeoutMs: null })
- }
-
- async #loadPageToCompletion(
- sessionId: string,
- session: BrowserPageSession,
- navigationSequence: number,
- url: string,
- assertControl: () => void,
- ): Promise {
- const startedAt = performance.now()
- session.state.url = url
- this.#publish(session)
- try {
- const page = await this.#waitForPage(session)
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
- this.#assertNavigationControl(session, navigationSequence, assertControl)
- await page.loadURL(url)
- this.#recordTiming(session, 'load_complete', startedAt)
- if (!this.#sessions.get(sessionId))
- throw this.#sessionNotFound(sessionId)
- if (!this.#isCurrentPageAction(session, navigationSequence))
- return snapshot(session.state)
- session.stoppedNavigationSequence = null
- this.#finishPageAction(session, navigationSequence)
- session.removeBootstrapHistory()
- session.refreshPageState()
- session.state.status = 'ready'
- this.#publish(session)
- return snapshot(session.state)
- }
- catch (error) {
- if (error instanceof BrowserHostError)
- throw error
- if (!this.#sessions.get(sessionId))
- throw this.#sessionNotFound(sessionId)
- if (!this.#isCurrentPageAction(session, navigationSequence))
- return snapshot(session.state)
- if (session.stoppedNavigationSequence === navigationSequence) {
- session.stoppedNavigationSequence = null
- this.#finishPageAction(session, navigationSequence)
- session.state.error = null
- session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
- session.refreshPageState()
- this.#publish(session)
- return snapshot(session.state)
- }
- return this.#waitForNavigationSettlement(
- sessionId,
- session,
- navigationSequence,
- error,
- )
- }
- }
-
- async #waitForNavigationSettlement(
- sessionId: string,
- session: BrowserPageSession,
- navigationSequence: number,
- loadError: unknown,
- ): Promise {
- const startedAt = Date.now()
- const deadline = startedAt + BROWSER_NAVIGATION_SETTLE_TIMEOUT_MS
- const isAbortedLoad = isNavigationAborted(loadError)
- const loadFailureDeadline = isAbortedLoad
- ? null
- : Math.min(deadline, startedAt + BROWSER_FAILED_NAVIGATION_SETTLE_MS)
- let pageFailureDeadline: number | null = null
- while (true) {
- if (this.#sessions.get(sessionId) !== session)
- throw this.#sessionNotFound(sessionId)
- if (!this.#isCurrentPageAction(session, navigationSequence))
- return snapshot(session.state)
- if (session.stoppedNavigationSequence === navigationSequence) {
- session.stoppedNavigationSequence = null
- this.#finishPageAction(session, navigationSequence)
- session.state.error = null
- session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
- session.refreshPageState()
- this.#publish(session)
- return snapshot(session.state)
- }
- const hasReplacementCommit = session.mainFrameCommitSequence === navigationSequence
- const pageFailure = session.state.error
- const now = Date.now()
- if (pageFailure) {
- pageFailureDeadline ??= Math.min(
- deadline,
- now + BROWSER_FAILED_NAVIGATION_SETTLE_MS,
- )
- }
- else {
- pageFailureDeadline = null
- }
- if (
- pageFailure
- && (
- session.activeNavigationSequence !== navigationSequence
- || now >= (pageFailureDeadline ?? deadline)
- )
- ) {
- this.#finishPageAction(session, navigationSequence)
- throw new BrowserHostError(
- pageFailure.code,
- pageFailure.message,
- pageFailure.reason ?? null,
- )
- }
- if (
- session.state.status === 'ready'
- && (isAbortedLoad || hasReplacementCommit)
- ) {
- return snapshot(session.state)
- }
- if (loadFailureDeadline !== null && now >= loadFailureDeadline) {
- const message = browserLoadErrorMessage(loadError)
- this.#finishPageAction(session, navigationSequence)
- session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
- session.state.status = 'error'
- this.#publish(session)
- throw new BrowserHostError('BROWSER_PAGE_FAILED', message)
- }
- const remainingMs = Math.min(
- pageFailureDeadline ?? deadline,
- loadFailureDeadline ?? deadline,
- ) - now
- if (remainingMs <= 0) {
- const message = 'Browser navigation did not settle after the initial load was replaced'
- this.#finishPageAction(session, navigationSequence)
- session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
- session.state.status = 'error'
- this.#publish(session)
- throw new BrowserHostError('BROWSER_PAGE_FAILED', message)
- }
- await wait(Math.min(remainingMs, 50))
- }
- }
-
- goBack(sessionId: string): void {
- this.#operations.assertCanMutate()
- const session = this.#requireSession(sessionId)
- const history = session.requirePage().navigationHistory
- if (!history.canGoBack())
- return
- this.#beginPageAction(session)
- history.goBack()
- }
-
- goForward(sessionId: string): void {
- this.#operations.assertCanMutate()
- const session = this.#requireSession(sessionId)
- const history = session.requirePage().navigationHistory
- if (!history.canGoForward())
- return
- this.#beginPageAction(session)
- history.goForward()
- }
-
- async reload(sessionId: string, assertControl: () => void = () => {}): Promise {
- assertControl()
- this.#operations.assertCanMutate()
- const session = this.#requireSession(sessionId)
- const failedTarget = this.#failedNavigationTargets.get(session)
- if (session.state.status === 'error' && failedTarget !== undefined) {
- await this.navigate(sessionId, failedTarget, 'load', assertControl)
- return
- }
- if (session.state.url === 'about:blank')
- return
- this.#beginPageAction(session)
- session.requirePage().reload()
- }
-
- stop(sessionId: string): void {
- const session = this.#requireSession(sessionId)
- if (session.state.status !== 'loading')
- return
- session.stoppedNavigationSequence = session.navigationSequence
- this.#finishPageAction(session, session.navigationSequence)
- if (session.page && !session.page.isDestroyed())
- session.page.stop()
- session.refreshPageState()
- session.state.error = null
- session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
- this.#publish(session)
- }
-
- async openLocalFile(
- sessionId: string,
- grant: BrowserLocalFileGrant,
- readiness: 'load' | 'document-ready' = 'load',
- assertControl: () => void = () => {},
- ): Promise {
- assertControl()
- this.#operations.assertCanMutate()
- const session = this.#requireSession(sessionId)
- const startedAt = performance.now()
- await this.#waitForPage(session)
- this.#recordTiming(session, 'guest_ready', startedAt)
- this.#operations.assertCanMutate()
- const navigationSequence = this.#beginPageAction(session)
- const authorizationStartedAt = performance.now()
- let url: string
- try {
- url = await session.securityPolicy?.authorizeLocalFile(
- grant.entryPath,
- grant.rootPath,
- ) ?? ''
- this.#recordTiming(session, 'authorized', authorizationStartedAt)
- }
- catch (error) {
- if (session.state.error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
- throw new BrowserHostError('BROWSER_PAGE_UNRESPONSIVE', session.state.error.message)
- if (!(error instanceof BrowserSecurityPolicyError))
- throw error
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
- session.state.error = {
- code: error.code,
- message: error.message,
- reason: error.reason,
- }
- session.state.status = 'error'
- this.#finishPageAction(session, navigationSequence)
- this.#publish(session)
- throw new BrowserHostError(error.code, error.message, error.reason)
- }
- if (!this.#shouldContinuePageAction(session, navigationSequence))
- return snapshot(session.state)
- this.#assertNavigationControl(session, navigationSequence, assertControl)
- return this.#loadPage(sessionId, session, navigationSequence, url, readiness, assertControl)
+ goBack(sessionId: string): void { this.#navigation.goBack(sessionId) }
+ goForward(sessionId: string): void { this.#navigation.goForward(sessionId) }
+ reload(sessionId: string, assertControl: () => void = () => {}): Promise { return this.#navigation.reload(sessionId, assertControl) }
+ stop(sessionId: string): void { this.#navigation.stop(sessionId) }
+ openLocalFile(sessionId: string, grant: BrowserLocalFileGrant, readiness: 'load' | 'document-ready' = 'load', assertControl: () => void = () => {}): Promise {
+ return this.#navigation.openLocalFile(sessionId, grant, readiness, assertControl)
}
async #replaceSessionProfile(
@@ -1230,8 +872,8 @@ export class BrowserHost {
if (this.#disposed)
return
this.#disposed = true
- this.#window.off('closed', this.#windowClosedListener)
- this.#window.webContents.off('will-attach-webview', this.#willAttachWebviewListener)
+ this.#window?.off('closed', this.#windowClosedListener)
+ this.#window?.webContents.off('will-attach-webview', this.#willAttachWebviewListener)
const pending = this.#sessions.values().map(session => session.actionTail)
this.#sessions.dispose()
this.#evictedConversationIds.clear()
@@ -1306,7 +948,7 @@ export class BrowserHost {
session.state.status = 'error'
}
session.state.visible = false
- this.#failedNavigationTargets.delete(session)
+ this.#navigation.release(session)
this.#revokeSession(session.state.sessionId)
session.releasePage()
const cleanup = session.whenIdle()
@@ -1327,49 +969,6 @@ export class BrowserHost {
}
}
- #beginPageAction(session: BrowserPageSession): number {
- this.#failedNavigationTargets.delete(session)
- this.#sessions.touch(session.state.sessionId)
- session.navigationSequence += 1
- session.activeNavigationSequence = session.navigationSequence
- session.semanticDriver?.invalidateDocument()
- session.stoppedNavigationSequence = null
- session.state.error = null
- session.state.status = 'loading'
- this.#publish(session)
- return session.navigationSequence
- }
-
- #isCurrentPageAction(session: BrowserPageSession, navigationSequence: number): boolean {
- return session.navigationSequence === navigationSequence
- }
-
- #finishPageAction(session: BrowserPageSession, navigationSequence: number): void {
- if (session.activeNavigationSequence === navigationSequence)
- session.activeNavigationSequence = null
- }
-
- #assertNavigationControl(session: BrowserPageSession, navigationSequence: number, assertControl: () => void): void {
- try {
- assertControl()
- }
- catch (error) {
- if (this.#shouldContinuePageAction(session, navigationSequence)) {
- this.#finishPageAction(session, navigationSequence)
- session.refreshPageState()
- session.state.error = null
- session.state.status = session.page?.isLoading() ? 'loading' : session.state.url === 'about:blank' ? 'idle' : 'ready'
- this.#publish(session)
- }
- throw error
- }
- }
-
- #shouldContinuePageAction(session: BrowserPageSession, navigationSequence: number): boolean {
- return this.#isCurrentPageAction(session, navigationSequence)
- && session.stoppedNavigationSequence !== navigationSequence
- }
-
#publish(session: BrowserPageSession): void {
session.publish()
}
@@ -1510,22 +1109,6 @@ export class BrowserHost {
}
}
-function isNavigationAborted(error: unknown): boolean {
- if (!error || typeof error !== 'object')
- return false
- const candidate = error as { code?: unknown, errno?: unknown }
- if (candidate.code === 'ERR_ABORTED' || candidate.errno === -3)
- return true
- return error instanceof Error
- && /^ERR_ABORTED(?: \(-3\))?(?: |$)/.test(error.message)
-}
-
-function browserLoadErrorMessage(error: unknown): string {
- if (error instanceof Error && error.message.trim())
- return error.message.slice(0, 1_024)
- return 'Browser page failed to load'
-}
-
function swallowDriverProbeFailure(error: unknown): false {
if (error instanceof SemanticBrowserDriverError && error.code === 'BROWSER_PAGE_FAILED')
return false
@@ -1555,3 +1138,5 @@ function wait(durationMs: number): Promise {
}
export { BrowserHostError } from './BrowserHostError'
+
+export type { BrowserLocalFileGrant } from './BrowserNavigation'
diff --git a/apps/buddy/electron/main/browser/BrowserIntegration.ts b/apps/buddy/electron/main/browser/BrowserIntegration.ts
index 5a365f048..b3f5c1c84 100644
--- a/apps/buddy/electron/main/browser/BrowserIntegration.ts
+++ b/apps/buddy/electron/main/browser/BrowserIntegration.ts
@@ -1,5 +1,6 @@
import type { BrowserWindow } from 'electron'
import type { LocalEndpoint } from '../../../platform/ipc/localTransport'
+import type { DesktopBrowserPresentationInput } from '../../../shared/browser/browserDesktopApi'
import type { BrowserPreferences } from '../../../shared/browser/browserPreferences'
import type { ApplicationDiagnosticReporter } from '../../../shared/diagnostics/applicationDiagnostic'
import { DESKTOP_IPC_CHANNELS } from '../../shared/desktopApi'
@@ -8,6 +9,7 @@ import { BrowserAdapterTestLeasePublisher } from './BrowserAdapterTestLeasePubli
import { BrowserDataService } from './BrowserDataService'
import { BrowserHost } from './BrowserHost'
import { BrowserOperationGuard } from './BrowserOperationGuard'
+import { BrowserPresentationHost } from './BrowserPresentationHost'
import { BrowserScreenshotService } from './BrowserScreenshotService'
interface BrowserIntegrationOptions {
@@ -23,6 +25,8 @@ export class BrowserIntegration {
readonly adapter: BrowserAdapterServer
readonly data: BrowserDataService
readonly screenshots: BrowserScreenshotService
+ readonly #presentation = new BrowserPresentationHost((sessionId, visible) => this.#host?.setSurface({ sessionId, visible }))
+ #window: BrowserWindow | null = null
readonly #operations = new BrowserOperationGuard()
#host: BrowserHost | null = null
#adapterStarted = false
@@ -43,7 +47,23 @@ export class BrowserIntegration {
}
bindWindow(window: BrowserWindow): void {
- this.closeWindow()
+ this.#window = window
+ this.#presentation.bindWindow(window)
+ }
+
+ acquirePresentation(window: BrowserWindow): string {
+ return this.#presentation.acquire(window)
+ }
+
+ async present(window: BrowserWindow, input: DesktopBrowserPresentationInput): Promise {
+ if (this.host?.getState(input.sessionId).pageId !== input.pageId)
+ throw new Error('BROWSER_PAGE_FAILED')
+ return this.#presentation.present(window, input)
+ }
+
+ #startHost(): void {
+ if (this.host)
+ return
this.#host = new BrowserHost({
getFreezeDelay: (visible) => {
if (!this.#options.isTaskLinked?.())
@@ -54,22 +74,24 @@ export class BrowserIntegration {
: null
},
onActivityError: this.#options.onActivityError,
- window,
+ createPage: descriptor => this.#presentation.createPage(descriptor),
operations: this.#operations,
getDefaultZoomFactor: () => this.#options.getPreferences().defaultZoomFactor,
requestGuestAttachment: () => {
- if (!window.isDestroyed())
- window.webContents.send(DESKTOP_IPC_CHANNELS.browserGuestsChanged)
+ this.#send(DESKTOP_IPC_CHANNELS.browserGuestsChanged)
},
revokeSession: id => this.adapter.revokeSession(id),
})
this.#host.onDidChange((change) => {
- if ((change.kind === 'session' || (change.kind === 'guest' && change.status === 'detached')) && !window.isDestroyed())
- window.webContents.send(DESKTOP_IPC_CHANNELS.browserGuestsChanged)
+ if (change.kind === 'session' || (change.kind === 'guest' && change.status === 'detached'))
+ this.#send(DESKTOP_IPC_CHANNELS.browserGuestsChanged)
})
this.#host.onDidChange((change) => {
- if (change.kind === 'state' && !window.isDestroyed())
- window.webContents.send(DESKTOP_IPC_CHANNELS.browserStateChanged, change.state)
+ if (change.kind === 'state') {
+ if (!change.state.visible)
+ this.#presentation.hide(change.state.sessionId)
+ this.#send(DESKTOP_IPC_CHANNELS.browserStateChanged, change.state)
+ }
})
this.#host.onDidChange((change) => {
if (change.kind === 'state')
@@ -93,6 +115,17 @@ export class BrowserIntegration {
}
closeWindow(): void {
+ this.#presentation.detachWindow()
+ this.#window = null
+ }
+
+ #send(channel: string, value?: unknown): void {
+ const window = this.#window
+ if (window && !window.isDestroyed())
+ window.webContents.send(channel, value)
+ }
+
+ #stopHost(): void {
const host = this.#host
host?.dispose()
if (host) {
@@ -103,6 +136,7 @@ export class BrowserIntegration {
}
async startAdapter(): Promise {
+ this.#startHost()
await this.adapter.start()
this.#adapterStarted = true
if (this.#options.testBrokerSocketPath) {
@@ -114,6 +148,7 @@ export class BrowserIntegration {
}
async stopAdapter(): Promise {
+ this.#stopHost()
await Promise.all([...this.#closingHosts])
this.#testLeasePublisher?.dispose()
this.#testLeasePublisher = null
@@ -121,5 +156,6 @@ export class BrowserIntegration {
this.#adapterStarted = false
await this.adapter.dispose()
}
+ this.#presentation.dispose()
}
}
diff --git a/apps/buddy/electron/main/browser/BrowserNavigation.ts b/apps/buddy/electron/main/browser/BrowserNavigation.ts
new file mode 100644
index 000000000..f474b4a77
--- /dev/null
+++ b/apps/buddy/electron/main/browser/BrowserNavigation.ts
@@ -0,0 +1,477 @@
+import type { DesktopBrowserError, DesktopBrowserState } from '../../../shared/browser/browserDesktopApi'
+import type { Event } from '../../../shared/events/Emitter'
+import type { BrowserHostChange } from './BrowserHostEvents'
+import type { BrowserOperationGuard } from './BrowserOperationGuard'
+import type { BrowserPage, BrowserPageSession } from './BrowserPageSession'
+import type { BrowserSessionRegistry } from './BrowserSessionRegistry'
+import { BrowserHostError } from './BrowserHostError'
+import { snapshot } from './BrowserPageSession'
+import { BrowserSecurityPolicyError } from './BrowserSecurityPolicy'
+
+const BROWSER_NAVIGATION_WAIT_TIMEOUT_MS = 30_000
+const BROWSER_FAILED_NAVIGATION_SETTLE_MS = 200
+const BROWSER_NAVIGATION_SETTLE_TIMEOUT_MS = 15_000
+
+export interface BrowserLocalFileGrant {
+ entryPath: string
+ rootPath: string
+}
+
+interface BrowserNavigationOptions {
+ sessions: Pick, 'get' | 'touch'>
+ operations: Pick
+ requireSession: (id: string) => BrowserPageSession
+ waitForPage: (session: BrowserPageSession) => Promise
+ assertCurrentPage: (session: BrowserPageSession, pageId: string, operation: string) => void
+ notFound: (id: string) => BrowserHostError
+ onDidChange: Event
+ recordTiming: (session: BrowserPageSession, phase: 'guest_ready' | 'authorized' | 'document_ready' | 'load_complete', startedAt: number) => void
+}
+
+export class BrowserNavigation {
+ readonly #options: BrowserNavigationOptions
+ readonly #failedNavigationTargets = new WeakMap()
+
+ constructor(options: BrowserNavigationOptions) {
+ this.#options = options
+ }
+
+ release(session: BrowserPageSession): void {
+ this.#failedNavigationTargets.delete(session)
+ }
+
+ async navigate(sessionId: string, rawUrl: string, readiness: 'load' | 'document-ready' = 'load', assertControl: () => void = () => {}): Promise {
+ assertControl()
+ this.#options.operations.assertCanMutate()
+ const session = this.#options.requireSession(sessionId)
+ const startedAt = performance.now()
+ const navigationSequence = this.#beginPageAction(session)
+ let url: string
+ try {
+ await this.#options.waitForPage(session)
+ this.#options.requireSession(sessionId)
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+ this.#options.recordTiming(session, 'guest_ready', startedAt)
+ this.#assertNavigationControl(session, navigationSequence, assertControl)
+ this.#options.operations.assertCanMutate()
+ const authorizationStartedAt = performance.now()
+ url = await session.securityPolicy?.authorizeNavigation(rawUrl) ?? ''
+ this.#options.recordTiming(session, 'authorized', authorizationStartedAt)
+ }
+ catch (error) {
+ this.#options.requireSession(sessionId)
+ if (error instanceof BrowserHostError && error.code === 'BROWSER_CONTROL_REQUIRED')
+ throw error
+ if (session.state.error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
+ throw new BrowserHostError('BROWSER_PAGE_UNRESPONSIVE', session.state.error.message)
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+ this.#failedNavigationTargets.set(session, rawUrl)
+ const failure: DesktopBrowserError = error instanceof BrowserSecurityPolicyError
+ ? { code: error.code, message: error.message, reason: error.reason }
+ : { code: 'BROWSER_PAGE_FAILED', message: browserLoadErrorMessage(error) }
+ session.state.error = failure
+ session.state.status = 'error'
+ this.#finishPageAction(session, navigationSequence)
+ session.publish()
+ throw error instanceof BrowserHostError
+ ? error
+ : new BrowserHostError(failure.code, failure.message, failure.reason)
+ }
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+
+ this.#assertNavigationControl(session, navigationSequence, assertControl)
+ return this.#loadPage(sessionId, session, navigationSequence, url, readiness, assertControl)
+ }
+
+ async #loadPage(
+ sessionId: string,
+ session: BrowserPageSession,
+ navigationSequence: number,
+ url: string,
+ readiness: 'load' | 'document-ready',
+ assertControl: () => void,
+ ): Promise {
+ return session.runWhileActive(async () => {
+ const startedAt = performance.now()
+ const page = session.requirePage()
+ const pageId = session.state.pageId
+ let hasCommittedDocument = false
+ let resolveWait!: (state: DesktopBrowserState) => void
+ let rejectWait!: (error: unknown) => void
+ const waiting = new Promise((resolve, reject) => {
+ resolveWait = resolve
+ rejectWait = reject
+ })
+ const checkInterrupted = (): boolean => {
+ try {
+ this.#options.requireSession(sessionId)
+ this.#options.assertCurrentPage(session, pageId, 'while waiting for navigation')
+ assertControl()
+ if (!this.#shouldContinuePageAction(session, navigationSequence)) {
+ resolveWait(snapshot(session.state))
+ return true
+ }
+ const error = session.state.error
+ if (error?.code === 'BROWSER_PAGE_CRASHED' || error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
+ throw new BrowserHostError(error.code, error.message, error.reason)
+ return false
+ }
+ catch (error) {
+ rejectWait(error)
+ return true
+ }
+ }
+ const onDocumentCommitted = () => {
+ if (this.#shouldContinuePageAction(session, navigationSequence))
+ hasCommittedDocument = true
+ }
+ const onDocumentReady = () => {
+ if (checkInterrupted() || readiness !== 'document-ready' || session.mainFrameCommitSequence !== navigationSequence)
+ return
+ this.#options.recordTiming(session, 'document_ready', startedAt)
+ resolveWait(snapshot(session.state))
+ }
+ const subscription = this.#options.onDidChange((change) => {
+ if ((change.kind === 'state' || change.kind === 'session') && change.state.sessionId === sessionId)
+ checkInterrupted()
+ })
+ page.on('did-navigate', onDocumentCommitted)
+ page.on('dom-ready', onDocumentReady)
+ const timer = setTimeout(() => {
+ if (checkInterrupted())
+ return
+ const failure = session.state.error
+ if (failure) {
+ rejectWait(new BrowserHostError(failure.code, failure.message, failure.reason))
+ return
+ }
+ if (hasCommittedDocument && session.mainFrameCommitSequence === navigationSequence) {
+ resolveWait(snapshot(session.state))
+ return
+ }
+ const message = 'Browser navigation did not commit before its deadline'
+ rejectWait(new BrowserHostError('BROWSER_PAGE_FAILED', message))
+ session.navigationSequence += 1
+ this.#finishPageAction(session, navigationSequence)
+ this.#failedNavigationTargets.set(session, url)
+ session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
+ session.state.status = 'error'
+ try {
+ page.stop()
+ }
+ catch {}
+ session.publish()
+ }, BROWSER_NAVIGATION_WAIT_TIMEOUT_MS)
+ try {
+ return await Promise.race([
+ waiting,
+ this.#loadPageToCompletion(sessionId, session, navigationSequence, url, assertControl),
+ ])
+ }
+ finally {
+ clearTimeout(timer)
+ subscription.dispose()
+ page.off('did-navigate', onDocumentCommitted)
+ page.off('dom-ready', onDocumentReady)
+ }
+ }, { timeoutMs: null })
+ }
+
+ async #loadPageToCompletion(
+ sessionId: string,
+ session: BrowserPageSession,
+ navigationSequence: number,
+ url: string,
+ assertControl: () => void,
+ ): Promise {
+ const startedAt = performance.now()
+ session.state.url = url
+ session.publish()
+ try {
+ const page = await this.#options.waitForPage(session)
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+ this.#assertNavigationControl(session, navigationSequence, assertControl)
+ await page.loadURL(url)
+ this.#options.recordTiming(session, 'load_complete', startedAt)
+ if (!this.#options.sessions.get(sessionId))
+ throw this.#options.notFound(sessionId)
+ if (!this.#isCurrentPageAction(session, navigationSequence))
+ return snapshot(session.state)
+ session.stoppedNavigationSequence = null
+ this.#finishPageAction(session, navigationSequence)
+ session.removeBootstrapHistory()
+ session.refreshPageState()
+ session.state.status = 'ready'
+ session.publish()
+ return snapshot(session.state)
+ }
+ catch (error) {
+ if (error instanceof BrowserHostError)
+ throw error
+ if (!this.#options.sessions.get(sessionId))
+ throw this.#options.notFound(sessionId)
+ if (!this.#isCurrentPageAction(session, navigationSequence))
+ return snapshot(session.state)
+ if (session.stoppedNavigationSequence === navigationSequence) {
+ session.stoppedNavigationSequence = null
+ this.#finishPageAction(session, navigationSequence)
+ session.state.error = null
+ session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
+ session.refreshPageState()
+ session.publish()
+ return snapshot(session.state)
+ }
+ return this.#waitForNavigationSettlement(
+ sessionId,
+ session,
+ navigationSequence,
+ error,
+ )
+ }
+ }
+
+ async #waitForNavigationSettlement(
+ sessionId: string,
+ session: BrowserPageSession,
+ navigationSequence: number,
+ loadError: unknown,
+ ): Promise {
+ const startedAt = Date.now()
+ const deadline = startedAt + BROWSER_NAVIGATION_SETTLE_TIMEOUT_MS
+ const isAbortedLoad = isNavigationAborted(loadError)
+ const loadFailureDeadline = isAbortedLoad
+ ? null
+ : Math.min(deadline, startedAt + BROWSER_FAILED_NAVIGATION_SETTLE_MS)
+ let pageFailureDeadline: number | null = null
+ while (true) {
+ if (this.#options.sessions.get(sessionId) !== session)
+ throw this.#options.notFound(sessionId)
+ if (!this.#isCurrentPageAction(session, navigationSequence))
+ return snapshot(session.state)
+ if (session.stoppedNavigationSequence === navigationSequence) {
+ session.stoppedNavigationSequence = null
+ this.#finishPageAction(session, navigationSequence)
+ session.state.error = null
+ session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
+ session.refreshPageState()
+ session.publish()
+ return snapshot(session.state)
+ }
+ const hasReplacementCommit = session.mainFrameCommitSequence === navigationSequence
+ const pageFailure = session.state.error
+ const now = Date.now()
+ if (pageFailure) {
+ pageFailureDeadline ??= Math.min(
+ deadline,
+ now + BROWSER_FAILED_NAVIGATION_SETTLE_MS,
+ )
+ }
+ else {
+ pageFailureDeadline = null
+ }
+ if (
+ pageFailure
+ && (
+ session.activeNavigationSequence !== navigationSequence
+ || now >= (pageFailureDeadline ?? deadline)
+ )
+ ) {
+ this.#finishPageAction(session, navigationSequence)
+ throw new BrowserHostError(
+ pageFailure.code,
+ pageFailure.message,
+ pageFailure.reason ?? null,
+ )
+ }
+ if (
+ session.state.status === 'ready'
+ && (isAbortedLoad || hasReplacementCommit)
+ ) {
+ return snapshot(session.state)
+ }
+ if (loadFailureDeadline !== null && now >= loadFailureDeadline) {
+ const message = browserLoadErrorMessage(loadError)
+ this.#finishPageAction(session, navigationSequence)
+ session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
+ session.state.status = 'error'
+ session.publish()
+ throw new BrowserHostError('BROWSER_PAGE_FAILED', message)
+ }
+ const remainingMs = Math.min(
+ pageFailureDeadline ?? deadline,
+ loadFailureDeadline ?? deadline,
+ ) - now
+ if (remainingMs <= 0) {
+ const message = 'Browser navigation did not settle after the initial load was replaced'
+ this.#finishPageAction(session, navigationSequence)
+ session.state.error = { code: 'BROWSER_PAGE_FAILED', message }
+ session.state.status = 'error'
+ session.publish()
+ throw new BrowserHostError('BROWSER_PAGE_FAILED', message)
+ }
+ await wait(Math.min(remainingMs, 50))
+ }
+ }
+
+ goBack(sessionId: string): void {
+ this.#options.operations.assertCanMutate()
+ const session = this.#options.requireSession(sessionId)
+ const history = session.requirePage().navigationHistory
+ if (!history.canGoBack())
+ return
+ this.#beginPageAction(session)
+ history.goBack()
+ }
+
+ goForward(sessionId: string): void {
+ this.#options.operations.assertCanMutate()
+ const session = this.#options.requireSession(sessionId)
+ const history = session.requirePage().navigationHistory
+ if (!history.canGoForward())
+ return
+ this.#beginPageAction(session)
+ history.goForward()
+ }
+
+ async reload(sessionId: string, assertControl: () => void = () => {}): Promise {
+ assertControl()
+ this.#options.operations.assertCanMutate()
+ const session = this.#options.requireSession(sessionId)
+ const failedTarget = this.#failedNavigationTargets.get(session)
+ if (session.state.status === 'error' && failedTarget !== undefined) {
+ await this.navigate(sessionId, failedTarget, 'load', assertControl)
+ return
+ }
+ if (session.state.url === 'about:blank')
+ return
+ this.#beginPageAction(session)
+ session.requirePage().reload()
+ }
+
+ stop(sessionId: string): void {
+ const session = this.#options.requireSession(sessionId)
+ if (session.state.status !== 'loading')
+ return
+ session.stoppedNavigationSequence = session.navigationSequence
+ this.#finishPageAction(session, session.navigationSequence)
+ if (session.page && !session.page.isDestroyed())
+ session.page.stop()
+ session.refreshPageState()
+ session.state.error = null
+ session.state.status = session.state.url === 'about:blank' ? 'idle' : 'ready'
+ session.publish()
+ }
+
+ async openLocalFile(
+ sessionId: string,
+ grant: BrowserLocalFileGrant,
+ readiness: 'load' | 'document-ready' = 'load',
+ assertControl: () => void = () => {},
+ ): Promise {
+ assertControl()
+ this.#options.operations.assertCanMutate()
+ const session = this.#options.requireSession(sessionId)
+ const startedAt = performance.now()
+ await this.#options.waitForPage(session)
+ this.#options.recordTiming(session, 'guest_ready', startedAt)
+ this.#options.operations.assertCanMutate()
+ const navigationSequence = this.#beginPageAction(session)
+ const authorizationStartedAt = performance.now()
+ let url: string
+ try {
+ url = await session.securityPolicy?.authorizeLocalFile(
+ grant.entryPath,
+ grant.rootPath,
+ ) ?? ''
+ this.#options.recordTiming(session, 'authorized', authorizationStartedAt)
+ }
+ catch (error) {
+ if (session.state.error?.code === 'BROWSER_PAGE_UNRESPONSIVE')
+ throw new BrowserHostError('BROWSER_PAGE_UNRESPONSIVE', session.state.error.message)
+ if (!(error instanceof BrowserSecurityPolicyError))
+ throw error
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+ session.state.error = {
+ code: error.code,
+ message: error.message,
+ reason: error.reason,
+ }
+ session.state.status = 'error'
+ this.#finishPageAction(session, navigationSequence)
+ session.publish()
+ throw new BrowserHostError(error.code, error.message, error.reason)
+ }
+ if (!this.#shouldContinuePageAction(session, navigationSequence))
+ return snapshot(session.state)
+ this.#assertNavigationControl(session, navigationSequence, assertControl)
+ return this.#loadPage(sessionId, session, navigationSequence, url, readiness, assertControl)
+ }
+
+ #beginPageAction(session: BrowserPageSession): number {
+ this.#failedNavigationTargets.delete(session)
+ this.#options.sessions.touch(session.state.sessionId)
+ session.navigationSequence += 1
+ session.activeNavigationSequence = session.navigationSequence
+ session.semanticDriver?.invalidateDocument()
+ session.stoppedNavigationSequence = null
+ session.state.error = null
+ session.state.status = 'loading'
+ session.publish()
+ return session.navigationSequence
+ }
+
+ #isCurrentPageAction(session: BrowserPageSession, navigationSequence: number): boolean {
+ return session.navigationSequence === navigationSequence
+ }
+
+ #finishPageAction(session: BrowserPageSession, navigationSequence: number): void {
+ if (session.activeNavigationSequence === navigationSequence)
+ session.activeNavigationSequence = null
+ }
+
+ #assertNavigationControl(session: BrowserPageSession, navigationSequence: number, assertControl: () => void): void {
+ try {
+ assertControl()
+ }
+ catch (error) {
+ if (this.#shouldContinuePageAction(session, navigationSequence)) {
+ this.#finishPageAction(session, navigationSequence)
+ session.refreshPageState()
+ session.state.error = null
+ session.state.status = session.page?.isLoading() ? 'loading' : session.state.url === 'about:blank' ? 'idle' : 'ready'
+ session.publish()
+ }
+ throw error
+ }
+ }
+
+ #shouldContinuePageAction(session: BrowserPageSession, navigationSequence: number): boolean {
+ return this.#isCurrentPageAction(session, navigationSequence)
+ && session.stoppedNavigationSequence !== navigationSequence
+ }
+}
+
+function isNavigationAborted(error: unknown): boolean {
+ if (!error || typeof error !== 'object')
+ return false
+ const candidate = error as { code?: unknown, errno?: unknown }
+ if (candidate.code === 'ERR_ABORTED' || candidate.errno === -3)
+ return true
+ return error instanceof Error
+ && /^ERR_ABORTED(?: \(-3\))?(?: |$)/.test(error.message)
+}
+
+function browserLoadErrorMessage(error: unknown): string {
+ if (error instanceof Error && error.message.trim())
+ return error.message.slice(0, 1_024)
+ return 'Browser page failed to load'
+}
+
+function wait(durationMs: number): Promise {
+ return new Promise(resolve => setTimeout(resolve, durationMs))
+}
diff --git a/apps/buddy/electron/main/browser/BrowserObservationStore.ts b/apps/buddy/electron/main/browser/BrowserObservationStore.ts
new file mode 100644
index 000000000..5eae77e32
--- /dev/null
+++ b/apps/buddy/electron/main/browser/BrowserObservationStore.ts
@@ -0,0 +1,94 @@
+import type { BrowserScreenshotRef } from '../../../shared/browser'
+import type { SemanticBrowserTarget } from './browserObservationProjection'
+import { BrowserHostError } from './BrowserHostError'
+
+interface BrowserObservationEntry {
+ documentRevision: number
+ screenshot?: { bytes: Uint8Array, ref: BrowserScreenshotRef }
+ targets: ReadonlyMap
+}
+
+interface StoredObservation extends BrowserObservationEntry {
+ expiresAt: number
+ requiresHumanInput: boolean
+}
+
+interface Options {
+ now: () => number
+ ttlMs: number
+ maxObservations?: number
+}
+
+const MAX_SCREENSHOT_CACHE_BYTES = 32 * 1_024 * 1_024
+
+export class BrowserObservationStore {
+ readonly #observations = new Map()
+ readonly #options: Options
+ #expiryTimer: ReturnType | null = null
+ #disposed = false
+
+ constructor(options: Options) {
+ this.#options = options
+ }
+
+ get(id: string): StoredObservation | undefined {
+ this.#prune()
+ return this.#observations.get(id)
+ }
+
+ store(id: string, observation: BrowserObservationEntry): void {
+ if (this.#disposed)
+ throw new BrowserHostError('BROWSER_PAGE_FAILED', 'Browser observation store is disposed')
+ this.#prune()
+ this.#observations.delete(id)
+ this.#observations.set(id, {
+ ...observation,
+ expiresAt: this.#options.now() + this.#options.ttlMs,
+ requiresHumanInput: [...observation.targets.values()].some(target => target.inputMode === 'human'),
+ })
+ let bytes = [...this.#observations.values()].reduce((total, entry) => total + (entry.screenshot?.bytes.byteLength ?? 0), 0)
+ while (this.#observations.size > (this.#options.maxObservations ?? 8) || bytes > MAX_SCREENSHOT_CACHE_BYTES) {
+ const oldest = this.#observations.keys().next().value
+ if (oldest === undefined)
+ break
+ bytes -= this.#observations.get(oldest)?.screenshot?.bytes.byteLength ?? 0
+ this.#observations.delete(oldest)
+ }
+ this.#scheduleExpiry()
+ }
+
+ clear(): void {
+ if (this.#expiryTimer)
+ clearTimeout(this.#expiryTimer)
+ this.#expiryTimer = null
+ this.#observations.clear()
+ }
+
+ dispose(): void {
+ this.#disposed = true
+ this.clear()
+ }
+
+ #prune(): void {
+ const now = this.#options.now()
+ for (const [id, observation] of this.#observations) {
+ if (observation.expiresAt <= now)
+ this.#observations.delete(id)
+ }
+ }
+
+ #scheduleExpiry(): void {
+ if (this.#expiryTimer)
+ clearTimeout(this.#expiryTimer)
+ this.#expiryTimer = null
+ if (!this.#observations.size)
+ return
+ const expiresAt = Math.min(...[...this.#observations.values()].map(observation => observation.expiresAt))
+ this.#expiryTimer = setTimeout(() => {
+ this.#expiryTimer = null
+ this.#prune()
+ this.#scheduleExpiry()
+ }, Math.max(1, expiresAt - this.#options.now()))
+ this.#expiryTimer.unref()
+ }
+}
diff --git a/apps/buddy/electron/main/browser/BrowserPresentationHost.ts b/apps/buddy/electron/main/browser/BrowserPresentationHost.ts
new file mode 100644
index 000000000..5e24f1e9e
--- /dev/null
+++ b/apps/buddy/electron/main/browser/BrowserPresentationHost.ts
@@ -0,0 +1,167 @@
+import type { BrowserWindow as ElectronWindow, WebContents } from 'electron'
+import type { DesktopBrowserGuestDescriptor, DesktopBrowserPresentationInput } from '../../../shared/browser/browserDesktopApi'
+import { randomUUID } from 'node:crypto'
+import { BrowserWindow, View, WebContentsView } from 'electron'
+
+interface OwnedPage {
+ view: WebContentsView
+ clip: View
+ displayed: boolean
+}
+
+export class BrowserPresentationHost {
+ readonly #pages = new Map()
+ #parking: ElectronWindow | null = null
+ #window: ElectronWindow | null = null
+ #token: string | null = null
+ #unbind: (() => void) | null = null
+ readonly #setSurface: (sessionId: string, visible: boolean) => void
+
+ constructor(setSurface: (sessionId: string, visible: boolean) => void) {
+ this.#setSurface = setSurface
+ }
+
+ createPage(descriptor: DesktopBrowserGuestDescriptor): WebContents {
+ if (this.#pages.has(descriptor.sessionId))
+ throw new Error('Browser page already exists')
+ this.#parking ??= new BrowserWindow({ show: false, width: 1280, height: 800, webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } })
+ const view = new WebContentsView({ webPreferences: { partition: descriptor.partition, sandbox: true, contextIsolation: true, nodeIntegration: false, nodeIntegrationInSubFrames: false, nodeIntegrationInWorker: false, webSecurity: true, allowRunningInsecureContent: false, webviewTag: false, devTools: false, backgroundThrottling: false } })
+ const clip = new View()
+ clip.addChildView(view)
+ clip.setBounds({ x: 0, y: 0, width: 1280, height: 800 })
+ view.setBounds({ x: 0, y: 0, width: 1280, height: 800 })
+ this.#parking.contentView.addChildView(clip)
+ const page = { view, clip, displayed: false }
+ this.#pages.set(descriptor.sessionId, page)
+ view.webContents.once('destroyed', () => {
+ if (this.#pages.get(descriptor.sessionId) !== page)
+ return
+ this.#remove(page)
+ this.#pages.delete(descriptor.sessionId)
+ })
+ return view.webContents
+ }
+
+ bindWindow(window: ElectronWindow): void {
+ this.detachWindow()
+ this.#window = window
+ const contents = window.webContents
+ const invalidate = () => this.#revoke()
+ const closed = () => {
+ if (this.#window !== window)
+ return
+ this.#token = null
+ this.#unbind?.()
+ this.#unbind = null
+ this.#window = null
+ for (const page of this.#pages.values())
+ page.displayed = false
+ }
+ const navigation = (_event: unknown, _url: string, inPlace: boolean, mainFrame: boolean) => {
+ if (mainFrame && !inPlace)
+ invalidate()
+ }
+ const closing = (event: { defaultPrevented: boolean }) => {
+ if (!event.defaultPrevented)
+ this.detachWindow()
+ }
+ window.on('close', closing)
+ window.once('closed', closed)
+ contents.on('did-start-navigation', navigation)
+ contents.on('render-process-gone', invalidate)
+ this.#unbind = () => {
+ window.off('close', closing)
+ window.off('closed', closed)
+ contents.off('did-start-navigation', navigation)
+ contents.off('render-process-gone', invalidate)
+ }
+ }
+
+ acquire(window: ElectronWindow): string {
+ if (this.#window !== window || window.isDestroyed())
+ throw new Error('DESKTOP_REQUIRED')
+ this.#revoke()
+ this.#token = randomUUID()
+ return this.#token
+ }
+
+ present(window: ElectronWindow, input: DesktopBrowserPresentationInput): Promise {
+ if (this.#window !== window || window.isDestroyed() || this.#token !== input.presentationId)
+ throw new Error('BROWSER_PRESENTATION_EXPIRED')
+ const page = this.#pages.get(input.sessionId)
+ if (!page || page.view.webContents.isDestroyed())
+ throw new Error('BROWSER_PAGE_FAILED')
+ if (!input.visible) {
+ const capture = page.displayed ? page.view.webContents.capturePage() : null
+ this.hide(input.sessionId)
+ return (capture ?? Promise.resolve(null)).catch(() => null).then(snapshot => this.#token === input.presentationId && this.#pages.get(input.sessionId) === page ? snapshot?.toDataURL() ?? null : null)
+ }
+ const zoom = window.webContents.getZoomFactor()
+ const rounded = (value: number) => Math.round(value * zoom)
+ const { bounds, clip } = input
+ const content = window.getContentBounds()
+ const x = Math.max(0, rounded(clip.x))
+ const y = Math.max(0, rounded(clip.y))
+ const width = Math.min(rounded(clip.width), content.width - x)
+ const height = Math.min(rounded(clip.height), content.height - y)
+ if (width <= 0 || height <= 0) {
+ this.hide(input.sessionId)
+ return Promise.resolve(null)
+ }
+ if (!page.displayed)
+ this.#remove(page)
+ page.clip.setBounds({ x, y, width, height })
+ page.view.setBounds({ x: rounded(bounds.x) - x, y: rounded(bounds.y) - y, width: Math.max(1, rounded(bounds.width)), height: Math.max(1, rounded(bounds.height)) })
+ if (!page.displayed)
+ window.contentView.addChildView(page.clip)
+ page.displayed = true
+ this.#setSurface(input.sessionId, true)
+ return Promise.resolve(null)
+ }
+
+ hide(sessionId: string): void {
+ const page = this.#pages.get(sessionId)
+ if (!page)
+ return
+ this.#remove(page)
+ if (this.#parking && !this.#parking.isDestroyed())
+ this.#parking.contentView.addChildView(page.clip)
+ page.displayed = false
+ this.#setSurface(sessionId, false)
+ }
+
+ detachWindow(): void {
+ this.#revoke()
+ this.#unbind?.()
+ this.#unbind = null
+ this.#window = null
+ }
+
+ dispose(): void {
+ this.detachWindow()
+ for (const page of this.#pages.values()) {
+ this.#remove(page)
+ if (!page.view.webContents.isDestroyed())
+ page.view.webContents.close({ waitForBeforeUnload: false })
+ }
+ this.#pages.clear()
+ this.#parking?.destroy()
+ this.#parking = null
+ }
+
+ #remove(page: OwnedPage): void {
+ if (this.#window && !this.#window.isDestroyed()) {
+ if (page.displayed && page.view.webContents.isFocused())
+ this.#window.webContents.focus()
+ this.#window.contentView.removeChildView(page.clip)
+ }
+ if (this.#parking && !this.#parking.isDestroyed())
+ this.#parking.contentView.removeChildView(page.clip)
+ }
+
+ #revoke(): void {
+ this.#token = null
+ for (const sessionId of this.#pages.keys())
+ this.hide(sessionId)
+ }
+}
diff --git a/apps/buddy/electron/main/browser/SemanticBrowserDriver.ts b/apps/buddy/electron/main/browser/SemanticBrowserDriver.ts
index 162efa06b..80389beca 100644
--- a/apps/buddy/electron/main/browser/SemanticBrowserDriver.ts
+++ b/apps/buddy/electron/main/browser/SemanticBrowserDriver.ts
@@ -25,6 +25,7 @@ import { BrowserDebugger } from './BrowserDebugger'
import { collectBrowserRegionNodes, resolveBrowserRegion } from './browserDomRegion'
import { BrowserHostError } from './BrowserHostError'
import { collectDomFieldMetadata, collectFrameIds, collectViewportNodeIds, containsSensitiveFieldMetadata, createScreenshotRef, createTruncation, deduplicateAccessibilityNodes, hasPngSignature, MAX_OBSERVED_FRAMES, normalizeElementLimit, projectElements, scopeAccessibilityNodes } from './browserObservationProjection'
+import { BrowserObservationStore } from './BrowserObservationStore'
import {
projectBrowserObservedValue,
redactBrowserRuntimeUrl,
@@ -96,17 +97,6 @@ export interface SemanticBrowserScreenshot {
export type { SemanticBrowserTarget } from './browserObservationProjection'
-interface StoredObservation {
- documentRevision: number
- expiresAt: number
- requiresHumanInput: boolean
- screenshot?: {
- bytes: Uint8Array
- ref: BrowserScreenshotRef
- }
- targets: Map
-}
-
type SemanticBrowserDriverErrorCode = Extract<
BrowserErrorCode,
| 'BROWSER_HUMAN_INPUT_REQUIRED'
@@ -114,9 +104,7 @@ type SemanticBrowserDriverErrorCode = Extract<
| 'BROWSER_TARGET_STALE'
>
-const DEFAULT_MAX_OBSERVATIONS = 8
const DEFAULT_OBSERVATION_TTL_MS = 30_000
-const MAX_SCREENSHOT_CACHE_BYTES = 32 * 1_024 * 1_024
const BROWSER_ACTION_OBJECT_GROUP = 'lexora-browser-action'
const BROWSER_TARGET_ACTIONABILITY_FUNCTION = `async function (checkClickability) {
const element = this
@@ -264,10 +252,8 @@ export class SemanticBrowserDriverError extends Error {
export class SemanticBrowserDriver {
readonly #createId: () => string
readonly #createScreenshotId: () => string
- readonly #maxObservations: number
readonly #now: () => number
- readonly #observations = new Map()
- #observationExpiryTimer: ReturnType | null = null
+ readonly #observations: BrowserObservationStore
readonly #observationTtlMs: number
readonly #contentReader: BrowserContentReader
readonly #page: SemanticBrowserPage
@@ -279,10 +265,10 @@ export class SemanticBrowserDriver {
constructor(options: SemanticBrowserDriverOptions) {
this.#createId = options.createId ?? randomUUID
this.#createScreenshotId = options.createScreenshotId ?? randomUUID
- this.#maxObservations = options.maxObservations ?? DEFAULT_MAX_OBSERVATIONS
this.#now = options.now ?? Date.now
this.#observationTtlMs = options.observationTtlMs ?? DEFAULT_OBSERVATION_TTL_MS
this.#contentReader = new BrowserContentReader(this.#now, this.#observationTtlMs)
+ this.#observations = new BrowserObservationStore({ now: this.#now, ttlMs: this.#observationTtlMs, maxObservations: options.maxObservations })
this.#page = options.page
this.#connection = options.connection ?? new BrowserDebugger(options.page.debugger)
this.#ownsConnection = !options.connection
@@ -477,16 +463,14 @@ export class SemanticBrowserDriver {
projected.targets.delete(removed.ref)
}
- this.#storeObservation(
- observation.observationId,
- input.mode === 'screenshot' ? new Map() : projected.targets,
- screenshot && observation.screenshot
- ? {
- bytes: screenshot.bytes,
- ref: observation.screenshot,
- }
+ this.#assertActive()
+ this.#observations.store(observation.observationId, {
+ documentRevision: revision,
+ targets: input.mode === 'screenshot' ? new Map() : projected.targets,
+ screenshot: screenshot && observation.screenshot
+ ? { bytes: screenshot.bytes, ref: observation.screenshot }
: undefined,
- )
+ })
return observation
}
catch (error) {
@@ -614,7 +598,6 @@ export class SemanticBrowserDriver {
observationId: string
}): void {
this.#assertActive()
- this.#pruneObservations(this.#now())
const observation = this.#observations.get(reference.observationId)
if (
reference.documentRevision !== this.#documentRevision
@@ -640,7 +623,6 @@ export class SemanticBrowserDriver {
reference: SemanticBrowserScreenshotReference,
): SemanticBrowserScreenshot {
this.#assertActive()
- this.#pruneObservations(this.#now())
const observation = this.#observations.get(reference.observationId)
const screenshot = observation?.screenshot
if (
@@ -662,7 +644,7 @@ export class SemanticBrowserDriver {
throw new SemanticBrowserDriverError()
this.#documentRevision += 1
this.#contentReader.clear()
- this.#clearObservations()
+ this.#observations.clear()
}
async isTextVisible(text: string): Promise {
@@ -753,7 +735,7 @@ export class SemanticBrowserDriver {
return
this.#disposed = true
this.#contentReader.clear()
- this.#clearObservations()
+ this.#observations.dispose()
if (this.#ownsConnection)
this.#connection.dispose()
}
@@ -985,68 +967,6 @@ export class SemanticBrowserDriver {
width,
}
}
-
- #pruneObservations(now: number): void {
- for (const [observationId, observation] of this.#observations) {
- if (
- observation.expiresAt <= now
- || observation.documentRevision !== this.#documentRevision
- ) {
- this.#observations.delete(observationId)
- }
- }
- }
-
- #clearObservations(): void {
- if (this.#observationExpiryTimer)
- clearTimeout(this.#observationExpiryTimer)
- this.#observationExpiryTimer = null
- this.#observations.clear()
- }
-
- #scheduleObservationExpiry(): void {
- if (this.#observationExpiryTimer)
- clearTimeout(this.#observationExpiryTimer)
- this.#observationExpiryTimer = null
- if (!this.#observations.size)
- return
- const expiresAt = Math.min(...[...this.#observations.values()].map(observation => observation.expiresAt))
- this.#observationExpiryTimer = setTimeout(() => {
- this.#observationExpiryTimer = null
- this.#pruneObservations(this.#now())
- this.#scheduleObservationExpiry()
- }, Math.max(1, expiresAt - this.#now()))
- this.#observationExpiryTimer.unref()
- }
-
- #storeObservation(
- observationId: string,
- targets: Map,
- screenshot?: StoredObservation['screenshot'],
- ): void {
- this.#assertActive()
- const now = this.#now()
- this.#pruneObservations(now)
- this.#observations.delete(observationId)
- this.#observations.set(observationId, {
- documentRevision: this.#documentRevision,
- expiresAt: now + this.#observationTtlMs,
- requiresHumanInput: [...targets.values()].some(
- target => target.inputMode === 'human',
- ),
- ...(screenshot ? { screenshot } : {}),
- targets,
- })
- let screenshotBytes = [...this.#observations.values()].reduce((total, observation) => total + (observation.screenshot?.bytes.byteLength ?? 0), 0)
- while (this.#observations.size > this.#maxObservations || screenshotBytes > MAX_SCREENSHOT_CACHE_BYTES) {
- const oldestObservationId = this.#observations.keys().next().value
- if (oldestObservationId === undefined)
- break
- screenshotBytes -= this.#observations.get(oldestObservationId)?.screenshot?.bytes.byteLength ?? 0
- this.#observations.delete(oldestObservationId)
- }
- this.#scheduleObservationExpiry()
- }
}
function supportsTargetAction(
diff --git a/apps/buddy/electron/main/browser/__tests__/BrowserPresentationHost.spec.ts b/apps/buddy/electron/main/browser/__tests__/BrowserPresentationHost.spec.ts
new file mode 100644
index 000000000..c5b3309b0
--- /dev/null
+++ b/apps/buddy/electron/main/browser/__tests__/BrowserPresentationHost.spec.ts
@@ -0,0 +1,91 @@
+import { BrowserWindow } from 'electron'
+import { describe, expect, it, vi } from 'vitest'
+import { BrowserPresentationHost } from '../BrowserPresentationHost'
+
+vi.mock('electron', async () => {
+ const { EventEmitter } = await import('node:events')
+ class View {
+ children: View[] = []
+ bounds = { x: 0, y: 0, width: 0, height: 0 }
+ addChildView(view: View) {
+ this.removeChildView(view)
+ this.children.push(view)
+ }
+
+ removeChildView(view: View) { this.children = this.children.filter(child => child !== view) }
+ setBounds(bounds: typeof this.bounds) { this.bounds = bounds }
+ getBounds() { return this.bounds }
+ }
+ class Contents extends EventEmitter {
+ destroyed = false
+ isDestroyed() { return this.destroyed }
+ isFocused() { return false }
+ focus() {}
+ getZoomFactor() { return 1.25 }
+ capturePage() { return Promise.resolve({ toDataURL: () => 'data:image/png;base64,c2NyZWVuc2hvdA==' }) }
+ close() {
+ this.destroyed = true
+ this.emit('destroyed')
+ }
+ }
+ class Window extends EventEmitter {
+ readonly contentView = new View()
+ readonly webContents = new Contents()
+ destroyed = false
+ isDestroyed() { return this.destroyed }
+ getContentBounds() { return { x: 0, y: 0, width: 1000, height: 800 } }
+ destroy() {
+ this.destroyed = true
+ this.emit('closed')
+ }
+ }
+ return { BrowserWindow: Window, View, WebContentsView: class extends View { readonly webContents = new Contents() } }
+})
+
+function input(presentationId: string) {
+ return { presentationId, sessionId: 'session', pageId: 'page', visible: true, bounds: { x: 10, y: 20, width: 400, height: 300 }, clip: { x: 20, y: 30, width: 300, height: 200 } }
+}
+
+describe('browser presentation ownership', () => {
+ it('preserves the page through window close and rejects the old display token in a new window', async () => {
+ const host = new BrowserPresentationHost(() => {})
+ const page = host.createPage({ sessionId: 'session', partition: 'persist:isolated-fixture' })
+ const first = new BrowserWindow()
+ host.bindWindow(first)
+ const token = host.acquire(first)
+ await host.present(first, input(token))
+ expect(first.contentView.children).toHaveLength(1)
+ first.destroy()
+ expect(page.isDestroyed()).toBe(false)
+ const second = new BrowserWindow()
+ host.bindWindow(second)
+ expect(() => host.present(second, input(token))).toThrow('BROWSER_PRESENTATION_EXPIRED')
+ await host.present(second, input(host.acquire(second)))
+ expect(second.contentView.children).toHaveLength(1)
+ expect(page.isDestroyed()).toBe(false)
+ host.dispose()
+ expect(page.isDestroyed()).toBe(true)
+ })
+
+ it('revokes renderer generations without closing pages and preserves clipped viewport geometry', async () => {
+ const host = new BrowserPresentationHost(() => {})
+ const page = host.createPage({ sessionId: 'session', partition: 'persist:isolated-fixture' })
+ const window = new BrowserWindow()
+ host.bindWindow(window)
+ const token = host.acquire(window)
+ await host.present(window, input(token))
+ const clip = window.contentView.children[0]!
+ expect(clip.getBounds()).toEqual({ x: 25, y: 38, width: 375, height: 250 })
+ expect(clip.children[0]!.getBounds()).toEqual({ x: -12, y: -13, width: 500, height: 375 })
+ window.webContents.emit('did-start-navigation', {}, 'lexora-app://desktop/index.html', false, true)
+ expect(window.contentView.children).toHaveLength(0)
+ expect(page.isDestroyed()).toBe(false)
+ expect(() => host.present(window, input(token))).toThrow('BROWSER_PRESENTATION_EXPIRED')
+ const next = host.acquire(window)
+ await host.present(window, input(next))
+ expect(await host.present(window, { ...input(next), visible: false })).toMatch(/^data:image\/png/)
+ expect(window.contentView.children).toHaveLength(0)
+ expect(page.isDestroyed()).toBe(false)
+ host.dispose()
+ })
+})
diff --git a/apps/buddy/electron/main/browser/registerBrowserDesktopIpc.ts b/apps/buddy/electron/main/browser/registerBrowserDesktopIpc.ts
index f4437a1d0..3c06fcd1e 100644
--- a/apps/buddy/electron/main/browser/registerBrowserDesktopIpc.ts
+++ b/apps/buddy/electron/main/browser/registerBrowserDesktopIpc.ts
@@ -2,6 +2,7 @@ import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
import type { TaskFileTarget } from '../../../shared/files/taskFileApi'
import type { BrowserDataService } from './BrowserDataService'
import type { BrowserHost } from './BrowserHost'
+import type { BrowserIntegration } from './BrowserIntegration'
import type { BrowserScreenshotService } from './BrowserScreenshotService'
import { fileURLToPath } from 'node:url'
import { ipcMain, session, shell, webContents } from 'electron'
@@ -12,6 +13,7 @@ import {
browserNavigateInputSchema,
browserOpenArtifactInputSchema,
browserOpenFileInputSchema,
+ browserPresentationInputSchema,
browserSessionInputSchema,
browserSetProfileModeInputSchema,
browserSetSurfaceInputSchema,
@@ -24,6 +26,7 @@ import { DESKTOP_IPC_CHANNELS } from '../../shared/desktopApi'
import { assertTrustedSender } from '../ipc'
export interface RegisterBrowserDesktopIpcOptions {
+ presentation?: Pick
data: Pick
screenshots: Pick
getHost: () => BrowserHost | null
@@ -51,6 +54,18 @@ export function registerBrowserDesktopIpc(
})
}
+ handle(DESKTOP_IPC_CHANNELS.browserAcquirePresentation, (_host, _input, event) => {
+ const window = options.getWindow()
+ if (!window || !options.presentation || event.senderFrame !== event.sender.mainFrame)
+ throw new Error('DESKTOP_REQUIRED')
+ return options.presentation.acquirePresentation(window)
+ })
+ handle(DESKTOP_IPC_CHANNELS.browserPresent, (_host, input, event) => {
+ const window = options.getWindow()
+ if (!window || !options.presentation || event.senderFrame !== event.sender.mainFrame)
+ throw new Error('DESKTOP_REQUIRED')
+ return options.presentation.present(window, browserPresentationInputSchema.parse(input))
+ })
handle(DESKTOP_IPC_CHANNELS.browserPickElement, async (host, input, event) => {
if (event.senderFrame !== event.sender.mainFrame)
throw new Error('Element picking requires the trusted main frame')
@@ -69,6 +84,8 @@ export function registerBrowserDesktopIpc(
return host.locateElement(browserLocateElementInputSchema.parse(input))
})
handle(DESKTOP_IPC_CHANNELS.browserAttachGuest, (host, input, event) => {
+ if (options.presentation)
+ throw new Error('Browser pages are owned by the platform host')
const { sessionId, webContentsId } = browserAttachGuestInputSchema.parse(input)
const guest = webContents.fromId(webContentsId)
if (
diff --git a/apps/buddy/electron/main/config/LexoraConfigStore.ts b/apps/buddy/electron/main/config/LexoraConfigStore.ts
index e1b9f89ee..9124553dd 100644
--- a/apps/buddy/electron/main/config/LexoraConfigStore.ts
+++ b/apps/buddy/electron/main/config/LexoraConfigStore.ts
@@ -17,6 +17,7 @@ import { copyEventSnapshot } from '../../../shared/events/eventSnapshot'
import { extensionAuthorSchema } from '../../../shared/extensions/extensionIdentity'
import { BUILTIN_FILE_ICON_THEME, fileIconPreferenceSchema } from '../../../shared/icons/fileIconTheme'
import { imagePreferencesSchema } from '../../../shared/images/imagePreferences'
+import { DEFAULT_DESKTOP_EXIT_BEHAVIOR, desktopExitBehaviorSchema } from '../../../shared/lifecycle/exitBehavior'
import { downloadSettingsSchema } from '../../../shared/network/downloadSettings'
import { DEFAULT_PROXY_SETTINGS, proxySettingsSchema } from '../../../shared/network/proxySettings'
import { DEFAULT_NOTIFICATION_SOUND_PREFERENCES, notificationSoundAssetIdSchema, notificationSoundAssetSchema, notificationSoundPreferencesPatchSchema, notificationSoundPreferencesSchema } from '../../../shared/notifications/notificationSound'
@@ -30,11 +31,12 @@ import { DEFAULT_LOCAL_BACKUP_LIMIT, localBackupLimitSchema } from '../../../sha
import { DESKTOP_ACCENT_COLORS, legacyThemePreferenceSchema, migrateThemePreference, themePreferenceSchema } from '../../../shared/theme/themePreferences'
import { DEFAULT_TYPOGRAPHY, typographyPreferencesSchema } from '../../../shared/typography/typographyPreferences'
import { DEFAULT_DESKTOP_CHAT_PREFERENCES, DEFAULT_DESKTOP_CHAT_WELCOME_ITEMS, DESKTOP_CHAT_OUTLINE_POSITIONS, DESKTOP_CHAT_READING_WIDTHS, DESKTOP_PROFILE_AVATAR_MAX_DATA_URL_LENGTH, DESKTOP_TASK_SIDEBAR_SECTIONS } from '../../shared/desktopApi'
-
import { desktopChatWelcomeItemsSchema } from '../../shared/desktopApiSchemas'
+
import { isPresetWelcomeId, normalizeDesktopChatWelcomePreference } from '../../shared/desktopChatWelcome'
import { desktopUpdateChannelSchema } from '../../shared/desktopUpdates'
import { isWelcomeCompanionImageDataUrl, welcomeCompanionImageSchema, welcomeCompanionImagesSchema } from '../../shared/welcomeCompanionImage'
+import { runProfileWrite } from '../storage/profileWrites'
function migrateWelcomeItems(value: unknown): unknown {
if (!Array.isArray(value))
@@ -120,6 +122,7 @@ const desktopConfigSchema = z.object({
}),
developer_tools_enabled: z.boolean().default(false),
language: z.enum(['zh-CN', 'en-US']).default('zh-CN'),
+ exit_behavior: desktopExitBehaviorSchema.default(DEFAULT_DESKTOP_EXIT_BEHAVIOR),
launch_at_login: z.boolean().default(false),
notifications_enabled: z.boolean().default(true),
notification_sound: notificationSoundPreferencesSchema.prefault({}),
@@ -165,6 +168,7 @@ const desktopConfigSchema = z.object({
profile: { user_name: '', device_name: '', avatar: '' },
developer_tools_enabled: false,
language: 'zh-CN',
+ exit_behavior: DEFAULT_DESKTOP_EXIT_BEHAVIOR,
launch_at_login: false,
notifications_enabled: true,
notification_sound: DEFAULT_NOTIFICATION_SOUND_PREFERENCES,
@@ -244,12 +248,29 @@ export class LexoraConfigStore {
}
async read(): Promise {
- await this.#writeQueue
const config = decodeConfig(await this.#readFile())
this.#persisted = structuredClone(config)
return config
}
+ initializeExitBehavior(): Promise {
+ return runProfileWrite(dirname(this.#configPath), () => this.#initializeExitBehavior())
+ }
+
+ #initializeExitBehavior(): Promise {
+ const operation = this.#writeQueue.then(async () => {
+ const raw = await this.#readFile() as Record
+ const config = decodeConfig(raw)
+ const desktop = raw.desktop as Record | undefined
+ if (desktop?.exit_behavior === undefined)
+ await this.#write({ ...raw, desktop: { ...desktop, exit_behavior: DEFAULT_DESKTOP_EXIT_BEHAVIOR } }, () => {}, () => {})
+ this.#persisted = structuredClone(config)
+ return config
+ })
+ this.#writeQueue = operation.then(() => undefined, () => undefined)
+ return operation
+ }
+
get snapshot() { return copyEventSnapshot({ revision: this.#revision, persisted: this.#persisted, applied: this.#applied }) }
update(patch: LexoraConfigPatch, apply?: (config: LexoraConfig) => Promise | void, assertCurrent: () => void = () => {}): Promise {
@@ -300,6 +321,10 @@ export class LexoraConfigStore {
}
#update(transform: (current: LexoraConfig) => LexoraConfig, apply: ((config: LexoraConfig) => Promise | void) | undefined, assertCurrent: () => void): Promise {
+ return runProfileWrite(dirname(this.#configPath), () => this.#updateWritable(transform, apply, assertCurrent))
+ }
+
+ #updateWritable(transform: (current: LexoraConfig) => LexoraConfig, apply: ((config: LexoraConfig) => Promise | void) | undefined, assertCurrent: () => void): Promise {
if (this.#disposing)
return Promise.reject(new Error('CONFIG_STORE_STOPPED'))
const operation = this.#writeQueue.then(async () => {
@@ -472,6 +497,7 @@ function decodeConfig(value: unknown): LexoraConfig {
},
developerToolsEnabled: config.desktop.developer_tools_enabled,
language: config.desktop.language,
+ exitBehavior: config.desktop.exit_behavior,
launchAtLogin: config.desktop.launch_at_login,
notificationsEnabled: config.desktop.notifications_enabled,
notificationSound: config.desktop.notification_sound,
@@ -555,6 +581,7 @@ function encodeConfig(config: LexoraConfig) {
},
developer_tools_enabled: config.desktop.developerToolsEnabled,
language: config.desktop.language,
+ exit_behavior: config.desktop.exitBehavior,
launch_at_login: config.desktop.launchAtLogin,
notifications_enabled: config.desktop.notificationsEnabled,
notification_sound: config.desktop.notificationSound,
diff --git a/apps/buddy/electron/main/config/__tests__/initializeDesktopConfig.spec.ts b/apps/buddy/electron/main/config/__tests__/initializeDesktopConfig.spec.ts
index e528d02ff..50fad7c4c 100644
--- a/apps/buddy/electron/main/config/__tests__/initializeDesktopConfig.spec.ts
+++ b/apps/buddy/electron/main/config/__tests__/initializeDesktopConfig.spec.ts
@@ -1,8 +1,9 @@
import { mkdir, readFile, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import { createTemporaryDirectory } from '@buddy-tests/temporaryDirectories'
+import { parse } from 'smol-toml'
import { expect, it } from 'vitest'
-import { initializeDesktopConfig, resolveSystemLanguage } from '../initializeDesktopConfig'
+import { initializeDesktopConfig } from '../initializeDesktopConfig'
import { LexoraConfigStore } from '../LexoraConfigStore'
async function fixture() {
@@ -20,18 +21,18 @@ it('initializes only fresh profiles and persists language, incomplete setup and
expect(await initializeDesktopConfig(new LexoraConfigStore(options), options)).toMatchObject({ desktop: { language: 'zh-CN', onboardingCompleted: true, navigationLayout: 'immersive' }, pet: { enabled: false } })
})
-it('does not enroll or rewrite existing profiles, including empty configs and data without a config', async () => {
+it('persists the exit default without enrolling existing profiles or dropping unknown preferences', async () => {
for (const content of ['', '[desktop]\nlanguage="zh-CN"\n[pet]\nenabled=false\n']) {
const { options, store } = await fixture()
await writeFile(options.configPath, content)
expect((await initializeDesktopConfig(store, options)).desktop).toMatchObject({ language: 'zh-CN', onboardingCompleted: true })
- expect(await readFile(options.configPath, 'utf8')).toBe(content)
+ expect(parse(await readFile(options.configPath, 'utf8'))).toMatchObject({ ...parse(content), desktop: { ...(parse(content).desktop as object ?? {}), exit_behavior: 'stop_service' } })
}
const { options, store } = await fixture()
await mkdir(options.buddyHome)
await writeFile(join(options.buddyHome, 'buddy.sqlite3'), 'existing data')
expect((await initializeDesktopConfig(store, options)).desktop.onboardingCompleted).toBe(true)
- await expect(readFile(options.configPath)).rejects.toMatchObject({ code: 'ENOENT' })
+ expect(parse(await readFile(options.configPath, 'utf8'))).toEqual({ desktop: { exit_behavior: 'stop_service' } })
})
it('preserves corrupt configuration for recovery instead of resetting onboarding', async () => {
@@ -42,10 +43,13 @@ it('preserves corrupt configuration for recovery instead of resetting onboarding
expect(await readFile(options.configPath, 'utf8')).toBe(content)
})
-it.each([
- [['ja-JP', 'zh-Hant-TW', 'en-US'], 'zh-CN'],
- [['en_AU', 'zh-CN'], 'en-US'],
- [['fr-FR'], 'en-US'],
-] as const)('matches supported system languages in priority order: %j', (languages, expected) => {
- expect(resolveSystemLanguage(languages)).toBe(expected)
+it('preserves an explicit exit choice across repeated initialization and partial updates', async () => {
+ const { options, store } = await fixture()
+ await writeFile(options.configPath, '[desktop]\nexit_behavior="keep_service"\nfuture=true\n')
+ const before = await readFile(options.configPath, 'utf8')
+ expect((await initializeDesktopConfig(store, options)).desktop.exitBehavior).toBe('keep_service')
+ expect(await readFile(options.configPath, 'utf8')).toBe(before)
+ await Promise.all([store.initializeExitBehavior(), store.update({ desktop: { language: 'en-US' } })])
+ expect((await new LexoraConfigStore(options).initializeExitBehavior()).desktop.exitBehavior).toBe('keep_service')
+ expect(parse(await readFile(options.configPath, 'utf8'))).toMatchObject({ desktop: { exit_behavior: 'keep_service', future: true } })
})
diff --git a/apps/buddy/electron/main/config/initializeDesktopConfig.ts b/apps/buddy/electron/main/config/initializeDesktopConfig.ts
index 51b6b3cdc..230d16ddc 100644
--- a/apps/buddy/electron/main/config/initializeDesktopConfig.ts
+++ b/apps/buddy/electron/main/config/initializeDesktopConfig.ts
@@ -23,7 +23,7 @@ export async function initializeDesktopConfig(store: LexoraConfigStore, options:
readdir(options.buddyHome).catch(missing),
])
if (config || data?.length)
- return store.read()
+ return store.initializeExitBehavior()
return store.update({ desktop: { onboardingCompleted: false, language: resolveSystemLanguage(options.languages) } })
}
diff --git a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts b/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts
index c2988e44f..060d5e18f 100644
--- a/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts
+++ b/apps/buddy/electron/main/extensions/__tests__/ExtensionTaskCleanupRuntime.spec.ts
@@ -34,6 +34,9 @@ async function runtime(execute: (context: { taskCleanup?: CleanupCommand }) => P
AbortController,
Worker: class {},
createExtensionWorkers: () => ({}),
+ createExtensionResourceClient: () => ({}),
+ createExtensionNetworkClient: () => ({}),
+ createExtensionInferenceClient: () => ({}),
ExtensionHostEvents: class { events = {} },
addEventListener: (_name: string, callback: () => void) => { pagehide = callback },
})
@@ -66,7 +69,6 @@ it('routes by command token, isolates callback failures and releases listeners b
expect(await run).toEqual({ success: true, result })
await f.progress('current', { ...progress, phase: 'scanning', total: null, processed: 0 })
expect(received).toHaveLength(2)
- expect(result.summary).toEqual(summary)
})
it('keeps concurrent command callbacks isolated and removes rejected and unloaded listeners', async () => {
@@ -108,7 +110,7 @@ it('requires confirm before sending a request and does not expose cleanup outsid
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) => {
+it.each([true, false, 'true', '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)
diff --git a/apps/buddy/electron/main/extensions/registerExtensionIpc.ts b/apps/buddy/electron/main/extensions/registerExtensionIpc.ts
index c3544a5f7..92d1923ec 100644
--- a/apps/buddy/electron/main/extensions/registerExtensionIpc.ts
+++ b/apps/buddy/electron/main/extensions/registerExtensionIpc.ts
@@ -74,7 +74,7 @@ export function registerExtensionIpc(options: {
record?: ApplicationDiagnosticReporter
conditionRuntime?: (input: { models: boolean, task: boolean, taskId: string | null, runId: string | null }, signal: AbortSignal) => Promise
agentRequest?: (input: { invocationId: string, method: string, params: JsonValue }, signal: AbortSignal) => Promise
-}): { speech?: SpeechBackend, shells: { list: ExtensionService['shellContributions'] }, skills: { list: ExtensionService['skillContributions'] }, capabilities: { list: ExtensionService['capabilityContributions'] }, inference: { imageReaders: ExtensionService['inferenceImageReaders'], imageModels: ExtensionService['inferenceImageModels'], models: ExtensionService['inferenceModels'], list: ExtensionService['inferenceContributions'], prepare: ExtensionService['prepareInference'], invoke: (extensionId: string, revision: string, input: InferenceInvocation) => Promise, reset: () => Promise }, withStoppedStorage: ExtensionService['withStoppedStorage'], themesReady: Promise, conditions: ExtensionService['conditions'], dispose: () => Promise, reviewPackage: (path: string) => Promise, inspect: (id: string) => Promise, agent: { readResource: ExtensionService['readAgentResource'], list: () => Promise, invoke: (input: ExtensionAgentInvocation, signal: AbortSignal) => Promise } } {
+}): { detachDesktop: () => Promise, speech?: SpeechBackend, shells: { list: ExtensionService['shellContributions'] }, skills: { list: ExtensionService['skillContributions'] }, capabilities: { list: ExtensionService['capabilityContributions'] }, inference: { imageReaders: ExtensionService['inferenceImageReaders'], imageModels: ExtensionService['inferenceImageModels'], models: ExtensionService['inferenceModels'], list: ExtensionService['inferenceContributions'], prepare: ExtensionService['prepareInference'], invoke: (extensionId: string, revision: string, input: InferenceInvocation) => Promise, reset: () => Promise }, withStoppedStorage: ExtensionService['withStoppedStorage'], themesReady: Promise, conditions: ExtensionService['conditions'], dispose: () => Promise, reviewPackage: (path: string) => Promise, inspect: (id: string) => Promise, agent: { releaseAllRuns: ExtensionService['releaseAllRuns'], releaseRun: ExtensionService['releaseRun'], readResource: ExtensionService['readAgentResource'], list: () => Promise, invoke: (input: ExtensionAgentInvocation, signal: AbortSignal) => Promise } } {
const store = new ExtensionPackageStore(join(options.home, 'extensions'), options.version, processExtensionPackageInBackground)
async function reviewResult(operation: () => Promise): Promise {
try {
@@ -90,7 +90,8 @@ export function registerExtensionIpc(options: {
const stopProtocol = protocol.install(session.defaultSession, 'view')
const hosts = new Set()
const replies = new Map void }>()
- const bound = new Set()
+ const bound = new Map void, reset: () => void, navigate: (event: Electron.Event) => void }>()
+ let desktopOwner: BrowserWindow | null = null
let resourcePickerOpen = false
let initializing = true
const vault = createCredentialVault({ buddyHome: options.home, reportDiagnostic: options.record })
@@ -105,6 +106,7 @@ export function registerExtensionIpc(options: {
}
const speechListeners = new Set<() => void>()
const service = new ExtensionService(store, {
+ desktopAvailable: () => false,
documents: options.documents,
clipboard: createExtensionClipboard(options.getWindow),
taskCleanup: options.conversationCleanup ? createExtensionTaskCleanup(options.conversationCleanup) : undefined,
@@ -255,27 +257,37 @@ export function registerExtensionIpc(options: {
}),
observeExtensionDiagnostics(service, event => options.record?.(event)),
]
- const resetHosts = () => {
+ const resetHosts = (owner: BrowserWindow) => {
+ if (desktopOwner !== owner)
+ return
+ desktopOwner = null
options.themes.releaseOwner('desktop')
- void service.resetHosts().catch(() => {})
- }
- const cancelUnconfirmedTaskCleanup = () => service.cancelUnconfirmedTaskCleanup()
- const resetOnNavigation = (event: Electron.Event) => {
- if (event.isMainFrame && !event.isSameDocument)
- resetHosts()
+ void service.detachDesktop().catch(() => {})
}
function window(): BrowserWindow | null {
const current = options.getWindow()
if (current && !current.isDestroyed() && !bound.has(current)) {
- bound.add(current)
- current.on('hide', cancelUnconfirmedTaskCleanup)
- current.webContents.on('will-frame-navigate', guardNavigation)
- current.webContents.on('did-start-navigation', resetOnNavigation)
- current.webContents.on('render-process-gone', resetHosts)
- current.webContents.once('destroyed', () => {
+ const reset = () => resetHosts(current)
+ const navigate = (event: Electron.Event) => {
+ if (event.isMainFrame && !event.isSameDocument)
+ reset()
+ }
+ const hide = () => {
+ if (desktopOwner === current)
+ service.cancelUnconfirmedTaskCleanup()
+ }
+ bound.set(current, { hide, reset, navigate })
+ current.on('hide', hide)
+ const contents = current.webContents
+ contents.on('will-frame-navigate', guardNavigation)
+ contents.on('did-start-navigation', navigate)
+ contents.on('render-process-gone', reset)
+ contents.once('destroyed', () => {
bound.delete(current)
- for (const reply of replies.values()) reply.finish(null)
- resetHosts()
+ if (desktopOwner === current) {
+ for (const reply of replies.values()) reply.finish(null)
+ reset()
+ }
})
}
return current
@@ -307,7 +319,10 @@ export function registerExtensionIpc(options: {
powerMonitor.on('suspend', suspend)
powerMonitor.on('resume', resume)
ipcMain.handle(EXTENSION_IPC.request, async (event, raw: unknown) => {
- assertTrustedSender(event, window())
+ const current = window()
+ assertTrustedSender(event, current)
+ desktopOwner = current
+ service.attachDesktop()
try {
const input = extensionManagementSchema.parse(raw)
await prepared
@@ -406,13 +421,13 @@ export function registerExtensionIpc(options: {
finally {
for (const subscription of subscriptions) subscription.dispose()
for (const reply of replies.values()) reply.finish(null)
- for (const current of bound) {
+ for (const [current, binding] of bound) {
if (current.isDestroyed())
continue
- current.off('hide', cancelUnconfirmedTaskCleanup)
+ current.off('hide', binding.hide)
current.webContents.off('will-frame-navigate', guardNavigation)
- current.webContents.off('did-start-navigation', resetOnNavigation)
- current.webContents.off('render-process-gone', resetHosts)
+ current.webContents.off('did-start-navigation', binding.navigate)
+ current.webContents.off('render-process-gone', binding.reset)
}
stopProtocol()
ipcMain.removeHandler(EXTENSION_IPC.request)
@@ -427,6 +442,11 @@ export function registerExtensionIpc(options: {
owner.webContents.send(EXTENSION_IPC.conditionsChanged, event)
}))
return {
+ async detachDesktop() {
+ desktopOwner = null
+ options.themes.releaseOwner('desktop')
+ await service.detachDesktop()
+ },
skills: { list: async () => {
await prepared
return service.skillContributions()
@@ -490,6 +510,8 @@ export function registerExtensionIpc(options: {
conditions: service.conditions,
dispose,
agent: {
+ releaseAllRuns: () => service.releaseAllRuns(),
+ releaseRun: runId => service.releaseRun(runId),
readResource: (input, signal) => service.readAgentResource(input, signal),
list: async () => {
await prepared
diff --git a/apps/buddy/electron/main/extensions/runtime/host.js b/apps/buddy/electron/main/extensions/runtime/host.js
index 320dab8a7..27370fe64 100644
--- a/apps/buddy/electron/main/extensions/runtime/host.js
+++ b/apps/buddy/electron/main/extensions/runtime/host.js
@@ -32,6 +32,23 @@ 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 executionCapabilities(invocationId, signal) {
+ const scoped = (method, params = null) => {
+ signal.throwIfAborted()
+ return request('invocation.request', { invocationId, method, params })
+ }
+ return Object.freeze({
+ resources: createExtensionResourceClient(scoped),
+ network: createExtensionNetworkClient(scoped),
+ inference: createExtensionInferenceClient(scoped, events),
+ storage: Object.freeze({ get: () => scoped('storage.get'), set: value => scoped('storage.set', { value, version: manifest.dataVersion }) }),
+ window: Object.freeze({ styles: Object.freeze({ set: (id, css) => scoped('window.styles.set', { id, css }), remove: id => scoped('window.styles.remove', { id }) }) }),
+ views: Object.freeze({ broadcast: message => scoped('views.broadcast', message), open: (type, options = {}) => scoped('views.open', { type, resource: options.resource ?? null, state: options.state ?? {} }) }),
+ placements: Object.freeze({ show: (id, options) => scoped('placements.show', { id, ...(typeof options === 'string' ? { instanceId: options } : options ?? {}) }), hide: (id, options) => scoped('placements.hide', { id, ...(typeof options === 'string' ? { instanceId: options } : options ?? {}) }) }),
+ notifications: Object.freeze({ show: notification => scoped('notifications.show', notification) }),
+ })
+}
+
function cleanupCommand(token, signal) {
let used = false
return Object.freeze({ run: async (options) => {
@@ -115,7 +132,7 @@ bridge.subscribe(async ({ id, method, params }) => {
context = Object.freeze({
signal: lifetime.signal,
workers,
- extension: Object.freeze({ id: manifest.id, version: manifest.version, apiVersion: manifest.apiVersion }),
+ extension: Object.freeze({ id: manifest.id, version: manifest.version, apiVersion: manifest.apiVersion, executionScope: manifest.executionScope ?? 'desktop' }),
events,
themes: createThemeClient(input => request('themes.request', input), (listener) => {
themeListeners.add(listener)
@@ -282,6 +299,7 @@ bridge.subscribe(async ({ id, method, params }) => {
try {
const invocation = Object.freeze({
signal: controller.signal,
+ capabilities: executionCapabilities(params.invocationId, controller.signal),
task: Object.freeze({ get: () => call('task.get'), messages: () => call('task.messages'), rename: value => call('task.rename', value) }),
models: Object.freeze({ generateText: value => call('models.generateText', value) }),
...!params.action ? { scope: Object.freeze(await call('task.scope')), artifacts: Object.freeze({ publish: input => call('artifacts.publish', { ...input, resource: { id: input.resource.id } }) }), results: Object.freeze({ addImage: input => call('results.addImage', { resource: { id: input.resource.id } }) }), references: Object.freeze({ list: () => call('references.list'), resolve: (referenceId, options = {}) => call('references.resolve', { ...options, referenceId }) }) } : {},
@@ -301,7 +319,7 @@ bridge.subscribe(async ({ id, method, params }) => {
throw new Error('EXTENSION_COMMAND_UNAVAILABLE')
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
+ result = await commands.get(params.command)(Object.freeze({ signal: controller.signal, capabilities: executionCapabilities(params.scopeId, controller.signal), resource: params.resource, arguments: params.arguments ?? null, invocation: params.invocation ?? null, taskCleanup: params.cleanupToken ? cleanupCommand(params.cleanupToken, controller.signal) : undefined })) ?? null
}
finally { controller.abort() }
}
diff --git a/apps/buddy/electron/main/index.ts b/apps/buddy/electron/main/index.ts
index 20fe52cc5..31185c40e 100644
--- a/apps/buddy/electron/main/index.ts
+++ b/apps/buddy/electron/main/index.ts
@@ -1,3 +1,6 @@
import { startDesktopApplication } from './app/DesktopApplication'
+import { startDesktopServiceEntry } from './app/desktopServiceEntry'
+import { registerDesktopSchemes } from './app/environment'
-void startDesktopApplication()
+registerDesktopSchemes()
+void startDesktopServiceEntry().then(handled => handled ? undefined : startDesktopApplication())
diff --git a/apps/buddy/electron/main/local-chat/conversation.ts b/apps/buddy/electron/main/local-chat/conversation.ts
index 5303081a1..618aa5380 100644
--- a/apps/buddy/electron/main/local-chat/conversation.ts
+++ b/apps/buddy/electron/main/local-chat/conversation.ts
@@ -37,7 +37,6 @@ export function registerConversationIpc(context: LocalChatIpcContext): void {
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsGet, (_event, input) => request(conversationsRpc.get, conversationRequestSchemas.conversationId.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsGetModelControls, (_event, input) => request(conversationsRpc.getModelControls, conversationRequestSchemas.modelControls.parse(input)))
- handle(LOCAL_CHAT_IPC_CHANNELS.conversationsDeletePermanently, (_event, input) => request(conversationArchiveRpc.deletePermanently, conversationArchiveRpc.deletePermanently.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsArchive, (_event, input) => request(conversationArchiveRpc.archive, conversationArchiveRpc.archive.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsRestoreArchive, (_event, input) => request(conversationArchiveRpc.restoreArchive, conversationArchiveRpc.restoreArchive.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsDeleteArchived, (_event, input) => request(conversationArchiveRpc.deleteArchived, conversationArchiveRpc.deleteArchived.input.parse(input)))
@@ -45,7 +44,7 @@ export function registerConversationIpc(context: LocalChatIpcContext): void {
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsGetArchivePolicy, () => request(conversationArchiveRpc.getArchivePolicy, {}))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsSetArchivePolicy, (_event, input) => request(conversationArchiveRpc.setArchivePolicy, conversationArchiveRpc.setArchivePolicy.input.parse(input)))
- handle(LOCAL_CHAT_IPC_CHANNELS.conversationsDelete, (_event, input) => request(conversationsRpc.delete, conversationRequestSchemas.conversationId.parse(input)))
+ handle(LOCAL_CHAT_IPC_CHANNELS.conversationsDelete, (_event, input) => request(conversationsRpc.delete, conversationsRpc.delete.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.conversationsActivateBranch, (_event, input) => request(conversationsRpc.activateBranch, conversationRequestSchemas.conversationBranchActivation.parse(input)))
@@ -77,5 +76,5 @@ export function registerConversationIpc(context: LocalChatIpcContext): void {
handle(LOCAL_CHAT_IPC_CHANNELS.chatRegenerateAssistant, (_event, input) => request(chatRpc.regenerateAssistant, chatRequestSchemas.regenerateAssistant.parse(input)))
- handle(LOCAL_CHAT_IPC_CHANNELS.chatCancel, (_event, input) => request(chatRpc.cancel, runsRequestSchemas.runId.parse(input)))
+ handle(LOCAL_CHAT_IPC_CHANNELS.chatCancel, (_event, input) => request(chatRpc.cancel, runsRequestSchemas.cancel.parse(input)))
}
diff --git a/apps/buddy/electron/main/local-chat/executions.ts b/apps/buddy/electron/main/local-chat/executions.ts
index 2110a4193..d3555dcce 100644
--- a/apps/buddy/electron/main/local-chat/executions.ts
+++ b/apps/buddy/electron/main/local-chat/executions.ts
@@ -3,6 +3,7 @@ import { executionPresentationRpc } from '../../../shared/executions/executionPr
import { LOCAL_CHAT_IPC_CHANNELS } from '../../shared/localChatApi'
export function registerExecutionsIpc({ handle, request }: LocalChatIpcContext): void {
+ handle(LOCAL_CHAT_IPC_CHANNELS.executionsActivity, (_event, input) => request(executionPresentationRpc.activity, executionPresentationRpc.activity.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.executionsList, (_event, input) => request(executionPresentationRpc.list, executionPresentationRpc.list.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.executionsDetail, (_event, input) => request(executionPresentationRpc.detail, executionPresentationRpc.detail.input.parse(input)))
handle(LOCAL_CHAT_IPC_CHANNELS.executionsInputs, (_event, input) => request(executionPresentationRpc.inputs, executionPresentationRpc.inputs.input.parse(input)))
diff --git a/apps/buddy/electron/main/local-chat/privateNetwork.ts b/apps/buddy/electron/main/local-chat/privateNetwork.ts
new file mode 100644
index 000000000..8805df28b
--- /dev/null
+++ b/apps/buddy/electron/main/local-chat/privateNetwork.ts
@@ -0,0 +1,12 @@
+import type { LocalChatIpcContext } from './registrar'
+import { privateNetworkManagement } from '../../../shared/privateNetwork/management'
+import { PRIVATE_NETWORK_IPC_PREFIX } from '../../shared/privateNetworkApi'
+
+export function registerPrivateNetworkIpc({ handle, options }: LocalChatIpcContext): void {
+ for (const [name, contract] of Object.entries(privateNetworkManagement)) {
+ handle(`${PRIVATE_NETWORK_IPC_PREFIX}${name}`, async (_event, input) => {
+ const value = contract.input.parse(input)
+ return contract.response.parse(await options.runtime.request(contract.method, value))
+ })
+ }
+}
diff --git a/apps/buddy/electron/main/local-chat/registrar.ts b/apps/buddy/electron/main/local-chat/registrar.ts
index d0fa1669f..2726b4fb9 100644
--- a/apps/buddy/electron/main/local-chat/registrar.ts
+++ b/apps/buddy/electron/main/local-chat/registrar.ts
@@ -2,6 +2,7 @@ import type { BrowserWindow, IpcMainInvokeEvent } from 'electron'
import type { ApplicationDiagnostic, ApplicationDiagnosticReporter } from '../../../shared/diagnostics/applicationDiagnostic'
import type { RuntimeRequestContract, RuntimeRequestInput, RuntimeRequestResult } from '../../../shared/runtime/apiContract'
import type { LocalChatErrorCode } from '../../../shared/runtime/localChatError'
+import type { ProductRecoveryItem } from '../../../shared/runtime/productRecovery'
import type { LexoraConfig } from '../../shared/desktopApi'
import { randomUUID } from 'node:crypto'
import { ipcMain } from 'electron'
@@ -12,6 +13,9 @@ import { formatLocalChatPublicError, readLocalChatErrorCode } from '../../../sha
import { assertTrustedSender } from '../ipc'
export interface DesktopRuntimeGateway {
+ recover?: () => Promise
+ acknowledgeRecovery?: (id: string) => Promise
+ restoreRecovery?: (id: string) => Promise
readonly state: unknown
onNotification: (
listener: (notification: { method: string, params: unknown }) => void,
diff --git a/apps/buddy/electron/main/local-chat/runtime.ts b/apps/buddy/electron/main/local-chat/runtime.ts
index c95574600..711daee6c 100644
--- a/apps/buddy/electron/main/local-chat/runtime.ts
+++ b/apps/buddy/electron/main/local-chat/runtime.ts
@@ -1,10 +1,21 @@
import type { LocalChatIpcContext } from './registrar'
+import { productRecoveryListSchema, productRecoveryTargetSchema } from '../../../shared/runtime/productRecovery'
import { runtimeResponseSchemas } from '../../../shared/runtime/serviceState'
import { LOCAL_CHAT_IPC_CHANNELS } from '../../shared/localChatApi'
export function registerRuntimeIpc(context: LocalChatIpcContext): void {
const { handle, options } = context
+ handle(LOCAL_CHAT_IPC_CHANNELS.runtimeRecoveryList, async () => productRecoveryListSchema.parse(await options.runtime.recover?.() ?? []))
+ handle(LOCAL_CHAT_IPC_CHANNELS.runtimeRecoveryAcknowledge, async (_event, input) => {
+ await options.runtime.acknowledgeRecovery?.(productRecoveryTargetSchema.parse(input).id)
+ })
+ handle(LOCAL_CHAT_IPC_CHANNELS.runtimeRecoveryRestore, async (_event, input) => {
+ if (!options.runtime.restoreRecovery)
+ throw new Error('Recovery unavailable')
+ return options.runtime.restoreRecovery(productRecoveryTargetSchema.parse(input).id)
+ })
+
handle(LOCAL_CHAT_IPC_CHANNELS.runtimeStatus, () => (
runtimeResponseSchemas.runtimeState.parse(options.runtime.state)
))
diff --git a/apps/buddy/electron/main/localChatIpc.ts b/apps/buddy/electron/main/localChatIpc.ts
index a9709eb5c..215175263 100644
--- a/apps/buddy/electron/main/localChatIpc.ts
+++ b/apps/buddy/electron/main/localChatIpc.ts
@@ -7,6 +7,7 @@ import { registerConnectorsIpc } from './local-chat/connectors'
import { registerConversationIpc } from './local-chat/conversation'
import { registerExecutionsIpc } from './local-chat/executions'
import { registerLocalChatNotifications } from './local-chat/notifications'
+import { registerPrivateNetworkIpc } from './local-chat/privateNetwork'
import { registerPromptsIpc } from './local-chat/prompts'
import { registerProvidersIpc } from './local-chat/providers'
import { registerQuestionsIpc } from './local-chat/questions'
@@ -26,6 +27,7 @@ export function registerLocalChatIpc(options: RegisterLocalChatIpcOptions): () =
registerExecutionsIpc(context)
registerQuestionsIpc(context)
registerRuntimeIpc(context)
+ registerPrivateNetworkIpc(context)
registerActivityIpc(context)
registerAutomationsIpc(context)
registerPromptsIpc(context)
diff --git a/apps/buddy/electron/main/productProtocol/DesktopProductCommands.ts b/apps/buddy/electron/main/productProtocol/DesktopProductCommands.ts
new file mode 100644
index 000000000..ad35481a9
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/DesktopProductCommands.ts
@@ -0,0 +1,120 @@
+import type { ProductIdentity } from '../../../shared/productProtocol/identity'
+import type { ProductCommandMethod } from '../../../shared/productProtocol/methods'
+import type { ProductOutboxRecord, ProductOutboxStore, ProductRecoveryInput } from './ProductOutboxStore'
+import { productCommandLookupSchema, productCommandResultSchema } from '../../../shared/productProtocol/receipts'
+import { isProductOutboxOwner } from './ProductOutboxStore'
+
+export interface DesktopProductConnection {
+ readonly identity: ProductIdentity
+ request: (method: string, params: unknown) => Promise
+}
+export interface DesktopCommandOutcome {
+ state: 'decided' | 'not_accepted' | 'unknown' | 'trust_changed' | 'connection_replaced'
+ record: ProductOutboxRecord
+}
+
+export class DesktopProductCommands {
+ #connection: DesktopProductConnection | null = null
+ #commands = new Map>()
+
+ readonly outbox: ProductOutboxStore
+
+ constructor(outbox: ProductOutboxStore) {
+ this.outbox = outbox
+ }
+
+ attach(connection: DesktopProductConnection): () => void {
+ this.#connection = connection
+ return () => {
+ if (this.#connection === connection)
+ this.#connection = null
+ }
+ }
+
+ execute(input: { method: ProductCommandMethod, commandId: string, intent: unknown, recovery?: ProductRecoveryInput }): Promise {
+ const connection = this.#connection
+ if (!connection)
+ return Promise.reject(new Error('PRODUCT_CONNECTION_UNAVAILABLE'))
+ const key = commandKey(connection.identity, input.commandId)
+ const prior = this.#commands.get(key)
+ const run = () => this.#execute(connection, input)
+ const next = prior ? prior.then(run, run) : run()
+ this.#commands.set(key, next)
+ void next.finally(() => {
+ if (this.#commands.get(key) === next)
+ this.#commands.delete(key)
+ }).catch(() => {})
+ return next
+ }
+
+ async #execute(connection: DesktopProductConnection, input: { method: ProductCommandMethod, commandId: string, intent: unknown, recovery?: ProductRecoveryInput }): Promise {
+ const { created, record } = await this.outbox.create({
+ identity: connection.identity,
+ method: input.method,
+ envelope: { commandId: input.commandId, dataGeneration: connection.identity.dataGeneration, expectedServiceInstanceId: connection.identity.serviceInstanceId, intent: input.intent },
+ recovery: input.recovery,
+ })
+ if (!created)
+ return this.#reconcile(record)
+ if (this.#connection !== connection)
+ return { state: 'connection_replaced', record }
+ const uncertain = await this.outbox.markUncertain(record)
+ if (this.#connection !== connection)
+ return { state: 'connection_replaced', record: uncertain }
+ try {
+ const result = productCommandResultSchema.parse(await connection.request(record.method, record.envelope))
+ const decided = await this.outbox.decide(uncertain, result.receipt)
+ return { state: this.#connection === connection ? 'decided' : 'connection_replaced', record: decided }
+ }
+ catch {
+ return { state: this.#connection === connection ? 'unknown' : 'connection_replaced', record: uncertain }
+ }
+ }
+
+ async reconcile(record: ProductOutboxRecord): Promise {
+ const pending = this.#commands.get(commandKey(record.owner, record.commandId))
+ if (pending)
+ await pending.catch(() => {})
+ return this.#reconcile(await this.outbox.read(record.owner, record.commandId) ?? record)
+ }
+
+ async #reconcile(record: ProductOutboxRecord): Promise {
+ const connection = this.#connection
+ if (!connection)
+ return { state: 'unknown', record }
+ if (!isProductOutboxOwner(record.owner, connection.identity))
+ return { state: 'trust_changed', record }
+ if (record.state === 'decided')
+ return { state: 'decided', record }
+ try {
+ const result = productCommandLookupSchema.parse(await connection.request('commands.get', { dataGeneration: record.owner.dataGeneration, commandId: record.commandId }))
+ if (this.#connection !== connection)
+ return { state: 'connection_replaced', record }
+ if (result.lookup === 'decided') {
+ const decided = await this.outbox.decide(record, result.receipt)
+ return { state: this.#connection === connection ? 'decided' : 'connection_replaced', record: decided }
+ }
+ if (result.lookup === 'not_found') {
+ const absent = await this.outbox.confirmAbsent(record)
+ return { state: this.#connection === connection ? 'not_accepted' : 'connection_replaced', record: absent }
+ }
+ return { state: 'unknown', record }
+ }
+ catch {
+ return { state: this.#connection === connection ? 'unknown' : 'connection_replaced', record }
+ }
+ }
+
+ async recover(): Promise {
+ const outcomes: DesktopCommandOutcome[] = []
+ for (const record of await this.outbox.list()) {
+ if (record.envelope || record.recovery)
+ outcomes.push(await this.reconcile(record))
+ }
+ return outcomes
+ }
+}
+
+function commandKey(owner: Pick, commandId: string): string {
+ return JSON.stringify([owner.serviceId, owner.profileId, owner.dataGeneration, owner.deviceId, commandId])
+}
diff --git a/apps/buddy/electron/main/productProtocol/DesktopTaskSynchronization.ts b/apps/buddy/electron/main/productProtocol/DesktopTaskSynchronization.ts
new file mode 100644
index 000000000..ae88b71c6
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/DesktopTaskSynchronization.ts
@@ -0,0 +1,83 @@
+import type { z } from 'zod'
+import type { ProductRpcClient } from './ProductRpcClient'
+import { CONVERSATION_CHANGED, conversationSchema } from '../../../shared/conversation/conversationApi'
+import { productTaskSummarySchema } from '../../../shared/productProtocol/queries'
+import { decodeSafeProductRevision } from '../../../shared/productProtocol/scalars'
+import { productTaskIndexChangeSchema } from '../../../shared/productProtocol/topics'
+import { ProductSyncClient } from './ProductSyncClient'
+
+type Task = z.infer
+
+export class DesktopTaskSynchronization {
+ readonly #sync: ProductSyncClient
+ readonly #notify: (notification: { method: string, params: unknown }) => void
+ #closed = false
+ #tasks = new Map()
+ #retry: ReturnType | undefined
+
+ constructor(client: ProductRpcClient, notify: (notification: { method: string, params: unknown }) => void) {
+ this.#sync = new ProductSyncClient(client)
+ this.#notify = notify
+ this.#subscribe()
+ }
+
+ close(): void {
+ this.#closed = true
+ clearTimeout(this.#retry)
+ this.#sync.close()
+ this.#tasks.clear()
+ }
+
+ #subscribe(): void {
+ if (this.#closed)
+ return
+ let staged = new Map()
+ const handle = this.#sync.subscribe('taskIndex', {
+ item: productTaskSummarySchema,
+ change: productTaskIndexChangeSchema,
+ beginSnapshot: () => { staged = new Map() },
+ appendSnapshot: (tasks) => { for (const task of tasks) staged.set(task.id, task) },
+ commitSnapshot: () => {
+ if (this.#closed)
+ return
+ for (const [id, task] of this.#tasks) {
+ if (!staged.has(id))
+ this.#publish(task, true)
+ }
+ this.#tasks = staged
+ for (const task of staged.values()) this.#publish(task)
+ },
+ applyChanges: (changes) => {
+ if (this.#closed)
+ return
+ const next = new Map(this.#tasks)
+ for (const change of changes) {
+ if (change.kind === 'remove') {
+ const previous = next.get(change.id)
+ next.delete(change.id)
+ if (previous)
+ this.#publish(previous, true)
+ }
+ else {
+ next.set(change.value.id, change.value)
+ this.#publish(change.value)
+ }
+ }
+ this.#tasks = next
+ },
+ invalidate: () => {
+ if (!this.#closed) {
+ clearTimeout(this.#retry)
+ this.#retry = setTimeout(() => this.#subscribe(), 1000)
+ }
+ },
+ })
+ void handle.ready.catch(() => {})
+ }
+
+ #publish(task: Task, deleted = false): void {
+ const fields = Object.fromEntries(Object.keys(conversationSchema.shape).filter(key => key in task).map(key => [key, task[key as keyof Task]]))
+ const value = conversationSchema.parse({ ...fields, metadataRevision: decodeSafeProductRevision(task.revision), titleRevision: decodeSafeProductRevision(task.titleRevision), ...(deleted ? { deletedAt: new Date().toISOString() } : {}) })
+ this.#notify({ method: CONVERSATION_CHANGED, params: value })
+ }
+}
diff --git a/apps/buddy/electron/main/productProtocol/ProductDesktopGateway.ts b/apps/buddy/electron/main/productProtocol/ProductDesktopGateway.ts
new file mode 100644
index 000000000..be18e9615
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/ProductDesktopGateway.ts
@@ -0,0 +1,384 @@
+import type { z } from 'zod'
+import type { ProductCommandMethod } from '../../../shared/productProtocol/methods'
+import type { productCommandReceiptSchema } from '../../../shared/productProtocol/receipts'
+import type { ProductRecoveryItem } from '../../../shared/runtime/productRecovery'
+import type { DesktopRuntimeGateway } from '../local-chat/registrar'
+import type { ProductOutboxRecord, ProductRecoveryInput } from './ProductOutboxStore'
+import { randomUUID } from 'node:crypto'
+import { buddyComposerDraftSchema } from '../../../shared/conversation/composerDraft'
+import { conversationRequestSchemas, conversationResponseSchemas } from '../../../shared/conversation/conversationApi'
+import { conversationArchivePolicySchema } from '../../../shared/conversation/conversationArchiveApi'
+import { APPROVAL_REVIEW_KINDS } from '../../../shared/permissions/approvalReviewPayload'
+import { productCommandIntents } from '../../../shared/productProtocol/methods'
+import { productConversationArchivePageSchema } from '../../../shared/productProtocol/queries'
+import { decodeSafeProductRevision, encodeProductRevision } from '../../../shared/productProtocol/scalars'
+import { desktopProductContentProject } from '../../../shared/productProtocol/transport'
+import { userQuestionRpc } from '../../../shared/questions/userQuestionApi'
+import { runsResponseSchemas } from '../../../shared/runs/runApi'
+import { DesktopProductCommands } from './DesktopProductCommands'
+import { DesktopTaskSynchronization } from './DesktopTaskSynchronization'
+import { isProductOutboxOwner, productOutboxRecordId, ProductOutboxStore } from './ProductOutboxStore'
+import { ProductRpcClient } from './ProductRpcClient'
+
+const turnMethods = new Set(['chat.startTurn', 'chat.editUserMessage', 'chat.regenerateAssistant', 'chat.executeCommand'])
+const draftMethods = new Set(['composerDrafts.open', 'composerDrafts.save'])
+const questionMethods = new Set(['questions.answer', 'questions.cancel', 'questions.retry'])
+type Receipt = z.infer
+
+export class ProductDesktopGateway implements DesktopRuntimeGateway {
+ readonly #runtime: DesktopRuntimeGateway
+ readonly #version: string
+ readonly #commands: DesktopProductCommands
+ readonly #stopState: () => void
+ readonly #notifications = new Set<(notification: { method: string, params: unknown }) => void>()
+ #synchronization: DesktopTaskSynchronization | null = null
+ #client: Promise | null = null
+ #current: ProductRpcClient | null = null
+ #generation = 0
+ #detach: (() => void) | null = null
+
+ constructor(runtime: DesktopRuntimeGateway, directory: string, version: string) {
+ this.#runtime = runtime
+ this.#version = version
+ this.#commands = new DesktopProductCommands(new ProductOutboxStore(directory))
+ this.#stopState = runtime.onStateChange((state) => {
+ if (!state || typeof state !== 'object' || !('status' in state) || state.status !== 'ready')
+ this.#reset()
+ })
+ }
+
+ get state(): unknown {
+ return this.#runtime.state
+ }
+
+ onNotification: DesktopRuntimeGateway['onNotification'] = (listener) => {
+ const stop = this.#runtime.onNotification(listener)
+ this.#notifications.add(listener)
+ return () => {
+ stop()
+ this.#notifications.delete(listener)
+ }
+ }
+
+ onStateChange: DesktopRuntimeGateway['onStateChange'] = listener => this.#runtime.onStateChange(listener)
+ restart: DesktopRuntimeGateway['restart'] = () => this.#runtime.restart()
+
+ async request(method: string, params: unknown, options?: { timeoutMs?: number, requestId?: string }): Promise {
+ if (method === 'conversations.listArchived' || method === 'conversations.getArchivePolicy') {
+ const client = await this.#connect()
+ const result = await client.request(method, params)
+ if (this.#current !== client)
+ throw gatewayError('COMMAND_RESULT_UNKNOWN')
+ if (method === 'conversations.getArchivePolicy')
+ return conversationArchivePolicySchema.parse(result)
+ const page = productConversationArchivePageSchema.parse(result)
+ return { ...page, items: page.items.map(({ revision, ...item }) => ({ ...item, metadataRevision: decodeSafeProductRevision(revision) })) }
+ }
+ const productMethod = method === 'approvals.approve' || method === 'approvals.deny' ? 'approvals.resolve' : method
+ if (!Object.hasOwn(productCommandIntents, productMethod))
+ return this.#runtime.request(method, params, options)
+ const client = await this.#connect()
+ const input = objectInput(params)
+ const intent = { ...input }
+ const commandId = !questionMethods.has(method) && typeof intent.requestId === 'string' ? intent.requestId : options?.requestId ?? randomUUID()
+ if (!questionMethods.has(method))
+ delete intent.requestId
+ if (method === 'composerDrafts.open') {
+ const current = objectInput(await client.request('composerDrafts.find', { scope: input.scope }))
+ if (current.draft) {
+ const draft = objectInput(current.draft)
+ return this.#runtime.request('composerDrafts.get', { draftId: draft.draftId }, options)
+ }
+ intent.expectedSlotRevision = current.slotRevision
+ }
+ if (draftMethods.has(method)) {
+ const field = method === 'composerDrafts.open' ? 'initialContent' : 'content'
+ intent[field] = desktopProductContentProject.response.parse(await this.#runtime.request(desktopProductContentProject.method, { content: input[field] }, options)).content
+ }
+ if (method === 'composerDrafts.copy' && intent.recoveredInput) {
+ const recovered = objectInput(intent.recoveredInput)
+ intent.recoveredInput = { ...recovered, content: desktopProductContentProject.response.parse(await this.#runtime.request(desktopProductContentProject.method, { content: recovered.content }, options)).content }
+ }
+ if (productMethod === 'approvals.resolve') {
+ const conditions = objectInput(input.conditions)
+ intent.runId = conditions.runId
+ intent.reviewVersion = conditions.reviewVersion
+ intent.decision = method === 'approvals.deny' ? 'denied' : input.scope === 'once' ? 'approved' : input.scope === 'persistent' ? 'approved_persistently' : `approved_for_${input.scope}`
+ delete intent.conditions
+ delete intent.scope
+ }
+ const actualMethod = productMethod === 'chat.queue.steer' && intent.targetRunId === null ? 'chat.queue.continue' : productMethod
+ if (actualMethod === 'chat.queue.continue') {
+ delete intent.targetRunId
+ delete intent.expectedRunGeneration
+ }
+ for (const key of ['expectedRevision', 'expectedSourceRevision', 'expectedSlotRevision', 'expectedRunGeneration', 'expectedTitleRevision', 'expectedAssignmentRevision', 'readRevision']) {
+ if (typeof intent[key] === 'number')
+ intent[key] = encodeProductRevision(intent[key])
+ }
+ if (intent.expectedActiveRun && typeof intent.expectedActiveRun === 'object') {
+ const active = objectInput(intent.expectedActiveRun)
+ intent.expectedActiveRun = { ...active, generation: encodeProductRevision(Number(active.generation)) }
+ }
+ const recovery = await this.#recoveryInput(method, input, client, commandId)
+ const outcome = await this.#commands.execute({ method: actualMethod as ProductCommandMethod, commandId, intent, recovery })
+ if (outcome.state !== 'decided' || !outcome.record.receipt)
+ throw gatewayError(outcome.state === 'trust_changed' ? 'AUTHENTICATION_REQUIRED' : 'COMMAND_RESULT_UNKNOWN')
+ const receipt = outcome.record.receipt
+ if (receipt.decision === 'rejected')
+ throw gatewayError(receipt.errorCode ?? 'LOCAL_CHAT_OPERATION_FAILED')
+ if (this.#current !== client)
+ throw gatewayError('COMMAND_RESULT_UNKNOWN')
+ const result = await this.#projectResult(method, input, receipt, options)
+ if (this.#current !== client)
+ throw gatewayError('COMMAND_RESULT_UNKNOWN')
+ void this.#commands.outbox.archive(outcome.record).catch(() => {})
+ return result
+ }
+
+ async getIdentity() {
+ return (await this.#connect()).identity
+ }
+
+ async recover(): Promise {
+ const client = await this.#connect()
+ const outcomes = await this.#commands.recover()
+ return outcomes.map(({ state, record }) => {
+ const status = state === 'decided' ? record.receipt!.decision : state === 'connection_replaced' ? 'unknown' : state
+ return {
+ id: productOutboxRecordId(record),
+ commandId: record.commandId,
+ method: record.method,
+ createdAt: record.createdAt,
+ state: status,
+ conversationId: record.receipt?.target.conversationId ?? null,
+ content: record.recovery?.content ?? null,
+ canRestore: (status === 'rejected' || status === 'not_accepted') && Boolean(record.recovery?.executionConfig) && isProductOutboxOwner(record.owner, client.identity),
+ }
+ })
+ }
+
+ async acknowledgeRecovery(id: string): Promise {
+ const record = await this.#recoveryRecord(id)
+ await this.#commands.outbox.archive(record)
+ }
+
+ async restoreRecovery(id: string): Promise {
+ const client = await this.#connect()
+ const outcome = await this.#commands.reconcile(await this.#recoveryRecord(id))
+ const source = outcome.record.recovery
+ if (!isProductOutboxOwner(outcome.record.owner, client.identity) || !source?.executionConfig
+ || !(outcome.state === 'not_accepted' || (outcome.state === 'decided' && outcome.record.receipt?.decision === 'rejected'))) {
+ throw gatewayError('COMMAND_RESULT_UNKNOWN')
+ }
+ const commandId = `recovery-${id}`
+ const previous = await this.#commands.outbox.read(outboxOwner(client), commandId)
+ if (previous) {
+ const recovered = await this.#commands.reconcile(previous)
+ if (recovered.state !== 'decided' || recovered.record.receipt?.decision !== 'accepted' || !recovered.record.receipt.target.draftId)
+ throw gatewayError('COMMAND_RESULT_UNKNOWN')
+ await this.#commands.outbox.archive(outcome.record)
+ return recovered.record.receipt.target.draftId
+ }
+ const current = await client.request('composerDrafts.get', { draftId: source.draftId }) as { revision: string } | null
+ let draftId: string
+ if (current) {
+ const draft = buddyComposerDraftSchema.parse(await this.request('composerDrafts.copy', {
+ sourceDraftId: source.draftId,
+ expectedSourceRevision: current.revision,
+ targetScope: { kind: 'task', spaceId: null },
+ expectedSlotRevision: '0',
+ recoveredInput: { content: source.content, executionConfig: source.executionConfig, modelSelection: source.modelSelection ?? null, ...(source.participants ? { participants: source.participants } : {}) },
+ }, { requestId: commandId }))
+ draftId = draft.draftId
+ }
+ else {
+ draftId = `recovered-${id.slice(0, 32)}`
+ await this.request('composerDrafts.open', {
+ draftId,
+ scope: { kind: 'task', draftId, spaceId: null },
+ initialContent: source.content,
+ initialExecutionConfig: source.executionConfig,
+ initialModelSelection: source.modelSelection ?? null,
+ ...(source.participants ? { initialParticipants: source.participants } : {}),
+ }, { requestId: commandId })
+ }
+ await this.#commands.outbox.archive(outcome.record)
+ return draftId
+ }
+
+ async #recoveryRecord(id: string): Promise {
+ const record = (await this.#commands.outbox.list()).find(record => productOutboxRecordId(record) === id)
+ if (!record)
+ throw gatewayError('OBJECT_DELETED')
+ return record
+ }
+
+ async #recoveryInput(method: string, input: Record, client: ProductRpcClient, commandId: string): Promise {
+ const existing = await this.#commands.outbox.read(outboxOwner(client), commandId)
+ if (existing)
+ return existing.recovery ?? undefined
+ if (method === 'composerDrafts.open' || method === 'composerDrafts.save') {
+ const opening = method === 'composerDrafts.open'
+ const draft = buddyComposerDraftSchema.parse({
+ draftId: input.draftId,
+ content: input[opening ? 'initialContent' : 'content'],
+ modelSelection: input[opening ? 'initialModelSelection' : 'modelSelection'],
+ executionConfig: input[opening ? 'initialExecutionConfig' : 'executionConfig'],
+ participants: input[opening ? 'initialParticipants' : 'participants'],
+ scope: input.scope ?? { kind: 'global' },
+ revision: input.expectedRevision ?? 0,
+ updatedAt: new Date().toISOString(),
+ })
+ return { draftId: draft.draftId, editSequence: String(draft.revision), content: draft.content, executionConfig: draft.executionConfig, modelSelection: draft.modelSelection, participants: draft.participants }
+ }
+ if (typeof input.draftId === 'string' && (turnMethods.has(method) || method === 'chat.queue.enqueue')) {
+ const draft = buddyComposerDraftSchema.parse(await this.#runtime.request('composerDrafts.get', { draftId: input.draftId }))
+ if (draft.revision === input.expectedRevision)
+ return { draftId: draft.draftId, editSequence: String(draft.revision), content: draft.content, executionConfig: draft.executionConfig, modelSelection: draft.modelSelection, participants: draft.participants }
+ }
+ return undefined
+ }
+
+ dispose(): void {
+ this.#stopState()
+ this.#reset()
+ }
+
+ #reset(): void {
+ this.#generation += 1
+ this.#synchronization?.close()
+ this.#synchronization = null
+ this.#detach?.()
+ this.#detach = null
+ this.#current?.close()
+ this.#current = null
+ this.#client = null
+ }
+
+ #connect(): Promise {
+ if (this.#client)
+ return this.#client
+ const generation = this.#generation
+ const client = new ProductRpcClient({
+ send: frame => this.#runtime.request('product.exchange', { frame }).then(() => {}),
+ subscribe: listener => this.#runtime.onNotification((notification) => {
+ if (notification.method !== 'product.frame')
+ return
+ const value = notification.params
+ if (value && typeof value === 'object' && 'frame' in value && typeof value.frame === 'string')
+ listener(value.frame)
+ }),
+ close: () => {},
+ })
+ this.#current = client
+ this.#client = client.initialize({ protocol: { major: 1, minMinor: 0, maxMinor: 0 }, client: { kind: 'desktop', version: this.#version }, supportedContentKinds: ['buddy-user-content-v1'], supportedReviewKinds: [...APPROVAL_REVIEW_KINDS] }).then(() => {
+ if (generation !== this.#generation) {
+ client.close()
+ throw gatewayError('RUNTIME_UNAVAILABLE')
+ }
+ this.#detach = this.#commands.attach(client)
+ this.#synchronization = new DesktopTaskSynchronization(client, (notification) => {
+ if (generation !== this.#generation)
+ return
+ for (const listener of this.#notifications) {
+ try {
+ listener(notification)
+ }
+ catch {}
+ }
+ })
+ return client
+ })
+ return this.#client
+ }
+
+ async #projectResult(method: string, input: Record, receipt: Receipt, options?: { timeoutMs?: number, requestId?: string }): Promise {
+ const read = (method: string, params: unknown) => this.#runtime.request(method, params, options)
+ if (questionMethods.has(method)) {
+ const questions = userQuestionRpc.list.response.parse(await read('questions.list', { conversationId: input.conversationId, branchId: input.branchId }))
+ const question = questions.find(question => question.id === receipt.target.questionId)
+ if (!question)
+ throw gatewayError('OBJECT_DELETED')
+ return question
+ }
+ if (turnMethods.has(method)) {
+ const run = runsResponseSchemas.run.parse(await read('runs.get', { runId: receipt.target.runId }))
+ let userMessage = null
+ if (run.purpose === 'chat' && run.triggeringMessageId) {
+ let cursor: string | null = null
+ do {
+ const page = conversationResponseSchemas.messagePage.parse(await read('conversations.listMessages', conversationRequestSchemas.conversationMessages.parse({ conversationId: run.conversationId, branchId: run.branchId, ...(cursor ? { cursor } : {}) })))
+ userMessage = page.items.find(message => message.id === run.triggeringMessageId) ?? null
+ cursor = page.nextCursor
+ } while (!userMessage && cursor)
+ }
+ const draft = receipt.result.draftReceipt
+ return { conversationId: run.conversationId, branchId: run.branchId, runId: run.id, run, userMessage, draftReceipt: draft ? { draftId: draft.draftId, sourceRevision: input.expectedRevision, committedRevision: decodeSafeProductRevision(draft.committedRevision) } : null }
+ }
+ if (draftMethods.has(method) || method === 'composerDrafts.copy') {
+ const draft = buddyComposerDraftSchema.parse(await read('composerDrafts.get', { draftId: receipt.target.draftId }))
+ if (method === 'composerDrafts.save' && draft.revision !== decodeSafeProductRevision(receipt.result.revision!))
+ throw gatewayError('DRAFT_CONFLICT')
+ return draft
+ }
+ if (method === 'composerDrafts.discard')
+ return receipt.result.discarded === true
+ if (method === 'chat.queue.enqueue') {
+ const draft = receipt.result.draftReceipt!
+ return { id: receipt.target.queueId, conversationId: receipt.target.conversationId, branchId: receipt.target.branchId, draftReceipt: { draftId: draft.draftId, sourceRevision: input.expectedRevision, committedRevision: decodeSafeProductRevision(draft.committedRevision) } }
+ }
+ if (method === 'chat.queue.cancel')
+ return receipt.result.cancelled === true
+ if (method === 'chat.queue.steer')
+ return 'accepted'
+ if (method === 'chat.cancel')
+ return read('runs.get', { runId: receipt.target.runId })
+ if (method === 'approvals.approve' || method === 'approvals.deny') {
+ const approvals = await read('approvals.list', { runId: receipt.target.runId }) as Array<{ id: string }>
+ const approval = approvals.find(approval => approval.id === receipt.target.approvalId)
+ if (!approval)
+ throw gatewayError('OBJECT_DELETED')
+ return approval
+ }
+ if (method === 'conversations.delete')
+ return true
+ if (method === 'conversations.archive')
+ return receipt.result.archived === true
+ if (method === 'conversations.restoreArchive')
+ return receipt.result.restored === true
+ if (method === 'conversations.deleteArchived' || method === 'conversations.deleteLegacyRemoved')
+ return receipt.result.deleted === true
+ if (method === 'conversations.setArchivePolicy')
+ return conversationArchivePolicySchema.parse(receipt.result.archivePolicy)
+ if (method === 'taskMarks.delete')
+ return { ok: true }
+ if (method === 'conversations.addMember' || method === 'conversations.removeMember')
+ return read('conversations.listMembers', { conversationId: input.conversationId })
+ if (method.startsWith('conversations.'))
+ return read('conversations.get', { conversationId: input.conversationId })
+ if (method === 'taskMarks.create' || method === 'taskMarks.update') {
+ const marks = await read('taskMarks.list', {}) as Array<{ id: string }>
+ return marks.find(mark => mark.id === receipt.target.markId)
+ }
+ if (method.startsWith('taskMarks.')) {
+ const states = await read('taskMarks.states', { conversationIds: [input.conversationId] }) as unknown[]
+ return states[0]
+ }
+ throw gatewayError('METHOD_NOT_AVAILABLE')
+ }
+}
+
+function objectInput(value: unknown): Record {
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ throw gatewayError('VALIDATION_FAILED')
+ return value as Record
+}
+function gatewayError(code: string): Error {
+ return Object.assign(new Error(code), { code })
+}
+
+function outboxOwner(client: ProductRpcClient) {
+ const { serviceId, profileId, dataGeneration, deviceId } = client.identity
+ return { serviceId, profileId, dataGeneration, deviceId }
+}
diff --git a/apps/buddy/electron/main/productProtocol/ProductOutboxStore.ts b/apps/buddy/electron/main/productProtocol/ProductOutboxStore.ts
new file mode 100644
index 000000000..7e5d46078
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/ProductOutboxStore.ts
@@ -0,0 +1,199 @@
+import type { ProductIdentity } from '../../../shared/productProtocol/identity'
+import type { ProductCommandMethod } from '../../../shared/productProtocol/methods'
+import { Buffer } from 'node:buffer'
+import { createHash } from 'node:crypto'
+import { readdir, unlink } from 'node:fs/promises'
+import { join } from 'node:path'
+import { z } from 'zod'
+import { isMissing, readStorageJson, syncStorageDirectory, writeStorageJson } from '../../../platform/storage/storageFiles'
+import { buddyUserContentV1Schema } from '../../../shared/conversation/buddyUserContent'
+import { buddyComposerDraftExecutionConfigSchema, buddyComposerDraftModelSelectionSchema, buddyDraftParticipantsSchema } from '../../../shared/conversation/composerDraft'
+import { productIdentitySchema } from '../../../shared/productProtocol/identity'
+import { PRODUCT_LIMITS } from '../../../shared/productProtocol/limits'
+import { getProductMethod } from '../../../shared/productProtocol/methods'
+import { productCommandReceiptSchema } from '../../../shared/productProtocol/receipts'
+import { productIdSchema, productRevisionSchema } from '../../../shared/productProtocol/scalars'
+
+const ownerSchema = productIdentitySchema.pick({ serviceId: true, profileId: true, dataGeneration: true, deviceId: true })
+const envelopeSchema = z.object({ dataGeneration: productIdSchema, commandId: productIdSchema, expectedServiceInstanceId: productIdSchema, intent: z.unknown() }).strict()
+const recoverySchema = z.object({ draftId: productIdSchema, editSequence: productRevisionSchema, content: buddyUserContentV1Schema, executionConfig: buddyComposerDraftExecutionConfigSchema.optional(), modelSelection: buddyComposerDraftModelSelectionSchema.nullable().optional(), participants: buddyDraftParticipantsSchema.nullable().optional() }).strict()
+const recordSchema = z.object({
+ version: z.literal(1),
+ owner: ownerSchema,
+ commandId: productIdSchema,
+ method: productIdSchema,
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/),
+ createdAt: z.iso.datetime(),
+ state: z.enum(['prepared', 'uncertain', 'not_accepted', 'decided']),
+ envelope: envelopeSchema.nullable(),
+ recovery: recoverySchema.nullable(),
+ receipt: productCommandReceiptSchema.nullable(),
+}).strict().refine(record => (record.state === 'decided') === (record.receipt !== null))
+export type ProductOutboxRecord = z.infer
+export type ProductOutboxOwner = z.infer
+export type ProductRecoveryInput = z.infer
+export type ProductOutboxEnvelope = z.infer
+const maxRecordBytes = PRODUCT_LIMITS.frameBytes * 2
+
+export class ProductOutboxStore {
+ #tail: Promise = Promise.resolve()
+
+ readonly directory: string
+
+ constructor(directory: string) {
+ this.directory = directory
+ }
+
+ create(input: { identity: ProductIdentity, method: ProductCommandMethod, envelope: ProductOutboxEnvelope, recovery?: ProductRecoveryInput }): Promise<{ created: boolean, record: ProductOutboxRecord }> {
+ const method = getProductMethod(input.method)
+ if (!method?.command)
+ throw new Error('OUTBOX_INVALID_METHOD')
+ const envelope = envelopeSchema.parse(method.input.parse(input.envelope))
+ const owner = ownerSchema.parse({ serviceId: input.identity.serviceId, profileId: input.identity.profileId, dataGeneration: input.identity.dataGeneration, deviceId: input.identity.deviceId })
+ if (envelope.dataGeneration !== owner.dataGeneration)
+ throw new Error('OUTBOX_IDENTITY_CHANGED')
+ const fingerprint = digest({ method: input.method, dataGeneration: envelope.dataGeneration, commandId: envelope.commandId, intent: envelope.intent })
+ const record = recordSchema.parse({ version: 1, owner, commandId: envelope.commandId, method: input.method, fingerprint, createdAt: new Date().toISOString(), state: 'prepared', envelope, recovery: input.recovery ?? null, receipt: null })
+ return this.#serial(async () => {
+ const existing = await this.#read(owner, envelope.commandId)
+ if (existing) {
+ if (existing.fingerprint !== fingerprint)
+ throw new Error('OUTBOX_COMMAND_ID_REUSED')
+ return { created: false, record: existing }
+ }
+ await this.#write(record)
+ return { created: true, record }
+ })
+ }
+
+ read(owner: ProductOutboxOwner, commandId: string): Promise {
+ return this.#serial(() => this.#read(ownerSchema.parse(owner), productIdSchema.parse(commandId)))
+ }
+
+ list(): Promise {
+ return this.#serial(async () => {
+ const names = await readdir(this.directory).catch((error) => {
+ if (!isMissing(error))
+ throw error
+ return []
+ })
+ const records: ProductOutboxRecord[] = []
+ for (const name of names.sort()) {
+ if (!/^[a-f0-9]{64}\.json$/.test(name))
+ continue
+ const record = recordSchema.parse(await readStorageJson(join(this.directory, name), maxRecordBytes))
+ if (name !== recordName(record.owner, record.commandId))
+ throw new Error('OUTBOX_IDENTITY_CHANGED')
+ validateRecord(record)
+ records.push(record)
+ }
+ return records
+ })
+ }
+
+ markUncertain(record: ProductOutboxRecord): Promise {
+ return this.#update(record, current => current.state === 'prepared' ? { ...current, state: 'uncertain' } : current)
+ }
+
+ confirmAbsent(record: ProductOutboxRecord): Promise {
+ return this.#update(record, current => current.state === 'decided' ? current : { ...current, state: 'not_accepted' })
+ }
+
+ decide(record: ProductOutboxRecord, receipt: z.infer): Promise {
+ const parsed = productCommandReceiptSchema.parse(receipt)
+ if (parsed.dataGeneration !== record.owner.dataGeneration || parsed.commandId !== record.commandId || parsed.method !== record.method)
+ throw new Error('OUTBOX_RECEIPT_MISMATCH')
+ return this.#update(record, (current) => {
+ if (current.receipt && digest(current.receipt) !== digest(parsed))
+ throw new Error('OUTBOX_RECEIPT_CHANGED')
+ return { ...current, state: 'decided', receipt: parsed }
+ })
+ }
+
+ archive(record: ProductOutboxRecord): Promise {
+ return this.#serial(async () => {
+ const current = await this.#read(record.owner, record.commandId)
+ if (!current || current.fingerprint !== record.fingerprint)
+ throw new Error('OUTBOX_RECORD_CHANGED')
+ if (current.state !== 'decided' && current.state !== 'not_accepted')
+ throw new Error('OUTBOX_NOT_RECONCILED')
+ const archived = recordSchema.parse({ ...current, envelope: null, recovery: null })
+ const name = recordName(current.owner, current.commandId)
+ await writeStorageJson(join(this.directory, 'archive', name), archived)
+ await unlink(join(this.directory, name)).catch((error) => {
+ if (!isMissing(error))
+ throw error
+ })
+ await syncStorageDirectory(this.directory)
+ return archived
+ })
+ }
+
+ #update(record: ProductOutboxRecord, update: (current: ProductOutboxRecord) => ProductOutboxRecord): Promise {
+ return this.#serial(async () => {
+ const current = await this.#read(record.owner, record.commandId)
+ if (!current || current.fingerprint !== record.fingerprint)
+ throw new Error('OUTBOX_RECORD_CHANGED')
+ const next = recordSchema.parse(update(current))
+ await this.#write(next)
+ return next
+ })
+ }
+
+ async #read(owner: ProductOutboxOwner, commandId: string): Promise {
+ const name = recordName(owner, commandId)
+ const raw = await readStorageJson(join(this.directory, name), maxRecordBytes) ?? await readStorageJson(join(this.directory, 'archive', name), maxRecordBytes)
+ if (raw === null)
+ return null
+ const record = recordSchema.parse(raw)
+ if (digest(record.owner) !== digest(owner) || record.commandId !== commandId)
+ throw new Error('OUTBOX_IDENTITY_CHANGED')
+ validateRecord(record)
+ return record
+ }
+
+ async #write(record: ProductOutboxRecord): Promise {
+ validateRecord(record)
+ if (Buffer.byteLength(JSON.stringify(record)) > maxRecordBytes)
+ throw new Error('OUTBOX_INPUT_TOO_LARGE')
+ await writeStorageJson(join(this.directory, recordName(record.owner, record.commandId)), record)
+ }
+
+ #serial(operation: () => Promise): Promise {
+ const next = this.#tail.then(operation, operation)
+ this.#tail = next
+ return next
+ }
+}
+
+export function isProductOutboxOwner(owner: ProductOutboxOwner, identity: ProductIdentity): boolean {
+ return owner.serviceId === identity.serviceId && owner.profileId === identity.profileId && owner.dataGeneration === identity.dataGeneration && owner.deviceId === identity.deviceId
+}
+
+function validateRecord(record: ProductOutboxRecord): void {
+ if (!record.envelope && (record.state === 'prepared' || record.state === 'uncertain'))
+ throw new Error('OUTBOX_INPUT_MISSING')
+ if (record.envelope && (record.envelope.commandId !== record.commandId || record.envelope.dataGeneration !== record.owner.dataGeneration
+ || digest({ method: record.method, dataGeneration: record.envelope.dataGeneration, commandId: record.commandId, intent: record.envelope.intent }) !== record.fingerprint)) {
+ throw new Error('OUTBOX_INTENT_CHANGED')
+ }
+ if (record.receipt && (record.receipt.commandId !== record.commandId || record.receipt.dataGeneration !== record.owner.dataGeneration || record.receipt.method !== record.method))
+ throw new Error('OUTBOX_RECEIPT_MISMATCH')
+}
+function recordName(owner: ProductOutboxOwner, commandId: string): string {
+ return `${digest({ ...owner, commandId })}.json`
+}
+function digest(value: unknown): string {
+ return createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex')
+}
+function canonical(value: unknown): unknown {
+ if (Array.isArray(value))
+ return value.map(canonical)
+ if (value && typeof value === 'object')
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, entry]) => [key, canonical(entry)]))
+ return value
+}
+
+export function productOutboxRecordId(record: ProductOutboxRecord): string {
+ return digest({ owner: record.owner, commandId: record.commandId })
+}
diff --git a/apps/buddy/electron/main/productProtocol/ProductRpcClient.ts b/apps/buddy/electron/main/productProtocol/ProductRpcClient.ts
new file mode 100644
index 000000000..ab1d760a4
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/ProductRpcClient.ts
@@ -0,0 +1,161 @@
+import type { z } from 'zod'
+import type { ProductError } from '../../../shared/productProtocol/errors'
+import type { ProductIdentity } from '../../../shared/productProtocol/identity'
+import { randomUUID } from 'node:crypto'
+import { z as schema } from 'zod'
+import { productErrorSchema } from '../../../shared/productProtocol/errors'
+import { productIdentitySchema, productInitializeResultSchema, productInitializeSchema } from '../../../shared/productProtocol/identity'
+import { encodeProductFrame, PRODUCT_LIMITS, productByteLength } from '../../../shared/productProtocol/limits'
+import { getProductMethod } from '../../../shared/productProtocol/methods'
+import { productAckSchema, productSnapshotPageSchema, productSubscribeSchema, productUnsubscribeSchema } from '../../../shared/productProtocol/sync'
+
+export interface ProductClientTransport {
+ send: (frame: string) => void | Promise
+ subscribe: (listener: (frame: string) => void) => () => void
+ close: () => void
+}
+interface PendingRequest {
+ resolve: (value: unknown) => void
+ reject: (error: unknown) => void
+ timer: ReturnType
+}
+const replySchema = schema.union([
+ schema.object({ jsonrpc: schema.literal('2.0'), id: schema.string(), result: schema.unknown() }).strict(),
+ schema.object({ jsonrpc: schema.literal('2.0'), id: schema.string().nullable(), error: productErrorSchema }).strict(),
+ schema.object({ jsonrpc: schema.literal('2.0'), method: schema.enum(['sync.delta', 'sync.resyncRequired']), params: schema.unknown() }).strict(),
+])
+
+export class ProductRpcClient {
+ readonly #transport: ProductClientTransport
+ readonly #pending = new Map()
+ readonly #listeners = new Set<(notification: { method: string, params: unknown }) => void>()
+ readonly #unsubscribe: () => void
+ readonly #timeoutMs: number
+ #identity: ProductIdentity | null = null
+ #initializing: Promise> | null = null
+ #closed = false
+
+ constructor(transport: ProductClientTransport, timeoutMs = 30_000) {
+ this.#transport = transport
+ this.#timeoutMs = timeoutMs
+ this.#unsubscribe = transport.subscribe(frame => this.#receive(frame))
+ }
+
+ get identity(): ProductIdentity {
+ if (!this.#identity)
+ throw new Error('PRODUCT_NOT_INITIALIZED')
+ return this.#identity
+ }
+
+ initialize(input: z.infer): Promise> {
+ if (!this.#initializing) {
+ const parsed = productInitializeSchema.parse(input)
+ this.#initializing = this.#request('initialize', parsed).then((raw) => {
+ const result = productInitializeResultSchema.parse(raw)
+ this.#identity = Object.freeze(productIdentitySchema.parse(Object.fromEntries(Object.keys(productIdentitySchema.shape).map(key => [key, result[key as keyof typeof result]]))))
+ return result
+ }).catch((error) => {
+ this.close()
+ throw error
+ })
+ }
+ return this.#initializing
+ }
+
+ async request(method: string, params: unknown): Promise {
+ if (!this.#identity)
+ throw new Error('PRODUCT_NOT_INITIALIZED')
+ const contract = getProductMethod(method)
+ if (contract)
+ return contract.output.parse(await this.#request(method, contract.input.parse(params)))
+ const sync = method === 'sync.subscribe' ? productSubscribeSchema : method === 'sync.snapshotPage' ? productSnapshotPageSchema : method === 'sync.ack' ? productAckSchema : method === 'sync.unsubscribe' ? productUnsubscribeSchema : null
+ if (!sync)
+ throw new Error('PRODUCT_METHOD_NOT_AVAILABLE')
+ return this.#request(method, sync.parse(params))
+ }
+
+ onNotification(listener: (notification: { method: string, params: unknown }) => void): () => void {
+ this.#listeners.add(listener)
+ return () => this.#listeners.delete(listener)
+ }
+
+ close(): void {
+ if (this.#closed)
+ return
+ this.#closed = true
+ this.#unsubscribe()
+ this.#transport.close()
+ for (const request of this.#pending.values()) {
+ clearTimeout(request.timer)
+ request.reject(new Error('PRODUCT_CONNECTION_CLOSED'))
+ }
+ this.#pending.clear()
+ this.#listeners.clear()
+ }
+
+ #request(method: string, params: unknown): Promise {
+ if (this.#closed)
+ return Promise.reject(new Error('PRODUCT_CONNECTION_CLOSED'))
+ if (this.#pending.size >= PRODUCT_LIMITS.inFlightRequests)
+ return Promise.reject(new Error('PRODUCT_REQUEST_LIMIT'))
+ const id = randomUUID()
+ const frame = encodeProductFrame({ jsonrpc: '2.0', id, method, params })
+ return new Promise((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.#pending.delete(id)
+ reject(new Error('PRODUCT_RESPONSE_UNKNOWN'))
+ }, this.#timeoutMs)
+ this.#pending.set(id, { resolve, reject, timer })
+ try {
+ Promise.resolve(this.#transport.send(frame)).catch(() => this.close())
+ }
+ catch { this.close() }
+ })
+ }
+
+ #receive(frame: string): void {
+ if (this.#closed)
+ return
+ try {
+ if (frame.length > PRODUCT_LIMITS.frameBytes || productByteLength(frame) > PRODUCT_LIMITS.frameBytes)
+ throw new Error('PRODUCT_FRAME_LIMIT')
+ const reply = replySchema.parse(JSON.parse(frame))
+ if ('method' in reply) {
+ if (!this.#identity)
+ throw new Error('PRODUCT_NOT_INITIALIZED')
+ for (const listener of this.#listeners) {
+ try {
+ listener({ method: reply.method, params: reply.params })
+ }
+ catch {}
+ }
+ return
+ }
+ if (reply.id === null)
+ throw new Error('PRODUCT_UNCORRELATED_ERROR')
+ const request = this.#pending.get(reply.id)
+ if (!request)
+ return
+ this.#pending.delete(reply.id)
+ clearTimeout(request.timer)
+ if ('error' in reply)
+ request.reject(new ProductResponseError(reply.error))
+ else
+ request.resolve(reply.result)
+ }
+ catch { this.close() }
+ }
+}
+
+export class ProductResponseError extends Error {
+ readonly code: ProductError['code']
+ readonly acceptance: ProductError['acceptance']
+ readonly recovery: ProductError['recovery']
+
+ constructor(error: ProductError) {
+ super(error.message)
+ this.code = error.code
+ this.acceptance = error.acceptance
+ this.recovery = error.recovery
+ }
+}
diff --git a/apps/buddy/electron/main/productProtocol/ProductSyncClient.ts b/apps/buddy/electron/main/productProtocol/ProductSyncClient.ts
new file mode 100644
index 000000000..7dc1a2593
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/ProductSyncClient.ts
@@ -0,0 +1,181 @@
+import type { ZodType } from 'zod'
+import type { ProductSyncCursor, ProductSyncDelta } from '../../../shared/productProtocol/sync'
+import type { ProductRpcClient } from './ProductRpcClient'
+import { randomUUID } from 'node:crypto'
+import { PRODUCT_LIMITS, productByteLength } from '../../../shared/productProtocol/limits'
+import { classifyProductDelta, productResyncRequiredSchema, productSyncDeltaSchema, productSyncSnapshotSchema } from '../../../shared/productProtocol/sync'
+
+export interface ProductTopicConsumer- {
+ item: ZodType
-
+ change: ZodType
+ beginSnapshot: () => void | Promise
+ appendSnapshot: (items: Item[]) => void | Promise
+ commitSnapshot: (cursor: ProductSyncCursor) => void | Promise
+ applyChanges: (changes: Change[], cursor: ProductSyncCursor) => void | Promise
+ invalidate: (error: unknown) => void
+}
+interface Subscription {
+ id: string
+ cursor: ProductSyncCursor | null
+ queue: Array<{ delta: ProductSyncDelta, bytes: number }>
+ bytes: number
+ items: number
+ ready: boolean
+ active: boolean
+ processing: boolean
+ consumer: ProductTopicConsumer
+}
+
+export class ProductSyncClient {
+ readonly #client: Pick
+ readonly #stop: () => void
+ readonly #subscriptions = new Map()
+ #bytes = 0
+ #closed = false
+
+ constructor(client: Pick) {
+ this.#client = client
+ this.#stop = client.onNotification(notification => this.#receive(notification))
+ }
+
+ subscribe
- (topic: string, consumer: ProductTopicConsumer
- ) {
+ if (this.#closed || this.#subscriptions.size >= PRODUCT_LIMITS.subscriptionsPerConnection)
+ throw new Error('PRODUCT_SUBSCRIPTION_LIMIT')
+ const subscription: Subscription = { id: randomUUID(), cursor: null, queue: [], bytes: 0, items: 0, ready: false, active: true, processing: false, consumer: consumer as ProductTopicConsumer }
+ this.#subscriptions.set(subscription.id, subscription)
+ const ready = this.#snapshot(subscription, topic).catch((error) => {
+ this.#invalidate(subscription, error)
+ throw error
+ })
+ return { ready, dispose: () => this.#remove(subscription) }
+ }
+
+ close(): void {
+ if (this.#closed)
+ return
+ this.#closed = true
+ this.#stop()
+ for (const subscription of [...this.#subscriptions.values()])
+ this.#remove(subscription)
+ }
+
+ async #snapshot(subscription: Subscription, topic: string): Promise {
+ let page = productSyncSnapshotSchema.parse(await this.#client.request('sync.subscribe', { subscriptionId: subscription.id, topic }))
+ if (!subscription.active)
+ return
+ if (page.mode !== 'snapshot' || page.subscriptionId !== subscription.id)
+ throw new Error('SYNC_INVALID')
+ const cursor = page.cursor
+ await subscription.consumer.beginSnapshot()
+ const cursors = new Set()
+ while (subscription.active) {
+ if (page.mode !== 'snapshot' || page.subscriptionId !== subscription.id || page.cursor.syncEpoch !== cursor.syncEpoch || page.cursor.seq !== cursor.seq)
+ throw new Error('SYNC_INVALID')
+ const bytes = productByteLength(JSON.stringify(page))
+ if (bytes > PRODUCT_LIMITS.pageBytes || this.#bytes + bytes > PRODUCT_LIMITS.connectionBytes)
+ throw new Error('RESYNC_REQUIRED')
+ this.#bytes += bytes
+ try {
+ const items = page.items.map(item => subscription.consumer.item.parse(item))
+ await subscription.consumer.appendSnapshot(items)
+ }
+ finally { this.#bytes -= bytes }
+ if (!subscription.active)
+ return
+ if (page.complete)
+ break
+ if (!page.nextCursor || cursors.has(page.nextCursor))
+ throw new Error('SYNC_INVALID')
+ cursors.add(page.nextCursor)
+ page = productSyncSnapshotSchema.parse(await this.#client.request('sync.snapshotPage', { subscriptionId: subscription.id, cursor: page.nextCursor }))
+ }
+ if (!subscription.active)
+ return
+ await subscription.consumer.commitSnapshot(cursor)
+ if (!subscription.active)
+ return
+ subscription.cursor = cursor
+ subscription.ready = true
+ await this.#pump(subscription)
+ }
+
+ #receive(notification: { method: string, params: unknown }): void {
+ try {
+ if (notification.method === 'sync.resyncRequired') {
+ const request = productResyncRequiredSchema.parse(notification.params)
+ const subscription = this.#subscriptions.get(request.subscriptionId)
+ if (subscription)
+ this.#invalidate(subscription, new Error('RESYNC_REQUIRED'))
+ return
+ }
+ if (notification.method !== 'sync.delta')
+ return
+ const delta = productSyncDeltaSchema.parse(notification.params)
+ const subscription = this.#subscriptions.get(delta.subscriptionId)
+ if (!subscription?.active)
+ return
+ const bytes = productByteLength(JSON.stringify(delta))
+ if (subscription.bytes + bytes > PRODUCT_LIMITS.subscriptionBytes || subscription.items + delta.changes.length > PRODUCT_LIMITS.subscriptionItems || this.#bytes + bytes > PRODUCT_LIMITS.connectionBytes) {
+ this.#invalidate(subscription, new Error('RESYNC_REQUIRED'))
+ return
+ }
+ subscription.queue.push({ delta, bytes })
+ subscription.items += delta.changes.length
+ subscription.bytes += bytes
+ this.#bytes += bytes
+ void this.#pump(subscription).catch(error => this.#invalidate(subscription, error))
+ }
+ catch (error) {
+ for (const subscription of [...this.#subscriptions.values()])
+ this.#invalidate(subscription, error)
+ }
+ }
+
+ async #pump(subscription: Subscription): Promise {
+ if (!subscription.active || !subscription.ready || subscription.processing)
+ return
+ subscription.processing = true
+ try {
+ while (subscription.active && subscription.queue.length) {
+ const { delta, bytes } = subscription.queue[0]!
+ const classification = classifyProductDelta(subscription.cursor!, delta)
+ if (classification === 'resync')
+ throw new Error('RESYNC_REQUIRED')
+ if (classification === 'apply') {
+ const cursor = { syncEpoch: delta.syncEpoch, seq: delta.toSeq }
+ await subscription.consumer.applyChanges(delta.changes.map(change => subscription.consumer.change.parse(change)), cursor)
+ if (!subscription.active)
+ return
+ subscription.cursor = cursor
+ }
+ await this.#client.request('sync.ack', { subscriptionId: subscription.id, ...subscription.cursor })
+ if (!subscription.active)
+ return
+ subscription.queue.shift()
+ subscription.items -= delta.changes.length
+ subscription.bytes -= bytes
+ this.#bytes -= bytes
+ }
+ }
+ finally { subscription.processing = false }
+ }
+
+ #invalidate(subscription: Subscription, error: unknown): void {
+ if (!subscription.active)
+ return
+ this.#remove(subscription)
+ subscription.consumer.invalidate(error)
+ }
+
+ #remove(subscription: Subscription): void {
+ if (!subscription.active)
+ return
+ subscription.active = false
+ this.#subscriptions.delete(subscription.id)
+ this.#bytes -= subscription.bytes
+ subscription.queue = []
+ subscription.bytes = 0
+ subscription.items = 0
+ void this.#client.request('sync.unsubscribe', { subscriptionId: subscription.id }).catch(() => {})
+ }
+}
diff --git a/apps/buddy/electron/main/productProtocol/RendererDraftStore.ts b/apps/buddy/electron/main/productProtocol/RendererDraftStore.ts
new file mode 100644
index 000000000..0ac2e2e43
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/RendererDraftStore.ts
@@ -0,0 +1,86 @@
+import type { DraftRecoveryOwner, DraftRecoveryRecord } from '../../../shared/conversation/draftRecovery'
+import { Buffer } from 'node:buffer'
+import { createHash } from 'node:crypto'
+import { readdir } from 'node:fs/promises'
+import { join } from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+import { z } from 'zod'
+import { isMissing, readStorageJson, writeStorageJson } from '../../../platform/storage/storageFiles'
+import { draftRecoveryOwnerSchema, draftRecoveryRecordSchema } from '../../../shared/conversation/draftRecovery'
+
+const entrySchema = z.object({ owner: draftRecoveryOwnerSchema, sequence: z.number().int().nonnegative(), editorSessionId: z.uuid(), record: draftRecoveryRecordSchema.nullable() }).strict()
+const maxBytes = 8 * 1024 * 1024
+
+export class RendererDraftStore {
+ readonly #directory: string
+ #tail: Promise = Promise.resolve()
+
+ constructor(directory: string) {
+ this.#directory = directory
+ }
+
+ load(): Promise {
+ return this.#serial(async () => {
+ const files = await readdir(this.#directory).catch((error: unknown) => {
+ if (isMissing(error))
+ return []
+ throw error
+ })
+ const records: DraftRecoveryRecord[] = []
+ for (const name of files) {
+ if (!/^[a-f0-9]{64}\.json$/.test(name))
+ continue
+ const entry = entrySchema.parse(await readStorageJson(join(this.#directory, name), maxBytes))
+ if (name !== this.#name(entry.owner, entry.editorSessionId))
+ throw new Error('DRAFT_RECOVERY_CORRUPTED')
+ if (entry.record) {
+ if (!isDeepStrictEqual(entry.record.owner, entry.owner) || entry.record.sequence !== entry.sequence || entry.record.snapshot.editorSessionId !== entry.editorSessionId)
+ throw new Error('DRAFT_RECOVERY_CORRUPTED')
+ records.push(entry.record)
+ }
+ }
+ if (records.length > 1000)
+ throw new Error('DRAFT_RECOVERY_LIMIT')
+ return records
+ })
+ }
+
+ write(raw: DraftRecoveryRecord): Promise {
+ if (Buffer.byteLength(JSON.stringify(raw)) > maxBytes)
+ return Promise.reject(new Error('DRAFT_RECOVERY_LIMIT'))
+ const record = draftRecoveryRecordSchema.parse(raw)
+ return this.#write({ owner: record.owner, sequence: record.sequence, editorSessionId: record.snapshot.editorSessionId, record })
+ }
+
+ remove(owner: DraftRecoveryOwner, editorSessionId: string, sequence: number): Promise {
+ return this.#write({ owner, editorSessionId, sequence, record: null })
+ }
+
+ #write(value: z.infer): Promise {
+ const entry = entrySchema.parse(value)
+ return this.#serial(async () => {
+ const path = join(this.#directory, this.#name(entry.owner, entry.editorSessionId))
+ const previous = await readStorageJson(path, maxBytes).then(value => value === null ? null : entrySchema.parse(value)).catch((error: unknown) => {
+ if (isMissing(error))
+ return null
+ throw error
+ })
+ if (previous && (!isDeepStrictEqual(previous.owner, entry.owner) || previous.editorSessionId !== entry.editorSessionId))
+ throw new Error('DRAFT_RECOVERY_CORRUPTED')
+ if (previous && (previous.sequence > entry.sequence || (previous.sequence === entry.sequence && !isDeepStrictEqual(previous, entry))))
+ throw new Error('DRAFT_RECOVERY_STALE_WRITE')
+ if (!previous || previous.sequence !== entry.sequence)
+ await writeStorageJson(path, entry)
+ })
+ }
+
+ #name(owner: DraftRecoveryOwner, editorSessionId: string): string {
+ return `${createHash('sha256').update(JSON.stringify([owner.serviceId, owner.profileId, owner.dataGeneration, owner.deviceId, editorSessionId])).digest('hex')}.json`
+ }
+
+ #serial(operation: () => Promise): Promise {
+ const pending = this.#tail.catch(() => {}).then(operation)
+ this.#tail = pending
+ return pending
+ }
+}
diff --git a/apps/buddy/electron/main/productProtocol/__tests__/DesktopProductCommands.spec.ts b/apps/buddy/electron/main/productProtocol/__tests__/DesktopProductCommands.spec.ts
new file mode 100644
index 000000000..d33d57a4b
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/__tests__/DesktopProductCommands.spec.ts
@@ -0,0 +1,140 @@
+import type { ProductIdentity } from '../../../../shared/productProtocol/identity'
+import type { DesktopProductConnection } from '../DesktopProductCommands'
+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { DesktopProductCommands } from '../DesktopProductCommands'
+import { ProductOutboxStore } from '../ProductOutboxStore'
+
+const roots: string[] = []
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })))
+})
+const identity: ProductIdentity = { serviceId: 'service', profileId: 'profile', dataGeneration: 'data', serviceInstanceId: 'instance', connectionId: 'connection', clientSessionId: 'session', deviceId: 'desktop-owner' }
+const command = { method: 'chat.startTurn' as const, commandId: 'command', intent: { draftId: 'draft', expectedRevision: '2' } }
+const receipt = { dataGeneration: 'data', commandId: 'command', method: 'chat.startTurn', decision: 'accepted' as const, decidedAt: '2026-11-07T00:00:00.000Z', target: { runId: 'run', draftId: 'draft' }, result: { draftReceipt: { draftId: 'draft', committedRevision: '3' } } }
+async function fixture() {
+ const root = await mkdtemp(join(tmpdir(), 'lexora-product-outbox-'))
+ roots.push(root)
+ const store = new ProductOutboxStore(join(root, 'outbox'))
+ return { root, store, client: new DesktopProductCommands(store) }
+}
+
+function connection(request: DesktopProductConnection['request'], changes: Partial = {}): DesktopProductConnection {
+ return { identity: { ...identity, ...changes }, request }
+}
+
+describe('desktop durable command delivery', () => {
+ it('persists before dispatch, reconciles a lost response after restart and retains deduplication after archival', async () => {
+ const { root, store, client } = await fixture()
+ let dispatched = 0
+ client.attach(connection(async () => {
+ dispatched += 1
+ const [persisted] = await new ProductOutboxStore(join(root, 'outbox')).list()
+ expect(persisted).toMatchObject({ state: 'uncertain', envelope: { commandId: 'command', intent: command.intent } })
+ throw new Error('transport lost after commit')
+ }))
+ const first = await client.execute(command)
+ expect(first.state).toBe('unknown')
+ expect(dispatched).toBe(1)
+ const restarted = new DesktopProductCommands(new ProductOutboxStore(store.directory))
+ const calls: string[] = []
+ restarted.attach(connection(async (method) => {
+ calls.push(method)
+ return { lookup: 'decided', receipt }
+ }, { serviceInstanceId: 'instance-2' }))
+ const [recovered] = await restarted.recover()
+ expect(recovered).toMatchObject({ state: 'decided', record: { receipt } })
+ expect(calls).toEqual(['commands.get'])
+ const archived = await store.archive(recovered!.record)
+ expect(archived.envelope).toBeNull()
+ expect(archived.fingerprint).toMatch(/^[a-f0-9]{64}$/)
+ expect((await restarted.execute(command)).state).toBe('decided')
+ expect(calls).toEqual(['commands.get'])
+ await expect(restarted.execute({ ...command, intent: { ...command.intent, expectedRevision: '3' } })).rejects.toThrow('OUTBOX_COMMAND_ID_REUSED')
+ })
+
+ it('does not send when durable preparation fails', async () => {
+ const { root } = await fixture()
+ const directory = join(root, 'not-a-directory')
+ await writeFile(directory, 'keep')
+ const client = new DesktopProductCommands(new ProductOutboxStore(directory))
+ let dispatched = 0
+ client.attach(connection(async () => {
+ dispatched += 1
+ }))
+ await expect(client.execute(command)).rejects.toThrow()
+ expect(dispatched).toBe(0)
+ expect(await readFile(directory, 'utf8')).toBe('keep')
+ })
+
+ it('returns absent commands as recoverable input and never changes identity or resends automatically', async () => {
+ const { store, client } = await fixture()
+ const record = await store.create({ identity, method: command.method, envelope: { dataGeneration: identity.dataGeneration, commandId: command.commandId, expectedServiceInstanceId: identity.serviceInstanceId, intent: command.intent } })
+ const calls: string[] = []
+ client.attach(connection(async (method) => {
+ calls.push(method)
+ return { lookup: 'not_found' }
+ }))
+ expect((await client.reconcile(record.record)).state).toBe('not_accepted')
+ expect((await store.list())[0]!.envelope?.intent).toEqual(command.intent)
+ client.attach(connection(async (method) => {
+ calls.push(method)
+ }, { dataGeneration: 'restored-data' }))
+ expect((await client.recover())[0]!.state).toBe('trust_changed')
+ expect(calls).toEqual(['commands.get'])
+ expect((await store.list())[0]!.owner.dataGeneration).toBe('data')
+ })
+
+ it('keeps unknown results and corrupted records without silently reconstructing an empty outbox', async () => {
+ const { store, client } = await fixture()
+ client.attach(connection(async () => ({ receipt: { ...receipt, commandId: 'another-command' } })))
+ expect((await client.execute(command)).state).toBe('unknown')
+ client.attach(connection(async () => {
+ throw new Error('storage unavailable')
+ }))
+ expect((await client.recover())[0]!.state).toBe('unknown')
+ const [name] = await readdir(store.directory)
+ await writeFile(join(store.directory, name!), '{broken')
+ await expect(client.recover()).rejects.toThrow()
+ expect(await readFile(join(store.directory, name!), 'utf8')).toBe('{broken')
+ })
+
+ it('archives the original receipt but fences a late response from the replaced window connection', async () => {
+ const { client, store } = await fixture()
+ let respond!: (result: unknown) => void
+ let sent!: () => void
+ const dispatched = new Promise((resolve) => {
+ sent = resolve
+ })
+ const detach = client.attach(connection(async () => {
+ sent()
+ return new Promise((resolve) => {
+ respond = resolve
+ })
+ }))
+ const sending = client.execute(command)
+ await dispatched
+ client.attach(connection(async () => ({ lookup: 'decided', receipt }), { connectionId: 'new-window', clientSessionId: 'new-session' }))
+ detach()
+ respond({ receipt })
+ expect((await sending).state).toBe('connection_replaced')
+ expect((await store.list())[0]!.receipt).toEqual(receipt)
+ expect((await client.recover())[0]!.state).toBe('decided')
+ })
+
+ it('serializes concurrent retries of one identity without returning an early not-found result', async () => {
+ const { client } = await fixture()
+ let dispatched = 0
+ client.attach(connection(async (method) => {
+ if (method === 'commands.get')
+ return { lookup: 'not_found' }
+ dispatched += 1
+ return { receipt }
+ }))
+ const results = await Promise.all([client.execute(command), client.execute(command)])
+ expect(results.map(result => result.state)).toEqual(['decided', 'decided'])
+ expect(dispatched).toBe(1)
+ })
+})
diff --git a/apps/buddy/electron/main/productProtocol/__tests__/ProductRpcClient.spec.ts b/apps/buddy/electron/main/productProtocol/__tests__/ProductRpcClient.spec.ts
new file mode 100644
index 000000000..54deb5f11
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/__tests__/ProductRpcClient.spec.ts
@@ -0,0 +1,61 @@
+import type { ProductClientTransport } from '../ProductRpcClient'
+import { describe, expect, it } from 'vitest'
+import { ProductConnection } from '../../../../service/src/productProtocol/ProductConnection'
+import { ProductRpcClient } from '../ProductRpcClient'
+
+const initialize = { protocol: { major: 1, minMinor: 0, maxMinor: 0 }, client: { kind: 'desktop' as const, version: '0.20.0' }, supportedContentKinds: ['buddy.user.v1'], supportedReviewKinds: [] }
+const context = { serviceId: 'service', profileId: 'profile', dataGeneration: 'generation', serviceInstanceId: 'instance', connectionId: 'connection', clientSessionId: 'session', deviceId: 'desktop', ownerPrincipalId: 'desktop-local', credentialId: 'local', grantGeneration: '1', role: 'owner' as const }
+
+function fixture() {
+ let receive: (frame: string) => void = () => {}
+ let disconnected = false
+ const frames: string[] = []
+ const server = new ProductConnection({ context, assertCurrent() {}, phase: () => 'ready', handlers: { 'commands.get': { handle: () => ({ lookup: 'not_found' }) } }, send(frame) {
+ receive(frame)
+ return true
+ }, close() {} })
+ const transport: ProductClientTransport = {
+ send(frame) {
+ frames.push(frame)
+ return server.receive(frame)
+ },
+ subscribe(listener) {
+ receive = listener
+ return () => {
+ receive = () => {}
+ }
+ },
+ close() {
+ disconnected = true
+ },
+ }
+ const client = new ProductRpcClient(transport)
+ return { client, server, frames, emit: (frame: string) => receive(frame), disconnected: () => disconnected }
+}
+
+describe('product JSON transport client', () => {
+ it('negotiates with the real server connection and preserves the restricted error and query contracts', async () => {
+ const { client, server, frames } = fixture()
+ try {
+ await expect(client.request('commands.get', { dataGeneration: 'generation', commandId: 'command' })).rejects.toThrow('PRODUCT_NOT_INITIALIZED')
+ const result = await client.initialize(initialize)
+ expect(result).toMatchObject({ dataGeneration: 'generation', profileId: 'profile', capabilities: ['commands.get'] })
+ expect(await client.request('commands.get', { dataGeneration: 'generation', commandId: 'command' })).toEqual({ lookup: 'not_found' })
+ await expect(client.request('chat.cancel', { dataGeneration: 'generation', commandId: 'cancel', expectedServiceInstanceId: 'instance', intent: { runId: 'run', expectedRunGeneration: '1' } })).rejects.toMatchObject({ code: 'METHOD_NOT_AVAILABLE', acceptance: 'not_accepted' })
+ expect(JSON.parse(frames[2]!).params.intent.expectedRunGeneration).toBe('1')
+ }
+ finally {
+ client.close()
+ server.close()
+ }
+ })
+
+ it('closes only its transport on malformed frames and does not accept secret-bearing error extensions', async () => {
+ const { client, server, emit, disconnected } = fixture()
+ await client.initialize(initialize)
+ emit(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: 'INTERNAL_ERROR', message: 'INTERNAL_ERROR', acceptance: 'unknown', recovery: 'query_command', path: '/private/profile' } }))
+ expect(disconnected()).toBe(true)
+ await expect(client.request('commands.get', { dataGeneration: 'generation', commandId: 'command' })).rejects.toThrow('PRODUCT_CONNECTION_CLOSED')
+ server.close()
+ })
+})
diff --git a/apps/buddy/electron/main/productProtocol/__tests__/ProductSyncClient.spec.ts b/apps/buddy/electron/main/productProtocol/__tests__/ProductSyncClient.spec.ts
new file mode 100644
index 000000000..d434a1920
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/__tests__/ProductSyncClient.spec.ts
@@ -0,0 +1,98 @@
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+import { ProductConnection } from '../../../../service/src/productProtocol/ProductConnection'
+import { ProductSyncPublisher } from '../../../../service/src/productProtocol/ProductSyncPublisher'
+import { ProductRpcClient } from '../ProductRpcClient'
+import { ProductSyncClient } from '../ProductSyncClient'
+
+const cursor = { syncEpoch: 'epoch', seq: '0' }
+
+it('commits every snapshot page before applying the following delta and acknowledging it', async () => {
+ const publisher = new ProductSyncPublisher()
+ let reads = 0
+ let closed = false
+ const schema = z.number()
+ publisher.register('index', { item: schema, change: schema, readSnapshot: () => ({ items: [], complete: true, nextCursor: null }), openSnapshot: () => ({ read: () => ++reads === 1 ? { items: [1], complete: false, nextCursor: 'more' } : { items: [2], complete: true, nextCursor: null }, close: () => {
+ closed = true
+ } }) })
+ let receive = (_frame: string) => {}
+ const context = { serviceId: 'service', profileId: 'profile', dataGeneration: 'data', serviceInstanceId: 'instance', connectionId: 'connection', clientSessionId: 'session', deviceId: 'desktop', ownerPrincipalId: 'desktop-local', credentialId: 'local', grantGeneration: '1', role: 'owner' as const }
+ const connection = new ProductConnection({ context, assertCurrent() {}, phase: () => 'ready', handlers: {}, sync: publisher, authorizeTopic() {}, send(frame) {
+ receive(frame)
+ return true
+ }, close() {} })
+ const client = new ProductRpcClient({ send: frame => connection.receive(frame), subscribe(listener) {
+ receive = listener
+ return () => {}
+ }, close() {} })
+ const sync = new ProductSyncClient(client)
+ const events: string[] = []
+ try {
+ await client.initialize({ protocol: { major: 1, minMinor: 0, maxMinor: 0 }, client: { kind: 'desktop', version: 'test' }, supportedContentKinds: [], supportedReviewKinds: [] })
+ const handle = sync.subscribe('index', {
+ item: schema,
+ change: schema,
+ beginSnapshot: () => { events.push('begin') },
+ appendSnapshot(items) {
+ events.push(`page:${items.join(',')}`)
+ if (items[0] === 1)
+ publisher.publishCommitted('index', () => [3])
+ },
+ commitSnapshot: () => { events.push('commit') },
+ applyChanges: (changes) => { events.push(`delta:${changes.join(',')}`) },
+ invalidate: () => { events.push('invalid') },
+ })
+ await handle.ready
+ expect(events).toEqual(['begin', 'page:1', 'page:2', 'commit', 'delta:3'])
+ expect(closed).toBe(true)
+ expect(publisher.inspect().connections[0]?.bytes).toBe(0)
+ }
+ finally {
+ sync.close()
+ client.close()
+ connection.close()
+ }
+})
+
+describe('ordered client synchronization', () => {
+ it('ignores duplicates, rejects gaps and does not consume a removed subscription', async () => {
+ let listener = (_notification: { method: string, params: unknown }) => {}
+ let id = ''
+ const acknowledgements: unknown[] = []
+ const applied: unknown[] = []
+ const invalidations: unknown[] = []
+ const sync = new ProductSyncClient({
+ onNotification(value) {
+ listener = value
+ return () => {}
+ },
+ async request(method, params) {
+ if (method === 'sync.subscribe') {
+ id = (params as { subscriptionId: string }).subscriptionId
+ return { subscriptionId: id, mode: 'snapshot', cursor, items: [], complete: true, nextCursor: null }
+ }
+ if (method === 'sync.ack')
+ acknowledgements.push(params)
+ return {}
+ },
+ })
+ const handle = sync.subscribe('index', { item: z.number(), change: z.number(), beginSnapshot() {}, appendSnapshot() {}, commitSnapshot() {}, applyChanges: (changes) => {
+ applied.push(changes)
+ }, invalidate: (error) => {
+ invalidations.push(error)
+ } })
+ await handle.ready
+ const emit = (fromSeq: string, toSeq: string) => listener({ method: 'sync.delta', params: { subscriptionId: id, syncEpoch: 'epoch', fromSeq, toSeq, changes: [1] } })
+ emit('0', '1')
+ await expect.poll(() => acknowledgements.length).toBe(1)
+ emit('0', '1')
+ await expect.poll(() => acknowledgements.length).toBe(2)
+ expect(applied).toEqual([[1]])
+ emit('2', '3')
+ await expect.poll(() => invalidations.length).toBe(1)
+ emit('1', '2')
+ expect(applied).toEqual([[1]])
+ expect(acknowledgements).toHaveLength(2)
+ sync.close()
+ })
+})
diff --git a/apps/buddy/electron/main/productProtocol/__tests__/RendererDraftStore.spec.ts b/apps/buddy/electron/main/productProtocol/__tests__/RendererDraftStore.spec.ts
new file mode 100644
index 000000000..54e405d6d
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/__tests__/RendererDraftStore.spec.ts
@@ -0,0 +1,77 @@
+import type { DraftRecoveryRecord } from '../../../../shared/conversation/draftRecovery'
+import { randomUUID } from 'node:crypto'
+import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { createBuddyUserContent } from '../../../../shared/conversation/buddyUserContent'
+import { RendererDraftStore } from '../RendererDraftStore'
+
+const roots: string[] = []
+afterEach(async () => {
+ await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })))
+})
+async function directory() {
+ const root = await mkdtemp(join(tmpdir(), 'renderer-drafts-'))
+ roots.push(root)
+ return root
+}
+function record(): DraftRecoveryRecord {
+ return {
+ owner: { serviceId: 'service', profileId: 'profile', dataGeneration: 'generation', deviceId: 'desktop' },
+ sequence: 1,
+ snapshot: {
+ targetKey: 'global',
+ draftId: randomUUID(),
+ editorSessionId: randomUUID(),
+ editVersion: 1,
+ revision: 2,
+ confirmedSnapshot: null,
+ content: createBuddyUserContent('unsent input'),
+ approvalPolicy: 'policy',
+ executionProfile: 'workspace_write',
+ modelSelection: null,
+ },
+ }
+}
+
+describe('rendererDraftStore', () => {
+ it('durably restores independent scopes and generations in a fresh store', async () => {
+ const root = await directory()
+ const store = new RendererDraftStore(root)
+ const first = record()
+ const second = record()
+ second.snapshot.targetKey = 'space:space-1'
+ second.owner.dataGeneration = 'previous-generation'
+ await Promise.all([store.write(first), store.write(second)])
+ expect(await new RendererDraftStore(root).load()).toEqual(expect.arrayContaining([first, second]))
+ })
+
+ it('rejects stale writes and preserves the deletion watermark across restarts', async () => {
+ const root = await directory()
+ const store = new RendererDraftStore(root)
+ const first = record()
+ const newer = { ...first, sequence: 2, snapshot: { ...first.snapshot, editVersion: 2, content: createBuddyUserContent('newer input') } }
+ await store.write(newer)
+ await expect(store.write(first)).rejects.toThrow('DRAFT_RECOVERY_STALE_WRITE')
+ await store.write(newer)
+ await store.remove(first.owner, first.snapshot.editorSessionId, 3)
+ const restarted = new RendererDraftStore(root)
+ await expect(restarted.write(newer)).rejects.toThrow('DRAFT_RECOVERY_STALE_WRITE')
+ expect(await restarted.load()).toEqual([])
+ })
+
+ it('leaves malformed or future content intact instead of overwriting the recovery copy', async () => {
+ const root = await directory()
+ const store = new RendererDraftStore(root)
+ const first = record()
+ await store.write(first)
+ const path = join(root, (await readdir(root))[0]!)
+ const original = await readFile(path, 'utf8')
+ const future = original.replace('"version":1', '"version":2')
+ await writeFile(path, future)
+ await expect(store.load()).rejects.toThrow()
+ await expect(store.write({ ...first, sequence: 2 })).rejects.toThrow()
+ expect(await readFile(path, 'utf8')).toBe(future)
+ })
+})
diff --git a/apps/buddy/electron/main/productProtocol/registerDraftRecoveryIpc.ts b/apps/buddy/electron/main/productProtocol/registerDraftRecoveryIpc.ts
new file mode 100644
index 000000000..c71629779
--- /dev/null
+++ b/apps/buddy/electron/main/productProtocol/registerDraftRecoveryIpc.ts
@@ -0,0 +1,41 @@
+import type { BrowserWindow } from 'electron'
+import type { DraftRecoveryOwner } from '../../../shared/conversation/draftRecovery'
+import type { ProductIdentity } from '../../../shared/productProtocol/identity'
+import { ipcMain } from 'electron'
+import { draftRecoveryOwnerSchema, draftRecoveryRecordSchema, draftRecoveryRemovalSchema, sameDraftRecoveryOwner } from '../../../shared/conversation/draftRecovery'
+import { LOCAL_CHAT_IPC_CHANNELS } from '../../shared/localChatApi'
+import { assertTrustedSender } from '../ipc'
+import { RendererDraftStore } from './RendererDraftStore'
+
+export function registerDraftRecoveryIpc(options: { directory: string, getWindow: () => BrowserWindow | null, identity: () => Promise }): () => void {
+ const store = new RendererDraftStore(options.directory)
+ const channels = [LOCAL_CHAT_IPC_CHANNELS.draftRecoveryLoad, LOCAL_CHAT_IPC_CHANNELS.draftRecoveryWrite, LOCAL_CHAT_IPC_CHANNELS.draftRecoveryRemove]
+ let activeOwner: DraftRecoveryOwner | null = null
+ const owner = async () => {
+ const identity = await options.identity()
+ activeOwner = identity ? draftRecoveryOwnerSchema.parse({ serviceId: identity.serviceId, profileId: identity.profileId, dataGeneration: identity.dataGeneration, deviceId: identity.deviceId }) : null
+ return activeOwner
+ }
+ ipcMain.handle(channels[0]!, async (event) => {
+ assertTrustedSender(event, options.getWindow())
+ const current = await owner()
+ return { owner: current, records: current ? await store.load() : [] }
+ })
+ ipcMain.handle(channels[1]!, async (event, input: unknown) => {
+ assertTrustedSender(event, options.getWindow())
+ const record = draftRecoveryRecordSchema.parse(input)
+ const current = activeOwner
+ if (!current || !sameDraftRecoveryOwner(current, record.owner))
+ throw new Error('DRAFT_RECOVERY_IDENTITY_CHANGED')
+ await store.write(record)
+ })
+ ipcMain.handle(channels[2]!, async (event, input: unknown) => {
+ assertTrustedSender(event, options.getWindow())
+ const request = draftRecoveryRemovalSchema.parse(input)
+ const current = activeOwner
+ if (!current || !sameDraftRecoveryOwner(current, request.owner))
+ throw new Error('DRAFT_RECOVERY_IDENTITY_CHANGED')
+ await store.remove(request.owner, request.editorSessionId, request.sequence)
+ })
+ return () => channels.forEach(channel => ipcMain.removeHandler(channel))
+}
diff --git a/apps/buddy/electron/main/runtime/RemoteServiceClient.ts b/apps/buddy/electron/main/runtime/RemoteServiceClient.ts
new file mode 100644
index 000000000..526ade3d1
--- /dev/null
+++ b/apps/buddy/electron/main/runtime/RemoteServiceClient.ts
@@ -0,0 +1,193 @@
+import type { RuntimeLifecycleChange, RuntimeLifecycleSnapshot } from '../../../shared/lifecycle/runtimeLifecycle'
+import type { RuntimeRpcPeerContract } from '../../../shared/runtime/rpcPeer'
+import type { ServiceHostBootstrap } from '../../../shared/service/localServiceProtocol'
+import type { BuddyServiceNotification, BuddyServiceRequestOptions, BuddyServiceSupervisorState } from './BuddyServiceSupervisor'
+import { randomUUID } from 'node:crypto'
+import { connectLocalService } from '../../../platform/service/connectLocalService'
+import { ServiceRpcChannel } from '../../../platform/service/ServiceRpcChannel'
+import { Emitter } from '../../../shared/events/Emitter'
+import { SERVICE_LIFECYCLE_METHOD, serviceLifecycleChangeSchema } from '../../../shared/lifecycle/serviceLifecycle'
+import { serviceMaintenanceTicketSchema, serviceRuntimeStateSchema } from '../../../shared/service/localServiceProtocol'
+
+export class RemoteServiceClient {
+ readonly #bootstrap: ServiceHostBootstrap
+ readonly #host: RuntimeRpcPeerContract
+ readonly #changes = new Emitter(() => {})
+ readonly #lifecycle = new Emitter(() => {})
+ readonly #notifications = new Emitter(() => {})
+ readonly onDidChangeLifecycle = this.#lifecycle.event
+ #peer: ServiceRpcChannel | undefined
+ #connecting: Promise | undefined
+ #state: BuddyServiceSupervisorState = { status: 'stopped', pid: null, restartAttempt: 0, lastError: null }
+ #snapshot: RuntimeLifecycleSnapshot
+ #closed = false
+ #transitioning = false
+
+ constructor(bootstrap: ServiceHostBootstrap, host: RuntimeRpcPeerContract) {
+ this.#bootstrap = bootstrap
+ this.#host = host
+ this.#snapshot = { revision: 0, generation: bootstrap.identity.serviceInstanceId, status: 'stopped', maintenance: null, errorCode: null, connection: null, services: null }
+ host.onNotification((method, params) => {
+ if (method === 'service.runtimeState') {
+ const state = serviceRuntimeStateSchema.parse(params)
+ this.#snapshot = { ...this.#snapshot, ...state, services: state.generation === this.#snapshot.generation ? this.#snapshot.services : null }
+ this.#setState(state.status)
+ if (state.status === 'ready' && !this.#closed)
+ void this.#connect().catch(() => {})
+ }
+ if (method === SERVICE_LIFECYCLE_METHOD) {
+ const change = serviceLifecycleChangeSchema.safeParse(params)
+ if (change.success) {
+ this.#snapshot = { ...this.#snapshot, revision: this.#snapshot.revision + 1, services: change.data.snapshot }
+ this.#lifecycle.fire({ snapshot: this.lifecycleState })
+ }
+ }
+ this.#notifications.fire({ method, params })
+ })
+ }
+
+ get state() {
+ return { ...this.#state }
+ }
+
+ get lifecycleState(): RuntimeLifecycleSnapshot {
+ return structuredClone(this.#snapshot)
+ }
+
+ onStateChange(listener: (state: BuddyServiceSupervisorState) => void) {
+ return this.#changes.event(listener).dispose
+ }
+
+ onNotification(listener: (notification: BuddyServiceNotification) => void) {
+ return this.#notifications.event(listener).dispose
+ }
+
+ start(): void {
+ void this.#connect().catch(() => {})
+ }
+
+ async request(method: string, params: unknown, options: BuddyServiceRequestOptions = {}): Promise {
+ const peer = method === 'extensions.inference.acquire' || method === 'extensions.inference.release' ? this.#host : await this.#connect()
+ return peer.request(method, params, options.timeoutMs, options.signal, options.requestId)
+ }
+
+ notify(method: string, params: unknown): boolean {
+ if (this.#closed)
+ return false
+ try {
+ this.#host.notify(method, params)
+
+ return true
+ }
+ catch {
+ return false
+ }
+ }
+
+ async restartDesktop(): Promise {
+ if (this.#closed || this.#transitioning)
+ throw new Error('SERVICE_NOT_READY')
+ await this.#host.request('service.restartDesktop', { expectedServiceInstanceId: this.#bootstrap.identity.serviceInstanceId }, 30000)
+ }
+
+ restart(): Promise {
+ return this.#withMaintenance('restart', async () => {})
+ }
+
+ withStoppedStorage(operation: () => Promise): Promise {
+ return this.#withMaintenance('backup', operation)
+ }
+
+ async #withMaintenance(kind: 'backup' | 'restart', operation: () => Promise): Promise {
+ if (this.#closed || this.#transitioning || this.#state.status !== 'ready')
+ throw new Error('SERVICE_NOT_READY')
+ this.#transitioning = true
+ try {
+ const ticket = serviceMaintenanceTicketSchema.parse(await this.#host.request('service.beginMaintenance', { expectedServiceInstanceId: this.#bootstrap.identity.serviceInstanceId, kind }, 30000))
+ try {
+ return await operation()
+ }
+ finally {
+ await this.#host.request('service.endMaintenance', ticket, 120000)
+ await this.#connect()
+ }
+ }
+ finally {
+ this.#transitioning = false
+ }
+ }
+
+ async stop(): Promise {
+ if (this.#closed)
+ return
+ let stop = () => {}
+ let timeout: ReturnType | undefined
+ const finished = new Promise