Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(rail): New organization from + for a Team plan with organizations (#3787)
Milind Soni7345f4c7d31b
diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdxindex a6aee458c9..1c29ef726c 100644--- a/apps/docs/content/docs/security/analytics.mdx+++ b/apps/docs/content/docs/security/analytics.mdx@@ -165,7 +165,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin| `cloud_checkout_opened` | A Cloud checkout opens in the browser | `plan`: Cloud plan; `trial`: true/false; `source`: as for `cloud_dialog_shown` || `cloud_add_another` | Buying another Cloud, for someone who has one, takes a step | `step`: `plan` (a plan chosen), `checkout_opened`, `ready`; `plan`: Cloud plan, for `plan` and `checkout_opened` || `rail_place_opened` | You open a place from the rail of Clouds at the window's left edge | `kind`: `computer`, `cloud`, `team`, `server` |-| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead) |+| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead), `organization` (a new organization added on the Team plan) || `cloud_setup_started` | A new Cloud starts its first job | none || `cloud_intent_submitted` | You tell a new Cloud what to do first | `idea`: `digest`, `watch`, `research`, `plan`, or none for your own words; `edited`: true/false || `cloud_intent_skipped` | You skip that question | none |diff --git a/docs/analytics.md b/docs/analytics.mdindex 3bfee040be..5dddc638cb 100644--- a/docs/analytics.md+++ b/docs/analytics.md@@ -161,7 +161,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin| `cloud_checkout_opened` | A Cloud checkout opens in the browser | `plan`: Cloud plan; `trial`: true/false; `source`: as for `cloud_dialog_shown` || `cloud_add_another` | Buying another Cloud, for someone who has one, takes a step | `step`: `plan` (a plan chosen), `checkout_opened`, `ready`; `plan`: Cloud plan, for `plan` and `checkout_opened` || `rail_place_opened` | You open a place from the rail of Clouds at the window's left edge | `kind`: `computer`, `cloud`, `team`, `server` |-| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead) |+| `rail_add` | You use the rail's + | `step`: `opened` (its sheet opened), `cloud` (Buy a Cloud, on this computer's own sheet), `link` (Paste pairing link), `address` (Enter its address instead), `organization` (a new organization added on the Team plan) || `cloud_setup_started` | A new Cloud starts its first job | none || `cloud_intent_submitted` | You tell a new Cloud what to do first | `idea`: `digest`, `watch`, `research`, `plan`, or none for your own words; `edited`: true/false || `cloud_intent_skipped` | You skip that question | none |diff --git a/electron/cloud-account-clouds.node-test.mjs b/electron/cloud-account-clouds.node-test.mjsindex 45a478df40..6562739567 100644--- a/electron/cloud-account-clouds.node-test.mjs+++ b/electron/cloud-account-clouds.node-test.mjs@@ -14,11 +14,12 @@ const PRIMARY = entry({ id: "c-home", name: "My Cloud", color: null, origin: HOMconst paid = { plan: "pro", tier: "pro", status: "active", expiresAt: NOW + 30 * 86400_000, version: 1 };const grant = (origin) => ({ cloudContractVersion: 1, origin, code: "ABCD-EFGH-JK23", expiresAt: NOW + 60_000 });-/** A fake Admin: the session says `f.session`, pairing answers `f.pairing(body)`, adding a Cloud answers `f.add(body)`. */+/** A fake Admin: the session says `f.session`, pairing answers `f.pairing(body)`, adding a Cloud answers `f.add(body)`, adding+ * an organization `f.organization(body)`. */async function admin(t) {const f = { requests: [], browsers: [], timer: null, delay: null,session: { cloud: { state: "ready", origin: HOME, pairingAvailable: true } },- pairing: () => [200, grant(HOME)], add: () => [404, { error: "not_found" }], patch: () => [404, { error: "not_found" }] };+ pairing: () => [200, grant(HOME)], add: () => [404, { error: "not_found" }], patch: () => [404, { error: "not_found" }], organization: () => [404, { error: "not_found" }] };const server = createServer(async (req, res) => {let body = ""; for await (const chunk of req) body += chunk;const parsed = body ? JSON.parse(body) : undefined;@@ -29,6 +30,7 @@ async function admin(t) {account: { id: "acct-1", email: "[email protected]" }, entitlement: paid, ...f.session }]);if (req.url === "/api/cloud/desktop/pairing" && req.method === "POST") return send(f.pairing(parsed));if (req.url === "/api/cloud/desktop/clouds" && req.method === "POST") return send(f.add(parsed));+ if (req.url === "/api/cloud/desktop/organizations" && req.method === "POST") return send(f.organization(parsed));if (req.url.startsWith("/api/cloud/desktop/clouds/") && req.method === "PATCH") return send(f.patch(decodeURIComponent(req.url.slice("/api/cloud/desktop/clouds/".length)), parsed));if (req.url === "/api/public/config") return send([200, { plans: [{ tier: "pro", price: { currency: "USD", interval: "month", amount: 4900 } }], trial: { days: 7 } }]);send([404, { error: "not_found" }]);@@ -204,3 +206,46 @@ test("a Cloud's colour is the Admin's: PATCH with the swatch, then the session rawait assert.rejects(f.client.setCloudColor("c-a", "chartreuse"), /Invalid Cloud color/);await assert.rejects(f.client.setCloudColor("../c-a", "blue"), /Invalid Cloud color/);});++const PLAN = "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", ORGANIZATION = "3c4d5e6f-7a8b-4c9d-8e1f-2a3b4c5d6e7f";+test("a new organization on the Team plan this account pays for: its name and swatch go to the Admin, nothing opens, and the session is read again", async t => {+ const f = await admin(t);+ f.session = { ...f.session, clouds: [PRIMARY, entry({ id: PLAN, name: "Agency", tier: "team", origin: TEAM, teamId: "team-1", primary: false })],+ organizations: { planCloudId: PLAN, canAdd: true, count: 1, max: 10, seats: { used: 3, limit: 20 } } };+ await f.client.start();+ assert.deepEqual(f.client.state().organizations, { planCloudId: PLAN, canAdd: true, count: 1, max: 10 });+ await assert.rejects(f.client.addOrganization({ name: "" }), /Invalid organization/);+ await assert.rejects(f.client.addOrganization({ name: "Client B", color: "url(x)" }), /Invalid organization/);+ assert.equal(f.requests.some(row => row.route.endsWith("/organizations")), false, "nothing malformed is sent");+ f.organization = body => [201, { cloudContractVersion: 1, cloud: entry({ id: ORGANIZATION, name: body.name, color: body.color, tier: "team", status: "setting_up", origin: null, teamId: "team-2" }) }];+ const reads = f.requests.filter(row => row.route.endsWith("/session")).length;+ assert.deepEqual(await f.client.addOrganization({ name: " Client B ", color: "rose" }), { outcome: "added", cloudId: ORGANIZATION });+ assert.deepEqual(f.requests.find(row => row.route.endsWith("/organizations")), { route: "/api/cloud/desktop/organizations", method: "POST", body: { name: "Client B", color: "rose" } });+ assert.equal(f.requests.filter(row => row.route.endsWith("/session")).length, reads + 1, "the rail then shows it being set up");+ assert.deepEqual(f.browsers, [], "no checkout: the plan already pays for it");+ await f.client.addOrganization({ name: "Client C" });+ assert.deepEqual(f.requests.filter(row => row.route.endsWith("/organizations")).at(-1).body, { name: "Client C" }, "no swatch: the Admin picks one");+});++test("the Admin's word on a new organization: the name is taken, the plan has as many as it can or isn't running, too many at once, or an Admin without them", async t => {+ const f = await admin(t);+ await f.client.start();+ assert.deepEqual(await f.client.addOrganization({ name: "Client B" }), { outcome: "unsupported" }, "no organizations in the session: nothing is asked");+ assert.equal(f.requests.some(row => row.route.endsWith("/organizations")), false);+ f.session = { ...f.session, clouds: [PRIMARY], organizations: { planCloudId: PLAN, canAdd: true, count: 2, max: 10, seats: { used: 3, limit: 5 } } };+ await f.client.refresh();+ for (const [answer, outcome] of [+ [[409, { error: "name_taken" }], { outcome: "taken" }],+ [[409, { error: "organization_unavailable", addBlocked: "limit" }], { outcome: "blocked", blocked: "limit" }],+ [[409, { error: "organization_unavailable", addBlocked: "no_team_plan" }], { outcome: "blocked", blocked: "no_team_plan" }],+ [[409, { error: "organization_unavailable", addBlocked: "mystery" }], { outcome: "failed" }],+ [[429, { error: "rate_limited", interval: 60 }], { outcome: "blocked", blocked: "rate" }],+ [[404, { error: "not_found" }], { outcome: "unsupported" }],+ [[400, { error: "invalid_request" }], { outcome: "failed" }],+ [[500, { error: "oops" }], { outcome: "failed" }],+ ]) {+ f.organization = () => answer;+ assert.deepEqual(await f.client.addOrganization({ name: "Client B" }), outcome, JSON.stringify(answer));+ }+ assert.deepEqual(f.browsers, []);+});diff --git a/electron/cloud-account.d.mts b/electron/cloud-account.d.mtsindex 2e90d88049..2279d44db7 100644--- a/electron/cloud-account.d.mts+++ b/electron/cloud-account.d.mts@@ -26,6 +26,8 @@ export interface CloudAccountState {clouds?: import("./cloud-list.mjs").CloudListEntry[];/** With `clouds`: whether the Admin opens another Cloud's checkout now, and why not. */addCloud?: { canAdd: true } | { canAdd: false; blocked: CloudAddBlock };+ /** With `clouds`, for the account a Team plan with organizations is billed to: whether + may add one to it now. */+ organizations?: import("./cloud-list.mjs").CloudOrganizations;/** The newest OpenMausBot release the Admin knows, while it follows releases (with `clouds`); absent otherwise. */latestVersion?: string;/** Another Cloud this app is buying (in the last 24 hours): its id, name, swatch and plan, when its checkout opened,@@ -89,6 +91,12 @@ export type CloudAddResult =| { outcome: "opened"; state: CloudAccountState }| { outcome: "unsupported" | "failed" }| { outcome: "blocked"; blocked: CloudAddBlock };+/** What adding an organization did: `added` (its Cloud is being set up), `taken` (another of the plan's has that name),+ * `blocked` with the Admin's reason, `unsupported` (an Admin without organizations), or `failed` (nothing was added). */+export type OrganizationAddResult =+ | { outcome: "added"; cloudId?: string }+ | { outcome: "taken" | "unsupported" | "failed" }+ | { outcome: "blocked"; blocked: import("./cloud-list.mjs").OrganizationBlock };/** What opening a checkout did: `opened` in the browser; `signing-in` (signed* out, the browser signs in first); `conflict` (the account changed, now read* again); `rate-limited`; or `failed` (nothing was opened). */@@ -267,6 +275,8 @@ export interface CloudAccountClient {isOwnCloud(origin: string | null | undefined): boolean;/** Buys another Cloud (POST /api/cloud/desktop/clouds): its checkout opens in the browser. */addCloud(input: { tier: string; interval?: "month" | "year"; name: string; color?: import("./cloud-list.mjs").CloudSwatch | null }): Promise<CloudAddResult>;+ /** A new organization on the Team plan this account pays for (POST /api/cloud/desktop/organizations): no checkout. */+ addOrganization(input: { name: string; color?: import("./cloud-list.mjs").CloudSwatch | null }): Promise<OrganizationAddResult>;/** A Cloud's colour on the Admin (PATCH /api/cloud/desktop/clouds/:id), for its owner or its team's Super admin and Admins. */setCloudColor(cloudId: string, color: import("./cloud-list.mjs").CloudSwatch | null): Promise<{ outcome: "saved" | "refused" | "unsupported" | "failed" }>;/** That checkout's page again (never a new one); false when none is kept. */diff --git a/electron/cloud-account.mjs b/electron/cloud-account.mjsindex ff126edf4c..3185e8a198 100644--- a/electron/cloud-account.mjs+++ b/electron/cloud-account.mjs@@ -1,6 +1,6 @@import { createManagedDesktopStore, retryDelay, unreadableRecord } from "./managed-desktop.mjs";import { CLOUD_MACHINE_CONNECTABLE, cloudUnreachableText, parseCloudCredit, parseCloudOffer, parseCloudPurchase, parseCloudSummary, parseCloudTeams, parseCloudTrial, parseCloudUsage, parsePairingGrant, parsePublicOffer, withoutTrial } from "./cloud-home.mjs";-import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, otherOwnClouds, ownCloud, parseCloudList, parseCloudRenewal, releaseVersion } from "./cloud-list.mjs";+import { CLOUD_ID, CLOUD_SWATCHES, cleanCloudListName, ORGANIZATION_BLOCKS, otherOwnClouds, ownCloud, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion } from "./cloud-list.mjs";import { planTeam, teamPlan } from "./cloud-team-plan.mjs";import { cleanCode, cleanEmail, parseSignInStart, SIGN_IN_START, SIGN_IN_TRIES, SIGN_IN_VERIFY, signInIdentity, startFailure, verifyFailure } from "./cloud-signin.mjs";@@ -258,6 +258,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNconst trial = parseCloudTrial(result.cloud?.trial), credit = parseCloudCredit(result.cloud?.credit), offer = parseCloudOffer(result.offer);const usage = access.status === "active" ? parseCloudUsage(result.cloud?.usage) : null;const clouds = parseCloudList(result.clouds), more = clouds ? addOffer(result) : null, latest = clouds ? releaseVersion(result.latestVersion) : null;+ const organizations = clouds ? parseOrganizations(result.organizations) : null;const { cloudId: renewingCloud = null, ...renewal } = parseCloudRenewal(result.clouds) ?? {};const hint = access.plan === "pro" ? { ...(access.tier ? { tier: access.tier } : {}), active: access.status === "active" } : null;if (next.expiresAt !== previous.expiresAt) {@@ -287,7 +288,7 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNaccess.status === "active" && access.expiresAt !== null ? access.expiresAt : Infinity);publish({ ...view("connected"), entitlement: access, ...(machine ? { machine } : {}), ...(teams.length ? { teams } : {}), ...(purchase ? { purchase } : {}),...(trial ? { trial } : {}), ...(credit ? { credit } : {}), ...(offer ? { offer } : {}), ...(usage ? { usage } : {}), ...(renewingCloud ? { renewal } : {}),- ...(clouds ? { clouds, addCloud: more } : {}), ...(latest ? { latestVersion: latest } : {}), verifiedAt: now(), verifiedUntil });+ ...(clouds ? { clouds, addCloud: more } : {}), ...(organizations ? { organizations } : {}), ...(latest ? { latestVersion: latest } : {}), verifiedAt: now(), verifiedUntil });const planCloud = teamPlan(value) ? planTeam(value)?.machine ?? null : machine;const settingUp = planCloud?.status === "provisioning" || (access.status === "active" && !planCloud) || Boolean(purchase) || otherOwnClouds(clouds).some(cloud => cloud.status === "setting_up");const added = adding ? clouds?.find(cloud => cloud.id === adding.cloudId) ?? null : null;@@ -696,6 +697,27 @@ export function createCloudAccountClient({ store, openBrowser, platform, deviceNschedule(refresh, WATCH_REFRESH_MS);return { outcome: "opened", state: state() };},+ /** A new organization on the Team plan this account pays for (POST organizations, contract v1): its name and swatch, and+ * no checkout. `added` once the Admin made it (the session is read again, so the rail shows it being set up); `blocked`+ * with the Admin's reason; `taken` when another of the plan's has that name; `unsupported` from an Admin without it. */+ async addOrganization({ name, color = null } = {}) {+ const cleanName = cleanCloudListName(name);+ if (!cleanName || !(color === null || CLOUD_SWATCHES.includes(color))) throw new Error("Invalid organization to add.");+ const signedIn = grant;+ if (!signedIn || state().status !== "connected") return { outcome: "failed" };+ if (!value.organizations) return { outcome: "unsupported" };+ let result;+ try { result = await request("organizations", { method: "POST", body: { name: cleanName, ...(color ? { color } : {}) }, token: signedIn.token }); } catch (error) {+ if (signInEnded(error)) { await refresh().catch(() => {}); return { outcome: "failed" }; }+ if (!error?.opaque && ORGANIZATION_BLOCKS.includes(error?.blocked)) return { outcome: "blocked", blocked: error.blocked };+ if (!error?.opaque && error?.code === "name_taken") return { outcome: "taken" };+ if (!error?.opaque && error?.status === 429) return { outcome: "blocked", blocked: "rate" };+ if ([404, 405, 501].includes(error?.status)) return { outcome: "unsupported" };+ return { outcome: "failed" };+ }+ if (grant === signedIn) await refresh().catch(() => {});+ return { outcome: "added", ...(typeof result?.cloud?.id === "string" && CLOUD_ID.test(result.cloud.id) ? { cloudId: result.cloud.id } : {}) };+ },/** A Cloud's colour (PATCH clouds/:id, contract v1), which only its owner or its team's Super admin and Admins* change: `saved` once the Admin keeps it (the session is read again, so every place follows); `refused` when the* Admin says it is someone else's to change; `unsupported` from an Admin without the route or the list. */diff --git a/electron/cloud-list.d.mts b/electron/cloud-list.d.mtsindex dec3629710..9918b410e8 100644--- a/electron/cloud-list.d.mts+++ b/electron/cloud-list.d.mts@@ -34,6 +34,13 @@ export interface CloudListEntry {*/export interface CloudRenewal { trial: boolean; cancelled: boolean; renewsAt: number | null; endsAt: number | null; keptDays: number | null; team?: string }export declare function parseCloudRenewal(clouds: unknown): (CloudRenewal & { cloudId: string }) | null;+/** Why an organization can't be added to the Team plan now. */+export type OrganizationBlock = "no_team_plan" | "limit" | "rate" | "off";+/** The session's `organizations`: the Team plan this account pays for, whether + may add an organization to it now (else+ * why), and how many it has of how many. */+export interface CloudOrganizations { planCloudId: string; canAdd: boolean; blocked?: OrganizationBlock; count: number; max: number }+export declare const ORGANIZATION_BLOCKS: readonly OrganizationBlock[];+export declare function parseOrganizations(input: unknown): CloudOrganizations | null;export declare const MAX_CLOUDS: number;export declare const CLOUD_LIST_STATUSES: readonly CloudListStatus[];export declare const CLOUD_SWATCH_COLORS: Readonly<Record<CloudSwatch, import("./cloud-buy.mjs").CloudColor | null>>;diff --git a/electron/cloud-list.mjs b/electron/cloud-list.mjsindex 6098092e19..399153b969 100644--- a/electron/cloud-list.mjs+++ b/electron/cloud-list.mjs@@ -99,6 +99,20 @@ export function parseCloudList(input) {return clouds;}+/** Why the Admin can't add an organization to a Team plan now: none of the account's runs, the plan has as many as it can,+ * too many were added in the last hour, or adding them was turned off. */+export const ORGANIZATION_BLOCKS = Object.freeze(["no_team_plan", "limit", "rate", "off"]);+/**+ * The session's `organizations` (contract v1, additive): the Team plan this account pays for whose organizations it runs,+ * whether one may be added now (else why), and how many it has of how many. Null without one, or from an older Admin.+ */+export function parseOrganizations(input) {+ if (!record(input) || typeof input.planCloudId !== "string" || !CLOUD_ID.test(input.planCloudId) || typeof input.canAdd !== "boolean") return null;+ if (!Number.isSafeInteger(input.count) || input.count < 0 || !Number.isSafeInteger(input.max) || input.max < 1) return null;+ const blocked = ORGANIZATION_BLOCKS.includes(input.addBlocked) ? input.addBlocked : null;+ return { planCloudId: input.planCloudId, canAdd: input.canAdd, ...(blocked && !input.canAdd ? { blocked } : {}), count: input.count, max: input.max };+}+/** OMB_CLOUD_STOPPED_HOLD_DAYS allows parts of a day, and at most 60. */const keptDays = value => value === null ? null : typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 60 ? value : undefined;/**diff --git a/electron/cloud-list.node-test.mjs b/electron/cloud-list.node-test.mjsindex b722893c28..7531458bfa 100644--- a/electron/cloud-list.node-test.mjs+++ b/electron/cloud-list.node-test.mjs@@ -1,7 +1,7 @@import assert from "node:assert/strict";import test from "node:test";-import { cloudMachine, cloudSetupProgress, listedColors, MAX_CLOUDS, olderRelease, otherOwnClouds, ownCloudPlaces, parseCloudList, parseCloudRenewal, releaseVersion, signedInServers, swatchColor } from "./cloud-list.mjs";+import { cloudMachine, cloudSetupProgress, listedColors, MAX_CLOUDS, olderRelease, otherOwnClouds, ownCloudPlaces, parseCloudList, parseCloudRenewal, parseOrganizations, releaseVersion, signedInServers, swatchColor } from "./cloud-list.mjs";import environments from "./environments.cjs";import { createHomePlaces } from "./home-places.mjs";@@ -169,3 +169,14 @@ test("the plan's renewal is the account's own primary Cloud's, only as the Adminassert.equal(parseCloudRenewal(clouds), null, JSON.stringify(clouds)?.slice(0, 80));}});++test("the session's organizations: the Team plan this account runs them for, whether + may add one now and why not; anything else is none", () => {+ const plan = { planCloudId: "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", canAdd: true, count: 3, max: 10, seats: { used: 9, limit: 20 } };+ assert.equal(parseOrganizations(undefined), null, "an older Admin, or no Team plan of this account's: no New organization");+ assert.deepEqual(parseOrganizations(plan), { planCloudId: plan.planCloudId, canAdd: true, count: 3, max: 10 }, "its seats are the Cloud page's, not the app's");+ assert.deepEqual(parseOrganizations({ ...plan, canAdd: false, addBlocked: "limit", count: 10 }), { planCloudId: plan.planCloudId, canAdd: false, blocked: "limit", count: 10, max: 10 });+ assert.deepEqual(parseOrganizations({ ...plan, canAdd: false, addBlocked: "mystery" }), { planCloudId: plan.planCloudId, canAdd: false, count: 3, max: 10 }, "a reason this app doesn't know is none");+ assert.deepEqual(parseOrganizations({ ...plan, addBlocked: "limit" }), { planCloudId: plan.planCloudId, canAdd: true, count: 3, max: 10 }, "a reason only counts while adding is closed");+ for (const bad of [null, "x", [], { ...plan, planCloudId: "../x" }, { ...plan, planCloudId: 7 }, { ...plan, canAdd: "yes" }, { ...plan, count: -1 }, { ...plan, count: 1.5 },+ { ...plan, max: 0 }, { ...plan, max: "10" }]) assert.equal(parseOrganizations(bad), null, JSON.stringify(bad));+});diff --git a/electron/cloud-rail.d.mts b/electron/cloud-rail.d.mtsindex 0d412f569d..bada2dfdc5 100644--- a/electron/cloud-rail.d.mts+++ b/electron/cloud-rail.d.mts@@ -31,8 +31,9 @@ export interface RailPlace {* sign-in may change it, if so. None for this computer, and for a Cloud still being made. */paint?: { swatch: import("./cloud-list.mjs").CloudSwatch | null; locked?: "member" | "signed-out" };}-/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings. */-export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean }+/** +'s choices here: buying a Cloud, pasting a server's pairing link, typing its address on this computer's Settings, and+ * a new organization on the Team plan this account pays for (absent from an older app's main). */+export interface RailAddChoices { cloud: boolean; link: boolean; address: boolean; organization?: boolean }/** `beside`: a place's page, which never reads the list, learns that the window's rail stands beside it. */export interface RailState { places: RailPlace[]; add: RailAddChoices; beside?: true }/** Buying another Cloud as a page sees it: what the sheet says, never the account, an address or the checkout page. */@@ -49,6 +50,9 @@ export type AddCloudView =offer: import("./cloud-home.mjs").CloudOffer | null;/** How many Clouds of their own they have: the next one is suggested as "Cloud {count + 1}". */count: number;+ /** For the account a Team plan with organizations is billed to: whether a new one may be added now (else why), how many+ * it has of how many. */+ organizations?: { canAdd: boolean; blocked?: import("./cloud-list.mjs").OrganizationBlock; count: number; max: number };home?: { name: string; color: import("./cloud-buy.mjs").CloudColor | null };adding?: {name: string; color: import("./cloud-list.mjs").CloudSwatch | null; tier: string | null; startedAt: number;diff --git a/electron/cloud-rail.mjs b/electron/cloud-rail.mjsindex e0748f37da..ef07de6c01 100644--- a/electron/cloud-rail.mjs+++ b/electron/cloud-rail.mjs@@ -88,6 +88,8 @@ export function addCloudView(state, offer) {canAdd: Boolean(clouds) && connected.addCloud?.canAdd !== false,...(connected.addCloud?.canAdd === false ? { blocked: connected.addCloud.blocked } : {}),offer: offer ?? null, count: Math.max(owned.length, has ? 1 : 0),+ ...(connected.organizations ? { organizations: { canAdd: connected.organizations.canAdd, count: connected.organizations.count, max: connected.organizations.max,+ ...(connected.organizations.blocked ? { blocked: connected.organizations.blocked } : {}) } } : {}),...(home ? { home: { name: home.name, color: swatchColor(home.color) } } : {}),...(adding ? { adding: { name: adding.name, color: adding.color, tier: adding.tier, startedAt: adding.startedAt, status,...(listed && cloudSetupProgress(listed) !== null ? { progress: cloudSetupProgress(listed) } : {}), ...(adding.link ? { link: true } : {}), ...(adding.done ? { done: true } : {}) } } : {}),@@ -135,8 +137,11 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, besreturn handler(event, ...args);}));const view = async () => addCloudView(account()?.state() ?? null, account() ? await account().offer().catch(() => null) : null);- ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places(), add: add.choices() }- : { places: [], add: { cloud: false, link: false, address: false }, ...(beside() ? { beside: true } : {}) })));+ // +'s choices: main's, and a new organization while this account runs a Team plan's organizations (unless the Admin has+ // turned adding them off).+ const choices = () => { const organizations = account()?.state().organizations; return { ...add.choices(), organization: Boolean(organizations) && organizations.blocked !== "off" }; };+ ipcMain.handle("workspaces:places", guard((event) => (lists(event) ? { places: places(), add: choices() }+ : { places: [], add: { cloud: false, link: false, address: false, organization: false }, ...(beside() ? { beside: true } : {}) })));listed("workspaces:open", (_event, id) => {const place = places().find(entry => entry.id === plain(id) && entry.opens);if (!place) throw new Error("That place isn't here any more.");@@ -156,6 +161,14 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, besconst result = await client.addCloud({ tier: plain(tier), interval: "month", name: cleanName, color: swatch });return result.outcome === "blocked" ? { outcome: "blocked", blocked: result.blocked } : { outcome: result.outcome };});+ handle("cloud-add:organization", async (_event, name, color) => {+ const client = account();+ if (!client) throw new Error("Sign in to MausBot Cloud first.");+ const cleanName = cleanCloudListName(plain(name)), swatch = CLOUD_SWATCHES.includes(color) ? color : null;+ if (!cleanName) throw new Error("Give the organization a name to continue.");+ const result = await client.addOrganization({ name: cleanName, color: swatch });+ return result.outcome === "blocked" ? { outcome: "blocked", blocked: result.blocked } : { outcome: result.outcome };+ });handle("cloud-add:reopen", () => account()?.reopenAdd() ?? false);handle("cloud-add:copy-link", () => {const url = account()?.addLink() ?? null;@@ -178,7 +191,7 @@ export function installCloudRail({ ipcMain, guard, trusted, lists = trusted, bessheetOpen: () => sheetOpen,/** The places or the sign-in changed: the page that shows the rail reads it again (a signal only, never the list). */changed() {- const key = JSON.stringify([places(), add.choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null]);+ const key = JSON.stringify([places(), choices(), account()?.state().adding ?? null, account()?.state().addCloud ?? null]);if (key === sent) return;sent = key;for (const target of targets()) if (target && !target.isDestroyed()) target.send("workspaces:changed");diff --git a/electron/cloud-rail.node-test.mjs b/electron/cloud-rail.node-test.mjsindex 71a3dc47b1..4e6277a25a 100644--- a/electron/cloud-rail.node-test.mjs+++ b/electron/cloud-rail.node-test.mjs@@ -103,8 +103,10 @@ test("a server of the person's own that signed in with their account: one savedfunction rail(over = {}) {const handlers = new Map(), opened = [], ran = [], sent = [];- const w = { trusted: true, lists: true, beside: true, state: session(), offer: { recommended: "pro", plans: [{ tier: "pro", amount: 4900 }] }, added: [] };+ const w = { trusted: true, lists: true, beside: true, state: session(), offer: { recommended: "pro", plans: [{ tier: "pro", amount: 4900 }] }, added: [], organized: [],+ organization: { outcome: "added", cloudId: "c-new" } };const account = { state: () => w.state, offer: async () => w.offer, addCloud: async (input) => { w.added.push(input); return { outcome: "opened", state: w.state }; },+ addOrganization: async (input) => { w.organized.push(input); return w.organization; },reopenAdd: async () => true, addLink: () => "https://test.checkout.dodopayments.com/x", addDone: () => { w.done = true; }, interest: async () => {} };const installed = installCloudRail({ ipcMain: { handle: (channel, handler) => handlers.set(channel, handler) }, guard: handler => handler, trusted: () => w.trusted,lists: () => w.lists, beside: () => w.beside,@@ -119,10 +121,10 @@ test("the rail's channels: the list only for the rail's own page, a circle onlyconst r = rail();assert.deepEqual((await r.call("workspaces:places")).places.map(place => place.id), ["home", "a", "acme", "vps"]);r.w.lists = false;- assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false }, beside: true },+ assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false, organization: false }, beside: true },"a place's page, this computer's and a Cloud's included, learns only that the rail stands beside it");r.w.beside = false;- assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false } });+ assert.deepEqual(await r.call("workspaces:places"), { places: [], add: { cloud: false, link: false, address: false, organization: false } });assert.throws(() => r.call("workspaces:open", "a"), /only available/);assert.throws(() => r.call("workspaces:add", "link"), /only available/);assert.equal(typeof await r.call("cloud-add:state"), "object", "+'s buying sheet still runs on a page main vouches for (this computer's own)");@@ -158,6 +160,28 @@ test("buying another Cloud from a page: the plan must be on sale, the name is chfor (const channel of ["cloud-add:state", "cloud-add:start", "cloud-add:open", "cloud-add:copy-link", "cloud-add:interest"]) assert.throws(() => r.call(channel), /only available/, channel);});+test("New organization on +: only while this account runs a Team plan's organizations and the Admin hasn't turned adding them off; the name is checked, the page gets only the outcome", async () => {+ const r = rail(), plan = { planCloudId: "5d4c3b2a-1f0e-4d9c-8b7a-6f5e4d3c2b1a", canAdd: true, count: 2, max: 10 };+ assert.equal((await r.call("workspaces:places")).add.organization, false, "no Team plan's organizations: no such choice");+ r.w.state = session({ organizations: plan });+ assert.deepEqual((await r.call("workspaces:places")).add, { cloud: true, link: true, address: false, organization: true });+ r.w.state = session({ organizations: { ...plan, canAdd: false, blocked: "limit" } });+ assert.equal((await r.call("workspaces:places")).add.organization, true, "at the plan's limit it is still there, to say so");+ r.w.state = session({ organizations: { ...plan, canAdd: false, blocked: "off" } });+ assert.equal((await r.call("workspaces:places")).add.organization, false, "turned off on the Admin: not offered");+ r.installed.changed(); r.w.state = session({ organizations: plan }); r.installed.changed();+ assert.deepEqual(r.sent.filter(item => item === "rail:workspaces:changed"), ["rail:workspaces:changed", "rail:workspaces:changed"], "the rail reads +'s choices again");+ await assert.rejects(r.call("cloud-add:organization", " ", "rose"), /Give the organization a name/);+ assert.deepEqual(await r.call("cloud-add:organization", " Client B ", "url(x)"), { outcome: "added" }, "only the outcome, never an id");+ assert.deepEqual(r.w.organized, [{ name: "Client B", color: null }], "the name folded; an unknown swatch is none");+ r.w.organization = { outcome: "blocked", blocked: "limit" };+ assert.deepEqual(await r.call("cloud-add:organization", "Client C", "rose"), { outcome: "blocked", blocked: "limit" });+ assert.deepEqual(addCloudView(session({ organizations: { ...plan, canAdd: false, blocked: "limit" } }), null).organizations, { canAdd: false, blocked: "limit", count: 2, max: 10 });+ assert.equal(addCloudView(session(), null).organizations, undefined);+ r.w.trusted = false;+ assert.throws(() => r.call("cloud-add:organization", "Client D", null), /only available/);+});+test("what the add sheet says: an older Admin is one Cloud for now, the Admin's cap says why, and a new Cloud's setup is followed", () => {assert.deepEqual(addCloudView({ status: "signed-out" }, null), { signedIn: false });const older = addCloudView(session({ clouds: undefined }), null);@@ -213,7 +237,7 @@ function preload(origin, { activation = false } = {}) {test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle, + and checkout open only from the person's click", async () => {const page = preload(HOME);assert.deepEqual(Object.keys(page.bridge.workspaces), ["state", "menu", "line", "places", "open", "add", "look", "color", "recolor", "onChanged"]);- assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet"]);+ assert.deepEqual(Object.keys(page.bridge.cloudAdd), ["state", "start", "reopen", "copyLink", "open", "interest", "sheet", "organization"]);await page.bridge.workspaces.places();await page.bridge.cloudAdd.state();await assert.rejects(page.bridge.workspaces.open("a"), /Choose a place/);@@ -222,6 +246,7 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await assert.rejects(page.bridge.cloudAdd.reopen(), /Reopen checkout/);await assert.rejects(page.bridge.cloudAdd.copyLink(), /Copy link/);await assert.rejects(page.bridge.cloudAdd.open(), /Open/);+ await assert.rejects(page.bridge.cloudAdd.organization("Client B", "rose"), /Create organization/);await assert.rejects(page.bridge.workspaces.color("rose"), /Choose a color/, "a page changes its place's colour only from the person's click");await assert.rejects(page.bridge.workspaces.recolor("vps", "rose"), /Choose a color/);await page.bridge.workspaces.look();@@ -232,7 +257,9 @@ test("a Cloud's page gets the rail and the add sheet's narrow bridges; a circle,await clicked.bridge.cloudAdd.start("pro", "Client B", null);await clicked.bridge.workspaces.color("rose");await clicked.bridge.workspaces.color(null);- assert.deepEqual(clicked.invoked, [["workspaces:open", "a"], ["workspaces:add", "link"], ["cloud-add:start", "pro", "Client B", null], ["workspaces:color", "rose"], ["workspaces:color", null]]);+ await clicked.bridge.cloudAdd.organization({ toString: () => "Client C" }, null);+ assert.deepEqual(clicked.invoked, [["workspaces:open", "a"], ["workspaces:add", "link"], ["cloud-add:start", "pro", "Client B", null], ["workspaces:color", "rose"], ["workspaces:color", null],+ ["cloud-add:organization", "Client C", null]]);assert.equal(page.bridge.cloudAccount, undefined, "never the account bridge");const local = preload(LOCAL);await local.bridge.workspaces.open("a");diff --git a/electron/preload.cjs b/electron/preload.cjsindex ae918543af..397602af2b 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -172,6 +172,8 @@ const bridge = {? ipcRenderer.invoke("cloud-add:open") : Promise.reject(new Error("Choose Open to open it.")),interest: () => ipcRenderer.invoke("cloud-add:interest"),sheet: (open) => ipcRenderer.invoke("cloud-add:sheet", open === true),+ organization: (name, color) => isLocalPage || navigator.userActivation?.isActive === true+ ? ipcRenderer.invoke("cloud-add:organization", String(name), color === null ? null : String(color)) : Promise.reject(new Error("Choose Create organization.")),},getCapabilities: () => ipcRenderer.invoke("desktop:capabilities"),onCapabilitiesChanged: (cb) => {diff --git a/src/components/PlaceAddSheet.tsx b/src/components/PlaceAddSheet.tsxindex a58ff62572..8272fc96ff 100644--- a/src/components/PlaceAddSheet.tsx+++ b/src/components/PlaceAddSheet.tsx@@ -1,7 +1,8 @@-// + at the end of the rail: one sheet, two choices. Buy a Cloud (the buying sheet: another Cloud right here, or the-// first one on this computer's own sheet) or add a server of the person's own through today's pairing link.+// + at the end of the rail: one sheet of choices. A new organization on the Team plan the person pays for (when they run+// one), buy a Cloud (the buying sheet: another Cloud right here, or the first one on this computer's own sheet), or add a+// server of the person's own through today's pairing link.import { useEffect, useRef, useState, type ReactNode } from "react";-import { Check, Cloud, Copy, Server, X } from "lucide-react";+import { Building2, Check, Cloud, Copy, Server, X } from "lucide-react";import type { RailAddChoices } from "../../electron/cloud-rail.mjs";import { track } from "@/lib/analytics";import { cn } from "@/lib/cn";@@ -9,6 +10,7 @@ import { useCopyFeedback } from "@/lib/copy-text";import { t } from "@/lib/i18n";import type { LocaleKey } from "@/locales";import { AddCloudFlow } from "./cloud-buy/AddCloudFlow";+import { NewOrganization } from "./cloud-buy/NewOrganization";import { BackLink, Heading } from "./cloud-buy/parts";/** The commands a server of the person's own runs to be reached from this app. */@@ -109,8 +111,9 @@ export function RailSheet({ wide = false, focusKey, onClose, children }: { wide?}export function PlaceAddSheet({ choices, connect = null, onClose }: { choices: RailAddChoices; connect?: { name: string } | null; onClose: () => void }) {- const server = choices.link || choices.address;- const [view, setView] = useState<"choose" | "cloud" | "server">(connect ? "server" : choices.cloud && server ? "choose" : choices.cloud ? "cloud" : "server");+ const server = choices.link || choices.address, organization = choices.organization === true;+ const several = [organization, choices.cloud, server].filter(Boolean).length > 1;+ const [view, setView] = useState<"choose" | "cloud" | "server" | "organization">(connect ? "server" : several ? "choose" : organization ? "organization" : choices.cloud ? "cloud" : "server");const [wide, setWide] = useState(false);const workspaces = window.ogb?.workspaces;const choose = (choice: "cloud" | "link" | "address") => {@@ -122,11 +125,13 @@ export function PlaceAddSheet({ choices, connect = null, onClose }: { choices: R{view === "choose" && <div data-place-add="choose" className="flex flex-col gap-5 px-[30px] pb-[26px] pt-7"><Heading title={t("rail.add")} /><div className="flex flex-col gap-3 sm:flex-row">- <Choice kind="cloud" icon={<Cloud size={19} />} title={t("rail.buy")} sub={t("rail.buySub")} onClick={() => setView("cloud")} />- <Choice kind="server" icon={<Server size={19} />} title={t("rail.own")} sub={t("rail.ownSub")} onClick={() => setView("server")} />+ {organization && <Choice kind="organization" icon={<Building2 size={19} />} title={t("rail.org")} sub={t("rail.orgSub")} onClick={() => setView("organization")} />}+ {choices.cloud && <Choice kind="cloud" icon={<Cloud size={19} />} title={t("rail.buy")} sub={t("rail.buySub")} onClick={() => setView("cloud")} />}+ {server && <Choice kind="server" icon={<Server size={19} />} title={t("rail.own")} sub={t("rail.ownSub")} onClick={() => setView("server")} />}</div></div>}- {view === "server" && <OwnServerSteps choices={choices} onBack={choices.cloud && !connect ? () => setView("choose") : null} onChoose={choose} connect={connect} />}- {view === "cloud" && <AddCloudFlow onClose={onClose} onFirstCloud={() => choose("cloud")} onWide={setWide} onBack={server ? () => setView("choose") : null} />}+ {view === "server" && <OwnServerSteps choices={choices} onBack={several && !connect ? () => setView("choose") : null} onChoose={choose} connect={connect} />}+ {view === "cloud" && <AddCloudFlow onClose={onClose} onFirstCloud={() => choose("cloud")} onWide={setWide} onBack={several ? () => setView("choose") : null} />}+ {view === "organization" && <NewOrganization onClose={onClose} onBack={several ? () => setView("choose") : null} />}</RailSheet>;}diff --git a/src/components/PlacesRail.test.ts b/src/components/PlacesRail.test.tsindex 73c919b56c..121ca78f8e 100644--- a/src/components/PlacesRail.test.ts+++ b/src/components/PlacesRail.test.ts@@ -25,8 +25,12 @@ let host: HTMLDivElement, root: Root | null = null;let rail: RailState;const workspaces = { state: vi.fn(async () => ({ local: false, name: "My Cloud" })), menu: vi.fn(async () => {}), places: vi.fn(async () => rail),open: vi.fn(async () => {}), add: vi.fn(async () => {}), onChanged: vi.fn(() => () => {}) };-const cloudAdd = { state: vi.fn(async () => ({ signedIn: true, hasCloud: true, supported: false, canAdd: false, offer: null, count: 1, home: { name: "My Cloud", color: null } })),- start: vi.fn(), reopen: vi.fn(), copyLink: vi.fn(), open: vi.fn(), interest: vi.fn(async () => {}), sheet: vi.fn(async () => {}) };+type Organizations = { canAdd: boolean; blocked?: "no_team_plan" | "limit" | "rate" | "off"; count: number; max: number };+let organizations: Organizations | undefined;+const cloudAdd = { state: vi.fn(async () => ({ signedIn: true, hasCloud: true, supported: false, canAdd: false, offer: null, count: 1, home: { name: "My Cloud", color: null },+ ...(organizations ? { organizations } : {}) })),+ start: vi.fn(), reopen: vi.fn(), copyLink: vi.fn(), open: vi.fn(), interest: vi.fn(async () => {}), sheet: vi.fn(async () => {}),+ organization: vi.fn(async (): Promise<{ outcome: "added" | "taken" | "unsupported" | "failed" } | { outcome: "blocked"; blocked: "no_team_plan" | "limit" | "rate" | "off" }> => ({ outcome: "added" })) };async function mount(element: ReturnType<typeof createElement>) {root = createRoot(host);await act(async () => { await refreshPlaces(); root!.render(element); });@@ -36,6 +40,7 @@ const click = async (element: Element | null | undefined) => { expect(element).tbeforeEach(() => {setLocale("en");rail = { places: PLACES, add: { cloud: true, link: true, address: false } };+ organizations = undefined;Object.assign(window, { ogb: { workspaces, cloudAdd } });vi.clearAllMocks();host = document.createElement("div"); document.body.append(host);@@ -116,6 +121,81 @@ it("+ offers buying a Cloud or adding the person's own server; the server's thexpect(document.querySelector("[data-place-add-sheet]")).toBeNull();});+const type = async (input: Element | null, value: string) => {+ expect(input).toBeTruthy();+ await act(async () => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);+ input!.dispatchEvent(new Event("input", { bubbles: true }));+ });+};+const createButton = () => [...document.querySelectorAll<HTMLButtonElement>('[data-place-add="organization"] button[type="submit"]')][0];++it("+ for the account a Team plan's organizations are billed to: New organization first; a name and a color add it at once, no checkout, and the sheet closes", async () => {+ rail = { places: PLACES, add: { cloud: true, link: true, address: false, organization: true } };+ organizations = { canAdd: true, count: 3, max: 10 };+ await mount(createElement(PlacesRail));+ await click(host.querySelector("[data-rail-add]"));+ const sheet = document.querySelector("[data-place-add-sheet]")!;+ expect([...sheet.querySelectorAll("[data-place-add-choice]")].map((choice) => choice.getAttribute("data-place-add-choice"))).toEqual(["organization", "cloud", "server"]);+ await click(sheet.querySelector('[data-place-add-choice="organization"]'));+ await act(async () => { await Promise.resolve(); });+ const form = document.querySelector('[data-place-add="organization"]')!;+ expect(form.querySelector("h2")?.textContent).toBe("New organization");+ expect(form.textContent).toContain("nothing to pay now");+ expect(form.querySelector("[data-org-count]")?.textContent).toBe("Organization 4 of 10");+ expect(createButton()?.disabled, "a name first").toBe(true);+ await type(form.querySelector("input"), " Client B ");+ expect(form.querySelector("[data-org-preview]")?.textContent).toBe("Client B");+ await click(form.querySelector("[data-swatch='violet']"));+ await click(createButton());+ await act(async () => { await Promise.resolve(); });+ expect(cloudAdd.organization.mock.calls).toEqual([["Client B", "violet"]]);+ expect(cloudAdd.start, "never a checkout").not.toHaveBeenCalled();+ expect(document.querySelector("[data-place-add-sheet]"), "added: the rail shows it being set up").toBeNull();+});++it("New organization says plainly why it can't be added: the plan has as many as it can, the name is taken, or it didn't work; nothing else is offered then", async () => {+ rail = { places: PLACES, add: { cloud: false, link: false, address: false, organization: true } };+ organizations = { canAdd: false, blocked: "limit", count: 10, max: 10 };+ await mount(createElement(PlacesRail));+ await click(host.querySelector("[data-rail-add]"));+ await act(async () => { await Promise.resolve(); });+ const form = document.querySelector('[data-place-add="organization"]')!;+ expect(form, "the only choice opens at once").toBeTruthy();+ expect(form.querySelector("[data-org-problem]")?.textContent).toBe("Your Team plan has as many organizations as it can have. Email us to add more.");+ await type(form.querySelector("input"), "Client K");+ expect(createButton()?.disabled).toBe(true);+ // Closed for a reason this app doesn't know: the neutral word, not the limit.+ await act(async () => root?.unmount()); root = null; document.body.innerHTML = ""; host = document.createElement("div"); document.body.append(host);+ organizations = { canAdd: false, count: 2, max: 10 };+ await mount(createElement(PlacesRail));+ await click(host.querySelector("[data-rail-add]"));+ await act(async () => { await Promise.resolve(); });+ expect(document.querySelector('[data-place-add="organization"] [data-org-problem]')?.textContent).toBe("New organizations aren't available right now.");+ await act(async () => root?.unmount()); root = null; document.body.innerHTML = ""; host = document.createElement("div"); document.body.append(host);+ organizations = { canAdd: true, count: 2, max: 10 };+ await mount(createElement(PlacesRail));+ await click(host.querySelector("[data-rail-add]"));+ await act(async () => { await Promise.resolve(); });+ const again = document.querySelector('[data-place-add="organization"]')!;+ await type(again.querySelector("input"), "Client A");+ for (const [answer, said] of [+ [{ outcome: "taken" }, "Another of your organizations has that name. Choose another."],+ [{ outcome: "blocked", blocked: "rate" }, "Too many organizations were added just now. Try again in a few minutes."],+ [{ outcome: "unsupported" }, "Nothing was added. Try again in a moment."],+ ] as const) {+ cloudAdd.organization.mockResolvedValueOnce(answer);+ await click(createButton());+ await act(async () => { await Promise.resolve(); });+ expect(again.querySelector("[data-org-problem]")?.textContent).toBe(said);+ }+ cloudAdd.organization.mockRejectedValueOnce(new Error("main went away"));+ await click(createButton());+ await act(async () => { await Promise.resolve(); });+ expect(again.querySelector("[data-org-problem]")?.textContent).toBe("Nothing was added. Try again in a moment.");+ expect(document.querySelector("[data-place-add-sheet]"), "the sheet stays open to try again").toBeTruthy();+});+it("Buy a Cloud, for someone whose Admin sells one Cloud per account: the calm word, never an error", async () => {await mount(createElement(PlacesRail));await click(host.querySelector("[data-rail-add]"));diff --git a/src/components/PlacesRail.tsx b/src/components/PlacesRail.tsxindex 3424296c09..ebc9049c25 100644--- a/src/components/PlacesRail.tsx+++ b/src/components/PlacesRail.tsx@@ -204,7 +204,7 @@ export function PlacesRail({ chrome = false }: { chrome?: boolean }) {const drag = draggable ? ({ WebkitAppRegion: "drag" } as CSSProperties) : undefined;const noDrag = draggable ? ({ WebkitAppRegion: "no-drag" } as CSSProperties) : undefined;const shown = shownPlaces(state.places);- const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair;+ const canPair = state.add.link || state.add.address, canAdd = state.add.cloud || canPair || state.add.organization === true;// The menu opens next to the circle or row it was asked from (measured now, while that row is there), within the rail.const openMenu = ({ place, from }: MenuAt) => {const nav = navRef.current;diff --git a/src/components/cloud-buy/NewOrganization.tsx b/src/components/cloud-buy/NewOrganization.tsxnew file mode 100644index 0000000000..362bd23940--- /dev/null+++ b/src/components/cloud-buy/NewOrganization.tsx@@ -0,0 +1,68 @@+// A new organization on the Team plan the person pays for, from the rail's +: a name and a color, then it is added at once+// (no checkout, nothing to pay) and its circle shows it being set up. Main asks the Admin; the page sees only what it says.+import { useEffect, useState } from "react";+import { Loader2 } from "lucide-react";+import type { CloudSwatch, OrganizationBlock } from "../../../electron/cloud-list.mjs";+import type { AddCloudView } from "../../../electron/cloud-rail.mjs";+import { track } from "@/lib/analytics";+import { cn } from "@/lib/cn";+import { CLOUD_LIST_NAME_LIMIT, DEFAULT_SWATCH, swatchFill } from "@/lib/cloud-extra";+import { t } from "@/lib/i18n";+import { placeInitials, refreshPlaces } from "@/lib/places";+import type { LocaleKey } from "@/locales";+import { SwatchRadios } from "../SwatchRadios";+import { BackLink, FIELD, Heading, PRIMARY_WIDE } from "./parts";++const BLOCKED: Record<OrganizationBlock, LocaleKey> = { no_team_plan: "rail.orgNoPlan", limit: "rail.orgLimit", rate: "rail.orgRate", off: "rail.orgOff" };+type OrganizationAnswer = { outcome: "added" | "taken" | "unsupported" | "failed" } | { outcome: "blocked"; blocked: OrganizationBlock };++/** What main's answer means for the sheet: added (it closes), or the sentence to show. */+export function organizationProblem(answer: OrganizationAnswer | null): LocaleKey | null {+ if (answer?.outcome === "added") return null;+ return answer?.outcome === "taken" ? "rail.orgTaken" : answer?.outcome === "blocked" ? BLOCKED[answer.blocked] : "rail.orgFailed";+}++export function NewOrganization({ onBack, onClose }: { onBack: (() => void) | null; onClose: () => void }) {+ const [view, setView] = useState<AddCloudView | null>(null);+ const [name, setName] = useState(""), [color, setColor] = useState<CloudSwatch>(DEFAULT_SWATCH);+ const [busy, setBusy] = useState(false), [problem, setProblem] = useState<LocaleKey | null>(null);+ useEffect(() => { void window.ogb?.cloudAdd?.state().then(setView, () => setView(null)); }, []);+ const facts = view?.signedIn ? view.organizations ?? null : null;+ // Closed for a reason this app doesn't know: the neutral word, never a limit it may not be at.+ const blocked = facts && !facts.canAdd ? facts.blocked ? BLOCKED[facts.blocked] : "rail.orgOff" : null;+ const shown = name.trim().replace(/\s+/g, " ");+ const create = async () => {+ if (!shown || busy || blocked) return;+ setBusy(true); setProblem(null);+ const answer = await window.ogb?.cloudAdd?.organization?.(shown, color).catch(() => null) ?? null;+ setBusy(false);+ const why = organizationProblem(answer);+ if (why) { setProblem(why); return; }+ track("rail_add", { step: "organization" });+ void refreshPlaces();+ onClose();+ };+ return <form data-place-add="organization" className="flex flex-col gap-4 px-[30px] pb-[26px] pt-7" onSubmit={(event) => { event.preventDefault(); void create(); }}>+ {onBack && <div><BackLink label={t("rail.back")} onClick={onBack} /></div>}+ <Heading title={t("rail.org")} sub={t("rail.orgLede")} />+ <label className="flex flex-col gap-1.5 text-[13px] font-medium text-ink">{t("rail.orgName")}+ <input data-autofocus value={name} maxLength={CLOUD_LIST_NAME_LIMIT} placeholder={t("rail.orgPlaceholder")} disabled={busy} onChange={(event) => setName(event.target.value)} className={FIELD} />+ </label>+ <div className="flex flex-col gap-1.5">+ <span aria-hidden="true" className="text-[13px] font-medium text-ink">{t("rail.orgColor")}</span>+ <SwatchRadios value={color} onChange={setColor} label={t("rail.orgColor")} disabled={busy} />+ </div>+ <div className="flex items-center gap-3 rounded-xl border border-hairline/70 bg-card/70 px-4 py-3">+ <span aria-hidden="true" className={cn("grid size-10 shrink-0 place-items-center rounded-full text-[14px] font-semibold", color === "slate" ? "bg-raised text-ink" : "text-white")}+ style={color === "slate" ? undefined : { background: swatchFill(color) }}>{placeInitials(shown || t("rail.org"))}</span>+ <span className="min-w-0">+ <span data-org-preview className="block truncate text-[14px] font-semibold text-ink">{shown || t("rail.org")}</span>+ {facts && <span data-org-count className="block text-[13px] text-ink-secondary">{t("rail.orgCount", { count: Math.min(facts.count + 1, facts.max), max: facts.max })}</span>}+ </span>+ </div>+ {(blocked || problem) && <p role="alert" data-org-problem className="text-[13px] leading-relaxed text-danger">{t(blocked ?? problem!)}</p>}+ <button type="submit" className={PRIMARY_WIDE} disabled={busy || !shown || Boolean(blocked)}>+ {busy && <Loader2 size={15} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}{t("rail.orgCreate")}+ </button>+ </form>;+}diff --git a/src/locales/de.json b/src/locales/de.jsonindex f1150ef28c..2066090e8b 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -2484,6 +2484,20 @@"rail.add": "Cloud oder eigenen Server hinzufügen","rail.buy": "Cloud kaufen","rail.buySub": "Eine neue Cloud mit eigenen Bots, Personen, Apps und Tarif, immer an.",+ "rail.org": "Neue Organisation",+ "rail.orgSub": "Eine weitere Cloud in deinem Team-Tarif, mit eigenen Personen und Bots. Nichts extra zu zahlen.",+ "rail.orgLede": "Sie bekommt eine eigene Cloud, Personen, Bots, Apps und Schlüssel. Sie gehört zu deinem Team-Tarif: kein neuer Tarif, jetzt nichts zu zahlen.",+ "rail.orgName": "Name",+ "rail.orgColor": "Farbe",+ "rail.orgPlaceholder": "Ein Kunde oder Team",+ "rail.orgCount": "Organisation {count} von {max}",+ "rail.orgCreate": "Organisation erstellen",+ "rail.orgTaken": "Eine andere deiner Organisationen heißt schon so. Wähle einen anderen Namen.",+ "rail.orgLimit": "Dein Team-Tarif hat schon so viele Organisationen, wie er haben kann. Schreib uns, um mehr hinzuzufügen.",+ "rail.orgRate": "Gerade wurden zu viele Organisationen hinzugefügt. Versuch es in ein paar Minuten noch einmal.",+ "rail.orgNoPlan": "Dein Team-Tarif läuft gerade nicht, deshalb kann keine Organisation hinzugefügt werden. Warum, steht bei der Abrechnung auf der Cloud-Seite.",+ "rail.orgOff": "Neue Organisationen sind gerade nicht verfügbar.",+ "rail.orgFailed": "Es wurde nichts hinzugefügt. Versuch es gleich noch einmal.","rail.own": "Eigenen Server hinzufügen","rail.ownSub": "Einen gemieteten im Netz, einen Mac mini zu Hause oder einen Computer in deinem Tailscale-Netzwerk.","rail.ownLede": "Installiere dort OpenMausBot, und diese App öffnet ihn wie eine Cloud. Seine Bots bleiben auf ihm.",diff --git a/src/locales/en.json b/src/locales/en.jsonindex 3b62706058..78ed55d409 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -282,6 +282,20 @@"rail.add": "Add a Cloud or your own server","rail.buy": "Buy a Cloud","rail.buySub": "A new Cloud with its own bots, people, apps and plan, always on.",+ "rail.org": "New organization",+ "rail.orgSub": "Another Cloud on your Team plan, with its own people and bots. Nothing more to pay.",+ "rail.orgLede": "It gets its own Cloud, people, bots, apps and keys. It's part of your Team plan: no new plan, nothing to pay now.",+ "rail.orgName": "Name",+ "rail.orgColor": "Color",+ "rail.orgPlaceholder": "A client or team",+ "rail.orgCount": "Organization {count} of {max}",+ "rail.orgCreate": "Create organization",+ "rail.orgTaken": "Another of your organizations has that name. Choose another.",+ "rail.orgLimit": "Your Team plan has as many organizations as it can have. Email us to add more.",+ "rail.orgRate": "Too many organizations were added just now. Try again in a few minutes.",+ "rail.orgNoPlan": "Your Team plan isn't running right now, so no organization can be added. Its billing on the Cloud page says why.",+ "rail.orgOff": "New organizations aren't available right now.",+ "rail.orgFailed": "Nothing was added. Try again in a moment.","rail.own": "Add your own server","rail.ownSub": "One you rent online, a Mac mini at home, or a computer on your Tailscale network.","rail.ownLede": "Install OpenMausBot there, and this app opens it like a Cloud. Its bots stay on it.",diff --git a/src/locales/es.json b/src/locales/es.jsonindex f34a813a60..20f8095b9d 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -250,6 +250,20 @@"rail.add": "Añadir una Cloud o tu propio servidor","rail.buy": "Comprar una Cloud","rail.buySub": "Una Cloud nueva con sus propios bots, personas, apps y plan, siempre encendida.",+ "rail.org": "Nueva organización",+ "rail.orgSub": "Otra Cloud en tu plan Team, con sus propias personas y bots. Nada más que pagar.",+ "rail.orgLede": "Tiene su propia Cloud, personas, bots, apps y claves. Forma parte de tu plan Team: sin plan nuevo y nada que pagar ahora.",+ "rail.orgName": "Nombre",+ "rail.orgColor": "Color",+ "rail.orgPlaceholder": "Un cliente o equipo",+ "rail.orgCount": "Organización {count} de {max}",+ "rail.orgCreate": "Crear organización",+ "rail.orgTaken": "Otra de tus organizaciones ya tiene ese nombre. Elige otro.",+ "rail.orgLimit": "Tu plan Team ya tiene todas las organizaciones que puede tener. Escríbenos para añadir más.",+ "rail.orgRate": "Se añadieron demasiadas organizaciones hace un momento. Vuelve a intentarlo en unos minutos.",+ "rail.orgNoPlan": "Tu plan Team no está activo ahora mismo, así que no se puede añadir ninguna organización. La facturación en la página de Cloud explica por qué.",+ "rail.orgOff": "Las organizaciones nuevas no están disponibles ahora mismo.",+ "rail.orgFailed": "No se añadió nada. Vuelve a intentarlo en un momento.","rail.own": "Añadir tu propio servidor","rail.ownSub": "Uno que alquilas en internet, un Mac mini en casa o un equipo de tu red de Tailscale.","rail.ownLede": "Instala OpenMausBot allí y esta app lo abrirá como una Cloud. Sus bots se quedan en él.",diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 53b2eaac68..3d2f50a3a8 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -2466,6 +2466,20 @@"rail.add": "Ajouter un Cloud ou votre propre serveur","rail.buy": "Acheter un Cloud","rail.buySub": "Un nouveau Cloud avec ses propres bots, personnes, apps et forfait, toujours allumé.",+ "rail.org": "Nouvelle organisation",+ "rail.orgSub": "Un autre Cloud dans votre forfait Team, avec ses propres personnes et bots. Rien de plus à payer.",+ "rail.orgLede": "Elle a son propre Cloud, ses personnes, bots, apps et clés. Elle fait partie de votre forfait Team : pas de nouveau forfait, rien à payer maintenant.",+ "rail.orgName": "Nom",+ "rail.orgColor": "Couleur",+ "rail.orgPlaceholder": "Un client ou une équipe",+ "rail.orgCount": "Organisation {count} sur {max}",+ "rail.orgCreate": "Créer l'organisation",+ "rail.orgTaken": "Une autre de vos organisations porte déjà ce nom. Choisissez-en un autre.",+ "rail.orgLimit": "Votre forfait Team a déjà autant d'organisations que possible. Écrivez-nous pour en ajouter.",+ "rail.orgRate": "Trop d'organisations viennent d'être ajoutées. Réessayez dans quelques minutes.",+ "rail.orgNoPlan": "Votre forfait Team n'est pas actif en ce moment, donc aucune organisation ne peut être ajoutée. La facturation sur la page Cloud indique pourquoi.",+ "rail.orgOff": "Les nouvelles organisations ne sont pas disponibles pour le moment.",+ "rail.orgFailed": "Rien n'a été ajouté. Réessayez dans un instant.","rail.own": "Ajouter votre propre serveur","rail.ownSub": "Un serveur loué en ligne, un Mac mini à la maison ou un ordinateur de votre réseau Tailscale.","rail.ownLede": "Installez-y OpenMausBot, et cette app l'ouvre comme un Cloud. Ses bots restent dessus.",diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex c1204f51d8..e3e343ee0d 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -2466,6 +2466,20 @@"rail.add": "Cloud या अपना सर्वर जोड़ें","rail.buy": "Cloud खरीदें","rail.buySub": "अपने बॉट, लोग, ऐप्स और प्लान वाला नया Cloud, हमेशा चालू।",+ "rail.org": "नया संगठन",+ "rail.orgSub": "आपके Team प्लान पर एक और Cloud, अपने लोगों और बॉट के साथ। कुछ और नहीं देना होगा।",+ "rail.orgLede": "इसे अपना Cloud, लोग, बॉट, ऐप्स और कुंजियाँ मिलती हैं। यह आपके Team प्लान का हिस्सा है: कोई नया प्लान नहीं, अभी कुछ नहीं देना।",+ "rail.orgName": "नाम",+ "rail.orgColor": "रंग",+ "rail.orgPlaceholder": "कोई क्लाइंट या टीम",+ "rail.orgCount": "संगठन {count}/{max}",+ "rail.orgCreate": "संगठन बनाएँ",+ "rail.orgTaken": "आपके किसी दूसरे संगठन का यही नाम है। कोई दूसरा नाम चुनें।",+ "rail.orgLimit": "आपके Team प्लान में जितने संगठन हो सकते हैं, उतने हो चुके हैं। और जोड़ने के लिए हमें ईमेल करें।",+ "rail.orgRate": "अभी बहुत सारे संगठन जोड़े गए हैं। कुछ मिनट बाद फिर कोशिश करें।",+ "rail.orgNoPlan": "आपका Team प्लान अभी चालू नहीं है, इसलिए कोई संगठन नहीं जोड़ा जा सकता। Cloud पेज पर बिलिंग में इसकी वजह दिखेगी।",+ "rail.orgOff": "नए संगठन अभी उपलब्ध नहीं हैं।",+ "rail.orgFailed": "कुछ नहीं जोड़ा गया। थोड़ी देर में फिर कोशिश करें।","rail.own": "अपना सर्वर जोड़ें","rail.ownSub": "ऑनलाइन किराए का, घर पर रखा Mac mini, या आपके Tailscale नेटवर्क का कोई कंप्यूटर।","rail.ownLede": "वहाँ OpenMausBot इंस्टॉल करें, और यह ऐप उसे Cloud की तरह खोलेगा। उसके बॉट उसी पर रहते हैं।",diff --git a/src/locales/it.json b/src/locales/it.jsonindex bbb6494d17..05283b4a06 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -254,6 +254,20 @@"rail.add": "Aggiungi un Cloud o il tuo server","rail.buy": "Compra un Cloud","rail.buySub": "Un nuovo Cloud con i suoi bot, le sue persone, le sue app e il suo piano, sempre acceso.",+ "rail.org": "Nuova organizzazione",+ "rail.orgSub": "Un altro Cloud nel tuo piano Team, con le sue persone e i suoi bot. Niente di più da pagare.",+ "rail.orgLede": "Ha il suo Cloud, le sue persone, i suoi bot, le sue app e le sue chiavi. Fa parte del tuo piano Team: nessun nuovo piano, niente da pagare ora.",+ "rail.orgName": "Nome",+ "rail.orgColor": "Colore",+ "rail.orgPlaceholder": "Un cliente o un team",+ "rail.orgCount": "Organizzazione {count} di {max}",+ "rail.orgCreate": "Crea organizzazione",+ "rail.orgTaken": "Un'altra delle tue organizzazioni ha già questo nome. Scegline un altro.",+ "rail.orgLimit": "Il tuo piano Team ha già tutte le organizzazioni che può avere. Scrivici per aggiungerne altre.",+ "rail.orgRate": "Sono state aggiunte troppe organizzazioni poco fa. Riprova tra qualche minuto.",+ "rail.orgNoPlan": "Il tuo piano Team non è attivo in questo momento, quindi non si possono aggiungere organizzazioni. La fatturazione nella pagina del Cloud spiega perché.",+ "rail.orgOff": "Le nuove organizzazioni non sono disponibili in questo momento.",+ "rail.orgFailed": "Non è stato aggiunto niente. Riprova tra un attimo.","rail.own": "Aggiungi il tuo server","rail.ownSub": "Uno che affitti online, un Mac mini a casa o un computer della tua rete Tailscale.","rail.ownLede": "Installa lì OpenMausBot e questa app lo apre come un Cloud. I suoi bot restano lì.",diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex ce6c59dbde..79b2894dea 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -260,6 +260,20 @@"rail.add": "Cloudまたは自分のサーバーを追加","rail.buy": "Cloudを購入","rail.buySub": "専用のボット、メンバー、アプリ、プランを持つ新しいCloud。常に稼働します。",+ "rail.org": "新しい組織",+ "rail.orgSub": "Teamプランに追加するもう1つのCloud。専用のメンバーとボットを持てます。追加料金はかかりません。",+ "rail.orgLede": "専用のCloud、メンバー、ボット、アプリ、キーを持てます。今のTeamプランに含まれるので、新しいプランも今の支払いも不要です。",+ "rail.orgName": "名前",+ "rail.orgColor": "色",+ "rail.orgPlaceholder": "クライアント名やチーム名",+ "rail.orgCount": "組織 {count}/{max}",+ "rail.orgCreate": "組織を作成",+ "rail.orgTaken": "ほかの組織ですでに使われている名前です。別の名前にしてください。",+ "rail.orgLimit": "このTeamプランでは、これ以上組織を追加できません。追加したい場合はメールでご連絡ください。",+ "rail.orgRate": "短時間に多くの組織が追加されました。数分後にもう一度お試しください。",+ "rail.orgNoPlan": "Teamプランが現在有効ではないため、組織を追加できません。理由はCloudページの請求情報で確認できます。",+ "rail.orgOff": "新しい組織は現在ご利用いただけません。",+ "rail.orgFailed": "何も追加されませんでした。しばらくしてからもう一度お試しください。","rail.own": "自分のサーバーを追加","rail.ownSub": "オンラインで借りたもの、自宅のMac mini、またはTailscaleネットワーク上のコンピューター。","rail.ownLede": "そこにOpenMausBotをインストールすると、このアプリでCloudのように開けます。ボットはそのサーバーに置かれたままです。",diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex a796148a41..6413ff60b4 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -260,6 +260,20 @@"rail.add": "Dodaj Chmurę lub własny serwer","rail.buy": "Kup Chmurę","rail.buySub": "Nowa Chmura z własnymi botami, osobami, aplikacjami i planem, zawsze włączona.",+ "rail.org": "Nowa organizacja",+ "rail.orgSub": "Kolejna Chmura w Twoim planie Team, z własnymi osobami i botami. Nic więcej do zapłaty.",+ "rail.orgLede": "Dostaje własną Chmurę, osoby, boty, aplikacje i klucze. Jest częścią Twojego planu Team: bez nowego planu, nic do zapłaty teraz.",+ "rail.orgName": "Nazwa",+ "rail.orgColor": "Kolor",+ "rail.orgPlaceholder": "Klient lub zespół",+ "rail.orgCount": "Organizacja {count} z {max}",+ "rail.orgCreate": "Utwórz organizację",+ "rail.orgTaken": "Inna z Twoich organizacji ma już tę nazwę. Wybierz inną.",+ "rail.orgLimit": "Twój plan Team ma już tyle organizacji, ile może mieć. Napisz do nas, aby dodać więcej.",+ "rail.orgRate": "Przed chwilą dodano zbyt wiele organizacji. Spróbuj ponownie za kilka minut.",+ "rail.orgNoPlan": "Twój plan Team nie jest teraz aktywny, więc nie można dodać organizacji. Powód znajdziesz w rozliczeniach na stronie Chmury.",+ "rail.orgOff": "Nowe organizacje są teraz niedostępne.",+ "rail.orgFailed": "Nic nie zostało dodane. Spróbuj ponownie za chwilę.","rail.own": "Dodaj własny serwer","rail.ownSub": "Wynajęty w sieci, Mac mini w domu albo komputer w twojej sieci Tailscale.","rail.ownLede": "Zainstaluj tam OpenMausBot, a ta aplikacja otworzy go jak Chmurę. Jego boty zostają na nim.",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex 334143f21a..eb7ce02700 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -250,6 +250,20 @@"rail.add": "Adicionar um Cloud ou seu próprio servidor","rail.buy": "Comprar um Cloud","rail.buySub": "Um novo Cloud com seus próprios bots, pessoas, apps e plano, sempre ligado.",+ "rail.org": "Nova organização",+ "rail.orgSub": "Outro Cloud no seu plano Team, com pessoas e bots próprios. Nada a mais para pagar.",+ "rail.orgLede": "Ela tem o próprio Cloud, pessoas, bots, apps e chaves. Faz parte do seu plano Team: nenhum plano novo, nada para pagar agora.",+ "rail.orgName": "Nome",+ "rail.orgColor": "Cor",+ "rail.orgPlaceholder": "Um cliente ou equipe",+ "rail.orgCount": "Organização {count} de {max}",+ "rail.orgCreate": "Criar organização",+ "rail.orgTaken": "Outra das suas organizações já tem esse nome. Escolha outro.",+ "rail.orgLimit": "Seu plano Team já tem todas as organizações que pode ter. Mande um e-mail para nós para adicionar mais.",+ "rail.orgRate": "Muitas organizações foram adicionadas agora há pouco. Tente de novo em alguns minutos.",+ "rail.orgNoPlan": "Seu plano Team não está ativo agora, então nenhuma organização pode ser adicionada. O faturamento na página do Cloud mostra o motivo.",+ "rail.orgOff": "Novas organizações não estão disponíveis agora.",+ "rail.orgFailed": "Nada foi adicionado. Tente de novo em instantes.","rail.own": "Adicionar seu próprio servidor","rail.ownSub": "Um que você aluga online, um Mac mini em casa ou um computador na sua rede Tailscale.","rail.ownLede": "Instale o OpenMausBot lá, e este app o abre como um Cloud. Os bots dele ficam nele.",diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex c2fb1f1f50..642929c469 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -260,6 +260,20 @@"rail.add": "Добавить Cloud или свой сервер","rail.buy": "Купить Cloud","rail.buySub": "Новый Cloud со своими ботами, людьми, приложениями и тарифом, всегда включён.",+ "rail.org": "Новая организация",+ "rail.orgSub": "Ещё один Cloud в вашем тарифе Team, со своими людьми и ботами. Ничего доплачивать не нужно.",+ "rail.orgLede": "У неё свой Cloud, люди, боты, приложения и ключи. Она входит в ваш тариф Team: без нового тарифа и без оплаты сейчас.",+ "rail.orgName": "Название",+ "rail.orgColor": "Цвет",+ "rail.orgPlaceholder": "Клиент или команда",+ "rail.orgCount": "Организация {count} из {max}",+ "rail.orgCreate": "Создать организацию",+ "rail.orgTaken": "Это название уже у другой вашей организации. Выберите другое.",+ "rail.orgLimit": "В вашем тарифе Team уже столько организаций, сколько возможно. Напишите нам, чтобы добавить больше.",+ "rail.orgRate": "Только что было добавлено слишком много организаций. Попробуйте снова через несколько минут.",+ "rail.orgNoPlan": "Ваш тариф Team сейчас не действует, поэтому добавить организацию нельзя. Причину покажет раздел оплаты на странице Cloud.",+ "rail.orgOff": "Новые организации сейчас недоступны.",+ "rail.orgFailed": "Ничего не добавлено. Попробуйте снова через минуту.","rail.own": "Добавить свой сервер","rail.ownSub": "Арендованный в сети, Mac mini дома или компьютер в вашей сети Tailscale.","rail.ownLede": "Установите туда OpenMausBot, и это приложение откроет его как Cloud. Его боты останутся на нём.",diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex f4cf00477e..77f2c8f3d7 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -4937,6 +4937,20 @@"rail.add": "Cloud veya kendi sunucunuzu ekleyin","rail.buy": "Cloud satın al","rail.buySub": "Kendi botları, kişileri, uygulamaları ve planı olan yeni bir Cloud, her zaman açık.",+ "rail.org": "Yeni organizasyon",+ "rail.orgSub": "Team planınızda kendi kişileri ve botları olan bir Cloud daha. Ek ödeme yok.",+ "rail.orgLede": "Kendi Cloud'u, kişileri, botları, uygulamaları ve anahtarları olur. Team planınızın bir parçasıdır: yeni plan yok, şimdi ödenecek bir şey yok.",+ "rail.orgName": "Ad",+ "rail.orgColor": "Renk",+ "rail.orgPlaceholder": "Bir müşteri veya ekip",+ "rail.orgCount": "Organizasyon {count}/{max}",+ "rail.orgCreate": "Organizasyon oluştur",+ "rail.orgTaken": "Organizasyonlarınızdan biri zaten bu adı kullanıyor. Başka bir ad seçin.",+ "rail.orgLimit": "Team planınız olabilecek en fazla organizasyona sahip. Daha fazlası için bize e-posta gönderin.",+ "rail.orgRate": "Az önce çok fazla organizasyon eklendi. Birkaç dakika sonra yeniden deneyin.",+ "rail.orgNoPlan": "Team planınız şu anda çalışmıyor, bu yüzden organizasyon eklenemiyor. Nedenini Cloud sayfasındaki faturalandırma bölümünde görebilirsiniz.",+ "rail.orgOff": "Yeni organizasyonlar şu anda kullanılamıyor.",+ "rail.orgFailed": "Hiçbir şey eklenmedi. Biraz sonra yeniden deneyin.","rail.own": "Kendi sunucunuzu ekleyin","rail.ownSub": "Çevrimiçi kiraladığınız biri, evdeki bir Mac mini ya da Tailscale ağınızdaki bir bilgisayar.","rail.ownLede": "Oraya OpenMausBot'u kurun; bu uygulama onu bir Cloud gibi açar. Botları onun üzerinde kalır.",diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex 889b7bf293..b8c9cd940d 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -2911,6 +2911,20 @@"rail.add": "Додати Cloud або власний сервер","rail.buy": "Купити Cloud","rail.buySub": "Новий Cloud із власними ботами, людьми, застосунками й планом, завжди увімкнений.",+ "rail.org": "Нова організація",+ "rail.orgSub": "Ще один Cloud у вашому плані Team, зі своїми людьми й ботами. Нічого доплачувати не треба.",+ "rail.orgLede": "Вона має власний Cloud, людей, ботів, застосунки й ключі. Вона входить у ваш план Team: без нового плану й без оплати зараз.",+ "rail.orgName": "Назва",+ "rail.orgColor": "Колір",+ "rail.orgPlaceholder": "Клієнт або команда",+ "rail.orgCount": "Організація {count} з {max}",+ "rail.orgCreate": "Створити організацію",+ "rail.orgTaken": "Ця назва вже є в іншої вашої організації. Виберіть іншу.",+ "rail.orgLimit": "У вашому плані Team уже стільки організацій, скільки можливо. Напишіть нам, щоб додати більше.",+ "rail.orgRate": "Щойно додано забагато організацій. Спробуйте знову за кілька хвилин.",+ "rail.orgNoPlan": "Ваш план Team зараз не діє, тож додати організацію не можна. Причину покаже розділ оплати на сторінці Cloud.",+ "rail.orgOff": "Нові організації зараз недоступні.",+ "rail.orgFailed": "Нічого не додано. Спробуйте знову за хвилину.","rail.own": "Додати власний сервер","rail.ownSub": "Орендований в інтернеті, Mac mini вдома або комп'ютер у вашій мережі Tailscale.","rail.ownLede": "Установіть туди OpenMausBot, і цей застосунок відкриватиме його як Cloud. Його боти залишаться на ньому.",diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex 518c35cf96..077a9eef43 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -4937,6 +4937,20 @@"rail.add": "Thêm Cloud hoặc máy chủ của riêng bạn","rail.buy": "Mua Cloud","rail.buySub": "Một Cloud mới với bot, thành viên, ứng dụng và gói riêng, luôn bật.",+ "rail.org": "Tổ chức mới",+ "rail.orgSub": "Thêm một Cloud trong gói Team của bạn, với thành viên và bot riêng. Không phải trả thêm.",+ "rail.orgLede": "Tổ chức có Cloud, thành viên, bot, ứng dụng và khóa riêng. Nó thuộc gói Team của bạn: không cần gói mới, không phải trả gì bây giờ.",+ "rail.orgName": "Tên",+ "rail.orgColor": "Màu",+ "rail.orgPlaceholder": "Một khách hàng hoặc nhóm",+ "rail.orgCount": "Tổ chức {count}/{max}",+ "rail.orgCreate": "Tạo tổ chức",+ "rail.orgTaken": "Một tổ chức khác của bạn đã dùng tên này. Hãy chọn tên khác.",+ "rail.orgLimit": "Gói Team của bạn đã có số tổ chức tối đa. Hãy gửi email cho chúng tôi để thêm.",+ "rail.orgRate": "Vừa có quá nhiều tổ chức được thêm. Hãy thử lại sau vài phút.",+ "rail.orgNoPlan": "Gói Team của bạn hiện không hoạt động nên không thể thêm tổ chức. Phần thanh toán trên trang Cloud cho biết lý do.",+ "rail.orgOff": "Hiện chưa thể tạo tổ chức mới.",+ "rail.orgFailed": "Chưa thêm được gì. Hãy thử lại sau giây lát.","rail.own": "Thêm máy chủ của riêng bạn","rail.ownSub": "Một máy chủ bạn thuê trực tuyến, một Mac mini ở nhà hoặc một máy tính trong mạng Tailscale của bạn.","rail.ownLede": "Cài OpenMausBot ở đó, và ứng dụng này sẽ mở nó như một Cloud. Bot của nó vẫn ở trên đó.",diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 013c0cb1ce..098e4193ca 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -4321,6 +4321,20 @@"rail.add": "新增 Cloud 或你自己的伺服器","rail.buy": "購買 Cloud","rail.buySub": "全新的 Cloud,擁有自己的機器人、成員、應用程式和方案,隨時在線。",+ "rail.org": "新增組織",+ "rail.orgSub": "你的 Team 方案裡的另一個 Cloud,擁有自己的成員和機器人。不必額外付費。",+ "rail.orgLede": "它有自己的 Cloud、成員、機器人、應用程式和金鑰。它包含在你的 Team 方案裡:不需要新方案,現在也不必付費。",+ "rail.orgName": "名稱",+ "rail.orgColor": "顏色",+ "rail.orgPlaceholder": "客戶或團隊名稱",+ "rail.orgCount": "組織 {count}/{max}",+ "rail.orgCreate": "建立組織",+ "rail.orgTaken": "你的另一個組織已經使用這個名稱。請換一個。",+ "rail.orgLimit": "你的 Team 方案已達組織數量上限。如需更多,請寄電子郵件給我們。",+ "rail.orgRate": "剛剛新增的組織太多了。請幾分鐘後再試。",+ "rail.orgNoPlan": "你的 Team 方案目前未生效,所以無法新增組織。Cloud 頁面上的帳單資訊會說明原因。",+ "rail.orgOff": "目前無法新增組織。",+ "rail.orgFailed": "沒有新增任何內容。請稍後再試。","rail.own": "新增你自己的伺服器","rail.ownSub": "線上租用的伺服器、家裡的 Mac mini,或你 Tailscale 網路中的電腦。","rail.ownLede": "在那裡安裝 OpenMausBot,這個 App 就能像 Cloud 一樣開啟它。它的機器人會留在上面。",diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex 110661ad7c..475cec19cd 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -3309,6 +3309,20 @@"rail.add": "添加 Cloud 或你自己的服务器","rail.buy": "购买 Cloud","rail.buySub": "全新的 Cloud,拥有自己的机器人、成员、应用和方案,始终在线。",+ "rail.org": "新建组织",+ "rail.orgSub": "你的 Team 方案里的又一个 Cloud,拥有自己的成员和机器人。无需额外付费。",+ "rail.orgLede": "它有自己的 Cloud、成员、机器人、应用和密钥。它包含在你的 Team 方案里:无需新方案,现在也无需付费。",+ "rail.orgName": "名称",+ "rail.orgColor": "颜色",+ "rail.orgPlaceholder": "客户或团队名称",+ "rail.orgCount": "组织 {count}/{max}",+ "rail.orgCreate": "创建组织",+ "rail.orgTaken": "你的另一个组织已经用了这个名称。请换一个。",+ "rail.orgLimit": "你的 Team 方案已达到组织数量上限。如需更多,请给我们发邮件。",+ "rail.orgRate": "刚刚添加的组织太多了。请几分钟后再试。",+ "rail.orgNoPlan": "你的 Team 方案目前未生效,所以无法添加组织。Cloud 页面上的账单信息会说明原因。",+ "rail.orgOff": "目前无法新建组织。",+ "rail.orgFailed": "没有添加任何内容。请稍后再试。","rail.own": "添加你自己的服务器","rail.ownSub": "在线租用的服务器、家里的 Mac mini,或你 Tailscale 网络中的电脑。","rail.ownLede": "在那里安装 OpenMausBot,这个应用就能像 Cloud 一样打开它。它的机器人会留在上面。",diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex ab783ba09c..98739516d6 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -184,6 +184,9 @@ const __APP_VERSION__: string;interest(): Promise<void>;/** The sheet is open on this page (main then says "ready" here, not with a notification). */sheet(open: boolean): Promise<void>;+ /** A new organization on the Team plan this account pays for, of this name and swatch: no checkout; only from the person's click. */+ organization?(name: string, color: import("../../electron/cloud-list.mjs").CloudSwatch | null): Promise<{ outcome: "added" | "taken" | "unsupported" | "failed" }+ | { outcome: "blocked"; blocked: import("../../electron/cloud-list.mjs").OrganizationBlock }>;};/** Saved servers and the active one (desktop Server menu). Present on* the local server's UI; a remote server's page sees a reduced bridge. */