Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## Unreleased

- Pinned conversations are saved on the account, so every app shows the same pins in the same order. The session returns them as `pinnedConversations`, `update-user` saves the whole list (up to nine `agent:<id>` or `group:<id>` keys), and `/v1/events` sends a `pins` event to the account's open apps when they change. On the web, pin or unpin a bot chat or group chat from its **More** menu in the sidebar, and drag pins in the **Pinned** section to reorder them.
- Bots may stay quiet after automations. A scheduled or event automation, and a succeeded script automation's result, tell the bot it can react with 👍 instead of replying when the run found nothing the owner needs, unless the automation asks for a message every time. A reaction sends no notification. Results of failed, timed-out, and interrupted script runs don't carry the note.
- Push notifications wait at least three seconds after enqueue and are suppressed on every device when the reply was seen or its bot or group chat is active in a focused web tab. Request cards count as seen only after their content loads and appears in the viewport. Browser notifications and unread counters are unchanged.
- Breaking: independent chat views and explicit reply acknowledgements replace the device-presence endpoint. Existing Apple and Android clients still register for and receive pushes, but must adopt the new attention API before their foreground chats suppress pushes on other devices.
Expand Down
19 changes: 10 additions & 9 deletions apps/docs/content/clients/web.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,16 @@ Sign in with the account you created when you

## Sidebar

| Section | What's there |
| --------------- | ----------------------------------------------------------------------------------------------------------------------------------------- |
| **Bots** | Each bot's chat, with its jobs and desktop. |
| **Group chats** | Chats with several bots. |
| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. |
| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. |
| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. |
| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. |
| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. |
| Section | What's there |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Pinned** | Up to nine bot chats and group chats. Pin or unpin one from its **More** menu, and drag pins to reorder them. Your other apps show the same pins. |
| **Bots** | Each bot's chat, with its jobs and desktop. |
| **Group chats** | Chats with several bots. |
| **Memory** | Every bot's memories and your shared memories. Edit or delete them here. |
| **Automations** | Every automation with its schedule, next run, and status, plus a **Runs** tab with recent runs. |
| **Activity** | Everything bots did, by day. Filter by kind or bot, and revert a change to a skill or memory. |
| **Theme** | System, Light, or Dark. The choice is saved to your account, so your other devices use it too. |
| **Settings** | Providers, web search, credentials, logins, the judge and vision models, MCP integrations, skills, notifications, passkeys, and sign-out. |

Press `⌘K`, or `Ctrl+K`, or select **Search** in the sidebar to open the
command palette. It jumps to a bot, group chat, workspace page, or settings
Expand Down
14 changes: 14 additions & 0 deletions apps/server/src/app/api.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -737,6 +737,20 @@ describe("HTTP API for bots, chats, and activity", () => {
);
});

test("/v1/events sends pins as their own event", async () => {
const { app, service } = setup();

const response: Response = await req(app, "/v1/events");
const reader = response.body!.getReader();
service.announce({ type: "pins", pinnedConversations: ["group:g1"] });
const text = await readUntil(reader, '"group:g1"');
expect(text).toContain(
'event: pins\ndata: {"pinnedConversations":["group:g1"]}',
);
expect(text).not.toContain('event: activity\ndata: {"type":"pins"');
await reader.cancel();
});

