Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Keep the shell for a routine made in the follow-up of a person's own wait (#7984)
Milind Soni41d5e8626252
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjsindex 7982b4dde8..69c976836a 100644--- a/scripts/ci-scope.mjs+++ b/scripts/ci-scope.mjs@@ -204,6 +204,7 @@ export const VITEST_SUBSETS = {"server/outside-lineage.e2e.test.ts","server/same-name-mentions.e2e.test.ts","server/skill-switch.test.ts",+ "server/wait-follow-up-lineage.e2e.test.ts",],shards: 2,nodeTests: true,diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.tsindex 3d79a4efd9..ebe5ac90c8 100644--- a/scripts/ci-scope.test.ts+++ b/scripts/ci-scope.test.ts@@ -344,6 +344,7 @@ describe("CI outputs", () => {"server/outside-lineage.e2e.test.ts","server/same-name-mentions.e2e.test.ts","server/skill-switch.test.ts",+ "server/wait-follow-up-lineage.e2e.test.ts",]);expect(out.vitest_matrix.include).toEqual([1, 2].map((shard) => ({os: "ubuntu-latest", part: `locale tests ${shard}/2`, shard, shards: 2,diff --git a/server/automation-destinations.test.ts b/server/automation-destinations.test.tsindex b07fe28803..15642da649 100644--- a/server/automation-destinations.test.ts+++ b/server/automation-destinations.test.ts@@ -44,6 +44,16 @@ describe("where an automation reports on a Cloud", () => {expect(w.destinations.event({ webhookId: "w", webhookName: "Hook", botId: "bot" })).toBe("made-1");expect(w.outside).toEqual(["made-1"]);});++ it("records the chat a wait's follow-up reports into as outside work only when nothing says a person's turn set the wait", () => {+ const w = world("owner");+ expect(w.destinations.event({ webhookId: "wait:1", webhookName: "Build", botId: "bot", eventSource: "wait", waitSetBy: "owner" })).toBe("made-1");+ expect(w.destinations.event({ webhookId: "wait:2", webhookName: "Build", botId: "bot", eventSource: "wait", waitSetBy: "person" })).toBe("made-2");+ expect(w.outside).toEqual([]);+ expect(w.destinations.event({ webhookId: "wait:3", webhookName: "Build", botId: "bot", eventSource: "wait" })).toBe("made-3");+ expect(w.destinations.event({ webhookId: "w", webhookName: "Hook", botId: "bot", eventSource: "app", waitSetBy: "owner" })).toBe("made-4");+ expect(w.outside).toEqual(["made-3", "made-4"]);+ });});describe("where an outside event reports on a desktop or self-hosted home", () => {diff --git a/server/automation-destinations.ts b/server/automation-destinations.tsindex d523017612..d97ab21873 100644--- a/server/automation-destinations.ts+++ b/server/automation-destinations.ts@@ -54,7 +54,7 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) {const threadId = cloud ? chatOfItsOwn(routine.botId, routine.name, opener!) : undefined;return threadId ? { threadId } : undefined;},- event({ webhookId, webhookName, botId }: { webhookId: string; webhookName: string; botId: string }): string | undefined {+ event({ webhookId, webhookName, botId, eventSource, waitSetBy }: { webhookId: string; webhookName: string; botId: string; eventSource?: "app" | "wait"; waitSetBy?: "owner" | "person" }): string | undefined {const bot = store.bot(botId);if (!bot || bot.hidden) return undefined;const earlier = deps.runs().find((run) => run.webhookId === webhookId && run.botId === botId && run.resultsThreadId)?.resultsThreadId;@@ -62,7 +62,8 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) {const lines = kept && !kept.routineRunId ? store.messagesFor(kept.threadId) : undefined;const stillItsOwn = kept && lines && (cloud ? lines.length === 0 || lines.some(cloud.reportFromOthers) : legacyResultsThread(webhookName, kept));const threadId = stillItsOwn ? kept.threadId : chatOfItsOwn(botId, webhookName, cloud?.owner);- if (threadId) cloud?.outside(threadId);+ // The follow-up of a wait a person's own turn set reports that person's work, not an outside event's.+ if (threadId && !(eventSource === "wait" && waitSetBy)) cloud?.outside(threadId);return threadId;},};diff --git a/server/cloud-home-settle.test.ts b/server/cloud-home-settle.test.tsindex a417e69cea..c88ff5e75e 100644--- a/server/cloud-home-settle.test.ts+++ b/server/cloud-home-settle.test.ts@@ -21,7 +21,7 @@ const line = (id: string, person?: string) => ({ id, role: "user", kind: "text",/** A Cloud home's records: conversations by id, routines, their writers, and the people who have sessions. */function cloudHome(threads: Record<string, any[]>, routines: Array<{ id: string; sourceThreadId?: string }>, writers: Record<string, string>,- options: { sessions?: Array<{ id: string; scopes: string[] }>; webhookRuns?: string[] } = {}) {+ options: { sessions?: Array<{ id: string; scopes: string[] }>; webhookRuns?: string[]; waitRuns?: Record<string, "owner" | "person" | undefined> } = {}) {const dir = mkdtempSync(join(tmpdir(), "omb-cloud-home-settle-")); dirs.push(dir);writeFileSync(join(dir, "lending-routines.json"), JSON.stringify({ version: 1, routines: {}, writers }));writeFileSync(join(dir, "thread-starters.json"), "{}");@@ -33,7 +33,7 @@ function cloudHome(threads: Record<string, any[]>, routines: Array<{ id: string;file: join(dir, "cloud-owner.json"), machineId: "machine", ownerKey: OWNER, nobodyKey: NOBODY,sessions: { list: () => sessions, revoke: (id) => { const at = sessions.findIndex((s) => s.id === id); if (at >= 0) sessions.splice(at, 1); return at >= 0; } },personKey: (session) => key(session.id), starters: new ThreadStarters(join(dir, "thread-starters.json")), authors,- routines: () => ({ listRoutines: () => shaped, listRuns: () => (options.webhookRuns ?? []).map((threadId) => ({ triggerSource: "webhook", threadId })), update: () => null }) as any,+ routines: () => ({ listRoutines: () => shaped, listRuns: () => [...(options.webhookRuns ?? []).map((threadId) => ({ triggerSource: "webhook", threadId })), ...Object.entries(options.waitRuns ?? {}).map(([threadId, waitSetBy]) => ({ triggerSource: "webhook", eventSource: "wait", threadId, waitSetBy }))], update: () => null }) as any,store: { bots: [{ id: "bot" }], tasks: () => Object.keys(threads).map((threadId) => ({ threadId })), groups: [], messagesFor: (threadId: string) => threads[threadId] ?? [],botByThread: (threadId: string) => threads[threadId] ? { id: "bot" } : null, groupByThread: () => null, unpinTaskCwd: () => {} } as any,linePersonKey: (message) => message.role === "user" && !message.peerAsk ? message.sender?.id : undefined, asSchedule,@@ -57,6 +57,16 @@ describe("settling a Cloud home's people at start (server/cloud-home-settle.ts)"expect(home.authors.writer("mine")).toBe(OWNER);});+ it("leaves a routine made in the follow-up of a wait a person's own turn set as it was written, and marks one from a wait nothing vouches for", () => {+ const home = cloudHome({ chat: [line("m1", OWNER)], owners: [line("follow-up"), card("after-owner")], persons: [line("follow-up"), card("after-person")], unknown: [line("follow-up"), card("after-unknown")] },+ [{ id: "after-owner", sourceThreadId: "owners" }, { id: "after-person", sourceThreadId: "persons" }, { id: "after-unknown", sourceThreadId: "unknown" }],+ { "after-owner": NOBODY, "after-person": NOBODY, "after-unknown": NOBODY }, { waitRuns: { owners: "owner", persons: "person", unknown: undefined } });+ home.settle();+ expect(home.authors.writer("after-owner")).not.toBe(CLOUD_OUTSIDE_KEY);+ expect(home.authors.writer("after-person")).not.toBe(CLOUD_OUTSIDE_KEY);+ expect(home.authors.writer("after-unknown")).toBe(CLOUD_OUTSIDE_KEY);+ });+it("is shared on any trace of a second person, and the first one after a start that found only the owner keeps what the owner made alone", () => {const home = cloudHome({ desk: [line("d1"), card("desktop")], theirs: [line("g1", GUEST), card("guests")] },[{ id: "desktop", sourceThreadId: "desk" }, { id: "guests", sourceThreadId: "theirs" }], {});diff --git a/server/cloud-home-settle.ts b/server/cloud-home-settle.tsindex 0235a55ee6..b8d4bfcad1 100644--- a/server/cloud-home-settle.ts+++ b/server/cloud-home-settle.ts@@ -5,6 +5,7 @@ import type { createCloudRoutineAuthors } from "./cloud-lending.ts";import { recordCloudSharing, settleCloudOwnership, type CloudOwnership, type CloudOwnershipOptions } from "./cloud-owner.ts";import { approvalShape, createdShape, ownersRoutinesMadeInChat, routinesKeptAtSharing, type OwnersRoutinesInput } from "./cloud-routine-level.ts";import { CLOUD_OUTSIDE_KEY, cloudShared } from "./cloud-sharing.ts";+import { outsideEvent } from "./host/outside-lineage.ts";import type { asSchedule } from "./routine-requests.ts";import type { RoutineManager } from "./routines.ts";import type { Message, Store } from "./store.ts";@@ -44,7 +45,7 @@ export function settleCloudHome(deps: CloudHomeSettleDeps): { solo(): boolean; sconst routineById = (id: string) => deps.routines()?.listRoutines().find((routine) => routine.id === id);const shapeOf = (id: string) => { const routine = routineById(id); return routine ? approvalShape(routine) : undefined; };const thread = (threadId: string) => store.botByThread(threadId) || store.groupByThread(threadId) ? store.messagesFor(threadId) : [];- const webhookRuns = new Set((deps.routines()?.listRuns() ?? []).flatMap((run) => run.triggerSource === "webhook" && run.threadId ? [run.threadId] : []));+ const webhookRuns = new Set((deps.routines()?.listRuns() ?? []).flatMap((run) => outsideEvent(run) && run.threadId ? [run.threadId] : []));const outsideThread = (threadId: string, lines: readonly Message[] = thread(threadId)) => webhookRuns.has(threadId) || lines.some((line) => line.webhookPost || line.via === "api");/** Every conversation once: who wrote and answered, the owner's card approvals, and the routines a webhook-driven conversation made or changed. */const search = () => {diff --git a/server/host/outside-lineage.test.ts b/server/host/outside-lineage.test.tsindex d1b1b81d82..7cf68e41be 100644--- a/server/host/outside-lineage.test.ts+++ b/server/host/outside-lineage.test.ts@@ -4,7 +4,7 @@ import "../server-line-packs.ts";import { CLOUD_OUTSIDE_KEY } from "../cloud-sharing.ts";import type { HandoffView } from "../coordinator.ts";import type { RoutineRun } from "../routines.ts";-import { createOutsideLineage, type OutsideLineageDeps } from "./outside-lineage.ts";+import { createOutsideLineage, outsideEvent, type OutsideLineageDeps } from "./outside-lineage.ts";function world(over: Partial<OutsideLineageDeps> = {}) {const tasks = new Map<string, { threadId: string; outside?: true }>();@@ -135,6 +135,57 @@ describe("work from outside stays with that work", () => {});});+describe("the follow-up of a wait a person's own turn set", () => {+ const waitRun = (threadId: string, waitSetBy?: "owner" | "person") => webhookRun(threadId, { eventSource: "wait", ...(waitSetBy ? { waitSetBy } : {}) });++ it("is that person's work, not an outside event's, while it runs and after a restart", () => {+ for (const setBy of ["owner", "person"] as const) {+ const w = world();+ w.runs.set("hook-run", waitRun("hook-run", setBy));+ expect(outsideEvent(waitRun("hook-run", setBy))).toBe(false);+ expect(w.lineage.outsideDrivenThread("hook-run")).toBe(false);+ expect(w.lineage.cloudGuestDriven("hook-run")).toBe(false);+ expect(w.lineage.handsNoLevel("hook-run")).toBe(false);+ w.lineage.carry("hook-run", "teammate");+ w.lineage.settle([waitRun("hook-run", setBy)], () => undefined);+ expect(w.tasks.get("hook-run")?.outside).toBeUndefined();+ expect(w.tasks.get("teammate")?.outside).toBeUndefined();+ }+ });++ it("stays outside when nothing says who set the wait, as every wait from before did", () => {+ const w = world();+ w.runs.set("hook-run", waitRun("hook-run"));+ expect(outsideEvent(waitRun("hook-run"))).toBe(true);+ expect(w.lineage.outsideDrivenThread("hook-run")).toBe(true);+ expect(w.lineage.cloudGuestDriven("hook-run")).toBe(true);+ w.lineage.settle([waitRun("hook-run")], () => undefined);+ expect(w.tasks.get("hook-run")?.outside).toBe(true);+ });++ it("gives a webhook's or a connected app's run nothing, whatever it carries", () => {+ expect(outsideEvent(webhookRun("hook-run"))).toBe(true);+ expect(outsideEvent(webhookRun("hook-run", { waitSetBy: "owner" }))).toBe(true);+ expect(outsideEvent(webhookRun("hook-run", { eventSource: "app", waitSetBy: "owner" }))).toBe(true);+ expect(outsideEvent({ triggerSource: "schedule" })).toBe(false);+ const w = world();+ w.runs.set("hook-run", webhookRun("hook-run", { eventSource: "app", waitSetBy: "owner" }));+ expect(w.lineage.cloudGuestDriven("hook-run")).toBe(true);+ });++ it("is outside all the same once outside work reaches its conversation", () => {+ const w = world();+ w.runs.set("person-work", waitRun("person-work", "owner"));+ w.lines.set("person-work", [{ webhookPost: true }]);+ expect(w.lineage.outsideDrivenThread("person-work")).toBe(true);+ const marked = world();+ marked.runs.set("person-work", waitRun("person-work", "owner"));+ marked.lineage.mark("hook-run");+ marked.lineage.carry("hook-run", "person-work");+ expect(marked.lineage.cloudGuestDriven("person-work")).toBe(true);+ });+});+describe("confinement explanations follow the conversation language without choosing branches by translated text", () => {it.each([["en", "Work from outside came into this conversation", "This bot's AI can't run it that way.", "This conversation is from before the Cloud was only yours"],diff --git a/server/host/outside-lineage.ts b/server/host/outside-lineage.tsindex 61d0b904c1..be212722f6 100644--- a/server/host/outside-lineage.ts+++ b/server/host/outside-lineage.ts@@ -18,6 +18,11 @@ const CONVERSATION_FROM_OUTSIDE = "server.outside.conversationFromOutside";const MAX_HOPS = 32;+/** An outside event started this run: every webhook-kind run but the follow-up of a wait a person's own turn set, which is+ * that person's work still. A wait with no such record (an older one, or one a turn that proved nothing set) stays outside. */+export const outsideEvent = (run: Pick<RoutineRun, "triggerSource" | "eventSource" | "waitSetBy">): boolean =>+ run.triggerSource === "webhook" && !(run.eventSource === "wait" && run.waitSetBy !== undefined);+export interface OutsideLineageDeps {/** A Cloud home of any kind; off a Cloud nothing is confined, the record only stops a level travelling. */home: boolean;@@ -67,7 +72,7 @@ export function createOutsideLineage(deps: OutsideLineageDeps) {/** A webhook or app event drove this conversation: its record, its run, a payload posted into it, or a conversation that handed it the work. */const outsideDrivenThread = (threadId: string): boolean => outsideDriven(threadId, {marked,- webhookRun: (id) => deps.activeRun(id)?.triggerSource === "webhook",+ webhookRun: (id) => { const run = deps.activeRun(id); return run !== null && outsideEvent(run); },webhookPosted: (id) => store.messagesFor(id).some((line) => line.webhookPost),handedFrom: (id) => deps.active().filter((node) => node.threadId === id).flatMap((node) => handedFrom(node.id)),});@@ -142,7 +147,7 @@ export function createOutsideLineage(deps: OutsideLineageDeps) {/** At every start: what ran without a record of its own, or was still in flight, keeps its lineage. */function settle(runs: readonly RoutineRun[], eventChat: (run: RoutineRun) => string | undefined): void {for (const run of runs) {- if (run.triggerSource !== "webhook" || !run.threadId) continue;+ if (!outsideEvent(run) || !run.threadId) continue;// Off a Cloud a wait's follow-up runs in the person's own chat.if (deps.home || run.eventSource !== "wait") mark(run.threadId);const chat = eventChat(run);diff --git a/server/index.ts b/server/index.tsindex 6ec7d76e4b..151bc8d525 100644--- a/server/index.ts+++ b/server/index.ts@@ -484,7 +484,7 @@ import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts"import { addressFor } from "./webhook-address.ts";import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts";import { WebhookManager } from "./webhooks.ts";-import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitLineFields, waitRunChat, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";+import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { cancelWaitFromCard, createWaitHost, waitContinuationCheck, waitLineFields, waitRunChat, waitSetBy, waitTurnRunId } from "./wait-host.ts"; import { continuedConversation } from "./routine-same-conversation.ts"; import { createWaitRoutes, findWaitPeer, handedAssignment, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts";import type { WebhookTrigger } from "../shared/webhooks.ts";import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts";import { agentsProxyLaunch, agentsToolBridgeEnv, applyAgentsBridge, bridgedToolTitle, turnEngine } from "./agents-bridge-switch.ts"; import { serverTurnedOff } from "./drivers/agents-tool-groups.ts"; import { availableToolGroups, toolsOffPart } from "./tool-groups.ts"; import { agentsServerEnv, botDrivenConversation, COMPUTER_OFF_REFUSAL, computerPickRefusal, directTurnKind, handRoomSkills, roomSkillsRefusal, roomSkillsTurn, takeRoomSkills, type RoomSkillsClaim, type TurnKind } from "./agents-turn.ts";@@ -637,7 +637,7 @@ import { createReactionRoutes } from "./routes/reactions.ts";import { createReactions, createRoomReactionNotes, withReactionNotes, type Reactor } from "./reactions.ts";import { createPersonReplies } from "./person-replies.ts";import { handedOwnServerLender, lendingPerson, lendingPersonKey, OWN_SERVER_LENDER, ownWindowLender, personKey, relayedPersonKey } from "./person-key.ts"; import { ownWindowLine } from "./own-window-sends.ts"; import { ownServerLendingRefusal } from "./own-server-lending-refusal.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 { createOutsideLineage, outsideEvent, 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 { botsElsewhere } from "./host/message-person-bots.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 { cloudStorage, createPerfHost } from "./perf/perf-host.ts"; import { afterLaunchSettles, 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 { createCachesRoutes } from "./routes/caches.ts"; import { botEnginesLive, createCacheSweepHost, withCacheCounters } from "./cache-sweep/host.ts"; import { bugReportEndpoint, devsReportSender, devsStatusAsker } from "./devs-report-send.ts"; import { captureRecentLog } from "./recent-log.ts"; import { createShareAnswer } from "./host/share-answer.ts";import { createCardRequester, linePersonKey } from "./host/thread-person.ts"; import { selfThreadRefusal } from "./host/self-threads.ts"; import { lookedAfterBy } from "./host/looked-after.ts"; import { createActingPeople, HANDED_PEOPLE_FILE, HandedPeople, type HandedRun, keptPrivate, privateHandBack, withPerson } from "./host/acting-person.ts"; import { createTurnCallSignals } from "./host/turn-call-signals.ts";@@ -8681,7 +8681,7 @@ routines = new RoutineManager({// On a Cloud home the routine's writer opens a run's conversation; a webhook run is the owner's, but its payload never reaches the lent Mac.const task = store.createTask(botId, title, false, undefined, undefined, undefined, routineThreadModel(run && routines?.listRoutines().find((routine) => routine.id === run.routineId), routineModelChecks), undefined,CLOUD_HOME && run ? (created) => threadStarters.set(created.threadId, run.triggerSource === "webhook" ? CLOUD_OWNER_KEY! : routineOpener(run.routineId)) : undefined);- if (task && run?.triggerSource === "webhook") outsideLineage.mark(task.threadId);+ if (task && run && outsideEvent(run)) outsideLineage.mark(task.threadId);return task;},joinConversation: (run) => {@@ -10980,8 +10980,8 @@ function connectorThread(botId: string, threadId: string) {return null;}function directChatOf(botId: string, threadId: string): boolean { const source = connectorThread(botId, threadId); return source !== null && !source.group; }-function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "continuationAllowed" | "hostRefusal" | "guest" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id)), continuationAllowed = waitContinuationCheck(capability, { active: internalCapabilityIsActive, request: (id) => directRequestOwners.get(id), run: activeRoutineRunForThread, store });- return { assignmentId, continuationAllowed, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: continuationAllowed(), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment, cloudHome: Boolean(CLOUD_HOME) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }+function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick<WaitRouteContext, "sourceRefusal" | "assignmentId" | "continuationAllowed" | "hostRefusal" | "guest" | "setBy" | "peer" | "elsewhere"> { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }, assignmentId = () => handedAssignment(capability.roomHandoffId ?? directCoordinationSettlers.get(capability.generation)?.nodeId, (id) => coordinator.node(id)), continuationAllowed = waitContinuationCheck(capability, { active: internalCapabilityIsActive, request: (id) => directRequestOwners.get(id), run: activeRoutineRunForThread, store });+ return { assignmentId, continuationAllowed, sourceRefusal: (op, assignment) => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), waitContinuation: continuationAllowed(), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId), op, assignmentId: assignment, cloudHome: Boolean(CLOUD_HOME) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), hosted: HOSTED_WORKSPACE, guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), setBy: () => CLOUD_HOME ? waitSetBy({ personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId) || botApiThread(threadId), outsideDriven: outsideDrivenThread(threadId), run: activeRoutineRunForThread(threadId), continuation: continuationAllowed(), ownerOnly: () => cloudOwnerOnlyThread(threadId) || ownerSpokeOnly(store.messagesFor(threadId), cloudThreadStarters(threadId), cloudProvenOwnerPerson, cloudCardAnswerer) }) : undefined, peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; }/** Read fresh every time; a line stamped via the HTTP API does not count, so a bot cannot re-arm the ceiling it just spent. */function lastHumanRoomMessageAt(group: GroupRecord): number | undefined {@@ -13141,10 +13141,10 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {const proposedInput = { ...request.proposal, forBot };if (proposedInput.action !== "create" && (proposedInput.action === "update" ? outsideWorkStaysHere(fromThreadId) : cloudGuestDriven(fromThreadId)) && !outsideLineage.routineRunsConfined(String(proposedInput.routineId))) return json(res, 403, { error: OUTSIDE_STAYS_HERE });const wasOwners = proposedInput.action !== "create" && typeof proposedInput.routineId === "string" ? cloudRoutineIsOwners(proposedInput.routineId) : false;- const run = activeRoutineRunForThread(fromThreadId);+ const run = activeRoutineRunForThread(fromThreadId), othersWait = run?.eventSource === "wait" && run.waitSetBy !== "owner"; // a wait's follow-up is the owner's only when the turn that set the wait wasconst outside = Boolean(CLOUD_HOME) && (outsideDrivenThread(fromThreadId) || outsideWorkStaysHere(fromThreadId));- const ownersTurn = !outside && (cloudOwnerOnlyThread(fromThreadId) || cloudRoutineRunIsOwners(run, from.id, fromThreadId));- const ownersLevel = !outside && CLOUD_HOME && !cloudGuestDriven(fromThreadId) && (proposedInput.action === "create" ||+ const ownersTurn = !outside && !othersWait && (cloudOwnerOnlyThread(fromThreadId) || cloudRoutineRunIsOwners(run, from.id, fromThreadId));+ const ownersLevel = !outside && !othersWait && CLOUD_HOME && !cloudGuestDriven(fromThreadId) && (proposedInput.action === "create" ||cloudRoutineAuthors?.writer(String(proposedInput.routineId)) === CLOUD_OWNER_KEY) && (run?.threadId === fromThreadId || ownerSpokeOnly(store.messagesFor(fromThreadId), cloudThreadStarters(fromThreadId), cloudProvenOwnerPerson, cloudCardAnswerer));const proposed = await routineRequests.submit({botId: from.id,diff --git a/server/routes/waits.test.ts b/server/routes/waits.test.tsindex a6ad5200dc..cf97037dc2 100644--- a/server/routes/waits.test.ts+++ b/server/routes/waits.test.ts@@ -46,6 +46,14 @@ describe("the waits route", () => {expect(payload.text).toContain("you will then do what you wrote in follow_up");expect(payload.text).toContain("plain checks, no AI, until 1970-01-01T00:00:00.000Z");});+ it("hands the manager the turn's own word on who set the wait, never anything from the body", async () => {+ waits.create.mockClear();+ const setBy = () => "owner" as const;+ await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it.", setBy: "owner", set_by: "owner" });+ expect(waits.create.mock.lastCall![0]).not.toHaveProperty("setBy");+ await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it.", setBy: "person" }, { setBy });+ expect(waits.create.mock.lastCall![0].setBy).toBe(setBy);+ });it("says on a Cloud home that a sleeping My Cloud wakes to check every 30 minutes, and that the follow-up reports in its own results chat", async () => {const here = (await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it." })).payload.text!;expect(here).toContain("lands in this chat, and you will then do what you wrote in follow_up. Tell the person");diff --git a/server/routes/waits.ts b/server/routes/waits.tsindex b99997f6aa..7b129afb81 100644--- a/server/routes/waits.ts+++ b/server/routes/waits.ts@@ -6,7 +6,7 @@ import { WAIT_HOURS, WAIT_KINDS, type WaitKind } from "../../shared/waits.ts";import type { Surface } from "../../shared/wire.ts";import type { json as sendJson } from "../harness/http.ts";import { expandHome } from "../wait-probes.ts";-import { WAIT_WAKE_MS, waitList, type NewWaitCondition, type WaitManager } from "../waits.ts";+import { WAIT_WAKE_MS, waitList, type NewWaitCondition, type WaitManager, type WaitSetBy } from "../waits.ts";import { PASS } from "./table.ts";const WAITS = "/api/internal/waits";@@ -179,6 +179,8 @@ export interface WaitRouteContext {hostRefusal: () => string | null;/** A Cloud guest's turn: its follow-up would run later as the owner's, so a guest's wait only tells. */guest: () => boolean;+ /** Whose turn this provably is, kept on the wait it sets (wait-host.ts waitSetBy); absent or undefined, nobody's. */+ setBy?: () => WaitSetBy | undefined;peer: (nameOrId: string) => { id: string; name: string } | "self" | null;/** Why no bot here has that name: where it lives among the person's other places, or that bots work as one place. */elsewhere?: (name: string) => { where: string } | { hint: string } | null;@@ -251,6 +253,7 @@ export function createWaitRoutes(deps: { waits: Pick<WaitManager, "create" | "li...(request.followUp ? { followUp: request.followUp } : {}),hours: request.hours,...(assignmentId ? { assignmentId } : {}),+ ...(ctx.setBy ? { setBy: ctx.setBy } : {}),...(assignmentId || continuation ? {stillAllowed: () => {if (assignmentId && ctx.assignmentId?.() !== assignmentId) return WAIT_MESSAGES.notPerson;diff --git a/server/routines.test.ts b/server/routines.test.tsindex df508c546f..bef51c5e0f 100644--- a/server/routines.test.ts+++ b/server/routines.test.ts@@ -4416,6 +4416,23 @@ describe("runs that report into a chat", () => {expect(h.taskTitles).toHaveLength(0);});+ it("keeps whose turn set a wait on its follow-up's run across a restart, tells where it reports, and gives no other event that word", () => {+ const h = harness();+ const asked: unknown[] = [];+ h.options.eventResultsThread = (event) => { asked.push(event); return "results"; };+ const event = { prompt: "[Wait finished: the build] Deploy.", botId: "maus-1", runOn: "maus" as const, receivedAt: Date.now() };+ const owners = h.manager.enqueueWebhook({ ...event, webhookId: "wait:w1", webhookName: "the build", deliveryId: "w1", eventSource: "wait", waitSetBy: "owner" });+ const unknown = h.manager.enqueueWebhook({ ...event, webhookId: "wait:w2", webhookName: "the tests", deliveryId: "w2", eventSource: "wait" });+ const app = h.manager.enqueueWebhook({ ...event, webhookId: "trigger-1", webhookName: "Mail", deliveryId: "m1", eventSource: "app", waitSetBy: "owner" });+ const hook = h.manager.enqueueWebhook({ ...event, webhookId: "hook", webhookName: "Hook", deliveryId: "d1", waitSetBy: "owner" });+ expect(asked[0]).toMatchObject({ eventSource: "wait", waitSetBy: "owner" });+ for (const manager of [h.manager, new RoutineManager(h.options)]) {+ const run = (id: string) => manager.listRuns().find((one) => one.id === id)!;+ expect(run(owners.id)).toMatchObject({ triggerSource: "webhook", eventSource: "wait", waitSetBy: "owner" });+ for (const other of [unknown, app, hook]) expect(run(other.id)).not.toHaveProperty("waitSetBy");+ }+ });+it("finds a conversation's live run before an older finished one", async () => {const h = harness();h.options.joinConversation = () => "chat";diff --git a/server/routines.ts b/server/routines.tsindex 71ca0062a3..f749390f62 100644--- a/server/routines.ts+++ b/server/routines.ts@@ -133,7 +133,7 @@ export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark, WakeRetrworkedMs?: number;triggerSource?: RoutineRunTrigger;/** "app": a connected-app event started it; "wait": a wait's follow-up did (its triggerSource stays "webhook", an outside event). sameConversation: its trigger keeps one conversation (routine-same-conversation.ts). */- eventSource?: "app" | "wait"; sameConversation?: true; /** A person's own "Run now" test of its webhook started it: a usage cap treats it as a run started by hand. */ byPerson?: true;+ eventSource?: "app" | "wait"; /** Security invariant: harness-set only, on the follow-up of a wait a person's own turn set (waits.ts setBy): that run is theirs, not an outside event's. */ waitSetBy?: "owner" | "person"; sameConversation?: true; /** A person's own "Run now" test of its webhook started it: a usage cap treats it as a run started by hand. */ byPerson?: true;webhookId?: string;deliveryId?: string;sourceThreadId?: string;@@ -247,7 +247,7 @@ export interface RoutineManagerOptions {createGoalTask?: (groupId: string, title: string) => { threadId: string } | null;isResultsThread?: (botId: string, threadId: string) => boolean;resolveResultsThread?: (routine: Routine, forceNew: boolean) => { threadId: string; main?: true } | undefined;- eventResultsThread?: (event: { webhookId: string; webhookName: string; botId: string }) => string | undefined;+ eventResultsThread?: (event: { webhookId: string; webhookName: string; botId: string; eventSource?: "app" | "wait"; waitSetBy?: "owner" | "person" }) => string | undefined;frozenResultsThread?: (botId: string, threadId: string) => boolean;discardResultsThread?: (botId: string, threadId: string) => void;startTurn: (@@ -772,7 +772,7 @@ export class RoutineManager {enqueueWebhook(input: {webhookId: string; webhookName: string; prompt: string; botId: string; runOn: RoutineRunOn; deliveryId: string; receivedAt: number;- eventSource?: "app" | "wait"; sameConversation?: boolean; byPerson?: boolean;+ eventSource?: "app" | "wait"; waitSetBy?: "owner" | "person"; sameConversation?: boolean; byPerson?: boolean;/** Where the run reports, instead of the event's own results chat. */resultsThreadId?: string;}): { id: string } {@@ -786,7 +786,7 @@ export class RoutineManager {id: randomUUID(), routineId: input.webhookId, routineName: input.webhookName, prompt: input.prompt, target: "bot",botId: input.botId, runOn: input.runOn, scheduledFor: input.receivedAt, status: "queued", manual: false,triggerSource: "webhook", webhookId: input.webhookId, deliveryId: input.deliveryId, attachments: [], createdAt: this.now(),- resultsThreadId: input.resultsThreadId ?? this.options.eventResultsThread?.(input), ...(input.eventSource ? { eventSource: input.eventSource } : {}), ...(input.sameConversation ? { sameConversation: true } : {}), ...(input.byPerson ? { byPerson: true } : {}),+ resultsThreadId: input.resultsThreadId ?? this.options.eventResultsThread?.(input), ...(input.eventSource ? { eventSource: input.eventSource } : {}), ...(input.eventSource === "wait" && input.waitSetBy ? { waitSetBy: input.waitSetBy } : {}), ...(input.sameConversation ? { sameConversation: true } : {}), ...(input.byPerson ? { byPerson: true } : {}),};this.commitEvent(run, input.deliveryId, () => { this.runs.push(run); });return cloneRun(run);diff --git a/server/wait-follow-up-lineage.e2e.test.ts b/server/wait-follow-up-lineage.e2e.test.tsnew file mode 100644index 0000000000..b44b53d0b7--- /dev/null+++ b/server/wait-follow-up-lineage.e2e.test.ts@@ -0,0 +1,181 @@+// A wait's follow-up is the work of the person whose own turn set the wait, on a real personal Cloud and a real Team+// Cloud, with the fake engine: the level each turn really got, read from what the engine was started with. A routine the+// follow-up makes keeps its shell; one an outside event's run makes still does not.+import { randomBytes } from "node:crypto";+import { readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";++import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";+import { CLOUD_NOBODY_KEY, CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts";+import { WAIT_MESSAGES } from "./routes/waits.ts";+import { hostTimeout } from "./testing/host-timeout.ts";++const tag = randomBytes(6).toString("hex");+const dump = join(tmpdir(), `wait-lineage-${tag}.json`), release = join(tmpdir(), `wait-lineage-${tag}.release`),+ holding = join(tmpdir(), `wait-lineage-${tag}.holding`), held = join(tmpdir(), `wait-lineage-${tag}.held`);+// A turn started while `holding` is there ends on `held`, every other on `release`: one bot stays busy while another's turn ends.+const engine = `const { existsSync: __has } = await import("node:fs"); process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(dump)}; process.env.FAKE_CLAUDE_RELEASE = __has(${JSON.stringify(holding)}) ? ${JSON.stringify(held)} : ${JSON.stringify(release)};`;+const KEY = randomBytes(16).toString("hex");+const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+const read = () => { try { return JSON.parse(readFileSync(dump, "utf8")); } catch { return null; } };+async function until<V>(what: string, fn: () => Promise<V> | V, ms = hostTimeout(40_000)): Promise<V> {+ const end = Date.now() + ms;+ for (;;) {+ const value = await fn();+ if (value) return value;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(100);+ }+}+type Turn = { argv: string[]; mcpConfig: { mcpServers: { agents: { env: { OMB_COMMS_TOKEN: string } } } } };+const turnWith = async (marker: string): Promise<Turn> => (await until(`a turn with ${marker}`, () => { const turn = read(); return turn && JSON.stringify(turn.prompt ?? "").includes(marker) ? turn as Turn : null; }))!;+const confined = (turn: Turn) => turn.argv.includes("--restricted");+const atFull = (turn: Turn) => turn.argv[turn.argv.indexOf("--permission-mode") + 1] === "bypassPermissions";+const tokenOf = (turn: Turn) => turn.mcpConfig.mcpServers.agents.env.OMB_COMMS_TOKEN;++type Api = (method: string, path: string, body?: unknown) => Promise<{ status: number; body: any }>;+/** One Cloud, as one signed-in person: its routes, and the routes a bot's own turn calls. */+function home(base: string, as: Api, capability: (botId: string, threadId: string) => Promise<string>) {+ const internal = async (botId: string, threadId: string, path: string, body: object, token?: string) => {+ const bearer = token ?? await capability(botId, threadId);+ const response = await fetch(`${base}${path}?fromBotId=${botId}`, { method: "POST", headers: { authorization: `Bearer ${bearer}`, "content-type": "application/json" }, body: JSON.stringify({ fromBotId: botId, fromThreadId: threadId, ...body }) });+ return { status: response.status, body: await response.json().catch(() => null) as any };+ };+ const runs = async () => (await as("GET", "/api/routines")).body.runs as any[];+ const idle = (...ids: string[]) => until(`${ids} idle`, async () => {+ const bots = (await as("GET", "/api/bots")).body.bots as any[];+ return ids.every((id) => !bots.find((bot) => bot.id === id)?.busy);+ });+ const finish = async (...ids: string[]) => {+ writeFileSync(release, ""); writeFileSync(held, "");+ await idle(...ids);+ await sleep(300);+ for (const file of [release, held, holding, dump]) rmSync(file, { force: true });+ };+ /** The routine a turn in `threadId` makes, run at once: the turn that run got. */+ const routineMadeIn = async (botId: string, threadId: string, marker: string, token?: string) => {+ const made = await internal(botId, threadId, "/api/internal/trigger-requests", { action: "create", kind: "schedule", routine: { name: `Made by ${marker}`, instructions: marker, schedule: { type: "interval", everyMinutes: 60 } } }, token);+ expect(made.body?.state, JSON.stringify(made.body)).toBe("applied");+ const id = made.body.result.resultId as string;+ return { id, started: () => internal(botId, threadId, "/api/internal/trigger-requests", { action: "run_now", triggerId: id }, token) };+ };+ /**+ * `waiter` is asked by this person, sets a wait for `busy` to finish with a follow-up, and both turns end: the+ * follow-up's own turn, running. Needs both bots idle.+ */+ const followUpOfAWait = async (waiter: { id: string; threadId: string }, busy: { id: string; name: string; threadId: string }, marker: string, send: Api = as) => {+ writeFileSync(holding, "");+ expect((await send("POST", `/api/bots/${busy.id}/messages`, { text: `${marker}-busy`, threadId: busy.threadId })).status).toBe(202);+ await turnWith(`${marker}-busy`);+ rmSync(holding, { force: true });+ expect((await send("POST", `/api/bots/${waiter.id}/messages`, { text: `${marker}-asked`, threadId: waiter.threadId })).status).toBe(202);+ const asked = await turnWith(`${marker}-asked`);+ const set = await internal(waiter.id, waiter.threadId, "/api/internal/waits", { label: marker, kind: "bot_idle", bot: busy.name, follow_up: `${marker}-follow-up` }, tokenOf(asked));+ expect(set.status, JSON.stringify(set.body)).toBe(201);+ writeFileSync(release, "");+ await idle(waiter.id);+ rmSync(release, { force: true });+ rmSync(dump, { force: true });+ writeFileSync(held, "");+ const turn = await turnWith(`${marker}-follow-up`);+ rmSync(held, { force: true });+ const run = await until("the follow-up's run", async () => (await runs()).find((one) => one.eventSource === "wait" && one.routineName === marker && one.threadId));+ return { turn, run, thread: run.threadId as string, asked };+ };+ return { internal, runs, idle, finish, routineMadeIn, followUpOfAWait };+}++let fx: CloudSendFixture, team: CloudTeamFixture, ada: string, ben: string;+beforeAll(async () => {+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-${randomBytes(8).toString("hex")}`, cloudEngine: engine, desktopEngine: engine, env: { OMB_TEST_INTERNAL_CAPABILITY_KEY: KEY },+ team: { id: "team-acme-1", name: "Acme", engine } });+ team = fx.team!;+ ada = (await team.pair({ email: "[email protected]", role: "admin" })).token!;+ ben = (await team.pair({ email: "[email protected]", role: "member" })).token!;+}, hostTimeout(180_000));+afterAll(async () => {+ writeFileSync(release, ""); writeFileSync(held, "");+ await sleep(500);+ await fx?.close?.();+ for (const file of [dump, release, holding, held]) rmSync(file, { force: true });+});++describe("a personal Cloud only its owner has used", () => {+ it("keeps the shell for a routine the follow-up of the owner's own wait makes, and takes it from one a webhook's run makes", async () => {+ const cloud = fx.onCloud, at = home(fx.cloudBase, cloud, async (botId, threadId) => ((await (await fetch(`${fx.cloudBase}/api/testing/internal-capability`, { method: "POST",+ headers: { "content-type": "application/json", "x-openmausbot-test-capability": KEY }, body: JSON.stringify({ botId, threadId }) })).json()) as { token: string }).token);+ const bot = async (name: string) => {+ const made = (await cloud("POST", "/api/bots", { name })).body.bot as { id: string; name: string; threadId: string };+ expect((await cloud("PATCH", `/api/bots/${made.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);+ return made;+ };+ const scout = await bot("Wait scout"), mate = await bot("Wait mate");+ const writers = () => JSON.parse(readFileSync(join(fx.root, "cloud", ".openmausbot", "lending-routines.json"), "utf8")).writers as Record<string, string>;++ const first = await at.followUpOfAWait(scout, mate, "owners-wait");+ expect(first.run).toMatchObject({ triggerSource: "webhook", eventSource: "wait", waitSetBy: "owner" });+ expect(confined(first.turn)).toBe(false);+ const made = await at.routineMadeIn(scout.id, first.thread, "routine-after-owners-wait");+ expect(writers()[made.id]).not.toBe(CLOUD_OUTSIDE_KEY);+ await at.finish(scout.id, mate.id);+ expect((await made.started()).status).toBe(201);+ const ran = await turnWith("routine-after-owners-wait");+ expect(confined(ran)).toBe(false);+ expect(atFull(ran)).toBe(true);+ await at.finish(scout.id, mate.id);++ // A bot changing it from another such follow-up leaves it as it was: still with its shell.+ const second = await at.followUpOfAWait(scout, mate, "owners-second-wait");+ const changed = await at.internal(scout.id, second.thread, "/api/internal/trigger-requests", { action: "update", triggerId: made.id, changes: { instructions: "routine-changed-after-wait" } });+ expect(changed.body?.state, JSON.stringify(changed.body)).toBe("applied");+ expect(writers()[made.id]).not.toBe(CLOUD_OUTSIDE_KEY);+ // The follow-up's own run cannot set the next wait on a Cloud: no chain of waits starts here.+ expect(await at.internal(scout.id, second.thread, "/api/internal/waits", { label: "again", kind: "bot_idle", bot: mate.name, follow_up: "again-follow-up" }, tokenOf(second.turn)))+ .toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.notPerson } });+ await at.finish(scout.id, mate.id);+ expect((await made.started()).status).toBe(201);+ expect(confined(await turnWith("routine-changed-after-wait"))).toBe(false);+ await at.finish(scout.id, mate.id);++ // A webhook's run: it sets no wait at all, and the routine it makes is outside work's, as before.+ const hook = (await cloud("POST", "/api/webhooks", { name: "Wait hook", prompt: "Handle the event.", botId: scout.id })).body;+ const receiver = fx.cloudBase.replace(/:(\d+)$/, (_: string, port: string) => `:${Number(port) + 1}`);+ expect((await fetch(`${receiver}/hooks/${hook.webhook.endpointId}/${encodeURIComponent(hook.credential.secret)}`, { method: "POST", headers: { "content-type": "application/json", "idempotency-key": randomBytes(6).toString("hex") }, body: JSON.stringify({ text: "marker-wait-hook" }) })).status).toBe(202);+ const hooked = await turnWith("marker-wait-hook");+ const hookThread = (await until("the webhook's run", async () => (await at.runs()).find((run) => run.webhookId === hook.webhook.id && run.threadId))).threadId as string;+ expect(await at.internal(scout.id, hookThread, "/api/internal/waits", { label: "from outside", kind: "bot_idle", bot: mate.name, follow_up: "outside-follow-up" }, tokenOf(hooked)))+ .toMatchObject({ status: 403, body: { error: WAIT_MESSAGES.notPerson } });+ const outside = await at.routineMadeIn(scout.id, hookThread, "routine-after-webhook");+ expect(writers()[outside.id]).toBe(CLOUD_OUTSIDE_KEY);+ expect((await outside.started()).status).toBe(201);+ expect(confined(await turnWith("routine-after-webhook"))).toBe(true);+ await at.finish(scout.id, mate.id);+ }, hostTimeout(240_000));+});++describe("a Team Cloud", () => {+ it("runs a member's wait follow-up and the routine it makes with the shell, as the member's and never the owner's", async () => {+ const at = home(team.base, (method, path, body) => team.as(ada, method, path, body), (botId, threadId) => team.capability(botId, threadId));+ const asBen: Api = (method, path, body) => team.as(ben, method, path, body);+ const bot = async (name: string) => {+ const made = (await team.as(ada, "POST", "/api/bots", { name, visibility: "everyone" })).body.bot as { id: string; name: string; threadId: string };+ expect((await team.as(ada, "PATCH", `/api/bots/${made.id}`, { approvalMode: "full", applyToAllThreads: true })).status).toBe(200);+ return made;+ };+ const scout = await bot("Team wait scout"), mate = await bot("Team wait mate");+ const own = async (of: { id: string; name: string }, title: string) => ({ ...of, threadId: (await asBen("POST", `/api/bots/${of.id}/tasks`, { title })).body.task.threadId as string });+ const writers = () => JSON.parse(readFileSync(join(team.home, ".openmausbot", "lending-routines.json"), "utf8")).writers as Record<string, string>;++ const follow = await at.followUpOfAWait(await own(scout, "Ben asks"), await own(mate, "Ben's busy work"), "members-wait", asBen);+ expect(follow.run).toMatchObject({ eventSource: "wait", waitSetBy: "person" });+ expect(confined(follow.turn)).toBe(false);+ const made = await at.routineMadeIn(scout.id, follow.thread, "routine-after-members-wait");+ expect(writers()[made.id]).toBe(CLOUD_NOBODY_KEY);+ await at.finish(scout.id, mate.id);+ expect((await made.started()).status).toBe(201);+ expect(confined(await turnWith("routine-after-members-wait"))).toBe(false);+ await at.finish(scout.id, mate.id);+ }, hostTimeout(240_000));+});diff --git a/server/wait-host.test.ts b/server/wait-host.test.tsindex 421da22630..5a9512fb16 100644--- a/server/wait-host.test.ts+++ b/server/wait-host.test.ts@@ -2,7 +2,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import type { Notification } from "../shared/notification.ts";import type { Message } from "./store.ts";-import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitContinuationCheck, waitLineFields, waitRunChat, waitTurnRunId, type WaitHostDeps } from "./wait-host.ts";+import { cancelWaitFromCard, createWaitHost, waitContinuesHere, waitContinuationCheck, waitLineFields, waitRunChat, waitSetBy, waitTurnRunId, type WaitHostDeps } from "./wait-host.ts";import type { WaitRecord } from "./waits.ts";const NOW = 1_700_000_000_000;@@ -107,6 +107,36 @@ describe("the store side of waits", () => {expect(waitRunChat({ botId: "bot-1", resultsThreadId: "room" }, () => false, false)).toBeNull();});+ it("hands the follow-up whose turn set the wait, and nothing when no record says", () => {+ host.followUp({ ...wait, followUp: "Deploy it.", setBy: "owner" });+ expect(enqueue.mock.lastCall![0]).toMatchObject({ eventSource: "wait", waitSetBy: "owner" });+ cloudHost.followUp({ ...wait, followUp: "Deploy it.", setBy: "person" });+ expect(enqueue.mock.lastCall![0]).toMatchObject({ eventSource: "wait", waitSetBy: "person" });+ cloudHost.followUp({ ...wait, followUp: "Deploy it." });+ expect(enqueue.mock.lastCall![0]).not.toHaveProperty("waitSetBy");+ });++ it("takes whose turn sets a wait from the turn's own records, and keeps it wait after wait", () => {+ const person = { personStarted: true, guest: false, outsideDriven: false, run: null, continuation: false, ownerOnly: () => true };+ expect(waitSetBy(person)).toBe("owner");+ expect(waitSetBy({ ...person, ownerOnly: () => false })).toBe("person");+ // Nothing a person started: a routine's run, an outside event's run, a guest's turn, a conversation outside work reached.+ expect(waitSetBy({ ...person, personStarted: false })).toBeUndefined();+ expect(waitSetBy({ ...person, guest: true })).toBeUndefined();+ expect(waitSetBy({ ...person, outsideDriven: true })).toBeUndefined();+ expect(waitSetBy({ ...person, run: {} })).toBeUndefined();+ expect(waitSetBy({ ...person, run: { eventSource: "app" }, continuation: true })).toBeUndefined();+ // A wait set in a wait's follow-up keeps what the first wait had, both ways, and only as its verified follow-up.+ for (const first of ["owner", "person", undefined] as const) {+ const second = waitSetBy({ ...person, personStarted: false, run: { eventSource: "wait", waitSetBy: first }, continuation: true });+ expect(second).toBe(first);+ expect(waitSetBy({ ...person, personStarted: false, run: { eventSource: "wait", waitSetBy: second }, continuation: true })).toBe(first);+ }+ expect(waitSetBy({ ...person, run: { eventSource: "wait", waitSetBy: "owner" }, continuation: false })).toBeUndefined();+ expect(waitSetBy({ ...person, run: { eventSource: "wait", waitSetBy: "owner" }, continuation: true, outsideDriven: true })).toBeUndefined();+ expect(waitSetBy({ ...person, run: { eventSource: "wait" }, continuation: true })).toBeUndefined();+ });+it("knows a deleted bot from an idle one", () => {expect([host.botBusy("bot-1"), host.botBusy("gone")]).toEqual([false, undefined]);});diff --git a/server/wait-host.ts b/server/wait-host.tsindex 3b6152bfa1..67303589e0 100644--- a/server/wait-host.ts+++ b/server/wait-host.ts@@ -4,7 +4,7 @@ import type { Notification } from "../shared/notification.ts";import { buildNotification } from "./notify.ts";import type { RoutineManager, RoutineRun } from "./routines.ts";import type { BotRecord, Store } from "./store.ts";-import type { WaitManager, WaitManagerOptions } from "./waits.ts";+import type { WaitManager, WaitManagerOptions, WaitSetBy } from "./waits.ts";export interface WaitHostDeps {store: Pick<Store, "appendMessage" | "patchMessage" | "patchTask" | "messagesFor" | "bot">;@@ -51,6 +51,25 @@ export function waitLineFields(&& run.deliveryId && run.webhookId === `wait:${run.deliveryId}` ? { waitId: run.deliveryId } : {};}+/**+ * Security invariant: whose turn sets a wait, from the harness's records only, so its follow-up is that person's work+ * and not an outside event's. A person's own request, in a conversation no outside work has reached, proves it; so+ * does the verified follow-up of a wait that carried it, which keeps what that wait had, however many waits deep. A+ * guest's turn, a routine's run, an outside event's run and a follow-up of any of them prove nothing.+ */+export function waitSetBy(turn: {+ personStarted: boolean; guest: boolean; outsideDriven: boolean;+ /** The run this conversation is working in now, and whether this turn is that wait's verified follow-up. */+ run: Pick<RoutineRun, "eventSource" | "waitSetBy"> | null; continuation: boolean;+ /** Only the Cloud's owner has spoken in this conversation: a routine made here would be theirs. */+ ownerOnly: () => boolean;+}): WaitSetBy | undefined {+ if (turn.guest || turn.outsideDriven) return undefined;+ if (turn.run) return turn.continuation && turn.run.eventSource === "wait" ? turn.run.waitSetBy : undefined;+ if (!turn.personStarted) return undefined;+ return turn.ownerOnly() ? "owner" : "person";+}+interface WaitRunOwner {automationRunId?: string;messageId?: string;@@ -139,6 +158,7 @@ export function createWaitHost(deps: WaitHostDeps): Pick<WaitManagerOptions, "sodeliveryId: wait.id,receivedAt: now(),eventSource: "wait",+ ...(wait.setBy ? { waitSetBy: wait.setBy } : {}),...(deps.cloudHome ? {} : { resultsThreadId: wait.threadId }),});},diff --git a/server/waits.test.ts b/server/waits.test.tsindex 209c7fc014..ff6c42c1a6 100644--- a/server/waits.test.ts+++ b/server/waits.test.ts@@ -1,4 +1,4 @@-import { existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, describe, expect, it, vi } from "vitest";@@ -195,6 +195,26 @@ describe("WaitManager", () => {if (process.platform !== "win32") expect(statSync(h.file).mode & 0o777).toBe(0o600);});+ it("keeps whose turn set a wait across a restart, read as the wait is stored, and takes nothing a record did not hold", async () => {+ const h = harness();+ let reached = false;+ const setBy = () => (reached ? undefined : "owner" as const);+ const owners = await h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the report", condition: { kind: "file_exists", path: "/r.txt" }, followUp: "Read it.", setBy });+ expect(owners).toMatchObject({ state: "created", wait: { setBy: "owner" } });+ reached = true;+ const late = await h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the build", condition: { kind: "file_exists", path: "/b.txt" }, followUp: "Read it.", setBy });+ const plain = await h.manager.create({ botId: "bot-1", threadId: "t-1", label: "the tests", condition: { kind: "file_exists", path: "/t.txt" }, followUp: "Read it." });+ for (const made of [late, plain]) expect(made.state === "created" && "setBy" in made.wait).toBe(false);+ const saved = JSON.parse(readFileSync(h.file, "utf8"));+ saved.waits[1].setBy = "admin";+ writeFileSync(h.file, JSON.stringify(saved));+ expect(h.reload().list("bot-1").map((wait) => wait.setBy)).toEqual(["owner", undefined, undefined]);+ h.stamp = { size: 1, mtimeMs: 1 };+ h.advance(5_000);+ await h.manager.tick();+ expect(h.followUp.mock.calls.map(([wait]) => wait.setBy)).toEqual(["owner", undefined, undefined]);+ });+it("creates nothing when the condition is already true", async () => {const h = harness();h.stamp = { size: 1, mtimeMs: 1 };diff --git a/server/waits.ts b/server/waits.tsindex b593760b65..7177a809b9 100644--- a/server/waits.ts+++ b/server/waits.ts@@ -40,10 +40,15 @@ export type WaitCondition =| { kind: "file_changed"; path: string; before: FileStamp | null }| { kind: "process_running" | "process_gone"; process: string }| { kind: "bot_idle"; botId: string; botName: string; sawBusy: boolean };+/** Whose turn set a wait: "owner" where only the Cloud's owner had spoken, "person" any other person's own request. */+export type WaitSetBy = "owner" | "person";export interface WaitNotice { status: "fired" | "expired" | "stopped"; text: string }export interface WaitRecord {id: string; botId: string; threadId: string; label: string; condition: WaitCondition; followUp?: string;assignmentId?: string;+ /** Security invariant: harness-set only, from the records of the turn that set it (wait-host.ts waitSetBy). Absent, on an+ * older record or a turn that proved nothing, its follow-up counts as an outside event's run. */+ setBy?: WaitSetBy;createdAt: number; expiresAt: number; nextCheckAt: number; errors: number; cardMessageId?: string;/** Decided and saved first; posted once its chat is free. */ending?: WaitNotice;@@ -52,6 +57,8 @@ export interface NewWait {botId: string; threadId: string; label: string; condition: NewWaitCondition; followUp?: string; hours?: number; assignmentId?: string;/** Asked again right before the wait is stored, after the checks `create` awaits; a refusal text stores nothing, so work stopped meanwhile leaves no wait behind. Never saved. */stillAllowed?: () => string | null;+ /** Read once, as the wait is stored, so what reached the chat during the checks `create` awaits counts. Never saved as given. */+ setBy?: () => WaitSetBy | undefined;}export type CreateWaitResult =| { state: "created"; wait: WaitRecord; note?: string }@@ -87,6 +94,7 @@ const recordSchema = z.object({condition: conditionSchema,followUp: z.string().optional(),assignmentId: z.string().optional(),+ setBy: z.enum(["owner", "person"]).optional().catch(undefined),createdAt: z.number(),expiresAt: z.number(),nextCheckAt: z.number(),@@ -198,6 +206,7 @@ export class WaitManager {const crowded = this.limitRefusal(input);if (crowded) return crowded;const now = this.now();+ const setBy = input.setBy?.();const wait: WaitRecord = {id: randomUUID(),botId: input.botId,@@ -206,6 +215,7 @@ export class WaitManager {condition,...(input.followUp ? { followUp: input.followUp } : {}),...(input.assignmentId ? { assignmentId: input.assignmentId } : {}),+ ...(setBy ? { setBy } : {}),createdAt: now,expiresAt: now + (input.hours ?? WAIT_HOURS.default) * 3_600_000,nextCheckAt: now + interval(condition.kind, 0),