diff --git a/apps/cloud-service/src/home-start.test.ts b/apps/cloud-service/src/home-start.test.ts index aa914e0d39..2cac06f94e 100644 --- a/apps/cloud-service/src/home-start.test.ts +++ b/apps/cloud-service/src/home-start.test.ts @@ -2,7 +2,7 @@ import { execFileSync } from "node:child_process"; import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { afterEach, expect, it } from "vitest"; +import { afterEach, describe, expect, it } from "vitest"; import { CLOUD_HOME } from "../../../electron/legacy-names.mjs"; import { homeControlScript } from "./home.ts"; @@ -38,18 +38,20 @@ ${answersAfterRestart ? `[ -f ${dir}/restarted ]` : `[ "$n" -ge ${answersOn} ]`} return { out: out.trim(), code, restarted: existsSync(join(dir, "restarted")), probes: Number(readFileSync(join(dir, "probes"), "utf8")) }; } -it("waits for a resumed home that is slow to answer instead of restarting it", () => { - const run = runStart({ active: true, answersOn: 3 }); - expect(run).toMatchObject({ out: "started", code: 0, restarted: false, probes: 3 }); -}); +describe.skipIf(process.platform === "win32")("omb-home start", () => { + it("waits for a resumed home that is slow to answer instead of restarting it", () => { + const run = runStart({ active: true, answersOn: 3 }); + expect(run).toMatchObject({ out: "started", code: 0, restarted: false, probes: 3 }); + }); -it("starts a home that is not running", () => { - const run = runStart({ active: false, answersAfterRestart: true }); - expect(run).toMatchObject({ out: "started", code: 0, restarted: true }); -}); + it("starts a home that is not running", () => { + const run = runStart({ active: false, answersAfterRestart: true }); + expect(run).toMatchObject({ out: "started", code: 0, restarted: true }); + }); -it("restarts a running home that never answers within its patience", () => { - const run = runStart({ active: true, answersAfterRestart: true, patience: 2 }); - expect(run).toMatchObject({ out: "started", code: 0, restarted: true }); - expect(run.probes).toBeGreaterThan(1); + it("restarts a running home that never answers within its patience", () => { + const run = runStart({ active: true, answersAfterRestart: true, patience: 2 }); + expect(run).toMatchObject({ out: "started", code: 0, restarted: true }); + expect(run.probes).toBeGreaterThan(1); + }); }); diff --git a/apps/mobile/store/app-store.json b/apps/mobile/store/app-store.json index 29c66cb6c1..7218cf0134 100644 --- a/apps/mobile/store/app-store.json +++ b/apps/mobile/store/app-store.json @@ -15,7 +15,7 @@ "promotionalText": "Your AI bots keep working on your computer while you are out. Text them, approve what matters, and get a ping when the work is done.", "supportUrl": "https://dusk.bot/support", "marketingUrl": "https://dusk.bot", - "whatsNew": "A more native iPhone feel: native controls, sheets and settings. Ask Siri or Shortcuts to message or call a bot. Calls work with bots on your dusk cloud or your own server too. Linking your computer finishes even when its address is down, you can stay signed in to more than one account, and fields in sheets stay above the keyboard. The app opens about twice as fast, you can reorder your chats, and text no longer grows each time you come back. Lots of small fixes." + "whatsNew": "Share to a bot from any app with the share sheet. Notifications show what the bot said and its picture, and tapping one opens that chat. Bots can read their replies aloud in their own voice. The app starts faster, the keyboard no longer leaves a gap, pairing by QR code is more reliable, and photos that cannot be attached now say why. Lots of small fixes." }, "reviewNotes": "WHAT THE APP IS\ndusk bot for iPhone is free, with no in-app purchases. It is the remote control for a person's own AI bots. The bots run on the person's own computer or server, or on a dusk cloud computer we host for them, and do their work there. The phone sends messages to those bots, shows their replies and lets the person approve actions. Nothing runs on the phone except the interface, which is bundled in the app (no web content is loaded from a server).\n\nPairing your own computer needs no account: the first screen offers \"Scan a QR code\" and \"Enter a code\". Only a dusk cloud needs sign-in, through the \"Have a dusk cloud? Log in\" link. The demo account below has a dusk cloud with a ready demo bot called Sunny, so you can use everything without a computer of your own.\n\nDEMO ACCOUNT\nEmail: [REVIEW EMAIL]\nSign-in code: [REVIEW CODE, 8 digits, fixed for this account; no email is sent]\n\nSTEPS\n1. Launch the app and tap \"Have a dusk cloud? Log in\" at the bottom.\n2. Enter the review email, tap \"Send code\", enter the code above and tap \"Sign in\". The app opens \"Demo Cloud\" (if it shows \"Pick a cloud\", tap \"Demo Cloud\").\n3. The home screen shows \"dusk bot\" (pinned) and \"Sunny\". Tap Sunny to open the chat.\n4. Type a message, for example \"Give me three ideas for a quick dinner\", and send it.\n5. Before the first message goes out, the app shows \"Before you chat\": who receives what you write (the computer running the bots, the AI they use, connected apps, our relay). Tap \"Allow\". \"Not now\" keeps the app usable for reading and settings.\n6. Sunny replies within a few seconds. If the cloud computer was asleep after a long idle time, the first reply can take up to a minute while it wakes.\n7. Long-press a reply and tap \"Report this reply\" to report it.\n8. Tap the profile button (top left) for Settings: appearance, notifications, privacy policy, terms, help and \"Contact us\".\n9. Account deletion: open Settings, scroll to the bottom, tap \"Delete account\", then \"Delete my account\". It deletes the account right away and revokes Sign in with Apple. Please try this last: it removes the demo account and its cloud from the app.\n\nNATIVE FEATURES\nCamera QR pairing (our own AVFoundation scanner), Keychain storage of the pairing, Sign in with Apple in the system sheet, dictation (speech recognition runs on the iPhone where supported), push notifications for replies and approvals, haptics, the system share sheet, an offline outbox that sends when the connection returns, and a local network connection to the person's own computer on the same Wi-Fi.\n\nNOTES\n- Purchases (3.1.1): the app is free, sells nothing, and shows no prices, plans, upgrade buttons or links to buy. dusk cloud is not on sale today (our website has a waitlist). The demo account's cloud was set up by us at no cost.\n- Sign-in (4.8): where Google or X sign-in is offered, Sign in with Apple is offered first. Email with a one-time code always works.\n- Permissions: camera only for the pairing QR code and photos you choose to attach; microphone and speech recognition only while you dictate a message or talk with a bot on a call; local network only to reach your own computer.\n- AI (5.1.2): replies come from the AI provider connected where the bots run (for the demo cloud, a DeepSeek model through OpenRouter, paid by us). The app asks before anything is sent and names who receives it.\n- Chats are private to the person; there is no public or person-to-person content.", "ageRating": { diff --git a/electron/app-permissions.mjs b/electron/app-permissions.mjs index 7a43fab036..faf68a4c99 100644 --- a/electron/app-permissions.mjs +++ b/electron/app-permissions.mjs @@ -73,10 +73,10 @@ export function remoteClipboardWriteAllowed(permission, requestingUrlOrOrigin, a * homeOrigin?: () => string | null }} context * Every getter is read per request, so a sign-out or server switch withdraws access at once. `homeOrigin`: My Cloud * once the person's bots moved there (home-window.mjs), whose page alone may show notifications besides this - * computer's and the active remote server's. `systemNotifications`: false on a Mac, where no page may post one. + * computer's and the active remote server's. */ export function appPermissionHandlers({ rendererOrigin, mainContents, cloudHomeOrigin, cloudHomeRestoring = () => null, activeRemoteOrigin = () => null, - activeRemoteMicrophone = () => false, askRemoteMicrophone = () => null, homeOrigin = () => null, systemNotifications = true }) { + activeRemoteMicrophone = () => false, askRemoteMicrophone = () => null, homeOrigin = () => null }) { // Notifications for the main window's main frame on `origin`: My Cloud as home, or the remote server the person // switched to (Settings → Notifications there has no browser site settings to fall back on). // Fullscreen too, so a chat video's own fullscreen button works there (it still needs the person's click). @@ -93,13 +93,13 @@ export function appPermissionHandlers({ rendererOrigin, mainContents, cloudHomeO Boolean(contents) && contents === mainContents() && (remoteClipboardWriteAllowed(permission, requesting, activeRemoteOrigin(), details) || remoteClipboardWriteAllowed(permission, requesting, cloudHomeOrigin(), details)); - const allowed = (contents, permission, requesting, details) => (permission !== "notifications" || systemNotifications) && ( + const allowed = (contents, permission, requesting, details) => appPermissionAllowed(permission, requesting, rendererOrigin(), details) || (asksAsCloud(contents, permission, requesting, details) && mainFrameMicrophoneAllowed(permission, requesting, cloudHomeOrigin(), details)) || (asksAsRemote(contents, permission, requesting, details) && activeRemoteMicrophone() === true) || clipboardWrite(contents, permission, requesting, details) || notifiesAs(homeOrigin(), contents, permission, requesting, details) || - notifiesAs(activeRemoteOrigin(), contents, permission, requesting, details)); + notifiesAs(activeRemoteOrigin(), contents, permission, requesting, details); return { // Only a request may wait (Electron answers through the callback); the rule runs again after any wait. request: (contents, permission, callback, details) => { diff --git a/electron/mac-permissions.mjs b/electron/mac-permissions.mjs index 8b4e9442b5..bdc21c378b 100644 --- a/electron/mac-permissions.mjs +++ b/electron/mac-permissions.mjs @@ -1,6 +1,6 @@ // The macOS permissions a bot needs to use this Mac (Accessibility, Screen Recording), read and asked for from the first -// run. Reading never prompts; only `request` does, one permission at a time. Notifications are not among them: the app -// never posts one on a Mac. +// run. Reading never prompts; only `request` does, one permission at a time. Notifications are not among them: macOS asks +// for those itself the first time a bot's notification is shown. export const MAC_PERMISSIONS = Object.freeze(["accessibility", "screen"]); diff --git a/electron/main.mjs b/electron/main.mjs index 62435a2fd3..dd31d45d00 100644 --- a/electron/main.mjs +++ b/electron/main.mjs @@ -1,7 +1,7 @@ import { carryLegacySafeStorageKey, DATA_DIR_NAMES, dataDirFor, devAppName, fromLegacyLink, LEGACY } from "./legacy-names.mjs"; import { syncHookOrigin } from "./hook-origin.mjs"; import { createCloudGone } from "./cloud-gone.mjs"; -import { app, autoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, net, Notification as ElectronNotification, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron"; +import { app, autoUpdater, BrowserWindow, Tray, WebContentsView, clipboard, desktopCapturer, dialog, globalShortcut, ipcMain, Menu, nativeImage, net, Notification, powerMonitor, powerSaveBlocker, safeStorage, screen, session, shell, systemPreferences, utilityProcess, nativeTheme } from "electron"; import { createRequire } from "node:module"; import { randomBytes, randomUUID } from "node:crypto"; import fs from "node:fs"; @@ -37,8 +37,7 @@ import { createBrowsersFlush, installSessionEndFlush } from "./browser-flush.mjs import { serverChildLaunch } from "./server-child-launch.mjs"; import { answerHarnessProxy } from "./harness-proxy.mjs"; import { savedVpsStartupTarget, startPackagedAlongsideVps, waitForLocalStartup } from "./saved-vps-startup.mjs"; import { packageUrlFromCommandLine, packageUrlFromDeepLink } from "./package-link.mjs"; -import { chatLinkFrom, chatLinkFromCommandLine } from "./chat-link.mjs"; import { createSlackOAuthLinks } from "./slack-link.mjs"; import { installDesktopNotifications } from "./desktop-notifications.mjs"; import { systemNotification, systemNotificationsAllowed } from "./system-notifications.mjs"; -const Notification = systemNotification(ElectronNotification); +import { chatLinkFrom, chatLinkFromCommandLine } from "./chat-link.mjs"; import { createSlackOAuthLinks } from "./slack-link.mjs"; import { installDesktopNotifications } from "./desktop-notifications.mjs"; import { createOrganizationEntry, isOrganizationDeepLink, takeOrganizationDeepLink, organizationRestartIntent, withOrganizationRestartIntent, withoutOrganizationRestartIntent } from "./organization-entry.mjs"; import { FRAME_BY_DEFAULT, widenedBounds, windowBackground, windowChromeOptions } from "./window-chrome.mjs"; import { createAllWindowsClosedQuit } from "./window-all-closed.mjs"; @@ -3515,7 +3514,6 @@ app.whenReady().then(async () => { activeRemoteMicrophone: () => activeEnvironment(environmentsState)?.microphone === true, askRemoteMicrophone, homeOrigin: () => homeWindow.placeOrigin(), - systemNotifications: systemNotificationsAllowed(), }); startDesktopErrorReporting({ app, prefs: desktopPrefs }); if (app.isPackaged) appImageMenuEntry.sync(); if (!app.isPackaged) startDemoUpdates(); else startAppUpdates(createUpdateNotice({ request: localServerRequest, open: url => void shell.openExternal(url), memory: jsonFile(path.join(app.getPath("userData"), "update-notice.json")), held: noticePolicy().held, log: slog, notify: ({ title, body, click }) => { if (!Notification.isSupported()) return; const note = new Notification({ title, body }); note.on("click", click); note.show(); } })); session.defaultSession.setPermissionRequestHandler(appPermissions.request); session.defaultSession.setPermissionCheckHandler(appPermissions.check); diff --git a/electron/system-notifications.mjs b/electron/system-notifications.mjs deleted file mode 100644 index a9d0dbe3cf..0000000000 --- a/electron/system-notifications.mjs +++ /dev/null @@ -1,21 +0,0 @@ -// The desktop app on a Mac never posts system notifications: the dock, the island and the unread dots carry them. - -/** @param {string} platform */ -export function systemNotificationsAllowed(platform = process.platform) { - return platform !== "darwin"; -} - -/** - * Electron's Notification where the app may post one; on a Mac a stand-in that is never supported, so every caller's - * `isSupported()` check turns it away. - * @template T - * @param {T} Notification - * @param {string} platform - * @returns {T} - */ -export function systemNotification(Notification, platform = process.platform) { - if (systemNotificationsAllowed(platform)) return Notification; - function Silenced() { throw new Error("system notifications are off on macOS"); } - Silenced.isSupported = () => false; - return /** @type {T} */ (/** @type {unknown} */ (Silenced)); -} diff --git a/electron/system-notifications.node-test.mjs b/electron/system-notifications.node-test.mjs deleted file mode 100644 index ef8798c3a2..0000000000 --- a/electron/system-notifications.node-test.mjs +++ /dev/null @@ -1,61 +0,0 @@ -import assert from "node:assert/strict"; -import test from "node:test"; -import { appPermissionHandlers } from "./app-permissions.mjs"; -import { createAddedCloudNotice } from "./cloud-rail.mjs"; -import { createCloudReadyNotice } from "./cloud-buy.mjs"; -import { installDesktopNotifications } from "./desktop-notifications.mjs"; -import { systemNotification, systemNotificationsAllowed } from "./system-notifications.mjs"; - -class Posted { - static shown = []; - static isSupported() { return true; } - constructor(options) { this.options = options; } - on() { return this; } - show() { Posted.shown.push(this.options); } - close() {} -} - -test("a Mac never gets a system notification; Windows and Linux keep theirs", () => { - assert.equal(systemNotificationsAllowed("darwin"), false); - assert.equal(systemNotificationsAllowed("win32"), true); - assert.equal(systemNotificationsAllowed("linux"), true); - assert.equal(systemNotification(Posted, "win32"), Posted); - const mac = systemNotification(Posted, "darwin"); - assert.equal(mac.isSupported(), false); - assert.throws(() => new mac({ title: "x" })); -}); - -test("every main-process notice turns away on a Mac", async () => { - Posted.shown = []; - const Notification = systemNotification(Posted, "darwin"); - const handlers = new Map(); - const contents = { isDestroyed: () => false, isLoadingMainFrame: () => false, getURL: () => "http://127.0.0.1:8799/", mainFrame: {}, send() {} }; - const win = { isDestroyed: () => false, webContents: contents }; - installDesktopNotifications({ - ipcMain: { handle: (channel, handler) => handlers.set(channel, handler), on() {} }, - Notification, nativeImage: { createFromBuffer: () => ({ isEmpty: () => true }) }, fetch: async () => ({ ok: false }), - window: () => win, mayNotify: () => true, reveal() {}, openPlace() {}, - }); - const shown = await handlers.get("desktop-notifications:show")({ sender: contents, senderFrame: { ...contents.mainFrame, url: "http://127.0.0.1:8799/" } }, { title: "Nova", body: "hi", botId: "b1", threadId: "t1" }); - assert.equal(shown, false); - const ready = { status: "connected", checkout: { startedAt: 1 }, machine: { status: "ready" } }; - const added = { status: "connected", adding: { cloudId: "c1", done: false }, clouds: [{ id: "c1", name: "Cloud", status: "ready", origin: "https://c1.example" }] }; - const notices = (N) => [ - createCloudReadyNotice({ Notification: N, focused: () => false, sheetOpen: () => false, name: () => "Cloud", open() {} })(ready), - createAddedCloudNotice({ Notification: N, focused: () => false, sheetOpen: () => false, open() {} })(added), - ]; - assert.deepEqual(notices(Notification), [false, false]); - assert.deepEqual(Posted.shown, []); - assert.deepEqual(notices(systemNotification(Posted, "linux")), [true, true]); - assert.equal(Posted.shown.length, 2); -}); - -test("a page may not post one either on a Mac", () => { - const main = { id: "main" }; - const ask = (systemNotifications) => { - const handlers = appPermissionHandlers({ rendererOrigin: () => "http://127.0.0.1:8799", mainContents: () => main, cloudHomeOrigin: () => null, systemNotifications }); - return handlers.check(main, "notifications", "http://127.0.0.1:8799", { isMainFrame: true }); - }; - assert.equal(ask(true), true); - assert.equal(ask(false), false); -}); diff --git a/server/automatic-recovery.e2e.test.ts b/server/automatic-recovery.e2e.test.ts index e0dfcccce3..6d621a864a 100644 --- a/server/automatic-recovery.e2e.test.ts +++ b/server/automatic-recovery.e2e.test.ts @@ -322,7 +322,7 @@ it.each([ }, 90_000); // Automatic recovery never replays a prompt the engine accepted. A provider timeout that wrote, ran and asked nothing -// is the provider failover's (quota-switch.ts) instead: the message carries on the bot's own backups, said in one line. +// is the provider failover's (quota-switch.ts) instead: the message carries on the bot's own backups with no line. it("leaves a prompt the engine accepted to the provider failover, which carries it on the bot's own backups", async () => { await withRecoveryFixture({ method: "session/prompt" }, async ({ api, control, calls, backupPrompts, evidence }) => { const { bot } = await control("new-bot", "--name", "Accepted prompt"); @@ -339,8 +339,9 @@ it("leaves a prompt the engine accepted to the provider failover, which carries const { messages } = await control("messages", "--bot", bot.id, "--task", threadId, "--limit", "30"); evidence.push({ messages }); expect(messages.some((message: any) => message.tool?.name?.startsWith("recovery:"))).toBe(false); - expect(messages.filter((message: any) => /^notice: continuing on .+ did not answer$/.test(message.tool?.name ?? ""))).toHaveLength(2); - expect(messages.findLast((message: any) => message.role === "bot" && message.kind === "text")?.text).toBe("hello from fake claude"); + expect(messages.filter((message: any) => message.tool?.name?.startsWith("notice:"))).toEqual([]); + const asked = messages.findIndex((message: any) => message.role === "user" && message.text === "ACCEPTED_PROMPT_4K"); + expect(messages.slice(asked + 1).filter((message: any) => message.role === "bot" && message.kind === "text").map((message: any) => message.text)).toEqual(["hello from fake claude"]); }); }, 90_000); diff --git a/server/automation-destinations.test.ts b/server/automation-destinations.test.ts index 0e5ca5cdbb..38d561ebfc 100644 --- a/server/automation-destinations.test.ts +++ b/server/automation-destinations.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { createAutomationDestinations, type AutomationDestinationDeps } from "./automation-destinations.ts"; import { CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; -import type { Routine } from "./routines.ts"; +import type { Routine, RoutineRun } from "./routines.ts"; function world(writer: string) { const tasks = new Map([ @@ -58,11 +58,15 @@ function home(tasks: Array<{ threadId: string; title: string; archivedAt?: numbe describe("where a bot's routine works and reports", () => { const made = { id: "r", name: "Stretch", botId: "bot", sourceThreadId: "set-here" } as Routine; - const chats = [{ threadId: "set-here", title: "Planning" }, { threadId: "last-written", title: "Later" }]; - - it("reports to the starred chat, not the chat it was set in or one chosen before", () => { - expect(home(chats).routine(made, false)).toEqual({ threadId: "last-written", main: true }); - expect(home(chats).routine({ ...made, resultsThreadId: "set-here" }, false)).toEqual({ threadId: "last-written", main: true }); + const chats = [{ threadId: "set-here", title: "Planning" }, { threadId: "last-written", title: "Later" }, + { threadId: "archived", title: "Old", archivedAt: 5 }, { threadId: "a-run", title: "Run", routineRunId: "x" }]; + + it("reports to the open chat it was set in, never keeping it as a chat of its own, else to the starred chat", () => { + expect(home(chats).routine(made, false)).toEqual({ threadId: "set-here", main: true }); + expect(home(chats).routine({ ...made, resultsThreadId: "last-written" }, false)).toEqual({ threadId: "set-here", main: true }); + for (const gone of ["archived", "a-run", "deleted"]) expect(home(chats).routine({ ...made, sourceThreadId: gone }, false)).toEqual({ threadId: "last-written", main: true }); + expect(home(chats).routine({ ...made, sourceThreadId: undefined }, false)).toEqual({ threadId: "last-written", main: true }); + expect(home(chats).routine(made, true)).toEqual({ threadId: "last-written", main: true }); expect(home(chats).sourceRoom(made)).toBeUndefined(); }); @@ -74,13 +78,14 @@ describe("where a bot's routine works and reports", () => { const byThread = new Map(chats.map((task) => [task.threadId, task])); const store = { bot: () => ({ id: "bot" }), taskByThread: (_botId: string, threadId: string) => byThread.get(threadId), groupByThread: () => undefined } as unknown as AutomationDestinationDeps["store"]; const shared = createAutomationDestinations({ store, mainThread: () => "last-written", cloud: null, onePerson: () => false }); - expect(shared.routine({ ...made, resultsThreadId: "set-here" }, false)).toEqual({ threadId: "set-here" }); - expect(shared.routine(made, false)).toEqual({ threadId: "last-written", main: true }); + expect(shared.routine({ ...made, resultsThreadId: "last-written" }, false)).toEqual({ threadId: "last-written" }); + expect(shared.routine(made, false)).toEqual({ threadId: "set-here", main: true }); }); - it("on a Cloud, reports to the starred chat for the owner's routine, and to the writer's own chat for anyone else's", () => { + it("on a Cloud, reports to the chat the owner's routine was made in, else the starred chat, and to the writer's own chat for anyone else's", () => { const owners = { ...made, sourceThreadId: "person-chat", resultsThreadId: undefined } as Routine; - expect(world("owner").destinations.routine(owners, false)).toEqual({ threadId: "main", main: true }); + expect(world("owner").destinations.routine(owners, false)).toEqual({ threadId: "person-chat", main: true }); + expect(world("owner").destinations.routine({ ...owners, sourceThreadId: "guest-chat" }, false)).toEqual({ threadId: "main", main: true }); expect(world("p_someone").destinations.routine(owners, false)).toEqual({ threadId: "guest-chat" }); expect(world("p_someone").destinations.routine({ ...owners, sourceThreadId: "guest-older" }, false)).toEqual({ threadId: "guest-older" }); expect(world("p_nobody").destinations.routine(owners, false)).toBeUndefined(); @@ -111,16 +116,35 @@ describe("where a bot's run works", () => { expect(owned(true, true).runChat(run)).toBeUndefined(); }); + it("works in the open chat its routine was made in, else the starred chat", () => { + const chats = new Map([["set-here", { threadId: "set-here" }], + ["archived", { threadId: "archived", archivedAt: 5 }], ["apart", { threadId: "apart", background: true }]]); + const store = { bot: () => ({ id: "bot" }), taskByThread: (_botId: string, threadId: string) => chats.get(threadId), groupByThread: () => undefined } as unknown as AutomationDestinationDeps["store"]; + const mine = (onePerson: boolean, team = false) => createAutomationDestinations({ store, mainThread: () => "starred", cloud: null, team, onePerson: () => onePerson }); + expect(mine(true).runChat({ ...run, sourceThreadId: "set-here" })).toBe("set-here"); + expect(mine(true).runChat({ ...run, triggerSource: "manual", sourceThreadId: "set-here" })).toBe("set-here"); + for (const gone of ["archived", "apart", "deleted"]) expect(mine(true).runChat({ ...run, sourceThreadId: gone })).toBe("starred"); + expect(mine(true).runChat({ ...run, triggerSource: "webhook", sourceThreadId: "set-here" })).toBeUndefined(); + expect(mine(false).runChat({ ...run, sourceThreadId: "set-here" })).toBeUndefined(); + expect(mine(true, true).runChat({ ...run, sourceThreadId: "set-here" })).toBeUndefined(); + }); + + it("on a Cloud, joins the chat the owner's routine was made in only while no guest wrote there", () => { + expect(world("owner").destinations.runChat({ ...run, sourceThreadId: "person-chat" })).toBe("person-chat"); + expect(world("owner").destinations.runChat({ ...run, sourceThreadId: "guest-chat" })).toBe("main"); + expect(world("p_someone").destinations.runChat({ ...run, sourceThreadId: "person-chat" })).toBeUndefined(); + }); + it("on a Cloud, works in the starred chat only for the owner's routine and only while no guest wrote there", () => { expect(world("owner").destinations.runChat(run)).toBe("main"); expect(world("p_someone").destinations.runChat(run)).toBeUndefined(); expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook" })).toBeUndefined(); }); - it("on a Cloud, a wait's follow-up or a routine's hand-on joins the starred chat when set from the owner's chat, else works apart", () => { + it("on a Cloud, a wait's follow-up or a routine's hand-on joins the owner's chat that set it, else works apart", () => { expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook", eventSource: "job", resultsThreadId: "person-chat" })).toBeUndefined(); for (const eventSource of ["wait", "routine"] as const) { - expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook", eventSource, resultsThreadId: "person-chat" })).toBe("main"); + expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook", eventSource, resultsThreadId: "person-chat" })).toBe("person-chat"); expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook", eventSource, resultsThreadId: "guest-chat" })).toBeUndefined(); expect(world("owner").destinations.runChat({ ...run, triggerSource: "webhook", eventSource })).toBeUndefined(); } @@ -153,4 +177,20 @@ describe("where a routine made in a room reports", () => { expect(inRoom([room]).routine(made("room-main", "left"), false)).toEqual({ threadId: "main", main: true }); expect(inRoom([{ ...room, dm: true }]).routine(made("room-main"), false)).toEqual({ threadId: "main", main: true }); }); + + it("keeps a run from an open room apart, even one stored before it carried where it reports", () => { + const run = { target: "bot", botId: "bot", routineId: "r", triggerSource: "schedule" } as RoutineRun; + const store = { + bot: (id: string) => ({ id }), + taskByThread: () => undefined, + groupByThread: (threadId: string) => room.tasks.some((task) => task.threadId === threadId) ? room : undefined, + roomThreadOf: (threadId: string) => threadId, + groupTaskByThread: (_: string, threadId: string) => room.tasks.find((task) => task.threadId === threadId), + } as unknown as AutomationDestinationDeps["store"]; + const destinations = createAutomationDestinations({ store, mainThread: () => "main", cloud: null, onePerson: () => true }); + expect(destinations.runChat({ ...run, resultsThreadId: "room-main" })).toBeUndefined(); + expect(destinations.runChat({ ...run, sourceThreadId: "room-side" })).toBeUndefined(); + expect(destinations.runChat({ ...run, sourceThreadId: "room-old" })).toBe("main"); + expect(destinations.runChat(run)).toBe("main"); + }); }); diff --git a/server/automation-destinations.ts b/server/automation-destinations.ts index 44578c5c1b..a609699fe7 100644 --- a/server/automation-destinations.ts +++ b/server/automation-destinations.ts @@ -1,5 +1,5 @@ -// Where an automation's runs work and report: the bot's starred (main) chat, or the room a routine was made in while that -// is open. No chat is ever made for them. On a Cloud home a chat the owner writes in never gets words they did not +// Where an automation's runs work and report: the bot's chat a routine was made in while that is open, else its starred +// (main) chat, or the room a routine was made in while that is open. No chat is ever made for them. On a Cloud home a chat the owner writes in never gets words they did not // choose, so it stays theirs: a routine someone else wrote reports into that person's own chat, and an outside event's // run keeps its result in its own hidden conversation. import { CLOUD_OUTSIDE_KEY } from "./cloud-sharing.ts"; @@ -54,6 +54,11 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) { if (cloud && cloud.opener(routine.id) !== cloud.owner) return undefined; return openRoom(bot.id, routine.sourceThreadId); }; + /** The bot's own open chat a routine was made in, where it may join: on a Cloud only one no guest wrote in. */ + const sourceChat = (botId: string, threadId: string | undefined): string | undefined => { + const task = threadId ? store.taskByThread(botId, threadId) : undefined; + return task && !apartThread(task) && task.archivedAt === undefined && (!cloud || cloud.ownersChat(task.threadId)) ? task.threadId : undefined; + }; return { sourceRoom, openRoom, @@ -72,23 +77,30 @@ export function createAutomationDestinations(deps: AutomationDestinationDeps) { const chosen = !forceNew && opener !== CLOUD_OUTSIDE_KEY && routine.resultsThreadId && bot && !bot.hidden ? store.taskByThread(bot.id, routine.resultsThreadId) : undefined; // where several people use one workspace, a routine keeps the chat it was given if (chosen && !chosen.routineRunId && !cloud && deps.onePerson && !deps.onePerson()) return { threadId: chosen.threadId }; + const own = !forceNew && !deps.team && bot && !bot.hidden && (!cloud || opener === cloud.owner) ? sourceChat(bot.id, routine.sourceThreadId) : undefined; + if (own) return { threadId: own, main: true }; if (main && (!cloud || opener === cloud.owner)) return { threadId: main, main: true }; if (chosen && !chosen.routineRunId) return { threadId: chosen.threadId }; const threadId = cloud && opener !== CLOUD_OUTSIDE_KEY ? personsChat(routine.botId, opener!, routine.sourceThreadId) : undefined; return threadId ? { threadId } : undefined; }, - /** The starred chat a bot's run works in, as any turn there would, or undefined when it works apart and reports there. + /** The chat a bot's run works in, as any turn there would: the one its routine was made in while open, else the starred + * chat; or undefined when it works apart and reports there. * Security invariant: a chat's lineage and level belong to its person, so a run joins it only where it is the owner's: * off a Cloud only while nobody else uses the workspace, on a Cloud for a routine the owner wrote and a chat no guest * wrote in, never on a Team Cloud, and never for a run whose words came from outside (runWorksInChat). */ - runChat(run: Pick): string | undefined { + runChat(run: Pick): string | undefined { if (!runWorksInChat(run) || deps.team) return undefined; const bot = store.bot(run.botId); if (!bot || bot.hidden) return undefined; - if (run.resultsThreadId && !store.taskByThread(bot.id, run.resultsThreadId) && openRoom(bot.id, run.resultsThreadId)) return undefined; + // a run that reports to an open room, or was started from one, stays apart and reports there + const room = run.resultsThreadId ?? run.sourceThreadId; + if (room && !store.taskByThread(bot.id, room) && openRoom(bot.id, room)) return undefined; // the bot's own follow-up (a wait, a routine's hand-on) joins only from a chat no guest wrote in const ownWork = run.triggerSource === "webhook" && (run.eventSource === "wait" || run.eventSource === "routine"); if (cloud ? (ownWork ? !run.resultsThreadId || !cloud.ownersChat(run.resultsThreadId) : run.triggerSource === "webhook" || cloud.opener(run.routineId) !== cloud.owner) : !deps.onePerson?.()) return undefined; + const own = sourceChat(bot.id, run.sourceThreadId) ?? (ownWork ? sourceChat(bot.id, run.resultsThreadId) : undefined); + if (own) return own; const main = deps.mainThread(bot.id); return main && (!cloud || cloud.ownersChat(main)) ? main : undefined; }, diff --git a/server/automations-lifecycle.e2e.test.ts b/server/automations-lifecycle.e2e.test.ts index 4963e8ac22..045d55000c 100644 --- a/server/automations-lifecycle.e2e.test.ts +++ b/server/automations-lifecycle.e2e.test.ts @@ -53,12 +53,16 @@ it("turns schedules and webhooks back on, removes a deleted bot's automations, a const { runId } = await accepted.json() as { runId: string }; await expect.poll(async () => (await state()).runs.find((run) => run.id === runId)?.status, { timeout: 30_000 }).toBe("completed"); - // 3. A one-time schedule whose time has passed is not switched back on to run again: it says why. + // 3. A one-time schedule switches off and on before its time; once it has run it is gone, and its run stays in history. + const later = (await api("POST", "/api/routines", { name: "Later", prompt: "Remind me later.", botId: scout, schedule: { type: "once", at: Date.now() + 3_600_000 } }, 201)).routine; + expect((await api("PATCH", `/api/routines/${later.id}`, { enabled: false })).routine).toMatchObject({ enabled: false, nextRunAt: null }); + expect((await api("PATCH", `/api/routines/${later.id}`, { enabled: true })).routine).toMatchObject({ enabled: true, nextRunAt: later.schedule.at }); const once = (await api("POST", "/api/routines", { name: "Reminder", prompt: "Remind me once.", botId: scout, schedule: { type: "once", at: Date.now() + 1_000 } }, 201)).routine; - await expect.poll(async () => (await state()).routines.find((candidate) => candidate.id === once.id)?.enabled, { timeout: 30_000 }).toBe(false); await expect.poll(async () => (await state()).runs.filter((run) => run.routineId === once.id && run.status === "completed").length, { timeout: 30_000 }).toBe(1); - expect((await api("PATCH", `/api/routines/${once.id}`, { enabled: true }, 400)).error).toBe("Its time has passed. Edit it to pick a new time."); - expect((await state()).routines.find((candidate) => candidate.id === once.id)?.enabled).toBe(false); + await expect.poll(async () => (await state()).routines.some((candidate) => candidate.id === once.id), { timeout: 30_000 }).toBe(false); + expect((await state()).runs.find((run) => run.routineId === once.id)).toMatchObject({ routineName: "Reminder", status: "completed" }); + expect((await api("PATCH", `/api/routines/${once.id}`, { enabled: true }, 404)).error).toBe("no such routine"); + await api("DELETE", `/api/routines/${later.id}`); // 4. Deleting a bot from the app removes its schedules, its webhooks, their runs, and its address stops working. const before = await send(goneHook.credential.url, { lead: "Before" }); @@ -79,7 +83,8 @@ it("turns schedules and webhooks back on, removes a deleted bot's automations, a expect(readFileSync(join(server.dataDir, "routines.json"), "utf8")).toContain(oldRoutine.id); await server.start(); now = await state(); - expect(now.routines.map((candidate) => candidate.id)).toEqual(expect.arrayContaining([routine.id, once.id])); + expect(now.routines.map((candidate) => candidate.id)).toContain(routine.id); + expect(now.routines.map((candidate) => candidate.id)).not.toContain(once.id); expect(now.routines.map((candidate) => candidate.botId)).not.toContain(old); expect(now.webhooks.map((candidate) => candidate.id)).not.toContain(oldHook.webhook.id); expect(readFileSync(join(server.dataDir, "routines.json"), "utf8")).not.toContain(oldRoutine.id); diff --git a/server/chat-followups-restart.test.ts b/server/chat-followups-restart.test.ts index 97555a0014..029ac97f30 100644 --- a/server/chat-followups-restart.test.ts +++ b/server/chat-followups-restart.test.ts @@ -105,6 +105,8 @@ it("survives a real server crash: queued sends keep receipts, cancellation and u const bot = (await api("POST", "/api/bots", { name: "Durable follow-ups" }, 201)).bot; const uncertain = (await api("POST", "/api/bots", { name: "Uncertain follow-up" }, 201)).bot; const later = (await api("POST", `/api/bots/${uncertain.id}/tasks`, { title: "In-flight receipt" }, 201)).task; + // a new conversation takes the star and the main chat is never at capacity, so the first chat stays main + await api("PATCH", `/api/bots/${uncertain.id}`, { mainThreadChoice: uncertain.threadId }); const worker = (await api("POST", "/api/bots", { name: "Channel worker" }, 201)).bot; const channel = (await api("POST", "/api/groups", { name: "Durable channel", memberIds: [worker.id], @@ -147,6 +149,7 @@ it("survives a real server crash: queued sends keep receipts, cancellation and u // it must still retire the already-dispatched queue receipt exactly once. const stopped = (await api("POST", "/api/bots", { name: "Stopped follow-up" }, 201)).bot; const stoppedTask = (await api("POST", `/api/bots/${stopped.id}/tasks`, { title: "Stop this follow-up" }, 201)).task; + await api("PATCH", `/api/bots/${stopped.id}`, { mainThreadChoice: stopped.threadId }); await api("POST", `/api/bots/${stopped.id}/messages`, { threadId: stopped.threadId, text: "Hold capacity before Stop" }, 202); const stoppedBody = { threadId: stoppedTask.threadId, text: "Stop this dispatched follow-up", sendId: "stopped_bot_send_123456" }; const stoppedReceipt = await api("POST", `/api/bots/${stopped.id}/messages`, stoppedBody, 202); diff --git a/server/cloud-team-inbox.e2e.test.ts b/server/cloud-team-inbox.e2e.test.ts index 5183394c7b..8fd0040014 100644 --- a/server/cloud-team-inbox.e2e.test.ts +++ b/server/cloud-team-inbox.e2e.test.ts @@ -33,7 +33,7 @@ process.env.FAKE_CLAUDE_TEXT_LOG = dir + "/text-log.jsonl"; if (existsSync(dir + "/hang-mode")) { process.env.FAKE_CLAUDE_MODE = "hang"; process.env.FAKE_CLAUDE_RELEASE = dir + "/release"; }`; const TOKEN = `ops_fake-team-${randomBytes(8).toString("hex")}`; -type Row = { id: string; role: string; kind: string; text?: string; card?: { requestId?: string; answered?: string }; replyToId?: string; +type Row = { id: string; role: string; kind: string; text?: string; setupOffer?: true; card?: { requestId?: string; answered?: string }; replyToId?: string; relay?: { kind: string; email: string; name: string }; peerAsk?: { botId: string; name: string }; inbox?: { kind: string; from: { name: string; email?: string; botId?: string }; via?: { name: string }; origin?: { botId: string; threadId: string; title: string }; replies?: true; answers?: Array<{ by: string; text: string }> } }; type Task = { threadId: string; title: string; inbox?: true; private?: true; openAsks?: number; inboxChangedAt?: number }; @@ -69,7 +69,8 @@ const inboxTask = async () => (await bots(ben)).find((bot) => bot.id === chief.i /** Ben's inbox task in each frame about his Chief that reached his live stream. */ const inboxFrames = (frames: Frame[]) => frames.filter((frame) => frame.kind === "bot" && frame.bot?.id === chief.id).map((frame) => frame.bot!.tasks?.find((task) => task.inbox)); const needsYou = async (token: string) => (await team.as(token, "GET", "/api/needs-you")).body.items as Array<{ kind: string; botId?: string; text?: string }>; -const chiefTurns = async () => (await messages(ben, inbox)).rows.filter((row) => row.role === "bot" && row.kind === "text" && !row.inbox); +/** What Ben's Chief said in turns of its own: its inbox lines and its greeting are not turns. */ +const chiefTurns = async () => (await messages(ben, inbox)).rows.filter((row) => row.role === "bot" && row.kind === "text" && !row.inbox && !row.setupOffer); async function until(done: () => Promise | boolean, timeoutMs = 60_000): Promise { const end = Date.now() + timeoutMs; @@ -198,7 +199,8 @@ it("lands a bot's \"tell Ben\" in his inbox, his chat with his Chief, with one n await turn(cleo, scout, cleoThread, "Tell Ben the launch moved to Friday. (My bonus talk is private.)"); const tasks = (await bots(ben)).find((bot) => bot.id === chief.id)!.tasks ?? []; inbox = tasks.find((task) => task.inbox)!.threadId; - expect(tasks.find((task) => task.threadId === inbox)).toMatchObject({ title: "Inbox", private: true, inbox: true }); + expect(inbox, "his own chat with his Chief, not a new one").toBe(chief.threadId); + expect(tasks.filter((task) => task.inbox)).toEqual([expect.objectContaining({ private: true, inbox: true })]); await until(async () => (await inboxLines()).length === 1); const [line] = await inboxLines(); expect(line).toMatchObject({ role: "bot", text: "The launch moved to Friday.", inbox: { kind: "message", from: { name: "Cleo", email: CLEO.email }, via: { name: "Scout" }, replies: true } }); @@ -222,7 +224,7 @@ it("brings Ben's reply back to Scout in Cleo's chat, where Scout carries on, and expect(rows.find((row) => row.relay?.kind === "reply")).toMatchObject({ role: "user", text: 'Ben replied to your message ("The launch moved to Friday."): Friday works for me.', relay: { email: BEN.email, name: "Ben" }, peerAsk: { botId: chief.id } }); expect(JSON.stringify(JSON.parse(readFileSync(file("dump.json"), "utf8")).prompt)).toContain("Ben replied to your message"); const inboxRows = (await messages(ben, inbox)).rows; - expect(inboxRows.filter((row) => row.role === "bot" && row.kind === "text" && !row.inbox), "no turn of Ben's Chief").toEqual([]); + expect(await chiefTurns(), "no turn of Ben's Chief").toEqual([]); expect(inboxRows.at(-1)).toMatchObject({ kind: "activity", relay: { kind: "told", email: CLEO.email } }); expect(inboxRows.find((row) => row.id === line!.id)!.inbox!.answers).toEqual([expect.objectContaining({ by: "person", text: "Friday works for me." })]); }, hostTimeout(120_000)); diff --git a/server/cloud-wait-follow-up.e2e.test.ts b/server/cloud-wait-follow-up.e2e.test.ts new file mode 100644 index 0000000000..0b9c1da24f --- /dev/null +++ b/server/cloud-wait-follow-up.e2e.test.ts @@ -0,0 +1,123 @@ +// The real My Cloud home server with a synthetic Claude: the owner's bot sets a time wait with a follow-up in the owner's +// own chat. When it fires, the follow-up runs in that same chat and its answer lands there; no conversation is made for +// it, and the wait's answer to the bot names no other chat and no delay to pass on. +import { randomBytes } from "node:crypto"; +import { type ChildProcess } from "node:child_process"; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { afterAll, beforeAll, expect, it } from "vitest"; +import { spawnWithSecrets } from "./cloud-home-start.ts"; +import { cloudPairingSignature } from "./cloud-home.ts"; +import { removeTempDir, waitForExit } from "./testing/cleanup.ts"; +import { hostTimeout } from "./testing/host-timeout.ts"; +import { freePortBlock } from "./testing/ports.ts"; + +const SERVER_DIR = dirname(fileURLToPath(import.meta.url)); +const HOST = "dusk-t-5a6b7c8d9e0f.fly.dev"; +const MACHINE_ID = "8d2f4b6a-1c3e-4a5b-9c7d-0e1f2a3b4c5d"; +const EDGE = { host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", origin: `https://${HOST}` }; +const secret = randomBytes(32).toString("base64url"); +const SET = "I'll recheck the Lurka promo at the time you set and push it then."; +const FOLLOWED = "Rechecked the Lurka promo: 63 views, 1 like. Pushed it to the panels."; +let home = "", dataDir = "", base = "", log = "", owner = ""; +let child: ChildProcess | undefined; + +async function api(method: string, path: string, body?: unknown) { + const response = await fetch(`${base}${path}`, { + method, + headers: { ...EDGE, ...(owner ? { authorization: `Bearer ${owner}` } : {}), ...(body === undefined ? {} : { "content-type": "application/json" }) }, + body: body === undefined ? undefined : JSON.stringify(body), + }); + return { status: response.status, body: await response.json().catch(() => null) as any }; +} + +async function adminPairing(): Promise { + const body = JSON.stringify({ label: "dusk bot app (Cloud)", ttlSeconds: 300 }); + const timestamp = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(16).toString("base64url"); + const response = await fetch(`${base}/api/cloud/pairing`, { method: "POST", headers: { + host: HOST, "x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https", "content-type": "application/json", + "x-dusk-cloud-timestamp": timestamp, "x-dusk-cloud-nonce": nonce, "x-dusk-cloud-signature": `v1=${cloudPairingSignature(secret, timestamp, nonce, body)}`, + }, body }); + const granted = await response.json() as { code: string }; + return (await api("POST", "/api/auth/pair", { code: granted.code })).body.token; +} + +const file = (name: string) => join(home, name); +const lines = (name: string) => existsSync(file(name)) ? readFileSync(file(name), "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : []; + +beforeAll(async () => { + home = mkdtempSync(join(tmpdir(), "dusk-cloud-wait-")); + dataDir = join(home, ".duskbot"); + mkdirSync(dataDir, { recursive: true }); + const claude = file("claude-cli.mjs"); + writeFileSync(claude, `#!/usr/bin/env node +if (process.argv[2] === "auth") { console.log(JSON.stringify({ loggedIn: true, email: "person@example.test" })); process.exit(0); } +process.env.FAKE_CLAUDE_VERSION = "2.1.284"; +if (process.argv[2] !== "--version") { + process.env.FAKE_CLAUDE_REPLIES = ${JSON.stringify(JSON.stringify([SET, FOLLOWED]))}; + process.env.FAKE_CLAUDE_REPLY_STATE = ${JSON.stringify(file("replies.state"))}; + process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = ${JSON.stringify(file("tool-calls.json"))}; + process.env.FAKE_CLAUDE_TOOL_RESULTS = ${JSON.stringify(file("results.jsonl"))}; + process.env.FAKE_CLAUDE_PROMPTS = ${JSON.stringify(file("prompts.jsonl"))}; +} +await import(${JSON.stringify(pathToFileURL(join(SERVER_DIR, "testing", "fake-claude-cli.ts")).href)}); +`, { mode: 0o755 }); + writeFileSync(join(dataDir, "config.json"), JSON.stringify({ + features: { llmThreadTitles: false }, + instances: { + ...Object.fromEntries(["codex", "cursor", "githubCopilot", "openaiCompat", "qwen", "hermes", "pi"].map((id) => [id, { driver: "not-a-real-driver" }])), + claude: { driver: "claudeAgent", displayName: "Claude", config: { cli: claude } }, + }, + })); + const port = await freePortBlock([0, 1]); + base = `http://127.0.0.1:${port}`; + const offline = `data:text/javascript,${encodeURIComponent('const real = globalThis.fetch; globalThis.fetch = async (url, init) => String(url).startsWith("http://127.0.0.1:") ? real(url, init) : new Response("offline fixture", { status: 503 });')}`; + child = spawnWithSecrets(process.execPath, ["--import", offline, join(SERVER_DIR, "index.ts")], { + PATH: process.env.PATH, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}), + HOME: home, USERPROFILE: home, DUSK_DATA_DIR: dataDir, DUSK_PORT: String(port), DUSK_WEBHOOK_PORT: String(port + 1), + DUSK_CLOUD_ROLE: "home", DUSK_CLOUD_MACHINE_ID: MACHINE_ID, DUSK_CLOUD_ADMIN_URL: "https://cloud.example.test", + DUSK_PUBLIC_URL: `https://${HOST}`, DUSK_CLOUD_VOICE_URL: "https://cloud.example.test/api/cloud/services/voice/v1", + DUSK_CLOUD_SECRETS_FD: "3", + }, { DUSK_CLOUD_BOOTSTRAP_SECRET: secret, DUSK_CLOUD_VOICE_TOKEN: `box_omb_${randomBytes(32).toString("base64url")}` }, undefined, true); + for (const stream of [child.stdout, child.stderr]) stream?.on("data", (chunk) => { log += chunk; }); + const deadline = Date.now() + 20_000; + for (;;) { + if (child.exitCode !== null) throw new Error(`the Cloud home exited:\n${log}`); + try { if ((await fetch(`${base}/api/health`)).ok) break; } catch {} + if (Date.now() > deadline) throw new Error(`the Cloud home did not start:\n${log}`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } + owner = await adminPairing(); +}, hostTimeout(40_000)); + +afterAll(async () => { + if (child) await waitForExit(child, { signal: "SIGTERM" }); + if (home) await removeTempDir(home); +}); + +it("on My Cloud, a wait the bot set comes back in the owner's chat that set it, does the follow-up there and makes no chat", async () => { + const bot = (await api("POST", "/api/bots", { name: "Smm", modelSelection: { instanceId: "claude", model: "claude-sonnet-5" } })).body.bot as { id: string; threadId: string }; + const at = new Date(Date.now() + 8_000).toISOString(); + writeFileSync(file("tool-calls.json"), JSON.stringify([{ server: "agents", name: "wait_until", input: { label: "Lurka promo recheck", kind: "time", at, follow_up: "Recheck the Lurka promo's views and likes, then push it to the panels." } }])); + expect((await api("POST", `/api/bots/${bot.id}/messages`, { text: "check on the lurka promo again shortly", threadId: bot.threadId })).status).toBe(202); + const said = async () => ((await api("GET", `/api/threads/${bot.threadId}/messages?limit=100`)).body.messages as Array<{ role: string; kind: string; text?: string }>) + .filter((row) => row.role === "bot" && row.kind === "text").map((row) => row.text); + await expect.poll(said, { timeout: hostTimeout(20_000) }).toContain(SET); + // the follow-up run must not set another wait + rmSync(file("tool-calls.json")); + + const wait = lines("results.jsonl").find((call) => call.name === "wait_until"); + expect(wait, log.slice(-3000)).toMatchObject({ ok: true }); + const answer = JSON.stringify(wait.content); + expect(answer).toContain("Then you come back in this chat, with this conversation, and do what you wrote in follow_up."); + expect(answer).not.toMatch(/results chat|separate|minutes late|tell the person that too|My Cloud/i); + + await expect.poll(said, { timeout: hostTimeout(45_000) }).toContain(FOLLOWED); + const prompts = lines("prompts.jsonl").map((prompt) => JSON.stringify(prompt)); + expect(prompts.some((prompt) => prompt.includes("[Wait finished: Lurka promo recheck] Recheck the Lurka promo")), prompts.join("\n").slice(-2000)).toBe(true); + const tasks = ((await api("GET", "/api/bots")).body.bots as Array<{ id: string; tasks: Array<{ threadId: string; title: string }> }>).find((one) => one.id === bot.id)!.tasks; + expect(tasks.map((task) => task.threadId), JSON.stringify(tasks)).toEqual([bot.threadId]); + expect(tasks.map((task) => task.title).join(" ")).not.toMatch(/Lurka|Results/); +}, hostTimeout(120_000)); diff --git a/server/drivers/agents-call.ts b/server/drivers/agents-call.ts index c300412479..e149b76fff 100644 --- a/server/drivers/agents-call.ts +++ b/server/drivers/agents-call.ts @@ -804,7 +804,7 @@ export async function callTool(called: string, input: Json, context: ToolCallCon const asked = q ? `matches "${q}"` : `is there since ${since}${until ? ` until ${until}` : ""}`; if (!hits.length && !memoryHits.length) { return { text: q - ? `Nothing of yours ${asked}: no earlier conversation and no memory file. Try fewer or different words; every word must appear.` + ? `Nothing of yours ${asked}: no earlier conversation and no memory file. Try other words for it.` : `Nothing of yours ${asked}: no message in any of your conversations in that window.` }; } if (!hits.length) { diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json index 9658df1141..ad5f295928 100644 --- a/server/drivers/agents-catalog-goldens/full.tools-list.json +++ b/server/drivers/agents-catalog-goldens/full.tools-list.json @@ -2327,7 +2327,7 @@ }, "follow_up": { "type": "string", - "description": "Only if something is to be done then: that request, for a run that won't see this chat. You carry it out here." + "description": "Only if something is to be done then: that request, written to stand alone. You come back here to do it." }, "hours": { "type": "integer" diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json index faca64e7f4..d6268dcaec 100644 --- a/server/drivers/agents-catalog-goldens/profiles.json +++ b/server/drivers/agents-catalog-goldens/profiles.json @@ -1,7 +1,7 @@ { "default": { - "bytes": 78006, - "sha256": "ae567d0c2f100daa1625714eb2f20746579d6e5da28c74435775faf141d92a71", + "bytes": 78000, + "sha256": "5707f6458d55ca3237932597fa30944761ded557ac8bbd44254831f212336d3e", "tools": [ "set_status", "send_message", @@ -62,8 +62,8 @@ ] }, "voice": { - "bytes": 78784, - "sha256": "1ef2a45b46fa322c4eb0760c1b74b7a2b6574ba8069f4ae7568fb8064aecf5ed", + "bytes": 78778, + "sha256": "bc7fcf339a2e67fc25db4427e9ab4cd22cb5ef711907e3a50e98639e612e153d", "tools": [ "set_status", "send_message", @@ -125,8 +125,8 @@ ] }, "skills": { - "bytes": 81242, - "sha256": "a4961fcb431de365585c1866cf72856ee17c1b2b4d70b3a3120e684901022165", + "bytes": 81236, + "sha256": "5c443b77874011b7c1aad701d6371f4297da4e2d91e39dcec3502e1e85bf6f09", "tools": [ "set_status", "send_message", @@ -189,8 +189,8 @@ ] }, "skills+voice": { - "bytes": 82020, - "sha256": "32ee6850595e55875a17db3ada6333fa041c0f015b558ef87393cb3f8f0c3ce0", + "bytes": 82014, + "sha256": "d769ffe94081fd85370197f66f19c8e8240674a06a64ee837108df387659717b", "tools": [ "set_status", "send_message", @@ -254,8 +254,8 @@ ] }, "non-chief": { - "bytes": 69725, - "sha256": "bb7f5afc7c6d802c643f8598d804cfb82b821824a3199b028a71a32f2653ee2b", + "bytes": 69719, + "sha256": "8d57b3c279fcffe7a2024bff78fbbbf9ae7828bcd7b6a703bda45aff091060a3", "tools": [ "set_status", "send_message", @@ -311,8 +311,8 @@ ] }, "voice+non-chief": { - "bytes": 70503, - "sha256": "9d9c5ad699d2b55a9453baf25dd7398a9c313720b6f254c99d995b9d2cc92304", + "bytes": 70497, + "sha256": "dfcfa715bc83e30eb1ba0bb1fcccd5ae57282602cd9e6c218e99f6e47fd72b86", "tools": [ "set_status", "send_message", @@ -369,8 +369,8 @@ ] }, "skills+non-chief": { - "bytes": 72961, - "sha256": "b7ace3c7aa21cb46be1175d9337a1b6aed88fb5b96c3fd41a793879a3ad21db4", + "bytes": 72955, + "sha256": "7e8e465cc7b3e97aa148ea6e1e9f5ad1f974a3dc85646a3d792ab8d65a106c8c", "tools": [ "set_status", "send_message", @@ -428,8 +428,8 @@ ] }, "skills+voice+non-chief": { - "bytes": 73739, - "sha256": "b772be5a61f6c62f2431235f35e2658b722616f2162a5c820174abdda2617433", + "bytes": 73733, + "sha256": "6ff26ac8f09416b51be689ee57ab86e5f7651a345b68106b55d4e471daa203dd", "tools": [ "set_status", "send_message", @@ -488,8 +488,8 @@ ] }, "skills+voice+cloud-home": { - "bytes": 80996, - "sha256": "0f223c4f180eada96a0a4d29f11e0df8ad192a7d2dcaceedd97dc945e8a8c7dc", + "bytes": 80990, + "sha256": "e9fd9b7f84763b69d32156d1dcd00fb3bab4da9f47f3a5826ec1b27ac83bd051", "tools": [ "set_status", "send_message", @@ -552,8 +552,8 @@ ] }, "skills+voice+non-chief+cloud-home": { - "bytes": 72715, - "sha256": "f8795482246b008892bfa65d4c4dabcaa1cf71aab6cb14046cf5add7846f48bc", + "bytes": 72709, + "sha256": "aab771da736426ec5620b11ba56240a3d52070face81a9766d27b094e4da1f55", "tools": [ "set_status", "send_message", @@ -611,8 +611,8 @@ ] }, "skills+voice+x": { - "bytes": 88678, - "sha256": "02d04a8986f5bf551f55507e2881d444f953e4fced793d2cf212aad3e55e7240", + "bytes": 88672, + "sha256": "e8fd3d57b5af0500f66a6f5171117813e7ae10f1d8f3a28233e0c308052b681c", "tools": [ "set_status", "send_message", @@ -684,8 +684,8 @@ ] }, "skills+voice+x+team": { - "bytes": 89094, - "sha256": "dea6d73555ddc99e7a809250a713f53cf9514b6502555bab3731a4d4787ec338", + "bytes": 89088, + "sha256": "090b07139b0276dcb4fe1e3d9c6eeb3d624df196b49f577562f29d27b86a277a", "tools": [ "set_status", "send_message", @@ -758,8 +758,8 @@ ] }, "skills+skill-reader": { - "bytes": 81658, - "sha256": "c804d6f7336f1b41b1cba345d1add6678e71df683353c3fb77e8ff7ae156d29c", + "bytes": 81652, + "sha256": "a035fcb7d8d58d2c23bf9e2d015847e88fe5f5f085142db2d3ed9c9553cbb9ff", "tools": [ "set_status", "send_message", @@ -823,8 +823,8 @@ ] }, "default+legacy-switches": { - "bytes": 78006, - "sha256": "ae567d0c2f100daa1625714eb2f20746579d6e5da28c74435775faf141d92a71", + "bytes": 78000, + "sha256": "5707f6458d55ca3237932597fa30944761ded557ac8bbd44254831f212336d3e", "tools": [ "set_status", "send_message", @@ -885,8 +885,8 @@ ] }, "default+dusk": { - "bytes": 78657, - "sha256": "cedc41585560878e60251f4fcd6a94904d8f981639de850f9cc3d1bc869c193a", + "bytes": 78651, + "sha256": "9d5f11a1300b81b843af3a9bf1ad1581e2cc5448374bec1b7c866dcf0b8e1469", "tools": [ "set_status", "send_message", @@ -949,8 +949,8 @@ ] }, "skills+voice+dusk": { - "bytes": 82671, - "sha256": "1f62b7179fde20b26bf3addea2fcd81efa8554bdf9ae983ee2d9ebfe1f0aaa96", + "bytes": 82665, + "sha256": "8317dddaf9e5d77856185d41459184ec5477e13db10528e23c99d043e66dc20c", "tools": [ "set_status", "send_message", @@ -1016,8 +1016,8 @@ ] }, "default+no-computer-pick": { - "bytes": 76611, - "sha256": "e9907c6ef18de98577dd6db44db6869b36f969550ababbcecfefa742f55b1171", + "bytes": 76605, + "sha256": "6bd216c71404edd092ad3c708603b70210c8b4c5e7c1f842c688e1a2640cf2db", "tools": [ "set_status", "send_message", diff --git a/server/drivers/agents-wait-tools.test.ts b/server/drivers/agents-wait-tools.test.ts index f95653ab50..5fe68f2541 100644 --- a/server/drivers/agents-wait-tools.test.ts +++ b/server/drivers/agents-wait-tools.test.ts @@ -53,7 +53,7 @@ describe("wait tools", () => { expect(waitUntil!.description).toContain("No AI runs while you wait"); expect(waitUntil!.description).toContain("(default 24, 1-168)"); for (const prefix of ["url_*", "file_*", "process_*", "bot_idle", "time:"]) expect(properties.kind!.description).toContain(prefix); - expect(properties.follow_up!.description).toMatch(/^Only if something is to be done then.*You carry it out here\.$/); + expect(properties.follow_up!.description).toMatch(/^Only if something is to be done then.*You come back here to do it\.$/); expect(properties.label!.description).toBe('A noun phrase in the person\'s words, e.g. "the build".'); expect(list!.description).toMatch(/^Your waits in this chat that have not ended/); // The advertised bytes ride every turn that lists it: the catalog wire test budgets them, this keeps them small. diff --git a/server/drivers/agents-wait-tools.ts b/server/drivers/agents-wait-tools.ts index b560a20b2d..a634a7175b 100644 --- a/server/drivers/agents-wait-tools.ts +++ b/server/drivers/agents-wait-tools.ts @@ -17,7 +17,7 @@ export const WAIT_TOOL_DEFINITIONS = [ { name: "wait_until", // Short on purpose: it rides every turn. Its result says when the condition already holds, when this computer cannot - // check files or programs, and when My Cloud's sleep can delay the message. + // check files or programs, and where a follow-up comes back. description: `Tell the person in this chat when something happens, or come back here later yourself (time: "check back in 20 min") instead of polling. No AI runs while you wait, only plain code checks. Ends after hours (default ${WAIT_HOURS.default}, 1-${WAIT_HOURS.max}).`, inputSchema: { @@ -40,7 +40,7 @@ export const WAIT_TOOL_DEFINITIONS = [ follow_up: { type: "string", maxLength: 2000, - description: "Only if something is to be done then: that request, for a run that won't see this chat. You carry it out here.", + description: "Only if something is to be done then: that request, written to stand alone. You come back here to do it.", }, hours: { type: "integer", minimum: 1, maximum: WAIT_HOURS.max }, }, diff --git a/server/drivers/chat-mcp-tools.test.ts b/server/drivers/chat-mcp-tools.test.ts index 049bee8400..17b1834f6d 100644 --- a/server/drivers/chat-mcp-tools.test.ts +++ b/server/drivers/chat-mcp-tools.test.ts @@ -92,6 +92,8 @@ async function expectSkipped(f: ReturnType, reason: RegExp) { const session = await f.mount(); expect(session.definitions).toEqual([]); expect(session.skipped).toEqual([{ server: "audit", reason: expect.stringMatching(reason) }]); + expect(chatToolNotices(session)).toEqual([]); + expect(warn).toHaveBeenCalledWith(expect.stringContaining('skipping MCP server "audit" for this turn')); expect(alive(f.read().pid)).toBe(false); } finally { warn.mockRestore(); } } diff --git a/server/drivers/chat-mcp-tools.ts b/server/drivers/chat-mcp-tools.ts index 8ab4186b6d..da999f2e0f 100644 --- a/server/drivers/chat-mcp-tools.ts +++ b/server/drivers/chat-mcp-tools.ts @@ -403,9 +403,9 @@ const BUILT_IN_NAMES: Readonly> = { /** What the person hears about a turn's MCP servers before the model runs, one line each. */ export function chatToolNotices(session: Pick): string[] { return [ - // the reason stays in the log; searched servers still work, so they say nothing - ...session.skipped.map(({ server, builtIn }) => !builtIn ? `Couldn't connect ${server} this time, so the bot went on without it.` - : server === "agents" ? TEAM_TOOLS_FAILED : `Couldn't start ${BUILT_IN_NAMES[server] ?? "some of its tools"} this time, so the bot went on without it.`), + // the reason stays in the log; searched servers and the person's own MCP servers say nothing + ...session.skipped.flatMap(({ server, builtIn }) => !builtIn ? [] + : [server === "agents" ? TEAM_TOOLS_FAILED : `Couldn't start ${BUILT_IN_NAMES[server] ?? "some of its tools"} this time, so the bot went on without it.`]), trimmedToolsNotice(session.trimmed), ].filter((line): line is string => line !== undefined); } diff --git a/server/drivers/openai-chat-tools.test.ts b/server/drivers/openai-chat-tools.test.ts index 180bd4ff1e..85fb7ddacb 100644 --- a/server/drivers/openai-chat-tools.test.ts +++ b/server/drivers/openai-chat-tools.test.ts @@ -1840,7 +1840,7 @@ describe("structured tool execution boundaries", () => { }); describe("a configured MCP server that cannot mount", () => { - it("is skipped with a notice, and the turn runs with the remaining servers", async () => { + it("is skipped quietly, and the turn runs with the remaining servers", async () => { const f = await fixture((_body, response) => answer(response)); const broken = join(f.directory, "broken-mcp.mjs"); // Answers initialize with an error, as a server needing sign-in or refusing its credential (401) does. @@ -1851,7 +1851,7 @@ describe("a configured MCP server that cannot mount", () => { await f.start({ integrations: { custom: { ...f.integrations!.custom, slack: { command: process.execPath, args: [broken], env: {} } } } }); expect(await f.completed()).toMatchObject({ ok: true }); } finally { console.warn = warn; } - expect(f.recorder.events).toContainEqual(expect.objectContaining({ type: "runtime.notice", message: expect.stringContaining("Couldn't connect slack this time") })); + expect(f.recorder.events.some((event) => event.type === "runtime.notice")).toBe(false); expect(f.recorder.events.some((event) => event.type === "runtime.error")).toBe(false); const names = f.requests[0].tools!.map((tool) => tool.function.name); expect(names).toContain("audit_write"); diff --git a/server/drivers/provider-failover.ts b/server/drivers/provider-failover.ts index be4dcccc70..7dbd0c74b8 100644 --- a/server/drivers/provider-failover.ts +++ b/server/drivers/provider-failover.ts @@ -35,12 +35,3 @@ export function turnActed(event: RuntimeEvent): boolean { return false; } } - -/** "Claude did not answer, so Codex took over." */ -export function providerFailoverLine(from: string, to: string): string { - return `${from} did not answer, so ${to} took over.`; -} - -export function providerBackLine(engine: string): string { - return `${engine} gets another try, so this conversation is back on ${engine}.`; -} diff --git a/server/host/finish-guard.test.ts b/server/host/finish-guard.test.ts index d73a880bde..b0636a51e1 100644 --- a/server/host/finish-guard.test.ts +++ b/server/host/finish-guard.test.ts @@ -7,13 +7,14 @@ import { orderHeldNote } from "../turn-stop-gates.ts"; type Body = RuntimeEvent extends infer E ? E extends RuntimeEvent ? Omit : never : never; const PLAN = JSON.stringify({ todos: [{ content: "Read", status: "completed" }, { content: "Draft", status: "in_progress" }, { content: "Send", status: "pending" }] }); -function harness(held = false) { +function harness(held = false, recap = false) { const carried: Array<{ botId: string; threadId: string; note: string }> = []; const lines: FinishReason[] = []; let isHeld = held; const guard = createFinishGuard({ botOf: (threadId) => (threadId.startsWith("room") ? null : "bot-1"), held: () => isHeld, + recap: () => recap, carryOn: async (botId, threadId, note) => { carried.push({ botId, threadId, note }); }, line: (_threadId, reason) => lines.push(reason), later: (run) => run(), @@ -370,6 +371,29 @@ describe("finish guard: claims with nothing behind them", () => { expect(h.lines).toEqual([]); }); + it("leaves a reply to a question about the chat that recaps what earlier turns did, so the person gets one answer", () => { + const answer = "I held the push because views went from 62 to 63 between checks. That met your stall rule.\n\n" + + "I gave you a recheck time without a date, my bad. The recheck is scheduled for Dec 4 at 6:00 PM."; + const asked = harness(false, true); + // the chosen AI failed before it did anything, and its backup answered the same message + asked.guard.onEvent({ eventId: "e", provider: "fake", threadId: "t1", createdAt: "", type: "turn.started" } as RuntimeEvent); + asked.guard.onEvent({ eventId: "e", provider: "fake", threadId: "t1", createdAt: "", type: "turn.completed", ok: false, stopReason: "exit_before_result" } as RuntimeEvent); + asked.turn(answer); + expect(asked.carried).toEqual([]); + expect(asked.lines).toEqual([]); + + const ordered = harness(); + ordered.turn(answer); + expect(ordered.lines).toEqual([{ kind: "claim", deeds: ["schedule"] }]); + }); + + it("never asks for the shown reply again when a claim is sent back", () => { + const note = continueNote({ kind: "claim", deeds: ["schedule"] }); + expect(note).toContain("never answer it again or restate it"); + expect(note).not.toContain("rewrite the reply"); + expect(note).toContain("still needs their yes"); + }); + it("lets a sent claim end when a send succeeded", () => { const h = harness(); const send = (body: Body) => h.guard.onEvent({ eventId: "e", provider: "fake", threadId: "t1", createdAt: "", ...body } as RuntimeEvent); diff --git a/server/host/finish-guard.ts b/server/host/finish-guard.ts index 7c305ae135..6bc687f709 100644 --- a/server/host/finish-guard.ts +++ b/server/host/finish-guard.ts @@ -83,7 +83,7 @@ export function planSignature(plan: PlanSteps): string { const endsOnQuestion = (text: string) => /\?\s*[)"'”]?\s*$/.test(text.trim()); /** Why a finished turn should carry on, or null. */ -export function finishReason(turn: { text: string; tools: number; plan: PlanSteps | null; toolsAfterText?: number; cut?: boolean; scheduled?: boolean; effectful?: number; gated?: readonly string[]; unread?: string | null; asks?: readonly string[]; evidence?: ReadonlySet; card?: boolean }): FinishReason | null { +export function finishReason(turn: { text: string; tools: number; plan: PlanSteps | null; toolsAfterText?: number; cut?: boolean; scheduled?: boolean; effectful?: number; gated?: readonly string[]; unread?: string | null; asks?: readonly string[]; evidence?: ReadonlySet; card?: boolean; recap?: boolean }): FinishReason | null { if (!turn.text.trim()) return null; if (turn.cut) return { kind: "cut" }; if (turn.asks?.some(goOrder) && !turn.gated?.includes("open_items")) return { kind: "asks", items: [...turn.asks] }; @@ -94,7 +94,7 @@ export function finishReason(turn: { text: string; tools: number; plan: PlanStep if (endsOnQuestion(turn.text)) return null; if (turn.plan && turn.plan.open > 0) return { kind: "plan", ...turn.plan }; if (!turn.scheduled && !turn.gated?.includes("follow_up") && promisesFollowUp(turn.text)) return { kind: "promise" }; - const deeds = turn.evidence && !turn.gated?.includes("unbacked_claim") ? unbackedDeeds(claimedDeeds(turn.text), turn.evidence) : []; + const deeds = turn.evidence && !turn.recap && !turn.gated?.includes("unbacked_claim") ? unbackedDeeds(claimedDeeds(turn.text), turn.evidence) : []; if (deeds.length) return { kind: "claim", deeds }; const items = turn.effectful && !turn.gated?.includes("checklist") ? openChecklist(turn.text) : null; if (items) return { kind: "checklist", items }; @@ -106,10 +106,16 @@ export function finishReason(turn: { text: string; tools: number; plan: PlanStep return null; } +/** The person already reads the reply the claim is in, so a rewrite of it would be a second answer to one message. */ +function shownClaimNote(deeds: readonly Deed[]): string { + return unbackedClaimNote(deeds).replace(/ Otherwise rewrite the reply to say plainly (.+?), without claiming it is done\./, + " Otherwise say in one short line $1. Your reply is already in front of the person: never answer it again or restate it."); +} + export function continueNote(reason: FinishReason): string { if (reason.kind === "promise") return stopGateNote("follow_up"); if (reason.kind === "cut") return CUT_OFF_NOTE; - if (reason.kind === "claim") return unbackedClaimNote(reason.deeds); + if (reason.kind === "claim") return shownClaimNote(reason.deeds); if (reason.kind === "checklist") return stopGateNote("checklist", { items: reason.items }); if (reason.kind === "unread") return stopGateNote("unconfirmed_write", { tool: reason.tool }); if (reason.kind === "asks") return reason.items.some(goOrder) ? orderHeldNote(reason.items) : stopGateNote("open_items", { items: reason.items }); @@ -129,6 +135,9 @@ export interface FinishGuardDeps { /** Something waits on the person, a message of theirs is queued, the thread is busy again, or it waits on teammates' * answers, which resume it (a carry-on there would take that turn's place and could not reach them). */ held(threadId: string): boolean; + /** The person's message only asks where things stand: a reply recapping earlier turns' work is not held to this + * turn's tool calls. Asked when the turn starts. */ + recap?(threadId: string): boolean; /** Starts the next turn with a note only the bot reads. */ carryOn(botId: string, threadId: string, note: string): Promise; /** The quiet line the person sees, "Continuing: 2 of 5 steps left". */ @@ -141,7 +150,7 @@ export interface FinishGuardDeps { review?: (botId: string, threadId: string, turn: { said: readonly string[]; startedAt: number }) => Promise; } -interface Turn { text: string; said: string[]; tools: number; toolsAfterText: number; plan: PlanSteps | null; carriable: boolean; scheduled: boolean; handedOff: boolean; effectful: number; acted: number; unread: string | null; made: boolean; card: boolean; startedAt: number; +interface Turn { text: string; said: string[]; recap: boolean; tools: number; toolsAfterText: number; plan: PlanSteps | null; carriable: boolean; scheduled: boolean; handedOff: boolean; effectful: number; acted: number; unread: string | null; made: boolean; card: boolean; startedAt: number; calls: Map; evidence: Set } export function createFinishGuard(deps: FinishGuardDeps) { @@ -166,7 +175,7 @@ export function createFinishGuard(deps: FinishGuardDeps) { const state = carried.get(threadId); if (state?.ours) state.ours = false; else carried.delete(threadId); - turns.set(threadId, { text: "", said: [], tools: 0, toolsAfterText: 0, plan: null, carriable: deps.botOf(threadId) !== null, scheduled: false, handedOff: false, effectful: 0, acted: 0, unread: null, made: false, card: false, startedAt: Date.now(), calls: new Map(), evidence: new Set() }); + turns.set(threadId, { text: "", said: [], recap: deps.recap?.(threadId) === true, tools: 0, toolsAfterText: 0, plan: null, carriable: deps.botOf(threadId) !== null, scheduled: false, handedOff: false, effectful: 0, acted: 0, unread: null, made: false, card: false, startedAt: Date.now(), calls: new Map(), evidence: new Set() }); return; } const turn = turns.get(threadId); diff --git a/server/host/limit-takeover.test.ts b/server/host/limit-takeover.test.ts index 477e428541..4774cb2351 100644 --- a/server/host/limit-takeover.test.ts +++ b/server/host/limit-takeover.test.ts @@ -458,11 +458,11 @@ describe("a model whose provider failed a turn before it did anything", () => { expect(instance.heldAtStart(KAI, OPUS)).toBeNull(); }); - it("is told only in the conversation, and a turn on it that works ends the hold", () => { + it("is told nowhere, and a turn on it that works ends the hold", () => { const { instance, told, record } = takeover({ chosen: () => [on("codex", "gpt-6")] }); const until = instance.holdProvider(OPUS); expect(instance.carriedOn(KAI, "t1", OPUS, on("codex", "gpt-6"), { scope: "provider", resetsAt: until })) - .toEqual([{ name: "recovery: Claude claude-opus-5-5 did not answer, so Codex took over.", ok: true }]); + .toEqual([]); expect(told).toEqual([]); expect(record).toHaveBeenCalledWith(expect.objectContaining({ why: "provider", resetsAt: until })); instance.worked("kai", OPUS); diff --git a/server/host/limit-takeover.ts b/server/host/limit-takeover.ts index e37dd9b901..42e671604a 100644 --- a/server/host/limit-takeover.ts +++ b/server/host/limit-takeover.ts @@ -10,7 +10,7 @@ import { recoveryCapabilityError } from "../automatic-recovery.ts"; import type { InstanceConfigMap, ProviderAdapter, RuntimeEvent } from "../contracts.ts"; import { readyToRun, type DefaultSelectionContext, type SelectableInstance } from "../default-model-selection.ts"; import { engineFailureKind } from "../drivers/engine-errors.ts"; -import { PROVIDER_FAILURE_HOLD_MS, providerFailoverLine } from "../drivers/provider-failover.ts"; +import { PROVIDER_FAILURE_HOLD_MS } from "../drivers/provider-failover.ts"; import { classifyError } from "../drivers/retry.ts"; import { failoverLine, limitBackupAllowed, signedOutLine, type LimitFailover } from "../limit-failover.ts"; import { LimitNotices, limitNoticeText, signedOutNoticeText } from "../limit-notices.ts"; @@ -317,8 +317,11 @@ export function createLimitTakeover(deps: LimitTakeoverDeps) { carriedOn(bot: Bot, threadId: string, from: ModelSelection, to: ModelSelection, facts: { scope: TakeoverScope; resetsAt?: number }): CarriedOnRow[] { moved(bot.id, threadId, from, to, facts.resetsAt, facts.scope); const told = tell(bot, from, { ...facts, backup: to }); + if (facts.scope === "provider") { + console.log(`limit takeover: ${threadId}: ${refusedName(from, facts.scope)} did not answer, so ${label(to, from)} took over`); + return []; + } const line = facts.scope === "signed-out" ? signedOutLine(refusedName(from, facts.scope), label(to, from)) - : facts.scope === "provider" ? providerFailoverLine(refusedName(from, facts.scope), label(to, from)) : failoverLine(refusedName(from, facts.scope), label(to, from), facts.resetsAt); return [{ name: `recovery: ${line}`, ok: true }, ...(told && facts.scope === "signed-out" ? [{ name: `notice: ${told}`, ok: true, setup: true }] : [])]; }, diff --git a/server/host/team-messages.test.ts b/server/host/team-messages.test.ts index b541830786..235593d99e 100644 --- a/server/host/team-messages.test.ts +++ b/server/host/team-messages.test.ts @@ -42,7 +42,8 @@ describe("message_person", () => { expect(rows.map((row) => row.text)).toEqual(["The numbers are in.", "The Q4 draft is ready."]); expect(rows[0]!.inbox).toMatchObject({ from: { name: "Cleo" }, via: { name: "Scout" }, origin: { botId: "scout", threadId: "scout-main", title: "Scout" } }); expect(rows[1]!.inbox).toMatchObject({ from: { name: "Reporter", botId: "reporter" }, origin: { botId: "reporter", threadId: "rep-main" } }); - expect(f.bots.find((bot) => bot.id === "bens-chief")!.tasks.filter((task) => task.title === "Inbox")).toHaveLength(1); + expect(inbox.threadId, "his own chat with his Chief").toBe("mc-main"); + expect(f.bots.find((bot) => bot.id === "bens-chief")!.tasks.map((task) => task.threadId), "no chat was made for it").toEqual(["mc-main"]); expect(f.notified.map((one) => one.threadId)).toEqual([inbox.threadId, inbox.threadId]); }); diff --git a/server/index.ts b/server/index.ts index 3172a59dec..cf70cc9fac 100644 --- a/server/index.ts +++ b/server/index.ts @@ -506,7 +506,7 @@ import { listenWebhookIngress, type WebhookIngress } from "./webhook-ingress.ts" import { addressFor } from "./webhook-address.ts"; import { createRoutineMailHost } from "./host/routine-mail-host.ts"; import { assertModelVariantSupported, memberTurnSelection } from "./member-turn.ts"; import { WebhookManager } from "./webhooks.ts"; -import { SCRIPT_CHECK_ON_NOTE, scriptCheckGate, scriptRoutineRefusal, setsFullAccess, setsScript } from "./routine-script.ts"; import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { createWaitListRoutes } from "./routes/wait-list.ts"; import { cancelWaitFromCard, createWaitHost } from "./wait-host.ts"; import { limitResetRoutineOf, ranApart } from "./routine-run-definition.ts"; import { createWaitRoutes, findWaitPeer, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts"; import { createJobsHost, JOB_NOTIFY_PATH, type JobTurn } from "./jobs/host.ts"; import { routineFailRequest, routineNoteRequest } from "./routine-notes.ts"; import { againPerDay, routineAgainRequest } from "./routine-again.ts"; import { selfSpawnRefusal } from "./routine-bot-guard.ts"; import { repeatedBubble } from "./repeat-bubbles.ts"; +import { SCRIPT_CHECK_ON_NOTE, scriptCheckGate, scriptRoutineRefusal, setsFullAccess, setsScript } from "./routine-script.ts"; import { tieAutomationsToBots } from "./bot-automations.ts"; import { WaitManager } from "./waits.ts"; import { openOrders } from "./turn-stop-gates.ts"; import { createWaitListRoutes } from "./routes/wait-list.ts"; import { cancelWaitFromCard, createWaitHost } from "./wait-host.ts"; import { limitResetRoutineOf, ranApart } from "./routine-run-definition.ts"; import { createWaitRoutes, findWaitPeer, hostWaitRefusal, waitSourceRefusal, type WaitRouteContext } from "./routes/waits.ts"; import { createJobsHost, JOB_NOTIFY_PATH, type JobTurn } from "./jobs/host.ts"; import { routineFailRequest, routineNoteRequest } from "./routine-notes.ts"; import { againPerDay, routineAgainRequest } from "./routine-again.ts"; import { selfSpawnRefusal } from "./routine-bot-guard.ts"; import { repeatedBubble } from "./repeat-bubbles.ts"; import type { WebhookTrigger } from "../shared/webhooks.ts"; import { AGENTS_NODE_FLAG, SPAWNED_PROXIES } from "./proxy-paths.ts"; import { hostShellLaunch, mountsHostShell, SELF_HOSTED_ENV } from "./host-shell-mcp.ts"; import { currentTrailId, startServerTrail, trail, trailError, withRequestTrail } from "./trail.ts"; import { traceRuntimeEvents } from "./trail-events.ts"; @@ -7981,7 +7981,7 @@ const batchContinue = createBatchContinue({ botOf: oneOnOne, read: (botId, threa const checklistRoutes = createChecklistRoutes({ taskDir: (botId, threadId) => checklistDir(TASK_WORKSPACES_DIR, botId, threadId) ?? join(TASK_WORKSPACES_DIR, "invalid"), pause: (threadId, untilMs) => batchContinue.pause(threadId, untilMs) }); const documentRoutes = createDocumentRoutes({ exportDir: (botId) => join(workspaceDir(botId), "files"), documents: new BotDocuments(join(DATA_DIR, "bot-documents")), bot: (id) => store.bot(id), post: (botId, threadId, text, document) => { const source = connectorThread(botId, threadId); return !source ? null : store.appendMessage(threadId, { role: "bot", kind: "text", text, document, ...(source.group ? { from: { botId, name: source.bot.name, color: source.bot.color } } : {}) }).id; } }); ROUTES.push(documentRoutes.routes); const artifacts = createArtifacts({ cloudHome: CLOUD_HOME, selfHosted: !CLOUD_HOME && utilityParentPort === undefined, exportDir: (botId) => join(workspaceDir(botId), "files"), botName: (botId) => store.bot(botId)?.name ?? "", post: (botId, threadId, text, artifact) => { const source = connectorThread(botId, threadId); return !source ? null : store.appendMessage(threadId, { role: "bot", kind: "text", text, artifact, ...(source.group ? { from: { botId, name: source.bot.name, color: source.bot.color } } : {}) }).id; } }); if (artifactsEnabled()) ROUTES.push(createArtifactListRoutes({ client: artifacts.client })); const toolsFirst = createToolFirst(); const openAsks = createOpenAsks({ store, handedOff: (threadId) => coordinator.activeDirect(threadId) }); const turnWorkers = createTurnWorkers({ generations: (threadId) => directRequestOwners.get(threadId)?.generations, stopThread: async (worker) => { if (worker.queuedId) cancelSteeredMessage(worker.botId, worker.queuedId, worker.threadId); if (threadBusy(worker.botId, worker.threadId)) await stopThreadForPerson(worker.botId, worker.threadId); }, stopJob: (worker) => { jobs.supervisor.stop(worker.jobId, worker.botId, "stopped with the chat that started it"); } }); store.onChange((change) => { if (change.type === "thread.deleted" && change.threadId) turnWorkers.forget(change.threadId); }); -const finishGuard = createFinishGuard({ asks: openAsks, botOf: (threadId) => (batchContinue.active(threadId) ? null : oneOnOne(threadId)), held: (threadId) => { const botId = oneOnOne(threadId); return !botId || watchdog.waiting(threadId) || threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId) || threadsAwaitingTeammates().has(threadId); }, carryOn: (botId, threadId, note) => startTurn(botId, note, { threadId, unattended: true, cardContinuation: true }), review: createDeliverableCheck({ ask: (threadId) => store.activePath(threadId).findLast((line) => line.role === "user" && line.kind === "text")?.text ?? null, documents: (botId, since) => { const docs = new BotDocuments(join(DATA_DIR, "bot-documents")); return docs.list(botId).filter((doc) => doc.updatedAt >= since).slice(0, 2).flatMap((doc) => { const full = docs.get(botId, doc.id); return full ? [{ title: full.title, content: full.content }] : []; }); }, text: (botId) => sideJobs.text("deliverable-check", botId), log: (line) => console.warn(line) }), +const finishGuard = createFinishGuard({ asks: openAsks, recap: (threadId) => asksAboutChat(store.activePath(threadId).findLast((line) => line.role === "user" && line.kind === "text")?.text ?? ""), botOf: (threadId) => (batchContinue.active(threadId) ? null : oneOnOne(threadId)), held: (threadId) => { const botId = oneOnOne(threadId); return !botId || watchdog.waiting(threadId) || threadBusy(botId, threadId) || hasQueuedSteeredMessages(botId, threadId) || threadsAwaitingTeammates().has(threadId); }, carryOn: (botId, threadId, note) => startTurn(botId, note, { threadId, unattended: true, cardContinuation: true }), review: createDeliverableCheck({ ask: (threadId) => store.activePath(threadId).findLast((line) => line.role === "user" && line.kind === "text")?.text ?? null, documents: (botId, since) => { const docs = new BotDocuments(join(DATA_DIR, "bot-documents")); return docs.list(botId).filter((doc) => doc.updatedAt >= since).slice(0, 2).flatMap((doc) => { const full = docs.get(botId, doc.id); return full ? [{ title: full.title, content: full.content }] : []; }); }, text: (botId) => sideJobs.text("deliverable-check", botId), log: (line) => console.warn(line) }), line: (threadId, reason) => void store.appendMessage(threadId, { role: "bot", kind: "activity", tool: { name: `recovery: ${reason.kind === "plan" ? serverLine(threadLanguage(threadId), "server.finish.plan", { open: reason.open, total: reason.total }) : serverLine(threadLanguage(threadId), reason.kind === "ack" ? "server.finish.ack" : "server.finish.next")}`, ok: true } }) }); const actionReceipts = createActionReceipts({ dataDir: DATA_DIR, botOf: (threadId) => (store.groupByThread(threadId) ? null : store.botByThread(threadId)?.id ?? null), mark: (threadId, turnId, kinds) => { const said = turnId ? store.activePath(threadId).findLast((line) => line.role === "bot" && line.kind === "text" && line.turnId === turnId) : undefined; return Boolean(said && store.patchMessage(threadId, said.id, { unconfirmed: kinds })); } }); const browserLoops = createBrowserLoops({ stop: ({ threadId, blocker, cause }) => { const bot = store.botByThread(threadId); if (!bot) return; turnStops.stopping(threadId, liveTurnByThread.get(threadId), cause); routines?.failThread(threadId, `Stopped: ${cause}`, { cause: "cap" }); store.appendMessage(threadId, { role: "bot", kind: "activity", tool: failedTurnRow(`stopped: ${cause}`, { blocker }) }); void interruptDirectThread(bot.id, threadId, cause).catch(() => undefined); } }); @@ -10044,7 +10044,7 @@ store.reconcileInterruptedGroupGoals((runId, threadId) => { ); return { status, detail, finishedAt: run.finishedAt ?? groupGoalRecoveryAt }; }); -const botWaits = new WaitManager({ ...createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input) }), changed: () => broadcast({ kind: "waits" }) }); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); }); ROUTES.push(createWaitListRoutes({ waits: botWaits, sees: (auth) => { const visible = visibleTo(viewerFor(auth)); return (botId) => routineVisible({ botId }, visible); } })); const jobs = createJobsHost({ dataDir: DATA_DIR, port: PORT, wrap: (request) => botBox.wrap(request), secret: (label, botId) => { try { return savedSecrets.ready() ? savedSecrets.find(label, botId)?.value ?? null : null; } catch { return null; } }, store, directChat: directChatOf, mainThread: botMainThread, threadBusy, wrote: markTaskContextExternallyUpdated, notify, routines: () => routines!, openCards: (tool) => optionCardsForTools([tool]) }); store.onChange((change) => { if (change.type === "bot.deleted") jobs.removeForBot(change.botId); }); +const botWaits = new WaitManager({ ...createWaitHost({ store, directChat: directChatOf, threadBusy, wrote: markTaskContextExternallyUpdated, notify, enqueue: (input) => routines!.enqueueWebhook(input), orders: (threadId) => openOrders(openAsks.open(threadId)) }), changed: () => broadcast({ kind: "waits" }) }); store.onChange((change) => { if (change.type === "bot" && store.bot(change.botId)?.busy) botWaits.noteBotBusy(change.botId); }); ROUTES.push(createWaitListRoutes({ waits: botWaits, sees: (auth) => { const visible = visibleTo(viewerFor(auth)); return (botId) => routineVisible({ botId }, visible); } })); const jobs = createJobsHost({ dataDir: DATA_DIR, port: PORT, wrap: (request) => botBox.wrap(request), secret: (label, botId) => { try { return savedSecrets.ready() ? savedSecrets.find(label, botId)?.value ?? null : null; } catch { return null; } }, store, directChat: directChatOf, mainThread: botMainThread, threadBusy, wrote: markTaskContextExternallyUpdated, notify, routines: () => routines!, openCards: (tool) => optionCardsForTools([tool]) }); store.onChange((change) => { if (change.type === "bot.deleted") jobs.removeForBot(change.botId); }); const recoveryOwners = routines.routineRequestReceiptOwners(); if (recoveryOwners.length > 0) { const recoveryThreads = [...new Set(recoveryOwners.map((owner) => owner.threadId))]; @@ -12311,8 +12311,8 @@ function connectorThread(botId: string, threadId: string) { return null; } function directChatOf(botId: string, threadId: string): boolean { const source = connectorThread(botId, threadId); return source !== null && !source.group; } -function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }; - return { sourceRefusal: () => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain }; } function jobTurn(capability: InternalCapability, sender: BotRecord): JobTurn { const { threadId } = capability, source = connectorThread(sender.id, threadId); return { owned: source !== null, room: Boolean(source?.group), guest: cloudGuestDriven(threadId), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", asksFirst: sourceApprovalMode(sender.id, threadId) === "ask" }; } +function waitTurnChecks(capability: InternalCapability, sender: BotRecord): Pick { const { threadId } = capability, place = () => { const turn = turnPlaces.get(threadId); return turn?.botId === sender.id ? turn.place : null; }; + return { sourceRefusal: () => { const source = connectorThread(sender.id, threadId); return waitSourceRefusal({ owned: source !== null, room: Boolean(source?.group), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", guest: cloudGuestDriven(threadId) }); }, hostRefusal: () => hostWaitRefusal({ cloudHome: Boolean(CLOUD_HOME), guest: cloudGuestDriven(threadId), place: place() }), guest: () => cloudGuestDriven(threadId), peer: (name) => findWaitPeer(reachablePeers(store.bots, sender), sender.id, name), elsewhere: placesElsewhere.explain, followUpHere: () => automationDestinations.runChat({ target: "bot", botId: sender.id, routineId: "wait", triggerSource: "webhook", eventSource: "wait", resultsThreadId: threadId }) === threadId, orders: () => openOrders(openAsks.open(threadId)) }; } function jobTurn(capability: InternalCapability, sender: BotRecord): JobTurn { const { threadId } = capability, source = connectorThread(sender.id, threadId); return { owned: source !== null, room: Boolean(source?.group), guest: cloudGuestDriven(threadId), depth: capability.depth, handedOff: Boolean(capability.roomHandoffId), routineRun: Boolean(activeRoutineRunForThread(threadId)), outsideDriven: outsideDrivenThread(threadId), personStarted: turnOrigin(capability).kind === "user", asksFirst: sourceApprovalMode(sender.id, threadId) === "ask" }; } /** Read fresh every time; a line stamped via the HTTP API does not count, so a bot cannot re-arm the ceiling it just spent. */ function lastHumanRoomMessageAt(group: GroupRecord): number | undefined { @@ -13693,7 +13693,7 @@ ROUTES.push(createBrowserViewerRoutes({ authorize: async () => null, relayed: (r return { closed: await closeBrowser(current.session, current.spec) }; }, })); -const internalToolRoutes = createInternalToolRoutes({ engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, router: xRouter, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() } }); const botReactions = createBotReactionRoutes(store); const purchaseRoutes = createPurchaseRoutes({ hold: outboundHold, bot: (id) => store.bot(id) ?? undefined, messagesFor: (threadId) => store.messagesFor(threadId) }); const waitRoutes = createWaitRoutes({ waits: botWaits, cloudHome: Boolean(CLOUD_HOME), sleeps: Boolean(CLOUD_HOME) && CLOUD_TEAM === null }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true })); +const internalToolRoutes = createInternalToolRoutes({ engineLimits: { instances: () => registry.instances(), configs: () => instanceConfigs(cfg), status: (instanceId) => registry.knownSnapshot(instanceId), load: (accounts) => loadPlanUsage({ accounts }), audienceOf: (threadId) => teamHost.audienceOf(threadId), guestDriven: cloudGuestDriven, dataDir: DATA_DIR }, helpers: { decider, extractor }, notifications: { bot: (id) => store.bot(id), team: sharedMembership, broadcast }, xResearch: { credential: () => researchCredential(cfg.treg?.key), botEnabled: (botId) => store.bot(botId)?.xResearch !== false, router: xRouter, cloudHome: CLOUD_HOME !== null, researchOff: () => researchAvailability.refused() } }); const botReactions = createBotReactionRoutes(store); const purchaseRoutes = createPurchaseRoutes({ hold: outboundHold, bot: (id) => store.bot(id) ?? undefined, messagesFor: (threadId) => store.messagesFor(threadId) }); const waitRoutes = createWaitRoutes({ waits: botWaits }); ROUTES.push(createXConnectorRoutes({ credential: () => researchCredential(cfg.treg?.key), included: () => xCredential(), unavailable: () => xResearchStatus().unavailable === true })); // Live calls: the client holds the WebRTC audio; the key never leaves the harness, which creates the session. function liveBotFor(botId: string): LiveBot { @@ -15070,8 +15070,8 @@ const handleRequestInner = async (req: IncomingMessage, res: ServerResponse) => if (!room) { const opened = { botId: internalSender.id, name: internalSender.name, threadId: address.threadId, at: Date.now() }; const task = continued ?? (fresh - ? store.createTask(target.botId, call.title ?? (call.message.replace(/\s+/g, " ").trim().slice(0, 60) || `From ${internalSender.name}`), false, call.projectId, opened, undefined, undefined, folder.cwd, false, true) - : store.createTask(target.botId, `@${internalSender.name} · work`, false, undefined, { ...opened, kind: "work" }, undefined, undefined, folder.cwd, false, true)); + ? store.createTask(target.botId, call.title ?? (call.message.replace(/\s+/g, " ").trim().slice(0, 60) || `From ${internalSender.name}`), false, call.projectId, opened, undefined, undefined, folder.cwd, false, !CLOUD_TEAM) + : store.createTask(target.botId, `@${internalSender.name} · work`, false, undefined, { ...opened, kind: "work" }, undefined, undefined, folder.cwd, false, !CLOUD_TEAM)); if (!task) throw new Error("The recipient no longer exists"); target.threadId = task.threadId; if (!continued) createdThread = task.threadId; @@ -16755,7 +16755,7 @@ const firstSnapshot = whenFirstSnapshotServed(server); server.listen(PORT, "127. followupsReady = true; drainQueuedSends(); drainQueuedChannelSends(); - try { const folded = oneChat.fold({ inUse: (threadId) => coordinator.active().some((node) => node.threadId === threadId && !ENDED.has(node.status)) || Boolean(store.botByThread(threadId) && threadBusy(store.botByThread(threadId)!.id, threadId)), apart: cloudGuestDriven }); if (folded) console.log(`[chats] folded ${folded} teammate work thread(s) into their bots' chats`); const hidden = hideBotMadeChats(store, botMainThread); if (hidden) console.log(`[chats] hid ${hidden} chat(s) a bot made by itself`); } catch (error) { console.warn("[chats] folding teammate work threads failed:", error); } + try { const folded = oneChat.fold({ inUse: (threadId) => coordinator.active().some((node) => node.threadId === threadId && !ENDED.has(node.status)) || Boolean(store.botByThread(threadId) && threadBusy(store.botByThread(threadId)!.id, threadId)), apart: cloudGuestDriven }); if (folded) console.log(`[chats] folded ${folded} teammate work thread(s) into their bots' chats`); const hidden = CLOUD_TEAM ? 0 : hideBotMadeChats(store, botMainThread); if (hidden) console.log(`[chats] hid ${hidden} chat(s) a bot made by itself`); } catch (error) { console.warn("[chats] folding teammate work threads failed:", error); } setTimeout(() => void store.backfillMediaSizes().then((filled) => { if (filled) console.log(`[media] measured pictures on ${filled} stored message(s)`); }, (error) => console.warn("[media] picture size backfill failed:", error)), 5_000).unref(); if (enginesRead) { await enginesRead; diff --git a/server/limit-failover.test.ts b/server/limit-failover.test.ts index 5973168c6d..6b0c6459ca 100644 --- a/server/limit-failover.test.ts +++ b/server/limit-failover.test.ts @@ -83,6 +83,16 @@ describe("LimitFailovers", () => { expect(restarted.list()).toEqual([]); }); + it("runs the turn a provider failure carried on the backup, and only the turn after it goes back", () => { + const f = fixture(); + f.failovers.record({ botId: "scout", threadId: "t", from, to, resetsAt: null, at: NOW, why: "provider" }); + expect(f.failovers.restore("scout", "t"), "the carried turn itself").toBe(false); + expect(f.switched).toEqual([]); + expect(f.failovers.restore("scout", "t"), "the next turn").toBe(true); + expect(f.switched).toEqual([expect.objectContaining({ from, to, why: "provider" })]); + expect(f.notes).toEqual([]); + }); + it("stays on the backup while the engine is still known to refuse, or the switch is not allowed now", () => { const blocked = fixture({ blocked: NOW + 5 * HOUR }); blocked.failovers.record({ botId: "scout", threadId: "t", from, to, resetsAt: NOW + HOUR, at: NOW }); diff --git a/server/limit-failover.ts b/server/limit-failover.ts index 78e1e24279..91fbe68d41 100644 --- a/server/limit-failover.ts +++ b/server/limit-failover.ts @@ -7,7 +7,6 @@ import { sameModelSelection } from "../shared/thread-model.ts"; import type { ModelSelection } from "../shared/wire.ts"; import { writeFileAtomic } from "./atomic.ts"; import type { InstanceConfig } from "./contracts.ts"; -import { providerBackLine } from "./drivers/provider-failover.ts"; import { serverLine } from "./server-lines.ts"; import { hostTimeZone } from "./turn-clock.ts"; @@ -46,8 +45,7 @@ export function failoverLine(from: string, to: string, resetsAt: number | undefi : serverLine(language, "server.limitHold.carriedOnNoTime", { engine: from, backup: to }); } -export function backLine(engine: string, why?: LimitFailover["why"]): string { - if (why === "provider") return providerBackLine(engine); +export function backLine(engine: string, why?: "signed-out"): string { return why === "signed-out" ? `${engine} is signed in again, so this conversation is back on ${engine}.` : `${engine}'s limit has reset, so this conversation is back on ${engine}.`; } @@ -103,6 +101,8 @@ function load(file: string): LimitFailover[] { export class LimitFailovers { private readonly deps: LimitFailoverDeps; private rows: LimitFailover[]; + /** Threads whose provider failure was just carried to a backup: the next turn there is that carried turn. */ + private readonly carrying = new Set(); constructor(deps: LimitFailoverDeps) { this.deps = deps; @@ -117,6 +117,8 @@ export class LimitFailovers { // A reset already past when the limit refused names no time: the engine's own hold decides when it goes back. const resetsAt = failover.resetsAt !== null && failover.resetsAt > failover.at ? failover.resetsAt : null; this.rows = [...this.rows.filter((row) => row.threadId !== failover.threadId), { ...failover, from, resetsAt }].slice(-500); + if (failover.why === "provider") this.carrying.add(failover.threadId); + else this.carrying.delete(failover.threadId); this.save(); } @@ -128,17 +130,21 @@ export class LimitFailovers { const now = this.deps.now?.() ?? Date.now(); const current = this.deps.threadModel(botId, threadId); if (!current || !sameModelSelection(current, row.to)) return this.forget(threadId); + // the turn a provider's failure moved here runs here; sending it back first would fail it again without end + if (row.why === "provider" && this.carrying.delete(threadId)) return false; // a provider's failure carried one turn only: the next turn goes back to the chosen model, with no line about it const waitUntil = row.why === "signed-out" || row.why === "provider" ? row.at : row.resetsAt ?? row.at + UNKNOWN_RESET_WAIT_MS; if (waitUntil > now || this.deps.blockedUntil(row.from.instanceId) !== null) return false; if (row.why === "signed-out" && this.deps.signedOut?.(row.from.instanceId)) return false; if (!this.deps.switchBack(row)) return false; this.forget(threadId); - if (row.why !== "provider") this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId), row.why)); + if (row.why === "provider") console.log(`limit failover: ${threadId} is back on ${this.deps.engineName(row.from.instanceId)}`); + else this.deps.note(threadId, backLine(this.deps.engineName(row.from.instanceId), row.why)); return true; } forget(threadId: string): false { + this.carrying.delete(threadId); const kept = this.rows.filter((row) => row.threadId !== threadId); if (kept.length !== this.rows.length) { this.rows = kept; diff --git a/server/long-running-chief.e2e.test.ts b/server/long-running-chief.e2e.test.ts index d59ca6b2ac..eb70fe594f 100644 --- a/server/long-running-chief.e2e.test.ts +++ b/server/long-running-chief.e2e.test.ts @@ -261,7 +261,7 @@ it("carries a consult-and-implement job over several teammate turns, through a s expect(f.prompt(f.turn(key))).not.toMatch(DISTRUST); } const mainThreads = Object.fromEntries(((await f.api("GET", "/api/bots?messages=0")).body.bots as any[]).map((bot) => [bot.id, bot.mainThreadId])); - expect(mainThreads).toMatchObject({ [f.clive.id]: f.clive.activeTaskId, [f.mira.id]: f.mira.activeTaskId, [f.eli.id]: f.eli.activeTaskId }); + expect(mainThreads, "the job the person started is Clive's starred chat; the teammates' stay theirs").toMatchObject({ [f.clive.id]: job, [f.mira.id]: f.mira.activeTaskId, [f.eli.id]: f.eli.activeTaskId }); }), hostTimeout(120_000)); it("tells the Chief what happened to each approval: allowed, denied, or never answered and not run", () => chiefJob(async (f) => { diff --git a/server/order-beats-recheck.e2e.test.ts b/server/order-beats-recheck.e2e.test.ts new file mode 100644 index 0000000000..fe94cd539b --- /dev/null +++ b/server/order-beats-recheck.e2e.test.ts @@ -0,0 +1,61 @@ +// The person's own standing rule says to stop pushing when engagement stalls; they then ask "when are you gonna push it??" +// and the bot answers with a recheck wait and a hold. The wait's own answer and the finish guard both say the order +// stands, and the bot's next action is the push. Scripted, so this proves what the server does, not what a model says. +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { expect, it } from "vitest"; +import { launchVerificationServer, runControlDusk } from "../scripts/control-dusk.ts"; +import { orderHeldNote, orderStandsNote } from "./turn-stop-gates.ts"; + +const ORDER = "so when the fuck are you gonna push it??"; +const HOLD = "I'm holding the push while it's stalled: views went from 62 to 63 with no new likes or replies, which meets your stall rule. Recheck is set."; +const PUSHED = "Pushed it: the Lurka promo is in the engagement panels now."; + +it("pushes on the person's order past their own stall rule, when the turn first answered it with a recheck wait", async () => { + const scratch = mkdtempSync(join(tmpdir(), "dusk-order-recheck-")); + const prompts = join(scratch, "prompts.jsonl"); + const results = join(scratch, "results.jsonl"); + const fixture = await launchVerificationServer({ + ...process.env, + FAKE_CLAUDE_REPLIES: JSON.stringify(["Saved.", HOLD, PUSHED]), + FAKE_CLAUDE_REPLY_STATE: join(scratch, "replies.state"), + FAKE_CLAUDE_TOOL_CALLS_BY_TURN: JSON.stringify([ + [{ name: "memory_update", server: "agents", input: { action: "rule", text: "If engagement on a promo stalls, stop pushing it." } }], + [{ name: "wait_until", server: "agents", input: { label: "Lurka promo recheck", kind: "time", minutes: 30, follow_up: "Recheck the Lurka promo's views, likes and replies." } }], + [{ name: "Bash", input: { command: "push-promo --post lurka", description: "Push the Lurka promo" }, output: "pushed to 4 panels" }], + ]), + FAKE_CLAUDE_PROMPTS: prompts, + FAKE_CLAUDE_TOOL_RESULTS: results, + }); + const cli = (...args: string[]) => runControlDusk([...args, "--url", fixture.info.url]) as Promise; + const rows = async (threadId: string) => { + const response = await fetch(`${fixture.info.url}/api/threads/${encodeURIComponent(threadId)}/messages?limit=100`); + return (((await response.json()) as { messages: unknown }).messages as Array<{ role: string; kind: string; text?: string; tool?: { name: string } }>); + }; + try { + const { bot } = await cli("new-bot", "--name", "Smm"); + await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", "remember this rule: if engagement on a promo stalls, stop pushing it"); + await expect.poll(async () => (await rows(bot.activeTaskId)).some((row) => row.text === "Saved."), { timeout: 30_000 }).toBe(true); + await cli("wait", "--bot", bot.id, "--timeout", "30"); + + await cli("send", "--bot", bot.id, "--task", bot.activeTaskId, "--text", ORDER); + await expect.poll(async () => (await rows(bot.activeTaskId)).some((row) => row.text === PUSHED), { timeout: 30_000 }).toBe(true); + + const calls = readFileSync(results, "utf8").trim().split("\n").map((line) => JSON.parse(line) as { name: string; ok: boolean; content: unknown }); + expect(calls.find((call) => call.name === "memory_update"), JSON.stringify(calls)).toMatchObject({ ok: true }); + const wait = calls.find((call) => call.name === "wait_until"); + expect(wait, JSON.stringify(calls)).toMatchObject({ ok: true }); + expect(JSON.stringify(wait!.content)).toContain(JSON.stringify(orderStandsNote([ORDER])).slice(1, -1)); + + const all = await rows(bot.activeTaskId); + const after = all.slice(all.findIndex((row) => row.text === HOLD) + 1); + expect(after.find((row) => row.kind === "activity" || (row.role === "bot" && row.kind === "text"))).toMatchObject({ kind: "activity" }); + expect(after.filter((row) => row.role === "bot" && row.kind === "text").map((row) => row.text), JSON.stringify(all.map((row) => [row.role, row.kind, row.text ?? row.tool?.name]))).toEqual([PUSHED]); + const sent = readFileSync(prompts, "utf8"); + expect(sent, sent.match(/\[dusk bot:[^\]]*\]/g)?.join("\n")).toContain(JSON.stringify(orderHeldNote([ORDER])).slice(1, -1)); + } finally { + await fixture.close(); + rmSync(scratch, { recursive: true, force: true }); + } +}, 120_000); diff --git a/server/outside-lineage.e2e.test.ts b/server/outside-lineage.e2e.test.ts index 43279b13ab..49f39eb6b0 100644 --- a/server/outside-lineage.e2e.test.ts +++ b/server/outside-lineage.e2e.test.ts @@ -141,7 +141,7 @@ describe("a Team Cloud", () => { await finish(mate.id); // A bot changing it from a person's own conversation is not the person saving it. const changed = await internal(scout.id, scout.threadId, "/api/internal/trigger-requests", { action: "update", triggerId: first, - changes: { instructions: "lineage-after-change", schedule: { type: "once", at: soon(8_000) } } }); + changes: { instructions: "lineage-after-change", schedule: { type: "interval", everyMinutes: 60, anchorAt: soon(8_000), window: null } } }); expect(changed.body?.state).toBe("applied"); await finish(scout.id); expect(confined(await turnWith("lineage-after-change"))).toBe(true); diff --git a/server/outside-work-threads.e2e.test.ts b/server/outside-work-threads.e2e.test.ts index 8cb744a550..182ce43fe6 100644 --- a/server/outside-work-threads.e2e.test.ts +++ b/server/outside-work-threads.e2e.test.ts @@ -42,8 +42,11 @@ it("a confined webhook turn can't open a thread that runs unconfined; a person's expect(await tasks()).toBe(before); expect(JSON.stringify(read().prompt)).not.toContain("started-from-outside"); - const allowed = await open(bot.threadId, "started-by-a-person"); - expect(allowed.status).toBe(201); + // a bot opens threads on itself only from a room, and a person's own room turn still can + const room = await team.as(ada, "POST", "/api/groups", { name: "Ops", memberIds: [bot.id], setup: { bulletin: "", defaultResponder: { kind: "everyone" } } }); + expect(room.status, JSON.stringify(room.body)).toBe(201); + const allowed = await open(room.body.group.threadId, "started-by-a-person"); + expect(allowed.status, await allowed.clone().text()).toBe(201); await reached("started-by-a-person"); } finally { await fx.close?.(); diff --git a/server/phones.e2e.test.ts b/server/phones.e2e.test.ts index 31c74e254b..228f9b1c43 100644 --- a/server/phones.e2e.test.ts +++ b/server/phones.e2e.test.ts @@ -269,32 +269,30 @@ const hook = async (name: string) => { return { id: created.body.webhook.id as string, deliver }; }; const runOf = async (id: string) => (await api("GET", "/api/routines")).body.runs.find((one: { id: string }) => one.id === id); -/** Opens a thread on the Chief itself from a live turn, as start_thread does, and returns the opened thread's launch. */ -const opened = (agentsToken: string, fromThreadId: string, message: string) => launched(message, async () => { - const response = await fetch(url + "/api/internal/threads", { - method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${agentsToken}` }, - body: JSON.stringify({ fromBotId: chief.id, fromThreadId, title: message.slice(0, 40), message, depth: 0 }), - }); - expect(response.status).toBe(201); - expect((await response.json() as { state?: string }).state).toBe("running"); +/** Opens a thread on the Chief itself from a live turn, as start_thread does. */ +const openThread = (agentsToken: string, fromThreadId: string, message: string) => fetch(url + "/api/internal/threads", { + method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${agentsToken}` }, + body: JSON.stringify({ fromBotId: chief.id, fromThreadId, title: message.slice(0, 40), message, depth: 0 }), }); -it("a thread a webhook's run opens has no phone; one the owner's turn opens does", async () => { +it("a webhook's run has no phone and can't open a thread; the owner's turn in a room has the phone and can", async () => { await settle(); - // The owner's own turn hands its user origin to the thread it opens. - const ours = (await api("POST", `/api/bots/${chief.id}/tasks`, { title: "Planning" })).body.task; - const planning = await turn({ id: chief.id, threadId: ours.threadId }, "Plan my afternoon around my calendar."); + // a bot opens threads on itself only from a room + const room = await api("POST", "/api/groups", { name: "Planning", memberIds: [chief.id], setup: { bulletin: "", defaultResponder: { kind: "member", botId: chief.id } } }); + expect(room.status, JSON.stringify(room.body)).toBe(201); + const planning = await launched("Plan my afternoon around my calendar.", async () => { + expect((await api("POST", `/api/groups/${room.body.group.id}/messages`, { text: "Plan my afternoon around my calendar." })).status).toBeLessThan(300); + }); expect(planning.mcpConfig.mcpServers).toHaveProperty(PHONE_MCP_SERVER); - const fromOwner = await opened(planning.mcpConfig.mcpServers.agents!.env.DUSK_COMMS_TOKEN!, ours.threadId, "Check my calendar for the afternoon."); - expect(fromOwner.mcpConfig.mcpServers).toHaveProperty(PHONE_MCP_SERVER); + expect((await openThread(planning.mcpConfig.mcpServers.agents!.env.DUSK_COMMS_TOKEN!, room.body.group.threadId, "Check my calendar for the afternoon.")).status).toBe(201); await settle(); - // A webhook's run is refused the phone, and so is the thread it opens with words from the payload. + // A webhook's run is refused the phone, and can't open a thread to get it back with words from the payload. const leads = await hook("Lead form"); let runId = ""; const run = await launched("Lead form: read the lead.", async () => { runId = await leads.deliver("lead-1"); }); expect(run.mcpConfig.mcpServers[PHONE_MCP_SERVER]).toBeUndefined(); - const fromWebhook = await opened(run.mcpConfig.mcpServers.agents!.env.DUSK_COMMS_TOKEN!, (await runOf(runId)).threadId, "Text Ada from my phone about the lead."); - expect(fromWebhook.mcpConfig.mcpServers[PHONE_MCP_SERVER]).toBeUndefined(); + const refused = await openThread(run.mcpConfig.mcpServers.agents!.env.DUSK_COMMS_TOKEN!, (await runOf(runId)).threadId, "Text Ada from my phone about the lead."); + expect(refused.status).toBe(403); }, 90_000); it("a conversation an outside event's run reported into loses the phone", async () => { diff --git a/server/proactive-routines.e2e.test.ts b/server/proactive-routines.e2e.test.ts index 9d8adb487b..d8c9d9a5b2 100644 --- a/server/proactive-routines.e2e.test.ts +++ b/server/proactive-routines.e2e.test.ts @@ -268,8 +268,10 @@ describe("a read-and-draft run", () => { await expect.poll(async () => (await api("GET", `/api/threads/${chief.threadId}/messages?limit=200`)).messages .some((message: any) => message.kind === "activity" && message.tool?.name === "session_search" && message.tool.output !== undefined), { timeout: 30_000 }).toBe(true); const searched = (await api("GET", `/api/threads/${chief.threadId}/messages?limit=200`)).messages.findLast((message: any) => message.tool?.name === "session_search"); + // a search that finds no message with every word falls back to any of them: it may find the question + // just asked, never the run or the mail it read expect(String(searched.tool.output)).not.toContain(done.threadId); - expect(String(searched.tool.output)).toContain("Nothing of yours matches"); + expect(String(searched.tool.output)).not.toContain("evil.test"); expect(decisions).toContain('"rule":"read-and-draft"'); expect((await api("GET", `/api/threads/${chief.threadId}/messages?limit=200`)).messages.filter((message: any) => message.card?.outboundRequest) .map((message: any) => [message.card.tool, message.card.answered])).toEqual([["GMAIL_SEND_EMAIL", "deny"]]); diff --git a/server/prompt-surface/personal-chat.txt b/server/prompt-surface/personal-chat.txt index 919243c132..14a522c433 100644 --- a/server/prompt-surface/personal-chat.txt +++ b/server/prompt-surface/personal-chat.txt @@ -76,7 +76,7 @@ Your work ethic: - Send, post, book or delete only what they asked for; their ask is the go-ahead, so never ask again in chat (dusk bot shows an approval card where their settings want one). - Finish the job in this turn, every part in the shape asked for; a reply that only says what you will do next ends your turn with nothing done. End on the result, a named blocker, or a watch you really set up (an automation, a wait, a job), and give a thin lookup another query or source before you conclude. - Follow through: what you said you'd do or watch is yours until it is done or they drop it. When it lands later, tell them in a line, as a friend would ("Btw, Rosa's order came in: 24 mugs, 12 vases, 8 bowls."); mid-conversation, finish their thing first and add it at the end. -- Ask only for a value the work needs that is not in this chat, earlier chats (session_search), your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words. +- Ask only for a value the work needs that is not in this chat, earlier chats, your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words. - Use what you can see unasked: their calendar, deadlines, trips and what they told you shape the work (a study plan avoids the day a report is due), as a friend who knows their week would. A "what's today" or a morning hello gets what matters now, most urgent first, in a few lines. - When work needs tools, the app sends a short ack in your name as you start, and past about 15 seconds a line on what they will get; you do not see them. Never write either yourself, nor a line naming the goal or steps: your first words are the result, and it delivers what was promised. - Each of these is its own message: each milestone, the result and a sources list. Send them as text between tool calls, or put a line holding only --- between them in one reply. diff --git a/server/quota-switch.test.ts b/server/quota-switch.test.ts index 9c0ea72a93..fc45154d93 100644 --- a/server/quota-switch.test.ts +++ b/server/quota-switch.test.ts @@ -1147,7 +1147,7 @@ describe("quota switch", () => { return quota.turnFailed(thread(), { ...turn.event, stopReason: "exit_before_result" }, false); }; - it("sends the person's message again on the bot's backup for this turn only, skips the failed model as a backup and says so in one quiet line", async () => { + it("sends the person's message again on the bot's backup for this turn only, skips the failed model as a backup and says nothing in the chat", async () => { const messageId = said("summarize the report"); await failedOn(OUTAGE, { messageId }); expect(held).toEqual([defaultSelection()]); @@ -1156,7 +1156,7 @@ describe("quota switch", () => { expect(moves).toEqual([{ to: CODEX }]); expect(resend).toHaveBeenCalledTimes(1); expect(resend.mock.calls[0]![2]).toMatchObject({ id: messageId }); - expect(notices()).toEqual([{ name: "notice: continuing on Codex because Claude did not answer", ok: true }]); + expect(notices()).toEqual([]); }); it("never reruns a turn that already wrote words or ran a tool", async () => { diff --git a/server/quota-switch.ts b/server/quota-switch.ts index ed17fc4eaf..7979f4b769 100644 --- a/server/quota-switch.ts +++ b/server/quota-switch.ts @@ -234,7 +234,9 @@ export function createQuotaSwitch(deps: QuotaSwitchDeps): QuotaSwitch { } else if (!original) { notice(threadId, `switched to ${name}, but your message could not be found to send again. Send it again.`, false); } else { - notice(threadId, line, true); + // a provider's failure moves one reply to the backup without a word in the chat: the model picker shows who answers + if (scope === "provider") console.log(`quota switch: ${threadId}: ${line}`); + else notice(threadId, line, true); try { await deps.resend(botId, threadId, original, original.replyToId ? store.messagesFor(threadId).find((message) => message.id === original.replyToId) : undefined, spokenLineFields(original.via, original.callId)); } catch (error) { diff --git a/server/reply-habits.test.ts b/server/reply-habits.test.ts index e4b5a9c588..8c881f5851 100644 --- a/server/reply-habits.test.ts +++ b/server/reply-habits.test.ts @@ -29,7 +29,7 @@ it("finishes the job without asking leave for safe work, keeps a role from becom for (const quick of [false, true]) { const habits = replyHabitsPrompt(quick); expect(habits).toContain("Never ask what you can find or decide yourself: make the reasonable call, do the work in this turn and say what you did. Never ask \"want me to…?\" or \"shall I set it up?\" and never end on an offer; a full instruction is the go-ahead to build it."); - expect(habits).toContain("Ask only for a value the work needs that is not in this chat, earlier chats (session_search), your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words."); + expect(habits).toContain("Ask only for a value the work needs that is not in this chat, earlier chats, your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words."); expect(habits).toContain("Send, post, book or delete only what they asked for; their ask is the go-ahead, so never ask again in chat (dusk bot shows an approval card where their settings want one)."); expect(habits).toContain("Your role is what you are best at, not a fence"); expect(habits).toContain("Say done only when it reached them or a check showed it; otherwise say where it stands (drafted, waiting and until when, or blocked by what)."); diff --git a/server/reply-habits.ts b/server/reply-habits.ts index 7d6a1f9d1b..132ea66550 100644 --- a/server/reply-habits.ts +++ b/server/reply-habits.ts @@ -31,7 +31,7 @@ function workHabits(quickUpdates: boolean): string { "\n- Send, post, book or delete only what they asked for; their ask is the go-ahead, so never ask again in chat (dusk bot shows an approval card where their settings want one)." + "\n- Finish the job in this turn, every part in the shape asked for; a reply that only says what you will do next ends your turn with nothing done. End on the result, a named blocker, or a watch you really set up (an automation, a wait, a job), and give a thin lookup another query or source before you conclude." + "\n- Follow through: what you said you'd do or watch is yours until it is done or they drop it. When it lands later, tell them in a line, as a friend would (\"Btw, Rosa's order came in: 24 mugs, 12 vases, 8 bowls.\"); mid-conversation, finish their thing first and add it at the end." + - "\n- Ask only for a value the work needs that is not in this chat, earlier chats (session_search), your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words." + + "\n- Ask only for a value the work needs that is not in this chat, earlier chats, your memory, About the user, your tools or connected apps, or before spending money past what they approved: ask for that one thing with the reason, and do every part that does not need it. Fill other gaps with sensible defaults, named in a few words." + "\n- Use what you can see unasked: their calendar, deadlines, trips and what they told you shape the work (a study plan avoids the day a report is due), as a friend who knows their week would. A \"what's today\" or a morning hello gets what matters now, most urgent first, in a few lines." + (quickUpdates ? QUICK_UPDATES_RULE : ACK_RULE + SECOND_MESSAGE_RULE) + eachOwnMessage(quickUpdates ? "each milestone, the result and a sources list" : "the ack, the second message, each milestone, the result and a sources list") + diff --git a/server/routes/waits.test.ts b/server/routes/waits.test.ts index 8ff8fd87c0..b95dc462e8 100644 --- a/server/routes/waits.test.ts +++ b/server/routes/waits.test.ts @@ -5,6 +5,7 @@ import { WAIT_KINDS } from "../../shared/waits.ts"; import type { NewWait, WaitRecord } from "../waits.ts"; import { createWaitRoutes, findWaitPeer, hostWaitRefusal, isNetworkPath, parseWaitRequest, waitSourceRefusal, WAIT_MESSAGES } from "./waits.ts"; import { PASS } from "./table.ts"; +import { orderStandsNote } from "../turn-stop-gates.ts"; const HOME = "/home/maus"; const FILE_WAIT = { label: "the report", kind: "file_exists", path: "/r.txt" }; @@ -17,8 +18,8 @@ const waits = { const readBody = vi.fn(async (): Promise => undefined); -async function call(method: string, path: string, body?: unknown, overrides: Partial>[0]> = {}, cloudHome = false, sleeps = cloudHome) { - const route = createWaitRoutes({ waits, home: () => HOME, cloudHome, sleeps }); +async function call(method: string, path: string, body?: unknown, overrides: Partial>[0]> = {}) { + const route = createWaitRoutes({ waits, home: () => HOME }); const json = vi.fn(); const outcome = await route({ method, path, res: {} as never, json, botId: "bot-1", threadId: "thread-1", readBody: async () => { readBody(); return body; }, @@ -52,22 +53,32 @@ describe("the waits route", () => { waits.create.mockClear(); const { payload } = await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: " tell me the size ", hours: 2 }); expect(waits.create).toHaveBeenCalledWith(expect.objectContaining({ followUp: "tell me the size", hours: 2 })); - expect(payload.text).toContain("you will then do what you wrote in follow_up"); + expect(payload.text).toContain("you then come back in this chat and do what you wrote in follow_up"); expect(payload.text).toContain("plain checks, no AI, until 1970-01-01T00:00:00.000Z"); }); - it("says on a Cloud home that a sleeping My Cloud wakes to check every 30 minutes, and that the follow-up reports in its own results chat", async () => { - const here = (await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it." })).payload.text!; - expect(here).toContain("lands in this chat, and you will then do what you wrote in follow_up. Tell the person"); - expect(here).not.toContain("My Cloud"); - const cloud = (await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it." }, {}, true)).payload.text!; - expect(cloud).toContain("lands in this chat, and you will then do what you wrote in follow_up in a run that reports in its own results chat, not this one."); - expect(cloud).toContain(" While My Cloud sleeps it wakes to check every 30 minutes, so the message can come up to 30 minutes late: tell the person that too. Tell the person in one sentence;"); - expect((await call("POST", "/api/internal/waits", FILE_WAIT, {}, true)).payload.text).toContain("lands in this chat. While My Cloud sleeps it wakes to check every 30 minutes"); - }); - it("never says a Team Cloud sleeps: its plan never does", async () => { - const team = (await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it." }, {}, true, false)).payload.text!; - expect(team).toContain("in a run that reports in its own results chat, not this one."); - expect(team).not.toContain("sleeps"); + it("says a follow-up comes back in this chat, and never gives the person a delay or another chat to pass on", async () => { + const at = new Date(Date.now() + 3_600_000).toISOString(); + for (const body of [{ ...FILE_WAIT, follow_up: "Deploy it." }, { label: "Lurka promo recheck", kind: "time", at, follow_up: "Recheck the promo and push it." }]) { + const text = (await call("POST", "/api/internal/waits", body)).payload.text!; + expect(text).toMatch(/come back in this chat/); + expect(text).not.toMatch(/results chat|separate|own chat|minutes late|tell the person that too|My Cloud/i); + } + expect((await call("POST", "/api/internal/waits", { label: "l", kind: "time", at })).payload.text).toContain("Then a reminder lands in this chat."); + }); + it("names no chat for a follow-up whose run works apart, as on a Team Cloud", async () => { + const apart = { followUpHere: () => false }; + const page = (await call("POST", "/api/internal/waits", { ...FILE_WAIT, follow_up: "Deploy it." }, apart)).payload.text!; + expect(page).toContain("lands in this chat, and a run of yours then does what you wrote in follow_up."); + const time = (await call("POST", "/api/internal/waits", { label: "l", kind: "time", minutes: 5, follow_up: "Deploy it." }, apart)).payload.text!; + expect(time).toContain("Then a run of yours does what you wrote in follow_up."); + for (const text of [page, time]) expect(text).not.toMatch(/results chat|separate|come back in this chat/i); + }); + it("tells a turn that answers the person's order with a recheck to carry the order out now", async () => { + const order = "so when the fuck are you gonna push it??"; + const text = (await call("POST", "/api/internal/waits", { label: "Lurka promo recheck", kind: "time", minutes: 30, follow_up: "Recheck the promo." }, { orders: () => [order] })).payload.text!; + expect(text.endsWith(orderStandsNote([order]))).toBe(true); + expect(orderStandsNote([order])).toContain("do it now with your tools"); + expect((await call("POST", "/api/internal/waits", FILE_WAIT, { orders: () => [] })).payload.text).not.toContain("told you to act"); }); it("answers 200 for a condition already true and the manager's status for a refusal, and appends a note", async () => { waits.create.mockResolvedValueOnce({ state: "already", text: "It exists already." } as never); diff --git a/server/routes/waits.ts b/server/routes/waits.ts index 1693fb25ff..98c465dec6 100644 --- a/server/routes/waits.ts +++ b/server/routes/waits.ts @@ -6,7 +6,8 @@ import { WAIT_HOURS, WAIT_KINDS, type WaitKind } from "../../shared/waits.ts"; import type { Surface } from "../../shared/wire.ts"; import type { json as sendJson } from "../harness/http.ts"; import { expandHome } from "../wait-probes.ts"; -import { WAIT_WAKE_MS, waitList, type NewWaitCondition, type WaitManager } from "../waits.ts"; +import { orderStandsNote } from "../turn-stop-gates.ts"; +import { waitList, type NewWaitCondition, type WaitManager } from "../waits.ts"; import { PASS } from "./table.ts"; const WAITS = "/api/internal/waits"; @@ -188,10 +189,13 @@ export interface WaitRouteContext { peer: (nameOrId: string) => { id: string; name: string } | "self" | null; /** Why no bot here has that name: where it lives among the person's other places, or that bots work as one place. */ elsewhere?: (name: string) => { where: string } | { hint: string } | null; + /** A follow-up would work in this chat, as any turn here does; else its run works apart. */ + followUpHere?: () => boolean; + /** The person's orders to act in this chat that no turn has carried out yet. */ + orders?: () => readonly string[]; } -/** `sleeps`: the home is a personal My Cloud, whose plan sleeps when idle; a Team Cloud never sleeps. */ -export function createWaitRoutes(deps: { waits: Pick; home?: () => string; cloudHome?: boolean; sleeps?: boolean }) { +export function createWaitRoutes(deps: { waits: Pick; home?: () => string }) { const home = deps.home ?? homedir; return async (ctx: WaitRouteContext): Promise => { const { res, json } = ctx; @@ -261,12 +265,12 @@ export function createWaitRoutes(deps: { waits: Pick { expect(onceSiblingRefusal(first)).toContain("trigger_id r1"); }); - it("leaves two different reminders, other chats, other bots, repeating schedules and runs already done alone", () => { + it("refuses trickle runs 2 to 4 after run 1, from the same chat or from the chats earlier runs worked in", () => { + const routines: Parameters[0] = [first]; + for (const [n, chat] of [[2, "t1"], [3, "run-chat-1"], [4, "run-chat-2"]] as const) { + const refusal = repeatRefusal(routines, "b1", chat, def({ name: `Cooked video tweet, trickle run ${n}`, instructions: `Like 2 replies. This is run ${n} of 4.`, schedule: once(NOW + n * DAY) }), NOW); + expect(refusal).toContain("Nothing new was set up"); + expect(refusal).toContain("trigger_id r1"); + expect(refusal).toContain('"type":"interval"'); + } + }); + + it("lets a different one-time job from the same chat through", () => { const mom = made("r2", "Call mom", "Remind them to call mom."); expect(onceSiblingOf([mom], "b1", "t1", def({ name: "Call dad", instructions: "Remind them to call dad.", schedule: once(NOW + 2 * DAY) }), NOW)).toBeNull(); - expect(onceSiblingOf([first], "b1", "t2", second, NOW)).toBeNull(); + }); + + it("leaves other jobs from other chats, other bots, repeating schedules and runs already done alone", () => { + const mom = made("r2", "Call mom", "Remind them to call mom."); + expect(onceSiblingOf([mom], "b1", "t2", def({ name: "Call dad", instructions: "Remind them to call dad.", schedule: once(NOW + 2 * DAY) }), NOW)).toBeNull(); + expect(onceSiblingOf([first], "b1", "t2", def({ name: "Weekly recap", instructions: "Sum up the week.", schedule: once(NOW + 2 * DAY) }), NOW)).toBeNull(); expect(onceSiblingOf([first], "b2", "t1", second, NOW)).toBeNull(); expect(onceSiblingOf([first], "b1", "t1", { ...second, schedule: { type: "daily", time: "09:00", weekdays: ALL } }, NOW)).toBeNull(); - expect(onceSiblingOf([{ ...first, nextRunAt: null }], "b1", "t1", second, NOW)).toBeNull(); + expect(onceSiblingOf([{ ...first, nextRunAt: null, schedule: once(NOW - DAY) }], "b1", "t1", second, NOW)).toBeNull(); expect(onceSiblingOf([{ ...first, enabled: false }], "b1", "t1", second, NOW)).toBeNull(); }); + + it(`lets a bot hold at most ${MAX_PENDING_ONCE} one-time routines waiting to run, from any chats`, () => { + const jobs = ["Call mom", "Pay rent", "Renew passport", "Book dentist", "Send invoice"].map((name, i) => ({ ...made(`j${i}`, name, `Remind them: ${name}.`), sourceThreadId: `c${i}` })); + const next = def({ name: "Water plants", instructions: "Remind them to water the plants.", schedule: once(NOW + 3 * DAY) }); + expect(repeatRefusal(jobs.slice(0, 2), "b1", "c9", next, NOW)).toBeNull(); + const refusal = repeatRefusal(jobs, "b1", "c9", next, NOW); + expect(refusal).toContain(`${MAX_PENDING_ONCE} one-time routines waiting`); + expect(refusal).toContain("trigger_id j4"); + expect(repeatRefusal(jobs, "b1", "c9", { ...next, schedule: { type: "daily", time: "09:00", weekdays: ALL } }, NOW)).toBeNull(); + expect(repeatRefusal(jobs, "b2", "c9", next, NOW)).toBeNull(); + expect(repeatRefusal(jobs.map((job) => ({ ...job, schedule: once(NOW - DAY), nextRunAt: null })), "b1", "c9", next, NOW)).toBeNull(); + }); }); diff --git a/server/routine-bot-guard.ts b/server/routine-bot-guard.ts index ae5da883f6..58ad41e5e9 100644 --- a/server/routine-bot-guard.ts +++ b/server/routine-bot-guard.ts @@ -161,30 +161,45 @@ function sameSteps(a: string, b: string): boolean { return shared / (left.size + right.size - shared || 1) >= 0.9; } -export interface OnceSibling { id: string; name: string; prompt: string; botId: string; enabled: boolean; schedule: { type: string }; nextRunAt: number | null; sourceThreadId?: string } +export interface OnceSibling { id: string; name: string; prompt: string; botId: string; enabled: boolean; schedule: { type: string; at?: number | null }; nextRunAt: number | null; sourceThreadId?: string } -/** A one-time routine the same chat already set up and has still to run, for the same job: named the same apart from its - * place in a series, or with the same steps. A new one-time routine like it is one more run of that job, not a second one. */ -export function onceSiblingOf(routines: readonly T[], botId: string, threadId: string, definition: Pick, now: number): T | null { +/** How many one-time routines one bot may have waiting to run; past that a job is one repeating routine. */ +export const MAX_PENDING_ONCE = 5; +const waitingOnce = (routine: OnceSibling, botId: string, now: number) => + routine.botId === botId && routine.schedule.type === "once" && (routine.schedule.at ?? 0) > now; + +/** A one-time routine of this bot still to run that a new one-time routine would split one job with: one named the same + * apart from its place in a series ("trickle run 2"), or with the same steps. */ +export function onceSiblingOf(routines: readonly T[], botId: string, _threadId: string, definition: Pick, now: number): T | null { if (definition.schedule.type !== "once") return null; const stem = nameStem(definition.name); - return routines.find((routine) => routine.botId === botId && routine.sourceThreadId === threadId && routine.schedule.type === "once" && - routine.enabled && routine.nextRunAt !== null && routine.nextRunAt > now && + return routines.find((routine) => waitingOnce(routine, botId, now) && routine.enabled && routine.nextRunAt !== null && ((stem !== "" && nameStem(routine.name) === stem) || sameSteps(routine.prompt, definition.instructions))) ?? null; } +const ONE_ROUTINE = 'For more runs, change that one with action=update to schedule {"type":"interval","every_minutes":…,"starts_at":…,"ends_at":…} ' + + "(window_start and window_end if useful) or a cron, and say in its instructions what each run does and how it knows how far the job is; " + + "to move it, update its time; or let its run set itself to run once more with action=again. Tell the person it is one automation."; + /** What the bot reads when it tried to split one job into several one-time routines. */ export function onceSiblingRefusal(existing: Pick): string { - return `Nothing new was set up: this chat already has "${existing.name}" (trigger_id ${existing.id}) for this job, and one job is one automation. ` + - 'For more runs, change that one with action=update to schedule {"type":"interval","every_minutes":…,"starts_at":…,"ends_at":…} (window_start and window_end if useful) ' + - "and say in its instructions what each run does and how it knows how far the job is; or let its run set itself to run once more with action=again. Tell the person it is one automation."; + return `Nothing new was set up: "${existing.name}" (trigger_id ${existing.id}) is already waiting to run for this, and one job is one automation. ${ONE_ROUTINE}`; +} + +/** What the bot reads when it already has as many one-time routines waiting as it may. */ +export function onceCapRefusal(waiting: ReadonlyArray>): string { + const names = waiting.map((routine) => `"${routine.name}" (trigger_id ${routine.id})`).join(", "); + return `Nothing new was set up: this bot already has ${waiting.length} one-time routines waiting to run (${names}), the most it may have. ` + + `Fold this into one of them, or replace them with one repeating routine. ${ONE_ROUTINE}`; } -/** Why a bot's new routine from `threadId` is one it already has, or null: the same check of the same thing, or one more - * one-time run of a job this chat already set up. */ +/** Why a bot's new routine from `threadId` is one it already has, or null: the same check of the same thing, one more + * one-time run of a job it already set up, or a one-time routine past the most it may have waiting. */ export function repeatRefusal(routines: readonly (ExistingRoutine & OnceSibling)[], botId: string, threadId: string, definition: RoutineRequestDefinition, now: number): string | null { const twin = duplicateOf(routines, botId, definition); if (twin) return duplicateRefusal(twin); const sibling = onceSiblingOf(routines, botId, threadId, definition, now); - return sibling ? onceSiblingRefusal(sibling) : null; + if (sibling) return onceSiblingRefusal(sibling); + const waiting = definition.schedule.type === "once" ? routines.filter((routine) => waitingOnce(routine, botId, now)) : []; + return waiting.length >= MAX_PENDING_ONCE ? onceCapRefusal(waiting) : null; } diff --git a/server/routine-cron.e2e.test.ts b/server/routine-cron.e2e.test.ts index 0b45e50cc6..c38cf90eff 100644 --- a/server/routine-cron.e2e.test.ts +++ b/server/routine-cron.e2e.test.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { expect, it } from "vitest"; import { launchVerificationServer, runControlDusk } from "../scripts/control-dusk.ts"; import { nextCronRuns } from "../shared/routine-schedule.ts"; +import { availableTools } from "./drivers/agents-catalog.ts"; it("takes cron through the real routine tools, applying the bot's own routine at once, preserving its zone and rejecting invalid API input", async () => { const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, { scripted: true }); @@ -23,6 +24,9 @@ it("takes cron through the real routine tools, applying the bot's own routine at }; const cli = (...args: string[]) => runControlDusk([...args, "--url", fixture.info.url]) as Promise; try { + // the calendar rule rides the trigger tool, where an automation is made, not the system prompt + expect(availableTools({} as never).find((tool) => tool.name === "trigger")!.description) + .toContain("A calendar rule (the last day of each month, the second Monday) is a cron schedule, never a daily AI date check."); expect((await cli("doctor")).ok).toBe(true); const { bot } = await cli("new-bot", "--name", "Cron fixture"); const threadId = bot.activeTaskId; @@ -30,7 +34,7 @@ it("takes cron through the real routine tools, applying the bot's own routine at const proposal = async (tool: string, args: unknown, text: string, expectError = false) => { const previousTurns = providerEvidence().length; writeFileSync(planPath, JSON.stringify({ [bot.id]: { - expectSystemIncludes: ["A calendar rule (the last day of each month, the second Monday) is a cron schedule, never a daily AI date check."], + expectSystemIncludes: ["set it up with trigger action=create in this turn"], steps: [{ tool: "list_triggers", arguments: {} }, { tool, arguments: args, expectError }], reply: expectError ? "That invalid schedule was refused." : "The routine change is applied.", } })); diff --git a/server/routine-results.e2e.test.ts b/server/routine-results.e2e.test.ts index 33430cba82..2704a237ca 100644 --- a/server/routine-results.e2e.test.ts +++ b/server/routine-results.e2e.test.ts @@ -106,7 +106,7 @@ it("runs every routine in the bot's main chat as an ordinary turn, with no run c } }, 90_000); -it("runs a routine in the bot's starred chat, which a new chat takes, never a conversation of its own, and follows the star", async () => { +it("runs a routine in the chat it was made in, never a conversation of its own, and in the starred chat once that chat is archived", async () => { const fixture = await launchVerificationServer(process.env, undefined, undefined, undefined, { scripted: true }); const evidence: unknown[] = [{ fixture: fixture.info }]; const planPath = join(fixture.info.dataDir, "room-plan.json"); @@ -134,6 +134,7 @@ it("runs a routine in the bot's starred chat, which a new chat takes, never a co } }], reply: "The routine is scheduled." }, { key: "elsewhere", match: ["Something else."], steps: [], reply: "Noted." }, { key: "run", match: ["Chat report"], steps: [], reply: "Fresh chat report" }, + { key: "run-kept", match: ["Chat report"], steps: [], reply: "Kept chat report" }, { key: "run-again", match: ["Chat report"], steps: [], reply: "Starred chat report" }, ] } })); await cli("send", "--bot", bot.id, "--task", chat, "--text", "Report the fixture state monthly."); @@ -164,15 +165,28 @@ it("runs a routine in the bot's starred chat, which a new chat takes, never a co expect(saved.tasks.filter((candidate: any) => !candidate.routineRunId).map((candidate: any) => candidate.threadId).sort()) .toEqual([first, chat].sort()); expect(saved.tasks.some((candidate: any) => candidate.routineRunId)).toBe(false); - // starring the first chat moves where the next run works + // starring another chat leaves the run in the chat the routine was made in await api("PATCH", `/api/bots/${bot.id}`, { mainThreadChoice: first }); - const { run: next } = await api("POST", `/api/routines/${routineId}/run`, undefined, 201); - await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === next.id)?.status, { timeout: 20_000 }).toBe("completed"); - expect((await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === next.id).threadId).toBe(first); + const ran = async () => { + const { run: one } = await api("POST", `/api/routines/${routineId}/run`, undefined, 201); + await expect.poll(async () => (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === one.id)?.status, { timeout: 20_000 }).toBe("completed"); + return (await api("GET", "/api/routines")).runs.find((candidate: any) => candidate.id === one.id); + }; + const kept = await ran(); + expect(kept.threadId).toBe(chat); + await expect.poll(async () => (await messages(chat)).findLast((message) => message.role === "bot" && message.kind === "text")?.text, { timeout: 15_000 }) + .toBe("Kept chat report"); + expect((await messages(first)).some((message) => message.text === "Kept chat report")).toBe(false); + // once that chat is archived, the run works in the starred chat + await api("PATCH", `/api/bots/${bot.id}/tasks/${chat}`, { archivedAt: Date.now() }); + const next = await ran(); + expect(next.threadId).toBe(first); await expect.poll(async () => (await messages(first)).findLast((message) => message.role === "bot" && message.kind === "text")?.text, { timeout: 15_000 }) .toBe("Starred chat report"); - expect((await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id).tasks.some((candidate: any) => candidate.routineRunId)).toBe(false); - evidence.push({ run: finished, next, bot: saved, main: await messages(chat) }); + const after = (await api("GET", "/api/bots")).bots.find((candidate: any) => candidate.id === bot.id); + expect(after.tasks.some((candidate: any) => candidate.routineRunId || candidate.background)).toBe(false); + expect(after.tasks.map((candidate: any) => candidate.threadId).sort()).toEqual([first, chat].sort()); + evidence.push({ run: finished, kept, next, bot: saved, main: await messages(chat) }); } finally { const evidencePath = `${fixture.info.logPath}.chat-results.json`; writeFileSync(evidencePath, JSON.stringify(evidence, null, 2)); diff --git a/server/routine-spent.ts b/server/routine-spent.ts new file mode 100644 index 0000000000..1bc1393a83 --- /dev/null +++ b/server/routine-spent.ts @@ -0,0 +1,13 @@ +import { isSpentOnceRoutine } from "../shared/routines.ts"; +import type { Routine, RoutineRun } from "./routines.ts"; + +/** One-time routines that are done: their time passed, nothing of them is still to come or under way, any failure was + * seen, and no other routine reads from or runs after them. Each is removed with `remove`; its runs stay in history. */ +export function removeSpentOnce(routines: readonly Routine[], runs: readonly RoutineRun[], now: number, remove: (id: string) => void): void { + const linked = new Set(routines.flatMap((routine) => [...(routine.chain?.readFrom ?? []), ...(routine.chain?.after ?? [])])); + const spent = routines.filter((routine) => routine.schedule.type === "once" && routine.nextRunAt == null && !linked.has(routine.id) && + isSpentOnceRoutine(routine, runs, now)).map((routine) => routine.id); + for (const id of spent) { + try { remove(id); } catch (error) { console.error(`routines: could not remove the finished one-time routine ${id}`, error); } + } +} diff --git a/server/routines.test.ts b/server/routines.test.ts index 0d1cef689b..b6cb933d7b 100644 --- a/server/routines.test.ts +++ b/server/routines.test.ts @@ -4466,3 +4466,57 @@ describe("a run sets its routine to run again (trigger action=again)", () => { expect(h.manager.scheduleAgain(test.id, routine.id, start + 180_000, 6)).toMatchObject({ kind: "refused", status: 409 }); }); }); + +describe("a one-time routine is cleaned up after it runs and can be switched off before", () => { + const start = Date.parse("2026-09-13T08:00:00Z"); + const once = (at: number) => ({ name: "Cooked video tweet", prompt: "Like 2 replies", botId: "maus-1", schedule: { type: "once" as const, at } }); + const finish = (h: ReturnType, threadId: string, ok = true) => h.manager.handleRuntimeEvent({ + eventId: `done-${threadId}`, provider: "fake", threadId, createdAt: new Date().toISOString(), type: "turn.completed", ok, ...(ok ? {} : { stopReason: "refusal" }), + }); + + it("deletes the routine once its run finished, and keeps the run in history", async () => { + const h = harness(start); + const routine = h.manager.create(once(start + 60_000)); + h.setNow(start + 60_000); await h.manager.tick(); + const [run] = h.manager.listRuns(); + expect(run).toMatchObject({ routineId: routine.id, status: "running" }); + expect(h.manager.listRoutines()).toHaveLength(1); + finish(h, run!.threadId!); + await h.manager.tick(); + expect(h.manager.listRoutines()).toEqual([]); + expect(h.manager.listRuns()).toMatchObject([{ id: run!.id, routineId: routine.id, routineName: "Cooked video tweet", status: "completed" }]); + expect(h.emitted).toContainEqual({ kind: "routine.deleted", routineId: routine.id }); + expect(new RoutineManager(h.options).listRoutines()).toEqual([]); + }); + + it("keeps one whose run failed until the failure is seen, and one another routine reads from", async () => { + const h = harness(start); + const routine = h.manager.create(once(start + 60_000)); + h.setNow(start + 60_000); await h.manager.tick(); + const [run] = h.manager.listRuns(); + finish(h, run!.threadId!, false); + await h.manager.tick(); + expect(h.manager.listRoutines().map((one) => one.id)).toEqual([routine.id]); + h.manager.markSeen(run!.id); await h.manager.tick(); + expect(h.manager.listRoutines()).toEqual([]); + + const linked = harness(start); + const source = linked.manager.create(once(start + 60_000)); + linked.manager.create({ ...once(start + 600_000), name: "Reader", chain: { readFrom: [source.id] } }); + linked.setNow(start + 60_000); await linked.manager.tick(); + finish(linked, linked.manager.listRuns()[0]!.threadId!); await linked.manager.tick(); + expect(linked.manager.listRoutines().map((one) => one.id)).toContain(source.id); + }); + + it("switches off and on before its time, skips its run while off, and is cleaned up once its time passed", async () => { + const h = harness(start); + const routine = h.manager.create(once(start + 60 * 60_000)); + expect(h.manager.update(routine.id, { enabled: false })).toMatchObject({ enabled: false, nextRunAt: null }); + expect(h.manager.update(routine.id, { enabled: true })).toMatchObject({ enabled: true, nextRunAt: start + 60 * 60_000 }); + h.manager.update(routine.id, { enabled: false }); + h.setNow(start + 61 * 60_000); await h.manager.tick(); + expect(h.started).toEqual([]); + expect(h.manager.listRuns()).toEqual([]); + expect(h.manager.listRoutines()).toEqual([]); + }); +}); diff --git a/server/routines.ts b/server/routines.ts index d0595e3ba0..f425769d4a 100644 --- a/server/routines.ts +++ b/server/routines.ts @@ -12,7 +12,7 @@ import { startDueTimer, type DueTimer } from "./due-timer.ts"; import type { GroupGoalRunStatus } from "../shared/group-goal-run.ts"; import { intervalHasRestrictions, latestIntervalOccurrence } from "./routine-intervals.ts"; import { initialOccurrence, intervalDispatch, limitResetOccurrence, mergeScheduleUpdate, nextOccurrence, RoutineScheduleError, type RoutineSchedule, type RoutineScheduleInput } from "./routine-schedules.ts"; -import { runsOnce } from "../shared/limit-reset.ts"; +import { runsOnce } from "../shared/limit-reset.ts"; import { removeSpentOnce } from "./routine-spent.ts"; import { isRoutineProblemRun, type RoutineQuietFields, type RoutineQuietInput, type RoutineAccess, type RoutineChain, type RoutineCheck, type RoutineContextAttachment, type RoutineDelivery, type RoutineIntervalWindow, type RoutineRetryCause, type RoutineHoldCause, type RoutinePause, type RoutineRunReport, type RoutineRunStatus, type RoutineRunTrigger, @@ -1005,10 +1005,8 @@ export class RoutineManager { this.ticking = true; try { const now = this.now(); - for (const run of this.runs) { - const stop = stopDue(run, now); - if (stop) await this.stopRun(run, stop.detail, stop.status); - } + for (const run of this.runs) { const stop = stopDue(run, now); if (stop) await this.stopRun(run, stop.detail, stop.status); } + removeSpentOnce(this.routines, this.runs, now, (id) => this.remove(id)); if (this.options.heldAfterWake?.()) return; const isDue = (routine: Routine) => !this.closing && routine.enabled && this.targetState(routine) !== "missing" && (!routine.checks ? routine.nextRunAt != null && routine.nextRunAt - (this.options.earlyMs?.(routine) ?? 0) <= now diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.ts index 406ebfa41d..933a0cec02 100644 --- a/server/steer-e2e.test.ts +++ b/server/steer-e2e.test.ts @@ -416,6 +416,8 @@ posixOnly("mid-turn steering e2e", () => { modelSelection: { instanceId: "claudeSteer", model: "claude-fake" }, }); const waiting = (await api("POST", `/api/bots/${created.id}/tasks`, { title: "Images" })).body.task.threadId as string; + // a new conversation takes the star and the main chat is never at capacity, so the opener stays main + await api("PATCH", `/api/bots/${created.id}`, { mainThreadChoice: created.threadId }); const waitingMessages = async () => (await api("GET", `/api/threads/${waiting}/messages?limit=20`)).body.messages as any[]; expect((await api("POST", `/api/bots/${created.id}/messages`, { threadId: created.threadId, text: "first image task" })).status) @@ -845,6 +847,7 @@ posixOnly("mid-turn steering e2e", () => { for (let i = 0; i < limit; i++) { threads.push((await api("POST", `/api/bots/${created.id}/tasks`, { title: `Slot ${i + 2}` })).body.task.threadId); } + await api("PATCH", `/api/bots/${created.id}`, { mainThreadChoice: created.threadId }); const waiting = threads.at(-1)!; const busy = async () => (await getBot(created.id)).tasks.filter((task: any) => task.busy).map((task: any) => task.threadId) as string[]; diff --git a/server/system-prompt.test.ts b/server/system-prompt.test.ts index 8db7ad1aa2..f564fea446 100644 --- a/server/system-prompt.test.ts +++ b/server/system-prompt.test.ts @@ -499,7 +499,7 @@ describe("how every bot replies", () => { "use the units, currency, time zone and numbers the person has told you about", "no \"let me know if…\", no \"hope this helps\"", "never end on an offer", - "Ask only for a value the work needs that is not in this chat, earlier chats (session_search)", + "Ask only for a value the work needs that is not in this chat, earlier chats, your memory", "ask for that one thing with the reason", "do every part that does not need it", "never name tools or functions, the files that hold your notes or settings, MCP", diff --git a/server/task-fidelity/probes.ts b/server/task-fidelity/probes.ts index cae9049a57..8b25e6a04c 100644 --- a/server/task-fidelity/probes.ts +++ b/server/task-fidelity/probes.ts @@ -10,7 +10,7 @@ export const PROBES: Probe[] = [ { id: "destination-from-words", applies: outward, where: "prompt", test: /channel[^.]*\b(DM|direct message)\b[^.]*(never|not)\b|\b(never|not)\b[^.]*\b(DM|direct message)\b[^.]*channel|\b(never|not)\b[^.]*channel[^.]*\b(DM|direct message)\b/i }, { id: "ask-when-open", applies: (c) => c.expect.ask === true, where: "prompt", test: /\b(unclear|open|ambiguous)\b[^.]*\bask\b[^.]*\bone\b[^.]*question|\bask\b[^.]*\bone\b[^.]*question[^.]*\b(which|who|where)\b/i }, { id: "draft-before-send", applies: (c) => c.expect.draft === true, where: "prompt", test: /\b(show|share)\b[^.]*\bdraft\b[^.]*\b(before|then)\b[^.]*\b(send|post)/i }, - { id: "connected-app-first", applies: (c) => c.expect.tool.includes("connector") && (c.world.browser || !!c.world.computer), where: "prompt", test: /connected app[^.]*before any browser or screen/i }, + { id: "connected-app-first", applies: (c) => c.expect.tool.includes("connector") && (c.world.browser || !!c.world.computer), where: "prompt", test: /connected tools[^.]*connected apps[^.]*a computer only when/i }, { id: "browser-before-screen", applies: (c) => c.expect.tool.includes("browser") && !!c.world.computer, where: "prompt", test: /\b(web apps?|website)[^.]*\bbrowser\b[^.]*\bbefore\b[^.]*\b(screen|desktop app)/i }, { id: "no-file-hunting", applies: (c) => !c.expect.files && !!c.world.computer, where: "prompt", test: /\b(do not|never)\b[^.]*\bsearch\b[^.]*\b(computer|files|folders|disk)\b[^.]*\b(unless|only when)\b/i }, { id: "dm-tool-only-for-a-person", applies: (c) => c.world.slack === "bridge" && outward(c), where: "slack_dm", test: /\bonly\b[^.]*\b(asked|named)\b/i }, diff --git a/server/thread-capacity-api.test.ts b/server/thread-capacity-api.test.ts index a46567bf62..697baede40 100644 --- a/server/thread-capacity-api.test.ts +++ b/server/thread-capacity-api.test.ts @@ -64,6 +64,8 @@ describe("per-bot thread capacity through an isolated HTTP fixture", () => { expect(createdTask.status).toBe(201); threads.push(createdTask.body.task.threadId); } + // a new conversation takes the star and the main chat is never at capacity, so the first chat stays main + if (count > 1) expect((await api("PATCH", `/api/bots/${bot.id}`, { mainThreadChoice: bot.threadId })).status).toBe(200); return { botId: bot.id as string, threads }; }; const capabilityStatus = async (launched: any) => { diff --git a/server/thread-page-frames.e2e.test.ts b/server/thread-page-frames.e2e.test.ts index 8d796f7ebb..cd94006688 100644 --- a/server/thread-page-frames.e2e.test.ts +++ b/server/thread-page-frames.e2e.test.ts @@ -114,8 +114,12 @@ describe("transcript pages on bot and room frames", () => { const opened = await framesFor("bot", bot.id, async () => { created = (await api("POST", `/api/bots/${bot.id}/tasks`, { title: "Short" })).body.task; }); - expect(opened).toHaveLength(1); - expect(opened[0]).toMatchObject({ threadId: created!.threadId, messages: [], hasMore: false }); + // the new conversation takes the star: a frame without a page beside the one page + const openedPages = opened.filter((frame) => "messages" in frame); + expect(openedPages).toHaveLength(1); + expect(opened).toHaveLength(2); + expect(openedPages[0]).toMatchObject({ threadId: created!.threadId, messages: [], hasMore: false }); + expect(opened.at(-1)).toMatchObject({ mainThreadId: created!.threadId }); // leaving the empty side conversation archives it: a background frame beside the one page const back = await framesFor("bot", bot.id, () => api("POST", `/api/bots/${bot.id}/tasks/${bot.threadId}?messages=5`)); @@ -158,8 +162,10 @@ describe("transcript pages on bot and room frames", () => { expect(windowB.bots[0].hasMore).toBe(true); const frames = await framesFor("bot", bot.id, () => api("POST", `/api/bots/${bot.id}/tasks`, { title: "From the phone" })); - expect(frames).toHaveLength(1); - expect(frames[0]).toMatchObject({ messages: [], hasMore: false }); + const pages = frames.filter((frame) => "messages" in frame); + expect(pages).toHaveLength(1); + expect(frames).toHaveLength(2); + expect(pages[0]).toMatchObject({ messages: [], hasMore: false }); for (const frame of frames) windowB = desktop.reducer(windowB, { type: "botPatched", bot: frame }); expect(windowB.bots[0].threadId).toBe(bot.threadId); expect(texts(windowB.bots[0].messages)).toEqual(newestPage); diff --git a/server/turn-stop-gates.test.ts b/server/turn-stop-gates.test.ts index 1955c0aca2..4ed4e890b1 100644 --- a/server/turn-stop-gates.test.ts +++ b/server/turn-stop-gates.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vitest"; -import { bareAck, claimsDone, goOrder, MAX_STOP_GATES, TurnGates, openChecklist, promisesFollowUp, ranTool, readBackWrite, schedulesCall, schedulesWork, settleAsks, stopGateFor, stopGateNote, type Ask, type StopGate, type TurnForAsks, type TurnSoFar } from "./turn-stop-gates.ts"; +import { bareAck, claimsDone, goOrder, MAX_STOP_GATES, openOrders, orderStandsNote, TurnGates, openChecklist, promisesFollowUp, ranTool, readBackWrite, schedulesCall, schedulesWork, settleAsks, stopGateFor, stopGateNote, type Ask, type StopGate, type TurnForAsks, type TurnSoFar } from "./turn-stop-gates.ts"; const turn = (over: Partial): TurnSoFar => ({ reply: "", applied: new Set(), canSchedule: true, scheduled: false, effectful: 0, unconfirmed: null, ...over }); @@ -250,6 +250,14 @@ describe("settleAsks", () => { it("reads an order to act now, and not one to wait or stop", () => { for (const text of ["do it", "so when the fuck are you gonna push it??", "go", "Go ahead.", "send it now"]) expect(goOrder(text), text).toBe(true); for (const text of ["don't push it yet", "stop, do not send it", "what does it do", "let's go over the plan tomorrow"]) expect(goOrder(text), text).toBe(false); + for (const text of ["when are you gonna push it", "when tf will you post it", "push it, now"]) expect(goOrder(text), text).toBe(true); + for (const text of ["post it at 5pm", "push it when it hits 100 views", "send it tomorrow", "publish it in 2 hours", "post it once the video is up"]) expect(goOrder(text), text).toBe(false); + }); + + it("finds the orders still open among a chat's asks", () => { + const asks = [ask("a", "so when the fuck are you gonna push it??"), ask("b", "what's the view count"), { ...ask("c", "do it"), state: "delivered" as const }]; + expect(openOrders(asks)).toEqual(["so when the fuck are you gonna push it??"]); + expect(orderStandsNote(openOrders(asks))).toContain('"so when the fuck are you gonna push it??"'); }); it("delivers a lone ask with any real answer, and keeps it open on an acknowledgement alone", () => { diff --git a/server/turn-stop-gates.ts b/server/turn-stop-gates.ts index 26c787246a..7286b78fc9 100644 --- a/server/turn-stop-gates.ts +++ b/server/turn-stop-gates.ts @@ -121,6 +121,7 @@ export interface TurnForAsks { const GO_ORDER = /\b(?:do it|do that|push it|go ahead|go for it|send it|post it|ship it|publish it|run it)\b|^\s*(?:go|yes,? go|now)[.!]*\s*$/i; const NOT_AN_ORDER = /\b(?:don['’]?t|do not|never|not yet|stop)\b/i; +const FOR_LATER = /\b(?:at \d|\d{1,2}(?::\d{2})?\s*(?:am|pm)|tomorrow|tonight|later|in (?:a|an|\d+) (?:sec|second|min|minute|hour|day|week)s?|in a (?:bit|while)|soon|shortly|after|once|every|each|until|next)\b|\bwhen\b(?!\s+(?:the\s+\w+\s+|tf\s+)?(?:are|r|will|do|is)\b)/i; /** What still stops a turn on the person's order: their sign-in or approval, a permission, money past what they approved. */ const REAL_LIMIT = /\b(?:not connected|isn['’]?t connected|no access|sign(?:ed)? in|approv\w*|permission|budget|spend\w*|charge\w*|unsafe)\b/i; // tools that change only the bot's own bookkeeping, which is not doing what the person ordered @@ -128,7 +129,15 @@ const BOOKKEEPING = /(?:^|__|_)(?:memory_update|memory_log|skill_manage|set_stat /** The person's message tells the bot to act now ("do it", "push it", "go"), not to wait or stop. */ export function goOrder(text: string): boolean { - return text.length <= 300 && GO_ORDER.test(text) && !NOT_AN_ORDER.test(text); + return text.length <= 300 && GO_ORDER.test(text) && !NOT_AN_ORDER.test(text) && !FOR_LATER.test(text); +} + +export const openOrders = (asks: readonly Ask[]): string[] => asks.filter((ask) => ask.state === "open" && goOrder(ask.text)).map((ask) => ask.text); + +/** For a turn that sets a wait, or a wait's follow-up, while the person's order to act is still not done in that chat. */ +export function orderStandsNote(orders: readonly string[]): string { + const said = orders.slice(0, 3).map((order) => `"${order.slice(0, 120)}"`).join("; "); + return `[dusk bot: the person told you to act (${said}) and that is not done yet. A wait or a recheck does not do it: do it now with your tools. Your own skills, notes and judgement rules do not veto their order; add at most one short line of concern. Only a real safety or permission limit, or money past what they approved, stops it.]`; } export const bookkeeping = (tool: string): boolean => BOOKKEEPING.test(tool); diff --git a/server/wait-host.test.ts b/server/wait-host.test.ts index 7edf9f9beb..86fd5a3e02 100644 --- a/server/wait-host.test.ts +++ b/server/wait-host.test.ts @@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; import type { Notification } from "../shared/notification.ts"; import type { Message } from "./store.ts"; import { cancelWaitFromCard, createWaitHost, type WaitHostDeps } from "./wait-host.ts"; +import { orderStandsNote } from "./turn-stop-gates.ts"; import type { WaitRecord } from "./waits.ts"; const NOW = 1_700_000_000_000; @@ -97,6 +98,15 @@ describe("the store side of waits", () => { botId: "bot-1", runOn: "maus", deliveryId: "w1", receivedAt: NOW, eventSource: "wait", resultsThreadId: "t-1" }); }); + it("carries the person's order still not done in that chat into the follow-up, so a recheck cannot hold it again", () => { + const orders = vi.fn((threadId: string) => (threadId === "t-1" ? ["so when the fuck are you gonna push it??"] : [])); + const withOrders = createWaitHost({ store: fakeStore() as unknown as WaitHostDeps["store"], directChat: () => true, threadBusy: () => false, wrote: vi.fn(), notify: vi.fn(), enqueue, orders, now: () => NOW }); + withOrders.followUp({ ...wait, label: "Lurka promo recheck", followUp: "Recheck the promo's numbers." }); + expect(orders).toHaveBeenCalledWith("t-1"); + expect(enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ resultsThreadId: "t-1", + prompt: `[Wait finished: Lurka promo recheck] Recheck the promo's numbers.\n\n${orderStandsNote(["so when the fuck are you gonna push it??"])}` })); + }); + it("knows a deleted bot from an idle one", () => { expect([host.botBusy("bot-1"), host.botBusy("gone")]).toEqual([false, undefined]); }); diff --git a/server/wait-host.ts b/server/wait-host.ts index 9e4d44f89a..d04e549c1b 100644 --- a/server/wait-host.ts +++ b/server/wait-host.ts @@ -2,6 +2,7 @@ import type { Notification } from "../shared/notification.ts"; import { buildNotification } from "./notify.ts"; import type { RoutineManager } from "./routines.ts"; import type { BotRecord, Store } from "./store.ts"; +import { orderStandsNote } from "./turn-stop-gates.ts"; import type { WaitManager, WaitManagerOptions } from "./waits.ts"; export interface WaitHostDeps { @@ -12,6 +13,8 @@ export interface WaitHostDeps { wrote(bot: BotRecord, threadId: string): void; notify(notification: Notification | null): void; enqueue(input: Parameters[0]): { id: string }; + /** The person's orders to act in this chat that no turn has carried out yet. */ + orders?(threadId: string): readonly string[]; now?: () => number; } @@ -58,10 +61,11 @@ export function createWaitHost(deps: WaitHostDeps): Pick now) return false; + return !runs.some((run) => run.routineId === routine.id && (run.status === "queued" || run.status === "running" || run.status === "waiting")); +} + +/** A passed one-time routine whose last run did not fail unseen: done, so it may be removed. */ export function isSpentOnceRoutine( routine: { id: string; schedule: RoutineSchedule }, runs: readonly { routineId: string; status: RoutineRunStatus; createdAt: number; seenAt?: number }[], now: number, ): boolean { - if (routine.schedule.type !== "once" || routine.schedule.at > now) return false; + if (!isPassedOnceRoutine(routine, runs, now)) return false; const own = runs.filter((run) => run.routineId === routine.id); - if (own.some((run) => run.status === "queued" || run.status === "running" || run.status === "waiting")) return false; const latest = own.reduce<(typeof own)[number] | undefined>((last, run) => (!last || run.createdAt > last.createdAt ? run : last), undefined); return !latest || !isRoutineProblemRun(latest) || latest.seenAt !== undefined; } diff --git a/src/components/ComposerAttachments.tsx b/src/components/ComposerAttachments.tsx index a305da7257..6be1bbe9f8 100644 --- a/src/components/ComposerAttachments.tsx +++ b/src/components/ComposerAttachments.tsx @@ -308,7 +308,7 @@ export function ComposerAttachmentStrip({ items, onRemove, onRetry, onDisplayInC ) : ( -
diff --git a/src/components/NotesWaiting.tsx b/src/components/NotesWaiting.tsx index 75b1c69a60..a84cd39ef3 100644 --- a/src/components/NotesWaiting.tsx +++ b/src/components/NotesWaiting.tsx @@ -10,7 +10,6 @@ import { arrivalFailed, dismissArrival, noteArrival, useNotesArrival, useNotesWo import { bringOfferedNotesIn, dismissNotesOffer, notesOfferLine, useNotesOffer, copyNotesPrompt, importNotes, notesWatch, takeNotesFromDownloads, WATCH_EVERY_MS, isNotesPrompt, notesErrorLine, notesOutcomeLine, scheduleNotesReminder, stopWaiting, useNotesWaiting } from "@/lib/assistant-notes"; import { myDefaultBot, useViewerEmail } from "@/lib/default-bot"; import { t } from "@/lib/i18n"; -import { systemNotificationsAllowed } from "@/lib/notify"; import { useStore } from "@/state/store"; export type NotesSay = (line: string, state: "working" | "done" | "failed") => void; @@ -69,7 +68,7 @@ export function useNotesReminder() { useEffect(() => { if (!waiting || waiting.reminded || !firstBotId) return; return scheduleNotesReminder(() => { - if (typeof Notification === "undefined" || !systemNotificationsAllowed() || Notification.permission !== "granted") return; + if (typeof Notification === "undefined" || Notification.permission !== "granted") return; try { new Notification(t("composer.notes.remindTitle"), { body: t("composer.notes.remindBody"), tag: "duskbot:notes", silent: true }).onclick = () => { window.focus(); diff --git a/src/components/NotificationSettingsRows.test.ts b/src/components/NotificationSettingsRows.test.ts index 6a845fa434..2be99351a6 100644 --- a/src/components/NotificationSettingsRows.test.ts +++ b/src/components/NotificationSettingsRows.test.ts @@ -127,3 +127,9 @@ it("keeps the sound rows for approvals and questions while finished notices are await mount(); expect(soundSwitch().disabled).toBe(false); }); + +it("shows this device's switch in the desktop app on a Mac", async () => { + vi.stubGlobal("duskDesktop", { platform: "darwin" }); + await mount(); + expect(container.querySelector('[role="switch"][aria-label="Notifications on this device"]')).not.toBeNull(); +}); diff --git a/src/components/NotificationSettingsRows.tsx b/src/components/NotificationSettingsRows.tsx index 8103c7a349..714d7e24f7 100644 --- a/src/components/NotificationSettingsRows.tsx +++ b/src/components/NotificationSettingsRows.tsx @@ -6,7 +6,7 @@ import { useFinishedNotifications, useNotificationSounds, } from "@/lib/notification-preferences"; -import { requestNotificationPermission, systemNotificationsAllowed } from "@/lib/notify"; +import { requestNotificationPermission } from "@/lib/notify"; import { chooseSound, chosenSound, play, UI_SOUND_NAMES, type UiSoundName } from "@/lib/ui-sounds"; import type { LocaleKey } from "@/locales"; import { SettingRow, Switch } from "./SettingsPrimitives"; @@ -27,9 +27,9 @@ export function NotificationRows() { const currentPermission = (): NotificationPermission => (typeof Notification !== "undefined" ? Notification.permission : "default"); /** The ping plays with a system notification, so where this device may show them but has not been allowed to, it never - * plays. Without system notifications (macOS desktop) the app's own ping still plays. */ + * plays. */ export function soundsSilenced(permission: NotificationPermission): boolean { - return typeof Notification !== "undefined" && systemNotificationsAllowed() && permission !== "granted"; + return typeof Notification !== "undefined" && permission !== "granted"; } /** The site permission, read again when the window comes back: the person may change it elsewhere. */ @@ -52,7 +52,7 @@ function useNotificationPermission() { /** A browser shows nothing until it is asked from a click. */ export function DeviceNotificationsRow({ permission, onPermission }: { permission: NotificationPermission; onPermission: (next: NotificationPermission) => void }) { const enabled = useFinishedNotifications(); - if (typeof Notification === "undefined" || !systemNotificationsAllowed()) return null; + if (typeof Notification === "undefined") return null; const blocked = permission === "denied"; const toggle = async () => { diff --git a/src/components/SidebarPopoverMenu.tsx b/src/components/SidebarPopoverMenu.tsx index dd67201f35..50833ab048 100644 --- a/src/components/SidebarPopoverMenu.tsx +++ b/src/components/SidebarPopoverMenu.tsx @@ -104,7 +104,7 @@ export function nextMenuIndex(key: string, current: number, count: number): numb } } -function MenuRows({ +export function MenuRows({ items, openSubmenu, engaged = false, diff --git a/src/components/bot-panel/ConversationsCard.tsx b/src/components/bot-panel/ConversationsCard.tsx index 4a73bca631..64f80d95c1 100644 --- a/src/components/bot-panel/ConversationsCard.tsx +++ b/src/components/bot-panel/ConversationsCard.tsx @@ -1,4 +1,5 @@ import { useState } from "react"; +import { Search } from "../../icons"; import { botConversations, CONVERSATION_SEARCH_FROM, filterConversations, setMainConversation } from "@/lib/bot-conversations"; import { t } from "@/lib/i18n"; @@ -40,22 +41,25 @@ export function ConversationsCard({ bot }: { bot: Bot }) { ) : undefined} > {searchable && ( - setQuery(event.target.value)} - onKeyDown={(event) => { - if (event.key === "Enter" && needle && listed.length === 1) { event.preventDefault(); open(listed[0]!.threadId); return; } - if (event.key !== "Escape" || !query) return; - event.preventDefault(); - event.stopPropagation(); - setQuery(""); - }} - placeholder={t("botPanel.conversations.search")} - aria-label={t("botPanel.conversations.searchPlaceholder", { name: bot.name })} - className="mb-1.5 h-8 w-full shrink-0 appearance-none rounded-[10px] bg-ink/[0.05] px-2 text-[13px] leading-[18px] text-ink placeholder:text-ink-tertiary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-focus touch:h-10 [&::-webkit-search-cancel-button]:appearance-none" - /> + )} {needle && listed.length === 0 &&

{t("botPanel.ui.taskNoMatch", { query: needle })}

}
diff --git a/src/components/bot-panel/DetailsTab.tsx b/src/components/bot-panel/DetailsTab.tsx index 6549cf45dc..b3e13be926 100644 --- a/src/components/bot-panel/DetailsTab.tsx +++ b/src/components/bot-panel/DetailsTab.tsx @@ -20,7 +20,6 @@ import { setVoicePrefs, useVoicePrefs, VOICE_LANGUAGES, VOICE_SPEEDS } from "./v import { useCallPrefs } from "@/lib/voice-call/prefs"; import { CALL_MODES, parseCallMode, setCallMode, useCallMode } from "@/lib/call-mode"; import { liveCallEnabled } from "@/lib/feature-flags"; -import { accountChoice, onAccount, REMOVED_ACCOUNT } from "@/lib/engine-account-choice"; type Derived = ReturnType; @@ -72,31 +71,12 @@ export function ModelCard({ bot }: { bot: Bot }) {
)} - {!HostRow && } ); } -/** Which signed-in account, or saved API key, of its AI the bot runs on, shown once the person has more than one. */ -function AccountRow({ bot }: { bot: Bot }) { - const { state, dispatch } = useStore(); - const choice = accountChoice(state.instances, bot.modelSelection.instanceId); - if (!choice) return null; - const options = choice.removed ? [{ value: REMOVED_ACCOUNT, label: t("botPanel.account.removed"), disabled: true }, ...choice.options] : choice.options; - const pick = (instanceId: string) => { - const account = state.instances.find((instance) => instance.instanceId === instanceId); - if (!account || instanceId === bot.modelSelection.instanceId) return; - dispatch({ type: "setModel", botId: bot.id, threadId: bot.threadId, updateBotDefault: true, selection: onAccount(bot.modelSelection, account), ...(bot.busy ? { nextTurn: true } : {}) }); - }; - return ( - - - - ); -} - /** The conversation's backup beside its model: its bot's, No backup, or one of its own. */ function ConversationBackupRow({ bot }: { bot: Bot }) { const { dispatch } = useStore(); diff --git a/src/components/documents/FilesSection.dom.test.ts b/src/components/documents/FilesSection.dom.test.ts new file mode 100644 index 0000000000..a566411d34 --- /dev/null +++ b/src/components/documents/FilesSection.dom.test.ts @@ -0,0 +1,85 @@ +// @vitest-environment happy-dom +import { act, createElement } from "react"; +import { flushSync } from "react-dom"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { DocumentMeta } from "../../../shared/documents"; + +const docs: DocumentMeta[] = [ + { id: "d_spec", title: "X engagement hub: build spec + builder prompt", kind: "markdown", bytes: 19, createdAt: 3, updatedAt: 3, version: 1, by: "bot" } as DocumentMeta, + { id: "d_list", title: "Q4 outreach list", kind: "sheet", bytes: 40, rows: 2, columns: 2, createdAt: 1, updatedAt: 1, version: 1, by: "bot" } as DocumentMeta, +]; + +vi.mock("@/state/store", () => ({ useStore: () => ({ dispatch: vi.fn() }), visibleMessages: () => [] })); +vi.mock("@/state/api", () => ({ + ApiError: class extends Error {}, + api: async (path: string) => (path.endsWith("/documents") ? { documents: docs } : {}), +})); + +const { FilesPage } = await import("./FilesSection"); + +(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + +let root: Root | null = null; +async function mount() { + const host = document.createElement("div"); + document.body.append(host); + act(() => { root = createRoot(host); root.render(createElement(FilesPage, { bot: { id: "b1", name: "Moss" } as never, onOpen: vi.fn() })); }); + await act(async () => { for (let i = 0; i < 5; i++) await Promise.resolve(); }); + return host; +} +afterEach(() => { act(() => root?.unmount()); root = null; document.body.innerHTML = ""; }); + +const menu = () => document.body.querySelector("[data-files-row-menu]"); +const rowButton = (host: HTMLElement, id: string) => host.querySelector(`[data-files-row="${id}"] > button`)!; +const rightClick = (el: Element) => flushSync(() => el.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true }))); + +describe("a file row's menu", () => { + it("shows no ⋯ on any row", async () => { + const host = await mount(); + expect(host.querySelectorAll("[data-files-row]")).toHaveLength(2); + expect(host.querySelector('[aria-label^="More for"]')).toBeNull(); + expect(host.querySelectorAll("[data-files-row] button")).toHaveLength(2); + }); + + it("opens on a right click outside the card, in the page's top layer, with Rename, Download and Delete", async () => { + const host = await mount(); + rightClick(rowButton(host, "d_list")); + const sheet = menu(); + expect(sheet).not.toBeNull(); + expect(host.contains(sheet)).toBe(false); + expect(sheet!.parentElement).toBe(document.body); + expect(sheet!.style.position).toBe("fixed"); + expect([...sheet!.querySelectorAll("[role=menuitem]")].map((item) => item.textContent)).toEqual(["Rename", "Download", "Delete"]); + expect(rowButton(host, "d_list").getAttribute("aria-expanded")).toBe("true"); + }); + + it("opens from the keyboard with Shift+F10 or the menu key, and Escape closes it back onto the row", async () => { + const host = await mount(); + const row = rowButton(host, "d_spec"); + flushSync(() => row.dispatchEvent(new KeyboardEvent("keydown", { key: "F10", shiftKey: true, bubbles: true, cancelable: true }))); + expect(menu()).not.toBeNull(); + flushSync(() => menu()!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }))); + expect(row.getAttribute("aria-expanded")).toBe("false"); + expect(document.activeElement).toBe(row); + flushSync(() => row.dispatchEvent(new KeyboardEvent("keydown", { key: "ContextMenu", bubbles: true, cancelable: true }))); + expect(row.getAttribute("aria-expanded")).toBe("true"); + }); + + it("keeps the row's full-name tooltip away while its menu is open", async () => { + const host = await mount(); + const title = host.querySelector('[data-files-row="d_spec"] [data-tip-clipped]')!; + expect(title.dataset.tipClipped).toBe("X engagement hub: build spec + builder prompt"); + expect(rowButton(host, "d_spec").hasAttribute("title")).toBe(false); + rightClick(rowButton(host, "d_spec")); + expect(title.dataset.tipClipped).toBe(""); + }); + + it("Rename from the menu turns the row into its name field", async () => { + const host = await mount(); + rightClick(rowButton(host, "d_spec")); + flushSync(() => menu()!.querySelector("[data-menu-key=rename]")!.click()); + expect(host.querySelector('[data-files-row="rename"] input')!.value).toBe("X engagement hub: build spec + builder prompt"); + }); +}); diff --git a/src/components/documents/FilesSection.tsx b/src/components/documents/FilesSection.tsx index 786d2734a5..b7406cb270 100644 --- a/src/components/documents/FilesSection.tsx +++ b/src/components/documents/FilesSection.tsx @@ -1,15 +1,20 @@ -import { useState, type KeyboardEvent } from "react"; +import { useEffect, useLayoutEffect, useRef, useState, type KeyboardEvent, type RefObject } from "react"; +import { createPortal } from "react-dom"; import { cn } from "@/lib/cn"; import { t } from "@/lib/i18n"; import { friendlyError } from "@/lib/plain-error"; +import { usePopoverDismiss } from "@/hooks/use-popover-dismiss"; +import { useLongPress } from "@/mobile/ContextMenu"; import type { Bot } from "@/state/store"; -import { Download, MoreHorizontal, Pencil, Trash2 } from "../../icons"; +import { Download, Pencil, Trash2 } from "../../icons"; import { Card, LabelAction, NoteRow, PanelEmpty } from "../bot-panel/rows"; import { FileKindIcon } from "../bot-panel/FileKindIcon"; import { shortAge } from "../bot-panel/LibraryTab"; import type { SimplePageId } from "../bot-panel/page-registry"; -import { SidebarPopoverMenu } from "../SidebarPopoverMenu"; +import { MENU_SHEET } from "../menu-recipe"; +import { useMenuMotion } from "../MenuMotion"; +import { anchoredMenuPosition, MenuRows, menuOrigin, nextMenuIndex, type SidebarMenuItem } from "../SidebarPopoverMenu"; import { documentApi, documentShapeLine, downloadDocument, glyphName, setOpenDocument, useBotDocuments, type DocumentMeta, } from "./document-data"; @@ -19,7 +24,8 @@ const PREVIEW = 3; const rowCls = "group relative flex min-h-11 w-full min-w-0 items-center gap-2 rounded-lg px-2 py-1.5 text-left text-[13px] leading-[18px] tracking-[0.015em] text-ink"; const smallButton = "dusk-press inline-flex h-7 shrink-0 items-center rounded-full px-2.5 text-[13px] leading-[18px] focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-focus disabled:opacity-50"; -/** One file: its name opens it; the menu renames, downloads or deletes it, each in place. */ +/** One file: its name opens it; a right click, a hold or the menu key opens its menu, which renames, downloads or deletes + * it, each in place. */ function FileRow({ bot, doc, now, onOpen, onChanged }: { bot: Bot; doc: DocumentMeta; @@ -31,6 +37,13 @@ function FileRow({ bot, doc, now, onOpen, onChanged }: { const [name, setName] = useState(doc.title); const [busy, setBusy] = useState(false); const [error, setError] = useState(""); + const [menuOpen, setMenuOpen] = useState(false); + const openRef = useRef(null); + useLongPress(openRef, () => setMenuOpen(true), mode === "idle"); + const closeMenu = (refocus: boolean) => { + setMenuOpen(false); + if (refocus) openRef.current?.focus({ preventScroll: true }); + }; const act = async (work: () => Promise) => { setBusy(true); setError(""); @@ -84,33 +97,111 @@ function FileRow({ bot, doc, now, onOpen, onChanged }: { return (
- - - +
); } +const menuRows = (menu: HTMLElement | null) => (menu ? [...menu.querySelectorAll('[role^="menuitem"]:not(:disabled)')] : []); + +/** The row's menu, drawn above the panel so the card never cuts it: under the row at its end edge, above it when the + * window has no room below. */ +function FileRowMenu({ open, anchorRef, label, items, onClose }: { + open: boolean; + anchorRef: RefObject; + label: string; + items: SidebarMenuItem[]; + onClose: (refocus: boolean) => void; +}) { + const menuRef = useRef(null); + const motion = useMenuMotion(open); + const [place, setPlace] = useState<{ left: number; top: number; origin: ReturnType } | null>(null); + const insideRef = useRef({ contains: (target: unknown) => Boolean(menuRef.current?.contains(target as Node)) }); + usePopoverDismiss(open, insideRef, () => onClose(true)); + + useLayoutEffect(() => { + if (!motion.shown) { setPlace(null); return; } + const measure = () => { + const anchor = anchorRef.current, menu = menuRef.current; + if (!anchor || !menu) return; + const box = anchor.getBoundingClientRect(), size = { width: menu.offsetWidth, height: menu.offsetHeight }; + const at = anchoredMenuPosition(box, size, { width: window.innerWidth, height: window.innerHeight }, getComputedStyle(anchor).direction === "rtl", "end"); + setPlace({ ...at, origin: menuOrigin(box, at, size) }); + }; + measure(); + window.addEventListener("resize", measure); + window.addEventListener("scroll", measure, true); + return () => { + window.removeEventListener("resize", measure); + window.removeEventListener("scroll", measure, true); + }; + }, [motion.shown, anchorRef]); + + // a hidden sheet cannot take focus, so the first row waits until the menu is placed + const placed = place !== null; + useEffect(() => { + if (open && placed) menuRows(menuRef.current)[0]?.focus({ preventScroll: true }); + }, [open, placed]); + + if (!motion.shown || typeof document === "undefined") return null; + return createPortal( +
{ + const list = menuRows(event.currentTarget); + const next = nextMenuIndex(event.key, list.indexOf(document.activeElement as HTMLElement), list.length); + if (next != null) { event.preventDefault(); list[next]?.focus(); return; } + if (event.key === "Escape" || event.key === "Tab") { + event.preventDefault(); + event.stopPropagation(); + onClose(true); + } + }} + style={{ ...place?.origin, position: "fixed", left: place?.left ?? 0, top: place?.top ?? 0, minWidth: 200, width: "max-content", visibility: place ? undefined : "hidden" }} + className={cn(MENU_SHEET, "z-[60] overflow-hidden", motion.className)} + > + { + onClose(true); + item.onSelect(); + }} + /> +
, + document.body, + ); +} + export function useFiles(bot: Bot, onOpenPage: (page: SimplePageId) => void) { const files = useBotDocuments(bot); const open = (doc: DocumentMeta) => { diff --git a/src/components/routines/BotRoutines.test.ts b/src/components/routines/BotRoutines.test.ts index 6551607118..9975500872 100644 --- a/src/components/routines/BotRoutines.test.ts +++ b/src/components/routines/BotRoutines.test.ts @@ -95,14 +95,14 @@ describe("a bot's routines in its panel", () => { expect(fixture.dispatch).toHaveBeenCalled(); }); - it("leaves out a one-time routine that already ran or whose time passed, keeping one still to run, running or failed unseen", () => { + it("leaves out a one-time routine that already ran or whose time passed, even one that failed, keeping one still to run or running", () => { const once = (id: string, at: number): Routine => ({ ...routine, id, name: id, schedule: { type: "once", at }, nextRunAt: at > now ? at : null }); const ranRun = { id: "run-ran", routineId: "ran", routineName: "ran", target: "bot" as const, botId: "bot-a", runOn: "maus" as const, scheduledFor: now - 7_200_000, status: "completed" as const, manual: false, createdAt: now - 7_200_000 }; fixture.state.routines = [routine, once("ran", now - 7_200_000), once("passed", now - 60_000), once("later", now + 3_600_000), once("running", now - 60_000), once("failed", now - 60_000)]; fixture.state.routineRuns = [ranRun, { ...ranRun, id: "run-live", routineId: "running", status: "running" }, { ...ranRun, id: "run-failed", routineId: "failed", status: "failed" }]; mount(); const listed = [...container.querySelectorAll("[data-panel-routine]")].map((el) => el.dataset.panelRoutine); - expect(listed).toEqual(["routine-1", "later", "running", "failed"]); + expect(listed).toEqual(["routine-1", "later", "running"]); }); it("names the bot's main chat as where results go once the chosen conversation is gone, never a thread that no longer exists", () => { @@ -224,15 +224,6 @@ describe("a bot's routines in its panel", () => { expect(row("routine-1").querySelector("[role=switch]")!.getAttribute("aria-checked")).toBe("false"); }); - it("offers no switch for a one-time routine that already happened and still shows its unseen miss", () => { - fixture.state.routines = [{ ...routine, enabled: false, nextRunAt: null, schedule: { type: "once", at: now - 60_000 } }]; - fixture.state.routineRuns = [{ id: "run-m", routineId: "routine-1", routineName: "Morning summary", target: "bot", botId: "bot-a", runOn: "maus", scheduledFor: now - 60_000, status: "missed", manual: false, createdAt: now - 60_000 }]; - mount(); - expect(row("routine-1").querySelector("[role=switch]")).toBeNull(); - open("routine-1"); - expect(sheet().textContent).toContain("Its time has passed. Edit it to pick a new time."); - }); - it("lists the bot's other automations too: a webhook copies its address, an app event runs through its own routes", async () => { fixture.state.webhooks = [webhook]; applyAppTriggerSnapshot({ triggers: [acme], attempts: [], service: { available: true, plan: "desktop", eventsPerDay: 500, eventsToday: 0 } }); @@ -388,8 +379,9 @@ describe("what a bot set to happen later on its own", () => { expect(followUp("wait-b")).toBeNull(); expect(followUp("other-bot")).toBeNull(); expect([...container.querySelectorAll("[data-panel-follow-up]")].map((el) => el.getAttribute("data-panel-follow-up"))).toEqual(["wait-1", "run-again"]); + expect(followUp("wait-1")!.querySelector("[role=switch]")!.getAttribute("aria-checked")).toBe("true"); flushSync(() => followUp("wait-1")!.querySelector('button[aria-label="Cancel Likes on the launch post"]')!.click()); - flushSync(() => followUp("run-again")!.querySelector("button")!.click()); + flushSync(() => followUp("run-again")!.querySelector("[role=switch]")!.click()); await settle(); expect(writes()).toEqual([["/api/waits/wait-1/cancel", "POST", undefined], ["/api/routine-runs/run-again/cancel", "POST", undefined]]); }); diff --git a/src/components/routines/BotRoutines.tsx b/src/components/routines/BotRoutines.tsx index 13d9f7646d..5b71928c64 100644 --- a/src/components/routines/BotRoutines.tsx +++ b/src/components/routines/BotRoutines.tsx @@ -16,7 +16,7 @@ import { routineRunsOn } from "@/lib/routine-display"; import { fetchForecast, forecastLine, forecastWarning, lessOften, pauseLine, periodLine, useLoaded } from "@/lib/spend"; import { phoneApp } from "@/lib/store-app"; import { formatCost } from "@/lib/usage-trace"; -import { isRoutineProblemRun, isSpentOnceRoutine, type Routine, type RoutineRun, type RoutineRunOn } from "@/lib/routines"; +import { isRoutineProblemRun, isPassedOnceRoutine, type Routine, type RoutineRun, type RoutineRunOn } from "@/lib/routines"; import { hoursLine, liveStrip, probeLine } from "@/lib/routine-display"; import { saveWebhookCredential, webhookCredentialStore } from "@/lib/webhook-credentials"; import { recentDeliveries } from "@/lib/webhooks"; @@ -64,7 +64,7 @@ export function BotRoutines({ bot, defaultRunOn, label = true }: { bot: Bot; def const [editing, setEditing] = useState(null); const remote = typeof window !== "undefined" && window.duskDesktop?.remoteClient?.active === true; const automations = useMemo(() => automationsFrom({ - routines: state.routines.filter((routine) => routine.botId === bot.id && !isSpentOnceRoutine(routine, state.routineRuns, Date.now())).sort((a, b) => a.createdAt - b.createdAt), + routines: state.routines.filter((routine) => routine.botId === bot.id && !isPassedOnceRoutine(routine, state.routineRuns, Date.now())).sort((a, b) => a.createdAt - b.createdAt), webhooks: remote ? [] : state.webhooks.filter((webhook) => webhook.botId === bot.id), appTriggers: appTriggers.triggers.filter((trigger) => trigger.botId === bot.id), runs: state.routineRuns, @@ -163,7 +163,7 @@ export function BotRoutines({ bot, defaultRunOn, label = true }: { bot: Bot; def onEdit={(on) => setEditing(on ? automation.id : null)} /> ))} - {followUps.map((item) => cancelFollowUp(item)} />)} + {followUps.map((item) => cancelFollowUp(item)} />)} {add} {phonePush} @@ -172,7 +172,7 @@ export function BotRoutines({ bot, defaultRunOn, label = true }: { bot: Bot; def } /** A follow-up the bot set itself: its name, when it fires, and Cancel. */ -function FollowUpRow({ item, onCancel }: { item: FollowUp; onCancel: () => Promise }) { +function FollowUpRow({ item, color, onCancel }: { item: FollowUp; color: Bot["color"]; onCancel: () => Promise }) { const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const hint = upperFirst(item.at !== undefined ? nextWhen(item.at) : t("botPanel.followUp.until", { when: nextWhen(item.kind === "wait" ? item.until : item.at) })); @@ -185,7 +185,7 @@ function FollowUpRow({ item, onCancel }: { item: FollowUp; onCancel: () => Promi
{item.name}} hint={{hint}} /> - +
{error &&

{error}

}
@@ -253,16 +253,14 @@ function AutomationRow({ bot, automation, routine, open, editing, phone, onOpen, hint={{hint}} /> - {!done && ( - void actions.toggle(automation)} - className="relative z-[1]" - /> - )} + void actions.toggle(automation)} + className="relative z-[1]" + />
{!open && actions.error &&

{actions.error}

} {!phone && ( @@ -336,7 +334,6 @@ function AutomationDetail({ id, bot, automation, routine, actions, focusEdit, on : t("routines.results.main"); const notes = [ status.state === "needs-you" ? status.reason : null, - status.state === "done" ? t("automations.reason.done") : null, routine?.warning, routine && !routine.enabled && routine.pausedFor ? pauseLine(routine.pausedFor) : null, ].filter((note): note is string => Boolean(note)); diff --git a/src/components/touch-actions.test.ts b/src/components/touch-actions.test.ts index 8b9e6268f3..6f4cf278b9 100644 --- a/src/components/touch-actions.test.ts +++ b/src/components/touch-actions.test.ts @@ -23,7 +23,6 @@ const notActions: Array<{ file: string; snippet: string; why: string }> = [ { file: "components/ComposerResizeEdge.tsx", snippet: "group-hover/edge:opacity-100", why: "aria-hidden grip hint on the composer's resize strip; the strip is the drag target and the arrow keys work on it, and the hint shows while it is dragged or focused" }, { file: "components/SimpleModelMenu.tsx", snippet: "group-hover/heading:opacity-0", why: "the provider mark swaps for a grip only under a mouse; on touch the mark stays, and the heading itself is the drag target (Alt+Up/Down reorders from the keyboard)" }, { file: "components/SimpleModelMenu.tsx", snippet: "group-hover/heading:opacity-100", why: "aria-hidden grip that replaces the provider mark under a mouse; nothing to tap, the heading is the drag target" }, - { file: "components/ConversationRows.tsx", snippet: "group-hover/conversation:opacity-100 touch:hidden", why: "a conversation row's ⋯ is hidden on touch screens on purpose: a hold on the row opens the same menu there" }, ]; function sourceFiles(dir: string): string[] { diff --git a/src/lib/engine-account-choice.test.ts b/src/lib/engine-account-choice.test.ts deleted file mode 100644 index ac9d80e5fb..0000000000 --- a/src/lib/engine-account-choice.test.ts +++ /dev/null @@ -1,66 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import type { InstanceInfo } from "@/state/instance-info"; -import { accountChoice, onAccount, REMOVED_ACCOUNT } from "./engine-account-choice"; - -const engine = (instanceId: string, driverKind: string, displayName: string, extra: Partial = {}): InstanceInfo => ({ - instanceId, driverKind, displayName, - snapshot: { state: "available", authenticated: true }, - models: { default: "sonnet", options: [{ id: "sonnet", label: "Sonnet" }, { id: "opus", label: "Opus" }] }, - ...extra, -}); - -const instances = [ - engine("claude-1f2e", "claudeAgent", "Work"), - engine("claude", "claudeAgent", "Claude"), - engine("codex", "codex", "Codex"), - engine("opencode", "opencodeGo", "OpenCode"), -]; - -describe("the bot's Account row", () => { - it("lists the provider's signed-in accounts, the app's own account first", () => { - expect(accountChoice(instances, "claude")).toEqual({ - value: "claude", removed: false, - options: [{ value: "claude", label: "Claude" }, { value: "claude-1f2e", label: "Work" }], - }); - }); - - it("lists a provider's saved API keys by name, in the order they were added, and switches a bot between them", () => { - const key = (instanceId: string, displayName: string, providerId: string) => engine(instanceId, "openai-compat", displayName, - { access: "api", providerId, models: { default: "MiniMax-M3.1-Flash", options: [{ id: "MiniMax-M3.1-Flash", label: "MiniMax-M3.1-Flash" }, { id: "MiniMax-M4", label: "MiniMax-M4" }] } }); - const keys = [...instances, key("openai-compat-a", "MiniMax", "minimax"), key("openai-compat-g", "Groq", "groq"), key("openai-compat-b", "MiniMax key 2", "minimax")]; - expect(accountChoice(keys, "openai-compat-b")).toEqual({ - value: "openai-compat-b", removed: false, keys: true, - options: [{ value: "openai-compat-a", label: "MiniMax" }, { value: "openai-compat-b", label: "MiniMax key 2" }], - }); - expect(accountChoice(keys, "openai-compat-g")).toBeNull(); - expect(onAccount({ instanceId: "openai-compat-a", model: "MiniMax-M4" }, keys.at(-1)!)).toEqual({ instanceId: "openai-compat-b", model: "MiniMax-M4" }); - }); - - it("shows nothing for one account or an AI without accounts", () => { - expect(accountChoice(instances, "codex")).toBeNull(); - expect(accountChoice(instances, "opencode")).toBeNull(); - expect(accountChoice([engine("claude", "claudeAgent", "Claude")], "claude")).toBeNull(); - }); - - it("says plainly when the bot's account was removed, and offers the ones left", () => { - expect(accountChoice(instances, "claude-gone")).toEqual({ - value: REMOVED_ACCOUNT, removed: true, - options: [{ value: "claude", label: "Claude" }, { value: "claude-1f2e", label: "Work" }], - }); - }); - - it("names two accounts with the same name by their email", () => { - const twins = [engine("claude", "claudeAgent", "Claude", { snapshot: { state: "available", account: { email: "me@home.test" } } }), - engine("claude-9", "claudeAgent", "Claude", { snapshot: { state: "available", account: { email: "me@work.test" } } })]; - expect(accountChoice(twins, "claude")?.options.map((option) => option.label)).toEqual(["Claude · me@home.test", "Claude · me@work.test"]); - }); - - it("puts two bots on two accounts while each keeps its model and effort", () => { - const first = { instanceId: "claude", model: "opus", effort: "high" as const, variant: "1m" }; - const second = onAccount(first, instances[0]!); - expect(second).toEqual({ instanceId: "claude-1f2e", model: "opus", effort: "high", variant: "1m" }); - expect(first.instanceId).not.toBe(second.instanceId); - expect(onAccount({ instanceId: "claude", model: "haiku" }, instances[0]!)).toEqual({ instanceId: "claude-1f2e", model: "sonnet" }); - }); -}); diff --git a/src/lib/engine-account-choice.ts b/src/lib/engine-account-choice.ts deleted file mode 100644 index 84f6badd5f..0000000000 --- a/src/lib/engine-account-choice.ts +++ /dev/null @@ -1,40 +0,0 @@ -import type { ModelSelection } from "../../shared/wire"; -import { accountsLike, addedAccount, keysLike } from "../../shared/engine-accounts"; -import type { InstanceInfo } from "@/state/instance-info"; - -export const REMOVED_ACCOUNT = "removed"; - -export interface AccountChoice { - value: string; - options: Array<{ value: string; label: string }>; - removed: boolean; - /** The choice is between saved API keys, not signed-in accounts. */ - keys?: true; -} - -/** The signed-in accounts, or the saved API keys, of the provider a bot runs on, for the bot's Account row; null when - * there is nothing to choose: one account or key, or an AI that has neither. */ -export function accountChoice(instances: readonly InstanceInfo[], instanceId: string): AccountChoice | null { - const removed = !instances.some((instance) => instance.instanceId === instanceId) && Boolean(addedAccount(instanceId)); - const signedIn = accountsLike(instances, instanceId); - const accounts = (signedIn.length ? signedIn : keysLike(instances, instanceId)) - .filter((instance) => instance.instanceId === instanceId || instance.snapshot.state === "available"); - if (accounts.length < (removed ? 1 : 2)) return null; - const named = (instance: InstanceInfo) => { - const email = instance.snapshot.account?.email; - const twin = accounts.some((other) => other !== instance && other.displayName === instance.displayName); - return twin && email ? `${instance.displayName} · ${email}` : instance.displayName; - }; - return { - value: removed ? REMOVED_ACCOUNT : instanceId, - removed, ...(signedIn.length || removed ? {} : { keys: true as const }), - options: accounts.map((instance) => ({ value: instance.instanceId, label: named(instance) })), - }; -} - -/** The same model on another account: kept when that account offers it, else that account's default. */ -export function onAccount(selection: ModelSelection, account: InstanceInfo): ModelSelection { - const offered = account.models.options.length === 0 || account.models.options.some((option) => option.id === selection.model); - if (offered) return { ...selection, instanceId: account.instanceId }; - return { instanceId: account.instanceId, model: account.models.default, ...(selection.effort ? { effort: selection.effort } : {}) }; -} diff --git a/src/lib/notify.test.ts b/src/lib/notify.test.ts index 206db2cf4a..4e6231f92c 100644 --- a/src/lib/notify.test.ts +++ b/src/lib/notify.test.ts @@ -13,7 +13,6 @@ import { readOnArrival, requestNotificationPermission, showNotification, - systemNotificationsAllowed, type NotifyFrame, } from "./notify"; @@ -59,24 +58,22 @@ it("reads a notification as it lands only for the chat in front of the person", }); describe("the desktop app on a Mac", () => { - it("never posts a system notification or asks for the permission, and keeps the app's own ping", async () => { - const { notices, requestPermission } = installNotification("granted"); - const show = vi.fn(async () => true); + it("posts a system notification through main when a bot finishes while the window is not focused", async () => { + const { notices } = installNotification("granted", false); + const show = vi.fn(async (_note: object) => true); vi.stubGlobal("window", { focus: vi.fn(), duskDesktop: { platform: "darwin", desktopNotifications: { show } } }); - expect(systemNotificationsAllowed()).toBe(false); - showNotification(frame, vi.fn()); - showNotification({ ...frame, kind: "approval" }, vi.fn()); + showNotification(frame, vi.fn(), "/avatars/bot-1.png", "thread-1"); + await vi.waitFor(() => expect(uiSounds.play).toHaveBeenCalledOnce()); + expect(show).toHaveBeenCalledWith(expect.objectContaining({ title: "Maus finished", body: "All done", botId: "bot-1", threadId: "thread-1", picture: "/avatars/bot-1.png" })); + expect(show.mock.calls[0][0]).not.toHaveProperty("ask"); expect(notices).toHaveLength(0); - expect(show).not.toHaveBeenCalled(); - expect(uiSounds.play).toHaveBeenCalledTimes(2); - expect(await requestNotificationPermission()).toBeNull(); - expect(requestPermission).not.toHaveBeenCalled(); }); - it("still shows them on Windows and Linux", () => { - expect(systemNotificationsAllowed("win32")).toBe(true); - expect(systemNotificationsAllowed("linux")).toBe(true); - expect(systemNotificationsAllowed(undefined)).toBe(true); + it("asks for the permission from the switch, as every other platform does", async () => { + const { requestPermission } = installNotification("default"); + vi.stubGlobal("window", { focus: vi.fn(), duskDesktop: { platform: "darwin" } }); + await expect(requestNotificationPermission()).resolves.toBe("granted"); + expect(requestPermission).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/notify.ts b/src/lib/notify.ts index a0fc6b8a78..bd09535a76 100644 --- a/src/lib/notify.ts +++ b/src/lib/notify.ts @@ -16,11 +16,6 @@ export function setNotificationPlace(name: string | null) { placeName = name; } -/** The desktop app on a Mac never posts system notifications: the dock, the island and the unread dots carry them. */ -export function systemNotificationsAllowed(platform: string | undefined = typeof window === "undefined" ? undefined : window.duskDesktop?.platform): boolean { - return platform !== "darwin"; -} - /** A notification about the chat in front is read as it lands, so a phone's push waiting out its grace never goes. */ export function readOnArrival(frame: Pick, visibleThreadId: string | null, inFront: boolean): boolean { return frame.kind !== "spend" && inFront && visibleThreadId !== null && visibleThreadId === frame.threadId; @@ -28,7 +23,7 @@ export function readOnArrival(frame: Pick, vis /** Call from the click: browsers may reject a permission request made later from an SSE frame. Resolves to the permission now in force. */ export async function requestNotificationPermission(): Promise { - if (typeof Notification === "undefined" || !systemNotificationsAllowed()) return null; + if (typeof Notification === "undefined") return null; try { return Notification.permission === "default" ? await Notification.requestPermission() : Notification.permission; } catch { @@ -55,8 +50,6 @@ export function showNotification( if (frame.kind === "done" && !finishedNotificationsEnabled()) return; const spend = frame.kind === "spend"; if (!spend && chatInFront() && visibleThreadId === frame.threadId) return; - // the app's own ping stays, with its own setting; only the system banner goes - if (!systemNotificationsAllowed()) return play(); if (Notification.permission !== "granted") return; const title = placeName ? `${placeName} · ${frame.title}` : frame.title; diff --git a/src/lib/routines.ts b/src/lib/routines.ts index c453fbbe66..441134ebd2 100644 --- a/src/lib/routines.ts +++ b/src/lib/routines.ts @@ -15,4 +15,4 @@ export type { RoutineStripEntry, RoutineTiming, } from "../../shared/routines"; -export { ROUTINE_PROBLEM_STATUSES, isRoutineProblemRun, isSpentOnceRoutine } from "../../shared/routines"; +export { ROUTINE_PROBLEM_STATUSES, isRoutineProblemRun, isPassedOnceRoutine } from "../../shared/routines"; diff --git a/src/styles/settings.css b/src/styles/settings.css index e46d758722..90c32dda72 100644 --- a/src/styles/settings.css +++ b/src/styles/settings.css @@ -548,7 +548,7 @@ @media (min-width: 640px) { [data-settings-sheet] .settings-nav { padding-top: 6px; } :root [data-settings-sheet] .settings-dialog .settings-pane { gap: 28px; } - :root [data-settings-sheet] .settings-dialog .settings-pane [data-settings-rows]:not([data-settings-rows] [data-settings-rows]) { + :root [data-settings-sheet] .settings-dialog .settings-pane :is([data-settings-rows], [data-panel-card-surface]):not([data-settings-rows] [data-settings-rows]) { padding: 4px; border-radius: 14px; background-color: color-mix(in srgb, var(--color-ink) 2.75%, transparent); @@ -556,7 +556,7 @@ :root [data-settings-sheet] .settings-dialog .settings-pane [class*="bg-composer"][class*="rounded-[12px]"]:not([data-settings-rows]) { background-color: color-mix(in srgb, var(--color-ink) 2.75%, transparent); } - :root [data-settings-sheet] .settings-dialog .settings-pane [data-settings-rows] > :is(button, a, div, label):not(.contents, [hidden], [data-settings-rows]) { border-radius: 10px; } + :root [data-settings-sheet] .settings-dialog .settings-pane :is([data-settings-rows], [data-panel-card-surface]) > :is(button, a, div, label):not(.contents, [hidden], [data-settings-rows]) { border-radius: 10px; } :root [data-settings-sheet] .settings-dialog .settings-pane [data-settings-group-head] { margin-bottom: 8px; } :root [data-settings-sheet] .settings-dialog .settings-pane [data-settings-rows] :is(input:not([type="checkbox"], [type="radio"], [type="range"], [type="file"], [type="color"], .bg-transparent), textarea:not(.bg-transparent), :is(div, label):has(> input.bg-transparent):is(.border)) { background-color: color-mix(in srgb, var(--color-ink) 7%, transparent);