Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions .playwright/scripts/__tests__/mobile-desktop.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ 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'
const serviceInterruption = process.env.LEXORA_TEST_MOBILE_SERVICE_INTERRUPTION === '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')
Expand Down Expand Up @@ -103,16 +104,21 @@ test('real Desktop and Android keep independent local input and submit one immut
await new Promise(resolve => listener.close(resolve))
const configuration = test.info().outputPath('pairing.json')
let instrument
let instrumentOutcome
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 })
await fs.writeFile(configuration, JSON.stringify({ pairing, networkRecovery: networkRecovery || serviceInterruption, 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 }))
.then((value) => {
instrumentOutcome = value
return value
})
let checkpoint
await expect.poll(async () => {
try {
Expand All @@ -138,20 +144,33 @@ test('real Desktop and Android keep independent local input and submit one immut
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) {
if (networkRecovery || serviceInterruption) {
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 }
catch {
if (instrumentOutcome)
throw new Error(instrumentOutcome.result?.stdout ?? String(instrumentOutcome.error))
return false
}
}, { timeout: 45000 }).toBe(true)
expect((await adb('shell', 'settings', 'get', 'global', 'wifi_on')).stdout.trim()).toBe('1')
if (networkRecovery)
expect((await adb('shell', 'settings', 'get', 'global', 'wifi_on')).stdout.trim()).toBe('1')
await waitMarker('network-ready')
await adb('shell', 'svc', 'wifi', 'disable')
if (serviceInterruption)
await page.evaluate(() => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: false }))
else
await adb('shell', 'svc', 'wifi', 'disable')
try {
await waitMarker('offline')
}
finally { await adb('shell', 'svc', 'wifi', 'enable') }
finally {
if (serviceInterruption)
await page.evaluate(({ bindAddress, port }) => window.lexoraDesktop.localChat.privateNetwork.configure({ enabled: true, bindAddress, port }), { bindAddress, port })
else
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))
Expand All @@ -174,7 +193,7 @@ test('real Desktop and Android keep independent local input and submit one immut
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))
await fs.writeFile(test.info().outputPath('workflow.json'), JSON.stringify({ ...checkpoint, localDrafts: true, immutableInput: true, nativeAndroidUi: true, electronUi: true, coreAdapter: serviceMode, wifiInterruptionRecovery: networkRecovery, serviceInterruptionRecovery: serviceInterruption, customAvatar: true, avatarHash, offlineAvatar: networkRecovery || serviceInterruption, transport: useAdbReverse ? 'adb-reverse' : 'private-network', serverAddress: bindAddress }, null, 2))
}
finally {
if (networkRecovery)
Expand Down
2 changes: 1 addition & 1 deletion .playwright/scripts/__tests__/mobile-history.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ test('Android historical followup, edit and regeneration preserve branches, rest
}, original.conversation_id)
await signal('task-deleted')
const evidence = await checkpoint('done')
expect(evidence).toMatchObject({ independentBranchEditAccepted: true, deletedSourceRejection: { decision: 'rejected', errorCode: 'SOURCE_CHANGED' } })
expect(evidence).toMatchObject({ independentBranchEditAccepted: true, deletedSourceUiBlocked: true, deletedSourceRejection: { decision: 'rejected', errorCode: 'SOURCE_CHANGED' } })
const result = await instrument
expect(result.error).toBeUndefined()
expect(result.result.stdout).toMatch(/OK \(1 test\)/)
Expand Down
8 changes: 8 additions & 0 deletions .playwright/scripts/__tests__/mobile-task-controls.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,14 @@ test('Android direct stop, queue, branch switching and read state preserve exact
}
catch (error) { cleanupErrors.push(error) }
}
if (started && failure) {
await cleanup(async () => {
const log = await adb('logcat', '-d', '-t', '1000', '-v', 'threadtime')
await fs.writeFile(testInfo.outputPath('android-failure-logcat.txt'), log.stdout)
const capture = await execute(process.env.ADB ?? 'adb', ['-s', serial, 'exec-out', 'screencap', '-p'], { encoding: 'buffer', maxBuffer: 8 * 1024 * 1024 })
await fs.writeFile(testInfo.outputPath('android-failure.png'), capture.stdout)
})
}
if (started)
await cleanup(() => adb('shell', 'am', 'force-stop', appPackage))
const result = await instrument
Expand Down
90 changes: 87 additions & 3 deletions apps/buddy/service/src/chat/ChatQueueService.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { LocalChatQueueReceipt, LocalChatQueueScope, LocalChatQueueSteerResult, LocalChatQueueTarget } from '../../../shared/conversation/chatQueueApi'
import type { EventSnapshot } from '../../../shared/events/eventTypes'
import type { BuddyExecutionProfile } from '../../../shared/permissions/executionProfile'
import type { ProductQueueControl } from '../../../shared/productProtocol/queries'
import type { LocalRun } from '../../../shared/runs/runApi'
import type { BuddyAgentRunner } from '../agent/execution/BuddyAgentRunner'
import type { BuddyTurnLauncher } from '../agent/execution/BuddyTurnLauncher'
Expand Down Expand Up @@ -103,6 +104,78 @@ export class ChatQueueService {
})
}

