Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/copy/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1431,6 +1431,7 @@
"HM-BOT-02.olderTitle": "Older chats",
"HM-BOT-02.newFailed": "Couldn't start a new chat.",
"HM-BOT-02.olderFailed": "Couldn't open that chat.",
"HM-BOT-02.clearing": "This conversation is being cleared. Write again in a moment.",
"HM-BOT-03.title": "New bot",
"HM-BOT-03.templatesIntro": "Start from a template or from scratch. You adjust everything after.",
"HM-BOT-03.blank": "Start from scratch",
Expand Down
1 change: 1 addition & 0 deletions packages/copy/locales/es-419.json
Original file line number Diff line number Diff line change
Expand Up @@ -1431,6 +1431,7 @@
"HM-BOT-02.olderTitle": "Chats anteriores",
"HM-BOT-02.newFailed": "No se pudo empezar un chat nuevo.",
"HM-BOT-02.olderFailed": "No se pudo abrir ese chat.",
"HM-BOT-02.clearing": "Se está borrando esta conversación. Escribe de nuevo en un momento.",
"HM-BOT-03.title": "Bot nuevo",
"HM-BOT-03.templatesIntro": "Empieza con una plantilla o desde cero. Después ajustas todo.",
"HM-BOT-03.blank": "Empezar desde cero",
Expand Down
14 changes: 14 additions & 0 deletions packages/copy/test/copy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,20 @@ describe("locale files (CT-10)", () => {
}
});

