kaizen-agent 1.56.0 → 1.57.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/board.test.ts +56 -0
- package/cli/docs.test.ts +92 -0
- package/cli/docs.ts +84 -0
- package/cli/install.ts +13 -0
- package/cli/project-tree.test.ts +39 -0
- package/cli/pty.test.ts +1 -1
- package/cli/state.test.ts +18 -2
- package/cli/state.ts +21 -17
- package/cli/usage.test.ts +142 -0
- package/cli/usage.ts +66 -0
- package/cli/web.ts +194 -7
- package/package.json +1 -1
- package/skills/kaizen/SKILL.md +1 -1
- package/skills/kaizen/docs.md +6 -1
- package/skills/kaizen/spec-main.md +4 -2
- package/web/board/api.ts +2 -0
- package/web/board/badge.ts +41 -0
- package/web/board/cards.ts +58 -11
- package/web/board/context.ts +247 -0
- package/web/board/home.ts +3 -3
- package/web/board/ideas.ts +176 -0
- package/web/board/keys.ts +2 -5
- package/web/board/labels.ts +4 -0
- package/web/board/live.ts +3 -1
- package/web/board/main.ts +21 -0
- package/web/board/panel.ts +33 -8
- package/web/board/projects.ts +42 -2
- package/web/board/run-view.ts +691 -0
- package/web/board/settings.ts +1 -0
- package/web/board/store.ts +2 -0
- package/web/board/terms.ts +7 -3
- package/web/board/views.ts +21 -4
- package/web/board/workspace.ts +318 -0
- package/web/board.html +200 -36
- package/web/board.js +43 -40
- package/web/notebook.js +24 -23
- package/web/notebook.ts +7 -1
- package/web/notes.html +67 -21
- package/web/term.js +34 -34
- package/web/term.ts +14 -8
- package/web/video.html +65 -21
- package/web/video.js +54 -53
- package/web/video.ts +5 -1
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// The footer's usage and phone readers, and the run workspace's /shell route on a real
|
|
2
|
+
// board: guarded like /pty, an agent only from the known list, a pwd in the project.
|
|
3
|
+
import { test, expect } from "bun:test";
|
|
4
|
+
import { mkdtempSync, mkdirSync, writeFileSync, realpathSync, utimesSync } from "node:fs";
|
|
5
|
+
import { tmpdir } from "node:os";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { codexUsage, claudeUsage, phonePeers } from "./usage.ts";
|
|
8
|
+
|
|
9
|
+
const root = realpathSync(mkdtempSync(join(tmpdir(), "kaizen-usage-")));
|
|
10
|
+
const rl = (p: number, s: number) => JSON.stringify({ type: "event_msg", payload: { type: "token_count", rate_limits: { primary: { used_percent: p, window_minutes: 300, resets_at: 1800000000 }, secondary: { used_percent: s, window_minutes: 10080, resets_at: 1800500000 } } } });
|
|
11
|
+
|
|
12
|
+
test("codexUsage: the newest rollout's last rate_limits, windows by length; nothing when absent", () => {
|
|
13
|
+
const h = join(root, "codex");
|
|
14
|
+
expect(codexUsage(h)).toBeNull();
|
|
15
|
+
const d = join(h, ".codex", "sessions", "2026", "10", "28");
|
|
16
|
+
mkdirSync(d, { recursive: true });
|
|
17
|
+
const old = join(d, "rollout-a.jsonl"), nu = join(d, "rollout-b.jsonl");
|
|
18
|
+
writeFileSync(old, rl(99, 99) + "\n");
|
|
19
|
+
writeFileSync(nu, rl(10, 20) + "\n" + rl(42, 7) + "\n{\"torn");
|
|
20
|
+
utimesSync(old, new Date(1000), new Date(1000));
|
|
21
|
+
expect(codexUsage(h)).toEqual({ agent: "codex", five: { pct: 42, resetsAt: 1800000000000 }, week: { pct: 7, resetsAt: 1800500000000 } });
|
|
22
|
+
// A session just started, no rate_limits yet: the one before it still counts.
|
|
23
|
+
writeFileSync(nu, '{"type":"session_meta"}\n');
|
|
24
|
+
expect(codexUsage(h)?.five?.pct).toBe(99);
|
|
25
|
+
writeFileSync(old, '{"type":"session_meta"}\n');
|
|
26
|
+
expect(codexUsage(h)).toBeNull();
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
test("claudeUsage: maps the windows; a failure is an error that never carries the token", async () => {
|
|
30
|
+
const h = join(root, "claude");
|
|
31
|
+
expect(await claudeUsage(h, (() => { throw new Error("no call"); }) as any)).toBeNull();
|
|
32
|
+
mkdirSync(join(h, ".claude"), { recursive: true });
|
|
33
|
+
writeFileSync(join(h, ".claude", ".credentials.json"), JSON.stringify({ claudeAiOauth: { accessToken: "sk-ant-oat-SECRET" } }));
|
|
34
|
+
let sent: any;
|
|
35
|
+
const ok = (async (_u: string, init: any) => { sent = init; return new Response(JSON.stringify({ five_hour: { utilization: 62, resets_at: "2026-10-28T12:00:00Z" }, seven_day: { utilization: 34.4, resets_at: null } })); }) as any;
|
|
36
|
+
expect(await claudeUsage(h, ok)).toEqual({ agent: "claude", five: { pct: 62, resetsAt: Date.parse("2026-10-28T12:00:00Z") }, week: { pct: 34, resetsAt: null } });
|
|
37
|
+
expect(sent.headers["anthropic-beta"]).toBe("oauth-2025-04-20");
|
|
38
|
+
const fail = (async () => { throw new Error("refused Bearer sk-ant-oat-SECRET"); }) as any;
|
|
39
|
+
const e = await claudeUsage(h, fail);
|
|
40
|
+
expect(e).toHaveProperty("error");
|
|
41
|
+
expect(JSON.stringify(e)).not.toContain("SECRET");
|
|
42
|
+
expect(await claudeUsage(h, (async () => new Response("", { status: 401 })) as any)).toEqual({ agent: "claude", error: "HTTP 401" });
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
test("phonePeers: online, offline, no phone, not running", () => {
|
|
46
|
+
const st = (peers: object, state = "Running") => JSON.stringify({ BackendState: state, Peer: peers });
|
|
47
|
+
expect(phonePeers(st({ a: { OS: "iOS", HostName: "iphone", Online: true }, b: { OS: "linux", Online: true } }))).toEqual({ running: true, phones: [{ name: "iphone", online: true }] });
|
|
48
|
+
expect(phonePeers(st({ a: { OS: "android", HostName: "pixel", Online: false } })).phones).toEqual([{ name: "pixel", online: false }]);
|
|
49
|
+
expect(phonePeers(st({ b: { OS: "windows", Online: true } })).phones).toEqual([]);
|
|
50
|
+
expect(phonePeers(st({}, "Stopped")).running).toBe(false);
|
|
51
|
+
expect(phonePeers("").running).toBe(false);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test.skipIf(process.platform === "win32")("/shell: foreign origin, unknown project and unknown agent refused; a shell opens in the project; /usage and /phone answer", async () => {
|
|
55
|
+
const homeDir = join(root, "home"), proj = join(homeDir, "a"), st = join(proj, ".kaizen"), bin = join(root, "bin");
|
|
56
|
+
for (const d of [st, join(homeDir, ".kaizen"), bin]) mkdirSync(d, { recursive: true });
|
|
57
|
+
writeFileSync(join(homeDir, ".kaizen", "projects"), proj + "\n");
|
|
58
|
+
writeFileSync(join(st, "inbox.md"), "# Inbox\n");
|
|
59
|
+
// A shell that says where it is, then echoes.
|
|
60
|
+
const sh = join(bin, "fakesh");
|
|
61
|
+
writeFileSync(sh, '#!/bin/sh\necho "pwd:$(pwd)"\nwhile read x; do echo "got:$x"; done\n', { mode: 0o755 });
|
|
62
|
+
// Some agent must exist for the board to start; not claude or codex, so /usage has none.
|
|
63
|
+
writeFileSync(join(bin, "gemini"), "#!/bin/sh\n", { mode: 0o755 });
|
|
64
|
+
const port = 20000 + Math.floor(Math.random() * 20000);
|
|
65
|
+
const repo = join(import.meta.dir, "..");
|
|
66
|
+
// PATH without tailscale, claude or codex: /phone and /usage must still answer.
|
|
67
|
+
const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], {
|
|
68
|
+
cwd: proj, stdout: "ignore", stderr: "ignore",
|
|
69
|
+
env: { ...process.env, HOME: homeDir, USERPROFILE: homeDir, KAIZEN_HOME: repo, PATH: bin, SHELL: sh, DISPLAY: "", WAYLAND_DISPLAY: "", TERMINAL: "", TMUX: "" },
|
|
70
|
+
});
|
|
71
|
+
try {
|
|
72
|
+
const at = `http://127.0.0.1:${port}`;
|
|
73
|
+
for (let i = 0; ; i++) { try { await fetch(at + "/state"); break; } catch { if (i > 100) throw new Error("board did not start"); await Bun.sleep(50); } }
|
|
74
|
+
const post = (body: object, origin?: string, type = "application/json") => fetch(at + "/shell", { method: "POST", headers: { "content-type": type, ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
|
|
75
|
+
expect((await post({ dir: st }, "https://evil.example")).status).toBe(403);
|
|
76
|
+
// Another local server's page: same hostname, other port.
|
|
77
|
+
expect((await post({ dir: st }, `http://127.0.0.1:${port + 1}`)).status).toBe(403);
|
|
78
|
+
expect((await post({ dir: st }, "http://localhost:3000")).status).toBe(403);
|
|
79
|
+
// A simple (no-preflight) POST body type.
|
|
80
|
+
expect((await post({ dir: st }, at, "text/plain")).status).toBe(415);
|
|
81
|
+
expect((await post({ dir: join(root, "elsewhere", ".kaizen") })).status).toBe(404);
|
|
82
|
+
expect((await post({ dir: join(homeDir, ".kaizen") })).status).toBe(404);
|
|
83
|
+
expect((await post({ dir: st, agent: "rm -rf /" })).status).toBe(400);
|
|
84
|
+
expect((await post({ dir: st, agent: "codex" })).status).toBe(400); // known, not installed
|
|
85
|
+
|
|
86
|
+
// Resume: the session id comes only from the run's own state.json; a page-sent one is ignored.
|
|
87
|
+
const resume = (run: string, extra = {}) => post({ dir: st, run, resume: true, ...extra }, at);
|
|
88
|
+
mkdirSync(join(st, "runs", "r1"), { recursive: true });
|
|
89
|
+
writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ id: "r1", agent: "claude" }));
|
|
90
|
+
expect((await resume(`run:${st}:r1`, { session: "aaaaaaaa-page-chosen" })).status).toBe(404); // no session recorded
|
|
91
|
+
expect((await resume(`run:${st}:..`)).status).toBe(404);
|
|
92
|
+
expect((await resume(`run:${st}:../r1`)).status).toBe(404);
|
|
93
|
+
expect((await resume(`run:/elsewhere/.kaizen:r1`)).status).toBe(404); // a run of another dir
|
|
94
|
+
writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ id: "r1", agent: "codex", session: "abcdef12-3456" }));
|
|
95
|
+
expect((await resume(`run:${st}:r1`)).status).toBe(404); // not a Claude run
|
|
96
|
+
writeFileSync(join(st, "runs", "r1", "state.json"), JSON.stringify({ id: "r1", agent: "claude", session: "abcdef12-3456" }));
|
|
97
|
+
expect((await resume(`run:${st}:r1`)).status).toBe(400); // claude is not on this test's PATH
|
|
98
|
+
|
|
99
|
+
// /open-url: the same guards, and only an http(s) address. No success case: it opens a real window.
|
|
100
|
+
const open = (body: object, origin?: string, type = "application/json") => fetch(at + "/open-url", { method: "POST", headers: { "content-type": type, ...(origin ? { origin } : {}) }, body: JSON.stringify(body) });
|
|
101
|
+
expect((await open({ url: "http://localhost:3000/" }, "http://localhost:3000")).status).toBe(403);
|
|
102
|
+
expect((await open({ url: "http://localhost:3000/" }, at, "text/plain")).status).toBe(415);
|
|
103
|
+
expect((await open({ url: "file:///etc/passwd" }, at)).status).toBe(400);
|
|
104
|
+
expect((await open({ url: "javascript:alert(1)" }, at)).status).toBe(400);
|
|
105
|
+
// /frameable: board pages only, http(s) only; the answer is a boolean (or null when unreachable).
|
|
106
|
+
expect((await fetch(`${at}/frameable?url=${encodeURIComponent(at + "/")}`, { headers: { origin: "https://evil.example" } })).status).toBe(403);
|
|
107
|
+
expect((await fetch(`${at}/frameable?url=${encodeURIComponent("file:///etc/passwd")}`)).status).toBe(400);
|
|
108
|
+
expect(await (await fetch(`${at}/frameable?url=${encodeURIComponent(at + "/")}`)).json()).toEqual({ frameable: true });
|
|
109
|
+
|
|
110
|
+
const r = await post({ dir: st }, at);
|
|
111
|
+
expect(r.status).toBe(200);
|
|
112
|
+
const sh1 = await r.json() as any;
|
|
113
|
+
expect(sh1).toMatchObject({ dir: st, title: "shell", agent: "", run: "" });
|
|
114
|
+
expect(sh1.key).toMatch(/^sh-[\w-]+$/);
|
|
115
|
+
const url = `${at}/pty?key=${sh1.key}`, up = { upgrade: "websocket", connection: "Upgrade", "sec-websocket-version": "13", "sec-websocket-key": "dGhlIHNhbXBsZSBub25jZQ==" };
|
|
116
|
+
expect((await fetch(url, { headers: { ...up, origin: "https://evil.example" } })).status).toBe(403);
|
|
117
|
+
let seen = "";
|
|
118
|
+
const ws = new WebSocket(url.replace("http", "ws"), { headers: { origin: at } } as any);
|
|
119
|
+
ws.onmessage = (e) => { seen += String(e.data); };
|
|
120
|
+
await new Promise((ok, no) => { ws.onopen = ok; ws.onerror = no; });
|
|
121
|
+
for (let i = 0; i < 100 && !seen.includes("pwd:"); i++) await Bun.sleep(30);
|
|
122
|
+
expect(seen).toContain(`pwd:${proj}`);
|
|
123
|
+
ws.close();
|
|
124
|
+
expect(((await (await fetch(`${at}/shells?dir=${encodeURIComponent(st)}`)).json()) as any[]).map((s) => s.key)).toEqual([sh1.key]);
|
|
125
|
+
expect((await fetch(at + "/pty/exit", { method: "POST", body: JSON.stringify({ key: sh1.key }) })).status).toBe(200);
|
|
126
|
+
for (let i = 0; i < 100; i++) { if (!((await (await fetch(`${at}/shells`)).json()) as any[]).length) break; await Bun.sleep(50); }
|
|
127
|
+
expect(await (await fetch(`${at}/shells`)).json()).toEqual([]);
|
|
128
|
+
|
|
129
|
+
// At most 8 live terminals per project.
|
|
130
|
+
const keys: string[] = [];
|
|
131
|
+
for (let i = 0; i < 8; i++) { const x = await post({ dir: st }, at); expect(x.status).toBe(200); keys.push(((await x.json()) as any).key); }
|
|
132
|
+
expect((await post({ dir: st }, at)).status).toBe(429);
|
|
133
|
+
for (const k of keys) await fetch(at + "/pty/exit", { method: "POST", body: JSON.stringify({ key: k }) });
|
|
134
|
+
|
|
135
|
+
const u = await fetch(at + "/usage");
|
|
136
|
+
expect(u.status).toBe(200);
|
|
137
|
+
expect(await u.json()).toEqual([]);
|
|
138
|
+
const p = await fetch(at + "/phone");
|
|
139
|
+
expect(p.status).toBe(200);
|
|
140
|
+
expect(await p.json()).toEqual({ tailscale: false });
|
|
141
|
+
} finally { proc.kill(); }
|
|
142
|
+
}, 30_000);
|
package/cli/usage.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The board footer's agent usage and phone status. Usage is the agent's own plan
|
|
2
|
+
// windows (5 hours, a week): Codex writes them into its session logs, Claude answers
|
|
3
|
+
// them from its OAuth usage endpoint. The Claude token is read here, sent only to
|
|
4
|
+
// api.anthropic.com, and never returned or logged.
|
|
5
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
|
|
8
|
+
export type Window = { pct: number; resetsAt: number | null };
|
|
9
|
+
export type Usage = { agent: string; five: Window | null; week: Window | null } | { agent: string; error: string };
|
|
10
|
+
|
|
11
|
+
const win = (pct: unknown, resets: unknown): Window | null =>
|
|
12
|
+
typeof pct === "number" ? { pct: Math.round(pct), resetsAt: typeof resets === "number" ? resets * 1000 : typeof resets === "string" ? Date.parse(resets) || null : null } : null;
|
|
13
|
+
|
|
14
|
+
// The last rate_limits in the newest ~/.codex/sessions/**/rollout-*.jsonl that has one, or null.
|
|
15
|
+
export function codexUsage(home: string): Usage | null {
|
|
16
|
+
const root = join(home, ".codex", "sessions");
|
|
17
|
+
if (!existsSync(root)) return null;
|
|
18
|
+
// Newest first: a session that has only just started has no rate_limits line yet.
|
|
19
|
+
const files = [...new Bun.Glob("**/rollout-*.jsonl").scanSync({ cwd: root })]
|
|
20
|
+
.map((f) => ({ f, t: statSync(join(root, f)).mtimeMs }))
|
|
21
|
+
.sort((a, b) => b.t - a.t)
|
|
22
|
+
// ponytail: batch tools start dozens of sessions at once with no limits in them; 300 files covers that, a cursor file would scale further.
|
|
23
|
+
.slice(0, 300);
|
|
24
|
+
for (const { f } of files) {
|
|
25
|
+
const lines = readFileSync(join(root, f), "utf8").split("\n");
|
|
26
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
27
|
+
if (!lines[i]!.includes('"rate_limits"')) continue;
|
|
28
|
+
try {
|
|
29
|
+
const find = (o: any): any => o && typeof o === "object" ? ("rate_limits" in o ? o.rate_limits : Object.values(o).map(find).find(Boolean)) : null;
|
|
30
|
+
const rl = find(JSON.parse(lines[i]!));
|
|
31
|
+
if (!rl) continue;
|
|
32
|
+
const by = (m: number) => [rl.primary, rl.secondary].find((w) => w?.window_minutes === m);
|
|
33
|
+
const five = by(300), week = by(10080);
|
|
34
|
+
if (!five && !week) continue;
|
|
35
|
+
return { agent: "codex", five: win(five?.used_percent, five?.resets_at), week: win(week?.used_percent, week?.resets_at) };
|
|
36
|
+
} catch { /* a torn last line: try the one before */ }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Claude's plan usage, or null when there is no Claude login. A failure is an error
|
|
43
|
+
// entry, so the footer says "usage unavailable" instead of showing 0%.
|
|
44
|
+
export async function claudeUsage(home: string, get: typeof fetch = fetch): Promise<Usage | null> {
|
|
45
|
+
let token = "";
|
|
46
|
+
try { token = JSON.parse(readFileSync(join(home, ".claude", ".credentials.json"), "utf8"))?.claudeAiOauth?.accessToken ?? ""; } catch { return null; }
|
|
47
|
+
if (!token) return null;
|
|
48
|
+
try {
|
|
49
|
+
const r = await get("https://api.anthropic.com/api/oauth/usage", { headers: { authorization: `Bearer ${token}`, "anthropic-beta": "oauth-2025-04-20" }, signal: AbortSignal.timeout(8000) });
|
|
50
|
+
if (!r.ok) return { agent: "claude", error: `HTTP ${r.status}` };
|
|
51
|
+
const d: any = await r.json();
|
|
52
|
+
return { agent: "claude", five: win(d?.five_hour?.utilization, d?.five_hour?.resets_at), week: win(d?.seven_day?.utilization, d?.seven_day?.resets_at) };
|
|
53
|
+
} catch (e) {
|
|
54
|
+
// The message is the fetch's own; scrub the token in case a client ever echoes it.
|
|
55
|
+
return { agent: "claude", error: String((e as Error)?.name === "TimeoutError" ? "timed out" : (e as Error)?.message ?? e).split(token).join("…") };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Phones on the tailnet from `tailscale status --json`: iOS and Android peers.
|
|
60
|
+
export function phonePeers(json: string): { running: boolean; phones: { name: string; online: boolean }[] } {
|
|
61
|
+
try {
|
|
62
|
+
const s = JSON.parse(json);
|
|
63
|
+
const phones = Object.values<any>(s?.Peer ?? {}).filter((p) => /^(ios|android)$/i.test(p?.OS ?? "")).map((p) => ({ name: String(p.HostName ?? p.DNSName ?? ""), online: !!p.Online }));
|
|
64
|
+
return { running: s?.BackendState === "Running", phones };
|
|
65
|
+
} catch { return { running: false, phones: [] }; }
|
|
66
|
+
}
|
package/cli/web.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// `kaizen web`: the board in a browser. A loopback HTTP server over state.ts and
|
|
2
2
|
// one HTML page; the page never sees the filesystem, only JSON.
|
|
3
|
-
import { existsSync, readdirSync, statSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
|
|
3
|
+
import { existsSync, readdirSync, statSync, lstatSync, realpathSync, readFileSync, watch, appendFileSync, mkdirSync, cpSync, rmSync, writeFileSync, type FSWatcher } from "node:fs";
|
|
4
4
|
import { join, dirname, resolve, sep, basename } from "node:path";
|
|
5
5
|
import {
|
|
6
6
|
home, type Item, type Card, boardCards, knownProjects, remember, locate, label, tilde, searchRoots, findProjects,
|
|
@@ -9,7 +9,8 @@ import {
|
|
|
9
9
|
reviewFindings, pickFindings, backlogCards, backlogItem, startedBacklog, closeBacklog, markBacklogDone, fixPrompt, approvalPrompt, canApproveAwaiting, nativePath, closeSessions, sweepSessions, issueUrl,
|
|
10
10
|
launchMode, readSessions, ownerOf, runIndex, resumePrompt, runAgent, firstSession, webHosts,
|
|
11
11
|
} from "./state.ts";
|
|
12
|
-
import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv } from "./pty.ts";
|
|
12
|
+
import { attachPty, writePty, resizePty, exitPty, ptyState, ptyKeys, adoptLoginEnv, startPty, ptySupported } from "./pty.ts";
|
|
13
|
+
import { claudeUsage, codexUsage, phonePeers, type Usage } from "./usage.ts";
|
|
13
14
|
import { readSources, addSource, removeSource, moveSource, setCategory, setWriteback, setPaused, readIcebox, promote, dismiss, restore, addItem, githubRepo, markDone, markReplied, gatherSource, freshImages, gatherAll, gatherDirs, due, socialUrl, socialOf } from "./sources.ts";
|
|
14
15
|
import { projectLogo, LOGO_TYPES } from "./logo.ts";
|
|
15
16
|
import * as chatgpt from "./chatgpt.ts";
|
|
@@ -209,10 +210,26 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
209
210
|
const json = (body: unknown, status = 200) =>
|
|
210
211
|
new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
|
|
211
212
|
const bad = (why: string, status = 400) => json({ error: why }, status);
|
|
213
|
+
// Stricter than local(), for routes that start a process: another local server's page
|
|
214
|
+
// (the dev server a localhost tab frames) shares the hostname, so the port must match
|
|
215
|
+
// too, and a JSON content type forces a preflight that a foreign page cannot pass.
|
|
216
|
+
const strict = (req: Request) => {
|
|
217
|
+
const origin = req.headers.get("origin");
|
|
218
|
+
let same = !origin;
|
|
219
|
+
try { if (origin) { const o = new URL(origin); same = o.host === req.headers.get("host") || extraHosts.has(o.hostname); } } catch { /* bad origin */ }
|
|
220
|
+
if (!same) return bad("cross-origin request refused", 403);
|
|
221
|
+
if (!/^application\/json\b/i.test(req.headers.get("content-type") ?? "")) return bad("json body expected", 415);
|
|
222
|
+
return null;
|
|
223
|
+
};
|
|
212
224
|
|
|
213
225
|
// Change notification: one SSE stream per open board, fed by fs.watch where it
|
|
214
226
|
// works and a slow poll where it does not.
|
|
215
227
|
const clients = new Set<ReadableStreamDefaultController>();
|
|
228
|
+
// Shells the board started (POST /shell), by /pty key; dead ones drop on the next /shells.
|
|
229
|
+
const shells = new Map<string, { key: string; dir: string; title: string; agent: string; run: string }>();
|
|
230
|
+
const SHELL_CAP = 8;
|
|
231
|
+
let usageCache: Usage[] = [];
|
|
232
|
+
let usageAt = 0;
|
|
216
233
|
let pending: ReturnType<typeof setTimeout> | null = null;
|
|
217
234
|
const changed = () => {
|
|
218
235
|
if (pending) return;
|
|
@@ -274,18 +291,25 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
274
291
|
const ptyOf = (cards: Card[]) => {
|
|
275
292
|
const live = new Set(ptyKeys());
|
|
276
293
|
if (!live.size) return () => undefined;
|
|
277
|
-
const runs = new Map<string, string>();
|
|
294
|
+
const runs = new Map<string, string[]>();
|
|
278
295
|
for (const d of new Set(cards.filter((c) => c.kind === "run").map((c) => c.state))) {
|
|
279
296
|
const ids = runIndex(d);
|
|
280
|
-
for (const s of readSessions(d))
|
|
297
|
+
for (const s of readSessions(d))
|
|
298
|
+
if (live.has(s.key)) {
|
|
299
|
+
const k = `${d}\0${ownerOf(d, s, ids)}`;
|
|
300
|
+
runs.set(k, [...(runs.get(k) ?? []), s.key]); // oldest first: the newest is the card's
|
|
301
|
+
}
|
|
281
302
|
}
|
|
282
303
|
return (c: Card) => {
|
|
283
|
-
const
|
|
284
|
-
|
|
304
|
+
const keys = c.kind === "run" ? runs.get(`${c.state}\0${c.id}`) ?? [] : [ideaPty.get(`${c.state}\0${c.text}`)].filter((k): k is string => !!k && live.has(k));
|
|
305
|
+
const key = keys.at(-1);
|
|
306
|
+
if (!key) return undefined;
|
|
285
307
|
const st = ptyState(key)!;
|
|
286
308
|
// A finished run's agent that has ended has nothing left to show or resume.
|
|
287
309
|
if (!st.alive && (c.status === "done" || c.status === "abandoned")) return undefined;
|
|
288
|
-
|
|
310
|
+
// Every agent session the run has had on this board, for the workspace's Agent tabs.
|
|
311
|
+
const all = keys.filter((k) => ptyState(k)?.alive || k === key);
|
|
312
|
+
return { key, alive: st.alive, asking: st.asking, all };
|
|
289
313
|
};
|
|
290
314
|
};
|
|
291
315
|
const watchers: FSWatcher[] = [];
|
|
@@ -596,6 +620,118 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
596
620
|
return json({ ok: exitPty(key) });
|
|
597
621
|
}
|
|
598
622
|
|
|
623
|
+
// A plain shell, or a bare Claude/Codex session, in a project folder: the run
|
|
624
|
+
// workspace's + menu. Code execution, so local() as for every write, a registered
|
|
625
|
+
// project, and an agent only from KNOWN_AGENTS: no argv ever comes from the page.
|
|
626
|
+
// Its keys (sh-…) are /pty keys, so /pty's exact-origin check covers the socket.
|
|
627
|
+
if (req.method === "POST" && path === "/shell") {
|
|
628
|
+
const refused = strict(req);
|
|
629
|
+
if (refused) return refused;
|
|
630
|
+
if (!ptySupported) return bad("terminals need a newer Bun", 501);
|
|
631
|
+
let body: any;
|
|
632
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
633
|
+
const dir = String(body.dir ?? "");
|
|
634
|
+
if (!states(true).includes(dir) || dir === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
635
|
+
let cmd: string[];
|
|
636
|
+
let agent = "";
|
|
637
|
+
// The run's own agent session, resumed here ("run:<dir>:<id>" names the run; the session
|
|
638
|
+
// id is read from that run's state.json, never taken from the page). Claude only: it is
|
|
639
|
+
// the agent whose session id runs record. Refused while that session is still running
|
|
640
|
+
// elsewhere, since two copies of one conversation overwrite each other's history.
|
|
641
|
+
const runKey = typeof body.run === "string" && body.run.length <= 300 ? body.run : "";
|
|
642
|
+
if (body.resume === true) {
|
|
643
|
+
const id = runKey.startsWith("run:" + dir + ":") ? runKey.slice(dir.length + 5) : "";
|
|
644
|
+
let st: any = {};
|
|
645
|
+
try { if (/^[\w-][\w.-]*$/.test(id) && !id.includes("..")) st = JSON.parse(readFileSync(join(dir, "runs", id, "state.json"), "utf8")); } catch {}
|
|
646
|
+
const sid = typeof st.session === "string" && /^[\w-]{8,80}$/.test(st.session) ? st.session : "";
|
|
647
|
+
if (!sid || (st.agent && st.agent !== "claude")) return bad("this run has no Claude session to resume", 404);
|
|
648
|
+
if (!onPath("claude")) return bad("claude is not installed", 400);
|
|
649
|
+
if ([...shells.values()].some((x) => x.run === runKey && x.agent === "claude" && ptyState(x.key)?.alive)) return bad("already open", 409);
|
|
650
|
+
// Live on this board already (an agent pty the run owns, idle or not): sessionLive's
|
|
651
|
+
// transcript-age check alone would miss it where there is no /proc.
|
|
652
|
+
const idx = runIndex(dir);
|
|
653
|
+
if (readSessions(dir).some((x) => ptyState(x.key)?.alive && ownerOf(dir, x, idx) === id)) return json({ live: true }, 409);
|
|
654
|
+
if (sessionLive(sid)) return json({ live: true }, 409);
|
|
655
|
+
agent = "claude";
|
|
656
|
+
cmd = ["claude", "--resume", sid];
|
|
657
|
+
} else if (body.agent != null) {
|
|
658
|
+
const a = KNOWN_AGENTS.find((k) => k.cmd === body.agent);
|
|
659
|
+
if (!a || !onPath(a.cmd)) return bad("unknown agent", 400);
|
|
660
|
+
agent = a.cmd;
|
|
661
|
+
cmd = [a.cmd];
|
|
662
|
+
} else cmd = process.platform === "win32" ? [powershellExe()] : [process.env.SHELL || "sh", "-l"];
|
|
663
|
+
for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
|
|
664
|
+
if ([...shells.values()].filter((x) => x.dir === dir).length >= SHELL_CAP) return bad(`at most ${SHELL_CAP} terminals per project: close one first`, 429);
|
|
665
|
+
const key = "sh-" + crypto.randomUUID().slice(0, 8);
|
|
666
|
+
const title = agent ? KNOWN_AGENTS.find((k) => k.cmd === agent)!.name : "shell";
|
|
667
|
+
startPty(key, cmd, projectOf(dir), undefined, changed);
|
|
668
|
+
// The run workspace that opened it (its card key), so each run keeps its own centre.
|
|
669
|
+
shells.set(key, { key, dir, title, agent, run: runKey });
|
|
670
|
+
changed();
|
|
671
|
+
return json(shells.get(key));
|
|
672
|
+
}
|
|
673
|
+
if (req.method === "GET" && path === "/shells") {
|
|
674
|
+
const dir = url.searchParams.get("dir");
|
|
675
|
+
for (const k of shells.keys()) if (!ptyState(k)?.alive) shells.delete(k);
|
|
676
|
+
return json([...shells.values()].filter((s) => !dir || s.dir === dir));
|
|
677
|
+
}
|
|
678
|
+
// The localhost tab's "Open in browser": a Chromium app window on this computer, for
|
|
679
|
+
// sites that refuse to be framed. Launches a process, so /shell's guards, and only an
|
|
680
|
+
// http(s) address, passed as one --app= argument, never a shell string.
|
|
681
|
+
if (req.method === "POST" && path === "/open-url") {
|
|
682
|
+
const refused = strict(req);
|
|
683
|
+
if (refused) return refused;
|
|
684
|
+
let body: any;
|
|
685
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
686
|
+
let u: URL;
|
|
687
|
+
try { u = new URL(String(body.url ?? "")); } catch { return bad("not a url"); }
|
|
688
|
+
if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
|
|
689
|
+
return json({ ok: await openApp(u.href, join(home, ".kaizen", "app-window")) });
|
|
690
|
+
}
|
|
691
|
+
// Whether a page may be framed: X-Frame-Options or a CSP frame-ancestors that is not
|
|
692
|
+
// "*" says no. The browser hides that behind its own error page, so the localhost tab
|
|
693
|
+
// asks here first. Board pages only (it fetches on the user's behalf); the answer is
|
|
694
|
+
// one boolean, never the page; unknown (unreachable, timeout) counts as frameable.
|
|
695
|
+
if (req.method === "GET" && path === "/frameable") {
|
|
696
|
+
if (!local(req)) return bad("cross-origin request refused", 403);
|
|
697
|
+
let u: URL;
|
|
698
|
+
try { u = new URL(url.searchParams.get("url") ?? ""); } catch { return bad("not a url"); }
|
|
699
|
+
if (!/^https?:$/.test(u.protocol)) return bad("only an http(s) address", 400);
|
|
700
|
+
try {
|
|
701
|
+
const r = await fetch(u.href, { redirect: "follow", signal: AbortSignal.timeout(4000) });
|
|
702
|
+
r.body?.cancel().catch(() => {});
|
|
703
|
+
const xfo = (r.headers.get("x-frame-options") ?? "").trim();
|
|
704
|
+
const fa = /frame-ancestors([^;]*)/i.exec(r.headers.get("content-security-policy") ?? "")?.[1].trim() ?? "";
|
|
705
|
+
return json({ frameable: !xfo && (!fa || fa.split(/\s+/).includes("*")) });
|
|
706
|
+
} catch { return json({ frameable: null }); }
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// The footer: each installed agent's plan usage (cached a minute, ?refresh=1 asks
|
|
710
|
+
// again) and whether a phone is on the tailnet.
|
|
711
|
+
if (req.method === "GET" && path === "/usage") {
|
|
712
|
+
// A forced refresh only from the board's own pages, and not more than every 5 s: each one is a call with the user's token.
|
|
713
|
+
const force = url.searchParams.has("refresh") && local(req) && Date.now() - usageAt > 5_000;
|
|
714
|
+
if (force || Date.now() - usageAt > 60_000) {
|
|
715
|
+
const out: Usage[] = [];
|
|
716
|
+
if (onPath("claude")) { const u = await claudeUsage(home); if (u) out.push(u); }
|
|
717
|
+
if (onPath("codex")) { const u = codexUsage(home); if (u) out.push(u); }
|
|
718
|
+
usageCache = out;
|
|
719
|
+
usageAt = Date.now();
|
|
720
|
+
}
|
|
721
|
+
return json(usageCache);
|
|
722
|
+
}
|
|
723
|
+
if (req.method === "GET" && path === "/phone") {
|
|
724
|
+
// Async: a hung tailscale must not stall every terminal socket on this event loop.
|
|
725
|
+
let out = "";
|
|
726
|
+
try {
|
|
727
|
+
const p = Bun.spawn(["tailscale", "status", "--json"], { stdout: "pipe", stderr: "ignore", timeout: 5000 });
|
|
728
|
+
out = await new Response(p.stdout).text();
|
|
729
|
+
await p.exited;
|
|
730
|
+
} catch { return json({ tailscale: false }); }
|
|
731
|
+
const r = phonePeers(out);
|
|
732
|
+
return json({ tailscale: r.running, phones: r.phones.length, online: r.phones.some((x) => x.online) });
|
|
733
|
+
}
|
|
734
|
+
|
|
599
735
|
// Every note of one project, text included: search, tags and backlinks are the page's.
|
|
600
736
|
if (req.method === "GET" && path === "/vault") {
|
|
601
737
|
const dir = url.searchParams.get("dir") ?? state ?? join(home, ".kaizen");
|
|
@@ -603,6 +739,37 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
603
739
|
return json({ dir, notes: listNotes(dir) });
|
|
604
740
|
}
|
|
605
741
|
|
|
742
|
+
if (req.method === "GET" && (path === "/project-tree" || path === "/project-text")) {
|
|
743
|
+
const treeState = url.searchParams.get("dir") ?? state;
|
|
744
|
+
if (!treeState || !states(true).includes(treeState) || treeState === join(home, ".kaizen")) return bad("choose a project", 404);
|
|
745
|
+
const rel = url.searchParams.get("path") ?? "";
|
|
746
|
+
const parts = rel ? rel.split("/") : [];
|
|
747
|
+
if (rel.includes("\\") || rel.startsWith("/") || /^[A-Za-z]:/.test(rel) || parts.some((part) => !part || part === "." || part === ".." || part.startsWith("."))) return bad("invalid path", 400);
|
|
748
|
+
const root = realpathSync(projectOf(treeState));
|
|
749
|
+
let file = root;
|
|
750
|
+
try {
|
|
751
|
+
for (const part of parts) {
|
|
752
|
+
file = join(file, part);
|
|
753
|
+
if (lstatSync(file).isSymbolicLink()) return bad("symlinks are unavailable", 403);
|
|
754
|
+
}
|
|
755
|
+
const actual = realpathSync(file);
|
|
756
|
+
if (actual !== root && !actual.startsWith(root + sep)) return bad("outside project", 403);
|
|
757
|
+
if (path === "/project-tree") {
|
|
758
|
+
if (!statSync(file).isDirectory()) return bad("not a folder", 400);
|
|
759
|
+
const skip = new Set(["node_modules", "dist", "build", "coverage", "target", "vendor", ".git", ".kaizen"]);
|
|
760
|
+
const entries = readdirSync(file, { withFileTypes: true }).filter((e) => !e.name.startsWith(".") && !skip.has(e.name) && !e.isSymbolicLink() && (e.isDirectory() || e.isFile())).sort((a, b) => Number(b.isDirectory()) - Number(a.isDirectory()) || a.name.localeCompare(b.name)).slice(0, 200).map((e) => ({ name: e.name, dir: e.isDirectory() }));
|
|
761
|
+
return json({ path: rel, entries });
|
|
762
|
+
}
|
|
763
|
+
const info = statSync(file);
|
|
764
|
+
if (!info.isFile() || info.size > 65536) return bad("file is unavailable or too large", 415);
|
|
765
|
+
const bytes = readFileSync(file);
|
|
766
|
+
if (bytes.includes(0)) return bad("binary file is unavailable", 415);
|
|
767
|
+
const content = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
|
|
768
|
+
if (url.searchParams.has("download")) return new Response(content, { headers: { "content-type": "text/plain; charset=utf-8", "content-disposition": `attachment; filename*=UTF-8''${encodeURIComponent(basename(file))}`, "x-content-type-options": "nosniff" } });
|
|
769
|
+
return json({ path: rel, content });
|
|
770
|
+
} catch { return bad("file not found", 404); }
|
|
771
|
+
}
|
|
772
|
+
|
|
606
773
|
// What a note can link to on this project's board: runs, findings, backlog, ideas.
|
|
607
774
|
if (req.method === "GET" && path === "/links") {
|
|
608
775
|
const dir = url.searchParams.get("dir") ?? state ?? join(home, ".kaizen");
|
|
@@ -741,6 +908,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
741
908
|
if (req.method === "GET" && path === "/settings") {
|
|
742
909
|
const { listSettings } = await import("./settings.ts");
|
|
743
910
|
const cfg = listSettings(repoDir);
|
|
911
|
+
Object.assign(cfg, { phoneUrls: [...webHosts()].filter((h) => /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.ts\.net$/.test(h)).map((h) => `https://${h}`) });
|
|
744
912
|
// Connected, the model is chosen from what the plan offers rather than typed.
|
|
745
913
|
const m = cfg.rows.find((r) => r.key === "sources.model");
|
|
746
914
|
if (m && chatgpt.status().connected) {
|
|
@@ -1518,6 +1686,25 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1518
1686
|
// which is as close to a desktop app as a web page gets. Anything else gets a tab.
|
|
1519
1687
|
// A profile folder gives the window a browser instance of its own (Kaizen Bot's app);
|
|
1520
1688
|
// on macOS that takes -n, as `open` otherwise hands the args to a running browser.
|
|
1689
|
+
// Whether a Claude Code session is running somewhere: a process whose command line names
|
|
1690
|
+
// it (Linux /proc), or its transcript written in the last 90 s (every platform).
|
|
1691
|
+
export function sessionLive(id: string): boolean {
|
|
1692
|
+
try {
|
|
1693
|
+
for (const pid of readdirSync("/proc")) {
|
|
1694
|
+
if (!/^\d+$/.test(pid)) continue;
|
|
1695
|
+
try { if (readFileSync(`/proc/${pid}/cmdline`, "utf8").split("\0").includes(id)) return true; } catch {}
|
|
1696
|
+
}
|
|
1697
|
+
} catch { /* no /proc */ }
|
|
1698
|
+
try {
|
|
1699
|
+
const root = join(home, ".claude", "projects");
|
|
1700
|
+
for (const d of readdirSync(root)) {
|
|
1701
|
+
const f = join(root, d, id + ".jsonl");
|
|
1702
|
+
if (existsSync(f) && Date.now() - statSync(f).mtimeMs < 90_000) return true;
|
|
1703
|
+
}
|
|
1704
|
+
} catch {}
|
|
1705
|
+
return false;
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1521
1708
|
export async function openApp(url: string, profile?: string) {
|
|
1522
1709
|
// Kaizen Bot's window (a profile) is always an app; the board asks the setting.
|
|
1523
1710
|
if (!profile) {
|
package/package.json
CHANGED
package/skills/kaizen/SKILL.md
CHANGED
|
@@ -51,7 +51,7 @@ Porting the workflow to Codex or Antigravity is covered in [`adapters.md`](adapt
|
|
|
51
51
|
| `/kaizen gather` | Read the request sources kaizen cannot read by itself and hand their requests over to the icebox |
|
|
52
52
|
| `/kaizen discover` | Read the icebox, group what was gathered, propose ideas, and promote the ones the user picks |
|
|
53
53
|
| `/kaizen docs` | Write this project's documentation into the notebook as a vault agents read first, or bring it up to date |
|
|
54
|
-
| `/kaizen docs lint` |
|
|
54
|
+
| `/kaizen docs lint` | Run the read-only `kaizen docs lint` CLI command; report broken links, missing sources and stale notes |
|
|
55
55
|
| `/kaizen approve` | Approve whatever the current run is waiting on |
|
|
56
56
|
| `/kaizen reject <reason>` | Reject it; the reason is fed back to the stage that produced it |
|
|
57
57
|
| `/kaizen abort` | Mark the current run abandoned |
|
package/skills/kaizen/docs.md
CHANGED
|
@@ -27,7 +27,7 @@ inside a project note: that section is theirs, and it is never rewritten.
|
|
|
27
27
|
|
|
28
28
|
- No `Project/Index.md`: **build**.
|
|
29
29
|
- `Project/Index.md` exists: **update**.
|
|
30
|
-
- `/kaizen docs lint`:
|
|
30
|
+
- `/kaizen docs lint`: run the read-only CLI command `kaizen docs lint`; nothing written.
|
|
31
31
|
|
|
32
32
|
Build and update both end with lint.
|
|
33
33
|
|
|
@@ -134,6 +134,11 @@ updated: YYYY-MM-DD
|
|
|
134
134
|
|
|
135
135
|
## Lint
|
|
136
136
|
|
|
137
|
+
Run `kaizen docs lint` from the project or any directory under it. It reports each
|
|
138
|
+
finding and exits 1 when any are present; a clean vault exits 0. Without a vault it
|
|
139
|
+
exits 1 and says to run `/kaizen docs` first. The Docs gate skips lint when no vault
|
|
140
|
+
exists, as `spec-main.md` says.
|
|
141
|
+
|
|
137
142
|
Checks, reported and not silently fixed:
|
|
138
143
|
|
|
139
144
|
- every `[[link]]` in `Project/` resolves to a note in it (`[[run:<id>]]` links point
|
|
@@ -121,8 +121,10 @@ note covers.
|
|
|
121
121
|
area, write a note for it as step 4 of *Update* in [`docs.md`](docs.md) says and
|
|
122
122
|
list it in `Index.md`. A path that is not part of the project's material — a lock
|
|
123
123
|
file, a generated bundle — needs no note.
|
|
124
|
-
4. **Lint
|
|
125
|
-
this run
|
|
124
|
+
4. **Lint:** run `kaizen docs lint` from the project or worktree. It checks the whole
|
|
125
|
+
vault and exits nonzero on findings. Fix findings this run introduced before the
|
|
126
|
+
final report, and report any pre-existing findings with the command output. Run it
|
|
127
|
+
again after any later fix round before setting `stage: "done"`.
|
|
126
128
|
|
|
127
129
|
Name the notes touched in the final report; the commit at done includes them. A run
|
|
128
130
|
whose changes leave every note true touches nothing and says so in one line.
|
package/web/board/api.ts
CHANGED
|
@@ -4,6 +4,7 @@ import { $, vt } from "./dom.ts";
|
|
|
4
4
|
import { close, ideaBody, open, openRun } from "./panel.ts";
|
|
5
5
|
import { notifyUser, toast } from "./toast.ts";
|
|
6
6
|
import { openTerms, termsShowing } from "./terms.ts";
|
|
7
|
+
import { refreshBoardBadge } from "./badge.ts";
|
|
7
8
|
|
|
8
9
|
// The server writes notifier() from state.ts over a marker in board.html: one rule for both UIs.
|
|
9
10
|
declare const due: (key: string, say: string | null, done: boolean, now: number) => boolean;
|
|
@@ -30,6 +31,7 @@ export async function load(quiet) {
|
|
|
30
31
|
}
|
|
31
32
|
const was = store.openKey && store.S.cards.find((x) => key(x) === store.openKey);
|
|
32
33
|
store.S = await r.json();
|
|
34
|
+
if (!store.all) void refreshBoardBadge();
|
|
33
35
|
// Home follows a project switch without the board importing it.
|
|
34
36
|
dispatchEvent(new Event("kz-state"));
|
|
35
37
|
{
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
type BadgeCard = { archived?: boolean; kind: string; status: string; pty?: { alive: boolean; asking: boolean } };
|
|
2
|
+
|
|
3
|
+
export function waitingCount(cards: BadgeCard[]) {
|
|
4
|
+
return cards.filter((c) => !c.archived && ((c.kind === "run" && c.status === "waiting") || (c.pty?.alive && c.pty.asking))).length;
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
// The rail's Projects list draws from the same cards: one fetch feeds both.
|
|
8
|
+
let onCards: ((cards: any[], projects?: any[]) => void) | null = null;
|
|
9
|
+
export const onBoardCards = (f: typeof onCards) => { onCards = f; };
|
|
10
|
+
|
|
11
|
+
export function boardBadge(cards: BadgeCard[], projects?: unknown[]) {
|
|
12
|
+
generation++;
|
|
13
|
+
onCards?.(cards, projects);
|
|
14
|
+
// The waiting-on-you count sits on Ideas, the page that lists every run and idea.
|
|
15
|
+
const a = document.querySelector<HTMLElement>('.rail a[data-view="ideas"]');
|
|
16
|
+
if (!a) return;
|
|
17
|
+
const n = waitingCount(cards);
|
|
18
|
+
if (n) a.dataset.n = String(n);
|
|
19
|
+
else delete a.dataset.n;
|
|
20
|
+
a.title = n ? `Ideas: ${n} waiting on you` : "Ideas: every idea and run, filtered";
|
|
21
|
+
a.setAttribute("aria-label", a.title);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
let generation = 0;
|
|
25
|
+
let loading = false;
|
|
26
|
+
let again = false;
|
|
27
|
+
export async function refreshBoardBadge() {
|
|
28
|
+
if (loading) { again = true; return; }
|
|
29
|
+
loading = true;
|
|
30
|
+
do {
|
|
31
|
+
again = false;
|
|
32
|
+
const current = generation;
|
|
33
|
+
try {
|
|
34
|
+
const r = await fetch("/state?all=1");
|
|
35
|
+
if (!r.ok) continue;
|
|
36
|
+
const { cards, projects } = await r.json();
|
|
37
|
+
if (!again && current === generation) boardBadge(cards, projects);
|
|
38
|
+
} catch { /* keep the last count while the board is offline */ }
|
|
39
|
+
} while (again);
|
|
40
|
+
loading = false;
|
|
41
|
+
}
|