Skip to content

Commit 744b3d5

Browse files
committed
test(perf): אבחון בקר macOS לאחר פתיחה ושמירת ראיות מוצר
1 parent c314e48 commit 744b3d5

5 files changed

Lines changed: 124 additions & 7 deletions

File tree

‎.github/workflows/apple-plugin-activity.yml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,6 +95,7 @@ jobs:
9595
- name: Resolve exact dependencies
9696
run: flutter pub get --enforce-lockfile
9797
- name: Select actual runtime
98+
id: runtime_selection
9899
env:
99100
PROBE_PLATFORM: ${{ matrix.platform }}
100101
run: |
@@ -122,11 +123,14 @@ jobs:
122123
open -a Simulator
123124
fi
124125
- name: Verify public identity and diagnose native macOS hide
126+
id: mac_controls
125127
if: matrix.platform == 'macos'
126128
env:
127129
APPLE_HELPER_CONTROL_OUTPUT: ${{ runner.temp }}/apple-helper-controls
128130
run: python3 -m unittest discover -s tool/perf_probe/apple_plugin_activity -p 'test_macos_controller.py' -v
129131
- name: Run installed app hosts and quiet OS transitions
132+
# Collect product evidence after a helper-control failure; that failure remains fatal to this job.
133+
if: ${{ !cancelled() && (success() || (matrix.platform == 'macos' && steps.runtime_selection.outcome == 'success' && steps.mac_controls.outcome == 'failure')) }}
130134
run: >-
131135
python3 tool/perf_probe/apple_plugin_activity/run.py
132136
--platform '${{ matrix.platform }}' --mode '${{ matrix.mode }}'