test("every TaintSource kind has HM-APPR-01.taintFrom copy in both locales", () => {
const types = readFileSync(new URL("../../core/src/types.ts", import.meta.url), "utf8");
const kinds = /interface TaintSource \{\s*kind: ([^;]+);/
.exec(types)![1]!
.split("|")
.map((k) => k.trim().replace(/"/g, ""));
expect(kinds.length).toBeGreaterThanOrEqual(6);
for (const kind of kinds) {
const key = `HM-APPR-01.taintFrom.${kind}`;
expect(en[key], key).toBeTruthy();
expect(es[key], key).toBeTruthy();
}
});

test("no em or en dashes in copy (house style)", () => {
for (const [k, v] of [...Object.entries(en), ...Object.entries(es)]) expect(v, k).not.toMatch(/[–—]/);
});
Expand Down
21 changes: 14 additions & 7 deletions packages/runtime/src/bots.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ export interface BotsApiDeps {
clear(botId: string): Promise<string>;
/** A turn of that bot is running (Review Focus 1). */
busy(botId: string): boolean;
/** Marks a bot as clearing while its chats or row are being deleted (#108). */
setClearing?(botId: string, active: boolean): void;
/** The fingerprint. Without it, every change that needs one is declined. */
confirm?: BotPorts["confirm"];
/** A copy key in the app's language, for the fingerprint's prompt; English without it. */
Expand Down Expand Up @@ -333,15 +335,20 @@ export function createBotsApi(deps: BotsApiDeps): { bots: HermitBots; modes: Her
if (bot.primary) return refused("primary");
// Review Focus 1: never under a running turn, whose late writes would leave chats or notes for a bot that is gone.
if (deps.busy(id)) return refused("busy");
deps.setClearing?.(id, true);
try {
await store.remove(id);
} catch (err) {
return storeRefusal(err);
try {
await store.remove(id);
} catch (err) {
return storeRefusal(err);
}
// The store deleted its chats, notes, grants and sources; this also drops its sessions kept in memory.
await deps.sessions.clear(id);
await log(id, "bot.deleted");
return done(bot);
} finally {
deps.setClearing?.(id, false);
}
// The store deleted its chats, notes, grants and sources; this also drops its sessions kept in memory.
await deps.sessions.clear(id);
await log(id, "bot.deleted");
return done(bot);
},

async notes(id, opts = {}) {
Expand Down
37 changes: 33 additions & 4 deletions packages/runtime/src/hermit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,10 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
store, sessions, memory, settings: table, audit,
clear: (botId) => api.clearConversation(botId),
busy: (botId) => running.has(botId),
setClearing: (botId, active) => {
if (active) clearing.add(botId);
else clearing.delete(botId);
},
...(ports.bots ? { confirm: (prompt: string) => ports.bots!.confirm(prompt) } : {}),
...(ports.copy ? { say: (key: string) => ports.copy!(ports.language(), key) } : {}),
proposals,
Expand Down Expand Up @@ -887,7 +891,16 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
* send already sees it.
*/
const running = new Map<string, string[]>();
const clearing = new Set<string>();
const botOf = new Map<string, string>();
class ClearingError extends Error {
constructor() {
super("This conversation is being cleared.");
this.name = "ClearingError";
}
}
const clearingReply = (): string =>
ports.copy ? ports.copy(ports.language(), "HM-BOT-02.clearing") : "This conversation is being cleared. Write again in a moment.";
const markRunning = (botId: string, sessionId: string): (() => void) => {
running.set(botId, [...(running.get(botId) ?? []), sessionId]);
let ended = false;
Expand All @@ -907,14 +920,16 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
* so lower-priority work waits for the whole turn, not just its current call (spec 6.6), and its bot is marked running.
*/
const inTurn = <T>(sessionId: string, priority: RunPriority, run: (session: SessionState, botId: string) => Promise<T>): Promise<T> => {
const release = queue.hold(priority);
const handedOut = botOf.get(sessionId);
if (handedOut !== undefined && clearing.has(handedOut)) return Promise.reject(new ClearingError());
const release = queue.hold(priority);
let unmark = handedOut !== undefined ? markRunning(handedOut, sessionId) : undefined;
return (async () => {
try {
const session = await sessions.load(sessionId);
if (!session) throw new Error(`No session ${sessionId}.`);
const botId = session.botId ?? HERMIT_BOT_ID;
if (clearing.has(botId)) throw new ClearingError();
botOf.set(sessionId, botId);
unmark ??= markRunning(botId, sessionId);
return await run(session, botId);
Expand Down Expand Up @@ -1111,6 +1126,7 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
},
async startSession(opts = {}) {
const botId = opts.botId ?? HERMIT_BOT_ID;
if (clearing.has(botId)) throw new ClearingError();
// Only for a bot that exists (Hermit's row is the migration's own): a session of no bot could never run a turn.
if (botId !== HERMIT_BOT_ID && !(await store.get(botId))) throw new Error(`No bot ${botId}.`);
const id = ports.newId();
Expand All @@ -1120,6 +1136,7 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
return id;
},
async resumeSession(botId = HERMIT_BOT_ID) {
if (clearing.has(botId)) throw new ClearingError();
const last = await sessions.latest(botId);
if (!last) return api.startSession({ botId });
botOf.set(last, botId);
Expand All @@ -1137,7 +1154,12 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
// F-M14: while a turn of that bot runs nothing is cleared, so its late writes never land in a chat that is gone.
const runningIn = running.get(botId)?.at(-1);
if (runningIn !== undefined) return runningIn;
await sessions.clear(botId);
clearing.add(botId);
try {
await sessions.clear(botId);
} finally {
clearing.delete(botId);
}
return api.startSession({ botId });
},
memories: {
Expand All @@ -1154,7 +1176,9 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
},
},
// The user's own turn, run as the session's bot (spec 6.6): its values are this turn's, built for that bot.
send: (sessionId, text, live = {}) => inTurn(sessionId, "user", async (session, botId) => {
send: async (sessionId, text, live = {}) => {
try {
return await inTurn(sessionId, "user", async (session, botId) => {
const turn = await turnFor(botId);
// Security review 00:40: what the prompt's notes were read from, this session has read too, before any model call.
addReads(session, turn.profileReads);
Expand Down Expand Up @@ -1307,7 +1331,12 @@ export function createHermit(ports: HermitPorts, profile: ModelProfile): Hermit
},
});
return view;
}),
});
} catch (err) {
if (err instanceof ClearingError) return { kind: "reply", text: clearingReply() };
throw err;
}
},
// Seguir, a reply the user is waiting for: it holds that priority, as the session's bot, with the bot's cache key (a
// long reply's Seguir reads under the bot's own long key).
continueReply: (sessionId, live = {}) => inTurn(sessionId, "reply", async (session, botId) => {
Expand Down
155 changes: 155 additions & 0 deletions packages/runtime/test/bots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -483,3 +483,158 @@ describe("a proposal's offer (F-M15)", () => {
expect(p.used).toEqual(["o1"]);
});
});

describe("refuse turns, startSession and resumeSession while a bot is being cleared (#108)", () => {
function defer() {
let open = () => {};
const promise = new Promise<void>((resolve) => {
open = resolve;
});
return { promise, open };
}

/** Wraps a SqlPort so the first write matching `match` waits on a deferred gate. */
function holdSqlOn(match: RegExp) {
const base = nodeSql();
const gate = defer();
const entered = defer();
let held = false;
const sql: typeof base = {
exec: async (q, params) => {
if (!held && match.test(q)) {
held = true;
entered.open();
await gate.promise;
}
return base.exec(q, params);
},
query: (q, params) => base.query(q, params),
transaction: (fn) => base.transaction((tx) => fn({
...tx,
exec: async (q, params) => {
if (!held && match.test(q)) {
held = true;
entered.open();
await gate.promise;
}
return tx.exec(q, params);
},
})),
close: () => base.close(),
};
return { sql, entered: entered.promise, release: gate.open };
}

test("bots.reset refuses a concurrent send, startSession, and resumeSession without orphan chat_turns", async () => {
const h = holdSqlOn(/DELETE FROM sessions WHERE bot_id = \?/i);
const { createHermit } = await import("../src/hermit.ts");
const { PROFILE } = await import("./bot-harness.ts");
const store = createBotsStore(h.sql, () => NOW);
await migrate(h.sql);
await store.create({ id: "b1", name: "Viajes", role: "Planeas viajes.", grants: ["notes"], sources: none, mode: null });
let n = 0;
const hermit = createHermit({
sql: h.sql,
signer: ed25519Signer(new Uint8Array(32).fill(8)),
notifier: { schedule: async () => "n", cancel: async () => {} },
calendar: { list: async () => [], add: async () => {}, calendars: async () => [] },
replySender: { send: async () => "sent" },
engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) },
approvals: { request: async () => ({ kind: "denied" }) },
now: () => NOW,
timeZone: () => "America/Costa_Rica",
language: () => "es-419",
newId: () => `id${++n}`,
copy,
}, PROFILE);

const oldSession = await hermit.resumeSession("b1");
const resetting = hermit.bots.reset("b1");
await h.entered;

const refused = await hermit.send(oldSession, "hola durante reset");
expect(refused).toEqual({ kind: "reply", text: copy("es-419", "HM-BOT-02.clearing") });
await expect(hermit.startSession({ botId: "b1" })).rejects.toThrow();
await expect(hermit.resumeSession("b1")).rejects.toThrow();

h.release();
const res = await resetting;
expect(res.kind).toBe("done");
const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)");
expect(orphans).toEqual([]);
});

test("bots.remove refuses a concurrent send, startSession, and resumeSession without orphan chat_turns", async () => {
const h = holdSqlOn(/DELETE FROM bots WHERE id = \?/i);
const { createHermit } = await import("../src/hermit.ts");
const { PROFILE } = await import("./bot-harness.ts");
await migrate(h.sql);
const store = createBotsStore(h.sql, () => NOW);
await store.create({ id: "b1", name: "Viajes", role: "Planeas viajes.", grants: ["notes"], sources: none, mode: null });
let n = 0;
const hermit = createHermit({
sql: h.sql,
signer: ed25519Signer(new Uint8Array(32).fill(8)),
notifier: { schedule: async () => "n", cancel: async () => {} },
calendar: { list: async () => [], add: async () => {}, calendars: async () => [] },
replySender: { send: async () => "sent" },
engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) },
approvals: { request: async () => ({ kind: "denied" }) },
now: () => NOW,
timeZone: () => "America/Costa_Rica",
language: () => "en",
newId: () => `id${++n}`,
copy,
}, PROFILE);

const oldSession = await hermit.resumeSession("b1");
const removing = hermit.bots.remove("b1");
await h.entered;

const refused = await hermit.send(oldSession, "hello during remove");
expect(refused).toEqual({ kind: "reply", text: copy("en", "HM-BOT-02.clearing") });
await expect(hermit.startSession({ botId: "b1" })).rejects.toThrow();
await expect(hermit.resumeSession("b1")).rejects.toThrow();

h.release();
const res = await removing;
expect(res.kind).toBe("done");
const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)");
expect(orphans).toEqual([]);
});

test("clearConversation refuses a concurrent send without orphan chat_turns", async () => {
const h = holdSqlOn(/DELETE FROM sessions WHERE bot_id = \?/i);
const { createHermit } = await import("../src/hermit.ts");
const { PROFILE } = await import("./bot-harness.ts");
await migrate(h.sql);
let n = 0;
const hermit = createHermit({
sql: h.sql,
signer: ed25519Signer(new Uint8Array(32).fill(8)),
notifier: { schedule: async () => "n", cancel: async () => {} },
calendar: { list: async () => [], add: async () => {}, calendars: async () => [] },
replySender: { send: async () => "sent" },
engine: { complete: async () => ({ text: '{"choice":"respond"}', toolCalls: [] }) },
approvals: { request: async () => ({ kind: "denied" }) },
now: () => NOW,
timeZone: () => "America/Costa_Rica",
language: () => "es-419",
newId: () => `id${++n}`,
copy,
}, PROFILE);

const oldSession = await hermit.resumeSession();
const clearing = hermit.clearConversation();
await h.entered;

const refused = await hermit.send(oldSession, "hola durante clear");
expect(refused).toEqual({ kind: "reply", text: copy("es-419", "HM-BOT-02.clearing") });

h.release();
const fresh = await clearing;
expect(fresh).toBeTruthy();
const orphans = await h.sql.query("SELECT id FROM chat_turns WHERE session_id NOT IN (SELECT id FROM sessions)");
expect(orphans).toEqual([]);
});
});
Loading