Files
orca/mobile/scripts/start-emulator-pairing-runtime.mjs
T
Jinjing c16aa89ea7 Improve mobile emulator pairing startup (#6527)
* Implement automated git preparation workflow for mobile PR creation

Introduce a structured hosted review intent preparation workflow to handle
staging, AI commit message generation, committing, and pushing changes
automatically before displaying the pull request composer on mobile.

- Map creation block reasons to descriptive user-facing validation errors
  (e.g., dirty working tree, default branch, detached head) to match desktop.
- Decouple hosted-review business logic into a dedicated service helper.
- Update source control runner hooks to handle the new preparation flow.

* Refactor mobile PR creation to run intent and open URL directly

Remove MobilePrComposeSheet and the local compose form, moving instead
to a direct PR creation workflow that matches the desktop experience.

- Add runMobileHostedReviewCreateIntent to handle the full prepare,
  push, and create sequence.
- Replace useMobileOpenPrSheetRunner with useMobileCreatePrRunner to
  trigger the creation workflow and directly open the created PR URL.
- Simplify state management by removing showPrSheet, prPrefill, and
  associated local compose sheets.

* Propagate git status and commit state on PR creation failure

Update `MobileHostedReviewCreateIntentOutcome` and the local change
commit helper to include optional `committed` and `status` fields in
their failure results.

This ensures that if PR preparation fails, callers still receive the
current repository status and know if their local changes have already
been committed.

* Add tests for mobile hosted review creation flow

Introduce unit tests for runMobileHostedReviewCreateIntent to verify
different scenarios of creating a hosted review on mobile, including:

- Successful flow including staging, committing, pushing, and creating
- Eligibility block handling (e.g., authentication requirements)
- Error reporting when creation fails after an automatic commit

* Block mobile PR creation on unresolved conflicts and refresh status

Prevent creating a hosted review on mobile when there are unresolved
merge conflicts. Also, return the latest git status on failures and
reload it in the UI to keep the source control screen in sync.

* Prefer fetched PR head SHA over cached status SHA for PR checks

On mobile, a create command can commit before opening the review,
meaning the fetched PR's head SHA is fresher than the route's cached
status SHA. Prioritizing the fetched PR head SHA ensures we fetch checks
for the most up-to-date commit.

* Fix mobile PR creation errors and validate branch presence

- Reject branch matches when the status branch is null or missing to
  prevent PR creation when the branch is lost.
- Display actual PR creation errors in the sidebar instead of silently
  ignoring them on failure.
- Trim leading and trailing whitespace from the base branch reference
  before persisting the worktree link.

* Improve mobile emulator pairing startup
2026-06-27 18:48:14 -07:00

155 lines
3.7 KiB
JavaScript

import { spawn } from 'node:child_process'
import { mkdtempSync } from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import process from 'node:process'
import readline from 'node:readline'
function primaryLanIp(lanIpCandidates) {
return lanIpCandidates()[0] || '127.0.0.1'
}
export async function startHeadlessPairingRuntime({
enabled,
orcaCli,
cwd,
lanIpCandidates,
logStep,
logSuccess
}) {
if (!enabled) {
return null
}
logStep('0', 'Starting temporary desktop runtime for mobile pairing...')
const runDir = mkdtempSync(path.join(os.tmpdir(), 'orca-mobile-run.'))
const userData = path.join(runDir, 'userData')
const pairingAddress = primaryLanIp(lanIpCandidates)
const child = spawn(
orcaCli,
['serve', '--mobile-pairing', '--pairing-address', pairingAddress, '--json'],
{
cwd,
env: {
...process.env,
ORCA_E2E_USER_DATA_DIR: userData
},
stdio: ['ignore', 'pipe', 'pipe']
}
)
return await waitForPairingRuntime({ child, userData, pairingAddress, logSuccess })
}
export async function registerWorktreeForPairingRuntime(runtime, worktree, tools) {
if (!runtime) {
return
}
tools.logStep('0.1', 'Registering current worktree in temporary runtime...')
await tools.orca(['repo', 'add', '--path', worktree, '--json'], {
cwd: worktree,
env: runtime.env,
timeout: 60000
})
tools.logSuccess('Registered worktree for mobile runtime')
}
async function waitForPairingRuntime({ child, userData, pairingAddress, logSuccess }) {
let output = ''
let stderr = ''
let resolved = false
let exited = false
let rl = null
let rlErr = null
const stop = () => {
if (!exited) {
child.kill('SIGTERM')
}
rl?.close()
rlErr?.close()
child.stdout?.destroy()
child.stderr?.destroy()
}
const runtimeResult = (pairingUrl) => ({
pairingUrl,
userData,
process: child,
env: {
...process.env,
ORCA_USER_DATA_PATH: userData
},
stop
})
return await new Promise((resolve, reject) => {
const timeout = setTimeout(() => {
if (!resolved) {
resolved = true
stop()
reject(new Error('Timeout waiting for temporary desktop runtime pairing URL'))
}
}, 120000)
const finishResolve = (pairingUrl) => {
if (resolved) {
return
}
resolved = true
clearTimeout(timeout)
logSuccess(`Temporary desktop runtime ready (${pairingAddress})`)
resolve(runtimeResult(pairingUrl))
}
const finishReject = (error) => {
if (resolved) {
return
}
resolved = true
clearTimeout(timeout)
stop()
reject(error)
}
rl = readline.createInterface({ input: child.stdout })
rl.on('line', (line) => {
output += line + '\n'
handleRuntimeLine(line, finishResolve)
})
rlErr = readline.createInterface({ input: child.stderr })
rlErr.on('line', (line) => {
stderr += line + '\n'
})
child.on('error', (error) => {
finishReject(new Error(`Failed to start temporary desktop runtime: ${error.message}`))
})
child.on('exit', (code) => {
exited = true
if (!resolved) {
const detail = stderr.trim() || output.trim() || `exit code ${code}`
finishReject(new Error(`Temporary desktop runtime exited before pairing: ${detail}`))
}
})
})
}
function handleRuntimeLine(line, finishResolve) {
const trimmed = line.trim()
if (!trimmed.startsWith('{')) {
return
}
try {
const result = JSON.parse(trimmed)
const pairingUrl = result?.pairing?.url
if (typeof pairingUrl === 'string' && pairingUrl.length > 0) {
finishResolve(pairingUrl)
}
} catch {
// Ignore non-JSON log lines from Electron startup.
}
}