@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.41

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 (99) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/device-service-conformance.d.ts +38 -0
  4. package/dist/device-service-conformance.js +142 -0
  5. package/dist/dual-replica.d.ts +23 -1
  6. package/dist/dual-replica.js +53 -0
  7. package/dist/fake-channel.d.ts +44 -5
  8. package/dist/fake-channel.js +63 -2
  9. package/dist/fake-dial-in-machine.d.ts +173 -0
  10. package/dist/fake-dial-in-machine.js +429 -0
  11. package/dist/fake-e2b.d.ts +34 -0
  12. package/dist/fake-e2b.js +95 -1
  13. package/dist/fake-git-server.d.ts +32 -4
  14. package/dist/fake-git-server.js +87 -19
  15. package/dist/fake-lark.d.ts +12 -1
  16. package/dist/fake-lark.js +63 -10
  17. package/dist/fake-oauth-server.d.ts +62 -2
  18. package/dist/fake-oauth-server.js +86 -5
  19. package/dist/fake-slack.d.ts +17 -1
  20. package/dist/fake-slack.js +98 -0
  21. package/dist/fake-telegram.d.ts +173 -0
  22. package/dist/fake-telegram.js +632 -0
  23. package/dist/fixtures.d.ts +24 -8
  24. package/dist/fixtures.js +31 -8
  25. package/dist/index.d.ts +15 -9
  26. package/dist/index.js +10 -4
  27. package/dist/kernel-helpers.d.ts +16 -4
  28. package/dist/kernel-helpers.js +39 -4
  29. package/dist/media-samples.d.ts +2 -0
  30. package/dist/media-samples.js +2 -0
  31. package/dist/model-conformance.d.ts +15 -10
  32. package/dist/model-conformance.js +87 -14
  33. package/dist/push-conformance.d.ts +31 -0
  34. package/dist/push-conformance.js +160 -0
  35. package/dist/replica-runner.js +2 -0
  36. package/dist/sandbox-native-conformance.d.ts +31 -0
  37. package/dist/sandbox-native-conformance.js +153 -0
  38. package/dist/sandbox-permission-conformance.d.ts +310 -0
  39. package/dist/sandbox-permission-conformance.js +1491 -0
  40. package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
  41. package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
  42. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  43. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  44. package/fixtures/extensions/fake-client/package.json +12 -0
  45. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  46. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  47. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  48. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  49. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  50. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  51. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  52. package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
  53. package/fixtures/extensions/fake-connector/src/index.ts +64 -34
  54. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  55. package/fixtures/extensions/fake-context/package.json +12 -0
  56. package/fixtures/extensions/fake-context/src/index.ts +78 -0
  57. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  59. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  60. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  61. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  62. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  63. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  64. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  65. package/fixtures/extensions/fake-im/src/directory.ts +44 -20
  66. package/fixtures/extensions/fake-im/src/index.ts +59 -11
  67. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  68. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  69. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  70. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  71. package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
  72. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  73. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  74. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  75. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  76. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  77. package/fixtures/extensions/fake-push/package.json +12 -0
  78. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  79. package/fixtures/extensions/fake-push/src/index.ts +56 -0
  80. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  81. package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
  82. package/fixtures/extensions/fake-web/src/index.ts +5 -4
  83. package/fixtures/extensions/fake-web/src/web.ts +11 -7
  84. package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
  85. package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
  88. package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
  89. package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
  90. package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
  91. package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
  92. package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
  93. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  94. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  95. package/fixtures/plugins/fake-theme/package.json +8 -0
  96. package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
  97. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  98. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  99. package/package.json +6 -5
@@ -38,12 +38,17 @@ export declare const DEFAULT_CONTAINER_STARTS = 4;
38
38
  * `key` is the slot set (tests use their own).
39
39
  */
40
40
  export declare function withStartSlot<T>(start: () => Promise<T>, key?: string): Promise<T>;
41
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
42
+ export declare const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
41
43
  /**
42
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
43
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
44
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
45
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
46
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
47
+ * tests (no fsync).
44
48
  */
45
49
  export declare function startPostgresContainer(opts?: {
46
50
  tuned?: boolean;
51
+ image?: string;
47
52
  }): Promise<TestContainer>;
48
53
  /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
