Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(ios-simulator): verify recording startup

JiangJiahaod337f7ea74f7
diff --git a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
index 781ec9d522..05ea7e0434 100644
--- a/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
+++ b/apps/desktop/src/main/mcp-integrations/__tests__/ios-simulator-media.test.ts
@@ -239,6 +239,7 @@ describe('IOSSimulatorMediaCapture', () => {
launchArgs = args;
const videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -288,6 +289,222 @@ describe('IOSSimulatorMediaCapture', () => {
await expect(stat(path.dirname(launchArgs.at(-1)!))).rejects.toMatchObject({ code: 'ENOENT' });
});
+ it('rejects an immediately exited recorder and clears its state and temp directory', async () => {
+ const videoPaths: string[] = [];
+ const launch = vi.fn((args: readonly string[]) => {
+ videoPaths.push(args.at(-1)!);
+ return {
+ started: new Promise<void>(() => undefined),
+ exited: Promise.resolve(),
+ isAlive: () => false,
+ kill: vi.fn(),
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });
+ const input = {
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent' as const,
+ };
+
+ await expect(capture.startRecording(input)).rejects.toMatchObject({
+ code: 'RECORDING_FAILED',
+ });
+ await expect(capture.startRecording(input)).rejects.toMatchObject({
+ code: 'RECORDING_FAILED',
+ });
+
+ expect(launch).toHaveBeenCalledTimes(2);
+ await Promise.all(
+ videoPaths.map((videoPath) =>
+ expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' }),
+ ),
+ );
+ });
+
+ it('does not report recording success before the first frame is processed', async () => {
+ let resolveStarted: () => void = () => undefined;
+ let resolveExit: () => void = () => undefined;
+ let processAlive = true;
+ const kill = vi.fn(() => {
+ processAlive = false;
+ resolveExit();
+ });
+ const launch = vi.fn(() => ({
+ started: new Promise<void>((resolve) => {
+ resolveStarted = resolve;
+ }),
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ isAlive: () => processAlive,
+ kill,
+ }));
+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });
+ let settled = false;
+ const starting = capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ void starting.then(
+ () => {
+ settled = true;
+ },
+ () => {
+ settled = true;
+ },
+ );
+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());
+ await Promise.resolve();
+ expect(settled).toBe(false);
+
+ resolveStarted();
+ await expect(starting).resolves.toEqual({
+ recordingId: expect.any(String),
+ startedAt: expect.any(String),
+ });
+ await expect(capture.discardInstance('instance-a')).resolves.toBeUndefined();
+ expect(kill).toHaveBeenCalledWith('SIGKILL');
+ });
+
+ it('kills and clears a recorder that never processes its first frame', async () => {
+ let resolveExit: () => void = () => undefined;
+ let processAlive = true;
+ let videoPath = '';
+ const kill = vi.fn(() => {
+ processAlive = false;
+ resolveExit();
+ });
+ const launch = vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ started: new Promise<void>(() => undefined),
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ isAlive: () => processAlive,
+ kill,
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });
+
+ vi.useFakeTimers();
+ const starting = capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ const failure = expect(starting).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());
+ await vi.advanceTimersByTimeAsync(5_000);
+
+ await failure;
+ expect(kill).toHaveBeenCalledWith('SIGKILL');
+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('retries a stuck startup cleanup before launching the next recorder', async () => {
+ let firstResolveExit: () => void = () => undefined;
+ let firstAlive = true;
+ let firstKillCount = 0;
+ let secondResolveExit: () => void = () => undefined;
+ let secondAlive = true;
+ const firstKill = vi.fn(() => {
+ firstKillCount += 1;
+ if (firstKillCount < 2) return;
+ firstAlive = false;
+ firstResolveExit();
+ });
+ const secondKill = vi.fn(() => {
+ secondAlive = false;
+ secondResolveExit();
+ });
+ const launch = vi.fn(() => {
+ if (launch.mock.calls.length === 1) {
+ return {
+ started: new Promise<void>(() => undefined),
+ exited: new Promise<void>((resolve) => {
+ firstResolveExit = resolve;
+ }),
+ isAlive: () => firstAlive,
+ kill: firstKill,
+ };
+ }
+ return {
+ started: Promise.resolve(),
+ exited: new Promise<void>((resolve) => {
+ secondResolveExit = resolve;
+ }),
+ isAlive: () => secondAlive,
+ kill: secondKill,
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });
+ const input = {
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent' as const,
+ };
+
+ vi.useFakeTimers();
+ const firstStart = capture.startRecording(input);
+ const firstFailure = expect(firstStart).rejects.toMatchObject({ code: 'RECORDING_FAILED' });
+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());
+ await vi.advanceTimersByTimeAsync(5_500);
+ await firstFailure;
+ expect(firstKill).toHaveBeenCalledTimes(1);
+
+ const secondStart = await capture.startRecording(input);
+ expect(secondStart.recordingId).toEqual(expect.any(String));
+ expect(firstKill).toHaveBeenCalledTimes(2);
+ expect(launch).toHaveBeenCalledTimes(2);
+ await expect(capture.discardInstance('instance-a')).resolves.toBeUndefined();
+ expect(secondKill).toHaveBeenCalledWith('SIGKILL');
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('keeps a starting recorder visible to Host disposal', async () => {
+ let resolveExit: () => void = () => undefined;
+ let videoPath = '';
+ const kill = vi.fn(() => resolveExit());
+ const launch = vi.fn((args: readonly string[]) => {
+ videoPath = args.at(-1)!;
+ return {
+ started: new Promise<void>(() => undefined),
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ kill,
+ };
+ });
+ const capture = new IOSSimulatorMediaCapture({ recordingLauncher: { launch } });
+ const starting = capture.startRecording({
+ simulatorUdid: 'EXACT-UDID',
+ sessionId: 'session-a',
+ instanceId: 'instance-a',
+ generation: 1,
+ source: 'agent',
+ });
+ await vi.waitFor(() => expect(launch).toHaveBeenCalledOnce());
+
+ const disposing = capture.dispose();
+
+ await expect(starting).rejects.toMatchObject({ code: 'RECORDING_NOT_FOUND' });
+ await expect(disposing).resolves.toBeUndefined();
+ expect(kill).toHaveBeenCalledWith('SIGKILL');
+ await expect(stat(path.dirname(videoPath))).rejects.toMatchObject({ code: 'ENOENT' });
+ });
+
it('does not ingest a recording after its data owner changes during finalization', async () => {
let ownerScopeKey = 'owner-a';
let videoPath = '';
@@ -301,6 +518,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -362,6 +580,7 @@ describe('IOSSimulatorMediaCapture', () => {
const launch = vi.fn((args: readonly string[]) => {
firstVideoPath ||= args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveFirstExit = resolve;
}),
@@ -418,6 +637,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -461,6 +681,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -508,7 +729,7 @@ describe('IOSSimulatorMediaCapture', () => {
if (signal === 'SIGKILL') resolveExit();
});
kills.push(kill);
- return { exited, kill };
+ return { started: Promise.resolve(), exited, kill };
}),
},
});
@@ -581,6 +802,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -645,6 +867,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -693,13 +916,21 @@ describe('IOSSimulatorMediaCapture', () => {
it('bounds recording ingest even when storage never settles', async () => {
let videoPath = '';
+ let resolveExit: () => void = () => undefined;
+ let processAlive = true;
const ingest = vi.fn(() => new Promise<never>(() => undefined));
const launch = vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
- exited: Promise.resolve(),
- isAlive: () => false,
- kill: vi.fn(),
+ started: Promise.resolve(),
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ isAlive: () => processAlive,
+ kill: vi.fn(() => {
+ processAlive = false;
+ resolveExit();
+ }),
};
});
const capture = new IOSSimulatorMediaCapture({
@@ -751,7 +982,11 @@ describe('IOSSimulatorMediaCapture', () => {
recordingLauncher: {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
- return { exited: new Promise<void>(() => undefined), kill };
+ return {
+ started: Promise.resolve(),
+ exited: new Promise<void>(() => undefined),
+ kill,
+ };
}),
},
});
@@ -791,6 +1026,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>(() => undefined),
kill,
};
@@ -855,6 +1091,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveLeaderExit = resolve;
}),
@@ -937,6 +1174,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -980,6 +1218,7 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
videoPath = args.at(-1)!;
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => {
resolveExit = resolve;
}),
@@ -1024,11 +1263,19 @@ describe('IOSSimulatorMediaCapture', () => {
launch: vi.fn((args: readonly string[]) => {
const instanceId = args[2] === 'UDID-A' ? 'instance-a' : 'instance-b';
paths.set(instanceId, args.at(-1)!);
- const kill = vi.fn();
+ let resolveExit: () => void = () => undefined;
+ let processAlive = true;
+ const kill = vi.fn(() => {
+ processAlive = false;
+ resolveExit();
+ });
kills.set(instanceId, kill);
return {
- exited: Promise.resolve(),
- isAlive: () => false,
+ started: Promise.resolve(),
+ exited: new Promise<void>((resolve) => {
+ resolveExit = resolve;
+ }),
+ isAlive: () => processAlive,
kill,
};
}),
@@ -1090,6 +1337,7 @@ describe('IOSSimulatorMediaCapture', () => {
});
kills.set(instanceId, kill);
return {
+ started: Promise.resolve(),
exited: new Promise<void>((resolve) => exits.set(instanceId, resolve)),
kill,
};
diff --git a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
index f2d217ab9b..7d513b1810 100644
--- a/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
+++ b/apps/desktop/src/main/mcp-integrations/ios-simulator-media.ts
@@ -26,6 +26,8 @@ const MAX_SCREENSHOT_BYTES = 32 * 1024 * 1024;
// an amount Electron Main can safely validate and ingest without multi-GiB
// allocations; larger captures are rejected before readFile.
const MAX_BUFFERED_RECORDING_BYTES = 128 * 1024 * 1024;
+const RECORDING_STARTED_MARKER = 'Recording started';
+const RECORDING_STARTUP_TIMEOUT_MS = 5_000;
const RECORDING_STOP_TIMEOUT_MS = 5_000;
const RECORDING_TERM_TIMEOUT_MS = 1_000;
const RECORDING_KILL_TIMEOUT_MS = 500;
@@ -43,6 +45,8 @@ export interface IOSSimulatorMediaCaptureOptions {
}
export interface IOSSimulatorRecordingProcess {
+ /** Resolves only after simctl has processed the first frame. */
+ started: Promise<void>;
exited: Promise<void>;
/** True while the detached recorder process group still owns live members. */
isAlive?(): boolean;
@@ -70,7 +74,7 @@ interface ActiveRecording {
tempRoot: string;
videoPath: string;
process: IOSSimulatorRecordingProcess;
- phase: 'active' | 'finalizing';
+ phase: 'starting' | 'active' | 'finalizing';
discardRequested: boolean;
discardSignalSent: boolean;
discarded: Promise<void>;
@@ -113,7 +117,7 @@ function createRecordingLauncher(): IOSSimulatorRecordingLauncher {
shell: false,
detached: process.platform !== 'win32',
windowsHide: true,
- stdio: ['ignore', 'ignore', 'ignore'],
+ stdio: ['ignore', 'ignore', 'pipe'],
});
child.on('error', () => {
// ChildProcess requires an error listener to avoid an uncaught Main
@@ -127,6 +131,24 @@ function createRecordingLauncher(): IOSSimulatorRecordingLauncher {
}
const pid = child.pid;
let leaderClosed = false;
+ let resolveStarted: () => void = () => undefined;
+ let startedResolved = false;
+ let stderrTail = '';
+ const started = new Promise<void>((resolve) => {
+ resolveStarted = resolve;
+ });
+ child.stderr?.setEncoding('utf8');
+ child.stderr?.on('data', (chunk: string | Buffer) => {
+ if (startedResolved) return;
+ stderrTail = `${stderrTail}${chunk.toString()}`;
+ if (stderrTail.includes(RECORDING_STARTED_MARKER)) {
+ startedResolved = true;
+ stderrTail = '';
+ resolveStarted();
+ return;
+ }
+ stderrTail = stderrTail.slice(-(RECORDING_STARTED_MARKER.length - 1));
+ });
const exited = new Promise<void>((resolve) => {
child.once('close', () => {
leaderClosed = true;
@@ -136,6 +158,7 @@ function createRecordingLauncher(): IOSSimulatorRecordingLauncher {
// gone. `close` plus the group liveness probe remains authoritative.
});
return {
+ started,
exited,
isAlive: () => isProcessGroupAlive(pid, leaderClosed),
kill(signal) {
@@ -154,6 +177,46 @@ function createRecordingLauncher(): IOSSimulatorRecordingLauncher {
};
}
+async function waitForRecordingStartup(
+ process: IOSSimulatorRecordingProcess,
+ timeoutMs: number,
+): Promise<'started' | 'exited' | 'timeout'> {
+ return new Promise((resolve) => {
+ let settled = false;
+ let poll: ReturnType<typeof setInterval> | null = null;
+ const finish = (result: 'started' | 'exited' | 'timeout'): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (poll) clearInterval(poll);
+ resolve(result);
+ };
+ const timer = setTimeout(() => finish('timeout'), timeoutMs);
+ const confirmExit = (): void => {
+ try {
+ if (process.isAlive && !process.isAlive()) finish('exited');
+ } catch {
+ // A failed liveness probe cannot prove the process group is gone.
+ }
+ };
+ if (process.isAlive) {
+ poll = setInterval(confirmExit, 25);
+ confirmExit();
+ }
+ void process.started.then(
+ () => finish('started'),
+ () => undefined,
+ );
+ void process.exited.then(
+ () => {
+ if (!process.isAlive) finish('exited');
+ else confirmExit();
+ },
+ () => undefined,
+ );
+ });
+}
+
async function waitForRecordingExit(
process: IOSSimulatorRecordingProcess,
timeoutMs: number,
@@ -721,6 +784,14 @@ export class IOSSimulatorMediaCapture {
true,
);
}
+ const abandonedStart = (recording: ActiveRecording): boolean =>
+ recording.instanceId === input.instanceId &&
+ recording.phase === 'starting' &&
+ recording.discardRequested;
+ if (Array.from(this.#recordings.values()).some(abandonedStart)) {
+ this.#requestDiscard(abandonedStart);
+ await this.#discardMatching(abandonedStart);
+ }
if (
Array.from(this.#recordings.values()).some((item) => item.instanceId === input.instanceId)
) {
@@ -732,6 +803,7 @@ export class IOSSimulatorMediaCapture {
const tempRoot = await mkdtemp(path.join(os.tmpdir(), 'cindy-ios-recording-'));
const videoPath = path.join(tempRoot, 'recording.mov');
const recordingId = randomUUID();
+ let recording: ActiveRecording | null = null;
try {
if (
this.#closed ||
@@ -758,13 +830,13 @@ export class IOSSimulatorMediaCapture {
'--codec=h264',
videoPath,
]);
- this.#recordings.set(recordingId, {
+ recording = {
...input,
recordingId,
tempRoot,
videoPath,
process,
- phase: 'active',
+ phase: 'starting',
discardRequested: false,
discardSignalSent: false,
discarded,
@@ -773,10 +845,58 @@ export class IOSSimulatorMediaCapture {
instanceEpoch,
ownerScopeKey: ownerScope.ownerScopeKey,
ingestDb: ownerScope.ingestDb,
- });
+ };
+ this.#recordings.set(recordingId, recording);
+ const startup = await waitForRecordingStartup(process, RECORDING_STARTUP_TIMEOUT_MS);
+ let startupError: unknown = null;
+ try {
+ this.#assertRecordingCurrent(recording);
+ } catch (error) {
+ startupError = error;
+ }
+ if (!startupError && startup === 'exited') {
+ startupError = new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The recording process exited before capture became ready.',
+ true,
+ );
+ }
+ if (!startupError && startup === 'timeout') {
+ startupError = new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The recording process did not process its first frame before the startup timeout.',
+ true,
+ );
+ }
+ if (!startupError && process.isAlive) {
+ try {
+ if (!process.isAlive()) {
+ startupError = new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The recording process exited before capture became ready.',
+ true,
+ );
+ }
+ } catch {
+ startupError = new IOSSimulatorInstanceError(
+ 'RECORDING_FAILED',
+ 'The recording process could not be verified after startup.',
+ true,
+ );
+ }
+ }
+ if (startupError) {
+ const matches = (candidate: ActiveRecording): boolean => candidate === recording;
+ this.#requestDiscard(matches);
+ await this.#discardMatching(matches);
+ throw startupError;
+ }
+ recording.phase = 'active';
return { recordingId, startedAt: new Date().toISOString() };
} catch (error) {
- await rm(tempRoot, { recursive: true, force: true });
+ if (!recording) {
+ await rm(tempRoot, { recursive: true, force: true });
+ }
throw error;
}
});