383b9ae231
- The chat over a terminal pane now covers Claude, Codex, omp, Cursor and Antigravity: Cursor's agent transcript and agy's step log (brain/<id>/.system_generated/logs/transcript_full.jsonl) are read as conversations; Cursor sessions are claimed by their workspace - Replies appear as soon as they are written: the projects-tree watcher broadcasts `transcript_changed` (at most every 250 ms per session) and the chat re-reads the transcript while the terminal underneath draws - Stop shows from the pane's own busy line (Claude/Codex `esc to interrupt`, agy `… esc to cancel`), or fresh output for omp/Cursor — no hooks needed - Permission prompts read off the terminal become a card with the tool, its command and "Deny with a note"; Codex gets Permission mode / Model buttons that open its own numbered pickers, answered from the menu card - Artifacts: cards for pages/documents/diagrams/tables/React components, a Preview | Code panel with versions, copy, download, save to the Artifacts Hub, full screen; sandboxed iframes without allow-same-origin - Claude panes get CLAUDE_CODE_ENABLE_TODO_TOOLS=1 so the Progress panel has a plan; multi-question pane menus read their Next row and question tabs - The realtime chat bridge (structured stdio, /api/chat-bridge, /ws-chat) from the unreleased ad9d475 is not kept
247 lines
9.5 KiB
JavaScript
247 lines
9.5 KiB
JavaScript
/**
|
|
* @file Tests server/lib/cursor-usage.js — Cursor sessions from its agent
|
|
* transcripts: a session created as `tool = 'cursor'` with its name, cwd (the
|
|
* project slug walked back onto the filesystem) and no tokens, an unchanged
|
|
* file never re-read, a quiet one settled to completed, a session the user
|
|
* deleted staying deleted, and a non-cursor row with the same id never
|
|
* touched, a session claimed by the Cursor pane it started in, and the
|
|
* transcript mapped to the Claude transcript shape by the
|
|
* transcript routes. The Cursor dir and the DB are temp dirs; the transcripts
|
|
* are synthetic, in the shape Cursor writes.
|
|
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
|
|
*/
|
|
|
|
const os = require("node:os");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = fs.mkdtempSync(path.join(os.tmpdir(), "agenthub-cursor-usage-"));
|
|
process.env.DASHBOARD_DB_PATH = path.join(ROOT, "dashboard.db");
|
|
process.env.AGENTHUB_CURSOR_DIR = path.join(ROOT, "cursor");
|
|
process.env.CLAUDE_HOME = path.join(ROOT, "claude");
|
|
|
|
const { describe, it, beforeEach, after } = require("node:test");
|
|
const assert = require("node:assert/strict");
|
|
const { db } = require("../db");
|
|
const cursor = require("../lib/cursor-usage");
|
|
|
|
let server;
|
|
after(() => {
|
|
server?.close();
|
|
fs.rmSync(ROOT, { recursive: true, force: true });
|
|
});
|
|
|
|
const ID = "7481e37e-9157-4145-b985-2ea9a2117f52";
|
|
const PROJECT = path.join(fs.realpathSync(ROOT), "work", "my app");
|
|
fs.mkdirSync(PROJECT, { recursive: true });
|
|
const slugOf = (p) => p.replace(/^\/+/, "").replace(/[^A-Za-z0-9]/g, "-");
|
|
|
|
function transcript(
|
|
id,
|
|
{ slug = slugOf(PROJECT), prompt = "Review the campaign code\nplease" } = {}
|
|
) {
|
|
const dir = path.join(process.env.AGENTHUB_CURSOR_DIR, "projects", slug, "agent-transcripts", id);
|
|
fs.mkdirSync(dir, { recursive: true });
|
|
const file = path.join(dir, `${id}.jsonl`);
|
|
const lines = [
|
|
{
|
|
role: "user",
|
|
message: {
|
|
content: [
|
|
{
|
|
type: "text",
|
|
text: `<timestamp>Thursday, Jun 11, 2026, 4:53 PM (UTC+7)</timestamp>\n<user_query>\n${prompt}\n</user_query>`,
|
|
},
|
|
],
|
|
},
|
|
},
|
|
{ role: "assistant", message: { content: [{ type: "tool_use", name: "Read", input: {} }] } },
|
|
{ type: "turn_ended", status: "success" },
|
|
];
|
|
fs.writeFileSync(file, lines.map((l) => JSON.stringify(l)).join("\n") + "\n");
|
|
return file;
|
|
}
|
|
|
|
function age(file, ms) {
|
|
const t = new Date(Date.now() - ms);
|
|
fs.utimesSync(file, t, t);
|
|
}
|
|
|
|
const session = (id) => db.prepare("SELECT * FROM sessions WHERE id = ?").get(id);
|
|
|
|
beforeEach(() => {
|
|
fs.rmSync(process.env.AGENTHUB_CURSOR_DIR, { recursive: true, force: true });
|
|
db.exec(
|
|
"DELETE FROM token_usage; DELETE FROM agents; DELETE FROM sessions; DELETE FROM cursor_transcripts;" +
|
|
" DELETE FROM dashboard_runs; DELETE FROM lanes;"
|
|
);
|
|
});
|
|
|
|
describe("cursor usage", () => {
|
|
it("walks a project slug back to an existing directory, else null", () => {
|
|
assert.equal(cursor.cwdFromSlug(slugOf(PROJECT)), PROJECT);
|
|
assert.equal(cursor.cwdFromSlug(slugOf(`${PROJECT}-gone`)), null);
|
|
assert.equal(cursor.cwdFromSlug("empty-window"), null);
|
|
assert.equal(cursor.cwdFromSlug(""), null);
|
|
});
|
|
|
|
it("bounds the walk: no symlink is followed, and it gives up after a budget", () => {
|
|
const base = path.join(fs.realpathSync(ROOT), "maze");
|
|
// A symlink loop: every `a` and `a-a` is the same directory again.
|
|
const loop = path.join(base, "loop");
|
|
fs.mkdirSync(loop, { recursive: true });
|
|
fs.symlinkSync(".", path.join(loop, "a"));
|
|
fs.symlinkSync(".", path.join(loop, "a-a"));
|
|
// A real tree with ~1000 directories that all prefix the slug.
|
|
const tree = path.join(base, "tree");
|
|
const grow = (dir, t) => {
|
|
if (t <= 0) return;
|
|
fs.mkdirSync(path.join(dir, "a"), { recursive: true });
|
|
grow(path.join(dir, "a"), t - 1);
|
|
if (t < 2) return;
|
|
fs.mkdirSync(path.join(dir, "a-a"), { recursive: true });
|
|
grow(path.join(dir, "a-a"), t - 2);
|
|
};
|
|
grow(tree, 13);
|
|
const real = fs.readdirSync;
|
|
let calls = 0;
|
|
fs.readdirSync = (...a) => {
|
|
if (++calls > 5000) throw new Error("unbounded walk");
|
|
return real(...a);
|
|
};
|
|
try {
|
|
assert.equal(cursor.cwdFromSlug(`${slugOf(loop)}${"-a".repeat(30)}-z`), null);
|
|
assert.ok(calls < 20, `followed a symlink loop: ${calls} reads`);
|
|
calls = 0;
|
|
assert.equal(cursor.cwdFromSlug(`${slugOf(tree)}${"-a".repeat(13)}-z`), null);
|
|
assert.ok(calls <= 501, `walked ${calls} directories`);
|
|
assert.equal(cursor.cwdFromSlug(slugOf(PROJECT)), PROJECT);
|
|
} finally {
|
|
fs.readdirSync = real;
|
|
fs.rmSync(base, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("creates the session with its name and cwd, and no tokens", async () => {
|
|
transcript(ID);
|
|
assert.deepEqual(await cursor.ingestCursorUsage(), { files: 1, sessions: 1 });
|
|
const s = session(ID);
|
|
assert.equal(s.tool, "cursor");
|
|
assert.equal(s.name, "Review the campaign code");
|
|
assert.equal(s.cwd, PROJECT);
|
|
assert.equal(s.model, null);
|
|
assert.equal(s.status, "active");
|
|
assert.equal(s.transcript_path, null);
|
|
assert.equal(db.prepare("SELECT COUNT(*) c FROM token_usage").get().c, 0);
|
|
// Unchanged: never re-read.
|
|
assert.deepEqual(await cursor.ingestCursorUsage(), { files: 0, sessions: 0 });
|
|
});
|
|
|
|
it("settles a quiet session to completed, and reads an old one completed", async () => {
|
|
const file = transcript(ID);
|
|
await cursor.ingestCursorUsage();
|
|
const seen = db.prepare("SELECT mtime_ms FROM cursor_transcripts").get().mtime_ms;
|
|
assert.deepEqual(await cursor.ingestCursorUsage({ now: seen + 5 * 60_000 }), {
|
|
files: 0,
|
|
sessions: 1,
|
|
});
|
|
assert.equal(session(ID).status, "completed");
|
|
assert.equal(session(ID).ended_at, new Date(seen).toISOString());
|
|
|
|
db.exec("DELETE FROM sessions; DELETE FROM cursor_transcripts;");
|
|
age(file, 10 * 60_000);
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(session(ID).status, "completed");
|
|
});
|
|
|
|
it("keeps a deleted session deleted until Cursor writes again", async () => {
|
|
const file = transcript(ID);
|
|
age(file, 10 * 60_000);
|
|
await cursor.ingestCursorUsage();
|
|
db.prepare("DELETE FROM sessions WHERE id = ?").run(ID);
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(session(ID), undefined);
|
|
fs.appendFileSync(file, JSON.stringify({ role: "user", message: { content: [] } }) + "\n");
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(session(ID).tool, "cursor");
|
|
});
|
|
|
|
it("never touches a session of another tool with the same id", async () => {
|
|
db.prepare(
|
|
"INSERT INTO sessions (id, name, status, tool) VALUES (?, 'mine', 'active', 'claude')"
|
|
).run(ID);
|
|
transcript(ID, { slug: "empty-window" });
|
|
await cursor.ingestCursorUsage();
|
|
const s = session(ID);
|
|
assert.equal(s.tool, "claude");
|
|
assert.equal(s.name, "mine");
|
|
});
|
|
|
|
it("names a session with no prompt by its id, with no cwd", async () => {
|
|
transcript(ID, { slug: "1778550192773", prompt: "" });
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(session(ID).name, `Cursor ${ID.slice(0, 8)}`);
|
|
assert.equal(session(ID).cwd, null);
|
|
});
|
|
|
|
it("maps the transcript to the transcript shape", async () => {
|
|
const file = transcript(ID);
|
|
const more = [
|
|
{
|
|
role: "assistant",
|
|
message: {
|
|
content: [
|
|
{ type: "text", text: "Reading it now." },
|
|
{ type: "tool_use", id: "t1", name: "Grep", input: { pattern: "x" } },
|
|
],
|
|
},
|
|
},
|
|
{
|
|
role: "user",
|
|
message: { content: [{ type: "tool_result", tool_use_id: "t1", content: "no match" }] },
|
|
},
|
|
{ role: "assistant", message: { content: [{ type: "text", text: "Done." }] } },
|
|
];
|
|
fs.appendFileSync(file, more.map((l) => JSON.stringify(l)).join("\n") + "\n");
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(cursor.transcriptPath(ID), file);
|
|
|
|
const { createApp, startServer } = require("../index");
|
|
server ||= await startServer(createApp(), 0);
|
|
const BASE = `http://127.0.0.1:${server.address().port}`;
|
|
const list = await (await fetch(`${BASE}/api/sessions/${ID}/transcripts`)).json();
|
|
assert.deepEqual(
|
|
list.transcripts.map((t) => [t.id, t.type]),
|
|
[["main", "main"]]
|
|
);
|
|
const body = await (await fetch(`${BASE}/api/sessions/${ID}/transcript`)).json();
|
|
assert.deepEqual(
|
|
body.messages.map((m) => [m.sender, m.content.map((c) => c.type)]),
|
|
[
|
|
["user", ["text"]],
|
|
["assistant", ["tool_use"]],
|
|
["assistant", ["text", "tool_use"]],
|
|
["tool", ["tool_result"]],
|
|
["assistant", ["text"]],
|
|
]
|
|
);
|
|
assert.equal(body.messages[0].content[0].text, "Review the campaign code\nplease");
|
|
assert.equal(body.messages[3].content[0].output, "no match");
|
|
const sub = await (await fetch(`${BASE}/api/sessions/${ID}/transcript?agent_id=x`)).json();
|
|
assert.equal(sub.messages.length, 0);
|
|
});
|
|
|
|
it("gives the session to the Cursor pane it started in", async () => {
|
|
db.prepare("INSERT INTO lanes (id, title, cwd) VALUES (5, 'w', ?)").run(PROJECT);
|
|
db.prepare(
|
|
`INSERT INTO dashboard_runs (id, lane_id, cwd, status, started_at, tool)
|
|
VALUES ('agenthub-lane-5', 5, ?, 'running', ?, 'cursor')`
|
|
).run(PROJECT, new Date(Date.now() - 60_000).toISOString());
|
|
transcript(ID);
|
|
await cursor.ingestCursorUsage();
|
|
assert.equal(session(ID).lane_id, 5);
|
|
const run = db.prepare("SELECT session_id FROM dashboard_runs WHERE id = 'agenthub-lane-5'");
|
|
assert.equal(run.get().session_id, ID);
|
|
});
|
|
});
|