channelstack 0.0.0-placeholder.0 → 0.1.1

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 (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +55 -1
  3. package/bin/channelstack.mjs +31 -0
  4. package/dist/integrations/checks/checks.test.d.ts +1 -0
  5. package/dist/integrations/checks/checks.test.js +31 -0
  6. package/dist/integrations/checks/index.d.ts +69 -0
  7. package/dist/integrations/checks/index.js +578 -0
  8. package/dist/integrations/matchers-core/index.d.ts +138 -0
  9. package/dist/integrations/matchers-core/index.js +458 -0
  10. package/dist/integrations/matchers-core/matchers.test.d.ts +1 -0
  11. package/dist/integrations/matchers-core/matchers.test.js +159 -0
  12. package/dist/integrations/vitest/global-setup.d.ts +3 -0
  13. package/dist/integrations/vitest/global-setup.js +19 -0
  14. package/dist/integrations/vitest/index.d.ts +80 -0
  15. package/dist/integrations/vitest/index.js +42 -0
  16. package/dist/integrations/vitest/plugin.test.d.ts +1 -0
  17. package/dist/integrations/vitest/plugin.test.js +19 -0
  18. package/dist/integrations/vitest/refused.d.ts +22 -0
  19. package/dist/integrations/vitest/refused.js +49 -0
  20. package/dist/integrations/vitest/setup.d.ts +1 -0
  21. package/dist/integrations/vitest/setup.js +109 -0
  22. package/dist/sdks/typescript/client.d.ts +13 -0
  23. package/dist/sdks/typescript/client.js +11 -0
  24. package/dist/sdks/typescript/generated/channels.d.ts +24 -0
  25. package/dist/sdks/typescript/generated/channels.js +2 -0
  26. package/dist/sdks/typescript/generated/index.d.ts +2747 -0
  27. package/dist/sdks/typescript/generated/index.js +3039 -0
  28. package/dist/sdks/typescript/runtime/client.d.ts +47 -0
  29. package/dist/sdks/typescript/runtime/client.js +69 -0
  30. package/dist/sdks/typescript/runtime/credentials.d.ts +7 -0
  31. package/dist/sdks/typescript/runtime/credentials.js +20 -0
  32. package/dist/sdks/typescript/runtime/duration.d.ts +4 -0
  33. package/dist/sdks/typescript/runtime/duration.js +13 -0
  34. package/dist/sdks/typescript/runtime/files.d.ts +32 -0
  35. package/dist/sdks/typescript/runtime/files.js +45 -0
  36. package/dist/sdks/typescript/runtime/launcher.d.ts +24 -0
  37. package/dist/sdks/typescript/runtime/launcher.js +121 -0
  38. package/dist/sdks/typescript/runtime/transport.d.ts +43 -0
  39. package/dist/sdks/typescript/runtime/transport.js +95 -0
  40. package/dist/sdks/typescript/runtime/wait.d.ts +82 -0
  41. package/dist/sdks/typescript/runtime/wait.js +136 -0
  42. package/dist/sdks/typescript/types.d.ts +72 -0
  43. package/dist/sdks/typescript/types.js +1 -0
  44. package/package.json +78 -4
  45. package/index.js +0 -1
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The channel matchers, independent of any test framework. Each one reads plain SDK methods and
3
+ * returns whether it passed and what to say if not; `integrations/vitest` only
4
+ * adapt them to their `expect`.
5
+ *
6
+ * - A positive matcher polls until its condition holds, or fails after the timeout.
7
+ * - A negated matcher, and one with an exact count, waits until the agent is quiet and checks once.
8
+ */
9
+ import { type Duration, type SlackConversation } from "../../sdks/typescript/client.ts";
10
+ export interface MatcherResult {
11
+ pass: boolean;
12
+ /** Why it failed (or, for a negated matcher, why it unexpectedly passed). */
13
+ message: () => string;
14
+ }
15
+ export interface MatcherState {
16
+ /** True under `.not`. */
17
+ isNot: boolean;
18
+ /** The test framework's own equality, which understands asymmetric matchers (`expect.any(Number)`). */
19
+ equals?: (actual: unknown, expected: unknown) => boolean;
20
+ /** Defaults from the integration's options. */
21
+ timeout: Duration;
22
+ quietFor: Duration;
23
+ }
24
+ interface Timing {
25
+ timeout?: Duration;
26
+ quietFor?: Duration;
27
+ }
28
+ type Author = {
29
+ readonly id: string;
30
+ readonly name: string;
31
+ };
32
+ type AuthorRef = Author | string;
33
+ /** Who a transcript is read as: the SDK's own type, so a change to that signature fails to compile here. */
34
+ type Viewer = NonNullable<NonNullable<Parameters<SlackConversation["transcript"]>[0]>["as"]>;
35
+ export declare const matchers: {
36
+ /** The thread (or DM) has at least one reply from this author. */
37
+ toHaveReplyFrom(state: MatcherState, subject: unknown, author: AuthorRef, options?: Timing & {
38
+ text?: string | RegExp;
39
+ }): Promise<MatcherResult>;
40
+ /** Exactly `count` replies from this author, checked once the agent is quiet. */
41
+ toHaveRepliesFrom(state: MatcherState, subject: unknown, author: AuthorRef, options: Timing & {
42
+ count: number;
43
+ text?: string | RegExp;
44
+ }): Promise<MatcherResult>;
45
+ /** A message from this author directly in the channel, outside any thread. */
46
+ toHaveChannelMessageFrom(state: MatcherState, subject: unknown, author: AuthorRef, options?: Timing): Promise<MatcherResult>;
47
+ /** Some entry a person would see contains this text. `count` makes it exact. */
48
+ toContainText(state: MatcherState, subject: unknown, text: string | RegExp, options?: Timing & {
49
+ count?: number;
50
+ from?: AuthorRef;
51
+ as?: Viewer;
52
+ }): Promise<MatcherResult>;
53
+ /** A reply from this author is being streamed right now. */
54
+ toHaveStreamingReplyFrom(state: MatcherState, subject: unknown, author?: AuthorRef, options?: Timing): Promise<MatcherResult>;
55
+ /** The agent's state in this thread: `working`, `streaming`, `stopped` or `idle`. */
56
+ toHaveStatus(state: MatcherState, subject: unknown, expected: "working" | "streaming" | "stopped" | "idle", options?: Timing): Promise<MatcherResult>;
57
+ /** The status line the agent set. */
58
+ toHaveStatusText(state: MatcherState, subject: unknown, text: string | RegExp, options?: Timing): Promise<MatcherResult>;
59
+ /** The message has a button with this label; for a thread or a conversation, the agent's latest message there. */
60
+ toHaveButton(state: MatcherState, subject: unknown, label: string | RegExp, options?: Timing): Promise<MatcherResult>;
61
+ toHaveReaction(state: MatcherState, subject: unknown, emoji: string, options?: Timing & {
62
+ by?: AuthorRef;
63
+ }): Promise<MatcherResult>;
64
+ /** Subject: a person. The agent opened a modal for them (it may be submitted by now), with this title if one is given. */
65
+ toHaveOpenedModal(state: MatcherState, subject: unknown, title?: string | RegExp, options?: Timing): Promise<MatcherResult>;
66
+ /** Subject: a GitHub issue or pull request, a Linear issue or a Notion discussion. At least one comment from this author. */
67
+ toHaveCommentFrom(state: MatcherState, subject: unknown, author: AuthorRef, options?: Timing & {
68
+ text?: string | RegExp;
69
+ }): Promise<MatcherResult>;
70
+ /** Exactly `count` comments from this author, checked once the agent is quiet. */
71
+ toHaveCommentsFrom(state: MatcherState, subject: unknown, author: AuthorRef, options: Timing & {
72
+ count: number;
73
+ }): Promise<MatcherResult>;
74
+ /** Subject: a pull request. A comment on the diff, matched by every field that is given. */
75
+ toHaveReviewComment(state: MatcherState, subject: unknown, expected: {
76
+ path?: string;
77
+ line?: number;
78
+ from?: AuthorRef;
79
+ text?: string | RegExp;
80
+ }, options?: Timing): Promise<MatcherResult>;
81
+ /** Subject: a pull request. A review from this author, with this verdict if one is given. */
82
+ toHaveReviewFrom(state: MatcherState, subject: unknown, author: AuthorRef, options?: Timing & {
83
+ state?: string;
84
+ }): Promise<MatcherResult>;
85
+ /** Subject: a pull request or a commit. A check run of this name, in this state if one is given. */
86
+ toHaveCheckRun(state: MatcherState, subject: unknown, name: string | RegExp, options?: Timing & {
87
+ status?: string;
88
+ conclusion?: string;
89
+ }): Promise<MatcherResult>;
90
+ /** Subject: an issue or a pull request. It has this label. */
91
+ toHaveLabel(state: MatcherState, subject: unknown, name: string, options?: Timing): Promise<MatcherResult>;
92
+ /** Subject: a pull request. It has been merged. */
93
+ toBeMerged(state: MatcherState, subject: unknown, options?: Timing): Promise<MatcherResult>;
94
+ /** Subject: a Linear agent session, or an issue (its latest session). The session's status. */
95
+ toHaveSessionState(state: MatcherState, subject: unknown, wanted: string, options?: Timing): Promise<MatcherResult>;
96
+ /**
97
+ * Subject: a Linear agent session, or an issue (its latest session). An activity of the agent's
98
+ * matching every field that is given: a person's turns (`prompt`, delegating's first among them)
99
+ * aren't what it published.
100
+ */
101
+ toHaveActivity(state: MatcherState, subject: unknown, expected: {
102
+ type?: string;
103
+ from?: AuthorRef;
104
+ text?: string | RegExp;
105
+ }, options?: Timing): Promise<MatcherResult>;
106
+ /** Subject: a Linear issue. It is delegated to this app, or (with `undefined`) to none. */
107
+ toBeDelegatedTo(state: MatcherState, subject: unknown, app: Author | undefined, options?: Timing): Promise<MatcherResult>;
108
+ /** Subject: a Linear issue. It is assigned to this person, or (with `undefined`) to no one. */
109
+ toBeAssignedTo(state: MatcherState, subject: unknown, user: Author | undefined, options?: Timing): Promise<MatcherResult>;
110
+ /** Subject: a Notion page. A block (at any depth) whose text matches. */
111
+ toHaveBlock(state: MatcherState, subject: unknown, text: string | RegExp, options?: Timing): Promise<MatcherResult>;
112
+ /** Subject: a Notion page. A property has this value; asymmetric matchers (`expect.any(Number)`) work. */
113
+ toHavePropertyValue(state: MatcherState, subject: unknown, name: string, expected: unknown, options?: Timing): Promise<MatcherResult>;
114
+ /** Subject: a Linear issue. Its workflow state, by name. */
115
+ toHaveState(state: MatcherState, subject: unknown, name: string, options?: Timing): Promise<MatcherResult>;
116
+ /** Only this person can see the message. */
117
+ toBeEphemeralFor(state: MatcherState, subject: unknown, user: {
118
+ readonly id: string;
119
+ readonly name: string;
120
+ }): Promise<MatcherResult>;
121
+ /** The agent answered the delivery with 2xx, within the platform's window. */
122
+ toBeAccepted(state: MatcherState, subject: unknown, options?: Timing & {
123
+ within?: Duration;
124
+ }): Promise<MatcherResult>;
125
+ /** A forged delivery (bad signature, stale timestamp) was refused by the agent with a 4xx. */
126
+ toBeRejected(state: MatcherState, subject: unknown, options?: Timing): Promise<MatcherResult>;
127
+ /** The delivery needed retries. */
128
+ toBeRetried(state: MatcherState, subject: unknown, options?: Timing & {
129
+ times?: number;
130
+ }): Promise<MatcherResult>;
131
+ /** The agent made this API call. */
132
+ toHaveReceivedCall(state: MatcherState, subject: unknown, operation: string | RegExp, options?: Timing & {
133
+ times?: number;
134
+ error?: string;
135
+ }): Promise<MatcherResult>;
136
+ };
137
+ export type MatcherName = keyof typeof matchers;
138
+ export {};
@@ -0,0 +1,458 @@
1
+ /**
2
+ * The channel matchers, independent of any test framework. Each one reads plain SDK methods and
3
+ * returns whether it passed and what to say if not; `integrations/vitest` only
4
+ * adapt them to their `expect`.
5
+ *
6
+ * - A positive matcher polls until its condition holds, or fails after the timeout.
7
+ * - A negated matcher, and one with an exact count, waits until the agent is quiet and checks once.
8
+ */
9
+ import { ChannelstackError, fromMatches, parseDuration, QUIET, textMatches, unreportedRefusals, untilQuiet, waitFor, WaitTimeoutError, } from "../../sdks/typescript/client.js";
10
+ const nameOf = (author) => (typeof author === "string" ? author : author.name);
11
+ const show = (expected) => typeof expected === "string" ? JSON.stringify(expected) : String(expected);
12
+ const listing = (lines) => lines.length === 0 ? " (nothing)" : lines.map((line) => ` ${line}`).join("\n");
13
+ const says = (messages) => listing(messages.map((message) => `${message.author.name}: ${message.text}`));
14
+ /**
15
+ * What was said in a subject: a thread's replies, or, for a conversation (a DM), everything in
16
+ * it, threads included, as its transcript has it.
17
+ */
18
+ async function messagesOf(subject) {
19
+ const handle = subject;
20
+ if (typeof handle.replies === "function")
21
+ return handle.replies();
22
+ // A transcript entry says `streaming`; a message has a `stream`. Here they read the same.
23
+ if (typeof handle.transcript === "function") {
24
+ return (await handle.transcript()).entries.map((entry) => ({
25
+ ...entry,
26
+ stream: entry.streaming === undefined ? undefined : { state: entry.streaming },
27
+ }));
28
+ }
29
+ throw new TypeError("This matcher needs a thread or a conversation");
30
+ }
31
+ /**
32
+ * Run a check the way its kind needs: poll until it holds, or wait for quiet and check once.
33
+ * `describe` says what was expected and what was there instead.
34
+ */
35
+ async function settle(subject, state, timing, options) {
36
+ const timeout = timing?.timeout ?? state.timeout;
37
+ let value;
38
+ if (options.onceQuiet || state.isNot) {
39
+ const handle = subject;
40
+ if (typeof handle[QUIET] !== "function")
41
+ throw new TypeError("This matcher needs a channelstack handle");
42
+ // The check watches for the whole quiet window: what arrives while it looks counts.
43
+ await untilQuiet(() => handle[QUIET](), {
44
+ timeout,
45
+ quietFor: timing?.quietFor ?? state.quietFor,
46
+ watching: true,
47
+ });
48
+ value = await options.read();
49
+ }
50
+ else {
51
+ let last;
52
+ try {
53
+ value = await waitFor("the condition", async () => {
54
+ last = await options.read();
55
+ return options.holds(last) ? last : undefined;
56
+ }, { timeout });
57
+ }
58
+ catch (error) {
59
+ if (!(error instanceof WaitTimeoutError))
60
+ throw error;
61
+ value = last;
62
+ }
63
+ }
64
+ const pass = options.holds(value);
65
+ // A failed check also says what the agent left open (a stream it never stopped): often that is the bug.
66
+ const open = pass === state.isNot ? await stillOpen(subject) : [];
67
+ const leftover = open.length === 0 ? "" : `\nStill open: ${open.join("; ")}`;
68
+ return { pass, message: () => `${options.describe(value)}${leftover}` };
69
+ }
70
+ /**
71
+ * What the agent has left open in the subject's session, in words. Nothing for a subject outside a
72
+ * session, or where the server can't tell (live, without proxy mode): it only adds to a failure's
73
+ * message, so its refusal must not turn the failure into a skip.
74
+ */
75
+ async function stillOpen(subject) {
76
+ const handle = subject;
77
+ if (typeof handle[QUIET] !== "function")
78
+ return [];
79
+ try {
80
+ return (await unreportedRefusals(() => handle[QUIET]())).open;
81
+ }
82
+ catch (error) {
83
+ if (error instanceof ChannelstackError)
84
+ return [];
85
+ throw error;
86
+ }
87
+ }
88
+ const from = (author, text) => (message) => fromMatches(message.author, author) && textMatches(message.text, text);
89
+ /** A Linear agent session, or the latest one of an issue (the subject a session matcher was given). */
90
+ async function sessionOf(subject) {
91
+ const handle = subject;
92
+ if (typeof handle.state === "function" && typeof handle.activities === "function")
93
+ return handle;
94
+ if (typeof handle.sessions === "function")
95
+ return (await handle.sessions()).at(-1);
96
+ throw new TypeError("This matcher needs an agent session or an issue");
97
+ }
98
+ const commentText = (comment) => comment.body ?? comment.text ?? "";
99
+ /** The text of each block of a Notion page, nested ones included: its rich text, or a child page's title. */
100
+ const blockTexts = (blocks) => blocks.flatMap((raw) => {
101
+ const block = raw;
102
+ const data = (block.type ? block[block.type] : undefined);
103
+ const text = data?.rich_text ? data.rich_text.map((item) => item.plain_text ?? "").join("") : (data?.title ?? "");
104
+ return [text, ...blockTexts(block.children ?? [])];
105
+ });
106
+ /**
107
+ * The comments of a subject that has a conversation: a GitHub issue or pull request, a Linear
108
+ * issue, a Notion discussion. A Notion page has none of its own: they are in its discussions.
109
+ */
110
+ const commentsOf = (subject, matcher) => {
111
+ const handle = subject;
112
+ if (typeof handle.comments === "function")
113
+ return handle.comments();
114
+ throw new Error(typeof handle.discussions === "function"
115
+ ? `${matcher} needs a Notion discussion, not a page: a page's comments are in its discussions. Pass \`comment.discussion\`, or one of \`await page.discussions()\`.`
116
+ : `${matcher} needs a GitHub issue or pull request, a Linear issue or a Notion discussion`);
117
+ };
118
+ const commentFrom = (author, text) => (comment) => fromMatches(comment.author, author) && textMatches(commentText(comment), text);
119
+ const written = (comments) => listing(comments.map((comment) => `${comment.author.name}: ${commentText(comment)}`));
120
+ export const matchers = {
121
+ /** The thread (or DM) has at least one reply from this author. */
122
+ toHaveReplyFrom(state, subject, author, options) {
123
+ const wanted = `a reply from ${nameOf(author)}${options?.text === undefined ? "" : ` matching ${show(options.text)}`}`;
124
+ return settle(subject, state, options, {
125
+ onceQuiet: false,
126
+ read: () => messagesOf(subject),
127
+ holds: (messages) => messages.some(from(author, options?.text)),
128
+ describe: (messages) => `Expected ${state.isNot ? wanted.replace(/^a /, "no ") : wanted}. The thread has:\n${says(messages)}`,
129
+ });
130
+ },
131
+ /** Exactly `count` replies from this author, checked once the agent is quiet. */
132
+ toHaveRepliesFrom(state, subject, author, options) {
133
+ return settle(subject, state, options, {
134
+ onceQuiet: true,
135
+ read: async () => (await messagesOf(subject)).filter(from(author, options.text)),
136
+ holds: (replies) => replies.length === options.count,
137
+ describe: (replies) => `Expected ${state.isNot ? "not " : ""}exactly ${options.count} ${options.count === 1 ? "reply" : "replies"} from ${nameOf(author)}, found ${replies.length}:\n${says(replies)}`,
138
+ });
139
+ },
140
+ /** A message from this author directly in the channel, outside any thread. */
141
+ toHaveChannelMessageFrom(state, subject, author, options) {
142
+ return settle(subject, state, options, {
143
+ onceQuiet: false,
144
+ read: async () => (await subject.messages()).filter(from(author)),
145
+ holds: (messages) => messages.length > 0,
146
+ describe: (messages) => state.isNot
147
+ ? `Expected no message from ${nameOf(author)} in the channel itself, found:\n${says(messages)}`
148
+ : `Expected a message from ${nameOf(author)} in the channel itself, found none`,
149
+ });
150
+ },
151
+ /** Some entry a person would see contains this text. `count` makes it exact. */
152
+ toContainText(state, subject, text, options) {
153
+ const read = async () => {
154
+ const transcript = await subject.transcript(options?.as ? { as: options.as } : {});
155
+ const entries = transcript.entries.filter((entry) => options?.from === undefined || fromMatches(entry.author, options.from));
156
+ return { entries, matching: entries.filter((entry) => textMatches(entry.text, text)) };
157
+ };
158
+ return settle(subject, state, options, {
159
+ onceQuiet: options?.count !== undefined,
160
+ read,
161
+ holds: ({ matching }) => (options?.count === undefined ? matching.length > 0 : matching.length === options.count),
162
+ describe: ({ entries, matching }) => `Expected ${state.isNot ? "no text" : options?.count === undefined ? "text" : `exactly ${options.count} entries with text`} matching ${show(text)}, found ${matching.length}. A person sees:\n${listing(entries.map((entry) => `${entry.author.name}: ${entry.text}`))}`,
163
+ });
164
+ },
165
+ /** A reply from this author is being streamed right now. */
166
+ toHaveStreamingReplyFrom(state, subject, author, options) {
167
+ return settle(subject, state, options, {
168
+ onceQuiet: false,
169
+ read: () => messagesOf(subject),
170
+ holds: (messages) => messages.some((message) => message.stream?.state === "open" && (author === undefined || fromMatches(message.author, author))),
171
+ describe: (messages) => `Expected ${state.isNot ? "no" : "a"} reply being streamed${author === undefined ? "" : ` by ${nameOf(author)}`}. The thread has:\n${listing(messages.map((message) => `${message.author.name}: ${message.text} [${message.stream?.state ?? "not a stream"}]`))}`,
172
+ });
173
+ },
174
+ /** The agent's state in this thread: `working`, `streaming`, `stopped` or `idle`. */
175
+ toHaveStatus(state, subject, expected, options) {
176
+ return settle(subject, state, options, {
177
+ onceQuiet: false,
178
+ read: () => subject.status(),
179
+ holds: (status) => status.state === expected,
180
+ describe: (status) => `Expected the thread ${state.isNot ? "not " : ""}to be ${expected}, it is ${status.state}${status.text ? ` ("${status.text}")` : ""}`,
181
+ });
182
+ },
183
+ /** The status line the agent set. */
184
+ toHaveStatusText(state, subject, text, options) {
185
+ return settle(subject, state, options, {
186
+ onceQuiet: false,
187
+ read: () => subject.status(),
188
+ holds: (status) => status.text !== undefined && textMatches(status.text, text),
189
+ describe: (status) => `Expected the status line ${state.isNot ? "not " : ""}to match ${show(text)}, ${status.text === undefined ? "there is none" : `it is "${status.text}"`}`,
190
+ });
191
+ },
192
+ /** The message has a button with this label; for a thread or a conversation, the agent's latest message there. */
193
+ toHaveButton(state, subject, label, options) {
194
+ const handle = subject;
195
+ return settle(subject, state, options, {
196
+ onceQuiet: false,
197
+ read: async () => {
198
+ // A message (it has a thread) is one entry of its thread's transcript.
199
+ if (handle.thread) {
200
+ const { entries } = await handle.thread.transcript();
201
+ return entries.filter((entry) => entry.id === handle.ts).flatMap((entry) => entry.controls);
202
+ }
203
+ const { entries } = await handle.transcript();
204
+ return entries.filter((entry) => entry.author.kind === "app").at(-1)?.controls ?? [];
205
+ },
206
+ holds: (controls) => controls.some((control) => textMatches(control, label)),
207
+ describe: (controls) => `Expected ${state.isNot ? "no" : "a"} button matching ${show(label)}. Buttons there: ${controls.length === 0 ? "none" : controls.join(", ")}`,
208
+ });
209
+ },
210
+ toHaveReaction(state, subject, emoji, options) {
211
+ const name = emoji.replace(/^:|:$/g, "");
212
+ return settle(subject, state, options, {
213
+ onceQuiet: false,
214
+ read: () => subject.reactions(),
215
+ holds: (reactions) => reactions.some((reaction) => reaction.emoji === name &&
216
+ (options?.by === undefined || reaction.by.some((author) => fromMatches(author, options.by)))),
217
+ describe: (reactions) => `Expected ${state.isNot ? "no" : "a"} :${name}: reaction${options?.by === undefined ? "" : ` by ${nameOf(options.by)}`}. Reactions there: ${reactions.length === 0 ? "none" : reactions.map((reaction) => `:${reaction.emoji}: by ${reaction.by.map((author) => author.name).join(", ")}`).join("; ")}`,
218
+ });
219
+ },
220
+ /** Subject: a person. The agent opened a modal for them (it may be submitted by now), with this title if one is given. */
221
+ toHaveOpenedModal(state, subject, title, options) {
222
+ return settle(subject, state, options, {
223
+ onceQuiet: false,
224
+ read: () => subject.modals(),
225
+ holds: (modals) => modals.some((modal) => textMatches(modal.title, title)),
226
+ describe: (modals) => `Expected ${state.isNot ? "no" : "a"} modal${title === undefined ? "" : ` titled ${show(title)}`} to have been opened. Opened: ${modals.length === 0 ? "none" : modals.map((modal) => JSON.stringify(modal.title)).join(", ")}`,
227
+ });
228
+ },
229
+ /** Subject: a GitHub issue or pull request, a Linear issue or a Notion discussion. At least one comment from this author. */
230
+ toHaveCommentFrom(state, subject, author, options) {
231
+ const wanted = `a comment from ${nameOf(author)}${options?.text === undefined ? "" : ` matching ${show(options.text)}`}`;
232
+ return settle(subject, state, options, {
233
+ onceQuiet: false,
234
+ read: () => commentsOf(subject, "toHaveCommentFrom"),
235
+ holds: (comments) => comments.some(commentFrom(author, options?.text)),
236
+ describe: (comments) => `Expected ${state.isNot ? wanted.replace(/^a /, "no ") : wanted}. The conversation has:\n${written(comments)}`,
237
+ });
238
+ },
239
+ /** Exactly `count` comments from this author, checked once the agent is quiet. */
240
+ toHaveCommentsFrom(state, subject, author, options) {
241
+ return settle(subject, state, options, {
242
+ onceQuiet: true,
243
+ read: () => commentsOf(subject, "toHaveCommentsFrom"),
244
+ holds: (comments) => comments.filter(commentFrom(author)).length === options.count,
245
+ describe: (comments) => `Expected ${state.isNot ? "not " : ""}exactly ${options.count} comments from ${nameOf(author)}, found ${comments.filter(commentFrom(author)).length}:\n${written(comments)}`,
246
+ });
247
+ },
248
+ /** Subject: a pull request. A comment on the diff, matched by every field that is given. */
249
+ toHaveReviewComment(state, subject, expected, options) {
250
+ const pull = subject;
251
+ const wanted = [
252
+ expected.path === undefined
253
+ ? ""
254
+ : ` on ${expected.path}${expected.line === undefined ? "" : `:${expected.line}`}`,
255
+ expected.from === undefined ? "" : ` from ${nameOf(expected.from)}`,
256
+ expected.text === undefined ? "" : ` matching ${show(expected.text)}`,
257
+ ].join("");
258
+ return settle(subject, state, options, {
259
+ onceQuiet: false,
260
+ read: () => pull.reviewComments(),
261
+ holds: (comments) => comments.some((comment) => (expected.path === undefined || comment.path === expected.path) &&
262
+ (expected.line === undefined || comment.line === expected.line) &&
263
+ (expected.from === undefined || fromMatches(comment.author, expected.from)) &&
264
+ textMatches(commentText(comment), expected.text)),
265
+ describe: (comments) => `Expected ${state.isNot ? "no" : "a"} comment on the diff${wanted}. The diff has:\n${listing(comments.map((comment) => `${comment.author.name} on ${comment.path}:${comment.line}: ${comment.body}`))}`,
266
+ });
267
+ },
268
+ /** Subject: a pull request. A review from this author, with this verdict if one is given. */
269
+ toHaveReviewFrom(state, subject, author, options) {
270
+ const pull = subject;
271
+ return settle(subject, state, options, {
272
+ onceQuiet: false,
273
+ read: () => pull.reviews(),
274
+ holds: (reviews) => reviews.some((review) => fromMatches(review.author, author) && (options?.state === undefined || review.state === options.state)),
275
+ describe: (reviews) => `Expected ${state.isNot ? "no" : "a"} review from ${nameOf(author)}${options?.state === undefined ? "" : ` with state ${options.state}`}. Reviews there:\n${listing(reviews.map((review) => `${review.author.name}: ${review.state}${review.body === "" ? "" : ` ${JSON.stringify(review.body)}`}`))}`,
276
+ });
277
+ },
278
+ /** Subject: a pull request or a commit. A check run of this name, in this state if one is given. */
279
+ toHaveCheckRun(state, subject, name, options) {
280
+ const target = subject;
281
+ const wanted = [options?.status, options?.conclusion].filter((part) => part !== undefined).join(", ");
282
+ return settle(subject, state, options, {
283
+ onceQuiet: false,
284
+ read: () => target.checkRuns(),
285
+ holds: (runs) => runs.some((run) => (typeof name === "string" ? run.name === name : textMatches(run.name, name)) &&
286
+ (options?.status === undefined || run.status === options.status) &&
287
+ (options?.conclusion === undefined || run.conclusion === options.conclusion)),
288
+ describe: (runs) => `Expected ${state.isNot ? "no" : "a"} check run ${show(name)}${wanted === "" ? "" : ` (${wanted})`}. Check runs there:\n${listing(runs.map((run) => `${run.name}: ${run.status}${run.conclusion === undefined ? "" : `, ${run.conclusion}`}`))}`,
289
+ });
290
+ },
291
+ /** Subject: an issue or a pull request. It has this label. */
292
+ toHaveLabel(state, subject, name, options) {
293
+ const issue = subject;
294
+ return settle(subject, state, options, {
295
+ onceQuiet: false,
296
+ read: () => issue.labels(),
297
+ holds: (labels) => labels.some((label) => label.toLowerCase() === name.toLowerCase()),
298
+ describe: (labels) => `Expected ${state.isNot ? "no" : "the"} label ${JSON.stringify(name)}. Labels there: ${labels.length === 0 ? "none" : labels.join(", ")}`,
299
+ });
300
+ },
301
+ /** Subject: a pull request. It has been merged. */
302
+ toBeMerged(state, subject, options) {
303
+ const pull = subject;
304
+ return settle(subject, state, options, {
305
+ onceQuiet: false,
306
+ read: () => pull.merged(),
307
+ holds: (merged) => merged,
308
+ describe: () => `Expected the pull request ${state.isNot ? "not " : ""}to be merged`,
309
+ });
310
+ },
311
+ /** Subject: a Linear agent session, or an issue (its latest session). The session's status. */
312
+ toHaveSessionState(state, subject, wanted, options) {
313
+ return settle(subject, state, options, {
314
+ onceQuiet: false,
315
+ read: async () => (await sessionOf(subject))?.state() ?? Promise.resolve("no session"),
316
+ holds: (current) => current === wanted,
317
+ describe: (current) => `Expected the agent session ${state.isNot ? "not " : ""}to be ${wanted}, it is ${current}`,
318
+ });
319
+ },
320
+ /**
321
+ * Subject: a Linear agent session, or an issue (its latest session). An activity of the agent's
322
+ * matching every field that is given: a person's turns (`prompt`, delegating's first among them)
323
+ * aren't what it published.
324
+ */
325
+ toHaveActivity(state, subject, expected, options) {
326
+ const wanted = [
327
+ expected.type ?? "activity",
328
+ expected.from === undefined ? "" : ` from ${nameOf(expected.from)}`,
329
+ expected.text === undefined ? "" : ` matching ${show(expected.text)}`,
330
+ ].join("");
331
+ return settle(subject, state, options, {
332
+ onceQuiet: false,
333
+ read: async () => ((await (await sessionOf(subject))?.activities()) ?? []).filter((activity) => activity.type !== "prompt"),
334
+ holds: (activities) => activities.some((activity) => (expected.type === undefined || activity.type === expected.type) &&
335
+ (expected.from === undefined || fromMatches(activity.author, expected.from)) &&
336
+ textMatches(activity.body ?? "", expected.text)),
337
+ describe: (activities) => `Expected ${state.isNot ? "no" : "a"} ${wanted}. The session has:\n${listing(activities.map((activity) => `${activity.author.name} (${activity.type}): ${activity.body ?? ""}`))}`,
338
+ });
339
+ },
340
+ /** Subject: a Linear issue. It is delegated to this app, or (with `undefined`) to none. */
341
+ toBeDelegatedTo(state, subject, app, options) {
342
+ const issue = subject;
343
+ return settle(subject, state, options, {
344
+ onceQuiet: false,
345
+ read: () => issue.delegatedTo(),
346
+ holds: (delegate) => (app === undefined ? delegate === undefined : delegate?.id === app.id),
347
+ describe: (delegate) => `Expected the issue ${state.isNot ? "not " : ""}to be delegated to ${app?.name ?? "no one"}, it is delegated to ${delegate?.name ?? "no one"}`,
348
+ });
349
+ },
350
+ /** Subject: a Linear issue. It is assigned to this person, or (with `undefined`) to no one. */
351
+ toBeAssignedTo(state, subject, user, options) {
352
+ const issue = subject;
353
+ return settle(subject, state, options, {
354
+ onceQuiet: false,
355
+ read: () => issue.assignee(),
356
+ holds: (assignee) => (user === undefined ? assignee === undefined : assignee?.id === user.id),
357
+ describe: (assignee) => `Expected the issue ${state.isNot ? "not " : ""}to be assigned to ${user?.name ?? "no one"}, it is assigned to ${assignee?.name ?? "no one"}`,
358
+ });
359
+ },
360
+ /** Subject: a Notion page. A block (at any depth) whose text matches. */
361
+ toHaveBlock(state, subject, text, options) {
362
+ const page = subject;
363
+ return settle(subject, state, options, {
364
+ onceQuiet: false,
365
+ read: async () => blockTexts(await page.blocks()),
366
+ holds: (texts) => texts.some((line) => textMatches(line, text)),
367
+ describe: (texts) => `Expected the page ${state.isNot ? "not " : ""}to have a block matching ${show(text)}. Its blocks:\n${listing(texts)}`,
368
+ });
369
+ },
370
+ /** Subject: a Notion page. A property has this value; asymmetric matchers (`expect.any(Number)`) work. */
371
+ toHavePropertyValue(state, subject, name, expected, options) {
372
+ const page = subject;
373
+ const equals = state.equals ?? ((a, b) => JSON.stringify(a) === JSON.stringify(b));
374
+ return settle(subject, state, options, {
375
+ onceQuiet: false,
376
+ read: () => page.property(name),
377
+ holds: (value) => equals(value, expected),
378
+ describe: (value) => `Expected ${name} ${state.isNot ? "not " : ""}to be ${String(expected)}, it is ${JSON.stringify(value)}`,
379
+ });
380
+ },
381
+ /** Subject: a Linear issue. Its workflow state, by name. */
382
+ toHaveState(state, subject, name, options) {
383
+ const issue = subject;
384
+ return settle(subject, state, options, {
385
+ onceQuiet: false,
386
+ read: async () => (await issue.state()).name,
387
+ holds: (current) => current.toLowerCase() === name.toLowerCase(),
388
+ describe: (current) => `Expected the issue ${state.isNot ? "not " : ""}to be in ${JSON.stringify(name)}, it is in ${JSON.stringify(current)}`,
389
+ });
390
+ },
391
+ /** Only this person can see the message. */
392
+ async toBeEphemeralFor(state, subject, user) {
393
+ const visibleTo = subject.visibleTo;
394
+ return {
395
+ pass: visibleTo?.id === user.id,
396
+ message: () => `Expected the message ${state.isNot ? "not " : ""}to be visible only to ${user.name}, ${visibleTo === undefined ? "everyone can see it" : `only ${visibleTo.name} can`}`,
397
+ };
398
+ },
399
+ /** The agent answered the delivery with 2xx, within the platform's window. */
400
+ toBeAccepted(state, subject, options) {
401
+ const delivery = subject;
402
+ const within = options?.within === undefined ? undefined : parseDuration(options.within);
403
+ return settle(subject, state, options, {
404
+ onceQuiet: false,
405
+ read: async () => (await delivery.refresh()).attempts.find((attempt) => !attempt.forgedSignature),
406
+ // Accepted, and with `within`, accepted that fast: the platform's window is only the outer limit.
407
+ holds: (attempt) => attempt?.status === "acknowledged" && (within === undefined || (attempt.durationMs ?? 0) <= within),
408
+ describe: (attempt) => {
409
+ const expected = `Expected delivery ${delivery.id} ${state.isNot ? "not " : ""}to be accepted${within === undefined ? "" : ` within ${within}ms`}`;
410
+ const http = attempt?.responseStatus === undefined ? "" : ` (HTTP ${attempt.responseStatus})`;
411
+ const took = attempt?.durationMs === undefined ? "" : ` after ${attempt.durationMs}ms`;
412
+ return `${expected}, its first attempt is ${attempt?.status ?? "missing"}${http}${took}`;
413
+ },
414
+ });
415
+ },
416
+ /** A forged delivery (bad signature, stale timestamp) was refused by the agent with a 4xx. */
417
+ toBeRejected(state, subject, options) {
418
+ const delivery = subject;
419
+ const refused = (attempt) => attempt?.status === "failed" &&
420
+ attempt.responseStatus !== undefined &&
421
+ attempt.responseStatus >= 400 &&
422
+ attempt.responseStatus < 500;
423
+ return settle(subject, state, options, {
424
+ onceQuiet: false,
425
+ read: async () => (await delivery.refresh()).attempts.filter((attempt) => attempt.forgedSignature).at(-1),
426
+ holds: refused,
427
+ describe: (attempt) => attempt === undefined
428
+ ? `Expected delivery ${delivery.id} to be rejected, but no forged attempt was sent. Call delivery.resend({ badSignature: true }) first`
429
+ : `Expected the forged attempt of delivery ${delivery.id} ${state.isNot ? "not " : ""}to be rejected with a 4xx, the agent answered ${attempt.responseStatus ?? attempt.status}`,
430
+ });
431
+ },
432
+ /** The delivery needed retries. */
433
+ toBeRetried(state, subject, options) {
434
+ const delivery = subject;
435
+ return settle(subject, state, options, {
436
+ onceQuiet: options?.times !== undefined,
437
+ read: async () => (await delivery.refresh()).attempts.filter((attempt) => !attempt.forgedSignature).length - 1,
438
+ holds: (retries) => (options?.times === undefined ? retries > 0 : retries === options.times),
439
+ describe: (retries) => `Expected delivery ${delivery.id} ${state.isNot ? "not " : ""}to be retried${options?.times === undefined ? "" : ` ${options.times} times`}, it was retried ${retries} times`,
440
+ });
441
+ },
442
+ /** The agent made this API call. */
443
+ toHaveReceivedCall(state, subject, operation, options) {
444
+ const fixture = subject;
445
+ return settle(subject, state, options, {
446
+ onceQuiet: options?.times !== undefined,
447
+ read: async () => {
448
+ const calls = await fixture.calls(options?.error === undefined ? {} : { error: options.error });
449
+ return {
450
+ calls,
451
+ matching: calls.filter((call) => typeof operation === "string" ? call.operation === operation : textMatches(call.operation, operation)),
452
+ };
453
+ },
454
+ holds: ({ matching }) => (options?.times === undefined ? matching.length > 0 : matching.length === options.times),
455
+ describe: ({ calls, matching }) => `Expected the agent ${state.isNot ? "not " : ""}to call ${show(operation)}${options?.times === undefined ? "" : ` ${options.times} times`}${options?.error === undefined ? "" : ` with error ${options.error}`}, found ${matching.length}. Its calls:\n${listing(calls.map((call) => `${call.operation}${call.error ? ` → ${call.error}` : ""}`))}`,
456
+ });
457
+ },
458
+ };
@@ -0,0 +1 @@
1
+ export {};