‎tool/perf_probe/apple_plugin_activity/README.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,6 +145,26 @@ Apple מתעדת שהקריאה הזו מאתחלת את
145145
LaunchServices. אלה בדיקות אבחון של הקורא, בהתאם להבחנה של Apple בין
146146
[בקשת הפעלה לבין העברת החזית בפועל](https://developer.apple.com/documentation/appkit/passing-control-from-one-app-to-another-with-cooperative-activation).
147147

148+
בקרות `dispatch-execution.json` ו־`active-dispatch-execution.json` קוראות
149+
stdin ב־thread נפרד בתוך אותו בקר, ומעבירות כל פקודה לתור
150+
הראשי. ההמתנה לאישור מחזירה שליטה ל־`NSApplication.run()` בין בדיקות,
151+
ו־`mainQueueTurnDelivered` מוכיח שנמסרה פנייה נוספת לתור הראשי. וריאנט
152+
regular דורש גם שהבקר יהיה פעיל ממש לפני קריאת `hide`.
153+
154+
בקרות `opened-bundle-execution.json` ו־`opened-bundle-dispatch-execution.json`
155+
מפעילות `open` על מארז היעד אחרי מוכנות, כמו `onAttached` של Flutter.
156+
`opened-caller-dispatch-execution.json` בודק בנפרד `open` על מארז הבקר
157+
האסינכרוני regular אחרי תשובת `info`. הבקר שומר כל launch לפני בדיקת
158+
הארגומנטים, ולכן גם מופע נוסף שנוצר ויצא מיד פוסל את הבקרה. נדרשים אותו
159+
PID, executable, מזהה launch והיסטוריית הפעלות לפני `open`, אחריו ואחרי
160+
hide/resume. הבקרה של הקורא דורשת `controllerActiveBeforeHide=true`, נוסף
161+
על `hide()==true`, מצב hidden בפועל וזהות היעד השמורה.
162+
163+
כאשר הכנת macOS הצליחה אך בקרות כלי העזר נכשלו, ה־CI אוסף גם את תוצאת
164+
האפליקציה האמיתית כדי להשוות בין ה־fixture למוצר. כשל הבקרות נשאר כשל
165+
בשלב וב־job כולו; הצלחת האפליקציה אינה מכשירה אותו. שני מסלולי הראיות
166+
נשמרים במלואם, וכל דרישות המעברים והזהות של האפליקציה נשארות מחייבות.
167+
148168
שירות ההפעלות החיצוניות בודק `FileSystemEntity.isWatchSupported` לפני
149169
יצירת watcher ברירת המחדל. כשמעקב קבצים אינו נתמך, כמו בריצת iOS,
150170
הערוץ הנייטיבי וניקוז התור ממשיכים לפעול. בפלטפורמה שתומכת במעקב נשמרים

‎tool/perf_probe/apple_plugin_activity/mac_controller_dispatch_diagnostic.swift‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ let diagnosticPolicyAccepted = diagnosticApplication.setActivationPolicy(diagnos
1616
var diagnosticLaunchObserved = false
1717
var diagnosticMainQueueTurnDelivered = false
1818
var diagnosticCommandInFlight = false
19+
var diagnosticActiveBeforeHide = false
1920

2021
func diagnosticRecord(_ details: [String: Any]) {
2122
let data = try! JSONSerialization.data(withJSONObject: details, options: [.sortedKeys])
@@ -63,7 +64,10 @@ func diagnosticReply(_ action: String, sequence: Int, beforeAction: [String: Any
6364
"mainQueueTurnDelivered": diagnosticMainQueueTurnDelivered,
6465
"controllerBoundaryMode": "asynchronous-main-dispatch"
6566
]
66-
if action == "hide" { observation["hideReturnValue"] = true }
67+
if action == "hide" {
68+
observation["hideReturnValue"] = true
69+
observation["controllerActiveBeforeHide"] = diagnosticActiveBeforeHide
70+
}
6771
let data = try! JSONSerialization.data(withJSONObject: observation, options: [.sortedKeys])
6872
print(String(decoding: data, as: UTF8.self))
6973
fflush(stdout)
@@ -91,10 +95,16 @@ func diagnosticCommand(_ line: String) {
9195
let perform = {
9296
verifyIdentity()
9397
if action == "hide" {
98+
diagnosticActiveBeforeHide = diagnosticApplication.isActive
99+
guard !diagnosticRequiresActive || diagnosticActiveBeforeHide else {
100+
fail("controllerActivation", "The controller lost activation before hide", 66,
101+
["applicationState": applicationState()])
102+
}
94103
guard app.hide() else {
95104
fail("hide", "The application refused hide", 2, [
96105
"pid": pid, "controllerPid": ProcessInfo.processInfo.processIdentifier,
97106
"sessionToken": sessionToken, "sequence": sequence, "returnValue": false,
107+
"controllerActiveBeforeHide": diagnosticActiveBeforeHide,
98108
"beforeAction": beforeAction, "applicationState": applicationState()
99109
])
100110
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Diagnostic-only prefix before the retained controller's argument parsing.
2+
// Audit every owned bundle launch, including an extra LaunchServices instance
3+
// that exits immediately because it did not receive the original PID argument.
4+
let diagnosticControllerBundle = Bundle.main.bundleURL.standardizedFileURL
5+
let diagnosticControllerLaunchId = UUID().uuidString
6+
let diagnosticControllerLaunchDirectory = diagnosticControllerBundle.deletingLastPathComponent()
7+
guard diagnosticControllerBundle.pathExtension == "app",
8+
Bundle.main.bundleIdentifier == "org.otzaria.dispatchcontroller" else { exit(64) }
9+
let diagnosticControllerLaunch: [String: Any] = [
10+
"launchId": diagnosticControllerLaunchId,
11+
"pid": ProcessInfo.processInfo.processIdentifier,
12+
"bundleURL": diagnosticControllerBundle.path,
13+
"executable": Bundle.main.executableURL?.path ?? "unavailable",
14+
"arguments": CommandLine.arguments,
15+
"atMs": Date().timeIntervalSince1970 * 1000
16+
]
17+
do {
18+
let data = try JSONSerialization.data(withJSONObject: diagnosticControllerLaunch, options: [.sortedKeys])
19+
try data.write(to: diagnosticControllerLaunchDirectory.appendingPathComponent(
20+
"controller-launch-\(diagnosticControllerLaunchId).json"), options: .atomic)
21+
} catch {
22+
fputs("Could not record owned controller launch: \(error)\n", stderr)
23+
exit(65)
24+
}

‎tool/perf_probe/apple_plugin_activity/test_macos_controller.py‎

Lines changed: 65 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -289,6 +289,11 @@ def setUpClass(cls):
289289
result["controllerIsActive"] = controllerApplication.isActive
290290
result["controllerOwnsMenuBar"] = NSRunningApplication.current.ownsMenuBar
291291
result["controllerBundleIdentifier"] = Bundle.main.bundleIdentifier ?? "unavailable"
292+
result["controllerBundleURL"] = Bundle.main.bundleURL.path
293+
result["controllerExecutable"] = Bundle.main.executableURL?.path ?? "unavailable"
294+
#if BUNDLED_CONTROLLER
295+
result["controllerLaunchId"] = diagnosticControllerLaunchId
296+
#endif
292297
result["frontmostApplicationPid"] = NSWorkspace.shared.frontmostApplication?.processIdentifier ?? -1
293298
''')
294299
dispatch_source = cls.directory / "dispatch_controller.swift"
@@ -307,6 +312,27 @@ def setUpClass(cls):
307312
})
308313
runner.recorded_output(cls.directory, f"compile-{label}-controller",
309314
["xcrun", "swiftc", str(dispatch_source), *flags, "-o", str(executable)], 120)
315+
caller_bundle = cls.directory / "DispatchController.app"
316+
cls.opened_caller_helper = caller_bundle / "Contents/MacOS/DispatchController"
317+
cls.opened_caller_helper.parent.mkdir(parents=True)
318+
(caller_bundle / "Contents/Info.plist").write_bytes(plistlib.dumps({
319+
"CFBundleExecutable": "DispatchController", "CFBundleIdentifier": "org.otzaria.dispatchcontroller",
320+
"CFBundleName": "DispatchController", "CFBundlePackageType": "APPL",
321+
"LSMinimumSystemVersion": "11.0", "NSHighResolutionCapable": True,
322+
}))
323+
caller_source = cls.directory / "opened_caller_controller.swift"
324+
caller_code = dispatch.replace(imports, imports +
325+
(runner.HERE / "mac_controller_launch_diagnostic.swift").read_text(), 1)
326+
caller_source.write_text(caller_code)
327+
flags = ["-D", "ACTIVE_CONTROLLER", "-D", "BUNDLED_CONTROLLER"]
328+
runner.save(cls.directory / "opened-caller-variant.json", {
329+
"productionSHA256": hashlib.sha256(original.encode()).hexdigest(),
330+
"diagnosticSHA256": hashlib.sha256(caller_code.encode()).hexdigest(),
331+
"compilerFlags": flags, "bundleIdentifier": "org.otzaria.dispatchcontroller",
332+
"scope": "Owned async regular caller bundle, Popen then open after info; every launch audited; same target and unchanged hide/hidden gates",
333+
})
334+
runner.recorded_output(cls.directory, "compile-opened-caller-controller",
335+
["xcrun", "swiftc", str(caller_source), *flags, "-o", str(cls.opened_caller_helper)], 120)
310336
inspector_source = cls.directory / "owned_bundle_instances.swift"
311337
inspector_source.write_text('''import AppKit
312338
import Foundation
@@ -325,13 +351,13 @@ def setUpClass(cls):
325351
["xcrun", "swiftc", str(inspector_source), "-o", str(cls.bundle_inspector)], 120)
326352
cls.launch_count = 0
327353

328-
def owned_bundle_snapshot(self, label):
329-
bundle = self.executable.parents[2]
354+
def owned_bundle_snapshot(self, label, *, bundle=None, launch_prefix="fixture"):
355+
bundle = self.executable.parents[2] if bundle is None else bundle
330356
instances = json.loads(runner.recorded_output(self.directory, label,
331357
[str(self.bundle_inspector), str(bundle)], 10))
332358
return {"instances": instances,
333359
"launches": [json.loads(path.read_text())
334-
for path in sorted(self.directory.glob("fixture-launch-*.json"))]}
360+
for path in sorted(self.directory.glob(f"{launch_prefix}-launch-*.json"))]}
335361

336362
def wait_for_evidence(self, path, process):
337363
deadline = time.monotonic() + 15
@@ -405,11 +431,17 @@ def test_opened_bundle_with_dispatching_controller_is_an_independent_diagnostic(
405431
self.exercise_controller(self.dispatch_helper, "opened-bundle-dispatch-execution", initialized=True,
406432
asynchronous_dispatch=True, open_bundle=True)
407433

434+
def test_opened_dispatching_caller_is_an_independent_diagnostic(self):
435+
self.exercise_controller(self.opened_caller_helper, "opened-caller-dispatch-execution", initialized=True,
436+
asynchronous_dispatch=True, prepare_foreground=True, open_caller=True)
437+
408438
def exercise_controller(self, helper, label, initialized=False, prepare_foreground=False, hide_timeout=10,
409-
asynchronous_dispatch=False, open_bundle=False):
439+
asynchronous_dispatch=False, open_bundle=False, open_caller=False):
410440
with native_result(self.directory, label,
411-
launchMethod=("Popen, ready, then open of the same bundle, matching Flutter profile onAttached"
412-
if open_bundle else "Popen of the executable; no open/LaunchServices launch"),
441+
targetLaunchMethod=("Popen, ready, then open of the same target bundle, matching Flutter profile onAttached"
442+
if open_bundle else "Popen of the target executable"),
443+
controllerLaunchMethod=("Popen, info, then open of the same owned caller bundle"
444+
if open_caller else "Popen of the controller executable"),
413445
diagnosticInitialization=initialized) as report:
414446
app, report["startup"], _ = self.start_owned_app()
415447
controller = runner.MacApplicationSession(helper, app.pid, self.directory, label)
@@ -438,6 +470,27 @@ def exercise_controller(self, helper, label, initialized=False, prepare_foregrou
438470
self.assertTrue(after["isActive"])
439471
if initialized:
440472
self.assertTrue(after["applicationState"]["controllerAppKitInitialized"])
473+
if open_caller:
474+
self.assertIsNone(controller.process.poll(), "The owned caller exited before open")
475+
state = after["applicationState"]
476+
self.assertEqual(state["controllerBundleIdentifier"], "org.otzaria.dispatchcontroller")
477+
self.assertEqual(state["controllerBundleURL"], str(helper.parents[2]))
478+
self.assertEqual(state["controllerExecutable"], str(helper))
479+
snapshot = report["callerBeforeOpen"] = self.owned_bundle_snapshot(f"{label}-caller-before-open",
480+
bundle=helper.parents[2], launch_prefix="controller")
481+
expected_caller = {"pid": controller.process.pid, "executable": str(helper),
482+
"bundle": str(helper.parents[2]), "launch_id": state["controllerLaunchId"],
483+
"initial_launches": snapshot["launches"]}
484+
verify_open_target(snapshot, **expected_caller)
485+
report["callerOpenCommandEvidence"] = f"{label}-caller-open.json"
486+
runner.recorded_output(self.directory, f"{label}-caller-open", ["open", expected_caller["bundle"]], 10)
487+
self.assertIsNone(controller.process.poll(), "open replaced or terminated the owned caller")
488+
snapshot = report["callerAfterOpen"] = self.owned_bundle_snapshot(f"{label}-caller-after-open",
489+
bundle=helper.parents[2], launch_prefix="controller")
490+
verify_open_target(snapshot, **expected_caller)
491+
caller_after = report["afterCallerOpen"] = controller.request("info")
492+
extra_observations.append(caller_after)
493+
self.assertEqual(caller_after["applicationState"]["controllerLaunchId"], state["controllerLaunchId"])
441494
hidden = report["hidden"] = controller.request("hide", timeout=hide_timeout)
442495
resumed = report["resumed"] = controller.request("activate")
443496
for value in [*extra_observations, before, after, hidden, resumed]:
@@ -457,6 +510,12 @@ def exercise_controller(self, helper, label, initialized=False, prepare_foregrou
457510
self.assertTrue(hidden["isHidden"])
458511
self.assertFalse(resumed["isHidden"])
459512
self.assertTrue(resumed["isActive"])
513+
if open_caller:
514+
self.assertTrue(hidden["controllerActiveBeforeHide"], "The caller must be active before requesting hide")
515+
self.assertIsNone(controller.process.poll(), "The original caller did not survive hide/resume")
516+
snapshot = report["callerAfterResume"] = self.owned_bundle_snapshot(f"{label}-caller-after-resume",
517+
bundle=helper.parents[2], launch_prefix="controller")
518+
verify_open_target(snapshot, **expected_caller)
460519
if open_bundle:
461520
self.assertIsNone(app.poll(), "The original Popen process did not survive hide/resume")
462521
snapshot = report["bundleAfterResume"] = self.owned_bundle_snapshot(f"{label}-after-resume")

0 commit comments

Comments
 (0)