Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(app-events): serialize automation identity checks
Afloat896e2e94a05e
diff --git a/server/app-trigger-identity.test.ts b/server/app-trigger-identity.test.tsnew file mode 100644index 0000000000..f6a0f6b701--- /dev/null+++ b/server/app-trigger-identity.test.ts@@ -0,0 +1,72 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it } from "vitest";+import type { AppTriggerBroker } from "./app-trigger-broker.ts";+import { AppTriggerManager } from "./app-triggers.ts";++const folders: string[] = [];+afterEach(() => { for (const dir of folders.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function harness() {+ const dir = mkdtempSync(join(tmpdir(), "omb-trigger-identity-"));+ folders.push(dir);+ let binds = 0;+ const broker: AppTriggerBroker = {+ triggerTypes: async () => ({}),+ triggerType: async () => ({ slug: "SLACK_CHANNEL_MESSAGE_RECEIVED", toolkit: "slack", name: "Message", description: "", config: {}, payload: {} }),+ create: async () => { binds++; return { triggerId: "copy" }; },+ setEnabled: async () => {}, remove: async () => {},+ inventory: async () => ({ triggers: [], unbound: [], limits: { plan: "desktop", eventsPerDay: 100 }, usage: { eventsToday: 0 } }),+ poll: async () => ({ events: [], cursor: 0 }), testEvent: async () => {},+ };+ const options = {+ file: join(dir, "triggers.json"), broker, service: () => ({ available: true as const }),+ connectedApps: async () => ({ slack: { connected: true, accounts: [{ id: "account", status: "ACTIVE" }] } }),+ botState: () => "ready" as const,+ runs: { enqueue: () => ({ id: "run" }), merge: () => null, receipt: () => null, pending: () => 0, cancelQueued: () => {} },+ };+ const manager = new AppTriggerManager(options);+ const create = (id: string) => manager.create({ id, botId: "bot", name: `Watch ${id}`, prompt: `Summarize ${id}`, app: "slack", event: "SLACK_CHANNEL_MESSAGE_RECEIVED", enabled: false });+ return { manager, create, binds: () => binds, reopened: () => new AppTriggerManager(options) };+}++it("restores an automation once when two undo requests arrive together", async () => {+ const h = harness();+ const original = await h.create("same");+ await h.manager.remove(original.id);+ const before = h.binds();+ const restored = await Promise.all([h.manager.restore(original.id), h.manager.restore(original.id)]);+ expect(restored.filter(Boolean)).toHaveLength(1);+ expect(h.manager.list()).toHaveLength(1);+ expect(h.reopened().list()).toHaveLength(1);+ expect(h.binds() - before).toBe(1);+});++it("adopts concurrent retries under one durable id", async () => {+ const source = harness();+ const original = await source.create("same");+ const target = harness();+ const copies = await Promise.all([target.manager.adopt(original), target.manager.adopt({ ...original, name: "Newest name" })]);+ expect(copies.map((copy) => copy.id)).toEqual([original.id, original.id]);+ expect(target.manager.list()).toHaveLength(1);+ expect(target.reopened().list()).toHaveLength(1);+ expect(target.manager.get(original.id)?.name).toBe("Newest name");+ expect(target.binds()).toBe(1);+});++it("rejects a duplicate explicit id while allowing unrelated creations", async () => {+ const h = harness();+ await Promise.all([h.create("first"), h.create("second")]);+ await expect(h.create("first")).rejects.toMatchObject({ status: 409 });+ expect(h.manager.list().map((trigger) => trigger.id).sort()).toEqual(["first", "second"]);+});++it("keeps an existing adoption's enabled switch", async () => {+ const h = harness();+ const original = await h.create("same");+ await h.manager.update(original.id, { enabled: true });+ const updated = await h.manager.adopt({ ...original, name: "New name" });+ expect(updated).toMatchObject({ id: original.id, enabled: true, name: "New name" });+ expect(h.manager.list()).toHaveLength(1);+});diff --git a/server/app-triggers.ts b/server/app-triggers.tsindex 3f77000aaf..ef41c4c363 100644--- a/server/app-triggers.ts+++ b/server/app-triggers.ts@@ -284,6 +284,7 @@ export class AppTriggerManager {received: 0, filtered: 0, createdAt: now, updatedAt: now,};await this.exclusive(async () => {+ if (this.triggers.some((candidate) => candidate.id === trigger.id)) throw new AppTriggerError("An automation with this id already exists.", 409);const duplicate = this.triggers.find((trigger) => trigger.enabled && trigger.botId === input.botId && trigger.event === type.slug &&trigger.accountId === account.id && trigger.prompt === prompt && JSON.stringify(trigger.config) === JSON.stringify(config));if (duplicate) throw new AppTriggerError(`The same automation already exists (${duplicate.id}). Use trigger_info to review it, then change that one instead.`, 409);@@ -311,9 +312,18 @@ export class AppTriggerManager {return (await this.update(record.id, { name: record.name, prompt: record.prompt, runOn: record.runOn, filter: record.filter ?? null, config,sameConversation: record.sameConversation === true }))!;}- return this.create({ id: record.id, botId: record.botId, name: record.name, prompt: record.prompt, app: record.app, event: record.event, account: record.accountId,- ...(record.filter ? { filter: record.filter } : {}), config, runOn: record.runOn, enabled: false, ...(record.sourceThreadId ? { sourceThreadId: record.sourceThreadId } : {}),- ...(record.sameConversation ? { sameConversation: true } : {}) });+ try {+ return await this.create({ id: record.id, botId: record.botId, name: record.name, prompt: record.prompt, app: record.app, event: record.event, account: record.accountId,+ ...(record.filter ? { filter: record.filter } : {}), config, runOn: record.runOn, enabled: false, ...(record.sourceThreadId ? { sourceThreadId: record.sourceThreadId } : {}),+ ...(record.sameConversation ? { sameConversation: true } : {}) });+ } catch (error) {+ // Another copy of the same move may have completed while this one validated its account and event.+ if (error instanceof AppTriggerError && error.status === 409 && this.triggers.some((candidate) => candidate.id === record.id)) {+ return (await this.update(record.id, { name: record.name, prompt: record.prompt, runOn: record.runOn, filter: record.filter ?? null, config,+ sameConversation: record.sameConversation === true }))!;+ }+ throw error;+ }}async update(id: string, patch: AppTriggerPatch, options: { protectInstructions?: boolean } = {}): Promise<AppTrigger | null> {@@ -395,20 +405,20 @@ export class AppTriggerManager {/** Brings back one deleted in the last week, with its settings; the service copy is made again. */async restore(id: string): Promise<AppTrigger | null> {this.assertWritable();- const entry = this.deleted.find((candidate) => candidate.trigger.id === id && candidate.at >= this.now() - RESTORE_WINDOW_MS);- if (!entry || this.triggers.some((trigger) => trigger.id === id)) return null;- if (this.options.botState(entry.trigger.botId) === "missing") throw new AppTriggerError("The assigned bot no longer exists.", 410);- const trigger: StoredTrigger = { ...structuredClone(entry.trigger), remote: { state: "pending" }, updatedAt: this.now() };- await this.exclusive(async () => {+ return this.exclusive(async () => {+ const entry = this.deleted.find((candidate) => candidate.trigger.id === id && candidate.at >= this.now() - RESTORE_WINDOW_MS);+ if (!entry || this.triggers.some((trigger) => trigger.id === id)) return null;+ if (this.options.botState(entry.trigger.botId) === "missing") throw new AppTriggerError("The assigned bot no longer exists.", 410);+ const trigger: StoredTrigger = { ...structuredClone(entry.trigger), remote: { state: "pending" }, updatedAt: this.now() };try { await this.bind(trigger); await this.applyEnabled(trigger.remote.triggerId); }catch (error) { this.markRemoteFailure(trigger, error); }this.deleted = this.deleted.filter((candidate) => candidate !== entry);this.triggers.unshift(trigger);this.save();+ this.emitTrigger(trigger);+ this.wake();+ return publicTrigger(trigger);});- this.emitTrigger(trigger);- this.wake();- return publicTrigger(trigger);}/** A test event marked as one, sent through the service's real queue when the automation has its copy there. */