@capybara-hq/testing 0.1.0-rc.11 → 0.1.0-rc.13

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({
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";
@@ -1,4 +1,4 @@
1
- import { defineExtension, EMBED_PROTOCOL, type EmbedClaims } from "@capybara-hq/plugin-sdk";
1
+ import { defineExtension, EMBED_PROTOCOL, type OrgEmbedClaims } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
 
4
4
  /**
@@ -96,14 +96,14 @@ export default defineExtension({
96
96
  {
97
97
  id: "panel",
98
98
  title: { zh: "面板", en: "Panel" },
99
- place: "page",
99
+ slot: "org.page",
100
100
  kind: "embed",
101
101
  path: "/ui/panel",
102
102
  },
103
103
  {
104
104
  id: "panel-conv",
105
105
  title: { zh: "面板", en: "Panel" },
106
- place: "conversation",
106
+ slot: "conversation.panel",
107
107
  kind: "embed",
108
108
  path: "/ui/panel-conv",
109
109
  },
@@ -120,9 +120,11 @@ export default defineExtension({
120
120
  ui: { embeds: ["panel", "panel-conv"] },
121
121
  },
122
122
  setup(ctx) {
123
- const auth = async (req: Request): Promise<EmbedClaims | null> => {
123
+ /** An org-scope token's claims (every contribution here is in an org slot), or null. */
124
+ const auth = async (req: Request): Promise<OrgEmbedClaims | null> => {
124
125
  const m = BEARER_RE.exec(req.headers.get("authorization") ?? "");
125
- return m?.[1] === undefined ? null : ctx.ui.verifyEmbedToken(m[1]);
126
+ const claims = m?.[1] === undefined ? null : await ctx.ui.verifyEmbedToken(m[1]);
127
+ return claims?.scope === "org" ? claims : null;
126
128
  };
127
129
  const page = async () =>
128
130
  new Response(PAGE, { headers: { "content-type": "text/html; charset=utf-8" } });
@@ -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
  });
@@ -104,8 +104,31 @@ export default defineExtension({
104
104
  sdk: "^0.1.0-rc.0",
105
105
  provides: [],
106
106
  migrations: "../migrations",
107
- ui: [{ id: "tasks", title: { zh: "条目", en: "Items" }, place: "conversation", kind: "view" }],
108
- permissions: { tools: ["write"], ui: { views: ["tasks"] } },
107
+ ui: [
108
+ { id: "tasks", title: { zh: "条目", en: "Items" }, slot: "conversation.panel", kind: "view" },
109
+ {
110
+ id: "agent-notes",
111
+ title: { zh: "智能体备注", en: "Agent notes" },
112
+ slot: "agent.detail.section",
113
+ kind: "view",
114
+ },
115
+ {
116
+ id: "org-admin",
117
+ title: { zh: "组织设置扩展", en: "Org admin" },
118
+ slot: "org.settings.section",
119
+ kind: "view",
120
+ },
121
+ {
122
+ id: "platform-home",
123
+ title: { zh: "平台首页", en: "Platform home" },
124
+ slot: "platform.page",
125
+ kind: "view",
126
+ },
127
+ ],
128
+ permissions: {
129
+ tools: ["write"],
130
+ ui: { views: ["tasks", "agent-notes", "org-admin", "platform-home"] },
131
+ },
109
132
  setup(ctx) {
110
133
  ctx.tools.register(WRITE, async (input, tctx) => {
111
134
  const parsed = WriteInput.safeParse(input);
@@ -136,5 +159,21 @@ export default defineExtension({
136
159
  ctx.ui.view("tasks", async ({ conversationId }) =>
137
160
  tasksView(conversationId === undefined ? [] : await readItems(ctx.db, conversationId)),
138
161
  );
162
+ const ping: UiView["blocks"] = [
163
+ { type: "actions", buttons: [{ actionId: "ping", label: "Ping" }] },
164
+ ];
165
+ const done = async () => ({ toast: { zh: "已完成", en: "Done" } });
166
+ ctx.ui.view("agent-notes", async (args) => ({
167
+ blocks: [{ type: "heading", text: `Agent ${args.agentId ?? ""}`.trim() }, ...ping],
168
+ }));
169
+ ctx.ui.action("agent-notes", done);
170
+ ctx.ui.view("org-admin", async () => ({
171
+ blocks: [{ type: "heading", text: "Org settings" }, ...ping],
172
+ }));
173
+ ctx.ui.action("org-admin", done);
174
+ ctx.ui.view("platform-home", async () => ({
175
+ blocks: [{ type: "heading", text: "Platform home" }, ...ping],
176
+ }));
177
+ ctx.ui.action("platform-home", done);
139
178
  },
140
179
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.11",
3
+ "version": "0.1.0-rc.13",
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,17 @@
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.11"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.14"
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.8"
55
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.10"
56
56
  },
57
57
  "peerDependencies": {
58
58
  "vitest": "^5.0.5",
59
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.8",
60
- "@capybara-hq/plugin-tools": "^0.1.0-rc.9"
59
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.10",
60
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.11"
61
61
  },
62
62
  "peerDependenciesMeta": {
63
63
  "@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
- }