Skip to content
Open
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
2 changes: 1 addition & 1 deletion config/main-sync-fs-baseline.txt
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@
1 src/main/emulator/emulator-probe.ts
2 src/main/emulator/serve-sim-detached-session.ts
7 src/main/emulator/serve-sim-execution.ts
17 src/main/emulator/serve-sim-runtime-materializer.ts
19 src/main/emulator/serve-sim-runtime-materializer.ts
12 src/main/external-editors/external-editor-launch.ts
17 src/main/filesystem/atomic-file-publication.ts
9 src/main/filesystem/durable-file-write.ts
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { findSqliteRuntimeTests } from './vitest-sqlite-runtime-scan.mjs'

// SQLite publication, native bindings, worker IPC, socket liveness, and V8 retention use Node.
const NODE_RUNTIME_INCLUDE = [
'src/main/ipc/emulator-control-stream.test.ts',
// Exercise the native fetch error and abort contracts used by the Linear SDK in Electron.
'tests/e2e/linear-cli-recovery.unit.test.ts',
'src/main/runtime/agent-session/lifecycle/structured-agent-cli-writers.test.ts',
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@
"proper-lockfile": "4.1.2",
"qrcode": "^1.5.4",
"react-i18next": "17.0.19",
"serve-sim": "0.1.47",
"serve-sim": "0.1.49",
"smol-toml": "1.9.1",
"ssh2": "^1.17.0",
"stream-chain": "4.2.6",
Expand Down
33 changes: 6 additions & 27 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions src/main/emulator/backends/ios-emulator-backend.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ describe('IosEmulatorBackend', () => {
expect(sendEmulatorGestureSequenceMock).not.toHaveBeenCalled()
})

it('sends taps in raw panel coordinates so serve-sim does not remap landscape twice', async () => {
const backend = new IosEmulatorBackend()
await backend.tap('device-1', 0.2, 0.3)
const args = execServeSimCommandMock.mock.calls.at(-1)?.[1]
expect(args?.slice(0, 3)).toEqual(['tap', '0.2', '0.3'])
expect(args).toContain('--raw')
})

it('does not recycle the device for unrelated helper start failures', async () => {
execServeSimCommandMock.mockRejectedValueOnce(
new EmulatorError('emulator_error', 'Helper failed:\n[main] Port 3100 already in use')
Expand Down
3 changes: 2 additions & 1 deletion src/main/emulator/backends/ios-emulator-backend.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,8 @@ export class IosEmulatorBackend implements EmulatorBackend {
async tap(deviceId: string, x: number, y: number): Promise<void> {
const udid = await this.resolveDeviceId(deviceId)
await assertSimulatorInputNotShadowedByDeviceHub(udid)
await this.execServeSim(['tap', x.toString(), y.toString(), '-d', udid])
// Callers already map to the raw portrait panel; serve-sim >= 0.1.49 would remap landscape again.
await this.execServeSim(['tap', x.toString(), y.toString(), '-d', udid, '--raw'])
}

async gesture(
Expand Down
5 changes: 3 additions & 2 deletions src/main/emulator/emulator-bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ export class EmulatorBridge {
return this.sessionRegistry.getActiveForWorktree(worktreeId)
}

hasControlStreamUrl = (url: string): boolean => this.sessionRegistry.hasControlStreamUrl(url)

// Keep slow-booting Android devices alive across switches for fast reattachment.
async stopActiveForSwitch(worktreeId: string): Promise<string | null> {
const keepAlive = this.backendForActiveWorktree(worktreeId)?.kind === 'android'
Expand Down Expand Up @@ -133,10 +135,9 @@ export class EmulatorBridge {
if (!backend) {
return null
}
const sessionInfo = this.sessionRegistry.toSessionInfo(session)
await this.startLeases.cleanupWhenIdle(
backend,
sessionInfo,
this.sessionRegistry.toSessionInfo(session),
(info) => this.sessionRegistry.hasActiveWorktreeForSession(info.deviceUdid),
{
includeOrphaned: !options.managedOnly,
Expand Down
9 changes: 9 additions & 0 deletions src/main/emulator/emulator-session-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,15 @@ export class EmulatorSessionRegistry {
return [...this.sessions.values()]
}

hasControlStreamUrl(url: string): boolean {
for (const session of this.sessions.values()) {
if (session.wsUrl === url) {
return true
}
}
return false
}

clearSessionAndWorktrees(key: string): void {
this.sessions.delete(key)
for (const [worktreeId, activeKey] of this.activeByWorktree.entries()) {
Expand Down
31 changes: 30 additions & 1 deletion src/main/emulator/serve-sim-runtime-materializer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ async function createBundledServeSimPackage(root: string): Promise<string> {
await writeFile(join(nodeModulesDir, 'ws', 'package.json'), '{"name":"ws"}')
await writeFile(
join(packageDir, 'package.json'),
JSON.stringify({ name: 'serve-sim', dependencies: { ws: '^8', 'not-bundled': '^1' } })
JSON.stringify({
name: 'serve-sim',
version: '0.1.47',
dependencies: { ws: '^8', 'not-bundled': '^1' }
})
)
await writeFile(join(packageDir, 'dist', 'serve-sim.js'), 'console.log("serve-sim")')
await writeFile(join(packageDir, 'dist', 'simcam', 'libSimCameraInjector.dylib'), DYLIB_CONTENT, {
Expand Down Expand Up @@ -95,6 +99,7 @@ describe('materializeServeSimRuntime', () => {
version: '1.2.3',
clearQuarantine: () => {
mkdirSync(join(winnerPackageDir, 'dist'), { recursive: true })
cpSync(join(bundledPackageDir, 'package.json'), join(winnerPackageDir, 'package.json'))
writeFileSync(join(winnerPackageDir, 'dist', 'serve-sim.js'), 'winner')
symlinkDir(join(root, 'bundle', 'node_modules', 'ws'), join(winnerNodeModulesDir, 'ws'))
}
Expand Down Expand Up @@ -145,6 +150,30 @@ describe('materializeServeSimRuntime', () => {
expect(seenEntries[0].slice(1)).toEqual(['serve-sim'])
})

it('replaces a cached helper after a dependency upgrade without an app version change', async () => {
const root = await createRoot()
const bundledPackageDir = await createBundledServeSimPackage(root)
const options = {
bundledPackageDir,
targetRootDir: join(root, 'runtime'),
version: '1.2.3',
clearQuarantine: () => {}
}
materializeServeSimRuntime(options)
await writeFile(
join(bundledPackageDir, 'package.json'),
JSON.stringify({ name: 'serve-sim', version: '0.1.49', dependencies: { ws: '^8' } })
)
await writeFile(join(bundledPackageDir, 'dist', 'serve-sim.js'), 'upgraded helper')

const materialized = materializeServeSimRuntime(options)

expect(materialized).not.toBeNull()
expect(await readFile(join(materialized!, 'dist', 'serve-sim.js'), 'utf8')).toBe(
'upgraded helper'
)
})

it('rebuilds when the app moved and the dependency links dangle', async () => {
const root = await createRoot()
const bundledPackageDir = await createBundledServeSimPackage(root)
Expand Down
7 changes: 7 additions & 0 deletions src/main/emulator/serve-sim-runtime-materializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,13 @@ function isMaterializedRuntimeCurrent(bundledPackageDir: string, versionDir: str
return false
}
try {
// The cache is keyed by Orca's version, so a same-version build can bundle a newer serve-sim.
if (
readFileSync(join(bundledPackageDir, 'package.json'), 'utf8') !==
readFileSync(join(nodeModulesDir, 'serve-sim', 'package.json'), 'utf8')
) {
return false
}
return bundledDependencyLinks(bundledPackageDir, nodeModulesDir).every(
({ linkPath, targetPath }) => realpathSync(linkPath) === realpathSync(targetPath)
)
Expand Down
122 changes: 122 additions & 0 deletions src/main/ipc/emulator-control-stream.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
import { EventEmitter, once } from 'node:events'
import { afterEach, expect, it, vi } from 'vitest'
import WebSocket, { WebSocketServer } from 'ws'
import type * as WsModule from 'ws'
import { EmulatorBridge } from '../emulator/emulator-bridge'
import { registerEmulatorControlStreamHandlers } from './emulator-control-stream'

const handlers = new Map<string, (event: unknown, args: unknown) => unknown>()
vi.mock('electron', () => ({
ipcMain: {
removeAllListeners: () => {},
removeHandler: () => {},
handle: (channel: string, handler: (event: unknown, args: unknown) => unknown) =>
handlers.set(channel, handler),
on: (channel: string, handler: (event: unknown, args: unknown) => unknown) =>
handlers.set(channel, handler)
},
BrowserWindow: { fromWebContents: () => ({}) }
}))
vi.mock('ws', async (importOriginal) => {
const actual = await importOriginal<typeof WsModule>()
return {
...actual,
default: Object.assign(
vi.fn(function (url: string) {
return new actual.default(url)
}),
{ OPEN: actual.default.OPEN }
)
}
})

class Owner extends EventEmitter {
isDestroyed = (): boolean => false
send = (_channel: string, event: { type: string; data?: unknown }): void => {
this.emit(event.type, event.data)
}
}

const owners: Owner[] = []
let server: WebSocketServer | undefined

afterEach(async () => {
for (const owner of owners.splice(0)) {
owner.emit('destroyed')
}
if (server) {
for (const socket of server.clients) {
socket.terminate()
}
const closed = once(server, 'close')
server.close()
await closed
server = undefined
}
vi.clearAllMocks()
})

function setup(wsUrl: string) {
const bridge = new EmulatorBridge()
bridge.registerActiveEmulator('worktree', {
deviceUdid: 'device',
streamUrl: 'http://127.0.0.1/stream.mjpeg',
wsUrl
})
registerEmulatorControlStreamHandlers(() => bridge)
const sender = new Owner()
owners.push(sender)
return {
sender,
start: (url = wsUrl, streamId = 'control') =>
handlers.get('emulator:controlStreamStart')?.({ sender }, { wsUrl: url, streamId })
}
}

it('never connects to URLs outside the registered session', () => {
const { start } = setup('ws://127.0.0.1:3100/ws')
for (const url of [
'ws://127.0.0.1:3101/ws',
'ws://example.com/ws',
'ws://127.0.0.1:3100/other'
]) {
expect(() => start(url)).toThrow('registered emulator session')
}
expect(WebSocket).not.toHaveBeenCalled()
})

it('relays text and binary without Origin and releases the socket when the renderer goes away', async () => {
server = new WebSocketServer({ host: '127.0.0.1', port: 0 })
await once(server, 'listening')
const address = server.address()
if (!address || typeof address === 'string') {
throw new Error('Expected TCP address')
}
const { sender, start } = setup(`ws://127.0.0.1:${address.port}/ws`)
const connection = once(server, 'connection')
const opened = once(sender, 'open')
start()
const [socket, request] = await connection
const otherRenderer = new Owner()
handlers.get('emulator:controlStreamSend')?.(
{ sender: otherRenderer },
{ streamId: 'control', data: 'unowned' }
)
handlers.get('emulator:controlStreamStop')?.({ sender: otherRenderer }, { streamId: 'control' })
await opened
expect(request.headers.origin).toBeUndefined()
for (const data of ['text', new Uint8Array([130, 1, 2])]) {
const received = once(socket, 'message')
handlers.get('emulator:controlStreamSend')?.({ sender }, { streamId: 'control', data })
const [bytes, binary] = await received
expect(binary).toBe(typeof data !== 'string')
expect(bytes.toString()).toBe(Buffer.from(data).toString())
const relayed = once(sender, 'message')
socket.send(data)
const [frame] = await relayed
expect(frame instanceof ArrayBuffer ? new Uint8Array(frame) : frame).toEqual(data)
}
const closed = once(socket, 'close')
sender.emit('destroyed')
await closed
})
Loading