Skip to content

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

Bot link: tell the other place every bot change, list both places' bots when a name is not found, and keep turn-off durable

milind-soni5cacc2d69377
diff --git a/server/bot-link.e2e.test.ts b/server/bot-link.e2e.test.ts
index fa6b9c3da7..d3ba26f4bf 100644
--- a/server/bot-link.e2e.test.ts
+++ b/server/bot-link.e2e.test.ts
@@ -223,3 +223,56 @@ it("a bot on the computer and a bot on the person's own server hand each other w
await Promise.all(fixtures.map((fixture) => fixture.close()));
}
}, 180_000);
+
+it("bots made, renamed, hidden or shown after the link is on reach the other place without a new session, and a name it cannot find is answered with both places' bots", async () => {
+ const fixtures = [await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true }),
+ await launchVerificationServer({}, undefined, undefined, undefined, undefined, { scripted: true })];
+ const computer = place(fixtures[0]!), home = place(fixtures[1]!);
+ try {
+ const writer = (await computer.cli("new-bot", "--name", "Writer")).bot;
+ const pairing = await home.api("POST", "/api/auth/pairing", { label: "The person's app", scopes: ["admin", "client"] });
+ const owner = (await home.api("POST", "/api/auth/pair", { code: pairing.code })).token as string;
+ const thisComputer = { id: (await computer.api("GET", "/.well-known/openmausbot/environment")).environmentId as string, name: "Sam's Mac" };
+ const paired = await home.api("POST", "/api/bot-link/pair", { computer: thisComputer, name: "My server" }, { token: owner });
+ await computer.api("PUT", "/api/bot-link", { on: true, origin: home.url, token: paired.token, name: "Sam's Mac", cloud: paired.place });
+ await expect.poll(async () => (await computer.api("GET", "/api/bot-link")).online, { timeout: 15_000 }).toBe(true);
+ const farNames = async (side: typeof computer) => ((await side.api("GET", "/api/bot-link/bots")).bots as any[]).map((row) => row.name).sort();
+ await expect.poll(() => farNames(home), { timeout: 15_000 }).toContain("Writer");
+
+ // Made on the server after the link is on: the computer lists it and finds it by its address.
+ const late = (await home.cli("new-bot", "--name", "Latecomer")).bot;
+ const address = linkedAddress(paired.place.id, late.id);
+ await expect.poll(() => farNames(computer), { timeout: 10_000 }).toContain("Latecomer");
+ expect(JSON.stringify(await computer.api("GET", `/api/bots/${address}`))).toContain("\"Latecomer\"");
+ // Renamed, hidden and shown again there: each reaches the computer as it happens.
+ await home.api("PATCH", `/api/bots/${late.id}/profile`, { name: "Lateblossom" });
+ await expect.poll(() => farNames(computer), { timeout: 10_000 }).toContain("Lateblossom");
+ expect(await farNames(computer)).not.toContain("Latecomer");
+ await home.api("PATCH", `/api/bots/${late.id}`, { hidden: true });
+ await expect.poll(() => farNames(computer), { timeout: 10_000 }).not.toContain("Lateblossom");
+ await computer.api("GET", `/api/bots/${address}`, undefined, { status: 404 });
+ await home.api("PATCH", `/api/bots/${late.id}`, { hidden: false });
+ await expect.poll(() => farNames(computer), { timeout: 10_000 }).toContain("Lateblossom");
+ // And the other way: a bot made on the computer reaches the server.
+ await computer.cli("new-bot", "--name", "Deskmate");
+ await expect.poll(() => farNames(home), { timeout: 10_000 }).toContain("Deskmate");
+
+ // A name no bot of either place has: the bot hears the bots of both places it can reach, and never that bots work
+ // only within one place. Two bots of the server with one name: it is asked which one, by id.
+ const twins = [(await home.cli("new-bot", "--name", "Twin")).bot, (await home.cli("new-bot", "--name", "Twin")).bot];
+ await expect.poll(async () => (await farNames(computer)).filter((name) => name === "Twin").length, { timeout: 10_000 }).toBe(2);
+ computer.plan(writer.id, { steps: [{ tool: "coordinate_bots", arguments: { bot_ids: ["Nobody"], request_key: "nobody", message: "Count the orders." }, expectError: true },
+ { tool: "coordinate_bots", arguments: { bot_ids: ["Twin"], request_key: "twin", message: "Count the orders." }, expectError: true }], reply: "Could not ask." });
+ await computer.cli("send", "--bot", writer.id, "--task", writer.activeTaskId, "--text", "Ask Nobody, then Twin, for the orders.");
+ expect((await computer.cli("wait", "--bot", writer.id, "--task", writer.activeTaskId, "--timeout", "30")).status).toBe("settled");
+ const said = ((computer.providerTurns().filter((turn) => turn.botId === writer.id).at(-1)?.evidence ?? []) as any[]).filter((entry) => entry?.step).map((entry) => JSON.stringify(entry.response));
+ expect(said).toHaveLength(2);
+ expect(said[0]).toContain("No bot with id or name");
+ expect(said[0]).toContain(`Lateblossom on My server (id ${address})`);
+ expect(said[0]).not.toMatch(/only within one place|can't be reached from here/u);
+ for (const twin of twins) expect(said[1]).toContain(linkedAddress(paired.place.id, twin.id));
+ expect(said[1]).toContain("Send it again with the id of the one you mean");
+ } finally {
+ await Promise.all(fixtures.map((fixture) => fixture.close()));
+ }
+}, 180_000);
diff --git a/server/bot-link/dial.ts b/server/bot-link/dial.ts
index 32be23eb1c..c125c9d93b 100644
--- a/server/bot-link/dial.ts
+++ b/server/bot-link/dial.ts
@@ -96,7 +96,9 @@ export function createDialer({ link, fetch: fetchImpl = fetch, log = () => {}, h
const stopWanted = link.onWanted(() => { if (stopped) return; asleep = false; retryMs = firstRetryMs; wakeUp?.(); });
async function exchange(target: { origin: string; token: string }, peer: string): Promise<void> {
- if (fresh) link.sessionStarted(peer);
+ // A new session takes everything the Cloud sends again from the start: a Cloud that ended this link and paired it again
+ // numbers its frames from one again, and a count kept from before would pass over its hello.
+ if (fresh) { link.sessionStarted(peer); ack = 0; }
const sending = link.outgoing(peer, 0);
const controller = new AbortController();
active = controller;
diff --git a/server/bot-link/link.test.ts b/server/bot-link/link.test.ts
index 409f67fce8..8c77da3fe9 100644
--- a/server/bot-link/link.test.ts
+++ b/server/bot-link/link.test.ts
@@ -1206,6 +1206,132 @@ describe("the link between a computer and its Cloud", () => {
expect(cloud.link.linked().some((one) => one.bot.name === "Odd")).toBe(false);
});
+ it("bots made, renamed and hidden while the link is on reach the other place in one hello per burst, and a change it is not told of sends none", async () => {
+ const { computer, cloud } = await two();
+ const hellos: string[][] = [];
+ const receive = cloud.link.receive;
+ cloud.link.receive = (peer, frames) => { for (const frame of frames as Frame[]) if (frame.t === "hello") hellos.push(frame.bots.map((bot) => bot.name)); receive(peer, frames); };
+ // A burst: one made, renamed, and one made hidden. The Cloud hears once, the list as it ended.
+ computer.bots.push({ id: "late", name: "Latecomer" });
+ computer.link.botsChanged();
+ computer.bots.find((bot) => bot.id === "late")!.name = "Lateblossom";
+ computer.link.botsChanged();
+ computer.bots.push({ id: "quiet", name: "Quiet", hidden: true });
+ computer.link.botsChanged();
+ await until(() => cloud.link.linked().some((one) => one.bot.name === "Lateblossom"), "the Cloud hears of the new bot");
+ // (The session's own hellos may still arrive: only the ones that carry the new bot count.)
+ const told = () => hellos.filter((names) => names.includes("Lateblossom"));
+ expect(told()).toEqual([["Scout", "Writer", "Lateblossom"]]);
+ expect(hellos.some((names) => names.includes("Latecomer") || names.includes("Quiet"))).toBe(false);
+ expect(cloud.link.resolve("Lateblossom")?.bot.id).toBe("late");
+ // A change the Cloud is not told of (a hidden bot's name) sends nothing; the next change it sees is one more hello.
+ computer.bots.find((bot) => bot.id === "quiet")!.name = "Quieter";
+ computer.link.botsChanged();
+ const before = hellos.length;
+ await new Promise((resolve) => setTimeout(resolve, 1_000));
+ expect(hellos).toHaveLength(before);
+ computer.bots.find((bot) => bot.id === "late")!.hidden = true;
+ computer.link.botsChanged();
+ await until(() => !cloud.link.linked().some((one) => one.bot.id === "late"), "the Cloud drops the hidden bot");
+ expect(hellos.slice(before)).toEqual([["Scout", "Writer"]]);
+ expect(told()).toHaveLength(1);
+ expect(cloud.link.resolve(onComputer("late"))).toBeUndefined();
+ // And the other way, over the same session.
+ cloud.bots.push({ id: "cloud-late", name: "Nimbus" });
+ cloud.link.botsChanged();
+ await until(() => computer.link.resolve("Nimbus")?.bot.id === "cloud-late", "the computer hears of the Cloud's new bot");
+ });
+
+ it("a bot moved to the Cloud is found there at once, and the computer's stub of it is no longer listed or answered there", async () => {
+ const { computer, cloud } = await two();
+ computer.bots.push({ id: "moved-bot-1", name: "Mover" });
+ computer.link.botsChanged();
+ await until(() => cloud.link.resolve(onComputer("moved-bot-1")) !== undefined, "the Cloud knows the computer's bot");
+ // The move: the bot is the Cloud's now; the computer keeps a hidden stub that says where it went.
+ cloud.bots.push({ id: "moved-bot-1", name: "Mover" });
+ cloud.link.botsChanged();
+ Object.assign(computer.bots.find((bot) => bot.id === "moved-bot-1")!, { hidden: true, movedTo: { team: { id: "my-cloud", name: "My Cloud" }, state: "moved" } });
+ computer.link.botsChanged();
+ await until(() => computer.link.resolve("Mover")?.bot.id === "moved-bot-1" && cloud.link.resolve(onComputer("moved-bot-1")) === undefined, "both places hear of the move");
+ expect(cloud.link.linked().some((one) => one.bot.id === "moved-bot-1")).toBe(false);
+ const { receipts } = await computer.handOff("local-writer", call(["Mover"], "Answer from My Cloud"));
+ expect(receipts[0]).toMatchObject({ botId: onCloud("moved-bot-1"), outcome: "queued" });
+ await until(() => cloud.runs.some((run) => run.botId === "moved-bot-1"), "the moved bot works on the Cloud");
+ });
+
+ it("with the link on, two bots of the other place with one name are not guessed between: the bot is asked which, by id", async () => {
+ const { computer, cloud } = await two();
+ cloud.bots.push({ id: "cloud-analyst-2", name: "Analyst" });
+ cloud.link.botsChanged();
+ await until(() => computer.link.linked().length === 3, "the computer hears of the second Analyst");
+ let asked = false;
+ const { answer } = await computer.handOff("local-writer", call(["Analyst"], "Count the orders"), async () => { asked = true; return { status: 200, body: {} }; });
+ expect(asked).toBe(false);
+ expect(answer.status).toBe(403);
+ expect(answer.body.error).toContain(`Analyst on My Cloud (id ${onCloud("cloud-analyst")})`);
+ expect(answer.body.error).toContain(`Analyst on My Cloud (id ${onCloud("cloud-analyst-2")})`);
+ expect(answer.body.error).toContain("Send it again with the id of the one you mean");
+ expect(computer.link.reachableElsewhere()).toBe(`Through the link to My Cloud you can also reach: Atlas on My Cloud (id ${onCloud("shared")}), Analyst on My Cloud (id ${onCloud("cloud-analyst")}), Analyst on My Cloud (id ${onCloud("cloud-analyst-2")}).`);
+ await computer.fetch("PUT", STATE_PATH, { on: false });
+ expect(computer.link.reachableElsewhere()).toBe("");
+ });
+
+ it("turned off and the computer's server stopped while it tells a Cloud that cannot answer: the end is already written, and the Cloud drops the computer's bots when it is told", async () => {
+ const { computer, cloud, cloudOrigin } = await two();
+ const at = cloud.port;
+ await cloud.unplug();
+ // Something answers at the Cloud's address but never replies, as a Cloud waking slowly does.
+ const silent = createServer(() => {});
+ const held = new Set<import("node:net").Socket>();
+ silent.on("connection", (socket) => { held.add(socket); });
+ await new Promise<void>((resolve) => silent.listen(at, "127.0.0.1", resolve));
+ const turningOff = computer.fetch("PUT", STATE_PATH, { on: false }).catch(() => null);
+ // Written at once, not after the Cloud's answer could have come (its wait is five seconds).
+ await until(() => existsSync(join(computer.dir, "bot-link-ended.json")), "the end is written before the Cloud is asked", 3_000);
+ expect(existsSync(join(computer.dir, "bot-link.json"))).toBe(false);
+ // The computer's server is stopped mid-way, and starts again.
+ await computer.restart();
+ await turningOff;
+ for (const socket of held) socket.destroy();
+ await new Promise<void>((resolve) => silent.close(() => resolve()));
+ expect(computer.link.on()).toBe(false);
+ expect((await computer.fetch("GET", STATE_PATH)).body).toEqual({ on: false, ended: [cloudOrigin] });
+ await cloud.listen(at);
+ expect(cloud.link.linked().length).toBeGreaterThan(0);
+ // The app says that Cloud is awake: it is told, and the computer's bots go there at once.
+ await computer.fetch("PUT", STATE_PATH, { cloud: "awake", origin: cloudOrigin });
+ expect(cloud.link.linked()).toEqual([]);
+ expect(cloud.link.on()).toBe(false);
+ expect(existsSync(join(computer.dir, "bot-link-ended.json"))).toBe(false);
+ });
+
+ it("turned off while the Cloud sleeps: the sleeping Cloud is not asked, and turning the link on again there ends the earlier one", async () => {
+ const { computer, cloud, cloudOrigin } = await two();
+ await computer.fetch("PUT", STATE_PATH, { cloud: "asleep", origin: cloudOrigin });
+ const before = cloud.requests.length;
+ expect((await computer.fetch("PUT", STATE_PATH, { on: false })).body).toEqual({ on: false, ended: [cloudOrigin] });
+ expect(cloud.requests.length).toBe(before);
+ await computer.restart();
+ expect(cloud.link.linked().length).toBeGreaterThan(0);
+ await pair(computer, cloud, cloudOrigin);
+ await until(() => !existsSync(join(computer.dir, "bot-link-ended.json")), "the earlier link's end is told");
+ expect(cloud.sessions()).toHaveLength(1);
+ });
+
+ it("a Cloud that ended the link and paired it again without restarting is heard: its bots are listed again", async () => {
+ const { computer, cloud, cloudOrigin } = await two();
+ await computer.dialer.stop();
+ cloud.link.unpair("computer-environment");
+ expect(cloud.link.on()).toBe(false);
+ computer.dialer.start();
+ await until(() => computer.dialer.state().needsPairing, "the computer hears the Cloud refuse");
+ // What the computer holds of the Cloud's bots is emptied, so only the new session's hello can fill it again.
+ computer.link.receive(CLOUD, [{ t: "hello", place: { id: "cloud-environment", name: "My Cloud" }, bots: [] }]);
+ expect(computer.link.linked()).toEqual([]);
+ await pair(computer, cloud, cloudOrigin);
+ expect(computer.link.linked().map((one) => one.bot.name)).toEqual(["Atlas", "Analyst"]);
+ });
+
it("the link's sign-in reaches the link's own routes and nothing else", () => {
const linked = { userId: "bot-link:computer-environment" };
expect(linkSessionRefusal(linked, "POST", SYNC_PATH)).toBeNull();
diff --git a/server/bot-link/link.ts b/server/bot-link/link.ts
index fab19416dd..0efc905bf6 100644
--- a/server/bot-link/link.ts
+++ b/server/bot-link/link.ts
@@ -51,6 +51,8 @@ const FILE_TRIES = 3;
/** A file that could not cross yet is tried again after this long, doubling up to five minutes. */
const FILE_RETRY_MS = 5_000;
const FILE_RETRY_MAX_MS = 5 * 60_000;
+/** This place's bots changed: the other places hear the new list once changes settle, so a burst of them is one hello. */
+const TELL_AFTER_MS = 250;
/** How a computer moves a file's bytes: it puts the ones it sends and gets the ones it is sent. `holds`: the Cloud already
* has this file, so it is not sent again. `gone` on an error: the Cloud said it will not take it or has no such file, so
@@ -156,6 +158,8 @@ export interface BotLinkDeps {
revoke?(sessionId: string): void;
now?: () => number;
log?(line: string): void;
+ /** How long after a change to this place's bots the other places are told (TELL_AFTER_MS). */
+ tellAfterMs?: number;
}
export interface CoordinateContext {
@@ -170,8 +174,9 @@ export interface CoordinateContext {
handed(nodeId: string): void;
}
type Remote = { peer: string; bot: LinkedBot };
-/** `level`: what that place's version reads (protocol.ts), 1 until it says more. `told`: the level its last hello was made for. */
-type Live = { online: boolean; seq: number; outbox: Numbered[]; level: number; told?: number };
+/** `level`: what that place's version reads (protocol.ts), 1 until it says more. `told`: the level its last hello was made
+ * for, and `bots` the list it carried. */
+type Live = { online: boolean; seq: number; outbox: Numbered[]; level: number; told?: number; bots?: string };
export type BotLink = ReturnType<typeof createBotLink>;
@@ -194,7 +199,8 @@ export function createBotLink(deps: BotLinkDeps) {
/** Hand-offs whose result came: the rest that end here (cut by restarts, refused, stopped) are stopped where they run. */
const resulted = new Set<string>();
let alive: NodeJS.Timeout | undefined;
- let toldBots = "";
+ /** A change to this place's bots waits here to be told. */
+ let telling: NodeJS.Timeout | undefined;
/** Hand-offs whose files are being taken in, and results whose files are being sent: one at a time each. */
const accepting = new Set<string>(), resultsGoing = new Set<string>();
/** What waits to be tried again because a file could not cross yet, by what it is for. */
@@ -221,13 +227,23 @@ export function createBotLink(deps: BotLinkDeps) {
}
/** A place on the first version takes a hello only with the fields that version knows. */
const basic = ({ id, name, title, description, model, level }: LinkedBot): LinkedBot => ({ id, name, ...(title ? { title } : {}), ...(description ? { description } : {}), ...(model ? { model } : {}), ...(level ? { level } : {}) });
- const hello = (peer: string) => {
+ const hello = (peer: string, bots = directory()) => {
if (!state) return;
- const bots = directory(), one = linkOf(peer);
- toldBots = JSON.stringify(bots);
+ const one = linkOf(peer);
+ one.bots = JSON.stringify(bots);
one.told = one.level;
+ // A hello not yet taken says less than this one: only the newest goes.
+ one.outbox = one.outbox.filter((entry) => entry.frame.t !== "hello");
send(peer, { t: "hello", place: state.self, bots: one.level >= 2 ? bots : bots.map(basic) });
};
+ /** Each place that was told this place's bots and now holds another list hears the new one. A place not yet in a session
+ * hears it when its session starts, and one that is away when it is back. */
+ const tellBots = () => {
+ telling = undefined;
+ if (!state) return;
+ const bots = directory(), listed = JSON.stringify(bots);
+ for (const peer of Object.keys(state.peers)) { const one = live.get(peer); if (one?.bots !== undefined && one.bots !== listed) hello(peer, bots); }
+ };
const spoolRoot = join(deps.dataDir, SPOOL);
const spoolOf = (peer: string, id: string) => join(spoolRoot, createHash("sha256").update(`${peer}\0${id}`).digest("hex").slice(0, 32));
@@ -316,16 +332,27 @@ export function createBotLink(deps: BotLinkDeps) {
* A bot's id here, in any case, or the start of one (8+ characters), stays with the local resolver, so a bot elsewhere
* named after it never takes that bot's work or its files. */
function resolve(raw: string): Remote | undefined {
- if (!state) return undefined;
+ const matches = candidates(raw);
+ return matches.length === 1 ? matches[0] : undefined;
+ }
+ /** Every bot of another place `raw` could name, by the rules of `resolve`: one is that bot, more say nothing. */
+ function candidates(raw: string): Remote[] {
+ if (!state) return [];
const wanted = raw.trim(), lower = wanted.toLowerCase();
const local = deps.bots();
- if (local.some((bot) => bot.id.toLowerCase() === lower)) return undefined;
- if (isLinkedId(wanted)) return remoteOf(wanted);
- if (isIdStart(wanted) && local.some((bot) => bot.id.toLowerCase().startsWith(lower))) return undefined;
+ if (local.some((bot) => bot.id.toLowerCase() === lower)) return [];
+ if (isLinkedId(wanted)) { const remote = remoteOf(wanted); return remote ? [remote] : []; }
+ if (isIdStart(wanted) && local.some((bot) => bot.id.toLowerCase().startsWith(lower))) return [];
const named = foldName(wanted);
- if (!named || local.some((bot) => !bot.hidden && foldName(bot.name) === named)) return undefined;
- const matches = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => foldName(bot.name) === named).map((bot) => ({ peer, bot })));
- return matches.length === 1 ? matches[0] : undefined;
+ if (!named || local.some((bot) => !bot.hidden && foldName(bot.name) === named)) return [];
+ return Object.entries(state.peers).flatMap(([peer, known]) => known.bots.filter((bot) => foldName(bot.name) === named).map((bot) => ({ peer, bot })));
+ }
+ /** A name more than one bot of the other places has (and no bot here): which one is meant, by its address. */
+ function sharedName(raw: string): string | null {
+ const matches = candidates(raw);
+ if (matches.length < 2) return null;
+ const listed = matches.slice(0, 12).map((remote) => `${remote.bot.name} on ${placeName(remote.peer)} (id ${linkedId(remote.peer, remote.bot.id)})`).join("; ");
+ return `${matches.length} bots of the person's other places are named "${raw.trim().slice(0, 120)}", so nothing was sent: ${listed}${matches.length > 12 ? `; and ${matches.length - 12} more` : ""}. Send it again with the id of the one you mean.`;
}
const offlineNote = (peer: string) => `${placeName(peer)} is offline now (off, asleep or not connected), so this waits and is delivered when it is back`;
@@ -612,8 +639,11 @@ export function createBotLink(deps: BotLinkDeps) {
if (!state) return;
const was = state;
state = null;
- try { rmSync(file, { force: true }); } catch (error) { log(`bot link: its record was not removed (${String(error)})`); }
+ clearTimeout(telling);
+ telling = undefined;
+ // The end is written down before the link's record goes, so a server stopped in between still tells its Cloud later.
if (!told && was.role === "dialer" && was.origin && was.token) writeEnded([...readEnded().filter((one) => one.token !== was.token), { origin: was.origin, token: was.token, at: now() }]);
+ try { rmSync(file, { force: true }); } catch (error) { log(`bot link: its record was not removed (${String(error)})`); }
if (was.role === "acceptor") for (const known of Object.values(was.peers)) if (known.sessionId) deps.revoke?.(known.sessionId);
const peers = [...live.keys()];
live.clear();
@@ -633,6 +663,7 @@ export function createBotLink(deps: BotLinkDeps) {
/** coordinate_bots for targets that live in another place; the rest go on as they always did (`local`). */
async function coordinate(call: CoordinateBotsCall, context: CoordinateContext, local: (call: CoordinateBotsCall) => Promise<CoordinateResult>): Promise<CoordinateResult> {
if (!state || context.external) return local(call);
+ for (const raw of call.botIds) { const shared = sharedName(raw); if (shared) return { status: 403, body: { error: shared } }; }
const away = new Map<string, Remote>();
for (const raw of call.botIds) { const remote = resolve(raw); if (remote) away.set(raw, remote); }
if (away.size === 0) return local(call);
@@ -766,6 +797,16 @@ export function createBotLink(deps: BotLinkDeps) {
/** Every bot of every linked place, with its address here. `kind`: what that place is, in the words the sidebar's
* own rows use for where a bot lives: a computer links to its Cloud, a Cloud to computers. */
linked: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), peer, place: known.place, kind: state!.role === "dialer" ? "cloud" as const : "computer" as const, online: isOnline(peer), bot }))),
+ /** What a bot that named no bot here or there is told past "no such bot" while the link is on: the other places' bots
+ * it can reach through the link, each by the id that reaches it. */
+ reachableElsewhere(): string {
+ if (!state) return "";
+ const far = Object.entries(state.peers).flatMap(([peer, known]) => known.bots.map((bot) => ({ peer, bot })));
+ const places = [...new Set(Object.keys(state.peers).map(placeName))].join(", ");
+ if (!far.length) return `This place is linked to ${places}, but no bot there can be reached through the link now.`;
+ const listed = far.slice(0, 12).map(({ peer, bot }) => `${bot.name} on ${placeName(peer)} (id ${linkedId(peer, bot.id)})`).join(", ");
+ return `Through the link to ${places} you can also reach: ${listed}${far.length > 12 ? `, and ${far.length - 12} more` : ""}.`;
+ },
/** Other places' bots as list_bots names them. */
agents: () => Object.entries(state?.peers ?? {}).flatMap(([peer, known]) => known.bots.map((bot) => ({ id: linkedId(peer, bot.id), name: bot.name, section: "", model: bot.model ?? "", busy: false,
status: isOnline(peer) ? "linked" : "offline", statusText: isOnline(peer) ? `on ${known.place.name}` : `on ${known.place.name}, offline now: work for it waits until it is back`,
@@ -817,8 +858,13 @@ export function createBotLink(deps: BotLinkDeps) {
},
/** Housekeeping, at start and once a day: old records go, and on the Cloud a computer long gone is unlinked. */
tidy(): void { prune(); expire(); sweep(); },
- /** This place's bots changed: connected places hear the new list. */
- botsChanged(): void { if (state && JSON.stringify(directory()) !== toldBots) for (const [peer, one] of live) if (one.online) hello(peer); },
+ /** This place's bots changed (one was made, renamed, hidden, moved, deleted, its look, model or level changed): once
+ * changes settle, the other places hear the new list, and nothing when what they are told did not change. */
+ botsChanged(): void {
+ if (!state || telling) return;
+ telling = setTimeout(tellBots, deps.tellAfterMs ?? TELL_AFTER_MS);
+ telling.unref?.();
+ },
setOnline,
/** What that place's version reads, as its last exchange said. One that turns out to read more than its last hello
* was made for is told again, in full. */
@@ -881,6 +927,6 @@ export function createBotLink(deps: BotLinkDeps) {
onWanted(listener: () => void): () => void { wantedListeners.add(listener); return () => wantedListeners.delete(listener); },
sleeps: () => state?.sleeps === true,
setSleeps(sleeps: boolean): void { if (state && state.role === "dialer" && (state.sleeps === true) !== sleeps) { state.sleeps = sleeps; save(); } },
- close(): void { if (alive) clearInterval(alive); alive = undefined; for (const retry of retries.values()) clearTimeout(retry.timer); retries.clear(); outboundListeners.clear(); wantedListeners.clear(); },
+ close(): void { if (alive) clearInterval(alive); alive = undefined; clearTimeout(telling); telling = undefined; for (const retry of retries.values()) clearTimeout(retry.timer); retries.clear(); outboundListeners.clear(); wantedListeners.clear(); },
};
}
diff --git a/server/host/bot-link-host.ts b/server/host/bot-link-host.ts
index 9437ce4048..19ac3554a0 100644
--- a/server/host/bot-link-host.ts
+++ b/server/host/bot-link-host.ts
@@ -7,6 +7,7 @@ import { mascotBodyColorSchema, mascotMaterialSchema } from "../../shared/bot-av
import { createDialer } from "../bot-link/dial.ts";
import { createBotLink } from "../bot-link/link.ts";
import type { Coordinator, HandoffView } from "../coordinator.ts";
+import type { createPlacesElsewhere, Explained } from "../places-elsewhere.ts";
import { redactSecretsInText } from "../redact.ts";
import type { RequestAuth } from "../request-auth.ts";
import { createBotLinkRoutes, linkSessionUser } from "../routes/bot-link.ts";
@@ -47,6 +48,8 @@ export interface BotLinkHostDeps {
log(line: string): void;
}
+type PlacesElsewhere = ReturnType<typeof createPlacesElsewhere>;
+
/** Another place's body tint and fur land here only as valid values, since the avatar paints them. */
const bodyColor = (value: string | undefined) => {
const color = mascotBodyColorSchema.safeParse(value).data;
@@ -131,9 +134,11 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {
});
const dialer = createDialer({ link, log: deps.log });
let stopWatching: (() => void) | undefined, upkeep: NodeJS.Timeout | undefined;
- /** While the link is on: bot changes reach the other places, and old records and stray file bytes are cleared hourly. */
+ /** While the link is on: bot changes reach the other places, and old records and stray file bytes are cleared hourly.
+ * Every change to a bot can change what the other places are told (a bot made, renamed, hidden, moved, its look, model
+ * or level); the link tells them once changes settle, and only what did change. */
const watch = () => {
- stopWatching ??= store.onChange((change) => { if (change.type.startsWith("bot.")) link.botsChanged(); });
+ stopWatching ??= store.onChange((change) => { if (link.on() && (change.type === "bot" || change.type === "bot.deleted" || change.type === "bots.order")) link.botsChanged(); });
watchRooms();
if (upkeep) return;
upkeep = setInterval(() => link.tidy(), 60 * 60_000);
@@ -153,6 +158,13 @@ export function createBotLinkHost(deps: BotLinkHostDeps) {
revoke: (sessionId) => { deps.sessions.revoke(sessionId); } });
return {
link, routes, rooms,
+ /** Why no bot here has the name a bot asked for, past "no such bot". With the link on, the other places' bots it can
+ * reach are listed and nothing says another place cannot be reached; a team, which the link never joins, is named as
+ * before. Off: what the person's app said of their other places, as always. */
+ explain(name: string, places: Pick<PlacesElsewhere, "explain" | "kindOf">): Explained {
+ if (!link.on() || places.kindOf(name) === "team") return places.explain(name);
+ return { hint: link.reachableElsewhere() };
+ },
/** Once the server is up. Off: nothing. On, on the computer: it starts asking the Cloud. */
start(): void {
// Off: nothing, unless a room here still has a member from another place, which is then found and shown as away.
diff --git a/server/index.ts b/server/index.ts
index 51bc477fac..7962b06c91 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -13493,7 +13493,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
if (destination && destination.id !== source?.id && !outsideLineage.mayReach(address.threadId, destination.threadId)) return refuse(403, OUTSIDE_STAYS_HERE);
const botIds: string[] = [];
for (const raw of call.botIds) {
- const resolved = resolveTeammate(store.bots, internalSender, raw, placesElsewhere.explain, (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null), { reaches: (bot) => personalReach.listed(internalSender, bot, address.threadId), hides: (bot) => personalReach.hides(internalSender, bot), refusal: (bot) => personalReach.refusal(internalSender, bot, address.threadId) });
+ const resolved = resolveTeammate(store.bots, internalSender, raw, (name) => botLink.explain(name, placesElsewhere), (bot) => (CLOUD_TEAM ? lookedAfterBy(bot, teamHost.personName) : null), { reaches: (bot) => personalReach.listed(internalSender, bot, address.threadId), hides: (bot) => personalReach.hides(internalSender, bot), refusal: (bot) => personalReach.refusal(internalSender, bot, address.threadId) });
if ("error" in resolved) return refuse(403, resolved.error);
botIds.push(resolved.id);
}
diff --git a/server/places-elsewhere.ts b/server/places-elsewhere.ts
index 49fb4abd73..67b76c2c5c 100644
--- a/server/places-elsewhere.ts
+++ b/server/places-elsewhere.ts
@@ -109,6 +109,8 @@ export function createPlacesElsewhere({ dataDir, now = Date.now }: { dataDir: st
const found = where(bot);
return found ? { where: livesElsewhere(found.bot, found.place, known.self) } : null;
},
+ /** What kind of place of the person's other places has `bot`, or null. */
+ kindOf: (bot: string): Place["kind"] | null => where(bot)?.place.kind ?? null,
/** The bots of the person's other places that `text` @mentions (none named like a bot `here`), each with where it
* lives, told to the bot answering it. */
mentioned(text: string, here: ReadonlyArray<{ name: string }>): string {
diff --git a/server/routes/bot-link.ts b/server/routes/bot-link.ts
index 8416e751bf..26dd1ac0ed 100644
--- a/server/routes/bot-link.ts
+++ b/server/routes/bot-link.ts
@@ -91,6 +91,14 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
held.set(peer, done);
});
const state = () => ({ ...link.status(), ...(link.role() === "dialer" ? dialer.state() : {}) });
+ /** Turned off on a computer. The end is written down before the Cloud is asked, so a server stopped mid-way tells its
+ * Cloud later (when the app next says it is awake); a Cloud the app says sleeps is not woken to be told. */
+ const endHere = async () => {
+ const target = link.dial(), sleeping = dialer.state().asleep;
+ await dialer.stop();
+ link.turnOff(false);
+ if (target && !sleeping) await dialer.tellEnded(target.origin);
+ };
return async ({ req, res, url, path, method, auth, json, readBody }) => {
if (path !== STATE_PATH && path !== PAIR_PATH && path !== SYNC_PATH && path !== FILE_PATH && path !== BOTS_PATH) return PASS;
@@ -120,15 +128,17 @@ export function createBotLinkRoutes(deps: BotLinkRouteDeps): RouteHandler {
return json(res, 200, state());
}
if (!body.data.on) {
- if (link.role() === "dialer") link.turnOff(await dialer.stop({ bye: true }));
+ if (link.role() === "dialer") await endHere();
return json(res, 200, link.status());
}
if (link.role() === "acceptor") return json(res, 409, { error: "This place already takes a computer's link." });
if (!body.data.origin.startsWith("https://") && !loopbackHost(body.data.origin)) return json(res, 400, { error: "The Cloud's address must be https." });
- if (link.role() === "dialer" && link.dial()?.origin !== body.data.origin) link.turnOff(await dialer.stop({ bye: true }));
+ if (link.role() === "dialer" && link.dial()?.origin !== body.data.origin) await endHere();
link.turnOn({ self: { id: deps.environmentId, name: body.data.name }, origin: body.data.origin, token: body.data.token, peer: body.data.cloud, ...(body.data.account ? { account: body.data.account } : {}) });
deps.turnedOn?.();
dialer.start();
+ // That Cloud is awake (it just paired): an earlier link to it that ended while it could not be told is ended there now.
+ void dialer.tellEnded(body.data.origin);
return json(res, 200, state());
}