Skip to content

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

fix(automations): restore previous enabled state on Undo

Afloatb63ecc7cb7be
diff --git a/server/app-trigger-requests.ts b/server/app-trigger-requests.ts
index dd30a64bf2..487b1a05ec 100644
--- a/server/app-trigger-requests.ts
+++ b/server/app-trigger-requests.ts
@@ -121,6 +121,7 @@ export class AppTriggerRequestService {
const parsed = operationSchema.safeParse(args.operation);
if (!parsed.success) throw new AppTriggerError(parsed.error.issues[0]?.message ?? "Invalid automation request");
const operation = parsed.data as AppTriggerRequestOperation;
+ const enabledOnly = operation.action === "pause" || operation.action === "resume";
const owner = operation.forBot?.botId ?? args.botId;
const triggers = this.options.triggers;
const before = operation.action === "create" ? undefined : this.owned(operation.triggerId, owner);
@@ -168,9 +169,10 @@ export class AppTriggerRequestService {
undo: {
name: redactSecretsInText(subject.name),
...(after && operation.action !== "run_now" ? { appliedUpdatedAt: after.updatedAt } : {}),
- ...(before && (operation.action === "update" || operation.action === "delete")
- ? { before: { name: before.name, prompt: before.prompt, runOn: before.runOn, enabled: before.enabled, config: before.config, ...(before.filter ? { filter: before.filter } : {}),
- ...(before.sameConversation ? { sameConversation: true } : {}) } }
+ ...(before && operation.action !== "run_now"
+ ? { before: { name: enabledOnly ? redactSecretsInText(before.name) : before.name, prompt: enabledOnly ? redactSecretsInText(before.prompt) : before.prompt,
+ runOn: before.runOn, enabled: before.enabled, config: enabledOnly ? {} : before.config, ...(!enabledOnly && before.filter ? { filter: before.filter } : {}),
+ ...(!enabledOnly && before.sameConversation ? { sameConversation: true } : {}) } }
: {}),
},
};
@@ -223,7 +225,7 @@ export class AppTriggerRequestService {
const patch = operation.action === "update"
? before ? { name: before.name, prompt: before.prompt, runOn: before.runOn, enabled: before.enabled, filter: before.filter ?? null, restoreConfig: before.config,
sameConversation: before.sameConversation === true } : undefined
- : { enabled: operation.action === "pause" };
+ : { enabled: before?.enabled ?? (operation.action === "pause") };
if (!patch || !await triggers.update(triggerId, patch)) return stale;
break;
}
diff --git a/server/app-trigger-switches.test.ts b/server/app-trigger-switches.test.ts
index 0f87c0ad1b..176aaf67a5 100644
--- a/server/app-trigger-switches.test.ts
+++ b/server/app-trigger-switches.test.ts
@@ -5,6 +5,7 @@ import { afterEach, expect, it } from "vitest";
import type { AppTriggerBroker } from "./app-trigger-broker.ts";
import { AppTriggerManager } from "./app-triggers.ts";
+import { AppTriggerRequestService, type AppTriggerRequestCard } from "./app-trigger-requests.ts";
const folders: string[] = [];
afterEach(() => { for (const dir of folders.splice(0)) rmSync(dir, { recursive: true, force: true }); });
@@ -83,3 +84,35 @@ it("switches a retained service copy off as soon as its last active automation i
expect(h.manager.get(paused.id)?.remote.triggerId).toBe("shared-copy");
expect(h.remoteEnabled()).toBe(false);
});
+
+it.each([
+ ["pause", false, false], ["pause", true, false], ["resume", false, false], ["resume", true, false],
+ ["pause", true, true], ["resume", false, true],
+] as const)("restores local and service state after undoing %s from %s (legacy: %s)", async (action, enabled, legacy) => {
+ const h = harness();
+ const config = { channel: "fixture-config-private" };
+ const filter = { text: "important" };
+ const prompt = "Use token=fixture-private-value.";
+ const saved = await h.manager.create({ botId: "first", name: "Status fixture", prompt, config, filter, app: "slack", event: "SLACK_CHANNEL_MESSAGE_RECEIVED", enabled });
+ const messages: Array<{ id: string; card: AppTriggerRequestCard }> = [];
+ const store = {
+ messagesFor: () => messages,
+ appendMessage: (_threadId: string, message: { card: AppTriggerRequestCard }) => {
+ const stored = { id: "receipt", card: message.card };
+ messages.push(stored);
+ return stored;
+ },
+ patchMessage: (_threadId: string, _messageId: string, patch: { card: AppTriggerRequestCard }) => { messages[0]!.card = patch.card; },
+ };
+ const service = new AppTriggerRequestService({ store, triggers: h.manager, botName: () => "First" });
+ const applied = await service.submit({ botId: "first", threadId: "thread", operation: { action, triggerId: saved.id } });
+ expect(h.manager.get(saved.id)?.enabled).toBe(action === "resume");
+ expect(JSON.stringify(messages[0]!.card)).not.toContain("fixture-private-value");
+ expect(JSON.stringify(messages[0]!.card)).not.toContain("fixture-config-private");
+ expect(messages[0]!.card.appTriggerRequest?.undo?.before?.filter).toBeUndefined();
+ if (legacy) delete messages[0]!.card.appTriggerRequest!.undo!.before;
+ expect(await service.undo({ botId: "first", threadId: "thread", requestId: applied.requestId })).toMatchObject({ state: "undone" });
+ expect(h.manager.get(saved.id)?.enabled).toBe(enabled);
+ expect(h.remoteEnabled()).toBe(enabled);
+ expect(h.reopened().get(saved.id)).toMatchObject({ enabled, prompt, config, filter });
+});
diff --git a/server/routine-requests.test.ts b/server/routine-requests.test.ts
index 182d0dfff8..46726274a9 100644
--- a/server/routine-requests.test.ts
+++ b/server/routine-requests.test.ts
@@ -16,6 +16,7 @@ import {
type RoutineToolDefinitionInput,
} from "./routine-requests.ts";
import { RoutineManager, type RoutineInput } from "./routines.ts";
+import { routineRequestCardDataSchema } from "./routine-request-schemas.ts";
import type { JsonValue } from "./schema.ts";
import "./server-line-packs.ts";
import { setConversationLanguage } from "./server-lines.ts";
@@ -2035,6 +2036,79 @@ describe("a bot's own routine changes", () => {
expect(routines.listRoutines().find((routine) => routine.prompt === "Start with the app.")?.runOnStartup).toBe(true);
});
+ it.each([
+ ["pause", false], ["pause", true], ["resume", false], ["resume", true],
+ ] as const)("restores the previous enabled state after %s from %s", async (action, enabled) => {
+ const { service, routines, clock } = own();
+ const saved = routines.create({ botId: "bot-a", name: "Status fixture", prompt: "Check the queue.", enabled,
+ schedule: { type: "daily", time: "09:00", weekdays: [1] } });
+ clock.now += 1_000;
+ const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
+ expect(routines.listRoutines()[0]?.enabled).toBe(action === "resume");
+ expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
+ expect(routines.listRoutines()[0]?.enabled).toBe(enabled);
+ });
+
+ it.each(["pause", "resume"] as const)("undoes an unchanged %s without disclosing instructions or losing attachments", async (action) => {
+ const { service, routines, store, clock } = own();
+ const enabled = action === "resume";
+ const prompt = "Use token=fixture-private-value.";
+ const attachments = [{ id: "context", name: "Context", path: "/fixture/context.txt", kind: "file" as const, size: 20 }];
+ const saved = routines.create({ botId: "bot-a", name: "Private status fixture", prompt, enabled, attachments,
+ schedule: { type: "daily", time: "09:00", weekdays: [1] } });
+ clock.now += 1_000;
+ const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
+ const receipt = store.messagesFor("ask-thread")[0]!.card!;
+ expect(JSON.stringify(receipt)).not.toContain("fixture-private-value");
+ expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
+ expect(routines.listRoutines()[0]).toMatchObject({ enabled, prompt, attachments });
+ });
+
+ it.each(["pause", "resume"] as const)("still undoes a legacy %s receipt without a before snapshot", async (action) => {
+ const { service, routines, store, clock } = own();
+ const enabled = action === "pause";
+ const saved = routines.create({ botId: "bot-a", name: "Legacy status fixture", prompt: "Check the queue.", enabled,
+ schedule: { type: "daily", time: "09:00", weekdays: [1] } });
+ clock.now += 1_000;
+ const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
+ delete store.messagesFor("ask-thread")[0]!.card!.routineRequest!.undo!.before;
+ expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
+ expect(routines.listRoutines()[0]?.enabled).toBe(enabled);
+ });
+
+ it.each([
+ ["pause", "name"], ["resume", "name"], ["pause", "prompt"], ["resume", "prompt"],
+ ] as const)("keeps %s Undo valid when redacting a maximum-length %s", async (action, field) => {
+ const { service, routines, store, clock } = own();
+ const name = field === "name" ? `${"x".repeat(65)} token=12345678` : "Status fixture";
+ const prompt = field === "prompt" ? `${"x".repeat(19_985)} token=12345678` : "Check the queue.";
+ const enabled = action === "resume";
+ const saved = routines.create({ botId: "bot-a", name, prompt, enabled,
+ schedule: { type: "daily", time: "09:00", weekdays: [1] } });
+ clock.now += 1_000;
+ const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
+ const receipt = JSON.parse(JSON.stringify(store.messagesFor("ask-thread")[0]!.card!.routineRequest));
+ expect(routineRequestCardDataSchema.safeParse(receipt).success).toBe(true);
+ expect(JSON.stringify(receipt)).not.toContain("12345678");
+ expect(receipt.undo.before.enabled).toBe(enabled);
+ expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
+ expect(routines.listRoutines()[0]).toMatchObject({ name, prompt, enabled });
+ });
+
+ it.each(["pause", "resume"] as const)("restores %s state without changing a fractional once timestamp", async (action) => {
+ const { service, routines, store, clock } = own();
+ const enabled = action === "resume";
+ const schedule = { type: "once" as const, at: clock.now + 60_000.5 };
+ const saved = routines.create({ botId: "bot-a", name: "Fractional time", prompt: "Check the queue.", enabled, schedule });
+ clock.now += 1_000;
+ const applied = await service.submit({ botId: "bot-a", threadId: "ask-thread", proposal: { action, routineId: saved.id } });
+ const receipt = JSON.parse(JSON.stringify(store.messagesFor("ask-thread")[0]!.card!.routineRequest));
+ expect(routineRequestCardDataSchema.safeParse(receipt).success).toBe(true);
+ expect(receipt.undo.before.enabled).toBe(enabled);
+ expect(undo(service, applied.requestId)).toMatchObject({ state: "undone" });
+ expect(routines.listRoutines()[0]).toMatchObject({ enabled, schedule });
+ });
+
it("undoes each kind of change once, and refuses a run or a stale change", async () => {
const { service, routines, store, clock } = own();
const submit = (proposal: RoutineProposalInput) => service.submit({ botId: "bot-a", threadId: "ask-thread", proposal });
diff --git a/server/routine-requests.ts b/server/routine-requests.ts
index 8e7d43f0f0..ca8b334ee2 100644
--- a/server/routine-requests.ts
+++ b/server/routine-requests.ts
@@ -887,23 +887,23 @@ function revalidateOperation(operation: RoutineRequestOperation, manager: Routin
}
}
-function routineSnapshot(routine: Routine): RoutineRequestSnapshot | undefined {
- if (routine.attachments?.length) return undefined;
- if (redactSecretsInText(routine.name) !== routine.name || redactSecretsInText(routine.prompt) !== routine.prompt) return undefined;
+function routineSnapshot(routine: Routine, enabledOnly = false): RoutineRequestSnapshot | undefined {
+ const name = redactSecretsInText(routine.name), instructions = redactSecretsInText(routine.prompt);
+ if (!enabledOnly && (routine.attachments?.length || name !== routine.name || instructions !== routine.prompt)) return undefined;
const snapshot: RoutineRequestSnapshot = {
- name: routine.name,
- instructions: routine.prompt,
- schedule: requestSchedule(routine.schedule),
+ name: enabledOnly ? name.slice(0, 80) : name,
+ instructions: enabledOnly ? instructions.slice(0, 20_000) : instructions,
+ schedule: enabledOnly && routine.schedule.type === "once" ? { type: "once", at: Math.max(0, Math.trunc(routine.schedule.at)) } : requestSchedule(routine.schedule),
runOn: routine.runOn,
durationMinutes: routine.durationMinutes,
- ...(routine.timeoutMinutes === undefined ? {} : { timeoutMinutes: routine.timeoutMinutes }),
- ...(routine.continuity ? { continuity: true } : {}), ...(routine.sameConversation ? { sameConversation: true } : {}),
- ...(routine.overlap === "queue" ? { overlap: "queue" as const } : {}),
- ...(routine.runOnStartup ? { runOnStartup: true } : {}),
+ ...(enabledOnly || routine.timeoutMinutes === undefined ? {} : { timeoutMinutes: routine.timeoutMinutes }),
+ ...(!enabledOnly && routine.continuity ? { continuity: true } : {}), ...(!enabledOnly && routine.sameConversation ? { sameConversation: true } : {}),
+ ...(!enabledOnly && routine.overlap === "queue" ? { overlap: "queue" as const } : {}),
+ ...(!enabledOnly && routine.runOnStartup ? { runOnStartup: true } : {}),
enabled: routine.enabled,
- ...(routine.target === "room-goal" ? { target: "room-goal" as const } : {}),
- ...(routine.groupId ? { groupId: routine.groupId } : {}),
- ...(routine.resultsThreadId ? { resultsThreadId: routine.resultsThreadId } : {}),
+ ...(!enabledOnly && routine.target === "room-goal" ? { target: "room-goal" as const } : {}),
+ ...(!enabledOnly && routine.groupId ? { groupId: routine.groupId } : {}),
+ ...(!enabledOnly && routine.resultsThreadId ? { resultsThreadId: routine.resultsThreadId } : {}),
};
return storedSnapshotSchema.safeParse(snapshot).success ? snapshot : undefined;
}
@@ -1016,8 +1016,8 @@ export class RoutineRequestService {
if (args.canCommit && !args.canCommit()) {
throw new RoutineRequestError("The requesting turn ended before this proposal could be saved", 401);
}
- const before = automatic && (operation.action === "update" || operation.action === "delete")
- ? this.snapshotOf(operation.routineId, owner)
+ const before = automatic && operation.action !== "create" && operation.action !== "run_now"
+ ? this.snapshotOf(operation.routineId, owner, operation.action === "pause" || operation.action === "resume")
: undefined;
if (automatic) {
messageInput.card.options = [];
@@ -1055,9 +1055,9 @@ export class RoutineRequestService {
throw new RoutineRequestError(result.state === "invalid" ? result.error : "The routine change could not be applied", result.state === "invalid" ? result.status : 409);
}
- private snapshotOf(routineId: string, owner: string): RoutineRequestSnapshot | undefined {
+ private snapshotOf(routineId: string, owner: string, enabledOnly = false): RoutineRequestSnapshot | undefined {
const routine = ownedRoutine(this.routines, routineId, owner);
- return routine ? routineSnapshot(routine) : undefined;
+ return routine ? routineSnapshot(routine, enabledOnly) : undefined;
}
private recordAutoApplied(
@@ -1133,7 +1133,7 @@ export class RoutineRequestService {
if (!current || current.updatedAt !== undo.appliedUpdatedAt) return stale;
const patch = operation.action === "update"
? restorePatch(undo.before!, now)
- : { enabled: operation.action === "pause" };
+ : { enabled: undo.before?.enabled ?? (operation.action === "pause") };
if (!this.routines.update(routineId, patch)) return stale;
break;
}
diff --git a/server/webhook-requests.test.ts b/server/webhook-requests.test.ts
index e74fd149bb..5f80c3c61f 100644
--- a/server/webhook-requests.test.ts
+++ b/server/webhook-requests.test.ts
@@ -50,6 +50,35 @@ function harness() {
const create = { action: "create", webhook: { name: "Interested replies", instructions: "Draft a follow-up for the lead in the payload." } };
describe("WebhookRequestService", () => {
+ it.each([
+ ["pause", false], ["pause", true], ["resume", false], ["resume", true],
+ ] as const)("restores the previous enabled state after %s from %s", (action, enabled) => {
+ const { service, webhooks, store, tick } = harness();
+ const prompt = "Use token=fixture-private-value.";
+ const payloadFilter = { note: "token=fixture-filter-value" };
+ const saved = webhooks.create({ name: "Status fixture", prompt, payloadFilter, botId: "bot-a", enabled }).webhook;
+ tick();
+ const applied = service.submit({ botId: "bot-a", threadId: "thread-a", operation: { action, webhookId: saved.id } });
+ expect(webhooks.list()[0]!.enabled).toBe(action === "resume");
+ const card = store.messagesFor("thread-a")[0]!.card!;
+ expect(JSON.stringify(card)).not.toContain("fixture-private-value");
+ expect(JSON.stringify(card)).not.toContain("fixture-filter-value");
+ expect(card.webhookRequest?.undo?.before?.payloadFilter).toBeUndefined();
+ expect(service.undo({ botId: "bot-a", threadId: "thread-a", requestId: applied.requestId })).toMatchObject({ state: "undone" });
+ expect(webhooks.list()[0]).toMatchObject({ enabled, prompt, payloadFilter });
+ });
+
+ it.each(["pause", "resume"] as const)("still undoes a legacy %s receipt without a before snapshot", (action) => {
+ const { service, webhooks, store, tick } = harness();
+ const enabled = action === "pause";
+ const saved = webhooks.create({ name: "Legacy fixture", prompt: "Check the queue.", botId: "bot-a", enabled }).webhook;
+ tick();
+ const applied = service.submit({ botId: "bot-a", threadId: "thread-a", operation: { action, webhookId: saved.id } });
+ delete store.messagesFor("thread-a")[0]!.card!.webhookRequest!.undo!.before;
+ expect(service.undo({ botId: "bot-a", threadId: "thread-a", requestId: applied.requestId })).toMatchObject({ state: "undone" });
+ expect(webhooks.list()[0]!.enabled).toBe(enabled);
+ });
+
it("refuses replacing redacted instructions atomically but allows a rename", () => {
const { service, webhooks, store } = harness();
const prompt = "Review the queue.\n".repeat(180) + "Use token=fixture-secret-value.";
diff --git a/server/webhook-requests.ts b/server/webhook-requests.ts
index b15fc97bd8..37e6a9f2c9 100644
--- a/server/webhook-requests.ts
+++ b/server/webhook-requests.ts
@@ -80,15 +80,15 @@ export type UndoWebhookRequestResult =
| { claimed: true; state: "invalid"; error: string; status: number; stale?: true }
| { claimed: true; state: "undone"; action: WebhookRequestOperation["action"]; webhookId: string };
-function snapshot(webhook: WebhookTrigger): WebhookRequestSnapshot {
+function snapshot(webhook: WebhookTrigger, enabledOnly = false): WebhookRequestSnapshot {
return {
- name: webhook.name,
- instructions: webhook.prompt,
+ name: enabledOnly ? redactSecretsInText(webhook.name) : webhook.name,
+ instructions: enabledOnly ? redactSecretsInText(webhook.prompt) : webhook.prompt,
runOn: webhook.runOn,
enabled: webhook.enabled,
- ...(webhook.eventTypes?.length ? { eventTypes: [...webhook.eventTypes] } : {}),
- ...(webhook.payloadFilter ? { payloadFilter: { ...webhook.payloadFilter } } : {}),
- ...(webhook.sameConversation ? { sameConversation: true } : {}),
+ ...(!enabledOnly && webhook.eventTypes?.length ? { eventTypes: [...webhook.eventTypes] } : {}),
+ ...(!enabledOnly && webhook.payloadFilter ? { payloadFilter: { ...webhook.payloadFilter } } : {}),
+ ...(!enabledOnly && webhook.sameConversation ? { sameConversation: true } : {}),
};
}
@@ -209,7 +209,7 @@ export class WebhookRequestService {
undo: {
name: redactSecretsInText(subject.name),
...(after && operation.action !== "run_now" ? { appliedUpdatedAt: after.updatedAt } : {}),
- ...(before && (operation.action === "update" || operation.action === "delete") ? { before: snapshot(before) } : {}),
+ ...(before && operation.action !== "run_now" ? { before: snapshot(before, operation.action === "pause" || operation.action === "resume") } : {}),
},
};
const message = this.options.store.appendMessage(args.threadId, {
@@ -260,7 +260,7 @@ export class WebhookRequestService {
if (!current || current.updatedAt !== payload.undo?.appliedUpdatedAt) return stale;
const patch = operation.action === "update"
? before ? { ...managerInput(before), eventTypes: before.eventTypes ?? [], payloadFilter: before.payloadFilter ?? null, sameConversation: before.sameConversation === true, enabled: before.enabled } : undefined
- : { enabled: operation.action === "pause" };
+ : { enabled: before?.enabled ?? (operation.action === "pause") };
if (!patch || !webhooks.update(webhookId, patch)) return stale;
break;
}