Skip to content
refs
History
138 lines · 8.7 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("the refs CLI sign-in works as the human for git only when its grant has the git scope", async () => {
52 const sqlite = seeded();
53 const ctx = { waitUntil() {} } as unknown as ExecutionContext;
54 const request = new Request("https://x/repo.git/info/refs", { headers: { authorization: "Bearer u1:g1:secret" } });
55 const oauth = (scope: string[]) => ({ unwrapToken: async () => ({ grant: { scope, props: { userId: "u1" } } }) }) as never;
56 const withGit = await resolveActor(d1(sqlite), ctx, request, oauth(["agents", "git"]));
57 assert.deepEqual([withGit.actor.kind, withGit.actor.kind === "human" && withGit.actor.via], ["human", "cli"]);
58 assert.equal((await resolveActor(d1(sqlite), ctx, request, oauth(["agents"]))).badCredentials, true);
59 assert.equal((await resolveActor(d1(sqlite), ctx, request)).badCredentials, true);
60});
61
62test("a mention asks the hub, not the machines projection, whether the machine is connected", async () => {
63 const sqlite = seeded();
64 sqlite.exec("INSERT INTO machines (user_id, name, runtimes, version, connected, last_seen_at) VALUES ('u1', 'laptop', '[]', '1', 1, 0)");
65 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
66 const dispatched: string[] = [];
67 const hub = { connected: async () => [] as string[], dispatch: async (machine: string) => (dispatched.push(machine), true) };
68 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env;
69 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
70 const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" });
71
72 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null);
73
74 assert.deepEqual(dispatched, []);
75 const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string };
76 assert.equal(JSON.parse(data).run, false);
77
78 hub.connected = async () => ["laptop"];
79 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} again`, null);
80 assert.deepEqual(dispatched, ["laptop"]);
81});
82
83test("a hub that fails after the mention is saved does not fail the comment that made it", async () => {
84 const sqlite = seeded();
85 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
86 const hub = { connected: async () => ["laptop"], dispatch: async () => Promise.reject(new Error("hub evicted")) };
87 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => hub } } as unknown as Env;
88 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
89 const pull = onPull({ repo_id: "repo", number: 7, title: "t", head_ref: "fix-login" });
90 const logged = console.error;
91 console.error = () => {};
92 try {
93 await deliverMentions(env, { waitUntil() {} }, actor, pull, `@agent/${SESSION} look`, null);
94 } finally {
95 console.error = logged;
96 }
97 assert.equal((sqlite.prepare("SELECT count(*) AS n FROM events WHERE kind = 'agent.mentioned'").get() as { n: number }).n, 1);
98});
99
100test("assigning on a pull request hands the agent its branch, never the default branch", async () => {
101 for (const [head, assigned] of [["queue-pushes", true], ["main", false]] as const) {
102 const sqlite = seeded();
103 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
104 const env = { DB: d1(sqlite), USER_HUB: { idFromName: (name: string) => name, get: () => ({ connected: async () => [] }) } } as unknown as Env;
105 const actor: Actor = { kind: "human", person: { id: "u1", name: "Aman" }, via: "session" } as never;
106
107 await deliverMentions(env, { waitUntil() {} }, actor, onPull({ repo_id: "repo", number: 3, title: "Queue pushes", head_ref: head }), `@agent/${SESSION} why?`, 12, { assign: true });
108
109 const { data } = sqlite.prepare("SELECT data FROM events WHERE kind = 'agent.mentioned'").get() as { data: string };
110 assert.deepEqual(JSON.parse(data), { session: SESSION, title: "Queue pushes", comment: 12, body: `@agent/${SESSION} why?`, assigned, run: false, pull: 3 });
111 assert.deepEqual({ ...sqlite.prepare("SELECT branch FROM agent_sessions WHERE id = ?").get(SESSION) }, { branch: assigned ? head : null });
112 }
113});
114
115test("the SessionEnd hook takes the conversation's session offline without ending it", async () => {
116 const sqlite = seeded();
117 sqlite.exec("INSERT INTO repos (id, namespace_id, name, visibility, artifacts_name, creator_id, created_at) VALUES ('repo', 'ns', 'refs', 'public', 'refs', 'u1', 0)");
118 sqlite.prepare("UPDATE agent_sessions SET client_session = 'conv' WHERE id = ?").run(SESSION);
119 const sessions = agentSessions({ DB: d1(sqlite) } as Env, { waitUntil() {} }, "u1", "hook", "claude-code", "https://x", "conv");
120
121 assert.equal(await sessions.events("SessionEnd"), "");
122
123 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 };
124 assert.deepEqual({ ...row }, { mcp_session: null, ended_at: null });
125});
126
127test("revoking one agent grant ends only the sessions that grant started, and sessions with no recorded grant", async () => {
128 const sqlite = seeded();
129 const at = Math.floor(Date.now() / 1000);
130 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', ?, ?, ?)");
131 insert.run("revoked", "h1", at, at + 3600, "g1");
132 insert.run("kept", "h2", at, at + 3600, "g2");
133 await endGrantSessions(d1(sqlite), "u1", "g1", at);
134 const ended = (id: string) => (sqlite.prepare("SELECT ended_at FROM agent_sessions WHERE id = ?").get(id) as { ended_at: number | null }).ended_at !== null;
135 assert.equal(ended("revoked"), true);
136 assert.equal(ended("kept"), false);
137 assert.equal(ended(SESSION), true);
138});