diff --git a/README.md b/README.md index 818844a..c51656d 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,10 @@ Agent products that act in your tools share three problems: approvals that live - Automations triggered by a cron schedule, new Gmail messages matching a search, or a secret webhook URL - MCP connections over Streamable HTTP with OAuth 2.1 + PKCE, or bearer tokens; presets for GitHub, Linear, Notion, Atlassian, Sentry - Approval inbox, editable approvals, deny-with-reason, cancel now / after this step +- Approve a plan, not every step: the agent proposes the exact actions it will take, you untick what you don't want, and the kept actions run without asking again (even after the task read outside content, because you saw each one) +- Several pending actions from one step can be ticked and signed off together +- Approvals that learn: after you approve the same kind of action unchanged a few times, Synapse offers a visible, removable rule ("emails where every address is @acme.com"). Tasks that read outside content still ask +- Undo window: approved sends and deletes wait a few seconds (default 10, configurable) with an Undo button - Knowledge base: upload docs, hybrid full-text + vector search (pgvector, reciprocal rank fusion) - Memory you can read and edit; the agent can add notes, but not from a tainted run without asking - Web search (Tavily, Brave or Exa) and SSRF-guarded web fetch diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts index f6c99b3..725ee2c 100644 --- a/apps/server/src/app.ts +++ b/apps/server/src/app.ts @@ -8,6 +8,7 @@ import { clientMetadataDocument, connections, oauthCallback } from "./routes/con import { googleCallback, integrations } from "./routes/integrations"; import { models } from "./routes/models"; import { approvals, runs } from "./routes/runs"; +import { suggestions } from "./routes/suggestions"; import type { Services } from "./services"; export function createApp(services: Services) { @@ -65,6 +66,7 @@ export function createApp(services: Services) { api.route("/connections", connections); api.route("/integrations/google/callback", googleCallback); api.route("/integrations", integrations); + api.route("/policy/suggestions", suggestions); api.route("/policy", policy); api.route("/memories", memories); api.route("/documents", documents); diff --git a/apps/server/src/prompt.ts b/apps/server/src/prompt.ts index c730f26..5890141 100644 --- a/apps/server/src/prompt.ts +++ b/apps/server/src/prompt.ts @@ -9,6 +9,7 @@ How you work: - Ask a short clarifying question only when a wrong guess would be costly (wrong recipient, wrong repository, irreversible change). Otherwise make a reasonable assumption and say what you assumed. - When you draft something that will be sent or published (an email, a message, an issue), put the complete final content in the tool call. The user reviews exactly that on an approval card. - Some actions need the user's approval. The system asks for it automatically; you do not need to ask in text first. If an action is denied, do not retry it in another form; acknowledge it and continue or ask what they want instead. +- When a task needs several actions that change things (sending, writing, deleting), first call propose_plan with the exact calls you intend to make, so the user can approve them once. After approval, make exactly the approved calls with exactly the same inputs, and nothing the user removed. For a single action, just make the call. - If a tool fails, read the error, fix your input once if it is clearly your mistake, and otherwise tell the user what failed. - Keep answers concise and skimmable. Cite sources (page titles and URLs, document names) for facts you looked up. diff --git a/apps/server/src/routes/account.ts b/apps/server/src/routes/account.ts index 96311f4..929c035 100644 --- a/apps/server/src/routes/account.ts +++ b/apps/server/src/routes/account.ts @@ -1,5 +1,5 @@ import { unsafePatternReason } from "@synapse/core"; -import { schema } from "@synapse/db"; +import { DEFAULT_UNDO_SECONDS, MAX_UNDO_SECONDS, schema } from "@synapse/db"; import { ingestDocument, searchKnowledge } from "@synapse/tools"; import { and, asc, desc, eq, gte, sql } from "drizzle-orm"; import { Hono } from "hono"; @@ -12,6 +12,11 @@ const Matcher = z.discriminatedUnion("op", [ z.object({ path: z.string().min(1), op: z.literal("in"), value: z.array(z.json()) }), z.object({ path: z.string().min(1), op: z.literal("allEndWith"), value: z.array(z.string()) }), z.object({ path: z.string().min(1), op: z.literal("matches"), value: z.string().max(500) }), + z.object({ + path: z.string().default("*"), + op: z.literal("emailsEndWith"), + value: z.array(z.string().min(2)).min(1), + }), ]); const Defaults = z.object({ read: Decision, @@ -233,6 +238,7 @@ export const settings = new Hono() providerKeys: z .partialRecord(z.enum(PROVIDERS), z.string().min(8).max(400).nullable()) .optional(), + undoSeconds: z.number().int().min(0).max(MAX_UNDO_SECONDS).optional(), }), ); const { db } = c.var.services.database; @@ -250,6 +256,7 @@ export const settings = new Hono() ...(input.instructions !== undefined ? { instructions: input.instructions } : {}), ...(input.models ? { models: input.models } : {}), ...(input.budgets ? { budgets: input.budgets } : {}), + ...(input.undoSeconds !== undefined ? { undoSeconds: input.undoSeconds } : {}), providerKeys: keys, }; await db @@ -273,6 +280,7 @@ async function loadSettings(c: { var: AppEnv["Variables"] }) { perDayUsd: config.DAY_MAX_COST_USD, }, providerKeys: Object.fromEntries(PROVIDERS.map((p) => [p, Boolean(s?.providerKeys?.[p])])), + undoSeconds: s?.undoSeconds ?? DEFAULT_UNDO_SECONDS, }; } diff --git a/apps/server/src/routes/chats.ts b/apps/server/src/routes/chats.ts index e3da180..445980f 100644 --- a/apps/server/src/routes/chats.ts +++ b/apps/server/src/routes/chats.ts @@ -73,6 +73,7 @@ export const chats = new Hono() output: r.output, decidedBy: r.decidedBy, preview: r.preview, + executeAfter: r.executeAfter?.toISOString() ?? null, })) : []; const [run] = await db diff --git a/apps/server/src/routes/runs.ts b/apps/server/src/routes/runs.ts index 63654e6..ab07418 100644 --- a/apps/server/src/routes/runs.ts +++ b/apps/server/src/routes/runs.ts @@ -1,11 +1,20 @@ -import { evaluatePolicy } from "@synapse/core"; -import { decideToolCall, PgRunStore, readEvents, requestCancel, schema } from "@synapse/db"; +import { evaluatePolicy, type RunEvent, UNDO_DENIAL } from "@synapse/core"; +import { + decideToolCall, + decideToolCalls, + PgRunStore, + readEvents, + requestCancel, + schema, + undoToolCall, +} from "@synapse/db"; import type { JSONValue } from "ai"; import { and, asc, desc, eq } from "drizzle-orm"; import { Hono } from "hono"; import { streamSSE } from "hono/streaming"; import { z } from "zod"; import { type AppEnv, apiError, body } from "../http"; +import type { Services } from "../services"; const PAUSE_OR_END = new Set(["waiting", "completed", "failed", "cancelled"]); const EVENT_PAGE = 1000; @@ -53,6 +62,7 @@ export const runs = new Hono() output: schema.toolCalls.output, decidedBy: schema.toolCalls.decidedBy, decidedAt: schema.toolCalls.decidedAt, + executeAfter: schema.toolCalls.executeAfter, createdAt: schema.toolCalls.createdAt, }) .from(schema.toolCalls) @@ -75,7 +85,7 @@ export const runs = new Hono() : 0; c.header("x-accel-buffering", "no"); - return streamSSE(c, async (stream) => { + const response = streamSSE(c, async (stream) => { let wake: (() => void) | null = null; let pending = true; // read once immediately const unsubscribe = bus.subscribe(run.id, () => { @@ -127,6 +137,10 @@ export const runs = new Hono() clearInterval(ping); } }); + // A compressing proxy (Next's rewrites gzip by default) buffers small writes, so a + // single status change could sit unsent until more output came. no-transform opts out. + response.headers.set("cache-control", "no-cache, no-transform"); + return response; }) .post("/:id/tool-calls/:toolCallId/decision", async (c) => { @@ -141,18 +155,99 @@ export const runs = new Hono() const runId = c.req.param("id"); if (input.approved && input.input !== undefined) await assertEditAllowed(c, runId, c.req.param("toolCallId"), input.input); - await decideToolCall(c.var.services.database.db, { + const toolCallId = c.req.param("toolCallId"); + const decided = await decideToolCall(c.var.services.database.db, { userId: c.var.user.id, runId, - toolCallId: c.req.param("toolCallId"), + toolCallId, approved: input.approved, ...(input.reason ? { reason: input.reason } : {}), ...(input.input !== undefined ? { editedInput: input.input } : {}), }); - await c.var.services.wake(runId); + const { services } = c.var; + const { executeAfter } = decided; + if (executeAfter) { + // Live viewers (another tab, the run panel) get the countdown too. + await emitNow(services, runId, { + type: "tool.status", + toolCallId, + status: "approved", + executeAfter: executeAfter.toISOString(), + }); + } + if (decided.requeued && decided.runnableAt) { + // Parked until the window ends: it is queued, not waiting on you. + await emitNow(services, runId, { type: "run.status", status: "queued" }); + wakeAt(services, runId, decided.runnableAt); + } else await services.wake(runId); + return c.json({ executeAfter: executeAfter?.toISOString() ?? null }); + }) + + .post("/:id/tool-calls/:toolCallId/undo", async (c) => { + const runId = c.req.param("id"); + const toolCallId = c.req.param("toolCallId"); + const { services } = c.var; + await undoToolCall(services.database.db, { userId: c.var.user.id, runId, toolCallId }); + const output = { type: "denied" as const, reason: UNDO_DENIAL }; + await emitNow(services, runId, { type: "tool.status", toolCallId, status: "denied" }); + await emitNow(services, runId, { type: "tool.result", toolCallId, output }); + await services.wake(runId); return c.body(null, 204); }) + // Several calls from one run decided at once (the grouped checklist). All or nothing. + .post("/:id/tool-calls/decisions", async (c) => { + const { decisions } = await body( + c, + z.object({ + decisions: z + .array( + z.object({ + toolCallId: z.string().min(1), + approved: z.boolean(), + reason: z.string().max(1000).optional(), + input: z.json().optional(), + }), + ) + .min(1) + .max(100), + }), + ); + const runId = c.req.param("id"); + if (new Set(decisions.map((d) => d.toolCallId)).size !== decisions.length) + apiError(400, "duplicate", "Each action can be decided once."); + for (const d of decisions) + if (d.approved && d.input !== undefined) + await assertEditAllowed(c, runId, d.toolCallId, d.input); + const { services } = c.var; + const decided = await decideToolCalls(services.database.db, { + userId: c.var.user.id, + runId, + decisions: decisions.map((d) => ({ + toolCallId: d.toolCallId, + approved: d.approved, + ...(d.reason ? { reason: d.reason } : {}), + ...(d.approved && d.input !== undefined ? { editedInput: d.input } : {}), + })), + }); + for (const [toolCallId, at] of Object.entries(decided.executeAfter)) + await emitNow(services, runId, { + type: "tool.status", + toolCallId, + status: "approved", + executeAfter: at.toISOString(), + }); + if (decided.requeued && decided.runnableAt) { + await emitNow(services, runId, { type: "run.status", status: "queued" }); + wakeAt(services, runId, decided.runnableAt); + } else await services.wake(runId); + return c.json({ + executeAfter: Object.fromEntries( + Object.entries(decided.executeAfter).map(([id, at]) => [id, at.toISOString()]), + ), + }); + }) + .post("/:id/cancel", async (c) => { const { mode } = await body( c, @@ -191,6 +286,24 @@ export const approvals = new Hono().get("/", async (c) => { return c.json({ approvals: rows }); }); +/** + * Appends an event for a run no worker may be driving (it is parked). Forgets the cached + * seq afterwards so a later writer on this instance re-reads the tail. + */ +async function emitNow(services: Services, runId: string, event: RunEvent) { + await services.events.emit(runId, event); + services.events.forget(runId); +} + +/** Wakes workers when a run parked on an undo window becomes claimable, not on the next poll. */ +function wakeAt(services: Services, runId: string, at: Date) { + const timer = setTimeout( + () => void services.wake(runId).catch(() => {}), + Math.max(0, at.getTime() - Date.now()) + 25, + ); + timer.unref?.(); +} + /** Edited arguments are re-checked against block rules: editing must not route around them. */ async function assertEditAllowed( c: { var: AppEnv["Variables"] }, diff --git a/apps/server/src/routes/suggestions.ts b/apps/server/src/routes/suggestions.ts new file mode 100644 index 0000000..48c8779 --- /dev/null +++ b/apps/server/src/routes/suggestions.ts @@ -0,0 +1,99 @@ +import { type PastDecision, SUGGEST_LOOKBACK_DAYS, suggestRules } from "@synapse/core"; +import { PgRunStore, schema } from "@synapse/db"; +import { and, desc, eq, gte, isNotNull, ne, sql } from "drizzle-orm"; +import { Hono } from "hono"; +import { type AppEnv, apiError } from "../http"; + +type Ctx = { var: AppEnv["Variables"] }; + +/** Learned rules: offer an allow rule for actions the user keeps approving unchanged. */ +export const suggestions = new Hono() + .get("/", async (c) => { + const { suggestions } = await load(c); + return c.json({ suggestions }); + }) + .post("/:id/accept", async (c) => { + const { suggestions, store } = await load(c); + const s = suggestions.find((x) => x.id === c.req.param("id")); + if (!s) apiError(404, "not_found", "Suggestion not found."); + const { db } = c.var.services.database; + const userId = c.var.user.id; + // First among allow/ask rules so it takes effect; block rules still win regardless. + await db.transaction(async (tx) => { + await tx + .update(schema.policyRules) + .set({ position: sql`${schema.policyRules.position} + 1` }) + .where(eq(schema.policyRules.userId, userId)); + await tx.insert(schema.policyRules).values({ + userId, + position: 0, + tool: s.tool, + decision: "allow", + when: s.when.length > 0 ? s.when : null, + note: s.note, + }); + }); + return c.json(await store.getPolicy(userId)); + }) + .post("/:id/dismiss", async (c) => { + const id = c.req.param("id"); + const { suggestions, dismissed } = await load(c); + if (!suggestions.some((x) => x.id === id) && !dismissed.includes(id)) + apiError(404, "not_found", "Suggestion not found."); + // Keep the list bounded; the oldest dismissals fall off first. + const next = [...dismissed.filter((d) => d !== id), id].slice(-200); + await c.var.services.database.db + .insert(schema.userSettings) + .values({ userId: c.var.user.id, dismissedSuggestions: next }) + .onConflictDoUpdate({ + target: schema.userSettings.userId, + set: { dismissedSuggestions: next }, + }); + return c.body(null, 204); + }); + +async function load(c: Ctx) { + const { db } = c.var.services.database; + const userId = c.var.user.id; + const since = new Date(Date.now() - SUGGEST_LOOKBACK_DAYS * 24 * 3600_000); + const rows = await db + .select({ + tool: schema.toolCalls.name, + effect: schema.toolCalls.effect, + input: schema.toolCalls.input, + inputEdited: schema.toolCalls.inputEdited, + status: schema.toolCalls.status, + decidedAt: schema.toolCalls.decidedAt, + preview: schema.toolCalls.preview, + }) + .from(schema.toolCalls) + .where( + and( + eq(schema.toolCalls.userId, userId), + // Human decisions only; auto-allowed calls carry no decider. + eq(schema.toolCalls.decidedBy, userId), + isNotNull(schema.toolCalls.decidedAt), + gte(schema.toolCalls.decidedAt, since), + ne(schema.toolCalls.effect, "read"), + ), + ) + .orderBy(desc(schema.toolCalls.decidedAt)) + .limit(2000); + const decisions: PastDecision[] = rows.map((r) => ({ + tool: r.tool, + effect: r.effect, + input: r.input, + inputEdited: r.inputEdited, + approved: r.status !== "denied", + decidedAt: r.decidedAt!, + preview: r.preview, + })); + const store = new PgRunStore(db); + const policy = await store.getPolicy(userId); + const [settings] = await db + .select({ dismissed: schema.userSettings.dismissedSuggestions }) + .from(schema.userSettings) + .where(eq(schema.userSettings.userId, userId)); + const dismissed = settings?.dismissed ?? []; + return { suggestions: suggestRules(decisions, policy.rules, dismissed), dismissed, store }; +} diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 8c2eddb..4db5142 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -2,6 +2,7 @@ import { afterAll, beforeAll, expect, test } from "bun:test"; import type { SeqEvent } from "@synapse/core"; import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; import { schema } from "@synapse/db"; +import { eq } from "drizzle-orm"; import { createApp } from "./app"; import { loadConfig } from "./config"; import { createServices, type Services } from "./services"; @@ -66,6 +67,8 @@ async function sse(cookie: string, runId: string, after = 0): Promise { json: { approved: true, input: { note: "likes green tea" } }, }) ).status, - ).toBe(204); + ).toBe(200); expect((await grace(path, { method: "POST", json: { approved: true } })).status).toBe(409); await worker.processNow(runId); @@ -342,6 +345,152 @@ test("edited approvals are re-checked against block rules; unsafe patterns are r expect(res.status).toBe(422); }); +const ASK_MEMORY = { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], +}; +const notes = (call: ReturnType) => + call("/api/memories").then((r) => + (r.json!.memories as { content: string }[]).map((m) => m.content).sort(), + ); + +test("batch decisions: several calls in one step, decided atomically", async () => { + const cookie = await signUp("batch@example.com"); + const me = api(cookie); + const other = api(await signUp("batch-eve@example.com")); + await me("/api/policy", { method: "PUT", json: ASK_MEMORY }); + script([ + { + toolCalls: [ + { name: "memory_save", input: { note: "one" }, id: "b1" }, + { name: "memory_save", input: { note: "two" }, id: "b2" }, + { name: "memory_save", input: { note: "three" }, id: "b3" }, + ], + }, + { text: "Saved what you approved." }, + ]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "save 3" } }); + const runId = json!.runId; + await worker.processNow(runId); + expect((await me("/api/approvals")).json!.approvals).toHaveLength(3); + + const path = `/api/runs/${runId}/tool-calls/decisions`; + const decisions = [ + { toolCallId: "b1", approved: true }, + { toolCallId: "b2", approved: true, input: { note: "two, edited" } }, + { toolCallId: "b3", approved: false, reason: "not this one" }, + ]; + // Another user's run is invisible; duplicates and unknown ids change nothing. + expect((await other(path, { method: "POST", json: { decisions } })).status).toBe(404); + expect( + ( + await me(path, { + method: "POST", + json: { decisions: [decisions[0], { toolCallId: "b1", approved: false }] }, + }) + ).status, + ).toBe(400); + expect( + ( + await me(path, { + method: "POST", + json: { decisions: [decisions[0], { toolCallId: "nope", approved: true }] }, + }) + ).status, + ).toBe(409); + expect((await me("/api/approvals")).json!.approvals).toHaveLength(3); + + expect((await me(path, { method: "POST", json: { decisions } })).status).toBe(200); + expect((await me(`/api/runs/${runId}`)).json!.run.status).toBe("queued"); + // A second submit (double click, replay) conflicts. + expect((await me(path, { method: "POST", json: { decisions } })).status).toBe(409); + + await worker.processNow(runId); + const detail = await me(`/api/runs/${runId}`); + expect(detail.json!.run.status).toBe("completed"); + expect( + detail.json!.toolCalls.map((c: { id: string; status: string }) => [c.id, c.status]), + ).toEqual([ + ["b1", "succeeded"], + ["b2", "succeeded"], + ["b3", "denied"], + ]); + expect(await notes(me)).toEqual(["one", "two, edited"]); + // Re-queued once: one pause, then straight through to the end. + const statuses = (await sse(cookie, runId)).flatMap((e) => + e.type === "run.status" ? [e.status] : [], + ); + expect(statuses).toEqual(["running", "waiting", "running", "completed"]); +}); + +test("propose_plan: approve with a step removed; the kept call runs, the other asks", async () => { + const me = api(await signUp("plan@example.com")); + await me("/api/policy", { method: "PUT", json: ASK_MEMORY }); + const keep = { tool: "memory_save", input: { note: "likes tea" }, why: "You said so." }; + const drop = { tool: "memory_save", input: { note: "likes coffee" }, why: "A guess." }; + script([ + { + toolCalls: [ + { + name: "propose_plan", + input: { summary: "Save two notes", steps: [keep, drop] }, + id: "plan1", + }, + ], + }, + { + toolCalls: [ + { name: "memory_save", input: { note: "likes tea" }, id: "k1" }, + { name: "memory_save", input: { note: "likes coffee" }, id: "u1" }, + ], + }, + { text: "Saved the note you approved." }, + ]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "save notes" } }); + const runId = json!.runId; + await worker.processNow(runId); + const [asked] = (await me("/api/approvals")).json!.approvals; + expect(asked).toMatchObject({ toolCallId: "plan1", preview: "Save two notes" }); + + // Untick the second step: approve with an input holding only the kept one. + const res = await me(`/api/runs/${runId}/tool-calls/plan1/decision`, { + method: "POST", + json: { approved: true, input: { summary: "Save two notes", steps: [keep] } }, + }); + expect(res.status).toBe(200); + await worker.processNow(runId); + + let detail = await me(`/api/runs/${runId}`); + expect(detail.json!.run.status).toBe("waiting"); + expect(detail.json!.run.planGrants).toEqual([ + { tool: "memory_save", inputHash: expect.any(String), usedBy: "k1" }, + ]); + const byId = (id: string) => + detail.json!.toolCalls.find((c: { id: string }) => c.id === id) as Record; + expect(byId("plan1")).toMatchObject({ status: "succeeded", inputEdited: true }); + expect(JSON.stringify(byId("plan1").output)).toContain("do not do them"); + expect(byId("k1")).toMatchObject({ + status: "approved", + decision: "allow", + decisionReason: "Part of the plan you approved", + }); + expect(byId("u1")).toMatchObject({ status: "awaiting_approval", decision: "ask" }); + expect((await me("/api/approvals")).json!.approvals).toEqual([ + expect.objectContaining({ toolCallId: "u1" }), + ]); + + await me(`/api/runs/${runId}/tool-calls/u1/decision`, { + method: "POST", + json: { approved: false }, + }); + await worker.processNow(runId); + detail = await me(`/api/runs/${runId}`); + expect(detail.json!.run.status).toBe("completed"); + expect(byId("k1")!.status).toBe("succeeded"); + expect(byId("u1")!.status).toBe("denied"); + expect(await notes(me)).toEqual(["likes tea"]); +}); + test("user budgets can only tighten the operator cap", async () => { const { capBudget } = await import("./worker"); expect(capBudget(undefined, 2)).toBe(2); @@ -437,3 +586,87 @@ test("model list covers the catalog, direct refs and the chain, with availabilit clearCatalog(); } }); + +test("approvals that learn: suggest, accept, dismiss", async () => { + const me = api(await signUp("learner@example.com")); + const other = api(await signUp("bystander@example.com")); + const askForNotes = { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [{ tool: "memory_save", decision: "ask" }], + }; + await me("/api/policy", { method: "PUT", json: askForNotes }); + await other("/api/policy", { method: "PUT", json: askForNotes }); + + let n = 0; + async function startNote(who: typeof me, opts: { tainted?: boolean } = {}) { + const id = `learn${++n}`; + script([ + { toolCalls: [{ name: "memory_save", input: { note: `fact ${n}` }, id }] }, + { text: "Noted." }, + ]); + const { json } = await who("/api/chats", { method: "POST", json: { content: "remember" } }); + const runId = json!.runId as string; + if (opts.tainted) + await services.database.db + .update(schema.runs) + .set({ tainted: true }) + .where(eq(schema.runs.id, runId)); + await worker.processNow(runId); + return { runId, id }; + } + async function approveNote(who: typeof me) { + const { runId, id } = await startNote(who); + const res = await who(`/api/runs/${runId}/tool-calls/${id}/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(res.status).toBe(200); + await worker.processNow(runId); + } + + for (let i = 0; i < 4; i++) await approveNote(me); + expect((await me("/api/policy/suggestions")).json!.suggestions).toEqual([]); + await approveNote(me); + const [s] = (await me("/api/policy/suggestions")).json!.suggestions; + expect(s).toMatchObject({ tool: "memory_save", effect: "write", count: 5, when: [] }); + expect(s.sentence).toContain("You approved 5"); + expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]); + + // Someone else can neither accept nor dismiss it. + const accept = `/api/policy/suggestions/${s.id}/accept`; + const dismiss = `/api/policy/suggestions/${s.id}/dismiss`; + expect((await other(accept, { method: "POST" })).status).toBe(404); + expect((await other(dismiss, { method: "POST" })).status).toBe(404); + + const accepted = await me(accept, { method: "POST" }); + expect(accepted.status).toBe(200); + expect(accepted.json!.rules).toEqual([ + expect.objectContaining({ + tool: "memory_save", + decision: "allow", + note: "Learned: you approved 5 of these", + }), + expect.objectContaining({ tool: "memory_save", decision: "ask" }), + ]); + expect((await me("/api/policy")).json!.rules).toHaveLength(2); + expect((await me("/api/policy/suggestions")).json!.suggestions).toEqual([]); + + // Untainted: allowed without asking. Tainted: still asks. + const clean = await startNote(me); + expect((await me(`/api/runs/${clean.runId}`)).json!.run.status).toBe("completed"); + const tainted = await startNote(me, { tainted: true }); + expect((await me(`/api/runs/${tainted.runId}`)).json!.run.status).toBe("waiting"); + expect((await me("/api/approvals")).json!.approvals).toEqual([ + expect.objectContaining({ runId: tainted.runId, name: "memory_save" }), + ]); + + // Dismissing hides it, also after more approvals. + for (let i = 0; i < 5; i++) await approveNote(other); + const [o] = (await other("/api/policy/suggestions")).json!.suggestions; + expect(o.id).toBe(s.id); + expect((await other(dismiss, { method: "POST" })).status).toBe(204); + expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]); + await approveNote(other); + expect((await other("/api/policy/suggestions")).json!.suggestions).toEqual([]); + expect((await other("/api/policy")).json!.rules).toHaveLength(1); +}); diff --git a/apps/server/src/undo.test.ts b/apps/server/src/undo.test.ts new file mode 100644 index 0000000..f86288b --- /dev/null +++ b/apps/server/src/undo.test.ts @@ -0,0 +1,308 @@ +import { afterAll, beforeAll, expect, test } from "bun:test"; +import { UNDO_DENIAL } from "@synapse/core"; +import { type ScriptedStep, scriptedModel } from "@synapse/core/testing"; +import { readEvents, schema } from "@synapse/db"; +import { fakeGoogle } from "@synapse/tools/testing"; +import { and, eq } from "drizzle-orm"; +import { createApp } from "./app"; +import { loadConfig } from "./config"; +import { createServices, type Services } from "./services"; +import { Worker } from "./worker"; + +const ORIGIN = "http://localhost:3000"; +const google = fakeGoogle({ email: "ada@example.com" }); +let services: Services; +let app: ReturnType; +let worker: Worker; +let model = scriptedModel([]); +const script = (steps: ScriptedStep[]) => { + model = scriptedModel(steps); +}; + +beforeAll(async () => { + services = await createServices( + loadConfig({ + NODE_ENV: "test", + DATABASE_URL: "pglite://memory", + SYNAPSE_SECRET: "t".repeat(40), + PUBLIC_URL: ORIGIN, + GOOGLE_CLIENT_ID: "cid", + GOOGLE_CLIENT_SECRET: "secret", + }), + ); + services.config.google!.fetch = google.fetch; + app = createApp(services); + worker = new Worker(services, () => [model]); +}); +afterAll(() => services.close()); + +type Call = ( + path: string, + init?: { method?: string; json?: unknown }, +) => Promise<{ + status: number; + // biome-ignore lint/suspicious/noExplicitAny: test responses are loosely typed JSON + json: any; +}>; + +async function signUp(email: string): Promise { + const res = await app.request("/api/auth/sign-up/email", { + method: "POST", + headers: { "content-type": "application/json", origin: ORIGIN }, + body: JSON.stringify({ email, password: "correct horse battery", name: email.split("@")[0] }), + }); + expect(res.status).toBe(200); + const cookie = res.headers + .getSetCookie() + .map((c) => c.split(";")[0]) + .join("; "); + return async (path, init = {}) => { + const r = await app.request(path, { + method: init.method ?? "GET", + headers: { + cookie, + origin: ORIGIN, + ...(init.json !== undefined ? { "content-type": "application/json" } : {}), + }, + ...(init.json !== undefined ? { body: JSON.stringify(init.json) } : {}), + }); + const text = await r.text(); + return { status: r.status, json: text ? JSON.parse(text) : null }; + }; +} + +async function connectedUser(email: string, undoSeconds?: number): Promise { + const me = await signUp(email); + const start = await me("/api/integrations/google/connect", { method: "POST", json: {} }); + const state = new URL(start.json.url).searchParams.get("state")!; + await me(`/api/integrations/google/callback?code=abc&state=${encodeURIComponent(state)}`); + if (undoSeconds !== undefined) { + const res = await me("/api/settings", { method: "PUT", json: { undoSeconds } }); + expect(res.json.undoSeconds).toBe(undoSeconds); + } + return me; +} + +const sentTo = (to: string) => + google.state.messages.filter((m) => m.labelIds.includes("SENT") && JSON.stringify(m).includes(to)) + .length; + +const sendStep = (to: string, id: string): ScriptedStep => ({ + toolCalls: [{ name: "gmail_send", id, input: { to: [to], subject: "Hi", body: "Hello" } }], +}); + +async function runOf(runId: string) { + const [run] = await services.database.db + .select() + .from(schema.runs) + .where(eq(schema.runs.id, runId)); + return run!; +} + +async function callOf(runId: string, id: string) { + const [call] = await services.database.db + .select() + .from(schema.toolCalls) + .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, id))); + return call!; +} + +/** Fast-forwards the undo window: the call is due and the run is claimable. */ +async function endWindow(runId: string, id: string) { + const past = new Date(Date.now() - 1000); + const { db } = services.database; + await db + .update(schema.toolCalls) + .set({ executeAfter: past }) + .where(and(eq(schema.toolCalls.runId, runId), eq(schema.toolCalls.id, id))); + await db.update(schema.runs).set({ leaseExpiresAt: past }).where(eq(schema.runs.id, runId)); +} + +/** Starts a task whose first step proposes one call, and drives it to the approval. */ +async function proposed(me: Call, first: ScriptedStep, then = "Done.") { + script([first, { text: then }]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "Go" } }); + await worker.processNow(json.runId); + expect((await runOf(json.runId)).status).toBe("waiting"); + return json.runId as string; +} + +test("settings expose the undo window, default 10s, capped at 60", async () => { + const me = await signUp("settings@example.com"); + expect((await me("/api/settings")).json.undoSeconds).toBe(10); + expect((await me("/api/settings", { method: "PUT", json: { undoSeconds: 61 } })).status).toBe( + 422, + ); + expect( + (await me("/api/settings", { method: "PUT", json: { undoSeconds: 0 } })).json.undoSeconds, + ).toBe(0); +}); + +test("an approved send waits out its window, then runs exactly once", async () => { + const me = await connectedUser("wait@example.com"); + const runId = await proposed(me, sendStep("wait@x.test", "s1")); + + const decided = await me(`/api/runs/${runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(decided.status).toBe(200); + const executeAfter = Date.parse(decided.json.executeAfter); + expect(executeAfter - Date.now()).toBeGreaterThan(8_000); + expect(executeAfter - Date.now()).toBeLessThanOrEqual(10_500); + + // Re-queued for when the window ends, so no worker takes it early. + const parked = await runOf(runId); + expect(parked.status).toBe("queued"); + expect(parked.leaseExpiresAt!.getTime()).toBe(executeAfter); + expect(await worker.processNow(runId)).toBe(false); + expect(sentTo("wait@x.test")).toBe(0); + + // The run detail and the event stream carry the deadline for a countdown. + const detail = await me(`/api/runs/${runId}`); + expect(detail.json.toolCalls[0]).toMatchObject({ status: "approved" }); + expect(Date.parse(detail.json.toolCalls[0].executeAfter)).toBe(executeAfter); + const chat = await me(`/api/chats/${parked.chatId}`); + const part = chat.json.messages + .flatMap((m: { parts: unknown[] }) => m.parts) + .find((p: { toolCallId?: string }) => p.toolCallId === "s1"); + expect(Date.parse(part.executeAfter)).toBe(executeAfter); + const log = await readEvents(services.database, runId, 0); + expect(log.slice(-2)).toMatchObject([ + { type: "tool.status", toolCallId: "s1", status: "approved", executeAfter: expect.any(String) }, + { type: "run.status", status: "queued" }, + ]); + + await endWindow(runId, "s1"); + expect(await worker.processNow(runId)).toBe(true); + expect(sentTo("wait@x.test")).toBe(1); + expect(await callOf(runId, "s1")).toMatchObject({ status: "succeeded" }); + expect((await runOf(runId)).status).toBe("completed"); + expect(await worker.processNow(runId)).toBe(false); + expect(sentTo("wait@x.test")).toBe(1); + + // Too late now. + const late = await me(`/api/runs/${runId}/tool-calls/s1/undo`, { method: "POST", json: {} }); + expect(late.status).toBe(409); + expect(late.json.error.message).toContain("Too late to undo"); +}); + +test("a worker that reaches a call early parks the run until the window ends", async () => { + const me = await connectedUser("early@example.com", 1); + const runId = await proposed(me, sendStep("early@x.test", "s1")); + await me(`/api/runs/${runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }); + // Something re-queued the run before the window ended (e.g. a stop-after-step request). + await services.database.db + .update(schema.runs) + .set({ leaseExpiresAt: null }) + .where(eq(schema.runs.id, runId)); + expect(await worker.processNow(runId)).toBe(true); + expect(sentTo("early@x.test")).toBe(0); + const parked = await runOf(runId); + expect(parked).toMatchObject({ status: "queued", leaseOwner: null, attempts: 0 }); + const call = await callOf(runId, "s1"); + expect(parked.leaseExpiresAt!.getTime()).toBeGreaterThan(Date.now()); + expect(parked.leaseExpiresAt!.getTime()).toBeLessThanOrEqual(call.executeAfter!.getTime() + 50); + + await Bun.sleep(Math.max(0, parked.leaseExpiresAt!.getTime() - Date.now()) + 20); + expect(await worker.processNow(runId)).toBe(true); + expect(sentTo("early@x.test")).toBe(1); + expect((await runOf(runId)).status).toBe("completed"); +}); + +test("undo inside the window denies the send and the agent hears why", async () => { + const me = await connectedUser("undo@example.com"); + const other = await connectedUser("other@example.com"); + const runId = await proposed(me, sendStep("undo@x.test", "s1"), "Okay, I won't send it."); + await me(`/api/runs/${runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }); + + const path = `/api/runs/${runId}/tool-calls/s1/undo`; + expect((await other(path, { method: "POST", json: {} })).status).toBe(404); + expect((await me(path, { method: "POST", json: {} })).status).toBe(204); + expect((await me(path, { method: "POST", json: {} })).status).toBe(409); + + // Re-queued right away so the agent can respond. + expect((await runOf(runId)).leaseExpiresAt).toBeNull(); + expect(await worker.processNow(runId)).toBe(true); + expect(sentTo("undo@x.test")).toBe(0); + expect(await callOf(runId, "s1")).toMatchObject({ + status: "denied", + output: { type: "denied", reason: UNDO_DENIAL }, + }); + expect(JSON.stringify(model.calls[1]!.prompt)).toContain(UNDO_DENIAL); + expect((await runOf(runId)).status).toBe("completed"); +}); + +test("undo window 0 runs approved sends at once", async () => { + const me = await connectedUser("off@example.com", 0); + const runId = await proposed(me, sendStep("off@x.test", "s1")); + const decided = await me(`/api/runs/${runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(decided.json.executeAfter).toBeNull(); + expect(await worker.processNow(runId)).toBe(true); + expect(sentTo("off@x.test")).toBe(1); + expect( + (await me(`/api/runs/${runId}/tool-calls/s1/undo`, { method: "POST", json: {} })).status, + ).toBe(409); +}); + +test("auto-allowed sends and approved writes are not delayed", async () => { + const me = await connectedUser("allow@example.com"); + await me("/api/policy", { + method: "PUT", + json: { + defaults: { read: "allow", write: "ask", send: "ask", destructive: "ask" }, + rules: [ + { tool: "gmail_send", decision: "allow" }, + { tool: "gmail_create_draft", decision: "ask" }, + ], + }, + }); + script([sendStep("allow@x.test", "s1"), { text: "Sent." }]); + const { json } = await me("/api/chats", { method: "POST", json: { content: "Go" } }); + await worker.processNow(json.runId); + expect(sentTo("allow@x.test")).toBe(1); + expect(await callOf(json.runId, "s1")).toMatchObject({ status: "succeeded", executeAfter: null }); + + const runId = await proposed(me, { + toolCalls: [ + { + name: "gmail_create_draft", + id: "d1", + input: { to: ["draft@x.test"], subject: "Hi", body: "Hello" }, + }, + ], + }); + const decided = await me(`/api/runs/${runId}/tool-calls/d1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect(decided.json.executeAfter).toBeNull(); + expect(await worker.processNow(runId)).toBe(true); + expect(await callOf(runId, "d1")).toMatchObject({ status: "succeeded", executeAfter: null }); + expect(google.state.drafts.length).toBeGreaterThan(0); +}); + +test("stopping a task inside the window cancels the send at once", async () => { + const me = await connectedUser("stop@example.com"); + const runId = await proposed(me, sendStep("stop@x.test", "s1")); + await me(`/api/runs/${runId}/tool-calls/s1/decision`, { + method: "POST", + json: { approved: true }, + }); + expect( + (await me(`/api/runs/${runId}/cancel`, { method: "POST", json: { mode: "now" } })).status, + ).toBe(204); + expect(await worker.processNow(runId)).toBe(true); + expect((await runOf(runId)).status).toBe("cancelled"); + expect(await callOf(runId, "s1")).toMatchObject({ status: "denied" }); + expect(sentTo("stop@x.test")).toBe(0); +}); diff --git a/apps/server/src/worker.ts b/apps/server/src/worker.ts index c89de9c..0f2972e 100644 --- a/apps/server/src/worker.ts +++ b/apps/server/src/worker.ts @@ -1,6 +1,7 @@ import { createModel, type ModelSpec, + nextUndoWaitMs, type ProviderKeys, parseModelRef, runAgent, @@ -82,6 +83,14 @@ export class Worker { this.wakers.shift()?.(); } + /** Nudges idle workers when a parked run becomes claimable, instead of waiting for a poll. */ + private wakeLater(runId: string, ms: number) { + const timer = setTimeout(() => { + if (!this.stopped) void this.s.wake(runId).catch(() => {}); + }, ms + 25); + timer.unref?.(); + } + private idle(): Promise { return new Promise((resolve) => { const done = () => { @@ -246,8 +255,13 @@ export class Worker { }, }); await events.flush(runId); - if (status !== "running") await resetAttempts(db, runId); - await releaseRun(db, runId, this.id); + await resetAttempts(db, runId); + // "running" means parked on an undo window: come back exactly when it ends. Read + // fresh so an undo that landed meanwhile resumes the run now. + const wait = + status === "running" ? nextUndoWaitMs(await new PgRunStore(db).listToolCalls(runId)) : 0; + await releaseRun(db, runId, this.id, wait); + if (wait > 0) this.wakeLater(runId, wait); } catch (error) { await events.flush(runId).catch(() => {}); if (controller.signal.aborted) { diff --git a/apps/web/app/(app)/inbox/page.tsx b/apps/web/app/(app)/inbox/page.tsx index cb3167b..eda2f8a 100644 --- a/apps/web/app/(app)/inbox/page.tsx +++ b/apps/web/app/(app)/inbox/page.tsx @@ -10,6 +10,9 @@ import { approvalTitle, MiniStamp, } from "@/components/approval/approval-card"; +import { ApprovalBatch, PLAN_TOOL } from "@/components/approval/checklist"; +import { LearnPrompt, SuggestionStrip } from "@/components/approval/learned-rules"; +import { UndoCountdown, type UndoTarget, useTimeLeft } from "@/components/approval/undo-window"; import { Markdown } from "@/components/markdown"; import { EffectPill, Kbd, Monogram, Skeleton, StatusDot } from "@/components/ui"; import { type Approval, api } from "@/lib/api"; @@ -22,6 +25,52 @@ interface Decided { approved: boolean; reason?: string; edited: boolean; + /** Set when an approved send or delete waits out its undo window. */ + executeAfter?: string | null; + /** Taken back inside the undo window. */ + undone?: boolean; +} + +function undoTarget(a: Approval, d: Decided): UndoTarget | null { + return d.executeAfter + ? { runId: a.runId, toolCallId: a.toolCallId, executeAfter: d.executeAfter } + : null; +} + +/** A signed row whose send is still inside its undo window. */ +function rowUndo(a: Approval, d: Decided | undefined): UndoTarget | null { + return d?.approved && !d.undone ? undoTarget(a, d) : null; +} + +/** The row's age, or nothing while its undo countdown sits in that corner. */ +function RowTime({ createdAt, undo }: { createdAt: string; undo: UndoTarget | null }) { + const left = useTimeLeft(undo?.executeAfter); + if (undo && left > 0) return null; + return ( + + {formatRelative(createdAt)} + + ); +} + +/** "Sending in 9s · Undo" on the row itself, so it stays reachable after the pane moves on. */ +function RowUndo({ + target, + effect, + onUndone, +}: { + target: UndoTarget; + effect: Approval["effect"]; + onUndone: () => void; +}) { + return ( + + ); } function isTyping(e: KeyboardEvent) { @@ -68,6 +117,12 @@ export default function InboxPage() { }, [ordered, pending, selected]); const current = ordered.find((a) => a.toolCallId === selected) ?? null; + // Open asks from the same run sign off together as one checklist (plans keep their card). + const batch = useMemo(() => { + if (!current || decided[current.toolCallId] || current.name === PLAN_TOOL) return []; + const same = pending.filter((a) => a.runId === current.runId && a.name !== PLAN_TOOL); + return same.length >= 2 ? same.sort((a, b) => a.createdAt.localeCompare(b.createdAt)) : []; + }, [current, decided, pending]); const tainted = (chatId: string) => tasks?.find((t) => t.id === chatId)?.tainted ?? false; const move = useCallback( @@ -103,6 +158,11 @@ export default function InboxPage() { return () => document.removeEventListener("keydown", onKey); }, [move, current, decided]); + function markUndone(id: string) { + setDecided((m) => (m[id] ? { ...m, [id]: { ...m[id], undone: true } } : m)); + void reload(); + } + function onDecided(a: Approval, d: Decided) { setKept((k) => ({ ...k, [a.toolCallId]: a })); setDecided((m) => ({ ...m, [a.toolCallId]: d })); @@ -111,6 +171,23 @@ export default function InboxPage() { void reload(); } + function onBatchDecided(list: Approval[], outcome: Record) { + setKept((k) => ({ ...k, ...Object.fromEntries(list.map((a) => [a.toolCallId, a])) })); + setDecided((m) => ({ + ...m, + ...Object.fromEntries( + list.map((a) => [ + a.toolCallId, + { approved: outcome[a.toolCallId] ?? false, edited: false }, + ]), + ), + })); + const done = new Set(list.map((a) => a.toolCallId)); + const next = pending.find((x) => !done.has(x.toolCallId)); + if (next && desktop) setSelected(next.toolCallId); + void reload(); + } + const loading = approvals === null; const empty = !loading && ordered.length === 0; const signed = ordered.length - pending.length; @@ -142,6 +219,7 @@ export default function InboxPage() {

+ {loading ? (
{[0, 1, 2].map((i) => ( @@ -172,7 +250,7 @@ export default function InboxPage() { const on = a.toolCallId === selected; const { source } = splitToolName(a.name); return ( -
  • +
  • + {rowUndo(a, d) ? ( + markUndone(a.toolCallId)} + /> + ) : null}
  • ); })} @@ -283,8 +366,14 @@ export default function InboxPage() { approved={decided[current.toolCallId]!.approved} reason={decided[current.toolCallId]!.reason} edited={decided[current.toolCallId]!.edited} + undo={undoTarget(current, decided[current.toolCallId]!)} + undone={decided[current.toolCallId]!.undone} + onUndone={() => markUndone(current.toolCallId)} phase="continuing" /> + {decided[current.toolCallId]!.approved && !decided[current.toolCallId]!.edited ? ( + + ) : null} {pending.length === 0 ? (

    @@ -296,6 +385,16 @@ export default function InboxPage() {

    ) : null}
    + ) : batch.length > 0 ? ( + a.toolCallId).join()} + handle={card} + runId={current.runId} + items={batch} + tainted={tainted(current.chatId)} + onDecided={(outcome) => onBatchDecided(batch, outcome)} + onConflict={() => void reload()} + /> ) : ( taskStatus(t.status) === "running").length; const needs = approvals?.length ?? 0; + // Rows approved here stay while their undo window runs, even after a reload drops them. + const [held, setHeld] = useState>({}); + const rows = useMemo(() => { + if (!approvals) return approvals; + const live = new Set(approvals.map((a) => a.toolCallId)); + const kept = Object.values(held).filter((a) => !live.has(a.toolCallId)); + return [...kept, ...approvals].sort((a, b) => b.createdAt.localeCompare(a.createdAt)); + }, [approvals, held]); + const listed = rows?.length ?? 0; const name = firstName(user?.name); const suggestions = useMemo(() => suggestionsFor(conns.data?.connections), [conns.data]); @@ -226,7 +242,7 @@ export default function HomePage() { /> ) : null} - {needs > 0 || !showGuide ? ( + {listed > 0 || !showGuide ? (
    {approvals === null ? ( - ) : needs === 0 ? ( + ) : listed === 0 ? (

    @@ -260,15 +276,25 @@ export default function HomePage() {

    ) : (
      - {approvals!.slice(0, 3).map((a) => ( + {rows!.slice(0, 3).map((a) => (
    • - void reload()} /> + setHeld((h) => ({ ...h, [a.toolCallId]: a }))} + onDone={() => { + setHeld((h) => { + const { [a.toolCallId]: _gone, ...rest } = h; + return rest; + }); + void reload(); + }} + />
    • ))} - {needs > 3 ? ( + {listed > 3 ? (
    • - and {plural(needs - 3, "more")} in the inbox + and {plural(listed - 3, "more")} in the inbox
    • ) : null} diff --git a/apps/web/app/(app)/settings/page.tsx b/apps/web/app/(app)/settings/page.tsx index 8c643d2..d3327a1 100644 --- a/apps/web/app/(app)/settings/page.tsx +++ b/apps/web/app/(app)/settings/page.tsx @@ -18,7 +18,7 @@ import { import { useRouter } from "next/navigation"; import { type ReactNode, useEffect, useMemo, useState } from "react"; import { useToast } from "@/components/toast"; -import { ErrorNote, Field, Page, PageHeader, Pill, Skeleton } from "@/components/ui"; +import { ErrorNote, Field, Page, PageHeader, Pill, Segmented, Skeleton } from "@/components/ui"; import { api, errorMessage, @@ -290,10 +290,37 @@ function General({ settings, save }: { settings: Settings; save: SaveFn }) { setText(settings.instructions ?? ""); }} /> +
    ); } +const UNDO_OPTIONS = ["0", "5", "10", "30"] as const; + +/** Saved on click, like the theme: there's nothing to draft. */ +function UndoWindow({ settings, save }: { settings: Settings; save: SaveFn }) { + const [value, setValue] = useState(String(settings.undoSeconds)); + useEffect(() => setValue(String(settings.undoSeconds)), [settings.undoSeconds]); + return ( + + + label="Undo window" + value={value} + options={UNDO_OPTIONS.map((v) => ({ value: v, label: v === "0" ? "Off" : `${v}s` }))} + onChange={async (v) => { + const prev = value; + setValue(v); + if (!(await save({ undoSeconds: Number(v) }))) setValue(prev); + }} + /> + + ); +} + function Models({ settings, save, known }: { settings: Settings; save: SaveFn; known: string[] }) { const [chain, setChain] = useState(settings.models.chain); const [picking, setPicking] = useState(false); diff --git a/apps/web/app/(app)/settings/policy-editor.tsx b/apps/web/app/(app)/settings/policy-editor.tsx index 865b3b8..9a93472 100644 --- a/apps/web/app/(app)/settings/policy-editor.tsx +++ b/apps/web/app/(app)/settings/policy-editor.tsx @@ -4,7 +4,7 @@ import type { ArgMatcher, Decision, Effect, PolicyDefaults, PolicyRule } from "@ import { GripVertical, Plus, ShieldAlert, X } from "lucide-react"; import { useCallback, useEffect, useRef, useState } from "react"; import { useToast } from "@/components/toast"; -import { EffectPill, ErrorNote, Segmented, Skeleton } from "@/components/ui"; +import { EffectPill, ErrorNote, Pill, Segmented, Skeleton } from "@/components/ui"; import { api, errorMessage, type Policy } from "@/lib/api"; import { cx, humanToolName } from "@/lib/format"; import { useApi } from "@/lib/use-api"; @@ -12,6 +12,7 @@ import { useApi } from "@/lib/use-api"; const EFFECTS: Effect[] = ["read", "write", "send", "destructive"]; const OPS: { op: ArgMatcher["op"]; label: string; hint: string }[] = [ { op: "allEndWith", label: "ends with", hint: "@acme.com, @acme.io" }, + { op: "emailsEndWith", label: "every email address ends with", hint: "@acme.com" }, { op: "equals", label: "is", hint: "main" }, { op: "in", label: "is one of", hint: "a, b, c" }, { op: "matches", label: "matches", hint: "^release/" }, @@ -57,7 +58,7 @@ function toDraft(rule: PolicyRule): DraftRule { raw: m.op === "matches" ? m.value - : m.op === "allEndWith" + : m.op === "allEndWith" || m.op === "emailsEndWith" ? m.value.join(", ") : m.op === "in" ? m.value.map((v) => (typeof v === "string" ? v : JSON.stringify(v))).join(", ") @@ -75,6 +76,11 @@ const splitList = (raw: string) => .filter(Boolean); function toMatcher(m: DraftMatcher, where: string): ArgMatcher { + if (m.op === "emailsEndWith") { + const value = splitList(m.raw); + if (value.length === 0) throw new Error(`${where}: give at least one ending`); + return { path: "*", op: "emailsEndWith", value }; + } const path = m.path.trim(); if (!path) throw new Error(`${where}: say which field the condition checks`); switch (m.op) { @@ -389,13 +395,15 @@ export function PolicyEditor({ prefillTool }: { prefillTool?: string | null }) { className="inline-flex flex-wrap items-center gap-x-2 gap-y-2" > and - updateMatcher(i, k, { path: v })} - /> + {m.op === "emailsEndWith" ? null : ( + updateMatcher(i, k, { path: v })} + /> + )} onChange(e.target.checked)} + className="peer size-[18px] cursor-pointer appearance-none rounded-[4px] border-[1.5px] border-line-strong bg-surface transition-colors outline-none checked:border-fg checked:bg-fg hover:border-fg focus-visible:ring-2 focus-visible:ring-accent/40 disabled:cursor-default disabled:opacity-50" + /> +