Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(skill-burger): give composed fields distinct workflow steps

Afloat1181d1d879a7
diff --git a/server/skill-burger/composed-fields.test.ts b/server/skill-burger/composed-fields.test.ts
new file mode 100644
index 0000000000..966d48739c
--- /dev/null
+++ b/server/skill-burger/composed-fields.test.ts
@@ -0,0 +1,100 @@
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+
+import { draftWorkflow } from "../../shared/skill-burger/draft.ts";
+import { applyChoices, draftView } from "../../shared/skill-burger/draft-view.ts";
+import { workflowSchema } from "../../shared/skill-burger/format.ts";
+import type { RunMessage } from "../../shared/skill-burger/layers.ts";
+import { resumeRun, startRun, type RunDeps, type RunState } from "./runner.ts";
+import { readWorkflowSkill, saveWorkflowSkill } from "./store.ts";
+
+const call = (id: string, slug: string, args: unknown, output?: unknown): RunMessage => ({
+ id, role: "bot", kind: "activity",
+ tool: {
+ name: "mcp__composio__COMPOSIO_MULTI_EXECUTE_TOOL", ok: true,
+ input: JSON.stringify({ tools: [{ tool_slug: slug, arguments: args }] }),
+ ...(output === undefined ? {} : { output: JSON.stringify(output) }),
+ },
+});
+
+const messages: RunMessage[] = [
+ { id: "ask", role: "user", kind: "text", text: "Summarise the results in Slack" },
+ call("read", "GOOGLESHEETS_BATCH_GET", { spreadsheet_id: "sales-sheet" }, { data: { values: [["North", 1000]] } }),
+ call("post", "SLACK_SEND_MESSAGE", {
+ channel: "C123456",
+ text: "Quarterly sales summary for the team. ".repeat(8),
+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "Detailed regional performance and next steps. ".repeat(8) } }],
+ }),
+];
+
+it("saves a run with separate composed fields in one app call", () => {
+ const root = mkdtempSync(join(tmpdir(), "burger-composed-"));
+ try {
+ const draft = draftWorkflow(messages)!;
+ expect(workflowSchema.safeParse(draft.workflow).success).toBe(true);
+ const writers = draft.workflow.steps.filter((step) => step.kind === "ai");
+ expect(writers).toHaveLength(2);
+ expect(new Set(writers.map((step) => step.id)).size).toBe(2);
+ expect(writers[0]!.id).toBe("s2_write");
+ const post = draft.workflow.steps.at(-1)!;
+ expect(post.kind === "app" && post.args).toMatchObject({
+ text: { $step: writers[0]!.id },
+ blocks: [{ text: { text: { $step: writers[1]!.id } } }],
+ });
+ const saved = saveWorkflowSkill({ workflow: draft.workflow, root, botIds: [] });
+ expect(saved).not.toHaveProperty("error");
+ if ("error" in saved) throw new Error(saved.error);
+ expect(readWorkflowSkill(saved.name, root)?.workflow).toEqual(draft.workflow);
+ } finally {
+ rmSync(root, { recursive: true, force: true });
+ }
+});
+
+it("resumes each composed field separately and delivers both results to the app", async () => {
+ const workflow = draftWorkflow(messages)!.workflow;
+ const saved: RunState[] = [];
+ const posts: Record<string, unknown>[] = [];
+ const unexpected = async () => { throw new Error("unexpected executor"); };
+ const deps: RunDeps = {
+ exec: {
+ app: async ({ tool, args }) => {
+ if (tool === "SLACK_SEND_MESSAGE") posts.push(args);
+ return { ok: true, output: tool === "GOOGLESHEETS_BATCH_GET" ? { rows: [["North", 2000]] } : { sent: true } };
+ },
+ shell: unexpected, file: unexpected, browser: unexpected,
+ },
+ events: { started() {}, ended() {} },
+ save: (state) => saved.push(structuredClone(state)),
+ };
+ const first = await startRun({ name: "sales", botId: "b", threadId: "t", sha256: "test", workflow }, deps);
+ expect(first).toMatchObject({ status: "needs_input", requiresInput: { type: "ai_step", step: "s2_write" } });
+ const second = await resumeRun(saved.shift()!, "New plain-text summary", deps);
+ expect(second).toMatchObject({ status: "needs_input", requiresInput: { type: "ai_step" } });
+ expect(second.requiresInput!.step).not.toBe(first.requiresInput!.step);
+ expect(posts).toEqual([]);
+ const done = await resumeRun(saved.shift()!, "New block summary", deps);
+ expect(done).toMatchObject({ ok: true, status: "ok" });
+ expect(posts).toEqual([{
+ channel: "C123456", text: "New plain-text summary",
+ blocks: [{ type: "section", text: { type: "mrkdwn", text: "New block summary" } }],
+ }]);
+});
+
+it("leaves out every composed field when its app step is removed", () => {
+ const chosen = applyChoices(draftWorkflow(messages)!.workflow, { skip: ["s2"] });
+ expect(chosen).not.toHaveProperty("error");
+ if ("error" in chosen) throw new Error(chosen.error);
+ expect(chosen.steps.map((step) => step.id)).toEqual(["s1"]);
+ expect(workflowSchema.safeParse(chosen).success).toBe(true);
+});
+
+it("counts a retried app call once instead of on each composed field", () => {
+ const post = messages.at(-1)!;
+ const retried = [...messages.slice(0, -1), { ...post, id: "failed", tool: { ...post.tool!, ok: false } }, post];
+ const draft = draftWorkflow(retried)!;
+ const view = draftView(draft.workflow, draft.layers, retried);
+ expect(view.steps.at(-1)).toMatchObject({ id: "s2", tries: 1 });
+ for (const step of view.steps.filter((step) => step.kind === "ai")) expect(step.tries).toBeUndefined();
+});
diff --git a/shared/skill-burger/draft-view.ts b/shared/skill-burger/draft-view.ts
index f89548d1c4..792c70caa5 100644
--- a/shared/skill-burger/draft-view.ts
+++ b/shared/skill-burger/draft-view.ts
@@ -52,6 +52,11 @@ export interface DraftChoices {
const clip = (text: string, max: number) => (text.length > max ? `${text.slice(0, max - 1)}…` : text);
+/** The app or file step a generated writer prepares a field for. */
+export function composedFor(id: string): string | null {
+ return /^(.+)_write(?:_\d+)?$/.exec(id)?.[1] ?? null;
+}
+
/** The steps whose output `node` uses. */
function refsIn(node: unknown, into = new Set<string>()): Set<string> {
if (Array.isArray(node)) node.forEach((item) => refsIn(item, into));
@@ -88,7 +93,7 @@ export function draftView(workflow: Workflow, layers: readonly BurgerLayer[], me
const base: DraftStepView = {
id: step.id, kind: step.kind, label: step.label, exact: step.kind !== "ai" && !(step.kind === "decide" && !step.rules?.length), needs: needsOf(step),
...(step.kind === "app" ? { app: step.app } : {}), ...(detailOf(step) ? { detail: detailOf(step) } : {}),
- ...(layer?.tries && !step.id.endsWith("_write") ? { tries: layer.tries } : {}),
+ ...(layer?.tries && !composedFor(step.id) ? { tries: layer.tries } : {}),
};
if (step.kind !== "delegate") return base;
const delegation = layer?.delegation;
@@ -138,7 +143,10 @@ function renameArg(steps: WorkflowStep[], from: string, to: string): WorkflowSte
export function applyChoices(workflow: Workflow, choices: DraftChoices | undefined): Workflow | { error: string } {
if (!choices) return workflow;
const skip = new Set(choices.skip ?? []);
- let steps = workflow.steps.filter((step) => !skip.has(step.id) && !(step.id.endsWith("_write") && skip.has(step.id.replace(/_write$/, ""))));
+ let steps = workflow.steps.filter((step) => {
+ const parent = composedFor(step.id);
+ return !skip.has(step.id) && !(parent && skip.has(parent));
+ });
if (!steps.length) return { error: "Keep at least one step." };
const kept = new Set(steps.map((step) => step.id));
for (const step of steps) {
diff --git a/shared/skill-burger/draft.ts b/shared/skill-burger/draft.ts
index 9e624dcb1b..00f92e0924 100644
--- a/shared/skill-burger/draft.ts
+++ b/shared/skill-burger/draft.ts
@@ -165,7 +165,8 @@ class Drafter {
private composer(id: string, field: string, example: string, looked = false, file?: string): WorkflowRef | null {
const read = [...this.recorded].reverse().find((entry) => entry.read) ?? [...this.recorded].reverse().find((entry) => entry.output !== undefined && entry.output !== "");
if (!read && !looked) return null;
- const aiId = `${id}_write`;
+ let aiId = `${id}_write`;
+ for (let n = 2; this.steps.some((step) => step.id === aiId); n += 1) aiId = `${id}_write_${n}`;
const what = file ?? `the ${field.replace(/_/g, " ")}`;
const request = this.request(400);
this.steps.push({
diff --git a/src/components/skill-burger/DraftSteps.tsx b/src/components/skill-burger/DraftSteps.tsx
index 06a384f427..49cd1f0037 100644
--- a/src/components/skill-burger/DraftSteps.tsx
+++ b/src/components/skill-burger/DraftSteps.tsx
@@ -5,7 +5,7 @@
import { Check, ChevronRight, Users } from "lucide-react";
import { useState, type KeyboardEvent } from "react";
-import { dependents, type DraftStepView, type DraftView } from "../../../shared/skill-burger/draft-view";
+import { composedFor, dependents, type DraftStepView, type DraftView } from "../../../shared/skill-burger/draft-view";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
import { LayerIcon } from "./SkillBurger";
@@ -105,8 +105,7 @@ export function DraftSteps({ steps, skipped, onSkip, disabled }: {
disabled: boolean;
}) {
const [open, setOpen] = useState<ReadonlySet<string>>(() => new Set());
- // A write step the AI composes and the file step it feeds read as one step on the card.
- const shown = steps.filter((step) => !step.id.endsWith("_write") || !steps.some((other) => `${other.id}_write` === step.id));
+ const shown = steps.filter((step) => !steps.some((other) => other.id === composedFor(step.id)));
const toggle = (step: DraftStepView) => {
const next = new Set(skipped);
const linked = [step.id, ...dependents(steps, step.id)];
@@ -119,7 +118,7 @@ export function DraftSteps({ steps, skipped, onSkip, disabled }: {
const line = draftLine(step);
const kept = !skipped.has(step.id);
const expanded = open.has(step.id);
- const judged = !step.exact || steps.some((other) => other.id === `${step.id}_write` && !other.exact);
+ const judged = !step.exact || steps.some((other) => composedFor(other.id) === step.id && !other.exact);
return (
<li key={step.id} data-burger-layer={step.kind} data-kept={kept ? "true" : "false"}
className={cn("burger-layer burger-open flex min-w-0 shrink-0 flex-col rounded-[8px] bg-card px-2 py-1.5 text-[13px] shadow-sm", !kept && "opacity-50")}>
@@ -160,8 +159,8 @@ export function DraftSteps({ steps, skipped, onSkip, disabled }: {
/** One honest line: how much of it repeats exactly, and how much the bot redoes with judgement. */
export function replayLine(steps: DraftStepView[], skipped: ReadonlySet<string>): string {
- const kept = steps.filter((step) => !skipped.has(step.id) && !(step.id.endsWith("_write") && steps.some((other) => `${other.id}_write` === step.id)));
- const judged = kept.filter((step) => !step.exact || steps.some((other) => other.id === `${step.id}_write` && !other.exact)).length;
+ const kept = steps.filter((step) => !skipped.has(step.id) && !steps.some((other) => other.id === composedFor(step.id)));
+ const judged = kept.filter((step) => !step.exact || steps.some((other) => composedFor(other.id) === step.id && !other.exact)).length;
if (!judged) return t("skillBurger.draft.allExact");
if (judged === kept.length) return t("skillBurger.draft.allJudgement");
return t("skillBurger.draft.mix", { exact: kept.length - judged, judgement: judged });
diff --git a/src/components/skill-burger/SkillBurger.dom.test.ts b/src/components/skill-burger/SkillBurger.dom.test.ts
index ec61c17716..f7626860a9 100644
--- a/src/components/skill-burger/SkillBurger.dom.test.ts
+++ b/src/components/skill-burger/SkillBurger.dom.test.ts
@@ -178,20 +178,25 @@ it("explains a finished delegation run and saves only what the person kept, unde
expect(body).toMatchObject({ botId: "scout", threadId: "t1", skip: ["s2"], inputs: { site: { name: "website" } } });
});
-it("leaving a step out leaves out the steps that use its output", async () => {
+it.each([1, 2, 10])("groups %i composed fields with their app step and leaves out dependent steps", async (fields) => {
+ const writers = Array.from({ length: fields }, (_, index) => ({
+ id: `s2_write${index ? `_${index + 1}` : ""}`, kind: "ai", label: "Write summary", exact: false, needs: ["s1"],
+ }));
const draft = {
- goal: "Fetch and write", inputs: [],
+ goal: "Fetch and send", inputs: [],
steps: [
{ id: "s1", kind: "shell", label: "Fetch example.com", exact: true, needs: [] },
- { id: "s2_write", kind: "ai", label: "Write top.md", exact: false, needs: ["s1"] },
- { id: "s2", kind: "file", label: "Write top.md", exact: true, needs: ["s2_write"] },
+ ...writers,
+ { id: "s2", kind: "app", label: "Send summary", exact: true, needs: writers.map((step) => step.id) },
],
};
fixture.api.mockImplementation(async (path: string) => (path === "/api/skill-burger-draft" ? { draft } : {}));
// Another run than the one saved above: a saved run's card comes back saved.
await render([ask, app("m31", "GOOGLESHEETS_BATCH_GET"), app("m32", "GMAIL_SEND_EMAIL")]);
await act(async () => { await Promise.resolve(); await Promise.resolve(); });
- expect([...host.querySelectorAll("[data-burger-layer]")].map((row) => row.textContent)).toEqual([expect.stringContaining("Fetch example.com"), expect.stringContaining("Write top.md")]);
+ expect([...host.querySelectorAll("[data-burger-layer]")].map((row) => row.textContent)).toEqual([expect.stringContaining("Fetch example.com"), expect.stringContaining("Send summary")]);
+ expect(host.querySelector("[data-burger-pill]")?.textContent).toContain("2 steps");
+ expect(host.querySelector(".burger-bun-top")?.textContent).toContain("1 exact, 1 by judgement");
await act(async () => host.querySelector<HTMLInputElement>('input[aria-label="Keep “Fetch example.com”"]')!.click());
expect([...host.querySelectorAll("[data-burger-layer]")].map((row) => row.getAttribute("data-kept"))).toEqual(["false", "false"]);
});
diff --git a/src/components/skill-burger/SkillBurger.tsx b/src/components/skill-burger/SkillBurger.tsx
index bc25bf0c57..af5fcc6ae0 100644
--- a/src/components/skill-burger/SkillBurger.tsx
+++ b/src/components/skill-burger/SkillBurger.tsx
@@ -2,6 +2,7 @@ import { Check, FileText, Globe, Monitor, Signpost, Sparkles, Terminal, Users, X
import { useEffect, useId, useRef, useState, type CSSProperties, type FocusEvent, type KeyboardEvent } from "react";
import { appMeta, BARE_READ } from "../../../shared/skill-burger/apps";
+import { composedFor } from "../../../shared/skill-burger/draft-view";
import type { BurgerLayer } from "../../../shared/skill-burger/layers";
import { cn } from "@/lib/cn";
import { t } from "@/lib/i18n";
@@ -136,7 +137,7 @@ export function SkillBurger({ run, layers, draft, summary: initialSummary, canSa
};
const toggleLabel = folded ? t("skillBurger.expand") : t("skillBurger.collapse");
- const stepCount = draft ? draft.steps.filter((step) => !step.id.endsWith("_write") || !draft.steps.some((other) => `${other.id}_write` === step.id)).length : layers.length;
+ const stepCount = draft ? draft.steps.filter((step) => !draft.steps.some((other) => other.id === composedFor(step.id))).length : layers.length;
const count = [stepCount === 1 ? t("skillBurger.layersOne") : t("skillBurger.layersMany", { count: stepCount }), draft && !saved ? replayLine(draft.steps, skipped) : ""].filter(Boolean).join(" · ");
const cooking = busy || live;
const failed = !cooking && layers.some((layer) => layer.status === "failed");