49
54
  export declare function startRedisContainer(opts?: {
@@ -90,12 +90,16 @@ export async function withStartSlot(start, key = START_SLOTS_KEY) {
90
90
  r.disconnect();
91
91
  }
92
92
  }
93
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
94
+ export const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
93
95
  /**
94
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
95
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
96
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
97
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
98
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
99
+ * tests (no fsync).
96
100
  */
97
101
  export async function startPostgresContainer(opts = {}) {
98
- const image = new PostgreSqlContainer("postgres:17");
102
+ const image = new PostgreSqlContainer(opts.image ?? TEST_PG_IMAGE);
99
103
  if (opts.tuned) {
100
104
  image.withCommand([
101
105
  "postgres",
@@ -0,0 +1,38 @@
1
+ import type { DeviceProvider, SandboxHandle } from "@capybara-hq/plugin-sdk";
2
+ /**
3
+ * The request body {@link DEVICE_SERVICE_ECHO_SCRIPT} answers with its own `process.argv[1]`
4
+ * (the entry path it was started from) instead of the body.
5
+ */
6
+ export declare const DEVICE_SERVICE_ARGV_PROBE = "capybara-conformance:argv1";
7
+ /**
8
+ * A framed echo device service (the device service socket protocol of the SDK's
9
+ * `device-service.ts`, written out so it runs alone from the service's code directory): it
10
+ * listens on `$CAPYBARA_SERVICE_SOCKET`, answers a `request` connection with its body unchanged
11
+ * (with its `process.argv[1]` for {@link DEVICE_SERVICE_ARGV_PROBE}) and echoes every message of a
12
+ * `stream` connection.
13
+ */
14
+ export declare const DEVICE_SERVICE_ECHO_SCRIPT: string;
15
+ /** What {@link runDeviceServiceConformance} runs against: one running instance of a fresh device. */
16
+ export interface DeviceServiceFixture {
17
+ provider: Pick<DeviceProvider, "ensureService" | "stopService" | "serviceRequest">;
18
+ /** A running instance with no service started yet. */
19
+ handle: SandboxHandle;
20
+ /** Removes fixture-owned resources (the instance, its files), also after a failure. */
21
+ dispose(): Promise<void>;
22
+ }
23
+ /**
24
+ * The device service contract every `device-provider@1` with services must pass (browser use spec
25
+ * §5). The kernel's launch review relies on it: a launch is reviewed only after an `ifRunning`
26
+ * ensure answered `stopped`, so a provider that started a service there would run it unreviewed.
27
+ * Every `ifRunning` ensure here uses the name-only spec the kernel sends
28
+ * (`{ name, runtime: "node", entry: "", args: [], files: {} }`). Checks: an `ifRunning` ensure of a
29
+ * stopped service starts nothing and answers `stopped` with an absolute `stateDir` (and an
30
+ * absolute `codeDir` when the provider reports one); both stay the same for the device and name
31
+ * across calls; a normal ensure starts the service once (a second one finds it running, same
32
+ * `startedAt`); an `ifRunning` ensure keeps a running one running; the service runs its entry
33
+ * from `codeDir ?? stateDir` (its `process.argv[1]` is exactly `<codeDir ?? stateDir>/<entry>`,
34
+ * the path the kernel reviewed); `serviceRequest` round-trips the echo service; `stopService`
35
+ * stops it (requests then fail, `ifRunning` answers `stopped`) and succeeds when it is not
36
+ * running. The fixture's `dispose` always runs.
37
+ */
38
+ export declare function runDeviceServiceConformance(fixture: DeviceServiceFixture): Promise<void>;
@@ -0,0 +1,142 @@
1
+ import assert from "node:assert/strict";
2
+ /**
3
+ * The request body {@link DEVICE_SERVICE_ECHO_SCRIPT} answers with its own `process.argv[1]`
4
+ * (the entry path it was started from) instead of the body.
5
+ */
6
+ export const DEVICE_SERVICE_ARGV_PROBE = "capybara-conformance:argv1";
7
+ /**
8
+ * A framed echo device service (the device service socket protocol of the SDK's
9
+ * `device-service.ts`, written out so it runs alone from the service's code directory): it
10
+ * listens on `$CAPYBARA_SERVICE_SOCKET`, answers a `request` connection with its body unchanged
11
+ * (with its `process.argv[1]` for {@link DEVICE_SERVICE_ARGV_PROBE}) and echoes every message of a
12
+ * `stream` connection.
13
+ */
14
+ export const DEVICE_SERVICE_ECHO_SCRIPT = `import { createServer } from "node:net";
15
+ const socket = process.env.CAPYBARA_SERVICE_SOCKET;
16
+ if (!socket) process.exit(2);
17
+ const frame = (body) => {
18
+ const out = Buffer.alloc(4 + body.byteLength);
19
+ out.writeUInt32BE(body.byteLength, 0);
20
+ Buffer.from(body).copy(out, 4);
21
+ return out;
22
+ };
23
+ createServer((conn) => {
24
+ let buf = Buffer.alloc(0);
25
+ let kind = null;
26
+ conn.on("data", (chunk) => {
27
+ buf = Buffer.concat([buf, chunk]);
28
+ for (;;) {
29
+ if (buf.byteLength < 4) return;
30
+ const len = buf.readUInt32BE(0);
31
+ if (buf.byteLength < 4 + len) return;
32
+ const msg = buf.subarray(4, 4 + len);
33
+ buf = buf.subarray(4 + len);
34
+ if (kind === null) {
35
+ kind = JSON.parse(msg.toString("utf8")).kind;
36
+ continue;
37
+ }
38
+ if (kind === "request") {
39
+ const probe = msg.toString("utf8") === ${JSON.stringify(DEVICE_SERVICE_ARGV_PROBE)};
40
+ conn.end(frame(probe ? Buffer.from(process.argv[1] ?? "", "utf8") : msg));
41
+ return;
42
+ }
43
+ conn.write(frame(msg));
44
+ }
45
+ });
46
+ conn.on("error", () => {});
47
+ }).listen(socket);
48
+ `;
49
+ /** The service id the conformance starts (a provider receives ids: `<extension>.<name>`). */
50
+ const SERVICE = "conformance.echo";
51
+ /** What the kernel sends with every `ifRunning` ensure: the name, nothing to run. */
52
+ const nameOnly = (name) => ({
53
+ name,
54
+ runtime: "node",
55
+ entry: "",
56
+ args: [],
57
+ files: {},
58
+ });
59
+ /**
60
+ * The device service contract every `device-provider@1` with services must pass (browser use spec
61
+ * §5). The kernel's launch review relies on it: a launch is reviewed only after an `ifRunning`
62
+ * ensure answered `stopped`, so a provider that started a service there would run it unreviewed.
63
+ * Every `ifRunning` ensure here uses the name-only spec the kernel sends
64
+ * (`{ name, runtime: "node", entry: "", args: [], files: {} }`). Checks: an `ifRunning` ensure of a
65
+ * stopped service starts nothing and answers `stopped` with an absolute `stateDir` (and an
66
+ * absolute `codeDir` when the provider reports one); both stay the same for the device and name
67
+ * across calls; a normal ensure starts the service once (a second one finds it running, same
68
+ * `startedAt`); an `ifRunning` ensure keeps a running one running; the service runs its entry
69
+ * from `codeDir ?? stateDir` (its `process.argv[1]` is exactly `<codeDir ?? stateDir>/<entry>`,
70
+ * the path the kernel reviewed); `serviceRequest` round-trips the echo service; `stopService`
71
+ * stops it (requests then fail, `ifRunning` answers `stopped`) and succeeds when it is not
72
+ * running. The fixture's `dispose` always runs.
73
+ */
74
+ export async function runDeviceServiceConformance(fixture) {
75
+ const { provider, handle } = fixture;
76
+ const ensure = provider.ensureService?.bind(provider);
77
+ const stop = provider.stopService?.bind(provider);
78
+ const request = provider.serviceRequest?.bind(provider);
79
+ assert(ensure && stop && request, "device services need ensureService, stopService and serviceRequest");
80
+ const signal = () => AbortSignal.timeout(30_000);
81
+ const spec = {
82
+ name: SERVICE,
83
+ runtime: "node",
84
+ entry: "echo.mjs",
85
+ args: [],
86
+ files: { "echo.mjs": new TextEncoder().encode(DEVICE_SERVICE_ECHO_SCRIPT) },
87
+ };
88
+ const ask = (text) => request(handle, SERVICE, new TextEncoder().encode(text), {
89
+ timeoutMs: 5_000,
90
+ signal: signal(),
91
+ });
92
+ const ifRunning = () => ensure(handle, nameOnly(SERVICE), signal(), { ifRunning: true });
93
+ const assertDirs = (s, first, when) => {
94
+ assert(s.stateDir.startsWith("/"), `${when}: stateDir must be absolute, got ${s.stateDir}`);
95
+ if (s.codeDir !== undefined)
96
+ assert(s.codeDir.startsWith("/"), `${when}: codeDir must be absolute, got ${s.codeDir}`);
97
+ if (first !== null) {
98
+ assert.equal(s.stateDir, first.stateDir, `${when}: stateDir must be stable`);
99
+ assert.equal(s.codeDir, first.codeDir, `${when}: codeDir must be stable`);
100
+ }
101
+ };
102
+ const assertStopped = async (s, first, when) => {
103
+ assert.equal(s.name, SERVICE, `${when}: status names the service`);
104
+ assert.equal(s.state, "stopped", `${when}: an ifRunning ensure must not start the service`);
105
+ assert.equal(s.startedAt, null, `${when}: a stopped service has no startedAt`);
106
+ assertDirs(s, first, when);
107
+ await assert.rejects(ask("nobody"), `${when}: no service may answer requests`);
108
+ };
109
+ try {
110
+ const before = await ifRunning();
111
+ await assertStopped(before, null, "before any start");
112
+ const again = await ifRunning();
113
+ await assertStopped(again, before, "a second ifRunning ensure");
114
+ const started = await ensure(handle, spec, signal());
115
+ assert.equal(started.state, "running", "a normal ensure starts the service");
116
+ assert.equal(typeof started.startedAt, "string", "a running service has startedAt");
117
+ assertDirs(started, before, "once started");
118
+ const found = await ensure(handle, spec, signal());
119
+ assert.deepEqual(found, started, "a second normal ensure keeps the running service");
120
+ const kept = await ifRunning();
121
+ assert.deepEqual(kept, started, "an ifRunning ensure keeps the running service");
122
+ const answer = await ask("hello conformance");
123
+ assert.equal(new TextDecoder().decode(answer), "hello conformance", "requests round-trip");
124
+ // the running service is still the one started, and it runs the reviewed entry path
125
+ const argv1 = new TextDecoder().decode(await ask(DEVICE_SERVICE_ARGV_PROBE));
126
+ const dir = (started.codeDir ?? started.stateDir).replace(/\/+$/, "");
127
+ assert.equal(argv1, `${dir}/${spec.entry}`, "the service's process.argv[1] must be <codeDir ?? stateDir>/<entry>, the reviewed path");
128
+ await stop(handle, SERVICE, signal());
129
+ const after = await ifRunning();
130
+ await assertStopped(after, before, "after stopService");
131
+ await stop(handle, SERVICE, signal());
132
+ }
133
+ finally {
134
+ try {
135
+ await stop(handle, SERVICE, signal());
136
+ }
137
+ catch {
138
+ // the fixture's dispose removes the instance anyway
139
+ }
140
+ await fixture.dispose();
141
+ }
142
+ }
@@ -22,10 +22,12 @@ export interface DualReplicaOptions {
22
22
  * offline directory (its `*.tgz` files are matched to the entries by sha512); the other entries
23
23
  * are downloaded from `packages.npmRegistry` (set it in `config`, e.g. to a
24
24
  * `startFakeNpmRegistry`). Build both with the kernel tests' `bootstrapFixture` helper.
25
+ * `extraManifest`: the path of an extra bootstrap manifest merged into `manifest`.
25
26
  */
26
27
  bootstrap?: {
27
28
  dir?: string;
28
29
  manifest: BootstrapManifest;
30
+ extraManifest?: string;
29
31
  };
30
32
  /**
31
33
  * 复用已有的 PostgreSQL(管理员连接串,需能 CREATE DATABASE)。传入则只创建并在 stop() 时删除本 harness 的 `cap_*` 库。
@@ -50,6 +52,12 @@ export interface DualReplicaOptions {
50
52
  * with the `api` role; use `requestTo(index, …)` to reach a specific replica.
51
53
  */
52
54
  roles?: [string[], string[]];
55
+ /**
56
+ * Runs against the harness's fresh database before the replicas start (it is not migrated yet:
57
+ * run the kernel migrations first when seeding tables), for state the replicas must find at
58
+ * their start.
59
+ */
60
+ beforeStart?: (dbUrl: string) => Promise<void>;
53
61
  }
54
62
  /** 一个副本(独立子进程)的句柄。 */
55
63
  export interface ReplicaHandle {
@@ -108,7 +116,21 @@ export interface Harness {
108
116
  * 另一个副本照常工作。已退出时是空操作。
109
117
  */
110
118
  kill(index: number): Promise<void>;
111
- /** 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。 */
119
+ /**
120
+ * Stops replica `index` gracefully, through the kernel's own shutdown (as `stop()` does for all of
121
+ * them), and waits for it to exit; the other replicas keep working. A stop stuck for 10 s ends
122
+ * with the replica's own forced exit (code 1), and the harness SIGKILLs it after 15 s. Like after
123
+ * `kill`, `request()` keeps rotating to the stopped replica and requests to it throw. A no-op
124
+ * when it already exited.
125
+ */
126
+ stopReplica(index: number): Promise<void>;
127
+ /**
128
+ * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
129
+ * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
130
+ * lost jobs" canary of the kernel's run-orphan-check, transactional outbox spec §11); after the
131
+ * cleanup it rejects naming such runs, or with the check's own error. A database or Redis it
132
+ * cannot reach skips the check.
133
+ */
112
134
  stop(): Promise<void>;
113
135
  }
114
136
  /**
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { createRequire } from "node:module";
4
4
  import { extname, resolve } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { Redis } from "ioredis";
6
7
  import { createFreshDatabase, sharedPgAdminUrl, startPostgresContainer, startTestRedis, } from "./containers.js";
7
8
  /** 副本在响应头里标明自己的序号(runner 把 `http.replicaId` 设为 `"0"` / `"1"`)。 */
8
9
  export const REPLICA_HEADER = "x-capybara-replica";
@@ -20,6 +21,41 @@ const ALL_ROLES = ["api", "worker", "gateway"];
20
21
  const STOP_TIMEOUT_MS = 15_000;
21
22
  const START_TIMEOUT_MS = 60_000;
22
23
  const STDERR_TAIL = 4000;
24
+ /**
25
+ * The queued runs of the harness's database whose job is neither in the outbox nor in BullMQ (the
26
+ * kernel's `queuedRunsWithoutJob`; a BullMQ job is the hash `bull:<queue>:<jobId>`). Null only when
27
+ * the database or Redis cannot be reached (a test that stopped them: the check is skipped); any
28
+ * other error is thrown.
29
+ */
30
+ async function queuedOrphansOf(dbUrl, redisUrl) {
31
+ // loaded here, not at the top: a process that only spawns replicas (or is killed) never needs
32
+ // the kernel in its own module graph
33
+ const { createDb, kernelDb, queuedRunsWithoutJob } = await import("@capybara-hq/kernel");
34
+ const { sql } = await import("kysely");
35
+ const raw = createDb(dbUrl, 1, () => { }, { connectTimeoutMs: 5000 });
36
+ const redis = new Redis(redisUrl, {
37
+ lazyConnect: true,
38
+ connectTimeout: 5000,
39
+ maxRetriesPerRequest: 1,
40
+ retryStrategy: () => null,
41
+ });
42
+ redis.on("error", () => { });
43
+ try {
44
+ try {
45
+ await redis.connect();
46
+ await sql `SELECT 1`.execute(raw);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ const found = await queuedRunsWithoutJob(kernelDb(raw), async (queue, jobId) => (await redis.exists(`bull:${queue}:${jobId}`)) === 1, { minAgeMs: 0 });
52
+ return found.map((c) => `${c.runId} (conversation ${c.conversationId}, job ${c.jobId})`);
53
+ }
54
+ finally {
55
+ redis.disconnect();
56
+ await raw.destroy().catch(() => { });
57
+ }
58
+ }
23
59
  /** runner 与本文件同目录;源码下是 .ts,编译后是 .js。 */
24
60
  const runnerPath = fileURLToPath(new URL(`./replica-runner${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
25
61
  /**
@@ -120,6 +156,8 @@ export async function createDualReplicaHarness(opts) {
120
156
  const runners = [];
121
157
  let dropDb;
122
158
  let stopPromise;
159
+ /** Set once both replicas started: `stop()` then checks for queued runs without a job. */
160
+ let checkOrphans;
123
161
  const stopRunner = async (r) => {
124
162
  if (r.child.exitCode !== null || r.child.signalCode !== null)
125
163
  return;
@@ -138,9 +176,18 @@ export async function createDualReplicaHarness(opts) {
138
176
  };
139
177
  const stop = () => {
140
178
  stopPromise ??= (async () => {
179
+ const checked = await checkOrphans?.().then((orphans) => ({ orphans }), (error) => ({ error }));
141
180
  await Promise.allSettled(runners.map(stopRunner));
142
181
  await Promise.allSettled([dropDb?.()]);
143
182
  await Promise.allSettled(owned.map((c) => c.stop()));
183
+ if (checked && "error" in checked)
184
+ throw checked.error;
185
+ const orphans = checked?.orphans ?? null;
186
+ if (orphans !== null && orphans.length > 0) {
187
+ throw new Error(`the replicas left ${orphans.length} queued run(s) without a job (neither owed by the ` +
188
+ `outbox nor in BullMQ; the run-orphan-check would report "the queue lost jobs"): ` +
189
+ orphans.join(", "));
190
+ }
144
191
  })();
145
192
  return stopPromise;
146
193
  };
@@ -161,6 +208,7 @@ export async function createDualReplicaHarness(opts) {
161
208
  }
162
209
  const db = await createFreshDatabase(pgUrl);
163
210
  dropDb = db.drop;
211
+ await opts.beforeStart?.(db.url);
164
212
  const config = {
165
213
  dbUrl: db.url,
166
214
  redisUrl,
@@ -169,6 +217,9 @@ export async function createDualReplicaHarness(opts) {
169
217
  ...(opts.bootstrap !== undefined && {
170
218
  bootstrap: {
171
219
  ...(opts.bootstrap.dir !== undefined && { dir: resolve(opts.bootstrap.dir) }),
220
+ ...(opts.bootstrap.extraManifest !== undefined && {
221
+ extraManifest: resolve(opts.bootstrap.extraManifest),
222
+ }),
172
223
  },
173
224
  bootstrapManifest: opts.bootstrap.manifest,
174
225
  }),
@@ -216,6 +267,7 @@ export async function createDualReplicaHarness(opts) {
216
267
  };
217
268
  let calls = 0;
218
269
  let extraChain = Promise.resolve();
270
+ checkOrphans = () => queuedOrphansOf(db.url, redisUrl);
219
271
  const kill = async (index) => {
220
272
  const { runner: r } = runnerAt(index);
221
273
  if (r.child.exitCode === null && r.child.signalCode === null)
@@ -228,6 +280,7 @@ export async function createDualReplicaHarness(opts) {
228
280
  redisUrl,
229
281
  stop,
230
282
  kill,
283
+ stopReplica: (index) => stopRunner(runnerAt(index).runner),
231
284
  startExtraReplica(extraRoles) {
232
285
  // Extra starts run one at a time: the index is the next free slot when the start begins,
233
286
  // and a failed start appends nothing, so there are never holes in the replica indexes
@@ -11,6 +11,9 @@ import type { CardAction, ChannelTarget, DirectoryMember, InboundEvent, Outbound
11
11
  * `code_challenge`(S256)的,换 token 必须带对应的 `codeVerifier`,否则 `invalid_grant`。
12
12
  * - **通讯录**:`GET /d/<key>/members?cursor=<n>` 按页返回 {@link FakeChannelServer.book} 的成员,可让某页失败、让第一页挂起。
13
13
  * - **其他写操作**:`POST /posts` 记下插件工具发的「公告」(`posts`),供断言工具确实执行(且只执行一次)。
14
+ * - **Setup checks**: `POST /checks` records each call of a `fake-im` setup check (`checks`), so a
15
+ * test can count third-party calls across replicas; {@link FakeChannelServer.holdChecks} makes
16
+ * the answers wait (a slow platform API).
14
17
  *
15
18
  * - **Webhook** (the platform calling the kernel): {@link signFakeWebhook} signs a body with HMAC-SHA256
16
19
  * for the `x-fake-signature` header; {@link fakeWebhookEvents} / {@link fakeWebhookChallenge} build bodies.
@@ -40,7 +43,22 @@ export interface FakeChannelSent {
40
43
  pid: number;
41
44
  /** 内核给的幂等键(`ChannelSendArgs.idempotencyKey`)。 */
42
45
  idempotencyKey?: string;
43
- /** 内核给的组织语言(`ChannelSendArgs.locale`)。 */
46
+ /** The language the kernel gave (`ChannelSendArgs.locale`: the recipient's, else the org's). */
47
+ locale?: "zh" | "en";
48
+ at: number;
49
+ }
50
+ /** A file the bot uploaded (`POST /send-file`). */
51
+ export interface FakeChannelSentFile {
52
+ appId: string;
53
+ target: ChannelTarget;
54
+ name: string;
55
+ contentType: string;
56
+ kind: "image" | "file";
57
+ data: Buffer;
58
+ sha256: string;
59
+ messageId: string;
60
+ pid: number;
61
+ idempotencyKey?: string;
44
62
  locale?: "zh" | "en";
45
63
  at: number;
46
64
  }
@@ -71,12 +89,21 @@ export interface FakeDirectoryBook {
71
89
  /** 整轮同步开始的次数(不带游标的请求数)。 */
72
90
  starts(): number;
73
91
  }
74
- /** Which `/send` or `/update` requests a {@link FakeChannelServer.failNext} failure applies to. */
92
+ /** Which `/send`, `/update` or `/send-file` requests a {@link FakeChannelServer.failNext} failure applies to. */
75
93
  export interface FakeChannelFailMatch {
76
94
  chatId?: string;
77
- /** The message's text contains it. */
95
+ /** The message's text (for `/send-file`: the file name) contains it. */
78
96
  textIncludes?: string;
79
97
  }
98
+ /** A `fake-im` setup check's call of `POST /checks`. */
99
+ export interface FakeChannelCheckCall {
100
+ /** The check id. */
101
+ check: string;
102
+ connectionId: string;
103
+ /** The process (replica) that made it (`x-pid`). */
104
+ pid: number;
105
+ at: number;
106
+ }
80
107
  /** 插件工具经 `POST /posts` 发出的一条记录。 */
81
108
  export interface FakeChannelPost {
82
109
  body: Record<string, unknown>;
@@ -99,8 +126,16 @@ export interface FakeChannelServer {
99
126
  updated: FakeChannelSent[];
100
127
  /** 命中幂等键、被平台去重的发送请求(没有产生新消息)。 */
101
128
  duplicateSends: FakeChannelSent[];
129
+ /** Files the bot uploaded (`/send-file`), after dedupe. */
130
+ sentFiles: FakeChannelSentFile[];
131
+ /** `/send-file` requests that hit an idempotency key already seen (no new message). */
132
+ duplicateFiles: FakeChannelSentFile[];
102
133
  /** 插件工具发的公告。 */
103
134
  posts: FakeChannelPost[];
135
+ /** Calls of `fake-im` setup checks (`POST /checks`). */
136
+ checks: FakeChannelCheckCall[];
137
+ /** `POST /checks` answers only once `hold` resolves (null: at once). */
138
+ holdChecks(hold: Promise<void> | null): void;
104
139
  /** 平台用户(OAuth 登录用),按 externalId 索引。 */
105
140
  users: Map<string, FakeChannelUser>;
106
141
  /**
@@ -111,14 +146,14 @@ export interface FakeChannelServer {
111
146
  * text (`textIncludes`: the message's text contains it). Without it the next requests to any chat
112
147
  * fail, so a late delivery from an earlier test can take the failure meant for the request under test.
113
148
  */
114
- failNext(path: "/send" | "/update", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
149
+ failNext(path: "/send" | "/update" | "/send-file", status: number, count?: number, retryAfterMs?: number, reason?: "auth" | "target_gone" | "rejected" | "too_large", delayMs?: number, match?: string | FakeChannelFailMatch): void;
115
150
  /**
116
151
  * Delay the response of the next `count` successful `/send` (or `/update`) requests by `delayMs`.
117
152
  * The message is recorded (visible in `sent` / `updated`) as soon as the request arrives; only the
118
153
  * response carrying its `messageId` is late (a slow platform API, or a sender that dies mid-call).
119
154
  * `onlyCards`: count and delay only requests whose message carries cards.
120
155
  */
121
- delayNext(path: "/send" | "/update", delayMs: number, opts?: {
156
+ delayNext(path: "/send" | "/update" | "/send-file", delayMs: number, opts?: {
122
157
  count?: number;
123
158
  onlyCards?: boolean;
124
159
  }): void;
@@ -144,6 +179,10 @@ export declare function startFakeChannelServer(opts?: FakeChannelServerOptions):
144
179
  export interface FakeSenderProfile {
145
180
  displayName?: string;
146
181
  avatarUrl?: string;
182
+ /** The sender's IANA time zone on the platform (channel@1 `sender.timeZone`). */
183
+ timeZone?: string;
184
+ /** The sender's language tag on the platform (channel@1 `sender.locale`). */
185
+ locale?: string;
147
186
  }
148
187
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
149
188
  export declare function fakeDm(messageId: string, externalId: string, text: string, tenantId?: string, profile?: FakeSenderProfile): InboundEvent;
@@ -20,11 +20,16 @@ export async function startFakeChannelServer(opts = {}) {
20
20
  const sent = [];
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
+ const sentFiles = [];
24
+ const duplicateFiles = [];
23
25
  const posts = [];
26
+ const checks = [];
27
+ let checkHold = null;
24
28
  const users = new Map();
25
29
  const books = new Map();
26
30
  const codes = new Map();
27
31
  const byKey = new Map();
32
+ const fileByKey = new Map();
28
33
  const failures = [];
29
34
  const delays = [];
30
35
  const live = new Map();
@@ -64,7 +69,8 @@ export async function startFakeChannelServer(opts = {}) {
64
69
  const parsed = JSON.parse(body);
65
70
  const matches = (m) => m === undefined ||
66
71
  ((m.chatId === undefined || m.chatId === parsed.target?.chatId) &&
67
- (m.textIncludes === undefined || (parsed.message?.text ?? "").includes(m.textIncludes)));
72
+ (m.textIncludes === undefined ||
73
+ (parsed.message?.text ?? parsed.file?.name ?? "").includes(m.textIncludes)));
68
74
  const f = failures.find((x) => x.path === path && x.left > 0 && matches(x.match));
69
75
  if (f) {
70
76
  f.left--;
@@ -73,6 +79,41 @@ export async function startFakeChannelServer(opts = {}) {
73
79
  json(res, f.status, { retryAfterMs: f.retryAfterMs ?? null, reason: f.reason ?? null });
74
80
  return;
75
81
  }
82
+ if (path === "/send-file") {
83
+ const fb = JSON.parse(body);
84
+ const data = Buffer.from(fb.file.data, "base64");
85
+ const fkey = fb.idempotencyKey ? `${fb.appId}\u0000${fb.idempotencyKey}` : undefined;
86
+ const fseen = fkey !== undefined ? fileByKey.get(fkey) : undefined;
87
+ const fid = fseen ?? `of_${++seq}`;
88
+ const frec = {
89
+ appId: fb.appId,
90
+ target: fb.target,
91
+ name: fb.file.name,
92
+ contentType: fb.file.contentType,
93
+ kind: fb.file.kind,
94
+ data,
95
+ sha256: createHash("sha256").update(data).digest("hex"),
96
+ messageId: fid,
97
+ pid: pidOf(req),
98
+ ...(fb.idempotencyKey !== undefined && { idempotencyKey: fb.idempotencyKey }),
99
+ ...(fb.locale !== undefined && { locale: fb.locale }),
100
+ at: Date.now(),
101
+ };
102
+ if (fseen !== undefined && dedupe)
103
+ duplicateFiles.push(frec);
104
+ else {
105
+ sentFiles.push(frec);
106
+ if (fkey !== undefined && fseen === undefined)
107
+ fileByKey.set(fkey, fid);
108
+ }
109
+ const fd = delays.find((x) => x.path === path && x.left > 0);
110
+ if (fd) {
111
+ fd.left--;
112
+ await new Promise((r) => setTimeout(r, fd.delayMs));
113
+ }
114
+ json(res, 200, { messageId: fid });
115
+ return;
116
+ }
76
117
  const b = JSON.parse(body);
77
118
  const key = b.idempotencyKey ? `${b.appId}\u0000${b.idempotencyKey}` : undefined;
78
119
  const seen = path === "/send" && key !== undefined ? byKey.get(key) : undefined;
@@ -163,7 +204,7 @@ export async function startFakeChannelServer(opts = {}) {
163
204
  const route = `${req.method} ${u.pathname}`;
164
205
  if (route === "GET /connect")
165
206
  return connect(req, res, u);
166
- if (route === "POST /send" || route === "POST /update") {
207
+ if (route === "POST /send" || route === "POST /update" || route === "POST /send-file") {
167
208
  return sendOrUpdate(req, res, u.pathname);
168
209
  }
169
210
  if (route === "POST /bot/verify") {
@@ -177,6 +218,18 @@ export async function startFakeChannelServer(opts = {}) {
177
218
  tenantId: b.tenant ?? "t1",
178
219
  });
179
220
  }
221
+ if (route === "POST /checks") {
222
+ const b = JSON.parse((await readBody(req)) || "{}");
223
+ checks.push({
224
+ check: String(b.check ?? ""),
225
+ connectionId: String(b.connectionId ?? ""),
226
+ pid: pidOf(req),
227
+ at: Date.now(),
228
+ });
229
+ if (checkHold)
230
+ await checkHold;
231
+ return json(res, 200, { ok: true });
232
+ }
180
233
  if (route === "GET /oauth/authorize")
181
234
  return authorize(res, u);
182
235
  if (route === "POST /oauth/token")
@@ -205,7 +258,13 @@ export async function startFakeChannelServer(opts = {}) {
205
258
  sent,
206
259
  updated,
207
260
  duplicateSends,
261
+ sentFiles,
262
+ duplicateFiles,
208
263
  posts,
264
+ checks,
265
+ holdChecks(hold) {
266
+ checkHold = hold;
267
+ },
209
268
  users,
210
269
  failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
211
270
  failures.push({
@@ -268,6 +327,8 @@ const senderOf = (externalId, tenantId, profile = {}) => ({
268
327
  tenantId,
269
328
  ...(profile.displayName !== undefined && { displayName: profile.displayName }),
270
329
  ...(profile.avatarUrl !== undefined && { avatarUrl: profile.avatarUrl }),
330
+ ...(profile.timeZone !== undefined && { timeZone: profile.timeZone }),
331
+ ...(profile.locale !== undefined && { locale: profile.locale }),
271
332
  });
272
333
  /** 私聊文本消息(chat id 为 `dm-<externalId>`);`profile` 给了就带上发言人的显示名 / 头像。 */
273
334
  export function fakeDm(messageId, externalId, text, tenantId = "t1", profile) {