Skip to content
refs
History
127 lines · 7.9 KBRaw
1import assert from "node:assert/strict";
2import type { DatabaseSync } from "node:sqlite";
3import { test } from "node:test";
4import { sha256 } from "../auth.ts";
5import type { Actor } from "../contract/actor.ts";
6import { resolveActor } from "../identity.ts";
7import { deliverMentions, onPull } from "../mentions.ts";
8import { endGrantSessions } from "../handles/account.ts";
9import { agentSessions } from "../sessions.ts";
10import { d1, migrated } from "./d1.ts";
11
12const SESSION = "11111111-2222-3333-4444-555555555555";
13
14function counting(sqlite: DatabaseSync, table: string): () => number {
15 sqlite.exec(`CREATE TABLE writes (n INTEGER); CREATE TRIGGER count_writes AFTER UPDATE ON ${table} BEGIN INSERT INTO writes VALUES (1); END;`);
16 return () => (sqlite.prepare("SELECT count(*) AS n FROM writes").get() as { n: number }).n;
17}
18
19function seeded(): DatabaseSync {
20 const sqlite = migrated();
21 const at = Math.floor(Date.now() / 1000);
22 sqlite.exec(`INSERT INTO namespaces (id, slug, name, kind, created_at) VALUES ('ns', 'refs', 'refs', 'org', 0); INSERT INTO users (id, email, name, password_hash, created_at) VALUES ('u1', 'a@x', 'Aman', 'x', 0); INSERT INTO memberships (namespace_id, user_id, role, created_at) VALUES ('ns', 'u1', 'owner', 0)`);
23 sqlite
24 .prepare("INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, last_seen_at, mcp_session, machine) VALUES (?, 'h', 'u1', 'repo', 'claude-code', ?, ?, NULL, 'mcp', 'laptop')")
25 .run(SESSION, at, at + 3600);
26 return sqlite;
27}
28
29test("consecutive MCP calls within a minute write last_seen_at once", async () => {
30 const sqlite = seeded();
31 const writes = counting(sqlite, "agent_sessions");
32 const sessions = agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "mcp", "claude-code", "https://x");
33 for (let i = 0; i < 5; i++) await sessions.touch();
34 assert.equal(writes(), 1);
35});
36
37test("a PAT used for several git requests within a minute writes last_used_at once", async () => {
38 const sqlite = seeded();
39 sqlite.prepare("INSERT INTO access_tokens (id, user_id, name, token_hash, created_at) VALUES ('t1', 'u1', 'cli', ?, 0)").run(await sha256("refs_pat"));
40 const writes = counting(sqlite, "access_tokens");
41 for (let i = 0; i < 5; i++) {
42 const pending: Promise<unknown>[] = [];
43 const ctx = { waitUntil: (promise: Promise<unknown>) => pending.push(promise) } as unknown as ExecutionContext;
44 const { actor } = await resolveActor(d1(sqlite), ctx, new Request("https://x/repo.git/info/refs", { headers: { authorization: "Bearer refs_pat" } }));
45 assert.equal(actor.kind, "human");
46 await Promise.all(pending);
47 }
48 assert.equal(writes(), 1);
49});
50
51test("a mention asks the hub, not the machines projection, whether the machine is connected", async () => {
52 const sqlite = seeded();
53 sqlite.exec("INSERT INTO machines (user_id, name, runtimes, version, connected, last_seen_at) VALUES ('u1', 'laptop', '[]', '1', 1, 0)");
54 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
55 const dispatched: string[] = [];
56 const hub = { connected: async () => [] as string[], dispatch: async (machine: string) => (dispatched.push(machine), true) };
57 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env;
58 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
59 const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" });
60
61 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null);
62
63 assert.deepEqual(dispatched, []);
64 const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string };
65 assert.equal(JSON.parse(data).run, false);
66
67 hub.connected = async () => ["laptop"];
68 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} again`, null);
69 assert.deepEqual(dispatched, ["laptop"]);
70});
71
72test("a hub that fails after the mention is saved does not fail the comment that made it", async () => {
73 const sqlite = seeded();
74 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
75 const hub = { connected: async () => ["laptop"], dispatch: async () => Promise.reject(new Error("hub evicted")) };
76 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env;
77 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
78 const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" });
79 const logged = console.error;
80 console.error = () => {};
81 try {
82 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null);
83 } finally {
84 console.error = logged;
85 }
86 assert.equal((sqlite.prepare("SELECT count(*) AS n FROM events WHERE kind = 'agent.mentioned'").get() as { n: number }).n, 1);
87});
88
89test("assigning on a pull request hands the agent its branch, never the default branch", async () => {
90 for (const [head, assigned] of [["queue-pushes", true], ["main", false]] as const) {
91 const sqlite = seeded();
92 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
93 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => ({ connected: async () => [] }) } } as unknown as Env;
94 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
95
96 await deliverMentions(env, { waitUntil() {} }, actor, onPull({ repo_id: "repo", number: 3, title: "Queue pushes", head_ref: head }), `@agent/${SESSION} why?`, 12, { assign: true });
97
98 const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string };
99 assert.deepEqual(JSON.parse(data), { session: SESSION, title: "Queue pushes", comment: 12, body: `@agent/${SESSION} why?`, assigned, run: false, pull: 3 });
100 assert.deepEqual({ ...sqlite.prepare("SELECT branch FROM agent_sessions WHERE id = ?").get(SESSION) }, { branch: assigned ? head : null });
101 }
102});
103
104test("the SessionEnd hook takes the conversation's session offline without ending it", async () => {
105 const sqlite = seeded();
106 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
107 sqlite.prepare("UPDATE agent_sessions SET client_session = 'conv' WHERE id = ?").run(SESSION);
108 const sessions = agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "hook", "claude-code", "https://x", "conv");
109
110 assert.equal(await sessions.events("SessionEnd"), "");
111
112 const row = sqlite.prepare("SELECT mcp_session, ended_at FROM agent_sessions WHERE id = ?").get(SESSION) as { mcp_session: string | null; ended_at: number | null };
113 assert.deepEqual({ ...row }, { mcp_session: null, ended_at: null });
114});
115
116test("revoking one agent grant ends only the sessions that grant started, and sessions with no recorded grant", async () => {
117 const sqlite = seeded();
118 const at = Math.floor(Date.now() / 1000);
119 const insert = sqlite.prepare("INSERT INTO agent_sessions (id, token_hash, user_id, repo_id, runtime, created_at, expires_at, grant_id) VALUES (?, ?, 'u1', 'repo', 'claude-code', ?, ?, ?)");
120 insert.run("revoked", "h1", at, at + 3600, "g1");
121 insert.run("kept", "h2", at, at + 3600, "g2");
122 await endGrantSessions(d1(sqlite), "u1", "g1", at);
123 const ended = (id: string) => (sqlite.prepare("SELECT ended_at FROM agent_sessions WHERE id = ?").get(id) as { ended_at: number | null }).ended_at !== null;
124 assert.equal(ended("revoked"), true);
125 assert.equal(ended("kept"), false);
126 assert.equal(ended(SESSION), true);
127});