Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions apps/bot/test/Config.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ describe("Config", () => {

assert.strictEqual(config.officeChannelId, "123");
assert.strictEqual(Redacted.value(config.botToken), "secret-token");
// oxlint-disable-next-line typescript/no-base-to-string -- the redacted string form is what this checks
assert.notInclude(String(config.botToken), "secret-token");
}),
);

Expand All @@ -40,7 +38,7 @@ describe("Config", () => {
}),
);

it.effect("rejects an empty secret without leaking anything", () =>
it.effect("rejects an empty secret, naming it", () =>
Effect.gen(function* () {
const exit = yield* SlackConfig.pipe(
withEnv({ SLACK_BOT_TOKEN: "", SLACK_APP_TOKEN: "xapp", SLACK_CHANNEL_ID: "C1" }),
Expand Down Expand Up @@ -118,7 +116,6 @@ describe("Config", () => {
const { url } = yield* DatabaseConfig.pipe(withEnv({ DATABASE_URL: databaseUrl }));

assert.deepStrictEqual(Option.map(url, Redacted.value), Option.some(databaseUrl));
assert.notInclude(String(url), "secret");
}),
);

Expand Down
16 changes: 8 additions & 8 deletions apps/bot/test/Program.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ const leave = (overrides: Partial<VoiceStateUpdate> = {}) =>
update({ oldChannelId: OFFICE, newChannelId: null, ...overrides });

describe("program", () => {
it.effect("1. announces the first join from outside voice with name and join link", () =>
it.effect("announces the first join from outside voice with name and join link", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([update({ oldChannelId: null })]);

Expand All @@ -179,15 +179,15 @@ describe("program", () => {
}),
);

it.effect("2. announces the office opening on a move in from another voice channel", () =>
it.effect("announces the office opening on a move in from another voice channel", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([update({ oldChannelId: "lobby" })]);

assert.deepStrictEqual(posted, [OPENED]);
}),
);

it.effect("3. ignores mute, deafen and video changes inside the office", () =>
it.effect("ignores mute, deafen and video changes inside the office", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram(
[update({ oldChannelId: OFFICE, newChannelId: OFFICE })],
Expand All @@ -199,15 +199,15 @@ describe("program", () => {
}),
);

it.effect("4. ignores bots joining and leaving the office", () =>
it.effect("ignores bots joining and leaving the office", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([update({ isBot: true }), leave({ isBot: true })]);

assert.deepStrictEqual(posted, []);
}),
);

it.effect("5. ignores other voice channels", () =>
it.effect("ignores other voice channels", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([
update({ newChannelId: "lobby" }),
Expand All @@ -218,7 +218,7 @@ describe("program", () => {
}),
);

it.effect("6. shows a display name with <, > and & literally without pinging", () =>
it.effect("shows a display name with <, > and & literally without pinging", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([update({ displayName: "<!channel> & <@U1>" })]);

Expand All @@ -227,7 +227,7 @@ describe("program", () => {
}),
);

it.effect("7. only announces the office opening and emptying, not everyone in between", () =>
it.effect("only announces the office opening and emptying, not everyone in between", () =>
Effect.gen(function* () {
const { posted } = yield* runProgram([
update({ userId: "u1", displayName: "Ada" }),
Expand All @@ -242,7 +242,7 @@ describe("program", () => {
}),
);

it.effect("8. logs revoked Slack access as an error and keeps handling events", () =>
it.effect("logs revoked Slack access as an error and keeps handling events", () =>
Effect.gen(function* () {
const { posted, logs } = yield* runProgram(
[update(), leave()],
Expand Down
26 changes: 7 additions & 19 deletions apps/bot/test/activity/OfficeStats.test.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,22 @@
import { PgliteClient } from "@effect/sql-pglite";
import { assert, describe, it } from "@effect/vitest";
import { Array, DateTime, Effect, Layer, Option, Redacted, Result } from "effect";
import { Array, DateTime, Effect, Layer, Option, Result } from "effect";
import { SecureRandom } from "effect/crypto";
import { HttpClientRequest, HttpServer } from "effect/http";
import { HttpApiMiddleware, HttpApiTest } from "effect/http-api";
import { HttpServer } from "effect/http";
import { HttpApiTest } from "effect/http-api";
import { SqlClient } from "effect/sql";
import { TestClock } from "effect/testing";
import type { BusyHour } from "office-domain/OfficeStats";
import { OfficeStatsReader } from "recording-requests/OfficeStats";
import { CurrentRequester, RecordingApi, SignedIn, Unauthorized } from "office-domain/RecordingApi";
import { RecordingApi } from "office-domain/RecordingApi";
import { StatsHandlers } from "recording-requests/StatsHandlers";

import { ActivityLog } from "../../src/activity/ActivityLog.ts";
import { columnNaming, Database } from "../../src/database/Database.ts";
import { NO_VOICE_DETAILS, type VoiceDetails } from "../../src/office/OfficeEvent.ts";
import type { TimedVoiceEffect } from "../../src/office/VoiceEffect.ts";
import type { VoiceObservation } from "../../src/office/VoiceObservation.ts";
import { signedInAs, VALID_SESSION, withSession } from "../fakes.ts";

const OFFICE = "office";

Expand Down Expand Up @@ -356,20 +357,7 @@ describe("OfficeStatsReader", () => {

const ada = { id: "ada", name: "Ada" };

const SignedInTest = Layer.succeed(
SignedIn,
SignedIn.of({
session: (httpEffect, { credential }) =>
Redacted.value(credential) === "ada-session"
? Effect.provideService(httpEffect, CurrentRequester, ada)
: Effect.fail(Unauthorized.make()),
}),
);

const withSession = (session: string) =>
HttpApiMiddleware.layerClient(SignedIn, ({ next, request }) =>
next(HttpClientRequest.bearerToken(request, session)),
);
const SignedInTest = signedInAs(ada);

const HttpLayer = Layer.mergeAll(
StatsHandlers.pipe(Layer.provideMerge(TestLayer), Layer.provideMerge(SignedInTest)),
Expand All @@ -388,7 +376,7 @@ describe("GET /api/stats", () => {
assert.strictEqual(stats.range, "month");
assert.deepStrictEqual(stats.since, at("2026-09-30T22:00:00Z"));
assert.deepStrictEqual(stats.recordings, { count: 0, seconds: 0 });
}).pipe(Effect.provide(Layer.mergeAll(withSession("ada-session"), HttpLayer))),
}).pipe(Effect.provide(Layer.mergeAll(withSession(VALID_SESSION), HttpLayer))),
);

it.effect("turns away anyone without a valid session", () =>
Expand Down
6 changes: 4 additions & 2 deletions apps/bot/test/announcing/Announcement.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,10 @@ describe("formatMessage", () => {
expect(texts[count]).toBe(texts[0]);
});

it("copes with a negative variant", () => {
expect(announce(OfficeEvent.Opened(member), -1).text).toBeTypeOf("string");
it("reads a negative variant as its positive", () => {
expect(announce(OfficeEvent.Opened(member), -1).text).toBe(
announce(OfficeEvent.Opened(member), 1).text,
);
});

it("escapes the display name in every phrasing", () => {
Expand Down
36 changes: 12 additions & 24 deletions apps/bot/test/announcing/SlackNotifier.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,18 @@ const makeSlack = Effect.fnUntraced(function* (
return { notifier, requests: fake.requests, recordedPosts: fake.recordedPosts };
});

const generated = Layer.succeed(
HeadlineWriter,
HeadlineWriter.of({
write: () =>
Effect.succeedSome({
template: "🛋️ {name} saved you a seat!",
button: "🪑 Grab a seat",
model: "test/model",
}),
}),
);

describe("SlackNotifier", () => {
it.effect("posts the formatted message to the office channel", () =>
Effect.gen(function* () {
Expand Down Expand Up @@ -81,18 +93,6 @@ describe("SlackNotifier", () => {

it.effect("posts a generated headline when the office opens", () =>
Effect.gen(function* () {
const generated = Layer.succeed(
HeadlineWriter,
HeadlineWriter.of({
write: () =>
Effect.succeedSome({
template: "🛋️ {name} saved you a seat!",
button: "🪑 Grab a seat",
model: "test/model",
}),
}),
);

const slack = yield* makeSlack([ok], generated);

yield* slack.notifier.notify(opened);
Expand All @@ -105,18 +105,6 @@ describe("SlackNotifier", () => {

it.effect("records each post with what it was and the model that wrote it", () =>
Effect.gen(function* () {
const generated = Layer.succeed(
HeadlineWriter,
HeadlineWriter.of({
write: () =>
Effect.succeedSome({
template: "🛋️ {name} saved you a seat!",
button: "🪑 Grab a seat",
model: "test/model",
}),
}),
);

const slack = yield* makeSlack(
[slackOk({ channel: "C-OFFICE", ts: "1700000000.000200" })],
generated,
Expand Down
38 changes: 0 additions & 38 deletions apps/bot/test/answering/CloudflareDecisionModel.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,44 +88,6 @@ describe("CloudflareDecisionModel", () => {
}),
);

it.effect("rejects an answer with a label it wasn't offered", () =>
Effect.gen(function* () {
const { response } = yield* decide(
clef({
action: {
type: "choice",
choice: "shrug",
probabilities: { reply: 0.5, react: 0.5, ignore: 0 },
},
}),
);

assert.isTrue(Result.isFailure(response));

if (Result.isFailure(response))
assert.instanceOf(response.failure.reason, AiError.InvalidOutputError);
}),
);

it.effect("rejects probabilities that don't add up", () =>
Effect.gen(function* () {
const { response } = yield* decide(
clef({
action: {
type: "choice",
choice: "react",
probabilities: { reply: 0.5, react: 0.9, ignore: 0.1 },
},
}),
);

assert.isTrue(Result.isFailure(response));

if (Result.isFailure(response))
assert.instanceOf(response.failure.reason, AiError.InvalidOutputError);
}),
);

it.effect("rejects a reply it can't read", () =>
Effect.gen(function* () {
const { response } = yield* decide(
Expand Down
42 changes: 29 additions & 13 deletions apps/bot/test/fakes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,22 +7,26 @@ import {
ErrorReporter,
Layer,
Option,
Predicate,
Queue,
Random,
Redacted,
Ref,
Schedule,
Schema,
Stream,
String,
} from "effect";
import { LanguageModel, Model } from "effect/ai";
import { CurrentRequester, SignedIn, Unauthorized } from "office-domain/RecordingApi";
import {
HttpBody,
HttpClient,
HttpClientRequest as ClientRequest,
HttpClientError,
type HttpClientRequest,
HttpClientResponse,
} from "effect/http";
import { HttpApiMiddleware } from "effect/http-api";

import { ActivityRecorder } from "../src/activity/ActivityRecorder.ts";
import { BotPosts } from "../src/slack/BotPosts.ts";
Expand Down Expand Up @@ -110,7 +114,7 @@ export const networkDown: Reply = (request) =>
export const hang: Reply = () => Effect.never;

export const requestText = (request: HttpClientRequest.HttpClientRequest): string =>
request.body instanceof HttpBody.Uint8Array ? new TextDecoder().decode(request.body.body) : "";
Predicate.isTagged(request.body, "Uint8Array") ? new TextDecoder().decode(request.body.body) : "";

export const requestJson = (request: HttpClientRequest.HttpClientRequest): Schema.Json =>
JSON.parse(requestText(request));
Expand Down Expand Up @@ -242,7 +246,7 @@ export const pollUntil = <A, E, R>(poll: Effect.Effect<A, E, R>, done: (value: A
),
);

export interface Report {
interface Report {
readonly name: string;
readonly message: string;
readonly severity: string;
Expand Down Expand Up @@ -274,7 +278,7 @@ export const DEFAULT_SETTINGS: ResponderSettings = {
reactionEmoji: ["joy", "eyes", "raised_hands"],
};

export interface FakeHistoryOptions {
interface FakeHistoryOptions {
readonly settings?: ResponderSettings | undefined;
readonly members?: ReadonlyMap<string, LinkedMember> | undefined;
readonly postsUnavailable?: boolean | undefined;
Expand Down Expand Up @@ -391,14 +395,14 @@ export interface FakeSlackClientOptions {
readonly threadPosts?: ReadonlyMap<string, ReadonlyArray<FetchedMessage>> | undefined;
}

export interface RewrittenMessage {
interface RewrittenMessage {
readonly channel: string;
readonly ts: string;
readonly text: string;
readonly blocks: Option.Option<Schema.JsonArray>;
}

export interface UpdatedMessage {
interface UpdatedMessage {
readonly channel: string;
readonly ts: string;
readonly message: SlackMessage;
Expand All @@ -418,7 +422,6 @@ export const makeFakeSlackClient = Effect.fnUntraced(function* (
const deletions = yield* Ref.make<ReadonlyArray<readonly [string, string]>>([]);
const rewrites = yield* Ref.make<ReadonlyArray<RewrittenMessage>>([]);
const deletedFiles = yield* Ref.make<ReadonlyArray<string>>([]);
const views = yield* Ref.make<ReadonlyArray<{ triggerId: string; view: Schema.Json }>>([]);
const threads = yield* Ref.make(new Map(options.threads ?? []));
const profiles = options.profiles ?? new Map<string, SlackProfile>();

Expand Down Expand Up @@ -474,7 +477,7 @@ export const makeFakeSlackClient = Effect.fnUntraced(function* (
? Effect.succeed(permalinkOf(channel, ts))
: Effect.fail(SlackError.make({ reason: options.permalinkFailure })),
openDirectMessage: (userId) => Effect.succeed(`D-${userId}`),
openView: (triggerId, view) => Ref.update(views, (all) => [...all, { triggerId, view }]),
openView: () => Effect.void,
botUserId: Effect.succeed(BOT_USER_ID),
openConnection: Effect.never,
}),
Expand All @@ -489,10 +492,23 @@ export const makeFakeSlackClient = Effect.fnUntraced(function* (
deletions: Ref.get(deletions),
rewrites: Ref.get(rewrites),
deletedFiles: Ref.get(deletedFiles),
views: Ref.get(views),
addToThread: (threadTs: string, message: ThreadMessage) =>
Ref.update(threads, (all) =>
new Map(all).set(threadTs, [...(all.get(threadTs) ?? []), message]),
),
};
});

export const VALID_SESSION = "valid-session";

export const signedInAs = (requester: CurrentRequester["Service"]) =>
Layer.succeed(
SignedIn,
SignedIn.of({
session: (httpEffect, { credential }) =>
Redacted.value(credential) === VALID_SESSION
? Effect.provideService(httpEffect, CurrentRequester, requester)
: Effect.fail(Unauthorized.make()),
}),
);

export const withSession = (session: string) =>
HttpApiMiddleware.layerClient(SignedIn, ({ next, request }) =>
next(ClientRequest.bearerToken(request, session)),
);
Loading