@capybara-hq/testing 0.1.0-rc.12 → 0.1.0-rc.14

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.
@@ -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.
@@ -77,6 +80,15 @@ export interface FakeChannelFailMatch {
77
80
  /** The message's text contains it. */
78
81
  textIncludes?: string;
79
82
  }
83
+ /** A `fake-im` setup check's call of `POST /checks`. */
84
+ export interface FakeChannelCheckCall {
85
+ /** The check id. */
86
+ check: string;
87
+ connectionId: string;
88
+ /** The process (replica) that made it (`x-pid`). */
89
+ pid: number;
90
+ at: number;
91
+ }
80
92
  /** 插件工具经 `POST /posts` 发出的一条记录。 */
81
93
  export interface FakeChannelPost {
82
94
  body: Record<string, unknown>;
@@ -101,6 +113,10 @@ export interface FakeChannelServer {
101
113
  duplicateSends: FakeChannelSent[];
102
114
  /** 插件工具发的公告。 */
103
115
  posts: FakeChannelPost[];
116
+ /** Calls of `fake-im` setup checks (`POST /checks`). */
117
+ checks: FakeChannelCheckCall[];
118
+ /** `POST /checks` answers only once `hold` resolves (null: at once). */
119
+ holdChecks(hold: Promise<void> | null): void;
104
120
  /** 平台用户(OAuth 登录用),按 externalId 索引。 */
105
121
  users: Map<string, FakeChannelUser>;
106
122
  /**
@@ -21,6 +21,8 @@ export async function startFakeChannelServer(opts = {}) {
21
21
  const updated = [];
22
22
  const duplicateSends = [];
23
23
  const posts = [];
24
+ const checks = [];
25
+ let checkHold = null;
24
26
  const users = new Map();
25
27
  const books = new Map();
26
28
  const codes = new Map();
@@ -177,6 +179,18 @@ export async function startFakeChannelServer(opts = {}) {
177
179
  tenantId: b.tenant ?? "t1",
178
180
  });
179
181
  }
182
+ if (route === "POST /checks") {
183
+ const b = JSON.parse((await readBody(req)) || "{}");
184
+ checks.push({
185
+ check: String(b.check ?? ""),
186
+ connectionId: String(b.connectionId ?? ""),
187
+ pid: pidOf(req),
188
+ at: Date.now(),
189
+ });
190
+ if (checkHold)
191
+ await checkHold;
192
+ return json(res, 200, { ok: true });
193
+ }
180
194
  if (route === "GET /oauth/authorize")
181
195
  return authorize(res, u);
182
196
  if (route === "POST /oauth/token")
@@ -206,6 +220,10 @@ export async function startFakeChannelServer(opts = {}) {
206
220
  updated,
207
221
  duplicateSends,
208
222
  posts,
223
+ checks,
224
+ holdChecks(hold) {
225
+ checkHold = hold;
226
+ },
209
227
  users,
210
228
  failNext(path, status, count = 1, retryAfterMs, reason, delayMs, match) {
211
229
  failures.push({
@@ -18,9 +18,11 @@
18
18
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
19
19
  * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
20
20
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
21
+ * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
22
+ * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
21
23
  * | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
22
24
  */
23
- export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-config-form"];
25
+ export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-config-form", "fake-client", "fake-client-broken"];
24
26
  /**
25
27
  * Fake plugins without an extension (declarative: they live in `fixtures/plugins/<name>`, same
26
28
  * pack layout).
package/dist/fixtures.js CHANGED
@@ -21,6 +21,8 @@ import { fileURLToPath } from "node:url";
21
21
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
22
22
  * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
23
23
  * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
24
+ * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
25
+ * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
24
26
  * | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
25
27
  */
26
28
  export const FAKE_EXTENSIONS = [
@@ -38,6 +40,8 @@ export const FAKE_EXTENSIONS = [
38
40
  "fake-web",
39
41
  "fake-web-2",
40
42
  "fake-config-form",
43
+ "fake-client",
44
+ "fake-client-broken",
41
45
  ];
42
46
  /**
43
47
  * Fake plugins without an extension (declarative: they live in `fixtures/plugins/<name>`, same
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig
7
7
  export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
8
8
  export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
- export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
10
+ export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
12
  export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, startFakeGitServer, } from "./fake-git-server.js";
13
13
  export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
@@ -0,0 +1,11 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-client",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: client extension components in five slots, CSS decoration, an events listener and a suggested appearance",
7
+ "suggestedAppearance": {
8
+ "theme": "fake",
9
+ "replacements": { "shell.brand": "brand" }
10
+ }
11
+ }
@@ -0,0 +1,11 @@
1
+ [data-cap-part~="button.primary"] {
2
+ outline-color: rgb(1, 2, 3);
3
+ }
4
+
5
+ [data-cap-part~="composer"] [data-cap-part~="button"] {
6
+ outline-color: rgb(1, 2, 3);
7
+ }
8
+
9
+ [data-cap-state~="run=running"] {
10
+ --cx-fake-client-run: 1;
11
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-client",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: client extension components in five slots, CSS decoration, an events listener and a suggested appearance",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "@capybara-hq/plugin-client": "^0.1.0-rc.0",
10
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.0"
11
+ }
12
+ }
@@ -0,0 +1,51 @@
1
+ import {
2
+ defineClientExtension,
3
+ defineComponent,
4
+ useClientStorage,
5
+ useView,
6
+ } from "@capybara-hq/plugin-client";
7
+
8
+ const Hud = () => {
9
+ // useView() is the view state ({ view, status, retry }); the server view's data is on `view`
10
+ const { view } = useView();
11
+ const data = view?.data as { n?: number } | undefined;
12
+ return <span data-testid="fake-client-hud">{`hud ${data?.n ?? "-"}`}</span>;
13
+ };
14
+
15
+ const Brand = ({ builtin }: { builtin: unknown }) => (
16
+ <span data-testid="fake-client-brand">{builtin as never}</span>
17
+ );
18
+
19
+ const Empty = ({ greeting }: { greeting: string }) => (
20
+ <p data-testid="fake-client-empty">{greeting}</p>
21
+ );
22
+
23
+ const Frame = ({ children }: { children?: unknown }) => (
24
+ <div data-testid="fake-client-frame">{children as never}</div>
25
+ );
26
+
27
+ const Fx = () => {
28
+ const storage = useClientStorage();
29
+ return <i data-testid="fake-client-fx" data-last={storage.get("last") ?? ""} />;
30
+ };
31
+
32
+ export default defineClientExtension({
33
+ name: "fake-client",
34
+ components: {
35
+ hud: defineComponent("conversation.properties.section", Hud),
36
+ brand: defineComponent("shell.brand", Brand),
37
+ empty: defineComponent("conversation.empty", Empty),
38
+ frame: defineComponent("conversation.composer.frame", Frame),
39
+ fx: defineComponent("shell.overlay", Fx),
40
+ },
41
+ events: {
42
+ "run.started": (e, api) => api.storage.set("last", e.type),
43
+ "run.finished": (e, api) => api.storage.set("last", e.type),
44
+ "run.failed": (e, api) => api.storage.set("last", e.type),
45
+ "message.sent": (e, api) => api.storage.set("last", e.type),
46
+ "message.received": (e, api) => api.storage.set("last", e.type),
47
+ "tool.started": (e, api) => api.storage.set("last", e.type),
48
+ "tool.finished": (e, api) => api.storage.set("last", e.type),
49
+ "approval.requested": (e, api) => api.storage.set("last", e.type),
50
+ },
51
+ });
@@ -0,0 +1,43 @@
1
+ import { defineExtension, type UiView } from "@capybara-hq/plugin-sdk";
2
+
3
+ const t = (zh: string, en: string) => ({ zh, en });
4
+
5
+ /**
6
+ * Test fake of a client extension (client extensions spec §5): one component in each of
7
+ * `conversation.properties.section` (`hud`, server view answering `data: { n: 1 }`), `shell.brand`
8
+ * (`brand`), `conversation.empty` (`empty`), `conversation.composer.frame` (`frame`) and
9
+ * `shell.overlay` (`fx`). The browser side is `src/client.tsx` (components and an `events`
10
+ * listener), `client/styles/fake.css` decorates by part and state, and the theme `fake` is the
11
+ * plugin's `suggestedAppearance` together with `shell.brand` -> `brand`.
12
+ */
13
+ export default defineExtension({
14
+ name: "fake-client",
15
+ version: "0.1.0",
16
+ sdk: "^0.1.0-rc.0",
17
+ provides: [],
18
+ ui: [
19
+ {
20
+ id: "hud",
21
+ title: t("状态", "Status"),
22
+ slot: "conversation.properties.section",
23
+ kind: "component",
24
+ },
25
+ { id: "brand", title: t("品牌", "Brand"), slot: "shell.brand", kind: "component" },
26
+ { id: "empty", title: t("问候", "Greeting"), slot: "conversation.empty", kind: "component" },
27
+ {
28
+ id: "frame",
29
+ title: t("边框", "Frame"),
30
+ slot: "conversation.composer.frame",
31
+ kind: "component",
32
+ },
33
+ { id: "fx", title: t("特效", "Effects"), slot: "shell.overlay", kind: "component" },
34
+ ],
35
+ permissions: {
36
+ client: true,
37
+ ui: { components: ["hud", "brand", "empty", "frame", "fx"] },
38
+ },
39
+ setup(ctx) {
40
+ const withData = (n: number): UiView => ({ blocks: [], data: { n } });
41
+ ctx.ui.view("hud", async () => withData(1));
42
+ },
43
+ });
@@ -0,0 +1,11 @@
1
+ {
2
+ "name": { "en": "Fake client", "zh": "客户端样例" },
3
+ "schemes": {
4
+ "light": {
5
+ "color": { "accent": "#1F5FBF", "on-accent": "#FFFFFF" }
6
+ },
7
+ "dark": {
8
+ "color": { "accent": "#8FB8FF", "on-accent": "#0B1220" }
9
+ }
10
+ }
11
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-client-broken",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: client code that throws (a component, an events listener and a conversation.empty replacement)"
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-client-broken",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: client code that throws (a component, an events listener and a conversation.empty replacement)",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "@capybara-hq/plugin-client": "^0.1.0-rc.0",
10
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.0"
11
+ }
12
+ }
@@ -0,0 +1,22 @@
1
+ import { defineClientExtension, defineComponent } from "@capybara-hq/plugin-client";
2
+
3
+ const Boom = (): never => {
4
+ throw new Error("fake-client-broken: boom");
5
+ };
6
+
7
+ const Empty = (): never => {
8
+ throw new Error("fake-client-broken: empty");
9
+ };
10
+
11
+ export default defineClientExtension({
12
+ name: "fake-client-broken",
13
+ components: {
14
+ boom: defineComponent("conversation.properties.section", Boom),
15
+ empty: defineComponent("conversation.empty", Empty),
16
+ },
17
+ events: {
18
+ "run.started": () => {
19
+ throw new Error("fake-client-broken: run.started");
20
+ },
21
+ },
22
+ });
@@ -0,0 +1,27 @@
1
+ import { defineExtension } from "@capybara-hq/plugin-sdk";
2
+
3
+ const t = (zh: string, en: string) => ({ zh, en });
4
+
5
+ /**
6
+ * Test fake of a client extension whose browser code is broken, for the host's isolation (error
7
+ * boundaries, the crash budget, safe mode): component `boom` (`conversation.properties.section`)
8
+ * throws on render, the module-level `events` listener throws on `run.started`, and `empty`
9
+ * (`conversation.empty`) throws on render. No server side beyond the declarations.
10
+ */
11
+ export default defineExtension({
12
+ name: "fake-client-broken",
13
+ version: "0.1.0",
14
+ sdk: "^0.1.0-rc.0",
15
+ provides: [],
16
+ ui: [
17
+ {
18
+ id: "boom",
19
+ title: t("崩溃", "Boom"),
20
+ slot: "conversation.properties.section",
21
+ kind: "component",
22
+ },
23
+ { id: "empty", title: t("问候", "Greeting"), slot: "conversation.empty", kind: "component" },
24
+ ],
25
+ permissions: { client: true, ui: { components: ["boom", "empty"] } },
26
+ setup() {},
27
+ });
@@ -7,33 +7,7 @@
7
7
  "setupGuides": [
8
8
  {
9
9
  "id": "fake-im-app",
10
- "place": "channel-connection",
11
- "title": { "en": "Create the fake IM app", "zh": "创建 fake IM 应用" },
12
- "steps": [
13
- {
14
- "en": "Open the fake platform console and create an app from the manifest below.",
15
- "zh": "打开 fake 平台控制台,用下面的 manifest 创建应用。"
16
- },
17
- {
18
- "mode": "webhook",
19
- "en": "The platform posts events to `{{webhookUrl}}`.",
20
- "zh": "平台把事件发到 `{{webhookUrl}}`。"
21
- }
22
- ],
23
- "files": [
24
- {
25
- "path": "./guides/app.long-connection.yaml.tmpl",
26
- "title": { "en": "App manifest", "zh": "应用 manifest" },
27
- "language": "yaml",
28
- "mode": "long_connection"
29
- },
30
- {
31
- "path": "./guides/app.webhook.json.tmpl",
32
- "title": { "en": "App manifest", "zh": "应用 manifest" },
33
- "language": "json",
34
- "mode": "webhook"
35
- }
36
- ]
10
+ "place": "channel-connection"
37
11
  }
38
12
  ]
39
13
  }
@@ -0,0 +1,32 @@
1
+ # Create the fake IM app
2
+
3
+ Open the fake platform console and create an app from the manifest below.
4
+
5
+ ::: mode long_connection
6
+
7
+ ```yaml title="App manifest"
8
+ # The fake IM app, fake-im {{pluginVersion}}.
9
+ app:
10
+ name: "{{connectionName}}"
11
+ long_connection: true
12
+ sign_in_redirect: "{{signInCallbackUrl}}"
13
+ ```
14
+
15
+ :::
16
+
17
+ ::: mode webhook
18
+
19
+ The platform posts events to `{{webhookUrl}}`.
20
+
21
+ ```json title="App manifest"
22
+ {
23
+ "app": {
24
+ "name": "{{connectionName}}",
25
+ "long_connection": false,
26
+ "request_url": "{{webhookUrl}}",
27
+ "sign_in_redirect": "{{signInCallbackUrl}}"
28
+ }
29
+ }
30
+ ```
31
+
32
+ :::
@@ -0,0 +1,32 @@
1
+ # 创建 fake IM 应用
2
+
3
+ 打开 fake 平台控制台,用下面的 manifest 创建应用。
4
+
5
+ ::: mode long_connection
6
+
7
+ ```yaml title="应用 manifest"
8
+ # The fake IM app, fake-im {{pluginVersion}}.
9
+ app:
10
+ name: "{{connectionName}}"
11
+ long_connection: true
12
+ sign_in_redirect: "{{signInCallbackUrl}}"
13
+ ```
14
+
15
+ :::
16
+
17
+ ::: mode webhook
18
+
19
+ 平台把事件发到 `{{webhookUrl}}`。
20
+
21
+ ```json title="应用 manifest"
22
+ {
23
+ "app": {
24
+ "name": "{{connectionName}}",
25
+ "long_connection": false,
26
+ "request_url": "{{webhookUrl}}",
27
+ "sign_in_redirect": "{{signInCallbackUrl}}"
28
+ }
29
+ }
30
+ ```
31
+
32
+ :::
@@ -0,0 +1,94 @@
1
+ import type { SetupCheckArgs, SetupCheckDefinition } from "@capybara-hq/plugin-sdk";
2
+ import { FakeImConnection } from "./channel.js";
3
+
4
+ /**
5
+ * The setup checks of `fake-im` (setup guides v2 §10), one per behavior the kernel's runner must
6
+ * handle. Each is registered in `index.ts` with a literal id (the `perm-setup-check` rule):
7
+ *
8
+ * - `pass` / `fail`: ok, and failing with a reason and a fix (no third-party call);
9
+ * - `proxy`: one `POST <platformUrl>/checks` per run (counted by `FakeChannelServer.checks`, held
10
+ * by `holdChecks`), then ok: what a real check's third-party call looks like;
11
+ * - `throw`: throws an error whose message carries the connection's `appSecret`;
12
+ * - `hang`: waits for `signal` and rejects when it aborts (a well-behaved slow check);
13
+ * - `ignore-signal`: never settles, whatever `signal` does;
14
+ * - `long`: a reason over the 300-character limit (an invalid result);
15
+ * - `echo-secret`: puts the connection's `appSecret` into the reason and the fix, and the
16
+ * deployment config's `clientSecret` (from `args.config`) into the fix;
17
+ * - `pad-to-limit`: a reason of exactly 300 characters that contains the connection's
18
+ * `webhookToken` (set it to 8 or 9 characters): valid as returned, too long once redacted.
19
+ */
20
+
21
+ const conn = (args: SetupCheckArgs) => {
22
+ if (args.target.kind !== "channel-connection") throw new Error("not a channel connection");
23
+ return FakeImConnection.parse(args.target.config);
24
+ };
25
+
26
+ const channelCheck = (run: SetupCheckDefinition["run"]): SetupCheckDefinition => ({
27
+ place: "channel-connection",
28
+ run,
29
+ });
30
+
31
+ export const passCheck = channelCheck(async () => ({
32
+ status: "ok",
33
+ reason: { en: "The fake platform accepted the app.", zh: "fake 平台接受了这个应用。" },
34
+ }));
35
+
36
+ export const failCheck = channelCheck(async () => ({
37
+ status: "failing",
38
+ reason: { en: "The fake platform refused the app." },
39
+ fix: { en: "Create the app again and copy the new secret." },
40
+ }));
41
+
42
+ export const proxyCheck = channelCheck(async (args) => {
43
+ const c = conn(args);
44
+ const res = await fetch(`${c.platformUrl}/checks`, {
45
+ method: "POST",
46
+ headers: { "content-type": "application/json", "x-pid": String(process.pid) },
47
+ body: JSON.stringify({
48
+ check: "proxy",
49
+ connectionId: args.target.kind === "channel-connection" ? args.target.connectionId : "",
50
+ }),
51
+ signal: args.signal,
52
+ });
53
+ await res.body?.cancel();
54
+ return res.status === 200
55
+ ? { status: "ok", reason: { en: "The fake platform answered." } }
56
+ : { status: "unknown", reason: { en: "The fake platform did not answer; retry later." } };
57
+ });
58
+
59
+ export const throwCheck = channelCheck(async (args) => {
60
+ throw new Error(`the platform refused ${conn(args).appSecret}`);
61
+ });
62
+
63
+ export const hangCheck = channelCheck(
64
+ (args) =>
65
+ new Promise((_, reject) => {
66
+ const stop = () => reject(new Error("aborted"));
67
+ if (args.signal.aborted) stop();
68
+ else args.signal.addEventListener("abort", stop, { once: true });
69
+ }),
70
+ );
71
+
72
+ export const ignoreSignalCheck = channelCheck(() => new Promise(() => {}));
73
+
74
+ export const longCheck = channelCheck(async () => ({
75
+ status: "ok",
76
+ reason: { en: "x".repeat(301) },
77
+ }));
78
+
79
+ export const echoSecretCheck = channelCheck(async (args) => {
80
+ const secret = conn(args).appSecret;
81
+ const client = (args.config as { clientSecret?: string } | null)?.clientSecret ?? "";
82
+ return {
83
+ status: "failing",
84
+ reason: { en: `The platform refused ${secret}.`, zh: `平台拒绝了 ${secret}。` },
85
+ fix: { en: `Replace ${secret} with a new secret (login client ${client}).` },
86
+ };
87
+ });
88
+
89
+ export const padToLimitCheck = channelCheck(async (args) => {
90
+ const c = conn(args);
91
+ const secret = c.webhookToken ?? c.appSecret;
92
+ const head = `Token ${secret} `;
93
+ return { status: "ok", reason: { en: head + "x".repeat(300 - head.length) } };
94
+ });
@@ -7,6 +7,17 @@ import {
7
7
  } from "@capybara-hq/plugin-sdk";
8
8
  import { z } from "zod";
9
9
  import { makeFakeImChannel } from "./channel.js";
10
+ import {
11
+ echoSecretCheck,
12
+ failCheck,
13
+ hangCheck,
14
+ ignoreSignalCheck,
15
+ longCheck,
16
+ padToLimitCheck,
17
+ passCheck,
18
+ proxyCheck,
19
+ throwCheck,
20
+ } from "./checks.js";
10
21
  import { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
11
22
  import { fakeImIdentitySource } from "./identity.js";
12
23
 
@@ -70,13 +81,27 @@ const postHandler =
70
81
  * 假 IM 平台的完整测试插件(连 `@capybara-hq/testing` 的 startFakeChannelServer):
71
82
  * `channel@1`(机器人)+ `identity-source@1`(登录)+ `directory@1`(通讯录),另带一个默认需要批准的写工具。
72
83
  * 三处的身份源键都是 `fake-im:<租户>`,同一个人只对应一行身份。T15–T18 的真实渠道插件照这个形状写。
84
+ * It also registers setup checks for the kernel's check runner tests (`checks.ts`).
73
85
  */
74
86
  export default defineExtension({
75
87
  name: "fake-im",
76
88
  version: "0.1.0",
77
89
  sdk: "^0.1.0-rc.0",
78
90
  provides: ["channel@1", "identity-source@1", "directory@1"],
79
- permissions: { tools: ["post_announcement"] },
91
+ permissions: {
92
+ tools: ["post_announcement"],
93
+ setupChecks: [
94
+ "pass",
95
+ "fail",
96
+ "proxy",
97
+ "throw",
98
+ "hang",
99
+ "ignore-signal",
100
+ "long",
101
+ "echo-secret",
102
+ "pad-to-limit",
103
+ ],
104
+ },
80
105
  config: { deployment: Deployment, org: FakeImOrgConfig },
81
106
  setup(ctx) {
82
107
  const config = () => Deployment.parse(ctx.config);
@@ -87,5 +112,15 @@ export default defineExtension({
87
112
  ctx.provide("identity-source@1", fakeImIdentitySource);
88
113
  ctx.provide("directory@1", fakeImDirectory);
89
114
  ctx.tools.register(POST_SPEC, postHandler(config));
115
+ // setup checks for the kernel's check runner tests (checks.ts says what each does)
116
+ ctx.setup.check("pass", passCheck);
117
+ ctx.setup.check("fail", failCheck);
118
+ ctx.setup.check("proxy", proxyCheck);
119
+ ctx.setup.check("throw", throwCheck);
120
+ ctx.setup.check("hang", hangCheck);
121
+ ctx.setup.check("ignore-signal", ignoreSignalCheck);
122
+ ctx.setup.check("long", longCheck);
123
+ ctx.setup.check("echo-secret", echoSecretCheck);
124
+ ctx.setup.check("pad-to-limit", padToLimitCheck);
90
125
  },
91
126
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.12",
3
+ "version": "0.1.0-rc.14",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,17 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.13"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.15"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.9"
55
+ "@capybara-hq/plugin-client": "^0.1.0-rc.1",
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.11"
56
57
  },
57
58
  "peerDependencies": {
58
59
  "vitest": "^5.0.5",
59
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.9",
60
- "@capybara-hq/plugin-tools": "^0.1.0-rc.10"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.11",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.12"
61
62
  },
62
63
  "peerDependenciesMeta": {
63
64
  "@capybara-hq/plugin-tools": {
@@ -1,5 +0,0 @@
1
- # The fake IM app for "{{connectionName}}" ({{orgName}}), fake-im {{pluginVersion}}.
2
- app:
3
- name: "{{connectionName}}"
4
- long_connection: true
5
- sign_in_redirect: "{{signInCallbackUrl}}"
@@ -1,8 +0,0 @@
1
- {
2
- "app": {
3
- "name": "{{connectionName}}",
4
- "long_connection": false,
5
- "request_url": "{{webhookUrl}}",
6
- "sign_in_redirect": "{{signInCallbackUrl}}"
7
- }
8
- }