async inspectControls(target: LocalChatQueueTarget): Promise<Pick<ProductQueueControl, 'allowedActions' | 'blockedReason'> & { steerTarget: { runId: string, generation: number } | null }> {
const result: Pick<ProductQueueControl, 'allowedActions' | 'blockedReason'> & { steerTarget: { runId: string, generation: number } | null } = { allowedActions: [], steerTarget: null, blockedReason: 'service_unavailable' }
const accepting = () => {
this.#options.control?.assertAccepting()
return !this.#disposed
}
try {
if (!accepting())
return result
}
catch { return result }
const condition = this.#options.control?.queueTarget(target)
if (!condition)
return { ...result, blockedReason: 'target_unavailable' }
result.allowedActions.push('cancel')
if (this.#options.runner.isStopping || this.#options.eventLog.state !== 'open')
return result
const reason = (error: unknown): ProductQueueControl['blockedReason'] => {
const code = error && typeof error === 'object' && 'code' in error ? error.code : null
return code === 'INPUT_DELIVERY_TARGET_UNAVAILABLE' || code === 'SOURCE_CHANGED'
? 'target_unavailable'
: code === 'INPUT_DELIVERY_INCOMPATIBLE' || code === 'BUDDY_CONFLICT'
? 'input_incompatible'
: code === 'SERVICE_STOPPING' ? 'service_unavailable' : 'input_unavailable'
}
try {
const pending = this.#options.queue.pending(target)
if (!pending)
return { ...result, allowedActions: [], blockedReason: 'target_unavailable' }
result.blockedReason = 'busy'
if (this.#canDispatch(pending)) {
try {
this.#options.queue.validateDelivery(pending)
const prepared = await this.prepareContinue(target)
this.#assertContinueReady(prepared)
result.allowedActions.push('continue')
}
catch (error) { result.blockedReason = reason(error) }
}
const active = this.#options.queue.activeRun(target, pending.buddyId)
if (active) {
try {
const run = this.#options.runs.findById(active.id)!
this.#options.control?.assertRun({ runId: run.id, expectedRunGeneration: run.generation }, true)
const prepared = await this.prepareSteer(target, run.id)
this.#options.control?.assertRun({ runId: run.id, expectedRunGeneration: run.generation }, true)
this.#assertSteerReady(prepared.input, run.id)
this.#options.queue.validateDelivery(prepared.input)
result.allowedActions.push('steer')
result.steerTarget = { runId: run.id, generation: run.generation }
}
catch (error) { result.blockedReason = reason(error) }
}
else if (pending.delivery?.mode === 'current' && pending.delivery.target) {
result.blockedReason = 'target_unavailable'
}
this.#options.control?.assertQueue(condition)
if (!accepting())
return { allowedActions: [], steerTarget: null, blockedReason: 'service_unavailable' }
if (this.#options.runner.isStopping || this.#options.eventLog.state !== 'open')
return { allowedActions: ['cancel'], steerTarget: null, blockedReason: 'service_unavailable' }
}
catch (error) {
result.blockedReason = reason(error)
result.allowedActions = result.blockedReason === 'service_unavailable' ? [] : result.allowedActions.filter(action => action === 'cancel')
result.steerTarget = null
}
if (result.allowedActions.some(action => action !== 'cancel'))
result.blockedReason = null
return result
}

cancelRun(runId: string): Promise<LocalRun> {
const pending = this.#cancellations.get(runId)
if (pending)
Expand Down Expand Up @@ -248,15 +321,21 @@ export class ChatQueueService {
return { input, runId, promoteNext }
}

commitSteer(prepared: Awaited<ReturnType<ChatQueueService['prepareSteer']>>) {
const { input, runId, promoteNext } = prepared
#assertSteerReady(input: QueuedTurnRequestInput, runId: string) {
const current = this.#options.runs.findById(runId)
if (this.#disposed || this.#options.eventLog.state !== 'open' || this.#isCancelling(input, input.buddyId)
|| !current || !this.#canFollowUp(current, input) || !this.#options.queue.isCurrentInput(input)
|| !this.#options.runner.hasActiveExecution(input.conversationId, input.buddyId, input.branchId)) {
throw new BuddyServiceError('INPUT_DELIVERY_TARGET_UNAVAILABLE')
}
this.#options.availability?.assertRunExecutable(runId)
if (current.purpose !== 'chat' || !['root', 'actor_child'].includes(current.executionKind))
throw new BuddyServiceError('INPUT_DELIVERY_TARGET_UNAVAILABLE')
}

commitSteer(prepared: Awaited<ReturnType<ChatQueueService['prepareSteer']>>) {
const { input, runId, promoteNext } = prepared
this.#assertSteerReady(input, runId)
const reference = this.#inputReference(input)
this.#options.queue.commitInRun(input, runId, this.#options.getRunPermissionCeiling(runId), promoteNext)
return () => {
Expand All @@ -275,13 +354,18 @@ export class ChatQueueService {
return { input, sourceRunId: latest?.id ?? null, sourceGeneration: latest ? this.#options.runs.findById(latest.id)?.generation ?? null : null }
}

commitContinue(prepared: Awaited<ReturnType<ChatQueueService['prepareContinue']>>) {
#assertContinueReady(prepared: Awaited<ReturnType<ChatQueueService['prepareContinue']>>) {
const { input } = prepared
const latest = this.#options.queue.latestRun(input, input.buddyId)
if (!this.#canDispatch(input) || !this.#options.queue.isCurrentInput(input)
|| (latest?.id ?? null) !== prepared.sourceRunId || (latest ? this.#options.runs.findById(latest.id)?.generation ?? null : null) !== prepared.sourceGeneration) {
throw new BuddyServiceError('INPUT_DELIVERY_TARGET_UNAVAILABLE')
}
}

commitContinue(prepared: Awaited<ReturnType<ChatQueueService['prepareContinue']>>) {
this.#assertContinueReady(prepared)
const { input } = prepared
const request = this.#options.requests.prepare({ ...input, createdAt: new Date().toISOString() })
return { request, notify: async () => {
this.#changed('dispatched', input)
Expand Down
Loading
Loading