Skip to content

armgit / alook

Public Imported from GitHub
0

Multi-Agent Collaboration for Team and Friends

feat: add self profile settings

Guscfc4a17249ba
diff --git a/src/daemon/src/cli/daemonRunner.ts b/src/daemon/src/cli/daemonRunner.ts
index edffe7097..49af49a8b 100644
--- a/src/daemon/src/cli/daemonRunner.ts
+++ b/src/daemon/src/cli/daemonRunner.ts
@@ -24,7 +24,7 @@ import { scrubRuntimeErrorDiagnosticText } from "../runtime/errorDiagnostics.js"
import { createRotatingFileSink, type RotatingFileSink } from "../util/rotatingFileSink.js";
import { createDaemonSelfUpdateHandler } from "./daemonUpdate.js";
-const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach", "friend"];
+const CAPABILITIES = ["send", "read", "mentions", "tasks", "reactions", "server", "channels", "knowledge", "attach", "friend", "profile"];
export const DAEMON_LOG_MAX_BYTES = 8 * 1024 * 1024;
const DAEMON_ERROR_MESSAGE_MAX_CHARS = 512;
const DIAGNOSTIC_MAX_LINE_BYTES = 128 * 1024;
diff --git a/src/daemon/src/cli/index.test.ts b/src/daemon/src/cli/index.test.ts
index 3a0a1c466..f779d0a2e 100644
--- a/src/daemon/src/cli/index.test.ts
+++ b/src/daemon/src/cli/index.test.ts
@@ -18,6 +18,7 @@ vi.mock("./messageReminderClient", async (importOriginal) => ({
}));
import { main, setApiForTesting, decodeTextEscapes } from "./index";
import type { ServerApi } from "../server/contract";
+import { MAX_SERVER_ICON_SIZE_BYTES } from "@alook/shared/constants/community";
/** Capture exactly the JSON object the CLI prints to stdout. */
function captureStdout(): { lines: () => string[]; restore: () => void } {
@@ -55,6 +56,12 @@ function stubApi(over: Partial<ServerApi> = {}): ServerApi {
listMarks: async () => ({ marked: [] }),
friendRequest: async () => ({ friendshipId: "fr_1", status: "pending", hint: "Your owner needs to approve this request in DM." }),
listFriends: async () => ({ accepted: [], pendingOutgoing: [], pendingIncoming: [] }),
+ updateProfile: async (req) => ({
+ updated: [req.avatar ? "avatar" as const : undefined, req.bio !== undefined ? "bio" as const : undefined]
+ .filter((value): value is "avatar" | "bio" => value !== undefined),
+ ...(req.bio !== undefined ? { bio: req.bio } : {}),
+ ...(req.avatar ? { avatarUrl: "/api/community/bots/agent_test/avatar" } : {}),
+ }),
nap: async () => ({ napped: true }),
...over,
} as ServerApi;
@@ -1526,6 +1533,144 @@ describe("friend list", () => {
});
});
+describe("setting profile", () => {
+ it("rejects an empty command before calling ServerApi", async () => {
+ const updateProfile = vi.fn();
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile"]);
+ const env = parseEnvelope(cap.lines());
+ expect(env.error).toContain("--set-bio")
+ expect(updateProfile).not.toHaveBeenCalled();
+ });
+
+ it("accepts an empty bio as an explicit clear", async () => {
+ const updateProfile = vi.fn(async () => ({ updated: ["bio" as const], bio: "" }));
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-bio", ""]);
+ expect(parseEnvelope(cap.lines())).toEqual({ success: { updated: ["bio"], bio: "" } });
+ expect(updateProfile).toHaveBeenCalledWith({ bio: "" });
+ });
+
+ it("updates a non-empty bio without an avatar", async () => {
+ const updateProfile = vi.fn(async () => ({ updated: ["bio" as const], bio: "Backend and infrastructure" }));
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-bio", "Backend and infrastructure"]);
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: { updated: ["bio"], bio: "Backend and infrastructure" },
+ });
+ expect(updateProfile).toHaveBeenCalledWith({ bio: "Backend and infrastructure" });
+ });
+
+ it("updates an avatar without a bio", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "profile-"));
+ const file = path.join(dir, "avatar.webp");
+ fs.writeFileSync(file, new Uint8Array([1, 2, 3]));
+ const updateProfile = vi.fn(async () => ({
+ updated: ["avatar" as const],
+ avatarUrl: "/api/community/bots/agent_test/avatar",
+ }));
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-avatar", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: {
+ updated: ["avatar"],
+ avatarUrl: "/api/community/bots/agent_test/avatar",
+ },
+ });
+ expect(updateProfile).toHaveBeenCalledWith({
+ avatar: expect.objectContaining({ filename: "avatar.webp", contentType: "image/webp" }),
+ });
+ });
+
+ it("preflights and sends bio plus avatar in one logical request", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "profile-"));
+ const file = path.join(dir, "avatar.png");
+ fs.writeFileSync(file, new Uint8Array([1, 2, 3]));
+ const updateProfile = vi.fn(async () => ({
+ updated: ["avatar" as const, "bio" as const],
+ avatarUrl: "/api/community/bots/agent_test/avatar",
+ bio: "infra",
+ }));
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-bio", "infra", "--set-avatar", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
+ expect(parseEnvelope(cap.lines())).toEqual({
+ success: {
+ updated: ["avatar", "bio"],
+ avatarUrl: "/api/community/bots/agent_test/avatar",
+ bio: "infra",
+ },
+ });
+ expect(updateProfile).toHaveBeenCalledWith({
+ bio: "infra",
+ avatar: expect.objectContaining({ filename: "avatar.png", contentType: "image/png" }),
+ });
+ });
+
+ it("rejects an unsupported avatar before calling ServerApi", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "profile-"));
+ const file = path.join(dir, "avatar.svg");
+ fs.writeFileSync(file, "<svg/>");
+ const updateProfile = vi.fn();
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-avatar", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
+ expect(parseEnvelope(cap.lines()).error).toContain("png / jpeg / webp / gif");
+ expect(updateProfile).not.toHaveBeenCalled();
+ });
+
+ it("rejects a missing avatar before calling ServerApi", async () => {
+ const os = await import("os");
+ const path = await import("path");
+ const updateProfile = vi.fn();
+ setApiForTesting(stubApi({ updateProfile }));
+ const missing = path.join(os.tmpdir(), `missing-avatar-${Date.now()}.png`);
+ await main(["setting", "profile", "--set-avatar", missing]);
+ expect(parseEnvelope(cap.lines()).error).toContain("cannot read avatar");
+ expect(updateProfile).not.toHaveBeenCalled();
+ });
+
+ it("rejects an oversize avatar before calling ServerApi", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "profile-"));
+ const file = path.join(dir, "avatar.png");
+ fs.writeFileSync(file, new Uint8Array(MAX_SERVER_ICON_SIZE_BYTES + 1));
+ const updateProfile = vi.fn();
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-avatar", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
+ expect(parseEnvelope(cap.lines()).error).toContain("avatar too large");
+ expect(updateProfile).not.toHaveBeenCalled();
+ });
+
+ it("rejects an empty avatar before calling ServerApi", async () => {
+ const fs = await import("fs");
+ const os = await import("os");
+ const path = await import("path");
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "profile-"));
+ const file = path.join(dir, "avatar.png");
+ fs.writeFileSync(file, "");
+ const updateProfile = vi.fn();
+ setApiForTesting(stubApi({ updateProfile }));
+ await main(["setting", "profile", "--set-avatar", file]);
+ fs.rmSync(dir, { recursive: true, force: true });
+ expect(parseEnvelope(cap.lines()).error).toContain("empty");
+ expect(updateProfile).not.toHaveBeenCalled();
+ });
+});
+
describe("decodeTextEscapes", () => {
it("decodes \\n to a real newline", () => {
expect(decodeTextEscapes("a\\nb")).toBe("a\nb");
diff --git a/src/daemon/src/cli/index.ts b/src/daemon/src/cli/index.ts
index 7ca652b32..035469974 100755
--- a/src/daemon/src/cli/index.ts
+++ b/src/daemon/src/cli/index.ts
@@ -26,8 +26,11 @@ import { daemonReplace } from "./daemonUpdate.js";
import { armMessageReminderFromEnv, parseRemindAfter } from "./messageReminderClient.js";
import { parseInviteToken } from "@alook/shared/lib/invite-link";
import {
+ ALLOWED_ICON_MIME_TYPES,
MAX_ATTACHMENT_THUMBNAIL_SIZE_BYTES,
MAX_EMOJI_BYTES,
+ MAX_PROFILE_ABOUT_LENGTH,
+ MAX_SERVER_ICON_SIZE_BYTES,
} from "@alook/shared/constants/community";
import { nowLocalISO, toLocalISO } from "../util/localTime.js";
@@ -181,7 +184,11 @@ function contentTypeFromFilename(filename: string): string {
*/
function isTransientMutationError(err: unknown): boolean {
const msg = err instanceof Error ? err.message : String(err);
+ const status = typeof err === "object" && err !== null && "status" in err
+ ? (err as { status?: unknown }).status
+ : undefined;
return (
+ (typeof status === "number" && status >= 500 && status <= 599) ||
/upstream returned 5\d\d/.test(msg) ||
msg.includes("upstream body read failed") ||
msg.includes("fetch failed") ||
@@ -547,6 +554,49 @@ async function cmdAttachmentDownload(opts: Record<string, unknown>): Promise<unk
return result;
}
+async function cmdSettingProfile(opts: Record<string, unknown>): Promise<unknown> {
+ const bio = opts.setBio as string | undefined;
+ const avatarPath = opts.setAvatar as string | undefined;
+ if (bio === undefined && avatarPath === undefined) {
+ throw new CliError("setting profile: --set-bio <text> or --set-avatar <path> is required");
+ }
+ if (bio !== undefined && bio.length > MAX_PROFILE_ABOUT_LENGTH) {
+ throw new CliError(`setting profile: bio must be ≤ ${MAX_PROFILE_ABOUT_LENGTH} characters`);
+ }
+
+ let avatar: { filename: string; contentType: string; data: Uint8Array } | undefined;
+ if (avatarPath !== undefined) {
+ const fs = await import("fs/promises");
+ let bytes: Buffer;
+ try {
+ bytes = await fs.readFile(avatarPath);
+ } catch (err) {
+ throw new CliError(`setting profile: cannot read avatar: ${(err as Error).message}`);
+ }
+ if (bytes.byteLength === 0) throw new CliError("setting profile: avatar file is empty");
+ if (bytes.byteLength > MAX_SERVER_ICON_SIZE_BYTES) {
+ throw new CliError(
+ `setting profile: avatar too large — ${bytes.byteLength} bytes, max ${MAX_SERVER_ICON_SIZE_BYTES}`,
+ );
+ }
+ const pathMod = await import("path");
+ const filename = pathMod.basename(avatarPath);
+ const contentType = contentTypeFromFilename(filename);
+ if (!(ALLOWED_ICON_MIME_TYPES as readonly string[]).includes(contentType)) {
+ throw new CliError("setting profile: avatar must be png / jpeg / webp / gif");
+ }
+ avatar = { filename, contentType, data: new Uint8Array(bytes) };
+ }
+
+ const api = getApi();
+ // updateProfile owns per-step retries so a successful avatar is never
+ // replayed merely because the following bio step failed transiently.
+ return api.updateProfile({
+ ...(bio !== undefined ? { bio } : {}),
+ ...(avatar ? { avatar } : {}),
+ });
+}
+
async function cmdInboxPull(opts: Record<string, unknown>): Promise<unknown> {
const api = getApi();
const agent = agentId(opts);
@@ -978,6 +1028,21 @@ function buildProgram(): Command {
printEnvelope({ success: result });
});
+ const setting = program.command("setting").description("account settings").exitOverride();
+ setting.configureOutput({ writeOut: () => {}, writeErr: () => {} });
+
+ setting
+ .command("profile")
+ .description("update your public bio and/or avatar")
+ .option("--set-bio <text>", "set public bio; pass an empty string to clear it")
+ .option("--set-avatar <path>", "upload a png, jpeg, webp, or gif avatar")
+ .exitOverride()
+ .configureOutput({ writeOut: () => {}, writeErr: () => {} })
+ .action(async function (this: Command) {
+ const result = await cmdSettingProfile({ ...program.opts(), ...this.opts() });
+ printEnvelope({ success: result });
+ });
+
program
.command("nap")
.description("end your session and start fresh, carrying a handoff to your reborn self (read the nap rule first)")
diff --git a/src/daemon/src/cli/proxyServerApi.test.ts b/src/daemon/src/cli/proxyServerApi.test.ts
index d0f25c3cb..86c31c7a6 100644
--- a/src/daemon/src/cli/proxyServerApi.test.ts
+++ b/src/daemon/src/cli/proxyServerApi.test.ts
@@ -42,6 +42,101 @@ function bufferResponse(bytes: Uint8Array, headers: Record<string, string> = {})
const cfg = { proxyUrl: "http://proxy.test", voucher: "vch_test" };
+describe("createProxyServerApi — updateProfile", () => {
+ it("applies avatar before bio and returns one ordered result", async () => {
+ const seen: Array<{ url: string; init?: RequestInit }> = [];
+ const fetchImpl: FetchLike = vi.fn(async (url: string, init?: RequestInit) => {
+ seen.push({ url, init });
+ return url.endsWith("/avatar")
+ ? jsonBody(JSON.stringify({ url: "/api/community/bots/b1/avatar" }))
+ : jsonBody(JSON.stringify({ aboutMe: "infra" }));
+ });
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ const result = await api.updateProfile({
+ bio: "infra",
+ avatar: { filename: "me.png", contentType: "image/png", data: new Uint8Array([1, 2, 3]) },
+ });
+ expect(seen.map((entry) => entry.url)).toEqual([
+ "http://proxy.test/api/community/users/me/avatar",
+ "http://proxy.test/api/community/users/me/profile",
+ ]);
+ expect(seen[0]?.init?.body).toBeInstanceOf(FormData);
+ expect(seen[1]?.init?.body).toBe(JSON.stringify({ aboutMe: "infra" }));
+ expect(result).toEqual({
+ updated: ["avatar", "bio"],
+ avatarUrl: "/api/community/bots/b1/avatar",
+ bio: "infra",
+ });
+ });
+
+ it("reports explicit partial state when avatar succeeds and bio fails", async () => {
+ const fetchImpl: FetchLike = vi.fn()
+ .mockResolvedValueOnce(jsonBody(JSON.stringify({ url: "/api/community/bots/b1/avatar" })))
+ .mockResolvedValue(jsonBody(JSON.stringify({ error: "bad bio" }), { status: 400 }));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ try {
+ await api.updateProfile({
+ bio: "infra",
+ avatar: { filename: "me.png", contentType: "image/png", data: new Uint8Array([1]) },
+ });
+ throw new Error("should have thrown");
+ } catch (err) {
+ expect((err as Error).message).toBe("bad bio");
+ expect((err as { hint?: string }).hint).toBe("avatar was applied; bio was not applied");
+ }
+ });
+
+ it("retries bio in place without replaying a previously committed avatar", async () => {
+ const fetchImpl: FetchLike = vi.fn()
+ .mockResolvedValueOnce(jsonBody(JSON.stringify({ url: "/api/community/bots/b1/avatar" })))
+ .mockResolvedValueOnce(jsonBody(JSON.stringify({ error: "temporary" }), { status: 503 }))
+ .mockResolvedValueOnce(jsonBody(JSON.stringify({ aboutMe: "infra" })));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+
+ await expect(api.updateProfile({
+ bio: "infra",
+ avatar: { filename: "me.png", contentType: "image/png", data: new Uint8Array([1]) },
+ })).resolves.toEqual({
+ updated: ["avatar", "bio"],
+ avatarUrl: "/api/community/bots/b1/avatar",
+ bio: "infra",
+ });
+
+ const urls = (fetchImpl as ReturnType<typeof vi.fn>).mock.calls.map(([url]) => url);
+ expect(urls.filter((url) => String(url).endsWith("/avatar"))).toHaveLength(1);
+ expect(urls.filter((url) => String(url).endsWith("/profile"))).toHaveLength(2);
+ });
+
+ it("retains the partial-state hint when every bio retry fails after avatar commit", async () => {
+ const fetchImpl: FetchLike = vi.fn()
+ .mockResolvedValueOnce(jsonBody(JSON.stringify({ url: "/api/community/bots/b1/avatar" })))
+ .mockResolvedValue(jsonBody(JSON.stringify({ error: "D1 unavailable" }), { status: 503 }));
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+
+ try {
+ await api.updateProfile({
+ bio: "infra",
+ avatar: { filename: "me.png", contentType: "image/png", data: new Uint8Array([1]) },
+ });
+ throw new Error("should have thrown");
+ } catch (err) {
+ expect((err as Error).message).toBe("D1 unavailable");
+ expect((err as { hint?: string }).hint).toBe("avatar was applied; bio was not applied");
+ }
+
+ const urls = (fetchImpl as ReturnType<typeof vi.fn>).mock.calls.map(([url]) => url);
+ expect(urls.filter((url) => String(url).endsWith("/avatar"))).toHaveLength(1);
+ expect(urls.filter((url) => String(url).endsWith("/profile"))).toHaveLength(4);
+ });
+
+ it("rejects an empty request before fetch", async () => {
+ const fetchImpl: FetchLike = vi.fn();
+ const api = createProxyServerApi({ ...cfg, fetchImpl: fetchImpl as typeof fetch });
+ await expect(api.updateProfile({})).rejects.toThrow("bio or avatar is required");
+ expect(fetchImpl).not.toHaveBeenCalled();
+ });
+});
+
describe("createProxyServerApi — parseJsonResponse via call<T>", () => {
it("throws structured 'non-JSON body' on empty 500", async () => {
const fetchImpl: FetchLike = vi.fn(async () => jsonBody("", { status: 500 }));
@@ -91,6 +186,7 @@ describe("createProxyServerApi — parseJsonResponse via call<T>", () => {
throw new Error("should have thrown");
} catch (err) {
expect((err as Error).message).toBe("not allowed");
+ expect((err as { status?: number }).status).toBe(403);
expect((err as { code?: string }).code).toBe("forbidden");
expect((err as { hint?: string }).hint).toBe("check owner");
}
diff --git a/src/daemon/src/cli/proxyServerApi.ts b/src/daemon/src/cli/proxyServerApi.ts
index c932c3071..d286ffeb4 100644
--- a/src/daemon/src/cli/proxyServerApi.ts
+++ b/src/daemon/src/cli/proxyServerApi.ts
@@ -50,8 +50,10 @@ import type {
AgentId,
FriendRequestResult,
FriendCard,
+ UpdateProfileRequest,
+ UpdateProfileResult,
} from "../server/contract.js";
-import { formatHandle } from "@alook/shared";
+import { CommunityAgentUpdateProfileRequestSchema, formatHandle } from "@alook/shared";
export interface ProxyServerApiConfig {
/** The credential proxy base URL (from `<PREFIX>_PROXY_URL`). */
@@ -106,6 +108,10 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
}
if (!res.ok) {
const e = new Error(json?.error ?? `proxy ${method} failed (${res.status})`);
+ // Preserve transport status independently from the server's human error
+ // text. Retry policy must classify a JSON `{ error: "temporary" }` 503
+ // by its stable status, while leaving the same text on a 4xx terminal.
+ (e as Error & { status: number }).status = res.status;
// Only attach when present — assigning `undefined` would leave an own
// property that trips `"code" in err` / `hasOwnProperty` checks in
// callers that use those as feature-tests.
@@ -119,6 +125,36 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
return json as T;
}
+ function isTransientProfileStepError(err: unknown): boolean {
+ const message = err instanceof Error ? err.message : String(err);
+ const status = typeof err === "object" && err !== null && "status" in err
+ ? (err as { status?: unknown }).status
+ : undefined;
+ return (
+ (typeof status === "number" && status >= 500 && status <= 599) ||
+ /upstream returned 5\d\d/.test(message) ||
+ message.includes("upstream body read failed") ||
+ message.includes("fetch failed") ||
+ message.includes("ECONNRESET") ||
+ message.includes("ETIMEDOUT") ||
+ message.includes("socket hang up") ||
+ message.includes("network")
+ );
+ }
+
+ async function withProfileStepRetry<T>(step: () => Promise<T>): Promise<T> {
+ const maxAttempts = 4;
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
+ try {
+ return await step();
+ } catch (err) {
+ if (!isTransientProfileStepError(err) || attempt === maxAttempts - 1) throw err;
+ await new Promise((resolve) => setTimeout(resolve, Math.min(2000, 150 * 2 ** attempt)));
+ }
+ }
+ throw new Error("profile step retry exhausted");
+ }
+
async function callUpload(req: AttachmentUploadRequest): Promise<AgentAttachmentUploadResult> {
const form = new FormData();
// The Blob's `type` becomes `File.type` on the server after multipart parsing;
@@ -494,6 +530,65 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
return parseJsonResponse<{ napped: boolean }>(res, "nap");
}
+ async function callUpdateProfile(req: UpdateProfileRequest): Promise<UpdateProfileResult> {
+ const parsed = CommunityAgentUpdateProfileRequestSchema.safeParse(req);
+ if (!parsed.success) {
+ throw new Error(parsed.error.issues[0]?.message ?? "invalid profile update");
+ }
+
+ const updated: Array<"avatar" | "bio"> = [];
+ let avatarUrl: string | undefined;
+ if (req.avatar) {
+ const body = await withProfileStepRetry(async () => {
+ // Rebuild FormData per attempt: fetch implementations are allowed to
+ // consume request bodies, so reusing one would make the retry unsafe.
+ // The avatar door overwrites one stable R2 key, making this step
+ // idempotent even when the first response is lost after commit.
+ const form = new FormData();
+ const blob = new Blob([new Uint8Array(req.avatar!.data)], { type: req.avatar!.contentType });
+ form.append("file", blob, req.avatar!.filename);
+ const res = await fetchImpl(`${base}/api/community/users/me/avatar`, {
+ method: "POST",
+ headers: { authorization: `Bearer ${config.voucher}` },
+ body: form,
+ });
+ return parseJsonResponse<{ url: string }>(res, "updateProfile avatar");
+ });
+ avatarUrl = body.url;
+ updated.push("avatar");
+ }
+
+ let bio: string | undefined;
+ if (req.bio !== undefined) {
+ try {
+ const body = await withProfileStepRetry(async () => {
+ const res = await fetchImpl(`${base}/api/community/users/me/profile`, {
+ method: "PATCH",
+ headers: {
+ "content-type": "application/json",
+ authorization: `Bearer ${config.voucher}`,
+ },
+ body: JSON.stringify({ aboutMe: req.bio }),
+ });
+ return parseJsonResponse<{ aboutMe: string }>(res, "updateProfile bio");
+ });
+ bio = body.aboutMe;
+ updated.push("bio");
+ } catch (err) {
+ if (avatarUrl !== undefined && err instanceof Error) {
+ (err as Error & { hint?: string }).hint = "avatar was applied; bio was not applied";
+ }
+ throw err;
+ }
+ }
+
+ return {
+ updated,
+ ...(bio !== undefined ? { bio } : {}),
+ ...(avatarUrl !== undefined ? { avatarUrl } : {}),
+ };
+ }
+
async function callInboxSnapshot(): Promise<InboxSnapshot> {
// RETARGETED off the flat `inboxSnapshot` verb onto GET users/me/inbox/snapshot
// (route/disc 轴3). A GET — snapshot is a pure peek (never advances the read
@@ -613,6 +708,7 @@ export function createProxyServerApi(config: ProxyServerApiConfig): ServerApi {
listMembers: callListMembers,
attachmentUpload: callUpload,
attachmentDownload: callDownload,
+ updateProfile: callUpdateProfile,
reactAdd: callReactAdd,
markSet: callMarkSet,
markRemove: callMarkRemove,
diff --git a/src/daemon/src/credentials/credentialProxy.test.ts b/src/daemon/src/credentials/credentialProxy.test.ts
index 2cb6e2c80..d0a998146 100644
--- a/src/daemon/src/credentials/credentialProxy.test.ts
+++ b/src/daemon/src/credentials/credentialProxy.test.ts
@@ -65,6 +65,15 @@ async function post(url: string, voucher: string, path: string) {
}
describe("DEFAULT_CAPABILITY_RESOLVER", () => {
+ it("maps only the exact self-profile route shapes to `profile`", () => {
+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/users/me/profile")).toBe("profile");
+ expect(DEFAULT_CAPABILITY_RESOLVER("PATCH", "/api/community/users/me/profile")).toBe("profile");
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/users/me/avatar")).toBe("profile");
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/users/me/profile")).toBeUndefined();
+ expect(DEFAULT_CAPABILITY_RESOLVER("GET", "/api/community/users/me/avatar")).toBeUndefined();
+ expect(DEFAULT_CAPABILITY_RESOLVER("POST", "/api/community/users/me/inbox/pull")).toBe("read");
+ });
+
it("maps a reaction (canonical door PUT messages/{id}/reactions) to `send` (a read-only voucher must not react)", () => {
// Flat /api/reactAdd is DELETED (folded into the canonical reaction door).
// The write capability now attaches to the door shape.
diff --git a/src/daemon/src/credentials/credentialProxy.ts b/src/daemon/src/credentials/credentialProxy.ts
index aae2bcb37..bee06411f 100644
--- a/src/daemon/src/credentials/credentialProxy.ts
+++ b/src/daemon/src/credentials/credentialProxy.ts
@@ -250,6 +250,10 @@ function parseBearer(authHeader: string | undefined): string | null {
export type CapabilityResolver = (method: string, pathname: string) => Capability | undefined;
export const DEFAULT_CAPABILITY_RESOLVER: CapabilityResolver = (method, pathname) => {
+ if (
+ ((method === "GET" || method === "PATCH") && pathname === "/api/community/users/me/profile")
+ || (method === "POST" && pathname === "/api/community/users/me/avatar")
+ ) return "profile";
// Match `/attachmentUpload` and `/attachmentDownload` (pre-rewrite pathname
// — the credential proxy inspects the client's `/api/...` path here). Both
// endpoints share the `"attach"` capability so a voucher can be scoped to
diff --git a/src/daemon/src/daemon/createDaemon.test.ts b/src/daemon/src/daemon/createDaemon.test.ts
index c43b582a4..1a6ebfad6 100644
--- a/src/daemon/src/daemon/createDaemon.test.ts
+++ b/src/daemon/src/daemon/createDaemon.test.ts
@@ -1229,6 +1229,11 @@ describe("deriveAuditLogSubcommand", () => {
// ack is the advance op of the trinity but writes NO audit row here (re-homed
// to the daemon reborn-ready signal) — null, same as flat /ack, NOT `users`.
expect(deriveAuditLogSubcommand("/api/community/users/me/inbox/ack", "POST")).toBe(null);
+ // One combined profile command issues two independently auditable writes.
+ expect(deriveAuditLogSubcommand("/api/community/users/me/avatar", "POST")).toBe("profileAvatarUpdate");
+ expect(deriveAuditLogSubcommand("/api/community/users/me/profile", "PATCH")).toBe("profileBioUpdate");
+ expect(deriveAuditLogSubcommand("/api/community/users/me/profile", "GET")).toBe(null);
+ expect(deriveAuditLogSubcommand("/api/community/users/me/avatar", "PATCH")).toBe(null);
// bot-self lifecycle door (bots/me/*): nap maps back to `nap`, not `bots`.
expect(deriveAuditLogSubcommand("/api/community/bots/me/nap", "POST")).toBe("nap");
// attachments door (attachments fold): channels/{id}/attachments = upload,
diff --git a/src/daemon/src/daemon/createDaemon.ts b/src/daemon/src/daemon/createDaemon.ts
index 01259b3f9..be43c6a55 100644
--- a/src/daemon/src/daemon/createDaemon.ts
+++ b/src/daemon/src/daemon/createDaemon.ts
@@ -193,6 +193,13 @@ export function deriveAuditLogSubcommand(pathname: string, method?: string): str
if (/^\/api\/community\/users\/me\/inbox\/snapshot(\/|$|\?)/.test(canonical)) return "inboxSnapshot";
if (/^\/api\/community\/users\/me\/inbox\/ack(\/|$|\?)/.test(canonical)) return null; // ack writes no audit row here (re-homed to daemon reborn-ready signal)
+ // A combined `setting profile` invocation is deliberately two canonical
+ // mutations (avatar first, then bio). Keep them distinct in the authoritative
+ // proxy audit so partial completion is visible instead of collapsing both
+ // writes into one ambiguous shell-level event.
+ if (method === "PATCH" && canonical === "/api/community/users/me/profile") return "profileBioUpdate";
+ if (method === "POST" && canonical === "/api/community/users/me/avatar") return "profileAvatarUpdate";
+
// Bot-self lifecycle door (bots/me/*, Blondie #527): nap relocated from the flat
// /nap to bots/me/nap. Map back to the logical `nap` verb so the audit stays
// `nap`, not the `bots` segment.
diff --git a/src/daemon/src/drivers/systemPrompt.ts b/src/daemon/src/drivers/systemPrompt.ts
index 25425b175..17b71cd72 100644
--- a/src/daemon/src/drivers/systemPrompt.ts
+++ b/src/daemon/src/drivers/systemPrompt.ts
@@ -149,6 +149,11 @@ function cliCommandsSection(): string {
`2. \`${CLI} friend list\` — list your friends and pending requests ` +
`(\`accepted\`, \`pendingOutgoing\`, \`pendingIncoming\`).`,
"",
+ "### Settings",
+ "",
+ `1. \`${CLI} setting profile --set-bio <text> --set-avatar <path>\` — update your public bio ` +
+ `and/or avatar. At least one flag is required; pass \`--set-bio ""\` to clear the bio.`,
+ "",
"### Context Lifecycle",
"",
`1. \`${CLI} nap --handoff <file>\` (or \`--text <note>\`) — reset your current session and ` +
diff --git a/src/daemon/src/server/contract.ts b/src/daemon/src/server/contract.ts
index 8f731326c..68479971c 100644
--- a/src/daemon/src/server/contract.ts
+++ b/src/daemon/src/server/contract.ts
@@ -32,6 +32,8 @@ export type {
AgentAttachmentDownloadResult,
AttachmentUploadRequest,
AttachmentDownloadRequest,
+ UpdateProfileRequest,
+ UpdateProfileResult,
FileHandle,
Cursor,
Page,
diff --git a/src/shared/src/community-cli-contract.ts b/src/shared/src/community-cli-contract.ts
index c8fc211fd..1bb1a15ad 100644
--- a/src/shared/src/community-cli-contract.ts
+++ b/src/shared/src/community-cli-contract.ts
@@ -366,6 +366,21 @@ export interface AttachmentDownloadRequest {
destPath: string;
}
+export interface UpdateProfileRequest {
+ bio?: string;
+ avatar?: {
+ filename: string;
+ contentType: string;
+ data: Uint8Array;
+ };
+}
+
+export interface UpdateProfileResult {
+ updated: Array<"avatar" | "bio">;
+ bio?: string;
+ avatarUrl?: string;
+}
+
/**
* Sent: the message landed. Blocked: the channel has unseen messages the agent
* must align to first (pull, then resend) — `latestSeq` is the current waterline.
@@ -650,6 +665,9 @@ export interface ServerApi {
/** Download an attachment by id, writing to `destPath` (atomic temp-then-rename). */
attachmentDownload(req: AttachmentDownloadRequest): Promise<AgentAttachmentDownloadResult>;
+ /** Update the authenticated account's public bio and/or avatar. */
+ updateProfile(req: UpdateProfileRequest): Promise<UpdateProfileResult>;
+
/** React to a message with a single emoji. Duplicates are idempotent (`duplicate:true`, no fan-out). */
reactAdd(req: { channel: ChannelRef; seq: Seq; emoji: string }): Promise<CommunityAgentReactAddResponse>;
diff --git a/src/shared/src/db/community-machine-schema.ts b/src/shared/src/db/community-machine-schema.ts
index f60049452..ebed2b2ad 100644
--- a/src/shared/src/db/community-machine-schema.ts
+++ b/src/shared/src/db/community-machine-schema.ts
@@ -256,6 +256,7 @@ export const communityBotBinding = sqliteTable(
.notNull()
.references(() => communityMachine.id, { onDelete: "restrict" }),
runtime: text("runtime").notNull(),
+ instruction: text("instruction").notNull().default(""),
// Full launchable model id (e.g. "claude-opus-4-6"), or NULL for the
// runtime's default. Kind is derived from the catalog at read time, never
// stored. Hand-maintained in lockstep with migration 0063 (no drizzle-kit
diff --git a/src/shared/src/db/queries/community/bot.ts b/src/shared/src/db/queries/community/bot.ts
index c7811b1cc..16e0c2ee8 100644
--- a/src/shared/src/db/queries/community/bot.ts
+++ b/src/shared/src/db/queries/community/bot.ts
@@ -61,6 +61,7 @@ export type BotBinding = {
userId: string;
machineId: string;
runtime: string;
+ instruction: string;
modelName: string | null;
createdAt: string;
};
@@ -92,17 +93,13 @@ export async function listBotsForOwner(
createdAt: user.createdAt,
updatedAt: user.updatedAt,
lastRefreshContextAt: user.lastRefreshContextAt,
- description: communityUserProfile.aboutMe,
+ description: communityBotBinding.instruction,
machineId: communityBotBinding.machineId,
runtime: communityBotBinding.runtime,
modelName: communityBotBinding.modelName,
})
.from(user)
.innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
- .leftJoin(
- communityUserProfile,
- eq(communityUserProfile.userId, user.id)
- )
.where(
and(
eq(user.isBot, true),
@@ -145,17 +142,13 @@ export async function getBotOwnedBy(
createdAt: user.createdAt,
updatedAt: user.updatedAt,
lastRefreshContextAt: user.lastRefreshContextAt,
- description: communityUserProfile.aboutMe,
+ description: communityBotBinding.instruction,
machineId: communityBotBinding.machineId,
runtime: communityBotBinding.runtime,
modelName: communityBotBinding.modelName,
})
.from(user)
.leftJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
- .leftJoin(
- communityUserProfile,
- eq(communityUserProfile.userId, user.id)
- )
.where(
and(
eq(user.id, botId),
@@ -395,7 +388,7 @@ export async function listBotsForMachine(
id: user.id,
name: user.name,
discriminator: user.discriminator,
- description: communityUserProfile.aboutMe,
+ description: communityBotBinding.instruction,
ownerName: owner.name,
ownerDiscriminator: owner.discriminator,
runtime: communityBotBinding.runtime,
@@ -404,10 +397,6 @@ export async function listBotsForMachine(
.from(user)
.innerJoin(communityBotBinding, eq(communityBotBinding.userId, user.id))
.innerJoin(owner, eq(owner.id, user.ownerUserId))
- .leftJoin(
- communityUserProfile,
- eq(communityUserProfile.userId, user.id)
- )
.where(
and(
eq(communityBotBinding.machineId, machineId),
@@ -524,6 +513,7 @@ export async function createBot(
userId: botId,
machineId: data.machineId,
runtime: data.runtime,
+ instruction: description,
modelName: data.modelName ?? null,
createdAt: nowIso,
});
@@ -568,13 +558,29 @@ export async function updateBot(
if (data.name !== undefined) set.name = data.name;
if (data.image !== undefined) set.image = data.image;
- // When description is changing, batch the user UPDATE + profile upsert so a
- // concurrent softDeleteBot can't slip in between and leave a fresh description
- // on a tombstoned bot. The upsert INSERT branch is safe (createBot writes the
- // profile row); it only fires for legacy rows that pre-date the profile write.
let rows: Array<{ id: string; name: string; discriminator: string; image: string | null }>;
if (data.description !== undefined) {
+ const ownerScopedIds = db
+ .select({ id: user.id })
+ .from(user)
+ .where(
+ and(
+ eq(user.id, botId),
+ eq(user.ownerUserId, ownerId),
+ eq(user.isBot, true),
+ isNull(user.deletedAt)
+ )
+ );
+ const ownerScopedBindingIds = db
+ .select({ id: communityBotBinding.userId })
+ .from(communityBotBinding)
+ .where(inArray(communityBotBinding.userId, ownerScopedIds));
const s1 = db
+ .update(communityBotBinding)
+ .set({ instruction: data.description })
+ .where(inArray(communityBotBinding.userId, ownerScopedIds))
+ .returning({ userId: communityBotBinding.userId });
+ const s2 = db
.update(user)
.set(set)
.where(
@@ -582,19 +588,15 @@ export async function updateBot(
eq(user.id, botId),
eq(user.ownerUserId, ownerId),
eq(user.isBot, true),
- isNull(user.deletedAt)
+ isNull(user.deletedAt),
+ inArray(user.id, ownerScopedBindingIds)
)
)
.returning({ id: user.id, name: user.name, discriminator: user.discriminator, image: user.image });
- const s2 = db
- .insert(communityUserProfile)
- .values({ userId: botId, aboutMe: data.description })
- .onConflictDoUpdate({
- target: communityUserProfile.userId,
- set: { aboutMe: data.description },
- });
const results = (await db.batch([s1, s2] as any)) as any[];
- rows = Array.isArray(results?.[0]) ? results[0] : [];
+ const bindingRows = Array.isArray(results?.[0]) ? results[0] : [];
+ rows = Array.isArray(results?.[1]) ? results[1] : [];
+ if (bindingRows.length === 0) rows = [];
} else {
rows = await db
.update(user)
@@ -614,12 +616,12 @@ export async function updateBot(
let description = data.description ?? "";
if (data.description === undefined) {
- const profileRows = await db
- .select({ aboutMe: communityUserProfile.aboutMe })
- .from(communityUserProfile)
- .where(eq(communityUserProfile.userId, botId))
+ const bindingRows = await db
+ .select({ instruction: communityBotBinding.instruction })
+ .from(communityBotBinding)
+ .where(eq(communityBotBinding.userId, botId))
.limit(1);
- description = profileRows[0]?.aboutMe ?? "";
+ description = bindingRows[0]?.instruction ?? "";
}
return {
diff --git a/src/shared/src/index.ts b/src/shared/src/index.ts
index 0b4cba613..879260e6a 100644
--- a/src/shared/src/index.ts
+++ b/src/shared/src/index.ts
@@ -292,6 +292,7 @@ export {
CommunityAgentListFriendsSchema,
CommunityAgentAttachmentUploadResponseSchema,
CommunityAgentAttachmentDownloadRequestSchema,
+ CommunityAgentUpdateProfileRequestSchema,
BotAuditEventSchema,
BotAuditEventKindSchema,
AuditLogCliInvocationPayloadSchema,
@@ -437,6 +438,8 @@ export type {
ServerApi as CommunityCliServerApi,
FriendRequestResult,
FriendCard,
+ UpdateProfileRequest as CommunityCliUpdateProfileRequest,
+ UpdateProfileResult as CommunityCliUpdateProfileResult,
UnreadNotice,
HostCommand,
HostReadyRuntime,
diff --git a/src/shared/src/schemas.ts b/src/shared/src/schemas.ts
index 2a0090058..645cb11aa 100644
--- a/src/shared/src/schemas.ts
+++ b/src/shared/src/schemas.ts
@@ -1,7 +1,13 @@
import { z } from "zod";
import { IssueStatus, TASK_TYPES } from "./constants";
import { sanitizeSlug } from "./utils/slug";
-import { MAX_ATTACHMENTS_PER_MESSAGE, MAX_MESSAGE_CONTENT_LENGTH } from "./constants/community";
+import {
+ ALLOWED_ICON_MIME_TYPES,
+ MAX_ATTACHMENTS_PER_MESSAGE,
+ MAX_MESSAGE_CONTENT_LENGTH,
+ MAX_PROFILE_ABOUT_LENGTH,
+ MAX_SERVER_ICON_SIZE_BYTES,
+} from "./constants/community";
// ---------------------------------------------------------------------------
// Task status
@@ -1200,6 +1206,29 @@ export type CommunityAgentAttachmentDownloadRequest = z.infer<
typeof CommunityAgentAttachmentDownloadRequestSchema
>;
+export const CommunityAgentUpdateProfileRequestSchema = z
+ .object({
+ bio: z.string().max(MAX_PROFILE_ABOUT_LENGTH).optional(),
+ avatar: z
+ .object({
+ filename: z.string().min(1),
+ contentType: z.enum(ALLOWED_ICON_MIME_TYPES),
+ data: z.instanceof(Uint8Array)
+ .refine((value) => value.byteLength > 0, "avatar must not be empty")
+ .refine(
+ (value) => value.byteLength <= MAX_SERVER_ICON_SIZE_BYTES,
+ `avatar must be ≤ ${MAX_SERVER_ICON_SIZE_BYTES} bytes`,
+ ),
+ })
+ .optional(),
+ })
+ .refine((value) => value.bio !== undefined || value.avatar !== undefined, {
+ message: "bio or avatar is required",
+ });
+export type CommunityAgentUpdateProfileRequest = z.infer<
+ typeof CommunityAgentUpdateProfileRequestSchema
+>;
+
export const CommunityAgentInboxPullRequestSchema = z.object({
max: z.number().int().min(1).max(200).optional(),
});
diff --git a/src/shared/test/migrations/community-bot-instruction.test.ts b/src/shared/test/migrations/community-bot-instruction.test.ts
new file mode 100644
index 000000000..31f8d575c
--- /dev/null
+++ b/src/shared/test/migrations/community-bot-instruction.test.ts
@@ -0,0 +1,52 @@
+import Sqlite from "better-sqlite3";
+import { readFileSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it } from "vitest";
+
+const testDirectory = dirname(fileURLToPath(import.meta.url));
+const migrationPath = resolve(
+ testDirectory,
+ "../../../web/migrations/0086_community_bot_instruction.sql",
+);
+
+describe("0086 community bot instruction migration", () => {
+ let sqlite: Sqlite.Database | undefined;
+
+ afterEach(() => sqlite?.close());
+
+ it("preserves each existing public bio exactly and uses an empty fallback without a profile row", () => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.exec(`
+ CREATE TABLE community_bot_binding (
+ user_id TEXT PRIMARY KEY,
+ machine_id TEXT NOT NULL,
+ runtime TEXT NOT NULL,
+ model_name TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_user_profile (
+ user_id TEXT PRIMARY KEY,
+ about_me TEXT
+ );
+ `);
+
+ const exactBio = " Exact owner role\nwith spacing ";
+ sqlite.prepare(`
+ INSERT INTO community_bot_binding (user_id, machine_id, runtime, created_at)
+ VALUES (?, 'machine_1', 'codex', '2026-01-01'), (?, 'machine_2', 'codex', '2026-01-01')
+ `).run("bot_with_profile", "bot_without_profile");
+ sqlite.prepare(`
+ INSERT INTO community_user_profile (user_id, about_me) VALUES (?, ?)
+ `).run("bot_with_profile", exactBio);
+
+ sqlite.exec(readFileSync(migrationPath, "utf8"));
+
+ expect(sqlite.prepare(`
+ SELECT user_id, instruction FROM community_bot_binding ORDER BY user_id
+ `).all()).toEqual([
+ { user_id: "bot_with_profile", instruction: exactBio },
+ { user_id: "bot_without_profile", instruction: "" },
+ ]);
+ });
+});
diff --git a/src/shared/test/queries/community-bot-instruction.test.ts b/src/shared/test/queries/community-bot-instruction.test.ts
new file mode 100644
index 000000000..5ff6663e1
--- /dev/null
+++ b/src/shared/test/queries/community-bot-instruction.test.ts
@@ -0,0 +1,97 @@
+import Sqlite from "better-sqlite3";
+import { drizzle } from "drizzle-orm/better-sqlite3";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { updateBot } from "../../src/db/queries/community/bot";
+
+describe("bot owner instruction updates", () => {
+ let sqlite: Sqlite.Database;
+ let db: ReturnType<typeof drizzle>;
+
+ beforeEach(() => {
+ sqlite = new Sqlite(":memory:");
+ sqlite.exec(`
+ CREATE TABLE user (
+ id TEXT PRIMARY KEY,
+ name TEXT NOT NULL,
+ email TEXT NOT NULL UNIQUE,
+ emailVerified INTEGER,
+ image TEXT,
+ createdAt TEXT NOT NULL,
+ updatedAt TEXT NOT NULL,
+ isBot INTEGER NOT NULL DEFAULT 0,
+ ownerUserId TEXT,
+ deletedAt TEXT,
+ discriminator TEXT NOT NULL DEFAULT '0000',
+ lastRefreshContextAt TEXT
+ );
+ CREATE TABLE community_bot_binding (
+ user_id TEXT PRIMARY KEY,
+ machine_id TEXT NOT NULL,
+ runtime TEXT NOT NULL,
+ instruction TEXT NOT NULL DEFAULT '',
+ model_name TEXT,
+ created_at TEXT NOT NULL
+ );
+ CREATE TABLE community_user_profile (
+ user_id TEXT PRIMARY KEY,
+ about_me TEXT
+ );
+ `);
+ db = drizzle(sqlite);
+ (db as any).batch = (statements: Array<{ toSQL: () => { sql: string; params: unknown[] } }>) =>
+ sqlite.transaction(() => statements.map((statement) => {
+ const query = statement.toSQL();
+ const prepared = sqlite.prepare(query.sql);
+ return prepared.reader ? prepared.all(...query.params) : prepared.run(...query.params);
+ }))();
+ const insertUser = sqlite.prepare(`
+ INSERT INTO user
+ (id, name, email, createdAt, updatedAt, isBot, ownerUserId, discriminator)
+ VALUES (?, ?, ?, '2026-01-01', '2026-01-01', ?, ?, '0001')
+ `);
+ insertUser.run("owner_1", "Owner", "[email protected]", 0, null);
+ insertUser.run("owner_2", "Other", "[email protected]", 0, null);
+ insertUser.run("bot_1", "Bot", "[email protected]", 1, "owner_1");
+ sqlite.prepare(`
+ INSERT INTO community_bot_binding
+ (user_id, machine_id, runtime, instruction, created_at)
+ VALUES ('bot_1', 'machine_1', 'codex', 'owner role', '2026-01-01')
+ `).run();
+ sqlite.prepare(`
+ INSERT INTO community_user_profile (user_id, about_me)
+ VALUES ('bot_1', 'public bio')
+ `).run();
+ });
+
+ afterEach(() => sqlite.close());
+
+ it("updates owner-controlled instruction without rewriting public bio", async () => {
+ const result = await updateBot(db as never, "bot_1", "owner_1", { description: "new role" });
+ expect(result?.description).toBe("new role");
+ expect(sqlite.prepare("SELECT instruction FROM community_bot_binding WHERE user_id='bot_1'").get())
+ .toEqual({ instruction: "new role" });
+ expect(sqlite.prepare("SELECT about_me FROM community_user_profile WHERE user_id='bot_1'").get())
+ .toEqual({ about_me: "public bio" });
+ });
+
+ it("requires an owner-scoped binding before updating the user row", async () => {
+ sqlite.prepare("DELETE FROM community_bot_binding WHERE user_id='bot_1'").run();
+ const result = await updateBot(db as never, "bot_1", "owner_1", {
+ name: "Renamed",
+ description: "new role",
+ });
+ expect(result).toBeNull();
+ expect(sqlite.prepare("SELECT name FROM user WHERE id='bot_1'").get()).toEqual({ name: "Bot" });
+ });
+
+ it("keeps both statements owner-scoped", async () => {
+ const result = await updateBot(db as never, "bot_1", "owner_2", {
+ name: "Stolen",
+ description: "stolen role",
+ });
+ expect(result).toBeNull();
+ expect(sqlite.prepare("SELECT name FROM user WHERE id='bot_1'").get()).toEqual({ name: "Bot" });
+ expect(sqlite.prepare("SELECT instruction FROM community_bot_binding WHERE user_id='bot_1'").get())
+ .toEqual({ instruction: "owner role" });
+ });
+});
diff --git a/src/shared/test/queries/community-bot.test.ts b/src/shared/test/queries/community-bot.test.ts
index 4e67b68a1..e81ae21dd 100644
--- a/src/shared/test/queries/community-bot.test.ts
+++ b/src/shared/test/queries/community-bot.test.ts
@@ -91,6 +91,8 @@ describe("createBot", () => {
const botUser = userValues[0] as { id: string; discriminator: string }
expect(botUser.discriminator).toBe(computeDiscriminator(botUser.id))
expect(botUser.discriminator).toMatch(/^\d{4}$/)
+ expect(userValues[1]).toEqual(expect.objectContaining({ instruction: "does things" }))
+ expect(userValues[2]).toEqual(expect.objectContaining({ aboutMe: "does things" }))
expect(db.batch).toHaveBeenCalledOnce()
})
diff --git a/src/shared/test/schemas/community-agent-profile.test.ts b/src/shared/test/schemas/community-agent-profile.test.ts
new file mode 100644
index 000000000..9506148a9
--- /dev/null
+++ b/src/shared/test/schemas/community-agent-profile.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { CommunityAgentUpdateProfileRequestSchema } from "../../src/schemas";
+import { MAX_PROFILE_ABOUT_LENGTH, MAX_SERVER_ICON_SIZE_BYTES } from "../../src/constants/community";
+
+describe("CommunityAgentUpdateProfileRequestSchema", () => {
+ it("requires at least one update and accepts an empty bio clear", () => {
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({}).success).toBe(false);
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({ bio: "" }).success).toBe(true);
+ });
+
+ it("enforces the public bio limit", () => {
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({
+ bio: "x".repeat(MAX_PROFILE_ABOUT_LENGTH + 1),
+ }).success).toBe(false);
+ });
+
+ it("accepts supported non-empty avatar bytes and rejects empty, unsupported, and oversize data", () => {
+ const base = { filename: "avatar.png", contentType: "image/png" };
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({
+ avatar: { ...base, data: new Uint8Array([1]) },
+ }).success).toBe(true);
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({
+ avatar: { ...base, data: new Uint8Array() },
+ }).success).toBe(false);
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({
+ avatar: { ...base, contentType: "image/svg+xml", data: new Uint8Array([1]) },
+ }).success).toBe(false);
+ expect(CommunityAgentUpdateProfileRequestSchema.safeParse({
+ avatar: { ...base, data: new Uint8Array(MAX_SERVER_ICON_SIZE_BYTES + 1) },
+ }).success).toBe(false);
+ });
+});
diff --git a/src/web/migrations/0086_community_bot_instruction.sql b/src/web/migrations/0086_community_bot_instruction.sql
new file mode 100644
index 000000000..dacffb133
--- /dev/null
+++ b/src/web/migrations/0086_community_bot_instruction.sql
@@ -0,0 +1,11 @@
+ALTER TABLE community_bot_binding ADD COLUMN instruction TEXT NOT NULL DEFAULT '';
+
+UPDATE community_bot_binding
+SET instruction = COALESCE(
+ (
+ SELECT community_user_profile.about_me
+ FROM community_user_profile
+ WHERE community_user_profile.user_id = community_bot_binding.user_id
+ ),
+ ''
+);
diff --git a/src/web/src/app/api/community/users/me/avatar/route.test.ts b/src/web/src/app/api/community/users/me/avatar/route.test.ts
index 21c86816a..007a8a93e 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.test.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.test.ts
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach } from "vitest"
import { NextRequest } from "next/server"
const mockHandleUserAvatarUpload = vi.fn()
+const mockHandleBotAvatarUpload = vi.fn()
const mockUpdateUser = vi.fn()
vi.mock("@opennextjs/cloudflare", () => ({
@@ -24,18 +25,26 @@ vi.mock("@alook/shared", async () => {
vi.mock("@/lib/community/upload", () => ({
handleUserAvatarUpload: (...a: unknown[]) => mockHandleUserAvatarUpload(...a),
+ handleBotAvatarUpload: (...a: unknown[]) => mockHandleBotAvatarUpload(...a),
}))
let isAuthed = true
+let actorKind: "human" | "bot" = "human"
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
if (!isAuthed) {
const { NextResponse } = require("next/server")
return NextResponse.json({ error: "unauthorized" }, { status: 401 })
}
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: { DB: {} }, userId: "u1", email: "[email protected]", params })
+ return handler(req, {
+ env: { DB: {} },
+ actor: actorKind === "bot"
+ ? { kind: "bot", userId: "b1", ownerUserId: "u1", machineId: "m1" }
+ : { kind: "human", userId: "u1", email: "[email protected]" },
+ params,
+ })
}),
}))
@@ -57,6 +66,7 @@ describe("POST /api/community/users/me/avatar", () => {
beforeEach(() => {
vi.clearAllMocks()
isAuthed = true
+ actorKind = "human"
mockUpdateUser.mockResolvedValue(undefined)
})
@@ -96,4 +106,23 @@ describe("POST /api/community/users/me/avatar", () => {
expect(mockHandleUserAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "u1")
expect(mockUpdateUser).toHaveBeenCalledWith(expect.anything(), "u1", { image: "/api/community/users/u1/avatar" })
})
+
+ it("uses the bot avatar key and URL for a bot actor", async () => {
+ actorKind = "bot"
+ mockHandleBotAvatarUpload.mockResolvedValue({
+ ok: true,
+ id: "b1",
+ key: "bot-avatar/b1",
+ url: "/api/community/bots/b1/avatar",
+ filename: "bot.png",
+ contentType: "image/png",
+ size: 10,
+ })
+ const res = await POST(postReq(), {} as never)
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ url: "/api/community/bots/b1/avatar" })
+ expect(mockHandleBotAvatarUpload).toHaveBeenCalledWith(expect.anything(), expect.anything(), "b1")
+ expect(mockHandleUserAvatarUpload).not.toHaveBeenCalled()
+ expect(mockUpdateUser).toHaveBeenCalledWith(expect.anything(), "b1", { image: "/api/community/bots/b1/avatar" })
+ })
})
diff --git a/src/web/src/app/api/community/users/me/avatar/route.ts b/src/web/src/app/api/community/users/me/avatar/route.ts
index 617f0e592..c77361056 100644
--- a/src/web/src/app/api/community/users/me/avatar/route.ts
+++ b/src/web/src/app/api/community/users/me/avatar/route.ts
@@ -1,18 +1,21 @@
import { NextRequest } from "next/server"
import { queries } from "@alook/shared"
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON } from "@/lib/middleware/helpers"
import { getDb } from "@/lib/db"
-import { handleUserAvatarUpload } from "@/lib/community/upload"
-import { userAvatarUrl } from "@/lib/community/storage"
+import { handleBotAvatarUpload, handleUserAvatarUpload } from "@/lib/community/upload"
+import { botAvatarUrl, userAvatarUrl } from "@/lib/community/storage"
-export const POST = withAuth(async (req: NextRequest, ctx) => {
- const result = await handleUserAvatarUpload(req, ctx.env, ctx.userId)
+export const POST = withCommunityActor(async (req: NextRequest, ctx) => {
+ const userId = ctx.actor.userId
+ const result = ctx.actor.kind === "bot"
+ ? await handleBotAvatarUpload(req, ctx.env, userId)
+ : await handleUserAvatarUpload(req, ctx.env, userId)
if (!result.ok) return result.response
const db = getDb(ctx.env.DB)
- const url = userAvatarUrl(ctx.userId)
- await queries.user.updateUser(db, ctx.userId, { image: url })
+ const url = ctx.actor.kind === "bot" ? botAvatarUrl(userId) : userAvatarUrl(userId)
+ await queries.user.updateUser(db, userId, { image: url })
return writeJSON({ url })
})
diff --git a/src/web/src/app/api/community/users/me/profile/route.test.ts b/src/web/src/app/api/community/users/me/profile/route.test.ts
index 661eacaa5..4ffb8667b 100644
--- a/src/web/src/app/api/community/users/me/profile/route.test.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.test.ts
@@ -9,6 +9,7 @@ const getMemberships = vi.fn()
const authApiUpdateUser = vi.fn()
const fanOutToServerMembers = vi.fn()
const fanOutStatusUpdate = vi.fn()
+let actorKind: "human" | "bot" = "human"
vi.mock("@opennextjs/cloudflare", () => ({
getCloudflareContext: vi.fn(() => ({ env: { DB: {} } })),
@@ -47,10 +48,16 @@ vi.mock("@alook/shared", async () => {
}
})
-vi.mock("@/lib/middleware/auth", () => ({
- withAuth: vi.fn((handler: any) => async (req: any, ctx?: any) => {
+vi.mock("@/lib/middleware/community-actor", () => ({
+ withCommunityActor: vi.fn((handler: any) => async (req: any, ctx?: any) => {
const params = ctx?.params instanceof Promise ? await ctx.params : ctx?.params
- return handler(req, { env: {}, userId: "u1", email: "[email protected]", params })
+ return handler(req, {
+ env: {},
+ actor: actorKind === "bot"
+ ? { kind: "bot", userId: "b1", ownerUserId: "u1", machineId: "m1" }
+ : { kind: "human", userId: "u1", email: "[email protected]" },
+ params,
+ })
}),
}))
@@ -75,6 +82,7 @@ function patchReq(body: unknown) {
describe("GET /api/community/users/me/profile", () => {
beforeEach(() => {
vi.clearAllMocks()
+ actorKind = "human"
getUser.mockResolvedValue({ id: "u1", discriminator: "4242" })
})
@@ -120,6 +128,7 @@ describe("GET /api/community/users/me/profile", () => {
describe("PATCH /api/community/users/me/profile", () => {
beforeEach(() => {
vi.clearAllMocks()
+ actorKind = "human"
authApiUpdateUser.mockResolvedValue({ headers: new Headers() })
listMemberServerIds.mockResolvedValue([])
getMemberships.mockResolvedValue([])
@@ -298,4 +307,24 @@ describe("PATCH /api/community/users/me/profile", () => {
expect(res.status).toBe(200)
expect(fanOutStatusUpdate).toHaveBeenCalledWith("u1", "🎧", "Vibing")
})
+
+ it("allows a bot to update only its own public bio", async () => {
+ actorKind = "bot"
+ const res = await PATCH(patchReq({ aboutMe: "bot bio" }), {} as never)
+ expect(res.status).toBe(200)
+ expect(updateProfile).toHaveBeenCalledWith({}, "b1", { aboutMe: "bot bio" })
+ expect(authApiUpdateUser).not.toHaveBeenCalled()
+ expect(fanOutStatusUpdate).not.toHaveBeenCalled()
+ })
+
+ it.each(["name", "bannerColor", "statusEmoji", "statusText"])(
+ "returns 403 when a bot supplies forbidden field %s",
+ async (field) => {
+ actorKind = "bot"
+ const res = await PATCH(patchReq({ [field]: "blocked" }), {} as never)
+ expect(res.status).toBe(403)
+ expect(updateProfile).not.toHaveBeenCalled()
+ expect(authApiUpdateUser).not.toHaveBeenCalled()
+ },
+ )
})
diff --git a/src/web/src/app/api/community/users/me/profile/route.ts b/src/web/src/app/api/community/users/me/profile/route.ts
index 363cebed8..0f72f53d7 100644
--- a/src/web/src/app/api/community/users/me/profile/route.ts
+++ b/src/web/src/app/api/community/users/me/profile/route.ts
@@ -11,19 +11,20 @@ import {
} from "@alook/shared"
import { getDb } from "@/lib/db"
import { createAuth } from "@/lib/auth"
-import { withAuth } from "@/lib/middleware/auth"
+import { withCommunityActor } from "@/lib/middleware/community-actor"
import { writeJSON, writeError } from "@/lib/middleware/helpers"
import { fanOutStatusUpdate, fanOutToServerMembers } from "@/lib/community/fanout"
-export const GET = withAuth(async (_req, ctx) => {
+export const GET = withCommunityActor(async (_req, ctx) => {
const db = getDb(ctx.env.DB)
+ const userId = ctx.actor.userId
const [profile, viewer] = await Promise.all([
withD1Retry(
- () => queries.communityUserProfile.getProfile(db, ctx.userId),
+ () => queries.communityUserProfile.getProfile(db, userId),
{ route: "community/profile:self-profile" }
),
withD1Retry(
- () => queries.user.getUserSelf(db, ctx.userId),
+ () => queries.user.getUserSelf(db, userId),
{ route: "community/profile:self-user" }
),
])
@@ -36,8 +37,9 @@ export const GET = withAuth(async (_req, ctx) => {
})
})
-export const PATCH = withAuth(async (req: NextRequest, ctx) => {
+export const PATCH = withCommunityActor(async (req: NextRequest, ctx) => {
const db = getDb(ctx.env.DB)
+ const userId = ctx.actor.userId
let body: {
name?: string
@@ -52,6 +54,13 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
return writeError("invalid request body", 400)
}
+ if (ctx.actor.kind === "bot") {
+ const forbidden = ["name", "bannerColor", "statusEmoji", "statusText"] as const
+ if (forbidden.some((field) => body[field] !== undefined)) {
+ return writeError("forbidden: bots may only update aboutMe", 403)
+ }
+ }
+
if (
body.aboutMe === undefined &&
body.bannerColor === undefined &&
@@ -67,7 +76,7 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// final response (see the return below).
let renameCookieHeaders: Headers | undefined
- if (body.name !== undefined) {
+ if (body.name !== undefined && ctx.actor.kind === "human") {
if (typeof body.name !== "string") return writeError("name must be a string", 400)
const trimmed = body.name.trim()
// Rejects empty, over-length, and names with `#`/`@`/line breaks — the last
@@ -93,15 +102,15 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
// Broadcast the new name to every server the user belongs to, so open
// member lists update without a refresh (previously nothing fired
// MEMBER_UPDATE for a self-rename — only role changes did).
- const serverIds = await queries.communityMember.listMemberServerIds(db, ctx.userId)
+ const serverIds = await queries.communityMember.listMemberServerIds(db, userId)
if (serverIds.length > 0) {
- const memberships = await queries.communityMember.getMemberships(db, ctx.userId, serverIds)
+ const memberships = await queries.communityMember.getMemberships(db, userId, serverIds)
for (const membership of memberships) {
fanOutToServerMembers(membership.serverId, {
type: WS_EVENTS.MEMBER_UPDATE,
serverId: membership.serverId,
memberId: membership.id,
- userId: ctx.userId,
+ userId,
changes: { nickname: trimmed },
})
}
@@ -168,14 +177,14 @@ export const PATCH = withAuth(async (req: NextRequest, ctx) => {
data.statusEmoji !== undefined ||
data.statusText !== undefined
) {
- updated = await queries.communityUserProfile.updateProfile(db, ctx.userId, data)
+ updated = await queries.communityUserProfile.updateProfile(db, userId, data)
}
// Fan out only when a status field was actually part of this patch — a
// plain aboutMe-only save must not trigger a broadcast.
if (data.statusEmoji !== undefined || data.statusText !== undefined) {
await fanOutStatusUpdate(
- ctx.userId,
+ userId,
updated?.statusEmoji ?? null,
updated?.statusText ?? null,
)