Skip to content

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

Cloud: a routine run refused the lent computer ends failed, saying why in the app's words (#6781)

Milind Sonid73f26a38623
diff --git a/server/automation-reports.test.ts b/server/automation-reports.test.ts
index a2464793d2..cf2f2f286f 100644
--- a/server/automation-reports.test.ts
+++ b/server/automation-reports.test.ts
@@ -79,7 +79,7 @@ describe("what the chat's own session reads", () => {
});
/** A real Store; the routine runs live in a stand-in for the RoutineManager, which keeps their report states. */
-function fixture(options: { threadLanguage?: (threadId: string) => string | undefined } = {}) {
+function fixture(options: { threadLanguage?: (threadId: string) => string | undefined; notes?: Map<string, string> } = {}) {
const store = new Store(selection);
const bot = store.createBot({ name: "Pepper" });
const main = bot.threadId;
@@ -107,6 +107,7 @@ function fixture(options: { threadLanguage?: (threadId: string) => string | unde
wrote: (_bot: BotRecord, threadId) => wrote.push(threadId),
notify: (kind, _bot, threadId, detail) => notified.push({ kind, threadId, detail }),
...(options.threadLanguage ? { threadLanguage: options.threadLanguage } : {}),
+ ...(options.notes ? { notes: { has: (runId: string) => options.notes!.has(runId), take: (runId: string) => { const note = options.notes!.get(runId) ?? null; options.notes!.delete(runId); return note; } } } : {}),
});
const reports = create();
let serial = 0;
@@ -262,6 +263,28 @@ describe("automation reports", () => {
expect(f.notified.map((entry) => entry.threadId)).toEqual([f.main, nowhere.threadId]);
});
+ it("puts the app's own line under a completed run's reply, apart from the bot's words, and says it even when the reply is quiet", () => {
+ const notes = new Map<string, string>();
+ const f = fixture({ notes });
+ const SAID = "\"Inbox brief\" can't use your PC because it isn't confirmed as yours: it was last changed or made outside your own chats. Open it and save it to make it yours again.";
+ const replied = f.finished("No execution environment was mounted, so I couldn't check.");
+ notes.set(replied.id, SAID);
+ f.reports.runSettled(replied, `turn-${replied.id}`);
+ const quiet = f.finished("NOTHING NEW");
+ notes.set(quiet.id, SAID);
+ f.reports.runSettled(quiet, `turn-${quiet.id}`);
+ expect(f.lines().map((line) => [line.text, line.automation?.failed])).toEqual([
+ [`No execution environment was mounted, so I couldn't check.\n\n${SAID}`, undefined],
+ [SAID, undefined],
+ ]);
+ expect(f.notified.map((entry) => entry.detail)).toEqual([`Inbox brief: No execution environment was mounted, so I couldn't check.\n\n${SAID}`, `Inbox brief: ${SAID}`]);
+ const nowhere = f.finished("Done.", "Orphan", { resultsThreadId: undefined });
+ notes.set(nowhere.id, SAID);
+ f.reports.runSettled(nowhere, `turn-${nowhere.id}`);
+ expect(f.notified.at(-1)).toEqual({ kind: "done", threadId: nowhere.threadId, detail: `Done.\n\n${SAID}` });
+ expect(notes.size).toBe(0);
+ });
+
it("says a run whose reply came back but a step failed was partly done, not that it didn't finish", () => {
const f = fixture();
const partly = f.finished(null, "Inbox brief", { status: "failed", error: "Stopped because the tool call failed.", partial: true });
diff --git a/server/automation-reports.ts b/server/automation-reports.ts
index b6b57a6156..b22b642d53 100644
--- a/server/automation-reports.ts
+++ b/server/automation-reports.ts
@@ -114,8 +114,15 @@ export interface AutomationReportDeps {
brief?(run: RoutineRun, turnId?: string): void;
/** The language a line in this conversation is written in (server/server-lines.ts); absent, English. */
threadLanguage?(threadId: string): string | undefined;
+ /** A line the app adds under a completed run's reply, in the language of the chat it reports to, taken once
+ * (host/refused-lending.ts): it is said even when the bot's reply is quiet. */
+ notes?: { has(runId: string): boolean; take(runId: string, language: string | undefined): string | null };
}
+/** The reply with the app's own line under it, apart from the bot's words. */
+const withNote = (reply: RunReply, note: string | null): RunReply =>
+ !note ? reply : reply.quiet ? { quiet: false, text: note } : { ...reply, text: `${reply.text}\n\n${note}` };
+
export function createAutomationReports(deps: AutomationReportDeps) {
const { store } = deps;
const waiting = new Map<string, Waiting>();
@@ -233,7 +240,7 @@ export function createAutomationReports(deps: AutomationReportDeps) {
}
const source = line.kind === "reply" ? replyOf(run, line.messageId) : undefined;
const language = deps.threadLanguage?.(target.threadId);
- const said: RunReply = line.kind === "reply" ? read(run, source)
+ const said: RunReply = line.kind === "reply" ? withNote(read(run, source), deps.notes?.take(run.id, language) ?? null)
: { quiet: false, text: line.detail ? serverLine(language, run.partial ? "server.runs.partlyDoneWhy" : "server.runs.didNotFinishWhy", { detail: line.detail }) : serverLine(language, "server.runs.didNotFinish") };
const recovered = said.quiet && lastSaidFailed(run, target.threadId);
if (said.quiet && !recovered) {
@@ -324,9 +331,12 @@ export function createAutomationReports(deps: AutomationReportDeps) {
const reply = read(run, said);
const bot = store.bot(run.botId);
const target = destination(run);
- if (target && (!reply.quiet || lastSaidFailed(run, target.threadId))) hold(run.id, { kind: "reply", run, messageId: said?.id ?? null });
- else if (reply.quiet) deps.routines()?.noteReport(run.id, { state: "quiet" });
- else if (bot) deps.notify("done", bot, run.threadId, reply.text);
+ if (target && (!reply.quiet || lastSaidFailed(run, target.threadId) || deps.notes?.has(run.id))) hold(run.id, { kind: "reply", run, messageId: said?.id ?? null });
+ else {
+ const noted = withNote(reply, deps.notes?.take(run.id, deps.threadLanguage?.(run.threadId)) ?? null);
+ if (noted.quiet) deps.routines()?.noteReport(run.id, { state: "quiet" });
+ else if (bot) deps.notify("done", bot, run.threadId, noted.text);
+ }
},
/** A run failed in a way the person is told about: one line says so where its reports go. */
runFailed(run: RoutineRun, detail: string): void {
diff --git a/server/cloud-lending.e2e.test.ts b/server/cloud-lending.e2e.test.ts
index 69feffc0ac..d10ffbba49 100644
--- a/server/cloud-lending.e2e.test.ts
+++ b/server/cloud-lending.e2e.test.ts
@@ -63,31 +63,37 @@ async function leftBehind(of: { threadIds?: string[]; routineIds?: string[] }) {
}
type Turn = { argv: string[]; cwd: string; systemPrompt?: string; mcpConfig: { mcpServers: { agents: { command: string; args: string[]; env: Record<string, string> } } } };
-/** The latest turn `agentsFor` found. */
+/** The latest turn `agentsFor` found, and the dump it was in. */
let turn: Turn;
+let turnDump = "";
+/** Ends the held turn that dumped itself there, as a model's last reply would. */
+const finish = (dump: string) => writeFileSync(join(turnDumps(), dump.replace(/\.json$/u, ".finish")), "");
const turnDumps = () => join(home, "turns");
const readTurns = () => new Map(readdirSync(turnDumps()).filter((name) => name.endsWith(".json")).flatMap((name) => {
try { return [[name, readFileSync(join(turnDumps(), name), "utf8")] as const]; } catch { return []; }
}));
-/** Each engine process dumps its own turn, so the turns a restart resumes never take the place of this one. */
-async function agentsFor(start: () => Promise<void>, botId: string, threadId?: string) {
+/** Each engine process dumps its own turn, so the turns a restart resumes never take the place of this one. `threadId`
+ * may be found only once `start` is done (a routine's run, whose conversation the scheduler makes): the wait for the
+ * turn then starts from there. */
+async function agentsFor(start: () => Promise<void>, botId: string, threadId?: string | (() => Promise<string>)) {
const before = readTurns();
await start();
+ if (typeof threadId === "function") threadId = await threadId();
await expect.poll(() => {
for (const [name, text] of readTurns()) {
if (before.get(name) === text) continue;
let found: Turn;
try { found = JSON.parse(text) as Turn; } catch { continue; }
const env = found.mcpConfig?.mcpServers?.agents?.env;
- if (env?.OMB_BOT_ID === botId && (!threadId || env.OMB_THREAD_ID === threadId)) { turn = found; return true; }
+ if (env?.OMB_BOT_ID === botId && (!threadId || env.OMB_THREAD_ID === threadId)) { turn = found; turnDump = name; return true; }
}
return false;
}, { timeout: 15_000 }).toBe(true);
return turn.mcpConfig.mcpServers.agents;
}
-async function proxyFor(start: () => Promise<void>, botId: string, threadId?: string) {
+async function proxyFor(start: () => Promise<void>, botId: string, threadId?: Parameters<typeof agentsFor>[2]) {
const agents = await agentsFor(start, botId, threadId);
const proxy = spawn(agents.command, agents.args, { env: { PATH: process.env.PATH, HOME: home, ...agents.env }, stdio: ["pipe", "pipe", "pipe"] });
proxies.push(proxy);
@@ -122,7 +128,8 @@ beforeAll(async () => {
if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "[email protected]" })); process.exit(0); }
process.env.FAKE_CLAUDE_VERSION = "2.1.284";
// One-shot runs (a new chat's title) dump elsewhere, so they never take the place of the turn a test is waiting for.
-if (process.argv[2] !== "--version") { process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(join(home, "turns"))} + "/" + process.pid + ".json"; process.env.FAKE_CLAUDE_TEXT_DUMP = ${JSON.stringify(join(home, "one-shot.json"))}; process.env.FAKE_CLAUDE_MODE = "hang"; }
+// A held turn ends well once its own finish file exists (finish()).
+if (process.argv[2] !== "--version") { process.env.FAKE_CLAUDE_DUMP = ${JSON.stringify(join(home, "turns"))} + "/" + process.pid + ".json"; process.env.FAKE_CLAUDE_TEXT_DUMP = ${JSON.stringify(join(home, "one-shot.json"))}; process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_FINISH_GATE = ${JSON.stringify(join(home, "turns"))} + "/" + process.pid + ".finish"; }
await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)});
`, { mode: 0o755 });
// No `features` block: the maintainer flag is off, as on every Cloud home.
@@ -635,3 +642,130 @@ it("paused, the PC still hears a bot that needs it: one card in the chat, the ap
expect(prompts, "the app's own prompt came up once").toHaveLength(1);
rmSync(pcHome, { recursive: true, force: true });
}, hostTimeout(90_000));
+
+it("a routine the bot changes in the owner's own chat keeps the lent computer on its next scheduled run, as does one its own run changes; one remade beside an old report is refused, and the app says why on every run until it is saved", async () => {
+ const device = ({ win32: "PC", darwin: "Mac" } as Record<string, string>)[process.platform] ?? "computer";
+ const folderPath = realpathSync(mkdtempSync(join(tmpdir(), "omb-cloud-lent-routines-")));
+ writeFileSync(join(folderPath, "plan.md"), "from the computer");
+ const env = { id: "my-cloud", name: "My Cloud", origin: base };
+ connector?.close();
+ rmSync(join(home, "desktop-profile"), { recursive: true, force: true });
+ connector = lend(env);
+ await connector.saveCloud(env, { folders: [{ id: randomUUID(), name: "Plans", path: folderPath, write: false }], screen: false });
+ await expect.poll(() => connector!.cloudState(env).connected, { timeout: 8000 }).toBe(true);
+ const [computer] = (await api("GET", "/api/shared-computers", { token: owner })).body.computers;
+ const authors = () => JSON.parse(readFileSync(join(home, ".openmausbot", "lending-routines.json"), "utf8"));
+ const lent = (listing: any) => JSON.parse(listing.content[0].text);
+ const applied = (result: unknown) => { const text = JSON.stringify(result); expect(text).not.toContain("isError\":true"); return text; };
+ const made = (result: unknown) => /trigger id ([\w-]+)/u.exec(applied(result))?.[1] ?? "";
+ const bot = (await api("POST", "/api/bots", { token: owner, body: { name: "Morning reader", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } } })).body.bot;
+ const chat = async () => (await api("GET", `/api/threads/${bot.threadId}/messages`, { token: owner })).body.messages as any[];
+ const ownerAsks = (text: string) => proxyFor(async () => {
+ expect((await api("POST", `/api/bots/${bot.id}/messages`, { token: owner, body: { text, threadId: bot.threadId } })).status).toBe(202);
+ }, bot.id, bot.threadId);
+ const stop = async () => expect((await api("POST", `/api/bots/${bot.id}/interrupt`, { token: owner, body: { threadId: bot.threadId } })).status).toBe(200);
+ type Row = { id: string; routineId: string; status: string; threadId?: string; triggerSource?: string; error?: string; partial?: boolean; attention?: string };
+ const runs = async () => (await api("GET", "/api/routines", { token: owner })).body.runs as Row[];
+ const seen = new Set<string>();
+ /** A run `start` begins (Run now by default; a schedule, after what `start` does): its tools, and its row once its turn
+ * ends well. It waits for the run itself to start, however long the scheduler or a busy bot holds it, and only then for
+ * that run's own turn. */
+ const runOf = async (routineId: string, start = async () => { expect((await api("POST", `/api/routines/${routineId}/run`, { token: owner })).status).toBe(201); }) => {
+ let started: Row | undefined;
+ const call = await proxyFor(start, bot.id, async () => {
+ await expect.poll(async () => {
+ const mine = (await runs()).filter((run) => run.routineId === routineId && !seen.has(run.id));
+ started = mine.find((run) => run.threadId && ["running", "waiting"].includes(run.status));
+ return started ? "started" : JSON.stringify(mine.map(({ status, attention, error }) => ({ status, attention, error })));
+ }, { timeout: hostTimeout(90_000), interval: 250 }).toBe("started");
+ seen.add(started!.id);
+ return started!.threadId!;
+ });
+ const dump = turnDump, runId = started!.id;
+ return { call, runId, trigger: started!.triggerSource, ended: async () => {
+ finish(dump);
+ let row: Awaited<ReturnType<typeof runs>>[number] | undefined;
+ await expect.poll(async () => (row = (await runs()).find((run) => run.id === runId))?.status, { timeout: hostTimeout(20_000) }).toMatch(/^(completed|failed)$/u);
+ return row!;
+ } };
+ };
+ /** What the run said in the chat it reports to. */
+ const reported = async (runId: string) => {
+ let line: any;
+ await expect.poll(async () => (line = (await chat()).find((message) => message.automation?.runId === runId && !message.automation.copyOf)) !== undefined, { timeout: hostTimeout(15_000) }).toBe(true);
+ return line as { text: string; automation: { failed?: boolean; partial?: boolean } };
+ };
+ const use = (call: Awaited<ReturnType<typeof proxyFor>>) => call("shared_computer", { computer_id: computer.id, folder_id: computer.scopes.folders[0].id, action: "read_file", path: "plan.md" });
+
+ // The person asks in their own chat; the bot makes the routine, then rewrites it there and sets it to run in a moment.
+ let call = await ownerAsks("Every morning, read plan.md from my computer.");
+ const morning = made(await call("create_trigger", { when: "schedule", name: "Morning plan", instructions: "Read plan.md from my computer.", schedule: { type: "interval", every_minutes: 60 } }));
+ expect(morning).not.toBe("");
+ // Its next run starts on its schedule, with nobody pressing Run now, and has the computer. The turns already started are
+ // taken before the run is set, so a fast schedule can't start it first.
+ const scheduled = await runOf(morning, async () => {
+ applied(await call("manage_trigger", { trigger_id: morning, action: "update", changes: { instructions: "Read plan.md from my computer, as I said it may today.", schedule: { type: "once", at: new Date(Date.now() + 8_000).toISOString() } } }));
+ expect(authors().routines[morning]).toMatch(/^[a-f0-9]{64}$/u);
+ await stop();
+ });
+ expect(scheduled.trigger).toBe("schedule");
+ expect(lent(await scheduled.call("list_shared_computers")).computers).toHaveLength(1);
+ expect((await scheduled.ended()).status).toBe("completed");
+ await reported(scheduled.runId);
+
+ // A run of the owner's routine that changes the routine itself keeps it theirs (cloud-personal.e2e.test.ts pins the fingerprint).
+ call = await ownerAsks("Read plan.md from my computer every hour.");
+ const hourly = made(await call("create_trigger", { when: "schedule", name: "Hourly plan", instructions: "Read plan.md from my computer.", schedule: { type: "interval", every_minutes: 60 } }));
+ await stop();
+ const first = authors().routines[hourly];
+ const tuning = await runOf(hourly);
+ applied(await tuning.call("manage_trigger", { trigger_id: hourly, action: "update", changes: { instructions: "Read plan.md and notes.md from my computer." } }));
+ expect(authors().routines[hourly]).toMatch(/^[a-f0-9]{64}$/u);
+ expect(authors().routines[hourly]).not.toBe(first);
+ expect((await tuning.ended()).status).toBe("completed");
+ const tuned = await runOf(hourly);
+ expect(lent(await tuned.call("list_shared_computers")).computers).toHaveLength(1);
+ expect((await tuned.ended()).status).toBe("completed");
+
+ // Deleted, Morning plan's report in the chat is no longer the owner's routine's, so the chat can't be proven theirs alone
+ // (cloud-routine-level.e2e.test.ts pins this): the routine the bot makes there again is not confirmed for the computer.
+ call = await ownerAsks("Replace Morning plan with a new one.");
+ applied(await call("delete_trigger", { trigger_id: morning }));
+ const again = made(await call("create_trigger", { when: "schedule", name: "Morning plan again", instructions: "Read plan.md from my computer.", schedule: { type: "interval", every_minutes: 60 } }));
+ expect(authors().routines[again]).toBeUndefined();
+ await stop();
+ const said = `"Morning plan again" can't use your ${device} because it isn't confirmed as yours: it was last changed or made outside your own chats. Open it and save it to make it yours again.`;
+
+ // A run that only lists the computers ends as it would: its reply reaches the chat, with the app's sentence under it.
+ const listed = await runOf(again);
+ const listing = lent(await listed.call("list_shared_computers"));
+ expect(listing.computers).toEqual([]);
+ expect(listing.say).toBe(said);
+ expect((await listed.ended()).status).toBe("completed");
+ const listedLine = await reported(listed.runId);
+ expect(listedLine.text).toBe(`fixture turn completed\n\n${said}`);
+ expect(listedLine.automation.failed).toBeUndefined();
+
+ // A run refused the computer it tried to use fails, whatever the bot said after: "didn't finish", on every run.
+ for (const attempt of [1, 2]) {
+ const used = await runOf(again);
+ const refusedUse = await use(used.call);
+ expect(refusedUse.isError).toBe(true);
+ expect(refusedUse.content[0].text).toContain(said);
+ const row = await used.ended();
+ expect([row.status, row.error, row.partial], `run ${attempt}`).toEqual(["failed", said, undefined]);
+ expect(await reported(used.runId), `run ${attempt}`).toMatchObject({ text: `This run didn't finish: ${said}`, automation: { failed: true } });
+ }
+
+ // Refused, then saved by the person while the run works: its next call gets the computer, and nothing is said.
+ const saved = await runOf(again);
+ expect((await use(saved.call)).isError).toBe(true);
+ expect((await api("PATCH", `/api/routines/${again}`, { token: owner, body: { prompt: "Read plan.md from my computer." } })).status).toBe(200);
+ expect(JSON.parse((await use(saved.call)).content[0].text).content).toBe("from the computer");
+ expect((await saved.ended()).status).toBe("completed");
+ expect((await reported(saved.runId)).text).toBe("fixture turn completed");
+ connector.close();
+ connector = undefined;
+ rmSync(join(home, "desktop-profile"), { recursive: true, force: true });
+ rmSync(folderPath, { recursive: true, force: true });
+}, hostTimeout(180_000));
diff --git a/server/host/cloud-lending-turns.test.ts b/server/host/cloud-lending-turns.test.ts
index 34eda3ccdc..1aff1aada5 100644
--- a/server/host/cloud-lending-turns.test.ts
+++ b/server/host/cloud-lending-turns.test.ts
@@ -234,7 +234,7 @@ describe("a card lifts a lock only for the owner's own line (server/host/cloud-l
describe("a routine someone else changed (email 1a1bca40)", () => {
const routinePrompt = { id: "m1", role: "user", automation: { routineId: "r1" } };
- function routineRun({ trigger = "schedule" as "schedule" | "manual" | "webhook" | "startup", ownerStarted = false, ownerAuthored = false, flagged = false } = {}) {
+ function routineRun({ trigger = "schedule" as "schedule" | "manual" | "webhook" | "startup", ownerStarted = false, ownerAuthored = false, flagged = false, refused = [] as unknown[][] } = {}) {
const run = { id: "run1", routineId: "r1", threadId: "t1", triggerSource: trigger };
return createCloudLendingTurns({
store: {
@@ -255,6 +255,7 @@ describe("a routine someone else changed (email 1a1bca40)", () => {
routines: () => ({ listRoutines: () => [{ id: "r1", name: "Morning inbox" }] }) as never,
routineAuthors: { authored: () => ownerAuthored },
lentPlatform: () => "darwin",
+ routineRefused: (...args) => { refused.push(args); },
});
}
const changed = "\"Morning inbox\" can't use your Mac because it isn't confirmed as yours: it was last changed or made outside your own chats. Open it and save it to make it yours again.";
@@ -267,6 +268,20 @@ describe("a routine someone else changed (email 1a1bca40)", () => {
expect(routineRun({ trigger: "startup" }).cloudLendingRefusalNotice(turn)).toBe(changed);
expect(routineRun({ trigger: "manual", ownerStarted: true }).cloudLendingRefusalNotice(turn)).toBe(changed);
});
+ it("a refused call records the run and its routine for the run's own ending, and nothing else does", () => {
+ const refused: unknown[][] = [];
+ const host = routineRun({ refused });
+ host.cloudLendingRefusalNotice(turn);
+ expect(refused, "only a call the bot was refused").toEqual([]);
+ host.cloudLendingRefusalForBot(turn);
+ host.cloudLendingRefusalForBot(turn, false);
+ expect(refused, "a use, then a listing").toEqual([["t1", "run1", "Morning inbox", true], ["t1", "run1", "Morning inbox", false]]);
+ const others: unknown[][] = [];
+ for (const options of [{ ownerAuthored: true }, { trigger: "webhook" as const }, { trigger: "manual" as const }, { flagged: true }]) {
+ routineRun({ ...options, refused: others }).cloudLendingRefusalForBot(turn);
+ }
+ expect(others).toEqual([]);
+ });
it("the owner's own routine still runs, and every other refusal keeps its words", () => {
expect(routineRun({ ownerAuthored: true }).cloudLendingRefusalNotice(turn)).toBeNull();
for (const host of [routineRun({ trigger: "webhook" }), routineRun({ trigger: "manual" }), routineRun({ flagged: true })]) {
diff --git a/server/host/cloud-lending-turns.ts b/server/host/cloud-lending-turns.ts
index 8a87399e26..3b8c5e99e8 100644
--- a/server/host/cloud-lending-turns.ts
+++ b/server/host/cloud-lending-turns.ts
@@ -33,6 +33,9 @@ export interface CloudLendingTurnsDeps {
lifts?: () => Pick<ReturnType<typeof createLendingLifts>, "raise" | "declined" | "outsideAllowed"> | null;
/** Work a bot handed into this conversation since `since`: made, or run, after then. Not the conversation's own turns, nor what they hand on. */
handedSince?(threadId: string, since: number): boolean;
+ /** A routine's run was refused the lent computer only because its routine isn't confirmed as the owner's
+ * (host/refused-lending.ts): `used` when it tried to use the computer, not only to list it. */
+ routineRefused?(threadId: string, runId: string, routineName: string, used: boolean): void;
}
export function createCloudLendingTurns(deps: CloudLendingTurnsDeps) {
@@ -106,19 +109,22 @@ export function createCloudLendingTurns(deps: CloudLendingTurnsDeps) {
const { conversation, memoryChanged } = shut;
if (!conversation && !memoryChanged) return null;
if (deps.team) return teamLendingRefusal(deps.team);
- const changed = conversation === "not-owner" && !memoryChanged ? changedRoutine(capability) : undefined;
- if (changed !== undefined) return changedRoutineRefusalText(changed, deviceWord(deps.lentPlatform()));
+ const changed = changedRoutineOnly(capability, shut);
+ if (changed) return changedRoutineRefusalText(changed.name, deviceWord(deps.lentPlatform()));
const thread = store.messagesFor(capability.threadId);
const others = thread.filter((line) => line.role === "user" && !deps.ownerPerson(line.peerAsk ? undefined : line.sender?.id));
return cloudLendingRefusalText(conversation ?? "memory-changed", { room: Boolean(store.groupByThread(capability.threadId)), fromBefore: others.length > 0 && others.every(unstamped),
botOpened: others.length === 0 && cloudBotOpened(capability.threadId), outside: others.length === 0 && thread.some(cloudReportFromOthers), memoryChanged, onCard: liftable(capability, shut) !== null, device: deviceWord(deps.lentPlatform()) });
}
- /** What a refused call answers: the notice, then that the bot should stop. Where the owner can lift it, the card goes up here. */
- function cloudLendingRefusalForBot(capability: Turn): string | null {
+ /** What a refused call answers: the notice, then that the bot should stop. Where the owner can lift it, the card goes up
+ * here. `used`: the call tried to use the computer (or asked for it), not only to list it. */
+ function cloudLendingRefusalForBot(capability: Turn, used = true): string | null {
const notice = cloudLendingRefusalNotice(capability);
if (!notice || deps.team) return notice;
- const lift = liftable(capability, gates(capability));
+ const shut = gates(capability), changed = changedRoutineOnly(capability, shut);
+ if (changed) deps.routineRefused?.(capability.threadId, changed.runId, changed.name, used);
+ const lift = liftable(capability, shut);
if (lift) deps.lifts?.()?.raise({ botId: capability.botId, threadId: capability.threadId, ...lift });
return `${notice} ${lift ? ON_THE_CARD : ONLY_THE_PERSON}`;
}
@@ -134,16 +140,22 @@ export function createCloudLendingTurns(deps: CloudLendingTurnsDeps) {
return deps.memoryChangedBySomeoneElse(capability.botId) ? "memory-changed" : conversationGate(capability, cloudHomeOwnTurnRefusal);
}
- /** The name of the routine this turn runs, when the run is refused only because the routine is no longer the owner's
- * (someone else changed it); a webhook's or another app's run, or one somebody else started by hand, is not this. */
- function changedRoutine(capability: Turn): string | undefined {
+ /** The routine this turn runs, when the run is refused only because the routine is no longer the owner's (someone else
+ * changed it); a webhook's or another app's run, or one somebody else started by hand, is not this. */
+ function changedRoutine(capability: Turn): { runId: string; name: string } | undefined {
const turn = cloudLendingTurn(capability);
const automation = turn.request?.automation;
if (automation === undefined || automation === "webhook" || automation === "api") return undefined;
const run = turn.routineRun();
if (!run || run.ownerAuthored || run.triggerSource === "webhook" || run.triggerSource === "api" || (run.triggerSource === "manual" && !run.ownerStarted)) return undefined;
- const routineId = deps.activeRoutineRun(capability.threadId)?.routineId;
- return deps.routines()?.listRoutines().find((routine) => routine.id === routineId)?.name;
+ const active = deps.activeRoutineRun(capability.threadId);
+ const name = deps.routines()?.listRoutines().find((routine) => routine.id === active?.routineId)?.name;
+ return active && name !== undefined ? { runId: active.id, name } : undefined;
+ }
+
+ /** That routine, when it is the only gate shut. */
+ function changedRoutineOnly(capability: Turn, { conversation, memoryChanged }: ReturnType<typeof gates>) {
+ return conversation === "not-owner" && !memoryChanged ? changedRoutine(capability) : undefined;
}
/** A bot opened this conversation (a hand-off's work thread, one a bot started itself, a Chief's notices). */
diff --git a/server/host/refused-lending.test.ts b/server/host/refused-lending.test.ts
new file mode 100644
index 0000000000..915636808e
--- /dev/null
+++ b/server/host/refused-lending.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from "vitest";
+
+import { changedRoutineRefusalText } from "../cloud-lending.ts";
+import { addServerLinePacks } from "../server-lines.ts";
+import type { RoutineRunStatus } from "../../shared/routines.ts";
+import { createRefusedLending } from "./refused-lending.ts";
+
+type Run = { id: string; startedAt?: number };
+
+function fixture(over: { device?: "PC" | "Mac" | "computer" | null; status?: (id: string) => RoutineRunStatus | undefined; language?: string } = {}) {
+ let current: Run | undefined = { id: "run_1" };
+ const refused = createRefusedLending({
+ runOf: () => current, statusOf: (id) => over.status?.(id) ?? "running",
+ lentDevice: () => (over.device === undefined ? "PC" : over.device), language: () => over.language,
+ });
+ return { refused, now: (run: Run | undefined) => { current = run; } };
+}
+
+const SAID = changedRoutineRefusalText("Morning plan", "PC");
+const FAILS = { text: SAID, partial: false, lendingRefused: true };
+
+describe("a routine's run refused the lent computer (server/host/refused-lending.ts)", () => {
+ it("a run refused a use of the computer fails, once, with the very sentence the bot was given, reading as not finished", () => {
+ const { refused } = fixture();
+ refused.refused("t", "run_1", "Morning plan", true);
+ expect(refused.ending("t", null)).toEqual(FAILS);
+ expect(refused.ending("t", null)).toBeNull();
+ const mac = fixture({ device: "Mac" });
+ mac.refused.refused("t", "run_1", "Morning plan", true);
+ expect(mac.refused.ending("t", null)).toEqual({ ...FAILS, text: changedRoutineRefusalText("Morning plan", "Mac") });
+ });
+
+ it("a run that only listed the computers ends as it would, and its report carries the sentence under its reply, once", () => {
+ const { refused } = fixture();
+ refused.refused("t", "run_1", "Morning plan", false);
+ expect(refused.ending("t", null)).toBeNull();
+ expect(refused.notes.has("run_1")).toBe(true);
+ expect(refused.notes.take("run_1", undefined)).toBe(SAID);
+ expect(refused.notes.has("run_1")).toBe(false);
+ expect(refused.notes.take("run_1", undefined)).toBeNull();
+ });
+
+ it("a use refused after a listing, or before one, is a use", () => {
+ for (const order of [[false, true], [true, false]]) {
+ const { refused } = fixture();
+ for (const used of order) refused.refused("t", "run_1", "Morning plan", used);
+ expect(refused.ending("t", null)).toEqual(FAILS);
+ }
+ });
+
+ it("forgets the refusal once a later call in the same run gets the computer (the person saved the routine meanwhile)", () => {
+ const { refused } = fixture();
+ refused.refused("t", "run_1", "Morning plan", true);
+ refused.allowed("t");
+ expect(refused.ending("t", null)).toBeNull();
+ expect(refused.notes.has("run_1")).toBe(false);
+ });
+
+ it("stays quiet for a run never refused, and when nothing is lent, since then the refusal cost it nothing", () => {
+ expect(fixture().refused.ending("t", null)).toBeNull();
+ const none = fixture({ device: null });
+ none.refused.refused("t", "run_1", "Morning plan", true);
+ expect(none.refused.ending("t", null)).toBeNull();
+ });
+
+ it("leaves a refused hand-off as it was when the computer was never refused, and says both, its own first, when it was", () => {
+ expect(fixture().refused.ending("t", "Nothing was sent.")).toBe("Nothing was sent.");
+ const used = fixture();
+ used.refused.refused("t", "run_1", "Morning plan", true);
+ expect(used.refused.ending("t", "Nothing was sent.")).toEqual({ ...FAILS, text: `${SAID} Nothing was sent.` });
+ const listed = fixture();
+ listed.refused.refused("t", "run_1", "Morning plan", false);
+ expect(listed.refused.ending("t", "Nothing was sent.")).toEqual({ text: `${SAID} Nothing was sent.`, partial: false });
+ expect(listed.refused.notes.has("run_1")).toBe(false);
+ });
+
+ it("keeps the instruction whole within a failed run's 500 characters: a long name gives way, and so does a long hand-off", () => {
+ const { refused } = fixture();
+ refused.refused("t", "run_1", "Plan ".repeat(60), true);
+ const ended = refused.ending("t", "Rooms couldn't hand this on. ".repeat(30)) as { text: string };
+ expect(ended.text.length).toBeLessThanOrEqual(500);
+ expect(ended.text).toContain("Open it and save it to make it yours again.");
+ expect(ended.text).toContain("…\" can't use your PC");
+ });
+
+ it("is never another run's: a refusal for a run that is no longer this conversation's, or a later run here, says nothing", () => {
+ const late = fixture();
+ late.refused.refused("t", "run_0", "Morning plan", true);
+ expect(late.refused.ending("t", null)).toBeNull();
+ const next = fixture();
+ next.refused.refused("t", "run_1", "Morning plan", true);
+ next.now({ id: "run_2" });
+ expect(next.refused.ending("t", null)).toBeNull();
+ });
+
+ it("forgets the refusal of a run that ended without saying it", () => {
+ const status = new Map<string, RoutineRunStatus>([["run_1", "failed"]]);
+ const { refused, now } = fixture({ status: (id) => status.get(id) });
+ refused.refused("t", "run_1", "Morning plan", true);
+ now({ id: "run_2" });
+ refused.refused("t", "run_2", "Evening plan", true);
+ now({ id: "run_1" });
+ expect(refused.ending("t", null)).toBeNull();
+ now({ id: "run_2" });
+ expect(refused.ending("t", null)).toEqual({ ...FAILS, text: changedRoutineRefusalText("Evening plan", "PC") });
+ });
+
+ it("is not a retry's: the same run started again after its refused attempt ends as that attempt did not", () => {
+ const { refused, now } = fixture();
+ now({ id: "run_1", startedAt: 1 });
+ refused.refused("t", "run_1", "Morning plan", true);
+ now({ id: "run_1", startedAt: 2 });
+ expect(refused.ending("t", null)).toBeNull();
+ now({ id: "run_1", startedAt: 1 });
+ expect(refused.ending("t", null), "taken once, by the attempt that ended").toBeNull();
+ });
+
+ it("reads in the language of the chat: the run's for a failure, the chat it reports to for the line under a reply", () => {
+ // A pack of its own: the catalogs themselves are the locale tests' to read (scripts/ci-scope.test.ts).
+ addServerLinePacks({ xx: { "server.runs.lentComputerUnconfirmed": "{name} · {device}" } });
+ const { refused } = fixture({ language: "xx" });
+ refused.refused("t", "run_1", "Plano da manhã", true);
+ expect(refused.ending("t", null)).toEqual({ ...FAILS, text: "Plano da manhã · PC" });
+ const listed = fixture();
+ listed.refused.refused("t", "run_1", "Plano da manhã", false);
+ listed.refused.ending("t", null);
+ expect(listed.refused.notes.take("run_1", "xx")).toBe("Plano da manhã · PC");
+ });
+});
diff --git a/server/host/refused-lending.ts b/server/host/refused-lending.ts
new file mode 100644
index 0000000000..18ddbc3497
--- /dev/null
+++ b/server/host/refused-lending.ts
@@ -0,0 +1,87 @@
+// A routine's run refused the computer the person lends My Cloud, only because the routine isn't confirmed as theirs.
+// The bot hears why and is told to say it, but may say anything after (that nothing was there to use, that files are
+// gone), so the app says it itself, every run it applies to, until the person saves the routine:
+// - a run that tried to use the computer and was refused, and never got it after, fails with the sentence (it reads
+// "didn't finish", it is said on every run, and it never spaces the routine out: only saving it helps);
+// - a run that only listed the computers ends as it would, its reply posted as usual with the sentence under it.
+// A call that gets the computer later in the same run (the person saved it meanwhile) forgets the refusal.
+import { serverLine } from "../server-lines.ts";
+import type { RefusedRunLine } from "../routine-recovery.ts";
+import type { RoutineRunStatus } from "../../shared/routines.ts";
+
+type Device = "PC" | "Mac" | "computer";
+type Refusal = { name: string; device: Device; used: boolean; startedAt?: number };
+
+/** What fits in a failed run's error (routines.ts keeps 500 characters): a long name gives way, never the instruction. */
+const ERROR_ROOM = 500;
+const NAME_ROOM = 80;
+
+export interface RefusedLendingDeps {
+ /** The run this conversation is, when it is one; `startedAt` tells a retry of it from the attempt that was refused. */
+ runOf(threadId: string): { id: string; startedAt?: number } | undefined;
+ /** Where the run with this id stands; nothing once its row left the history. */
+ statusOf(runId: string): RoutineRunStatus | undefined;
+ /** The kind of computer the person lends now; null when they lend none, and a refusal cost the run nothing. */
+ lentDevice(): Device | null;
+ /** The language of a line in this conversation. */
+ language(threadId: string): string | undefined;
+}
+
+const NOT_FINISHED: ReadonlySet<RoutineRunStatus> = new Set<RoutineRunStatus>(["queued", "running", "waiting"]);
+
+export function createRefusedLending(deps: RefusedLendingDeps) {
+ const refused = new Map<string, Refusal>();
+ /** Runs that completed after only listing: the line their report carries, by run id. */
+ const notes = new Map<string, Omit<Refusal, "used" | "startedAt">>();
+
+ const sentence = (language: string | undefined, { name, device }: Pick<Refusal, "name" | "device">) =>
+ serverLine(language, "server.runs.lentComputerUnconfirmed", { name: name.length > NAME_ROOM ? `${name.slice(0, NAME_ROOM - 1).trimEnd()}…` : name, device });
+
+ return {
+ /** The run `runId`, in this conversation, was refused the lent computer for the routine `name`: `used` when it tried
+ * to use it (a call, or asking for it), not only to list it. */
+ refused(threadId: string, runId: string, name: string, used: boolean): void {
+ const device = deps.lentDevice(), run = deps.runOf(threadId);
+ if (!device || run?.id !== runId) return;
+ // A run that has ended never takes its own, so it keeps none.
+ for (const id of refused.keys()) {
+ const status = id === runId ? undefined : deps.statusOf(id);
+ if (id !== runId && (status === undefined || !NOT_FINISHED.has(status))) refused.delete(id);
+ }
+ const before = refused.get(runId);
+ refused.set(runId, { name, device, used: used || (before !== undefined && before.startedAt === run.startedAt && before.used), startedAt: run.startedAt });
+ },
+ /** The run in this conversation got the lent computer: what it was refused before no longer holds. */
+ allowed(threadId: string): void {
+ const run = deps.runOf(threadId);
+ if (run) refused.delete(run.id);
+ },
+ /** The run in this conversation is ending well, after `handoff` (a refused hand-off's words, or null): what it must
+ * fail with instead, or null to end as it would; a run that only listed keeps its line for its report. */
+ ending(threadId: string, handoff: string | null): string | RefusedRunLine | null {
+ const run = deps.runOf(threadId), seen = run && refused.get(run.id);
+ if (run) refused.delete(run.id);
+ // A retry starts afresh: the attempt that was refused is not the one ending now.
+ if (!run || !seen || seen.startedAt !== run.startedAt) return handoff;
+ const said = sentence(deps.language(threadId), seen);
+ if (!seen.used && !handoff) {
+ if (notes.size >= 500) notes.delete(notes.keys().next().value!);
+ notes.set(run.id, { name: seen.name, device: seen.device });
+ return null;
+ }
+ const text = handoff ? `${said} ${handoff}`.slice(0, ERROR_ROOM) : said;
+ return seen.used ? { text, partial: false, lendingRefused: true } : { text, partial: false };
+ },
+ /** The line a completed run's report carries under its reply, once (automation-reports.ts `notes`). */
+ notes: {
+ has: (runId: string): boolean => notes.has(runId),
+ take(runId: string, language: string | undefined): string | null {
+ const note = notes.get(runId);
+ notes.delete(runId);
+ return note ? sentence(language, note) : null;
+ },
+ },
+ };
+}
+
+export type RefusedLending = ReturnType<typeof createRefusedLending>;
diff --git a/server/index.ts b/server/index.ts
index e99b0936f8..dfbf9594fe 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -458,7 +458,7 @@ import { createScreenFrameSource, rememberTurnFrame, type ScreenCapture } from "
import { screenFrameHash, screenSurfaceForTool, screenTouchingTool, settledFrameIsNews } from "./screen-frame-gate.ts";
import { asSchedule, RoutineRequestService } from "./routine-requests.ts"; import { ownerSpokeOnly } from "./cloud-routine-level.ts"; import { routineRunCard, routineRunFallbackText } from "./routine-run-card.ts";
import { activeRoutinesContext } from "./active-routines-context.ts";
-import { createRefusedHandoffs } from "./host/refused-handoffs.ts"; import { automationContextText, createAutomationReports, newestAutomationLines, routineRunNeedsReview } from "./automation-reports.ts"; import { createAutomationDestinations } from "./automation-destinations.ts"; import { createTeamRoutines } from "./host/team-routines.ts"; import { botOwner } from "../shared/bot-owner.ts"; import { forgetMember } from "./bot-owners.ts"; import { createProactive } from "./host/proactive.ts"; import { createFirstHourHooks, startFirstHour, welcomeDonePatch } from "./host/first-hour-host.ts"; import { greetingMessage } from "./host/first-hour.ts"; import { READ_AND_DRAFT_PARTS, READ_AND_DRAFT_REFUSAL, READ_AND_DRAFT_TOOLS, recordsAnswer } from "./read-and-draft.ts"; import { createPresenceRoutes } from "./routes/presence.ts"; import { needsYouNow } from "./today.ts"; import { createTeamPresenceHost } from "./host/team-presence-host.ts";
+import { createRefusedHandoffs } from "./host/refused-handoffs.ts"; import { createRefusedLending } from "./host/refused-lending.ts"; import { automationContextText, createAutomationReports, newestAutomationLines, routineRunNeedsReview } from "./automation-reports.ts"; import { createAutomationDestinations } from "./automation-destinations.ts"; import { createTeamRoutines } from "./host/team-routines.ts"; import { botOwner } from "../shared/bot-owner.ts"; import { forgetMember } from "./bot-owners.ts"; import { createProactive } from "./host/proactive.ts"; import { createFirstHourHooks, startFirstHour, welcomeDonePatch } from "./host/first-hour-host.ts"; import { greetingMessage } from "./host/first-hour.ts"; import { READ_AND_DRAFT_PARTS, READ_AND_DRAFT_REFUSAL, READ_AND_DRAFT_TOOLS, recordsAnswer } from "./read-and-draft.ts"; import { createPresenceRoutes } from "./routes/presence.ts"; import { needsYouNow } from "./today.ts"; import { createTeamPresenceHost } from "./host/team-presence-host.ts";
import { engineLabel, LimitResetClock, nearLimitNote } from "./limit-resets.ts"; import { loadPlanUsage, planAccountsFromInstances } from "./plan-usage.ts"; import { LimitFailovers, limitBackupAllowed } from "./limit-failover.ts"; import { createLimitResetRoutes } from "./routes/limit-resets.ts";
import { parseTriggerRequest, triggerTarget } from "./trigger-tools.ts"; import { WebhookRequestError, WebhookRequestService } from "./webhook-requests.ts"; import { createAppTriggerHost } from "./app-trigger-host.ts";
import { appliesNow, directApply, UNDO_STALE, type DirectApply } from "./direct-apply.ts";
@@ -884,7 +884,7 @@ 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) return cloudLendingRefusal(capability) === null ? CLOUD_HOME_LENDER : 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());
}
@@ -2761,8 +2761,8 @@ const replyVoiceNotes = createReplyVoiceNotes({ store, config: () => cfg, voiceR
const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusalForBot, cloudLendingRefusal, cloudThreadStarters, cloudBotOpened, cloudLendingView, cloudReportFromOthers, handsOnLending, handedInUnproven, cloudOwnTurnRefusal, roomTurnStarted, roomTurnEnded, roomRun } = createCloudLendingTurns({
store, cloudHome: CLOUD_HOME !== null, team: CLOUD_TEAM?.name ?? null, directRequest: (threadId) => directRequestOwners.get(threadId), threadStarter: (threadId) => threadStarters.get(threadId),
ownerPerson: cloudProvenOwnerPerson, cardAnswerer: cloudCardAnswerer, activeRoutineRun: activeRoutineRunForThread, ownerStartedRun: (runId) => ownerStartedRoutineRuns.has(runId),
- routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform,
- memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, handedSince: (threadId, since) => handedInSince(coordinator.inThread(threadId, { since }), threadId, since) });
+ routineRunIsOwners: cloudRoutineRunIsOwners, routines: () => routines, routineAuthors: cloudRoutineAuthors, lentPlatform: () => lentNow()?.platform,
+ memoryChangedBySomeoneElse: (botId) => lendingMemory?.reconcile(botId, foreignTurnRunning(botId), { cached: true }).changedBySomeoneElse === true, lifts: () => lendingLifts, routineRefused: (threadId, runId, name, used) => refusedLending.refused(threadId, runId, name, used), handedSince: (threadId, since) => handedInSince(coordinator.inThread(threadId, { since }), threadId, since) });
const teamAway = createTeamAwayHost({ cloudHome: CLOUD_HOME, dataDir: DATA_DIR, here: (person) => [...sseClients].some((client) => client.ask.person === person), people: () => teamOwners.people?.everyone() ?? [], language: personLanguages.forLine, audienceOf: teamHost.audienceOf, store, unseen: (person) => teamMessages.inbox.unseen(person), readUpTo: (key, person) => personRooms.reads?.readUpTo(key, person), session: (auth) => (auth.kind === "session" ? auth.session : null) }); const actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) }); const lendingLifts = lendingMemory ? createLendingLifts({ store, stopped: (threadId) => directRequestOwners.get(threadId)?.stopped === true, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: (botId, text, opts) => startTurn(botId, text, { ...opts, continuesRun: true }), notify, language: (threadId) => threadLanguage(threadId), device: () => deviceWord(sharedComputers.known(CLOUD_HOME_LENDER)[0]?.platform), decide: (row) => appendDecision(DATA_DIR, row), words: changedWords, ownersAnswer: (card) => cloudProvenOwnerPerson(cloudCardAnswerer(card)), memory: { info: (botId) => lendingMemory.reviewInfo(botId), accept: (botId, token) => lendingMemory.review(botId, foreignTurnRunning(botId), token).ok } }) : null;
const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: (botId, text, opts) => startTurn(botId, text, { ...opts, continuesRun: true }),
refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalForBot(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;
@@ -2773,7 +2773,7 @@ const { stopThreadForPerson, stopOnTypedCommand, restartForPerson } = createPers
const imageTools = createImageToolRoutes({ config: () => cfg, dataDir: DATA_DIR, liveTurn: (threadId) => liveTurnByThread.get(threadId), key: turnAttachmentKey, images: (key) => (turnAttachmentsByTurn.get(key) ?? []).filter((item) => item.kind === "image").length, park: (key, image) => { const saved = saveImage(image.bytes, image.mime); turnAttachmentsByTurn.set(key, [...turnAttachmentsByTurn.get(key) ?? [], { kind: "image", path: saved.path, mime: saved.mime }]); } });
const noAiNotice = createNoAiNotice({ team: CLOUD_TEAM, dataDir: DATA_DIR, people: () => teamOwners.people?.list() ?? [], personName: teamHost.personName, inbox: () => teamMessages.inbox, language: personLanguages.forLine, threadLanguage: conversationLanguage });
const botNameClash = createBotNameClash({ store, people: () => teamMessages.people(), profileName: () => cfg.profile?.name });
-const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
+const refusedHandoffs = createRefusedHandoffs({ bots: () => store.bots, hides: (from, target) => personalReach.hides(from, target), runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, writerOf: (routineId) => cloudRoutineAuthors?.writer(routineId), askedPerson: teamOwners.routing.askedPerson, theirOwn: (threadId, person) => audienceMember(teamHost.audienceOf(threadId)) === person, inbox: () => teamMessages.inbox, language: conversationLanguage }); const refusedLending = createRefusedLending({ runOf: (threadId) => (routines?.isActiveThread(threadId) ? routines.runForThread(threadId) ?? undefined : undefined), statusOf: (runId) => routines?.listRuns().find((run) => run.id === runId)?.status, lentDevice: () => { const lent = lentNow(); return lent ? deviceWord(lent.platform) : null; }, language: conversationLanguage }); const takeRefusedRun = (threadId: string) => refusedLending.ending(threadId, refusedHandoffs.take(threadId)); /** The computer the person lends My Cloud now, newest first: one source for the word every refusal names it by. */ function lentNow() { return sharedComputers.known(CLOUD_HOME_LENDER).find((one) => one.lent); } const botProcessOwners = footprintOwners({ botOf: (threadId) => store.botByThread(threadId)?.id ?? null, browsers: browserOwners }); const perf = createPerfHost({ dataDir: DATA_DIR, bus, store, limits: () => limitClock.report(), engines: () => engineMemory.enginePids(), owners: botProcessOwners, pruneOwners: (rows) => engineOwners.prune(rows), cap: botMemoryCapReport, wholeMachine: Boolean(CLOUD_HOME), ...(DESKTOP_MANAGED ? { launches: { launchId: process.env.OMB_DESKTOP_LAUNCH_ID ?? null, server: launchServerPart, counts: () => ({ bots: store.bots.length, threads: store.bots.reduce((sum, bot) => sum + (bot.tasks?.length ?? 0), 0) }) } } : {}) }); startBotMemoryCapHost({ owners: botProcessOwners, botName: (botId) => store.bot(botId)?.name, closeBrowsers: closeCapBrowsers }); const settingNudges = createSettingNudges({ dataDir: DATA_DIR, store }); const devsReports = createDevsReports({ dataDir: DATA_DIR, store, installId: ENVIRONMENT_ID, performance: perf.lines, appVersion: serverVersion(), runsOn: CLOUD_TEAM ? "Team Cloud" : CLOUD_HOME ? "My Cloud" : DESKTOP_MANAGED ? "desktop app" : HOSTED_WORKSPACE ? "hosted server" : "self-hosted server", recentLog: captureRecentLog(), send: devsReportSender(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin)), askStatus: devsStatusAsker(bugReportEndpoint(process.env, CLOUD_HOME?.adminOrigin), CLOUD_HOME), statusEveryMs: Number(process.env.OMB_DEVS_STATUS_MS) || undefined, tell: (threadId, text, person) => { const group = store.groupByThread(threadId), bot = group ? store.bot(group.memberIds[0] ?? "") : store.botByThread(threadId); if (bot) notify({ ...buildNoticeNotification(bot, threadId, text), ...(group ? { groupId: group.id } : {}), ...(CLOUD_TEAM && person ? { forPerson: person } : {}) }); }, working: (threadId) => { const group = store.groupByThread(threadId), bot = group ? null : store.botByThread(threadId); return group ? Boolean(group.busyBotId) || groupThreadIsWorking(group.id, threadId) : Boolean(bot && threadBusy(bot.id, threadId)); }, automated: (threadId) => Boolean(routines?.isActiveThread(threadId)), engine: (instanceId) => (registry.get(instanceId) ? { name: engineName(instanceId), snapshot: registry.lastSnapshot(instanceId) } : null), appsReady: () => composio.configured(cfg), sessions: () => sessions.list(), ownerKey: CLOUD_OWNER_KEY, team: Boolean(CLOUD_TEAM), profileEmail: () => cfg.profile?.email, language: appLanguage, lineLanguage: personLanguages.forLine });
const creditMoves = cloudCredit && createCreditMoves({ credit: cloudCredit, store, context: selectionContext, threadBusy, saveDefault: saveNewBotModel,
defaults: () => [cfg.defaultModelSelection, cfg.newBotDefaults?.profile.modelSelection], engineName: id => registry.get(id)?.displayName ?? id,
log: line => console.warn(line) });
@@ -5544,7 +5544,7 @@ function isUnattended(botId?: string | null, threadId?: string): boolean {
const reviewAnswerThreads = new Set<string>(); const firstHourHooks = createFirstHourHooks({ dataDir: DATA_DIR, personal: Boolean(CLOUD_PERSONAL) });
let routines: RoutineManager | null = null;
-const automationReports = createAutomationReports({ store, routines: () => routines, busy: threadBusy, wrote: markTaskContextExternallyUpdated, brief: (run, turnId) => proactive.runSettled(run, turnId), threadLanguage,
+const automationReports = createAutomationReports({ store, routines: () => routines, busy: threadBusy, wrote: markTaskContextExternallyUpdated, brief: (run, turnId) => proactive.runSettled(run, turnId), threadLanguage, notes: refusedLending.notes,
notify: (kind, bot, threadId, detail) => notify(buildNotification(kind, bot, threadId, detail, { avatarUrl: bot.avatarUrl }), { routine: true }) });
const proactive = createProactive({ store, cfg, composio, registry, dataDir: DATA_DIR, ideas: (botId) => memoryUpkeep.ideas(botId), ...firstHourHooks.proactive, team: Boolean(HOSTED_WORKSPACE || CLOUD_TEAM), frozen: moveFreeze.frozen, routines: () => routines, mainThread: botMainThread, threadBusy, notify, helpers: { decider, extractor }, cloud: Boolean(CLOUD_HOME || HOSTED_WORKSPACE || CLOUD_TEAM),
engineName: (instanceId) => engineName(instanceId), hostTimeZone: () => (CLOUD_HOME ? undefined : hostTimeZone()), decide: (row) => appendDecision(DATA_DIR, row), stale: shouldIgnoreProviderEvent, release: (threadId) => watchdog.setWaitingOnHuman(threadId, false),
@@ -8688,7 +8688,7 @@ routines = new RoutineManager({
launchId: DESKTOP_MANAGED && /^[\w-]{1,100}$/.test(process.env.OMB_DESKTOP_LAUNCH_ID ?? "")
? process.env.OMB_DESKTOP_LAUNCH_ID : undefined,
skipStartupRuns: (startedFromSleep = Boolean(CLOUD_HOME) && wokeFromSleep(DATA_DIR)), prepareRun: (run, signal) => runComputers.prepare(run, signal), preparing: RUN_COMPUTER_LINES.waking, // a Cloud home waking from a sleep it was stopped for
- hasPendingDelegations: runtimeWorkPending, refusedHandoff: refusedHandoffs.take, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,
+ hasPendingDelegations: runtimeWorkPending, refusedHandoff: takeRefusedRun, handedOffWorkLive: (threadId) => coordinator.outstandingFor(threadId).length > 0,
routineTurn: (threadId) => directRequestOwners.get(threadId)?.automation !== undefined, personTurn: (threadId) => directRequestOwners.get(threadId)?.origin?.kind === "user", home: { machine: CLOUD_HOME?.machineId, cloud: CLOUD_HOME !== null }, turnLive: (run) => runTurnLive(run, (threadId) => ({ busy: threadBusy(run.botId, threadId), settling: settlingTurns.has(threadId), queued: queuedThreadPosition(run.botId, threadId) !== null, pending: runtimeWorkPending(threadId), parked: store.taskByThread(run.botId, threadId)?.activity === "parked.computer" })),
botState: unattendedDispatchState, pausedText: (botId) => botHolds.text(botId, threadLanguage(store.bot(botId)?.threadId ?? "")) ?? starterCaps.pausedText(botId, threadLanguage(store.bot(botId)?.threadId ?? "")), held: (botId) => botHolds.held(botId), capSkip: (botId, routineId) => usageCapGate.routineSkip(botId, routineId), capText: (botId, trigger) => usageCapGate.runText(botId, trigger, threadLanguage(store.bot(botId)?.threadId ?? "")),
goalState: (groupId, coordinatorBotId) => {
@@ -8771,7 +8771,7 @@ routines = new RoutineManager({
onRunFailed: (run, alert) => {
const bot = store.bot(run.botId);
if (!bot || alert === null || run.deliver === "brief") return;
- const said = alert?.detail ?? run.error, detail = said ? `${run.routineName}: ${said}` : run.routineName;
+ const said = alert?.detail ?? run.error, detail = said ? (run.lendingRefused ? said : `${run.routineName}: ${said}`) : run.routineName; // a refused lent computer's sentence names the routine itself
automationReports.runFailed(run, said ?? "");
const notificationBot = routineSourceOwner(run)?.bot ?? bot;
notify(buildNotification("routine-failed", notificationBot, routineSourceThread(run) ?? run.threadId ?? bot.threadId, detail));
@@ -13038,7 +13038,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
const principal = sharedComputerPrincipal(internalCapability); await sharedComputers.settledAfterWake(principal, () => internalCapabilityIsActive(internalCapability));
// `say` too: the bot says why instead of asking the person to open OpenMausBot, which can't help while the computer is lent already.
const why = CLOUD_HOME && !principal && (CLOUD_TEAM || sharedComputers.status(CLOUD_HOME_LENDER).length > 0) ? cloudLendingRefusalNotice(internalCapability) : null;
- return json(res, 200, { computers: sharedComputers.list(principal), ...sharedComputers.away(principal), ...sharedComputers.screenNotLent(principal), ...(why ? { unavailable: cloudLendingRefusalForBot(internalCapability), say: why } : {}), ...(!CLOUD_HOME && turnPlaces.get(internalCapability.threadId)?.place !== "local" ? { thisComputer: `This computer itself is never in this list and needs no sharing. ${thisComputerSwitchFor(internalCapability, internalSender)}` } : {}) });
+ return json(res, 200, { computers: sharedComputers.list(principal), ...sharedComputers.away(principal), ...sharedComputers.screenNotLent(principal), ...(why ? { unavailable: cloudLendingRefusalForBot(internalCapability, false), say: why } : {}), ...(!CLOUD_HOME && turnPlaces.get(internalCapability.threadId)?.place !== "local" ? { thisComputer: `This computer itself is never in this list and needs no sharing. ${thisComputerSwitchFor(internalCapability, internalSender)}` } : {}) });
}
if (method === "POST" && path === "/api/internal/shared-computers" && botLending()) {
const parsed = sharedComputerOperation.safeParse(await readInternalBody());
diff --git a/server/routine-failure-spacing.ts b/server/routine-failure-spacing.ts
index 62557375fb..c644f26632 100644
--- a/server/routine-failure-spacing.ts
+++ b/server/routine-failure-spacing.ts
@@ -1,15 +1,15 @@
// A routine whose runs keep failing is never turned off for it. Each failed run spent the bot's AI, so after a few in a
// row its scheduled runs are spaced out as for a cloud computer that does not start, and every occurrence held back is
// counted on one `missed` row. The first run that completes, turning the routine on again, or any change to it ends the
-// spacing, and so does a run only the owner's AI account stopped (signed out, out of credit, a usage limit). A run that
-// never started work counts for nothing here.
+// spacing, and so does a run only the owner's AI account stopped (signed out, out of credit, a usage limit) or that the
+// lent computer refused because its routine isn't confirmed as theirs. A run that never started work counts for nothing here.
import { envWhole } from "./env-limits.ts";
import { afterSpacing, noStartSpacing } from "./routine-no-start.ts";
import { outcomesNewestFirst } from "./routine-outcomes.ts";
import type { RoutineAlert } from "./routine-recovery.ts";
import type { SkipWhy } from "./routine-skips.ts";
-type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; startedAt?: number | null; finishedAt?: number | null; ownerCause?: string };
+type Outcome = { id: string; routineId: string; status: string; error?: string | null; createdAt: number; startedAt?: number | null; finishedAt?: number | null; ownerCause?: string; lendingRefused?: true };
type Spaced = { id: string; updatedAt: number };
export interface FailureSpacingLimits {
@@ -33,11 +33,11 @@ export function failureSpacingLimits(env: NodeJS.ProcessEnv = process.env): Fail
}
/** The routine's newest failed runs that started work, since it last completed a run, was turned on or was changed, or
- * a run failed only on the owner's AI account (signed out, out of credit, a usage limit): that ends a streak and any
- * spacing it began, since the cause changed. */
+ * a run failed only on the owner's AI account (signed out, out of credit, a usage limit) or on a routine not confirmed
+ * for the lent computer: that ends a streak and any spacing it began, since the cause changed. */
export function failedRuns<T extends Outcome>(routine: Spaced, runs: readonly T[]): T[] {
const outcomes = outcomesNewestFirst(runs, routine.id);
- const end = outcomes.findIndex((run) => run.status !== "failed" || run.createdAt < routine.updatedAt || run.ownerCause !== undefined);
+ const end = outcomes.findIndex((run) => run.status !== "failed" || run.createdAt < routine.updatedAt || run.ownerCause !== undefined || run.lendingRefused === true);
return (end < 0 ? outcomes : outcomes.slice(0, end)).filter((run) => run.startedAt != null);
}
diff --git a/server/routine-recovery.ts b/server/routine-recovery.ts
index 6165d8e14e..780bb2a87c 100644
--- a/server/routine-recovery.ts
+++ b/server/routine-recovery.ts
@@ -50,6 +50,10 @@ export type RoutineFailureClass =
| { kind: "owner"; cause: RoutineOwnerCause; resetsAt?: number }
| { kind: "final" };
+/** Why a run that ended well fails instead, when more than its words: `partial: false` reads "didn't finish" whatever the
+ * bot said; `lendingRefused` marks a run only the owner can fix (server/host/refused-lending.ts). */
+export interface RefusedRunLine { text: string; partial?: false; lendingRefused?: true }
+
/** A failure notification's own words; null stays quiet because the owner was already told. */
export interface RoutineAlert { detail: string }
diff --git a/server/routine-reliability.test.ts b/server/routine-reliability.test.ts
index 537ab879b8..5ebbdc3412 100644
--- a/server/routine-reliability.test.ts
+++ b/server/routine-reliability.test.ts
@@ -137,6 +137,27 @@ describe("a routine whose runs fail", () => {
h.done("thread-3");
expect(h.manager.health(100)).toEqual([{ routineId: routine.id, status: "completed", at: START + 3 * HOUR, consecutiveFailures: 0 }]);
});
+
+ it("refused the lent computer it tried to use, a run fails reading as not finished, says so every time, and is never spaced out for it", async () => {
+ const SAID = "\"Fix new bugs\" can't use your PC because it isn't confirmed as yours: it was last changed or made outside your own chats. Open it and save it to make it yours again.";
+ const h = harness();
+ const refusals = new Set<string>();
+ h.options.refusedHandoff = (threadId) => (refusals.has(threadId) ? { text: SAID, partial: false, lendingRefused: true } : null);
+ h.restart();
+ h.manager.create(every(24 * 60));
+ for (const day of [1, 2, 3, 4]) {
+ await h.tickAt(START + day * 24 * HOUR);
+ refusals.add(`thread-${day}`);
+ h.event(`thread-${day}`, "item.completed", { itemType: "assistant_text", text: "No execution environment was mounted." });
+ h.done(`thread-${day}`);
+ expect(h.routine(), "its schedule is never held back for it").toMatchObject({ enabled: true, nextRunAt: START + (day + 1) * 24 * HOUR });
+ }
+ expect(h.runs().map((run) => [run.status, run.error, run.partial, run.lendingRefused])).toEqual(Array(4).fill(["failed", SAID, undefined, true]));
+ expect(h.failed.map((failure) => failure.alert), "said on every run, never silenced as a repeat").toEqual([undefined, undefined, undefined, undefined]);
+ await h.tickAt(START + 5 * 24 * HOUR);
+ expect(h.started, "its fifth occurrence runs on time").toHaveLength(5);
+ expect(h.runs().some((run) => run.status === "missed")).toBe(false);
+ });
});
describe("routines an earlier version turned off after three cloud-computer start failures", () => {
diff --git a/server/routines.ts b/server/routines.ts
index 0db71b43be..f1161f5207 100644
--- a/server/routines.ts
+++ b/server/routines.ts
@@ -24,7 +24,7 @@ import {
routineFailure, routineHostWarning, supersededBy,
} from "./routine-execution.ts";
import {
- dispatchRefusal, engineFacts, nextScheduledRun, recoverRun, requeueOnce, startPrompt, weekRuns, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerMark, type RoutineOwnerNotice,
+ dispatchRefusal, engineFacts, nextScheduledRun, recoverRun, requeueOnce, startPrompt, weekRuns, type RefusedRunLine, type RoutineAlert, type RoutineFailureFacts, type RoutineOwnerMark, type RoutineOwnerNotice,
} from "./routine-recovery.ts";
import { askOf, settleAsk, waitingFor, type RoutineRunAsk } from "./routine-waits.ts";
import { failsLikeLastOutcome, outcomesNewestFirst } from "./routine-outcomes.ts"; import { createRunGate, type RunPreparation } from "./routine-run-gate.ts";
@@ -143,7 +143,7 @@ export interface RoutineRun extends RoutineLineCodes, RoutineOwnerMark, WakeRetr
finishedAt?: number;
output?: string;
attention?: string;
- error?: string; partial?: boolean;
+ error?: string; partial?: boolean; /** It could not use the computer the person lends because its routine isn't confirmed as theirs: said on every run, never spacing it out. */ lendingRefused?: true;
cost?: number | null;
denials?: string[];
report?: RoutineRunReport;
@@ -278,7 +278,7 @@ export interface RoutineManagerOptions {
onRunDeferred?: (run: RoutineRun, alert?: RoutineAlert) => void;
/** A run a restart cut off, before it starts again or fails: its old turn's work must not resume as well. */
onRunCut?: (run: RoutineRun) => void;
- hasPendingDelegations?: (threadId: string) => boolean; /** Why a run that ended well in this thread must say a hand-off was refused, once; null when none was. */ refusedHandoff?: (threadId: string) => string | null;
+ hasPendingDelegations?: (threadId: string) => boolean; /** Why a run that ended well in this thread must fail instead (a hand-off refused, the lent computer refused), once; null when nothing was. */ refusedHandoff?: (threadId: string) => string | RefusedRunLine | null;
/** The turn in this thread is a routine's own, not one a person started there while its run waits on teammates. */
routineTurn?: (threadId: string) => boolean; /** The thread's latest turn is one a person started there by typing (false when not known, e.g. after a restart). */ personTurn?: (threadId: string) => boolean;
/** When an engine's usage limit resets (epoch ms), or null while that is not known. */
@@ -1294,7 +1294,7 @@ export class RoutineManager {
}
this.failureFacts.delete(run.id);
const waitsOnTeammates = this.options.hasPendingDelegations?.(event.threadId) === true, handoffRefused = waitsOnTeammates ? null : this.options.refusedHandoff?.(event.threadId);
- if (handoffRefused) { this.failRun(Object.assign(run, { partial: Boolean(run.output) || undefined }), handoffRefused); queueMicrotask(() => this.tickInBackground()); return cloneRun(run); }
+ if (handoffRefused) { const said = typeof handoffRefused === "string" ? { text: handoffRefused } : handoffRefused; this.failRun(Object.assign(run, { partial: (said.partial !== false && Boolean(run.output)) || undefined }, said.lendingRefused ? { lendingRefused: true as const } : {}), said.text); queueMicrotask(() => this.tickInBackground()); return cloneRun(run); }
if (waitsOnTeammates) this.wait(run, ROUTINE_HANDOFF_WAIT);
else { Object.assign(run, { status: "completed", attention: undefined, finishedAt: this.now() } satisfies Partial<RoutineRun>); this.ownerNotices = this.ownerNotices.filter((notice) => notice.botId !== run.botId); }
run.error = undefined;
@@ -1383,7 +1383,7 @@ export class RoutineManager {
Object.assign(run, { status, attention: undefined, error: redactSecretsInText(message).slice(0, 500), finishedAt: this.now() } satisfies Partial<RoutineRun>);
const routine = this.routines.find((candidate) => candidate.id === run.routineId), spaced = status === "failed" ? noStartAlert(routine, this.runs, run) ?? failureSpacingAlert(routine, this.runs, run) : undefined;
this.saveLater(); this.emitRun(run);
- const repeat = failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed");
+ const repeat = !run.lendingRefused && (failsLikeLastOutcome(this.runs, run) || (run.checkKey !== undefined && outcomesNewestFirst(this.runs, run.routineId, run.id)[0]?.status === "failed"));
this.options.onRunFailed?.(cloneRun(run), spaced ?? (alert === undefined && repeat ? null : alert));
}
diff --git a/src/locales/de.json b/src/locales/de.json
index 82a55132b1..5d4d7af5fb 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -67,6 +67,7 @@
"server.runs.partlyDoneWhy": "Diese Ausführung wurde teilweise erledigt: {detail}",
"server.runs.handoffApart": "{bot} konnte das nicht an {target} übergeben, weil sie mit unterschiedlichen Personen geteilt sind. Es wurde nichts gesendet.",
"server.runs.handoffRefusedTitle": "Die Routine von {bot} konnte ihre Arbeit nicht übergeben",
+ "server.runs.lentComputerUnconfirmed": "„{name}“ kann deinen {device} nicht benutzen, weil die Routine nicht als deine bestätigt ist: Sie wurde zuletzt außerhalb deiner eigenen Chats geändert oder erstellt. Öffne sie und speichere sie, damit sie wieder deine ist.",
"server.runs.recovered": "Wieder in Ordnung: {name} wurde um {time} erfolgreich beendet",
"server.runs.card.line": "Routine „{name}“ {state}",
"server.runs.state.needsInput": "braucht deine Eingabe",
diff --git a/src/locales/en.json b/src/locales/en.json
index b4181005db..016fc4938b 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -209,6 +209,7 @@
"server.runs.partlyDoneWhy": "This run was partly done: {detail}",
"server.runs.handoffApart": "{bot} couldn't hand this to {target}, because they're shared with different people. Nothing was sent.",
"server.runs.handoffRefusedTitle": "{bot}'s routine couldn't hand off its work",
+ "server.runs.lentComputerUnconfirmed": "\"{name}\" can't use your {device} because it isn't confirmed as yours: it was last changed or made outside your own chats. Open it and save it to make it yours again.",
"server.runs.recovered": "Recovered: {name} finished OK at {time}",
"server.runs.card.line": "Routine “{name}” {state}",
"server.runs.state.needsInput": "needs your input",
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index 3c67c63c77..a4ded5b00c 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -190,6 +190,7 @@
"server.runs.partlyDoneWhy": "Esta execução ficou parcialmente concluída: {detail}",
"server.runs.handoffApart": "{bot} não conseguiu repassar este trabalho para {target}, porque esses bots são compartilhados com pessoas diferentes. Nada foi enviado.",
"server.runs.handoffRefusedTitle": "A rotina de {bot} não conseguiu repassar o trabalho",
+ "server.runs.lentComputerUnconfirmed": "“{name}” não pode usar seu {device} porque não está confirmada como sua: ela foi alterada ou criada pela última vez fora das suas próprias conversas. Abra a rotina e salve para que ela volte a ser sua.",
"server.runs.recovered": "Voltou a funcionar: {name} terminou com sucesso às {time}",
"server.runs.card.line": "Rotina “{name}” {state}",
"server.runs.state.needsInput": "precisa da sua resposta",
diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.json
index 6a12df3ad1..90e4afc789 100644
--- a/src/locales/zh-tw.json
+++ b/src/locales/zh-tw.json
@@ -189,6 +189,7 @@
"server.runs.partlyDoneWhy": "這次執行只完成了一部分:{detail}",
"server.runs.handoffApart": "{bot} 無法將這項工作交給 {target},因為它們共享的對象不同。沒有傳送任何內容。",
"server.runs.handoffRefusedTitle": "{bot} 的例行任務無法交接工作",
+ "server.runs.lentComputerUnconfirmed": "「{name}」無法使用你的{device},因為它尚未確認為你的:它最近一次是在你自己的對話之外被修改或建立的。打開它並儲存,就能讓它重新成為你的。",
"server.runs.recovered": "已恢復:{name} 已於 {time} 正常完成",
"server.runs.card.line": "例行工作「{name}」{state}",
"server.runs.state.needsInput": "需要你回覆",
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 25897f0f4e..aad28da700 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -212,6 +212,7 @@
"server.runs.partlyDoneWhy": "这次运行只完成了一部分:{detail}",
"server.runs.handoffApart": "{bot} 无法将这项工作交给 {target},因为它们共享的对象不同。没有发送任何内容。",
"server.runs.handoffRefusedTitle": "{bot} 的例行任务无法交接工作",
+ "server.runs.lentComputerUnconfirmed": "「{name}」不能使用你的{device},因为它尚未被确认为你的:它最近一次是在你自己的对话之外被修改或创建的。打开它并保存,就能让它重新成为你的。",
"server.runs.recovered": "已恢复:{name} 已于 {time} 正常完成",
"server.runs.card.line": "例行任务「{name}」{state}",
"server.runs.state.needsInput": "需要你回复",