@ethlete/agent-rules 0.1.0-next.57 → 0.1.0-next.59

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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,33 @@
1
1
  # @ethlete/agent-rules
2
2
 
3
+ ## 0.1.0-next.59
4
+
5
+ ### Minor Changes
6
+
7
+ - Add an opt-in Apple device verification skill that opens any reachable URL in iOS Simulator Safari, captures screenshots, and tests gestures without requiring Storybook.
8
+
9
+ ### Patch Changes
10
+
11
+ - Use Up and Down to switch between Codex runs in the pane and Escape to close it.
12
+ - The iOS Simulator skill targets its own device by UDID, never `booted`, and waits for SpringBoard and retries a timed-out `openurl` once.
13
+ - sim-keyboard and sim-keyboard-reset no longer kill Simulator.app while another device is booted.
14
+ - The iOS Simulator skill detects a booted SpringBoard on iOS 18 and opens Simulator.app on the requested device only.
15
+ - `sim-open` closes the Safari first-run tip popover of a fresh simulator, and `sim-shot` fails while a tip popover is open.
16
+ - Boot the Simulator device before Simulator.app opens it so no "Unable to boot device" dialog appears, and let `sim-shot` wait until Safari runs.
17
+ - Pick the Xcode and iOS runtime of the Simulator skill with SIM_DEVELOPER_DIR and SIM_RUNTIME; a missing device on that runtime is created.
18
+ - `sim-swipe edge-back` now triggers Safari’s left-edge back gesture in the iOS 26.3 simulator.
19
+ - sim-shot waits until Safari has finished loading (SIM_LOAD_TIMEOUT, default 30 s) and says so when it gives up.
20
+
21
+ ## 0.1.0-next.58
22
+
23
+ ### Minor Changes
24
+
25
+ - `agent-sessions pane <name>` reports whether a session is busy, holds a typed draft, or shows only a CLI suggestion.
26
+
27
+ ### Patch Changes
28
+
29
+ - `agent-sessions restart` no longer waits on an idle session whose background agent row reads "Waiting for ...".
30
+
3
31
  ## 0.1.0-next.57
4
32
 
5
33
  ### Patch Changes
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "codex-runs",
3
- "version": "0.1.0-next.57",
3
+ "version": "0.1.0-next.59",
4
4
  "description": "Codex sessions in tmux with their state, duration, and recent output",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -15,6 +15,7 @@ import {
15
15
  } from './agent-runs';
16
16
  import type { AgentRun, Trace } from './agent-runs';
17
17
  import { discoverRuns, durationOf } from './progress';
18
+ import type { CodexRun } from './progress';
18
19
 
19
20
  const PANE = 'codex-runs';
20
21
  const POLL_MS = 3000;
@@ -140,6 +141,11 @@ async function runsForSession($: EngineInterface) {
140
141
  return shown.filter((run) => !run.owner || run.owner === sessionId);
141
142
  }
142
143
 
