Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Every click on a bot's message lands in its thread, on desktop as on the phone
milind-soni8e636860374c
diff --git a/docs/verification/threads.md b/docs/verification/threads.mdindex 7a4e9bd01e..81960ed67b 100644--- a/docs/verification/threads.md+++ b/docs/verification/threads.md@@ -70,7 +70,12 @@ switching and Stop can be exercised without a real provider or account.sibling has its own activity entry under that bot. Follow a notification,a thread chip or a search hit to a third thread of that bot: the siblingkeeps its unread entry, and the third thread is read once open. An- `openmausbot://bot/<id>` link opens the main thread.+ `openmausbot://bot/<id>` link opens the main thread. A row or tile with a+ mark on it opens the thread the mark is about (waiting on you, then unread,+ then work under way, a thread another bot opened included); a second click+ returns to the main thread. In Simple mode **Active Threads** appears beside+ Search while anything is active and lists what the phone's Updates sheet+ lists.13. Stop a running job through its activity entry while a sibling is queued;verify only the chosen job stops and the queued message starts normally.Reload and confirm Show threads remains off. Turn it back on to recoverdiff --git a/electron/desktop-notifications.d.mts b/electron/desktop-notifications.d.mtsnew file mode 100644index 0000000000..25d8c55e1e--- /dev/null+++ b/electron/desktop-notifications.d.mts@@ -0,0 +1,17 @@+export interface DesktopNotificationNote {+ title: string;+ body: string;+ tag?: string;+ silent?: boolean;+ /** The bot's picture, on the page's own origin. */+ picture?: string;+ botId: string;+ threadId: string;+}++export interface DesktopNotificationsBridge {+ /** Resolves false when main shows nothing (no system support, or not this window's page): the page shows its own. */+ show(note: DesktopNotificationNote): Promise<boolean>;+ /** A click on one of them brought this page up: open that thread. */+ onOpen(cb: (target: { botId: string; threadId: string }) => void): () => void;+}diff --git a/electron/desktop-notifications.mjs b/electron/desktop-notifications.mjsnew file mode 100644index 0000000000..087799e655--- /dev/null+++ b/electron/desktop-notifications.mjs@@ -0,0 +1,95 @@+// A bot's notification on the desktop app, shown by main. A page's own `new Notification` dies with the page: Electron 43+// hands its click to the page that made it, so a banner clicked after a reload, an update or a move to another place does+// nothing, and `window.focus()` from a page never raises a window (shell/browser/api/electron_api_browser_window.cc,+// OnActivateContents). Main knows which page asked, so the click comes back to that place whatever is on screen by then.++const ID = /^[\w-]{1,128}$/;+const TEXT_LIMIT = 1024;+/** A click waits this long for its place to open (a Cloud may have to wake), and no longer: opening that place hours later+ * must not jump to an old banner's thread. */+const PLACE_WAIT_MS = 2 * 60_000;+const ICON_WAIT_MS = 1_500;++const text = (value) => (typeof value === "string" ? value.slice(0, TEXT_LIMIT) : "");+const originOf = (url) => { try { return new URL(url).origin; } catch { return null; } };++/**+ * @param {{ ipcMain: { handle(channel: string, handler: (event: any, note: any) => unknown): void },+ * Notification: { new(options: object): any, isSupported(): boolean },+ * nativeImage: { createFromBuffer(buffer: Buffer): { isEmpty(): boolean } },+ * fetch: (url: string, init: { signal: AbortSignal }) => Promise<{ ok: boolean, arrayBuffer(): Promise<ArrayBuffer> }>,+ * window: () => any,+ * mayNotify: (contents: unknown, url: string) => boolean,+ * reveal: () => void,+ * openPlace: (origin: string) => unknown,+ * now?: () => number }} deps+ * `window`: the main window, if any. `mayNotify`: the same rule that lets its page use `new Notification`. `reveal`: raises+ * the window. `openPlace`: main's own switch to the place at an origin.+ */+export function installDesktopNotifications({ ipcMain, Notification, nativeImage, fetch, window, mayNotify, reveal, openPlace, now = Date.now }) {+ // Electron drops a notification's handlers once nothing holds it, so each is held until it is replaced or dismissed.+ const live = new Map();+ let waiting = null;++ const page = () => { const win = window(); return win && !win.isDestroyed() ? win.webContents : null; };+ /** The origin of the page on screen, null while one is loading. */+ const shownOrigin = () => { const contents = page(); return contents && !contents.isLoadingMainFrame() ? originOf(contents.getURL()) : null; };+ /** The window's own page may ask, in its main frame: never the rail, a viewer or a frame inside a page. */+ const askingOrigin = (event) => {+ const contents = page(), frame = event.senderFrame;+ return contents && event.sender === contents && frame === contents.mainFrame && mayNotify(contents, frame.url) ? originOf(frame.url) : null;+ };+ const open = (target) => page()?.send("desktop-notifications:open", target);++ const bring = (origin, target) => {+ reveal();+ const shown = shownOrigin();+ if (shown === origin) { waiting = null; open(target); return; }+ waiting = { origin, target, at: now(), asked: shown !== null };+ if (waiting.asked) void openPlace(origin);+ };++ const pictureOf = async (origin, raw) => {+ if (typeof raw !== "string" || !raw) return null;+ try {+ const url = new URL(raw, origin);+ if (url.origin !== origin) return null;+ const answer = await fetch(url.href, { signal: AbortSignal.timeout(ICON_WAIT_MS) });+ if (!answer.ok) return null;+ const image = nativeImage.createFromBuffer(Buffer.from(await answer.arrayBuffer()));+ return image.isEmpty() ? null : image;+ } catch { return null; }+ };++ ipcMain.handle("desktop-notifications:show", async (event, note) => {+ const origin = askingOrigin(event);+ if (!origin || !Notification.isSupported() || !note || typeof note !== "object") return false;+ const { title, body, tag, silent, picture, botId, threadId } = note;+ if (!text(title) || !ID.test(String(botId)) || !ID.test(String(threadId))) return false;+ const key = `${origin}\n${text(tag) || threadId}`;+ const image = await pictureOf(origin, picture);+ const shown = new Notification({ title: text(title), body: text(body), silent: silent === true, ...(image ? { icon: image } : {}) });+ const replaced = live.get(key);+ live.set(key, shown);+ replaced?.close();+ shown.on("close", () => { if (live.get(key) === shown) live.delete(key); });+ shown.on("click", () => { if (live.get(key) === shown) live.delete(key); bring(origin, { botId, threadId }); });+ shown.show();+ return true;+ });++ return {+ /** The window finished loading a page: a click that was waiting for this place lands now. */+ arrived() {+ if (!waiting) return;+ if (now() - waiting.at > PLACE_WAIT_MS) { waiting = null; return; }+ if (shownOrigin() !== waiting.origin) {+ if (!waiting.asked) { waiting.asked = true; void openPlace(waiting.origin); }+ return;+ }+ const { target } = waiting;+ waiting = null;+ open(target);+ },+ };+}diff --git a/electron/desktop-notifications.node-test.mjs b/electron/desktop-notifications.node-test.mjsnew file mode 100644index 0000000000..02380a52ee--- /dev/null+++ b/electron/desktop-notifications.node-test.mjs@@ -0,0 +1,186 @@+import assert from "node:assert/strict";+import { EventEmitter } from "node:events";+import { readFileSync } from "node:fs";+import { createRequire } from "node:module";+import test from "node:test";++import { installDesktopNotifications } from "./desktop-notifications.mjs";++const CLOUD = "https://studio.example.com", COMPUTER = "http://127.0.0.1:8799";+const NOTE = { title: "Scout resumed", body: "Results in", tag: "openmausbot:scout", botId: "scout", threadId: "work-thread" };++function world({ shown = CLOUD, supported = true, mayNotify = true, picture = async () => null } = {}) {+ const banners = [], log = [];+ class Banner extends EventEmitter {+ closed = false;+ constructor(options) { super(); this.options = options; banners.push(this); }+ show() { log.push("show"); }+ close() { this.closed = true; this.emit("close"); }+ static isSupported() { return supported; }+ }+ const at = { shown, now: 1_000 };+ const mainFrame = { url: `${shown}/` };+ const webContents = {+ mainFrame, isLoadingMainFrame: () => at.shown === null, getURL: () => `${at.shown}/somewhere`,+ send: (channel, target) => { assert.equal(channel, "desktop-notifications:open"); log.push(`open ${target.botId}/${target.threadId}`); },+ };+ let handler = null;+ const asked = [];+ const installed = installDesktopNotifications({+ ipcMain: { handle: (channel, run) => { assert.equal(channel, "desktop-notifications:show"); handler = run; } },+ Notification: Banner,+ nativeImage: { createFromBuffer: (buffer) => ({ isEmpty: () => buffer.length === 0, bytes: buffer.length }) },+ fetch: async (url) => { asked.push(url); const body = await picture(url); return { ok: body !== null, arrayBuffer: async () => new TextEncoder().encode(body ?? "").buffer }; },+ window: () => ({ isDestroyed: () => false, webContents }), mayNotify: () => mayNotify,+ reveal: () => log.push("reveal"), openPlace: (origin) => log.push(`place ${origin}`), now: () => at.now,+ });+ const fromPage = { sender: webContents, senderFrame: mainFrame };+ return { ...installed, at, banners, log, asked, fromPage, webContents, show: (note = NOTE, event = fromPage) => handler(event, note) };+}++test("a click with the place on screen raises the window and opens the thread", async () => {+ const w = world();+ assert.equal(await w.show(), true);+ w.banners[0].emit("click");+ assert.deepEqual(w.log, ["show", "reveal", "open scout/work-thread"]);+});++test("a click after the page reloaded still lands: main holds the banner, not the page that asked", async () => {+ const w = world();+ await w.show();+ w.at.shown = null;+ w.banners[0].emit("click");+ assert.deepEqual(w.log, ["show", "reveal"], "still loading: nothing is sent to a page on its way out, and the load is left alone");+ w.at.shown = CLOUD;+ w.arrived();+ assert.deepEqual(w.log, ["show", "reveal", "open scout/work-thread"]);+});++test("a click while another place loads asks for the banner's place once that page is up", async () => {+ const w = world();+ await w.show();+ w.at.shown = null;+ w.banners[0].emit("click");+ w.at.shown = COMPUTER;+ w.arrived();+ w.arrived();+ assert.deepEqual(w.log, ["show", "reveal", `place ${CLOUD}`]);+ w.at.shown = CLOUD;+ w.arrived();+ assert.equal(w.log.at(-1), "open scout/work-thread");+});++test("a click with another place on screen opens that place, then the thread there, and never tells the other page", async () => {+ const w = world();+ await w.show();+ w.at.shown = COMPUTER;+ w.banners[0].emit("click");+ assert.deepEqual(w.log, ["show", "reveal", `place ${CLOUD}`]);+ w.arrived();+ assert.equal(w.log.includes("open scout/work-thread"), false, "this computer's page has no such thread");+ w.at.shown = CLOUD;+ w.arrived();+ assert.equal(w.log.at(-1), "open scout/work-thread");+ w.arrived();+ assert.equal(w.log.filter((line) => line === "open scout/work-thread").length, 1, "once");+});++test("a place that took too long does not jump to an old banner's thread when opened later", async () => {+ const w = world();+ await w.show();+ w.at.shown = COMPUTER;+ w.banners[0].emit("click");+ w.at.now += 2 * 60_000 + 1;+ w.at.shown = CLOUD;+ w.arrived();+ assert.equal(w.log.some((line) => line.startsWith("open ")), false);+});++test("a later click replaces the one still waiting for its place", async () => {+ const w = world();+ await w.show();+ await w.show({ ...NOTE, tag: "openmausbot:atlas", botId: "atlas", threadId: "atlas-thread" });+ w.at.shown = COMPUTER;+ w.banners[0].emit("click");+ w.banners[1].emit("click");+ w.at.shown = CLOUD;+ w.arrived();+ assert.deepEqual(w.log.filter((line) => line.startsWith("open ")), ["open atlas/atlas-thread"]);+});++test("only the window's own page may ask, in its main frame, and only where it may notify", async () => {+ const w = world();+ assert.equal(await w.show(NOTE, { sender: {}, senderFrame: w.webContents.mainFrame }), false, "the rail or a viewer");+ assert.equal(await w.show(NOTE, { sender: w.webContents, senderFrame: { url: `${CLOUD}/frame` } }), false, "a frame inside the page");+ assert.equal(w.banners.length, 0);+ const refused = world({ mayNotify: false });+ assert.equal(await refused.show(), false, "a place the permission rule refuses");+ assert.equal(refused.banners.length, 0);+});++test("with no system support the page is told, and shows its own", async () => {+ const w = world({ supported: false });+ assert.equal(await w.show(), false);+ assert.equal(w.banners.length, 0);+});++test("refuses a note that names no thread to open", async () => {+ const w = world();+ for (const note of [null, "text", { ...NOTE, threadId: "../../etc" }, { ...NOTE, botId: "" }, { ...NOTE, title: "" }]) assert.equal(await w.show(note), false);+ assert.equal(w.banners.length, 0);+});++test("one banner per tag, as a page's tag does; the one replaced no longer opens anything", async () => {+ const w = world();+ await w.show();+ await w.show({ ...NOTE, threadId: "newer-thread" });+ assert.equal(w.banners[0].closed, true);+ assert.equal(w.banners[1].closed, false);+ w.banners[1].emit("click");+ assert.equal(w.log.at(-1), "open scout/newer-thread");+});++test("a bot's picture comes only from the page's own origin, and a failed one still shows the banner", async () => {+ const w = world({ picture: async (url) => { if (url.includes("broken")) throw new Error("nope"); return url.includes("missing") ? null : "png-bytes"; } });+ await w.show({ ...NOTE, picture: "/api/attachments/face.png" });+ assert.equal(w.banners[0].options.icon.bytes, "png-bytes".length);+ assert.deepEqual(w.asked, [`${CLOUD}/api/attachments/face.png`]);+ await w.show({ ...NOTE, tag: "a", picture: "https://elsewhere.example.com/track.png" });+ assert.equal(w.asked.length, 1, "never fetches another origin");+ assert.equal(w.banners[1].options.icon, undefined);+ for (const [tag, picture] of [["b", "/broken.png"], ["c", "/missing.png"]]) {+ assert.equal(await w.show({ ...NOTE, tag, picture }), true);+ assert.equal(w.banners.at(-1).options.icon, undefined);+ }+});++test("main opens a thread only from the window's own load, and a page gets the bridge whatever server it comes from", () => {+ const source = (name) => readFileSync(new URL(name, import.meta.url), "utf8");+ assert.match(source("./main.mjs"), /did-stop-loading", \(\) => \{[^}]*desktopNotifications\.arrived\(\)/);+ assert.match(source("./preload.cjs"), /const REMOTE_SAFE = new Set\(\[[^\]]*"desktopNotifications"/);+});++test("the bridge asks main, and holds a click that comes back before the page has listened", async () => {+ const require = createRequire(import.meta.url);+ const channels = new Map(), invoked = [];+ let api = null;+ const electron = require.resolve("electron");+ const held = require.cache[electron];+ require.cache[electron] = { id: electron, filename: electron, loaded: true, exports: {+ ipcRenderer: { on: (channel, run) => channels.set(channel, run), removeListener: () => undefined, invoke: async (...args) => { invoked.push(args); return true; }, send: () => undefined, sendSync: () => undefined },+ contextBridge: { exposeInMainWorld: (_name, exposed) => { api = exposed; } }, webUtils: { getPathForFile: () => "" },+ } };+ const preload = require.resolve("./preload.cjs");+ delete require.cache[preload];+ try { require(preload); } finally { if (held) require.cache[electron] = held; else delete require.cache[electron]; delete require.cache[preload]; }+ assert.equal(await api.desktopNotifications.show(NOTE), true);+ assert.deepEqual(invoked.at(-1), ["desktop-notifications:show", NOTE]);+ const target = { botId: "scout", threadId: "work-thread" };+ channels.get("desktop-notifications:open")({}, target);+ const heard = [];+ const stop = api.desktopNotifications.onOpen((seen) => heard.push(seen));+ assert.deepEqual(heard, [target]);+ channels.get("desktop-notifications:open")({}, { botId: "atlas", threadId: "next" });+ assert.equal(heard.length, 2);+ stop();+});diff --git a/electron/main.mjs b/electron/main.mjsindex 182e4e4a5f..83155c1b0c 100644--- a/electron/main.mjs+++ b/electron/main.mjs@@ -29,7 +29,7 @@ import { bootFailureMessage, listeningSignal, pollServerIdentity, SERVER_BOOT_TIimport { createServerSupervisor } from "./server-supervisor.mjs";import { serverChildLaunch } from "./server-child-launch.mjs";import { packageUrlFromCommandLine, packageUrlFromDeepLink } from "./package-link.mjs";-import { chatLinkFrom, chatLinkFromCommandLine } from "./chat-link.mjs";+import { chatLinkFrom, chatLinkFromCommandLine } from "./chat-link.mjs"; import { installDesktopNotifications } from "./desktop-notifications.mjs";import { createOrganizationEntry, isOrganizationDeepLink, takeOrganizationDeepLink, organizationRestartIntent, withOrganizationRestartIntent, withoutOrganizationRestartIntent } from "./organization-entry.mjs";import { windowBackground, windowChromeOptions } from "./window-chrome.mjs";import { createAllWindowsClosedQuit } from "./window-all-closed.mjs";@@ -2124,7 +2124,7 @@ function createWindow({ deferNavigation = false } = {}) {// Not did-finish-load: Electron still reports the main frame as loading then.win.webContents.on("did-stop-loading", () => {deliverPackageInstall(win);- deliverChatLink(win);+ deliverChatLink(win); desktopNotifications.arrived();});win.webContents.on("did-finish-load", () => void offerComputerSharing(win));@@ -2697,7 +2697,7 @@ const rail = installCloudRail({ ipcMain, clipboard, openCloud: openOwnCloud, accadd: { choices: () => ({ cloud: cloudOffersAllowed(), link: !desktopRemoteAccess, address: !desktopRemoteAccess && !homeWindow.cloudOrigin() }),run: (choice, link) => (choice === "link" ? (link ? connectHostedWorkspace(link) : addServerFromClipboard()) : choice === "address" ? openWorkspaceSettings() : homeWindow.cloudOrigin() ? undefined : openCloudAdd("app_menu")) } });const announceAddedCloud = createAddedCloudNotice({ Notification, focused: () => Boolean(mainWindow && !mainWindow.isDestroyed() && mainWindow.isFocused()), sheetOpen: rail.sheetOpen,- open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() });+ open: id => { if (!desktopTray?.show()) activateExistingWindow(appWindows()); void openOwnCloud(id); }, shown: () => cloudAccount?.addDone() }); const desktopNotifications = installDesktopNotifications({ ipcMain, Notification, nativeImage, fetch: (...args) => session.defaultSession.fetch(...args), window: () => mainWindow, mayNotify: (contents, url) => appPermissions?.check(contents, "notifications", url, { isMainFrame: true }) === true, reveal: revealForLink, openPlace: origin => (origin === homeWindow.cloudOrigin() ? showHome({ place: "cloud" }) : workspaceMenuAction(() => switchEnvironment(origin === rendererOrigin() ? LOCAL_ID : environmentsState.environments.find(entry => entry.origin === origin)?.id))) });// A place's colour (place-look.mjs): the Admin's for a Cloud, this app's for This computer and a server connected by// hand; changed on the place's own page or from the window's rail, whatever that server runs.installPlaceLook({ ipcMain, guard: workspaceOnly, place: () => savedPlace(environmentsState), session: () => ({ clouds: desktopRemoteAccess ? null : cloudAccount?.state().clouds ?? null, homeOrigin: myCloud() }),diff --git a/electron/preload.cjs b/electron/preload.cjsindex c32ec6b923..a0364eb7a3 100644--- a/electron/preload.cjs+++ b/electron/preload.cjs@@ -23,6 +23,16 @@ ipcRenderer.on("chat:open", (_event, link) => {for (const listener of chatLinkListeners) listener(link);});+let pendingNotificationOpen = null;+const notificationOpenListeners = new Set();+ipcRenderer.on("desktop-notifications:open", (_event, target) => {+ if (!notificationOpenListeners.size) {+ pendingNotificationOpen = target;+ return;+ }+ for (const listener of notificationOpenListeners) listener(target);+});+// Only fixed actions are retained, never a destination supplied by a renderer.const FIXED_SETTINGS_ACTIONS = new Set(["organization", "cloud", "cloud-settings", "cloud-add", "cloud-add-howto"]);let pendingSettingsAction = null;@@ -64,7 +74,7 @@ function railKeepsItsSize() {if (typeof window !== "undefined") {for (const type of ["resize", "DOMContentLoaded"]) window.addEventListener(type, () => { leaveRailRoom(); railKeepsItsSize(); });}-const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "accountSheet", "desktopNotices", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame"]);+const REMOTE_SAFE = new Set(["platform", "app", "getCapabilities", "onCapabilitiesChanged", "applySkin", "setUnreadCount", "permStatus", "workspaces", "rail", "cloudAdd", "cloudPlan", "cloudSendPage", "accountSheet", "desktopNotices", "desktopNotifications", "desktopAnalytics", "desktopLanguage", "updatesConsent", "windowControls", "onOpenAppSettings", "windowFrame"]);/** My Cloud's own page once it is the person's home (main checks the sender again): it is this app's page then. */const HOME_PAGE = ["home", "onChatLink", "onPackageInstall", "exportDiagnostics", "openLogsFolder", "openAtLogin", "callActive"];function updaterOffered() {@@ -613,6 +623,19 @@ const bridge = {// when it was missing. Nothing asks main any more: never the first showing today, so that page reports nothing.shown: () => Promise.resolve(false),},+ // A bot's notification, shown by main so its click outlives this page; older apps have no such key and the page shows its own.+ desktopNotifications: {+ show: (note) => ipcRenderer.invoke("desktop-notifications:show", note),+ onOpen: (cb) => {+ notificationOpenListeners.add(cb);+ if (pendingNotificationOpen) {+ const target = pendingNotificationOpen;+ pendingNotificationOpen = null;+ cb(target);+ }+ return () => notificationOpenListeners.delete(cb);+ },+ },desktopAnalytics: {enabled: () => {if (analyticsChoice === undefined) analyticsChoice = savedAnalyticsChoice();diff --git a/server/direct-coordination.e2e.test.ts b/server/direct-coordination.e2e.test.tsindex b08bade37d..5b72f9af66 100644--- a/server/direct-coordination.e2e.test.ts+++ b/server/direct-coordination.e2e.test.ts@@ -221,14 +221,9 @@ it("announces a settled delegation and its resume in the parent thread", () => fawait f.start();expect((await f.wait()).status).toBe("settled");// f.wait() resolves through the control CLI poll, independent of the SSE reader: until() proves both settles are stored first.- await Promise.all([- stream.until(frame => frame.kind === "notify"- && frame.notification?.kind === "delegation-settled"- && frame.notification.botId === f.chief.id),- stream.until(frame => frame.kind === "notify"- && frame.notification?.kind === "delegation-settled"- && frame.notification.botId === f.lead.id),- ]);+ await stream.until(frame => frame.kind === "notify"+ && frame.notification?.kind === "delegation-settled"+ && frame.notification.botId === f.chief.id);const settles = () => stream.frames.filter(frame => frame.kind === "notify" && frame.notification?.kind === "delegation-settled");const chiefFrames = settles().filter(frame => frame.notification.botId === f.chief.id);expect(chiefFrames).toHaveLength(1);@@ -237,10 +232,12 @@ it("announces a settled delegation and its resume in the parent thread", () => ftitle: "Clive resumed with results",body: "Results in from Engineering lead",});- const leadFrames = settles().filter(frame => frame.notification.botId === f.lead.id);- expect(leadFrames).toHaveLength(1);- expect(leadFrames[0].notification.threadId).not.toBe(f.lead.activeTaskId);+ expect(settles().filter(frame => frame.notification.botId === f.lead.id), "bot-to-bot: nothing there needs the person").toEqual([]);expect(settles().some(frame => frame.notification.botId === f.specialist.id)).toBe(false);+ const { bots } = await f.api("/api/bots?messages=0");+ const work = bots.find((bot: any) => bot.id === f.lead.id).tasks.find((task: any) => task.openedBy?.botId === f.chief.id);+ expect(work.unread, "no unread mark, on the desktop or the phone's To review, for a teammate's own step").toBeFalsy();+ expect(bots.find((bot: any) => bot.id === f.chief.id).tasks.find((task: any) => task.threadId === f.chief.activeTaskId).unread, "the person's own conversation still is").toBe(true);expect(stream.frames.some(frame => frame.kind === "notify" && frame.notification?.kind === "done"&& (frame.notification.botId === f.lead.id || frame.notification.botId === f.specialist.id))).toBe(false);const chips = (await f.messages(f.chief.activeTaskId))diff --git a/server/index.ts b/server/index.tsindex 8104d276fa..48fd88b51a 100644--- a/server/index.ts+++ b/server/index.ts@@ -4057,8 +4057,7 @@ const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoor});if (group) store.patchGroup(group.id, { unread: true });else {- const resultsPolled = !parent.parentId && parent.reply === "poll";- if (!resultsPolled) store.patchTask(parent.botId, parent.threadId, { unread: true });+ if (!parent.parentId && parent.reply !== "poll") store.patchTask(parent.botId, parent.threadId, { unread: true });const source = store.bot(parent.botId);if (source) markTaskContextExternallyUpdated(source, parent.threadId);}@@ -4100,7 +4099,7 @@ const handoffTicks = createHandoffTicks(), coordinator: Coordinator = createCoor});const quiet = turnAnswers(node.threadId, { cardContinuation: true, coordination: node }).quiet;const routineRoot = !node.parentId && activeRoutineRunForThread(node.threadId) !== null;- if (node.restart !== "rerun" && !quiet && !routineRoot && asking.length === 0) {+ if (node.restart !== "rerun" && !quiet && !routineRoot && !node.parentId && asking.length === 0) {notify(buildNotification("delegation-settled", bot, node.threadId, serverLine(language, "server.notify.resultsFrom", { who }), { avatarUrl: bot.avatarUrl }));}if (!node.parentId && !quiet) reviewAnswerThreads.add(node.threadId);diff --git a/shared/notification.ts b/shared/notification.tsindex d8d6917b6c..3b0f2ff83a 100644--- a/shared/notification.ts+++ b/shared/notification.ts@@ -13,9 +13,10 @@ export type NotifyKind =/** A bot asked the person to sign in to a website themselves* (request_sign_in): it waits on their hands, at the place it works. */| "sign-in"- /** A delegated room request settled and the coordinator auto-resumed with- * the results; both are internal, so without this the parent conversation- * sits silent until the resume's first token. */+ /** A delegated request settled and the coordinator auto-resumed the person's+ * own conversation with the results; both are internal, so without this it+ * sits silent until the resume's first token. A teammate's own step in a+ * longer chain sends none: nothing there waits on the person. */| "delegation-settled"/** A bot's settled room reply tagged the person (`@you` or their profile name). Rooms only. On a Team Cloud also* a teammate tagged by name, or a message a bot passed on to them, with `forPerson`. */diff --git a/src/App.tsx b/src/App.tsxindex 8d2027286b..b85b4a791b 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -58,7 +58,7 @@ import { shouldOpenKeyboardShortcuts } from "@/lib/keyboard-shortcuts";import { effectiveLanguage, useLanguageChoice, usePageLanguage } from "@/lib/language-preference";import { botUnreadCount, showBrowserUnread } from "@/lib/bot-unread";import { phonePairingSettingsAction, takePhonePairingRequest } from "@/lib/phone-pairing"; import { takeConnectRequest } from "@/lib/connect-link";-import { useExternalChatLinks } from "@/hooks/use-external-chat-links";+import { useDesktopNotificationOpens, useExternalChatLinks } from "@/hooks/use-external-chat-links";import { useUsageSnapshot } from "@/hooks/use-usage-snapshot";import { useReadShownChatOnFocus } from "@/hooks/use-read-shown-chat";import { usePresence } from "@/hooks/use-presence";@@ -126,7 +126,7 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {window.history.replaceState(null, "", request.rest);dispatch("section" in request ? { type: "toggleAppSettings", open: true, section: request.section } : { type: "togglePlugins", open: true, surface: request.surface });}, [dispatch]);- useExternalChatLinks(state, dispatch);+ useExternalChatLinks(state, dispatch); useDesktopNotificationOpens(state, dispatch);usePresence(state, dispatch);const [drawerOpen, setDrawerOpen] = useState(false);usePageLanguage(effectiveLanguage(useLanguageChoice(), state.config?.language));diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsxindex d54cf2a066..ecf5b33051 100644--- a/src/components/ChatView.tsx+++ b/src/components/ChatView.tsx@@ -19,7 +19,7 @@ import {currentTaskBot,useStore,formatTime,- openNotificationTarget,+ openRoomThread,openThread,visibleMessages,type Action,@@ -92,7 +92,7 @@ import { AttachmentGallery, collectMessageFiles, replyAttachmentGroup, splitMessimport { ScreenFrame } from "./ScreenFrame";import { CompactionChip, DigestChip } from "./DigestChip";import { RenameTitle } from "./RenameTitle"; import { ChatHeadRole, chiefOfStaffBadge } from "./BotRole";-import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill";+import { BotActivityPicker } from "./TaskPicker"; import { ChatHeadPill } from "./ChatHeadPill"; import { useStoreRef } from "@/state/store-ref";import { ELEVATED_FLOAT, ELEVATED_HOVER } from "./elevated";import { ModelPicker } from "./ModelPicker";import { ChatHeaderMenu, ChatMoreMenu } from "./ChatMoreMenu"; import { TeamOwnHelperHeader, TeamPrivateFirstLine, TeamPrivateHeader, TeamSharedHeader } from "./TeamPrivateChatsLine";@@ -632,14 +632,14 @@ function PeerLabel({ peer }: { peer: PeerLine }) {}const ActivityChip = memo(function ActivityChip({ message, place = "auto" }: { message: Message; place?: EffectivePlace }) {- const { bots, dispatch, threadId } = useChatRows(), liveTools = use(LiveToolsContext);+ const { bots, dispatch, threadId } = useChatRows(), liveTools = use(LiveToolsContext), store = useStoreRef();const tool = message.tool;if (!tool) return null;if (message.threadRef) return <ThreadChip message={message} />; if (message.relay) return <TeammateChip message={message} />;const comm = message.comm;if (comm) {return <HandoffChip message={message} bots={bots} title={t("chat.openConversationWith", { name: comm.withName })}- onClick={() => dispatch({ type: "select", id: comm.groupId })} />;+ onClick={() => openRoomThread(dispatch, comm, store.state().groups)} />;}return <ToolActivity tool={tool} live={liveTools.has(message.id)} place={toolPlace(tool.name, place)} source={{ threadId, messageId: message.id }} />;});@@ -1137,7 +1137,7 @@ export function ChatView({ bot: profile }: { bot: Bot }) {{(advanced || remoteClient) && <BotActivityPicker bot={bot} />}{privateChat && team && <TeamPrivateFirstLine key={team.id} team={team} />}{routineExecution && <div className="mx-5 mb-2 flex flex-wrap items-center gap-2 rounded-lg border border-hairline/40 bg-inset px-3 py-2 text-[12px] text-ink-secondary"><span className="min-w-0 flex-1 truncate">{t("routines.executionDetails", { name: routineExecution.routineName })}</span>- {canOpenResults && resultsThreadId && <button type="button" onClick={() => openNotificationTarget(dispatch, { botId: bot.id, threadId: resultsThreadId }, state, showThreads)} className="rounded px-2 py-1 text-accent hover:bg-raised">{t("routines.results.back")}</button>}+ {canOpenResults && resultsThreadId && <button type="button" onClick={() => openThread(dispatch, { botId: bot.id, threadId: resultsThreadId }, state, showThreads)} className="rounded px-2 py-1 text-accent hover:bg-raised">{t("routines.results.back")}</button>}<button type="button" onClick={() => dispatch({ type: "showRoutines", section: "logs", routineId: routineExecution.routineId, botId: bot.id })} className="rounded px-2 py-1 hover:bg-raised hover:text-ink">{t("routines.logs")}</button></div>}{findOpen && <ChatFindBar threadId={bot.threadId} onClose={() => setFindOpen(false)} />}diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex 13036fec3d..77d77bd3a4 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -9,7 +9,8 @@ import {api,useStore,formatTime,- openNotificationTarget,+ openRoomThread,+ openThread,type Bot,type Group,type GroupDefaultResponder,@@ -110,13 +111,7 @@ export function RoomToolChip({ message, roomId, threadId, live = false }: { mess}const comm = message.comm;if (comm && comm.groupId !== roomId) {- return <HandoffChip message={message} bots={state.bots} title={t("room.openBot", { name: comm.withName })} onClick={() => {- dispatch({ type: "select", id: comm.groupId });- const destination = state.groups.find(g => g.id === comm.groupId);- if (comm.threadId && destination?.tasks?.some(task => task.threadId === comm.threadId)) {- dispatch({ type: "switchGroupTask", groupId: comm.groupId, threadId: comm.threadId });- }- }} />;+ return <HandoffChip message={message} bots={state.bots} title={t("room.openBot", { name: comm.withName })} onClick={() => openRoomThread(dispatch, comm, state.groups)} />;}if (!comm) return <ToolActivity tool={tool} live={live} source={threadId ? { threadId, messageId: message.id } : undefined} />;return (@@ -453,7 +448,7 @@ export const Transcript = memo(function Transcript({<RoutineRunCardmessage={m}onOpen={routineTarget- ? () => openNotificationTarget(dispatch, routineTarget, state, showThreads)+ ? () => openThread(dispatch, routineTarget, state, showThreads): undefined}/></div>diff --git a/src/components/NotificationsPanel.test.ts b/src/components/NotificationsPanel.test.tsindex 585b2e6b94..5d58182a58 100644--- a/src/components/NotificationsPanel.test.ts+++ b/src/components/NotificationsPanel.test.ts@@ -1,11 +1,42 @@+import { Children, createElement, isValidElement, type ReactElement, type ReactNode } from "react";+import { renderToStaticMarkup } from "react-dom/server";import { afterEach, describe, expect, it, vi } from "vitest";-import { ALL_BOTS, filterNotifications, notificationBots, notificationBotForAvatar, notificationThreadName, postNotificationRead } from "./NotificationsPanel";+import { initialState, StoreContext, type Bot } from "@/state/store";+import { ALL_BOTS, filterNotifications, notificationBots, notificationBotForAvatar, notificationThreadName, NotificationsPanel, postNotificationRead } from "./NotificationsPanel";const state = {bots: [{ id: "b1", threadId: "t-main", tasks: [{ threadId: "t-main", title: "Notification Pane" }, { threadId: "t-2", title: "Hotpatches" }] }],groups: [{ threadId: "g-main", name: "Mantis-email & co.", tasks: [{ threadId: "g-task", title: "Skill rollout" }] }],};+describe("a row in the bell", () => {+ const scout: Bot = { id: "scout", threadId: "main", name: "Scout", title: "", description: "", notifications: true, color: "green", unread: false, modelSelection: { instanceId: "fake", model: "m" }, messages: [],+ tasks: [{ threadId: "main", title: "Main", createdAt: 1 }, { threadId: "work", title: "@CoS · work", createdAt: 2 }] };+ const entry = (threadId: string) => ({ id: threadId, at: 1, read: true, kind: "done" as const, botId: "scout", botName: "Scout", threadId, title: "Scout finished", body: "Done" });+ function click(threadId: string) {+ const dispatch = vi.fn();+ const rows: ReactElement<{ onOpen: () => void }>[] = [];+ const walk = (node: ReactNode) => Children.forEach(node, (child) => {+ if (!isValidElement<{ children?: ReactNode; onOpen?: () => void }>(child)) return;+ if (child.props.onOpen) rows.push(child as ReactElement<{ onOpen: () => void }>);+ walk(child.props.children);+ });+ const state = { ...initialState, bots: [scout], notifications: [entry(threadId)] };+ function Capture() { walk(NotificationsPanel()); return null; }+ renderToStaticMarkup(createElement(StoreContext.Provider, { value: { state, dispatch } as never }, createElement(Capture)));+ rows[0]!.props.onOpen();+ return dispatch.mock.calls.map(([action]) => action);+ }++ it("lands on a thread another bot opened, and reveals its row in the sidebar", () => {+ expect(click("work")).toEqual([{ type: "select", id: "scout" }, { type: "switchTask", botId: "scout", threadId: "work" }, { type: "revealThread", threadId: "work" }]);+ });++ it("says so when that thread is gone, never landing silently on another chat", () => {+ expect(click("deleted")).toContainEqual({ type: "notice", notice: { kind: "thread-gone", botName: "Scout" } });+ });+});+describe("notificationThreadName", () => {it("finds a bot task title", () => {expect(notificationThreadName({ botId: "b1", threadId: "t-2" }, state)).toBe("Hotpatches");diff --git a/src/components/NotificationsPanel.tsx b/src/components/NotificationsPanel.tsxindex 6d8958605d..cd6acf1ff6 100644--- a/src/components/NotificationsPanel.tsx+++ b/src/components/NotificationsPanel.tsx@@ -1,6 +1,6 @@import { useEffect, useState } from "react";import { AlertTriangle, AtSign, Bell, CheckCircle2, CircleHelp, HandHelping, Info, LogIn, Newspaper, Pin, RotateCcw, Wallet, X, type LucideIcon } from "lucide-react";-import { api, useStore, openNotificationTarget, type Action } from "@/state/store";+import { api, useStore, openThread, type Action } from "@/state/store";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";import { useShowThreads } from "@/lib/thread-preferences";@@ -123,7 +123,7 @@ export function NotificationsPanel() {dispatch({ type: "notificationRead", id: entry.id });void postNotificationRead(`/api/notifications/${entry.id}/read`, dispatch);}- openNotificationTarget(dispatch, { botId: entry.botId, threadId: entry.threadId }, state, showThreads);+ openThread(dispatch, { botId: entry.botId, threadId: entry.threadId }, state, showThreads);};const markAllRead = () => {diff --git a/src/components/PinnedCircleThreads.tsx b/src/components/PinnedCircleThreads.tsxindex b0bfc77182..3772503d62 100644--- a/src/components/PinnedCircleThreads.tsx+++ b/src/components/PinnedCircleThreads.tsx@@ -1,7 +1,7 @@import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentType, type DragEvent, type KeyboardEvent } from "react";import { createPortal } from "react-dom";import { ChevronRight, FolderPlus, Plus } from "lucide-react";-import { openBot, visibleMessages, type Bot, type Message } from "@/state/store";+import { openBotRow, visibleMessages, type Bot, type Message } from "@/state/store";import { avatarCropRadius, botAvatarProfile } from "../../shared/bot-avatar";import { liveActivityLabel } from "@/lib/live-activity";import { BotAvatar } from "./Avatar";@@ -203,7 +203,7 @@ export const PinnedBotCircle = memo(function PinnedBotCircle({aria-keyshortcuts={drag ? "Alt+ArrowUp Alt+ArrowDown" : undefined}aria-label={`${bot.name}${waiting ? ` · ${t("sidebar.preview.waiting")}` : working ? ` · ${t("chat.activity.working")}` : ""}${unread ? ` · ${t("task.unread")}` : ""}`}title={bot.name}- onClick={() => openBot(dispatch, bot, showThreads)}+ onClick={() => openBotRow(dispatch, bot, showThreads, selected)}{...pinnedCircleDragHandlers(bot.id, { drag, dragging, prevId, nextId })}onContextMenu={(event) => {event.preventDefault();diff --git a/src/components/RoutineCalendarPage.tsx b/src/components/RoutineCalendarPage.tsxindex 1a6cc7ffb5..d6e06e7ed8 100644--- a/src/components/RoutineCalendarPage.tsx+++ b/src/components/RoutineCalendarPage.tsx@@ -82,7 +82,7 @@ import {type RoutineScheduleInput,type RoutineTarget,} from "@/lib/routines";-import { api, openBotThread, openNotificationTarget, useStore, type Bot, type Group } from "@/state/store";+import { api, openBotThread, openThread, useStore, type Bot, type Group } from "@/state/store";import { RoutineScheduleNote } from "./RoutineScheduleNote";import { CalendarEventCard, HOUR_HEIGHT, statusState } from "./routines/CalendarEventCard";@@ -1492,7 +1492,7 @@ export function EventDetails({{call && call.botIds.length > 1 && <button onClick={joinRoom} disabled={working} className="flex items-center gap-1.5 rounded-lg bg-accent px-3 py-2 text-[12px] font-semibold text-accent-ink hover:brightness-110 disabled:opacity-50"><ExternalLink size={13} />Join group</button>}{isRoomGoal && goalGroup && !executionThreadId && <button onClick={() => { onOpenRoom(goalGroup.id); onClose(); }} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"><ExternalLink size={13} />Open group</button>}{canOpenExecution && <button onClick={openRunTask} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"><ExternalLink size={13} />{isRoomGoal && goalGroupId ? "Open group thread" : "Open thread"}</button>}- {canOpenResults && openResultsId && <button type="button" onClick={() => { openNotificationTarget(dispatch, { botId: botIds[0], threadId: openResultsId }, state, showThreads); onClose(); }} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"><ExternalLink size={13} />{t("routines.results.open")}</button>}+ {canOpenResults && openResultsId && <button type="button" onClick={() => { openThread(dispatch, { botId: botIds[0], threadId: openResultsId }, state, showThreads); onClose(); }} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink"><ExternalLink size={13} />{t("routines.results.open")}</button>}{run && ["queued", "running", "waiting"].includes(run.status) && <button onClick={() => void invoke(`/api/routine-runs/${run.id}/cancel`)} disabled={working} className="flex items-center gap-1.5 rounded-lg px-2.5 py-1.5 text-[12px] text-ink-secondary hover:bg-raised hover:text-ink disabled:opacity-40"><X size={13} />Cancel run</button>}<div className="ml-auto flex items-center gap-1">{(routine || call) && <button onClick={onEdit} className="rounded-lg px-2.5 py-1.5 text-[12px] font-medium text-ink hover:bg-raised">{t("routines.edit")}</button>}diff --git a/src/components/RoutineRunCard.tsx b/src/components/RoutineRunCard.tsxindex 03065a3e44..f15fe13ad4 100644--- a/src/components/RoutineRunCard.tsx+++ b/src/components/RoutineRunCard.tsx@@ -6,7 +6,7 @@ import { t } from "@/lib/i18n";import { useShowThreads } from "@/lib/thread-preferences";import { liveCardKind } from "../../shared/live-approval";import type { AutomationLine, RoutineRunCardData } from "../../shared/routine-run";-import { formatTime, openNotificationTarget, useStore, type Message } from "@/state/store";+import { formatTime, openThread, useStore, type Message } from "@/state/store";const DETAIL_LIMIT = 280;@@ -134,7 +134,7 @@ export function RoutineRunRow({ message, botId }: { message: Message; botId: str<RoutineRunCardmessage={message}onOpen={canOpen && executionThreadId- ? () => openNotificationTarget(dispatch, { botId, threadId: executionThreadId }, state, showThreads)+ ? () => openThread(dispatch, { botId, threadId: executionThreadId }, state, showThreads): undefined}/>);@@ -157,7 +157,7 @@ export function AutomationCaption({ message, line, botId }: { message: Message;{canOpen && (<buttontype="button"- onClick={() => openNotificationTarget(dispatch, { botId, threadId: line.executionThreadId }, state, showThreads)}+ onClick={() => openThread(dispatch, { botId, threadId: line.executionThreadId }, state, showThreads)}aria-label={t("chat.automation.openRunFor", { name: line.name })}className="shrink-0 rounded px-1 hover:bg-inset hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent">diff --git a/src/components/Sidebar.simple-layout.test.ts b/src/components/Sidebar.simple-layout.test.tsindex bbe871d204..282d3e671c 100644--- a/src/components/Sidebar.simple-layout.test.ts+++ b/src/components/Sidebar.simple-layout.test.ts@@ -107,6 +107,23 @@ afterEach(() => {});describe("Simple-mode sidebar layout", () => {+ describe("Active Threads, the desktop's list of what the phone's Updates shows", () => {+ const working = bot("spuernase", { threadId: "main", tasks: [{ threadId: "main", title: "Main", createdAt: 1 }, { threadId: "work", title: "@CoS · work", createdAt: 2, busy: true, activity: "working" }] });+ const opened = (tree: ReactElement<Props>[]) => tree.find((node) => node.props["aria-label"] === "Active Threads, 1");++ it("stays away while nothing is going on", () => {+ expect(labelled(render().tree, "Active Threads")).toBe(false);+ });++ it("is there while a bot works in a thread another bot opened, and leaves the corner room for it", () => {+ fixture.state = { ...fixture.state, bots: [working, bot("chief", { chiefOfStaff: true })] };+ const { tree } = render();+ expect(opened(tree), "reachable with no thread list in Simple").toBeTruthy();+ const grid = tree.find((node) => node.type === SidebarTileGrid)!.props as Parameters<typeof SidebarTileGrid>[0];+ expect(grid.cornerButtons).toBe(3);+ });+ });+it("lists the bots with no heading, then gives group chats and a person's own departments a quiet heading with a count", () => {const { tree } = render();expect(sectionOrder(tree)).toEqual([BOTS_SECTION_ID, CHANNELS_SECTION_ID, userSectionId("Work")]);diff --git a/src/components/Sidebar.simple-mode.test.ts b/src/components/Sidebar.simple-mode.test.tsindex 28941c5b56..e96a594d89 100644--- a/src/components/Sidebar.simple-mode.test.ts+++ b/src/components/Sidebar.simple-mode.test.ts@@ -38,6 +38,7 @@ const bot: Bot = {{ threadId: "unread", title: "Finished reply", createdAt: 6, unread: true },],};+const quiet: Bot = { ...bot, unread: false, tasks: bot.tasks!.filter((task) => !task.busy && !task.unread && !task.activity) };const densities: SidebarDensity[] = ["comfortable", "icons"];const botRow = (BotListItem as MemoExoticComponent<(props: BotRowProps) => ReactNode>).type;const pinnedCircle = (PinnedBotCircle as MemoExoticComponent<(props: BotRowProps) => ReactNode>).type;@@ -111,12 +112,12 @@ describe("bot-first sidebar", () => {it.each(densities)(`opens the last selected conversation on mouse or keyboard, %s density, threads ${enabled ? "on" : "off"}`, (density) => {fixture.showThreads = enabled;let tree: ReactNode;- function Capture() { tree = botRow(rowProps(density)); return tree; }+ function Capture() { tree = botRow(rowProps(density, quiet)); return tree; }renderToStaticMarkup(createElement(Capture));const row = findElement(tree, "data-sidebar-bot-row", bot.id)!;row.props.onClick!({ type: "click", target: {} } as MouseEvent);expect(fixture.dispatch).toHaveBeenCalledExactlyOnceWith({ type: "select", id: bot.id });- expect(bot.threadId).toBe("last-selected");+ expect(quiet.threadId).toBe("last-selected");for (const key of ["Enter", " "]) {fixture.dispatch.mockClear();const preventDefault = vi.fn();@@ -323,8 +324,25 @@ describe("bot-first sidebar", () => {expect(markup).not.toContain("waiting-dot");});+ it.each(densities)("opens the thread a row or circle is marked for, on mouse or keyboard, %s density", (density) => {+ fixture.showThreads = false;+ const trees: ReactNode[] = [];+ function Capture() { const tree = [botRow(rowProps(density)), pinnedCircle(rowProps(density))]; trees.push(...tree); return tree; }+ renderToStaticMarkup(createElement(Capture));+ for (const tree of trees) {+ const row = findElement(tree, "data-sidebar-bot-row", bot.id)!;+ fixture.dispatch.mockClear();+ row.props.onClick!({ type: "click", target: {} } as MouseEvent);+ expect(fixture.dispatch).toHaveBeenCalledExactlyOnceWith({ type: "switchTask", botId: bot.id, threadId: "approval" });+ if (!row.props.onKeyDown) continue;+ fixture.dispatch.mockClear();+ row.props.onKeyDown({ key: "Enter", preventDefault: vi.fn() } as unknown as KeyboardEvent);+ expect(fixture.dispatch).toHaveBeenCalledExactlyOnceWith({ type: "switchTask", botId: bot.id, threadId: "approval" });+ }+ });+it.each(densities)("opens the thread the person last wrote in when threads are hidden, %s density", (density) => {- const used = { ...bot, mainThreadId: "idle-history" };+ const used = { ...quiet, mainThreadId: "idle-history" };for (const enabled of [false, true]) {fixture.showThreads = enabled;const opened = enabled ? { type: "select", id: bot.id } : { type: "switchTask", botId: bot.id, threadId: "idle-history" };diff --git a/src/components/Sidebar.tsx b/src/components/Sidebar.tsxindex b0d86a83ec..1ec10d5fc4 100644--- a/src/components/Sidebar.tsx+++ b/src/components/Sidebar.tsx@@ -2,7 +2,7 @@ import { OrganizationIdentity } from "./OrganizationIdentity";import { memo, useCallback, useEffect, useMemo, useRef, useState, type CSSProperties, type Dispatch } from "react";import { createPortal } from "react-dom";import { Activity, Archive, Bot as BotIcon, Check, ChevronRight, ClipboardCopy, Crown, FolderPlus, Library, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, Phone, Pin, PinOff, Plus, Search, TextQuote, Trash2, Users, X } from "lucide-react";-import { api, useStore, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";+import { api, useStore, formatTime, visibleMessages, currentTaskBot, botOpensTo, openBot, openBotRow, openThread, type Action, type AppState, type Bot, type BotProject, type Group, type InstanceInfo, type Message } from "@/state/store";import { approvalModeFor } from "../../shared/approval-mode";import { liveActivityLabel } from "@/lib/live-activity";import { SidebarWorkingStep } from "./SidebarWorkingStep";@@ -625,7 +625,7 @@ export function BotThreadList({ bot, selected, query, pendingQueued, reveal, loc<span role="status" className="sr-only">{readStatus}</span>{projects.length > 0 && ungrouped.length > 0 && <div className="pl-6 pr-3 pb-1 pt-2 text-[11px] text-ink-tertiary">{t("task.list")}</div>}{ungrouped.map(renderThread)}- <HelperThreadGroup tasks={orderedThreadList(helpers)} busy={helpers.some((task) => currentTaskBot(bot, task.threadId).busy)} renderThread={renderThread} />+ <HelperThreadGroup tasks={orderedThreadList(helpers)} renderThread={renderThread} /><ThreadListFooter bulk={bulk} rows={shownRows} selected={selection} total={ownTasks.length} canShowAll={!query && !showAll && ownTasks.length > visibleTasks.length} canSelect={tasks.length > 1}onShowAll={() => setShowAll(true)} freshConversation onDelete={(threadIds) => deleteThreadsInBulk({ botId: bot.id }, threadIds, dispatch)} /><LocalComputerAutoWarning@@ -848,7 +848,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {if (renaming) return;const insideRenameInput = event.target instanceof HTMLInputElement;if (botListItemPointerIntent(event.type, insideRenameInput) === "select") {- openBot(dispatch, bot, showThreads);+ openBotRow(dispatch, bot, showThreads, selected);}};@@ -877,7 +877,7 @@ export const BotListItem = memo(function BotListItem(props: BotRowProps) {if (drag && stepKey(event)) { event.preventDefault(); drag.step(bot.id, stepKey(event)!); return; }if (event.key === "Enter" || event.key === " ") {event.preventDefault();- openBot(dispatch, bot, showThreads);+ openBotRow(dispatch, bot, showThreads, selected);}}}onContextMenu={onContextMenu}@@ -1141,7 +1141,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {const { interactive: layoutInteractive, collapsed: sectionCollapsed, toggle: toggleSection } = sections;const archivedBots = state.bots.filter((bot) => bot.hidden && !bot.movedTo);const archivedEntry = remoteClient ? undefined : { count: archivedBots.length, open: () => setArchivedBotsOpen(true) };- const attention = crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups);+ const attention = crossBotAttentionThreads(state.bots, state.pendingQueued, undefined, state.groups), activeThreadsShown = advanced || attention.length > 0;const pinnedThreads = crossBotPinnedThreads(state.bots, state.groups, state.pendingQueued);const pendingBotUndo = teamFeedback?.restoreBot;const botRow = (bot: Bot) => botRowProps(state, dispatch, bot, { density, query: q, onMenu: setMenu, renameRequest: renameRequest?.botId === bot.id ? renameRequest.nonce : 0, ...drops.row(bot.id) });@@ -1312,18 +1312,18 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {><Search size={20} strokeWidth={1.5} /></button>}- {advanced && <div ref={attentionMenuRef} className={density === "icons" ? "relative" : "contents"}>+ {activeThreadsShown && <div ref={attentionMenuRef} className={density === "icons" ? "relative" : "contents"}><buttontype="button"onClick={() => setAttentionOpen((o) => !o)}aria-label={attentionTriggerLabel(attention.length)}title={attentionTriggerLabel(attention.length)}className={cn(- "relative flex items-center justify-center text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",- density === "icons" ? "size-[46px] shrink-0 rounded-xl" : phone ? "size-10 shrink-0 rounded-full border border-hairline bg-card text-ink" : "size-8 rounded-full",+ "relative", corner ? SIMPLE_CORNER_BUTTON : simpleDesk ? SIMPLE_TOP_BUTTON : "flex items-center justify-center text-ink-secondary transition-colors hover:bg-ink/[0.06] hover:text-ink focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus",+ !corner && !simpleDesk && (density === "icons" ? "size-[46px] shrink-0 rounded-xl" : phone ? "size-10 shrink-0 rounded-full border border-hairline bg-card text-ink" : "size-8 rounded-full"),)}>- <Activity size={density === "icons" ? 20 : 18} strokeWidth={1.5} />+ <Activity size={corner ? 17 : density === "icons" ? 20 : 18} strokeWidth={1.5} />{attention.length > 0 && (<span className="absolute -right-0.5 -top-0.5 flex min-w-4 items-center justify-center rounded-full bg-accent px-0.5 text-[10px] font-semibold leading-4 text-ink">{attention.length > 9 ? "9+" : attention.length}</span>)}@@ -1420,7 +1420,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {onToggle={layoutInteractive ? () => toggleSection(PINNED_THREADS_SECTION_ID) : undefined}/>)}- {tiles && <SidebarTileGrid primary={primary} pinned={pinnedBots} row={botRow} corner={corner} />}+ {tiles && <SidebarTileGrid primary={primary} pinned={pinnedBots} row={botRow} corner={corner} cornerButtons={activeThreadsShown ? 3 : 2} />}{simpleDesk && !tiles && <SidebarNoBots />}</GlassBar>@@ -1434,7 +1434,7 @@ export function Sidebar({ open, onClose, collapseToIcons = false }: {)}{!q && <NeedsYouButton compact={rail} />}{!q && <SidebarPeople compact={rail} />}{unsectionedChief && (phone ? (- <PhoneHero bot={unsectionedChief} selected={botRow(unsectionedChief).selected} onOpen={() => openBot(dispatch, unsectionedChief, showThreads)} onMenu={setMenu} />+ <PhoneHero bot={unsectionedChief} selected={botRow(unsectionedChief).selected} onOpen={() => openBotRow(dispatch, unsectionedChief, showThreads, botRow(unsectionedChief).selected)} onMenu={setMenu} />) : (<div className="mb-1.5"><BotListItem {...botRow(unsectionedChief)} />diff --git a/src/components/SidebarThreadRow.test.ts b/src/components/SidebarThreadRow.test.tsindex 42db7251c8..cca621aefa 100644--- a/src/components/SidebarThreadRow.test.ts+++ b/src/components/SidebarThreadRow.test.ts@@ -693,22 +693,26 @@ describe("helper threads a bot opened", () => {const thread = (threadId: string, patch: Record<string, unknown> = {}) =>({ threadId, title: threadId, createdAt: 1, updatedAt: 1, ...patch }) as any;- it("folds open bot-opened threads into a group and keeps the person's own threads", () => {- const tasks = [thread("mine"), thread("email", { openedBy: opener, busy: true }), thread("pricing", { openedBy: opener })];+ it("folds idle bot-opened threads into a group and keeps the person's own threads", () => {+ const tasks = [thread("mine"), thread("email", { openedBy: opener }), thread("pricing", { openedBy: opener })];const { own, helpers } = partitionHelperThreads(tasks, "mine");expect(own.map((task) => task.threadId)).toEqual(["mine"]);expect(helpers.map((task) => task.threadId)).toEqual(["email", "pricing"]);});- it("keeps a helper thread in view while it needs the person", () => {+ it("keeps a helper thread in view while it needs the person or is doing something, as the phone lists it", () => {const tasks = [thread("open-now", { openedBy: opener }),thread("approval", { openedBy: opener, activity: "waiting-on-you" }),thread("reply", { openedBy: opener, unread: true }),thread("pinned", { openedBy: opener, pinned: true }),+ thread("working", { openedBy: opener, busy: true }),+ thread("thinking", { openedBy: opener, activity: "working" }),+ thread("waiting", { openedBy: opener, waitingForTeammates: true }),+ thread("queued", { openedBy: opener, queued: true }),];const { own, helpers } = partitionHelperThreads(tasks, "open-now");- expect(own.map((task) => task.threadId)).toEqual(["open-now", "approval", "reply", "pinned"]);+ expect(own.map((task) => task.threadId)).toEqual(["open-now", "approval", "reply", "pinned", "working", "thinking", "waiting", "queued"]);expect(helpers).toEqual([]);});diff --git a/src/components/SidebarThreadRow.tsx b/src/components/SidebarThreadRow.tsxindex 47c5d16d72..19e674f2f2 100644--- a/src/components/SidebarThreadRow.tsx+++ b/src/components/SidebarThreadRow.tsx@@ -99,15 +99,14 @@ export function partitionHelperThreads<T extends ThreadRowTask>(tasks: T[], acticonst helpers: T[] = [];for (const task of tasks) {const filed = folders.some((folder) => folder.id === task.projectId);- const needsPerson = task.threadId === activeId || task.activity === "waiting-on-you" || Boolean(task.unread);- const helper = Boolean(task.openedBy) && task.pinned !== true && !filed && !needsPerson &&+ const helper = Boolean(task.openedBy) && task.pinned !== true && !filed && !demandsAttention(task, activeId) &&!task.closedBy && !isArchived(task) && !isSnoozed(task);(helper ? helpers : own).push(task);}return { own, helpers };}-export function HelperThreadGroup<T>({ tasks, busy, renderThread }: { tasks: T[]; busy: boolean; renderThread: (task: T) => ReactNode }) {+export function HelperThreadGroup<T>({ tasks, renderThread }: { tasks: T[]; renderThread: (task: T) => ReactNode }) {const [open, setOpen] = useState(false);if (tasks.length === 0) return null;const label = t("task.helperGroup");@@ -117,7 +116,6 @@ export function HelperThreadGroup<T>({ tasks, busy, renderThread }: { tasks: T[]<ChevronRight aria-hidden="true" size={11} className={cn("shrink-0 transition-transform", open && "rotate-90")} /><span className="truncate">{label}</span><span className="shrink-0 text-[10px] opacity-50">{tasks.length}</span>- {!open && busy && <Loader2 size={10} className="shrink-0 animate-spin text-success" />}</button>{open && <div role="group" aria-label={label}>{tasks.map(renderThread)}</div>}</div>;diff --git a/src/components/SidebarTiles.test.ts b/src/components/SidebarTiles.test.tsindex a755f7f069..b55460b78f 100644--- a/src/components/SidebarTiles.test.ts+++ b/src/components/SidebarTiles.test.ts@@ -85,6 +85,17 @@ describe("the sidebar tiles", () => {});});+describe("a tile with a dot", () => {+ it("lands on the thread the dot is about: a tile has no row under it to reach it from", () => {+ const withWork = bot({ threadId: "main", mainThreadId: "main", unread: true, tasks: [{ threadId: "main", title: "Main", createdAt: 1 }, { threadId: "work", title: "@Scout · work", createdAt: 2, unread: true }] });+ let tree: ReactNode;+ function Capture() { tree = tile({ ...props(withWork), primary: true }); return tree; }+ renderToStaticMarkup(createElement(Capture));+ (find(tree, "data-sidebar-tile")!.props.onKeyDown as (event: KeyboardEvent) => void)({ key: "Enter", preventDefault: vi.fn() } as unknown as KeyboardEvent);+ expect(dispatch).toHaveBeenCalledWith({ type: "switchTask", botId: "mausbot", threadId: "work" });+ });+});+describe("the tile grid", () => {const main = bot({ chiefOfStaff: true });const pins = (count: number) => Array.from({ length: count }, (_, index) => bot({ id: `pin${index}`, name: `Pin ${index}`, pinned: true }));diff --git a/src/components/SidebarTiles.tsx b/src/components/SidebarTiles.tsxindex 903e88212a..5438e0206d 100644--- a/src/components/SidebarTiles.tsx+++ b/src/components/SidebarTiles.tsx@@ -6,7 +6,7 @@ import { t } from "@/lib/i18n";import { useLiveMedia } from "@/lib/live-call-media";import { stateForBot } from "@/lib/mascot";import { useShowThreads } from "@/lib/thread-preferences";-import { api, openBot, useStore, type Bot } from "@/state/store";+import { api, openBotRow, useStore, type Bot } from "@/state/store";import { useChiefStepOpen } from "@/lib/default-bot";import { BotAvatar } from "./Avatar";@@ -37,7 +37,7 @@ export const SidebarBotTile = memo(function SidebarBotTile({ primary = false, drconst status = waiting ? t("sidebar.preview.waiting") : working ? t("chat.activity.working") : teammateWait ? t("sidebar.preview.waitingOnTeammate") : queued ? t("task.queued") : "";const label = [bot.name, bot.chiefOfStaff ? t("sidebar.bot.chiefOfStaff") : "", onLiveCall ? t("call.live.badge") : "", status, unread ? t("task.unread") : ""].filter(Boolean).join(" · ");const reorder = pinnedCircleDragHandlers(bot.id, { drag, dragging, prevId, nextId });- const open = () => openBot(dispatch, bot, showThreads);+ const open = () => openBotRow(dispatch, bot, showThreads, selected);const rename = (name: string) => {if (!remoteClient) return dispatch({ type: "updateBot", botId: bot.id, patch: { name } });void api(`/api/bots/${bot.id}/profile`, { method: "PATCH", body: JSON.stringify({ name }) })@@ -134,19 +134,19 @@ export function SidebarNoBots() {return <p data-sidebar-empty="" className="px-5 pt-4 text-[13px] leading-[18px] text-ink-tertiary">{t("onboarding.shell.noBots")}</p>;}-/** How much of the grid's right end Search and New take in a framed window's corner (Sidebar's corner row). */-const CORNER_CLEAR = 60;+/** How much of the grid's right end each button takes in a framed window's corner (Sidebar's corner row). */+const CORNER_BUTTON = 30;/** Whether the tiles' first row, as laid out, ends before the corner's buttons: the sidebar's width and the number of* tiles decide it. */-export function tilesClearCorner(tiles: { top: number; right: number }[], gridRight: number): boolean {+export function tilesClearCorner(tiles: { top: number; right: number }[], gridRight: number, buttons = 2): boolean {if (!tiles.length) return false;const top = tiles[0]!.top;- return Math.max(...tiles.filter((tile) => Math.abs(tile.top - top) < 1).map((tile) => tile.right)) <= gridRight - CORNER_CLEAR;+ return Math.max(...tiles.filter((tile) => Math.abs(tile.top - top) < 1).map((tile) => tile.right)) <= gridRight - buttons * CORNER_BUTTON;}/** While the tiles clear the corner they rise beside its buttons (styles.css); else they start under them. */-function useBesideCorner(corner: boolean, count: number) {+function useBesideCorner(corner: boolean, count: number, buttons: number) {const ref = useRef<HTMLDivElement>(null);const [beside, setBeside] = useState(false);useLayoutEffect(() => {@@ -154,20 +154,20 @@ function useBesideCorner(corner: boolean, count: number) {if (!corner || !grid) { setBeside(false); return; }const measure = () => {const tiles = [...grid.querySelectorAll<HTMLElement>("[data-sidebar-tile]")].map((tile) => tile.getBoundingClientRect());- setBeside(tilesClearCorner(tiles, grid.getBoundingClientRect().right));+ setBeside(tilesClearCorner(tiles, grid.getBoundingClientRect().right, buttons));};measure();if (typeof ResizeObserver === "undefined") return;const observer = new ResizeObserver(measure);observer.observe(grid);return () => observer.disconnect();- }, [corner, count]);+ }, [corner, count, buttons]);return { ref, beside };}-export function SidebarTileGrid({ primary, pinned, row, corner = false }: { primary: Bot | null; pinned: Bot[]; row: (bot: Bot) => BotRowProps; corner?: boolean }) {+export function SidebarTileGrid({ primary, pinned, row, corner = false, cornerButtons = 2 }: { primary: Bot | null; pinned: Bot[]; row: (bot: Bot) => BotRowProps; corner?: boolean; cornerButtons?: number }) {const order = usePinnedCircleDrag(pinned);- const besideCorner = useBesideCorner(corner, (primary ? 1 : 0) + order.ranked.length);+ const besideCorner = useBesideCorner(corner, (primary ? 1 : 0) + order.ranked.length, cornerButtons);if (!primary && order.ranked.length === 0) return null;return (<div ref={besideCorner.ref} data-sidebar-tiles="" data-beside-corner={besideCorner.beside ? "" : undefined}diff --git a/src/components/WindowFrameBar.test.ts b/src/components/WindowFrameBar.test.tsindex 9493d17982..3f1681f440 100644--- a/src/components/WindowFrameBar.test.ts+++ b/src/components/WindowFrameBar.test.ts@@ -182,5 +182,7 @@ describe("Simple's sidebar corner", () => {expect(tilesClearCorner([...row(2), ...row(1, 106)], 280), "a second row under it changes nothing").toBe(true);expect(tilesClearCorner(row(2), 240), "a narrower sidebar").toBe(false);expect(tilesClearCorner([], 280)).toBe(false);+ expect(tilesClearCorner(row(2), 280, 3), "Active Threads beside them while anything is active").toBe(false);+ expect(tilesClearCorner(row(1), 280, 3)).toBe(true);});});diff --git a/src/hooks/use-external-chat-links.test.ts b/src/hooks/use-external-chat-links.test.tsindex 3db26459d0..7094a009b8 100644--- a/src/hooks/use-external-chat-links.test.ts+++ b/src/hooks/use-external-chat-links.test.ts@@ -10,7 +10,7 @@ vi.mock("react", async (original) => ({}));vi.mock("@/lib/thread-preferences", () => ({ useShowThreads: () => fixture.showThreads }));-import { useExternalChatLinks } from "./use-external-chat-links";+import { useDesktopNotificationOpens, useExternalChatLinks } from "./use-external-chat-links";const scout: Bot = {id: "scout", threadId: "scout-main", name: "Scout", title: "", description: "", notifications: true,@@ -88,3 +88,39 @@ describe("useExternalChatLinks", () => {expect(dispatch).not.toHaveBeenCalled();});});++describe("useDesktopNotificationOpens", () => {+ const work = { ...scout, tasks: [...scout.tasks!, { threadId: "scout-work", title: "@CoS · work", createdAt: 2 }] };+ const ready: AppState = { ...initialState, bots: [work], selectedId: "scout", hydrated: true };+ const opens = (state: AppState, dispatch: (action: Action) => void) => {+ fixture.effects = [];+ useDesktopNotificationOpens(state, dispatch);+ return fixture.effects.map((effect) => effect());+ };++ it("holds a click until a page just loaded for it has its bots, then opens that thread once", () => {+ let deliver: ((target: unknown) => void) | undefined;+ const unsubscribe = vi.fn();+ vi.stubGlobal("window", { ogb: { desktopNotifications: { onOpen: (cb: (target: unknown) => void) => { deliver = cb; return unsubscribe; } } } });+ const dispatch = vi.fn();+ const [cleanup] = opens(loading, dispatch);+ expect(cleanup).toBe(unsubscribe);+ deliver!({ botId: "scout", threadId: "scout-work" });+ opens(loading, dispatch);+ expect(dispatch).not.toHaveBeenCalled();+ opens(ready, dispatch);+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([+ { type: "select", id: "scout" },+ { type: "switchTask", botId: "scout", threadId: "scout-work" },+ { type: "revealThread", threadId: "scout-work" },+ ]);+ expect(fixture.link).toBeNull();+ });++ it("subscribes to nothing on a browser or an older app", () => {+ vi.stubGlobal("window", {});+ const dispatch = vi.fn();+ expect(opens(ready, dispatch)[0]).toBeUndefined();+ expect(dispatch).not.toHaveBeenCalled();+ });+});diff --git a/src/hooks/use-external-chat-links.ts b/src/hooks/use-external-chat-links.tsindex 904fe23d60..a4e0a971b3 100644--- a/src/hooks/use-external-chat-links.ts+++ b/src/hooks/use-external-chat-links.ts@@ -1,7 +1,7 @@import { useEffect, useState } from "react";import { openChatLink } from "@/components/ThreadRefs";import { useShowThreads } from "@/lib/thread-preferences";-import type { Action, AppState } from "@/state/store";+import { openThread, type Action, type AppState, type ThreadTarget } from "@/state/store";export function useExternalChatLinks(state: AppState, dispatch: (action: Action) => void): void {const [link, setLink] = useState<string | null>(null);@@ -15,3 +15,15 @@ export function useExternalChatLinks(state: AppState, dispatch: (action: Action)openChatLink(dispatch, link, state, showThreads);}, [link, state, showThreads, dispatch]);}++/** A click on a notification main showed brought this page up, maybe a page just loaded for it. */+export function useDesktopNotificationOpens(state: AppState, dispatch: (action: Action) => void): void {+ const [target, setTarget] = useState<ThreadTarget | null>(null);+ const showThreads = useShowThreads();+ useEffect(() => window.ogb?.desktopNotifications?.onOpen(setTarget), []);+ useEffect(() => {+ if (!target || !state.hydrated) return;+ setTarget(null);+ openThread(dispatch, target, state, showThreads);+ }, [target, state, showThreads, dispatch]);+}diff --git a/src/lib/notify.test.ts b/src/lib/notify.test.tsindex 78a78ff9f7..4cb1dfb1ee 100644--- a/src/lib/notify.test.ts+++ b/src/lib/notify.test.ts@@ -159,6 +159,55 @@ describe("desktop notifications", () => {});});+describe("on the desktop app, where main shows the banner so its click outlives the page", () => {+ const flush = () => new Promise((resolve) => setTimeout(resolve, 0));+ function installBridge(answer: () => Promise<boolean>) {+ const installed = installNotification("granted");+ const show = vi.fn(answer);+ vi.stubGlobal("window", { focus: vi.fn(), ogb: { desktopNotifications: { show } } });+ return { ...installed, show };+ }++ it("asks main, with the thread to come back to, and shows no banner of its own", async () => {+ const { notices, show } = installBridge(async () => true);+ showNotification(frame, vi.fn(), "/api/attachments/face.png");+ await flush();+ expect(show).toHaveBeenCalledWith({+ title: frame.title, body: frame.body, tag: "openmausbot:bot-1", silent: false, picture: "/api/attachments/face.png", botId: "bot-1", threadId: "thread-1",+ });+ expect(notices).toHaveLength(0);+ });++ it("asks main for nothing without the person's permission or over the thread on screen, as ever", async () => {+ const denied = installBridge(async () => true);+ vi.stubGlobal("Notification", class { static permission = "denied"; });+ showNotification(frame, vi.fn());+ await flush();+ expect(denied.show).not.toHaveBeenCalled();+ const { show } = installBridge(async () => true);+ vi.stubGlobal("document", { hasFocus: () => true });+ showNotification(frame, vi.fn(), undefined, frame.threadId);+ await flush();+ expect(show).not.toHaveBeenCalled();+ });++ it.each([["says no", async () => false], ["fails", async () => { throw new Error("no handler"); }]])("shows its own when main %s, so a banner is never lost", async (_case, answer) => {+ const { notices } = installBridge(answer as () => Promise<boolean>);+ const onOpen = vi.fn();+ showNotification(frame, onOpen);+ await flush();+ expect(notices).toHaveLength(1);+ notices[0]!.onclick!();+ expect(onOpen).toHaveBeenCalledWith({ botId: "bot-1", threadId: "thread-1" });+ });++ it("keeps the page's own banner on an older app, which has no bridge for it", () => {+ const { notices } = installNotification("granted");+ showNotification(frame, vi.fn());+ expect(notices).toHaveLength(1);+ });+});+describe("notification sounds", () => {it("lets the platform play its sound by default", () => {const { notices } = installNotification("granted");diff --git a/src/lib/notify.ts b/src/lib/notify.tsindex 67304599f9..f677d483ba 100644--- a/src/lib/notify.ts+++ b/src/lib/notify.ts@@ -40,19 +40,24 @@ export function showNotification(if (frame.kind === "done" && !finishedNotificationsEnabled()) return;const spend = frame.kind === "spend";if (!spend && document.hasFocus() && visibleThreadId === frame.threadId) return;-- const open = () => {- window.focus();- onOpen({ botId: frame.botId, threadId: frame.threadId });+ if (Notification.permission !== "granted") return;++ const title = placeName ? `${placeName} · ${frame.title}` : frame.title;+ const options: NotificationOptions = {+ body: frame.body,+ ...buildNotificationOptions({ id: frame.botId, avatarUrl }),+ ...(spend ? { tag: "openmausbot:spend", icon: undefined } : {}),+ ...(notificationSoundsEnabled() ? {} : { silent: true }),};-- if (Notification.permission === "granted") {- const options: NotificationOptions = {- body: frame.body,- ...buildNotificationOptions({ id: frame.botId, avatarUrl }),- ...(spend ? { tag: "openmausbot:spend", icon: undefined } : {}),- ...(notificationSoundsEnabled() ? {} : { silent: true }),+ const shownByPage = () => {+ new Notification(title, options).onclick = () => {+ window.focus();+ onOpen({ botId: frame.botId, threadId: frame.threadId });};- new Notification(placeName ? `${placeName} · ${frame.title}` : frame.title, options).onclick = open;- }+ };+ const desktop = window.ogb?.desktopNotifications;+ if (!desktop) return shownByPage();+ void desktop.show({+ title, body: frame.body, tag: options.tag, silent: options.silent === true, picture: options.icon, botId: frame.botId, threadId: frame.threadId,+ }).then((shown) => { if (!shown) shownByPage(); }, shownByPage);}diff --git a/src/state/notification-open.test.ts b/src/state/notification-open.test.tsindex 059e12b2ae..8680c7b158 100644--- a/src/state/notification-open.test.ts+++ b/src/state/notification-open.test.ts@@ -45,7 +45,7 @@ let firstBot = "other";let state: AppState;let dispatch: (action: Action) => void;-const { StoreProvider, useStore, openBot } = await import("./store");+const { StoreProvider, useStore, openBot, openBotRow, openThread } = await import("./store");const { landOnSearchHit } = await import("@/lib/focus-message");const { threadsWhenTreeHidden } = await import("@/components/SidebarBotActivity");const { setAdvancedMode } = await import("@/lib/interface-mode");@@ -155,6 +155,7 @@ describe("following a notification", () => {it("selects the bot first while threads are shown, as it always has", async () => {await threadsShown(true);await followNotification();+ expect(state.revealThread?.threadId, "the thread it landed on is shown in the sidebar").toBe("finished");expect(reads()).toEqual(["left-behind", "finished"]);expect(sent().filter((request) => request.startsWith("/api/bots/scout/tasks/finished"))).toHaveLength(1);expect(scoutNow().threadId).toBe("finished");@@ -214,6 +215,39 @@ describe("opening a bot with threads hidden", () => {});});+describe("a click on a bot's message", () => {+ it("lands from a row on the unread thread its dot is about, and reads only that thread", async () => {+ await threadsShown(false);+ flushSync(() => openBotRow(dispatch, scoutNow(), false, false));+ await settle();+ expect(state.selectedId).toBe("scout");+ expect(scoutNow().threadId).toBe("finished");+ expect(reads()).toEqual(["finished"]);+ expect(unread("left-behind")).toBe(true);+ });++ it("lands from the bell on a thread another bot opened, over Settings, and the thread's row is revealed", async () => {+ await threadsShown(true);+ flushSync(() => dispatch({ type: "toggleAppSettings", open: true }));+ expect(state.appSettingsOpen).toBe(true);+ flushSync(() => { openThread(dispatch, { botId: "scout", threadId: "finished" }, state, true); });+ await settle();+ expect(state.appSettingsOpen).toBe(false);+ expect(state.selectedId).toBe("scout");+ expect(scoutNow().threadId).toBe("finished");+ expect(state.revealThread?.threadId).toBe("finished");+ });++ it("says a thread is gone instead of landing silently on some other chat", async () => {+ await threadsShown(false);+ let found = true;+ flushSync(() => { found = openThread(dispatch, { botId: "scout", threadId: "deleted" }, state, false); });+ await settle();+ expect(found).toBe(false);+ expect(state.notice).toEqual({ kind: "thread-gone", botName: "Scout" });+ });+});+describe("launching the app on a bot", () => {async function relaunch(shown: boolean) {flushSync(() => root.unmount());diff --git a/src/state/store.test.ts b/src/state/store.test.tsindex ec559bb743..61c050c3db 100644--- a/src/state/store.test.ts+++ b/src/state/store.test.ts@@ -15,7 +15,6 @@ import {liveCallFromFrame,loadSnapshotBoundary,openBot,- openNotificationTarget,openThread,persistBotUpdate,persistTaskApproval,@@ -831,57 +830,34 @@ describe("notification routing", () => {],}];- it("selects the bot and switches to the notification's exact task", () => {- const dispatch = vi.fn();-- openNotificationTarget(dispatch, { botId: "bot-1", threadId: "detached-thread" }, { bots, groups }, true);-- expect(dispatch.mock.calls.map(([action]) => action)).toEqual([- { type: "select", id: "bot-1" },- { type: "switchTask", botId: "bot-1", threadId: "detached-thread" },- ]);- });-- it("opens the room when the thread is a group's — never a bot task switch that would 404", () => {- const dispatch = vi.fn();-- openNotificationTarget(dispatch, { botId: "bot-1", threadId: "room-thread" }, { bots, groups }, true);-- expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "select", id: "room-1" }]);- });-- it("opens the requesting conversation when a teammate's routine reports there", () => {- const dispatch = vi.fn();- openNotificationTarget(dispatch, { botId: "runner", threadId: "detached-thread" }, {- bots: [...bots, { id: "runner", threadId: "runner-thread", tasks: [] }], groups,- }, true);- expect(dispatch.mock.calls.map(([action]) => action)).toEqual([- { type: "select", id: "bot-1" },- { type: "switchTask", botId: "bot-1", threadId: "detached-thread" },- ]);- });-- it("opens the room and restores the exact inactive channel task", () => {- const dispatch = vi.fn();-- openNotificationTarget(dispatch, { botId: "bot-1", threadId: "older-room-thread" }, { bots, groups }, true);-- expect(dispatch.mock.calls.map(([action]) => action)).toEqual([- { type: "select", id: "room-1" },- { type: "switchGroupTask", groupId: "room-1", threadId: "older-room-thread" },- ]);- });+ describe("openThread", () => {+ const named = bots.map((bot) => ({ ...bot, name: "Scout" }));- it("lands on a plain bot select for a thread it cannot place, not an error", () => {- const dispatch = vi.fn();+ it("opens the room when a notification's thread is a group's, never a bot switch that would 404", () => {+ const dispatch = vi.fn();+ openThread(dispatch, { botId: "bot-1", threadId: "room-thread" }, { bots: named, groups }, true);+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "select", id: "room-1" }, { type: "revealThread", threadId: "room-thread" }]);+ });- openNotificationTarget(dispatch, { botId: "bot-1", threadId: "deleted-task-thread" }, { bots, groups }, true);+ it("opens the conversation that owns the thread when a teammate's routine reports there", () => {+ const dispatch = vi.fn();+ openThread(dispatch, { botId: "runner", threadId: "detached-thread" }, { bots: [...named, { id: "runner", name: "Runner", threadId: "runner-thread", tasks: [] }], groups }, true);+ expect(dispatch.mock.calls.map(([action]) => action)).toEqual([+ { type: "select", id: "bot-1" },+ { type: "switchTask", botId: "bot-1", threadId: "detached-thread" },+ { type: "revealThread", threadId: "detached-thread" },+ ]);+ });- expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "select", id: "bot-1" }]);- });+ it("shows the thread in the sidebar whichever list a switch came from", () => {+ const switched = reducer({ ...initialState, bots: named as never }, { type: "switchTask", botId: "bot-1", threadId: "detached-thread" });+ expect(switched.revealThread?.threadId).toBe("detached-thread");+ });- describe("openThread", () => {- const named = bots.map((bot) => ({ ...bot, name: "Scout" }));+ it("takes down what covers the chat, so the click is seen to land", () => {+ const covered = { ...initialState, appSettingsOpen: true, shortcutsOpen: true, pluginsOpen: true };+ expect(reducer(covered, { type: "revealThread", threadId: "t" })).toMatchObject({ appSettingsOpen: false, shortcutsOpen: false, pluginsOpen: false });+ });it("selects the bot, switches the view to the thread and reveals its row", () => {const dispatch = vi.fn();@@ -908,6 +884,7 @@ describe("notification routing", () => {expect(openThread(dispatch, { botId: "bot-1", threadId: "deleted-thread" }, { bots: named, groups }, true)).toBe(false);expect(dispatch.mock.calls.map(([action]) => action)).toEqual([{ type: "select", id: "bot-1" },+ { type: "revealThread", threadId: "deleted-thread" },{ type: "notice", notice: { kind: "thread-gone", botName: "Scout" } },]);});@@ -916,6 +893,7 @@ describe("notification routing", () => {const dispatch = vi.fn();expect(openThread(dispatch, { botId: "deleted-bot", threadId: "deleted-thread" }, { bots: named, groups }, true)).toBe(false);expect(dispatch.mock.calls.map(([action]) => action)).toEqual([+ { type: "revealThread", threadId: "deleted-thread" },{ type: "notice", notice: { kind: "thread-gone", botName: null } },]);});@@ -962,8 +940,8 @@ describe("notification routing", () => {const followed = (threadId: string, threadsShown: boolean) => {const dispatch = vi.fn();- openNotificationTarget(dispatch, { botId: "bot-1", threadId }, { bots: [bot], groups: [] }, threadsShown);- return dispatch.mock.calls.map(([action]) => action as Action);+ openThread(dispatch, { botId: "bot-1", threadId }, { bots: [bot], groups: [] }, threadsShown);+ return dispatch.mock.calls.map(([action]) => action as Action).filter((action) => action.type !== "revealThread");};it("opens a thread a notification names without passing the reply the bot was left on as read, with threads hidden", () => {diff --git a/src/state/store.tsx b/src/state/store.tsxindex c977bf6ff9..4b421bbf21 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -19,7 +19,7 @@ import { DATA_ROUTES, type DataSheet, type DataTable } from "../../shared/data-simport type { NotificationLogEntry } from "../../shared/notification";import { isNotificationFeedAction, reduceNotificationFeed, type NotificationFeedAction } from "./notification-feed";import { bumpThreadUpdatedAt, mergeTaskStamps, rewindThreadUpdatedAt } from "./thread-stamps";-import { botOpensTo, openBot, openNotificationTarget, visibleNotificationThread } from "./thread-navigation";+import { botOpensTo, openBot, openThread, visibleNotificationThread } from "./thread-navigation";import { patchGroupTask } from "./thread-edits";import type { EngineInstall } from "./engine-install";import { optimisticMessageId, optimisticUserMessage, sendArrived, sendReconciled } from "./optimistic-send";@@ -27,7 +27,7 @@ import { patchedGroups, roomAnswers, snapshotPatch } from "./room-frames";import { savedStateAction, type SavedOwner, type SavedSnapshot } from "./saved-state";import { keepBotNavigation, keepGroupNavigation, navigatedSince, visibleMessages } from "./snapshot-navigation";export { visibleMessages } from "./snapshot-navigation";-export { awayFromMainThread, botOpensTo, openBot, openBotThread, openNotificationTarget, openThread, visibleNotificationThread, type ThreadTarget } from "./thread-navigation";+export { awayFromMainThread, botOpensTo, markedThread, openBot, openBotRow, openBotThread, openRoomThread, openThread, visibleNotificationThread, type ThreadTarget } from "./thread-navigation";import type { TurnDigest } from "../../shared/digest";import type { ToolScope } from "../../shared/tool-scope";import type { ModelVariantOption, RuntimeEvent } from "../../shared/runtime-events";@@ -1450,7 +1450,7 @@ export function reducer(state: AppState, action: Action): AppState {case "notice":return { ...state, notice: action.notice };case "revealThread":- return { ...state, revealThread: { threadId: action.threadId, nonce: (state.revealThread?.nonce ?? 0) + 1 } };+ return { ...state, appSettingsOpen: false, shortcutsOpen: false, pluginsOpen: false, revealThread: { threadId: action.threadId, nonce: (state.revealThread?.nonce ?? 0) + 1 } };case "focusMessage":return {...state,@@ -1736,7 +1736,7 @@ export function reducer(state: AppState, action: Action): AppState {return action.cwd !== undefined ? state : { ...state, selectedId: action.botId, activeView: "chat" };case "switchTask": {const { [action.threadId]: _old, ...backgroundThreadEvents } = state.backgroundThreadEvents;- return updateBot({ ...state, backgroundThreadEvents, selectedId: action.botId, activeView: "chat" }, action.botId,+ return updateBot({ ...state, backgroundThreadEvents, selectedId: action.botId, activeView: "chat", revealThread: { threadId: action.threadId, nonce: (state.revealThread?.nonce ?? 0) + 1 } }, action.botId,(bot) => ({ ...bot, switchingTo: action.threadId }));}case "switchTaskFailed":@@ -3181,7 +3181,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {// The wrapped dispatch: only it PATCHes unread:false back to the server.showNotification(frame.notification,- (target) => openNotificationTarget(dispatch, target, stateRef.current, showThreadsRef.current),+ (target) => openThread(dispatch, target, stateRef.current, showThreadsRef.current),stateRef.current.bots.find((bot) => bot.id === frame.notification.botId)?.avatarUrl,visibleNotificationThread(stateRef.current),);diff --git a/src/state/thread-navigation.test.ts b/src/state/thread-navigation.test.tsnew file mode 100644index 0000000000..c84778d204--- /dev/null+++ b/src/state/thread-navigation.test.ts@@ -0,0 +1,86 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { setTeamChats } from "./team-chats";+import { markedThread, openBotRow, openRoomThread } from "./thread-navigation";++type Task = { threadId: string; activity?: string; unread?: boolean; busy?: boolean; routineRunId?: string; archivedAt?: number; createdAt?: number; updatedAt?: number };+const chief = (tasks: Task[], threadId = "main", mainThreadId = "main") => ({ id: "cos", threadId, mainThreadId, tasks: [{ threadId: "main", createdAt: 1 }, ...tasks] });+const opened = (bot: ReturnType<typeof chief>, threadsShown: boolean, onScreen = false) => {+ const dispatch = vi.fn();+ openBotRow(dispatch, bot, threadsShown, onScreen);+ return dispatch.mock.calls.map(([action]) => action);+};++afterEach(() => setTeamChats(null));++describe("what a bot's row or tile is marked for", () => {+ it("is what waits on the person first, then an unread reply, then work under way", () => {+ const working = { threadId: "work", busy: true }, unread = { threadId: "reply", unread: true }, waiting = { threadId: "ask", activity: "waiting-on-you" };+ expect(markedThread(chief([working]), false)).toBe("work");+ expect(markedThread(chief([working, unread]), false)).toBe("reply");+ expect(markedThread(chief([working, unread, waiting]), false)).toBe("ask");+ });++ it("is the newest of equals, unless the thread the bot opens to is one of them", () => {+ const older = { threadId: "older", unread: true, updatedAt: 5 }, newer = { threadId: "newer", unread: true, updatedAt: 9 };+ expect(markedThread(chief([older, newer]), false)).toBe("newer");+ expect(markedThread({ ...chief([older, newer]), tasks: [{ threadId: "main", unread: true, createdAt: 1 }, older, newer] }, false)).toBe("main");+ });++ it("is never a routine's run, nor an archived thread unless it waits on the person, as the row's own dot reads them", () => {+ expect(markedThread(chief([{ threadId: "run", busy: true, routineRunId: "r" }]), false)).toBeNull();+ expect(markedThread(chief([{ threadId: "put-away", unread: true, archivedAt: 1 }]), false)).toBeNull();+ expect(markedThread(chief([{ threadId: "put-away", activity: "waiting-on-you", archivedAt: 0 }]), false)).toBe("put-away");+ });++ it("is nothing on a quiet bot", () => {+ expect(markedThread(chief([{ threadId: "quiet" }]), false)).toBeNull();+ expect(markedThread({ id: "x", threadId: "t" } as unknown as ReturnType<typeof chief>, false)).toBeNull();+ });+});++describe("a click on a bot's row or tile", () => {+ const work = { threadId: "work", unread: true };++ it("lands on the thread the dot is about, by the switch alone so the thread left behind stays unread", () => {+ expect(opened(chief([work]), false)).toEqual([{ type: "switchTask", botId: "cos", threadId: "work" }]);+ });++ it("selects first while threads are shown, as every thread opener does there", () => {+ expect(opened(chief([work]), true)).toEqual([{ type: "select", id: "cos" }, { type: "switchTask", botId: "cos", threadId: "work" }]);+ });++ it("lands on a thread a teammate's work is running in, and a second click comes back to the main chat", () => {+ const running = { threadId: "work", busy: true };+ expect(opened(chief([running]), false)).toEqual([{ type: "switchTask", botId: "cos", threadId: "work" }]);+ expect(opened(chief([running], "work"), false, true)).toEqual([{ type: "switchTask", botId: "cos", threadId: "main" }]);+ });++ it("opens the bot as ever when nothing is marked, or when the main chat itself is what is marked", () => {+ expect(opened(chief([{ threadId: "quiet" }]), false)).toEqual([{ type: "select", id: "cos" }]);+ expect(opened({ ...chief([work]), tasks: [{ threadId: "main", unread: true, createdAt: 1 }, { threadId: "work" }] }, false)).toEqual([{ type: "select", id: "cos" }]);+ });++ it("leaves a team's Cloud alone: there a bot's row is the person's own conversation", () => {+ setTeamChats({ teamId: "acme", member: true });+ const bot = { ...chief([work]), tasks: [{ threadId: "mine", private: true, createdAt: 3 }, work] };+ expect(opened(bot as ReturnType<typeof chief>, false)).toEqual([{ type: "switchTask", botId: "cos", threadId: "mine" }]);+ });+});++describe("a hand-off's chip for work in a room", () => {+ const room = { id: "room", threadId: "room-now", tasks: [{ threadId: "room-now" }, { threadId: "room-older" }] };+ const clicked = (comm: { groupId: string; threadId?: string }) => {+ const dispatch = vi.fn();+ openRoomThread(dispatch, comm, [room]);+ return dispatch.mock.calls.map(([action]) => action);+ };++ it("lands on the thread it names, not whichever the room is on", () => {+ expect(clicked({ groupId: "room", threadId: "room-older" })).toEqual([{ type: "select", id: "room" }, { type: "switchGroupTask", groupId: "room", threadId: "room-older" }]);+ });++ it("opens the room when it names no thread, or one the room no longer has", () => {+ expect(clicked({ groupId: "room" })).toEqual([{ type: "select", id: "room" }]);+ expect(clicked({ groupId: "room", threadId: "deleted" })).toEqual([{ type: "select", id: "room" }]);+ });+});diff --git a/src/state/thread-navigation.ts b/src/state/thread-navigation.tsindex a50681d0d7..5774b35c4e 100644--- a/src/state/thread-navigation.ts+++ b/src/state/thread-navigation.ts@@ -1,14 +1,15 @@-import type { NotificationTarget } from "@/lib/notify";import type { Action, AppState } from "./store";-import { openOwnTeamChat } from "./team-chats";+import { openOwnTeamChat, teamChats } from "./team-chats";interface NotificationThreadOwner {id: string;threadId: string;mainThreadId?: string;- tasks?: Array<{ threadId: string }>;+ tasks?: Array<RowThread>;}+type RowThread = { threadId: string; activity?: string; unread?: boolean; busy?: boolean; routineRunId?: unknown; archivedAt?: unknown; updatedAt?: number; createdAt?: number };+interface NotificationRoutingState {bots: NotificationThreadOwner[];groups: NotificationThreadOwner[];@@ -25,39 +26,6 @@ export function visibleNotificationThread();}-export function openNotificationTarget(- dispatch: (action: Action) => void,- target: NotificationTarget,- state: NotificationRoutingState,- threadsShown: boolean,-) {- // A room notification carries the asker bot with the room's thread id; switching the bot to it would 404.- const group = state.groups.find(- (candidate) =>- candidate.threadId === target.threadId ||- (candidate.tasks ?? []).some((task) => task.threadId === target.threadId),- );- if (group) {- dispatch({ type: "select", id: group.id });- if (group.threadId !== target.threadId) {- dispatch({ type: "switchGroupTask", groupId: group.id, threadId: target.threadId });- }- return;- }- const bot = state.bots.find((candidate) =>- candidate.threadId === target.threadId || candidate.tasks?.some((task) => task.threadId === target.threadId)- ) ?? state.bots.find((candidate) => candidate.id === target.botId);- if (!bot) {- dispatch({ type: "select", id: target.botId });- return;- }- const known =- bot.threadId === target.threadId ||- (bot.tasks ?? []).some((task) => task.threadId === target.threadId);- if (known) openBotThread(dispatch, bot, target.threadId, threadsShown);- else openBot(dispatch, bot, threadsShown);-}-export function botOpensTo(bot: Pick<NotificationThreadOwner, "threadId" | "mainThreadId" | "tasks">, threadsShown: boolean): string {return !threadsShown && bot.mainThreadId && bot.tasks?.some((task) => task.threadId === bot.mainThreadId)? bot.mainThreadId : bot.threadId;@@ -79,6 +47,37 @@ export function openBot(else openBotThread(dispatch, bot, opened, threadsShown);}+const markRank = (task: RowThread): number | null => {+ if (task.routineRunId) return null;+ if (task.activity === "waiting-on-you") return 0;+ if (task.archivedAt !== undefined) return null;+ if (task.unread) return 1;+ return task.busy || task.activity === "working" ? 2 : null;+};++/** The thread a bot's row or tile is marked for: what waits on the person, then an unread reply, then work under way. The+ * thread the bot opens to wins a tie, then the newest. Null when the row has no mark. */+export function markedThread(bot: Pick<NotificationThreadOwner, "threadId" | "mainThreadId" | "tasks">, threadsShown: boolean): string | null {+ const home = botOpensTo(bot, threadsShown);+ const stamp = (task: RowThread) => task.updatedAt ?? task.createdAt ?? 0;+ const marked = (bot.tasks ?? []).flatMap((task) => { const rank = markRank(task); return rank === null ? [] : [{ task, rank }]; })+ .sort((a, b) => a.rank - b.rank || Number(b.task.threadId === home) - Number(a.task.threadId === home) || stamp(b.task) - stamp(a.task));+ return marked[0]?.task.threadId ?? null;+}++/** A click on a bot's row or tile opens the thread its mark is about; with no mark, or with that thread already on screen,+ * the bot as ever. Every other way into a bot is `openBot`. On a team a bot's row is the person's own chat. */+export function openBotRow(+ dispatch: (action: Action) => void,+ bot: Pick<NotificationThreadOwner, "id" | "threadId" | "mainThreadId" | "tasks"> & { yourAccess?: string },+ threadsShown: boolean,+ onScreen: boolean,+) {+ const marked = teamChats() ? null : markedThread(bot, threadsShown);+ if (!marked || marked === botOpensTo(bot, threadsShown) || (onScreen && marked === bot.threadId)) openBot(dispatch, bot, threadsShown);+ else openBotThread(dispatch, bot, marked, threadsShown);+}+/** With threads hidden the switch alone selects the bot, so the thread left behind keeps its unread mark. */export function openBotThread(dispatch: (action: Action) => void,@@ -90,6 +89,13 @@ export function openBotThread(dispatch({ type: "switchTask", botId: bot.id, threadId });}+/** A hand-off's chip for work in a room: the thread it names while the room still has it, else the room. */+export function openRoomThread(dispatch: (action: Action) => void, comm: { groupId: string; threadId?: string }, groups: readonly NotificationThreadOwner[]) {+ dispatch({ type: "select", id: comm.groupId });+ const room = groups.find((candidate) => candidate.id === comm.groupId);+ if (comm.threadId && room?.tasks?.some((task) => task.threadId === comm.threadId)) dispatch({ type: "switchGroupTask", groupId: comm.groupId, threadId: comm.threadId });+}+export interface ThreadTarget {botId: string;threadId: string;@@ -99,6 +105,8 @@ interface ThreadOpeningState extends NotificationRoutingState {bots: Array<NotificationThreadOwner & { name: string }>;}+/** The one way a click on a bot's message reaches its thread, wherever the thread is and whoever started it: a room's, or+ * any bot's own. A thread that is gone says so on its bot, never silently on some other chat. */export function openThread(dispatch: (action: Action) => void,target: ThreadTarget,@@ -107,13 +115,16 @@ export function openThread(): boolean {const owns = (owner: NotificationThreadOwner) =>owner.threadId === target.threadId || (owner.tasks ?? []).some((task) => task.threadId === target.threadId);- if (state.groups.some(owns) || state.bots.some(owns)) {- openNotificationTarget(dispatch, target, state, threadsShown);- dispatch({ type: "revealThread", threadId: target.threadId });- return true;- }- const bot = state.bots.find((candidate) => candidate.id === target.botId);- if (bot) openBot(dispatch, bot, threadsShown);- dispatch({ type: "notice", notice: { kind: "thread-gone", botName: bot?.name ?? null } });+ // A room notification carries the asker bot with the room's thread id; switching the bot to it would 404.+ const group = state.groups.find(owns), owner = group ? undefined : state.bots.find(owns);+ const named = state.bots.find((candidate) => candidate.id === target.botId);+ if (group) {+ dispatch({ type: "select", id: group.id });+ if (group.threadId !== target.threadId) dispatch({ type: "switchGroupTask", groupId: group.id, threadId: target.threadId });+ } else if (owner) openBotThread(dispatch, owner, target.threadId, threadsShown);+ else if (named) openBot(dispatch, named, threadsShown);+ dispatch({ type: "revealThread", threadId: target.threadId });+ if (group || owner) return true;+ dispatch({ type: "notice", notice: { kind: "thread-gone", botName: named?.name ?? null } });return false;}diff --git a/src/types/ogb.d.ts b/src/types/ogb.d.tsindex df2fd31d88..9285d5c561 100644--- a/src/types/ogb.d.ts+++ b/src/types/ogb.d.ts@@ -138,6 +138,7 @@ const __APP_VERSION__: string;/** This computer's page, and My Cloud's own page once it is the person's home: the window onto My Cloud. */home?: import("../../electron/home-window.mjs").HomeBridge;desktopNotices?: import("../../electron/desktop-prefs.mjs").DesktopNoticesBridge;+ desktopNotifications?: import("../../electron/desktop-notifications.mjs").DesktopNotificationsBridge;/** This computer's own page only: the account's full name, for a first run's profile (system-name.mjs). */desktopProfile?: { systemName(): Promise<string | null> };desktopAnalytics?: import("../../electron/desktop-prefs.mjs").DesktopAnalyticsBridge;