Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(shared-computers): own window and handed-on work see a lent Mac on a one-owner server
AdityaUmale960085ae91d9
diff --git a/server/host/acting-person.test.ts b/server/host/acting-person.test.tsindex 5dc2bf13f3..7066991cd8 100644--- a/server/host/acting-person.test.ts+++ b/server/host/acting-person.test.ts@@ -228,3 +228,21 @@ describe("what work in one person's private chat hands back", () => {expect(privateHandBack(done, { child: null, parent: null, bot: "Helper", person: "them" })).toBe(done);});});++describe("handing on for the desktop app's own window", () => {+ it("records the lender for work that lends when no person's line names one, and nothing for work that doesn't", () => {+ const { people, handed } = world({ threads: { own: [{ id: "m1", at: 1, role: "user" }] }, direct: { own: request("g1", { messageId: "m1" }) } });+ expect(people.requester("own", "g1")).toBeNull();+ people.handOn({ threadId: "own", generation: "g1" }, { id: "lends", rootId: "r" }, true, ADA);+ people.handOn({ threadId: "own", generation: "g1" }, { id: "plain", rootId: "r2" }, false, ADA);+ expect(handed.get("lends")).toMatchObject({ person: ADA, lends: true });+ expect(handed.get("plain")).toBeUndefined();+ expect(people.handedOrigin(userOrigin(), "lends")).toMatchObject({ person: ADA, lends: true });+ });++ it("keeps the person whose own line started the turn over the lender", () => {+ const { people, handed } = world({ threads: { ada: [said("m1", 1, ADA)] }, direct: { ada: request("g1", { messageId: "m1" }) } });+ people.handOn({ threadId: "ada", generation: "g1" }, { id: "n", rootId: "r" }, true, BEN);+ expect(handed.get("n")?.person).toBe(ADA);+ });+});diff --git a/server/host/acting-person.ts b/server/host/acting-person.tsindex 3c85870b70..b74ffe361a 100644--- a/server/host/acting-person.ts+++ b/server/host/acting-person.ts@@ -141,9 +141,10 @@ export function createActingPeople(deps: ActingPeopleDeps) {requester,/** Work this turn hands on now acts for whoever this turn acts for; the first hand-on of a turn that started its* work is kept for that turn too, so it still acts for them if a restart runs it again. `lends`: this turn could use- * the person's lent computer (cloud-lending-turns handsOnLending). */- handOn(turn: { threadId: string; generation: string }, work: { id: string; rootId: string }, lends = false): void {- const person = requester(turn.threadId, turn.generation);+ * the person's lent computer (cloud-lending-turns handsOnLending). `lender`: whom work that `lends` acts for when no+ * person's own line names one (the desktop app's own window on a server of one person's own). */+ handOn(turn: { threadId: string; generation: string }, work: { id: string; rootId: string }, lends = false, lender?: string): void {+ const person = requester(turn.threadId, turn.generation) ?? (lends ? lender ?? null : null);deps.handed.record(work.id, person, lends);if (work.rootId === turn.generation) deps.handed.record(work.rootId, person, lends);},diff --git a/server/index.ts b/server/index.tsindex e77ffdf0ed..e14f08aedf 100644--- a/server/index.ts+++ b/server/index.ts@@ -632,7 +632,7 @@ import { clearInternalTurn, isInternalTurn, markInternalTurn } from "./internal-import { createReactionRoutes } from "./routes/reactions.ts";import { createReactions, withReactionNotes, type Reactor } from "./reactions.ts";import { createPersonReplies } from "./person-replies.ts";-import { lendingPerson, lendingPersonKey, personKey, relayedPersonKey } from "./person-key.ts";+import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts";import { createOutsideLineage, OUTSIDE_STAYS_HERE } from "./host/outside-lineage.ts"; import { OUTSIDE_REFUSAL, outsideRouteRefused } from "./host/outside-fence.ts"; import { createOutsideWrites } from "./host/outside-writes.ts";import { teamAiOwner } from "./host/team-ai-owner.ts"; import { createTeamOwners, type AskViewer } from "./host/team-owners.ts"; import { createTeamMessages } from "./host/team-messages.ts"; import { createTeamAwayHost } from "./host/team-away-host.ts"; import { createPlaceInbox, guestNameIn, placeInboxViewer } from "./host/place-inbox.ts"; import { relayedTurn } from "./host/relayed-turn.ts"; import { createPersonCalendar } from "./host/person-calendar.ts";import { createDevsReports } from "./host/devs-reports.ts"; import { createSettingNudges } from "./host/setting-nudges.ts"; import { createPerfHost } from "./perf/perf-host.ts"; import { launchListening, launchServerPart } from "./perf/launch-probe.ts"; import { footprintOwners } from "./host/bot-footprint-owners.ts"; import { engineOwners } from "./engine-owners.ts"; import { startBotMemoryCapHost } from "./host/bot-memory-cap-host.ts"; import { botMemoryCapReport } from "./bot-memory-cap.ts"; import { createPerfDiagnosticsRoutes } from "./routes/perf-diagnostics.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";@@ -885,8 +885,9 @@ function turnOrigin(capability: Pick<InternalCapability, "threadId" | "generatio/** Fail closed: only the person whose own message provably started this exact turn generation. Deliberately not the usage ledger's trigger, which defaults to the owner. */function sharedComputerPrincipal(capability: Pick<InternalCapability, "botId" | "threadId" | "generation">): string | null {if (CLOUD_HOME) { const lends = cloudLendingRefusal(capability) === null; if (lends) refusedLending.allowed(capability.threadId); return lends ? CLOUD_HOME_LENDER : null; }- return lendingPerson(provenRequestPerson(directRequestOwners.get(capability.threadId), capability.generation,- (messageId) => linePersonKey(store.messagesFor(capability.threadId).find((message) => message.id === messageId))), ownHome.ownServer(), () => sessions.list());+ const own = ownHome.ownServer(), request = directRequestOwners.get(capability.threadId);+ const person = provenRequestPerson(request, capability.generation, (messageId) => { const line = store.messagesFor(capability.threadId).find((message) => message.id === messageId); return linePersonKey(line) ?? ownWindowLender(own, ownWindowLine(capability.threadId, line)); });+ return person ? lendingPerson(person, own, () => sessions.list()) : request?.origin?.kind === "user" ? handedOwnServerLender(own, request.origin, actingPeople.requester(capability.threadId, capability.generation), () => sessions.list()) : null;}/** The only conversations that may feed a bot's memory, daily log, recall or brief; dropped whenever a session is revoked. */@@ -13588,7 +13589,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {// Work a person's request hands on opens in the receiving bot's chat with them when it may use their own apps.const opener = (room ? null : handOnFor) ?? openerFrom(address.threadId); if (!room) personalReach.checkHandOn(internalSender, recipient, address.threadId, opener, call.answers ? { threadId: coordinator.node(call.answers)?.threadId } : undefined);// A Chief answers, for the person, the question a teammate it manages waits on in a thread the Chief did not open.- let lends = mode === "work" && handsOnLending(internalCapability); const forPerson = EXTERNAL || room || fresh || post || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) || !asksActingPerson(internalCapability.threadId, store.groupByThread(internalCapability.threadId) ? internalCapability.generation : undefined)(call.thread, recipient.id) ? undefined : await questionRouting.answerForPerson({ lends, sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });+ let lends = mode === "work" && (CLOUD_HOME ? handsOnLending(internalCapability) : !store.groupByThread(internalCapability.threadId) && sharedComputerPrincipal(internalCapability) === OWN_SERVER_LENDER); const forPerson = EXTERNAL || room || fresh || post || call.answers || mode !== "work" || call.thread === "standing" || !teammatePrompts.actsForPerson(internalSender, internalCapability.threadId) || !canManage(internalSender, recipient) || !threadReadableFrom(internalCapability.threadId)(call.thread) || !asksActingPerson(internalCapability.threadId, store.groupByThread(internalCapability.threadId) ? internalCapability.generation : undefined)(call.thread, recipient.id) ? undefined : await questionRouting.answerForPerson({ lends, sender: internalSender, senderThreadId: address.threadId, target: recipient, threadId: call.thread, message: call.message });if (forPerson) { if (forPerson.outcome === "failed") refused.push(forPerson.detail); else answeredForPerson.add(forPerson); receipts.push(forPerson); continue; }const continued = room || fresh ? undefined : workThreadFor(store, { botId: target.botId, botName: recipient.name, fromBotId: internalSender.id, fromThreadId: address.threadId, thread: call.thread, notice: mode === "notify", any: Boolean(post),answering: coordinator.answersTo(internalCapability.roomHandoffId ?? generation), also: (task) => !CLOUD_TEAM || threadStarters.get(task.threadId) === opener, reach: (task) => outsideLineage.mayReach(address.threadId, task.threadId) });@@ -13616,7 +13617,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {mode, reply, thread: lane || fresh || steersOwn || postsOwn ? "new" : "standing", rework: call.rework, ...(lane ? {} : { requestBatchKey }), ...(fanOut ? { fanOut } : {}), ...(call.ownThread || steersOwn || postsOwn ? { ownThread: true } : {}),...(call.doneWhen ? { doneWhen: call.doneWhen } : {}),});- usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) { actingPeople.handOn(internalCapability, node, lends); if (!lends && !room && !lane) handedInUnproven(routed.threadId); }+ usageTrace.link(node.id, node.parentId, { threadId: internalCapability.threadId, turnId: liveTurnByThread.get(internalCapability.threadId) ?? "" }); if (!duplicate) { actingPeople.handOn(internalCapability, node, lends, CLOUD_HOME ? undefined : OWN_SERVER_LENDER); if (!lends && !room && !lane) handedInUnproven(routed.threadId); }if (!duplicate && call.files?.length) handoffFiles.sent(node.id, { botId: internalSender.id, name: internalSender.name }, call.files);if (duplicate && createdThread) store.deleteTask(target.botId, createdThread);else if (createdThread) {diff --git a/server/own-window-sends.test.ts b/server/own-window-sends.test.tsnew file mode 100644index 0000000000..ab628fcfb2--- /dev/null+++ b/server/own-window-sends.test.ts@@ -0,0 +1,30 @@+import { randomUUID } from "node:crypto";+import { describe, expect, it } from "vitest";++import { noteOwnWindowSend, ownWindowLine } from "./own-window-sends.ts";++describe("lines the desktop app's own window sent", () => {+ it("knows a noted line by its thread, send and words, and nothing else", () => {+ const threadId = randomUUID(), sendId = randomUUID(), text = "list my lent Mac";+ const line = { role: "user", sendId, text };+ expect(ownWindowLine(threadId, line)).toBe(false);+ noteOwnWindowSend(threadId, sendId, text);+ expect(ownWindowLine(threadId, line)).toBe(true);+ expect(ownWindowLine(randomUUID(), line)).toBe(false);+ expect(ownWindowLine(threadId, { ...line, text: "other words" })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, sendId: randomUUID() })).toBe(false);+ expect(ownWindowLine(threadId, undefined)).toBe(false);+ });++ it("never a signed-in person's, a bot's, a relayed or an app's line, even with the same send", () => {+ const threadId = randomUUID(), sendId = randomUUID(), text = "use my Mac";+ noteOwnWindowSend(threadId, sendId, text);+ const line = { role: "user", sendId, text };+ expect(ownWindowLine(threadId, { ...line, sender: { name: "Guest", id: "p_guest" } })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, peerAsk: { botId: "b" } })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, relayed: true })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, via: "api" })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, aside: true })).toBe(false);+ expect(ownWindowLine(threadId, { ...line, role: "bot" })).toBe(false);+ });+});diff --git a/server/own-window-sends.ts b/server/own-window-sends.tsnew file mode 100644index 0000000000..8c3754f2cc--- /dev/null+++ b/server/own-window-sends.ts@@ -0,0 +1,24 @@+// The lines the desktop app's own window sent, noted at the one route that can tell. In the desktop app a change reaches+// the server only with the window's private capability (request-auth.ts DESKTOP_OWNER_HEADER), so a bot's shell on this+// machine can never send such a line. Bound to the thread and the words, like typed-sends.ts, so a bot that reads a+// sendId in a transcript cannot lend it to words of its own. In memory on purpose: after a restart a line is nobody's+// again, which only takes the owner's lent computers away.+import { createHash } from "node:crypto";++import { createPhoneSends } from "./phones/sends.ts";++const sends = createPhoneSends();+const proof = (threadId: string, sendId: string, text: string): string =>+ createHash("sha256").update(JSON.stringify(["own-window", threadId, sendId, text])).digest("base64");++export function noteOwnWindowSend(threadId: string, sendId: string, text: string): void {+ sends.note(proof(threadId, sendId, text));+}++type Line = { role?: string; text?: string; sendId?: string; sender?: unknown; peerAsk?: unknown; relayed?: boolean; via?: string; aside?: unknown };++/** A person's line the desktop app's own window sent: no signed-in sender, relay, app or bot wrote it. */+export function ownWindowLine(threadId: string, line: Line | undefined): boolean {+ if (!line || line.role !== "user" || line.sender || line.peerAsk || line.relayed || line.via !== undefined || line.aside) return false;+ return line.sendId !== undefined && line.text !== undefined && sends.has(proof(threadId, line.sendId, line.text));+}diff --git a/server/person-key.test.ts b/server/person-key.test.tsindex a96a0273b1..6ac26a849e 100644--- a/server/person-key.test.ts+++ b/server/person-key.test.ts@@ -1,7 +1,7 @@import { randomUUID } from "node:crypto";import { describe, expect, it } from "vitest";-import { lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, personKey } from "./person-key.ts";+import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey } from "./person-key.ts";import { SharedComputers } from "./shared-computers.ts";type Device = Parameters<typeof lendingPersonKey>[0];@@ -83,3 +83,52 @@ describe("shared computers on a self-hosted server without email sign-in", () =>expect(lendingPerson(personKey(desktop), null, () => [desktop])).toBe(personKey(desktop));});});++describe("the desktop app's own window and work handed on, on a server of one person's own", () => {+ const lend = (desktop: Device) => {+ const broker = new SharedComputers((id) => id === desktop.id);+ const computer = { id: randomUUID(), name: "Mac B", environmentId: randomUUID(), folders: [], terminal: true, computer: true };+ broker.register(computer, { session: desktop.id, person: lendingPersonKey(desktop, OWN) }, "a".repeat(64));+ return { broker, computer };+ };++ it("a line typed in the server's own window sees the Mac a paired device lends", () => {+ const other = device();+ const { broker, computer } = lend(other);+ // That window has no session, so its line names no sender: before, a turn it started listed nothing.+ expect(broker.list(lendingPerson(null, OWN, () => [other]))).toEqual([]);+ const fromWindow = lendingPerson(ownWindowLender(OWN, true) ?? null, OWN, () => [other]);+ expect(broker.list(fromWindow).map((entry) => entry.id)).toEqual([computer.id]);+ broker.close();+ });++ it("only on a server of one person's own, and only for a line the window itself sent", () => {+ expect(ownWindowLender(null, true)).toBeUndefined();+ expect(ownWindowLender(OWN, false)).toBeUndefined();+ expect(ownWindowLender(SIGNED_IN, true)).toBe(OWN_SERVER_LENDER);+ });++ it("work the owner's turn handed on with the lent computer goes on seeing it", () => {+ const other = device();+ const { broker, computer } = lend(other);+ const sessions = () => [other];+ const fromWindow = { lends: true as const, person: OWN_SERVER_LENDER };+ expect(broker.list(handedOwnServerLender(OWN, fromWindow, OWN_SERVER_LENDER, sessions)).map((entry) => entry.id)).toEqual([computer.id]);+ const fromDevice = { lends: true as const, person: personKey(other) };+ expect(handedOwnServerLender(OWN, fromDevice, personKey(other), sessions)).toBe(OWN_SERVER_LENDER);+ broker.close();+ });++ it("handed-on work never lends without the hand-on's own record, for someone else, or on another server", () => {+ const owner = device(), guest = device({ scopes: ["client"] });+ const sessions = () => [owner, guest];+ expect(handedOwnServerLender(OWN, { person: OWN_SERVER_LENDER }, OWN_SERVER_LENDER, sessions)).toBeNull();+ expect(handedOwnServerLender(OWN, undefined, OWN_SERVER_LENDER, sessions)).toBeNull();+ // Someone else's words joined the work: it acts for nobody.+ expect(handedOwnServerLender(OWN, { lends: true, person: OWN_SERVER_LENDER }, null, sessions)).toBeNull();+ expect(handedOwnServerLender(OWN, { lends: true, person: OWN_SERVER_LENDER }, personKey(guest), sessions)).toBeNull();+ expect(handedOwnServerLender(OWN, { lends: true, person: personKey(guest) }, personKey(guest), sessions)).toBeNull();+ expect(handedOwnServerLender(OWN, { lends: true, person: personKey({ id: "", email: "[email protected]" }) }, personKey({ id: "", email: "[email protected]" }), sessions)).toBeNull();+ expect(handedOwnServerLender(null, { lends: true, person: personKey(owner) }, personKey(owner), sessions)).toBeNull();+ });+});diff --git a/server/person-key.ts b/server/person-key.tsindex 73bcfa7016..63f792b8e3 100644--- a/server/person-key.ts+++ b/server/person-key.ts@@ -45,3 +45,18 @@ export function lendingPerson(person: string | null, own: OwnServer, sessions: (if (own.admin !== null && person === personKey({ id: "", email: own.admin })) return OWN_SERVER_LENDER;return sessions().some((session) => !session.email && ownersDevice(session, own) && personKey(session) === person) ? OWN_SERVER_LENDER : person;}++/** Who a line the desktop app's own window sent counts as, for shared computers: the server's one person, like their+ * paired devices. That window has no session, so its lines name no sender. Nobody on any other server. */+export function ownWindowLender(own: OwnServer, ownWindow: boolean): string | undefined {+ return own && ownWindow ? OWN_SERVER_LENDER : undefined;+}++/** Work handed on (a teammate's own thread) by a turn that could use the one person's lent computers: it may go on using+ * them while it still acts for that person (host/acting-person.ts requester). Never on any other server, never for work+ * handed on without `lends`, and never for anyone the lender rule would not count as that one person. */+export function handedOwnServerLender(own: OwnServer, origin: { lends?: true; person?: string } | undefined, actingFor: string | null,+ sessions: () => readonly DeviceSession[]): string | null {+ if (!own || origin?.lends !== true || !actingFor || actingFor !== origin.person) return null;+ return lendingPerson(actingFor, own, sessions) === OWN_SERVER_LENDER ? OWN_SERVER_LENDER : null;+}diff --git a/server/routes/bot-messages.test.ts b/server/routes/bot-messages.test.tsindex bc449ff97d..e0fa7c44fc 100644--- a/server/routes/bot-messages.test.ts+++ b/server/routes/bot-messages.test.ts@@ -18,6 +18,7 @@ import type { RequestAuth } from "../request-auth.ts";import { acceptedSendMatch, sendFingerprint, SendSequencer } from "../send-idempotency.ts";import { _queuedCount, drainSteeredMessages, queuedSteeredMessage, queueSteeredMessage } from "../steer-queue.ts";import { Store, type Message } from "../store.ts";+import { ownWindowLine } from "../own-window-sends.ts";import { typedWords } from "../typed-sends.ts";import { USER_ERROR } from "../user-errors.ts";import { createBotMessageRoutes, type BotMessageRouteDeps } from "./bot-messages.ts";@@ -714,3 +715,32 @@ describe("POST /api/bots/:id/messages from a registered phone", () => {expect(state.phoneSends).toEqual([]);});});++describe("POST /api/bots/:id/messages from the desktop app's own window", () => {+ const words = "What can you see on my other Mac?";++ it("notes a plain send from the desktop's own page as the window's", async () => {+ const { threadId, post } = await fixture();+ const plain = await post({ threadId, sendId: SEND, text: words });+ expect(plain.status, JSON.stringify(plain.body)).toBe(202);+ expect(ownWindowLine(threadId, plain.body.message)).toBe(true);+ });++ it("notes neither a press nor a relay", async () => {+ const { store, bot, threadId, post, show } = await fixture();+ const pressed = await post({ threadId, sendId: SEND, text: words, widgetAction: { messageId: show("routineForm"), ref: "confirm", values: { days: "mon,tue,wed,thu,fri,sat,sun", report: "discord:releases" } } });+ expect(pressed.status, JSON.stringify(pressed.body)).toBe(202);+ expect(ownWindowLine(threadId, pressed.body.message)).toBe(false);+ store.patchBot(bot.id, { approvalMode: "ask", autoApprove: false });+ const relayed = await post({ threadId, sendId: OTHER_SEND, text: words, expectedActiveLeafId: store.activeLeaf(threadId), expectedApprovalMode: "ask" }, "/guarded");+ expect(relayed.status, JSON.stringify(relayed.body)).toBe(202);+ expect(ownWindowLine(threadId, relayed.body.message)).toBe(false);+ });++ it("does not note a bare loopback send on a headless server, where it may be a bot's shell", async () => {+ const { threadId, post } = await fixture({}, false);+ const plain = await post({ threadId, sendId: SEND, text: words });+ expect(plain.status, JSON.stringify(plain.body)).toBe(202);+ expect(ownWindowLine(threadId, plain.body.message)).toBe(false);+ });+});diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 8d6311a1e6..3710f5be6f 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -35,6 +35,7 @@ import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { extractSteerImages } from "../turn-images.ts";import { followupFacts, helperFollowup, helperFollowupBody, mayFollowUp } from "../helper-followup.ts";import type { UsageTrigger } from "../usage-ledger.ts";+import { noteOwnWindowSend } from "../own-window-sends.ts";import { noteTypedSend } from "../typed-sends.ts";import { engineSessionOutdated, startFresh } from "../fresh-start.ts";import { parseMentionPicks } from "../../shared/room-mentions.ts";@@ -341,6 +342,8 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandler// paired session or the desktop capability proves a person and lifts the webhook block.const personPresent = auth.kind === "session" || DESKTOP_MANAGED;if (personPresent && sendId && !guarded && !press && !appSent) noteTypedSend(threadId, sendId, text);+ // The desktop app's own window: in the desktop app a loopback change needs its private capability.+ if (DESKTOP_MANAGED && auth.kind === "loopback" && !auth.companionDevice && sendId && !guarded && !press && !appSent) noteOwnWindowSend(threadId, sendId, text);if (pressKey) pressesInFlight.set(pressKey, sendId);try {const receipt = await acceptDirectSend({