144
+ function selectedRunId({ id, agents, terminals }: { id: string | null; agents: AgentRun[]; terminals: CodexRun[] }) {
145
+ if (agents.some((run) => run.id === id) || terminals.some((run) => run.id === id)) return id;
146
+ return (agents.find((run) => run.state === 'running') ?? agents[0] ?? terminals[0])?.id ?? null;
147
+ }
148
+
143
149
  export const register: Register = (on) => {
144
150
  on('session.start', async ($, e, next) => {
145
151
  await $.command.register({
@@ -194,11 +200,27 @@ export const register: Register = (on) => {
194
200
  if (name && !run && !agentRun) return { text: `No visible Codex run named ${name}.` };
195
201
 
196
202
  await update($, selected, () => agentRun?.id ?? run?.id ?? null);
197
- await $.ui.open({ id: PANE, title: 'Codex' });
203
+ await $.ui.open({ id: PANE, title: 'Codex', focus: true, closeOnEscape: true });
198
204
  if (agentRun) return { text: `Showing the trace of the Codex run ${name}.` };
199
205
  return { text: run ? `Showing recent output for ${run.name}.` : 'Codex pane opened.' };
200
206
  });
201
207
 
208
+ on('ui.key', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
209
+ if ((e.key !== 'up' && e.key !== 'down') || e.ctrl || e.shift || e.meta) return next(e);
210
+
211
+ const [agents, terminals] = await Promise.all([read($, agentRuns), runsForSession($)]);
212
+ const visible = [...agents, ...terminals];
213
+ if (visible.length === 0) return next(e);
214
+
215
+ const step = e.key === 'up' ? -1 : 1;
216
+ await update($, selected, (id) => {
217
+ const activeId = selectedRunId({ id, agents, terminals });
218
+ const index = visible.findIndex((run) => run.id === activeId);
219
+ return visible[index + step]?.id ?? activeId;
220
+ });
221
+ return {};
222
+ });
223
+
202
224
  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
203
225
  const { Box, Text } = $.ui.resolve(e);
204
226
  const [shown, agents, selectedId, sessionId, now] = await Promise.all([
@@ -210,10 +232,9 @@ export const register: Register = (on) => {
210
232
  ]);
211
233
  if (shown.length === 0 && agents.length === 0) return <Text dimColor>No Codex runs found.</Text>;
212
234
 
213
- const run = shown.find((run) => run.id === selectedId);
214
- const traced =
215
- agents.find((agent) => agent.id === selectedId) ??
216
- (run ? undefined : (agents.find((agent) => agent.state === 'running') ?? agents[0]));
235
+ const activeId = selectedRunId({ id: selectedId, agents, terminals: shown });
236
+ const run = shown.find((run) => run.id === activeId);
237
+ const traced = agents.find((agent) => agent.id === activeId);
217
238
  return (
218
239
  <Box flexDirection="column">
219
240
  {agents.map((agent) => (
@@ -224,7 +245,7 @@ export const register: Register = (on) => {
224
245
  </Text>
225
246
  ))}
226
247
  {shown.map((run) => (
227
- <Text key={run.id} wrap="truncate-end">
248
+ <Text key={run.id} wrap="truncate-end" bold={run.id === activeId}>
228
249
  {run.name} · {run.state} · {durationOf(run, now)}
229
250
  </Text>
230
251
  ))}
@@ -0,0 +1,21 @@
1
+ import { expect, test } from 'claude-code/testing';
2
+
3
+ const pane = 'codex-runs';
4
+ const command = {
5
+ command: pane,
6
+ args: '',
7
+ origin: { kind: 'composer' },
8
+ presentation: { isFullscreen: false, columns: 100 },
9
+ } as const;
10
+
11
+ test('opens the Codex pane with keyboard focus and Escape dismissal', async ($, on) => {
12
+ const opened: unknown[] = [];
13
+ on('ui.open', { id: pane }, (_$, event) => {
14
+ opened.push(event);
15
+ return { value: { isPlaced: true } };
16
+ });
17
+
18
+ await $.command.run(command);
19
+ expect(opened).toHaveLength(1);
20
+ expect(opened[0]).toMatchObject({ focus: true, closeOnEscape: true });
21
+ });
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "e2e-progress",
3
- "version": "0.1.0-next.57",
3
+ "version": "0.1.0-next.59",
4
4
  "description": "Live Playwright e2e progress from a run log, as a status line entry and a pane",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "status-line",
3
- "version": "0.1.0-next.57",
3
+ "version": "0.1.0-next.59",
4
4
  "description": "Always-visible band with the running task, its duration, the open queue, open questions and a CI blocked mark",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "usage-line",
3
- "version": "0.1.0-next.57",
3
+ "version": "0.1.0-next.59",
4
4
  "description": "Status line entry with the 5 hour and weekly usage, the reset time of the 5 hour window and the Codex limit",
5
5
  "types": "./types/index.d.ts"
6
6
  }
@@ -78,6 +78,7 @@ If the prompt of the agent holds typed text, the dispatcher waits until that tex
78
78
 
79
79
  - `inbox` keeps one cursor per sender name, so it never repeats a message. The first call shows the last 20.
80
80
  - `read` shows the last 20 messages. Use `--all` for the full history.
81
+ - `pane <name>` prints the state of a session's input box: `busy: <reason>`, `draft: <typed text>`, or `empty`, with the grey CLI suggestion if one shows. Use it instead of `tmux capture-pane`: a suggestion is not typed text.
81
82
  - `send` with no message reads it from standard input, so a long message needs no shell quoting.
82
83
  - `watch` is optional. It runs until you stop it. In Claude Code, start it with the `Monitor` tool, so a new message wakes the session. Without such a feature, rely on `inbox`.
83
84
  - Never rewrite or truncate the file. Only the script appends to it.
@@ -557,10 +557,11 @@ const BACKGROUND_FOOTER = /\b\d+ (?:shells?|agents?)\b/i;
557
557
  */
558
558
  const SGR = `${String.fromCharCode(27)}\\[([0-9;]*)m`;
559
559
  const BUSY_TEXT = /esc to interrupt|Waiting for/i;
560
- const isTranscript = (line) => /^\s*[●⎿]/.test(line);
560
+ const isTranscript = (line) => /^\s*[●⎿◯]/.test(line);
561
561
  /**
562
562
  * The line that shows a running turn: the spinner line right above the input box, or a footer line below it.
563
- * A transcript line (`●`, `⎿`) never counts, since an agent can end its turn with its own "Waiting for ..." text.
563
+ * A transcript line (`●`, `⎿`) or a background agent row (`◯`) never counts, since its own text can read
564
+ * "Waiting for ...".
564
565
  */
565
566
  const busyLineOf = (lines) => {
566
567
  const bottom = lastRuleIndex(lines);
@@ -743,6 +744,20 @@ const leavePanel = (session) => {
743
744
  return false;
744
745
  };
745
746
  const hasDraft = (session) => draftLine(session) !== null;
747
+ const promptText = (lines) =>
748
+ lines
749
+ .join('\n')
750
+ .replace(/^\s*[❯›]/, '')
751
+ .replace(IDE_CHIP, '')
752
+ .trim();
753
+ const paneStateOf = (session) => {
754
+ const busy = busyLine(session);
755
+ if (busy !== null) return `busy: ${busy.trim()}`;
756
+ const draft = draftLine(session);
757
+ if (draft !== null) return `draft: ${draft}`;
758
+ const suggestion = promptText(promptLines(paneLines(session)).map(plain));
759
+ return suggestion ? `empty; CLI suggestion, not typed: ${suggestion}` : 'empty';
760
+ };
746
761
  const isAttached = (name) => tmux('list-clients', '-t', `=${name}`).stdout.trim() !== '';
747
762
  const freeSessionFor = (agent) => {
748
763
  for (let number = 1; ; number++) {
@@ -1374,6 +1389,13 @@ if (command === 'stop-own') {
1374
1389
  };
1375
1390
  process.stdout.write(`Dispatching for ${resolve(mailbox)}\n`);
1376
1391
  setInterval(poll, 1000);
1392
+ } else if (command === 'pane' && sender) {
1393
+ const session = localSessionFor(sender) ?? (sessionExists(sender) ? sender : null);
1394
+ if (session) process.stdout.write(`${paneStateOf(session)}\n`);
1395
+ else {
1396
+ process.stderr.write(`No tmux session for ${sender}.\n`);
1397
+ process.exitCode = 1;
1398
+ }
1377
1399
  } else if (command === 'inbox' && sender) {
1378
1400
  showInbox(sender, Number(waitSeconds ?? 0));
1379
1401
  } else if (command === 'read') {
@@ -0,0 +1,100 @@
1
+ ---
2
+ name: verify-on-apple-devices
3
+ description: Drive a Mac's iOS Simulator over SSH to verify any reachable URL in Mobile Safari. Also supports WebDriver checks on a paired iPad.
4
+ kind: skill
5
+ scope: both
6
+ modelInvocation: false
7
+ ---
8
+
9
+ # Verify a URL on Apple devices
10
+
11
+ After syncing agent-rules, invoke `/ethlete-verify-on-apple-devices` when you need to verify behavior in iOS Safari.
12
+ Run {%resource:apple-remote.sh%} with Bash. In the examples below, `<skill-dir>` is the directory containing this file.
13
+
14
+ ```bash
15
+ bash <skill-dir>/apple-remote.sh detect
16
+ bash <skill-dir>/apple-remote.sh sim-open https://example.com
17
+ bash <skill-dir>/apple-remote.sh sim-shot safari.png
18
+ ```
19
+
20
+ ## Setup
21
+
22
+ - Enable Remote Login on the Mac and authorize your SSH key for non-interactive login.
23
+ The script uses the SSH host alias `ethlete-mac` by default. Set `ETHLETE_MAC_HOST` to use another alias or hostname.
24
+ - Install Xcode and an iOS Simulator runtime on the Mac. The default simulator is `iPhone 16`.
25
+ Pass a different device name as the second argument to `sim-open` if needed.
26
+ - The Mac and simulator must be able to reach the page. For a local app, bind the dev server to
27
+ `0.0.0.0` and use the dev machine's LAN address and port, for example `http://192.168.1.20:4200/`.
28
+ You can also use a staging URL reachable from the Mac. `localhost` in Simulator Safari refers
29
+ to the Mac. The simulator commands open the supplied URL directly.
30
+ - For taps, coordinate swipes and typing, install idb on the Mac. Run
31
+ `brew trust facebook/fb && brew install idb-companion` and install the Python CLI with
32
+ `pip3 install --user fb-idb`. The script expects the CLI under `~/Library/Python/*/bin/idb`.
33
+ - For WebDriver commands, run `safaridriver --enable` on the Mac. For a real iPad, pair it with the Mac
34
+ over USB and enable Web Inspector and Remote Automation under Settings → Apps → Safari → Advanced.
35
+
36
+ Use Xcode 26 with an iOS 26 runtime to verify Safari 26 behavior such as toolbar tinting.
37
+ Pick the Xcode and the runtime per call with `SIM_DEVELOPER_DIR` (the Xcode's `Contents/Developer` path, passed
38
+ to every remote `xcrun`, `simctl` and `open`) and `SIM_RUNTIME` (for example `iOS-26-3`). When the runtime has no
39
+ device of the requested name, `sim-open` creates one. Without them the Mac's selected Xcode and the newest runtime
40
+ are used. Never switch the Mac's Xcode with `xcode-select -s`. Record the runtime used in the verification report.
41
+ [Apple's Xcode simulator requirements](https://developer.apple.com/xcode/system-requirements)
42
+ and [WebKit issue 301756](https://bugs.webkit.org/show_bug.cgi?id=301756) cover the version requirements and tinting behavior.
43
+
44
+ ## Simulator commands
45
+
46
+ | Command | Behavior |
47
+ | ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | `detect` | Check SSH, available iPhone simulators and paired Apple devices. |
49
+ | `sim-open <url> [device]` | Boot the requested device if needed and open the URL in Safari. Quote URLs containing shell characters. |
50
+ | `sim-shot [file]` | Capture the full display, including Safari chrome and the keyboard. Defaults to `sim.png` in the working directory. Waits first until Safari stops loading (`SIM_LOAD_TIMEOUT`, default 30 s). |
51
+ | `sim-swipe edge-back` | Send a left-edge touch gesture in portrait. Visit two pages in the same Safari tab before testing back navigation. |
52
+ | `sim-swipe <x1> <y1> <x2> <y2> [duration]` | Swipe using device points. Duration is in seconds and defaults to 0.3. |
53
+ | `sim-tap <x> <y>` | Tap at device coordinates. Divide screenshot pixels by the display scale, typically 3 on iPhone 16. |
54
+ | `sim-type <text>` | Type into a focused field via idb. iOS autocorrect and capitalization apply. |
55
+ | `sim-keyboard on\|off [device]` | Detach or attach the hardware keyboard preference. Reopen the page afterward. |
56
+ | `sim-keyboard-reset [device]` | Restart Simulator.app and boot the device to restore the soft keys after `sim-type`. |
57
+ | `sim-stop` | Shut down the device selected by `sim-open` or `sim-probe` at the end of the session. |
58
+
59
+ A cold boot can take about a minute. If a command stalls, check the exact SSH or
60
+ Simulator error and whether Simulator.app is running. Simulator.app provides the UI that
61
+ `sim-shot` captures. Keep the device booted between verification rounds.
62
+
63
+ `sim-swipe edge-back` compiles {%resource:sim-edge-back.m%} with the selected Xcode on the Mac.
64
+ The helper sends an edge-tagged SimulatorKit touch directly to the selected device, so the Simulator
65
+ window can stay in the background. Verified with Xcode 26.3 and iOS 26.3. When running parallel sessions,
66
+ use a separate simulator and a separate existing `TMPDIR` on the machine running the script for each session.
67
+
68
+ ## Optional Storybook commands
69
+
70
+ Run `detect --storybook [url]` to also probe Storybook from the Mac. With no URL, the default is
71
+ the dev machine's LAN IP on port 4400. Set `ETHLETE_STORYBOOK_URL` to use a different reachable
72
+ Storybook base URL and include that probe whenever you run `detect`. Plain `detect` skips the
73
+ probe when the variable is unset.
74
+
75
+ `sim-open <story-id>` and `ipad-open <story-id>` still open the Storybook iframe.
76
+ `sim-probe <story-id> [device]` opens the viewport HUD when the Storybook instance serves
77
+ `/assets/viewport-probe.html`. Use `sim-tap` and `sim-shot` to read live viewport metrics
78
+ while the keyboard is open. The HUD disables focus zoom, so open the page directly to
79
+ check zoom on small inputs.
80
+
81
+ ## WebDriver commands
82
+
83
+ | Command | Behavior |
84
+ | --------------------------- | ----------------------------------------------------------------------------------------- |
85
+ | `ipad-start [sim]` | Start Safari WebDriver on the paired iPad or, with `sim`, on an already booted simulator. |
86
+ | `ipad-open <url>` | Navigate the session to a reachable URL. |
87
+ | `ipad-js <script>` | Run JavaScript in the page. Use `return` to read a value. |
88
+ | `ipad-viewport` | Read viewport units, safe-area insets, visual viewport and estimated keyboard state. |
89
+ | `ipad-tap <css>` | Click an element through WebDriver. |
90
+ | `ipad-type <css> <text>` | Call WebDriver send-keys. Safari on iOS may leave the field empty. |
91
+ | `ipad-shot <out.png> [css]` | Capture an element, defaulting to `html`. |
92
+ | `ipad-end` | End the session and close the WebDriver tunnel. |
93
+
94
+ `ipad-start` opens a blank Safari page. Follow it with `ipad-open`. Safari chrome turns
95
+ orange while WebDriver is active. End the session before using idb taps or swipes since
96
+ real input interrupts active automation. If Safari reports that it is already paired
97
+ with another WebDriver session, try `ipad-open` with the stored session first.
98
+
99
+ When reporting a result, include the device, iOS version, URL, interaction and observed
100
+ behavior. Save the screenshot alongside the report.
@@ -0,0 +1,421 @@
1
+ #!/usr/bin/env bash
2
+ # Drive the team Mac's iOS Simulator and the real iPad from a Linux PC over LAN.
3
+ # See SKILL.md in this directory for setup, gotchas, and usage examples.
4
+ # SIM_DEVELOPER_DIR picks the Xcode, SIM_RUNTIME the iOS runtime (e.g. iOS-26-3) for every simulator call.
5
+ set -euo pipefail
6
+
7
+ MAC_HOST=${ETHLETE_MAC_HOST:-ethlete-mac}
8
+ STORYBOOK_URL=${ETHLETE_STORYBOOK_URL:-}
9
+ DRIVER_PORT=${ETHLETE_SAFARIDRIVER_PORT:-4444}
10
+ STATE_DIR=${TMPDIR:-/tmp}/ethlete-apple-remote
11
+ SID_FILE=$STATE_DIR/ipad-session-id
12
+
13
+ SIM_DEVELOPER_DIR=${SIM_DEVELOPER_DIR:-}
14
+ SIM_RUNTIME=${SIM_RUNTIME:-}
15
+ [[ -z $SIM_RUNTIME || $SIM_RUNTIME == com.apple.CoreSimulator.SimRuntime.* ]] || SIM_RUNTIME=com.apple.CoreSimulator.SimRuntime.$SIM_RUNTIME
16
+
17
+ mac() {
18
+ local prefix=
19
+ [[ -z $SIM_DEVELOPER_DIR ]] || prefix="export DEVELOPER_DIR=$(remote_arg "$SIM_DEVELOPER_DIR"); "
20
+ ssh -T -o BatchMode=yes -o ConnectTimeout=8 "$MAC_HOST" "$prefix$*"
21
+ }
22
+
23
+ remote_arg() { printf "'%s'" "${1//\'/\'\\\'\'}"; }
24
+
25
+ usage_error() { printf 'Usage: apple-remote.sh %s\n' "$1" >&2; exit 2; }
26
+
27
+ pc_ip() {
28
+ local mac_ip
29
+ mac_ip=$(ssh -G "$MAC_HOST" | awk '/^hostname /{print $2}')
30
+ ip route get "$mac_ip" | grep -oP 'src \K\S+'
31
+ }
32
+
33
+ storybook_base() {
34
+ local lan_ip
35
+ if [[ -n $STORYBOOK_URL ]]; then
36
+ printf '%s\n' "${STORYBOOK_URL%/}"
37
+ else
38
+ lan_ip=$(pc_ip) || return
39
+ printf 'http://%s:4400\n' "$lan_ip"
40
+ fi
41
+ }
42
+
43
+ page_url() {
44
+ local base
45
+ if [[ $1 =~ ^[a-zA-Z][a-zA-Z0-9+.-]*: ]]; then
46
+ printf '%s\n' "$1"
47
+ else
48
+ base=$(storybook_base) || return
49
+ printf '%s/iframe.html?id=%s&viewMode=story\n' "$base" "$1"
50
+ fi
51
+ }
52
+
53
+ wd() {
54
+ curl -s -X "$1" "http://localhost:$DRIVER_PORT$2" \
55
+ ${3:+-H "Content-Type: application/json" -d "$3"}
56
+ }
57
+
58
+ sid() { cat "$SID_FILE"; }
59
+
60
+ SIM_UDID_FILE=$STATE_DIR/sim-udid
61
+
62
+ sim_udid() {
63
+ mac 'xcrun simctl list devices available -j' | python3 -I -c '
64
+ import json, re, sys
65
+ name, wanted = sys.argv[1], sys.argv[2]
66
+ best = None
67
+ for runtime, devices in json.load(sys.stdin)["devices"].items():
68
+ if wanted and runtime != wanted:
69
+ continue
70
+ match = re.search(r"\.iOS-(\d+(?:-\d+)*)$", runtime)
71
+ if not match:
72
+ continue
73
+ version = tuple(int(part) for part in match.group(1).split("-"))
74
+ for device in devices:
75
+ if device["name"] == name and device.get("isAvailable", True) and (best is None or version > best[0]):
76
+ best = (version, device["udid"])
77
+ if best:
78
+ print(best[1])
79
+ ' "$1" "$SIM_RUNTIME"
80
+ }
81
+
82
+ sim_create() {
83
+ local type_id
84
+ type_id=$(mac 'xcrun simctl list devicetypes -j' | python3 -I -c '
85
+ import json, sys
86
+ for t in json.load(sys.stdin)["devicetypes"]:
87
+ if t["name"] == sys.argv[1]:
88
+ print(t["identifier"])
89
+ break
90
+ ' "$1")
91
+ [[ -n $type_id ]] || { echo "no device type named '$1'" >&2; return 1; }
92
+ echo "no '$1' on $SIM_RUNTIME: creating one" >&2
93
+ mac "xcrun simctl create $(remote_arg "$1") $type_id $SIM_RUNTIME"
94
+ }
95
+
96
+ sim_target() {
97
+ [[ -s $SIM_UDID_FILE ]] || { echo 'no simulator booted by this script: run sim-open or sim-probe first' >&2; return 1; }
98
+ cat "$SIM_UDID_FILE"
99
+ }
100
+
101
+ sim_edge_back() {
102
+ local udid skill_dir
103
+ udid=$(sim_target) || return
104
+ skill_dir=$(dirname -- "${BASH_SOURCE[0]}")
105
+ mac "set -e
106
+ work=\$(mktemp -d)
107
+ trap 'rm -rf -- \"\$work\"' EXIT
108
+ xcrun clang -x objective-c -fobjc-arc -framework AppKit -o \"\$work/edge-back\" -
109
+ \"\$work/edge-back\" $(remote_arg "$udid") \"\${DEVELOPER_DIR:-\$(xcode-select -p)}\"" < "$skill_dir/sim-edge-back.m"
110
+ }
111
+
112
+ sim_boot() {
113
+ # simctl alone boots headless (black framebuffer, blank keyboard area, no window on
114
+ # the Mac) and openurl right after bootstatus times out - SpringBoard isn't up yet.
115
+ # Only the UDID of the requested device is ever passed to simctl: other agents' simulators stay untouched.
116
+ local udid
117
+ udid=$(sim_udid "$1")
118
+ if [[ -z $udid && -n $SIM_RUNTIME ]]; then
119
+ udid=$(sim_create "$1") || return 1
120
+ fi
121
+ [[ -n $udid ]] || { echo "no available device named '$1'" >&2; return 1; }
122
+ mkdir -p "$STATE_DIR"
123
+ printf '%s\n' "$udid" > "$SIM_UDID_FILE"
124
+ if mac "xcrun simctl list devices booted | grep -qF $udid && pgrep -xq Simulator"; then
125
+ return 0
126
+ elif [[ $? == 255 ]]; then
127
+ return 255
128
+ fi
129
+ echo "booting $1 ($udid; cold boot can take ~60s; anything past that is an error, not patience)..." >&2
130
+ mac "xcrun simctl boot $udid 2>/dev/null || true; open -g \"\$(xcode-select -p)/Applications/Simulator.app\" --args -CurrentDeviceUDID $udid; xcrun simctl bootstatus $udid" >/dev/null
131
+ mac "for i in \$(seq 1 20); do
132
+ xcrun simctl spawn $udid launchctl list 2>/dev/null | grep -q com.apple.SpringBoard && exit 0
133
+ sleep 3
134
+ done
135
+ echo 'SpringBoard did not come up within 60s' >&2; exit 1"
136
+ }
137
+
138
+ sim_restart_app() {
139
+ local others
140
+ others=$(mac "xcrun simctl list devices booted | grep -oE '[0-9A-F]{8}(-[0-9A-F]{4}){3}-[0-9A-F]{12}' | grep -vF $1 || true")
141
+ if [[ -n $others ]]; then
142
+ echo "not restarting Simulator.app: other devices are booted ($(echo $others)); only $1 was shut down" >&2
143
+ return 0
144
+ fi
145
+ mac 'killall Simulator 2>/dev/null || true'
146
+ }
147
+
148
+ sim_openurl() {
149
+ local udid cmd
150
+ udid=$(sim_target)
151
+ cmd="xcrun simctl openurl $udid $(remote_arg "$1")"
152
+ mac "$cmd" && return 0
153
+ echo 'openurl failed, retrying once...' >&2
154
+ sleep 2
155
+ mac "$cmd"
156
+ }
157
+
158
+ sim_wait_loaded() {
159
+ local udid limit
160
+ udid=$(sim_target)
161
+ limit=${SIM_LOAD_TIMEOUT:-30}
162
+ mac "export PATH=/usr/local/bin:\$PATH; idle=0
163
+ for i in \$(seq 1 $limit); do
164
+ xcrun simctl spawn $udid launchctl list 2>/dev/null | grep -q com.apple.mobilesafari && break
165
+ sleep 1
166
+ done
167
+ for i in \$(seq 1 $limit); do
168
+ if ~/Library/Python/*/bin/idb ui describe-all --udid $udid --json 2>/dev/null | grep -q StopButton; then idle=0; else idle=\$((idle + 1)); fi
169
+ (( idle >= 2 )) && exit 0
170
+ sleep 1
171
+ done
172
+ exit 3" && return 0
173
+ echo "page still loading after ${limit}s (Safari StopButton present): shot may be partial; raise SIM_LOAD_TIMEOUT" >&2
174
+ }
175
+
176
+ sim_tip_present() {
177
+ mac "export PATH=/usr/local/bin:\$PATH; ~/Library/Python/*/bin/idb ui describe-all --udid $(sim_target) --json 2>/dev/null | grep -q PopoverDismissRegion"
178
+ }
179
+
180
+ sim_dismiss_tips() {
181
+ local udid i
182
+ udid=$(sim_target)
183
+ for i in $(seq 0 "${SIM_TIP_WAIT:-5}"); do
184
+ if sim_tip_present; then
185
+ mac "export PATH=/usr/local/bin:\$PATH; idb=\$(echo ~/Library/Python/*/bin/idb)
186
+ set -- \$(\$idb ui describe-all --udid $udid --json | python3 -c \"import json,sys; d=json.load(sys.stdin); print(*next(([int(e['frame']['x']+e['frame']['width']/2), int(e['frame']['y']+e['frame']['height']/2)] for e in d if e.get('AXUniqueId')=='xmark.circle.fill'), []))\")
187
+ [ -n \"\$1\" ] && \$idb ui tap \$1 \$2 --udid $udid"
188
+ sleep 1
189
+ sim_tip_present && echo 'a Safari tip popover is still open after one tap on its close button' >&2
190
+ return 0
191
+ fi
192
+ sleep 1
193
+ done
194
+ }
195
+
196
+ find_el() {
197
+ local body
198
+ body=$(python3 -c 'import json,sys; print(json.dumps({"using": "css selector", "value": sys.argv[1]}))' "$1")
199
+ wd POST "/session/$(sid)/element" "$body" \
200
+ | python3 -c "import json,sys; v=json.load(sys.stdin)['value']; assert isinstance(v,dict) and 'error' not in v, v; print(list(v.values())[0])"
201
+ }
202
+
203
+ VIEWPORT_PROBE='return (() => {
204
+ const p = document.createElement("div");
205
+ p.style.cssText = "position:fixed;top:0;width:0;";
206
+ document.body.appendChild(p);
207
+ const h = (v) => { p.style.height = v; return p.getBoundingClientRect().height; };
208
+ const sizes = { vh: h("100vh"), dvh: h("100dvh"), svh: h("100svh"), lvh: h("100lvh") };
209
+ p.style.cssText = "padding:env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left)";
210
+ const cs = getComputedStyle(p);
211
+ const safeArea = { top: cs.paddingTop, right: cs.paddingRight, bottom: cs.paddingBottom, left: cs.paddingLeft };
212
+ p.remove();
213
+ const vv = window.visualViewport;
214
+ return { innerWidth, innerHeight, ...sizes, safeArea,
215
+ visualViewport: vv ? { width: vv.width, height: vv.height, offsetTop: vv.offsetTop, scale: vv.scale } : null,
216
+ keyboardLikelyOpen: vv ? innerHeight - vv.height > 100 : null,
217
+ activeElement: document.activeElement?.tagName };
218
+ })()'
219
+
220
+ case ${1:-help} in
221
+ detect) # [--storybook [url]] — check Mac and Apple devices, with an optional Storybook probe
222
+ case ${2:-} in
223
+ --storybook)
224
+ (( $# <= 3 )) || usage_error 'detect [--storybook [url]]'
225
+ STORYBOOK_URL=${3:-$STORYBOOK_URL}
226
+ ;;
227
+ '') ;;
228
+ *) usage_error 'detect [--storybook [url]]' ;;
229
+ esac
230
+ mac 'echo "mac: $(hostname) ($(sw_vers -productVersion))"'
231
+ mac 'xcrun simctl list devices available | grep -ci iphone | sed "s/^/iphone sims: /"'
232
+ mac 'xcrun devicectl list devices 2>/dev/null | tail -n +3 | sed "s/^/device: /"' || true
233
+ if [[ ${2:-} == --storybook || -n $STORYBOOK_URL ]]; then
234
+ if URL=$(storybook_base) &&
235
+ STATUS=$(mac "curl -s --max-time 8 -o /dev/null -w '%{http_code}' -- $(remote_arg "$URL/")"); then
236
+ printf 'storybook from mac: %s\n' "$STATUS"
237
+ else
238
+ echo 'storybook from mac: unreachable'
239
+ fi
240
+ fi
241
+ ;;
242
+
243
+ sim-open) # <url-or-story-id> [device-name] — open a page in the simulator
244
+ [[ -n ${2:-} && $# -le 3 ]] || usage_error 'sim-open <url-or-story-id> [device-name]'
245
+ URL=$(page_url "$2")
246
+ sim_boot "${3:-iPhone 16}"
247
+ sim_openurl "$URL"
248
+ sim_wait_loaded
249
+ sim_dismiss_tips
250
+ echo "opened on simulator: $URL"
251
+ ;;
252
+
253
+ sim-probe) # <story-id> [device-name] — open story wrapped in the live viewport HUD (assets/viewport-probe.html);
254
+ # use with sim-tap/sim-type, read metrics off sim-shot (works without a WebDriver session)
255
+ URL="$(storybook_base)/assets/viewport-probe.html?story=$2"
256
+ sim_boot "${3:-iPhone 16}"
257
+ sim_openurl "$URL"
258
+ sim_wait_loaded
259
+ sim_dismiss_tips
260
+ echo "opened probe: $URL"
261
+ ;;
262
+
263
+ sim-shot) # [out.png] — save a full-device screenshot
264
+ (( $# <= 2 )) || usage_error 'sim-shot [out.png]'
265
+ OUTPUT=${2:-sim.png}
266
+ sim_wait_loaded
267
+ if sim_tip_present; then
268
+ echo 'a Safari tip popover covers the page: the shot would hide the bottom bar. Close it with sim-tap on its close button and shoot again' >&2
269
+ exit 4
270
+ fi
271
+ TEMP_SHOT=$(mktemp -- "$OUTPUT.XXXXXX")
272
+ trap 'rm -f -- "$TEMP_SHOT"' EXIT
273
+ mac "xcrun simctl io $(sim_target) screenshot -" > "$TEMP_SHOT"
274
+ mv -f -- "$TEMP_SHOT" "$OUTPUT"
275
+ file -- "$OUTPUT"
276
+ ;;
277
+
278
+ sim-tap) # <x> <y> — real touch tap (device points); focusing an input opens the soft keyboard
279
+ UDID=$(sim_target)
280
+ mac "export PATH=/usr/local/bin:\$PATH; ~/Library/Python/*/bin/idb ui tap $2 $3 --udid $UDID 2>/dev/null"
281
+ ;;
282
+
283
+ sim-swipe) # edge-back | <x1> <y1> <x2> <y2> [duration-s] — real touch swipe in device points
284
+ if [[ $# == 2 && $2 == edge-back ]]; then
285
+ sim_edge_back
286
+ exit
287
+ fi
288
+ SWIPE_USAGE='sim-swipe edge-back | sim-swipe <x1> <y1> <x2> <y2> [duration-s]'
289
+ (( $# == 5 || $# == 6 )) || usage_error "$SWIPE_USAGE"
290
+ DURATION=${6:-0.3}
291
+ for POINT in "$2" "$3" "$4" "$5" "$DURATION"; do
292
+ [[ $POINT =~ ^-?([0-9]+([.][0-9]*)?|[.][0-9]+)$ ]] || usage_error "$SWIPE_USAGE"
293
+ done
294
+ UDID=$(sim_target)
295
+ mac "export PATH=/usr/local/bin:\$PATH; ~/Library/Python/*/bin/idb ui swipe --duration $DURATION $2 $3 $4 $5 --udid $UDID 2>/dev/null"
296
+ ;;
297
+
298
+ sim-type) # <text> — types on the open soft keyboard (tap a field first via sim-tap)
299
+ UDID=$(sim_target)
300
+ TEXT=$(printf %q "$2")
301
+ mac "export PATH=/usr/local/bin:\$PATH; ~/Library/Python/*/bin/idb ui text $TEXT --udid $UDID 2>/dev/null"
302
+ ;;
303
+
304
+ sim-keyboard-reset) # [device-name] — bring back soft-keyboard keys hidden by sim-type's HID keyboard events.
305
+ # `idb ui text` registers as a hardware keyboard; iOS then hides the keys (only the „Fertig"
306
+ # accessory bar shows). That state lives in the RUNNING Simulator.app process — it survives
307
+ # device reboots and pref writes, and dies only with the app. Restart it + reboot the device.
308
+ if [[ -s $SIM_UDID_FILE ]]; then
309
+ mac "xcrun simctl shutdown $(sim_target) 2>/dev/null || true"
310
+ sim_restart_app "$(sim_target)"
311
+ else
312
+ sim_restart_app none
313
+ fi
314
+ sim_boot "${2:-iPhone 16}"
315
+ echo "keyboard reset for ${2:-iPhone 16} — reopen your URL (sim-open/sim-probe) and tap a field"
316
+ ;;
317
+
318
+ sim-keyboard) # on|off [device-name] — detach the hardware keyboard so the soft keyboard shows (restarts sims)
319
+ # Modern Simulator reads the per-device DevicePreferences key, NOT the legacy global
320
+ # ConnectHardwareKeyboard — writing only the global one silently does nothing.
321
+ [ "$2" = on ] && V=false && D=0 || { V=true; D=1; }
322
+ DEVICE=${3:-iPhone 16}
323
+ UDID=$(sim_udid "$DEVICE")
324
+ [ -n "$UDID" ] || { echo "no available device named '$DEVICE'" >&2; exit 1; }
325
+ mac "defaults write com.apple.iphonesimulator ConnectHardwareKeyboard -bool $V; defaults write com.apple.iphonesimulator DevicePreferences -dict-add '$UDID' '{ConnectHardwareKeyboard = $D;}'; xcrun simctl shutdown $UDID 2>/dev/null || true"
326
+ sim_restart_app "$UDID"
327
+ echo "soft keyboard $2 for $DEVICE ($UDID); re-run sim-open / sim-probe"
328
+ ;;
329
+
330
+ sim-stop)
331
+ [[ ! -s $SIM_UDID_FILE ]] || mac "xcrun simctl shutdown $(sim_target) 2>/dev/null || true"
332
+ ;;
333
+
334
+ ipad-start) # [sim] — tunnel + safaridriver + session (against the real iPad, or the booted simulator with `sim`)
335
+ mkdir -p "$STATE_DIR"
336
+ if ! curl -sf "http://localhost:$DRIVER_PORT/status" >/dev/null 2>&1; then
337
+ mac 'pkill -x safaridriver 2>/dev/null || true' # stale driver from a dead tunnel
338
+ ssh -f -T -o BatchMode=yes -o ExitOnForwardFailure=yes \
339
+ -L "$DRIVER_PORT:localhost:$DRIVER_PORT" "$MAC_HOST" \
340
+ "/usr/bin/safaridriver --port $DRIVER_PORT"
341
+ for _ in $(seq 1 10); do
342
+ curl -sf "http://localhost:$DRIVER_PORT/status" >/dev/null 2>&1 && break
343
+ sleep 1
344
+ done
345
+ fi
346
+ CAPS='{"browserName":"safari","platformName":"ios"}'
347
+ [ "${2:-}" = sim ] && CAPS='{"browserName":"safari","platformName":"ios","safari:useSimulator":true}'
348
+ RESP=$(wd POST /session "{\"capabilities\":{\"alwaysMatch\":$CAPS}}")
349
+ SID=$(echo "$RESP" | python3 -c "import json,sys; print(json.load(sys.stdin)['value'].get('sessionId',''))" 2>/dev/null || true)
350
+ if [ -z "$SID" ] && echo "$RESP" | grep -q "already paired"; then
351
+ # stale pairing from a dead session: drop it and restart the driver, then retry once
352
+ [ -f "$SID_FILE" ] && wd DELETE "/session/$(sid)" >/dev/null 2>&1 && rm -f "$SID_FILE"
353
+ pkill -f "ssh.*-L $DRIVER_PORT:localhost:$DRIVER_PORT" 2>/dev/null || true
354
+ mac 'pkill -x safaridriver 2>/dev/null || true'
355
+ ssh -f -T -o BatchMode=yes -o ExitOnForwardFailure=yes \
356
+ -L "$DRIVER_PORT:localhost:$DRIVER_PORT" "$MAC_HOST" \
357
+ "/usr/bin/safaridriver --port $DRIVER_PORT"
358
+ for _ in $(seq 1 10); do
359
+ curl -sf "http://localhost:$DRIVER_PORT/status" >/dev/null 2>&1 && break
360
+ sleep 1
361
+ done
362
+ RESP=$(wd POST /session "{\"capabilities\":{\"alwaysMatch\":$CAPS}}")
363
+ SID=$(echo "$RESP" | python3 -c "import json,sys; print(json.load(sys.stdin)['value'].get('sessionId',''))" 2>/dev/null || true)
364
+ fi
365
+ if [ -z "$SID" ]; then echo "session failed: $RESP" >&2; exit 1; fi
366
+ echo "$SID" > "$SID_FILE"
367
+ echo "$RESP" | python3 -c "import json,sys; c=json.load(sys.stdin)['value']['capabilities']; print(c.get('safari:deviceName'), c.get('browserVersion'))"
368
+ echo "session: $SID"
369
+ ;;
370
+
371
+ ipad-open) # <story-id-or-url>
372
+ URL=$(page_url "$2")
373
+ BODY=$(python3 -c 'import json,sys; print(json.dumps({"url": sys.argv[1]}))' "$URL")
374
+ wd POST "/session/$(sid)/url" "$BODY" >/dev/null
375
+ echo "opened on iPad: $URL"
376
+ ;;
377
+
378
+ ipad-js) # <script> — sync script, `return` its result
379
+ SCRIPT=$(python3 -c 'import json,sys; print(json.dumps({"script": sys.argv[1], "args": []}))' "$2")
380
+ wd POST "/session/$(sid)/execute/sync" "$SCRIPT"
381
+ echo
382
+ ;;
383
+
384
+ ipad-viewport) # probe vh/dvh/svh/lvh, safe-area, visualViewport, keyboard state
385
+ SCRIPT=$(python3 -c 'import json,sys; print(json.dumps({"script": sys.argv[1], "args": []}))' "$VIEWPORT_PROBE")
386
+ wd POST "/session/$(sid)/execute/sync" "$SCRIPT" | python3 -m json.tool
387
+ ;;
388
+
389
+ ipad-type) # <css-selector> <text> — tap the field and type; opens the real soft keyboard
390
+ EID=$(find_el "$2")
391
+ wd POST "/session/$(sid)/element/$EID/click" '{}' >/dev/null
392
+ BODY=$(python3 -c 'import json,sys; print(json.dumps({"text": sys.argv[1]}))' "$3")
393
+ wd POST "/session/$(sid)/element/$EID/value" "$BODY"
394
+ echo
395
+ ;;
396
+
397
+ ipad-tap) # <css-selector>
398
+ EID=$(find_el "$2")
399
+ wd POST "/session/$(sid)/element/$EID/click" '{}'
400
+ echo
401
+ ;;
402
+
403
+ ipad-shot) # <out.png> [css-selector] — element screenshot (full-screen endpoint is broken on real devices)
404
+ EID=$(find_el "${3:-html}")
405
+ wd GET "/session/$(sid)/element/$EID/screenshot" \
406
+ | python3 -c "import json,sys,base64; open(sys.argv[1],'wb').write(base64.b64decode(json.load(sys.stdin)['value']))" "$2"
407
+ file "$2"
408
+ ;;
409
+
410
+ ipad-end)
411
+ [ -f "$SID_FILE" ] && wd DELETE "/session/$(sid)" >/dev/null && rm -f "$SID_FILE"
412
+ pkill -f "ssh.*-L $DRIVER_PORT:localhost:$DRIVER_PORT" 2>/dev/null || true
413
+ mac 'pkill -x safaridriver 2>/dev/null || true'
414
+ echo "session + tunnel closed"
415
+ ;;
416
+
417
+ *)
418
+ sed -n "s/^ \([a-z-]*\)) #\?/\1 /p" "$0"
419
+ echo "state: $STATE_DIR mac host: $MAC_HOST (override: ETHLETE_MAC_HOST)"
420
+ ;;
421
+ esac
@@ -0,0 +1,159 @@
1
+ #import <AppKit/AppKit.h>
2
+ #import <dlfcn.h>
3
+
4
+ @protocol SimDevice
5
+ - (NSUUID *)UDID;
6
+ - (NSUInteger)state;
7
+ @end
8
+
9
+ @protocol SimDeviceSet
10
+ - (NSArray<id<SimDevice>> *)devices;
11
+ @end
12
+
13
+ @protocol SimServiceContext
14
+ + (id<SimServiceContext>)sharedServiceContextForDeveloperDir:(NSString *)directory error:(NSError **)error;
15
+ - (id<SimDeviceSet>)defaultDeviceSetWithError:(NSError **)error;
16
+ @end
17
+
18
+ @protocol SimHIDClient
19
+ - (id<SimHIDClient>)initWithDevice:(id<SimDevice>)device error:(NSError **)error;
20
+ - (void)sendWithMessage:(void *)message
21
+ freeWhenDone:(BOOL)freeWhenDone
22
+ completionQueue:(dispatch_queue_t)queue
23
+ completion:(void (^)(NSError *))completion;
24
+ @end
25
+
26
+ typedef void *(*MakeTouch)(CGPoint *, CGPoint *, uint32_t, NSEventType, CGSize, uint32_t);
27
+
28
+ enum {
29
+ SimDeviceBooted = 3,
30
+ IndigoDigitizerTarget = 0x32,
31
+ IndigoLeftEdge = 2,
32
+ IndigoHeaderSize = 0x20,
33
+ IndigoPayloadSize = 0x90,
34
+ IndigoSizeOffset = 0x18,
35
+ IndigoTypeOffset = 0x1c,
36
+ IndigoTouchOffset = 0x10,
37
+ IndigoSingleTouch = 2,
38
+ };
39
+
40
+ static void *makeSingleTouch(MakeTouch makeTouch, CGPoint position, NSEventType event) {
41
+ unsigned char *source = makeTouch(&position, NULL, IndigoDigitizerTarget, event, CGSizeMake(1, 1), IndigoLeftEdge);
42
+ if (!source) return NULL;
43
+
44
+ // SimulatorKit's mouse builder emits a multi-touch frame. The single-contact path needs a second payload with indices 1 and 2.
45
+ unsigned char *message = calloc(1, IndigoHeaderSize + 2 * IndigoPayloadSize);
46
+ if (message) {
47
+ memcpy(message, source, IndigoHeaderSize + IndigoPayloadSize);
48
+ const uint32_t payloadSize = IndigoPayloadSize;
49
+ memcpy(message + IndigoSizeOffset, &payloadSize, sizeof(payloadSize));
50
+ message[IndigoTypeOffset] = IndigoSingleTouch;
51
+ unsigned char *secondPayload = message + IndigoHeaderSize + IndigoPayloadSize;
52
+ memcpy(secondPayload, message + IndigoHeaderSize, IndigoPayloadSize);
53
+ const uint32_t contactIndices[] = {1, 2};
54
+ memcpy(secondPayload + IndigoTouchOffset, contactIndices, sizeof(contactIndices));
55
+ }
56
+
57
+ free(source);
58
+ return message;
59
+ }
60
+
61
+ static BOOL sendTouch(id<SimHIDClient> client, MakeTouch makeTouch, CGPoint position, NSEventType event) {
62
+ void *message = makeSingleTouch(makeTouch, position, event);
63
+ if (!message) {
64
+ fputs("edge-back: could not build an Indigo digitizer event\n", stderr);
65
+ return NO;
66
+ }
67
+
68
+ dispatch_semaphore_t done = dispatch_semaphore_create(0);
69
+ __block NSError *sendError = nil;
70
+ [client sendWithMessage:message
71
+ freeWhenDone:YES
72
+ completionQueue:dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0)
73
+ completion:^(NSError *error) {
74
+ sendError = error;
75
+ dispatch_semaphore_signal(done);
76
+ }];
77
+ if (dispatch_semaphore_wait(done, dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC))) {
78
+ fputs("edge-back: SimulatorKit did not acknowledge the touch\n", stderr);
79
+ return NO;
80
+ }
81
+
82
+ if (sendError) NSLog(@"edge-back: %@", sendError);
83
+ return sendError == nil;
84
+ }
85
+
86
+ int main(int argc, char **argv) {
87
+ @autoreleasepool {
88
+ if (argc != 3) return 2;
89
+ NSUUID *udid = [[NSUUID alloc] initWithUUIDString:@(argv[1])];
90
+ if (!udid) {
91
+ fputs("edge-back: expected a simulator UDID\n", stderr);
92
+ return 2;
93
+ }
94
+
95
+ NSString *developerDir = @(argv[2]);
96
+ if (!dlopen("/Library/Developer/PrivateFrameworks/CoreSimulator.framework/CoreSimulator", RTLD_NOW)) {
97
+ fprintf(stderr, "edge-back: %s\n", dlerror());
98
+ return 1;
99
+ }
100
+ NSString *kitPath = [developerDir stringByAppendingPathComponent:
101
+ @"Library/PrivateFrameworks/SimulatorKit.framework/SimulatorKit"];
102
+ void *kit = dlopen(kitPath.fileSystemRepresentation, RTLD_NOW);
103
+ if (!kit) {
104
+ fprintf(stderr, "edge-back: %s\n", dlerror());
105
+ return 1;
106
+ }
107
+
108
+ MakeTouch makeTouch = dlsym(kit, "IndigoHIDMessageForMouseNSEvent");
109
+ Class<SimServiceContext> contextClass = NSClassFromString(@"SimServiceContext");
110
+ Class clientClass = NSClassFromString(@"SimulatorKit.SimDeviceLegacyHIDClient");
111
+ if (!makeTouch ||
112
+ ![(Class)contextClass respondsToSelector:@selector(sharedServiceContextForDeveloperDir:error:)] ||
113
+ ![clientClass instancesRespondToSelector:@selector(initWithDevice:error:)] ||
114
+ ![clientClass instancesRespondToSelector:@selector(sendWithMessage:freeWhenDone:completionQueue:completion:)]) {
115
+ fputs("edge-back: this Xcode does not expose the SimulatorKit Indigo HID API\n", stderr);
116
+ return 1;
117
+ }
118
+
119
+ NSError *error = nil;
120
+ id<SimServiceContext> context = [contextClass sharedServiceContextForDeveloperDir:developerDir error:&error];
121
+ id<SimDeviceSet> devices = [context defaultDeviceSetWithError:&error];
122
+ if (!devices) {
123
+ NSLog(@"edge-back: could not load the simulator device set (%@)", error);
124
+ return 1;
125
+ }
126
+
127
+ id<SimDevice> target = nil;
128
+ for (id<SimDevice> device in devices.devices) {
129
+ if ([device.UDID isEqual:udid] && device.state == SimDeviceBooted) {
130
+ target = device;
131
+ break;
132
+ }
133
+ }
134
+ if (!target) {
135
+ NSLog(@"edge-back: simulator %@ is not booted", udid);
136
+ return 1;
137
+ }
138
+
139
+ id<SimHIDClient> client = [(id<SimHIDClient>)[clientClass alloc] initWithDevice:target error:&error];
140
+ if (!client) {
141
+ NSLog(@"edge-back: could not connect to simulator %@ (%@)", udid, error);
142
+ return 1;
143
+ }
144
+
145
+ const int steps = 24;
146
+ CGPoint position = CGPointMake(0, 0.5);
147
+ BOOL delivered = YES;
148
+ for (int step = 0; step <= steps; step++) {
149
+ position.x = 0.8 * step / steps;
150
+ if (!sendTouch(client, makeTouch, position, NSEventTypeLeftMouseDown)) {
151
+ delivered = NO;
152
+ break;
153
+ }
154
+ [NSThread sleepForTimeInterval:0.015];
155
+ }
156
+ BOOL released = sendTouch(client, makeTouch, position, NSEventTypeLeftMouseUp);
157
+ return delivered && released ? 0 : 1;
158
+ }
159
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ethlete/agent-rules",
3
- "version": "0.1.0-next.57",
3
+ "version": "0.1.0-next.59",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/ethlete-io/ethdk",