@ait-co/devtools 0.1.128 → 0.1.129

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.
Files changed (66) hide show
  1. package/dist/{attach-orchestrator-CpE0dMew.js → attach-orchestrator-Bdt5Zdo9.js} +3 -94
  2. package/dist/attach-orchestrator-Bdt5Zdo9.js.map +1 -0
  3. package/dist/{attach-orchestrator-CPMQWkGV.js → attach-orchestrator-DvrgUIx7.js} +4 -95
  4. package/dist/attach-orchestrator-DvrgUIx7.js.map +1 -0
  5. package/dist/{bundle-Cb3GFuw6.d.ts → bundle-BKqyhEK9.d.ts} +1 -1
  6. package/dist/{bundle-Cb3GFuw6.d.ts.map → bundle-BKqyhEK9.d.ts.map} +1 -1
  7. package/dist/{capture-B1zfGyTo.d.ts → capture-ltuV0gZa.d.ts} +1 -1
  8. package/dist/{capture-B1zfGyTo.d.ts.map → capture-ltuV0gZa.d.ts.map} +1 -1
  9. package/dist/{cdp-connection-Dxw_EY8s.d.ts → cdp-connection-D7AYQck2.d.ts} +1 -1
  10. package/dist/{cdp-connection-Dxw_EY8s.d.ts.map → cdp-connection-D7AYQck2.d.ts.map} +1 -1
  11. package/dist/{cell-D0dJSGHi.js → cell-DA_lcpDI.js} +2 -2
  12. package/dist/{cell-D0dJSGHi.js.map → cell-DA_lcpDI.js.map} +1 -1
  13. package/dist/{cell-CX92lDI0.js → cell-DLRv4iG6.js} +2 -2
  14. package/dist/{cell-CX92lDI0.js.map → cell-DLRv4iG6.js.map} +1 -1
  15. package/dist/{debug-server-Dctc9GAh.js → debug-server--Y0QZVJS.js} +57 -58
  16. package/dist/debug-server--Y0QZVJS.js.map +1 -0
  17. package/dist/debug-server-Bu3pCG9c.js +436 -0
  18. package/dist/debug-server-Bu3pCG9c.js.map +1 -0
  19. package/dist/debug-server-e1qPe0ZB.js +379 -0
  20. package/dist/{debug-server-BzzNkETg.js.map → debug-server-e1qPe0ZB.js.map} +1 -1
  21. package/dist/log-CUik_tHp.js +95 -0
  22. package/dist/log-CUik_tHp.js.map +1 -0
  23. package/dist/mcp/cli.js +1152 -1099
  24. package/dist/mcp/cli.js.map +1 -1
  25. package/dist/mcp/server.js +1 -1
  26. package/dist/panel/index.js +1 -1
  27. package/dist/{pool-DBLKNeRC.d.ts → pool-C0pc7T2p.d.ts} +4 -4
  28. package/dist/{pool-DBLKNeRC.d.ts.map → pool-C0pc7T2p.d.ts.map} +1 -1
  29. package/dist/{qr-http-server-Bo8LMOJQ.js → qr-http-server-HANhOFwI.js} +1 -1
  30. package/dist/{qr-http-server-Bo8LMOJQ.js.map → qr-http-server-HANhOFwI.js.map} +1 -1
  31. package/dist/{relay-factory-Dug7W6Ao.js → relay-factory-Ck3vBonr.js} +6 -6
  32. package/dist/{relay-factory-Dug7W6Ao.js.map → relay-factory-Ck3vBonr.js.map} +1 -1
  33. package/dist/{relay-secret-store-DKxs7zwq.js → relay-secret-store-DzxDsK6S.js} +1 -1
  34. package/dist/{relay-secret-store-DKxs7zwq.js.map → relay-secret-store-DzxDsK6S.js.map} +1 -1
  35. package/dist/{relay-url-store-xmUuTjXA.js → relay-url-store-D3rY-GJJ.js} +2 -2
  36. package/dist/{relay-url-store-xmUuTjXA.js.map → relay-url-store-D3rY-GJJ.js.map} +1 -1
  37. package/dist/{debug-server-BzzNkETg.js → relay-worker-Bt0QYKQH.js} +212 -346
  38. package/dist/relay-worker-Bt0QYKQH.js.map +1 -0
  39. package/dist/{relay-worker-TReZtzGl.d.ts → relay-worker-o0M2ndyJ.d.ts} +7 -7
  40. package/dist/relay-worker-o0M2ndyJ.d.ts.map +1 -0
  41. package/dist/{runtime-ozyPnRbU.d.ts → runtime-9xhN9pr8.d.ts} +1 -1
  42. package/dist/{runtime-ozyPnRbU.d.ts.map → runtime-9xhN9pr8.d.ts.map} +1 -1
  43. package/dist/test-runner/bin.js +706 -13
  44. package/dist/test-runner/bin.js.map +1 -1
  45. package/dist/test-runner/bundle.d.ts +1 -1
  46. package/dist/test-runner/capture.d.ts +1 -1
  47. package/dist/test-runner/config.d.ts +1 -1
  48. package/dist/test-runner/config.js +1 -1
  49. package/dist/test-runner/pool.d.ts +1 -1
  50. package/dist/test-runner/pool.js +1 -1
  51. package/dist/test-runner/relay-factory.d.ts +1 -1
  52. package/dist/test-runner/relay-factory.js +1 -1
  53. package/dist/test-runner/relay-worker.d.ts +1 -1
  54. package/dist/test-runner/relay-worker.js +1 -187
  55. package/dist/test-runner/report.d.ts +3 -3
  56. package/dist/test-runner/rpc.d.ts +2 -2
  57. package/dist/test-runner/runtime.d.ts +1 -1
  58. package/dist/test-runner/task-graph.d.ts +1 -1
  59. package/package.json +1 -1
  60. package/dist/attach-orchestrator-CPMQWkGV.js.map +0 -1
  61. package/dist/attach-orchestrator-CpE0dMew.js.map +0 -1
  62. package/dist/debug-server-1dhDA3aw.js +0 -980
  63. package/dist/debug-server-1dhDA3aw.js.map +0 -1
  64. package/dist/debug-server-Dctc9GAh.js.map +0 -1
  65. package/dist/relay-worker-TReZtzGl.d.ts.map +0 -1
  66. package/dist/test-runner/relay-worker.js.map +0 -1
package/dist/mcp/cli.js CHANGED
@@ -2024,7 +2024,7 @@ async function readMcpSdkVersion() {
2024
2024
  * some test environments that skip the build step).
2025
2025
  */
2026
2026
  function readDevtoolsVersion() {
2027
- return "0.1.128";
2027
+ return "0.1.129";
2028
2028
  }
2029
2029
  /**
2030
2030
  * Derives the next recommended action from a completed diagnostics snapshot.
@@ -3003,949 +3003,194 @@ async function discoverTestFiles(patterns, cwd) {
3003
3003
  return [...out].sort();
3004
3004
  }
3005
3005
  //#endregion
3006
- //#region src/test-runner/bundle.ts
3006
+ //#region src/shared/relay-auth-close.ts
3007
3007
  /**
3008
- * esbuild-based bundler for user test files.
3009
- *
3010
- * Bundles a single test file into a self-contained IIFE string that can be
3011
- * injected into a WebView via `Runtime.evaluate`. The bundle includes the
3012
- * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
3013
- * the `runTestModule(factory)` entry point.
3014
- *
3015
- * ## How the wiring works
3016
- *
3017
- * The bundle exposes two exports on `globalThis.__testBundle`:
3018
- * - `runTestModule` — the runtime's entry function.
3019
- * - `__userFactory` — an async function whose body is the user's top-level
3020
- * test registration code (describe/it/test calls).
3021
- *
3022
- * The Node-side RPC (`rpc.ts`) calls:
3023
- * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
3024
- *
3025
- * `runTestModule` then installs `describe/it/test/expect` as globals, invokes
3026
- * the factory (which registers all tests), runs them, and returns a `RunReport`.
3027
- *
3028
- * ## Why a factory wrapper is needed
3029
- *
3030
- * Naively adding the runtime to `entryPoints` and bundling the user file would
3031
- * fail for two reasons:
3032
- * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
3033
- * scope. The user's top-level `describe(...)` calls expect them as globals —
3034
- * they are not globals until `runTestModule` installs them.
3035
- * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
3036
- * time, before the RPC layer calls `runTestModule` to reset state and start
3037
- * the test clock.
3038
- *
3039
- * The factory approach solves both: the user's registration code is deferred
3040
- * into a function that `runTestModule` calls AFTER installing the globals.
3041
- *
3042
- * ## Factory extraction algorithm
3043
- *
3044
- * The `userFactoryPlugin` reads the user file and splits lines into:
3045
- * - **top-level**: `import …` and re-export lines — kept at module scope
3046
- * (the only valid position for static `import` in ESM).
3047
- * - **body**: all other statements — moved into the body of the exported
3048
- * `__userFactory` async function.
3008
+ * Shared constants for the relay's named TOTP-auth rejection (issue #478).
3049
3009
  *
3050
- * esbuild processes the re-generated module, following each static import
3051
- * through the normal dependency graph (including the SDK-redirect plugin).
3010
+ * Before #478 the relay rejected an unauthenticated WebSocket upgrade with a
3011
+ * raw `HTTP/1.1 401` + `socket.destroy()`. A handshake aborted that way is
3012
+ * indistinguishable from a network failure on the browser side — the
3013
+ * WebSocket only ever sees close code 1006, so the phone (env-2 launcher PWA)
3014
+ * could not tell "stale TOTP code" apart from "tunnel down" and stayed
3015
+ * silent. The fix is accept-then-close: complete the handshake, then close
3016
+ * with an application close code that NAMES the rejection.
3052
3017
  *
3053
- * ## SDK redirect
3018
+ * Three parties share this contract:
3019
+ * - `src/mcp/chii-relay.ts` (Node) sends the close frame / HTTP error body;
3020
+ * - `src/in-app/attach.ts` (browser) observes relay-bound WebSockets and
3021
+ * surfaces the code to the launcher shell;
3022
+ * - `src/mcp/chii-connection.ts` (Node daemon client) recognises the code
3023
+ * as an auth failure on its own `/client` dial (defensive — #439's fresh
3024
+ * code mint means it should not normally hit this).
3054
3025
  *
3055
- * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
3056
- * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
3057
- * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
3026
+ * This module is intentionally dependency-free (no Node, no DOM) so it is
3027
+ * safe to import from both the browser in-app bundle and the MCP daemon
3028
+ * bundle.
3058
3029
  *
3059
- * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
3030
+ * SECRET-HANDLING: these are fixed enum values. The close reason / error body
3031
+ * must never grow to carry a secret, a TOTP code, or a host.
3060
3032
  */
3061
- /** The SDK package name that mini-app test code imports from. */
3062
- const SDK_PACKAGE = "@apps-in-toss/web-framework";
3063
3033
  /**
3064
- * Names the runtime installs as globals before invoking the user factory.
3065
- * The `vitest` virtual module re-exports each as a lazy getter that reads from
3066
- * `globalThis` at access time. Keep in sync with the globals installed in
3067
- * `runtime.ts#runTestModule`.
3034
+ * WebSocket close code sent by the relay when TOTP auth is rejected.
3035
+ *
3036
+ * 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
3037
+ * HTTP 401 so it reads as "unauthorized" at a glance.
3068
3038
  */
3069
- const VITEST_GLOBAL_NAMES = [
3070
- "describe",
3071
- "it",
3072
- "test",
3073
- "expect",
3074
- "beforeAll",
3075
- "afterAll",
3076
- "beforeEach",
3077
- "afterEach",
3078
- "vi"
3079
- ];
3039
+ const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
3080
3040
  /**
3081
- * Matches the bare SDK package and any sub-path import
3082
- * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).
3083
- * Built from {@link SDK_PACKAGE} so the package name has a single source.
3041
+ * Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
3042
+ * the `error` value of the relay's HTTP 401 JSON body. Enum string only —
3043
+ * never interpolated with request data.
3084
3044
  */
3085
- const SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
3045
+ const RELAY_AUTH_REJECT_REASON = "totp-rejected";
3046
+ //#endregion
3047
+ //#region src/mcp/chii-connection.ts
3086
3048
  /**
3087
- * esbuild plugin that intercepts SDK imports and redirects them to the
3088
- * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.
3049
+ * Production `CdpConnection` backed by the local Chii relay.
3089
3050
  *
3090
- * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),
3091
- * esbuild resolves it to a virtual module that re-exports all named exports
3092
- * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not
3093
- * be available in the test environment) while still making named imports work.
3051
+ * Topology (debug mode):
3052
+ * phone target.js --WS--> Chii relay :9100 <--WS-- this connection
3094
3053
  *
3095
- * If `window.__sdk` is absent (non-dog-food build), every access throws a
3096
- * descriptive error rather than returning `undefined` silently.
3097
- */
3098
- function sdkRedirectPlugin() {
3099
- return {
3100
- name: "sdk-redirect",
3101
- setup(build) {
3102
- build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({
3103
- path: args.path,
3104
- namespace: "sdk-redirect"
3105
- }));
3106
- build.onLoad({
3107
- filter: /.*/,
3108
- namespace: "sdk-redirect"
3109
- }, () => ({
3110
- contents: `
3111
- var __proxy = (typeof window !== 'undefined' && window.__sdk)
3112
- ? window.__sdk
3113
- : new Proxy({}, {
3114
- get: function(_t, p) {
3115
- throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));
3116
- }
3117
- });
3118
- module.exports = __proxy;
3119
- `,
3120
- loader: "js"
3121
- }));
3122
- }
3123
- };
3124
- }
3125
- /**
3126
- * esbuild plugin that intercepts `import … from 'vitest'` and replaces it with
3127
- * a virtual module that delegates every named import to `globalThis` at ACCESS
3128
- * time (not at bundle-evaluation time).
3054
+ * The phone connects to the relay as a `target`; this module connects as a
3055
+ * `client` (the role a CDP frontend would take) so CDP events the page emits
3056
+ * (`Runtime.consoleAPICalled`, `Network.*`) flow back here. We buffer recent
3057
+ * events in ring buffers the tool layer reads via `getBufferedEvents`.
3129
3058
  *
3130
- * The runtime installs `describe/it/test/expect/beforeAll/afterAll/beforeEach/
3131
- * afterEach/vi` as globals inside `runTestModule`, which runs AFTER the bundle
3132
- * IIFE is evaluated. A value-copy redirect (`export var describe =
3133
- * globalThis.describe`) would therefore capture `undefined` at evaluation time
3134
- * and the user's `describe(...)` calls would be no-ops — registering zero tests.
3059
+ * Node-only: imports `ws`. Never bundled into the browser/in-app entries.
3135
3060
  *
3136
- * The fix defers the lookup to call time using per-name **getter** exports.
3137
- * We emit a CommonJS module that:
3138
- * 1. sets `__esModule = true` so esbuild's `__toESM` interop maps each named
3139
- * import directly to a property access on the module (NOT wrapped under a
3140
- * `default` shim which is what happens for a bare Proxy whose own-keys
3141
- * are empty, leaving every named import `undefined`);
3142
- * 2. defines each global name as a getter that reads `globalThis[name]` on
3143
- * every access. So `import { describe } from 'vitest'` compiles to
3144
- * `import_vitest.describe`, whose getter returns the real `describe` only
3145
- * when the factory calls it after `runTestModule` installs the globals.
3061
+ * Attach reliability (#281):
3062
+ * `refreshTargets()` emits an internal 'target:attached' event whenever a
3063
+ * new target is added to the relay. `waitForFirstTarget()` awaits that event
3064
+ * (with a polling-interval fallback) so `start_attach`'s attach wait
3065
+ * resolves deterministically rather than racing between polling rounds.
3066
+ */
3067
+ /** Max events retained per domain ring buffer. */
3068
+ const DEFAULT_BUFFER_SIZE$1 = 500;
3069
+ /**
3070
+ * Substrings that mark a "relay websocket is dead" class error, as produced by
3071
+ * `handleDisconnect('relay WebSocket 연결이 끊겼습니다')` (ws close handler) and
3072
+ * the fail-fast `sendCommand` rejection (`relay에 연결되어 있지 않습니다 (...)`).
3146
3073
  *
3147
- * A plain `module.exports = new Proxy(...)` does NOT work here: esbuild routes
3148
- * the virtual module through `__toESM`, which enumerates own-keys (none on an
3149
- * empty Proxy target) and therefore exposes zero named exports. Explicit getter
3150
- * properties give `__toESM` real keys to map while keeping access lazy.
3074
+ * Exported so callers outside this module (e.g. `test-runner/relay-worker.ts`)
3075
+ * can detect the same error class without hardcoding a fragile full-sentence
3076
+ * match mirrors the `EVALUATE_TIMEOUT_MARKER` precedent in
3077
+ * `test-runner/relay-worker.ts`. Kept in sync with `classifyToolError`'s
3078
+ * `relayDisconnectError` branch in `mcp/errors.ts`.
3151
3079
  */
