Skip to content

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

fix(first-hour): retry a failed first look; greet bots that moved in instead of offering the inbox (#7347)

Milind Soni4e9ecb275a1a
diff --git a/server/cloud-send-lease.test.ts b/server/cloud-send-lease.test.ts
index aa68d336ef..a85e89e375 100644
--- a/server/cloud-send-lease.test.ts
+++ b/server/cloud-send-lease.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { createMoveLeases, LEASE_MS, moveLeaseRoute } from "./cloud-send-lease.ts";
+import { createMoveLeases, LEASE_MS, MOVE_QUIET_MS, moveInRunning, moveLeaseRoute } from "./cloud-send-lease.ts";
function cloud(owner = true) {
let clock = 1_000;
@@ -17,6 +17,29 @@ function cloud(owner = true) {
}
describe("POST /api/cloud-send/lease", () => {
+ it("tells the rest of this server a move is running while its lease is held, and not once it is let go or runs out", async () => {
+ const { ask, advance } = cloud();
+ expect(moveInRunning()).toBe(false);
+ await ask({ v: 1, holder: "computer-mac", label: "Mac" });
+ expect(moveInRunning()).toBe(true);
+ await ask({ v: 1, holder: "computer-mac", release: true });
+ expect(moveInRunning()).toBe(false);
+ await ask({ v: 1, holder: "computer-mac", label: "Mac" });
+ advance(LEASE_MS + 1);
+ expect(moveInRunning()).toBe(false);
+ });
+
+ it("counts the owner's computer asking about a move as one about to run, for a while", () => {
+ const { leases, advance } = cloud();
+ expect(moveInRunning()).toBe(false);
+ leases.touched();
+ expect(moveInRunning()).toBe(true);
+ advance(MOVE_QUIET_MS - 1);
+ expect(moveInRunning()).toBe(true);
+ advance(1);
+ expect(moveInRunning()).toBe(false);
+ });
+
it("lets one computer at a time move in: the other hears who moves now, and goes once that one lets go", async () => {
const { ask } = cloud();
expect(await ask({ v: 1, holder: "computer-mac", label: "Mac" })).toEqual({ status: 200, body: { v: 1, held: true, until: 1_000 + LEASE_MS } });
diff --git a/server/cloud-send-lease.ts b/server/cloud-send-lease.ts
index a8008358cb..52b20f44ef 100644
--- a/server/cloud-send-lease.ts
+++ b/server/cloud-send-lease.ts
@@ -20,10 +20,22 @@ const askSchema = z.object({
release: z.literal(true).optional(),
});
+/** A computer of the owner's asked this Cloud about a move this recently: one is starting or running. */
+export const MOVE_QUIET_MS = 10 * 60_000;
+
+/** This server's lease, the one its move routes made: a new Cloud's first hour holds its inbox offer while a move runs,
+ * or while the owner's computer is still asking about one (it compares and plans before it takes the lease). */
+let serverLeases: MoveLeases | null = null;
+export const moveInRunning = (): boolean => Boolean(serverLeases?.held() || serverLeases?.asked());
+
/** One Cloud's lease. `ask`: held by `holder` from now on (null), or who holds it. */
export function createMoveLeases(now: () => number = Date.now) {
let held: MoveLease | null = null;
- return {
+ let askedAt: number | null = null;
+ const leases = {
+ /** The owner's computer used one of this Cloud's move routes just now. */
+ touched(): void { askedAt = now(); },
+ asked: (): boolean => askedAt !== null && now() - askedAt < MOVE_QUIET_MS,
ask(holder: string, label: string): MoveLease | null {
if (held && held.holder !== holder && held.until > now()) return held;
held = { holder, label: label || (held?.holder === holder ? held.label : ""), until: now() + LEASE_MS };
@@ -32,6 +44,8 @@ export function createMoveLeases(now: () => number = Date.now) {
release(holder: string): void { if (held?.holder === holder) held = null; },
held: (): MoveLease | null => (held && held.until > now() ? held : null),
};
+ serverLeases = leases;
+ return leases;
}
export type MoveLeases = ReturnType<typeof createMoveLeases>;
diff --git a/server/host/first-hour-host.ts b/server/host/first-hour-host.ts
index a62ea359b1..afced6b237 100644
--- a/server/host/first-hour-host.ts
+++ b/server/host/first-hour-host.ts
@@ -4,6 +4,7 @@
import { CLOUD_WELCOME_DONE } from "../../shared/cloud-hints.ts";
import type { Notification } from "../../shared/notification.ts";
import type { RuntimeEvent } from "../../shared/runtime-events.ts";
+import { moveInRunning } from "../cloud-send-lease.ts";
import type { AppConfig } from "../config.ts";
import type { RoutineManager } from "../routines.ts";
import type { BotRecord, Store } from "../store.ts";
@@ -50,6 +51,10 @@ export interface FirstHourHostDeps {
cfg: AppConfig;
dataDir: string;
proactive: Pick<Proactive, "brief">;
+ /** A move into this Cloud is running: its lease is held (cloud-send-lease.ts), unless a test says otherwise. */
+ moving?(): boolean;
+ /** The person pressed Stop on the turn running in this chat. */
+ stopped?(threadId: string): boolean;
/** The brief is on: the proactive bot's briefing routine. */
briefOn(): boolean;
ensureBrief(): void;
@@ -98,6 +103,8 @@ export function startFirstHour(deps: FirstHourHostDeps): FirstHour | null {
return { label: card.label, description: card.blurb ?? "" };
},
},
+ moving: deps.moving ?? moveInRunning,
+ ...(deps.stopped ? { stopped: deps.stopped } : {}),
briefOn: deps.briefOn,
ensureBrief: deps.ensureBrief,
briefCard: () => deps.proactive.brief.latestCard(),
diff --git a/server/host/first-hour-words.test.ts b/server/host/first-hour-words.test.ts
index 6fa9d93433..042d559029 100644
--- a/server/host/first-hour-words.test.ts
+++ b/server/host/first-hour-words.test.ts
@@ -13,10 +13,18 @@ describe("the first hour's words", () => {
for (const language of FIRST_HOUR_LANGUAGES) {
const w = firstHourWords(language);
const english = language !== "en" ? firstHourWords("en") : null;
- for (const line of [w.connect, w.connected, w.briefOn, w.phoneTitle, w.phoneBody, w.phoneButton, w.firstLookReady, w.firstBriefReady]) {
+ const lines = (words: typeof w) => [words.connect, words.lookLater("Gmail", 1), words.arrivedGreeting("Sam", "MausBot", ["Coder"]), words.briefOn, words.phoneTitle, words.phoneBody, words.phoneButton, words.firstLookReady, words.firstBriefReady];
+ for (const line of lines(w)) {
expect(line.trim(), language).not.toBe("");
- if (english) expect([english.connect, english.connected, english.briefOn, english.phoneTitle, english.phoneBody, english.phoneButton, english.firstLookReady, english.firstBriefReady], language).not.toContain(line);
+ if (english) expect(lines(english), language).not.toContain(line);
}
+ expect(w.lookLater("Gmail and Google Calendar", 2), language).toContain("Gmail and Google Calendar");
+ for (const arrived of [["Coder"], ["Coder", "Writer"]]) {
+ const line = w.arrivedGreeting("Sam", "MausBot", arrived);
+ for (const part of ["Sam", "MausBot", ...arrived]) expect(line, language).toContain(part);
+ }
+ expect(w.arrivedGreeting(undefined, "MausBot", ["A", "B", "C", "D"]), language).toContain("4");
+ expect(w.arrivedGreeting(undefined, "MausBot", ["Coder"]), language).not.toContain("undefined");
expect(w.greeting("Sam", "MausBot"), language).toContain("Sam");
expect(w.greeting(undefined, "MausBot"), language).toContain("MausBot");
expect(w.greeting(undefined, "MausBot"), language).not.toContain("undefined");
diff --git a/server/host/first-hour-words.ts b/server/host/first-hour-words.ts
index db562e8baa..dbaf6fec79 100644
--- a/server/host/first-hour-words.ts
+++ b/server/host/first-hour-words.ts
@@ -6,10 +6,12 @@ type Count = (n: number) => string;
export interface FirstHourWords {
greeting(name: string | undefined, bot: string): string;
+ /** The greeting for someone whose own bots (`arrived`, by name) are already here: moved from their computer, or made. */
+ arrivedGreeting(name: string | undefined, bot: string, arrived: readonly string[]): string;
/** The connect offer, with why: the cards for Gmail and Google Calendar follow it. */
connect: string;
- /** An app came in but the first look could not run. */
- connected: string;
+ /** The apps came in but the first look failed twice: which are in, and how to get the look. */
+ lookLater(apps: string, count: number): string;
briefOn: string;
phoneTitle: string;
phoneBody: string;
@@ -44,8 +46,13 @@ const plural = (language: string) => {
const en: FirstHourWords = {
greeting: (name, bot) => `Hi${name ? ` ${name}` : ""}! I'm ${bot}, your Chief of Staff. I live on the Cloud, so I keep working while your computer is off. What do you want off your plate?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} and ${arrived[1]}` : `Your ${arrived.length} bots`;
+ return `Hi${name ? ` ${name}` : ""}! ${who} ${one ? "is" : "are"} here now and ${one ? "keeps" : "keep"} working while your computer is off. I'm ${bot}, your Chief of Staff on this Cloud: carry on with ${one ? arrived[0] : "them"} as before, or tell me what else you want off your plate.`;
+ },
connect: "So I can see what needs you today, connect Gmail and Google Calendar. It's one sign-in each. I only read and write drafts: nothing is sent, accepted or deleted without you.",
- connected: "You're connected. I couldn't take a first look just now; I'll keep an eye on it and tell you when something needs you.",
+ lookLater: (apps, count) => `${apps} ${count === 1 ? "is" : "are"} connected, but I couldn't take my first look just now. Ask me "what needs me today?" whenever you like and I'll look then.`,
briefOn: "Every morning at 8 I'll send you a brief of what needs you.",
phoneTitle: "Get me on your phone",
phoneBody: "Your morning brief and anything that needs you will reach you there.",
@@ -65,8 +72,13 @@ const en: FirstHourWords = {
const de: FirstHourWords = {
greeting: (name, bot) => `Hallo${name ? ` ${name}` : ""}! Ich bin ${bot}, dein Chief of Staff. Ich lebe in deiner Cloud und arbeite weiter, auch wenn dein Computer aus ist. Was soll ich dir abnehmen?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} und ${arrived[1]}` : `Deine ${arrived.length} Bots`;
+ return `Hallo${name ? ` ${name}` : ""}! ${who} ${one ? "ist" : "sind"} jetzt hier und ${one ? "arbeitet" : "arbeiten"} weiter, auch wenn dein Computer aus ist. Ich bin ${bot}, dein Chief of Staff in dieser Cloud: Mach mit ${one ? arrived[0] : "ihnen"} weiter wie bisher, oder sag mir, was ich dir sonst abnehmen soll.`;
+ },
connect: "Damit ich sehe, was heute auf dich wartet, verbinde Gmail und Google Kalender. Das ist je eine Anmeldung. Ich lese nur und schreibe Entwürfe: Ohne dich wird nichts gesendet, zugesagt oder gelöscht.",
- connected: "Du bist verbunden. Einen ersten Überblick konnte ich gerade nicht machen; ich behalte alles im Blick und sage dir Bescheid, wenn etwas auf dich wartet.",
+ lookLater: (apps) => `${apps}: verbunden. Einen ersten Überblick konnte ich gerade nicht machen. Frag mich jederzeit „Was wartet heute auf mich?“, dann schaue ich nach.`,
briefOn: "Jeden Morgen um 8 schicke ich dir einen Überblick über das, was auf dich wartet.",
phoneTitle: "Hol mich auf dein Handy",
phoneBody: "Dein Morgenüberblick und alles, was auf dich wartet, erreicht dich dort.",
@@ -86,8 +98,13 @@ const de: FirstHourWords = {
const es: FirstHourWords = {
greeting: (name, bot) => `¡Hola${name ? `, ${name}` : ""}! Soy ${bot}, tu jefe de gabinete. Vivo en tu Cloud, así que sigo trabajando aunque tu ordenador esté apagado. ¿Qué quieres quitarte de encima?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} y ${arrived[1]}` : `Tus ${arrived.length} bots`;
+ return `¡Hola${name ? `, ${name}` : ""}! ${who} ya ${one ? "está" : "están"} aquí y ${one ? "sigue" : "siguen"} trabajando aunque tu ordenador esté apagado. Soy ${bot}, tu jefe de gabinete en esta Cloud: sigue con ${one ? arrived[0] : "ellos"} como antes, o dime qué más quieres quitarte de encima.`;
+ },
connect: "Para ver qué te necesita hoy, conecta Gmail y Google Calendar. Es un inicio de sesión para cada uno. Solo leo y escribo borradores: nada se envía, acepta ni borra sin ti.",
- connected: "Ya está conectado. Ahora no he podido echar un primer vistazo; lo vigilo y te aviso cuando algo te necesite.",
+ lookLater: (apps) => `${apps}: conectado. Ahora no he podido echar un primer vistazo. Pregúntame «¿qué me necesita hoy?» cuando quieras y lo miro entonces.`,
briefOn: "Cada mañana a las 8 te enviaré un resumen de lo que te necesita.",
phoneTitle: "Llévame en tu teléfono",
phoneBody: "Tu resumen de la mañana y todo lo que te necesite te llegará allí.",
@@ -107,8 +124,13 @@ const es: FirstHourWords = {
const fr: FirstHourWords = {
greeting: (name, bot) => `Bonjour${name ? ` ${name}` : ""} ! Je suis ${bot}, votre chef de cabinet. Je vis sur votre Cloud, alors je continue à travailler même quand votre ordinateur est éteint. Qu’aimeriez-vous que je vous enlève des mains ?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} et ${arrived[1]}` : `Vos ${arrived.length} bots`;
+ return `Bonjour${name ? ` ${name}` : ""} ! ${who} ${one ? "est" : "sont"} maintenant ici et ${one ? "continue" : "continuent"} à travailler même quand votre ordinateur est éteint. Je suis ${bot}, votre chef de cabinet sur ce Cloud : continuez avec ${one ? arrived[0] : "eux"} comme avant, ou dites-moi ce que je peux encore vous enlever des mains.`;
+ },
connect: "Pour voir ce qui demande votre attention aujourd’hui, connectez Gmail et Google Agenda. Une connexion pour chacun. Je ne fais que lire et rédiger des brouillons : rien n’est envoyé, accepté ni supprimé sans vous.",
- connected: "C’est connecté. Je n’ai pas pu faire un premier tour d’horizon pour l’instant ; je garde un œil dessus et je vous préviens dès que quelque chose demande votre attention.",
+ lookLater: (apps) => `${apps} : connecté. Je n’ai pas pu faire un premier tour d’horizon pour l’instant. Demandez-moi « qu’est-ce qui m’attend aujourd’hui ? » quand vous voulez, et je regarderai à ce moment-là.`,
briefOn: "Chaque matin à 8 h, je vous enverrai un point sur ce qui demande votre attention.",
phoneTitle: "Emmenez-moi sur votre téléphone",
phoneBody: "Votre point du matin et tout ce qui demande votre attention vous y attendront.",
@@ -128,8 +150,13 @@ const fr: FirstHourWords = {
const it: FirstHourWords = {
greeting: (name, bot) => `Ciao${name ? ` ${name}` : ""}! Sono ${bot}, il tuo capo di gabinetto. Vivo nel tuo Cloud, quindi continuo a lavorare anche quando il computer è spento. Che cosa vuoi toglierti di dosso?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} e ${arrived[1]}` : `I tuoi ${arrived.length} bot`;
+ return `Ciao${name ? ` ${name}` : ""}! ${who} ${one ? "è" : "sono"} qui adesso e ${one ? "continua" : "continuano"} a lavorare anche quando il computer è spento. Sono ${bot}, il tuo capo di gabinetto in questo Cloud: continua con ${one ? arrived[0] : "loro"} come prima, oppure dimmi cos'altro vuoi toglierti di dosso.`;
+ },
connect: "Per vedere cosa ti aspetta oggi, collega Gmail e Google Calendar. Basta un accesso per ciascuno. Leggo e scrivo solo bozze: niente viene inviato, accettato o eliminato senza di te.",
- connected: "Collegato. Per ora non sono riuscito a dare un primo sguardo; tengo d’occhio la situazione e ti avviso quando qualcosa richiede la tua attenzione.",
+ lookLater: (apps) => `${apps}: collegato. Per ora non sono riuscito a dare un primo sguardo. Chiedimi «cosa mi aspetta oggi?» quando vuoi e ci guardo allora.`,
briefOn: "Ogni mattina alle 8 ti mando un riepilogo di ciò che richiede la tua attenzione.",
phoneTitle: "Portami sul telefono",
phoneBody: "Il riepilogo del mattino e tutto ciò che ti riguarda ti arriveranno lì.",
@@ -149,8 +176,13 @@ const it: FirstHourWords = {
const ptBr: FirstHourWords = {
greeting: (name, bot) => `Oi${name ? `, ${name}` : ""}! Eu sou o ${bot}, seu chefe de gabinete. Eu moro na sua Cloud, então continuo trabalhando mesmo com seu computador desligado. O que você quer tirar das suas costas?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} e ${arrived[1]}` : `Seus ${arrived.length} bots`;
+ return `Oi${name ? `, ${name}` : ""}! ${who} ${one ? "já está" : "já estão"} aqui e ${one ? "continua" : "continuam"} trabalhando mesmo com seu computador desligado. Eu sou o ${bot}, seu chefe de gabinete nesta Cloud: continue com ${one ? arrived[0] : "eles"} como antes, ou me diga o que mais você quer tirar das suas costas.`;
+ },
connect: "Para eu ver o que precisa de você hoje, conecte o Gmail e o Google Agenda. É um login para cada um. Eu só leio e escrevo rascunhos: nada é enviado, aceito ou apagado sem você.",
- connected: "Conectado. Não consegui dar uma primeira olhada agora; vou ficar de olho e aviso quando algo precisar de você.",
+ lookLater: (apps) => `${apps}: conectado. Não consegui dar uma primeira olhada agora. Me pergunte "o que precisa de mim hoje?" quando quiser, e eu olho na hora.`,
briefOn: "Toda manhã às 8 eu te mando um resumo do que precisa de você.",
phoneTitle: "Me leve no seu celular",
phoneBody: "Seu resumo da manhã e tudo o que precisar de você vão chegar lá.",
@@ -170,8 +202,12 @@ const ptBr: FirstHourWords = {
const ja: FirstHourWords = {
greeting: (name, bot) => `${name ? `${name}さん、` : ""}こんにちは!${bot}です。あなたのチーフ・オブ・スタッフです。Cloud上にいるので、パソコンの電源が切れていても働き続けます。何を任せたいですか?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length <= 2 ? arrived.join("と") : `あなたのボット${arrived.length}体`;
+ return `${name ? `${name}さん、` : ""}こんにちは!${who}はもうここにいて、パソコンの電源が切れていても働き続けます。私は${bot}、このCloudでのあなたのチーフ・オブ・スタッフです。これまで通り${arrived.length === 1 ? arrived[0] : "それぞれのボット"}と続けるか、ほかに任せたいことを教えてください。`;
+ },
connect: "今日あなたの対応が必要なことを確認できるよう、GmailとGoogleカレンダーを接続してください。それぞれ1回サインインするだけです。読むことと下書きを書くことしかしません。あなたなしで送信・承諾・削除することはありません。",
- connected: "接続できました。今は最初のまとめを作れませんでした。引き続き確認して、対応が必要なことがあればお知らせします。",
+ lookLater: (apps) => `${apps}:接続済みです。今は最初のまとめを作れませんでした。いつでも「今日対応が必要なことは?」と聞いてください。そのときに確認します。`,
briefOn: "毎朝8時に、対応が必要なことのまとめをお送りします。",
phoneTitle: "スマホでも使えます",
phoneBody: "朝のまとめや対応が必要なことがスマホに届きます。",
@@ -191,8 +227,12 @@ const ja: FirstHourWords = {
const ko: FirstHourWords = {
greeting: (name, bot) => `안녕하세요${name ? `, ${name}님` : ""}! 저는 비서실장 ${bot}입니다. 클라우드에 있어서 컴퓨터가 꺼져 있어도 계속 일해요. 어떤 일을 덜어 드릴까요?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length <= 2 ? arrived.join(", ") : `봇 ${arrived.length}개`;
+ return `안녕하세요${name ? `, ${name}님` : ""}! 이제 여기서 일해요: ${who}. 컴퓨터가 꺼져 있어도 계속 일해요. 저는 이 클라우드의 비서실장 ${bot}입니다. 하던 대로 계속하시거나, 다른 일을 덜어 드릴 게 있으면 말씀해 주세요.`;
+ },
connect: "오늘 확인할 일을 살펴볼 수 있게 Gmail과 Google 캘린더를 연결해 주세요. 각각 한 번만 로그인하면 돼요. 저는 읽고 초안만 써요. 허락 없이 보내거나, 수락하거나, 삭제하지 않아요.",
- connected: "연결됐어요. 지금은 첫 살펴보기를 하지 못했어요. 계속 지켜보다가 확인할 일이 생기면 알려 드릴게요.",
+ lookLater: (apps) => `${apps}: 연결됐어요. 지금은 첫 살펴보기를 하지 못했어요. 언제든 "오늘 내가 할 일은?"이라고 물어보시면 그때 살펴볼게요.`,
briefOn: "매일 아침 8시에 확인할 일을 정리한 브리핑을 보내 드릴게요.",
phoneTitle: "휴대폰에서도 만나요",
phoneBody: "아침 브리핑과 확인할 일이 휴대폰으로 와요.",
@@ -212,8 +252,12 @@ const ko: FirstHourWords = {
const zh: FirstHourWords = {
greeting: (name, bot) => `你好${name ? `,${name}` : ""}!我是 ${bot},你的幕僚长。我在你的 Cloud 上,所以电脑关机时我也在工作。你想让我帮你分担什么?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length <= 2 ? arrived.join(" 和 ") : `你的 ${arrived.length} 个机器人`;
+ return `你好${name ? `,${name}` : ""}!${who}已经在这里了,电脑关机时也会继续工作。我是 ${bot},你在这个 Cloud 上的幕僚长:像以前一样继续和${arrived.length === 1 ? ` ${arrived[0]} ` : "它们"}合作,或者告诉我还想让我帮你分担什么。`;
+ },
connect: "为了看清今天有哪些事需要你,请连接 Gmail 和 Google 日历。各登录一次即可。我只读取内容并写草稿:没有你的同意,不会发送、接受或删除任何东西。",
- connected: "已连接。我刚才没能完成第一份概览;我会继续留意,有需要你处理的事会告诉你。",
+ lookLater: (apps) => `${apps}:已连接。我刚才没能完成第一份概览。随时问我“今天有什么需要我处理?”,我到时再看。`,
briefOn: "每天早上 8 点,我会给你发一份需要你处理的事项简报。",
phoneTitle: "在手机上用我",
phoneBody: "早间简报和需要你处理的事都会发到手机上。",
@@ -233,8 +277,12 @@ const zh: FirstHourWords = {
const zhTw: FirstHourWords = {
greeting: (name, bot) => `你好${name ? `,${name}` : ""}!我是 ${bot},你的幕僚長。我在你的 Cloud 上,所以電腦關機時我也在工作。你想讓我幫你分擔什麼?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length <= 2 ? arrived.join(" 和 ") : `你的 ${arrived.length} 個機器人`;
+ return `你好${name ? `,${name}` : ""}!${who}已經在這裡了,電腦關機時也會繼續工作。我是 ${bot},你在這個 Cloud 上的幕僚長:像以前一樣繼續和${arrived.length === 1 ? ` ${arrived[0]} ` : "它們"}合作,或者告訴我還想讓我幫你分擔什麼。`;
+ },
connect: "為了看清今天有哪些事需要你,請連接 Gmail 和 Google 日曆。各登入一次即可。我只讀取內容並寫草稿:沒有你的同意,不會傳送、接受或刪除任何東西。",
- connected: "已連接。我剛才沒能完成第一份概覽;我會繼續留意,有需要你處理的事會告訴你。",
+ lookLater: (apps) => `${apps}:已連接。我剛才沒能完成第一份概覽。隨時問我「今天有什麼需要我處理?」,我到時再看。`,
briefOn: "每天早上 8 點,我會傳給你一份需要你處理的事項簡報。",
phoneTitle: "在手機上用我",
phoneBody: "早晨簡報和需要你處理的事都會送到手機上。",
@@ -254,8 +302,13 @@ const zhTw: FirstHourWords = {
const hi: FirstHourWords = {
greeting: (name, bot) => `नमस्ते${name ? ` ${name}` : ""}! मैं ${bot} हूँ, आपका चीफ़ ऑफ़ स्टाफ़। मैं आपके Cloud पर रहता हूँ, इसलिए आपका कंप्यूटर बंद होने पर भी काम करता रहता हूँ। आप कौन सा काम मुझे सौंपना चाहेंगे?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} और ${arrived[1]}` : `आपके ${arrived.length} बॉट`;
+ return `नमस्ते${name ? ` ${name}` : ""}! ${who} अब यहाँ ${one ? "है" : "हैं"} और आपका कंप्यूटर बंद होने पर भी ${one ? "काम करता रहता है" : "काम करते रहते हैं"}। मैं ${bot} हूँ, इस Cloud पर आपका चीफ़ ऑफ़ स्टाफ़: ${one ? arrived[0] : "उन"} के साथ पहले की तरह काम जारी रखें, या बताएँ कि और कौन सा काम मुझे सौंपना चाहेंगे।`;
+ },
connect: "आज किन बातों में आपकी ज़रूरत है, यह देखने के लिए Gmail और Google Calendar जोड़ें। हर एक के लिए एक बार साइन इन करना है। मैं सिर्फ़ पढ़ता हूँ और ड्राफ़्ट लिखता हूँ: आपके बिना कुछ भी भेजा, स्वीकार या मिटाया नहीं जाता।",
- connected: "जुड़ गया। अभी मैं पहला जायज़ा नहीं ले पाया; मैं नज़र रखूँगा और आपकी ज़रूरत होने पर बताऊँगा।",
+ lookLater: (apps) => `${apps}: जुड़ गया। अभी मैं पहला जायज़ा नहीं ले पाया। जब चाहें मुझसे पूछें "आज किन बातों में मेरी ज़रूरत है?", मैं तब देख लूँगा।`,
briefOn: "हर सुबह 8 बजे मैं आपको उन बातों का सार भेजूँगा जिनमें आपकी ज़रूरत है।",
phoneTitle: "मुझे अपने फ़ोन पर पाएँ",
phoneBody: "आपका सुबह का सार और हर ज़रूरी बात वहीं पहुँचेगी।",
@@ -276,8 +329,13 @@ const hi: FirstHourWords = {
const ruCount = plural("ru");
const ru: FirstHourWords = {
greeting: (name, bot) => `Здравствуйте${name ? `, ${name}` : ""}! Я ${bot}, ваш начальник штаба. Я живу в вашем Cloud и продолжаю работать, даже когда компьютер выключен. Что вы хотите переложить на меня?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} и ${arrived[1]}` : `Ваши боты (${arrived.length})`;
+ return `Здравствуйте${name ? `, ${name}` : ""}! ${who} теперь ${one ? "здесь и продолжает" : "здесь и продолжают"} работать, даже когда компьютер выключен. Я ${bot}, ваш начальник штаба в этом Cloud: продолжайте, как раньше, или скажите, что ещё вы хотите переложить на меня.`;
+ },
connect: "Чтобы видеть, что сегодня требует вашего внимания, подключите Gmail и Google Календарь. По одному входу для каждого. Я только читаю и пишу черновики: без вас ничего не отправляется, не принимается и не удаляется.",
- connected: "Подключено. Сделать первый обзор сейчас не получилось; я слежу и сообщу, когда что-то потребует вашего внимания.",
+ lookLater: (apps) => `${apps}: подключено. Сделать первый обзор сейчас не получилось. Спросите меня «что сегодня требует моего внимания?», когда захотите, и я посмотрю.`,
briefOn: "Каждое утро в 8 я буду присылать сводку того, что требует вашего внимания.",
phoneTitle: "Возьмите меня в телефон",
phoneBody: "Утренняя сводка и всё, что требует вашего внимания, будут приходить туда.",
@@ -298,8 +356,13 @@ const ru: FirstHourWords = {
const ukCount = plural("uk");
const uk: FirstHourWords = {
greeting: (name, bot) => `Вітаю${name ? `, ${name}` : ""}! Я ${bot}, ваш керівник апарату. Я живу у вашому Cloud і працюю далі, навіть коли комп'ютер вимкнено. Що ви хочете перекласти на мене?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} і ${arrived[1]}` : `Ваші боти (${arrived.length})`;
+ return `Вітаю${name ? `, ${name}` : ""}! ${who} тепер ${one ? "тут і працює" : "тут і працюють"} далі, навіть коли комп'ютер вимкнено. Я ${bot}, ваш керівник апарату в цьому Cloud: продовжуйте, як раніше, або скажіть, що ще ви хочете перекласти на мене.`;
+ },
connect: "Щоб бачити, що сьогодні потребує вашої уваги, підключіть Gmail і Google Календар. По одному входу для кожного. Я лише читаю і пишу чернетки: без вас нічого не надсилається, не приймається і не видаляється.",
- connected: "Підключено. Зробити перший огляд зараз не вдалося; я стежу і повідомлю, коли щось потребуватиме вашої уваги.",
+ lookLater: (apps) => `${apps}: підключено. Зробити перший огляд зараз не вдалося. Запитайте мене «що сьогодні потребує моєї уваги?», коли захочете, і я подивлюся.`,
briefOn: "Щоранку о 8 я надсилатиму зведення того, що потребує вашої уваги.",
phoneTitle: "Візьміть мене в телефон",
phoneBody: "Ранкове зведення і все, що потребує вашої уваги, надходитимуть туди.",
@@ -320,8 +383,13 @@ const uk: FirstHourWords = {
const plCount = plural("pl");
const pl: FirstHourWords = {
greeting: (name, bot) => `Cześć${name ? `, ${name}` : ""}! Jestem ${bot}, twój szef sztabu. Mieszkam w twoim Cloud, więc pracuję dalej, nawet gdy komputer jest wyłączony. Co chcesz zrzucić ze swojej głowy?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const one = arrived.length === 1;
+ const who = one ? arrived[0] : arrived.length === 2 ? `${arrived[0]} i ${arrived[1]}` : `Twoje boty (${arrived.length})`;
+ return `Cześć${name ? `, ${name}` : ""}! ${who} ${one ? "jest już tutaj i pracuje" : "są już tutaj i pracują"} dalej, nawet gdy komputer jest wyłączony. Jestem ${bot}, twój szef sztabu w tym Cloud: pracuj dalej jak dotąd albo powiedz, co jeszcze chcesz zrzucić ze swojej głowy.`;
+ },
connect: "Żebym widział, co dziś czeka na ciebie, połącz Gmaila i Kalendarz Google. Wystarczy jedno logowanie do każdego. Tylko czytam i piszę szkice: bez ciebie nic nie zostanie wysłane, przyjęte ani usunięte.",
- connected: "Połączono. Na razie nie udało się zrobić pierwszego przeglądu; będę mieć wszystko na oku i dam znać, gdy coś będzie na ciebie czekać.",
+ lookLater: (apps) => `${apps}: połączono. Na razie nie udało się zrobić pierwszego przeglądu. Zapytaj mnie „co dziś na mnie czeka?”, kiedy zechcesz, a wtedy zajrzę.`,
briefOn: "Każdego ranka o 8 wyślę ci podsumowanie tego, co na ciebie czeka.",
phoneTitle: "Weź mnie do telefonu",
phoneBody: "Poranne podsumowanie i wszystko, co na ciebie czeka, trafi właśnie tam.",
@@ -341,8 +409,12 @@ const pl: FirstHourWords = {
const vi: FirstHourWords = {
greeting: (name, bot) => `Chào${name ? ` ${name}` : " bạn"}! Tôi là ${bot}, Chief of Staff của bạn. Tôi sống trên Cloud của bạn, nên vẫn làm việc khi máy tính của bạn tắt. Bạn muốn tôi gánh bớt việc gì?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length === 1 ? arrived[0] : arrived.length === 2 ? `${arrived[0]} và ${arrived[1]}` : `${arrived.length} bot của bạn`;
+ return `Chào${name ? ` ${name}` : " bạn"}! ${who} đã ở đây và vẫn làm việc khi máy tính của bạn tắt. Tôi là ${bot}, Chief of Staff của bạn trên Cloud này: cứ tiếp tục với ${arrived.length === 1 ? arrived[0] : "các bot đó"} như trước, hoặc cho tôi biết bạn muốn tôi gánh bớt việc gì khác.`;
+ },
connect: "Để biết hôm nay việc gì cần bạn, hãy kết nối Gmail và Google Lịch. Mỗi cái chỉ cần đăng nhập một lần. Tôi chỉ đọc và viết bản nháp: không có gì được gửi, chấp nhận hay xóa mà không có bạn.",
- connected: "Đã kết nối. Lúc này tôi chưa xem tổng quan được; tôi sẽ theo dõi và báo khi có việc cần bạn.",
+ lookLater: (apps) => `${apps}: đã kết nối. Lúc này tôi chưa xem tổng quan được. Cứ hỏi tôi "hôm nay việc gì cần tôi?" bất cứ lúc nào, tôi sẽ xem khi đó.`,
briefOn: "Mỗi sáng lúc 8 giờ, tôi sẽ gửi bạn bản tóm tắt những việc cần bạn.",
phoneTitle: "Mang tôi theo trên điện thoại",
phoneBody: "Bản tóm tắt buổi sáng và mọi việc cần bạn sẽ đến đó.",
@@ -362,8 +434,12 @@ const vi: FirstHourWords = {
const tr: FirstHourWords = {
greeting: (name, bot) => `Merhaba${name ? ` ${name}` : ""}! Ben ${bot}, kurmay başkanın. Cloud'unda yaşıyorum, bu yüzden bilgisayarın kapalıyken de çalışmaya devam ederim. Hangi işi senin yerine üstleneyim?`,
+ arrivedGreeting: (name, bot, arrived) => {
+ const who = arrived.length === 1 ? arrived[0] : arrived.length === 2 ? `${arrived[0]} ve ${arrived[1]}` : `${arrived.length} botun`;
+ return `Merhaba${name ? ` ${name}` : ""}! ${who} artık burada ve bilgisayarın kapalıyken de çalışmaya devam ediyor. Ben ${bot}, bu Cloud'daki kurmay başkanın: önceki gibi devam et ya da senin yerine başka hangi işi üstleneyim, söyle.`;
+ },
connect: "Bugün seni neyin beklediğini görebilmem için Gmail ve Google Takvim'i bağla. Her biri için bir kez giriş yapman yeter. Sadece okurum ve taslak yazarım: sen olmadan hiçbir şey gönderilmez, kabul edilmez ya da silinmez.",
- connected: "Bağlandı. Şu an ilk genel bakışı yapamadım; takipteyim, seni bekleyen bir şey çıkınca haber veririm.",
+ lookLater: (apps) => `${apps}: bağlandı. Şu an ilk genel bakışı yapamadım. İstediğin zaman bana "bugün beni ne bekliyor?" diye sor, o zaman bakarım.`,
briefOn: "Her sabah 8'de seni bekleyenlerin bir özetini göndereceğim.",
phoneTitle: "Beni telefonuna al",
phoneBody: "Sabah özetin ve seni bekleyen her şey oraya gelir.",
diff --git a/server/host/first-hour.test.ts b/server/host/first-hour.test.ts
index 31d13ebbef..57b6353638 100644
--- a/server/host/first-hour.test.ts
+++ b/server/host/first-hour.test.ts
@@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import type { RoutineRun } from "../routines.ts";
import { Store, type Message } from "../store.ts";
-import { createFirstHour, firstName, greetingMessage, LOOK_DRAFTS, lookPrompt, OFFER_UNASKED_MS, type FirstHourDeps } from "./first-hour.ts";
+import { createFirstHour, firstName, greetingMessage, LOOK_DRAFTS, LOOK_RETRY_MS, lookPrompt, OFFER_UNASKED_MS, type FirstHourDeps } from "./first-hour.ts";
import { createValueLedger } from "./value-ledger.ts";
const MINUTE = 60_000;
@@ -13,6 +13,7 @@ const HOUR = 60 * MINUTE;
const dirs: string[] = [];
afterEach(() => {
vi.useRealTimers();
+ vi.restoreAllMocks();
for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true });
});
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
@@ -22,6 +23,8 @@ function setup(options: { start?: string; connected?: { gmail?: boolean; googlec
dirs.push(dir);
let now = Date.parse(options.start ?? "2026-10-27T15:00:00Z");
const store = new Store(() => ({ instanceId: "claude", model: "claude-sonnet-5" }));
+ // The store keeps its bots in the data folder all these tests share: each new Cloud starts with none.
+ for (const id of store.bots.map((bot) => bot.id)) store.deleteBot(id);
const chief = store.createBot({ name: "MausBot" }, { seedMessages: false });
store.setChiefOfStaff(chief.id);
const thread = () => store.bot(chief.id)!.threadId;
@@ -34,18 +37,27 @@ function setup(options: { start?: string; connected?: { gmail?: boolean; googlec
briefCard: undefined as { threadId: string; messageId: string } | undefined,
/** While set, the first look's turn runs until this is called. */
held: null as null | (() => void), hold: false,
+ /** A move into the Cloud is running; the next first look's start throws this. */
+ moving: false, refuse: null as null | Error, chiefId: chief.id, stopped: false,
+ /** Runs as a first look's turn starts. */
+ onTurn: undefined as undefined | (() => void),
+ /** How the next first look's turn fails: without a reply, or as a failed turn. */
+ failure: undefined as undefined | { text: string; stopReason?: string },
};
const ledger = createValueLedger({ dataDir: dir, now: () => now });
const deps: FirstHourDeps = {
- store, dataDir: dir, now: () => now, chief: () => store.bot(chief.id), mainThread: () => thread(), threadBusy: () => world.busy,
+ store, dataDir: dir, now: () => now, chief: () => store.bot(world.chiefId), mainThread: (botId) => store.bot(botId)?.threadId, threadBusy: () => world.busy,
person: () => world.person, language: () => world.language, timeZone: () => world.zone,
apps: { reachable: () => true, connected: async () => ({ ...world.connected }), card: async (slug) => ({ label: slug === "gmail" ? "Gmail" : "Google Calendar", description: "" }) },
briefOn: () => world.briefOn, ensureBrief: () => { world.briefOn = true; }, briefCard: () => world.briefCard, phones: () => world.phones,
+ moving: () => world.moving, stopped: () => world.stopped,
startTurn: async (_botId, text, opts) => {
world.turns.push({ text, threadId: opts.threadId });
+ world.onTurn?.();
+ if (world.refuse) throw world.refuse;
const end = () => {
if (world.reply) store.appendMessage(opts.threadId, { role: "bot", kind: "text", text: world.reply, turnId: "look" });
- opts.onSettled({ ok: world.reply !== null, text: world.reply ?? "" });
+ opts.onSettled(world.failure ? { ok: false, text: world.failure.text, failure: world.failure } : { ok: world.reply !== null, text: world.reply ?? "" });
};
if (world.hold) world.held = end;
else end();
@@ -78,6 +90,147 @@ function setup(options: { start?: string; connected?: { gmail?: boolean; googlec
return { store, chief, thread, world, ledger, make, rows, texts, cards, write, reply, answer, advance: (ms: number) => { now += ms; }, set: (iso: string) => { now = Date.parse(iso); }, now: () => now };
}
+describe("a new Cloud the person's own bots came to", () => {
+ const ONE = "Hi Sam! Coder is here now and keeps working while your computer is off. I'm MausBot, your Chief of Staff on this Cloud: carry on with Coder as before, or tell me what else you want off your plate.";
+
+ it("greets them with the bot that moved in, never offers the inbox unasked, and lets the Chief offer it only when asked", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ s.world.person = { name: "Sam Lee" };
+ s.store.createBot({ name: "Coder" }, { seedMessages: false });
+ fh.arrived();
+ expect(s.texts()).toEqual([ONE]);
+ await vi.advanceTimersByTimeAsync(OFFER_UNASKED_MS);
+ vi.useRealTimers();
+ fh.tick();
+ await s.answer(fh, "Is Coder still on my repo?");
+ expect(s.cards()).toEqual([]);
+ expect(s.texts().some((text) => text?.includes("connect Gmail"))).toBe(false);
+ s.advance(25 * HOUR);
+ fh.tick();
+ expect(s.texts().some((text) => text?.startsWith("So far"))).toBe(false);
+ expect(fh.health()!.ms.movedIn).toBe(0);
+ expect(fh.health()!.ms.offered).toBeUndefined();
+ fh.stop();
+ });
+
+ it("tells the Chief the bots are there and that the inbox waits until the person brings it up", () => {
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ s.store.createBot({ name: "Coder" }, { seedMessages: false });
+ s.store.createBot({ name: "Writer" }, { seedMessages: false });
+ fh.tick();
+ expect(s.texts()[0]).toBe("Hi! Coder and Writer are here now and keep working while your computer is off. I'm MausBot, your Chief of Staff on this Cloud: carry on with them as before, or tell me what else you want off your plate.");
+ s.store.createBot({ name: "Scout" }, { seedMessages: false });
+ fh.tick();
+ expect(s.texts()[0]).toMatch(/^Hi! Your 3 bots are here now and keep working while your computer is off\./u);
+ const prompt = fh.prompt(s.chief.id, s.thread());
+ expect(prompt).toMatch(/Their own bots (?:Coder|Writer|Scout), (?:Coder|Writer|Scout), (?:Coder|Writer|Scout) are here too/u);
+ expect(prompt).toContain("If they bring up their email or calendar, you may offer to connect Gmail and Google Calendar then.");
+ expect(prompt).not.toContain("COMPOSIO_MANAGE_CONNECTIONS");
+ expect(prompt).not.toContain("morning brief is on");
+ });
+
+ it("holds the unasked offer while a move runs: a bot that arrives gets the greeting, a move that brings none lets the offer come", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const moved = setup();
+ const a = moved.make();
+ a.begin();
+ moved.world.moving = true;
+ a.arrived();
+ await vi.advanceTimersByTimeAsync(OFFER_UNASKED_MS);
+ expect(moved.cards()).toEqual([]);
+ moved.store.createBot({ name: "Coder" }, { seedMessages: false });
+ moved.world.moving = false;
+ a.tick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(moved.cards()).toEqual([]);
+ expect(moved.texts()[0]).toMatch(/^Hi! Coder is here now/u);
+ a.stop();
+ const empty = setup();
+ const b = empty.make();
+ b.begin();
+ empty.world.moving = true;
+ b.arrived();
+ await vi.advanceTimersByTimeAsync(OFFER_UNASKED_MS);
+ b.tick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(empty.cards()).toEqual([]);
+ empty.world.moving = false;
+ b.tick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(empty.cards()).toHaveLength(2);
+ b.stop();
+ });
+
+ it("names the bots that came, not the computer's own MausBot that came with them, and stops rewriting the greeting after the first day", () => {
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ s.store.createBot({ name: "MausBot (MacBook)" }, { seedMessages: false });
+ s.store.createBot({ name: "Coder" }, { seedMessages: false });
+ fh.tick();
+ expect(s.texts()[0]).toMatch(/^Hi! Coder is here now/u);
+ s.advance(25 * HOUR);
+ s.store.createBot({ name: "Writer" }, { seedMessages: false });
+ s.world.language = "de";
+ fh.tick();
+ fh.arrived();
+ fh.stop();
+ expect(s.texts()[0]).toMatch(/^Hi! Coder is here now/u);
+ });
+
+ it("changes nothing for a bot that comes after the first day", () => {
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ s.advance(25 * HOUR);
+ s.store.createBot({ name: "Coder" }, { seedMessages: false });
+ fh.arrived();
+ fh.tick();
+ fh.stop();
+ expect(s.texts()[0]).toMatch(/^Hi! I'm MausBot/u);
+ expect(fh.health()!.ms.movedIn).toBeUndefined();
+ });
+
+ it("changes nothing for a bot made after the inbox was offered", async () => {
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ await s.answer(fh);
+ expect(s.cards()).toHaveLength(2);
+ s.store.createBot({ name: "Coder" }, { seedMessages: false });
+ fh.arrived();
+ fh.tick();
+ fh.stop();
+ expect(s.texts()[0]).toMatch(/^Hi! I'm MausBot/u);
+ expect(fh.health()!.ms.movedIn).toBeUndefined();
+ });
+
+ it("leaves a Chief that arrived by a move alone: nothing posted in its chat and no first-day words for it", async () => {
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ const arrived = s.store.createBot({ name: "MausBot (MacBook)" }, { seedMessages: false });
+ s.store.setChiefOfStaff(arrived.id);
+ s.world.chiefId = arrived.id;
+ fh.arrived();
+ await vi.advanceTimersByTimeAsync(OFFER_UNASKED_MS);
+ fh.tick();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(s.store.messagesFor(arrived.threadId)).toEqual([]);
+ expect(fh.prompt(arrived.id, arrived.threadId)).toBe("");
+ // The computer's own MausBot is no news in the greeting: it stays as it was, and no inbox offer comes.
+ expect(s.texts()[0]).toMatch(/^Hi! I'm MausBot/u);
+ expect(fh.health()!.ms.movedIn).toBe(0);
+ fh.stop();
+ });
+});
+
describe("a new Cloud's first hour", () => {
it("begins once, on the new Cloud only: its welcome steps end and the Chief opens", () => {
const s = setup();
@@ -188,18 +341,157 @@ describe("a new Cloud's first hour", () => {
expect(fh.health()!.ms.declined).toBeDefined();
});
- it("says plainly when the first look could not run, and still offers the phone", async () => {
+ it("tries a failed first look once more after a short wait, then says which apps are in and how to get the look, and still offers the phone", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
const s = setup({ connected: { googlecalendar: true } });
const fh = s.make();
fh.begin();
s.world.reply = null;
await s.answer(fh);
expect(s.cards().map((card) => card.connector!.slug)).toEqual(["gmail"]);
+ expect(s.world.turns).toHaveLength(1);
expect(s.world.turns[0]!.text).toContain("just connected Google Calendar");
- expect(s.texts()).toContain("You're connected. I couldn't take a first look just now; I'll keep an eye on it and tell you when something needs you.");
+ const said = s.texts().length;
+ fh.tick();
+ await settle();
+ expect(s.texts()).toHaveLength(said);
+ expect(s.world.turns).toHaveLength(1);
+ expect(fh.health()).toMatchObject({ lookFailure: "error", lookTries: 1 });
+ expect(fh.health()!.look).toBeUndefined();
+ s.advance(LOOK_RETRY_MS);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(2);
+ expect(s.texts()).toContain("Google Calendar is connected, but I couldn't take my first look just now. Ask me \"what needs me today?\" whenever you like and I'll look then.");
+ expect(s.texts().some((text) => text?.includes("You're connected"))).toBe(false);
fh.tick();
expect(s.rows().at(-1)!.widget?.root.title).toBe("Get me on your phone");
+ expect(fh.health()).toMatchObject({ look: "failed", lookFailure: "error", lookTries: 2 });
+ const lines = warn.mock.calls.map((call) => String(call[0])).filter((line) => line.startsWith("first hour: the first look failed"));
+ expect(lines).toEqual([
+ expect.stringMatching(/^first hour: the first look failed \(try 1 of 2, again in 60 s\): path=settled ok=false replied=false stalled=false stop=- code=- sinceBoot=\d+ sinceApp=0 ms=0 apps=googlecalendar rows=[\w,-]+ drafts=0 cause="-"$/u),
+ expect.stringMatching(/^first hour: the first look failed \(try 2 of 2, the last\): path=settled ok=false replied=false/u),
+ ]);
+ });
+
+ it("gets the first look on its second try when the first one could not start, and logs the cause in the system's words only", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const s = setup({ connected: { gmail: true, googlecalendar: true } });
+ const fh = s.make();
+ fh.begin();
+ s.world.refuse = Object.assign(new Error("this provider account is being updated — try again shortly ([email protected])"), { status: 409, code: "settling" });
+ await s.answer(fh);
+ expect(s.world.turns).toHaveLength(1);
+ expect(fh.health()).toMatchObject({ lookFailure: "start", lookTries: 1 });
+ expect(warn.mock.calls.map((call) => String(call[0])).find((line) => line.startsWith("first hour: the first look failed"))).toMatch(/path=start code=settling .* cause="this provider account is being updated — try again shortly \(<address>\)"$/u);
+ s.world.refuse = null;
+ s.advance(LOOK_RETRY_MS - 1_000);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(1);
+ s.advance(1_000);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(2);
+ expect(s.texts()).toContain("This week: Standup Tue 10:00.");
+ expect(s.world.pushed).toEqual(["Your first look is ready"]);
+ expect(fh.health()).toMatchObject({ look: "delivered", lookTries: 1 });
+ });
+
+ it("waits out a move into the Cloud: no look starts while it runs, and a try that fails during it is not counted", async () => {
+ const s = setup();
+ const fh = s.make();
+ fh.begin();
+ await s.answer(fh);
+ s.world.moving = true;
+ const gmail = s.cards().find((card) => card.connector!.slug === "gmail")!;
+ s.store.patchMessage(s.thread(), gmail.id, { connector: { ...gmail.connector!, status: "connected" } });
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toEqual([]);
+ s.world.moving = false;
+ s.world.reply = null;
+ s.world.onTurn = () => { s.world.moving = true; };
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(1);
+ expect(fh.health()!.lookTries).toBeUndefined();
+ expect(fh.health()!.look).toBeUndefined();
+ s.world.moving = false;
+ s.world.onTurn = undefined;
+ s.world.reply = "This week: Standup Tue 10:00.";
+ s.advance(LOOK_RETRY_MS);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(2);
+ expect(fh.health()).toMatchObject({ look: "delivered" });
+ expect(s.texts().some((text) => text?.includes("couldn't take my first look"))).toBe(false);
+ });
+
+ it("never starts again a first look the person stopped, and says nothing about it", async () => {
+ const s = setup({ connected: { gmail: true } });
+ const fh = s.make();
+ fh.begin();
+ s.world.reply = null;
+ s.world.stopped = true;
+ await s.answer(fh);
+ expect(fh.health()).toMatchObject({ look: "failed", lookFailure: "stopped" });
+ s.advance(LOOK_RETRY_MS);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(1);
+ expect(s.texts().some((text) => text?.includes("first look"))).toBe(false);
+ });
+
+ it("does not try again once the person has written in that chat since the first try failed", async () => {
+ const s = setup({ connected: { gmail: true } });
+ const fh = s.make();
+ fh.begin();
+ s.world.reply = null;
+ await s.answer(fh);
+ expect(fh.health()).toMatchObject({ lookTries: 1 });
+ s.write("Never mind, look at my repo instead.");
+ s.advance(LOOK_RETRY_MS);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(1);
expect(fh.health()).toMatchObject({ look: "failed" });
+ expect(s.texts().some((text) => text?.includes("first look"))).toBe(false);
+ });
+
+ it("does not repeat a first look that already wrote a draft: a second try would start its three drafts over", async () => {
+ const s = setup({ connected: { gmail: true } });
+ const fh = s.make();
+ fh.begin();
+ s.world.reply = null;
+ s.world.onTurn = () => { expect(fh.look(s.thread())!.draft({} as never)).toBe(true); };
+ await s.answer(fh);
+ expect(fh.health()).toMatchObject({ look: "failed", lookTries: 1 });
+ s.advance(LOOK_RETRY_MS);
+ fh.tick();
+ await settle();
+ expect(s.world.turns).toHaveLength(1);
+ expect(s.texts().some((text) => text?.startsWith("Gmail is connected, but I couldn't take my first look"))).toBe(true);
+ });
+
+ it("does not try again when the bot is paused, and logs a failed turn's stop reason", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ const paused = setup({ connected: { gmail: true } });
+ const first = paused.make();
+ first.begin();
+ paused.world.refuse = Object.assign(new Error("MausBot is paused."), { status: 409, code: "bot_paused" });
+ await paused.answer(first);
+ expect(first.health()).toMatchObject({ look: "failed", lookFailure: "start", lookTries: 1 });
+ expect(paused.world.turns).toHaveLength(1);
+ expect(paused.texts().some((text) => text?.includes("first look"))).toBe(false);
+ const failing = setup({ connected: { gmail: true } });
+ const second = failing.make();
+ second.begin();
+ failing.world.reply = null;
+ failing.world.failure = { text: "Claude is signed out.", stopReason: "error" };
+ await failing.answer(second);
+ expect(second.health()).toMatchObject({ lookFailure: "error", lookTries: 1 });
+ expect(warn.mock.calls.map((call) => String(call[0])).at(-1)).toMatch(/path=settled ok=false replied=false stalled=false stop=error code=- .* cause="Claude is signed out."$/u);
});
it("pushes the first look to a phone paired after it, once; otherwise the first morning brief says it is the first", async () => {
diff --git a/server/host/first-hour.ts b/server/host/first-hour.ts
index c2d8a7df35..1d98d0b980 100644
--- a/server/host/first-hour.ts
+++ b/server/host/first-hour.ts
@@ -1,7 +1,9 @@
// A new personal Cloud's first hour, run by its Chief in its own chat, with no setup screen: a greeting by name and one
// question; after the first answer, Gmail and Google Calendar offered with the reason; a first look the moment one of
// them is in; the morning brief said once; the phone offered; and on day two a recap of what was really done. Each step
-// happens once, kept with its time in first-hour.json, which the health report carries to the Admin.
+// happens once, kept with its time in first-hour.json, which the health report carries to the Admin. A person who already
+// has bots here (moved in from their computer, or made) is greeted with them instead, and is never offered the inbox
+// unasked: they came for those bots.
import { randomUUID } from "node:crypto";
import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
@@ -15,6 +17,8 @@ import { createAgentCard } from "../chat-widgets.ts";
import { connectorCardText } from "../connector-card-text.ts";
import type { DraftReply } from "../read-and-draft.ts";
import { localDate, validZone } from "./check-plan.ts";
+import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../../shared/bot-limit.ts";
+import { PERSON_STOPPED_TURN_NAME } from "../../shared/client-cancel.ts";
import { FIRST_HOUR_OFFER_KEY } from "../../shared/person-wait.ts";
import { firstHourWords, type FirstHourWords } from "./first-hour-words.ts";
import { anyValue, minutesSaved, type ValueLedger, type ValueTally } from "./value-ledger.ts";
@@ -33,6 +37,10 @@ export const LOOK_DRAFTS = 3;
/** While the offer is open, how often a connection made elsewhere (another tab, the phone) is looked for, and how long. */
const CONNECTED_POLL_MS = MINUTE;
const CONNECTED_POLL_FOR_MS = 6 * HOUR;
+/** A first look that failed is tried once more after this: a new Cloud's AI or apps may need a moment more. */
+export const LOOK_RETRY_MS = MINUTE;
+/** Tries of the first look in all, the first included. */
+export const LOOK_TRIES = 2;
/** A first look that never reports back frees its chat after this. */
const LOOK_MAX_MS = 15 * MINUTE;
/** A first look waiting on a busy chat stops waiting after this. */
@@ -64,6 +72,15 @@ const stateSchema = z.object({
firstLookAt: at.optional(),
/** Why there was no first look: it failed, or the person's own task continued once its app was connected. */
lookSkipped: z.enum(["failed", "own-task"]).optional(),
+ /** Tries of the first look that failed, the newest one's way of failing, and when the next try may start. */
+ lookTries: z.number().int().min(0).max(LOOK_TRIES).optional(),
+ lookFailure: z.enum(["start", "error", "stalled", "no-reply", "busy", "stopped"]).optional(),
+ lookRetryAt: at.optional(),
+ /** How many messages the person had written in the look's chat when a try failed: one written since ends the retry. */
+ lookSaid: z.number().int().nonnegative().optional(),
+ /** The Chief that greeted, and when bots of the person's own were first seen here besides it. */
+ chiefId: id.optional(),
+ movedInAt: at.optional(),
briefOnAt: at.optional(),
phoneOfferedAt: at.optional(),
phonePairedAt: at.optional(),
@@ -77,13 +94,27 @@ type FirstHourState = z.infer<typeof stateSchema>;
/** The milestones as times since the Cloud's first boot, for the Admin to set beside the trial's outcome. Times only. */
export interface FirstHourReport {
startedAt: number;
- ms: Partial<Record<"seen" | "firstMessage" | "offered" | "firstApp" | "declined" | "firstLook" | "briefOn" | "phoneOffered" | "phonePaired" | "recap", number>>;
+ ms: Partial<Record<"seen" | "firstMessage" | "offered" | "firstApp" | "declined" | "firstLook" | "briefOn" | "phoneOffered" | "phonePaired" | "recap" | "movedIn", number>>;
apps: LookApp[];
look?: "delivered" | "failed" | "own-task";
+ /** How the newest failed try of the first look failed, and how many tries failed. */
+ lookFailure?: NonNullable<FirstHourState["lookFailure"]>;
+ lookTries?: number;
}
+/** How a try of the first look ended without a look: never the turn's own words. */
+interface LookMiss { path: "start" | "settled"; ok?: boolean; replied?: boolean; stalled?: boolean; stopReason?: string | null; code?: string; cause?: string; rows?: string[];
+ /** The person pressed Stop on it. */ stopped?: boolean; /** Reply drafts it already wrote. */ drafted?: number }
+/** Causes no second try changes: the bot is paused or held, or gone. */
+const LASTING = new Set([BOT_PAUSED_CODE, BOT_HELD_CODE, "moved", "404"]);
+/** A cause in the system's words, on one line, with no addresses in it. */
+const causeLine = (text: string | undefined): string | undefined => {
+ const line = text?.replace(/[\w.+-]+@[\w-]+(?:\.[\w-]+)+/gu, "<address>").replace(/\s+/gu, " ").trim().slice(0, 160);
+ return line || undefined;
+};
+
export interface FirstHourDeps {
- store: Pick<Store, "bot" | "messagesFor" | "activePath" | "appendMessage" | "patchMessage" | "patchTask" | "patchBot" | "taskByThread" | "groupByThread">;
+ store: Pick<Store, "bot" | "bots" | "messagesFor" | "activePath" | "appendMessage" | "patchMessage" | "patchTask" | "patchBot" | "taskByThread" | "groupByThread">;
dataDir: string;
now?: () => number;
/** The Chief the first hour belongs to: the place's MausBot, or its main Chief. */
@@ -100,6 +131,11 @@ export interface FirstHourDeps {
connected(): Promise<Partial<Record<LookApp, boolean>> | null>;
card(slug: LookApp): Promise<{ label: string; description: string }>;
};
+ /** A move into this Cloud is running or about to (cloud-send-lease.ts): the inbox is not offered while bots may still
+ * arrive, and the first look waits. */
+ moving?(): boolean;
+ /** The person pressed Stop on the turn running in this chat. */
+ stopped?(threadId: string): boolean;
/** The Chief's brief is on. */
briefOn(): boolean;
/** An app it reads is in: the brief is made now if it was not yet. */
@@ -129,8 +165,10 @@ export function firstName(person: { name?: string; email?: string }): string | u
return first[0]!.toUpperCase() + first.slice(1);
}
-export function greetingMessage(bot: Pick<BotRecord, "name">, person: { name?: string; email?: string }, language: string | undefined): Omit<Message, "id" | "at"> {
- return { role: "bot", kind: "text", text: firstHourWords(language).greeting(firstName(person), bot.name) };
+/** `arrived`: the names of the person's own bots already here besides the Chief, which the greeting says are here now. */
+export function greetingMessage(bot: Pick<BotRecord, "name">, person: { name?: string; email?: string }, language: string | undefined, arrived: readonly string[] = []): Omit<Message, "id" | "at"> {
+ const words = firstHourWords(language);
+ return { role: "bot", kind: "text", text: arrived.length ? words.arrivedGreeting(firstName(person), bot.name, arrived) : words.greeting(firstName(person), bot.name) };
}
const languageName = (language: string | undefined): string => {
@@ -198,6 +236,8 @@ export function createFirstHour(deps: FirstHourDeps) {
const threadId = bot ? deps.mainThread(bot.id) : undefined;
return bot && threadId ? { bot, threadId } : null;
};
+ /** How many messages the person has written in a chat. */
+ const written = (threadId: string): number => deps.store.messagesFor(threadId).filter((message) => message.role === "user" && message.kind === "text").length;
const said = (threadId: string, from: number): boolean =>
deps.store.messagesFor(threadId).some((message) => message.role === "user" && message.kind === "text" && message.at >= from);
/** The person's newest message on the shown branch has no answer from a bot turn yet (text or a rich reply such as a
@@ -220,28 +260,58 @@ export function createFirstHour(deps: FirstHourDeps) {
let look: { threadId: string; drafts: number; until: number } | null = null;
let offerTimer: ReturnType<typeof setTimeout> | null = null;
+ /** The offer was due while a move into this Cloud was running: it is tried again once the move lets go. */
+ let offerHeld = false;
let lastPoll = 0;
let busy = false;
- /** The greeting in the person's language and with their name, while it is still the last thing in the chat. */
+ /** The bot that greeted: kept since the first hour began, else the bot whose chat the greeting is in. */
+ const greeter = (): string | undefined => state?.chiefId ?? (state?.greeting ? deps.store.bots.find((bot) => bot.threadId === state!.greeting!.threadId)?.id : undefined);
+ /** The person's own bots here besides the Chief that greeted them: moved in from their computer, or made. */
+ const others = (): BotRecord[] => {
+ const chief = greeter();
+ return deps.store.bots.filter((bot) => bot.id !== chief && !bot.hidden && !bot.movedTo).sort((a, b) => (a.createdAt ?? 0) - (b.createdAt ?? 0) || a.name.localeCompare(b.name));
+ };
+ /** Their names for the greeting, leaving out a MausBot that came along: "MausBot is here now… I'm MausBot" says nothing. */
+ const arrivals = (): string[] => {
+ const own = greeter() ? deps.store.bot(greeter()!)?.name : undefined;
+ return others().filter((bot) => !bot.defaultBot && (!own || (bot.name !== own && !bot.name.startsWith(`${own} (`)))).map((bot) => bot.name);
+ };
+ /** Bots of the person's own came before the inbox was offered: the first hour greets them with those bots and never
+ * offers the inbox unasked. Decided once, and kept. */
+ const movedIn = (): boolean => {
+ if (!state) return false;
+ if (state.movedInAt) return true;
+ if (state.offeredAt || now() - state.startedAt > FIRST_DAY_MS || !others().length) return false;
+ mark({ movedInAt: now() });
+ return true;
+ };
+
+ /** The greeting in the person's language and with their name, and the bots already here, while it is still the last
+ * thing in the chat. */
function refreshGreeting(): void {
const greeting = state?.greeting;
- const bot = deps.chief();
- if (!greeting || !bot) return;
+ const bot = greeter() ? deps.store.bot(greeter()!) : deps.chief();
+ if (!greeting || !bot || (state!.movedInAt && now() - state!.startedAt > FIRST_DAY_MS)) return;
const rows = deps.store.messagesFor(greeting.threadId);
if (rows.at(-1)?.id !== greeting.messageId) return;
- const text = greetingMessage(bot, deps.person(), deps.language()).text!;
+ const text = greetingMessage(bot, deps.person(), deps.language(), movedIn() ? arrivals() : []).text!;
if (rows.at(-1)!.text !== text) deps.store.patchMessage(greeting.threadId, greeting.messageId, { text });
}
async function offer(): Promise<void> {
- if (!state || state.offeredAt || busy) return;
+ if (!state || state.offeredAt || busy || movedIn()) return;
+ if (deps.moving?.()) {
+ offerHeld = true;
+ return;
+ }
+ offerHeld = false;
const place = home();
if (!place || !deps.apps.reachable(place.bot) || deps.threadBusy(place.bot.id, place.threadId)) return;
busy = true;
try {
const connected = await deps.apps.connected().catch(() => null);
- if (!state || state.offeredAt || deps.threadBusy(place.bot.id, place.threadId)) return;
+ if (!state || state.offeredAt || movedIn() || deps.threadBusy(place.bot.id, place.threadId)) return;
const missing = LOOK_APPS.filter((app) => connected?.[app] !== true);
const there = LOOK_APPS.filter((app) => connected?.[app] === true);
if (!missing.length) {
@@ -250,7 +320,7 @@ export function createFirstHour(deps: FirstHourDeps) {
return;
}
const cards = await Promise.all(missing.map(async (slug) => ({ slug, ...(await deps.apps.card(slug).catch(() => ({ label: APP_NAME[slug], description: "" }))) })));
- if (!state || state.offeredAt || deps.threadBusy(place.bot.id, place.threadId)) return;
+ if (!state || state.offeredAt || movedIn() || deps.threadBusy(place.bot.id, place.threadId)) return;
const key = `${FIRST_HOUR_OFFER_KEY}${randomUUID()}`;
say(place.bot, place.threadId, words().connect);
for (const card of cards) {
@@ -280,11 +350,20 @@ export function createFirstHour(deps: FirstHourDeps) {
}
async function startLook(): Promise<void> {
- if (!state || state.lookStartedAt || state.lookSkipped || look) return;
+ if (!state || state.lookStartedAt || state.lookSkipped || look || (state.lookRetryAt && now() < state.lookRetryAt)) return;
const place = home();
if (!place) return;
- if (deps.threadBusy(place.bot.id, place.threadId)) {
- if (now() - (state.firstAppAt ?? now()) > LOOK_WAIT_MS) mark({ lookSkipped: "failed" });
+ if (deps.threadBusy(place.bot.id, place.threadId) || deps.moving?.()) {
+ if (now() - (state.firstAppAt ?? now()) > LOOK_WAIT_MS) {
+ console.warn(`first hour: the first look gave up waiting: its chat stayed busy, or a move into this Cloud ran, for ${Math.round((now() - state.firstAppAt!) / MINUTE)} minutes after an app came in`);
+ mark({ lookSkipped: "failed", lookFailure: "busy", lookRetryAt: undefined });
+ }
+ return;
+ }
+ if (state.lookSaid !== undefined && written(place.threadId) > state.lookSaid) {
+ // The person has moved on in that chat: a look arriving now would land in the middle of it.
+ console.warn("first hour: the first look is not tried again: the person wrote in its chat since it failed");
+ mark({ lookSkipped: "failed", lookRetryAt: undefined });
return;
}
const started = now();
@@ -292,29 +371,63 @@ export function createFirstHour(deps: FirstHourDeps) {
mark({ lookStartedAt: started });
const prompt = lookPrompt({ apps: state.apps ?? [], ...(firstName(deps.person()) ? { name: firstName(deps.person()) } : {}), language: deps.language() });
try {
- await deps.startTurn(place.bot.id, prompt, { threadId: place.threadId, cardContinuation: true, onSettled: (outcome) => lookSettled(place.bot, place.threadId, started, outcome.ok) });
+ await deps.startTurn(place.bot.id, prompt, { threadId: place.threadId, cardContinuation: true, onSettled: (outcome) => lookSettled(place.bot, place.threadId, started, outcome) });
} catch (error) {
look = null;
- const code = (error as { code?: unknown } | null)?.code;
+ const fields = (error ?? {}) as { code?: unknown; status?: unknown };
+ const code = typeof fields.code === "string" ? fields.code : fields.status === 404 ? "404" : undefined;
if (code === "thread_busy" || code === "thread_limit") mark({ lookStartedAt: undefined });
- else {
- console.warn(`first hour: the first look could not start: ${error instanceof Error ? error.message : String(error)}`);
- lookSettled(place.bot, place.threadId, started, false);
- }
+ else lookMissed(place.bot, place.threadId, started, { path: "start", ...(code ? { code } : {}), cause: error instanceof Error ? error.message : String(error) });
}
}
- function lookSettled(bot: BotRecord, threadId: string, started: number, ok: boolean): void {
+ function lookSettled(bot: BotRecord, threadId: string, started: number, outcome: HostTurnResult): void {
+ const drafted = look?.drafts ?? 0;
look = null;
if (!state || state.firstLookAt || state.lookSkipped) return;
- const replied = ok && deps.store.activePath(threadId).some((message) => message.role === "bot" && message.kind === "text" && message.at >= started && Boolean(message.text?.trim()));
+ const since = deps.store.activePath(threadId).filter((message) => message.role === "bot" && message.at >= started);
+ const replied = outcome.ok && since.some((message) => message.kind === "text" && Boolean(message.text?.trim()));
if (replied) {
- mark({ firstLookAt: now() });
+ mark({ firstLookAt: now(), lookRetryAt: undefined });
deps.notify(bot, threadId, words().firstLookReady);
- } else {
- mark({ lookSkipped: "failed" });
- if (!deps.threadBusy(bot.id, threadId)) say(bot, threadId, words().connected);
+ soon(afterLook);
+ return;
}
+ // outcome.text is the bot's own reply when the turn ended well: only a failed turn's cause, in the system's words, is kept.
+ lookMissed(bot, threadId, started, { path: "settled", ok: outcome.ok, replied: false, stalled: Boolean(outcome.stalled), stopReason: outcome.failure?.stopReason ?? null,
+ ...(outcome.ok ? {} : { cause: outcome.failure?.text || outcome.text }), rows: [...new Set(since.map((message) => message.kind))], drafted,
+ stopped: Boolean(deps.stopped?.(threadId)) || since.some((message) => message.tool?.name === PERSON_STOPPED_TURN_NAME) });
+ }
+
+ /** A try of the first look ended without one: logged with how, then tried once more after a short wait, unless the bot
+ * is paused, held or gone. After the last try the person hears which apps are in and how to get the look. */
+ function lookMissed(bot: BotRecord, threadId: string, started: number, miss: LookMiss): void {
+ if (!state) return;
+ if (miss.stopped) {
+ // The person stopped it: never started again, and nothing said about it.
+ console.warn("first hour: the person stopped the first look; it is not tried again");
+ mark({ lookTries: Math.min(LOOK_TRIES, (state.lookTries ?? 0) + 1), lookFailure: "stopped", lookSkipped: "failed", lookRetryAt: undefined });
+ return;
+ }
+ // A try that failed while a move into this Cloud ran is not counted: the move, not the look, was the trouble.
+ const counted = !deps.moving?.();
+ const tries = Math.min(LOOK_TRIES, (state.lookTries ?? 0) + (counted ? 1 : 0));
+ const failure = miss.path === "start" ? "start" : miss.stalled ? "stalled" : miss.ok ? "no-reply" : "error";
+ const lasting = miss.code !== undefined && LASTING.has(miss.code);
+ // A second try would start its drafts over: one that already wrote a draft is not repeated.
+ const last = lasting || (miss.drafted ?? 0) > 0 || (counted && tries >= LOOK_TRIES);
+ console.warn([`first hour: the first look failed (try ${tries} of ${LOOK_TRIES}${last ? ", the last" : `, again in ${LOOK_RETRY_MS / 1000} s`}${counted ? "" : ", not counted: a move is running"}):`,
+ `path=${miss.path}`, ...(miss.path === "settled" ? [`ok=${miss.ok}`, `replied=${miss.replied}`, `stalled=${miss.stalled}`, `stop=${miss.stopReason ?? "-"}`] : []),
+ `code=${miss.code ?? "-"}`, `sinceBoot=${started - state.startedAt}`, `sinceApp=${started - (state.firstAppAt ?? started)}`, `ms=${now() - started}`,
+ `apps=${(state.apps ?? []).join(",") || "-"}`, ...(miss.rows ? [`rows=${miss.rows.join(",") || "-"}`, `drafts=${miss.drafted ?? 0}`] : []), `cause=${JSON.stringify(causeLine(miss.cause) ?? "-")}`].join(" "));
+ if (!last) {
+ mark({ ...(tries ? { lookTries: tries } : {}), lookFailure: failure, lookStartedAt: undefined, lookRetryAt: now() + LOOK_RETRY_MS, lookSaid: written(threadId) });
+ return;
+ }
+ mark({ ...(tries ? { lookTries: tries } : {}), lookFailure: failure, lookSkipped: "failed", lookRetryAt: undefined });
+ const w = words();
+ // A paused, held or gone bot has its own notice: "ask me later" would only be refused again.
+ if (!lasting && !deps.threadBusy(bot.id, threadId)) say(bot, threadId, w.lookLater(w.list((state.apps ?? []).map((app) => APP_NAME[app])), state.apps?.length ?? 0));
soon(afterLook);
}
@@ -385,6 +498,11 @@ export function createFirstHour(deps: FirstHourDeps) {
if (!state || state.recapAt) return;
const at = now(), zone = deps.timeZone();
if (at - state.startedAt < RECAP_AFTER_MS || localDate(at, zone) === localDate(state.startedAt, zone) || localMinutes(at, zone) < clockMinutes(MORNING)) return;
+ if (state.movedInAt) {
+ // The recap tells an inbox's first day: someone who came for their own bots never had one.
+ mark({ recapAt: at, recapQuiet: true });
+ return;
+ }
const place = home();
if (!place || deps.threadBusy(place.bot.id, place.threadId) || personUnanswered(place.threadId)) return;
const counts = tally();
@@ -413,6 +531,8 @@ export function createFirstHour(deps: FirstHourDeps) {
if (!state) return;
if (look && now() > look.until) look = null;
const place = home();
+ if (!state.offeredAt && state.greeting && now() - state.startedAt <= FIRST_DAY_MS && others().length) refreshGreeting();
+ if (offerHeld && !deps.moving?.()) void offer();
if (!state.offeredAt && state.firstMessageAt && place && answered(place.threadId, state.firstMessageAt)) void offer();
if (!state.phonePairedAt && deps.phones() > 0) phonePaired();
if (state.firstAppAt && !state.lookStartedAt && !state.lookSkipped) void startLook();
@@ -430,7 +550,7 @@ export function createFirstHour(deps: FirstHourDeps) {
if (state || existsSync(file)) return;
const place = home();
const first = place ? deps.store.messagesFor(place.threadId).find((message) => message.role === "bot") : undefined;
- state = { version: 1, startedAt: now(), ...(place && first ? { greeting: { threadId: place.threadId, messageId: first.id } } : {}) };
+ state = { version: 1, startedAt: now(), ...(place ? { chiefId: place.bot.id } : {}), ...(place && first ? { greeting: { threadId: place.threadId, messageId: first.id } } : {}) };
save();
deps.welcomeDone();
if (place) {
@@ -507,9 +627,22 @@ export function createFirstHour(deps: FirstHourDeps) {
prompt(botId: string, threadId: string): string {
const place = home();
if (!state || !place || place.bot.id !== botId || place.threadId !== threadId || now() - state.startedAt > FIRST_DAY_MS) return "";
+ // A Chief that arrived by a move has its own history with the person: the first day is the greeting Chief's.
+ if (greeter() && greeter() !== botId) return "";
const name = firstName(deps.person());
+ const theirs = name ? `${name}'s` : "the person's";
+ if (state.movedInAt) {
+ const arrived = arrivals();
+ const who = arrived.length ? `Their own ${arrived.length === 1 ? "bot" : "bots"} ${arrived.join(", ")} ${arrived.length === 1 ? "is" : "are"}` : "Their own bots are";
+ return [
+ ` This is ${theirs} first day with you on their new Cloud. ${who} here too, moved from their computer or already made, and keep${arrived.length === 1 ? "s" : ""} working while their computer is off: that is mostly what they came for. You greeted them${arrived.length ? " and said so" : ""}.`,
+ "Help with what they ask, and point them to their own bots for those bots' work. Keep replies short and concrete.",
+ "Don't offer Gmail, Google Calendar or a morning brief unasked. If they bring up their email or calendar, you may offer to connect Gmail and Google Calendar then.",
+ "Anything that would send, accept, decline or delete waits for them: write drafts and ask first.",
+ ].join(" ");
+ }
return [
- ` This is ${name ? `${name}'s` : "the person's"} first day with you on their new Cloud. You greeted them and asked one question: what they want off their plate. Treat the answer as your first job: say in a line or two how you'll take it on, and do the first part now when you can. Keep replies short and concrete.`,
+ ` This is ${theirs} first day with you on their new Cloud. You greeted them and asked one question: what they want off their plate. Treat the answer as your first job: say in a line or two how you'll take it on, and do the first part now when you can. Keep replies short and concrete.`,
"The app itself offers Gmail and Google Calendar in this chat, with the reason, right after your first reply: never call COMPOSIO_MANAGE_CONNECTIONS for them and don't ask the person to connect them.",
`Their morning brief is on: every morning at ${MORNING.replace(/^0/, "")} their time you send a brief of what needs them.`,
"Anything that would send, accept, decline or delete waits for them: write drafts and ask first.",
@@ -521,12 +654,13 @@ export function createFirstHour(deps: FirstHourDeps) {
const since = (time: number | undefined) => (time === undefined ? undefined : Math.max(0, time - s.startedAt));
const ms: FirstHourReport["ms"] = {};
const times = { seen: s.seenAt, firstMessage: s.firstMessageAt, offered: s.offeredAt, firstApp: s.firstAppAt, declined: s.declinedAt, firstLook: s.firstLookAt,
- briefOn: s.briefOnAt, phoneOffered: s.phoneOfferedAt, phonePaired: s.phonePairedAt, recap: s.recapAt };
+ briefOn: s.briefOnAt, phoneOffered: s.phoneOfferedAt, phonePaired: s.phonePairedAt, recap: s.recapAt, movedIn: s.movedInAt };
for (const [key, time] of Object.entries(times) as Array<[keyof FirstHourReport["ms"], number | undefined]>) {
const value = since(time);
if (value !== undefined) ms[key] = value;
}
- return { startedAt: s.startedAt, ms, apps: s.apps ?? [], ...(s.firstLookAt ? { look: "delivered" as const } : s.lookSkipped ? { look: s.lookSkipped } : {}) };
+ return { startedAt: s.startedAt, ms, apps: s.apps ?? [], ...(s.firstLookAt ? { look: "delivered" as const } : s.lookSkipped ? { look: s.lookSkipped } : {}),
+ ...(s.lookFailure ? { lookFailure: s.lookFailure } : {}), ...(s.lookTries ? { lookTries: s.lookTries } : {}) };
},
tally,
tick,
diff --git a/server/index.ts b/server/index.ts
index 51bc477fac..c8f555fa1b 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -8767,7 +8767,7 @@ if (CLOUD_HOME && CLOUD_OWNER_KEY && cloudRoutineAuthors) {
ownerOnlyCache.clear();
}
// Only now: an earlier owner key is the owner's once settled.
-routines.clearFrozenResultsThreads(); proactive.ensureWatch(); startFirstHour({ hooks: firstHourHooks, fresh: firstHourFresh, store, bus, cfg, dataDir: DATA_DIR, proactive, briefOn: () => proactive.briefOn(), ensureBrief: () => { proactive.ensureWatch(); }, composio, sessions, phones: () => phones.paired(), routines: () => routines, mainThread: botMainThread, threadBusy, startTurn, notify, wrote: markTaskContextExternallyUpdated, stale: shouldIgnoreProviderEvent, welcomeDone: () => { adminActorScope.exit(() => saveConfig(welcomeDonePatch(cfg.onboarding))); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } });
+routines.clearFrozenResultsThreads(); proactive.ensureWatch(); startFirstHour({ hooks: firstHourHooks, fresh: firstHourFresh, store, bus, cfg, dataDir: DATA_DIR, proactive, stopped: (threadId) => personStops.stopped(threadId, undefined), briefOn: () => proactive.briefOn(), ensureBrief: () => { proactive.ensureWatch(); }, composio, sessions, phones: () => phones.paired(), routines: () => routines, mainThread: botMainThread, threadBusy, startTurn, notify, wrote: markTaskContextExternallyUpdated, stale: shouldIgnoreProviderEvent, welcomeDone: () => { adminActorScope.exit(() => saveConfig(welcomeDonePatch(cfg.onboarding))); Object.assign(cfg, loadConfig()); broadcast({ kind: "config", ...configStatus() }); } });
orgLibrary = new OrgLibrary({
dataDir: DATA_DIR,
store,
diff --git a/server/routes/cloud-send.ts b/server/routes/cloud-send.ts
index 420fe848f3..1917008071 100644
--- a/server/routes/cloud-send.ts
+++ b/server/routes/cloud-send.ts
@@ -84,6 +84,8 @@ export function createCloudSendRoutes(deps: CloudSendRouteDeps): RouteHandler {
const { req, res, path, method, url, json, readBody } = ctx;
if (path !== "/api/cloud-send" && !path.startsWith("/api/cloud-send/")) return PASS;
const home = deps.cloudHome === true || deps.ownHome?.(ctx.auth) === true;
+ // A move into this Cloud starts with its owner's computer asking here: a new Cloud's first hour holds its inbox offer.
+ if (move && home && move.owner(ctx.auth)) leases.touched();
const scoped = deps.scope?.(ctx.auth) ?? null;
// Downstream handlers rely on this outer wrapper as the sole gate: team refusal rejects callers unless
// scoped to a specific bot move session.