Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(rooms): let people point at a member's page in a room

AdityaUmaleab3c185cbe33
diff --git a/docs/verification/room-pages.md b/docs/verification/room-pages.md
index 0db0291fe5..e8341d0b32 100644
--- a/docs/verification/room-pages.md
+++ b/docs/verification/room-pages.md
@@ -23,7 +23,7 @@ share a room whose lead is Pepper.
that gate reports the app, and its row is Basil's.
- `GET /api/threads/<room>/messages/<id>/app` answers both with `room: true` and `can` with `message`,
`modelContext`, `serverTools` and `serverResources` off.
-- Both rows are live in the room, the page with Full screen but without Point or Share.
+- Both rows are live in the room, the page with Full screen and Point (a pick goes to the bot that made the page) but without Share.
- A real mouse click on the page's send button makes the page report that `send()` resolved (it grows to 300px; a
refusal would leave it at 240px), and a click on the board's "Paint it red" is answered by the host with the room's
refusal. The renderer makes no request but GETs meanwhile, the room gains no message and no app row gains context,
@@ -32,7 +32,7 @@ share a room whose lead is Pepper.
Evidence (with `OMB_UI_EVIDENCE_DIR`): `room-pages-shown.png`, `room-pages-clicked-send.png`,
`room-pages-clicked-app.png` and `room-pages.json` (the rows, the page document's head, the requests and the console).
-What it looks like when the recipe passes: both rows in the room, the page without Point or Share
+What it looks like when the recipe passes: both rows in the room, the page without Share
(`evidence/room-pages/shown.png`); the page after a real click on its send button, which resolved and posted nothing
(`evidence/room-pages/clicked-send.png`); and the board after a click on "Paint it red", answered by the host with the
room's refusal (`evidence/room-pages/clicked-app.png`).
diff --git a/scripts/testing/room-pages-ui.e2e.test.ts b/scripts/testing/room-pages-ui.e2e.test.ts
index 8cdd9505dc..f60219950b 100644
--- a/scripts/testing/room-pages-ui.e2e.test.ts
+++ b/scripts/testing/room-pages-ui.e2e.test.ts
@@ -153,10 +153,10 @@ async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 3
expect(pageDoc).toMatchObject({ room: true, can: { message: false, modelContext: false, serverTools: false, openLinks: true } });
expect(await api("GET", `/api/threads/${room.threadId}/messages/${boardRow.id}/app`)).toMatchObject({ room: true, can: { serverTools: false, serverResources: false, message: false } });
- // Both rows render in the room for the person, view-only: no Point and no Share on the page.
+ // Both rows render in the room for the person, view-only: Point (its pick goes to the page's bot), no Share.
const live = (id: string) => `[data-app="${id}"][data-app-room][data-app-state="live"] iframe[data-app-frame]`;
await until(() => evaluate(`Boolean(document.querySelector('${live(pageId)}') && document.querySelector('${live(boardRow.id)}'))`), "both frames to go live", 30_000);
- expect(await evaluate(`[...document.querySelectorAll('[data-app="${pageId}"] button')].map((b) => b.textContent.trim()).filter((t) => t === "Point" || t === "Share")`)).toEqual([]);
+ expect(await evaluate(`[...document.querySelectorAll('[data-app="${pageId}"] button')].map((b) => b.textContent.trim()).filter((t) => t === "Point" || t === "Share")`)).toEqual(["Point"]);
expect(await evaluate(`Boolean([...document.querySelectorAll('[data-app="${pageId}"] button')].find((b) => b.getAttribute("aria-label") === "Full screen"))`)).toBe(true);
mkdirSync(evidenceDir, { recursive: true });
diff --git a/server/channel-queue.ts b/server/channel-queue.ts
index 7d036bf23f..d8319247ba 100644
--- a/server/channel-queue.ts
+++ b/server/channel-queue.ts
@@ -6,6 +6,7 @@ import { chatFollowups, saveChatFollowup, settleChatFollowups } from "./message-
import { drainCoalesceHead, DRAIN_COALESCE_MAX_ITEMS } from "./admission.ts";
import type { ResolvedSender } from "../shared/wire.ts";
import type { UsageTrigger } from "./usage-ledger.ts";
+import type { RoomPick } from "./room-pointed.ts";
export interface ChannelQueueItem {
id: string;
@@ -19,6 +20,8 @@ export interface ChannelQueueItem {
reaction?: string;
/** Bot ids picked from the @ list; the turn that drains this line reads its @names with them. */
mentions?: string[];
+ /** What the person pointed at in a member's page; only that page's bot reads it. */
+ pointed?: RoomPick;
queuedAt: number;
}
@@ -65,6 +68,7 @@ export function queueChannelMessage(
trigger?: UsageTrigger;
reaction?: string;
mentions?: string[];
+ pointed?: RoomPick;
} = {},
): QueuedChannelMessage {
const entry = queues.get(threadId) ?? { groupId, items: [] };
@@ -80,6 +84,7 @@ export function queueChannelMessage(
trigger: options.trigger,
...(options.reaction ? { reaction: options.reaction } : {}),
...(options.mentions?.length ? { mentions: options.mentions } : {}),
+ ...(options.pointed ? { pointed: options.pointed } : {}),
queuedAt: Date.now(),
};
saveChatFollowup({ id: item.id, kind: "channel", ownerId: groupId, threadId, payload: item });
@@ -208,6 +213,7 @@ export function headChannelGroup(items: readonly ChannelQueueItem[]): ChannelQue
function coalesceIdentity(item: ChannelQueueItem): string {
if (item.via === "api") return `api:${item.id}`;
if (item.mode !== "chat") return `mode:${item.mode}:${item.id}`;
+ if (item.pointed) return `pointed:${item.id}`;
if (item.sender) return `person:${item.sender.id ?? item.sender.name}`;
return "person:local";
}
diff --git a/server/index.ts b/server/index.ts
index ac1f293fef..2402b88b9d 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -262,7 +262,7 @@ import {
drainChannelMessages,
restoreChannelMessages,
type ChannelQueueItem,
-} from "./channel-queue.ts";
+} from "./channel-queue.ts"; import { copyRoomPick, pointedResponders, takeRoomPick, type RoomPick } from "./room-pointed.ts";
import {
acceptedSendMatch,
sendFingerprint,
@@ -3525,7 +3525,7 @@ type GroupTurnOperation = {
line?: RoomRoundLine;
/** The person's room line this run answers (its member turns, mentions included, act for whoever wrote it), or the handed-on work it does. */
requestMessageId?: string; handedFor?: HandedRun;
- goalRun?: LiveGoalRun;
+ goalRun?: LiveGoalRun; /** What the person pointed at in a member's page; taken once by the page's bot (takeRoomPick). */ pick?: RoomPick;
};
// Wider than busyBotId (setup and queued responders too), so polling clients never mistake a handoff for completion.
@@ -10319,13 +10319,13 @@ async function runClaimedGroupMemberTurn(
}
if (roomReset || displaced) broadcast({ kind: "group", group: publicGroupState(store.group(groupId) ?? group) });
const roomShareNote = skillsHost.shareNote(bot, threadId, Boolean(workspace));
- const clock = turnClockLine(Date.now(), hostTimeZone());
+ const clock = turnClockLine(Date.now(), hostTimeZone()), roomPick = cardContinuation ? "" : takeRoomPick(operation, readyBot.id);
const roomToolScope = toolScopeForTurn(readyBot.id), roomUserMcp = claudeUserMcpEnabled(cfg) && !managedPolicy.restrictsMcp();
const roomSession = roomSessions.dispatch({
threadId, botId: readyBot.id, claimId: internalGeneration, instance, guestConfined: roomGuestConfined, reset: Boolean(roomReset), hooks: Boolean(integrations.hooks),
context: () => ({ ...roomMemberContexts.forThread(threadId)?.[readyBot.id], compactAt: nativeCompactTokens(instance) }),
config: [roomSystem.stable, cwd, readyBot.modelSelection, turnApprovalMode, roomToolScope, roomUserMcp, integrations],
- window: roomWindow, tail: roomTail, wrap: (body) => withTurnClock(clock, withRecalled(roomRecalled, attachmentsForBox(body, cwd) + roomShareNote.text + devsReports.note(threadId, Boolean(integrations.agents)))),
+ window: roomWindow, tail: roomTail, wrap: (body) => withTurnClock(clock, withRecalled(roomRecalled, roomPick + attachmentsForBox(body, cwd) + roomShareNote.text + devsReports.note(threadId, Boolean(integrations.agents)))),
});
guardTurnDispatch(roomShareNote.after(instance.adapter.sendTurn({
...roomSession.send,
@@ -10727,7 +10727,7 @@ type StartGroupTurnOptions = {
via?: "api";
sender?: ResolvedSender;
trigger?: UsageTrigger;
- queuedGroup?: ChannelQueueItem[];
+ queuedGroup?: ChannelQueueItem[]; /** What the person pointed at in a member's page: the page's bot reads it on its turn, and the line shows the chips. */ pointed?: RoomPick;
};
function startGroupTurn(
@@ -10787,7 +10787,7 @@ function startGroupTurn(
channelMode: item.mode,
queueId: item.id,
via: item.via,
- sender: item.sender,
+ sender: item.sender, ...(item.pointed ? { pointed: item.pointed.refs } : {}),
});
}
const last = queuedGroup[queuedGroup.length - 1]!;
@@ -10801,7 +10801,7 @@ function startGroupTurn(
channelMode: last.mode,
queueId: last.id,
via: last.via,
- sender: last.sender,
+ sender: last.sender, ...(last.pointed ? { pointed: last.pointed.refs } : {}),
});
})()
: store.appendMessage(threadId, {
@@ -10814,7 +10814,7 @@ function startGroupTurn(
channelMode,
queueId,
via: options.via,
- sender: options.sender,
+ sender: options.sender, ...(options.pointed ? { pointed: options.pointed.refs } : {}),
});
if (options.trigger) turnTriggers.set(threadId, options.trigger);
const titled = group.dm ? null : store.titleGroupTaskFromFirstMessage(group.id, text, threadId);
@@ -10832,7 +10832,8 @@ function startGroupTurn(
},
});
}
- let responders = roomResponders(text, members, group.defaultResponder, options.mentions);
+ const pageBots = channelMode === "chat" ? pointedResponders(options.pointed, availableMembers, () => roomResponders(text, availableMembers, { kind: "mentions" }, options.mentions)) : [];
+ let responders = pageBots.length ? pageBots : roomResponders(text, members, group.defaultResponder, options.mentions);
if (!group.dm) {
const addressed = stopWordPlacement(text) === "adjacent" ? undefined : message.id;
for (const held of responders.filter(isHeld)) noteHeldSkip(group.id, threadId, held, addressed);
@@ -10850,7 +10851,7 @@ function startGroupTurn(
responders = last ? [last] : [];
}
// Auto's responders are a fallback until the decision model answers; the append and the return stay synchronous.
- const autoRoute = autoCandidate && !goalCoordinator && routableMembers.length > 1 &&
+ const autoRoute = autoCandidate && !goalCoordinator && !pageBots.length && routableMembers.length > 1 &&
roomResponders(text, availableMembers, { kind: "mentions" }, options.mentions).length === 0;
if (!responders.length && !goalCoordinator && !autoRoute) {
@@ -10900,9 +10901,8 @@ function startGroupTurn(
signal: operation.cancellation.signal,
})
: null;
- if (queuedGroup && queuedGroup.length > 0) {
- operation.queuedQueueIds = queuedGroup.map((item) => item.id);
- }
+ if (queuedGroup?.length) operation.queuedQueueIds = queuedGroup.map((item) => item.id);
+ if (options.pointed && !goalCoordinator) operation.pick = copyRoomPick(options.pointed);
if (goalCoordinator) {
operation.goalRun = goalCards.start(threadId, goalCoordinator, text, options.goalRunId?.trim() || `goal-${Date.now().toString(36)}-${randomUUID()}`);
}
@@ -11010,7 +11010,7 @@ function drainQueuedChannelSendsNow(): void {
threadId,
sender: head.sender,
trigger: queuedTurnTrigger({ trigger: head.trigger, sender: head.sender }),
- queuedGroup: items, mentions: items.flatMap((item) => item.mentions ?? []),
+ queuedGroup: items, mentions: items.flatMap((item) => item.mentions ?? []), pointed: items.find((item) => item.pointed)?.pointed,
});
} catch (error) {
for (const item of items) {
diff --git a/server/room-pages-point.e2e.test.ts b/server/room-pages-point.e2e.test.ts
new file mode 100644
index 0000000000..bc2a030677
--- /dev/null
+++ b/server/room-pages-point.e2e.test.ts
@@ -0,0 +1,73 @@
+// End-to-end on the fakes: in a room, the person points at part of a member's page and the pick goes to the bot that
+// made the page, as records in that bot's turn only. No model is called and no external service is reached.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { afterAll, beforeAll, expect, it } from "vitest";
+import { launchVerificationServer, runControlOmb } from "../scripts/control-omb.ts";
+
+let fixture: Awaited<ReturnType<typeof launchVerificationServer>>;
+
+beforeAll(async () => {
+ fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, undefined, { scripted: true });
+}, 90_000);
+afterAll(async () => {
+ await fixture?.close();
+});
+
+it("sends a pick on a room page to the bot that made it, and to no other member", async () => {
+ const cli = (...args: string[]) => runControlOmb(args, { env: { OPENMAUSBOT_URL: fixture.info.url } }) as Promise<any>;
+ const api = async (path: string, body?: unknown) => {
+ const response = await fetch(`${fixture.info.url}${path}`, {
+ method: body === undefined ? "GET" : "POST", headers: { "content-type": "application/json" },
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
+ });
+ return { status: response.status, body: await response.json() as any };
+ };
+ const planPath = join(fixture.info.dataDir, "room-plan.json");
+ const designer = (await cli("new-bot", "--name", "Designer")).bot;
+ const helper = (await cli("new-bot", "--name", "Helper")).bot;
+ const evidence = (botId: string) => (existsSync(`${planPath}.evidence.jsonl`) ? readFileSync(`${planPath}.evidence.jsonl`, "utf8").trim().split("\n").filter(Boolean) : [])
+ .map((line) => JSON.parse(line)).filter((entry: any) => entry.botId === botId && entry.prompt !== undefined);
+ const plan = (steps: Array<{ tool: string; arguments: unknown }>) =>
+ writeFileSync(planPath, JSON.stringify({ [designer.id]: { steps, reply: "Done." }, [helper.id]: { steps: [], reply: "Done." } }));
+ const settled = async (botId: string) => expect((await cli("wait", "--bot", botId, "--timeout", "30")).status).toBe("settled");
+ // Helper answers the room by default, so only the pick can send the next line to Designer.
+ const created = await api("/api/groups", {
+ name: "Design room", memberIds: [designer.id, helper.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: helper.id } },
+ });
+ expect(created.status, JSON.stringify(created.body)).toBeLessThan(300);
+ const group = created.body.group;
+ const transcript = async () => (await api(`/api/threads/${group.threadId}/messages?limit=50`)).body.messages as any[];
+
+ plan([{ tool: "show_html", arguments: { html: "<main><button>Go</button></main>", title: "Launch" } }]);
+ expect((await api(`/api/groups/${group.id}/messages`, { text: "@Designer make a launch page", mentions: [designer.id] })).status).toBe(202);
+ await expect.poll(async () => (await transcript()).find((message) => message.kind === "app")?.id, { timeout: 30_000 }).toBeTruthy();
+ await settled(designer.id);
+ const page = (await transcript()).find((message) => message.kind === "app");
+ expect(page).toMatchObject({ from: { botId: designer.id }, app: { source: "html", title: "Launch" } });
+
+ plan([]);
+ const designerTurns = evidence(designer.id).length, helperTurns = evidence(helper.id).length;
+ const pointed = { appId: page.id, rev: 0, tag: "button", role: "", text: "Go", selector: "main > button", html: "<button>Go</button>" };
+ const sent = await api(`/api/groups/${group.id}/messages`, { text: "Make this one bigger", pointed: [pointed] });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ expect(sent.body.message).toMatchObject({ role: "user", text: "Make this one bigger", pointed: [{ appId: page.id }] });
+ await expect.poll(() => evidence(designer.id).length, { timeout: 30_000 }).toBe(designerTurns + 1);
+ await settled(designer.id);
+ const prompt = JSON.stringify(evidence(designer.id).at(-1).prompt);
+ expect(prompt).toContain("While writing this message the person pointed at parts of your page.");
+ expect(prompt).toContain(`Page app_id \\"${page.id}\\" (now version 1); the person was looking at version 1.`);
+ expect(prompt).toContain("1. <button>; text: Go; selector: main > button; html: <button>Go</button>");
+ expect(evidence(helper.id).length).toBe(helperTurns);
+
+ // A plain line still goes to the room's default responder, and carries no pick.
+ expect((await api(`/api/groups/${group.id}/messages`, { text: "Thanks" })).status).toBe(202);
+ await expect.poll(() => evidence(helper.id).length, { timeout: 30_000 }).toBe(helperTurns + 1);
+ await settled(helper.id);
+ expect(JSON.stringify(evidence(helper.id).at(-1).prompt)).not.toContain("pointed at parts of your page");
+ expect(evidence(designer.id).length).toBe(designerTurns + 1);
+
+ // A pick must name a page in this room, and a goal is a plain typed line.
+ expect((await api(`/api/groups/${group.id}/messages`, { text: "This", pointed: [{ ...pointed, appId: "not-a-page" }] })).status).toBe(404);
+ expect((await api(`/api/groups/${group.id}/messages`, { text: "This", mode: "goal", pointed: [pointed] })).status).toBe(400);
+}, 120_000);
diff --git a/server/room-pointed.test.ts b/server/room-pointed.test.ts
new file mode 100644
index 0000000000..ad4d9eb53a
--- /dev/null
+++ b/server/room-pointed.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it } from "vitest";
+import { copyRoomPick, pointedResponders, roomPickBots, takeRoomPick, type RoomPick } from "./room-pointed.ts";
+
+const pick = (blocks: Record<string, string>): RoomPick => ({ refs: [{ appId: "app-1", label: "Go" }], blocks });
+
+describe("room picks", () => {
+ it("gives each bot the records of its own pages once, and nothing to another member", () => {
+ const holder = { pick: pick({ designer: "A", writer: "B" }) };
+ expect(roomPickBots(holder.pick)).toEqual(["designer", "writer"]);
+ expect(takeRoomPick(holder, "helper")).toBe("");
+ expect(takeRoomPick(holder, "designer")).toBe("A");
+ expect(takeRoomPick(holder, "designer")).toBe("");
+ expect(takeRoomPick(holder, "writer")).toBe("B");
+ expect(takeRoomPick(undefined, "designer")).toBe("");
+ expect(takeRoomPick({}, "designer")).toBe("");
+ expect(roomPickBots(undefined)).toEqual([]);
+ });
+
+ it("works on a copy, so taking a part leaves the queued line's pick whole", () => {
+ const queued = pick({ designer: "A" });
+ const run = { pick: copyRoomPick(queued) };
+ expect(takeRoomPick(run, "designer")).toBe("A");
+ expect(queued.blocks).toEqual({ designer: "A" });
+ });
+
+ it("sends the line to the page's bot first, then anyone named, and to no hidden member", () => {
+ const designer = { id: "designer" }, helper = { id: "helper" }, writer = { id: "writer", hidden: true };
+ const members = [helper, designer, writer];
+ expect(pointedResponders(pick({ designer: "A" }), members, () => [helper, designer])).toEqual([designer, helper]);
+ expect(pointedResponders(pick({ writer: "B" }), members, () => [helper])).toEqual([]);
+ expect(pointedResponders(undefined, members, () => [helper])).toEqual([]);
+ });
+});
diff --git a/server/room-pointed.ts b/server/room-pointed.ts
new file mode 100644
index 0000000000..e741cddfb3
--- /dev/null
+++ b/server/room-pointed.ts
@@ -0,0 +1,55 @@
+// Pointing in a room: the person points at parts of a member's page, and the pick goes to the bot that made the
+// page. Each bot reads only the parts of its own pages; everyone in the room sees the chips on the message.
+import type { AppPointedRef } from "../shared/app.ts";
+import { appRow } from "./chat-apps.ts";
+import type { AgentCardStore } from "./chat-widgets.ts";
+import { preparePointed, type Pointed } from "./pointed.ts";
+import { userError } from "./user-errors.ts";
+
+/** refs: the chips on the line; blocks: by bot id, the records of that bot's own pages. */
+export type RoomPick = { refs: AppPointedRef[]; blocks: Record<string, string> };
+
+export function prepareRoomPointed(store: Pick<AgentCardStore, "messagesFor">, threadId: string, value: unknown): { ok: true; pick: RoomPick } | Extract<Pointed, { ok: false }> | null {
+ const pointed = preparePointed(store, threadId, value);
+ if (!pointed || !pointed.ok) return pointed;
+ // Valid now, so value is the list of parts; each bot gets the records of its own pages only.
+ const byBot = new Map<string, unknown[]>();
+ for (const part of value as Array<{ appId: string }>) {
+ const botId = appRow(store, threadId, part.appId)?.from?.botId;
+ // A room page always names the bot that showed it; one without has nobody to read the pick.
+ if (!botId) return { ok: false, status: 404, ...userError("serverError.page.notHere") };
+ byBot.set(botId, [...(byBot.get(botId) ?? []), part]);
+ }
+ const blocks: Record<string, string> = {};
+ for (const [botId, parts] of byBot) {
+ const own = byBot.size === 1 ? pointed : preparePointed(store, threadId, parts);
+ if (!own?.ok) return own ?? { ok: false, status: 404, ...userError("serverError.page.notHere") };
+ blocks[botId] = own.block;
+ }
+ return { ok: true, pick: { refs: pointed.refs, blocks } };
+}
+
+export function roomPickBots(pick: RoomPick | undefined): string[] {
+ return pick ? Object.keys(pick.blocks) : [];
+}
+
+/** A line that points at a member's page goes to that member first, with anyone the person named too; none otherwise. */
+export function pointedResponders<T extends { id: string; hidden?: boolean }>(pick: RoomPick | undefined, members: T[], named: () => T[]): T[] {
+ const ids = roomPickBots(pick);
+ const pageBots = members.filter((member) => !member.hidden && ids.includes(member.id));
+ return pageBots.length ? [...pageBots, ...named().filter((member) => !pageBots.includes(member))] : [];
+}
+
+/** Each turn takes its own bot's part out of the pick, so a run works on a copy and the queued line keeps its own. */
+export function copyRoomPick(pick: RoomPick): RoomPick {
+ return { ...pick, blocks: { ...pick.blocks } };
+}
+
+/** The pick text for this bot's turn, once: the bot that made the page reads it on its first turn, no one else does. */
+export function takeRoomPick(holder: { pick?: RoomPick } | undefined, botId: string): string {
+ const blocks = holder?.pick?.blocks;
+ if (!blocks || !Object.hasOwn(blocks, botId)) return "";
+ const block = blocks[botId]!;
+ delete blocks[botId];
+ return block;
+}
diff --git a/server/routes/channels.ts b/server/routes/channels.ts
index abb2511692..5185e2295e 100644
--- a/server/routes/channels.ts
+++ b/server/routes/channels.ts
@@ -17,6 +17,8 @@ import { DATA_DIR, type AppConfig } from "../config.ts";
import type { ProviderInstance, SteerOutcome } from "../contracts.ts";
import { cancelledChatFollowup } from "../message-db.ts";
import { messageTextRefusal } from "../message-text.ts";
+import { prepareRoomPointed, roomPickBots, type RoomPick } from "../room-pointed.ts";
+import { refusalBody } from "../user-errors.ts";
import type { PhoneSecretSubmissionRegistry } from "../phone-secret.ts";
import { promptWithReply, type PersonName } from "../replies.ts";
import { clientGroupPatchViolation, requestSource, type RequestAuth } from "../request-auth.ts";
@@ -92,7 +94,7 @@ export interface ChannelRouteDeps {
sendId: string | undefined,
channelMode: "chat" | "goal",
queueId: undefined,
- options: { via?: "api"; sender?: ResolvedSender; trigger?: UsageTrigger; threadId?: string; mentions?: string[] },
+ options: { via?: "api"; sender?: ResolvedSender; trigger?: UsageTrigger; threadId?: string; mentions?: string[]; pointed?: RoomPick },
): Message;
applyRoomHoldsFromMessage(groupId: string, text: string, mentions?: readonly string[]): void;
cancelGroupTurnOperations(groupId: string, threadId: string): void;
@@ -354,6 +356,15 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
if (!ownsThread) {
return json(res, 409, { error: "the channel switched tasks before it could receive the message" });
}
+ // What the person pointed at in a member's page: only a typed chat line carries it, and it goes to the page's bot.
+ const pointing = body.pointed !== undefined && body.pointed !== null;
+ if (pointing && channelMode === "goal") return json(res, 400, { error: "a goal is a plain typed message" });
+ const pointed = pointing ? prepareRoomPointed(store, threadId, body.pointed) : null;
+ if (pointed && !pointed.ok) return json(res, pointed.status, refusalBody(pointed));
+ const pick = pointed?.pick;
+ if (pick && !roomPickBots(pick).some((id) => group.memberIds.includes(id) && store.bot(id))) {
+ return json(res, 409, { error: "the bot that made this page is no longer in this room" });
+ }
const sendId = parseSendId(body.sendId);
const replyTo = resolveReplyTarget(threadId, body.replyToId);
// A bot's shell is a loopback caller too: with no paired session and no browser origin the message
@@ -417,10 +428,11 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
sender: messageSender(auth),
trigger,
mentions,
+ ...(pick ? { pointed: pick } : {}),
});
return { ok: true as const, queued: true as const, queueId: queued.id, threadId };
}
- const message = startGroupTurn(current.id, text, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId, mentions });
+ const message = startGroupTurn(current.id, text, replyTo, sendId, channelMode, undefined, { via, sender: messageSender(auth), trigger, threadId, mentions, ...(pick ? { pointed: pick } : {}) });
return { ok: true as const, threadId, message };
},
);
@@ -488,7 +500,7 @@ export function createChannelRoutes(deps: ChannelRouteDeps): RouteHandler {
restoreHeldChannelQueue(held);
return json(res, 409, { error: "only the first queued message can steer" });
}
- if (decision.action === "queue" || !steerInput) {
+ if (decision.action === "queue" || !steerInput || headGroup.some((item) => item.pointed)) {
restoreHeldChannelQueue(held);
return json(res, 200, {
ok: true,
diff --git a/src/components/Composer.tsx b/src/components/Composer.tsx
index fba649d23f..62a13e004b 100644
--- a/src/components/Composer.tsx
+++ b/src/components/Composer.tsx
@@ -573,6 +573,7 @@ export function Composer({
channelMode: effectiveChannelMode, mentions: picks.ids(body), followUp,
};
if (group) {
+ const points = effectiveChannelMode === "goal" ? null : takePointedChips(threadId);
dispatch({
type: "sendGroup",
groupId: group.id,
@@ -581,7 +582,8 @@ export function Composer({
replyToId: replyTo?.id,
threadId,
mode: effectiveChannelMode, mentions: sentDraft.mentions,
- onError: () => restoreDraft(sentDraft),
+ ...(points ? { pointed: points.pointed } : {}),
+ onError: () => { points?.restore(); restoreDraft(sentDraft); },
});
roomMessageSent(effectiveChannelMode, busy);
} else if (bot) {
@@ -733,7 +735,7 @@ export function Composer({
/>
</div>
)}
- {!group && <PointedChips threadId={threadId} />}{!group && bot && <SetupRequestChip bot={bot} threadId={threadId} />}
+ <PointedChips threadId={threadId} />{!group && bot && <SetupRequestChip bot={bot} threadId={threadId} />}
<ComposerAttachments
items={attachments}
onAdd={addAttachments}
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 95d00c643d..620f793dea 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -88,7 +88,7 @@ import { citationPreviewText, splitTranscriptCitations, type CitationAttachment
import { highlightCitationSource } from "@/lib/citations-dom";
import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";
import { pendingApprovals } from "./PendingApproval";
-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { RoomRichRow } from "./RichMessageRow";
+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { RoomRichRow, UserLineNote } from "./RichMessageRow";
import { TranscriptAnnouncer } from "./TranscriptAnnouncer";
import { dayLabel, localDay } from "@/lib/transcript-derivations";
import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";
@@ -247,7 +247,7 @@ function RoomTextMessage({
data-citation-thread={group.threadId}
>
<ThreadRefText text={display} peers={peers} everyone={!group.dm} />
- </div>{m.bugReport && <BugReportNote report={m.bugReport} />}
+ </div>{m.bugReport ? <BugReportNote report={m.bugReport} /> : m.pointed?.length ? <UserLineNote message={m} /> : null}
{cited && <SentCitations
citations={cited.citations}
onNavigate={async (citation: CitationAttachment) => {
diff --git a/src/components/app/AppMessage.test.ts b/src/components/app/AppMessage.test.ts
index cddaa09b4b..dbda3612f2 100644
--- a/src/components/app/AppMessage.test.ts
+++ b/src/components/app/AppMessage.test.ts
@@ -212,13 +212,13 @@ describe("a bot's page", () => {
expect(frame().style.height).toBe("333px");
});
- it("in a room, shows the page to everyone with Full screen but no Point or Share, and sends nothing for anyone", async () => {
+ it("in a room, shows the page to everyone with Full screen and Point but no Share, and the page sends nothing for anyone", async () => {
fetchMock.mockImplementation(async (path) => /\/app(\?|$)/.test(path) ? json(200, botHtmlDocument({ messageId: "a1", rev: 0, html: counter.html, room: true })) : json(202, { ok: true }));
await mount(row(htmlPayload()), true);
expect(find("[data-app]")!.hasAttribute("data-app-room")).toBe(true);
expect(frame().getAttribute("sandbox")).toBe("allow-scripts allow-forms");
expect(frame().getAttribute("srcdoc")).toContain("var room = true;");
- expect(button("Point")).toBeUndefined();
+ expect(button("Point")).toBeTruthy();
expect(button("Share")).toBeUndefined();
expect(button("Full screen")).toBeTruthy();
await handshake();
diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsx
index 3279acadac..1c997edc8a 100644
--- a/src/components/app/PageTools.tsx
+++ b/src/components/app/PageTools.tsx
@@ -205,7 +205,7 @@ export interface PageToolsProps {
ready: boolean;
/** pane: the page opens in the chat's page pane, beside a usable message box, instead of covering the window. */
fullScreen: { open: boolean; toggle(): void; pane?: boolean };
- /** Shown in a room: view-only, so no Point and no Share. */
+ /** Shown in a room: the page acts for nobody, so no Share; Point sends the pick to the bot that made the page. */
room?: boolean;
pin?: ReturnType<typeof usePagePin>;
}
@@ -226,11 +226,11 @@ export function PageToolbar({ version, point, share, save, ready, fullScreen, ro
{version.flash && <span role="status" data-page-updated className="ms-1 rounded-full bg-accent/15 px-2 py-px font-medium text-accent-text">{t("chat.preview.updated")}</span>}
</div>
<div className="ms-auto flex flex-wrap items-center gap-1">
+ <button type="button" aria-pressed={point.pointing} onClick={point.toggle} disabled={!ready} title={t("chat.preview.pointHint")}
+ className={cn(ASK_CHIP, point.pointing ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>
+ <Crosshair size={14} />{t("chat.preview.point")}
+ </button>
{!room && <>
- <button type="button" aria-pressed={point.pointing} onClick={point.toggle} disabled={!ready} title={t("chat.preview.pointHint")}
- className={cn(ASK_CHIP, point.pointing ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>
- <Crosshair size={14} />{t("chat.preview.point")}
- </button>
<button type="button" onClick={() => void share.run(version.rev)} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>
{busy ? <Loader2 size={14} className="animate-spin" /> : <Share2 size={14} />}{t("chat.preview.share")}
</button>
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 170f816fc4..e9f8b3bcf4 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -662,7 +662,7 @@ export type Action =
sendId?: string;
replyToId?: string;
threadId?: string;
- mode?: "chat" | "goal"; mentions?: string[];
+ mode?: "chat" | "goal"; mentions?: string[]; pointed?: import("../../shared/app-frame/point").PointedElement[];
onError?: () => void;
}
| {
@@ -2665,7 +2665,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {
replyToId: action.replyToId,
threadId,
sendId,
- mode: action.mode ?? "chat", ...(action.mentions?.length ? { mentions: action.mentions } : {}),
+ mode: action.mode ?? "chat", ...(action.mentions?.length ? { mentions: action.mentions } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}),
}),
}))
.then((body) => {