mirror of
https://github.com/garrytan/gstack.git
synced 2026-05-30 23:09:32 +02:00
64f9aafa1e
* fix(office-hours): #1671 — session writer was writing to the legacy file User-visible symptom: returning /office-hours users get the same closing pitch every visit, no matter how many times they've run the skill. The welcome_back tier (which exists specifically to skip the pitch for returning users) was unreachable. Live since 2026-04-18 / v1.0.0.0 on every fresh-$HOME user. Root cause: the v1.0.0.0 migration moved the read path to ~/.gstack/developer-profile.json but left the writer in office-hours/SKILL.md.tmpl writing to the legacy ~/.gstack/builder-profile.jsonl. Reader and writer disagreed on storage, so SESSION_COUNT never incremented and /office-hours always treated the user as a first-timer. Fix: - bin/gstack-developer-profile: new --log-session subcommand that read-modify-writes developer-profile.json's sessions[] array (atomic mktemp+mv, signals/resources/topics aggregation, gbrain-enqueue mirror of gstack-timeline-log:40). Naming matches the gstack-*-log family verb. - bin/gstack-developer-profile: do_read filters mode:"resources" entries when picking LAST_PROJECT/LAST_ASSIGNMENT/LAST_DESIGN_TITLE so the Phase 6 resources auto-append doesn't clobber real-session state. Latent bug that was masked by the broken writer; activated by the fix. - office-hours/SKILL.md.tmpl: lines 490 + 893 swap echo >> for --log-session. - test/gstack-developer-profile.test.ts: +8 tests covering --log-session contract (regression, aggregation, dedup, validation, ts handling) plus the mode-filter regression. All 8 fail on main, all 8 pass with this fix. - test/static-no-legacy-writes.test.ts: new static-grep invariant walking every skill dir to prevent future regressions onto the legacy file. Affected users: stranded builder-profile.jsonl entries are not recovered automatically by this PR. On their next /office-hours run, the first new session lands in welcome_back; past data stays in the legacy file (still readable by other tools during deprecation). Most pre-existing users have only a handful of stranded sessions. See docs/designs/FIX_1671_PROFILE_MIGRATION.md for scope decisions (RC2/RC3 follow-ups, what was intentionally left out, and why). Issue: #1671 * test(office-hours): refine #1671 invariant regex comment for literal-path scope Clarifies that the WRITE_PATTERN regex catches literal-path writes only; variable-indirected writes (FILE=...; echo >> "$FILE") are not detected. The SKILL.md.tmpl assertions in the same suite pin the exact #1671 regression class directly; this regex is a backstop, not a flow analyzer. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(timeline): pass read filters as data * feat(next-version): support monorepo VERSION paths via --version-path + .gstack/version-path The workspace-aware ship queue hardcoded the VERSION file at the repo root. In monorepos where versioning is subproject-scoped (one app inside a larger repo), every PR's VERSION lookup 404s, the queue silently empties, and parallel /ship sessions all bump from "current main + 1" — producing a cascade of slot collisions. Repro: tinas-second-brain repo. Root VERSION is absent; the real VERSION lives at "Tinas Second Brain/health-tracker/VERSION". In one day, four sequential collisions: 0.4.0.1 -> 0.5.0.0 -> 0.5.0.1 -> 0.5.0.2 -> 0.5.0.3. Fix: add a --version-path flag and a repo-local .gstack/version-path config file. Resolution priority: CLI flag > .gstack/version-path > "VERSION". The resolved path threads through all four call sites — git show origin/<base>:<path>, the GitHub Contents API, the GitLab files API, and the local sibling-worktree scan — and shows up in the JSON output as version_path so /ship and operators can see what got picked. The previous warning "could not fetch VERSION (fork or private)" was misleading whenever the real cause was wrong path. The new wording names the path that 404'd and hints at the two knobs. Backward-compatible: no flag, no config, no change in behavior. Tests: 6 unit tests for resolveVersionPath (priority, parsing, blank / missing / empty edge cases) + a second integration smoke that drives --version-path end-to-end and asserts it surfaces in JSON output. * fix(investigate): support standalone freeze hook path * fix(browse): clarify localhost bind failures * fix(migration): defer v1.40.0.0 done-marker until every repair succeeds (#1581) The v1.40.0.0 migration unconditionally `touch`ed its done-marker, even when the jq-gated `.brain-privacy-map.json` patch was skipped because jq was missing on the user's machine. On subsequent runs, the script short-circuited on the marker so the privacy-map repair never landed. Federation sync then silently dropped `/plan-eng-review` test plans. Track every failure mode via a single `incomplete` flag: jq missing, malformed JSON, jq mutation failure, tempfile creation failure, `mv` failure, allowlist append failure, gitattributes append failure. The marker is written only when `incomplete=0`, so the migration runner retries on the next /gstack-upgrade once the prerequisites are met. * test(migration): unit tests for v1.40.0.0 deferred done-marker fix (#1581) 8 cases pinning the fix: - Case 1 (happy path): jq present, fresh privacy-map → all three files patched, marker written. - Case 2 (regression for #1581): jq missing, privacy-map present → marker must NOT be written. Fails against the buggy script, passes against the fix. - Case 3 (recovery): jq missing, then jq restored → patch lands on second run. - Case 4 (idempotency): privacy-map already has correct entry → no mutation, marker written. - Case 5 (fresh-init): privacy-map file absent → allowlist + gitattrs patched, marker written. - Case 6 (malformed JSON): broken privacy-map JSON → no marker, no mutation. - Case 7 (jq mutation failure): fake jq returning 1 → no marker, tempfile cleaned up. - Case 8 (allowlist append failure): read-only allowlist → no marker. Tests use spawnSync('bash', [MIGRATION], …) with isolated tmpHomes. "jq missing" sets PATH to a curated dir of symlinks to standard utils, omitting jq; "jq mutation fails" uses an `exit 1` shim. Avoids blanket-clearing PATH (which would hide bash/grep/etc). * fix(brain-sync): make artifact sync work on Windows (discover-new + drain) Automatic artifact sync was fully non-functional on Windows (Git Bash): --discover-new enqueued nothing and the --once drain staged nothing, so artifacts_sync_mode looked active but no artifacts ever reached the repo. Three independent Windows-only causes in bin/gstack-brain-sync: 1. discover-new matched os.path.relpath (backslash separators on Windows) against the forward-slash allowlist globs, so no nested file ever matched. Normalized the relpath to "/". 2. discover-new enqueued via subprocess.run([gstack-brain-enqueue, rel]), but Windows Python cannot exec a bash-shebang script, so nothing was enqueued even once matched. Now appends to the queue in-process. 3. compute_paths_to_stage ends in print(p); Windows Python emits CRLF, the bash `read -r` keeps the trailing CR, and `git add -- "path<CR>"` matches nothing under `2>/dev/null || true`. Now strips the CR before staging. The in-process enqueue mirrors gstack-brain-enqueue's contract: one atomic O_APPEND write per record (each line < PIPE_BUF) so a parallel writer-shim append can't interleave mid-record, and the discover cursor advances only after the write succeeds, so a failed write retries instead of silently recording the file as synced. Skip-list entries are separator-normalized on both the discover and drain (compute_paths_to_stage) sides, so a backslash .brain-skip.txt entry can't be honored at discovery yet bypassed at commit. Adds test/brain-sync-windows-paths.test.ts (static invariants -- behavioral spawn tests cannot run on the Windows lane, since Node/Bun cannot exec the bin/ shebang scripts there) and wires it into windows-free-tests.yml. Verified red->green and end-to-end on Windows 11 / Git Bash; macOS/Linux behavior unchanged (os.sep is already "/", no CRLF, compute path logic unchanged besides the shared skip normalization). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix: detect bun.lock (Bun v1.2+ text lockfile) in diff-scope CONFIG gstack-diff-scope only matched the legacy binary lockfile `bun.lockb` but not the newer text-based `bun.lock` introduced in Bun v1.2+. Projects using current Bun versions were silently missing the SCOPE_CONFIG signal when only the lockfile changed. 🤖 Generated with [Qoder][https://qoder.com] * fix(ios-qa): resolve CoreDevice tunnel via devicectl + keep tunnel alive The daemon's tunnel bootstrap used `dns.resolve6` to look up `<device>.coredevice.local`, which fails with ESERVFAIL on macOS 26.x (Darwin 25.x) because Node's resolve6 path goes through libresolv and does NOT consult mDNSResponder. `dns.lookup` (getaddrinfo) does. Even when resolution works, CoreDevice in Xcode 26 only holds the USB tunnel up while a devicectl command is in-flight, so the IPv6 ULA becomes unroutable within ~10-15s of idle and subsequent proxy requests time out. Two-part fix: 1. Resolution order is now (a) `xcrun devicectl device info details --json-output` to read `result.connectionProperties.tunnelIPAddress` directly, (b) mDNS via `dns.lookup`, (c) legacy `dns.resolve6` as a last-ditch fallback. 2. After a successful bootstrap the daemon spawns a periodic `devicectl device info details` (~5s) to keep the tunnel session alive. Cleaned up on SIGINT/SIGTERM/exit. Adds tests for `getDeviceTunnelIPv6FromDevicectl`, the `resolveTunnelIPv6` fallback chain, and `startTunnelKeepalive`. Existing bootstrap tests updated to include the new `device info details` spawn step. Tested against: iPhone 12 Pro on iOS 26.x via Mac Mini M-series running macOS Sequoia 15.x / Darwin 25.3.0. * chore(release): v1.44.1.0 — 9-PR community fix wave (post-windhoek paper-cut) Bump VERSION + CHANGELOG entry. Wave covers /office-hours session counter, iOS QA macOS 26 tunnels, Windows brain-sync, browse server bind diagnostics, monorepo VERSION layouts, /investigate freeze hook on standalone installs, gstack-timeline-read quote injection, v1.40.0.0 migration on jq-less machines, bun.lock detection. 9 community PRs: #1676 #1635 #1627 #1648 #1664 #1589 #1672 #1649 #1673 9 contributors credited: @pryow @jbetala7 @cfeddersen @Gujiassh @spacegeologist @stedfn @daveowenatl @hiSandog @sternryan 4 issues closed: #1671 #1677 #1634 #1647 #1581 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> --------- Co-authored-by: Rook <rook@robomovers.com> Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: Jayesh Betala <jayesh.betala7@gmail.com> Co-authored-by: Christoph <astaran@herr-der-ringe-film.de> Co-authored-by: gujishh <baiaoshh@163.com> Co-authored-by: zhengzuo0-ai <zheng.zuo0@gmail.com> Co-authored-by: Stefan Neamtu <stefan.neamtu@nearone.org> Co-authored-by: Dave Owen <daveowen66@gmail.com> Co-authored-by: 陈家名 <chenjiaming@kezaihui.com> Co-authored-by: Ryan Stern <206953196+sternryan@users.noreply.github.com>
432 lines
16 KiB
TypeScript
432 lines
16 KiB
TypeScript
// Bootstrap unit tests. Injects spawn + resolve + fetch stubs so we exercise
|
|
// every branch (no_devices, no_paired_device, device_locked, healthz timeout,
|
|
// rotate_failed, success) without needing a real iPhone connected.
|
|
|
|
import { describe, test, expect } from 'bun:test';
|
|
import { bootstrapTunnel } from '../src/tunnel-bootstrap';
|
|
import {
|
|
getDeviceTunnelIPv6FromDevicectl,
|
|
resolveTunnelIPv6,
|
|
startTunnelKeepalive,
|
|
type SpawnImpl,
|
|
} from '../src/devicectl';
|
|
import { writeFileSync } from 'fs';
|
|
|
|
interface ScriptedCall {
|
|
argsMatch: RegExp;
|
|
stdout?: string;
|
|
stderr?: string;
|
|
exitCode?: number;
|
|
/** If set, write this content to the JSON output path before returning. */
|
|
jsonOutput?: object;
|
|
/** If set, write this content to the file matching `--destination`. */
|
|
destOutput?: string;
|
|
}
|
|
|
|
/**
|
|
* Build a spawnImpl that walks through a scripted sequence of expected calls.
|
|
* Each call matches its args against `argsMatch`. Unmatched calls return
|
|
* exit-code 1 with an "unexpected call" stderr.
|
|
*/
|
|
function makeSpawn(scripts: ScriptedCall[]): SpawnImpl {
|
|
let idx = 0;
|
|
return (cmd: string, args: string[]) => {
|
|
const joined = `${cmd} ${args.join(' ')}`;
|
|
const script = scripts[idx];
|
|
if (!script) {
|
|
return makeReturn(1, '', `unexpected call beyond scripted: ${joined}`);
|
|
}
|
|
if (!script.argsMatch.test(joined)) {
|
|
return makeReturn(1, '', `unexpected call shape: ${joined} (expected ${script.argsMatch})`);
|
|
}
|
|
idx++;
|
|
// Honor --json-output: write to that path BEFORE returning.
|
|
if (script.jsonOutput) {
|
|
const flagIdx = args.indexOf('--json-output');
|
|
if (flagIdx !== -1 && args[flagIdx + 1]) {
|
|
writeFileSync(args[flagIdx + 1]!, JSON.stringify(script.jsonOutput));
|
|
}
|
|
}
|
|
if (script.destOutput) {
|
|
const flagIdx = args.indexOf('--destination');
|
|
if (flagIdx !== -1 && args[flagIdx + 1]) {
|
|
writeFileSync(args[flagIdx + 1]!, script.destOutput);
|
|
}
|
|
}
|
|
return makeReturn(script.exitCode ?? 0, script.stdout ?? '', script.stderr ?? '');
|
|
};
|
|
}
|
|
|
|
function makeReturn(exit: number, stdout: string, stderr: string) {
|
|
return {
|
|
pid: 0,
|
|
output: [null, Buffer.from(stdout), Buffer.from(stderr)],
|
|
stdout: Buffer.from(stdout),
|
|
stderr: Buffer.from(stderr),
|
|
status: exit,
|
|
signal: null,
|
|
} as ReturnType<SpawnImpl>;
|
|
}
|
|
|
|
describe('bootstrapTunnel', () => {
|
|
test('returns no_devices when devicectl list shows zero', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: { result: { devices: [] } },
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({ bundleId: 'com.test', spawnImpl: spawn });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toBe('no_devices');
|
|
});
|
|
|
|
test('returns no_paired_device when device is connected but not paired', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: {
|
|
devices: [{
|
|
identifier: 'TEST-UDID',
|
|
connectionProperties: { tunnelState: 'available (pairing)', pairingState: 'unpaired' },
|
|
deviceProperties: { name: 'Test iPhone' },
|
|
hardwareProperties: { productType: 'iPhone18,2' },
|
|
}],
|
|
},
|
|
},
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({ bundleId: 'com.test', spawnImpl: spawn });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) {
|
|
expect(r.error).toBe('no_paired_device');
|
|
expect(r.detail).toContain('Trust');
|
|
}
|
|
});
|
|
|
|
test('returns device_locked when launchApp errors due to lock', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: { devices: [{
|
|
identifier: 'TEST', connectionProperties: { tunnelState: 'connected', pairingState: 'paired' },
|
|
deviceProperties: { name: 'Test' }, hardwareProperties: { productType: 'iPhone18,2' },
|
|
}] },
|
|
},
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info processes/,
|
|
jsonOutput: { result: { runningProcesses: [] } },
|
|
},
|
|
{
|
|
argsMatch: /devicectl device process launch/,
|
|
stderr: 'Locked ("Unable to launch com.test because the device was not, or could not be, unlocked").',
|
|
exitCode: 1,
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({ bundleId: 'com.test', spawnImpl: spawn });
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toBe('device_locked');
|
|
});
|
|
|
|
test('returns state_server_unreachable when healthz never responds', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: { devices: [{
|
|
identifier: 'TEST', connectionProperties: { tunnelState: 'connected', pairingState: 'paired' },
|
|
deviceProperties: { name: 'Test' }, hardwareProperties: { productType: 'iPhone18,2' },
|
|
}] },
|
|
},
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info processes/,
|
|
jsonOutput: { result: { runningProcesses: [{ executable: 'file:///private/var/containers/Bundle/Application/.../com.test.app/com.test', processIdentifier: 1234 }] } },
|
|
stdout: 'com.test',
|
|
},
|
|
{
|
|
// devicectl device info details (devicectl-based IPv6 resolution).
|
|
// Return no tunnelIPAddress so we fall through to the injected resolver.
|
|
argsMatch: /devicectl device info details/,
|
|
jsonOutput: { result: { connectionProperties: {} } },
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({
|
|
bundleId: 'com.test',
|
|
spawnImpl: spawn,
|
|
resolveImpl: async () => ['fd00::1'],
|
|
// fetch always fails.
|
|
fetchImpl: (async () => { throw new Error('connection refused'); }) as typeof fetch,
|
|
startupTimeoutMs: 200, // short, so test runs fast
|
|
});
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toBe('state_server_unreachable');
|
|
});
|
|
|
|
test('happy path: returns DeviceTunnel with rotated token', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: { devices: [{
|
|
identifier: 'TEST-UDID',
|
|
connectionProperties: { tunnelState: 'connected', pairingState: 'paired' },
|
|
deviceProperties: { name: 'Test Device' },
|
|
hardwareProperties: { productType: 'iPhone18,2' },
|
|
}] },
|
|
},
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info processes/,
|
|
jsonOutput: { result: { runningProcesses: [{ executable: 'file:///var/containers/Bundle/Application/X/com.test.app/com.test', processIdentifier: 5678 }] } },
|
|
stdout: '/com.test.app/',
|
|
},
|
|
{
|
|
// devicectl-based IPv6 resolution succeeds — returns the tunnel
|
|
// address directly, so the injected resolveImpl is never called.
|
|
argsMatch: /devicectl device info details/,
|
|
jsonOutput: { result: { connectionProperties: { tunnelIPAddress: 'fd99::beef' } } },
|
|
},
|
|
{
|
|
argsMatch: /devicectl device copy from/,
|
|
destOutput: 'BOOT-TOKEN-XYZ-123\n',
|
|
},
|
|
]);
|
|
const fetchCalls: Array<{ url: string; method: string }> = [];
|
|
const r = await bootstrapTunnel({
|
|
bundleId: 'com.test',
|
|
spawnImpl: spawn,
|
|
resolveImpl: async () => ['fd99::beef'],
|
|
fetchImpl: (async (url, init) => {
|
|
const u = String(url);
|
|
const method = (init?.method ?? 'GET').toUpperCase();
|
|
fetchCalls.push({ url: u, method });
|
|
if (u.endsWith('/healthz')) {
|
|
return new Response('{"version":"1.0.0"}', { status: 200 }) as Response;
|
|
}
|
|
if (u.endsWith('/auth/rotate') && method === 'POST') {
|
|
// Verify the boot token is sent (not the rotated one).
|
|
const auth = (init?.headers as Record<string, string>)['Authorization'] ?? '';
|
|
if (auth !== 'Bearer BOOT-TOKEN-XYZ-123') {
|
|
return new Response('wrong bearer', { status: 401 }) as Response;
|
|
}
|
|
return new Response('{"ok":true}', { status: 200 }) as Response;
|
|
}
|
|
return new Response('not found', { status: 404 }) as Response;
|
|
}) as typeof fetch,
|
|
startupTimeoutMs: 1_000,
|
|
});
|
|
|
|
expect(r.ok).toBe(true);
|
|
if (r.ok) {
|
|
expect(r.tunnel.udid).toBe('TEST-UDID');
|
|
expect(r.tunnel.ipv6Addr).toBe('fd99::beef');
|
|
expect(r.tunnel.port).toBe(9999);
|
|
expect(r.tunnel.bootTokenRotated).toMatch(/^[A-Za-z0-9_-]+$/);
|
|
expect(r.tunnel.bootTokenRotated).not.toBe('BOOT-TOKEN-XYZ-123');
|
|
expect(r.tunnel.bootTokenRotated.length).toBeGreaterThan(20);
|
|
}
|
|
// Verify the bootstrap sequence: /healthz first, /auth/rotate second.
|
|
expect(fetchCalls[0]?.url).toContain('/healthz');
|
|
expect(fetchCalls[fetchCalls.length - 1]?.url).toContain('/auth/rotate');
|
|
});
|
|
|
|
test('resolve_failed when hostname cant be resolved to an IPv6', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: { devices: [{
|
|
identifier: 'TEST', connectionProperties: { tunnelState: 'connected', pairingState: 'paired' },
|
|
deviceProperties: { name: 'Test' }, hardwareProperties: { productType: 'iPhone18,2' },
|
|
}] },
|
|
},
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info processes/,
|
|
// jsonOutput body contains the bundle id path, so isAppRunning() returns true.
|
|
jsonOutput: { result: { runningProcesses: [{ executable: 'file:///var/containers/Bundle/Application/X/com.test.app/com.test' }] } },
|
|
},
|
|
{
|
|
// devicectl device info details returns no tunnel address.
|
|
argsMatch: /devicectl device info details/,
|
|
jsonOutput: { result: { connectionProperties: {} } },
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({
|
|
bundleId: 'com.test',
|
|
spawnImpl: spawn,
|
|
resolveImpl: async () => { throw new Error('ENOTFOUND'); },
|
|
});
|
|
expect(r.ok).toBe(false);
|
|
if (!r.ok) expect(r.error).toBe('resolve_failed');
|
|
});
|
|
|
|
test('respects explicit udid when set', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl list devices/,
|
|
jsonOutput: {
|
|
result: { devices: [
|
|
{ identifier: 'A', connectionProperties: { tunnelState: 'connected', pairingState: 'paired' }, deviceProperties: { name: 'A' }, hardwareProperties: { productType: 'iPhone18,2' } },
|
|
{ identifier: 'B', connectionProperties: { tunnelState: 'connected', pairingState: 'paired' }, deviceProperties: { name: 'B' }, hardwareProperties: { productType: 'iPhone18,2' } },
|
|
] },
|
|
},
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info processes -d B/,
|
|
jsonOutput: { result: { runningProcesses: [{ executable: 'file:///var/containers/Bundle/Application/X/com.test.app/com.test' }] } },
|
|
},
|
|
{
|
|
argsMatch: /devicectl device info details --device B/,
|
|
jsonOutput: { result: { connectionProperties: { tunnelIPAddress: 'fd00::b' } } },
|
|
},
|
|
{
|
|
argsMatch: /devicectl device copy from --device B/,
|
|
destOutput: 'TOKEN\n',
|
|
},
|
|
]);
|
|
const r = await bootstrapTunnel({
|
|
udid: 'B',
|
|
bundleId: 'com.test',
|
|
spawnImpl: spawn,
|
|
resolveImpl: async () => ['fd00::b'],
|
|
fetchImpl: (async () => new Response('{"ok":true}', { status: 200 })) as typeof fetch,
|
|
});
|
|
expect(r.ok).toBe(true);
|
|
if (r.ok) expect(r.tunnel.udid).toBe('B');
|
|
});
|
|
});
|
|
|
|
describe('getDeviceTunnelIPv6FromDevicectl', () => {
|
|
test('extracts tunnelIPAddress from connectionProperties', () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl device info details --device TEST-UDID/,
|
|
jsonOutput: { result: { connectionProperties: { tunnelIPAddress: 'fde4:2827:528e::1' } } },
|
|
},
|
|
]);
|
|
expect(getDeviceTunnelIPv6FromDevicectl('TEST-UDID', spawn)).toBe('fde4:2827:528e::1');
|
|
});
|
|
|
|
test('falls back to result.tunnel.ipAddress when connectionProperties absent', () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl device info details/,
|
|
jsonOutput: { result: { tunnel: { ipAddress: 'fd00::dead:beef' } } },
|
|
},
|
|
]);
|
|
expect(getDeviceTunnelIPv6FromDevicectl('UDID', spawn)).toBe('fd00::dead:beef');
|
|
});
|
|
|
|
test('returns null when devicectl exits non-zero', () => {
|
|
const spawn = makeSpawn([
|
|
{ argsMatch: /devicectl device info details/, exitCode: 1, stderr: 'no such device' },
|
|
]);
|
|
expect(getDeviceTunnelIPv6FromDevicectl('UDID', spawn)).toBeNull();
|
|
});
|
|
|
|
test('returns null when tunnelIPAddress missing or non-string', () => {
|
|
const spawn = makeSpawn([
|
|
{ argsMatch: /devicectl device info details/, jsonOutput: { result: { connectionProperties: {} } } },
|
|
]);
|
|
expect(getDeviceTunnelIPv6FromDevicectl('UDID', spawn)).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('resolveTunnelIPv6 fallback chain', () => {
|
|
test('prefers devicectl-based resolution', async () => {
|
|
const spawn = makeSpawn([
|
|
{
|
|
argsMatch: /devicectl device info details/,
|
|
jsonOutput: { result: { connectionProperties: { tunnelIPAddress: 'fd11::1' } } },
|
|
},
|
|
]);
|
|
let resolveCalled = false;
|
|
const addr = await resolveTunnelIPv6({
|
|
udid: 'U',
|
|
deviceName: 'Test',
|
|
spawn,
|
|
resolve: async () => { resolveCalled = true; return ['fd99::99']; },
|
|
legacyResolve: async () => { resolveCalled = true; return ['fdAA::AA']; },
|
|
});
|
|
expect(addr).toBe('fd11::1');
|
|
expect(resolveCalled).toBe(false);
|
|
});
|
|
|
|
test('falls through to dns.lookup when devicectl yields no address', async () => {
|
|
const spawn = makeSpawn([
|
|
{ argsMatch: /devicectl device info details/, jsonOutput: { result: { connectionProperties: {} } } },
|
|
]);
|
|
let legacyCalled = false;
|
|
const addr = await resolveTunnelIPv6({
|
|
udid: 'U',
|
|
deviceName: 'Test',
|
|
spawn,
|
|
resolve: async () => ['fd22::2'],
|
|
legacyResolve: async () => { legacyCalled = true; return ['fdAA::AA']; },
|
|
});
|
|
expect(addr).toBe('fd22::2');
|
|
expect(legacyCalled).toBe(false);
|
|
});
|
|
|
|
test('falls through to legacy resolve6 when both devicectl and dns.lookup fail', async () => {
|
|
const spawn = makeSpawn([
|
|
{ argsMatch: /devicectl device info details/, exitCode: 1 },
|
|
]);
|
|
const addr = await resolveTunnelIPv6({
|
|
udid: 'U',
|
|
deviceName: 'Test',
|
|
spawn,
|
|
resolve: async () => { throw new Error('ESERVFAIL'); },
|
|
legacyResolve: async () => ['fd33::3'],
|
|
});
|
|
expect(addr).toBe('fd33::3');
|
|
});
|
|
|
|
test('returns null when all three strategies fail', async () => {
|
|
const spawn = makeSpawn([
|
|
{ argsMatch: /devicectl device info details/, exitCode: 1 },
|
|
]);
|
|
const addr = await resolveTunnelIPv6({
|
|
udid: 'U',
|
|
deviceName: 'Test',
|
|
spawn,
|
|
resolve: async () => { throw new Error('ESERVFAIL'); },
|
|
legacyResolve: async () => { throw new Error('ESERVFAIL'); },
|
|
});
|
|
expect(addr).toBeNull();
|
|
});
|
|
});
|
|
|
|
describe('startTunnelKeepalive', () => {
|
|
test('invokes devicectl on each interval tick', async () => {
|
|
const calls: string[] = [];
|
|
const spawn: SpawnImpl = ((cmd: string, args: string[]) => {
|
|
calls.push(`${cmd} ${args.slice(0, 4).join(' ')}`);
|
|
return makeReturn(0, '{}', '');
|
|
}) as SpawnImpl;
|
|
const ka = startTunnelKeepalive('UDID-X', { intervalMs: 20, spawn });
|
|
await new Promise((res) => setTimeout(res, 75));
|
|
ka.stop();
|
|
const before = calls.length;
|
|
// After stop, no more calls.
|
|
await new Promise((res) => setTimeout(res, 50));
|
|
expect(calls.length).toBe(before);
|
|
expect(before).toBeGreaterThanOrEqual(2);
|
|
expect(calls[0]).toContain('devicectl');
|
|
expect(calls[0]).toContain('device info details');
|
|
});
|
|
|
|
test('stop() is idempotent', () => {
|
|
const spawn: SpawnImpl = (() => makeReturn(0, '', '')) as SpawnImpl;
|
|
const ka = startTunnelKeepalive('U', { intervalMs: 1_000, spawn });
|
|
ka.stop();
|
|
ka.stop();
|
|
// no throw
|
|
});
|
|
});
|