Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Let each person on a self-hosted server choose the name they go by (#5911)
Azad Jagtapaf968ee7c3f0
diff --git a/server/host/person-names.test.ts b/server/host/person-names.test.tsnew file mode 100644index 0000000000..033baa26a8--- /dev/null+++ b/server/host/person-names.test.ts@@ -0,0 +1,66 @@+import { mkdtempSync, readFileSync, statSync, writeFileSync } 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 { personOf } from "../replies.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { cleanDisplayName, createPersonNames } from "./person-names.ts";++const dirs: string[] = [];+afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });+const dataDir = () => { const dir = mkdtempSync(join(tmpdir(), "omb-person-names-")); dirs.push(dir); return dir; };++describe("a name a person chooses on a self-hosted server", () => {+ it("is trimmed, 1 to 60 characters, and never holds a control character", () => {+ expect(cleanDisplayName(" Grace Hopper ")).toBe("Grace Hopper");+ expect(cleanDisplayName(" ")).toBeNull();+ expect(cleanDisplayName("x".repeat(60))).toBe("x".repeat(60));+ expect(cleanDisplayName("x".repeat(61))).toBeNull();+ expect(cleanDisplayName("😀".repeat(60)), "counted in characters, not UTF-16 units").toBe("😀".repeat(60));+ expect(cleanDisplayName("Grace\nHopper")).toBeNull();+ expect(cleanDisplayName("Grace\u0007")).toBeNull();+ expect(cleanDisplayName("José Ñúñez")).toBe("José Ñúñez");+ });++ it("belongs to the address on every device signed in with it, or to the one device without one", () => {+ const names = createPersonNames(dataDir());+ names.save({ id: "laptop", email: "[email protected]" }, "Grace");+ expect(names.of({ id: "phone", email: "[email protected]" })).toBe("Grace");+ names.save({ id: "tablet" }, "Ada");+ expect(names.of({ id: "tablet" })).toBe("Ada");+ expect(names.of({ id: "other-device" })).toBeNull();+ expect(names.byKey(personKey({ id: "tablet" }))).toBe("Ada");+ expect(names.byKey(undefined)).toBeNull();+ names.save({ id: "tablet" }, null);+ expect(names.of({ id: "tablet" })).toBeNull();+ });++ it("is kept in a file only its owner can read, and read back on the next start", () => {+ const dir = dataDir();+ createPersonNames(dir).save({ id: "s1", email: "[email protected]" }, "Grace");+ const file = join(dir, "person-names.json");+ if (process.platform !== "win32") expect(statSync(file).mode & 0o777).toBe(0o600);+ expect(JSON.stringify(JSON.parse(readFileSync(file, "utf8")))).not.toContain("[email protected]");+ expect(createPersonNames(dir).of({ id: "s2", email: "[email protected]" })).toBe("Grace");+ });++ it("drops a name in the file that would not be accepted now", () => {+ const dir = dataDir();+ writeFileSync(join(dir, "person-names.json"), JSON.stringify({ v: 1, names: { [personKey({ id: "a" })]: "Bad\u0000", [personKey({ id: "b" })]: 7 } }));+ const names = createPersonNames(dir);+ expect(names.of({ id: "a" })).toBeNull();+ expect(names.of({ id: "b" })).toBeNull();+ });++ it("names each line in a turn by its sender's chosen name, and every other line by the profile's", () => {+ const names = createPersonNames(dataDir());+ expect(names.lineNames("Ada Lovelace")).toBe("Ada Lovelace");+ names.save({ id: "s1", email: "[email protected]" }, "Grace");+ const lineNames = names.lineNames("Ada Lovelace");+ expect(personOf(lineNames, { sender: { name: "Grace", id: personKey({ id: "", email: "[email protected]" }) } })).toBe("Grace");+ expect(personOf(lineNames, { sender: { name: "Chrome on Mac", id: personKey({ id: "s9" }) } })).toBe("Ada Lovelace");+ expect(personOf(lineNames, {})).toBe("Ada Lovelace");+ });+});diff --git a/server/host/person-names.ts b/server/host/person-names.tsnew file mode 100644index 0000000000..2bf9825868--- /dev/null+++ b/server/host/person-names.ts@@ -0,0 +1,54 @@+// What each person signed in to a self-hosted server chose to be called, in <data>/person-names.json by their person key:+// their sign-in address, or the device's own session when it has none. The server's profile stays the owner's name.+import { readFileSync } from "node:fs";+import { join } from "node:path";++import { writeFileAtomic } from "../atomic.ts";+import { personKey } from "../person-key.ts";+import type { PersonName } from "../replies.ts";+import type { SessionRecord } from "../sessions.ts";++export const DISPLAY_NAME_MAX = 60;++type Person = Pick<SessionRecord, "id" | "email">;++/** The name as kept, or null when it is empty, longer than DISPLAY_NAME_MAX characters, or holds a control character. */+export function cleanDisplayName(raw: string): string | null {+ const name = raw.trim();+ const length = [...name].length;+ return length >= 1 && length <= DISPLAY_NAME_MAX && !/\p{Cc}/u.test(name) ? name : null;+}++export interface PersonNames {+ of(session: Person): string | null;+ /** By the key on a message's sender. */+ byKey(person: string | undefined): string | null;+ /** null clears the name. */+ save(session: Person, name: string | null): void;+ /** What people's lines are called in a turn: each chosen name by its line's sender, otherwise `fallback`. */+ lineNames(fallback: string): PersonName;+}++export function createPersonNames(dataDir: string): PersonNames {+ const file = join(dataDir, "person-names.json");+ const names = new Map<string, string>();+ try {+ const raw = JSON.parse(readFileSync(file, "utf8")) as { names?: Record<string, unknown> };+ for (const [person, name] of Object.entries(raw.names ?? {})) {+ const clean = typeof name === "string" ? cleanDisplayName(name) : null;+ if (clean) names.set(person, clean);+ }+ } catch { /* none chosen yet */ }++ const byKey = (person: string | undefined) => (person ? names.get(person) ?? null : null);+ return {+ of: (session) => byKey(personKey(session)),+ byKey,+ save(session, name) {+ if (name === null) names.delete(personKey(session));+ else names.set(personKey(session), name);+ writeFileAtomic(file, `${JSON.stringify({ v: 1, names: Object.fromEntries(names) }, null, 2)}\n`, { mode: 0o600 });+ },+ lineNames: (fallback) => (names.size ? (line) => byKey(line.sender?.id) ?? fallback : fallback),+ };+}diff --git a/server/index.ts b/server/index.tsindex 45130ec9a3..7d76c5a5d6 100644--- a/server/index.ts+++ b/server/index.ts@@ -279,7 +279,7 @@ import { botBox, startBotBoxAtBoot } from "./bot-box/boot.ts"; import { attachmeimport { createCloudSignedHost } from "./host/cloud-signed-host.ts"; import { createDeleteLeftovers, engineSessionFolders, instanceEnvironment } from "./host/delete-leftovers.ts"; import { createBotNameClash } from "./host/bot-name-clash.ts"; import { hiddenThreadRefusal, hideOthersSyncFolders } from "./host/team-private.ts"; import { createTeamMemberLeft, memoryLayerRecords } from "./host/team-member-left.ts"; import { createUploadOwners, uploadsFor } from "./host/member-uploads.ts"; import { createMemberOwnBot } from "./host/member-own-bot.ts"; import { createVisibilityHost } from "./host/visibility-host.ts"; import { createBotAccessHost, refusalFor, relayedSendRefusal } from "./host/bot-access-gate.ts"; import { createBotAccessRoutes, writeAccess } from "./routes/bot-access.ts"; import { createAccessRequests } from "./host/access-requests.ts";import { cloudPowerNow, createCloudPower, registerCloudPower, wokeFromSleep, type CloudPower } from "./cloud-power.ts"; import { createWokeNotifier } from "./cloud-woke.ts"; import { createSharedComputerRoutes } from "./routes/shared-computers.ts";import { lentCopies, noteSyncBotTurn } from "./routes/cloud-sync.ts"; import { mcpReconnectLine, retryBrokeredMcp } from "./bot-box/broker-mcp.ts";-import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";+import { type CloudOwnership } from "./cloud-owner.ts"; import { memberLoginRefusal, personalMoveRefusal } from "./cloud-team.ts"; import { createCloudTeamHost, type MemberProfile } from "./host/cloud-team-host.ts"; import { engineHomes } from "./engine-homes/engine-homes.ts"; import { audienceMember, layerId, memberAudience } from "./audience.ts"; import { createPersonRooms, createRoomReads, type OwnGroupFrames } from "./host/room-reads.ts"; import { createPersonBotOrder } from "./host/person-bot-order.ts"; import { createMeRoutes } from "./routes/me.ts"; import { createPersonNames } from "./host/person-names.ts"; import { createTeamPhoneRoutes } from "./routes/team-phone.ts"; import { settleCloudHome } from "./cloud-home-settle.ts"; import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; import { createTeamSlackHost } from "./host/team-slack-host.ts"; import { createTeamSlackMessages } from "./team-slack.ts"; import { createTeamSlackRoutes } from "./routes/team-slack.ts";import { createCloudMoveRoutes } from "./cloud-move-http.ts";import { RESTART_EXIT_CODE } from "./restart.ts";import { applyIncludedXMessage, holdIncludedServices, hostingCredential, researchCredential, trialCreditCredential, xCredential, xResearchStatus } from "./included-services.ts"; import { applyPhoneLinkMessage, phoneLinkPart } from "./phone-link.ts"; import { createResearchAvailability } from "./research.ts";@@ -823,12 +823,12 @@ registerEnginesBinDir(); const engineUpdates = engineUpdatesFor({ drivers: BUILT// Set only when a turn is admitted, never on queue or steer, so a second person's words cannot re-book the first person's turn.const turnTriggers = new Map<string, UsageTrigger>();-const NOBODY_PROFILE: MemberProfile = { name: "", email: "", aboutMe: "" };+const NOBODY_PROFILE: MemberProfile = { name: "", email: "", aboutMe: "" }; const personNames = createPersonNames(DATA_DIR), SELF_HOSTED = !CLOUD_HOME && !HOSTED_WORKSPACE;-/** What a signed-in person is called on their lines, cards and reactions: on a Team Cloud the name they chose first. */+/** What a signed-in person is called on their lines, cards and reactions: first the name they chose, on a Team Cloud or here. */function sessionPersonName(session: SessionRecord): string {if (CLOUD_TEAM) return teamHost.memberProfile(session).name || (session.email ?? session.label ?? "").trim();- return selfHostedPersonName(session, signInAllowList().admins, cfg.profile);+ return personNames.of(session) ?? selfHostedPersonName(session, signInAllowList().admins, cfg.profile);}function messageSender(auth: RequestAuth): ResolvedSender | undefined {@@ -845,11 +845,11 @@ function teamConversationPerson(threadId: string): string | undefined {return run ? cloudRoutineAuthors?.writer(run.routineId) : undefined;}-/** What people's lines are called in this conversation's turns. Where one person uses the server, the profile's name; on+/** What people's lines are called in this conversation's turns. Off a team, the profile's name or the one its signed-in sender chose; on* a Team Cloud each line its own speaker's, and a line with none the person whose conversation it is. The server's* profile names nobody on a team. */function userNameFor(threadId: string): PersonName {- if (!CLOUD_TEAM) return cfg.profile?.name?.trim() || "User";+ if (!CLOUD_TEAM) return personNames.lineNames(cfg.profile?.name?.trim() || "User");const fallback = teamHost.personName(teamConversationPerson(threadId)) ?? "User";return (line) => teamHost.personName(line.sender?.id) ?? line.sender?.name ?? fallback;}@@ -12184,7 +12184,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 || DESKTOP_MANAGED ? 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: Boolean(botMoves) })); if (teamMoveIn) { ROUTES.unshift(teamMoveIn.guard); ROUTES.push(teamMoveIn.routes); teamOwners.backfill(teamMoveIn.list()); } ROUTES.push(createDeciderRoutes({ decider, extractor, config: () => cfg }), createImageSettingsRoutes({ 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, notificationListed), createUpdateCheckRoutes(updateRouteDeps({ desktopManaged: DESKTOP_MANAGED, managed: Boolean(CLOUD_HOME || HOSTED_WORKSPACE), dataDir: DATA_DIR, activeTurns: () => liveTurnByThread.size, actor: adminActorFor })), createSeatsRoutes({ signInList: signInAllowList, sessions: () => sessions.list() }), 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 }, connectionsMoved: (language) => cloudConnections.moved(language), 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)); const conversationSharing = createConversationSharing({ team: CLOUD_TEAM, store: () => store, shares: conversationShares, saves: createTeamMemorySaves({ dataDir: DATA_DIR }), starter: (threadId) => threadStarters.get(threadId), audienceOf: teamHost.audienceOf, sees: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), levelOf, levelFor: (person, botId) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }).level(botId), people: () => teamOwners.people?.list() ?? [], nameOf: (email) => teamHost.personName(personKey({ id: "", email })) ?? email, language: (person) => personLanguages.forLine(person), busy: threadBusy, routinesIn: (threadId) => (routines?.listRoutines() ?? []).filter((routine) => routine.sourceThreadId === threadId || routine.resultsThreadId === threadId).length, outside: cloudGuestDriven, audienceChanged: (botId, threadId) => { store.patchTask(botId, threadId, { rewound: true, resumeCursors: {} }); }, changed: (botId) => { const bot = store.bot(botId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, inbox: () => teamMessages.inbox, looking: (email, threadId) => teamPresence.looking(email, threadId), notify, botOf: (threadId) => store.botByThread(threadId)?.id, handTo: (threadId, person) => threadStarters.handTo(threadId, person) }); ROUTES.push(conversationSharing.routes);if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));-const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (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), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }) }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),+const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (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), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(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: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: () => composio.connectedServices(cfg), offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));ROUTES.push(createRoomHoldRoutes({group: (id) => store.group(id),diff --git a/server/person-names.e2e.test.ts b/server/person-names.e2e.test.tsnew file mode 100644index 0000000000..8e55baf3ee--- /dev/null+++ b/server/person-names.e2e.test.ts@@ -0,0 +1,45 @@+import { statSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++import { launchVerificationServer } from "../scripts/control-omb.ts";++describe("names people choose on a self-hosted server", () => {+ it("labels each signed-in person's lines with the name they chose, while the owner's computer keeps the profile's", async () => {+ const fixture = await launchVerificationServer();+ const remote = { "x-forwarded-for": "198.51.100.21", "x-forwarded-proto": "https" };+ const api = async (method: string, path: string, body?: unknown, headers: Record<string, string> = {}) => {+ const response = await fetch(`${fixture.info.url}${path}`, {+ method, headers: { "content-type": "application/json", ...headers },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(10_000),+ });+ return { status: response.status, body: await response.json() as any };+ };+ const pair = async (label: string) => {+ const opened = await api("POST", "/api/auth/pairing", { scopes: ["client"] });+ const paired = await api("POST", "/api/auth/pair", { code: opened.body.code, label }, remote);+ expect(paired.status).toBe(200);+ return { ...remote, authorization: `Bearer ${paired.body.token}` };+ };+ try {+ expect((await api("PUT", "/api/config", { profile: { name: "Ada Lovelace" } })).status).toBe(200);+ const grace = await pair("Grace's laptop");+ const guest = await pair("Guest phone");+ expect((await api("GET", "/api/me")).status).toBe(404);+ expect((await api("GET", "/api/me", undefined, guest)).body).toEqual({ displayName: "", shownAs: "Guest phone" });+ expect((await api("PUT", "/api/me", { displayName: "Grace\u0007" }, grace)).status).toBe(400);+ expect((await api("PUT", "/api/me", { displayName: " Grace Hopper " }, grace)).body).toEqual({ displayName: "Grace Hopper", shownAs: "Grace Hopper" });+ if (process.platform !== "win32") expect(statSync(join(fixture.info.dataDir, "person-names.json")).mode & 0o777).toBe(0o600);++ const bot = (await api("POST", "/api/bots")).body.bot as { id: string; threadId: string };+ for (const [headers, text] of [[grace, "from grace"], [guest, "from the guest"]] as const) {+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { text }, headers)).status).toBe(202);+ }+ const lines = (await api("GET", `/api/threads/${bot.threadId}/messages?limit=50`)).body.messages as Array<{ text?: string; sender?: { name: string } }>;+ expect(lines.find((line) => line.text === "from grace")?.sender?.name).toBe("Grace Hopper");+ expect(lines.find((line) => line.text === "from the guest")?.sender?.name).toBe("Guest phone");+ } finally {+ await fixture.close();+ }+ }, 60_000);+});diff --git a/server/routes/me.test.ts b/server/routes/me.test.tsnew file mode 100644index 0000000000..110028c8b7--- /dev/null+++ b/server/routes/me.test.ts@@ -0,0 +1,72 @@+import { mkdtempSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it, vi } from "vitest";++import { createPersonNames } from "../host/person-names.ts";+import type { RequestAuth } from "../request-auth.ts";+import type { SessionRecord } from "../sessions.ts";+import { removeTempDir } from "../testing/cleanup.ts";+import { callRoute } from "./call-route.ts";+import { createMeRoutes, type MeRouteDeps } from "./me.ts";++const dirs: string[] = [];+afterEach(async () => { for (const dir of dirs.splice(0)) await removeTempDir(dir); });++const session = (id: string, email?: string): SessionRecord => ({ id, tokenHash: "0".repeat(64), label: "Chrome on Mac", scopes: ["client"], createdAt: 0, lastSeenAt: 0, expiresAt: 1, ...(email ? { email } : {}) });+const signedIn = (record: SessionRecord): RequestAuth => ({ kind: "session", session: record, via: "bearer", scopes: record.scopes });+const owner: RequestAuth = { kind: "loopback", scopes: ["admin", "client"] };++function selfHosted(names: MeRouteDeps["names"]) {+ const changed = vi.fn();+ const routes = createMeRoutes({+ team: null, session: (auth) => (auth.kind === "session" ? auth.session : null), changed, names,+ welcome: { read: () => { throw new Error("no welcome off a team"); }, save: () => { throw new Error("no welcome off a team"); } },+ profile: () => { throw new Error("no member profile off a team"); }, save: () => { throw new Error("no member profile off a team"); },+ seed: () => { throw new Error("no member profile off a team"); }, seeded: () => [],+ });+ return { routes, changed };+}++describe("/api/me on a self-hosted server", () => {+ const setup = () => {+ const dir = mkdtempSync(join(tmpdir(), "omb-me-route-")); dirs.push(dir);+ const store = createPersonNames(dir);+ return selfHosted({ store, shownAs: (record) => store.of(record) ?? record.email ?? record.label }).routes;+ };++ it("lets each signed-in person read and set the name they go by, and clear it again", async () => {+ const routes = setup();+ const grace = signedIn(session("s1", "[email protected]"));+ expect(await callRoute(routes, { method: "GET", path: "/api/me", auth: grace })).toEqual({ status: 200, body: { displayName: "", shownAs: "[email protected]" } });+ expect(await callRoute(routes, { method: "PUT", path: "/api/me", auth: grace, body: { displayName: " Grace Hopper " } })).toEqual({ status: 200, body: { displayName: "Grace Hopper", shownAs: "Grace Hopper" } });+ const device = signedIn(session("s2"));+ expect((await callRoute(routes, { method: "GET", path: "/api/me", auth: device })).body).toEqual({ displayName: "", shownAs: "Chrome on Mac" });+ expect((await callRoute(routes, { method: "GET", path: "/api/me", auth: signedIn(session("s3", "[email protected]")) })).body.displayName).toBe("Grace Hopper");+ expect(await callRoute(routes, { method: "PUT", path: "/api/me", auth: grace, body: { displayName: "" } })).toEqual({ status: 200, body: { displayName: "", shownAs: "[email protected]" } });+ });++ it("refuses a name that is too long, holds a control character, or is not text", async () => {+ const routes = setup();+ const grace = signedIn(session("s1", "[email protected]"));+ for (const displayName of ["x".repeat(61), "Grace\u0007", "Grace\nHopper"]) {+ expect(await callRoute(routes, { method: "PUT", path: "/api/me", auth: grace, body: { displayName } })).toMatchObject({ status: 400, body: { error: expect.stringContaining("60 characters") } });+ }+ expect((await callRoute(routes, { method: "PUT", path: "/api/me", auth: grace, body: { displayName: 7 } })).status).toBe(400);+ expect((await callRoute(routes, { method: "PUT", path: "/api/me", auth: grace, body: {} })).status).toBe(400);+ expect((await callRoute(routes, { method: "DELETE", path: "/api/me", auth: grace })).status).toBe(405);+ expect((await callRoute(routes, { method: "GET", path: "/api/me", auth: grace })).body.displayName).toBe("");+ });++ it("has nothing for the owner's own computer, which goes by the profile, nor any welcome off a team", async () => {+ const routes = setup();+ expect((await callRoute(routes, { method: "GET", path: "/api/me", auth: owner })).status).toBe(404);+ expect((await callRoute(routes, { method: "PUT", path: "/api/me", auth: owner, body: { displayName: "Ada" } })).status).toBe(404);+ expect((await callRoute(routes, { method: "PUT", path: "/api/me/welcome", auth: signedIn(session("s1")), body: { welcomed: true } })).status).toBe(404);+ });++ it("answers 404 where no names are kept, such as a Cloud home", async () => {+ const { routes } = selfHosted(null);+ expect((await callRoute(routes, { method: "GET", path: "/api/me", auth: signedIn(session("s1")) })).status).toBe(404);+ });+});diff --git a/server/routes/me.ts b/server/routes/me.tsindex 6e108e8291..79883265a1 100644--- a/server/routes/me.ts+++ b/server/routes/me.ts@@ -1,10 +1,12 @@// GET and PUT /api/me: a person's own profile on a Team Cloud (people-about.ts): the name and picture they go by and their-// "About you", read into their own turns only, with the address of their verified sign-in. Anywhere else the server's one-// profile (Settings → Profile) is the person's, and this answers 404.+// "About you", read into their own turns only, with the address of their verified sign-in. On a self-hosted server the one+// profile (Settings → Profile) is the owner's, and each signed-in person only chooses the name they go by here. Anywhere+// else this answers 404.import { botAvatarUrlSchema } from "../../shared/bot-avatar.ts";import type { CloudTeam } from "../cloud-team.ts";import type { MemberProfile, MemberProfilePatch } from "../host/cloud-team-host.ts";import { ABOUT_ME_MAX, PERSON_NAME_MAX, type SeedField } from "../people-about.ts";+import { cleanDisplayName, DISPLAY_NAME_MAX, type PersonNames } from "../host/person-names.ts";import { personKey } from "../person-key.ts";import type { RequestAuth } from "../request-auth.ts";import { WELCOME_HINT, type TeamWelcomeStore } from "../team-welcome.ts";@@ -23,11 +25,27 @@ export interface MeRouteDeps {seeded(session: SessionRecord): SeedField[];/** After a save: the person's own windows and phones show it. */changed(): void;+ /** On a self-hosted server: the names people chose, and what each is called now (`shownAs`). Null anywhere else. */+ names?: { store: PersonNames; shownAs(session: SessionRecord): string } | null;}export function createMeRoutes(deps: MeRouteDeps): RouteHandler {return async ({ req, res, path, method, auth, json, readBody }) => {if (path !== "/api/me" && path !== "/api/me/welcome") return PASS;+ if (!deps.team && deps.names && path === "/api/me") {+ const session = deps.session(auth);+ if (!session) return json(res, 404, { error: "This computer goes by the name in Settings → Profile." });+ const { store, shownAs } = deps.names;+ if (method === "PUT") {+ const body = await readBody(req, 8 * 1024);+ const given = body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>).displayName : undefined;+ if (typeof given !== "string") return json(res, 400, { error: "send { displayName }: the name you go by here, or \"\" to clear it" });+ const name = given.trim() ? cleanDisplayName(given) : null;+ if (given.trim() && !name) return json(res, 400, { error: `Your name is at most ${DISPLAY_NAME_MAX} characters, without control characters` });+ store.save(session, name);+ } else if (method !== "GET") return json(res, 405, { error: "method not allowed" });+ return json(res, 200, { displayName: store.of(session) ?? "", shownAs: shownAs(session) });+ }if (!deps.team) return json(res, 404, { error: "not found" });const session = deps.session(auth);if (!session) return json(res, 403, { error: "Sign in to this team to have a profile." });diff --git a/src/components/DisplayNameSetting.test.ts b/src/components/DisplayNameSetting.test.tsnew file mode 100644index 0000000000..8d1750a81a--- /dev/null+++ b/src/components/DisplayNameSetting.test.ts@@ -0,0 +1,50 @@+// @vitest-environment happy-dom+import { act, createElement } from "react";+import { createRoot, type Root } from "react-dom/client";+import { afterEach, beforeEach, expect, it, vi } from "vitest";++const fixture = vi.hoisted(() => ({ team: false, signedIn: true, name: "", calls: [] as { path: string; init?: { method?: string; body?: string } }[] }));+vi.mock("@/state/store", () => ({+ useStore: () => ({ state: { config: fixture.team ? { team: { id: "t1", name: "Acme" } } : {} } }),+ api: async (path: string, init?: { method?: string; body?: string }) => {+ fixture.calls.push({ path, ...(init ? { init } : {}) });+ if (!fixture.signedIn) throw new Error("404 not found");+ if (init?.method === "PUT") fixture.name = (JSON.parse(init.body!) as { displayName: string }).displayName.trim();+ return { displayName: fixture.name, shownAs: fixture.name || "Chrome on Mac" };+ },+}));+const { DisplayNameSetting } = await import("./DisplayNameSetting");++let container: HTMLDivElement, root: Root;+beforeEach(() => {+ vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);+ Object.assign(fixture, { team: false, signedIn: true, name: "", calls: [] });+ container = document.createElement("div"); document.body.append(container); root = createRoot(container);+});+afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); });++const type = (input: HTMLInputElement, value: string) => {+ Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);+ input.dispatchEvent(new Event("input", { bubbles: true }));+};++it("lets a signed-in person on a self-hosted server choose their name, saved when they leave the field", async () => {+ await act(async () => { root.render(createElement(DisplayNameSetting)); });+ const input = container.querySelector<HTMLInputElement>("input")!;+ expect(container.textContent).toContain("Your name on this server");+ expect(input.placeholder).toBe("Chrome on Mac");+ await act(async () => { type(input, "Grace Hopper"); });+ await act(async () => { input.focus(); input.blur(); });+ expect(fixture.calls.at(-1)).toEqual({ path: "/api/me", init: expect.objectContaining({ method: "PUT", body: JSON.stringify({ displayName: "Grace Hopper" }) }) });+ expect(input.value).toBe("Grace Hopper");+});++it("shows nothing on the owner's own computer, and asks nothing on a team", async () => {+ fixture.signedIn = false;+ await act(async () => { root.render(createElement(DisplayNameSetting)); });+ expect(container.innerHTML).toBe("");+ fixture.team = true; fixture.calls = [];+ await act(async () => { root.render(createElement(DisplayNameSetting)); });+ expect(container.innerHTML).toBe("");+ expect(fixture.calls).toEqual([]);+});diff --git a/src/components/DisplayNameSetting.tsx b/src/components/DisplayNameSetting.tsxnew file mode 100644index 0000000000..cdb943b475--- /dev/null+++ b/src/components/DisplayNameSetting.tsx@@ -0,0 +1,42 @@+import { useEffect, useId, useState } from "react";+import { api, useStore } from "@/state/store";+import { t } from "@/lib/i18n";+import { SETTINGS_INPUT } from "./SettingsPrimitives";++interface OwnName { displayName: string; shownAs: string }++/** Settings → Bots → About you on a self-hosted server: the name a signed-in person goes by there (GET/PUT /api/me).+ * Nothing on a team, or on the owner's own computer, which goes by the profile's name. */+export function DisplayNameSetting() {+ const team = Boolean(useStore().state.config?.team);+ const [own, setOwn] = useState<OwnName | null>(null);+ const [draft, setDraft] = useState("");+ const [failed, setFailed] = useState(false);+ const label = useId();+ useEffect(() => {+ if (team) return;+ let active = true;+ void api<OwnName>("/api/me", { timeoutMs: 10_000 }).then((answer) => {+ if (!active || typeof answer?.displayName !== "string") return;+ setOwn(answer);+ setDraft(answer.displayName);+ }, () => {});+ return () => { active = false; };+ }, [team]);+ if (team || !own) return null;+ const save = () => {+ if (draft.trim() === own.displayName) return;+ setFailed(false);+ void api<OwnName>("/api/me", { method: "PUT", body: JSON.stringify({ displayName: draft }), timeoutMs: 10_000 })+ .then((answer) => { setOwn(answer); setDraft(answer.displayName); }, () => setFailed(true));+ };+ return (+ <div className="flex flex-col gap-1 px-4 py-[13px]">+ <label id={label} htmlFor={`${label}-input`} className="text-[14px] text-ink">{t("settings.profile.displayName")}</label>+ <input id={`${label}-input`} aria-labelledby={label} value={draft} maxLength={60} placeholder={own.shownAs}+ onChange={(event) => setDraft(event.target.value)} onBlur={save} className={SETTINGS_INPUT} />+ <div className="text-[12px] text-ink-secondary">{t("settings.profile.displayNameHelp")}</div>+ {failed && <div role="alert" className="text-[12px] text-danger">{t("settings.profile.displayNameError")}</div>}+ </div>+ );+}diff --git a/src/components/settings/pages/PlacePages.tsx b/src/components/settings/pages/PlacePages.tsxindex 9384c7edd7..ff439c08d6 100644--- a/src/components/settings/pages/PlacePages.tsx+++ b/src/components/settings/pages/PlacePages.tsx@@ -15,6 +15,7 @@ import { CloudKeepHere } from "../../CloudKeepHere";import { CustomDomainSettings } from "../../CustomDomainSettings";import { preloadConnectedApps } from "@/lib/connected-apps";import { DecisionModelSettings } from "../../DecisionModelSettings";+import { DisplayNameSetting } from "../../DisplayNameSetting";import { DefaultBotSidebarRow } from "../../DefaultBotControls";import { EnginesSettings } from "../../EnginesSettings";import { ImageGenerationSettings } from "../../ImageGenerationSettings";@@ -156,7 +157,7 @@ export function BotsPage() {footnote={ctx.here || !ctx.desktop ? t("settings.bots.aboutYouHome", { app: productName() }) : undefined}><div className="flex flex-col gap-2"><Card><ProfileFields /></Card>- <SettingsRows><AwayEmailsSetting row /></SettingsRows>+ <SettingsRows><DisplayNameSetting /><AwayEmailsSetting row /></SettingsRows></div></SettingsGroup><SettingsGroup label={t("settings.bots.newBots")} block="new-bots">diff --git a/src/locales/en.json b/src/locales/en.jsonindex 7b065c8164..8b5a617bdf 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1803,6 +1803,9 @@"settings.profile.awayEmails": "Email me when I'm away","settings.profile.awayEmailsHelp": "One email when a teammate mentions you, a bot is waiting on your answer, or work you asked for finishes while you're not in the app. It never includes what anyone wrote.","settings.profile.awayEmailsError": "That didn't save. Try again.",+ "settings.profile.displayName": "Your name on this server",+ "settings.profile.displayNameHelp": "What people and bots here call you. Leave it empty to go by your sign-in.",+ "settings.profile.displayNameError": "That didn't save. Use 1 to 60 characters.","settings.profile.everyBotRules": "Rules for every bot","settings.profile.everyBotRulesPlaceholder": "Every bot follows these. A bot's own instructions win where they differ.","settings.profile.saving": "Saving…",diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex e146c859d9..c0b1fbb8bf 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -1636,6 +1636,9 @@"settings.profile.awayEmails": "Me envie um e-mail quando eu estiver fora","settings.profile.awayEmailsHelp": "Um e-mail quando um colega mencionar você, um bot estiver esperando sua resposta ou um trabalho que você pediu terminar enquanto você não está no app. Ele nunca inclui o que alguém escreveu.","settings.profile.awayEmailsError": "Não foi salvo. Tente novamente.",+ "settings.profile.displayName": "Seu nome neste servidor",+ "settings.profile.displayNameHelp": "Como as pessoas e os bots daqui chamam você. Deixe em branco para usar o nome do seu login.",+ "settings.profile.displayNameError": "Não foi salvo. Use de 1 a 60 caracteres.","settings.profile.everyBotRules": "Regras para todos os bots","settings.profile.everyBotRulesPlaceholder": "Todos os bots seguem estas regras. Quando divergem, valem as instruções do próprio bot.","settings.profile.saving": "Salvando…",