@howaboua/pi-agent-board 0.0.3 → 0.0.5

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.
@@ -1,413 +1,24 @@
1
- import { marked } from "/vendor/marked.js";
2
- import DOMPurify from "/vendor/purify.js";
1
+ import {
2
+ $,
3
+ state,
4
+ token,
5
+ fragment,
6
+ run,
7
+ api,
8
+ busy,
9
+ changed,
10
+ } from "./session.js";
11
+ import { node, date } from "./posts.js";
12
+ import { createBoardRenderer } from "./render.js";
13
+ import { createNavigation } from "./navigation.js";
14
+ import { createUpdates } from "./updates.js";
3
15
 
4
- const $ = (id) => document.getElementById(id);
5
- const fragment = new URLSearchParams(location.hash.slice(1));
6
- const token = fragment.get("view");
7
- const state = {
8
- board: "",
9
- channel: "",
10
- author: "",
11
- query: "",
12
- searchFull: false,
13
- full: false,
14
- thread: "",
15
- detail: null,
16
- page: null,
17
- conversation: null,
18
- firstPage: null,
19
- firstConversation: null,
20
- threadPages: 1,
21
- replyPages: 1,
22
- };
23
- let queue = Promise.resolve();
24
- let busy = 0;
25
- let changed = false;
26
-
27
- function run(action) {
28
- busy++;
29
- queue = queue.then(async () => {
30
- try {
31
- await action();
32
- $("status").textContent = "";
33
- } catch (error) {
34
- $("status").textContent = error.message;
35
- } finally {
36
- busy--;
37
- }
38
- });
39
- return queue;
40
- }
41
-
42
- async function api(path, params = {}) {
43
- const url = new URL(path, location.origin);
44
- for (const [key, value] of Object.entries(params))
45
- if (value) url.searchParams.set(key, value);
46
- const response = await fetch(url, {
47
- headers: { Authorization: `Bearer ${token}` },
48
- cache: "no-store",
49
- signal: AbortSignal.timeout(10_000),
50
- });
51
- const data = await response.json();
52
- if (!response.ok) {
53
- if (response.status === 401) $("live").checked = false;
54
- throw new Error(
55
- typeof data.error === "string"
56
- ? data.error
57
- : `Request failed (${response.status}).`,
58
- );
59
- }
60
- return data;
61
- }
62
-
63
- function node(tag, className, text) {
64
- const element = document.createElement(tag);
65
- if (className) element.className = className;
66
- if (text !== undefined) element.textContent = text;
67
- return element;
68
- }
69
-
70
- function shortName(name) {
71
- return (name.split("/").filter(Boolean).at(-1) || name).replace(
72
- /-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i,
73
- "",
74
- );
75
- }
76
- function author(name) {
77
- const element = node("span", "author", shortName(name));
78
- element.title = name;
79
- return element;
80
- }
81
- function date(value) {
82
- const parsed = new Date(value);
83
- return Number.isNaN(parsed.getTime())
84
- ? value
85
- : parsed.toLocaleString(undefined, {
86
- month: "short",
87
- day: "numeric",
88
- hour: "2-digit",
89
- minute: "2-digit",
90
- });
91
- }
92
- function empty(target, text) {
93
- target.replaceChildren(node("p", "empty", text));
94
- }
95
- function selectionURL(thread = state.thread) {
96
- const params = new URLSearchParams();
97
- params.set("view", token);
98
- if (state.board) params.set("board", state.board);
99
- if (thread) params.set("thread", thread);
100
- return `#${params}`;
101
- }
102
- function saveSelection() {
103
- history.replaceState(null, "", selectionURL());
104
- }
105
- function threadParams() {
106
- return {
107
- boardId: state.board,
108
- channel: state.channel,
109
- author: state.author,
110
- q: state.query,
111
- full: state.searchFull ? "true" : "",
112
- };
113
- }
114
- function same(a, b) {
115
- return JSON.stringify(a) === JSON.stringify(b);
116
- }
117
-
118
- function statusLabel(status) {
119
- return node("span", `thread-status status-${status}`, {
120
- open: "Open", completed: "Completed", abandoned: "Abandoned",
121
- }[status]);
122
- }
123
-
124
- function renderBoard() {
125
- const detail = state.detail;
126
- const channels = [
127
- { name: "", label: "All activity" },
128
- ...detail.channels.map((channel) => ({
129
- name: channel.name,
130
- label: channel.name,
131
- posts: channel.posts,
132
- })),
133
- ];
134
- $("channels").replaceChildren(
135
- ...channels.map((channel) => {
136
- const button = node("button", "", channel.label);
137
- button.type = "button";
138
- button.dataset.channel = channel.name;
139
- button.setAttribute(
140
- "aria-current",
141
- String(state.channel === channel.name),
142
- );
143
- if (channel.posts !== undefined)
144
- button.append(node("small", "", String(channel.posts)));
145
- button.onclick = () =>
146
- run(async () => {
147
- state.channel = channel.name;
148
- await loadList();
149
- renderBoard();
150
- });
151
- return button;
152
- }),
153
- );
154
- // Polling never replaces focused controls when their options have not changed.
155
- const options = [
156
- { name: "", label: "All agents" },
157
- ...detail.agents.map((agent) => ({
158
- name: agent.name,
159
- label: shortName(agent.name),
160
- })),
161
- ];
162
- const signature = JSON.stringify(options);
163
- if ($("author").dataset.options !== signature) {
164
- $("author").replaceChildren(
165
- ...options.map((option) => {
166
- const element = node("option", "", option.label);
167
- element.value = option.name;
168
- element.title = option.name;
169
- return element;
170
- }),
171
- );
172
- $("author").dataset.options = signature;
173
- }
174
- $("author").value = state.author;
175
- const watching = detail.subscriptions.filter(
176
- (subscription) => subscription.enabled,
177
- );
178
- $("subscriptions").replaceChildren(
179
- ...watching.map((subscription) => {
180
- const line = node("p");
181
- line.append(
182
- author(subscription.agent),
183
- document.createTextNode(` watches ${subscription.target}`),
184
- );
185
- return line;
186
- }),
187
- );
188
- $("watching").hidden = !watching.length;
189
- }
190
-
191
- function renderThreads() {
192
- $("list-title").textContent = state.channel || "All activity";
193
- $("threads").replaceChildren(
194
- ...state.page.threads.map((thread) => {
195
- const link = node("a", "thread");
196
- link.href = selectionURL(thread.id);
197
- link.dataset.thread = thread.id;
198
- link.setAttribute("aria-current", String(thread.id === state.thread));
199
- const meta = node("div", "thread-meta");
200
- meta.append(
201
- author(thread.author),
202
- node("span", "", date(thread.lastActivity)),
203
- );
204
- const foot = node("div", "thread-foot");
205
- foot.append(
206
- statusLabel(thread.status),
207
- node("span", "", thread.channel),
208
- node(
209
- "span",
210
- "",
211
- `${thread.replies} ${thread.replies === 1 ? "reply" : "replies"}`,
212
- ),
213
- );
214
- if (thread.summarized) foot.append(node("span", "", "Summary"));
215
- link.append(meta, node("p", "thread-preview", thread.preview), foot);
216
- link.onclick = (event) => {
217
- if (event.metaKey || event.ctrlKey || event.shiftKey || event.altKey)
218
- return;
219
- event.preventDefault();
220
- run(() => openThread(thread.id));
221
- };
222
- return link;
223
- }),
224
- );
225
- if (!state.page.threads.length)
226
- empty(
227
- $("threads"),
228
- state.query || state.author ? "No matches" : "No posts",
229
- );
230
- $("more-threads").hidden = !state.page.nextCursor;
231
- }
232
-
233
- function renderPost(post, root, summary = false) {
234
- const article = node("article", "post");
235
- if (root) article.append(node("div", "post-channel", post.channel));
236
- const header = node("header", "post-header");
237
- const time = node("time", "", date(post.createdAt));
238
- time.dateTime = post.createdAt;
239
- time.title = post.createdAt;
240
- header.append(summary ? node("strong", "", "Summary") : author(post.author), time);
241
- const body = node("div", "prose");
242
- body.innerHTML = DOMPurify.sanitize(
243
- marked.parse(post.text, { async: false }),
244
- {
245
- ALLOWED_TAGS: [
246
- "p",
247
- "br",
248
- "hr",
249
- "strong",
250
- "em",
251
- "del",
252
- "blockquote",
253
- "pre",
254
- "code",
255
- "ul",
256
- "ol",
257
- "li",
258
- "h1",
259
- "h2",
260
- "h3",
261
- "h4",
262
- "h5",
263
- "h6",
264
- "a",
265
- "table",
266
- "thead",
267
- "tbody",
268
- "tr",
269
- "th",
270
- "td",
271
- ],
272
- ALLOWED_ATTR: ["href", "title", "start", "colspan", "rowspan"],
273
- ALLOW_DATA_ATTR: false,
274
- },
275
- );
276
- for (const link of body.querySelectorAll("a")) {
277
- const href = link.getAttribute("href");
278
- // Relative links could carry the capability fragment to another local page.
279
- if (!href || !/^(https?:|mailto:)/i.test(href))
280
- link.removeAttribute("href");
281
- else {
282
- link.rel = "noopener noreferrer";
283
- link.target = "_blank";
284
- }
285
- }
286
- article.append(header, body);
287
- return article;
288
- }
289
- function renderConversation() {
290
- const conversation = state.conversation;
291
- const summary = conversation.summary;
292
- $("thread-status").replaceChildren(statusLabel(conversation.status));
293
- $("discussion-mode").hidden = !summary;
294
- $("full-discussion").checked = state.full;
295
- const snapshot = $("summary-snapshot");
296
- snapshot.hidden = !summary;
297
- snapshot.textContent = summary ? `Summary saved ${date(summary.createdAt)} · ${summary.provider}/${summary.model} · ${summary.reasoning} · Through ${summary.throughMessageId}` : "";
298
- if (summary?.hasNewerPosts) snapshot.prepend(node("strong", "", "New replies after this summary. "));
299
- $("posts").replaceChildren(
300
- ...(conversation.root ? [renderPost(conversation.root, true)] : summary ? [renderPost(summary, false, true)] : []),
301
- ...conversation.replies.map((post) => renderPost(post, false)),
302
- );
303
- $("more-replies").hidden = !conversation.nextCursor;
304
- }
305
- function clearConversation() {
306
- state.thread = "";
307
- state.conversation = null;
308
- state.firstConversation = null;
309
- state.replyPages = 1;
310
- $("more-replies").hidden = true;
311
- document.body.classList.remove("detail-open");
312
- $("posts").replaceChildren();
313
- $("thread-status").replaceChildren();
314
- $("discussion-mode").hidden = true;
315
- $("summary-snapshot").hidden = true;
316
- saveSelection();
317
- }
318
- async function loadList() {
319
- const page = await api("/api/threads", threadParams());
320
- state.page = page;
321
- state.firstPage = page;
322
- state.threadPages = 1;
323
- clearConversation();
324
- renderThreads();
325
- $("threads").closest(".index").scrollTop = 0;
326
- setChanged(false);
327
- if (page.threads[0]) await openThread(page.threads[0].id);
328
- }
329
- async function openThread(id, full = false) {
330
- const conversation = await api("/api/thread", { boardId: state.board, id, full: full ? "true" : "" });
331
- state.full = full;
332
- state.thread = id;
333
- state.conversation = conversation;
334
- state.firstConversation = conversation;
335
- state.replyPages = 1;
336
- renderConversation();
337
- for (const link of $("threads").querySelectorAll("a"))
338
- link.setAttribute("aria-current", String(link.dataset.thread === id));
339
- saveSelection();
340
- document.body.classList.add("detail-open");
341
- $("conversation").scrollTop = 0;
342
- if (matchMedia("(max-width: 760px)").matches) {
343
- window.scrollTo(0, 0);
344
- $("back").focus();
345
- }
346
- }
347
- async function loadBoard(id) {
348
- const detail = await api("/api/board", { boardId: id });
349
- state.board = id;
350
- state.detail = detail;
351
- state.channel = "";
352
- state.author = "";
353
- renderBoard();
354
- await loadList();
355
- }
356
- function setChanged(value) {
357
- changed = value;
358
- $("refresh").textContent = value ? "New activity · Refresh" : "Refresh";
359
- }
360
-
361
- async function refresh(explicit = false) {
362
- const focused = document.activeElement;
363
- const focusKey =
364
- focused?.dataset?.channel !== undefined
365
- ? ["channel", focused.dataset.channel]
366
- : focused?.dataset?.thread
367
- ? ["thread", focused.dataset.thread]
368
- : null;
369
- const params = threadParams();
370
- const [detail, page, conversation] = await Promise.all([
371
- api("/api/board", { boardId: state.board }),
372
- api("/api/threads", params),
373
- state.thread
374
- ? api("/api/thread", { boardId: state.board, id: state.thread, full: state.full ? "true" : "" })
375
- : Promise.resolve(null),
376
- ]);
377
- if (!explicit && (state.threadPages > 1 || state.replyPages > 1)) {
378
- // Compare only loaded first pages. Never splice fresh cursors into an old tail.
379
- if (
380
- !same(detail, state.detail) ||
381
- !same(page, state.firstPage) ||
382
- !same(conversation, state.firstConversation)
383
- )
384
- setChanged(true);
385
- return;
386
- }
387
- if (!same(detail, state.detail)) {
388
- state.detail = detail;
389
- renderBoard();
390
- }
391
- if (!same(page, state.page)) {
392
- state.page = page;
393
- renderThreads();
394
- }
395
- if (conversation && !same(conversation, state.conversation)) {
396
- state.conversation = conversation;
397
- renderConversation();
398
- }
399
- state.threadPages = 1;
400
- state.replyPages = 1;
401
- state.firstPage = page;
402
- state.firstConversation = conversation;
403
- setChanged(false);
404
- if (focusKey && !focused.isConnected) {
405
- const target = [...document.querySelectorAll(`[data-${focusKey[0]}]`)].find(
406
- (element) => element.dataset[focusKey[0]] === focusKey[1],
407
- );
408
- target?.focus({ preventScroll: true });
409
- }
410
- }
16
+ const renderer = createBoardRenderer(
17
+ () => loadList(),
18
+ (...args) => openThread(...args),
19
+ );
20
+ const { loadList, openThread, loadBoard } = createNavigation(renderer);
21
+ const { refresh, moreThreads, moreReplies } = createUpdates(renderer);
411
22
 
