Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
A User pressing Send with no AI reads who connects it, and the owner is told
milind-sonic8544c8eff4e
diff --git a/docs/team-cloud.md b/docs/team-cloud.mdindex 368ac5748a..7064bc7d99 100644--- a/docs/team-cloud.md+++ b/docs/team-cloud.md@@ -458,6 +458,16 @@ allow, folders), where it runs, its department, whom it answers to or directs, cNot now changes nothing and tells nobody; they can ask again. The card is a set-answer question card(`card.accessRequest`), shown in each person's language, and its answer is always its own option.+## A team with no AI++Until someone connects an AI, a bot has nothing to answer with. A Send from a User comes back as `409` with `code: "no_ai"`:+*"Olive needs to connect an AI before bots can answer. I've told them."*, and the app keeps their message in the box for+them to send again. The owner gets one line in their inbox, naming who tried and never their words, at most once a day+for each person (`server/host/no-ai-notice.ts`). The machine learns who the owner is only when they first open the team, so+until then the User reads that the owner will be told, and the line goes when the owner first opens it+(`no-ai-notices.json`). An Admin reads *"Connect an AI first, so bots can answer."* and nobody is told; a run nobody+started by hand reads *"No AI is connected yet, so nothing can run."*+## One inbox per personEverything addressed to a person reaches one place, their **inbox** (`server/host/person-inbox.ts`): their own privatediff --git a/scripts/testing/cloud-send-fixture.ts b/scripts/testing/cloud-send-fixture.tsindex 7554d2aa5f..4112c9ae73 100644--- a/scripts/testing/cloud-send-fixture.ts+++ b/scripts/testing/cloud-send-fixture.ts@@ -161,7 +161,7 @@ exports.createClient = async ({ auth }) => {export async function launchCloudSendFixture({ onePasswordToken, cloudOnePasswordToken = onePasswordToken, toolCalls = 0, broker, env = {}, cloudEnv = {}, cloudEngine = "", desktopEngine = "", space, cloudSignedIn = true, team }: {onePasswordToken: string; cloudOnePasswordToken?: string; toolCalls?: number;/** A Team Cloud too (OMB_CLOUD_ROLE=team), with its own environment and synthetic Claude CLI lines. */- team?: { id: string; name: string; env?: NodeJS.ProcessEnv; engine?: string };+ team?: { id: string; name: string; env?: NodeJS.ProcessEnv; engine?: string; noAi?: boolean };broker?: { url: string; install(): Promise<{ id: string; token: string; userId: string }> };env?: NodeJS.ProcessEnv;/** My Cloud's own environment only (a store limit, say). */@@ -276,6 +276,10 @@ await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-cl// asked to stop over IPC and runs its own SIGTERM shutdown (as server/acp-shutdown.e2e.test.ts does).const stopOverIpc = process.platform === "win32";const stopOnMessage = `data:text/javascript,${encodeURIComponent('process.on("message", (message) => { if (message === "stop") process.emit("SIGTERM"); }); process.channel?.unref();')}`;+ if (team.noAi) {+ mkdirSync(join(root, "team", ".openmausbot"), { recursive: true });+ writeFileSync(join(root, "team", ".openmausbot", "config.json"), JSON.stringify({ instances: Object.fromEntries(["claude", "codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi", "grok"].map((id) => [id, { driver: "not-a-real-driver" }])) }));+ }const startTeam = (more: NodeJS.ProcessEnv = {}) => start("team", { OMB_CLOUD_ROLE: "team", OMB_CLOUD_TEAM_ID: team.id, OMB_CLOUD_TEAM_NAME: team.name,OMB_CLOUD_MACHINE_ID: "0d9e8f7a-6b5c-4d3e-9f8a-7b6c5d4e3f2a", OMB_CLOUD_ADMIN_URL: "https://cloud.example.test", OMB_CLOUD_BOOTSTRAP_SECRET: secret,OMB_PUBLIC_URL: `https://${CLOUD_HOST}`, OMB_TEST_INTERNAL_CAPABILITY_KEY: CAPABILITY_KEY, ...(broker ? { OMB_COMPOSIO_BROKER_URL: broker.url } : {}), ...team.env, ...more },diff --git a/server/host/no-ai-notice.test.ts b/server/host/no-ai-notice.test.tsnew file mode 100644index 0000000000..3eac3c7d07--- /dev/null+++ b/server/host/no-ai-notice.test.ts@@ -0,0 +1,107 @@+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { personKey } from "../person-key.ts";+import { createNoAiNotice } from "./no-ai-notice.ts";+import type { Delivery } from "./person-inbox.ts";++const OLIVE = { email: "[email protected]", role: "owner" as const };+const BEN = { email: "[email protected]", role: "admin" as const };+const DANA = { email: "[email protected]", role: "member" as const };+const MARA = { email: "[email protected]", role: "member" as const };+const key = (email: string) => personKey({ id: "", email });+const said = (person: { email: string }) => ({ name: person.email, id: key(person.email) });+const dirs: string[] = [];+afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); });++function fixture(over: { team?: null; reachable?: () => boolean; dataDir?: string } = {}) {+ const dataDir = over.dataDir ?? mkdtempSync(join(tmpdir(), "omb-no-ai-"));+ if (!over.dataDir) dirs.push(dataDir);+ const lines: Array<{ to: string; delivery: Delivery }> = [];+ const world = { people: [OLIVE, BEN, DANA, MARA] as Array<typeof OLIVE | typeof BEN | typeof DANA>, now: 1_000 };+ const make = () => createNoAiNotice({+ team: over.team === null ? null : { id: "team-acme", name: "Acme" }, dataDir,+ people: () => world.people, personName: (person) => (person === key(OLIVE.email) ? "Olive" : undefined),+ inbox: () => ({ deliver: (to, delivery) => { if (over.reachable && !over.reachable()) return null; lines.push({ to, delivery }); return { threadId: `inbox-${to}` }; } }),+ language: () => undefined, threadLanguage: () => undefined, now: () => world.now,+ });+ return { notice: make(), make, lines, world, dataDir };+}++describe("a Send with no AI on a team", () => {+ it("tells a User who connects it, as the app's own kind of refusal, and tells the owner in their inbox", () => {+ const { notice, lines } = fixture();+ const refused = notice.refusal("t1", said(DANA));+ expect(refused).toMatchObject({ status: 409, code: "no_ai", message: "Olive needs to connect an AI before bots can answer. I've told them." });+ expect(lines).toHaveLength(1);+ expect(lines[0]!.to).toBe(key(OLIVE.email));+ expect(lines[0]!.delivery).toMatchObject({ kind: "notice", from: { name: "Dana", email: DANA.email }, title: "Connect an AI for Acme",+ text: "Dana tried to use a bot in Acme, but no AI is connected yet. Connect one so bots can answer." });+ });++ it("tells the owner at most once a day for each person, and still says so to them", () => {+ const { notice, lines, world } = fixture();+ notice.refusal("t1", said(DANA));+ expect(notice.refusal("t1", said(DANA))?.message).toContain("I've told them");+ expect(lines, "the same person again").toHaveLength(1);+ notice.refusal("t2", said(MARA));+ expect(lines, "another person").toHaveLength(2);+ world.now += 24 * 60 * 60_000;+ notice.refusal("t1", said(DANA));+ expect(lines, "a day later").toHaveLength(3);+ });++ it("keeps the once a day across a restart", () => {+ const first = fixture();+ first.notice.refusal("t1", said(DANA));+ const again = fixture({ dataDir: first.dataDir });+ again.notice.refusal("t1", said(DANA));+ expect(again.lines).toEqual([]);+ });++ it("never says it told an owner it can't reach: it says it will, and does when they first open the team", () => {+ const { notice, make, lines, world, dataDir } = fixture();+ world.people = [DANA, MARA];+ expect(notice.refusal("t1", said(DANA))?.message).toBe("The team's owner needs to connect an AI before bots can answer. I'll tell them when they first open the team.");+ notice.refusal("t1", said(DANA));+ expect(lines).toEqual([]);+ notice.flush();+ expect(lines, "the owner still isn't here").toEqual([]);+ world.people = [OLIVE, DANA, MARA];+ const restarted = make();+ restarted.flush();+ expect(lines.map((line) => [line.to, line.delivery.from.email])).toEqual([[key(OLIVE.email), DANA.email]]);+ restarted.flush();+ expect(lines, "once").toHaveLength(1);+ restarted.refusal("t1", said(DANA));+ expect(lines, "and that counts as today's").toHaveLength(1);+ expect(dataDir).toBeTruthy();+ });++ it("says it will tell an owner whose inbox can't be made yet, and keeps them waiting", () => {+ let reachable = false;+ const { notice, lines } = fixture({ reachable: () => reachable });+ expect(notice.refusal("t1", said(DANA))?.message).toContain("I'll tell them");+ expect(lines).toEqual([]);+ reachable = true;+ notice.flush();+ expect(lines).toHaveLength(1);+ });++ it("asks an admin to connect one, and a run nobody started by hand says nothing can run; neither tells anyone", () => {+ const { notice, lines } = fixture();+ expect(notice.refusal("t1", said(BEN))?.message).toBe("Connect an AI first, so bots can answer.");+ expect(notice.refusal("t1", said(OLIVE))?.message).toBe("Connect an AI first, so bots can answer.");+ expect(notice.refusal("t1", undefined)).toMatchObject({ code: "no_ai", message: "No AI is connected yet, so nothing can run." });+ expect(lines).toEqual([]);+ });++ it("is nothing off a team", () => {+ const { notice, lines } = fixture({ team: null });+ expect(notice.refusal("t1", said(DANA))).toBeNull();+ notice.flush();+ expect(lines).toEqual([]);+ });+});diff --git a/server/host/no-ai-notice.ts b/server/host/no-ai-notice.tsnew file mode 100644index 0000000000..3869fa15cd--- /dev/null+++ b/server/host/no-ai-notice.ts@@ -0,0 +1,112 @@+// A Team Cloud's bot has no AI to answer with. A User can't connect one, so they read who can, and the team's owner hears+// about it in their inbox: at most once a day for each person. Someone who pressed Send before the owner ever opened the+// team is kept in no-ai-notices.json and passed on when the owner first does. The person's words never travel: their+// message stays in their own box.+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { z } from "zod";++import { nameFromEmail } from "../../shared/bot-owner.ts";+import type { ResolvedSender } from "../../shared/wire.ts";+import { writeFileAtomic } from "../atomic.ts";+import type { CloudTeam, TeamRole } from "../cloud-team.ts";+import { personKey } from "../person-key.ts";+import { serverLine, type LineLanguage } from "../server-lines.ts";+import type { Delivery } from "./person-inbox.ts";+import { teamAiOwner } from "./team-ai-owner.ts";++export const NO_AI_NOTICES_FILE = "no-ai-notices.json";+const DAY_MS = 24 * 60 * 60_000;+const MAX_WAITING = 50;++const fileSchema = z.object({ version: z.literal(1), told: z.record(z.string(), z.number()), waiting: z.array(z.string().min(3).max(254)).max(MAX_WAITING) });++export interface NoAiNoticeDeps {+ team: CloudTeam | null;+ dataDir: string;+ /** The team's current members. */+ people(): ReadonlyArray<{ email: string; role: TeamRole }>;+ /** The name a member chose, by their person key. */+ personName(person: string): string | undefined;+ /** Every person's inbox, made after this. */+ inbox(): { deliver(person: string, delivery: Delivery): { threadId: string } | null };+ /** The language of a line for this person. */+ language: LineLanguage;+ /** The language of a line in this conversation. */+ threadLanguage(threadId: string): string | undefined;+ now?: () => number;+}++export type NoAiRefusal = Error & { status: number; code: "no_ai" };++export function createNoAiNotice(deps: NoAiNoticeDeps) {+ const now = deps.now ?? Date.now;+ const file = join(deps.dataDir, NO_AI_NOTICES_FILE);+ const keyOf = (email: string) => personKey({ id: "", email });+ const nameOf = (email: string) => {+ const chosen = deps.personName(keyOf(email))?.trim();+ return chosen && chosen !== email ? chosen : nameFromEmail(email);+ };+ let told: Record<string, number> = {};+ let waiting: string[] = [];+ if (deps.team) {+ try {+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(file, "utf8")));+ if (parsed.success) ({ told, waiting } = parsed.data);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.warn(`no-AI notices: ${file} is unreadable; starting fresh`);+ }+ }+ const save = () => {+ try {+ writeFileAtomic(file, `${JSON.stringify({ version: 1, told, waiting })}\n`, { mode: 0o600 });+ } catch (error) {+ console.warn(`no-AI notices: could not save ${file}: ${error instanceof Error ? error.message : String(error)}`);+ }+ };++ /** One inbox line to the owner saying who is waiting; false when the owner can't be reached here yet. */+ function tellOwner(asker: string): boolean {+ const owner = teamAiOwner(deps.people(), deps.personName);+ if (!owner) return false;+ const ownerKey = keyOf(owner.email), language = deps.language(ownerKey), name = nameOf(asker);+ return Boolean(deps.inbox().deliver(ownerKey, {+ kind: "notice", from: { name, email: asker }, notify: "mention",+ title: serverLine(language, "server.noAi.ownerTitle", { team: deps.team!.name }),+ text: serverLine(language, "server.noAi.ownerLine", { name, team: deps.team!.name }),+ }));+ }++ /** Whoever pressed Send before the owner opened the team is passed on as soon as the owner can be told. */+ function flush(): void {+ if (!waiting.length) return;+ const still = waiting.filter((asker) => !tellOwner(asker));+ if (still.length === waiting.length) return;+ for (const asker of waiting) if (!still.includes(asker)) told[keyOf(asker)] = now();+ waiting = still;+ save();+ }++ return {+ /** The refusal for a turn that has no AI on a team, in the words of the conversation's language; null off a team. */+ refusal(threadId: string, sender: ResolvedSender | undefined): NoAiRefusal | null {+ if (!deps.team) return null;+ const language = deps.threadLanguage(threadId);+ const refused = (line: string) => Object.assign(new Error(line), { status: 409, code: "no_ai" as const });+ const asker = sender?.id ? deps.people().find((person) => keyOf(person.email) === sender.id) : undefined;+ if (!asker) return refused(serverLine(language, "server.noAi.nobodyHere"));+ if (asker.role !== "member") return refused(serverLine(language, "server.noAi.admin"));+ const owner = teamAiOwner(deps.people(), deps.personName);+ const key = keyOf(asker.email), last = told[key], recently = last !== undefined && now() - last < DAY_MS;+ if (owner && (recently || tellOwner(asker.email))) {+ if (!recently) { told[key] = now(); save(); }+ return refused(serverLine(language, "server.noAi.member", { owner: owner.name }));+ }+ if (!waiting.includes(asker.email) && waiting.length < MAX_WAITING) { waiting = [...waiting, asker.email]; save(); }+ return refused(serverLine(language, "server.noAi.memberNoOwner"));+ },+ flush,+ };+}++export type NoAiNotice = ReturnType<typeof createNoAiNotice>;diff --git a/server/host/team-ai-owner.test.ts b/server/host/team-ai-owner.test.tsnew file mode 100644index 0000000000..9819741603--- /dev/null+++ b/server/host/team-ai-owner.test.ts@@ -0,0 +1,15 @@+import { expect, it } from "vitest";++import { personKey } from "../person-key.ts";+import { teamAiOwner } from "./team-ai-owner.ts";++const OLIVE = { email: "[email protected]", role: "owner" as const };+const BEN = { email: "[email protected]", role: "admin" as const };++it("names the team's owner by the name they chose, else from their address, and nobody until they have opened the team", () => {+ const chosen = new Map([[personKey({ id: "", email: OLIVE.email }), "Olive"]]);+ expect(teamAiOwner([BEN, OLIVE], (person) => chosen.get(person))).toEqual({ email: OLIVE.email, name: "Olive" });+ expect(teamAiOwner([BEN, OLIVE], () => undefined)?.name).toBe("Olive Smith");+ expect(teamAiOwner([BEN, OLIVE], () => OLIVE.email)?.name, "an address is no chosen name").toBe("Olive Smith");+ expect(teamAiOwner([BEN], () => "Ben")).toBeNull();+});diff --git a/server/host/team-ai-owner.ts b/server/host/team-ai-owner.tsnew file mode 100644index 0000000000..fcf0612cb9--- /dev/null+++ b/server/host/team-ai-owner.ts@@ -0,0 +1,13 @@+// Who connects an AI for a team: its owner. A User can't, so what they read names the owner rather than telling them to.+import { nameFromEmail } from "../../shared/bot-owner.ts";+import type { TeamRole } from "../cloud-team.ts";+import { personKey } from "../person-key.ts";++/** The team's owner by the name they chose. The Admin names a person here only when they first pair, so null until the+ * owner has opened the team. */+export function teamAiOwner(people: ReadonlyArray<{ email: string; role: TeamRole }>, chosenName: (person: string) => string | undefined): { email: string; name: string } | null {+ const owner = people.find((person) => person.role === "owner");+ if (!owner) return null;+ const chosen = chosenName(personKey({ id: "", email: owner.email }))?.trim();+ return { email: owner.email, name: chosen && chosen !== owner.email ? chosen : nameFromEmail(owner.email) };+}diff --git a/server/index.ts b/server/index.tsindex 2f9d2519f7..d671b908e6 100644--- a/server/index.ts+++ b/server/index.ts@@ -44,7 +44,7 @@ import { escapeAttribute } from "../src/lib/composer-attachments.ts";import { isPendingSignInRequest, normalizeSignInSite, signInOutcome, signInResumePrompt } from "../shared/sign-in-request.ts";import { createRoomTurnLevels } from "./room-turn-level.ts";-import { createSignInSettle } from "./host/sign-in-settle.ts"; import { createPersonLanguages, THIS_COMPUTER } from "./host/person-languages.ts"; import "./server-line-packs.ts"; import { serverLine, setConversationLanguage } from "./server-lines.ts";+import { createSignInSettle } from "./host/sign-in-settle.ts"; import { createPersonLanguages, THIS_COMPUTER } from "./host/person-languages.ts"; import "./server-line-packs.ts"; import { conversationLanguage, serverLine, setConversationLanguage } from "./server-lines.ts";import { RoomMemberLock } from "./room-member-lock.ts";import { approvalHeldNote, approvalHeldReason, approvalModeForOrigin, autoVerdict, deliverFullAccessApproval, undeliveredApprovalTool } from "./auto-approve.ts"; import { readsOwnFiles } from "./own-file-reads.ts";import { bindSafetyFloor, denyAtSafetyFloor, heldAtSafetyFloor, safetyFloorOn } from "./safety-floor-gate.ts";@@ -568,7 +568,7 @@ import { PhoneSecretBridge, PhoneSecretSubmissionRegistry } from "./phone-secret// Keep these two last, so loading the route table leaves module start-up order as is.import { gzipTunnelReplies, json, onJsonBody, parsedBodyOf, readBody } from "./harness/http.ts";import { holdBodyDeadline } from "./body-deadline.ts";-import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";+import { createNoAiNotice } from "./host/no-ai-notice.ts"; import { PASS, ROUTES, dispatchRoutes } from "./routes/table.ts"; import { createSecretCards } from "./host/secret-cards.ts"; import { createInternalCredentialRequestRoutes, createSecretCardRoutes } from "./routes/secret-cards.ts"; import { applyIncludedPagesMessage } from "./pages/access.ts"; import { createPublishedPages } from "./pages/service.ts"; import { createInternalToolRoutes } from "./routes/internal-tools.ts"; import { createHelperSuggestionRoutes } from "./routes/helper-suggestion.ts"; import { createXConnectorRoutes } from "./routes/x-connector.ts"; import { createMoveFreeze, switchAutomationsOff } from "./move-freeze.ts"; import { createMoveFreezeRoutes } from "./routes/move-freeze.ts"; import { createMoveWaits } from "./move-waits.ts"; import { assertBotHere, createBotMoves } from "./bot-moves.ts"; import { createBotMoveRoutes } from "./routes/bot-moves.ts"; import { createTeamMoveIn, moveInRefusal } from "./team-move-in.ts";import { createHostedSlackRoutes } from "./routes/hosted-slack.ts";import { createBotPresetRoutes } from "./routes/bot-presets.ts"; import { createWorkspaceBannerRoutes, workspaceBannerStore, workspaceBannerSummary } from "./routes/workspace-banner.ts";import { createBotMemoryRoutes } from "./routes/bot-memory.ts";@@ -2853,6 +2853,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesstore, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });+const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,@@ -7734,10 +7735,7 @@ async function beginTurn(const instance = registry.get(bot.modelSelection.instanceId);if (!instance) {if (removedComputerInstanceIds(cfg.instances).has(bot.modelSelection.instanceId)) void retryComputerEngineMove();- throw Object.assign(- new Error(`provider instance "${bot.modelSelection.instanceId}" is unavailable — pick another model in settings`),- { status: 409 },- );+ throw noAiNotice.refusal(threadId, opts?.sender) ?? Object.assign(new Error(`provider instance "${bot.modelSelection.instanceId}" is unavailable — pick another model in settings`), { status: 409 });}const policyRefusal = policyModelRefusal(instance);if (policyRefusal) throw Object.assign(new Error(policyRefusal), { status: 409, code: "managed_policy" });@@ -12232,7 +12230,7 @@ ROUTES.push(createBotMessageRoutes({fromPhone: phones.fromPhone, notePhoneSend: phones.noteSend,desktopManaged: DESKTOP_MANAGED, cloudHome: Boolean(CLOUD_HOME), DirectSendRefused,acceptDirectSend, directSendRefusal, startTurn, usageTriggerFor, messageSender, cloudGuestSendRefusal, cloudThreadRefusal, resolveAccessRequest: accessRequests.resolve, relayRefusal: CLOUD_TEAM ? (bot, email) => relayedSendRefusal(bot, email, Boolean(email && teamOwners.people?.list().some((one) => one.email === email && one.role !== "member"))) : undefined,- cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,+ noAiRefusal: noAiNotice.refusal, cardAnswerRefusal, commandRememberRefusal, requestBehavior, requestedTaskBot, botForThread, threadBusy,botAtThreadCapacity, parksBehindCoordination, activeGroupTurnForBot, runningTurnInstance, engineSteersImages, resolveReplyTarget,turnSelection, policyModelRefusal, clearUnattended, drainQueuedSends, answeringCardAs, resolveAndSendTrust, resolveAndSendTeamSetup, resolveAndSendMcp,resolveAndSendRoutine, resolveAndSendProfile, resolveAndSendModel, resolveSkillRequest, sendSkillResolution, answerRequest,@@ -12335,7 +12333,7 @@ ROUTES.push(createBotMemoryRoutes({}));const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DATA_DIR, sessions, store, routines: () => routines, library: () => readSkillLibraryIndex(), starters: threadStarters }) : null; const cloudSendOwner = (auth: RequestAuth) => teamMoveIn ? teamMoveIn.owner(auth) : (CLOUD_HOME && auth.kind === "session" && auth.scopes.includes("admin")) || ownHome.owner(auth) ? { person: actorKey(auth as RequestAuth & { kind: "session" }), name: cfg.profile?.name?.trim() || "User" } : null; const botMoves = CLOUD_PERSONAL ? createBotMoves({ store, routines: () => routines, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits, busy: (id) => botHasActiveTurn(id) || Boolean(routines?.activeRunForBot(id)) }) : null; ROUTES.push(createBotMoveRoutes({ moves: botMoves, enabled: CLOUD_PERSONAL })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createTtsRoutes({ config: () => cfg }), createHelperSuggestionRoutes({ notNow: proactive.suggestionNotNow }), createSetupRequestRoutes({ store, language: () => appLanguage() ?? Intl.DateTimeFormat().resolvedOptions().locale, sendRefusal: cloudGuestSendRefusal, presser: (auth) => setupPresser(sharedMembership(), auth, messageSender(auth)), canSetUp: (botId, threadId) => registry.get(store.projectBotForTask(botId, threadId)?.modelSelection.instanceId ?? "")?.adapter.capabilities.agentsMcp === true, send: (auth, botId, threadId, text) => acceptDirectSend({ botId, threadId, text, sender: messageSender(auth), trigger: usageTriggerFor(auth), personPresent: auth.kind === "session" || DESKTOP_MANAGED }) }), createNotificationRoutes(undefined, threadShown, CLOUD_TEAM ? (auth, entry) => teamOwners.routing.notificationReaches(teamOwners.viewer(auth), entry) : undefined), createUpdateCheckRoutes({ check: serverUpdateChecker({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE) }) }), createTimeZoneRoutes({ adopts: Boolean(CLOUD_HOME), dataDir: DATA_DIR, changed: () => routines?.rescheduleLocalTimes() }), createCloudSendRoutes({ appVersion: serverVersion(), ...(CLOUD_TEAM ? { refusal: personalMoveRefusal(CLOUD_TEAM), scope: (auth) => teamMoveIn?.scope(auth) ?? null } : {}), bots: () => store.bots, messagesTail: (threadId, limit) => store.messagesTail(threadId, limit), skills: (bot) => listSkills(bot.id), logins, config: () => cfg, lineLanguage: personLanguages.forLine, chats: { store, dataDir: DATA_DIR, owner: cloudSendOwner, ...(CLOUD_OWNER_KEY ? { ownerKey: CLOUD_OWNER_KEY } : {}), stamped: (threadId) => ownerOnlyCache.delete(threadId), instanceExists: (id) => Boolean(registry.get(id)), approvalSupported: (selection, mode) => supportsApprovalMode(selection, mode) }, cloudHome: Boolean(CLOUD_HOME), ownHome: ownHome.owner, automations: { routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, waits: () => botWaits }, connections: () => cloudConnections.connections(), connectionFingerprints: (nonce) => cloudConnections.fingerprints(nonce), move: { dataDir: DATA_DIR, store, routines: () => routines, calls: () => calendarCalls, webhooks: () => webhooks, appEvents: () => appTriggers.manager, claudeCodeSkills: () => (claudeUserSkillsEnabled(cfg) ? claudeCodeSkillInputs() : []), instanceExists: (id) => Boolean(registry.get(id)), owner: cloudSendOwner, ownRoutine: (routine, person) => { cloudRoutineAuthors?.record(routine.id, routine); cloudRoutineAuthors?.wrote(routine.id, person); }, arrived: () => ownerOnlyCache.clear(), teamMemory, aboutMe: () => cfg.profile?.aboutMe ?? "", saveAboutMe: (text) => { saveConfig({ profile: { ...cfg.profile, aboutMe: text } }); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } } }), cloudConnections.routes, createTodayRoutes({ visibleFor: (auth) => visibleTo(viewerFor(auth)), ...(teamOwners.asks ? { asks: teamOwners.asks, messages: teamMessages.needsYou } : {}), sources: () => ({ bots: store.bots, groups: store.groups, routines, parked: coordinator.active(), engines: registry.instances().map((instance) => ({ instanceId: instance.instanceId, snapshot: registry.lastSnapshot(instance.instanceId) })) }) }), createInboxRoutes(teamMessages));if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));-ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: teamMessages.arrived } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),+ROUTES.push(createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot }), createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (auth, threadId) => { if (ownerOrAdmin(auth) && store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => publicUrl() ?? (auth.kind === "session" ? requestOrigin(req) : null) }),createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: { error: memberLoginRefusal(CLOUD_TEAM) } }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId) }));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),@@ -15561,7 +15559,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {} catch (e) {const status = (e as any)?.status ?? 500;const candidateCode = (e as { code?: unknown })?.code;- const code = typeof candidateCode === "string" && ["guarded_busy", "guarded_branch", "guarded_permissions", "guarded_request_changed", "guarded_request_untracked", "outside_workspace"].includes(candidateCode)+ const code = typeof candidateCode === "string" && ["guarded_busy", "guarded_branch", "guarded_permissions", "guarded_request_changed", "guarded_request_untracked", "outside_workspace", "no_ai"].includes(candidateCode)? candidateCode : undefined;return json(res, status, { error: e instanceof Error ? e.message : String(e), ...(code ? { code } : {}) });} finally {diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.tsindex 49836a12e6..bf635c1001 100644--- a/server/routes/bot-messages.test.ts+++ b/server/routes/bot-messages.test.ts@@ -40,7 +40,7 @@ class DirectSendRefused extends Error {type AcceptInput = Parameters<BotMessageRouteDeps["acceptDirectSend"]>[0];-async function fixture() {+async function fixture(over: Partial<Record<keyof BotMessageRouteDeps, unknown>> = {}) {const store = new Store(() => sonnet);const bot = store.createBot({ name: "Scout" });const threadId = bot.threadId;@@ -123,6 +123,7 @@ async function fixture() {state.serverPresses.push({ threadId: thread, messageId, type: action.type });return state.serverAnswer;},+ ...over,} as unknown as BotMessageRouteDeps;const routes = [createBotMessageRoutes(deps)];const server = createServer(async (req, res) => {@@ -161,6 +162,22 @@ async function fixture() {return { store, bot, threadId, state, post, edit, cancelQueued, show, row, sent, patches: vi.spyOn(store, "patchMessage") };}+describe("editing a message with no AI", () => {+ it("says what a Send says on a team, and starts no turn", async () => {+ const line = "Olive needs to connect an AI before bots can answer. I've told them.";+ const { store, threadId, state, edit } = await fixture({ registry: { get: () => undefined }, noAiRefusal: () => Object.assign(new Error(line), { status: 409, code: "no_ai" }) });+ const sent = store.appendMessage(threadId, { role: "user", kind: "text", text: "Hello" });+ expect(await edit(sent.id, { threadId, text: "Hello again" })).toMatchObject({ status: 409, body: { error: line } });+ expect(state.started).toEqual([]);+ });++ it("keeps its own words off a team", async () => {+ const { store, threadId, edit } = await fixture({ registry: { get: () => undefined }, noAiRefusal: () => null });+ const sent = store.appendMessage(threadId, { role: "user", kind: "text", text: "Hello" });+ expect((await edit(sent.id, { threadId, text: "Hello again" })).body.error).toContain("is unavailable");+ });+});+describe("POST /api/bots/:id/messages with widgetAction", () => {it("lets the server answer a press on its own card with no turn, refuses it for someone else, and reads no widget in another bot's chat", async () => {const { store, threadId, state, post, show, sent } = await fixture();diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 55e4290b39..ff949184de 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -51,6 +51,8 @@ export interface BotMessageRouteDeps {| "activeLeaf" | "appendMessage" | "bot" | "botByThread" | "bots" | "groupByThread" | "messagesFor"| "patchMessage" | "patchTask" | "projectBotForTask" | "setActiveLeaf" | "setTaskAskedAt" | "taskByThread" | "tasks">;registry: Pick<ProviderRegistry, "get">;+ /** On a team: the words for a turn with no AI to answer with, having told who can connect one. */+ noAiRefusal?(threadId: string, sender: ResolvedSender | undefined): Error | null;routines(): RoutineManager | null;handoffs: Pick<Handoffs, "current" | "steered">;/** The turn running in a thread now, as its runtime events name it. */@@ -481,6 +483,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler}const rerunSelection = turnSelection(bot.id, bot.threadId) ?? bot.modelSelection;if (!registry.get(rerunSelection.instanceId)) {+ const noAi = deps.noAiRefusal?.(bot.threadId, messageSender(auth));+ if (noAi) throw noAi;return json(res, 409, {error: `provider instance "${rerunSelection.instanceId}" is unavailable — pick another model in settings`,});diff --git a/server/team-no-ai.e2e.test.ts b/server/team-no-ai.e2e.test.tsnew file mode 100644index 0000000000..1495dbd2b4--- /dev/null+++ b/server/team-no-ai.e2e.test.ts@@ -0,0 +1,44 @@+// A real Team Cloud with no AI: what a User reads when they press Send, what stays theirs, and what reaches the owner.+import { randomBytes } from "node:crypto";+import { afterAll, beforeAll, expect, it } from "vitest";+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const OWNER = { email: "[email protected]", role: "owner" as const };+const USER = { email: "[email protected]", role: "member" as const };+const WORDS = "Our private numbers for the launch";+let fx: CloudSendFixture, team: CloudTeamFixture;+beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-team-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-1", name: "Acme", noAi: true } });+ team = fx.team!;+}, hostTimeout(120_000));+afterAll(async () => { await fx?.close(); });++const ownBot = async (token: string, email: string) => ((await team.as(token, "GET", "/api/bots")).body.bots as Array<{ id: string; threadId: string; defaultBot?: { person?: string }; modelSelection?: { instanceId?: string } }>).find((bot) => bot.defaultBot?.person === email)!;+const inboxRows = async (token: string) => ((await team.as(token, "GET", "/api/inbox")).body.rows ?? []) as Array<{ kind: string; text: string; from: { name: string } }>;++it("tells a User who connects the AI, sends nothing, and really tells the owner once they can be told", async () => {+ const dana = (await team.pair(USER)).token!;+ const maus = await ownBot(dana, USER.email);+ expect(maus.modelSelection?.instanceId, "this team has no AI").toBeFalsy();+ const send = () => team.as(dana, "POST", `/api/bots/${maus.id}/messages`, { text: WORDS, threadId: maus.threadId });++ const early = await send();+ expect(early).toMatchObject({ status: 409, body: { code: "no_ai", error: "The team's owner needs to connect an AI before bots can answer. I'll tell them when they first open the team." } });++ const olive = (await team.pair(OWNER)).token!;+ expect((await team.as(olive, "POST", "/api/presence/active", { source: "desktop" })).status).toBe(200);+ const lines = await inboxRows(olive);+ expect(lines.map((row) => [row.kind, row.from.name])).toEqual([["notice", "Dana"]]);+ expect(lines[0]!.text).toBe("Dana tried to use a bot in Acme, but no AI is connected yet. Connect one so bots can answer.");++ const later = await send();+ expect(later).toMatchObject({ status: 409, body: { code: "no_ai", error: "Olive needs to connect an AI before bots can answer. I've told them." } });+ expect(await inboxRows(olive), "not told twice in a day").toHaveLength(1);++ expect(JSON.stringify(lines), "the person's words stay theirs").not.toContain(WORDS);+ const after = await team.as(dana, "GET", "/api/bots?messages=50");+ const said = (after.body.bots as Array<{ id: string; messages?: Array<{ text?: string }> }>).find((bot) => bot.id === maus.id)!.messages;+ expect(Array.isArray(said), JSON.stringify(after.status)).toBe(true);+ expect(said!.some((line) => line.text === WORDS), "nothing was sent: the app keeps it in the box").toBe(false);+}, hostTimeout(120_000));diff --git a/src/locales/de.json b/src/locales/de.jsonindex 69ff67dbcc..0a4b63a365 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -237,6 +237,12 @@"server.teammates.personReplied": "{name} hat geantwortet","server.teammates.personAssistantAnswered": "Die Assistenz von {name} hat geantwortet","server.teammates.told": "{name} Bescheid gegeben",+ "server.noAi.member": "{owner} muss eine KI verbinden, bevor Bots antworten können. Ich habe Bescheid gegeben.",+ "server.noAi.memberNoOwner": "Der Inhaber des Teams muss eine KI verbinden, bevor Bots antworten können. Ich sage Bescheid, sobald er das Team zum ersten Mal öffnet.",+ "server.noAi.admin": "Verbinde zuerst eine KI, damit Bots antworten können.",+ "server.noAi.nobodyHere": "Es ist noch keine KI verbunden, daher kann nichts laufen.",+ "server.noAi.ownerTitle": "KI für {team} verbinden",+ "server.noAi.ownerLine": "{name} wollte in {team} einen Bot nutzen, aber es ist noch keine KI verbunden. Verbinde eine, damit Bots antworten können.","server.teammates.notPassed": "Nicht an {name} weitergegeben","server.mcp.reconnect.one": "Der MCP-Server {name} hat sich nicht verbunden, daher waren seine Tools diesmal nicht verfügbar. Bei deiner nächsten Nachricht verbindet er sich wieder.","server.mcp.reconnect.many": "Die MCP-Server {names} haben sich nicht verbunden, daher waren ihre Tools diesmal nicht verfügbar. Bei deiner nächsten Nachricht verbinden sie sich wieder.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 2dc463d346..0991b4a3a5 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -336,6 +336,12 @@"server.teammates.personReplied": "{name} replied","server.teammates.personAssistantAnswered": "{name}'s assistant answered","server.teammates.told": "Told {name}",+ "server.noAi.member": "{owner} needs to connect an AI before bots can answer. I've told them.",+ "server.noAi.memberNoOwner": "The team's owner needs to connect an AI before bots can answer. I'll tell them when they first open the team.",+ "server.noAi.admin": "Connect an AI first, so bots can answer.",+ "server.noAi.nobodyHere": "No AI is connected yet, so nothing can run.",+ "server.noAi.ownerTitle": "Connect an AI for {team}",+ "server.noAi.ownerLine": "{name} tried to use a bot in {team}, but no AI is connected yet. Connect one so bots can answer.","server.teammates.notPassed": "Not passed to {name}","server.mcp.reconnect.one": "The MCP server {name} didn't connect, so its tools weren't available this time. It connects again on your next message.","server.mcp.reconnect.many": "The MCP servers {names} didn't connect, so their tools weren't available this time. They connect again on your next message.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex 312451deba..cf310ad7fb 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -278,6 +278,12 @@"server.teammates.personReplied": "{name} respondió","server.teammates.personAssistantAnswered": "El asistente de {name} respondió","server.teammates.told": "Avisado a {name}",+ "server.noAi.member": "{owner} tiene que conectar una IA para que los bots puedan responder. Ya se lo he dicho.",+ "server.noAi.memberNoOwner": "Quien administra el equipo tiene que conectar una IA para que los bots puedan responder. Se lo diré en cuanto abra el equipo por primera vez.",+ "server.noAi.admin": "Conecta primero una IA para que los bots puedan responder.",+ "server.noAi.nobodyHere": "Todavía no hay ninguna IA conectada, así que nada puede ejecutarse.",+ "server.noAi.ownerTitle": "Conecta una IA para {team}",+ "server.noAi.ownerLine": "{name} intentó usar un bot en {team}, pero todavía no hay ninguna IA conectada. Conecta una para que los bots puedan responder.","server.teammates.notPassed": "No se pasó a {name}","star.title": "¿Te gusta {app}?","star.body": "Una estrella en GitHub ayuda a que más personas lo encuentren.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex e35c88773f..5eca952e82 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -232,6 +232,12 @@"server.teammates.personReplied": "{name} a répondu","server.teammates.personAssistantAnswered": "L'assistant de {name} a répondu","server.teammates.told": "{name} prévenu",+ "server.noAi.member": "{owner} doit connecter une IA pour que les bots puissent répondre. Je l'ai prévenu.",+ "server.noAi.memberNoOwner": "Le propriétaire de l'équipe doit connecter une IA pour que les bots puissent répondre. Je le préviendrai dès qu'il ouvrira l'équipe.",+ "server.noAi.admin": "Connectez d'abord une IA pour que les bots puissent répondre.",+ "server.noAi.nobodyHere": "Aucune IA n'est encore connectée, donc rien ne peut s'exécuter.",+ "server.noAi.ownerTitle": "Connectez une IA pour {team}",+ "server.noAi.ownerLine": "{name} a essayé d'utiliser un bot dans {team}, mais aucune IA n'est encore connectée. Connectez-en une pour que les bots puissent répondre.","server.teammates.notPassed": "Non transmis à {name}","star.title": "Vous aimez {app} ?","star.body": "Une étoile sur GitHub aide plus de gens à le découvrir.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 3330da0f9a..74a104814a 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -232,6 +232,12 @@"server.teammates.personReplied": "{name} ने जवाब दिया","server.teammates.personAssistantAnswered": "{name} के असिस्टेंट ने जवाब दिया","server.teammates.told": "{name} को बताया",+ "server.noAi.member": "बॉट जवाब दे सकें, इसके लिए {owner} को एक AI जोड़ना होगा। मैंने उन्हें बता दिया है।",+ "server.noAi.memberNoOwner": "बॉट जवाब दे सकें, इसके लिए टीम के मालिक को एक AI जोड़ना होगा। जब वे पहली बार टीम खोलेंगे, मैं उन्हें बता दूँगा।",+ "server.noAi.admin": "पहले एक AI जोड़ें, ताकि बॉट जवाब दे सकें।",+ "server.noAi.nobodyHere": "अभी कोई AI जुड़ा नहीं है, इसलिए कुछ भी नहीं चल सकता।",+ "server.noAi.ownerTitle": "{team} के लिए एक AI जोड़ें",+ "server.noAi.ownerLine": "{name} ने {team} में एक बॉट इस्तेमाल करना चाहा, लेकिन अभी कोई AI जुड़ा नहीं है। एक AI जोड़ें, ताकि बॉट जवाब दे सकें।","server.teammates.notPassed": "{name} तक नहीं पहुँचाया","star.title": "{app} पसंद आ रहा है?","star.body": "GitHub पर एक स्टार से ज़्यादा लोग इसे ढूँढ पाते हैं।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex 3192f02ce3..e3910e20c5 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -283,6 +283,12 @@"server.teammates.personReplied": "{name} ha risposto","server.teammates.personAssistantAnswered": "L'assistente di {name} ha risposto","server.teammates.told": "Avvisato {name}",+ "server.noAi.member": "{owner} deve collegare un'IA perché i bot possano rispondere. L'ho già avvisato.",+ "server.noAi.memberNoOwner": "Il proprietario del team deve collegare un'IA perché i bot possano rispondere. Lo avviserò appena aprirà il team per la prima volta.",+ "server.noAi.admin": "Prima collega un'IA, così i bot potranno rispondere.",+ "server.noAi.nobodyHere": "Non è ancora collegata nessuna IA, quindi non può partire nulla.",+ "server.noAi.ownerTitle": "Collega un'IA per {team}",+ "server.noAi.ownerLine": "{name} ha provato a usare un bot in {team}, ma non è ancora collegata nessuna IA. Collegane una perché i bot possano rispondere.","server.teammates.notPassed": "Non passato a {name}","star.title": "Ti piace {app}?","star.body": "Una stella su GitHub aiuta più persone a trovarlo.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 0e9bf7b0dc..f990df0bcb 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -285,6 +285,12 @@"server.teammates.personReplied": "{name} が返信しました","server.teammates.personAssistantAnswered": "{name} のアシスタントが回答しました","server.teammates.told": "{name} に伝えました",+ "server.noAi.member": "ボットが返答するには、{owner} さんが AI を接続する必要があります。お伝えしました。",+ "server.noAi.memberNoOwner": "ボットが返答するには、チームのオーナーが AI を接続する必要があります。オーナーが初めてチームを開いたときにお伝えします。",+ "server.noAi.admin": "ボットが返答できるよう、先に AI を接続してください。",+ "server.noAi.nobodyHere": "AI がまだ接続されていないため、何も実行できません。",+ "server.noAi.ownerTitle": "{team} に AI を接続",+ "server.noAi.ownerLine": "{name} さんが {team} でボットを使おうとしましたが、AI がまだ接続されていません。ボットが返答できるよう接続してください。","server.teammates.notPassed": "{name} に渡せませんでした","star.title": "{app} を気に入っていただけましたか?","star.body": "GitHub でスターを付けていただくと、より多くの人に見つけてもらえます。",diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex e6f4cadd85..53ecdcb252 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -328,6 +328,12 @@"server.teammates.personReplied": "{name} 님이 답했어요","server.teammates.personAssistantAnswered": "{name} 님의 어시스턴트가 답했어요","server.teammates.told": "{name} 님에게 알렸어요",+ "server.noAi.member": "봇이 답하려면 {owner} 님이 AI를 연결해야 해요. 제가 알려 드렸어요.",+ "server.noAi.memberNoOwner": "봇이 답하려면 팀 소유자가 AI를 연결해야 해요. 소유자가 팀을 처음 열 때 알려 드릴게요.",+ "server.noAi.admin": "봇이 답할 수 있도록 먼저 AI를 연결하세요.",+ "server.noAi.nobodyHere": "아직 연결된 AI가 없어 아무것도 실행할 수 없어요.",+ "server.noAi.ownerTitle": "{team}에 AI 연결",+ "server.noAi.ownerLine": "{name} 님이 {team}에서 봇을 쓰려 했지만 아직 연결된 AI가 없어요. 봇이 답할 수 있도록 AI를 연결하세요.","server.teammates.notPassed": "{name} 님에게 전달하지 못했어요","star.title": "{app}이 마음에 드세요?","star.body": "GitHub에 별을 눌러 주시면 더 많은 사람이 찾을 수 있어요.",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex 5ebfec6702..9afc346f8e 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -285,6 +285,12 @@"server.teammates.personReplied": "{name} odpowiedział","server.teammates.personAssistantAnswered": "Asystent {name} odpowiedział","server.teammates.told": "Powiadomiono: {name}",+ "server.noAi.member": "{owner} musi podłączyć AI, zanim boty będą mogły odpowiadać. Już dałem znać.",+ "server.noAi.memberNoOwner": "Właściciel zespołu musi podłączyć AI, zanim boty będą mogły odpowiadać. Dam mu znać, gdy po raz pierwszy otworzy zespół.",+ "server.noAi.admin": "Najpierw podłącz AI, aby boty mogły odpowiadać.",+ "server.noAi.nobodyHere": "Nie podłączono jeszcze AI, więc nic nie może działać.",+ "server.noAi.ownerTitle": "Podłącz AI dla {team}",+ "server.noAi.ownerLine": "{name} próbuje użyć bota w {team}, ale nie podłączono jeszcze AI. Podłącz je, aby boty mogły odpowiadać.","server.teammates.notPassed": "Nie przekazano do: {name}","star.title": "Podoba ci się {app}?","star.body": "Gwiazdka na GitHubie pomaga większej liczbie osób go znaleźć.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 8fe32c2164..04ea84e8bb 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -277,6 +277,12 @@"server.teammates.personReplied": "{name} respondeu","server.teammates.personAssistantAnswered": "O assistente de {name} respondeu","server.teammates.told": "Avisado: {name}",+ "server.noAi.member": "{owner} precisa conectar uma IA para os bots poderem responder. Já avisei.",+ "server.noAi.memberNoOwner": "O dono da equipe precisa conectar uma IA para os bots poderem responder. Vou avisar quando ele abrir a equipe pela primeira vez.",+ "server.noAi.admin": "Conecte uma IA primeiro para os bots poderem responder.",+ "server.noAi.nobodyHere": "Nenhuma IA está conectada ainda, então nada pode rodar.",+ "server.noAi.ownerTitle": "Conecte uma IA para {team}",+ "server.noAi.ownerLine": "{name} tentou usar um bot em {team}, mas nenhuma IA está conectada ainda. Conecte uma para os bots poderem responder.","server.teammates.notPassed": "Não repassado para {name}","star.title": "Está gostando do {app}?","star.body": "Uma estrela no GitHub ajuda mais pessoas a encontrá-lo.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex ee6cc7fa62..3eb79f1f25 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -285,6 +285,12 @@"server.teammates.personReplied": "{name} ответил","server.teammates.personAssistantAnswered": "Ассистент {name} ответил","server.teammates.told": "Сообщено: {name}",+ "server.noAi.member": "{owner} нужно подключить ИИ, чтобы боты могли отвечать. Я уже сообщил.",+ "server.noAi.memberNoOwner": "Владельцу команды нужно подключить ИИ, чтобы боты могли отвечать. Я сообщу ему, когда он впервые откроет команду.",+ "server.noAi.admin": "Сначала подключите ИИ, чтобы боты могли отвечать.",+ "server.noAi.nobodyHere": "ИИ ещё не подключён, поэтому ничего не может запуститься.",+ "server.noAi.ownerTitle": "Подключите ИИ для {team}",+ "server.noAi.ownerLine": "{name} пытается использовать бота в {team}, но ИИ ещё не подключён. Подключите его, чтобы боты могли отвечать.","server.teammates.notPassed": "Не передано: {name}","star.title": "Нравится {app}?","star.body": "Звезда на GitHub поможет большему числу людей его найти.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 9868a6c55e..e96a3772cc 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -263,6 +263,12 @@"server.teammates.personReplied": "{name} yanıtladı","server.teammates.personAssistantAnswered": "{name} asistanı yanıtladı","server.teammates.told": "{name} bilgilendirildi",+ "server.noAi.member": "Botların yanıt verebilmesi için {owner} bir yapay zekâ bağlamalı. Kendisine haber verdim.",+ "server.noAi.memberNoOwner": "Botların yanıt verebilmesi için ekibin sahibi bir yapay zekâ bağlamalı. Ekibi ilk açtığında kendisine haber vereceğim.",+ "server.noAi.admin": "Botların yanıt verebilmesi için önce bir yapay zekâ bağlayın.",+ "server.noAi.nobodyHere": "Henüz bağlı bir yapay zekâ yok, bu yüzden hiçbir şey çalışamaz.",+ "server.noAi.ownerTitle": "{team} için bir yapay zekâ bağlayın",+ "server.noAi.ownerLine": "{name}, {team} içinde bir bot kullanmak istedi ama henüz bağlı bir yapay zekâ yok. Botların yanıt verebilmesi için bir tane bağlayın.","server.teammates.notPassed": "{name} kişisine iletilmedi","star.title": "{app}'u beğendiniz mi?","star.body": "GitHub'da vereceğiniz bir yıldız, daha fazla kişinin onu bulmasına yardımcı olur.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 14c34fd934..99bd6eb7c4 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -232,6 +232,12 @@"server.teammates.personReplied": "{name} відповів","server.teammates.personAssistantAnswered": "Асистент {name} відповів","server.teammates.told": "Повідомлено: {name}",+ "server.noAi.member": "{owner} має підключити ШІ, щоб боти могли відповідати. Я вже повідомив.",+ "server.noAi.memberNoOwner": "Власник команди має підключити ШІ, щоб боти могли відповідати. Я повідомлю йому, коли він уперше відкриє команду.",+ "server.noAi.admin": "Спершу підключіть ШІ, щоб боти могли відповідати.",+ "server.noAi.nobodyHere": "ШІ ще не підключено, тому нічого не може запуститися.",+ "server.noAi.ownerTitle": "Підключіть ШІ для {team}",+ "server.noAi.ownerLine": "{name} намагається використати бота в {team}, але ШІ ще не підключено. Підключіть його, щоб боти могли відповідати.","server.teammates.notPassed": "Не передано: {name}","star.title": "Подобається {app}?","star.body": "Зірка на GitHub допомагає більшій кількості людей знайти його.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 475c50665f..1142f29bd1 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -263,6 +263,12 @@"server.teammates.personReplied": "{name} đã trả lời","server.teammates.personAssistantAnswered": "Trợ lý của {name} đã trả lời","server.teammates.told": "Đã báo cho {name}",+ "server.noAi.member": "{owner} cần kết nối AI thì bot mới trả lời được. Mình đã báo rồi.",+ "server.noAi.memberNoOwner": "Chủ nhóm cần kết nối AI thì bot mới trả lời được. Mình sẽ báo khi họ mở nhóm lần đầu.",+ "server.noAi.admin": "Hãy kết nối AI trước để bot có thể trả lời.",+ "server.noAi.nobodyHere": "Chưa kết nối AI nên chưa thể chạy gì.",+ "server.noAi.ownerTitle": "Kết nối AI cho {team}",+ "server.noAi.ownerLine": "{name} muốn dùng một bot trong {team} nhưng chưa kết nối AI. Hãy kết nối để bot có thể trả lời.","server.teammates.notPassed": "Chưa chuyển cho {name}","star.title": "Bạn thích {app} chứ?","star.body": "Một ngôi sao trên GitHub sẽ giúp nhiều người biết đến ứng dụng hơn.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 6128add6cb..979c215b34 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -262,6 +262,12 @@"server.teammates.personReplied": "{name} 已回覆","server.teammates.personAssistantAnswered": "{name} 的助理已回答","server.teammates.told": "已告知 {name}",+ "server.noAi.member": "{owner} 需要先連接 AI,機器人才能回覆。我已經告訴對方了。",+ "server.noAi.memberNoOwner": "團隊擁有者需要先連接 AI,機器人才能回覆。對方第一次開啟團隊時我會告知。",+ "server.noAi.admin": "請先連接 AI,機器人才能回覆。",+ "server.noAi.nobodyHere": "尚未連接 AI,因此無法執行。",+ "server.noAi.ownerTitle": "為 {team} 連接 AI",+ "server.noAi.ownerLine": "{name} 想在 {team} 使用機器人,但尚未連接 AI。請連接一個,機器人才能回覆。","server.teammates.notPassed": "未轉給 {name}","star.title": "喜歡 {app} 嗎?","star.body": "在 GitHub 上給顆星,能幫助更多人找到它。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 51a6d7ce1e..8fb0bcc89c 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -332,6 +332,12 @@"server.teammates.personReplied": "{name} 已回复","server.teammates.personAssistantAnswered": "{name} 的助理已回答","server.teammates.told": "已告知 {name}",+ "server.noAi.member": "{owner} 需要先连接 AI,机器人才能回复。我已经告诉对方了。",+ "server.noAi.memberNoOwner": "团队所有者需要先连接 AI,机器人才能回复。对方第一次打开团队时我会告知。",+ "server.noAi.admin": "请先连接 AI,机器人才能回复。",+ "server.noAi.nobodyHere": "尚未连接 AI,因此无法运行。",+ "server.noAi.ownerTitle": "为 {team} 连接 AI",+ "server.noAi.ownerLine": "{name} 想在 {team} 使用机器人,但尚未连接 AI。请连接一个,机器人才能回复。","server.teammates.notPassed": "未转给 {name}","server.mcp.reconnect.one": "MCP 服务器 {name} 未能连接,所以这次它的工具不可用。你下一条消息发出时它会重新连接。","server.mcp.reconnect.many": "MCP 服务器 {names} 未能连接,所以这次它们的工具不可用。你下一条消息发出时它们会重新连接。",diff --git a/src/state/chat-error.ts b/src/state/chat-error.tsindex ec65655636..b4dfa0a98d 100644--- a/src/state/chat-error.ts+++ b/src/state/chat-error.ts@@ -1,7 +1,13 @@import { useEffect } from "react";+import { ApiError } from "./api";export const CHAT_ERROR_CLEAR_MS = 6_000;+/** The server's answer to a Send with no AI on a team: news for the person, not a failure of theirs. */+export function isNoAiRefusal(error: unknown): error is ApiError {+ return error instanceof ApiError && error.body?.code === "no_ai";+}+export function useChatErrorClear(error: string | null, clear: () => void): void {useEffect(() => {if (!error) return;diff --git a/src/state/no-ai-send.test.ts b/src/state/no-ai-send.test.tsnew file mode 100644index 0000000000..7961758e51--- /dev/null+++ b/src/state/no-ai-send.test.ts@@ -0,0 +1,48 @@+// @vitest-environment happy-dom+import { createElement } from "react";+import { flushSync } from "react-dom";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { StoreProvider, useStore } from "./store";++class FixtureEventSource {+ onopen: (() => void) | null = null;+ onerror: (() => void) | null = null;+ onmessage: ((event: { data: string }) => void) | null = null;+ close() {}+}++let store!: ReturnType<typeof useStore>;+function StoreReader() { store = useStore(); return null; }+let root: Root;++const answering = (status: number, body: Record<string, unknown>) => vi.stubGlobal("fetch", async (path: unknown) =>+ (String(path).endsWith("/messages") ? new Response(JSON.stringify(body), { status }) : new Response(JSON.stringify({ bots: [], groups: [], instances: [] }))));++beforeEach(() => {+ vi.stubGlobal("EventSource", FixtureEventSource);+ root = createRoot(document.createElement("div"));+ flushSync(() => root.render(createElement(StoreProvider, null, createElement(StoreReader))));+});+afterEach(() => {+ flushSync(() => root.unmount());+ vi.unstubAllGlobals();+});++it("reads a Send with no AI as news that stays a while, not a failure, and hands the message back", async () => {+ const line = "Olive needs to connect an AI before bots can answer. I've told them.";+ answering(409, { error: line, code: "no_ai" });+ const onError = vi.fn();+ store.dispatch({ type: "send", botId: "maus", threadId: "t", text: "Hello", onError });+ await vi.waitFor(() => expect(onError).toHaveBeenCalledOnce());+ await vi.waitFor(() => expect(store.state.notice).toEqual({ kind: "note", botName: null, text: line }));+ expect(store.state.error).toBeNull();+});++it("shows any other refusal as the error it is", async () => {+ answering(409, { error: "this thread is already working", code: "thread_busy" });+ const onError = vi.fn();+ store.dispatch({ type: "send", botId: "maus", threadId: "t", text: "Hello", onError });+ await vi.waitFor(() => expect(store.state.error).toBe("this thread is already working"));+ expect(store.state.notice).toBeNull();+});diff --git a/src/state/store.tsx b/src/state/store.tsxindex 7b552bdc5d..4d9e743914 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -67,7 +67,7 @@ import { speechOwner, spokenReplyStream } from "@/lib/spoken-reply-stream";import { t } from "@/lib/i18n";import { createBotPatchQueue, flushWhenLeaving, keepaliveFits, type BotUpdatePatch } from "./bot-patch-queue"; import { createNewTaskOnce } from "./new-task-once";import { liveCallFromFrame, nextLiveCallLookup } from "./live-call";-import { useChatErrorClear } from "./chat-error";+import { isNoAiRefusal, useChatErrorClear } from "./chat-error";import { openLiveEvents, publishLiveFrame, publishMissedFrames, withoutScreenPixels } from "@/lib/live-events";import { unlessRefused } from "@/lib/admin-scope";import { olderRunsSince, ROUTINE_RUNS_WINDOW_MS, trimRoutineRuns, withOlderRoutineRuns } from "./routine-runs";@@ -2158,9 +2158,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {const olderPagesInFlight = new Set<string>();const newTaskOnce = createNewTaskOnce();let creatingBot = false;- const showError = (e: unknown) => {- rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) });- };+ const showError = (e: unknown) => { if (isNoAiRefusal(e)) wrapped({ type: "notice", notice: { kind: "note", botName: null, text: e.message } }); else rawDispatch({ type: "error", message: e instanceof Error ? e.message : String(e) }); };const showSavedState = (owner: SavedOwner) => (error: unknown) => {showError(error);void api<SavedSnapshot>("/api/bots?messages=0").then((snapshot) => {