3152
- function vitestRedirectPlugin() {
3153
- return {
3154
- name: "vitest-redirect",
3155
- setup(build) {
3156
- build.onResolve({ filter: /^vitest$/ }, () => ({
3157
- path: "vitest",
3158
- namespace: "vitest-redirect"
3159
- }));
3160
- build.onLoad({
3161
- filter: /^vitest$/,
3162
- namespace: "vitest-redirect"
3163
- }, () => {
3164
- return {
3165
- contents: `Object.defineProperty(exports, '__esModule', { value: true });\n${VITEST_GLOBAL_NAMES.map((name) => `Object.defineProperty(exports, ${JSON.stringify(name)}, { enumerable: true, get: function() { return globalThis[${JSON.stringify(name)}]; } });`).join("\n")}\n`,
3166
- loader: "js"
3167
- };
3168
- });
3169
- }
3170
- };
3080
+ const RELAY_DISCONNECT_MARKERS = ["relay WebSocket", "relay에 연결되어 있지 않습니다"];
3081
+ /**
3082
+ * Returns true when `message` matches the relay-websocket-dead error class
3083
+ * (socket closed, socket errored, or fail-fast "not connected" rejection).
3084
+ */
3085
+ function isRelayDisconnectMessage(message) {
3086
+ return RELAY_DISCONNECT_MARKERS.some((marker) => message.includes(marker));
3087
+ }
3088
+ function isObject$3(value) {
3089
+ return typeof value === "object" && value !== null;
3090
+ }
3091
+ function parseInbound$1(raw) {
3092
+ let parsed;
3093
+ try {
3094
+ parsed = JSON.parse(raw);
3095
+ } catch {
3096
+ return null;
3097
+ }
3098
+ if (!isObject$3(parsed)) return null;
3099
+ const message = {};
3100
+ if (typeof parsed.id === "number") message.id = parsed.id;
3101
+ if (typeof parsed.method === "string") message.method = parsed.method;
3102
+ if ("params" in parsed) message.params = parsed.params;
3103
+ if ("result" in parsed) message.result = parsed.result;
3104
+ if (isObject$3(parsed.error) && typeof parsed.error.message === "string") message.error = { message: parsed.error.message };
3105
+ return message;
3171
3106
  }
3107
+ const PHASE_1_EVENTS$1 = [
3108
+ "Runtime.consoleAPICalled",
3109
+ "Network.requestWillBeSent",
3110
+ "Network.responseReceived"
3111
+ ];
3172
3112
  /**
3173
- * esbuild plugin that transforms the user test file into a module that exports
3174
- * an async `__userFactory` function. The factory defers the user's top-level
3175
- * test registration code (describe/it/test calls) so it only runs when
3176
- * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
3177
- * installed describe/it/test/expect as globals.
3113
+ * Ring buffer size for `Runtime.exceptionThrown`.
3178
3114
  *
3179
- * Algorithm:
3180
- * - Import declarations and re-export statements are kept at module top-level
3181
- * (the only valid ESM position for static `import`). A statement that spans
3182
- * multiple lines — e.g. a named import with one member per line:
3183
- * import {
3184
- * appLogin,
3185
- * getAnonymousKey,
3186
- * } from '@apps-in-toss/web-framework';
3187
- * is tracked as a single block: every line from the opening `import {` /
3188
- * `export {` through the closing `from '…'` (or side-effect `'…'`) line is
3189
- * kept together at top-level. This prevents the member lines and the
3190
- * closing `} from '…'` line from leaking into the factory body, which would
3191
- * leave an unterminated `import {` at module scope (the #678 env3 failure:
3192
- * esbuild threw `Expected "as" but found "{"` on multi-line SDK imports).
3193
- * - All other lines (describe/it/test calls, local declarations, etc.) are
3194
- * moved into the body of the exported async factory function.
3115
+ * Exceptions are rarer than console messages but each is heavier (stack
3116
+ * trace). 50 is generous enough to cover a crash scenario while keeping
3117
+ * memory bounded.
3195
3118
  *
3196
- * This preserves SDK import resolution (the sdk-redirect plugin processes
3197
- * top-level imports normally) while deferring test registration to the factory.
3119
+ * **Lifecycle note**: the exception buffer intentionally survives `replaced` /
3120
+ * `crashed` / `destroyed` lifecycle events it is NOT cleared on target
3121
+ * transitions. Rationale: an exception fired just before a crash is exactly
3122
+ * the signal we want to preserve for root-cause analysis. The buffer
3123
+ * represents "exceptions seen in this MCP session", not "exceptions in the
3124
+ * current page".
3198
3125
  */
3199
- function userFactoryPlugin(absPath) {
3200
- const NAMESPACE = "user-test-factory";
3201
- return {
3202
- name: "user-test-factory",
3203
- setup(build) {
3204
- build.onResolve({ filter: /^user-test-factory$/ }, () => ({
3205
- path: absPath,
3206
- namespace: NAMESPACE
3207
- }));
3208
- build.onLoad({
3209
- filter: /.*/,
3210
- namespace: NAMESPACE
3211
- }, async (args) => {
3212
- const lines = (await fs.readFile(args.path, "utf8")).split("\n");
3213
- const topLevelLines = [];
3214
- const bodyLines = [];
3215
- const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
3216
- const isImportStart = (trimmed) => trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"");
3217
- const endsStatement = (trimmed) => /['"]\s*;?\s*$/.test(trimmed.replace(/\/\/.*$/, "").trimEnd());
3218
- let inImportBlock = false;
3219
- for (const line of lines) {
3220
- const trimmed = line.trimStart();
3221
- const indent = line.slice(0, line.length - trimmed.length);
3222
- if (inImportBlock) {
3223
- topLevelLines.push(line);
3224
- if (endsStatement(trimmed)) inImportBlock = false;
3225
- continue;
3226
- }
3227
- if (isImportStart(trimmed)) {
3228
- topLevelLines.push(line);
3229
- if (!endsStatement(trimmed)) inImportBlock = true;
3230
- } else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
3231
- else {
3232
- topLevelLines.push(line);
3233
- if (/\bfrom\b/.test(trimmed) ? !endsStatement(trimmed) : trimmed.endsWith("{")) inImportBlock = true;
3234
- }
3235
- else bodyLines.push(line);
3236
- }
3237
- return {
3238
- contents: [
3239
- ...topLevelLines,
3240
- "",
3241
- "// biome-ignore lint: generated factory wrapper",
3242
- "export default async function __userFactory(): Promise<void> {",
3243
- ...bodyLines.map((l) => ` ${l}`),
3244
- "}"
3245
- ].join("\n"),
3246
- loader: "ts",
3247
- resolveDir: path.dirname(absPath)
3248
- };
3249
- });
3250
- }
3251
- };
3252
- }
3126
+ const EXCEPTION_BUFFER_SIZE = 50;
3127
+ /** Default per-command timeout if neither option nor env var is set. */
3128
+ const DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
3253
3129
  /**
3254
- * Returns the absolute filesystem path to the test-runner runtime module
3255
- * (dist/test-runner/runtime.js a fully self-contained page-side bundle).
3256
- *
3257
- * Rolldown code-splitting duplicates this bundling logic into shared chunks
3258
- * emitted at ARBITRARY dist depths: the `devtools-test` CLI pulls it from
3259
- * dist/test-runner/bundle.js (dir = dist/test-runner/), while the `devtools-mcp`
3260
- * daemon (dist/mcp/cli.js) pulls it through a ROOT chunk
3261
- * (dist/debug-server-<hash>.js, dir = dist/). A fixed `..`-hop candidate list
3262
- * is therefore wrong from at least one chunk — the live #697 regression.
3263
- *
3264
- * This resolves WITHOUT assuming chunk depth: from `import.meta.url`'s dir it
3265
- * probes the co-located `runtime.js` and the nested `test-runner/runtime.js`,
3266
- * then ascends one directory at a time (bounded) repeating both probes. The
3267
- * nested probe catches dist/test-runner/runtime.js from the dist/ root level no
3268
- * matter which depth the chunk was hoisted to (root, dist/mcp/, or a future
3269
- * relocation). The build always emits dist/test-runner/runtime.js (tsdown entry
3270
- * `'test-runner/runtime'`; guarded by scripts/check-test-runner-dist.sh).
3271
- *
3272
- * An ABSOLUTE path is returned deliberately: esbuild loads it as a literal file
3273
- * read, bypassing Node module resolution entirely, so this works identically in
3274
- * the npx-daemon context (its own dist tree) and the consumer-CLI context
3275
- * (the mini-app's installed @ait-co/devtools dist) — neither needs the package
3276
- * to be node-resolvable from the caller.
3130
+ * Production CDP connection. Polls the relay for the first attached target,
3131
+ * opens a client websocket to it, enables Phase 1 domains, and buffers events.
3277
3132
  */
3278
- function getRuntimePath() {
3279
- const startDir = path.dirname(fileURLToPath(import.meta.url));
3280
- const RELATIVE_PROBES = [
3281
- ["runtime.js"],
3282
- ["test-runner", "runtime.js"],
3283
- ["runtime.ts"],
3284
- ["test-runner", "runtime.ts"]
3285
- ];
3286
- let dir = startDir;
3287
- for (let i = 0; i < 12; i++) {
3288
- for (const segs of RELATIVE_PROBES) {
3289
- const candidate = path.join(dir, ...segs);
3290
- try {
3291
- accessSync(candidate);
3292
- return candidate;
3293
- } catch {}
3294
- }
3295
- const parent = path.dirname(dir);
3296
- if (parent === dir) break;
3297
- dir = parent;
3133
+ var ChiiCdpConnection = class {
3134
+ /** Authoritative connection kind (issue #348) — relay-backed. */
3135
+ kind = "relay";
3136
+ relayBaseUrl;
3137
+ bufferSize;
3138
+ commandTimeoutMs;
3139
+ totpSecret;
3140
+ emitter = new EventEmitter();
3141
+ buffers = /* @__PURE__ */ new Map();
3142
+ targets = /* @__PURE__ */ new Map();
3143
+ ws = null;
3144
+ connectionState = "idle";
3145
+ nextCommandId = 1;
3146
+ /**
3147
+ * The single active target id under the single-attach model.
3148
+ * Updated by `refreshTargets()` whenever a non-null target is present.
3149
+ * Used to detect a new (different) target attach and evict the previous one.
3150
+ */
3151
+ activeTargetId = null;
3152
+ /** In-flight enableDomains() promise — concurrent callers share it. */
3153
+ enablingPromise = null;
3154
+ /** Pending request→response commands keyed by CDP message id. */
3155
+ pending = /* @__PURE__ */ new Map();
3156
+ /**
3157
+ * Timestamp (ms since epoch) of the most recent crash/destroy/detach event,
3158
+ * or `null` if no crash has been detected since the last `enableDomains()`.
3159
+ */
3160
+ lastCrashDetectedAt = null;
3161
+ /**
3162
+ * Per-target last-seen timestamp (ms since epoch). Updated on any inbound
3163
+ * CDP message carrying data from a target. Keyed by target id.
3164
+ */
3165
+ targetLastSeenAt = /* @__PURE__ */ new Map();
3166
+ /** Active heartbeat interval handle (only when `AIT_CDP_HEARTBEAT_MS` is set). */
3167
+ heartbeatHandle = null;
3168
+ /** Lifecycle event listeners (crash / destroyed / detached). */
3169
+ lifecycleListeners = [];
3170
+ constructor(options) {
3171
+ this.relayBaseUrl = options.relayBaseUrl.replace(/\/$/, "");
3172
+ this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE$1;
3173
+ this.totpSecret = options.totpSecret;
3174
+ const envMs = process.env.AIT_CDP_COMMAND_TIMEOUT_MS ? Number(process.env.AIT_CDP_COMMAND_TIMEOUT_MS) : void 0;
3175
+ this.commandTimeoutMs = (envMs !== void 0 && Number.isFinite(envMs) && envMs > 0 ? envMs : void 0) ?? options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
3176
+ for (const event of PHASE_1_EVENTS$1) this.buffers.set(event, []);
3177
+ this.buffers.set("Runtime.exceptionThrown", []);
3178
+ this.emitter.setMaxListeners(0);
3298
3179
  }
3299
- return path.join(startDir, "runtime.js");
3300
- }
3301
- /**
3302
- * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
3303
- *
3304
- * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
3305
- * - `runTestModule` — the runtime entry (from `runtime.ts`).
3306
- * - `__userFactory` — an async function wrapping the user's test registration
3307
- * code so it runs AFTER `runTestModule` installs the globals.
3308
- *
3309
- * Callers (rpc.ts) invoke:
3310
- * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
3311
- *
3312
- * @param absPath - Absolute path to the user test file.
3313
- * @param opts - Optional bundling overrides.
3314
- */
3315
- async function bundleTestFile(absPath, opts) {
3316
- const globalName = opts?.globalName ?? "__testBundle";
3317
- const extraExternals = opts?.extraExternals ?? [];
3318
- const esbuild = await import("esbuild");
3319
- const runtimePath = getRuntimePath();
3320
- const wrapperContent = [
3321
- `import { runTestModule } from ${JSON.stringify(runtimePath)};`,
3322
- `import __userFactory from "user-test-factory";`,
3323
- `export { runTestModule, __userFactory };`
3324
- ].join("\n");
3325
- const result = await esbuild.build({
3326
- stdin: {
3327
- contents: wrapperContent,
3328
- loader: "ts",
3329
- resolveDir: path.dirname(absPath)
3330
- },
3331
- bundle: true,
3332
- format: "iife",
3333
- globalName,
3334
- platform: "browser",
3335
- target: "es2022",
3336
- write: false,
3337
- plugins: [
3338
- userFactoryPlugin(absPath),
3339
- vitestRedirectPlugin(),
3340
- sdkRedirectPlugin()
3341
- ],
3342
- external: extraExternals,
3343
- treeShaking: true,
3344
- footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
3345
- });
3346
- const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
3347
- const outputFile = result.outputFiles?.[0];
3348
- if (!outputFile) throw new Error("bundleTestFile: esbuild produced no output — check entryPoints");
3349
- return {
3350
- code: outputFile.text,
3351
- warnings
3352
- };
3353
- }
3354
- //#endregion
3355
- //#region src/test-runner/capture.ts
3356
- /** The exact console-line prefix sdk-example's `flushCapture` emits. */
3357
- const CAPTURE_PREFIX = "__AIT_CAPTURE__ ";
3358
- /**
3359
- * Parses raw console line texts into {@link AitCaptureLine}s.
3360
- *
3361
- * Filtering rules (each independently drops a line — never throws):
3362
- * - the line text must `startsWith(CAPTURE_PREFIX)` exactly (allowlist);
3363
- * - there must be a non-empty category token (up to the next space);
3364
- * - the remaining payload must be valid JSON (`JSON.parse` succeeds).
3365
- *
3366
- * Lines that fail any rule (wss/scheme noise, truncated, broken JSON) are
3367
- * silently discarded — capture harvesting is best-effort and must never fail a
3368
- * run or leak a malformed/secret-bearing line.
3369
- *
3370
- * @param raw - Console line objects (only `.text` is read).
3371
- * @returns The captured lines, in input order.
3372
- */
3373
- function parseCaptureLines(raw) {
3374
- const out = [];
3375
- for (const { text } of raw) {
3376
- if (!text.startsWith(CAPTURE_PREFIX)) continue;
3377
- const body = text.slice(16);
3378
- const spaceIdx = body.indexOf(" ");
3379
- if (spaceIdx === -1) continue;
3380
- const category = body.slice(0, spaceIdx);
3381
- const json = body.slice(spaceIdx + 1);
3382
- if (category === "" || json === "") continue;
3383
- try {
3384
- JSON.parse(json);
3385
- } catch {
3386
- continue;
3387
- }
3388
- out.push({
3389
- category,
3390
- json
3391
- });
3392
- }
3393
- return out;
3394
- }
3395
- //#endregion
3396
- //#region src/test-runner/rpc.ts
3397
- /** Maximum milliseconds to wait for a single evaluate round-trip. */
3398
- const DEFAULT_TIMEOUT_MS = 6e4;
3399
- /**
3400
- * Wraps bundle code in a self-executing IIFE that:
3401
- * 1. Evaluates the bundle (registering describe/it/test).
3402
- * 2. Calls `__testBundle.runTestModule(...)` — the entry the runtime exports.
3403
- * 3. Returns a JSON-serialised `RunReport` string.
3404
- *
3405
- * The double-serialisation (RunReport → JSON string → returnByValue string)
3406
- * is intentional: CDP `returnByValue` reliably transports strings; deeply
3407
- * nested objects can lose fidelity across the Chii relay.
3408
- *
3409
- * SECRET-HANDLING: `bundleCode` MUST NOT be logged by callers.
3410
- */
3411
- function buildRunTestsExpression(bundleCode) {
3412
- return `(async () => { try { ${bundleCode} } catch(e) { return JSON.stringify({ok:false,error:'bundle-eval: ' + String(e && e.message || e)}); } if (typeof globalThis.__testBundle !== 'object' || typeof globalThis.__testBundle.runTestModule !== 'function' || typeof globalThis.__testBundle.__userFactory !== 'function') { return JSON.stringify({ok:false,error:'bundle-missing-export: __testBundle.runTestModule or __userFactory is not a function'}); } try { const report = await globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory); return JSON.stringify({ok:true,value:report}); } catch(e) { return JSON.stringify({ok:false,error:'test-run: ' + String(e && e.message || e)}); }})()`;
3413
- }
3414
- /**
3415
- * Parses the raw CDP `returnByValue` result from a `buildRunTestsExpression`
3416
- * evaluate call into a typed `RpcRunResult`.
3417
- *
3418
- * Throws only on parse failure — an `ok:false` envelope is a normal result.
3419
- *
3420
- * SECRET-HANDLING: `rawValue` is not included in error messages.
3421
- */
3422
- function parseRunTestsResult(rawValue) {
3423
- if (typeof rawValue !== "string") throw new Error(`rpc.parseRunTestsResult: unexpected return type "${typeof rawValue}" — expected JSON string`);
3424
- let parsed;
3425
- try {
3426
- parsed = JSON.parse(rawValue);
3427
- } catch {
3428
- throw new Error("rpc.parseRunTestsResult: bridge returned non-JSON string");
3429
- }
3430
- if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("rpc.parseRunTestsResult: parsed result is not an object");
3431
- const obj = parsed;
3432
- if (obj.ok === true) return {
3433
- ok: true,
3434
- report: obj.value
3435
- };
3436
- if (obj.ok === false) return {
3437
- ok: false,
3438
- error: typeof obj.error === "string" ? obj.error : String(obj.error)
3439
- };
3440
- throw new Error("rpc.parseRunTestsResult: result missing \"ok\" field");
3441
- }
3442
- /**
3443
- * Injects `bundleCode` into the attached page and awaits test execution.
3444
- *
3445
- * Uses `Runtime.evaluate` with `awaitPromise: true` to wait for the
3446
- * async IIFE to settle. The 30-second CDP command timeout covers even
3447
- * long-running test suites; split into smaller files if you hit it.
3448
- *
3449
- * @param connection - Active CDP connection (relay or local).
3450
- * @param bundleCode - IIFE bundle string from `bundleTestFile`.
3451
- * @param timeoutMs - Override the default 30 s timeout.
3452
- *
3453
- * SECRET-HANDLING: `bundleCode` and the raw CDP result value are never logged.
3454
- */
3455
- async function injectAndRunBundle(connection, bundleCode, timeoutMs = DEFAULT_TIMEOUT_MS) {
3456
- const expression = buildRunTestsExpression(bundleCode);
3457
- const TIMEOUT_SENTINEL = Symbol("timeout");
3458
- const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(TIMEOUT_SENTINEL), timeoutMs));
3459
- const evalPromise = connection.send("Runtime.evaluate", {
3460
- expression,
3461
- returnByValue: true,
3462
- awaitPromise: true
3463
- });
3464
- const raceResult = await Promise.race([evalPromise.then((v) => ({
3465
- tag: "eval",
3466
- v
3467
- })), timeoutPromise.then(() => ({ tag: "timeout" }))]);
3468
- if (raceResult.tag === "timeout") return {
3469
- ok: false,
3470
- error: `rpc: evaluate timed out after ${timeoutMs}ms`
3471
- };
3472
- const cdpResult = raceResult.v;
3473
- if (cdpResult.exceptionDetails) {
3474
- const msg = cdpResult.exceptionDetails.exception?.description ?? cdpResult.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
3475
- throw new Error(`rpc.injectAndRunBundle: ${msg}`);
3476
- }
3477
- return parseRunTestsResult(cdpResult.result.value);
3478
- }
3479
- //#endregion
3480
- //#region src/test-runner/relay-worker.ts
3481
- /**
3482
- * Sentinel string embedded in the error message by `injectAndRunBundle` when
3483
- * the per-file evaluate race hits the timeout. Used by the retry guard so only
3484
- * genuine timeouts get a second attempt — not bundle errors or parse failures.
3485
- *
3486
- * Exported for unit tests that assert the retry path is taken.
3487
- */
3488
- const EVALUATE_TIMEOUT_MARKER = "rpc: evaluate timed out after";
3489
- /**
3490
- * Runs all `files` sequentially over the given CDP `connection`.
3491
- *
3492
- * For each file:
3493
- * 1. Bundle with esbuild (includes SDK shim + runtime).
3494
- * 2. Inject into the attached page via `Runtime.evaluate`.
3495
- * 3. Await the `RunReport` JSON response.
3496
- * 4. Accumulate results.
3497
- *
3498
- * Returns a `RelayRunReport` with per-file results and flattened totals.
3499
- *
3500
- * This function does NOT open or manage the relay connection — the caller
3501
- * is responsible for attaching and closing it.
3502
- *
3503
- * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here
3504
- * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.
3505
- *
3506
- * @param connection - Active CDP connection (relay or local kind).
3507
- * @param files - Absolute paths to test files, run in order.
3508
- * @param opts - Optional per-run overrides.
3509
- */
3510
- async function runTestFilesOverRelay(connection, files, opts) {
3511
- const wallStart = Date.now();
3512
- const startedAt = new Date(wallStart).toISOString();
3513
- const fileResults = [];
3514
- let domainsEnabled = false;
3515
- try {
3516
- await connection.enableDomains();
3517
- domainsEnabled = true;
3518
- } catch (e) {
3519
- process.stderr.write(`relay-worker: enableDomains() failed before run — console capture may be empty (${e instanceof Error ? e.message : String(e)})\n`);
3520
- }
3521
- const collectCaptures = opts?.collectCaptures === true;
3522
- const liveConsole = [];
3523
- let unsubscribeConsole;
3524
- if (collectCaptures && domainsEnabled) unsubscribeConsole = connection.on("Runtime.consoleAPICalled", (event) => {
3525
- liveConsole.push(event);
3526
- });
3527
- try {
3528
- for (const file of files) {
3529
- let fileEntry;
3530
- try {
3531
- const { code } = await bundleTestFile(file, opts?.bundleOptions);
3532
- /**
3533
- * Runs one evaluate attempt and returns a FileResult, or `null` when the
3534
- * result is a genuine timeout and the caller should retry.
3535
- *
3536
- * We need to distinguish:
3537
- * - `rpcResult.ok = false` + timeout error → retry candidate (`return null`)
3538
- * - `rpcResult.ok = false` + other error → final error, no retry
3539
- * - `injectAndRunBundle` throws → CDP exceptionDetails (page
3540
- * engine threw); treated as a final (non-retryable) error.
3541
- *
3542
- * The Promise.race timeout in rpc.ts RETURNS `{ok:false, error: '…'}` (it
3543
- * does NOT throw/reject). Only genuine CDP `exceptionDetails` cause a throw.
3544
- * This distinction is what makes the EVALUATE_TIMEOUT_MARKER gate below
3545
- * reachable — the timeout result surfaces as `rpcResult.ok=false` with the
3546
- * marker string, not as a caught exception.
3547
- */
3548
- const attempt = async () => {
3549
- let rpcResult;
3550
- try {
3551
- rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
3552
- } catch (e) {
3553
- return {
3554
- file,
3555
- result: { error: e instanceof Error ? e.message : String(e) }
3556
- };
3557
- }
3558
- if (rpcResult.ok) return {
3559
- file,
3560
- result: rpcResult.report
3561
- };
3562
- if (rpcResult.error.includes("rpc: evaluate timed out after")) return null;
3563
- return {
3564
- file,
3565
- result: { error: rpcResult.error }
3566
- };
3567
- };
3568
- const firstResult = await attempt();
3569
- if (firstResult !== null) fileEntry = firstResult;
3570
- else {
3571
- process.stderr.write(`relay-worker: evaluate timed out for ${file} — retrying once\n`);
3572
- const retryResult = await attempt();
3573
- if (retryResult !== null) fileEntry = retryResult;
3574
- else fileEntry = {
3575
- file,
3576
- result: { error: `${EVALUATE_TIMEOUT_MARKER} ${opts?.timeoutMs ?? 3e4}ms (after retry)` }
3577
- };
3578
- }
3579
- } catch (e) {
3580
- fileEntry = {
3581
- file,
3582
- result: { error: e instanceof Error ? e.message : String(e) }
3583
- };
3584
- }
3585
- fileResults.push(fileEntry);
3586
- }
3587
- } finally {
3588
- unsubscribeConsole?.();
3589
- }
3590
- const captures = collectCaptures ? parseCaptureLines(liveConsole.map((e) => ({ text: renderConsoleLineText(e) }))) : [];
3591
- const totals = fileResults.reduce((acc, { result }) => {
3592
- if ("error" in result) {
3593
- acc.failed += 1;
3594
- acc.total += 1;
3595
- } else {
3596
- acc.passed += result.passed;
3597
- acc.failed += result.failed;
3598
- acc.skipped += result.skipped;
3599
- acc.total += result.passed + result.failed + result.skipped;
3600
- }
3601
- return acc;
3602
- }, {
3603
- passed: 0,
3604
- failed: 0,
3605
- skipped: 0,
3606
- total: 0
3607
- });
3608
- return {
3609
- startedAt,
3610
- duration: Date.now() - wallStart,
3611
- files: fileResults,
3612
- totals,
3613
- captures
3614
- };
3615
- }
3616
- /**
3617
- * Renders one `Runtime.consoleAPICalled` event to a single line of text, the
3618
- * same way `tools.ts#normalizeConsoleMessage` does (args rendered + space-
3619
- * joined). Inlined here (≈8 lines) so this module avoids importing `tools.ts`,
3620
- * which would drag the heavy MCP/Node graph (server-lock, parent-watcher, …)
3621
- * onto the test-runner entry.
3622
- *
3623
- * SECRET-HANDLING: this only stringifies console args; the caller's
3624
- * allowlist-prefix parser then discards everything that is not a genuine
3625
- * `__AIT_CAPTURE__` line.
3626
- */
3627
- function renderConsoleLineText(event) {
3628
- return event.args.map((arg) => {
3629
- if (arg.value !== void 0) {
3630
- if (typeof arg.value === "string") return arg.value;
3631
- try {
3632
- return JSON.stringify(arg.value);
3633
- } catch {
3634
- return String(arg.value);
3635
- }
3636
- }
3637
- if (arg.description !== void 0) return arg.description;
3638
- if (arg.className !== void 0) return arg.className;
3639
- return arg.subtype ?? arg.type;
3640
- }).join(" ");
3641
- }
3642
- `
3643
- devtools-test — run mini-app tests on a real device WebView over the CDP relay
3644
-
3645
- USAGE
3646
- devtools-test <glob> [<glob> ...] [options]
3647
-
3648
- OPTIONS
3649
- --scheme-url <url> intoss-private:// URL from \`ait deploy --scheme-only\`
3650
- (required for standalone relay attach / env3)
3651
- --timeout <ms> Per-file evaluate timeout in ms (default: 30000).
3652
- Controls how long a single test file is allowed to run
3653
- before it is considered hung. Does NOT affect how long
3654
- the CLI waits for a human to scan the QR code — use
3655
- --attach-timeout for that.
3656
- --attach-timeout <ms> How long to wait for a human to scan the QR code with
3657
- their phone (default: 600000 — 10 minutes). Omit to
3658
- use the relay factory's generous default. Decrease for
3659
- CI environments where a scan should arrive quickly.
3660
- --cell-sdk-line <line> SDK line to inject as __AIT_CELL__.sdkLine (2.x|3.x)
3661
- --cell-platform <plat> Platform to inject as __AIT_CELL__.platform
3662
- (mock|ios|android, default: AIT_CELL_PLATFORM env)
3663
- --report-dir <dir> Persist a runner-agnostic report + captures to <dir>
3664
- (report: <sdkLine>.<platform>.json; captures:
3665
- <dir>/.ait-capture/<category>.<sdkLine>.<platform>.json).
3666
- Omitted = nothing saved. Enables console capture.
3667
- --no-qr-stdout Suppress the QR/attach block on stdout (auto-on for
3668
- non-interactive stdout / CI / AIT_NO_QR_STDOUT)
3669
- --headless Disable browser auto-open (text QR only)
3670
- --project-root <dir> Project root for .ait_relay secret lookup
3671
- (default: current working directory)
3672
- --help, -h Show this help message
3673
-
3674
- DESCRIPTION
3675
- Boots a Chii relay + cloudflared tunnel, renders a QR code, waits for a real
3676
- device to scan and attach, injects the cell globals (__AIT_CELL__), bundles
3677
- each matched test file with esbuild (SDK imports redirected to window.__sdk),
3678
- injects the bundle into the attached WebView via Runtime.evaluate, and prints
3679
- a summary.
3680
-
3681
- With --report-dir, also harvests __AIT_CAPTURE__ console lines and writes a
3682
- runner-agnostic report + per-category capture files so 2.x↔3.0 runs can be
3683
- compared offline.
3684
-
3685
- The test files run against the live relay connection started by this process;
3686
- no separate MCP daemon is required.
3687
-
3688
- EXAMPLE
3689
- devtools-test 'src/**/*.ait.test.ts' \\
3690
- --scheme-url "intoss-private://..." \\
3691
- --cell-sdk-line 3.x \\
3692
- --cell-platform ios \\
3693
- --report-dir .ait-report \\
3694
- --timeout 60000
3695
-
3696
- `.trimStart();
3697
- /**
3698
- * Renders per-file result lines and the aggregate totals line to a string.
3699
- *
3700
- * Each file gets one line:
3701
- * - Error/timeout: `FAIL <basename>: <error-class>`
3702
- * - Pass (0 tests): `OK <basename>: 0 passed (empty file)`
3703
- * - Pass: `OK <basename>: N passed[, M failed][, K skipped]`
3704
- *
3705
- * The aggregate totals line always follows.
3706
- *
3707
- * SECRET-HANDLING: only `basename(file)` is used — no absolute paths, relay
3708
- * URLs, wss URLs, scheme URLs, or TOTP codes appear in the output. The error
3709
- * string comes from `result.error` which is already secret-free (relay-worker
3710
- * produces only error-class messages like "rpc: evaluate timed out after
3711
- * 30000ms").
3712
- *
3713
- * Exported so unit tests can assert the per-file lines without spawning a
3714
- * subprocess or going through the full relay attach flow.
3715
- */
3716
- function renderSummary(report) {
3717
- const lines = [];
3718
- for (const { file, result } of report.files) {
3719
- const name = basename(file);
3720
- if ("error" in result) lines.push(`FAIL ${name}: ${result.error}`);
3721
- else {
3722
- const parts = [`${result.passed} passed`];
3723
- if (result.failed > 0) parts.push(`${result.failed} failed`);
3724
- if (result.skipped > 0) parts.push(`${result.skipped} skipped`);
3725
- const suffix = result.passed + result.failed + result.skipped === 0 ? " (empty file)" : "";
3726
- lines.push(`OK ${name}: ${parts.join(", ")}${suffix}`);
3727
- }
3728
- }
3729
- const { totals, duration } = report;
3730
- lines.push(`\ndevtools-test: ${totals.passed} passed, ${totals.failed} failed, ${totals.skipped} skipped (${duration}ms)`);
3731
- return lines.join("\n");
3732
- }
3733
- /**
3734
- * Runs `files` over `connection` and returns the aggregate report.
3735
- * This pure function is the testable core of the CLI (and is what the
3736
- * `run_tests` MCP tool calls against the daemon's attached connection); it is
3737
- * separate from `main()` so tests can call it without spawning a subprocess.
3738
- */
3739
- async function runWithConnection(connection, files, opts) {
3740
- const report = await runTestFilesOverRelay(connection, files, opts);
3741
- if (opts?.printSummary) process.stdout.write(`\n${renderSummary(report)}\n`);
3742
- return report;
3743
- }
3744
- //#endregion
3745
- //#region src/mcp/ait-chii-source.ts
3746
- function isObject$3(value) {
3747
- return typeof value === "object" && value !== null;
3748
- }
3749
- /** Narrows an `AIT.getSdkCallHistory` response, tolerating a missing array. */
3750
- function asSdkCallHistory(raw) {
3751
- if (isObject$3(raw) && Array.isArray(raw.calls)) return { calls: raw.calls };
3752
- return { calls: [] };
3753
- }
3754
- /** Narrows an `AIT.getMockState` response to an opaque record. */
3755
- function asMockState(raw) {
3756
- return isObject$3(raw) ? raw : {};
3757
- }
3758
- /** Narrows an `AIT.getOperationalEnvironment` response. */
3759
- function asOperationalEnvironment(raw) {
3760
- return {
3761
- environment: isObject$3(raw) && typeof raw.environment === "string" ? raw.environment : "unknown",
3762
- sdkVersion: isObject$3(raw) && typeof raw.sdkVersion === "string" ? raw.sdkVersion : null
3763
- };
3764
- }
3765
- var ChiiAitSource = class {
3766
- constructor(sender) {
3767
- this.sender = sender;
3768
- }
3769
- async get(method) {
3770
- const raw = await this.sender.sendCommand(method);
3771
- switch (method) {
3772
- case "AIT.getSdkCallHistory": return asSdkCallHistory(raw);
3773
- case "AIT.getMockState": return asMockState(raw);
3774
- case "AIT.getOperationalEnvironment": return asOperationalEnvironment(raw);
3775
- default: throw new Error(`Unknown AIT method: ${String(method)}`);
3776
- }
3777
- }
3778
- };
3779
- //#endregion
3780
- //#region src/shared/relay-auth-close.ts
3781
- /**
3782
- * Shared constants for the relay's named TOTP-auth rejection (issue #478).
3783
- *
3784
- * Before #478 the relay rejected an unauthenticated WebSocket upgrade with a
3785
- * raw `HTTP/1.1 401` + `socket.destroy()`. A handshake aborted that way is
3786
- * indistinguishable from a network failure on the browser side — the
3787
- * WebSocket only ever sees close code 1006, so the phone (env-2 launcher PWA)
3788
- * could not tell "stale TOTP code" apart from "tunnel down" and stayed
3789
- * silent. The fix is accept-then-close: complete the handshake, then close
3790
- * with an application close code that NAMES the rejection.
3791
- *
3792
- * Three parties share this contract:
3793
- * - `src/mcp/chii-relay.ts` (Node) sends the close frame / HTTP error body;
3794
- * - `src/in-app/attach.ts` (browser) observes relay-bound WebSockets and
3795
- * surfaces the code to the launcher shell;
3796
- * - `src/mcp/chii-connection.ts` (Node daemon client) recognises the code
3797
- * as an auth failure on its own `/client` dial (defensive — #439's fresh
3798
- * code mint means it should not normally hit this).
3799
- *
3800
- * This module is intentionally dependency-free (no Node, no DOM) so it is
3801
- * safe to import from both the browser in-app bundle and the MCP daemon
3802
- * bundle.
3803
- *
3804
- * SECRET-HANDLING: these are fixed enum values. The close reason / error body
3805
- * must never grow to carry a secret, a TOTP code, or a host.
3806
- */
3807
- /**
3808
- * WebSocket close code sent by the relay when TOTP auth is rejected.
3809
- *
3810
- * 4000–4999 is the application-reserved range (RFC 6455 §7.4.2); 4401 mirrors
3811
- * HTTP 401 so it reads as "unauthorized" at a glance.
3812
- */
3813
- const RELAY_AUTH_REJECT_CLOSE_CODE = 4401;
3814
- /**
3815
- * Close reason string accompanying {@link RELAY_AUTH_REJECT_CLOSE_CODE}, and
3816
- * the `error` value of the relay's HTTP 401 JSON body. Enum string only —
3817
- * never interpolated with request data.
3818
- */
3819
- const RELAY_AUTH_REJECT_REASON = "totp-rejected";
3820
- //#endregion
3821
- //#region src/mcp/chii-connection.ts
3822
- /**
3823
- * Production `CdpConnection` backed by the local Chii relay.
3824
- *
3825
- * Topology (debug mode):
3826
- * phone target.js --WS--> Chii relay :9100 <--WS-- this connection
3827
- *
3828
- * The phone connects to the relay as a `target`; this module connects as a
3829
- * `client` (the role a CDP frontend would take) so CDP events the page emits
3830
- * (`Runtime.consoleAPICalled`, `Network.*`) flow back here. We buffer recent
3831
- * events in ring buffers the tool layer reads via `getBufferedEvents`.
3832
- *
3833
- * Node-only: imports `ws`. Never bundled into the browser/in-app entries.
3834
- *
3835
- * Attach reliability (#281):
3836
- * `refreshTargets()` emits an internal 'target:attached' event whenever a
3837
- * new target is added to the relay. `waitForFirstTarget()` awaits that event
3838
- * (with a polling-interval fallback) so `start_attach`'s attach wait
3839
- * resolves deterministically rather than racing between polling rounds.
3840
- */
3841
- /** Max events retained per domain ring buffer. */
3842
- const DEFAULT_BUFFER_SIZE$1 = 500;
3843
- function isObject$2(value) {
3844
- return typeof value === "object" && value !== null;
3845
- }
3846
- function parseInbound$1(raw) {
3847
- let parsed;
3848
- try {
3849
- parsed = JSON.parse(raw);
3850
- } catch {
3851
- return null;
3852
- }
3853
- if (!isObject$2(parsed)) return null;
3854
- const message = {};
3855
- if (typeof parsed.id === "number") message.id = parsed.id;
3856
- if (typeof parsed.method === "string") message.method = parsed.method;
3857
- if ("params" in parsed) message.params = parsed.params;
3858
- if ("result" in parsed) message.result = parsed.result;
3859
- if (isObject$2(parsed.error) && typeof parsed.error.message === "string") message.error = { message: parsed.error.message };
3860
- return message;
3861
- }
3862
- const PHASE_1_EVENTS$1 = [
3863
- "Runtime.consoleAPICalled",
3864
- "Network.requestWillBeSent",
3865
- "Network.responseReceived"
3866
- ];
3867
- /**
3868
- * Ring buffer size for `Runtime.exceptionThrown`.
3869
- *
3870
- * Exceptions are rarer than console messages but each is heavier (stack
3871
- * trace). 50 is generous enough to cover a crash scenario while keeping
3872
- * memory bounded.
3873
- *
3874
- * **Lifecycle note**: the exception buffer intentionally survives `replaced` /
3875
- * `crashed` / `destroyed` lifecycle events — it is NOT cleared on target
3876
- * transitions. Rationale: an exception fired just before a crash is exactly
3877
- * the signal we want to preserve for root-cause analysis. The buffer
3878
- * represents "exceptions seen in this MCP session", not "exceptions in the
3879
- * current page".
3880
- */
3881
- const EXCEPTION_BUFFER_SIZE = 50;
3882
- /** Default per-command timeout if neither option nor env var is set. */
3883
- const DEFAULT_COMMAND_TIMEOUT_MS = 3e4;
3884
- /**
3885
- * Production CDP connection. Polls the relay for the first attached target,
3886
- * opens a client websocket to it, enables Phase 1 domains, and buffers events.
3887
- */
3888
- var ChiiCdpConnection = class {
3889
- /** Authoritative connection kind (issue #348) — relay-backed. */
3890
- kind = "relay";
3891
- relayBaseUrl;
3892
- bufferSize;
3893
- commandTimeoutMs;
3894
- totpSecret;
3895
- emitter = new EventEmitter();
3896
- buffers = /* @__PURE__ */ new Map();
3897
- targets = /* @__PURE__ */ new Map();
3898
- ws = null;
3899
- connectionState = "idle";
3900
- nextCommandId = 1;
3901
- /**
3902
- * The single active target id under the single-attach model.
3903
- * Updated by `refreshTargets()` whenever a non-null target is present.
3904
- * Used to detect a new (different) target attach and evict the previous one.
3905
- */
3906
- activeTargetId = null;
3907
- /** In-flight enableDomains() promise — concurrent callers share it. */
3908
- enablingPromise = null;
3909
- /** Pending request→response commands keyed by CDP message id. */
3910
- pending = /* @__PURE__ */ new Map();
3911
- /**
3912
- * Timestamp (ms since epoch) of the most recent crash/destroy/detach event,
3913
- * or `null` if no crash has been detected since the last `enableDomains()`.
3914
- */
3915
- lastCrashDetectedAt = null;
3916
- /**
3917
- * Per-target last-seen timestamp (ms since epoch). Updated on any inbound
3918
- * CDP message carrying data from a target. Keyed by target id.
3919
- */
3920
- targetLastSeenAt = /* @__PURE__ */ new Map();
3921
- /** Active heartbeat interval handle (only when `AIT_CDP_HEARTBEAT_MS` is set). */
3922
- heartbeatHandle = null;
3923
- /** Lifecycle event listeners (crash / destroyed / detached). */
3924
- lifecycleListeners = [];
3925
- constructor(options) {
3926
- this.relayBaseUrl = options.relayBaseUrl.replace(/\/$/, "");
3927
- this.bufferSize = options.bufferSize ?? DEFAULT_BUFFER_SIZE$1;
3928
- this.totpSecret = options.totpSecret;
3929
- const envMs = process.env.AIT_CDP_COMMAND_TIMEOUT_MS ? Number(process.env.AIT_CDP_COMMAND_TIMEOUT_MS) : void 0;
3930
- this.commandTimeoutMs = (envMs !== void 0 && Number.isFinite(envMs) && envMs > 0 ? envMs : void 0) ?? options.commandTimeoutMs ?? DEFAULT_COMMAND_TIMEOUT_MS;
3931
- for (const event of PHASE_1_EVENTS$1) this.buffers.set(event, []);
3932
- this.buffers.set("Runtime.exceptionThrown", []);
3933
- this.emitter.setMaxListeners(0);
3934
- }
3935
- /** Refresh the attached-target list from the relay's `GET /targets`. */
3936
- async refreshTargets() {
3937
- let targetsUrl = `${this.relayBaseUrl}/targets`;
3938
- if (this.totpSecret) {
3939
- const code = generateTotp(this.totpSecret);
3940
- targetsUrl += `?at=${encodeURIComponent(code)}`;
3180
+ /** Refresh the attached-target list from the relay's `GET /targets`. */
3181
+ async refreshTargets() {
3182
+ let targetsUrl = `${this.relayBaseUrl}/targets`;
3183
+ if (this.totpSecret) {
3184
+ const code = generateTotp(this.totpSecret);
3185
+ targetsUrl += `?at=${encodeURIComponent(code)}`;
3941
3186
  }
3942
3187
  const res = await fetch(targetsUrl);
3943
3188
  if (!res.ok) throw new Error(`Chii relay /targets returned HTTP ${res.status} ${res.statusText}`);
3944
3189
  const body = await res.json();
3945
- const list = isObject$2(body) && Array.isArray(body.targets) ? body.targets : [];
3190
+ const list = isObject$3(body) && Array.isArray(body.targets) ? body.targets : [];
3946
3191
  let newestTargetId = null;
3947
3192
  for (const item of list) {
3948
- if (!isObject$2(item) || typeof item.id !== "string") continue;
3193
+ if (!isObject$3(item) || typeof item.id !== "string") continue;
3949
3194
  newestTargetId = item.id;
3950
3195
  }
3951
3196
  if (newestTargetId !== null && this.activeTargetId !== null && newestTargetId !== this.activeTargetId) {
@@ -3955,7 +3200,7 @@ var ChiiCdpConnection = class {
3955
3200
  }
3956
3201
  this.targets.clear();
3957
3202
  for (const item of list) {
3958
- if (!isObject$2(item) || typeof item.id !== "string") continue;
3203
+ if (!isObject$3(item) || typeof item.id !== "string") continue;
3959
3204
  if (item.id !== newestTargetId) continue;
3960
3205
  this.targets.set(item.id, {
3961
3206
  id: item.id,
@@ -4114,211 +3359,1019 @@ var ChiiCdpConnection = class {
4114
3359
  return this.sendCommand(method, params ?? {});
4115
3360
  }
4116
3361
  /**
4117
- * Issue an arbitrary request→response command over the relay and resolve with
4118
- * its raw result. Both the typed CDP {@link send} and the AIT domain (Phase 3
4119
- * `AIT.*` methods, forwarded over the same Chii channel) build on this.
3362
+ * Issue an arbitrary request→response command over the relay and resolve with
3363
+ * its raw result. Both the typed CDP {@link send} and the AIT domain (Phase 3
3364
+ * `AIT.*` methods, forwarded over the same Chii channel) build on this.
3365
+ *
3366
+ * Rejects immediately if the connection is disconnected (fail-fast — no
3367
+ * auto-reconnect). Caller should re-run `list_pages` or `enableDomains` to
3368
+ * reattach.
3369
+ *
3370
+ * Times out after `commandTimeoutMs` (default 30s, env
3371
+ * `AIT_CDP_COMMAND_TIMEOUT_MS`). On timeout the pending entry is cleaned up
3372
+ * and the promise rejects with a descriptive Korean error.
3373
+ */
3374
+ sendCommand(method, params = {}) {
3375
+ if (this.connectionState === "disconnected") return Promise.reject(/* @__PURE__ */ new Error(`relay에 연결되어 있지 않습니다 (${method}). list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`));
3376
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return Promise.reject(/* @__PURE__ */ new Error("No mini-app page attached to the Chii relay yet. Call enableDomains() first."));
3377
+ const id = this.nextCommandId++;
3378
+ const ws = this.ws;
3379
+ const timeoutMs = this.commandTimeoutMs;
3380
+ return new Promise((resolve, reject) => {
3381
+ const handle = setTimeout(() => {
3382
+ this.pending.delete(id);
3383
+ reject(/* @__PURE__ */ new Error(`CDP 명령이 타임아웃됐습니다 (${method}, ${timeoutMs}ms). 폰 측 토스 앱이 백그라운드로 내려갔거나 미니앱이 unload됐을 수 있습니다. list_pages로 attach 상태를 확인하세요.`));
3384
+ }, timeoutMs);
3385
+ this.pending.set(id, {
3386
+ resolve: (v) => {
3387
+ clearTimeout(handle);
3388
+ resolve(v);
3389
+ },
3390
+ reject: (e) => {
3391
+ clearTimeout(handle);
3392
+ reject(e);
3393
+ }
3394
+ });
3395
+ ws.send(JSON.stringify({
3396
+ id,
3397
+ method,
3398
+ params
3399
+ }));
3400
+ });
3401
+ }
3402
+ /**
3403
+ * Called on WebSocket `close` or `error` after a successful connection.
3404
+ * Rejects all pending commands and marks the connection as disconnected so
3405
+ * subsequent `sendCommand` calls fail fast (no auto-reconnect).
3406
+ */
3407
+ handleDisconnect(reason) {
3408
+ if (this.connectionState === "disconnected") return;
3409
+ this.connectionState = "disconnected";
3410
+ this.ws = null;
3411
+ this.stopHeartbeat();
3412
+ const err = /* @__PURE__ */ new Error(`${reason}. list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`);
3413
+ for (const waiter of this.pending.values()) waiter.reject(err);
3414
+ this.pending.clear();
3415
+ }
3416
+ /**
3417
+ * Evict a previously active target under the single-attach model.
3418
+ * Rejects pending commands with a 'replaced-by-new-attach' reason and emits
3419
+ * a 'replaced' lifecycle event. Does NOT clear all targets — only the specific
3420
+ * targetId. The caller is responsible for rebuilding the targets map afterwards.
3421
+ *
3422
+ * The error message uses 'replaced-by-new-attach' so test assertions can match it.
3423
+ */
3424
+ evictTarget(targetId) {
3425
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
3426
+ this.targets.delete(targetId);
3427
+ this.targetLastSeenAt.delete(targetId);
3428
+ const err = /* @__PURE__ */ new Error(`[ait-debug] replaced-by-new-attach — 이전 page 세션이 새 attach로 교체됐습니다 (targetId=${targetId}). list_pages로 현재 attach 상태를 확인하세요.`);
3429
+ for (const waiter of this.pending.values()) waiter.reject(err);
3430
+ this.pending.clear();
3431
+ const event = {
3432
+ kind: "replaced",
3433
+ targetId,
3434
+ detectedAt
3435
+ };
3436
+ for (const listener of this.lifecycleListeners) try {
3437
+ listener(event);
3438
+ } catch {}
3439
+ }
3440
+ /**
3441
+ * Handle a page-level crash or target destruction event.
3442
+ * Removes the target from the in-memory map, rejects all pending commands,
3443
+ * and emits a lifecycle event.
3444
+ *
3445
+ * @param kind - Event kind: 'crashed' | 'destroyed' | 'detached'
3446
+ * @param targetId - The target ID from the event params (may be null for
3447
+ * Inspector.targetCrashed which has no targetId in the params).
3448
+ */
3449
+ handleTargetGone(kind, targetId) {
3450
+ const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
3451
+ this.lastCrashDetectedAt = Date.now();
3452
+ if (targetId !== null) {
3453
+ this.targets.delete(targetId);
3454
+ this.targetLastSeenAt.delete(targetId);
3455
+ if (this.activeTargetId === targetId) this.activeTargetId = null;
3456
+ } else {
3457
+ this.targets.clear();
3458
+ this.targetLastSeenAt.clear();
3459
+ this.activeTargetId = null;
3460
+ }
3461
+ const err = /* @__PURE__ */ new Error(`[ait-debug] ${kind === "crashed" ? "page crash (Inspector.targetCrashed)" : kind === "destroyed" ? "target 종료 (Target.targetDestroyed)" : "target detach (Target.detachedFromTarget)"} 감지됨 — relay에서 제거됐습니다. 새 attach가 필요합니다 (list_pages로 확인 → enableDomains()로 재연결).`);
3462
+ for (const waiter of this.pending.values()) waiter.reject(err);
3463
+ this.pending.clear();
3464
+ const event = {
3465
+ kind,
3466
+ targetId,
3467
+ detectedAt
3468
+ };
3469
+ for (const listener of this.lifecycleListeners) try {
3470
+ listener(event);
3471
+ } catch {}
3472
+ }
3473
+ /**
3474
+ * Start the optional CDP heartbeat loop.
4120
3475
  *
4121
- * Rejects immediately if the connection is disconnected (fail-fast no
4122
- * auto-reconnect). Caller should re-run `list_pages` or `enableDomains` to
4123
- * reattach.
3476
+ * When `AIT_CDP_HEARTBEAT_MS` is set to a positive integer, every interval
3477
+ * we send `Runtime.evaluate({expression: '1'})` to each active target. If
3478
+ * the command times out (2 s hard deadline) or errors, we treat the target
3479
+ * as dead and call `handleTargetGone`.
4124
3480
  *
4125
- * Times out after `commandTimeoutMs` (default 30s, env
4126
- * `AIT_CDP_COMMAND_TIMEOUT_MS`). On timeout the pending entry is cleaned up
4127
- * and the promise rejects with a descriptive Korean error.
3481
+ * This is a zombie-detector fallback: cloudflared keeps-alive the tunnel ws
3482
+ * even when the phone app has crashed, so the ws-level disconnect (#252) won't
3483
+ * fire. The heartbeat catches this gap.
3484
+ *
3485
+ * Default: OFF. Only activates when `AIT_CDP_HEARTBEAT_MS` is set.
4128
3486
  */
4129
- sendCommand(method, params = {}) {
4130
- if (this.connectionState === "disconnected") return Promise.reject(/* @__PURE__ */ new Error(`relay에 연결되어 있지 않습니다 (${method}). list_pages로 attach 상태를 확인하고 enableDomains()로 재연결하세요.`));
4131
- if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return Promise.reject(/* @__PURE__ */ new Error("No mini-app page attached to the Chii relay yet. Call enableDomains() first."));
4132
- const id = this.nextCommandId++;
3487
+ startHeartbeat(initialTargetId) {
3488
+ this.stopHeartbeat();
3489
+ const envMs = process.env.AIT_CDP_HEARTBEAT_MS ? Number(process.env.AIT_CDP_HEARTBEAT_MS) : void 0;
3490
+ if (envMs === void 0 || !Number.isFinite(envMs) || envMs <= 0) return;
3491
+ const PING_TIMEOUT_MS = 2e3;
3492
+ this.heartbeatHandle = setInterval(() => {
3493
+ const targetIds = this.targets.size > 0 ? [...this.targets.keys()] : [initialTargetId];
3494
+ for (const targetId of targetIds) {
3495
+ const pingPromise = this.sendCommand("Runtime.evaluate", {
3496
+ expression: "1",
3497
+ returnByValue: true,
3498
+ timeout: PING_TIMEOUT_MS
3499
+ });
3500
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("heartbeat timeout")), PING_TIMEOUT_MS + 500));
3501
+ Promise.race([pingPromise, timeoutPromise]).catch(() => {
3502
+ if (this.targets.has(targetId)) this.handleTargetGone("destroyed", targetId);
3503
+ });
3504
+ }
3505
+ }, envMs);
3506
+ }
3507
+ stopHeartbeat() {
3508
+ if (this.heartbeatHandle !== null) {
3509
+ clearInterval(this.heartbeatHandle);
3510
+ this.heartbeatHandle = null;
3511
+ }
3512
+ }
3513
+ handleMessage(raw) {
3514
+ const message = parseInbound$1(raw);
3515
+ if (!message) return;
3516
+ if (typeof message.id === "number" && this.pending.has(message.id)) {
3517
+ const waiter = this.pending.get(message.id);
3518
+ this.pending.delete(message.id);
3519
+ if (waiter) if (message.error) waiter.reject(new Error(message.error.message));
3520
+ else waiter.resolve(message.result);
3521
+ return;
3522
+ }
3523
+ const now = Date.now();
3524
+ let firstMessageSeen = false;
3525
+ for (const targetId of this.targets.keys()) {
3526
+ if (!this.targetLastSeenAt.has(targetId)) firstMessageSeen = true;
3527
+ this.targetLastSeenAt.set(targetId, now);
3528
+ }
3529
+ if (firstMessageSeen && this.targets.size > 0) this.emitter.emit("target:attached", [...this.targets.values()]);
3530
+ if (typeof message.method !== "string") return;
3531
+ if (message.method === "Inspector.targetCrashed") {
3532
+ this.handleTargetGone("crashed", null);
3533
+ return;
3534
+ }
3535
+ if (message.method === "Target.targetDestroyed") {
3536
+ const targetId = isObject$3(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
3537
+ this.handleTargetGone("destroyed", targetId);
3538
+ return;
3539
+ }
3540
+ if (message.method === "Target.detachedFromTarget") {
3541
+ const targetId = isObject$3(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
3542
+ this.handleTargetGone("detached", targetId);
3543
+ return;
3544
+ }
3545
+ if (!this.buffers.has(message.method)) return;
3546
+ const event = message.method;
3547
+ const buffer = this.buffers.get(event);
3548
+ if (!buffer) return;
3549
+ buffer.push(message.params);
3550
+ const cap = event === "Runtime.exceptionThrown" ? EXCEPTION_BUFFER_SIZE : this.bufferSize;
3551
+ if (buffer.length > cap) buffer.shift();
3552
+ this.emitter.emit(event, message.params);
3553
+ }
3554
+ getBufferedEvents(event) {
3555
+ return this.buffers.get(event) ?? [];
3556
+ }
3557
+ on(event, listener) {
3558
+ this.emitter.on(event, listener);
3559
+ return () => this.emitter.off(event, listener);
3560
+ }
3561
+ /** Close the relay client websocket and reject any in-flight commands. */
3562
+ close() {
4133
3563
  const ws = this.ws;
4134
- const timeoutMs = this.commandTimeoutMs;
4135
- return new Promise((resolve, reject) => {
4136
- const handle = setTimeout(() => {
4137
- this.pending.delete(id);
4138
- reject(/* @__PURE__ */ new Error(`CDP 명령이 타임아웃됐습니다 (${method}, ${timeoutMs}ms). 폰 측 토스 앱이 백그라운드로 내려갔거나 미니앱이 unload됐을 수 있습니다. list_pages로 attach 상태를 확인하세요.`));
4139
- }, timeoutMs);
4140
- this.pending.set(id, {
4141
- resolve: (v) => {
4142
- clearTimeout(handle);
4143
- resolve(v);
4144
- },
4145
- reject: (e) => {
4146
- clearTimeout(handle);
4147
- reject(e);
4148
- }
3564
+ this.stopHeartbeat();
3565
+ this.handleDisconnect("Chii relay connection closed");
3566
+ ws?.close();
3567
+ }
3568
+ };
3569
+ //#endregion
3570
+ //#region src/test-runner/bundle.ts
3571
+ /**
3572
+ * esbuild-based bundler for user test files.
3573
+ *
3574
+ * Bundles a single test file into a self-contained IIFE string that can be
3575
+ * injected into a WebView via `Runtime.evaluate`. The bundle includes the
3576
+ * test runtime (`runtime.ts`), which provides `describe/it/test/expect` and
3577
+ * the `runTestModule(factory)` entry point.
3578
+ *
3579
+ * ## How the wiring works
3580
+ *
3581
+ * The bundle exposes two exports on `globalThis.__testBundle`:
3582
+ * - `runTestModule` — the runtime's entry function.
3583
+ * - `__userFactory` — an async function whose body is the user's top-level
3584
+ * test registration code (describe/it/test calls).
3585
+ *
3586
+ * The Node-side RPC (`rpc.ts`) calls:
3587
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
3588
+ *
3589
+ * `runTestModule` then installs `describe/it/test/expect` as globals, invokes
3590
+ * the factory (which registers all tests), runs them, and returns a `RunReport`.
3591
+ *
3592
+ * ## Why a factory wrapper is needed
3593
+ *
3594
+ * Naively adding the runtime to `entryPoints` and bundling the user file would
3595
+ * fail for two reasons:
3596
+ * 1. `describe/it/test/expect` from the runtime are module-local in the IIFE
3597
+ * scope. The user's top-level `describe(...)` calls expect them as globals —
3598
+ * they are not globals until `runTestModule` installs them.
3599
+ * 2. Even with globals pre-installed, the user file runs at IIFE-evaluation
3600
+ * time, before the RPC layer calls `runTestModule` to reset state and start
3601
+ * the test clock.
3602
+ *
3603
+ * The factory approach solves both: the user's registration code is deferred
3604
+ * into a function that `runTestModule` calls AFTER installing the globals.
3605
+ *
3606
+ * ## Factory extraction algorithm
3607
+ *
3608
+ * The `userFactoryPlugin` reads the user file and splits lines into:
3609
+ * - **top-level**: `import …` and re-export lines — kept at module scope
3610
+ * (the only valid position for static `import` in ESM).
3611
+ * - **body**: all other statements — moved into the body of the exported
3612
+ * `__userFactory` async function.
3613
+ *
3614
+ * esbuild processes the re-generated module, following each static import
3615
+ * through the normal dependency graph (including the SDK-redirect plugin).
3616
+ *
3617
+ * ## SDK redirect
3618
+ *
3619
+ * Imports of `@apps-in-toss/web-framework` (and sub-paths) are intercepted via
3620
+ * the `sdkRedirectPlugin` and replaced with a virtual `window.__sdk` proxy that
3621
+ * `src/in-app/auto.ts` installs at runtime. This works for both 2.x and 3.x SDK.
3622
+ *
3623
+ * SECRET-HANDLING: the returned bundle code is caller-managed; never log it.
3624
+ */
3625
+ /** The SDK package name that mini-app test code imports from. */
3626
+ const SDK_PACKAGE = "@apps-in-toss/web-framework";
3627
+ /**
3628
+ * Names the runtime installs as globals before invoking the user factory.
3629
+ * The `vitest` virtual module re-exports each as a lazy getter that reads from
3630
+ * `globalThis` at access time. Keep in sync with the globals installed in
3631
+ * `runtime.ts#runTestModule`.
3632
+ */
3633
+ const VITEST_GLOBAL_NAMES = [
3634
+ "describe",
3635
+ "it",
3636
+ "test",
3637
+ "expect",
3638
+ "beforeAll",
3639
+ "afterAll",
3640
+ "beforeEach",
3641
+ "afterEach",
3642
+ "vi"
3643
+ ];
3644
+ /**
3645
+ * Matches the bare SDK package and any sub-path import
3646
+ * (`@apps-in-toss/web-framework`, `@apps-in-toss/web-framework/foo`).
3647
+ * Built from {@link SDK_PACKAGE} so the package name has a single source.
3648
+ */
3649
+ const SDK_IMPORT_FILTER = new RegExp(`^${SDK_PACKAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
3650
+ /**
3651
+ * esbuild plugin that intercepts SDK imports and redirects them to the
3652
+ * `window.__sdk` proxy that `src/in-app/auto.ts` installs at runtime.
3653
+ *
3654
+ * Strategy: for every import of `@apps-in-toss/web-framework` (or sub-paths),
3655
+ * esbuild resolves it to a virtual module that re-exports all named exports
3656
+ * via `window.__sdk[name]`. This avoids bundling the real SDK (which may not
3657
+ * be available in the test environment) while still making named imports work.
3658
+ *
3659
+ * If `window.__sdk` is absent (non-dog-food build), every access throws a
3660
+ * descriptive error rather than returning `undefined` silently.
3661
+ */
3662
+ function sdkRedirectPlugin() {
3663
+ return {
3664
+ name: "sdk-redirect",
3665
+ setup(build) {
3666
+ build.onResolve({ filter: SDK_IMPORT_FILTER }, (args) => ({
3667
+ path: args.path,
3668
+ namespace: "sdk-redirect"
3669
+ }));
3670
+ build.onLoad({
3671
+ filter: /.*/,
3672
+ namespace: "sdk-redirect"
3673
+ }, () => ({
3674
+ contents: `
3675
+ var __proxy = (typeof window !== 'undefined' && window.__sdk)
3676
+ ? window.__sdk
3677
+ : new Proxy({}, {
3678
+ get: function(_t, p) {
3679
+ throw new Error('window.__sdk is not installed — run in a dog-food build. Missing: ' + String(p));
3680
+ }
3681
+ });
3682
+ module.exports = __proxy;
3683
+ `,
3684
+ loader: "js"
3685
+ }));
3686
+ }
3687
+ };
3688
+ }
3689
+ /**
3690
+ * esbuild plugin that intercepts `import … from 'vitest'` and replaces it with
3691
+ * a virtual module that delegates every named import to `globalThis` at ACCESS
3692
+ * time (not at bundle-evaluation time).
3693
+ *
3694
+ * The runtime installs `describe/it/test/expect/beforeAll/afterAll/beforeEach/
3695
+ * afterEach/vi` as globals inside `runTestModule`, which runs AFTER the bundle
3696
+ * IIFE is evaluated. A value-copy redirect (`export var describe =
3697
+ * globalThis.describe`) would therefore capture `undefined` at evaluation time
3698
+ * and the user's `describe(...)` calls would be no-ops — registering zero tests.
3699
+ *
3700
+ * The fix defers the lookup to call time using per-name **getter** exports.
3701
+ * We emit a CommonJS module that:
3702
+ * 1. sets `__esModule = true` so esbuild's `__toESM` interop maps each named
3703
+ * import directly to a property access on the module (NOT wrapped under a
3704
+ * `default` shim — which is what happens for a bare Proxy whose own-keys
3705
+ * are empty, leaving every named import `undefined`);
3706
+ * 2. defines each global name as a getter that reads `globalThis[name]` on
3707
+ * every access. So `import { describe } from 'vitest'` compiles to
3708
+ * `import_vitest.describe`, whose getter returns the real `describe` only
3709
+ * when the factory calls it — after `runTestModule` installs the globals.
3710
+ *
3711
+ * A plain `module.exports = new Proxy(...)` does NOT work here: esbuild routes
3712
+ * the virtual module through `__toESM`, which enumerates own-keys (none on an
3713
+ * empty Proxy target) and therefore exposes zero named exports. Explicit getter
3714
+ * properties give `__toESM` real keys to map while keeping access lazy.
3715
+ */
3716
+ function vitestRedirectPlugin() {
3717
+ return {
3718
+ name: "vitest-redirect",
3719
+ setup(build) {
3720
+ build.onResolve({ filter: /^vitest$/ }, () => ({
3721
+ path: "vitest",
3722
+ namespace: "vitest-redirect"
3723
+ }));
3724
+ build.onLoad({
3725
+ filter: /^vitest$/,
3726
+ namespace: "vitest-redirect"
3727
+ }, () => {
3728
+ return {
3729
+ contents: `Object.defineProperty(exports, '__esModule', { value: true });\n${VITEST_GLOBAL_NAMES.map((name) => `Object.defineProperty(exports, ${JSON.stringify(name)}, { enumerable: true, get: function() { return globalThis[${JSON.stringify(name)}]; } });`).join("\n")}\n`,
3730
+ loader: "js"
3731
+ };
4149
3732
  });
4150
- ws.send(JSON.stringify({
4151
- id,
4152
- method,
4153
- params
3733
+ }
3734
+ };
3735
+ }
3736
+ /**
3737
+ * esbuild plugin that transforms the user test file into a module that exports
3738
+ * an async `__userFactory` function. The factory defers the user's top-level
3739
+ * test registration code (describe/it/test calls) so it only runs when
3740
+ * `runTestModule(__userFactory)` explicitly invokes it — AFTER the runtime has
3741
+ * installed describe/it/test/expect as globals.
3742
+ *
3743
+ * Algorithm:
3744
+ * - Import declarations and re-export statements are kept at module top-level
3745
+ * (the only valid ESM position for static `import`). A statement that spans
3746
+ * multiple lines — e.g. a named import with one member per line:
3747
+ * import {
3748
+ * appLogin,
3749
+ * getAnonymousKey,
3750
+ * } from '@apps-in-toss/web-framework';
3751
+ * is tracked as a single block: every line from the opening `import {` /
3752
+ * `export {` through the closing `from '…'` (or side-effect `'…'`) line is
3753
+ * kept together at top-level. This prevents the member lines and the
3754
+ * closing `} from '…'` line from leaking into the factory body, which would
3755
+ * leave an unterminated `import {` at module scope (the #678 env3 failure:
3756
+ * esbuild threw `Expected "as" but found "{"` on multi-line SDK imports).
3757
+ * - All other lines (describe/it/test calls, local declarations, etc.) are
3758
+ * moved into the body of the exported async factory function.
3759
+ *
3760
+ * This preserves SDK import resolution (the sdk-redirect plugin processes
3761
+ * top-level imports normally) while deferring test registration to the factory.
3762
+ */
3763
+ function userFactoryPlugin(absPath) {
3764
+ const NAMESPACE = "user-test-factory";
3765
+ return {
3766
+ name: "user-test-factory",
3767
+ setup(build) {
3768
+ build.onResolve({ filter: /^user-test-factory$/ }, () => ({
3769
+ path: absPath,
3770
+ namespace: NAMESPACE
4154
3771
  }));
4155
- });
3772
+ build.onLoad({
3773
+ filter: /.*/,
3774
+ namespace: NAMESPACE
3775
+ }, async (args) => {
3776
+ const lines = (await fs.readFile(args.path, "utf8")).split("\n");
3777
+ const topLevelLines = [];
3778
+ const bodyLines = [];
3779
+ const EXPORT_DECLARATION_RE = /^(export\s+)(default\s+|async\s+function\s+|function\s+|class\s+|const\s+|let\s+|var\s+)/;
3780
+ const isImportStart = (trimmed) => trimmed.startsWith("import ") || trimmed.startsWith("import{") || trimmed.startsWith("import'") || trimmed.startsWith("import\"");
3781
+ const endsStatement = (trimmed) => /['"]\s*;?\s*$/.test(trimmed.replace(/\/\/.*$/, "").trimEnd());
3782
+ let inImportBlock = false;
3783
+ for (const line of lines) {
3784
+ const trimmed = line.trimStart();
3785
+ const indent = line.slice(0, line.length - trimmed.length);
3786
+ if (inImportBlock) {
3787
+ topLevelLines.push(line);
3788
+ if (endsStatement(trimmed)) inImportBlock = false;
3789
+ continue;
3790
+ }
3791
+ if (isImportStart(trimmed)) {
3792
+ topLevelLines.push(line);
3793
+ if (!endsStatement(trimmed)) inImportBlock = true;
3794
+ } else if (trimmed.startsWith("export ")) if (trimmed.match(EXPORT_DECLARATION_RE)) bodyLines.push(indent + trimmed.slice(7));
3795
+ else {
3796
+ topLevelLines.push(line);
3797
+ if (/\bfrom\b/.test(trimmed) ? !endsStatement(trimmed) : trimmed.endsWith("{")) inImportBlock = true;
3798
+ }
3799
+ else bodyLines.push(line);
3800
+ }
3801
+ return {
3802
+ contents: [
3803
+ ...topLevelLines,
3804
+ "",
3805
+ "// biome-ignore lint: generated factory wrapper",
3806
+ "export default async function __userFactory(): Promise<void> {",
3807
+ ...bodyLines.map((l) => ` ${l}`),
3808
+ "}"
3809
+ ].join("\n"),
3810
+ loader: "ts",
3811
+ resolveDir: path.dirname(absPath)
3812
+ };
3813
+ });
3814
+ }
3815
+ };
3816
+ }
3817
+ /**
3818
+ * Returns the absolute filesystem path to the test-runner runtime module
3819
+ * (dist/test-runner/runtime.js — a fully self-contained page-side bundle).
3820
+ *
3821
+ * Rolldown code-splitting duplicates this bundling logic into shared chunks
3822
+ * emitted at ARBITRARY dist depths: the `devtools-test` CLI pulls it from
3823
+ * dist/test-runner/bundle.js (dir = dist/test-runner/), while the `devtools-mcp`
3824
+ * daemon (dist/mcp/cli.js) pulls it through a ROOT chunk
3825
+ * (dist/debug-server-<hash>.js, dir = dist/). A fixed `..`-hop candidate list
3826
+ * is therefore wrong from at least one chunk — the live #697 regression.
3827
+ *
3828
+ * This resolves WITHOUT assuming chunk depth: from `import.meta.url`'s dir it
3829
+ * probes the co-located `runtime.js` and the nested `test-runner/runtime.js`,
3830
+ * then ascends one directory at a time (bounded) repeating both probes. The
3831
+ * nested probe catches dist/test-runner/runtime.js from the dist/ root level no
3832
+ * matter which depth the chunk was hoisted to (root, dist/mcp/, or a future
3833
+ * relocation). The build always emits dist/test-runner/runtime.js (tsdown entry
3834
+ * `'test-runner/runtime'`; guarded by scripts/check-test-runner-dist.sh).
3835
+ *
3836
+ * An ABSOLUTE path is returned deliberately: esbuild loads it as a literal file
3837
+ * read, bypassing Node module resolution entirely, so this works identically in
3838
+ * the npx-daemon context (its own dist tree) and the consumer-CLI context
3839
+ * (the mini-app's installed @ait-co/devtools dist) — neither needs the package
3840
+ * to be node-resolvable from the caller.
3841
+ */
3842
+ function getRuntimePath() {
3843
+ const startDir = path.dirname(fileURLToPath(import.meta.url));
3844
+ const RELATIVE_PROBES = [
3845
+ ["runtime.js"],
3846
+ ["test-runner", "runtime.js"],
3847
+ ["runtime.ts"],
3848
+ ["test-runner", "runtime.ts"]
3849
+ ];
3850
+ let dir = startDir;
3851
+ for (let i = 0; i < 12; i++) {
3852
+ for (const segs of RELATIVE_PROBES) {
3853
+ const candidate = path.join(dir, ...segs);
3854
+ try {
3855
+ accessSync(candidate);
3856
+ return candidate;
3857
+ } catch {}
3858
+ }
3859
+ const parent = path.dirname(dir);
3860
+ if (parent === dir) break;
3861
+ dir = parent;
4156
3862
  }
4157
- /**
4158
- * Called on WebSocket `close` or `error` after a successful connection.
4159
- * Rejects all pending commands and marks the connection as disconnected so
4160
- * subsequent `sendCommand` calls fail fast (no auto-reconnect).
4161
- */
4162
- handleDisconnect(reason) {
4163
- if (this.connectionState === "disconnected") return;
4164
- this.connectionState = "disconnected";
4165
- this.ws = null;
4166
- this.stopHeartbeat();
4167
- const err = /* @__PURE__ */ new Error(`${reason}. list_pages로 attach 상태를 확인하고 enableDomains() 재연결하세요.`);
4168
- for (const waiter of this.pending.values()) waiter.reject(err);
4169
- this.pending.clear();
3863
+ return path.join(startDir, "runtime.js");
3864
+ }
3865
+ /**
3866
+ * Bundles `absPath` into a single IIFE string suitable for `Runtime.evaluate`.
3867
+ *
3868
+ * The IIFE installs `window.__testBundle` (or the custom `globalName`) with:
3869
+ * - `runTestModule` — the runtime entry (from `runtime.ts`).
3870
+ * - `__userFactory` — an async function wrapping the user's test registration
3871
+ * code so it runs AFTER `runTestModule` installs the globals.
3872
+ *
3873
+ * Callers (rpc.ts) invoke:
3874
+ * `globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory)`
3875
+ *
3876
+ * @param absPath - Absolute path to the user test file.
3877
+ * @param opts - Optional bundling overrides.
3878
+ */
3879
+ async function bundleTestFile(absPath, opts) {
3880
+ const globalName = opts?.globalName ?? "__testBundle";
3881
+ const extraExternals = opts?.extraExternals ?? [];
3882
+ const esbuild = await import("esbuild");
3883
+ const runtimePath = getRuntimePath();
3884
+ const wrapperContent = [
3885
+ `import { runTestModule } from ${JSON.stringify(runtimePath)};`,
3886
+ `import __userFactory from "user-test-factory";`,
3887
+ `export { runTestModule, __userFactory };`
3888
+ ].join("\n");
3889
+ const result = await esbuild.build({
3890
+ stdin: {
3891
+ contents: wrapperContent,
3892
+ loader: "ts",
3893
+ resolveDir: path.dirname(absPath)
3894
+ },
3895
+ bundle: true,
3896
+ format: "iife",
3897
+ globalName,
3898
+ platform: "browser",
3899
+ target: "es2022",
3900
+ write: false,
3901
+ plugins: [
3902
+ userFactoryPlugin(absPath),
3903
+ vitestRedirectPlugin(),
3904
+ sdkRedirectPlugin()
3905
+ ],
3906
+ external: extraExternals,
3907
+ treeShaking: true,
3908
+ footer: { js: `globalThis[${JSON.stringify(globalName)}] = ${globalName};` }
3909
+ });
3910
+ const warnings = result.warnings.map((w) => `${path.relative(process.cwd(), w.location?.file ?? "")}:${w.location?.line ?? "?"}: ${w.text}`);
3911
+ const outputFile = result.outputFiles?.[0];
3912
+ if (!outputFile) throw new Error("bundleTestFile: esbuild produced no output — check entryPoints");
3913
+ return {
3914
+ code: outputFile.text,
3915
+ warnings
3916
+ };
3917
+ }
3918
+ //#endregion
3919
+ //#region src/test-runner/capture.ts
3920
+ /** The exact console-line prefix sdk-example's `flushCapture` emits. */
3921
+ const CAPTURE_PREFIX = "__AIT_CAPTURE__ ";
3922
+ /**
3923
+ * Parses raw console line texts into {@link AitCaptureLine}s.
3924
+ *
3925
+ * Filtering rules (each independently drops a line — never throws):
3926
+ * - the line text must `startsWith(CAPTURE_PREFIX)` exactly (allowlist);
3927
+ * - there must be a non-empty category token (up to the next space);
3928
+ * - the remaining payload must be valid JSON (`JSON.parse` succeeds).
3929
+ *
3930
+ * Lines that fail any rule (wss/scheme noise, truncated, broken JSON) are
3931
+ * silently discarded — capture harvesting is best-effort and must never fail a
3932
+ * run or leak a malformed/secret-bearing line.
3933
+ *
3934
+ * @param raw - Console line objects (only `.text` is read).
3935
+ * @returns The captured lines, in input order.
3936
+ */
3937
+ function parseCaptureLines(raw) {
3938
+ const out = [];
3939
+ for (const { text } of raw) {
3940
+ if (!text.startsWith(CAPTURE_PREFIX)) continue;
3941
+ const body = text.slice(16);
3942
+ const spaceIdx = body.indexOf(" ");
3943
+ if (spaceIdx === -1) continue;
3944
+ const category = body.slice(0, spaceIdx);
3945
+ const json = body.slice(spaceIdx + 1);
3946
+ if (category === "" || json === "") continue;
3947
+ try {
3948
+ JSON.parse(json);
3949
+ } catch {
3950
+ continue;
3951
+ }
3952
+ out.push({
3953
+ category,
3954
+ json
3955
+ });
4170
3956
  }
4171
- /**
4172
- * Evict a previously active target under the single-attach model.
4173
- * Rejects pending commands with a 'replaced-by-new-attach' reason and emits
4174
- * a 'replaced' lifecycle event. Does NOT clear all targets — only the specific
4175
- * targetId. The caller is responsible for rebuilding the targets map afterwards.
4176
- *
4177
- * The error message uses 'replaced-by-new-attach' so test assertions can match it.
4178
- */
4179
- evictTarget(targetId) {
4180
- const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
4181
- this.targets.delete(targetId);
4182
- this.targetLastSeenAt.delete(targetId);
4183
- const err = /* @__PURE__ */ new Error(`[ait-debug] replaced-by-new-attach 이전 page 세션이 새 attach로 교체됐습니다 (targetId=${targetId}). list_pages로 현재 attach 상태를 확인하세요.`);
4184
- for (const waiter of this.pending.values()) waiter.reject(err);
4185
- this.pending.clear();
4186
- const event = {
4187
- kind: "replaced",
4188
- targetId,
4189
- detectedAt
4190
- };
4191
- for (const listener of this.lifecycleListeners) try {
4192
- listener(event);
4193
- } catch {}
3957
+ return out;
3958
+ }
3959
+ //#endregion
3960
+ //#region src/test-runner/rpc.ts
3961
+ /** Maximum milliseconds to wait for a single evaluate round-trip. */
3962
+ const DEFAULT_TIMEOUT_MS = 6e4;
3963
+ /**
3964
+ * Wraps bundle code in a self-executing IIFE that:
3965
+ * 1. Evaluates the bundle (registering describe/it/test).
3966
+ * 2. Calls `__testBundle.runTestModule(...)` the entry the runtime exports.
3967
+ * 3. Returns a JSON-serialised `RunReport` string.
3968
+ *
3969
+ * The double-serialisation (RunReport JSON string returnByValue string)
3970
+ * is intentional: CDP `returnByValue` reliably transports strings; deeply
3971
+ * nested objects can lose fidelity across the Chii relay.
3972
+ *
3973
+ * SECRET-HANDLING: `bundleCode` MUST NOT be logged by callers.
3974
+ */
3975
+ function buildRunTestsExpression(bundleCode) {
3976
+ return `(async () => { try { ${bundleCode} } catch(e) { return JSON.stringify({ok:false,error:'bundle-eval: ' + String(e && e.message || e)}); } if (typeof globalThis.__testBundle !== 'object' || typeof globalThis.__testBundle.runTestModule !== 'function' || typeof globalThis.__testBundle.__userFactory !== 'function') { return JSON.stringify({ok:false,error:'bundle-missing-export: __testBundle.runTestModule or __userFactory is not a function'}); } try { const report = await globalThis.__testBundle.runTestModule(globalThis.__testBundle.__userFactory); return JSON.stringify({ok:true,value:report}); } catch(e) { return JSON.stringify({ok:false,error:'test-run: ' + String(e && e.message || e)}); }})()`;
3977
+ }
3978
+ /**
3979
+ * Parses the raw CDP `returnByValue` result from a `buildRunTestsExpression`
3980
+ * evaluate call into a typed `RpcRunResult`.
3981
+ *
3982
+ * Throws only on parse failure — an `ok:false` envelope is a normal result.
3983
+ *
3984
+ * SECRET-HANDLING: `rawValue` is not included in error messages.
3985
+ */
3986
+ function parseRunTestsResult(rawValue) {
3987
+ if (typeof rawValue !== "string") throw new Error(`rpc.parseRunTestsResult: unexpected return type "${typeof rawValue}" — expected JSON string`);
3988
+ let parsed;
3989
+ try {
3990
+ parsed = JSON.parse(rawValue);
3991
+ } catch {
3992
+ throw new Error("rpc.parseRunTestsResult: bridge returned non-JSON string");
4194
3993
  }
4195
- /**
4196
- * Handle a page-level crash or target destruction event.
4197
- * Removes the target from the in-memory map, rejects all pending commands,
4198
- * and emits a lifecycle event.
4199
- *
4200
- * @param kind - Event kind: 'crashed' | 'destroyed' | 'detached'
4201
- * @param targetId - The target ID from the event params (may be null for
4202
- * Inspector.targetCrashed which has no targetId in the params).
4203
- */
4204
- handleTargetGone(kind, targetId) {
4205
- const detectedAt = (/* @__PURE__ */ new Date()).toISOString();
4206
- this.lastCrashDetectedAt = Date.now();
4207
- if (targetId !== null) {
4208
- this.targets.delete(targetId);
4209
- this.targetLastSeenAt.delete(targetId);
4210
- if (this.activeTargetId === targetId) this.activeTargetId = null;
4211
- } else {
4212
- this.targets.clear();
4213
- this.targetLastSeenAt.clear();
4214
- this.activeTargetId = null;
4215
- }
4216
- const err = /* @__PURE__ */ new Error(`[ait-debug] ${kind === "crashed" ? "page crash (Inspector.targetCrashed)" : kind === "destroyed" ? "target 종료 (Target.targetDestroyed)" : "target detach (Target.detachedFromTarget)"} 감지됨 — relay에서 제거됐습니다. 새 attach가 필요합니다 (list_pages로 확인 → enableDomains()로 재연결).`);
4217
- for (const waiter of this.pending.values()) waiter.reject(err);
4218
- this.pending.clear();
4219
- const event = {
4220
- kind,
4221
- targetId,
4222
- detectedAt
4223
- };
4224
- for (const listener of this.lifecycleListeners) try {
4225
- listener(event);
4226
- } catch {}
3994
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new Error("rpc.parseRunTestsResult: parsed result is not an object");
3995
+ const obj = parsed;
3996
+ if (obj.ok === true) return {
3997
+ ok: true,
3998
+ report: obj.value
3999
+ };
4000
+ if (obj.ok === false) return {
4001
+ ok: false,
4002
+ error: typeof obj.error === "string" ? obj.error : String(obj.error)
4003
+ };
4004
+ throw new Error("rpc.parseRunTestsResult: result missing \"ok\" field");
4005
+ }
4006
+ /**
4007
+ * Injects `bundleCode` into the attached page and awaits test execution.
4008
+ *
4009
+ * Uses `Runtime.evaluate` with `awaitPromise: true` to wait for the
4010
+ * async IIFE to settle. The 30-second CDP command timeout covers even
4011
+ * long-running test suites; split into smaller files if you hit it.
4012
+ *
4013
+ * @param connection - Active CDP connection (relay or local).
4014
+ * @param bundleCode - IIFE bundle string from `bundleTestFile`.
4015
+ * @param timeoutMs - Override the default 30 s timeout.
4016
+ *
4017
+ * SECRET-HANDLING: `bundleCode` and the raw CDP result value are never logged.
4018
+ */
4019
+ async function injectAndRunBundle(connection, bundleCode, timeoutMs = DEFAULT_TIMEOUT_MS) {
4020
+ const expression = buildRunTestsExpression(bundleCode);
4021
+ const TIMEOUT_SENTINEL = Symbol("timeout");
4022
+ const timeoutPromise = new Promise((resolve) => setTimeout(() => resolve(TIMEOUT_SENTINEL), timeoutMs));
4023
+ const evalPromise = connection.send("Runtime.evaluate", {
4024
+ expression,
4025
+ returnByValue: true,
4026
+ awaitPromise: true
4027
+ });
4028
+ const raceResult = await Promise.race([evalPromise.then((v) => ({
4029
+ tag: "eval",
4030
+ v
4031
+ })), timeoutPromise.then(() => ({ tag: "timeout" }))]);
4032
+ if (raceResult.tag === "timeout") return {
4033
+ ok: false,
4034
+ error: `rpc: evaluate timed out after ${timeoutMs}ms`
4035
+ };
4036
+ const cdpResult = raceResult.v;
4037
+ if (cdpResult.exceptionDetails) {
4038
+ const msg = cdpResult.exceptionDetails.exception?.description ?? cdpResult.exceptionDetails.text ?? "Runtime.evaluate threw an exception";
4039
+ throw new Error(`rpc.injectAndRunBundle: ${msg}`);
4040
+ }
4041
+ return parseRunTestsResult(cdpResult.result.value);
4042
+ }
4043
+ //#endregion
4044
+ //#region src/test-runner/relay-worker.ts
4045
+ /**
4046
+ * Sentinel string embedded in the error message by `injectAndRunBundle` when
4047
+ * the per-file evaluate race hits the timeout. Used by the retry guard so only
4048
+ * genuine timeouts get a second attempt — not bundle errors or parse failures.
4049
+ *
4050
+ * Exported for unit tests that assert the retry path is taken.
4051
+ */
4052
+ const EVALUATE_TIMEOUT_MARKER = "rpc: evaluate timed out after";
4053
+ /**
4054
+ * Runs all `files` sequentially over the given CDP `connection`.
4055
+ *
4056
+ * For each file:
4057
+ * 1. Bundle with esbuild (includes SDK shim + runtime).
4058
+ * 2. Inject into the attached page via `Runtime.evaluate`.
4059
+ * 3. Await the `RunReport` JSON response.
4060
+ * 4. Accumulate results.
4061
+ *
4062
+ * Returns a `RelayRunReport` with per-file results and flattened totals.
4063
+ *
4064
+ * This function does NOT open or manage the relay connection — the caller
4065
+ * is responsible for attaching and closing it.
4066
+ *
4067
+ * TODO (#645): implement the Vitest `PoolRunnerInitializer` interface here
4068
+ * so that `runTestFilesOverRelay` can be used as a Vitest pool entry.
4069
+ *
4070
+ * @param connection - Active CDP connection (relay or local kind).
4071
+ * @param files - Absolute paths to test files, run in order.
4072
+ * @param opts - Optional per-run overrides.
4073
+ */
4074
+ async function runTestFilesOverRelay(connection, files, opts) {
4075
+ const wallStart = Date.now();
4076
+ const startedAt = new Date(wallStart).toISOString();
4077
+ const fileResults = [];
4078
+ let domainsEnabled = false;
4079
+ try {
4080
+ await connection.enableDomains();
4081
+ domainsEnabled = true;
4082
+ } catch (e) {
4083
+ process.stderr.write(`relay-worker: enableDomains() failed before run — console capture may be empty (${e instanceof Error ? e.message : String(e)})\n`);
4227
4084
  }
4085
+ const collectCaptures = opts?.collectCaptures === true;
4086
+ const liveConsole = [];
4087
+ let unsubscribeConsole;
4088
+ if (collectCaptures && domainsEnabled) unsubscribeConsole = connection.on("Runtime.consoleAPICalled", (event) => {
4089
+ liveConsole.push(event);
4090
+ });
4091
+ let pendingReconnectCheck = false;
4228
4092
  /**
4229
- * Start the optional CDP heartbeat loop.
4230
- *
4231
- * When `AIT_CDP_HEARTBEAT_MS` is set to a positive integer, every interval
4232
- * we send `Runtime.evaluate({expression: '1'})` to each active target. If
4233
- * the command times out (2 s hard deadline) or errors, we treat the target
4234
- * as dead and call `handleTargetGone`.
4093
+ * Attempts one `enableDomains()` reconnect. Logs the attempt and outcome to
4094
+ * stderr. Never throws — a failed reconnect just means the caller proceeds
4095
+ * as today (each remaining file / the retry will fail-fast on the still-dead
4096
+ * socket).
4235
4097
  *
4236
- * This is a zombie-detector fallback: cloudflared keeps-alive the tunnel ws
4237
- * even when the phone app has crashed, so the ws-level disconnect (#252) won't
4238
- * fire. The heartbeat catches this gap.
4098
+ * `context` selects the fixed log literal: 'next-file' for the between-files
4099
+ * case (a file's FINAL result was a WS-dead-class error — the primary #731
4100
+ * scenario), 'retry-precheck' for the defensive reconnect before retrying a
4101
+ * timed-out file (cheap no-op via `enableDomains()`'s idempotency when the
4102
+ * socket never actually died).
4239
4103
  *
4240
- * Default: OFF. Only activates when `AIT_CDP_HEARTBEAT_MS` is set.
4104
+ * SECRET-HANDLING: fixed literals only no relay wss URL, TOTP code, or
4105
+ * tunnel host.
4241
4106
  */
4242
- startHeartbeat(initialTargetId) {
4243
- this.stopHeartbeat();
4244
- const envMs = process.env.AIT_CDP_HEARTBEAT_MS ? Number(process.env.AIT_CDP_HEARTBEAT_MS) : void 0;
4245
- if (envMs === void 0 || !Number.isFinite(envMs) || envMs <= 0) return;
4246
- const PING_TIMEOUT_MS = 2e3;
4247
- this.heartbeatHandle = setInterval(() => {
4248
- const targetIds = this.targets.size > 0 ? [...this.targets.keys()] : [initialTargetId];
4249
- for (const targetId of targetIds) {
4250
- const pingPromise = this.sendCommand("Runtime.evaluate", {
4251
- expression: "1",
4252
- returnByValue: true,
4253
- timeout: PING_TIMEOUT_MS
4254
- });
4255
- const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(/* @__PURE__ */ new Error("heartbeat timeout")), PING_TIMEOUT_MS + 500));
4256
- Promise.race([pingPromise, timeoutPromise]).catch(() => {
4257
- if (this.targets.has(targetId)) this.handleTargetGone("destroyed", targetId);
4258
- });
4107
+ const attemptReconnect = async (context) => {
4108
+ process.stderr.write(context === "next-file" ? "relay-worker: relay connection lost — attempting reconnect before next file\n" : "relay-worker: evaluate timed out — attempting reconnect before retry\n");
4109
+ try {
4110
+ await connection.enableDomains();
4111
+ process.stderr.write("relay-worker: reconnect succeeded\n");
4112
+ } catch (e) {
4113
+ process.stderr.write(`relay-worker: reconnect failed (${e instanceof Error ? e.message : String(e)}) continuing, remaining files may fail\n`);
4114
+ }
4115
+ };
4116
+ try {
4117
+ for (const file of files) {
4118
+ if (pendingReconnectCheck) {
4119
+ await attemptReconnect("next-file");
4120
+ pendingReconnectCheck = false;
4121
+ }
4122
+ let fileEntry;
4123
+ try {
4124
+ const { code } = await bundleTestFile(file, opts?.bundleOptions);
4125
+ /**
4126
+ * Runs one evaluate attempt and returns a FileResult, or `null` when the
4127
+ * result is a genuine timeout and the caller should retry.
4128
+ *
4129
+ * We need to distinguish:
4130
+ * - `rpcResult.ok = false` + timeout error → retry candidate (`return null`)
4131
+ * - `rpcResult.ok = false` + other error → final error, no retry
4132
+ * - `injectAndRunBundle` throws → CDP exceptionDetails OR a
4133
+ * relay-disconnect rejection from `connection.send()` (page engine
4134
+ * threw, or the ws died mid-evaluate); treated as a final
4135
+ * (non-retryable) error either way.
4136
+ *
4137
+ * The Promise.race timeout in rpc.ts RETURNS `{ok:false, error: '…'}` (it
4138
+ * does NOT throw/reject). Only genuine CDP `exceptionDetails` (or a dead
4139
+ * `connection.send()`) cause a throw. This distinction is what makes the
4140
+ * EVALUATE_TIMEOUT_MARKER gate below reachable — the timeout result
4141
+ * surfaces as `rpcResult.ok=false` with the marker string, not as a
4142
+ * caught exception.
4143
+ */
4144
+ const attempt = async () => {
4145
+ let rpcResult;
4146
+ try {
4147
+ rpcResult = await injectAndRunBundle(connection, code, opts?.timeoutMs);
4148
+ } catch (e) {
4149
+ return {
4150
+ file,
4151
+ result: { error: e instanceof Error ? e.message : String(e) }
4152
+ };
4153
+ }
4154
+ if (rpcResult.ok) return {
4155
+ file,
4156
+ result: rpcResult.report
4157
+ };
4158
+ if (rpcResult.error.includes("rpc: evaluate timed out after")) return null;
4159
+ return {
4160
+ file,
4161
+ result: { error: rpcResult.error }
4162
+ };
4163
+ };
4164
+ const firstResult = await attempt();
4165
+ if (firstResult !== null) fileEntry = firstResult;
4166
+ else {
4167
+ await attemptReconnect("retry-precheck");
4168
+ process.stderr.write(`relay-worker: evaluate timed out for ${file} — retrying once\n`);
4169
+ const retryResult = await attempt();
4170
+ if (retryResult !== null) fileEntry = retryResult;
4171
+ else fileEntry = {
4172
+ file,
4173
+ result: { error: `${EVALUATE_TIMEOUT_MARKER} ${opts?.timeoutMs ?? 6e4}ms (after retry)` }
4174
+ };
4175
+ }
4176
+ } catch (e) {
4177
+ fileEntry = {
4178
+ file,
4179
+ result: { error: e instanceof Error ? e.message : String(e) }
4180
+ };
4259
4181
  }
4260
- }, envMs);
4261
- }
4262
- stopHeartbeat() {
4263
- if (this.heartbeatHandle !== null) {
4264
- clearInterval(this.heartbeatHandle);
4265
- this.heartbeatHandle = null;
4182
+ if ("error" in fileEntry.result && isRelayDisconnectMessage(fileEntry.result.error)) pendingReconnectCheck = true;
4183
+ fileResults.push(fileEntry);
4266
4184
  }
4185
+ } finally {
4186
+ unsubscribeConsole?.();
4267
4187
  }
4268
- handleMessage(raw) {
4269
- const message = parseInbound$1(raw);
4270
- if (!message) return;
4271
- if (typeof message.id === "number" && this.pending.has(message.id)) {
4272
- const waiter = this.pending.get(message.id);
4273
- this.pending.delete(message.id);
4274
- if (waiter) if (message.error) waiter.reject(new Error(message.error.message));
4275
- else waiter.resolve(message.result);
4276
- return;
4277
- }
4278
- const now = Date.now();
4279
- let firstMessageSeen = false;
4280
- for (const targetId of this.targets.keys()) {
4281
- if (!this.targetLastSeenAt.has(targetId)) firstMessageSeen = true;
4282
- this.targetLastSeenAt.set(targetId, now);
4283
- }
4284
- if (firstMessageSeen && this.targets.size > 0) this.emitter.emit("target:attached", [...this.targets.values()]);
4285
- if (typeof message.method !== "string") return;
4286
- if (message.method === "Inspector.targetCrashed") {
4287
- this.handleTargetGone("crashed", null);
4288
- return;
4188
+ const captures = collectCaptures ? parseCaptureLines(liveConsole.map((e) => ({ text: renderConsoleLineText(e) }))) : [];
4189
+ const totals = fileResults.reduce((acc, { result }) => {
4190
+ if ("error" in result) {
4191
+ acc.failed += 1;
4192
+ acc.total += 1;
4193
+ } else {
4194
+ acc.passed += result.passed;
4195
+ acc.failed += result.failed;
4196
+ acc.skipped += result.skipped;
4197
+ acc.total += result.passed + result.failed + result.skipped;
4289
4198
  }
4290
- if (message.method === "Target.targetDestroyed") {
4291
- const targetId = isObject$2(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
4292
- this.handleTargetGone("destroyed", targetId);
4293
- return;
4199
+ return acc;
4200
+ }, {
4201
+ passed: 0,
4202
+ failed: 0,
4203
+ skipped: 0,
4204
+ total: 0
4205
+ });
4206
+ return {
4207
+ startedAt,
4208
+ duration: Date.now() - wallStart,
4209
+ files: fileResults,
4210
+ totals,
4211
+ captures
4212
+ };
4213
+ }
4214
+ /**
4215
+ * Renders one `Runtime.consoleAPICalled` event to a single line of text, the
4216
+ * same way `tools.ts#normalizeConsoleMessage` does (args rendered + space-
4217
+ * joined). Inlined here (≈8 lines) so this module avoids importing `tools.ts`,
4218
+ * which would drag the heavy MCP/Node graph (server-lock, parent-watcher, …)
4219
+ * onto the test-runner entry.
4220
+ *
4221
+ * SECRET-HANDLING: this only stringifies console args; the caller's
4222
+ * allowlist-prefix parser then discards everything that is not a genuine
4223
+ * `__AIT_CAPTURE__` line.
4224
+ */
4225
+ function renderConsoleLineText(event) {
4226
+ return event.args.map((arg) => {
4227
+ if (arg.value !== void 0) {
4228
+ if (typeof arg.value === "string") return arg.value;
4229
+ try {
4230
+ return JSON.stringify(arg.value);
4231
+ } catch {
4232
+ return String(arg.value);
4233
+ }
4294
4234
  }
4295
- if (message.method === "Target.detachedFromTarget") {
4296
- const targetId = isObject$2(message.params) && typeof message.params.targetId === "string" ? message.params.targetId : null;
4297
- this.handleTargetGone("detached", targetId);
4298
- return;
4235
+ if (arg.description !== void 0) return arg.description;
4236
+ if (arg.className !== void 0) return arg.className;
4237
+ return arg.subtype ?? arg.type;
4238
+ }).join(" ");
4239
+ }
4240
+ `
4241
+ devtools-test — run mini-app tests on a real device WebView over the CDP relay
4242
+
4243
+ USAGE
4244
+ devtools-test <glob> [<glob> ...] [options]
4245
+
4246
+ OPTIONS
4247
+ --scheme-url <url> intoss-private:// URL from \`ait deploy --scheme-only\`
4248
+ (required for standalone relay attach / env3)
4249
+ --timeout <ms> Per-file evaluate timeout in ms (default: 60000).
4250
+ Controls how long a single test file is allowed to run
4251
+ before it is considered hung. Does NOT affect how long
4252
+ the CLI waits for a human to scan the QR code — use
4253
+ --attach-timeout for that.
4254
+ --attach-timeout <ms> How long to wait for a human to scan the QR code with
4255
+ their phone (default: 600000 — 10 minutes). Omit to
4256
+ use the relay factory's generous default. Decrease for
4257
+ CI environments where a scan should arrive quickly.
4258
+ --cell-sdk-line <line> SDK line to inject as __AIT_CELL__.sdkLine (2.x|3.x)
4259
+ --cell-platform <plat> Platform to inject as __AIT_CELL__.platform
4260
+ (mock|ios|android, default: AIT_CELL_PLATFORM env)
4261
+ --report-dir <dir> Persist a runner-agnostic report + captures to <dir>
4262
+ (report: <sdkLine>.<platform>.json; captures:
4263
+ <dir>/.ait-capture/<category>.<sdkLine>.<platform>.json).
4264
+ Omitted = nothing saved. Enables console capture.
4265
+ --no-qr-stdout Suppress the QR/attach block on stdout (auto-on for
4266
+ non-interactive stdout / CI / AIT_NO_QR_STDOUT)
4267
+ --headless Disable browser auto-open (text QR only)
4268
+ --project-root <dir> Project root for .ait_relay secret lookup
4269
+ (default: current working directory)
4270
+ --help, -h Show this help message
4271
+
4272
+ DESCRIPTION
4273
+ Boots a Chii relay + cloudflared tunnel, renders a QR code, waits for a real
4274
+ device to scan and attach, injects the cell globals (__AIT_CELL__), bundles
4275
+ each matched test file with esbuild (SDK imports redirected to window.__sdk),
4276
+ injects the bundle into the attached WebView via Runtime.evaluate, and prints
4277
+ a summary.
4278
+
4279
+ With --report-dir, also harvests __AIT_CAPTURE__ console lines and writes a
4280
+ runner-agnostic report + per-category capture files so 2.x↔3.0 runs can be
4281
+ compared offline.
4282
+
4283
+ The test files run against the live relay connection started by this process;
4284
+ no separate MCP daemon is required.
4285
+
4286
+ EXAMPLE
4287
+ devtools-test 'src/**/*.ait.test.ts' \\
4288
+ --scheme-url "intoss-private://..." \\
4289
+ --cell-sdk-line 3.x \\
4290
+ --cell-platform ios \\
4291
+ --report-dir .ait-report \\
4292
+ --timeout 60000
4293
+
4294
+ `.trimStart();
4295
+ /**
4296
+ * Renders per-file result lines and the aggregate totals line to a string.
4297
+ *
4298
+ * Each file gets one line:
4299
+ * - Error/timeout: `FAIL <basename>: <error-class>`
4300
+ * - Pass (0 tests): `OK <basename>: 0 passed (empty file)`
4301
+ * - Pass: `OK <basename>: N passed[, M failed][, K skipped]`
4302
+ *
4303
+ * The aggregate totals line always follows.
4304
+ *
4305
+ * SECRET-HANDLING: only `basename(file)` is used — no absolute paths, relay
4306
+ * URLs, wss URLs, scheme URLs, or TOTP codes appear in the output. The error
4307
+ * string comes from `result.error` which is already secret-free (relay-worker
4308
+ * produces only error-class messages like "rpc: evaluate timed out after
4309
+ * 30000ms").
4310
+ *
4311
+ * Exported so unit tests can assert the per-file lines without spawning a
4312
+ * subprocess or going through the full relay attach flow.
4313
+ */
4314
+ function renderSummary(report) {
4315
+ const lines = [];
4316
+ for (const { file, result } of report.files) {
4317
+ const name = basename(file);
4318
+ if ("error" in result) lines.push(`FAIL ${name}: ${result.error}`);
4319
+ else {
4320
+ const parts = [`${result.passed} passed`];
4321
+ if (result.failed > 0) parts.push(`${result.failed} failed`);
4322
+ if (result.skipped > 0) parts.push(`${result.skipped} skipped`);
4323
+ const suffix = result.passed + result.failed + result.skipped === 0 ? " (empty file)" : "";
4324
+ lines.push(`OK ${name}: ${parts.join(", ")}${suffix}`);
4299
4325
  }
4300
- if (!this.buffers.has(message.method)) return;
4301
- const event = message.method;
4302
- const buffer = this.buffers.get(event);
4303
- if (!buffer) return;
4304
- buffer.push(message.params);
4305
- const cap = event === "Runtime.exceptionThrown" ? EXCEPTION_BUFFER_SIZE : this.bufferSize;
4306
- if (buffer.length > cap) buffer.shift();
4307
- this.emitter.emit(event, message.params);
4308
- }
4309
- getBufferedEvents(event) {
4310
- return this.buffers.get(event) ?? [];
4311
4326
  }
4312
- on(event, listener) {
4313
- this.emitter.on(event, listener);
4314
- return () => this.emitter.off(event, listener);
4327
+ const { totals, duration } = report;
4328
+ lines.push(`\ndevtools-test: ${totals.passed} passed, ${totals.failed} failed, ${totals.skipped} skipped (${duration}ms)`);
4329
+ return lines.join("\n");
4330
+ }
4331
+ /**
4332
+ * Runs `files` over `connection` and returns the aggregate report.
4333
+ * This pure function is the testable core of the CLI (and is what the
4334
+ * `run_tests` MCP tool calls against the daemon's attached connection); it is
4335
+ * separate from `main()` so tests can call it without spawning a subprocess.
4336
+ */
4337
+ async function runWithConnection(connection, files, opts) {
4338
+ const report = await runTestFilesOverRelay(connection, files, opts);
4339
+ if (opts?.printSummary) process.stdout.write(`\n${renderSummary(report)}\n`);
4340
+ return report;
4341
+ }
4342
+ //#endregion
4343
+ //#region src/mcp/ait-chii-source.ts
4344
+ function isObject$2(value) {
4345
+ return typeof value === "object" && value !== null;
4346
+ }
4347
+ /** Narrows an `AIT.getSdkCallHistory` response, tolerating a missing array. */
4348
+ function asSdkCallHistory(raw) {
4349
+ if (isObject$2(raw) && Array.isArray(raw.calls)) return { calls: raw.calls };
4350
+ return { calls: [] };
4351
+ }
4352
+ /** Narrows an `AIT.getMockState` response to an opaque record. */
4353
+ function asMockState(raw) {
4354
+ return isObject$2(raw) ? raw : {};
4355
+ }
4356
+ /** Narrows an `AIT.getOperationalEnvironment` response. */
4357
+ function asOperationalEnvironment(raw) {
4358
+ return {
4359
+ environment: isObject$2(raw) && typeof raw.environment === "string" ? raw.environment : "unknown",
4360
+ sdkVersion: isObject$2(raw) && typeof raw.sdkVersion === "string" ? raw.sdkVersion : null
4361
+ };
4362
+ }
4363
+ var ChiiAitSource = class {
4364
+ constructor(sender) {
4365
+ this.sender = sender;
4315
4366
  }
4316
- /** Close the relay client websocket and reject any in-flight commands. */
4317
- close() {
4318
- const ws = this.ws;
4319
- this.stopHeartbeat();
4320
- this.handleDisconnect("Chii relay connection closed");
4321
- ws?.close();
4367
+ async get(method) {
4368
+ const raw = await this.sender.sendCommand(method);
4369
+ switch (method) {
4370
+ case "AIT.getSdkCallHistory": return asSdkCallHistory(raw);
4371
+ case "AIT.getMockState": return asMockState(raw);
4372
+ case "AIT.getOperationalEnvironment": return asOperationalEnvironment(raw);
4373
+ default: throw new Error(`Unknown AIT method: ${String(method)}`);
4374
+ }
4322
4375
  }
4323
4376
  };
4324
4377
  //#endregion
@@ -6798,7 +6851,7 @@ function createDebugServer(deps) {
6798
6851
  };
6799
6852
  const server = new Server({
6800
6853
  name: "ait-debug",
6801
- version: "0.1.128"
6854
+ version: "0.1.129"
6802
6855
  }, { capabilities: { tools: { listChanged: true } } });
6803
6856
  server.setRequestHandler(ListToolsRequestSchema, () => {
6804
6857
  const conn = router.active;
@@ -8770,7 +8823,7 @@ function createDevServer(deps = {}) {
8770
8823
  const aitSource = deps.aitSource ?? new HttpAitSource({ stateEndpoint });
8771
8824
  const server = new Server({
8772
8825
  name: "ait-devtools",
8773
- version: "0.1.128"
8826
+ version: "0.1.129"
8774
8827
  }, { capabilities: { tools: {} } });
8775
8828
  server.setRequestHandler(ListToolsRequestSchema, () => ({ tools: DEV_TOOL_DEFINITIONS.map((tool) => ({ ...tool })) }));
8776
8829
  server.setRequestHandler(CallToolRequestSchema, async (request) => {