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
62 changes: 60 additions & 2 deletions plugins/slack/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,28 @@ const PROJECTS = [
{ id: "prj-2", name: "Personal", kind: "personal" },
];

/** A machine that is on, and the project's checkout on it. */
const HOSTS = [
{ id: "host_off", status: "disconnected" },
{ id: "host_on", status: "connected" },
];
const SOURCES = [{ type: "local_path", hostId: "host_on", isDefault: true }];
/** The project's environments, newest last: a workspace on the machine that is on. */
const ENVIRONMENTS = [
{ environmentProviderId: "project-checkout", hostId: "host_on", createdAt: 1, lifecycle: { phase: "active" }, environmentProviderSelection: null },
{ environmentProviderId: "multi-repo-workspace", hostId: "host_on", createdAt: 2, lifecycle: { phase: "active" }, environmentProviderSelection: { inputs: { repos: ["a"] } } },
{ environmentProviderId: "git-worktree", hostId: "host_off", createdAt: 3, lifecycle: { phase: "active" }, environmentProviderSelection: null },
];

async function setup(
options: {
hooks?: ReturnType<typeof fakeHooks>;
token?: string;
project?: string;
projects?: typeof PROJECTS;
hosts?: Array<{ id: string; status: string }>;
sources?: Array<{ type: string; hostId: string; isDefault: boolean }>;
environments?: Array<{ environmentProviderId: string | null; hostId: string; createdAt: number; lifecycle: { phase: string }; environmentProviderSelection: { inputs: unknown } | null }>;
spawn?: () => unknown;
send?: () => unknown;
get?: () => unknown;
Expand All @@ -118,7 +134,12 @@ async function setup(
appUrl: APP_URL,
settings: { token: options.token ?? "", project: options.project ?? "" },
sdk: {
projects: { list: async () => options.projects ?? PROJECTS },
projects: {
list: async () => options.projects ?? PROJECTS,
get: async ({ projectId }: { projectId: string }) => ({ id: projectId, name: projectId, kind: "standard", sources: options.sources ?? SOURCES }),
},
hosts: { list: async () => options.hosts ?? HOSTS },
environments: { list: async () => options.environments ?? ENVIRONMENTS },
threads: {
spawn: async () => options.spawn?.() ?? { id: "thr-1" },
send: async () => options.send?.() ?? { outcome: "sent" },
Expand Down Expand Up @@ -230,7 +251,12 @@ describe("Slack plugin", () => {
await tick();
const spawns = s.harness.sdk.callsTo("threads.spawn");
expect(spawns).toHaveLength(1);
expect(spawns[0]![0]).toMatchObject({ projectId: "prj-1", environment: { type: "project-default" } });
// The thread runs where the developer's newest environment runs: that
// provider, with its inputs, on its machine; never the pod's own host.
expect(spawns[0]![0]).toMatchObject({
projectId: "prj-1",
environment: { type: "provider", environmentProviderId: "multi-repo-workspace", inputs: { repos: ["a"] }, machine: { type: "existing", hostId: "host_on" } },
});
expect(String((spawns[0]![0] as { prompt: string }).prompt)).toContain("session D0123:1712345678.901234");
expect(s.hooks.statuses.at(-1)).toMatchObject({ session: "D0123:1712345678.901234", body: { connection: "c_1", status: "is thinking…" } });

Expand Down Expand Up @@ -287,6 +313,38 @@ describe("Slack plugin", () => {
await s.stop();
});

it("runs the thread in the project's checkout on its connected machine when it has no environment there", async () => {
const s = await live({ environments: [] });
s.hooks.last().send(s.hooks.session());
await tick();
expect(s.harness.sdk.callsTo("threads.spawn")[0]![0]).toMatchObject({
environment: { type: "provider", environmentProviderId: "project-checkout", inputs: null, machine: { type: "existing", hostId: "host_on" } },
});
await s.stop();
});

it("skips a default source whose machine is off for one that is on", async () => {
const s = await live({
environments: [],
sources: [
{ type: "local_path", hostId: "host_off", isDefault: true },
{ type: "local_path", hostId: "host_on", isDefault: false },
],
});
s.hooks.last().send(s.hooks.session());
await tick();
expect(s.harness.sdk.callsTo("threads.spawn")[0]![0]).toMatchObject({ environment: { machine: { hostId: "host_on" } } });
await s.stop();
});

it("leaves the environment to bb only when the project has no connected machine", async () => {
const s = await live({ environments: [], hosts: [{ id: "host_off", status: "disconnected" }] });
s.hooks.last().send(s.hooks.session());
await tick();
expect(s.harness.sdk.callsTo("threads.spawn")[0]![0]).toMatchObject({ environment: { type: "project-default" } });
await s.stop();
});

it("says no project is available when the server has none", async () => {
const s = await live({ projects: [] });
s.hooks.last().send(s.hooks.session());
Expand Down
37 changes: 36 additions & 1 deletion plugins/slack/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,9 @@ function resultPage(title: string, body: string, status: number): Response {
/** The projects a Slack thread can be started in, in bb's own order. */
type Project = { id: string; name: string; kind: string };

/** The environment a spawned thread runs in: `threads.spawn`'s `environment`. */
type SpawnEnvironment = Parameters<BbPluginApi["sdk"]["threads"]["spawn"]>[0]["environment"];

/** The project a Slack conversation goes to: the chosen one, else the first. */
export function chooseProject(projects: Project[], chosen: string): Project | null {
const named = chosen.trim();
Expand Down Expand Up @@ -211,6 +214,38 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
return chooseProject(await projects(), (await settings.get()).project ?? "");
}

/**
* Where a Slack conversation's thread runs. A plugin has no composer to
* resolve "the project's default", and on a bb-gate server the pod itself
* is no machine (the local host daemon is never initialised), so the
* thread must name a connected machine. The project's newest environment
* says what the developer actually uses: its provider and inputs are
* replayed on its machine when that machine is connected. Otherwise the
* project's checkout on its default source's machine, and only when the
* project has no connected machine at all is the choice left to bb.
*/
async function environmentFor(project: Project): Promise<SpawnEnvironment> {
const [hosts, full, environments] = await Promise.all([
bb.sdk.hosts.list().catch(() => []),
bb.sdk.projects.get({ projectId: project.id }).catch(() => null),
bb.sdk.environments.list({ projectId: project.id }).catch(() => []),
]);
const connected = new Set(hosts.filter((h) => h.status === "connected").map((h) => h.id));
const newest = environments
.filter((e) => e.environmentProviderId !== null && e.lifecycle.phase === "active" && connected.has(e.hostId))
.sort((a, b) => b.createdAt - a.createdAt)[0];
if (newest !== undefined && newest.environmentProviderId !== null) {
return { type: "provider", environmentProviderId: newest.environmentProviderId, inputs: newest.environmentProviderSelection?.inputs ?? null, machine: { type: "existing", hostId: newest.hostId } };
}
const sources = (full?.sources ?? []).filter((source) => source.type === "local_path");
const source = sources.find((s) => s.isDefault && connected.has(s.hostId)) ?? sources.find((s) => connected.has(s.hostId));
if (source !== undefined) {
const providerId = project.kind === "personal" ? "personal-workspace" : "project-checkout";
return { type: "provider", environmentProviderId: providerId, inputs: null, machine: { type: "existing", hostId: source.hostId } };
}
return { type: "project-default" };
}

// ---- the hooks stream --------------------------------------------------

// The cached sign-in token, so the stream's identify can answer without an
Expand Down Expand Up @@ -350,7 +385,7 @@ export function createSlackPlugin(deps: SlackPluginDeps): (bb: BbPluginApi) => P
await backstop(event.session, "No bb project is available on this server, so a Slack thread cannot be started. Create a project in bb, then DM again.");
return;
}
const thread = await bb.sdk.threads.spawn({ projectId: project.id, environment: { type: "project-default" }, prompt: text, title: threadTitle(event) });
const thread = await bb.sdk.threads.spawn({ projectId: project.id, environment: await environmentFor(project), prompt: text, title: threadTitle(event) });
const after = sessions.get(event.session);
if (after !== undefined) {
sessions.set(event.session, { ...after, threadId: thread.id, projectId: project.id, handedAt });
Expand Down
Loading