mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-05 03:09:56 +01:00
* feat(sessions): a token reads its sessions and what was said in them An agent that starts Claude Code in a Loki session (tab-inject) could read the screen (#1641) but not the conversation: the parsed transcript was only readable over the cookie-only transcript stream, and since #1644 over OrangeCat's signed rail. - lib/session-reads: the list, one run, or one project with the last things said in its conversation, moved out of the signed route unchanged, so two doors share one copy - GET /api/control/sessions: the same reads with a session or ck_ token (?project=, ?runId=, ?items=), no-store - every row names its session and carries openUrl, the same session in Loki's Terminal on that run (lib/dispatch-card sessionOpenUrl) - the list says it is cut at 25 and carries total, so a cut list is never read as the whole one - LOOP-WALK's Session walk names the read; tests pin both doors to the one lib Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtCjm3CvrFm3kYaTgy * fix(sessions): the conversation read is current, on the session's builder, and never ends a person's view Traced end to end before merge (2026-11-12): - a cached conversation was served forever: after the first read sent peek_stop the runner stopped streaming, so a later read returned the same copy without the agent's answer. The cache now counts only while someone is watching; otherwise the read waits for a frame posted after it asked. - peek_start and peek_stop carried no channel, so the owner's laptop runner could take a read meant for the cloud session (transcript null). They now name the project's builder (projectPreferredChannel). - the read counted its viewer under a key of its own, so its peek_stop could end a person's live view of the same session on a phone. It now shares the Terminal's viewer count (same user, tab and channel). - a cloud link carried no source, so a phone that last chose 'Your computer' opened the laptop's session of the same name. sessionOpenUrl names the cloud builder, and each row's link uses the session's builder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_019MDtmtCjm3CvrFm3kYaTgy --------- Co-authored-by: Claude <noreply@anthropic.com>
318 lines
13 KiB
TypeScript
318 lines
13 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import { createHmac } from "node:crypto";
|
|
|
|
/**
|
|
* OrangeCat's read of one person's agent sessions (/api/orangecat/sessions).
|
|
*
|
|
* Two halves, like orangecat-actor-status: the pure shaping (what crosses, and
|
|
* how much of it), and the refusals that need no database: unconfigured, bad
|
|
* signature, stale request, bad body.
|
|
*
|
|
* Run: npx tsx scripts/test/orangecat-sessions.ts
|
|
*/
|
|
async function main(): Promise<void> {
|
|
console.log("orangecat sessions:");
|
|
process.env.DATABASE_URL ||= "postgres://test:test@127.0.0.1:5432/test";
|
|
|
|
const {
|
|
shapeSessionRow,
|
|
orderSessions,
|
|
shapeTranscriptItems,
|
|
oneLine,
|
|
SESSIONS_MAX_ITEMS,
|
|
SESSIONS_ITEM_CHARS,
|
|
} = await import("../../src/lib/integrations/orangecat-sessions");
|
|
|
|
// ── rows ───────────────────────────────────────────────────────────────────
|
|
|
|
const presence = { cloud: true, local: false, any: true };
|
|
const run = {
|
|
id: "11111111-1111-4111-8111-111111111111",
|
|
state: "working",
|
|
label: "Working",
|
|
reason: null,
|
|
task: "\n Fix the header\nand the footer",
|
|
track: "The agent is working on it.",
|
|
prUrl: "https://github.com/acme/site/pull/7",
|
|
lastProgressAt: "2026-11-12T03:00:00.000Z",
|
|
};
|
|
|
|
const working = shapeSessionRow({
|
|
project: "site",
|
|
builderPref: "cloud",
|
|
presence,
|
|
run,
|
|
transcriptAt: Date.parse("2026-11-12T03:05:00Z"),
|
|
});
|
|
assert.equal(working.state, "working");
|
|
assert.equal(working.builder, "cloud");
|
|
assert.equal(working.online, true);
|
|
assert.equal(working.task, "Fix the header", "the task is the first line asked");
|
|
assert.equal(
|
|
working.lastActivityAt,
|
|
"2026-11-12T03:05:00.000Z",
|
|
"a transcript frame is the freshest sign of life",
|
|
);
|
|
assert.equal(working.runId, run.id);
|
|
assert.match(working.statusUrl ?? "", /\/api\/orchestration\/runs\/11111111-/);
|
|
assert.equal(working.prUrl, run.prUrl);
|
|
assert.equal(working.session, "site", "a project's own session is named after it");
|
|
assert.match(
|
|
working.openUrl,
|
|
/^https:\/\/[^/]+\/terminal\?source=cloud&project=site&run=11111111-/,
|
|
"openUrl is the same session, on that run, in Loki's Terminal",
|
|
);
|
|
const lane = shapeSessionRow({
|
|
project: "site",
|
|
builderPref: "cloud",
|
|
presence,
|
|
run,
|
|
transcriptAt: null,
|
|
tab: "site~11111111",
|
|
});
|
|
assert.equal(lane.session, "site~11111111", "a parallel lane is named as its own tab");
|
|
assert.match(lane.openUrl, /\/terminal\?source=cloud&project=site~11111111&run=/);
|
|
const resolved = shapeSessionRow({
|
|
project: "plain",
|
|
builderPref: null,
|
|
presence,
|
|
run: null,
|
|
transcriptAt: null,
|
|
channel: "cloud",
|
|
});
|
|
assert.match(
|
|
resolved.openUrl,
|
|
/\/terminal\?source=cloud&project=plain$/,
|
|
"the link names the builder the session runs on, not this browser's last choice",
|
|
);
|
|
console.log(" ✓ a working session: canonical state, one-line task, run and PR");
|
|
|
|
const local = shapeSessionRow({
|
|
project: "site",
|
|
builderPref: "local",
|
|
presence,
|
|
run: { ...run, prUrl: "javascript:alert(1)" },
|
|
transcriptAt: null,
|
|
});
|
|
assert.equal(local.online, false, "online means the project's own builder");
|
|
assert.equal(local.lastActivityAt, run.lastProgressAt, "no frame: the runner's last progress");
|
|
assert.equal(local.prUrl, null, "a non-http URL never crosses");
|
|
assert.match(
|
|
local.openUrl,
|
|
/\/terminal\?source=machine&tab=site&run=/,
|
|
"a local session opens on This computer",
|
|
);
|
|
console.log(" ✓ online follows the preferred builder; unsafe URL dropped");
|
|
|
|
const idle = shapeSessionRow({
|
|
project: "quiet",
|
|
builderPref: null,
|
|
presence,
|
|
run: null,
|
|
transcriptAt: null,
|
|
});
|
|
assert.equal(idle.state, "idle");
|
|
assert.equal(idle.label, "Idle");
|
|
assert.equal(idle.runId, null);
|
|
assert.equal(idle.statusUrl, null);
|
|
assert.match(idle.openUrl, /\/terminal\?project=quiet$/, "no run: the session itself");
|
|
assert.equal(idle.online, true, "no preference: any builder counts");
|
|
console.log(" ✓ no run on record is idle");
|
|
|
|
const odd = shapeSessionRow({
|
|
project: "odd",
|
|
builderPref: "moon",
|
|
presence,
|
|
run: { ...run, state: "sideways" },
|
|
transcriptAt: null,
|
|
});
|
|
assert.equal(odd.state, "idle", "a state outside the canonical six is never forwarded");
|
|
assert.equal(odd.builder, null);
|
|
console.log(" ✓ unknown state and builder are not passed through");
|
|
|
|
const ordered = orderSessions([
|
|
idle,
|
|
working,
|
|
{ ...working, project: "stuck", state: "needs_you" },
|
|
{ ...idle, project: "quiet2" },
|
|
]);
|
|
assert.deepEqual(
|
|
ordered.map((r) => r.project),
|
|
["stuck", "site", "quiet", "quiet2"],
|
|
);
|
|
console.log(" ✓ what needs the person leads, then work in flight, then list order");
|
|
|
|
assert.equal(oneLine(" \n\n"), null);
|
|
assert.equal((oneLine("x".repeat(500)) ?? "").length, 200);
|
|
|
|
// ── transcript ─────────────────────────────────────────────────────────────
|
|
|
|
const items = [
|
|
{ id: "1", at: "2026-11-12T03:00:00Z", kind: "user" as const, text: "git status" },
|
|
{
|
|
id: "2",
|
|
at: "2026-11-12T03:00:01Z",
|
|
kind: "tool" as const,
|
|
name: "Bash",
|
|
summary: "git status --short --branch",
|
|
status: "done" as const,
|
|
result: "## main...origin/main",
|
|
},
|
|
{ id: "3", at: null, kind: "assistant" as const, text: "y".repeat(5000) },
|
|
{ id: "4", at: null, kind: "assistant" as const, text: " " },
|
|
];
|
|
const shaped = shapeTranscriptItems(items, 10);
|
|
assert.equal(shaped.length, 3, "an empty message is dropped");
|
|
assert.equal(shaped[1].kind, "tool");
|
|
assert.equal(shaped[1].text, "Bash: git status --short --branch\n## main...origin/main");
|
|
assert.equal(shaped[2].text.length, SESSIONS_ITEM_CHARS, "long text is clipped");
|
|
assert.equal(shapeTranscriptItems(items, 2).length, 1, "the LAST n items, then empties dropped");
|
|
const many = Array.from({ length: 100 }, (_, i) => ({
|
|
id: String(i),
|
|
at: null,
|
|
kind: "user" as const,
|
|
text: `m${i}`,
|
|
}));
|
|
assert.equal(shapeTranscriptItems(many, 999).length, SESSIONS_MAX_ITEMS);
|
|
assert.equal(shapeTranscriptItems(many, 999).at(-1)?.text, "m99");
|
|
console.log(" ✓ transcript: last n, clipped, tools as one row, capped at 40");
|
|
|
|
// ── the handoff and the transcript's freshness ─────────────────────────────
|
|
|
|
const { shapeTranscript } = await import("../../src/lib/integrations/orangecat-sessions");
|
|
const reported = shapeSessionRow({
|
|
project: "site",
|
|
builderPref: "cloud",
|
|
presence,
|
|
run: {
|
|
...run,
|
|
state: "done",
|
|
handoff: { done: ["On main, last commit abc123"], checked: null, next: [] },
|
|
},
|
|
transcriptAt: null,
|
|
});
|
|
assert.deepEqual(reported.handoff, {
|
|
done: ["On main, last commit abc123"],
|
|
checked: null,
|
|
next: [],
|
|
});
|
|
assert.equal(working.handoff, null, "no handoff until the agent reports");
|
|
assert.equal(idle.handoff, null);
|
|
console.log(" ✓ a finished run carries the agent's handoff; an open one does not");
|
|
|
|
const t = shapeTranscript("site", { at: Date.parse("2026-11-12T05:00:00Z"), items }, false, 2);
|
|
assert.equal(t.live, false, "an older copy is marked as such");
|
|
assert.equal(t.at, "2026-11-12T05:00:00.000Z");
|
|
assert.equal(t.items.length, 1);
|
|
console.log(" ✓ a transcript says whether it is live or an older copy");
|
|
|
|
// ── a bot's watch ──────────────────────────────────────────────────────────
|
|
|
|
const { watchTab, isWatched, watchSeconds, WATCH_MAX_SECONDS } =
|
|
await import("../../src/lib/integrations/orangecat-watch");
|
|
const { addPeekViewer, removePeekViewer } = await import("../../src/lib/sse-bus");
|
|
assert.equal(watchSeconds(0), 1);
|
|
assert.equal(watchSeconds(10_000), WATCH_MAX_SECONDS);
|
|
const u = "watch-test-user";
|
|
const first = await watchTab(u, "site~abcd1234", 1, "cloud", 1_000);
|
|
assert.equal(first, 2_000);
|
|
assert.ok(isWatched(u, "site~abcd1234", "cloud"));
|
|
// The watch holds a viewer: another viewer joining is not the first.
|
|
assert.equal(addPeekViewer(u, "site~abcd1234", "cloud"), false);
|
|
assert.equal(removePeekViewer(u, "site~abcd1234", "cloud"), false, "the watch still holds it");
|
|
const extended = await watchTab(u, "site~abcd1234", 1, "cloud", 1_500);
|
|
assert.equal(extended, 2_500, "watching again extends the same watch");
|
|
await new Promise((r) => setTimeout(r, 1_200));
|
|
assert.equal(isWatched(u, "site~abcd1234", "cloud"), false, "a watch ends by itself");
|
|
assert.equal(addPeekViewer(u, "site~abcd1234", "cloud"), true, "and leaves no viewer behind");
|
|
removePeekViewer(u, "site~abcd1234", "cloud");
|
|
console.log(" ✓ a watch holds one viewer, extends, and ends by itself");
|
|
|
|
// The route watches BEFORE it reads, and waits for a frame newer than its join.
|
|
const { readFileSync } = await import("node:fs");
|
|
// The reads live in lib/session-reads.ts, shared with a person's own token.
|
|
const routeSrc = readFileSync("src/lib/session-reads.ts", "utf8");
|
|
assert.match(
|
|
readFileSync("src/app/api/orangecat/sessions/route.ts", "utf8"),
|
|
/readSessions\(user\.id, \{ project, runId, items, watch, poll \}\)/,
|
|
);
|
|
assert.ok(
|
|
routeSrc.indexOf("await watchTab(") > -1 &&
|
|
routeSrc.indexOf("await watchTab(") <
|
|
routeSrc.indexOf("await readTranscript(userId, tab, channel)"),
|
|
"watch first, then read",
|
|
);
|
|
assert.match(routeSrc, /frame\.at >= joinedAt/, "a snapshot must be newer than the join");
|
|
assert.match(routeSrc, /settledFrame\(/, "and whole: every batch of it, not the first");
|
|
assert.match(
|
|
routeSrc,
|
|
/rowFor\(userId, project, run, presence, !poll\)/,
|
|
"a poll never looks at GitHub",
|
|
);
|
|
console.log(" ✓ the route follows before it reads, and never passes an old copy off as live");
|
|
|
|
// ── refusals (no database) ─────────────────────────────────────────────────
|
|
|
|
const { POST } = await import("../../src/app/api/orangecat/sessions/route");
|
|
const { NextRequest } = await import("next/server");
|
|
const secret = "sessions-test-secret-at-least-32-characters-long";
|
|
const sign = (raw: string) => "sha256=" + createHmac("sha256", secret).update(raw).digest("hex");
|
|
const request = (body: unknown, signature?: string) => {
|
|
const raw = JSON.stringify(body);
|
|
return new NextRequest("https://loki.orangecat.ch/api/orangecat/sessions", {
|
|
method: "POST",
|
|
headers: {
|
|
"content-type": "application/json",
|
|
...(signature ? { "x-orangecat-signature": signature } : {}),
|
|
},
|
|
body: raw,
|
|
});
|
|
};
|
|
const fresh = {
|
|
actorId: "00000000-0000-4000-8000-000000000000",
|
|
issuedAt: new Date().toISOString(),
|
|
};
|
|
const original = process.env.ORANGECAT_WEBHOOK_SECRET;
|
|
|
|
try {
|
|
delete process.env.ORANGECAT_WEBHOOK_SECRET;
|
|
assert.equal((await POST(request(fresh, sign(JSON.stringify(fresh))))).status, 503);
|
|
console.log(" ✓ unconfigured fails closed (503)");
|
|
|
|
process.env.ORANGECAT_WEBHOOK_SECRET = secret;
|
|
assert.equal((await POST(request(fresh, "sha256=deadbeef"))).status, 401);
|
|
assert.equal((await POST(request(fresh))).status, 401);
|
|
console.log(" ✓ bad or missing signature (401)");
|
|
|
|
const stale = { ...fresh, issuedAt: new Date(Date.now() - 10 * 60 * 1000).toISOString() };
|
|
const staleRes = await POST(request(stale, sign(JSON.stringify(stale))));
|
|
assert.equal(staleRes.status, 401);
|
|
assert.equal((await staleRes.json()).error, "stale request");
|
|
console.log(" ✓ a signed but stale request is refused (replay)");
|
|
|
|
for (const bad of [
|
|
{ ...fresh, actorId: "not-a-uuid" },
|
|
{ ...fresh, runId: "nope" },
|
|
{ ...fresh, items: 41 },
|
|
{ ...fresh, project: "" },
|
|
{ ...fresh, runId: "11111111-1111-4111-8111-111111111111", watch: 301 },
|
|
{ ...fresh, runId: "11111111-1111-4111-8111-111111111111", watch: 0 },
|
|
{ ...fresh, runId: "11111111-1111-4111-8111-111111111111", poll: "yes" },
|
|
]) {
|
|
assert.equal((await POST(request(bad, sign(JSON.stringify(bad))))).status, 400);
|
|
}
|
|
console.log(" ✓ a bad body is refused (400)");
|
|
} finally {
|
|
if (original === undefined) delete process.env.ORANGECAT_WEBHOOK_SECRET;
|
|
else process.env.ORANGECAT_WEBHOOK_SECRET = original;
|
|
}
|
|
|
|
console.log("orangecat sessions: all passed");
|
|
process.exit(0);
|
|
}
|
|
|
|
main().catch((err) => {
|
|
console.error(err);
|
|
process.exit(1);
|
|
});
|