bpmax-cli 0.2.1-beta.60 → 0.2.1-beta.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,55 @@
1
- import { chmod, lstat, readFile, realpath, rename, unlink, writeFile } from 'node:fs/promises';
2
- import path from 'node:path';
1
+ import {
2
+ chmod,
3
+ lstat,
4
+ readFile,
5
+ realpath,
6
+ rename,
7
+ unlink,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import path from "node:path";
3
11
 
4
- const REQUEST_KIND = 'bpmax_identity_browser_request';
5
- const RESULT_KIND = 'bpmax_identity_browser_result';
6
- const REVEAL_MOCK_ACTION = 'bpmaxzuibang';
12
+ const REQUEST_KIND = "bpmax_identity_browser_request";
13
+ const RESULT_KIND = "bpmax_identity_browser_result";
14
+ const REVEAL_MOCK_ACTION = "bpmaxzuibang";
7
15
  const TARGET_SEARCH_ATTEMPTS = 3;
8
16
  const TARGET_SEARCH_TIMEOUT_MS = 10_000;
17
+ const TARGET_SEARCH_SETTLE_MS = 2_000;
9
18
  const ROUTE_READY_TIMEOUT_MS = 120_000;
10
19
  const IDENTITY_READBACK_ATTEMPTS = 2;
11
20
  const LEASE_LOCK_STALE_MS = 5 * 60 * 1000;
12
21
  const LEASE_LOCK_ATTEMPTS = 100;
13
22
 
14
23
  function isRecord(value) {
15
- return typeof value === 'object' && value !== null && !Array.isArray(value);
24
+ return typeof value === "object" && value !== null && !Array.isArray(value);
16
25
  }
17
26
 
18
27
  function pathInside(parent, child) {
19
28
  const relative = path.relative(parent, child);
20
- return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
29
+ return (
30
+ relative === "" ||
31
+ (!relative.startsWith("..") && !path.isAbsolute(relative))
32
+ );
21
33
  }
22
34
 
23
35
  async function lstatOptional(file) {
24
36
  try {
25
37
  return await lstat(file);
26
38
  } catch (error) {
27
- if (error?.code === 'ENOENT') return null;
39
+ if (error?.code === "ENOENT") return null;
28
40
  throw error;
29
41
  }
30
42
  }
31
43
 
32
- async function assertRegularFileOrMissing(file, label, { mustBeMissing = false } = {}) {
44
+ async function assertRegularFileOrMissing(
45
+ file,
46
+ label,
47
+ { mustBeMissing = false } = {},
48
+ ) {
33
49
  const info = await lstatOptional(file);
34
50
  if (!info) return;
35
- if (info.isSymbolicLink() || !info.isFile()) throw new Error(`identity_${label}_unsafe`);
51
+ if (info.isSymbolicLink() || !info.isFile())
52
+ throw new Error(`identity_${label}_unsafe`);
36
53
  if (mustBeMissing) throw new Error(`identity_${label}_already_exists`);
37
54
  }
38
55
 
@@ -41,7 +58,8 @@ async function validateOutputPaths(request, requestFile) {
41
58
  const runDir = await realpath(path.resolve(request.run_dir));
42
59
  const evidenceDir = await realpath(path.resolve(request.evidence_dir));
43
60
  const requestInfo = await lstat(requestPath);
44
- if (requestInfo.isSymbolicLink() || !requestInfo.isFile()) throw new Error('identity_request_unsafe');
61
+ if (requestInfo.isSymbolicLink() || !requestInfo.isFile())
62
+ throw new Error("identity_request_unsafe");
45
63
  const realRequest = await realpath(requestPath);
46
64
  const resultPath = path.resolve(request.result_path);
47
65
  const screenshotPath = path.resolve(request.screenshot_path);
@@ -51,30 +69,42 @@ async function validateOutputPaths(request, requestFile) {
51
69
  realpath(path.dirname(screenshotPath)),
52
70
  realpath(path.dirname(leasePath)),
53
71
  ]);
54
- if (!pathInside(runDir, evidenceDir)
55
- || !pathInside(evidenceDir, realRequest)
56
- || !pathInside(evidenceDir, resultParent)
57
- || !pathInside(runDir, screenshotParent)
58
- || !pathInside(runDir, leaseParent)) {
59
- throw new Error('identity_output_scope_invalid');
72
+ if (
73
+ !pathInside(runDir, evidenceDir) ||
74
+ !pathInside(evidenceDir, realRequest) ||
75
+ !pathInside(evidenceDir, resultParent) ||
76
+ !pathInside(runDir, screenshotParent) ||
77
+ !pathInside(runDir, leaseParent)
78
+ ) {
79
+ throw new Error("identity_output_scope_invalid");
60
80
  }
61
81
  await Promise.all([
62
- assertRegularFileOrMissing(resultPath, 'result', { mustBeMissing: true }),
63
- assertRegularFileOrMissing(screenshotPath, 'screenshot', { mustBeMissing: true }),
64
- assertRegularFileOrMissing(leasePath, 'lease'),
82
+ assertRegularFileOrMissing(resultPath, "result", { mustBeMissing: true }),
83
+ assertRegularFileOrMissing(screenshotPath, "screenshot", {
84
+ mustBeMissing: true,
85
+ }),
86
+ assertRegularFileOrMissing(leasePath, "lease"),
65
87
  ]);
66
88
  }
67
89
 
68
90
  async function writeJsonExclusive(file, value) {
69
- await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
91
+ await writeFile(file, `${JSON.stringify(value, null, 2)}\n`, {
92
+ encoding: "utf8",
93
+ flag: "wx",
94
+ mode: 0o600,
95
+ });
70
96
  await chmod(file, 0o600);
71
97
  }
72
98
 
73
99
  async function writeJsonAtomic(file, value) {
74
- await assertRegularFileOrMissing(file, 'lease');
100
+ await assertRegularFileOrMissing(file, "lease");
75
101
  const temp = `${file}.tmp-${Date.now()}-${Math.random().toString(16).slice(2)}`;
76
102
  try {
77
- await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, { encoding: 'utf8', flag: 'wx', mode: 0o600 });
103
+ await writeFile(temp, `${JSON.stringify(value, null, 2)}\n`, {
104
+ encoding: "utf8",
105
+ flag: "wx",
106
+ mode: 0o600,
107
+ });
78
108
  await chmod(temp, 0o600);
79
109
  await rename(temp, file);
80
110
  } catch (error) {
@@ -88,66 +118,85 @@ async function withLeaseLock(leaseFile, action) {
88
118
  const owner = `${Date.now()}-${Math.random().toString(16).slice(2)}`;
89
119
  for (let attempt = 0; attempt < LEASE_LOCK_ATTEMPTS; attempt += 1) {
90
120
  try {
91
- await writeFile(lockFile, `${JSON.stringify({ owner, created_at: new Date().toISOString() })}\n`, {
92
- encoding: 'utf8',
93
- flag: 'wx',
94
- mode: 0o600,
95
- });
121
+ await writeFile(
122
+ lockFile,
123
+ `${JSON.stringify({ owner, created_at: new Date().toISOString() })}\n`,
124
+ {
125
+ encoding: "utf8",
126
+ flag: "wx",
127
+ mode: 0o600,
128
+ },
129
+ );
96
130
  try {
97
131
  return await action();
98
132
  } finally {
99
133
  try {
100
- const current = JSON.parse(await readFile(lockFile, 'utf8'));
101
- if (isRecord(current) && current.owner === owner) await unlink(lockFile);
134
+ const current = JSON.parse(await readFile(lockFile, "utf8"));
135
+ if (isRecord(current) && current.owner === owner)
136
+ await unlink(lockFile);
102
137
  } catch {
103
138
  // Never remove a lock whose ownership cannot be proved.
104
139
  }
105
140
  }
106
141
  } catch (error) {
107
- if (error?.code !== 'EEXIST') throw error;
142
+ if (error?.code !== "EEXIST") throw error;
108
143
  const info = await lstatOptional(lockFile);
109
- if (!info?.isFile() || info.isSymbolicLink()) throw new Error('identity_lease_lock_unsafe');
144
+ if (!info?.isFile() || info.isSymbolicLink())
145
+ throw new Error("identity_lease_lock_unsafe");
110
146
  await new Promise((resolve) => setTimeout(resolve, 20));
111
147
  }
112
148
  }
113
- throw new Error('identity_lease_lock_timeout');
149
+ throw new Error("identity_lease_lock_timeout");
114
150
  }
115
151
 
116
- function assertLeaseTransitionCurrent(existing, request, { allowMissing = false } = {}) {
152
+ function assertLeaseTransitionCurrent(
153
+ existing,
154
+ request,
155
+ { allowMissing = false } = {},
156
+ ) {
117
157
  if (!isRecord(existing) || Object.keys(existing).length === 0) {
118
158
  if (allowMissing) return;
119
- throw new Error('identity_lease_changed');
159
+ throw new Error("identity_lease_changed");
120
160
  }
121
- if (allowMissing && existing.state === 'released') return;
122
- if (existing.lease_id !== request.lease.lease_id
123
- || !['active', 'uncertain'].includes(existing.state)) {
124
- throw new Error('identity_lease_changed');
161
+ if (allowMissing && existing.state === "released") return;
162
+ if (
163
+ existing.lease_id !== request.lease.lease_id ||
164
+ !["active", "uncertain"].includes(existing.state)
165
+ ) {
166
+ throw new Error("identity_lease_changed");
125
167
  }
126
168
  }
127
169
 
128
170
  function assertReleaseClaimAvailable(existing, request) {
129
- const claimRequestId = String(existing.release_operation_request_id || '');
171
+ const claimRequestId = String(existing.release_operation_request_id || "");
130
172
  if (!claimRequestId || claimRequestId === request.request_id) return;
131
- const claimTime = Date.parse(String(existing.mutation_intent_at || ''));
132
- if (Number.isFinite(claimTime) && Date.now() - claimTime > LEASE_LOCK_STALE_MS) return;
133
- throw new Error('identity_lease_recovery_in_progress');
173
+ const claimTime = Date.parse(String(existing.mutation_intent_at || ""));
174
+ if (
175
+ Number.isFinite(claimTime) &&
176
+ Date.now() - claimTime > LEASE_LOCK_STALE_MS
177
+ )
178
+ return;
179
+ throw new Error("identity_lease_recovery_in_progress");
134
180
  }
135
181
 
136
182
  export function identityUiLabelCandidates() {
137
183
  return {
138
- simulation: ['模拟', 'Simulation', 'シミュレーション'],
139
- exitSimulation: ['退出模拟', 'Exit Simulation', 'シミュレーションを終了'],
140
- logout: ['退出登录', 'Log out', 'ログアウト'],
184
+ simulation: ["模拟", "Simulation", "シミュレーション"],
185
+ exitSimulation: ["退出模拟", "Exit Simulation", "シミュレーションを終了"],
186
+ logout: ["退出登录", "Log out", "ログアウト"],
141
187
  };
142
188
  }
143
189
 
144
190
  export function labelsFor(language) {
145
- const preferred = String(language).toLowerCase().startsWith('en')
191
+ const preferred = String(language).toLowerCase().startsWith("en")
146
192
  ? 1
147
193
  : /^(?:jap|ja)/i.test(String(language))
148
194
  ? 2
149
195
  : 0;
150
- const order = (values) => [values[preferred], ...values.filter((_, index) => index !== preferred)];
196
+ const order = (values) => [
197
+ values[preferred],
198
+ ...values.filter((_, index) => index !== preferred),
199
+ ];
151
200
  const candidates = identityUiLabelCandidates();
152
201
  return {
153
202
  simulation: order(candidates.simulation),
@@ -161,7 +210,7 @@ export function mockStateFromGuideAction(count, label, labels) {
161
210
  if (count === 0) return false;
162
211
  if (labels.exitSimulation.includes(label)) return true;
163
212
  if (labels.logout.includes(label)) return false;
164
- throw new Error('identity_action_label_not_found');
213
+ throw new Error("identity_action_label_not_found");
165
214
  }
166
215
 
167
216
  export function profileRouteUserId(value, returnUrl) {
@@ -169,97 +218,137 @@ export function profileRouteUserId(value, returnUrl) {
169
218
  const trusted = new URL(returnUrl);
170
219
  if (url.origin !== trusted.origin) return null;
171
220
  const workspaceMatch = trusted.pathname.match(/^\/w:([^/]+)(?:\/|$)/);
172
- const allowedPaths = new Set(['/userProfileEditor', '/userProfileEditor/']);
221
+ const allowedPaths = new Set(["/userProfileEditor", "/userProfileEditor/"]);
173
222
  if (workspaceMatch) {
174
223
  allowedPaths.add(`/w:${workspaceMatch[1]}/userProfileEditor`);
175
224
  allowedPaths.add(`/w:${workspaceMatch[1]}/userProfileEditor/`);
176
225
  }
177
226
  if (!allowedPaths.has(url.pathname)) return null;
178
- const id = Number(url.searchParams.get('id'));
227
+ const id = Number(url.searchParams.get("id"));
179
228
  return Number.isSafeInteger(id) && id > 0 ? id : null;
180
229
  }
181
230
 
182
231
  function validateRequest(value) {
183
- if (!isRecord(value)
184
- || value.schema_version !== 1
185
- || value.kind !== REQUEST_KIND
186
- || value.transport !== 'chrome_control_ui'
187
- || !['status', 'mock', 'unmock'].includes(value.operation)
188
- || !value.request_id
189
- || !value.nonce
190
- || !value.origin
191
- || !value.return_url
192
- || !value.run_dir
193
- || !value.evidence_dir
194
- || !value.result_path
195
- || !value.screenshot_path
196
- || !isRecord(value.lease)
197
- || !value.lease.lease_file
198
- || value.screenshot_mime !== 'image/jpeg'
199
- || !String(value.screenshot_path).toLowerCase().endsWith('.jpg')
200
- || (value.operation === 'mock' && (!Number.isSafeInteger(Number(value.target_user_id)) || !String(value.target_user_name || '').trim()))
201
- || (value.operation === 'unmock' && !trustedOriginalIdentity(value.lease.expected_original_user, 'lease'))) {
202
- throw new Error('identity_browser_request_invalid');
232
+ if (
233
+ !isRecord(value) ||
234
+ value.schema_version !== 1 ||
235
+ value.kind !== REQUEST_KIND ||
236
+ value.transport !== "chrome_control_ui" ||
237
+ !["status", "mock", "unmock"].includes(value.operation) ||
238
+ !value.request_id ||
239
+ !value.nonce ||
240
+ !value.origin ||
241
+ !value.return_url ||
242
+ !value.run_dir ||
243
+ !value.evidence_dir ||
244
+ !value.result_path ||
245
+ !value.screenshot_path ||
246
+ !isRecord(value.lease) ||
247
+ !value.lease.lease_file ||
248
+ value.screenshot_mime !== "image/jpeg" ||
249
+ !String(value.screenshot_path).toLowerCase().endsWith(".jpg") ||
250
+ (value.operation === "mock" &&
251
+ (!Number.isSafeInteger(Number(value.target_user_id)) ||
252
+ !String(value.target_user_name || "").trim())) ||
253
+ (value.operation === "unmock" &&
254
+ !trustedOriginalIdentity(value.lease.expected_original_user, "lease"))
255
+ ) {
256
+ throw new Error("identity_browser_request_invalid");
203
257
  }
204
- if (Date.parse(value.expires_at) <= Date.now()) throw new Error('identity_browser_request_expired');
258
+ if (Date.parse(value.expires_at) <= Date.now())
259
+ throw new Error("identity_browser_request_expired");
205
260
  const origin = new URL(value.origin).origin;
206
- const workspace = String(value.workspace || '').trim();
261
+ const workspace = String(value.workspace || "").trim();
207
262
  const expectedReturnUrl = new URL(value.href_path, origin).toString();
208
263
  const expectedManagementUrl = `${origin}/w:${encodeURIComponent(workspace)}/userManagement`;
209
- const expectedActions = value.operation === 'status'
210
- ? ['read_current_identity']
211
- : value.operation === 'mock'
212
- ? ['read_current_identity', 'filter_target_name', 'verify_exact_user_id', 'click_simulation', 'click_exit_simulation']
213
- : ['read_current_identity', 'click_exit_simulation'];
214
- if (value.origin !== origin
215
- || value.return_url !== expectedReturnUrl
216
- || value.user_management_url !== expectedManagementUrl) {
217
- throw new Error('identity_browser_origin_mismatch');
264
+ const expectedActions =
265
+ value.operation === "status"
266
+ ? ["read_current_identity"]
267
+ : value.operation === "mock"
268
+ ? [
269
+ "read_current_identity",
270
+ "filter_target_name",
271
+ "verify_exact_user_id",
272
+ "click_simulation",
273
+ "click_exit_simulation",
274
+ ]
275
+ : ["read_current_identity", "click_exit_simulation"];
276
+ if (
277
+ value.origin !== origin ||
278
+ value.return_url !== expectedReturnUrl ||
279
+ value.user_management_url !== expectedManagementUrl
280
+ ) {
281
+ throw new Error("identity_browser_origin_mismatch");
218
282
  }
219
- if (!Array.isArray(value.allowed_ui_actions)
220
- || value.allowed_ui_actions.length !== expectedActions.length
221
- || value.allowed_ui_actions.some((item, index) => item !== expectedActions[index])) {
222
- throw new Error('identity_browser_actions_mismatch');
283
+ if (
284
+ !Array.isArray(value.allowed_ui_actions) ||
285
+ value.allowed_ui_actions.length !== expectedActions.length ||
286
+ value.allowed_ui_actions.some(
287
+ (item, index) => item !== expectedActions[index],
288
+ )
289
+ ) {
290
+ throw new Error("identity_browser_actions_mismatch");
223
291
  }
224
292
  return value;
225
293
  }
226
294
 
227
- function normalizeIdentity(value, source = 'unknown') {
295
+ function normalizeIdentity(value, source = "unknown") {
228
296
  if (!isRecord(value)) return null;
229
297
  const id = Number(value.id);
230
298
  const organizationId = Number(value.organization_id);
231
- const mockByUser = Number(isRecord(value.mock_by_user) ? value.mock_by_user.id : value.mock_by_user);
299
+ const mockByUser = Number(
300
+ isRecord(value.mock_by_user) ? value.mock_by_user.id : value.mock_by_user,
301
+ );
232
302
  const hasPoints = Array.isArray(value.points);
233
303
  const points = hasPoints ? value.points.map(String) : [];
234
- const hasPermissionShape = value.can_mock === true || value.can_mock === false || typeof value.role_key === 'string' || hasPoints;
235
- const canMock = value.can_mock === true || value.can_mock === false
236
- ? value.can_mock
237
- : hasPermissionShape
238
- ? value.role_key === 'super' || points.includes('organization.admin') || points.includes('user.mock')
239
- : null;
304
+ const hasPermissionShape =
305
+ value.can_mock === true ||
306
+ value.can_mock === false ||
307
+ typeof value.role_key === "string" ||
308
+ hasPoints;
309
+ const canMock =
310
+ value.can_mock === true || value.can_mock === false
311
+ ? value.can_mock
312
+ : hasPermissionShape
313
+ ? value.role_key === "super" ||
314
+ points.includes("organization.admin") ||
315
+ points.includes("user.mock")
316
+ : null;
240
317
  return {
241
318
  id: Number.isSafeInteger(id) && id > 0 ? id : null,
242
- name: typeof value.name === 'string' && value.name.trim() ? value.name.trim() : null,
243
- organization_id: Number.isSafeInteger(organizationId) && organizationId > 0 ? organizationId : null,
319
+ name:
320
+ typeof value.name === "string" && value.name.trim()
321
+ ? value.name.trim()
322
+ : null,
323
+ organization_id:
324
+ Number.isSafeInteger(organizationId) && organizationId > 0
325
+ ? organizationId
326
+ : null,
244
327
  mock: value.mock === true || Number(value.mock) === 1,
245
- mock_by_user: Number.isSafeInteger(mockByUser) && mockByUser > 0 ? mockByUser : null,
328
+ mock_by_user:
329
+ Number.isSafeInteger(mockByUser) && mockByUser > 0 ? mockByUser : null,
246
330
  can_mock: canMock,
247
331
  source,
248
332
  };
249
333
  }
250
334
 
251
- function trustedOriginalIdentity(value, source = 'unknown') {
335
+ function trustedOriginalIdentity(value, source = "unknown") {
252
336
  if (!isRecord(value) || value.mock !== false) return null;
253
337
  const identity = normalizeIdentity(value, source);
254
338
  return identity?.id ? identity : null;
255
339
  }
256
340
 
257
- function recoverOriginalIdentity({ originalUser = null, targetUser = null, before = null } = {}) {
258
- const trusted = trustedOriginalIdentity(originalUser, 'lease')
259
- || trustedOriginalIdentity(before, before?.source || 'unknown');
341
+ function recoverOriginalIdentity({
342
+ originalUser = null,
343
+ targetUser = null,
344
+ before = null,
345
+ } = {}) {
346
+ const trusted =
347
+ trustedOriginalIdentity(originalUser, "lease") ||
348
+ trustedOriginalIdentity(before, before?.source || "unknown");
260
349
  if (trusted) return trusted;
261
350
  for (const value of [targetUser, originalUser, before]) {
262
- const identity = normalizeIdentity(value, value?.source || 'unknown');
351
+ const identity = normalizeIdentity(value, value?.source || "unknown");
263
352
  if (!identity?.mock_by_user) continue;
264
353
  return {
265
354
  id: identity.mock_by_user,
@@ -287,14 +376,25 @@ async function waitForUniqueVisible(locator, label, timeoutMs = 15_000) {
287
376
  lastCount = await locator.count();
288
377
  if (lastCount > 1) throw new Error(`${label}_count_${lastCount}`);
289
378
  if (lastCount === 1) {
290
- if (typeof locator.isVisible !== 'function' || await locator.isVisible()) return locator;
379
+ if (
380
+ typeof locator.isVisible !== "function" ||
381
+ (await locator.isVisible())
382
+ )
383
+ return locator;
291
384
  }
292
385
  await new Promise((resolve) => setTimeout(resolve, 250));
293
386
  }
294
- throw new Error(lastCount === 1 ? `${label}_not_visible` : `${label}_count_${lastCount}`);
387
+ throw new Error(
388
+ lastCount === 1 ? `${label}_not_visible` : `${label}_count_${lastCount}`,
389
+ );
295
390
  }
296
391
 
297
- async function waitForUrl(tab, expectedUrl, label, timeoutMs = ROUTE_READY_TIMEOUT_MS) {
392
+ async function waitForUrl(
393
+ tab,
394
+ expectedUrl,
395
+ label,
396
+ timeoutMs = ROUTE_READY_TIMEOUT_MS,
397
+ ) {
298
398
  const deadline = Date.now() + timeoutMs;
299
399
  const expected = new URL(expectedUrl).toString();
300
400
  let current = await tab.url();
@@ -307,7 +407,7 @@ async function waitForUrl(tab, expectedUrl, label, timeoutMs = ROUTE_READY_TIMEO
307
407
 
308
408
  async function navigateAndWait(tab, url, readySelector, label) {
309
409
  const expected = new URL(url).toString();
310
- if (await tab.url() !== expected) {
410
+ if ((await tab.url()) !== expected) {
311
411
  try {
312
412
  await tab.goto(expected);
313
413
  } catch {
@@ -316,59 +416,86 @@ async function navigateAndWait(tab, url, readySelector, label) {
316
416
  }
317
417
  await waitForUrl(tab, expected, label);
318
418
  if (readySelector) {
319
- await waitForUniqueVisible(tab.playwright.locator(readySelector), `${label}_ready`, ROUTE_READY_TIMEOUT_MS);
419
+ await waitForUniqueVisible(
420
+ tab.playwright.locator(readySelector),
421
+ `${label}_ready`,
422
+ ROUTE_READY_TIMEOUT_MS,
423
+ );
320
424
  } else {
321
- await tab.playwright.waitForLoadState({ state: 'domcontentloaded' });
425
+ await tab.playwright.waitForLoadState({ state: "domcontentloaded" });
322
426
  }
323
427
  }
324
428
 
325
- async function ensureOrigin(tab, request) {
429
+ function identityShellUrl(request) {
430
+ return `${request.origin}/w:${encodeURIComponent(request.workspace)}/myProject`;
431
+ }
432
+
433
+ function identityProfileUrl(request, userId) {
434
+ return `${request.origin}/w:${encodeURIComponent(request.workspace)}/userProfileEditor?id=${encodeURIComponent(userId)}`;
435
+ }
436
+
437
+ async function ensureIdentityShell(tab, request) {
326
438
  const current = await tab.url();
327
- if (!current || new URL(current).origin !== request.origin) {
439
+ const currentUrl = current ? new URL(current) : null;
440
+ const shellUrl = identityShellUrl(request);
441
+ const isSameOrigin = currentUrl?.origin === request.origin;
442
+ const isPluginLayout = Boolean(currentUrl?.pathname.includes("/plugin/"));
443
+ if (!isSameOrigin || isPluginLayout) {
328
444
  await navigateAndWait(
329
445
  tab,
330
- request.return_url,
331
- '.page-header .keep-right > .user-info',
332
- 'identity_return_page',
446
+ shellUrl,
447
+ ".page-header .keep-right > .user-info",
448
+ "identity_shell",
333
449
  );
334
450
  }
335
451
  }
336
452
 
453
+ async function navigateToReturnPage(tab, request, label) {
454
+ await navigateAndWait(tab, request.return_url, null, label);
455
+ }
456
+
337
457
  async function openGuide(tab) {
338
458
  const deadline = Date.now() + 15_000;
339
459
  while (Date.now() <= deadline) {
340
- const guide = tab.playwright.locator('.guid-menu-container');
460
+ const guide = tab.playwright.locator(".guid-menu-container");
341
461
  const guideCount = await guide.count();
342
462
  if (guideCount > 1) throw new Error(`identity_guide_count_${guideCount}`);
343
- if (guideCount === 1 && await guide.isVisible()) return guide;
463
+ if (guideCount === 1 && (await guide.isVisible())) return guide;
344
464
 
345
465
  const trigger = await waitForUniqueVisible(
346
- tab.playwright.locator('.page-header .keep-right > .user-info'),
347
- 'identity_header_trigger',
466
+ tab.playwright.locator(".page-header .keep-right > .user-info"),
467
+ "identity_header_trigger",
348
468
  Math.max(250, deadline - Date.now()),
349
469
  );
350
470
  await trigger.click({});
351
- if (typeof tab.playwright.waitForTimeout === 'function') {
471
+ if (typeof tab.playwright.waitForTimeout === "function") {
352
472
  await tab.playwright.waitForTimeout(400);
353
473
  } else {
354
474
  await new Promise((resolve) => setTimeout(resolve, 400));
355
475
  }
356
476
  }
357
- const count = await tab.playwright.locator('.guid-menu-container').count();
477
+ const count = await tab.playwright.locator(".guid-menu-container").count();
358
478
  throw new Error(`identity_guide_count_${count}`);
359
479
  }
360
480
 
361
481
  async function dismissGuideBeforeMutation(tab, actions) {
362
- const guide = tab.playwright.locator('.guid-menu-container');
482
+ const guide = tab.playwright.locator(".guid-menu-container");
363
483
  const guideCount = await guide.count();
364
484
  if (guideCount > 1) throw new Error(`identity_guide_count_${guideCount}`);
365
- if (guideCount === 0 || (typeof guide.isVisible === 'function' && !await guide.isVisible())) return;
485
+ if (
486
+ guideCount === 0 ||
487
+ (typeof guide.isVisible === "function" && !(await guide.isVisible()))
488
+ )
489
+ return;
366
490
 
367
- const close = tab.playwright.locator('.guid-menu-container .guide-header .el-icon-close');
491
+ const close = tab.playwright.locator(
492
+ ".guid-menu-container .guide-header .el-icon-close",
493
+ );
368
494
  const closeCount = await close.count();
369
- if (closeCount !== 1) throw new Error(`identity_guide_close_count_${closeCount}`);
370
- if (typeof close.isVisible === 'function' && !await close.isVisible()) {
371
- throw new Error('identity_guide_close_not_visible');
495
+ if (closeCount !== 1)
496
+ throw new Error(`identity_guide_close_count_${closeCount}`);
497
+ if (typeof close.isVisible === "function" && !(await close.isVisible())) {
498
+ throw new Error("identity_guide_close_not_visible");
372
499
  }
373
500
  try {
374
501
  await close.click({ trial: true });
@@ -376,23 +503,24 @@ async function dismissGuideBeforeMutation(tab, actions) {
376
503
  } catch (error) {
377
504
  if (!isTransientLocatorError(error)) throw error;
378
505
  const trigger = await waitForUniqueVisible(
379
- tab.playwright.locator('.page-header .keep-right > .user-info'),
380
- 'identity_header_trigger_close',
506
+ tab.playwright.locator(".page-header .keep-right > .user-info"),
507
+ "identity_header_trigger_close",
381
508
  5_000,
382
509
  );
383
510
  await trigger.click({ trial: true });
384
511
  await trigger.click({});
385
- actions.push('dismiss identity guide through stable header trigger');
512
+ actions.push("dismiss identity guide through stable header trigger");
386
513
  }
387
514
  await tab.playwright.waitForTimeout(400);
388
- actions.push('dismiss identity guide before target mutation');
515
+ actions.push("dismiss identity guide before target mutation");
389
516
  }
390
517
 
391
518
  async function readVuexIdentity(tab) {
392
519
  try {
393
520
  const value = await tab.playwright.evaluate(() => {
394
521
  const root = globalThis.$nuxt || globalThis.__NUXT__ || null;
395
- const info = root?.$store?.state?.userInfo || root?.state?.userInfo || null;
522
+ const info =
523
+ root?.$store?.state?.userInfo || root?.state?.userInfo || null;
396
524
  if (!info) return null;
397
525
  const points = Array.isArray(info.points) ? info.points.map(String) : [];
398
526
  return {
@@ -402,10 +530,13 @@ async function readVuexIdentity(tab) {
402
530
  mock: info.mock,
403
531
  mock_by_user: info.mock_by_user,
404
532
  role_key: info.role_key,
405
- can_mock: info.role_key === 'super' || points.includes('organization.admin') || points.includes('user.mock'),
533
+ can_mock:
534
+ info.role_key === "super" ||
535
+ points.includes("organization.admin") ||
536
+ points.includes("user.mock"),
406
537
  };
407
538
  });
408
- return normalizeIdentity(value, 'vuex');
539
+ return normalizeIdentity(value, "vuex");
409
540
  } catch {
410
541
  return null;
411
542
  }
@@ -413,10 +544,19 @@ async function readVuexIdentity(tab) {
413
544
 
414
545
  async function readProfileRouteIdentity(tab, returnUrl) {
415
546
  const guide = await openGuide(tab);
416
- const nameLocator = await unique(guide.locator('.guide-footer .user-name', {}), 'identity_footer_name');
547
+ const nameLocator = await unique(
548
+ guide.locator(".guide-footer .user-name", {}),
549
+ "identity_footer_name",
550
+ );
417
551
  const name = (await nameLocator.innerText({})).trim() || null;
418
- const userContainer = await unique(guide.locator('.guide-footer .user-container', {}), 'identity_profile_link');
419
- await userContainer.click({});
552
+ const editAction = await unique(
553
+ guide.locator(".guide-footer .action-item.edit", {}),
554
+ "identity_profile_link",
555
+ );
556
+ await tab.playwright.expectNavigation(() => editAction.click({}), {
557
+ waitUntil: "domcontentloaded",
558
+ timeoutMs: ROUTE_READY_TIMEOUT_MS,
559
+ });
420
560
  const profileDeadline = Date.now() + 10_000;
421
561
  let profileUrl = await tab.url();
422
562
  let id = profileRouteUserId(profileUrl, returnUrl);
@@ -425,92 +565,148 @@ async function readProfileRouteIdentity(tab, returnUrl) {
425
565
  profileUrl = await tab.url();
426
566
  id = profileRouteUserId(profileUrl, returnUrl);
427
567
  }
428
- if (id === null) throw new Error('identity_profile_route_untrusted');
429
- if (typeof tab.back === 'function') {
568
+ if (id === null) throw new Error("identity_profile_route_untrusted");
569
+ if (typeof tab.back === "function") {
430
570
  await tab.back();
431
571
  }
432
572
  await navigateAndWait(
433
573
  tab,
434
574
  returnUrl,
435
- '.page-header .keep-right > .user-info',
436
- 'identity_profile_return',
575
+ ".page-header .keep-right > .user-info",
576
+ "identity_profile_return",
437
577
  );
438
- return normalizeIdentity({ id, name }, 'profile_route');
578
+ return normalizeIdentity({ id, name }, "profile_route");
439
579
  }
440
580
 
441
581
  async function readCurrentIdentity(tab, request, labels) {
442
- await ensureOrigin(tab, request);
582
+ await ensureIdentityShell(tab, request);
443
583
  let identity = await readVuexIdentity(tab);
444
584
  const guide = await openGuide(tab);
445
- const nameLocator = await unique(guide.locator('.guide-footer .user-name', {}), 'identity_footer_name');
585
+ const nameLocator = await unique(
586
+ guide.locator(".guide-footer .user-name", {}),
587
+ "identity_footer_name",
588
+ );
446
589
  const visibleName = (await nameLocator.innerText({})).trim() || null;
447
- let mocked = identity?.source === 'vuex' ? identity.mock : false;
590
+ let mocked = identity?.source === "vuex" ? identity.mock : false;
448
591
  if (!identity?.id) {
449
- const exitAction = guide.locator('.guide-footer .action-item.log-out', {});
592
+ const exitAction = guide.locator(".guide-footer .action-item.log-out", {});
450
593
  const exitCount = await exitAction.count();
451
- const exitLabel = exitCount === 1 ? (await exitAction.innerText({})).trim() : null;
594
+ const exitLabel =
595
+ exitCount === 1 ? (await exitAction.innerText({})).trim() : null;
452
596
  mocked = mockStateFromGuideAction(exitCount, exitLabel, labels);
453
- identity = await readProfileRouteIdentity(tab, request.return_url);
597
+ identity = await readProfileRouteIdentity(tab, identityShellUrl(request));
454
598
  }
455
599
  await openGuide(tab);
456
600
  return {
457
- ...(identity || normalizeIdentity({}, 'dom')),
601
+ ...(identity || normalizeIdentity({}, "dom")),
458
602
  name: visibleName || identity?.name || null,
459
603
  mock: mocked,
460
604
  };
461
605
  }
462
606
 
463
607
  function expectedOriginalUserId(request, before = null) {
464
- const bound = trustedOriginalIdentity(request.lease.expected_original_user, 'lease');
608
+ const bound = trustedOriginalIdentity(
609
+ request.lease.expected_original_user,
610
+ "lease",
611
+ );
465
612
  if (bound?.id) return bound.id;
466
613
  const mockByUser = Number(before?.mock_by_user);
467
614
  return Number.isSafeInteger(mockByUser) && mockByUser > 0 ? mockByUser : null;
468
615
  }
469
616
 
470
- function isExpectedRestoredIdentity(request, before, identity, expectedIdOverride = null) {
617
+ function isExpectedRestoredIdentity(
618
+ request,
619
+ before,
620
+ identity,
621
+ expectedIdOverride = null,
622
+ ) {
471
623
  if (!identity || identity.mock !== false) return false;
472
624
  const override = Number(expectedIdOverride);
473
- const expectedId = Number.isSafeInteger(override) && override > 0
474
- ? override
475
- : expectedOriginalUserId(request, before);
625
+ const expectedId =
626
+ Number.isSafeInteger(override) && override > 0
627
+ ? override
628
+ : expectedOriginalUserId(request, before);
476
629
  return expectedId !== null && identity.id === expectedId;
477
630
  }
478
631
 
479
632
  async function refreshReturnPage(tab, request, label) {
633
+ const shellUrl = identityShellUrl(request);
480
634
  try {
481
- if (typeof tab.reload === 'function') {
635
+ if ((await tab.url()) === shellUrl && typeof tab.reload === "function") {
482
636
  await tab.reload();
483
637
  } else {
484
- await tab.goto(request.return_url);
638
+ await tab.goto(shellUrl);
485
639
  }
486
640
  } catch {
487
641
  // The route checks below still verify whether the refresh completed.
488
642
  }
489
643
  await navigateAndWait(
490
644
  tab,
491
- request.return_url,
492
- '.page-header .keep-right > .user-info',
645
+ shellUrl,
646
+ ".page-header .keep-right > .user-info",
493
647
  label,
494
648
  );
495
649
  }
496
650
 
497
- async function readRestoredIdentity(tab, request, labels, before, actions, expectedIdOverride = null) {
651
+ async function readRestoredIdentity(
652
+ tab,
653
+ request,
654
+ labels,
655
+ before,
656
+ actions,
657
+ expectedIdOverride = null,
658
+ ) {
498
659
  let identity = null;
499
660
  for (let attempt = 1; attempt <= IDENTITY_READBACK_ATTEMPTS; attempt += 1) {
500
- if (attempt > 1) actions.push(`retry restored identity readback attempt ${attempt}`);
661
+ if (attempt > 1)
662
+ actions.push(`retry restored identity readback attempt ${attempt}`);
501
663
  await refreshReturnPage(tab, request, `identity_unmock_refresh_${attempt}`);
502
664
  identity = await readCurrentIdentity(tab, request, labels);
503
- if (isExpectedRestoredIdentity(request, before, identity, expectedIdOverride)) return identity;
665
+ if (
666
+ isExpectedRestoredIdentity(request, before, identity, expectedIdOverride)
667
+ )
668
+ return identity;
669
+ }
670
+ return identity;
671
+ }
672
+
673
+ async function readMockedIdentity(tab, request, labels, actions) {
674
+ let identity = null;
675
+ for (let attempt = 1; attempt <= IDENTITY_READBACK_ATTEMPTS; attempt += 1) {
676
+ if (attempt > 1)
677
+ actions.push(`retry mocked identity readback attempt ${attempt}`);
678
+ // A normal user may be redirected away from myProject. Their own
679
+ // profile route still renders the authenticated desktop shell and lets
680
+ // readCurrentIdentity verify the Vuex identity without trusting the URL id.
681
+ await navigateAndWait(
682
+ tab,
683
+ identityProfileUrl(request, request.target_user_id),
684
+ ".page-header .keep-right > .user-info",
685
+ `identity_mock_profile_refresh_${attempt}`,
686
+ );
687
+ identity = await readCurrentIdentity(tab, request, labels);
688
+ if (
689
+ identity?.mock === true &&
690
+ identity.id === request.target_user_id &&
691
+ (!request.target_user_name || identity.name === request.target_user_name)
692
+ ) {
693
+ return identity;
694
+ }
504
695
  }
505
696
  return identity;
506
697
  }
507
698
 
508
699
  async function writeScreenshot(tab, file) {
509
700
  const jpeg = Buffer.from(await tab.screenshot({ fullPage: false }));
510
- if (jpeg.length < 3 || jpeg[0] !== 0xff || jpeg[1] !== 0xd8 || jpeg[2] !== 0xff) {
511
- throw new Error('identity_screenshot_jpeg_required');
701
+ if (
702
+ jpeg.length < 3 ||
703
+ jpeg[0] !== 0xff ||
704
+ jpeg[1] !== 0xd8 ||
705
+ jpeg[2] !== 0xff
706
+ ) {
707
+ throw new Error("identity_screenshot_jpeg_required");
512
708
  }
513
- await writeFile(file, jpeg, { flag: 'wx', mode: 0o600 });
709
+ await writeFile(file, jpeg, { flag: "wx", mode: 0o600 });
514
710
  await chmod(file, 0o600);
515
711
  }
516
712
 
@@ -525,147 +721,228 @@ function isMockActionRevealRequired(error) {
525
721
  }
526
722
 
527
723
  function cssAttributeValue(value) {
528
- return String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"');
724
+ return String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"');
529
725
  }
530
726
 
531
727
  async function inspectExactTargetAction(tab, request, labels, timeoutMs) {
532
728
  const targetUserId = String(request.target_user_id);
533
729
  const targetUserName = String(request.target_user_name).trim();
534
- return tab.playwright.evaluate(async ({ id, name, buttonLabels, waitMs, stableMs, managementUrl }) => {
535
- const trusted = new URL(managementUrl);
536
- const workspaceMatch = trusted.pathname.match(/^\/w:([^/]+)(?:\/|$)/);
537
- const allowedProfilePaths = new Set(['/userProfileEditor', '/userProfileEditor/']);
538
- if (workspaceMatch) {
539
- allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor`);
540
- allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor/`);
541
- }
542
- const trustedProfileId = (href) => {
543
- try {
544
- const url = new URL(href, trusted.origin);
545
- if (url.origin !== trusted.origin || !allowedProfilePaths.has(url.pathname)) return null;
546
- const value = Number(url.searchParams.get('id'));
547
- return Number.isSafeInteger(value) && value > 0 ? String(value) : null;
548
- } catch {
549
- return null;
730
+ return tab.playwright.evaluate(
731
+ async ({ id, name, buttonLabels, waitMs, stableMs, managementUrl }) => {
732
+ const trusted = new URL(managementUrl);
733
+ const workspaceMatch = trusted.pathname.match(/^\/w:([^/]+)(?:\/|$)/);
734
+ const allowedProfilePaths = new Set([
735
+ "/userProfileEditor",
736
+ "/userProfileEditor/",
737
+ ]);
738
+ if (workspaceMatch) {
739
+ allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor`);
740
+ allowedProfilePaths.add(`/w:${workspaceMatch[1]}/userProfileEditor/`);
550
741
  }
551
- };
552
- const inspect = () => {
553
- const input = document.querySelector('.button-line > .el-input input');
554
- const allRows = Array.from(document.querySelectorAll('tbody tr'));
555
- const rows = allRows.filter((row) => Array.from(row.querySelectorAll('a[href]')).some(
556
- (anchor) => trustedProfileId(anchor.getAttribute('href')) === id,
557
- ));
558
- if (rows.length !== 1) {
559
- return { status: rows.length > 1 ? 'ambiguous' : 'missing', row_count: rows.length };
560
- }
561
- const row = rows[0];
562
- const profileLinks = Array.from(row.querySelectorAll('a[href]')).filter(
563
- (anchor) => trustedProfileId(anchor.getAttribute('href')) === id,
564
- );
565
- const idCount = profileLinks.length;
566
- const nameNodes = Array.from(row.querySelectorAll('.user-name-text'));
567
- const actualName = nameNodes.length === 1 ? String(nameNodes[0].textContent || '').trim() : null;
568
- const buttons = Array.from(row.querySelectorAll('button')).filter(
569
- (button) => buttonLabels.includes(String(button.textContent || '').trim()),
570
- );
571
- const button = buttons.length === 1 ? buttons[0] : null;
572
- const actionLabel = button ? String(button.textContent || '').trim() : null;
573
- const buttonVisible = Boolean(button && button.getClientRects().length > 0);
574
- const buttonEnabled = Boolean(button && !button.disabled && button.getAttribute('aria-disabled') !== 'true');
575
- const ready = String(input?.value || '') === name
576
- && idCount === 1
577
- && nameNodes.length === 1
578
- && actualName === name
579
- && buttons.length === 1
580
- && buttonVisible
581
- && buttonEnabled;
582
- return {
583
- status: ready
584
- ? 'ready'
585
- : actualName && actualName !== name
586
- ? 'name_mismatch'
587
- : buttons.length === 0
588
- ? 'action_label_missing'
589
- : buttons.length > 1
590
- ? 'action_label_ambiguous'
591
- : !buttonVisible
592
- ? 'action_not_visible'
593
- : !buttonEnabled
594
- ? 'action_disabled'
595
- : 'candidate',
596
- row_count: rows.length,
597
- id_count: idCount,
598
- name_count: nameNodes.length,
599
- actual_name: actualName,
600
- action_label: actionLabel,
601
- button_count: buttons.length,
602
- input_value: String(input?.value || ''),
603
- row_index: allRows.indexOf(row),
604
- profile_href: profileLinks.length === 1 ? profileLinks[0].getAttribute('href') : null,
742
+ const trustedProfileId = (href) => {
743
+ try {
744
+ const url = new URL(href, trusted.origin);
745
+ if (
746
+ url.origin !== trusted.origin ||
747
+ !allowedProfilePaths.has(url.pathname)
748
+ )
749
+ return null;
750
+ const value = Number(url.searchParams.get("id"));
751
+ return Number.isSafeInteger(value) && value > 0
752
+ ? String(value)
753
+ : null;
754
+ } catch {
755
+ return null;
756
+ }
757
+ };
758
+ const inspect = () => {
759
+ const input = document.querySelector(".button-line > .el-input input");
760
+ const allRows = Array.from(document.querySelectorAll("tbody tr"));
761
+ const rows = allRows.filter((row) => {
762
+ const hasProfileId = Array.from(row.querySelectorAll("a[href]")).some(
763
+ (anchor) => trustedProfileId(anchor.getAttribute("href")) === id,
764
+ );
765
+ const firstCell = row.querySelector("td");
766
+ const hasVisibleId =
767
+ String(firstCell?.textContent || "").trim() === id;
768
+ return hasProfileId || hasVisibleId;
769
+ });
770
+ if (rows.length !== 1) {
771
+ return {
772
+ status: rows.length > 1 ? "ambiguous" : "missing",
773
+ row_count: rows.length,
774
+ };
775
+ }
776
+ const row = rows[0];
777
+ const profileLinks = Array.from(row.querySelectorAll("a[href]")).filter(
778
+ (anchor) => trustedProfileId(anchor.getAttribute("href")) === id,
779
+ );
780
+ const firstCell = row.querySelector("td");
781
+ const visibleIdMatches =
782
+ String(firstCell?.textContent || "").trim() === id ? 1 : 0;
783
+ const idCount = profileLinks.length || visibleIdMatches;
784
+ const idSource =
785
+ profileLinks.length === 1
786
+ ? "profile_link"
787
+ : visibleIdMatches === 1
788
+ ? "visible_first_cell"
789
+ : null;
790
+ const nameNodes = Array.from(row.querySelectorAll(".user-name-text"));
791
+ const actualName =
792
+ nameNodes.length === 1
793
+ ? String(nameNodes[0].textContent || "").trim()
794
+ : null;
795
+ const buttons = Array.from(row.querySelectorAll("button")).filter(
796
+ (button) =>
797
+ buttonLabels.includes(String(button.textContent || "").trim()),
798
+ );
799
+ const button = buttons.length === 1 ? buttons[0] : null;
800
+ const actionLabel = button
801
+ ? String(button.textContent || "").trim()
802
+ : null;
803
+ const buttonVisible = Boolean(
804
+ button && button.getClientRects().length > 0,
805
+ );
806
+ const buttonEnabled = Boolean(
807
+ button &&
808
+ !button.disabled &&
809
+ button.getAttribute("aria-disabled") !== "true",
810
+ );
811
+ const ready =
812
+ String(input?.value || "") === name &&
813
+ idCount === 1 &&
814
+ nameNodes.length === 1 &&
815
+ actualName === name &&
816
+ buttons.length === 1 &&
817
+ buttonVisible &&
818
+ buttonEnabled;
819
+ return {
820
+ status: ready
821
+ ? "ready"
822
+ : actualName && actualName !== name
823
+ ? "name_mismatch"
824
+ : buttons.length === 0
825
+ ? "action_label_missing"
826
+ : buttons.length > 1
827
+ ? "action_label_ambiguous"
828
+ : !buttonVisible
829
+ ? "action_not_visible"
830
+ : !buttonEnabled
831
+ ? "action_disabled"
832
+ : "candidate",
833
+ row_count: rows.length,
834
+ id_count: idCount,
835
+ name_count: nameNodes.length,
836
+ actual_name: actualName,
837
+ action_label: actionLabel,
838
+ button_count: buttons.length,
839
+ input_value: String(input?.value || ""),
840
+ row_index: allRows.indexOf(row),
841
+ profile_href:
842
+ profileLinks.length === 1
843
+ ? profileLinks[0].getAttribute("href")
844
+ : null,
845
+ id_source: idSource,
846
+ };
605
847
  };
606
- };
607
848
 
608
- const deadline = Date.now() + waitMs;
609
- let sawCandidate = false;
610
- let readySince = null;
611
- while (Date.now() <= deadline) {
612
- const state = inspect();
613
- if (state.status === 'ready') {
614
- readySince ??= Date.now();
615
- if (Date.now() - readySince >= stableMs) return state;
616
- } else {
617
- readySince = null;
849
+ const deadline = Date.now() + waitMs;
850
+ let sawCandidate = false;
851
+ let readySince = null;
852
+ while (Date.now() <= deadline) {
853
+ const state = inspect();
854
+ if (state.status === "ready") {
855
+ readySince ??= Date.now();
856
+ if (Date.now() - readySince >= stableMs) return state;
857
+ } else {
858
+ readySince = null;
859
+ }
860
+ if (state.status === "ambiguous" || state.status === "name_mismatch")
861
+ return state;
862
+ if (state.row_count > 0) sawCandidate = true;
863
+ else if (sawCandidate) return { ...state, status: "overwritten" };
864
+ await new Promise((resolve) => setTimeout(resolve, 250));
618
865
  }
619
- if (state.status === 'ambiguous' || state.status === 'name_mismatch') return state;
620
- if (state.row_count > 0) sawCandidate = true;
621
- else if (sawCandidate) return { ...state, status: 'overwritten' };
622
- await new Promise((resolve) => setTimeout(resolve, 250));
623
- }
624
- const finalState = inspect();
625
- return ['action_label_missing', 'action_label_ambiguous', 'action_not_visible', 'action_disabled'].includes(finalState.status)
626
- ? finalState
627
- : { ...finalState, status: 'timeout' };
628
- }, {
629
- id: targetUserId,
630
- name: targetUserName,
631
- buttonLabels: labels.simulation,
632
- managementUrl: request.user_management_url,
633
- waitMs: timeoutMs,
634
- stableMs: 750,
635
- }, { timeoutMs: timeoutMs + 5_000 });
866
+ const finalState = inspect();
867
+ return [
868
+ "action_label_missing",
869
+ "action_label_ambiguous",
870
+ "action_not_visible",
871
+ "action_disabled",
872
+ ].includes(finalState.status)
873
+ ? finalState
874
+ : { ...finalState, status: "timeout" };
875
+ },
876
+ {
877
+ id: targetUserId,
878
+ name: targetUserName,
879
+ buttonLabels: labels.simulation,
880
+ managementUrl: request.user_management_url,
881
+ waitMs: timeoutMs,
882
+ stableMs: 750,
883
+ },
884
+ { timeoutMs: timeoutMs + 5_000 },
885
+ );
636
886
  }
637
887
 
638
888
  async function resolveExactTargetAction(tab, request, labels, timeoutMs) {
639
889
  const state = await inspectExactTargetAction(tab, request, labels, timeoutMs);
640
- if (state.status === 'ambiguous') throw new Error(`identity_exact_user_row_count_${state.row_count}`);
641
- if (state.status === 'name_mismatch') throw new Error('identity_target_name_changed');
642
- if (state.status === 'action_label_missing') throw new Error('identity_action_label_not_found');
643
- if (state.status === 'action_label_ambiguous') throw new Error(`identity_action_label_ambiguous_${state.button_count}`);
644
- if (state.status === 'action_not_visible') throw new Error('identity_action_not_visible');
645
- if (state.status === 'action_disabled') throw new Error('identity_action_disabled');
646
- if (state.status !== 'ready') return { state, resolved: null };
890
+ if (state.status === "ambiguous")
891
+ throw new Error(`identity_exact_user_row_count_${state.row_count}`);
892
+ if (state.status === "name_mismatch")
893
+ throw new Error("identity_target_name_changed");
894
+ if (state.status === "action_label_missing")
895
+ throw new Error("identity_action_label_not_found");
896
+ if (state.status === "action_label_ambiguous")
897
+ throw new Error(`identity_action_label_ambiguous_${state.button_count}`);
898
+ if (state.status === "action_not_visible")
899
+ throw new Error("identity_action_not_visible");
900
+ if (state.status === "action_disabled")
901
+ throw new Error("identity_action_disabled");
902
+ if (state.status !== "ready") return { state, resolved: null };
647
903
 
648
904
  const targetUserName = String(request.target_user_name).trim();
649
- const profileHref = String(state.profile_href || '');
650
- const profileId = profileHref ? profileRouteUserId(new URL(profileHref, request.origin).toString(), request.user_management_url) : null;
651
- const row = profileHref
652
- ? tab.playwright.locator(`tbody tr:has(a[href="${cssAttributeValue(profileHref)}"])`)
905
+ const profileHref = String(state.profile_href || "");
906
+ const profileId = profileHref
907
+ ? profileRouteUserId(
908
+ new URL(profileHref, request.origin).toString(),
909
+ request.user_management_url,
910
+ )
653
911
  : null;
654
- if (!row
655
- || profileId !== request.target_user_id
656
- || await row.count() !== 1
657
- || await row.locator('.user-name-text', {}).count() !== 1) {
658
- return { state: { ...state, status: 'overwritten' }, resolved: null };
912
+ const row = profileHref
913
+ ? tab.playwright.locator(
914
+ `tbody tr:has(a[href="${cssAttributeValue(profileHref)}"])`,
915
+ )
916
+ : tab.playwright.locator("tbody tr").nth(Number(state.row_index));
917
+ const visibleId = profileHref
918
+ ? null
919
+ : Number((await row.locator("td").first().innerText({})).trim());
920
+ const exactIdConfirmed = profileHref
921
+ ? profileId === request.target_user_id
922
+ : state.id_source === "visible_first_cell" &&
923
+ visibleId === request.target_user_id;
924
+ if (
925
+ !exactIdConfirmed ||
926
+ (await row.count()) !== 1 ||
927
+ (await row.locator(".user-name-text", {}).count()) !== 1
928
+ ) {
929
+ return { state: { ...state, status: "overwritten" }, resolved: null };
659
930
  }
660
- const simulation = row.getByRole('button', { name: state.action_label, exact: true });
931
+ const simulation = row.getByRole("button", {
932
+ name: state.action_label,
933
+ exact: true,
934
+ });
661
935
  const simulationCount = await simulation.count();
662
- if (simulationCount !== 1) throw new Error(`identity_exact_simulation_button_count_${simulationCount}`);
936
+ if (simulationCount !== 1)
937
+ throw new Error(
938
+ `identity_exact_simulation_button_count_${simulationCount}`,
939
+ );
663
940
 
664
941
  return {
665
942
  state,
666
943
  resolved: {
667
944
  simulation,
668
- targetName: String(state.actual_name || '').trim(),
945
+ targetName: String(state.actual_name || "").trim(),
669
946
  actionLabel: state.action_label,
670
947
  },
671
948
  };
@@ -674,44 +951,70 @@ async function resolveExactTargetAction(tab, request, labels, timeoutMs) {
674
951
  async function waitForExactTargetAction(tab, search, request, labels, actions) {
675
952
  const targetUserName = String(request.target_user_name).trim();
676
953
  try {
677
- const existing = await resolveExactTargetAction(tab, request, labels, 1_000);
954
+ const existing = await resolveExactTargetAction(
955
+ tab,
956
+ request,
957
+ labels,
958
+ 1_000,
959
+ );
678
960
  if (existing.resolved) {
679
- actions.push('reuse stable exact target search result');
961
+ actions.push("reuse stable exact target search result");
680
962
  return existing.resolved;
681
963
  }
682
964
  } catch (error) {
683
- if (!isTransientLocatorError(error) && !isMockActionRevealRequired(error)) throw error;
684
- if (isMockActionRevealRequired(error)) actions.push('reveal hidden simulation action');
965
+ if (!isTransientLocatorError(error) && !isMockActionRevealRequired(error))
966
+ throw error;
967
+ if (isMockActionRevealRequired(error))
968
+ actions.push("reveal hidden simulation action");
685
969
  }
686
970
  for (let attempt = 1; attempt <= TARGET_SEARCH_ATTEMPTS; attempt += 1) {
687
971
  if (attempt === 1) {
688
972
  await search.fill(REVEAL_MOCK_ACTION, {});
689
- // userManagement reveals the mock column from a 500 ms debounced watcher.
690
- await tab.playwright.waitForTimeout(750);
973
+ // The same debounced watcher both reveals the mock column and starts a
974
+ // list request. Let that request settle before issuing the target query,
975
+ // otherwise its stale response can overwrite the exact target row.
976
+ await tab.playwright.waitForTimeout(TARGET_SEARCH_SETTLE_MS);
691
977
  } else {
692
- await search.fill('', {});
693
- await tab.playwright.waitForTimeout(100);
978
+ await search.fill("", {});
979
+ await tab.playwright.waitForTimeout(TARGET_SEARCH_SETTLE_MS);
694
980
  }
695
981
  await search.fill(targetUserName, {});
982
+ if (typeof search.press === "function") {
983
+ await search.press("Enter", {});
984
+ actions.push(`submit target user search attempt ${attempt}`);
985
+ }
696
986
  actions.push(`search target user name attempt ${attempt}`);
697
987
  await tab.playwright.waitForTimeout(2_000);
698
- for (let observationAttempt = 1; observationAttempt <= 3; observationAttempt += 1) {
988
+ for (
989
+ let observationAttempt = 1;
990
+ observationAttempt <= 3;
991
+ observationAttempt += 1
992
+ ) {
699
993
  try {
700
- const inspected = await resolveExactTargetAction(tab, request, labels, TARGET_SEARCH_TIMEOUT_MS);
994
+ const inspected = await resolveExactTargetAction(
995
+ tab,
996
+ request,
997
+ labels,
998
+ TARGET_SEARCH_TIMEOUT_MS,
999
+ );
701
1000
  if (inspected.resolved) return inspected.resolved;
702
- if (inspected.state.status === 'overwritten') {
703
- actions.push(`target result overwritten; retry search attempt ${attempt + 1}`);
1001
+ if (inspected.state.status === "overwritten") {
1002
+ actions.push(
1003
+ `target result overwritten; retry search attempt ${attempt + 1}`,
1004
+ );
704
1005
  break;
705
1006
  }
706
1007
  } catch (error) {
707
1008
  if (!isTransientLocatorError(error)) throw error;
708
1009
  const message = error instanceof Error ? error.message : String(error);
709
- actions.push(`transient target UI timeout on attempt ${attempt}.${observationAttempt}: ${message.slice(0, 120)}`);
1010
+ actions.push(
1011
+ `transient target UI timeout on attempt ${attempt}.${observationAttempt}: ${message.slice(0, 120)}`,
1012
+ );
710
1013
  }
711
1014
  await tab.playwright.waitForTimeout(2_000);
712
1015
  }
713
1016
  }
714
- throw new Error('identity_exact_user_row_count_0');
1017
+ throw new Error("identity_exact_user_row_count_0");
715
1018
  }
716
1019
 
717
1020
  async function clickUniqueVisibleAction(tab, actionLabels, fallbackLocator) {
@@ -721,99 +1024,188 @@ async function clickUniqueVisibleAction(tab, actionLabels, fallbackLocator) {
721
1024
  }
722
1025
  const visibleDom = String(await tab.dom_cua.get_visible_dom());
723
1026
  const labelPattern = actionLabels
724
- .map((label) => label.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
725
- .join('|');
726
- const matches = Array.from(visibleDom.matchAll(
727
- new RegExp(`<button\\s+[^>]*node_id=["']?([^\\s"'>]+)["']?[^>]*>(?:(?!</button>)[\\s\\S])*(?:${labelPattern})(?:(?!</button>)[\\s\\S])*</button>`, 'g'),
728
- ));
729
- if (matches.length !== 1) throw new Error(`identity_visible_action_count_${matches.length}`);
1027
+ .map((label) => label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"))
1028
+ .join("|");
1029
+ const matches = Array.from(
1030
+ visibleDom.matchAll(
1031
+ new RegExp(
1032
+ `<button\\s+[^>]*node_id=["']?([^\\s"'>]+)["']?[^>]*>(?:(?!</button>)[\\s\\S])*(?:${labelPattern})(?:(?!</button>)[\\s\\S])*</button>`,
1033
+ "g",
1034
+ ),
1035
+ ),
1036
+ );
1037
+ if (matches.length === 0) {
1038
+ // Some browser surfaces omit virtualized table actions from their visible
1039
+ // DOM snapshot. The fallback remains scoped to the exact, revalidated row.
1040
+ await fallbackLocator.click({});
1041
+ return;
1042
+ }
1043
+ if (matches.length !== 1)
1044
+ throw new Error(`identity_visible_action_count_${matches.length}`);
730
1045
  await tab.dom_cua.click({ node_id: matches[0][1] });
731
1046
  }
732
1047
 
733
- async function clickMock(tab, request, labels, actions, onMutationAttempt = async () => undefined) {
1048
+ async function clickMock(
1049
+ tab,
1050
+ request,
1051
+ labels,
1052
+ actions,
1053
+ onMutationAttempt = async () => undefined,
1054
+ ) {
734
1055
  await navigateAndWait(
735
1056
  tab,
736
1057
  request.user_management_url,
737
- '.button-line > .el-input input',
738
- 'identity_user_management',
1058
+ ".button-line > .el-input input",
1059
+ "identity_user_management",
739
1060
  );
740
- actions.push('navigate user management');
1061
+ actions.push("navigate user management");
741
1062
  const search = await waitForUniqueVisible(
742
- tab.playwright.locator('.button-line > .el-input input'),
743
- 'identity_user_search',
1063
+ tab.playwright.locator(".button-line > .el-input input"),
1064
+ "identity_user_search",
1065
+ );
1066
+ actions.push(
1067
+ `search target user name and verify exact id ${request.target_user_id}`,
1068
+ );
1069
+ let { simulation, targetName } = await waitForExactTargetAction(
1070
+ tab,
1071
+ search,
1072
+ request,
1073
+ labels,
1074
+ actions,
744
1075
  );
745
- actions.push(`search target user name and verify exact id ${request.target_user_id}`);
746
- let { simulation, targetName } = await waitForExactTargetAction(tab, search, request, labels, actions);
747
1076
  const simulationCount = await simulation.count();
748
- if (simulationCount !== 1) throw new Error(`identity_exact_simulation_button_count_${simulationCount}`);
749
- if (typeof simulation.isVisible === 'function' && !await simulation.isVisible()) {
750
- throw new Error('identity_exact_simulation_button_not_visible');
1077
+ if (simulationCount !== 1)
1078
+ throw new Error(
1079
+ `identity_exact_simulation_button_count_${simulationCount}`,
1080
+ );
1081
+ if (
1082
+ typeof simulation.isVisible === "function" &&
1083
+ !(await simulation.isVisible())
1084
+ ) {
1085
+ throw new Error("identity_exact_simulation_button_not_visible");
751
1086
  }
752
- if (typeof simulation.isEnabled === 'function' && !await simulation.isEnabled()) {
753
- throw new Error('identity_exact_simulation_button_disabled');
1087
+ if (
1088
+ typeof simulation.isEnabled === "function" &&
1089
+ !(await simulation.isEnabled())
1090
+ ) {
1091
+ throw new Error("identity_exact_simulation_button_disabled");
754
1092
  }
755
1093
  await dismissGuideBeforeMutation(tab, actions);
756
- const beforeTrial = await resolveExactTargetAction(tab, request, labels, 1_000);
757
- if (!beforeTrial.resolved) throw new Error('identity_exact_user_row_changed_before_click');
1094
+ const beforeTrial = await resolveExactTargetAction(
1095
+ tab,
1096
+ request,
1097
+ labels,
1098
+ 1_000,
1099
+ );
1100
+ if (!beforeTrial.resolved)
1101
+ throw new Error("identity_exact_user_row_changed_before_click");
758
1102
  simulation = beforeTrial.resolved.simulation;
759
1103
  targetName = beforeTrial.resolved.targetName;
760
1104
  await simulation.click({ trial: true });
761
- actions.push(`verify simulation action is clickable for exact user id ${request.target_user_id}`);
762
- const beforeMutation = await resolveExactTargetAction(tab, request, labels, 1_000);
763
- if (!beforeMutation.resolved) throw new Error('identity_exact_user_row_changed_before_click');
1105
+ actions.push(
1106
+ `verify simulation action is clickable for exact user id ${request.target_user_id}`,
1107
+ );
1108
+ const beforeMutation = await resolveExactTargetAction(
1109
+ tab,
1110
+ request,
1111
+ labels,
1112
+ 1_000,
1113
+ );
1114
+ if (!beforeMutation.resolved)
1115
+ throw new Error("identity_exact_user_row_changed_before_click");
764
1116
  simulation = beforeMutation.resolved.simulation;
765
1117
  targetName = beforeMutation.resolved.targetName;
766
1118
  await onMutationAttempt();
767
- await clickUniqueVisibleAction(tab, labels.simulation, simulation);
1119
+ await tab.playwright.expectNavigation(
1120
+ () => clickUniqueVisibleAction(tab, labels.simulation, simulation),
1121
+ {
1122
+ url: request.user_management_url,
1123
+ waitUntil: "domcontentloaded",
1124
+ timeoutMs: ROUTE_READY_TIMEOUT_MS,
1125
+ },
1126
+ );
768
1127
  actions.push(`click simulation for exact user id ${request.target_user_id}`);
769
1128
  await navigateAndWait(
770
1129
  tab,
771
- request.return_url,
772
- '.page-header .keep-right > .user-info',
773
- 'identity_mock_return',
1130
+ identityShellUrl(request),
1131
+ ".page-header .keep-right > .user-info",
1132
+ "identity_mock_return",
774
1133
  );
775
1134
  return targetName;
776
1135
  }
777
1136
 
778
- async function clickUnmock(tab, request, labels, actions, onMutationAttempt = async () => undefined) {
779
- await ensureOrigin(tab, request);
1137
+ async function clickUnmock(
1138
+ tab,
1139
+ request,
1140
+ labels,
1141
+ actions,
1142
+ onMutationAttempt = async () => undefined,
1143
+ ) {
1144
+ await ensureIdentityShell(tab, request);
780
1145
  const currentUrl = await tab.url();
781
1146
  const guide = await openGuide(tab);
782
1147
  const exit = await waitForUniqueVisible(
783
- guide.locator('.guide-footer .action-item.log-out', {}),
784
- 'identity_exit_simulation',
1148
+ guide.locator(".guide-footer .action-item.log-out", {}),
1149
+ "identity_exit_simulation",
785
1150
  );
786
1151
  if (!labels.exitSimulation.includes((await exit.innerText({})).trim())) {
787
- throw new Error('identity_action_label_not_found');
1152
+ throw new Error("identity_action_label_not_found");
788
1153
  }
789
1154
  await onMutationAttempt();
790
- await tab.playwright.expectNavigation(
791
- () => exit.click({}),
792
- { url: currentUrl, waitUntil: 'domcontentloaded', timeoutMs: ROUTE_READY_TIMEOUT_MS },
793
- );
794
- actions.push('click exit simulation');
1155
+ await tab.playwright.expectNavigation(() => exit.click({}), {
1156
+ url: currentUrl,
1157
+ waitUntil: "domcontentloaded",
1158
+ timeoutMs: ROUTE_READY_TIMEOUT_MS,
1159
+ });
1160
+ actions.push("click exit simulation");
795
1161
  await navigateAndWait(
796
1162
  tab,
797
- request.return_url,
798
- '.page-header .keep-right > .user-info',
799
- 'identity_unmock_return',
1163
+ identityShellUrl(request),
1164
+ ".page-header .keep-right > .user-info",
1165
+ "identity_unmock_return",
800
1166
  );
801
1167
  }
802
1168
 
803
- async function bestEffortUnmock(tab, request, labels, expectedOriginalId = null) {
1169
+ async function bestEffortUnmock(
1170
+ tab,
1171
+ request,
1172
+ labels,
1173
+ expectedOriginalId = null,
1174
+ ) {
804
1175
  try {
805
1176
  const before = await readCurrentIdentity(tab, request, labels);
806
- const isExpectedOriginal = (identity) => identity?.mock === false
807
- && (expectedOriginalId === null || identity.id === expectedOriginalId);
1177
+ const isExpectedOriginal = (identity) =>
1178
+ identity?.mock === false &&
1179
+ (expectedOriginalId === null || identity.id === expectedOriginalId);
808
1180
  if (!before.mock) {
809
- return { attempted: false, readback_confirmed: isExpectedOriginal(before), after: before };
1181
+ return {
1182
+ attempted: false,
1183
+ readback_confirmed: isExpectedOriginal(before),
1184
+ after: before,
1185
+ };
810
1186
  }
811
1187
  const actions = [];
812
1188
  await clickUnmock(tab, request, labels, actions);
813
- const after = await readRestoredIdentity(tab, request, labels, before, actions, expectedOriginalId);
814
- return { attempted: true, readback_confirmed: isExpectedOriginal(after), after, actions };
1189
+ const after = await readRestoredIdentity(
1190
+ tab,
1191
+ request,
1192
+ labels,
1193
+ before,
1194
+ actions,
1195
+ expectedOriginalId,
1196
+ );
1197
+ return {
1198
+ attempted: true,
1199
+ readback_confirmed: isExpectedOriginal(after),
1200
+ after,
1201
+ actions,
1202
+ };
815
1203
  } catch (error) {
816
- return { attempted: true, readback_confirmed: false, error: error instanceof Error ? error.message : String(error) };
1204
+ return {
1205
+ attempted: true,
1206
+ readback_confirmed: false,
1207
+ error: error instanceof Error ? error.message : String(error),
1208
+ };
817
1209
  }
818
1210
  }
819
1211
 
@@ -821,22 +1213,31 @@ async function persistMutationIntentLease(request, before) {
821
1213
  await withLeaseLock(request.lease.lease_file, async () => {
822
1214
  let existing = {};
823
1215
  try {
824
- const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
1216
+ const parsed = JSON.parse(
1217
+ await readFile(request.lease.lease_file, "utf8"),
1218
+ );
825
1219
  if (isRecord(parsed)) existing = parsed;
826
1220
  } catch {
827
1221
  // A mock starts without a lease; diagnostic recovery may also start without one.
828
1222
  }
829
- assertLeaseTransitionCurrent(existing, request, { allowMissing: request.operation === 'mock' });
830
- if (request.operation === 'unmock') assertReleaseClaimAvailable(existing, request);
831
- const targetUser = request.operation === 'mock'
832
- ? normalizeIdentity({
833
- id: request.target_user_id,
834
- name: request.target_user_name,
835
- organization_id: request.target_organization_id,
836
- mock: true,
837
- mock_by_user: before?.id,
838
- }, 'unknown')
839
- : existing.target_user || before || null;
1223
+ assertLeaseTransitionCurrent(existing, request, {
1224
+ allowMissing: request.operation === "mock",
1225
+ });
1226
+ if (request.operation === "unmock")
1227
+ assertReleaseClaimAvailable(existing, request);
1228
+ const targetUser =
1229
+ request.operation === "mock"
1230
+ ? normalizeIdentity(
1231
+ {
1232
+ id: request.target_user_id,
1233
+ name: request.target_user_name,
1234
+ organization_id: request.target_organization_id,
1235
+ mock: true,
1236
+ mock_by_user: before?.id,
1237
+ },
1238
+ "unknown",
1239
+ )
1240
+ : existing.target_user || before || null;
840
1241
  const originalUser = recoverOriginalIdentity({
841
1242
  originalUser: existing.original_user,
842
1243
  targetUser,
@@ -845,24 +1246,31 @@ async function persistMutationIntentLease(request, before) {
845
1246
  const nextLease = {
846
1247
  ...existing,
847
1248
  schema_version: 1,
848
- kind: 'bpmax_identity_lease',
1249
+ kind: "bpmax_identity_lease",
849
1250
  lease_id: request.lease.lease_id,
850
- state: 'uncertain',
1251
+ state: "uncertain",
851
1252
  operation_request_id: request.request_id,
852
1253
  created_at: existing.created_at || request.created_at,
853
- ...(request.lease.expires_at ? { expires_at: request.lease.expires_at } : {}),
1254
+ ...(request.lease.expires_at
1255
+ ? { expires_at: request.lease.expires_at }
1256
+ : {}),
854
1257
  target_user: targetUser,
855
1258
  original_user: originalUser,
856
- browser_tool: 'chrome:control-chrome',
1259
+ browser_tool: "chrome:control-chrome",
857
1260
  recovery_required: true,
858
- binding: request.operation === 'mock' ? request.binding : existing.binding || request.binding,
1261
+ binding:
1262
+ request.operation === "mock"
1263
+ ? request.binding
1264
+ : existing.binding || request.binding,
859
1265
  mutation_intent_at: new Date().toISOString(),
860
- ...(request.operation === 'unmock' ? {
861
- release_operation_request_id: request.request_id,
862
- release_binding: request.binding,
863
- } : {}),
1266
+ ...(request.operation === "unmock"
1267
+ ? {
1268
+ release_operation_request_id: request.request_id,
1269
+ release_binding: request.binding,
1270
+ }
1271
+ : {}),
864
1272
  };
865
- if (request.operation === 'mock') {
1273
+ if (request.operation === "mock") {
866
1274
  delete nextLease.released_at;
867
1275
  delete nextLease.release_operation_request_id;
868
1276
  delete nextLease.release_binding;
@@ -874,33 +1282,45 @@ async function persistMutationIntentLease(request, before) {
874
1282
 
875
1283
  function sameIdentityBinding(left, right) {
876
1284
  if (!isRecord(left) || !isRecord(right)) return false;
877
- return Boolean(left.diagnostic) === Boolean(right.diagnostic)
878
- && String(left.recording_session || '') === String(right.recording_session || '')
879
- && String(left.profile || '') === String(right.profile || '')
880
- && String(left.execution_manifest || '') === String(right.execution_manifest || '')
881
- && String(left.case_id || '') === String(right.case_id || '')
882
- && String(left.case_step_id || '') === String(right.case_step_id || '');
1285
+ return (
1286
+ Boolean(left.diagnostic) === Boolean(right.diagnostic) &&
1287
+ String(left.recording_session || "") ===
1288
+ String(right.recording_session || "") &&
1289
+ String(left.profile || "") === String(right.profile || "") &&
1290
+ String(left.execution_manifest || "") ===
1291
+ String(right.execution_manifest || "") &&
1292
+ String(left.case_id || "") === String(right.case_id || "") &&
1293
+ String(left.case_step_id || "") === String(right.case_step_id || "")
1294
+ );
883
1295
  }
884
1296
 
885
1297
  async function recoverMockMutationIntent(request, currentIdentity) {
886
1298
  try {
887
- const lease = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
888
- if (!isRecord(lease)
889
- || lease.kind !== 'bpmax_identity_lease'
890
- || lease.lease_id !== request.lease.lease_id
891
- || lease.operation_request_id !== request.request_id
892
- || !['active', 'uncertain'].includes(lease.state)
893
- || !sameIdentityBinding(lease.binding, request.binding)
894
- || !isRecord(lease.target_user)
895
- || Number(lease.target_user.id) !== Number(request.target_user_id)
896
- || Number(lease.target_user.organization_id || 0) !== Number(request.target_organization_id || 0)
897
- || !isRecord(lease.original_user)
898
- || Number(currentIdentity?.id) !== Number(request.target_user_id)
899
- || currentIdentity?.mock !== true) {
1299
+ const lease = JSON.parse(await readFile(request.lease.lease_file, "utf8"));
1300
+ if (
1301
+ !isRecord(lease) ||
1302
+ lease.kind !== "bpmax_identity_lease" ||
1303
+ lease.lease_id !== request.lease.lease_id ||
1304
+ lease.operation_request_id !== request.request_id ||
1305
+ !["active", "uncertain"].includes(lease.state) ||
1306
+ !sameIdentityBinding(lease.binding, request.binding) ||
1307
+ !isRecord(lease.target_user) ||
1308
+ Number(lease.target_user.id) !== Number(request.target_user_id) ||
1309
+ Number(lease.target_user.organization_id || 0) !==
1310
+ Number(request.target_organization_id || 0) ||
1311
+ !isRecord(lease.original_user) ||
1312
+ Number(currentIdentity?.id) !== Number(request.target_user_id) ||
1313
+ currentIdentity?.mock !== true
1314
+ ) {
900
1315
  return null;
901
1316
  }
902
- const original = normalizeIdentity(lease.original_user, 'lease');
903
- if (!original || original.mock || !Number.isSafeInteger(Number(original.id))) return null;
1317
+ const original = normalizeIdentity(lease.original_user, "lease");
1318
+ if (
1319
+ !original ||
1320
+ original.mock ||
1321
+ !Number.isSafeInteger(Number(original.id))
1322
+ )
1323
+ return null;
904
1324
  return { original };
905
1325
  } catch {
906
1326
  return null;
@@ -911,31 +1331,44 @@ async function persistBrowserLease(request, result, options = {}) {
911
1331
  const now = new Date().toISOString();
912
1332
  const cleanup = options.cleanup || result.cleanup;
913
1333
  const localResultWriteFailed = options.localResultWriteFailed === true;
914
- if (request.operation === 'mock') {
1334
+ if (request.operation === "mock") {
915
1335
  const originalId = Number(result.before?.id);
916
- const restored = cleanup?.readback_confirmed === true
917
- && cleanup.after?.mock === false
918
- && Number.isSafeInteger(originalId)
919
- && originalId > 0
920
- && cleanup.after?.id === originalId;
921
- const active = result.ok === true && result.readback_confirmed === true && result.after?.mock === true;
922
- if (!restored && !active && result.mutation_attempted !== true && result.remote_submitted !== true) return;
1336
+ const restored =
1337
+ cleanup?.readback_confirmed === true &&
1338
+ cleanup.after?.mock === false &&
1339
+ Number.isSafeInteger(originalId) &&
1340
+ originalId > 0 &&
1341
+ cleanup.after?.id === originalId;
1342
+ const active =
1343
+ result.ok === true &&
1344
+ result.readback_confirmed === true &&
1345
+ result.after?.mock === true;
1346
+ if (
1347
+ !restored &&
1348
+ !active &&
1349
+ result.mutation_attempted !== true &&
1350
+ result.remote_submitted !== true
1351
+ )
1352
+ return;
923
1353
  await withLeaseLock(request.lease.lease_file, async () => {
924
1354
  let existing = {};
925
1355
  try {
926
- const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
1356
+ const parsed = JSON.parse(
1357
+ await readFile(request.lease.lease_file, "utf8"),
1358
+ );
927
1359
  if (isRecord(parsed)) existing = parsed;
928
1360
  } catch {
929
1361
  // A mutating mock must already have persisted its intent lease.
930
1362
  }
931
1363
  assertLeaseTransitionCurrent(existing, request);
932
- if (existing.operation_request_id !== request.request_id) throw new Error('identity_lease_changed');
1364
+ if (existing.operation_request_id !== request.request_id)
1365
+ throw new Error("identity_lease_changed");
933
1366
  const lease = {
934
1367
  ...existing,
935
1368
  schema_version: 1,
936
- kind: 'bpmax_identity_lease',
1369
+ kind: "bpmax_identity_lease",
937
1370
  lease_id: request.lease.lease_id,
938
- state: restored ? 'released' : active ? 'active' : 'uncertain',
1371
+ state: restored ? "released" : active ? "active" : "uncertain",
939
1372
  operation_request_id: request.request_id,
940
1373
  created_at: request.created_at,
941
1374
  expires_at: request.lease.expires_at,
@@ -944,47 +1377,56 @@ async function persistBrowserLease(request, result, options = {}) {
944
1377
  : existing.target_user || result.after || result.current_user || null,
945
1378
  original_user: recoverOriginalIdentity({
946
1379
  originalUser: existing.original_user,
947
- targetUser: existing.target_user || result.after || result.current_user,
1380
+ targetUser:
1381
+ existing.target_user || result.after || result.current_user,
948
1382
  before: result.before,
949
1383
  }),
950
- browser_tool: 'chrome:control-chrome',
1384
+ browser_tool: "chrome:control-chrome",
951
1385
  recovery_required: !restored,
952
1386
  binding: existing.binding || request.binding,
953
1387
  ...(restored ? { released_at: now } : {}),
954
- ...(localResultWriteFailed ? { local_result_write_failed_at: now } : {}),
1388
+ ...(localResultWriteFailed
1389
+ ? { local_result_write_failed_at: now }
1390
+ : {}),
955
1391
  };
956
1392
  await writeJsonAtomic(request.lease.lease_file, lease);
957
1393
  });
958
1394
  return;
959
1395
  }
960
- if (request.operation !== 'unmock') return;
1396
+ if (request.operation !== "unmock") return;
961
1397
  if (result.ok !== true && result.mutation_attempted !== true) return;
962
1398
  await withLeaseLock(request.lease.lease_file, async () => {
963
1399
  let existing = {};
964
1400
  try {
965
- const parsed = JSON.parse(await readFile(request.lease.lease_file, 'utf8'));
1401
+ const parsed = JSON.parse(
1402
+ await readFile(request.lease.lease_file, "utf8"),
1403
+ );
966
1404
  if (isRecord(parsed)) existing = parsed;
967
1405
  } catch {
968
1406
  // A missing or invalid prior lease remains fail-closed below.
969
1407
  }
970
1408
  assertLeaseTransitionCurrent(existing, request);
971
1409
  if (existing.release_operation_request_id !== request.request_id) {
972
- throw new Error('identity_lease_changed');
1410
+ throw new Error("identity_lease_changed");
973
1411
  }
974
- const restored = result.ok === true
975
- && result.readback_confirmed === true
976
- && isExpectedRestoredIdentity(request, result.before, result.after);
1412
+ const restored =
1413
+ result.ok === true &&
1414
+ result.readback_confirmed === true &&
1415
+ isExpectedRestoredIdentity(request, result.before, result.after);
977
1416
  const lease = {
978
1417
  ...existing,
979
1418
  schema_version: 1,
980
- kind: 'bpmax_identity_lease',
1419
+ kind: "bpmax_identity_lease",
981
1420
  lease_id: request.lease.lease_id,
982
- state: restored ? 'released' : 'uncertain',
1421
+ state: restored ? "released" : "uncertain",
983
1422
  operation_request_id: request.request_id,
984
1423
  created_at: existing.created_at || request.created_at,
985
- original_user: trustedOriginalIdentity(request.lease.expected_original_user, 'lease'),
1424
+ original_user: trustedOriginalIdentity(
1425
+ request.lease.expected_original_user,
1426
+ "lease",
1427
+ ),
986
1428
  ...(restored ? { released_at: result.finished_at || now } : {}),
987
- browser_tool: 'chrome:control-chrome',
1429
+ browser_tool: "chrome:control-chrome",
988
1430
  recovery_required: !restored,
989
1431
  binding: existing.binding || request.binding,
990
1432
  release_operation_request_id: request.request_id,
@@ -999,7 +1441,7 @@ async function runOperation(tab, request) {
999
1441
  const startedAt = new Date().toISOString();
1000
1442
  const labels = labelsFor(request.language);
1001
1443
  const actions = [];
1002
- await ensureOrigin(tab, request);
1444
+ await ensureIdentityShell(tab, request);
1003
1445
  let before = await readCurrentIdentity(tab, request, labels);
1004
1446
  let after = before;
1005
1447
  let permissionPreflight;
@@ -1014,62 +1456,95 @@ async function runOperation(tab, request) {
1014
1456
  mutationAttempted = true;
1015
1457
  };
1016
1458
  try {
1017
- if (request.operation === 'mock') {
1459
+ if (request.operation === "mock") {
1018
1460
  if (before.mock) {
1019
1461
  const recovered = await recoverMockMutationIntent(request, before);
1020
- if (!recovered) throw new Error('identity_already_mocked');
1462
+ if (!recovered) throw new Error("identity_already_mocked");
1021
1463
  after = before;
1022
1464
  before = recovered.original;
1023
1465
  mutationAttempted = true;
1024
1466
  remoteSubmitted = true;
1025
1467
  operationExecuted = true;
1026
- permissionPreflight = { granted: true, source: 'request_mutation_intent' };
1027
- actions.push(`recover completed simulation for exact user id ${request.target_user_id}`);
1468
+ permissionPreflight = {
1469
+ granted: true,
1470
+ source: "request_mutation_intent",
1471
+ };
1472
+ actions.push(
1473
+ `recover completed simulation for exact user id ${request.target_user_id}`,
1474
+ );
1028
1475
  }
1029
- if (before.can_mock === false) throw new Error('identity_user_mock_permission_missing');
1030
- if (before.organization_id && request.target_organization_id && before.organization_id !== request.target_organization_id) {
1031
- throw new Error('identity_target_organization_mismatch');
1476
+ if (before.can_mock === false)
1477
+ throw new Error("identity_user_mock_permission_missing");
1478
+ if (
1479
+ before.organization_id &&
1480
+ request.target_organization_id &&
1481
+ before.organization_id !== request.target_organization_id
1482
+ ) {
1483
+ throw new Error("identity_target_organization_mismatch");
1032
1484
  }
1033
1485
  if (!after.mock) {
1034
1486
  permissionPreflight = {
1035
1487
  granted: before.can_mock !== false,
1036
- source: before.can_mock === true ? 'current_user_points' : 'user_management_action',
1488
+ source:
1489
+ before.can_mock === true
1490
+ ? "current_user_points"
1491
+ : "user_management_action",
1037
1492
  };
1038
- targetName = await clickMock(tab, request, labels, actions, markMutationAttempt);
1493
+ targetName = await clickMock(
1494
+ tab,
1495
+ request,
1496
+ labels,
1497
+ actions,
1498
+ markMutationAttempt,
1499
+ );
1039
1500
  remoteSubmitted = true;
1040
1501
  operationExecuted = true;
1041
- after = await readCurrentIdentity(tab, request, labels);
1042
- if (!after.mock || after.id !== request.target_user_id || (targetName && after.name !== targetName)) {
1043
- throw new Error('identity_mock_readback_mismatch');
1502
+ after = await readMockedIdentity(tab, request, labels, actions);
1503
+ if (
1504
+ !after.mock ||
1505
+ after.id !== request.target_user_id ||
1506
+ (targetName && after.name !== targetName)
1507
+ ) {
1508
+ throw new Error("identity_mock_readback_mismatch");
1044
1509
  }
1045
1510
  }
1046
- } else if (request.operation === 'unmock') {
1511
+ } else if (request.operation === "unmock") {
1047
1512
  await persistMutationIntentLease(request, before);
1048
- const expectedOriginalId = Number(request.lease.expected_original_user?.id);
1049
- alreadyRestored = !before.mock
1050
- && Number.isSafeInteger(expectedOriginalId)
1051
- && expectedOriginalId > 0
1052
- && before.id === expectedOriginalId;
1053
- if (!before.mock && !alreadyRestored) throw new Error('identity_not_mocked');
1513
+ const expectedOriginalId = Number(
1514
+ request.lease.expected_original_user?.id,
1515
+ );
1516
+ alreadyRestored =
1517
+ !before.mock &&
1518
+ Number.isSafeInteger(expectedOriginalId) &&
1519
+ expectedOriginalId > 0 &&
1520
+ before.id === expectedOriginalId;
1521
+ if (!before.mock && !alreadyRestored)
1522
+ throw new Error("identity_not_mocked");
1054
1523
  if (alreadyRestored) {
1055
- actions.push('confirm identity already restored to the lease origin');
1524
+ actions.push("confirm identity already restored to the lease origin");
1056
1525
  } else {
1057
1526
  await clickUnmock(tab, request, labels, actions, markMutationAttempt);
1058
1527
  remoteSubmitted = true;
1059
1528
  operationExecuted = true;
1060
- after = await readRestoredIdentity(tab, request, labels, before, actions);
1529
+ after = await readRestoredIdentity(
1530
+ tab,
1531
+ request,
1532
+ labels,
1533
+ before,
1534
+ actions,
1535
+ );
1061
1536
  if (!isExpectedRestoredIdentity(request, before, after)) {
1062
- throw new Error('identity_unmock_readback_mismatch');
1537
+ throw new Error("identity_unmock_readback_mismatch");
1063
1538
  }
1064
1539
  }
1065
1540
  }
1066
- await openGuide(tab);
1541
+ await navigateToReturnPage(tab, request, "identity_final_return");
1067
1542
  await writeScreenshot(tab, request.screenshot_path);
1068
1543
  return {
1069
1544
  schema_version: 1,
1070
1545
  kind: RESULT_KIND,
1071
- transport: 'chrome_control_ui',
1072
- browser_tool: 'chrome:control-chrome',
1546
+ transport: "chrome_control_ui",
1547
+ browser_tool: "chrome:control-chrome",
1073
1548
  request_id: request.request_id,
1074
1549
  nonce: request.nonce,
1075
1550
  operation: request.operation,
@@ -1082,14 +1557,18 @@ async function runOperation(tab, request) {
1082
1557
  before,
1083
1558
  after,
1084
1559
  current_user: after,
1085
- ...(permissionPreflight ? { permission_preflight: permissionPreflight } : {}),
1086
- ...(request.operation === 'mock' ? {
1087
- lease: {
1088
- lease_id: request.lease.lease_id,
1089
- expires_at: request.lease.expires_at,
1090
- recovery_required: true,
1091
- },
1092
- } : {}),
1560
+ ...(permissionPreflight
1561
+ ? { permission_preflight: permissionPreflight }
1562
+ : {}),
1563
+ ...(request.operation === "mock"
1564
+ ? {
1565
+ lease: {
1566
+ lease_id: request.lease.lease_id,
1567
+ expires_at: request.lease.expires_at,
1568
+ recovery_required: true,
1569
+ },
1570
+ }
1571
+ : {}),
1093
1572
  actions,
1094
1573
  runtime_url: await tab.url(),
1095
1574
  screenshot_path: request.screenshot_path,
@@ -1100,20 +1579,32 @@ async function runOperation(tab, request) {
1100
1579
  } catch (error) {
1101
1580
  if (mutationAttempted) {
1102
1581
  try {
1103
- after = request.operation === 'unmock'
1104
- ? await readRestoredIdentity(tab, request, labels, before, actions)
1105
- : await readCurrentIdentity(tab, request, labels);
1106
- if (request.operation === 'mock' && after.mock && after.id === request.target_user_id) {
1582
+ after =
1583
+ request.operation === "unmock"
1584
+ ? await readRestoredIdentity(tab, request, labels, before, actions)
1585
+ : await readCurrentIdentity(tab, request, labels);
1586
+ if (
1587
+ request.operation === "mock" &&
1588
+ after.mock &&
1589
+ after.id === request.target_user_id
1590
+ ) {
1107
1591
  remoteSubmitted = true;
1108
1592
  operationExecuted = true;
1109
- permissionPreflight ??= { granted: true, source: 'user_management_action' };
1110
- await openGuide(tab);
1593
+ permissionPreflight ??= {
1594
+ granted: true,
1595
+ source: "user_management_action",
1596
+ };
1597
+ await navigateToReturnPage(
1598
+ tab,
1599
+ request,
1600
+ "identity_recovered_final_return",
1601
+ );
1111
1602
  await writeScreenshot(tab, request.screenshot_path);
1112
1603
  return {
1113
1604
  schema_version: 1,
1114
1605
  kind: RESULT_KIND,
1115
- transport: 'chrome_control_ui',
1116
- browser_tool: 'chrome:control-chrome',
1606
+ transport: "chrome_control_ui",
1607
+ browser_tool: "chrome:control-chrome",
1117
1608
  request_id: request.request_id,
1118
1609
  nonce: request.nonce,
1119
1610
  operation: request.operation,
@@ -1140,16 +1631,23 @@ async function runOperation(tab, request) {
1140
1631
  finished_at: new Date().toISOString(),
1141
1632
  };
1142
1633
  }
1143
- if (request.operation === 'unmock' && isExpectedRestoredIdentity(request, before, after)) {
1634
+ if (
1635
+ request.operation === "unmock" &&
1636
+ isExpectedRestoredIdentity(request, before, after)
1637
+ ) {
1144
1638
  remoteSubmitted = true;
1145
1639
  operationExecuted = true;
1146
- await openGuide(tab);
1640
+ await navigateToReturnPage(
1641
+ tab,
1642
+ request,
1643
+ "identity_recovered_final_return",
1644
+ );
1147
1645
  await writeScreenshot(tab, request.screenshot_path);
1148
1646
  return {
1149
1647
  schema_version: 1,
1150
1648
  kind: RESULT_KIND,
1151
- transport: 'chrome_control_ui',
1152
- browser_tool: 'chrome:control-chrome',
1649
+ transport: "chrome_control_ui",
1650
+ browser_tool: "chrome:control-chrome",
1153
1651
  request_id: request.request_id,
1154
1652
  nonce: request.nonce,
1155
1653
  operation: request.operation,
@@ -1174,9 +1672,14 @@ async function runOperation(tab, request) {
1174
1672
  // The normal failure path below will retain a fail-closed lease state.
1175
1673
  }
1176
1674
  }
1177
- if (request.operation === 'mock' && (remoteSubmitted || after?.mock)) {
1675
+ if (request.operation === "mock" && (remoteSubmitted || after?.mock)) {
1178
1676
  remoteSubmitted = remoteSubmitted || after?.mock === true;
1179
- cleanup = await bestEffortUnmock(tab, request, labels, before?.id ?? null);
1677
+ cleanup = await bestEffortUnmock(
1678
+ tab,
1679
+ request,
1680
+ labels,
1681
+ before?.id ?? null,
1682
+ );
1180
1683
  }
1181
1684
  try {
1182
1685
  await openGuide(tab);
@@ -1187,8 +1690,8 @@ async function runOperation(tab, request) {
1187
1690
  return {
1188
1691
  schema_version: 1,
1189
1692
  kind: RESULT_KIND,
1190
- transport: 'chrome_control_ui',
1191
- browser_tool: 'chrome:control-chrome',
1693
+ transport: "chrome_control_ui",
1694
+ browser_tool: "chrome:control-chrome",
1192
1695
  request_id: request.request_id,
1193
1696
  nonce: request.nonce,
1194
1697
  operation: request.operation,
@@ -1199,11 +1702,14 @@ async function runOperation(tab, request) {
1199
1702
  readback_confirmed: false,
1200
1703
  before,
1201
1704
  after,
1202
- ...(permissionPreflight ? { permission_preflight: permissionPreflight } : {}),
1705
+ ...(permissionPreflight
1706
+ ? { permission_preflight: permissionPreflight }
1707
+ : {}),
1203
1708
  ...(cleanup ? { cleanup } : {}),
1204
1709
  actions,
1205
1710
  error: {
1206
- kind: error instanceof Error ? error.message : 'identity_browser_failed',
1711
+ kind:
1712
+ error instanceof Error ? error.message : "identity_browser_failed",
1207
1713
  message: error instanceof Error ? error.message : String(error),
1208
1714
  },
1209
1715
  runtime_url: await tab.url(),
@@ -1216,12 +1722,16 @@ async function runOperation(tab, request) {
1216
1722
  }
1217
1723
 
1218
1724
  export async function executeChromeIdentityBridge({ tab, requestFile }) {
1219
- if (!tab?.playwright
1220
- || typeof tab.goto !== 'function'
1221
- || typeof tab.screenshot !== 'function') {
1222
- throw new Error('chrome_control_tab_required');
1725
+ if (
1726
+ !tab?.playwright ||
1727
+ typeof tab.goto !== "function" ||
1728
+ typeof tab.screenshot !== "function"
1729
+ ) {
1730
+ throw new Error("chrome_control_tab_required");
1223
1731
  }
1224
- const request = validateRequest(JSON.parse(await readFile(requestFile, 'utf8')));
1732
+ const request = validateRequest(
1733
+ JSON.parse(await readFile(requestFile, "utf8")),
1734
+ );
1225
1735
  await validateOutputPaths(request, requestFile);
1226
1736
  const result = await runOperation(tab, request);
1227
1737
  try {
@@ -1229,10 +1739,18 @@ export async function executeChromeIdentityBridge({ tab, requestFile }) {
1229
1739
  await writeJsonExclusive(request.result_path, result);
1230
1740
  } catch (error) {
1231
1741
  let cleanup;
1232
- if (request.operation === 'mock' && result.ok) {
1233
- cleanup = await bestEffortUnmock(tab, request, labelsFor(request.language), result.before?.id ?? null);
1742
+ if (request.operation === "mock" && result.ok) {
1743
+ cleanup = await bestEffortUnmock(
1744
+ tab,
1745
+ request,
1746
+ labelsFor(request.language),
1747
+ result.before?.id ?? null,
1748
+ );
1234
1749
  }
1235
- await persistBrowserLease(request, result, { cleanup, localResultWriteFailed: true }).catch(() => undefined);
1750
+ await persistBrowserLease(request, result, {
1751
+ cleanup,
1752
+ localResultWriteFailed: true,
1753
+ }).catch(() => undefined);
1236
1754
  throw error;
1237
1755
  }
1238
1756
  return {