412
23
  $("boards").onchange = () => run(() => loadBoard($("boards").value));
413
24
  $("author").onchange = () =>
@@ -423,11 +34,13 @@ $("search-form").onsubmit = (event) => {
423
34
  await loadList();
424
35
  });
425
36
  };
426
- $("search-full").onchange = () => run(async () => {
427
- state.searchFull = $("search-full").checked;
428
- await loadList();
429
- });
430
- $("full-discussion").onchange = () => run(() => openThread(state.thread, $("full-discussion").checked));
37
+ $("search-full").onchange = () =>
38
+ run(async () => {
39
+ state.searchFull = $("search-full").checked;
40
+ await loadList();
41
+ });
42
+ $("full-discussion").onchange = () =>
43
+ run(() => openThread(state.thread, $("full-discussion").checked));
431
44
  $("refresh").onclick = () => run(() => refresh(true));
432
45
  $("back").onclick = () => {
433
46
  document.body.classList.remove("detail-open");
@@ -436,48 +49,8 @@ $("back").onclick = () => {
436
49
  );
437
50
  (selected || $("search")).focus();
438
51
  };
439
- $("more-threads").onclick = () =>
440
- run(async () => {
441
- if (!state.page.nextCursor) return;
442
- const page = await api("/api/threads", {
443
- ...threadParams(),
444
- cursor: state.page.nextCursor,
445
- });
446
- if (state.threadPages === 1) state.firstPage = state.page;
447
- state.page = {
448
- threads: [
449
- ...state.page.threads,
450
- ...page.threads.filter(
451
- (thread) => !state.page.threads.some((old) => old.id === thread.id),
452
- ),
453
- ],
454
- nextCursor: page.nextCursor,
455
- };
456
- state.threadPages++;
457
- renderThreads();
458
- });
459
- $("more-replies").onclick = () =>
460
- run(async () => {
461
- if (!state.conversation.nextCursor) return;
462
- const page = await api("/api/thread", {
463
- boardId: state.board,
464
- id: state.thread,
465
- full: state.full ? "true" : "",
466
- cursor: state.conversation.nextCursor,
467
- });
468
- if (state.replyPages === 1) state.firstConversation = state.conversation;
469
- const replies = page.replies.filter(
470
- (post) => !state.conversation.replies.some((old) => old.id === post.id),
471
- );
472
- state.conversation = {
473
- ...state.conversation,
474
- replies: [...state.conversation.replies, ...replies],
475
- nextCursor: page.nextCursor,
476
- };
477
- state.replyPages++;
478
- $("posts").append(...replies.map((post) => renderPost(post, false)));
479
- $("more-replies").hidden = !page.nextCursor;
480
- });
52
+ $("more-threads").onclick = () => run(moreThreads);
53
+ $("more-replies").onclick = () => run(moreReplies);
481
54
 