test("streams server-wide activity", async () => {
const { app } = setup();

Expand Down
133 changes: 133 additions & 0 deletions apps/server/src/app/auth.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,136 @@ test("closed sign-up needs an open invite, which works once", async () => {
accounts.close();
}
});

const ORIGIN = "http://localhost:7337";

/** Calls an auth endpoint as a client does: over HTTP, with the account's bearer token. */
const authRequest = (
accounts: Awaited<ReturnType<typeof createAuth>>,
token: string,
path: string,
body?: unknown,
) =>
accounts.auth.handler(
new Request(`${ORIGIN}/api/auth/${path}`, {
method: body === undefined ? "GET" : "POST",
headers: {
authorization: `Bearer ${token}`,
"content-type": "application/json",
origin: ORIGIN,
},
body: body === undefined ? null : JSON.stringify(body),
}),
);

const pinsOf = async (
accounts: Awaited<ReturnType<typeof createAuth>>,
token: string,
) => {
const session = (await (
await authRequest(accounts, token, "get-session")
).json()) as { user: { pinnedConversations?: unknown } };

return session.user.pinnedConversations;
};

test("a new account has no pins", async () => {
const accounts = await createAuth(
mkdtempSync(join(tmpdir(), "auth-")),
ORIGIN,
);

try {
const { token } = await signUp(accounts, "pins@example.com");

expect(await pinsOf(accounts, token!)).toEqual([]);
} finally {
accounts.close();
}
});

test("saves pins in order", async () => {
const accounts = await createAuth(
mkdtempSync(join(tmpdir(), "auth-")),
ORIGIN,
);

try {
const { token } = await signUp(accounts, "pins@example.com");
const saved = await authRequest(accounts, token!, "update-user", {
pinnedConversations: ["group:g1", "agent:b1"],
});

expect(saved.status).toBe(200);
expect(await pinsOf(accounts, token!)).toEqual(["group:g1", "agent:b1"]);
} finally {
accounts.close();
}
});

test("rejects more than nine pins, duplicates, and malformed keys", async () => {
const accounts = await createAuth(
mkdtempSync(join(tmpdir(), "auth-")),
ORIGIN,
);

try {
const { token } = await signUp(accounts, "pins@example.com");
await authRequest(accounts, token!, "update-user", {
pinnedConversations: ["agent:kept"],
});
const tooMany = Array.from({ length: 10 }, (_, index) => `agent:${index}`);

for (const pinnedConversations of [
tooMany,
["agent:a", "agent:a"],
["bot:a"],
]) {
const response = await authRequest(accounts, token!, "update-user", {
pinnedConversations,
});

expect(response.status).toBe(400);
}
expect(await pinsOf(accounts, token!)).toEqual(["agent:kept"]);
} finally {
accounts.close();
}
});

test("updating pins tells the account's listener", async () => {
const calls: [string, string[]][] = [];
const accounts = await createAuth(
mkdtempSync(join(tmpdir(), "auth-")),
ORIGIN,
{ onPinsChanged: (userId, pins) => calls.push([userId, pins]) },
);

try {
const { token, user } = await signUp(accounts, "pins@example.com");
await authRequest(accounts, token!, "update-user", {
pinnedConversations: ["agent:b1"],
});

expect(calls).toEqual([[user.id, ["agent:b1"]]]);
} finally {
accounts.close();
}
});

test("an account from before pins reads as no pins", async () => {
const dataDir = mkdtempSync(join(tmpdir(), "auth-"));
const accounts = await createAuth(dataDir, ORIGIN);

try {
const { token } = await signUp(accounts, "older@example.com");
// Accounts made before the column existed have NULL there, not the default.
const database = new Database(join(dataDir, "auth.sqlite"));
database.run('update user set "pinnedConversations" = NULL');
database.close();

expect(await pinsOf(accounts, token!)).toEqual([]);
} finally {
accounts.close();
}
});
48 changes: 43 additions & 5 deletions apps/server/src/app/auth.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { z } from "@hono/zod-openapi";
import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { randomBytes, randomUUID } from "node:crypto";
import { join } from "node:path";
Expand All @@ -19,7 +20,10 @@ import { getMigrations } from "better-auth/db/migration";
import { eq } from "drizzle-orm";
import { drizzle } from "drizzle-orm/bun-sqlite";
import { authUsers } from "./auth-schema";
import { userPreferenceFields } from "../contract/user-preferences";
import {
pinnedConversations,
userPreferenceFields,
} from "../contract/user-preferences";
import { INVITE_HEADER, invites, type Invites } from "./invites";
import {
serverSettingsStore,
Expand Down Expand Up @@ -117,9 +121,38 @@ function signUpGate() {

type SignUpGate = ReturnType<typeof signUpGate>;

const userDatabaseHooks = (gate: SignUpGate) =>
/** What the server does when an account changes, beyond saving it. */
export type AccountHooks = {
/** Every saved account update, with the pins it now has: a theme change reports unchanged pins. */
onPinsChanged?: (userId: string, pins: string[]) => void;
};

/** The pins on a saved user row: Better Auth hands hooks the stored JSON text, not the array. */
const storedPins = z
.string()
.transform((text, context) => {
try {
return pinnedConversations.parse(JSON.parse(text));
} catch {
context.addIssue({ code: "custom", message: "Unreadable pins" });

return z.NEVER;
}
})
.or(pinnedConversations)
.catch([]);

const userDatabaseHooks = (gate: SignUpGate, hooks: AccountHooks) =>
({
user: {
update: {
async after(user) {
hooks.onPinsChanged?.(
user.id,
storedPins.parse(user["pinnedConversations"]),
);
},
},
create: {
// Every way to create a user passes here: the gate for closed sign-up and the first admin.
async before(user, context) {
Expand Down Expand Up @@ -209,6 +242,7 @@ function authOptions(
baseURL: string,
secretPath: string,
gate: SignUpGate,
hooks: AccountHooks,
) {
const passkeyOrigin = passkeyOriginFor(baseURL);

Expand All @@ -222,7 +256,7 @@ function authOptions(
session: { cookieCache: { enabled: false } },
rateLimit: { enabled: true, storage: "database" },
user: { additionalFields: userPreferenceFields },
databaseHooks: userDatabaseHooks(gate),
databaseHooks: userDatabaseHooks(gate, hooks),
plugins: [
bearer(),
admin(),
Expand All @@ -237,7 +271,11 @@ function authOptions(
} satisfies BetterAuthOptions;
}

export async function createAuth(dataDir: string, baseURL: string) {
export async function createAuth(
dataDir: string,
baseURL: string,
hooks: AccountHooks = {},
) {
const secretPath = join(dataDir, ".auth-secret");

if (!existsSync(secretPath))
Expand All @@ -249,7 +287,7 @@ export async function createAuth(dataDir: string, baseURL: string) {
const database = new Database(join(dataDir, "auth.sqlite"));
database.run("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;");
const gate = signUpGate();
const options = authOptions(database, baseURL, secretPath, gate);
const options = authOptions(database, baseURL, secretPath, gate, hooks);

try {
const { runMigrations } = await getMigrations(options);
Expand Down
62 changes: 62 additions & 0 deletions apps/server/src/app/multi-user.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -731,3 +731,65 @@ test.serial(
}
},
);

/** Reads a stream until `text` arrives or `ms` pass, and returns what it saw. */
async function readFor(
reader: ReadableStreamDefaultReader<Uint8Array>,
text: string,
ms: number,
) {
const decoder = new TextDecoder();
const deadline = Date.now() + ms;
let seen = "";

while (!seen.includes(text) && Date.now() < deadline) {
const next = await Promise.race([
reader.read(),
Bun.sleep(deadline - Date.now()).then(() => undefined),
]);

if (!next || next.done) break;
seen += decoder.decode(next.value, { stream: true });
}

return seen;
}

test.serial("pins reach only their own account", async () => {
const dataDir = mkdtempSync(join(tmpdir(), "crumble-multi-user-"));
let running: Awaited<ReturnType<typeof startServer>> | undefined;

try {
running = await startServer({ dataDir, port: 0 });
const first = await signUp(running, `first-${crypto.randomUUID()}`);
const second = await signUp(running, `second-${crypto.randomUUID()}`);
const open = async (headers: Record<string, string>) =>
(
await fetch(new URL("/v1/events", running!.server.url), { headers })
).body!.getReader();
const firstEvents = await open(first);
const secondEvents = await open(second);

const saved = await fetch(
new URL("/api/auth/update-user", running.server.url),
{
method: "POST",
headers: { ...json(first), origin: running.server.url.origin },
body: JSON.stringify({ pinnedConversations: ["agent:b1"] }),
},
);

expect(saved.status).toBe(200);
const firstSaw = await readFor(firstEvents, '"agent:b1"', 5_000);
expect(firstSaw).toContain("event: pins");
expect(firstSaw).toContain('{"pinnedConversations":["agent:b1"]}');
expect(await readFor(secondEvents, "event: pins", 1_000)).not.toContain(
"event: pins",
);
await firstEvents.cancel();
await secondEvents.cancel();
} finally {
await running?.close();
rmSync(dataDir, { recursive: true, force: true });
}
});
11 changes: 10 additions & 1 deletion apps/server/src/app/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,13 @@ function tenantPool(pool: {
rmSync(accountDir(dataDir, userId), { recursive: true, force: true });
},
restore: (accounts: Accounts) => restoreTenants(dataDir, accounts, tenant),
/** Only an account that is running has streams to tell; this never starts one. */
announcePins: (userId: string, pins: string[]) => {
void tenants
.get(userId)
?.then((context) => context.announcePins(pins))
.catch(() => {});
},
outdatedWorkspaces: () => outdatedWorkspaces(tenants),
close: () => closeTenants(tenants.values()),
};
Expand Down Expand Up @@ -408,7 +415,9 @@ async function connectAccounts(
dataDir: string,
origin: string,
) {
state.identity = await createAuth(dataDir, origin);
state.identity = await createAuth(dataDir, origin, {
onPinsChanged: pool.announcePins,
});
state.admin = adminAPI({
accounts: state.identity,
origin: () => origin,
Expand Down
4 changes: 4 additions & 0 deletions apps/server/src/app/tenant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,8 @@ export type TenantRuntime = {
workspaces: Workspaces | undefined;
/** Deletes every bot's workspace, for an account being removed. A failure is logged, so it never rejects. */
removeWorkspaces: () => Promise<void>;
/** Tells the account's open /v1/events streams that its pinned conversations changed. */
announcePins: (pins: string[]) => void;
close: () => Promise<void>;
};

Expand Down Expand Up @@ -431,6 +433,8 @@ export async function createTenant(
workspaces,
removeWorkspaces: () =>
account.runPromise(removeAccountWorkspaces(workspaces)),
announcePins: (pins) =>
service.announce({ type: "pins", pinnedConversations: pins }),
close: () => account.dispose(),
};
}),
Expand Down
Loading
Loading