Skip to content

Commit 95c1e20

Browse files
authored
feat: --force/--overwrite for --save-script + arm-time EEXIST preflight (#1266)
* feat: add --force/--overwrite for --save-script, arm-time EEXIST preflight #1235 made healed-script publication refuse-on-exist. #1258 adds an escape hatch: --force (alias --overwrite) on open/close/replay makes publishHealedScriptAtomically atomically REPLACE an existing target (renameSync) instead of refusing. The flag threads CLI -> daemon request -> SessionState.saveScriptForce (persisted at arm time, like saveScriptPath, so a later close/auto-commit that doesn't repeat the flag still honors it) -> the publish primitive. Default (flag absent) is unchanged: refuse-on-exist. Second half: an arm-time EEXIST preflight in session-replay-runtime.ts now fails a repair-armed replay --save-script BEFORE any step dispatches when its target already exists and --force is not set, instead of only failing at publish time after the whole repair run (and its corrective steps) has already executed against the device. * refactor: extract write() catch-block into handleSessionScriptWriteFailure Pure structural refactor, no behavior change: moves the diagnose + classify-and-return / AppError-rethrow logic out of SessionScriptWriter.write into a module-level helper. Drops write()'s cyclomatic below Fallow's threshold (the finding CI flagged on #1266) — the extracted throw still propagates out of the catch exactly as before. * fix: make persisted save-script force consistent (preflight + per-target) Addresses two authorization inconsistencies in the #1258 --force work flagged in re-review: 1. Arm-time EEXIST preflight now uses the SAME effective force decision as publication — `req.flags?.force || preRunSession.saveScriptForce` — instead of the live flag alone. A repair armed with `--save-script --force` and continued via `replay --from … --save-script` (without repeating --force) is no longer rejected on a target the earlier forced leg authorized. 2. Force is now per-target, not sticky-across-retarget. Re-arming a DIFFERENT `--save-script=<other>` without a live --force CLEARS the persisted `saveScriptForce` (new shared `applySaveScriptRetarget`, used by both the replay armer and `recordActionEntry`/close), so a retarget can never silently overwrite a file nobody opted into. A live --force on the retarget re-grants it for the new target. Updated the SessionState doc accordingly. Regressions: persisted-force `--from` continuation is not preflight-rejected; retarget-without-force refuses an existing target (and the --force contrast overwrites it). Both verified to fail without their respective fix. * fix: match arm-time preflight force to per-target retarget contract Re-review ordering-mismatch fix. The preflight computed effective force as `req.flags?.force || preRunSession.saveScriptForce`, accepting persisted force regardless of whether THIS request retargets. So a `--from` continuation with explicit `--save-script=b.ad` (no live force) on a session forced for a.ad would PASS the preflight, run every step, then have `applySaveScriptRetarget` clear the force for b.ad, and finally refuse the existing b.ad at publish time — defeating the arm-time-preflight point and mutating the session mid-run. Now the effective-force decision is computed inside `preflightSaveScriptTarget` against the target THIS request resolves to (the same one the armer will set), matching `applySaveScriptRetarget`'s per-target contract: live force always bypasses; persisted force bypasses ONLY when `targetPath === existingSaveScriptPath` (same target). A retarget to a different path without live force is now refused BEFORE any step dispatches. The preflight stays read-only (runs before the armer; never mutates the session). Regression: a --from continuation retargeting to an existing b.ad without live force fails at the preflight, dispatches zero steps, and leaves saveScriptPath/ saveScriptForce unchanged. Verified it fails (leg passes preflight, runs) when the fix is reverted. Same-target continuation and live-force retarget stay correct. * fix: expose close savedScript to clients; preserve COMPLETE on retarget reject Two re-review blockers. BLOCKER 1 (client-contract gap): the typed close APIs accept --save-script/ --force inputs but dropped the daemon's `savedScript` response, so a Node client could request publication but not learn where the file landed. Add `savedScript?: string` to SessionCloseResult and AppCloseResult, and project it via readOptionalString in both close normalizers (sessions.close, apps.close). New public-client coverage asserts it round-trips (and is absent when the daemon published nothing). BLOCKER 2 (P1 ordering): the C2 `saveScriptComplete = false` reset ran BEFORE the EEXIST preflight's early-return, so a retarget REJECTION corrupted a prior COMPLETE transaction — a later close would then refuse to commit the original target. Move the reset to AFTER `if (saveScriptPreflight) return ...` (verified nothing between the two positions reads saveScriptComplete; applySaveScriptRetarget already runs later, so the original saveScriptPath is preserved). The reset is correct only when the run proceeds to re-arm. Strengthened the retarget-rejection regression to assert (a) saveScriptComplete survives the rejection and (b) a later bare close commits the ORIGINAL target, not the rejected new one. Both verified to fail without their respective fix.
1 parent 6efe544 commit 95c1e20

14 files changed

Lines changed: 747 additions & 65 deletions

‎src/__tests__/client.test.ts‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,34 @@ test('client close normalizes target shutdown results', async () => {
319319
assert.equal(appClose.shutdown, undefined);
320320
});
321321

322+
test('client close surfaces the daemon savedScript path on both sessions.close and apps.close (#1258)', async () => {
323+
const savedScriptPath = '/tmp/agent-device/flows/login.healed.ad';
324+
const setup = createTransport(async () => ({
325+
ok: true,
326+
data: { session: 'qa', savedScript: savedScriptPath },
327+
}));
328+
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
329+
330+
const sessionClose = await client.sessions.close({ saveScript: true });
331+
const appClose = await client.apps.close({ saveScript: true });
332+
333+
// The committed artifact path round-trips so a Node client that requested
334+
// publication learns where the file landed.
335+
assert.equal(sessionClose.savedScript, savedScriptPath);
336+
assert.equal(appClose.savedScript, savedScriptPath);
337+
});
338+
339+
test('client close omits savedScript when the daemon published nothing (#1258)', async () => {
340+
const setup = createTransport(async () => ({ ok: true, data: { session: 'qa' } }));
341+
const client = createAgentDeviceClient(setup.config, { transport: setup.transport });
342+
343+
const sessionClose = await client.sessions.close({});
344+
const appClose = await client.apps.close({});
345+
346+
assert.equal(sessionClose.savedScript, undefined);
347+
assert.equal(appClose.savedScript, undefined);
348+
});
349+
322350
test('observability.perf projects structured frame area to daemon positionals', async () => {
323351
const setup = createTransport(async (req) => {
324352
if (req.command === 'perf') {

‎src/agent-device-client.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -187,6 +187,7 @@ export function createAgentDeviceClient(
187187
session,
188188
shutdown: normalizeTargetShutdownResult(data.shutdown),
189189
provider: readObject(data.provider),
190+
savedScript: readOptionalString(data, 'savedScript'),
190191
identifiers: { session },
191192
};
192193
} finally {
@@ -259,6 +260,7 @@ export function createAgentDeviceClient(
259260
session,
260261
closedApp: options.app,
261262
shutdown: normalizeTargetShutdownResult(data.shutdown),
263+
savedScript: readOptionalString(data, 'savedScript'),
262264
identifiers: { session },
263265
};
264266
},

‎src/client/client-types.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,12 @@ export type SessionCloseResult = {
252252
session: string;
253253
shutdown?: TargetShutdownResult;
254254
provider?: CloudProviderSessionResult;
255+
/**
256+
* #1258: absolute path of the committed session/healed script when this close
257+
* published one (`close --save-script`, or a repair-armed session's finalize)
258+
* — so a client that requested publication learns where the file landed.
259+
*/
260+
savedScript?: string;
255261
identifiers: AgentDeviceIdentifiers;
256262
};
257263

@@ -292,6 +298,8 @@ export type AppOpenOptions = AgentDeviceRequestOverrides &
292298
launchArgs?: string[];
293299
relaunch?: boolean;
294300
saveScript?: boolean | string;
301+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
302+
force?: boolean;
295303
deviceHub?: boolean;
296304
testIme?: boolean;
297305
noRecord?: boolean;
@@ -316,12 +324,21 @@ export type AppOpenResult = {
316324
export type AppCloseOptions = AgentDeviceRequestOverrides & {
317325
app?: string;
318326
shutdown?: boolean;
327+
saveScript?: boolean | string;
328+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
329+
force?: boolean;
319330
};
320331

321332
export type AppCloseResult = {
322333
session: string;
323334
closedApp?: string;
324335
shutdown?: TargetShutdownResult;
336+
/**
337+
* #1258: absolute path of the committed session/healed script when this close
338+
* published one (`close --save-script`, or a repair-armed session's finalize)
339+
* — so a client that requested publication learns where the file landed.
340+
*/
341+
savedScript?: string;
325342
identifiers: AgentDeviceIdentifiers;
326343
};
327344

@@ -866,6 +883,8 @@ export type ReplayRunOptions = AgentDeviceRequestOverrides &
866883
* `<stem>.healed.ad` when the repair ends with `close --save-script`.
867884
*/
868885
saveScript?: boolean | string;
886+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
887+
force?: boolean;
869888
};
870889

871890
export type ReplayTestOptions = AgentDeviceRequestOverrides &
@@ -1072,6 +1091,8 @@ export type InternalRequestOptions = AgentDeviceClientConfig &
10721091
relaunch?: boolean;
10731092
shutdown?: boolean;
10741093
saveScript?: boolean | string;
1094+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
1095+
force?: boolean;
10751096
deviceHub?: boolean;
10761097
testIme?: boolean;
10771098
noRecord?: boolean;
@@ -1110,7 +1131,12 @@ export type AgentDeviceClient = {
11101131
options?: AgentDeviceRequestOverrides & Pick<AgentDeviceClientConfig, 'stateDir'>,
11111132
) => Promise<string>;
11121133
close: (
1113-
options?: AgentDeviceRequestOverrides & { shutdown?: boolean },
1134+
options?: AgentDeviceRequestOverrides & {
1135+
shutdown?: boolean;
1136+
saveScript?: boolean | string;
1137+
/** #1258: overwrite an existing --save-script target instead of refusing. Alias: --overwrite. */
1138+
force?: boolean;
1139+
},
11141140
) => Promise<SessionCloseResult>;
11151141
artifacts: (options?: CloudArtifactsOptions) => Promise<AgentArtifactsResult>;
11161142
};

‎src/commands/cli-grammar/flag-definitions-connection.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -195,10 +195,11 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
195195
},
196196
{
197197
key: 'force',
198-
names: ['--force'],
198+
names: ['--force', '--overwrite'],
199199
type: 'boolean',
200-
usageLabel: '--force',
201-
usageDescription: 'Force connection state replacement when reconnecting',
200+
usageLabel: '--force, --overwrite',
201+
usageDescription:
202+
'Force replacement of existing state (connect: replace an active connection; --save-script: overwrite an existing target instead of refusing)',
202203
},
203204
{
204205
key: 'noLogin',

‎src/commands/management/app.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,9 @@ const openCommandMetadata = defineFieldCommandMetadata(
4040
),
4141
relaunch: booleanField('Force relaunch.'),
4242
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
43+
force: booleanField(
44+
'Overwrite an existing --save-script target instead of refusing (alias: --overwrite).',
45+
),
4346
deviceHub: booleanField('Use Xcode Device Hub when surfacing Apple simulators.'),
4447
testIme: booleanField(
4548
'Activate the headless Android test IME for deterministic Unicode text entry (default on for emulators; opt-in on real devices).',
@@ -65,6 +68,9 @@ const closeCommandMetadata = defineFieldCommandMetadata(
6568
app: stringField('Optional app to close.'),
6669
shutdown: booleanField('Shutdown the session/device where supported.'),
6770
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
71+
force: booleanField(
72+
'Overwrite an existing --save-script target instead of refusing (alias: --overwrite).',
73+
),
6874
},
6975
);
7076

@@ -131,6 +137,7 @@ const openCliSchema = {
131137
'deviceHub',
132138
'testIme',
133139
'saveScript',
140+
'force',
134141
'noRecord',
135142
'relaunch',
136143
'surface',
@@ -143,7 +150,7 @@ const openCliSchema = {
143150

144151
const closeCliSchema = {
145152
positionalArgs: ['app?'],
146-
allowedFlags: ['saveScript', 'shutdown'],
153+
allowedFlags: ['saveScript', 'force', 'shutdown'],
147154
} as const satisfies CommandSchemaOverride;
148155

149156
const appsCliReader: CliReader = (_positionals, flags) => ({
@@ -161,6 +168,7 @@ const openCliReader: CliReader = (positionals, flags) => ({
161168
launchArgs: flags.launchArgs,
162169
relaunch: flags.relaunch,
163170
saveScript: flags.saveScript,
171+
force: flags.force,
164172
deviceHub: flags.deviceHub,
165173
testIme: flags.testIme,
166174
noRecord: flags.noRecord,
@@ -175,6 +183,7 @@ const closeCliReader: CliReader = (positionals, flags) => ({
175183
app: positionals[0],
176184
shutdown: flags.shutdown,
177185
saveScript: flags.saveScript,
186+
force: flags.force,
178187
});
179188

180189
const appsDaemonWriter: DaemonWriter = direct(PUBLIC_COMMANDS.apps);

‎src/commands/replay/index.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,9 @@ export const replayCommandMetadata = defineFieldCommandMetadata(
4949
// from the first replay attempt; optional string value is the healed
5050
// script's output path.
5151
saveScript: jsonSchemaField<boolean | string>({ oneOf: [booleanSchema(), stringSchema()] }),
52+
// #1258: overwrite an existing --save-script target (arm-time preflight +
53+
// publish) instead of refusing. Alias: --overwrite.
54+
force: booleanField(),
5255
},
5356
);
5457

@@ -96,6 +99,7 @@ const replayCliSchema = {
9699
'timeoutMs',
97100
'out',
98101
'saveScript',
102+
'force',
99103
],
100104
} as const satisfies CommandSchemaOverride;
101105

@@ -130,6 +134,7 @@ export const replayCliReader: CliReader = (positionals, flags) => ({
130134
resumeFrom: flags.replayFrom,
131135
resumePlanDigest: flags.replayPlanDigest,
132136
saveScript: flags.saveScript,
137+
force: flags.force,
133138
});
134139

135140
export const testCliReader: CliReader = (positionals, flags) => ({

‎src/daemon/__tests__/session-script-writer.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -283,6 +283,77 @@ test('write() now refuses to clobber a stale PARTIAL (non-sentinel) .healed.ad a
283283
expect(fs.readFileSync(healedPath, 'utf8')).toBe(before);
284284
});
285285

286+
// --- #1258: `--force`/`--overwrite` opts into replacing an existing target
287+
// atomically instead of refusing. ---
288+
289+
test('write(session, { force: true }) overwrites an existing COMPLETE target atomically', () => {
290+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-'));
291+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
292+
const healedPath = path.join(root, 'flows', 'login.healed.ad');
293+
fs.mkdirSync(path.dirname(healedPath), { recursive: true });
294+
fs.writeFileSync(
295+
healedPath,
296+
`context platform=ios device="x"\nclick id="old"\n${HEAL_COMPLETE_SENTINEL}\n`,
297+
);
298+
299+
const session = makeIosSession('default', {
300+
recordSession: true,
301+
saveScriptBoundary: 0,
302+
saveScriptComplete: true,
303+
saveScriptPath: healedPath,
304+
saveScriptDefaultedHealedPath: true,
305+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
306+
});
307+
308+
const result = writer.write(session, { force: true });
309+
expect(result.written).toBe(true);
310+
expect(result.written && result.path).toBe(healedPath);
311+
const parsed = parseReplayScriptDetailed(fs.readFileSync(healedPath, 'utf8'));
312+
expect(parsed.actions.map((a) => a.positionals[0])).toEqual(['id="new"']);
313+
// The overwrite is atomic (rename-replace): only the published target
314+
// remains in the directory, no stray temp file left behind.
315+
expect(fs.readdirSync(path.dirname(healedPath))).toEqual([path.basename(healedPath)]);
316+
});
317+
318+
test('write(session, { force: true }) overwrites an existing target for ORDINARY (non-repair) recording too', () => {
319+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-ordinary-'));
320+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
321+
const outPath = path.join(root, 'flows', 'existing.ad');
322+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
323+
fs.writeFileSync(outPath, 'context platform=ios device="x"\nclick id="old"\n');
324+
325+
const session = makeIosSession('default', {
326+
recordSession: true,
327+
// No saveScriptBoundary: ordinary open/close --save-script, not a repair.
328+
saveScriptPath: outPath,
329+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
330+
});
331+
332+
const result = writer.write(session, { force: true });
333+
expect(result.written).toBe(true);
334+
const parsed = parseReplayScriptDetailed(fs.readFileSync(outPath, 'utf8'));
335+
expect(parsed.actions.map((a) => a.positionals[0])).toEqual(['id="new"']);
336+
});
337+
338+
test('write(session) without { force: true } still refuses, even when a prior write in the same test used force', () => {
339+
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-script-writer-force-default-'));
340+
const writer = new SessionScriptWriter(path.join(root, 'sessions'));
341+
const outPath = path.join(root, 'flows', 'existing.ad');
342+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
343+
fs.writeFileSync(outPath, 'context platform=ios device="x"\nclick id="old"\n');
344+
const before = fs.readFileSync(outPath, 'utf8');
345+
346+
const session = makeIosSession('default', {
347+
recordSession: true,
348+
saveScriptPath: outPath,
349+
actions: [action({ command: 'click', positionals: ['id="new"'] })],
350+
});
351+
352+
// Default (no options / force omitted): refuse-on-exist, unchanged.
353+
expect(() => writer.write(session)).toThrow(/already exists/);
354+
expect(fs.readFileSync(outPath, 'utf8')).toBe(before);
355+
});
356+
286357
// The lock/lease machinery previously here (acquireLease/releaseLease/
287358
// stealExpiredLease/the three-writer interleaving) is gone: the publish
288359
// primitive is now a single exclusive `linkSync`, which already decides a

0 commit comments

Comments
 (0)