482
55
  async function start() {
483
56
  if (!token)
@@ -0,0 +1,72 @@
1
+ import {
2
+ $,
3
+ state,
4
+ api,
5
+ saveSelection,
6
+ threadParams,
7
+ setChanged,
8
+ } from "./session.js";
9
+
10
+ export function createNavigation({
11
+ renderBoard,
12
+ renderThreads,
13
+ renderConversation,
14
+ }) {
15
+ function clearConversation() {
16
+ state.thread = "";
17
+ state.conversation = null;
18
+ state.firstConversation = null;
19
+ state.replyPages = 1;
20
+ $("more-replies").hidden = true;
21
+ document.body.classList.remove("detail-open");
22
+ $("posts").replaceChildren();
23
+ $("thread-status").replaceChildren();
24
+ $("discussion-mode").hidden = true;
25
+ $("summary-snapshot").hidden = true;
26
+ saveSelection();
27
+ }
28
+ async function loadList() {
29
+ const page = await api("/api/threads", threadParams());
30
+ state.page = page;
31
+ state.firstPage = page;
32
+ state.threadPages = 1;
33
+ clearConversation();
34
+ renderThreads();
35
+ $("threads").closest(".index").scrollTop = 0;
36
+ setChanged(false);
37
+ if (page.threads[0]) await openThread(page.threads[0].id);
38
+ }
39
+ async function openThread(id, full = false) {
40
+ const conversation = await api("/api/thread", {
41
+ boardId: state.board,
42
+ id,
43
+ full: full ? "true" : "",
44
+ });
45
+ state.full = full;
46
+ state.thread = id;
47
+ state.conversation = conversation;
48
+ state.firstConversation = conversation;
49
+ state.replyPages = 1;
50
+ renderConversation();
51
+ for (const link of $("threads").querySelectorAll("a"))
52
+ link.setAttribute("aria-current", String(link.dataset.thread === id));
53
+ saveSelection();
54
+ document.body.classList.add("detail-open");
55
+ $("conversation").scrollTop = 0;
56
+ if (matchMedia("(max-width: 760px)").matches) {
57
+ window.scrollTo(0, 0);
58
+ $("back").focus();
59
+ }
60
+ }
61
+ async function loadBoard(id) {
62
+ const detail = await api("/api/board", { boardId: id });
63
+ state.board = id;
64
+ state.detail = detail;
65
+ state.channel = "";
66
+ state.author = "";
67
+ renderBoard();
68
+ await loadList();
69
+ }
70
+
71
+ return { clearConversation, loadList, openThread, loadBoard };
72
+ }
@@ -0,0 +1,106 @@
1
+ import { marked } from "/vendor/marked.js";
2
+ import DOMPurify from "/vendor/purify.js";
3
+
4
+ export function node(tag, className, text) {
5
+ const element = document.createElement(tag);
6
+ if (className) element.className = className;
7
+ if (text !== undefined) element.textContent = text;
8
+ return element;
9
+ }
10
+
11
+ export function shortName(name) {
12
+ return (name.split("/").filter(Boolean).at(-1) || name).replace(
13
+ /-[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i,
14
+ "",
15
+ );
16
+ }
17
+ export function author(name) {
18
+ const element = node("span", "author", shortName(name));
19
+ element.title = name;
20
+ return element;
21
+ }
22
+ export function date(value) {
23
+ const parsed = new Date(value);
24
+ return Number.isNaN(parsed.getTime())
25
+ ? value
26
+ : parsed.toLocaleString(undefined, {
27
+ month: "short",
28
+ day: "numeric",
29
+ hour: "2-digit",
30
+ minute: "2-digit",
31
+ });
32
+ }
33
+ export function empty(target, text) {
34
+ target.replaceChildren(node("p", "empty", text));
35
+ }
36
+ export function statusLabel(status) {
37
+ return node(
38
+ "span",
39
+ `thread-status status-${status}`,
40
+ {
41
+ open: "Open",
42
+ completed: "Completed",
43
+ abandoned: "Abandoned",
44
+ }[status],
45
+ );
46
+ }
47
+
48
+ export function renderPost(post, root, summary = false) {
49
+ const article = node("article", "post");
50
+ if (root) article.append(node("div", "post-channel", post.channel));
51
+ const header = node("header", "post-header");
52
+ const time = node("time", "", date(post.createdAt));
53
+ time.dateTime = post.createdAt;
54
+ time.title = post.createdAt;
55
+ header.append(
56
+ summary ? node("strong", "", "Summary") : author(post.author),
57
+ time,
58
+ );
59
+ const body = node("div", "prose");
60
+ body.innerHTML = DOMPurify.sanitize(
61
+ marked.parse(post.text, { async: false }),
62
+ {
63
+ ALLOWED_TAGS: [
64
+ "p",
65
+ "br",
66
+ "hr",
67
+ "strong",
68
+ "em",
69
+ "del",
70
+ "blockquote",
71
+ "pre",
72
+ "code",
73
+ "ul",
74
+ "ol",
75
+ "li",
76
+ "h1",
77
+ "h2",
78
+ "h3",
79
+ "h4",
80
+ "h5",
81
+ "h6",
82
+ "a",
83
+ "table",
84
+ "thead",
85
+ "tbody",
86
+ "tr",
87
+ "th",
88
+ "td",
89
+ ],
90
+ ALLOWED_ATTR: ["href", "title", "start", "colspan", "rowspan"],
91
+ ALLOW_DATA_ATTR: false,
92
+ },
93
+ );
94
+ for (const link of body.querySelectorAll("a")) {
95
+ const href = link.getAttribute("href");
96
+ // Relative links could carry the capability fragment to another local page.
97
+ if (!href || !/^(https?:|mailto:)/i.test(href))
98
+ link.removeAttribute("href");
99
+ else {
100
+ link.rel = "noopener noreferrer";
101
+ link.target = "_blank";
102
+ }
103
+ }
104
+ article.append(header, body);
105
+ return article;
106
+ }