backlog-tiny-mcp 0.35.0__py3-none-any.whl

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.
Files changed (97) hide show
  1. backlog_mcp/__init__.py +29 -0
  2. backlog_mcp/__main__.py +10 -0
  3. backlog_mcp/auth.py +199 -0
  4. backlog_mcp/backlog.py +696 -0
  5. backlog_mcp/cli.py +2046 -0
  6. backlog_mcp/client.py +320 -0
  7. backlog_mcp/computer.py +33 -0
  8. backlog_mcp/database.py +80 -0
  9. backlog_mcp/embeddings.py +900 -0
  10. backlog_mcp/global_rules.md +126 -0
  11. backlog_mcp/guidance.py +11 -0
  12. backlog_mcp/guide/index.md +11 -0
  13. backlog_mcp/guide/memory.md +27 -0
  14. backlog_mcp/guide/projects.md +16 -0
  15. backlog_mcp/guide/search.md +72 -0
  16. backlog_mcp/guide/tasks.md +40 -0
  17. backlog_mcp/guide/workflow.md +22 -0
  18. backlog_mcp/httpd.py +270 -0
  19. backlog_mcp/migrate.py +113 -0
  20. backlog_mcp/migrations/0001-initial.sql +194 -0
  21. backlog_mcp/migrations/0002-task-assignment.sql +2 -0
  22. backlog_mcp/migrations/0003-task-edit-claims.sql +5 -0
  23. backlog_mcp/migrations/0004-memory-visibility.sql +42 -0
  24. backlog_mcp/model/CITATION.bib +9 -0
  25. backlog_mcp/model/LICENSE +202 -0
  26. backlog_mcp/model/README.md +12 -0
  27. backlog_mcp/model/UPSTREAM.md +2053 -0
  28. backlog_mcp/model/config.json +12 -0
  29. backlog_mcp/model/model.safetensors +4 -0
  30. backlog_mcp/model/modules.json +14 -0
  31. backlog_mcp/model/provenance.json +16 -0
  32. backlog_mcp/model/tokenizer.json +1 -0
  33. backlog_mcp/models.py +581 -0
  34. backlog_mcp/names.py +35 -0
  35. backlog_mcp/paths.py +53 -0
  36. backlog_mcp/protocol_storage.py +104 -0
  37. backlog_mcp/queries.py +7 -0
  38. backlog_mcp/queries.sql +531 -0
  39. backlog_mcp/records.py +215 -0
  40. backlog_mcp/render.py +479 -0
  41. backlog_mcp/server.py +2864 -0
  42. backlog_mcp/skills/autopilot/SKILL.md +96 -0
  43. backlog_mcp/skills/planning/SKILL.md +106 -0
  44. backlog_mcp/skills/planning/references/splitting.md +45 -0
  45. backlog_mcp/skills/triage/SKILL.md +104 -0
  46. backlog_mcp/skills/triage/references/conventions.md +43 -0
  47. backlog_mcp/skills.py +56 -0
  48. backlog_mcp/static/agent-config.js +20 -0
  49. backlog_mcp/static/app.css +1950 -0
  50. backlog_mcp/static/app.js +1301 -0
  51. backlog_mcp/static/assignments.js +96 -0
  52. backlog_mcp/static/breadcrumbs.js +54 -0
  53. backlog_mcp/static/comment-composer.js +95 -0
  54. backlog_mcp/static/connect.css +98 -0
  55. backlog_mcp/static/connect.html +74 -0
  56. backlog_mcp/static/connect.js +160 -0
  57. backlog_mcp/static/credentials.js +72 -0
  58. backlog_mcp/static/diagrams.js +128 -0
  59. backlog_mcp/static/dom.js +162 -0
  60. backlog_mcp/static/editor-claim.js +104 -0
  61. backlog_mcp/static/editor.js +355 -0
  62. backlog_mcp/static/index.html +137 -0
  63. backlog_mcp/static/markdown.css +33 -0
  64. backlog_mcp/static/markdown.js +72 -0
  65. backlog_mcp/static/mcp.js +177 -0
  66. backlog_mcp/static/memory-append.js +34 -0
  67. backlog_mcp/static/memory-editor.js +173 -0
  68. backlog_mcp/static/memory.js +279 -0
  69. backlog_mcp/static/package.json +1 -0
  70. backlog_mcp/static/project-form.js +71 -0
  71. backlog_mcp/static/project-settings.js +225 -0
  72. backlog_mcp/static/scope.js +90 -0
  73. backlog_mcp/static/statistics.js +87 -0
  74. backlog_mcp/static/task-browser.js +100 -0
  75. backlog_mcp/static/task-pagination.js +94 -0
  76. backlog_mcp/static/task-picker.js +164 -0
  77. backlog_mcp/static/task-table.js +74 -0
  78. backlog_mcp/static/vendor/README.md +12 -0
  79. backlog_mcp/static/vendor/dompurify-LICENSE +202 -0
  80. backlog_mcp/static/vendor/highlight-LICENSE +29 -0
  81. backlog_mcp/static/vendor/highlight-dark.css +118 -0
  82. backlog_mcp/static/vendor/highlight-light.css +118 -0
  83. backlog_mcp/static/vendor/highlight.min.js +1262 -0
  84. backlog_mcp/static/vendor/marked-LICENSE +44 -0
  85. backlog_mcp/static/vendor/marked.esm.js +80 -0
  86. backlog_mcp/static/vendor/marked.esm.js.map +7 -0
  87. backlog_mcp/static/vendor/mermaid-LICENSE +21 -0
  88. backlog_mcp/static/vendor/mermaid.min.js +4376 -0
  89. backlog_mcp/static/vendor/purify.es.mjs +2722 -0
  90. backlog_mcp/static/vendor/purify.es.mjs.map +1 -0
  91. backlog_mcp/transaction.py +47 -0
  92. backlog_mcp/version.py +79 -0
  93. backlog_mcp/webui.py +63 -0
  94. backlog_tiny_mcp-0.35.0.dist-info/METADATA +84 -0
  95. backlog_tiny_mcp-0.35.0.dist-info/RECORD +97 -0
  96. backlog_tiny_mcp-0.35.0.dist-info/WHEEL +4 -0
  97. backlog_tiny_mcp-0.35.0.dist-info/entry_points.txt +4 -0
@@ -0,0 +1,1301 @@
1
+ import { MCP, HttpError } from "./mcp.js";
2
+ import { authorization, loadCredentials, saveCredentials, clearCredentials } from "./credentials.js";
3
+ import { markdown } from "./markdown.js";
4
+ import {
5
+ el,
6
+ button,
7
+ link,
8
+ select,
9
+ field,
10
+ date,
11
+ projectRoute,
12
+ memoryRoute,
13
+ taskRoute,
14
+ route,
15
+ modal,
16
+ } from "./dom.js";
17
+ import { editor } from "./editor.js";
18
+ import { taskPicker } from "./task-picker.js";
19
+ import { taskTable } from "./task-table.js";
20
+ import { taskPagination } from "./task-pagination.js";
21
+ import { memoryPage } from "./memory.js";
22
+ import { commentComposer } from "./comment-composer.js";
23
+ import { breadcrumbs } from "./breadcrumbs.js";
24
+ import { createProject } from "./project-form.js";
25
+ import { taskBrowser } from "./task-browser.js";
26
+ import { scopeArgs, scopeControls } from "./scope.js";
27
+ import { statisticsPage } from "./statistics.js";
28
+ import { assignmentControl, assignmentsPage } from "./assignments.js";
29
+ import { projectSettings } from "./project-settings.js";
30
+
31
+ const content = document.querySelector("#content");
32
+ const endpoint = document.documentElement.dataset.endpoint;
33
+ const pageLoading = document.querySelector("#page-loading");
34
+ let displayedUrl = "";
35
+ const statuses = ["todo", "doing", "blocked", "done", "cancelled"];
36
+ const priorities = ["urgent", "high", "normal", "low"];
37
+ const relations = [
38
+ "part_of",
39
+ "contains",
40
+ "depends_on",
41
+ "blocks",
42
+ "caused_by",
43
+ "causes",
44
+ "related_to",
45
+ ];
46
+ let client,
47
+ identity,
48
+ project = "",
49
+ generation = 0,
50
+ searchGeneration = 0;
51
+ let selectedResult = 0;
52
+ const actions = {
53
+ endpoint,
54
+ call,
55
+ refresh: render,
56
+ notify,
57
+ navigate,
58
+ markdown,
59
+ get principal() {
60
+ return identity?.principal;
61
+ },
62
+ };
63
+ function navigate(href) {
64
+ const url = new URL(href, location.href);
65
+ if (url.href !== location.href) history.pushState(null, "", url);
66
+ render();
67
+ }
68
+ function notify(error) {
69
+ if (error.name === "AbortError") return;
70
+ const toast = document.querySelector("#toast");
71
+ toast.textContent = error.message || String(error);
72
+ toast.hidden = false;
73
+ clearTimeout(notify.timer);
74
+ notify.timer = setTimeout(() => {
75
+ toast.hidden = true;
76
+ }, 8000);
77
+ }
78
+ async function call(name, args = {}) {
79
+ const active = client;
80
+ try {
81
+ return await active.call(name, args);
82
+ } catch (error) {
83
+ if (error instanceof HttpError && error.status === 401 && active === client) {
84
+ identity = null;
85
+ generation++;
86
+ showLogin(error);
87
+ }
88
+ throw error;
89
+ }
90
+ }
91
+ function operation(fn) {
92
+ return async () => {
93
+ try {
94
+ await fn();
95
+ } catch (error) {
96
+ notify(error);
97
+ }
98
+ };
99
+ }
100
+ async function connect(auth = authorization(loadCredentials(endpoint))) {
101
+ client?.close();
102
+ client = new MCP(endpoint, auth, async (request) => {
103
+ if (request.requestedSchema?.properties?.ok?.type !== "boolean")
104
+ return { action: "decline" };
105
+ const ok = await modal({
106
+ title: "Confirm deletion", description: request.message,
107
+ action: "Delete permanently", danger: true,
108
+ });
109
+ return { action: "accept", content: { ok } };
110
+ });
111
+ identity = await client.call("whoami");
112
+ document.querySelector("#principal").textContent = identity.principal;
113
+ document.querySelector("#logout").hidden = false;
114
+ document.querySelector("#section-switch").hidden = false;
115
+ await render();
116
+ }
117
+ function finishStartup() {
118
+ document.documentElement.removeAttribute("data-starting");
119
+ document.querySelector("header").inert = false;
120
+ }
121
+ function showLogin(error, reportError = true) {
122
+ finishStartup();
123
+ content.inert = false;
124
+ content.removeAttribute("aria-busy");
125
+ pageLoading.hidden = true;
126
+ displayedUrl = "";
127
+ content.firstElementChild?.dispose?.();
128
+ document.querySelector("#principal").textContent = "";
129
+ document.querySelector("#logout").hidden = true;
130
+ document.querySelector("#section-switch").hidden = true;
131
+ document.querySelector("#breadcrumbs").replaceChildren();
132
+ document.querySelector("#breadcrumbs").hidden = true;
133
+ document.querySelector("#search-dialog").close();
134
+ const methods = error?.schemes?.length ? [...new Set(error.schemes)] : ["basic", "bearer"];
135
+ const method = select(methods, methods[0], { name: "method" });
136
+ const username = el("input", { name: "username", autocomplete: "username", required: true });
137
+ const secret = el("input", {
138
+ name: "secret",
139
+ type: "password",
140
+ autocomplete: "current-password",
141
+ required: true,
142
+ });
143
+ const userField = field("Username", username),
144
+ secretField = field("Password", secret);
145
+ const message = el(
146
+ "p",
147
+ { class: "error", role: "alert" },
148
+ error && reportError ? error.message : "",
149
+ );
150
+ const submit = el("button", { type: "submit", class: "primary" }, "Sign in");
151
+ const form = el(
152
+ "form",
153
+ { class: "panel login" },
154
+ el("div", { class: "eyebrow" }, "Your workspace"),
155
+ el("h1", {}, "Sign in to Backlog"),
156
+ el("p", { class: "subtitle" }, "Projects, tasks and the work in between."),
157
+ field("Method", method),
158
+ userField,
159
+ secretField,
160
+ message,
161
+ submit,
162
+ );
163
+ function changeMethod() {
164
+ userField.hidden = method.value !== "basic";
165
+ username.required = !userField.hidden;
166
+ secretField.firstChild.textContent = method.value === "basic" ? "Password" : "Bearer token";
167
+ }
168
+ method.onchange = changeMethod;
169
+ changeMethod();
170
+ form.onsubmit = async (event) => {
171
+ event.preventDefault();
172
+ submit.disabled = true;
173
+ message.textContent = "";
174
+ try {
175
+ const credentials = {
176
+ method: method.value,
177
+ username: username.value,
178
+ secret: method.value === "bearer" ? secret.value.trim() : secret.value,
179
+ };
180
+ await connect(authorization(credentials));
181
+ saveCredentials(endpoint, credentials);
182
+ } catch (failure) {
183
+ message.textContent = failure.message;
184
+ } finally {
185
+ submit.disabled = false;
186
+ }
187
+ };
188
+ content.replaceChildren(form);
189
+ }
190
+ document.querySelector("#logout").onclick = () => {
191
+ clearCredentials(endpoint);
192
+ client?.close();
193
+ identity = null;
194
+ project = "";
195
+ generation++;
196
+ searchGeneration++;
197
+ showLogin();
198
+ };
199
+
200
+ async function render() {
201
+ let target = route();
202
+ if (target.redirect) {
203
+ history.replaceState(null, "", target.redirect);
204
+ target = route();
205
+ }
206
+ if (!identity) return;
207
+ const current = ++generation;
208
+ const targetUrl = location.href;
209
+ content.inert = true;
210
+ content.setAttribute("aria-busy", "true");
211
+ pageLoading.hidden = false;
212
+ let selectedProject = "";
213
+ await content.firstElementChild?.dispose?.();
214
+ if (current !== generation || !identity) return;
215
+ try {
216
+ let page;
217
+ if (target.kind === "projects") {
218
+ page = await projects(target);
219
+ } else if (target.kind === "memory") {
220
+ selectedProject = target.project;
221
+ page = await memoryPage(target, actions);
222
+ } else if (target.kind === "board") {
223
+ selectedProject = target.project;
224
+ page = await board(target);
225
+ } else if (target.kind === "tasks") {
226
+ selectedProject = target.project;
227
+ page = await taskBrowser(target, actions);
228
+ } else if (target.kind === "stats") {
229
+ selectedProject = target.project;
230
+ page = await statisticsPage(target, actions);
231
+ } else if (target.kind === "assigned") {
232
+ page = await assignmentsPage(target, actions);
233
+ } else if (target.kind === "settings") {
234
+ selectedProject = target.project;
235
+ page = await projectSettings(target.project, actions);
236
+ } else if (target.kind === "task") {
237
+ const task = await call("task_get", { id: target.id });
238
+ selectedProject = task.project;
239
+ page = await detail(task);
240
+ } else if (target.kind === "new" || target.kind === "edit") {
241
+ const task = target.kind === "edit" ? await call("task_get", { id: target.id }) : null;
242
+ selectedProject = task?.project || target.params.get("project") || "";
243
+ if (!selectedProject) throw new Error("Choose a project before creating a task.");
244
+ page = editor(task, selectedProject, actions);
245
+ } else page = el("div", {}, el("h1", {}, "Page not found"), link("Back to projects", "/ui/"));
246
+ if (current !== generation || !identity) {
247
+ page.dispose?.();
248
+ return;
249
+ }
250
+ project = selectedProject;
251
+ content.replaceChildren(page);
252
+ if (displayedUrl !== targetUrl) window.scrollTo(0, 0);
253
+ displayedUrl = targetUrl;
254
+ page.mount?.();
255
+ document.querySelector("#breadcrumbs").replaceChildren(breadcrumbs(target, project));
256
+ document.querySelector("#breadcrumbs").hidden = false;
257
+ document.querySelector("#memory-open").href = memoryRoute(project);
258
+ document.querySelector("#tasks-open").href = project ? projectRoute(project) : "/ui/";
259
+ for (const section of ["tasks", "memory"]) {
260
+ const control = document.querySelector(`#${section}-open`);
261
+ if ((target.kind === "memory") === (section === "memory"))
262
+ control.setAttribute("aria-current", "page");
263
+ else control.removeAttribute("aria-current");
264
+ }
265
+ } catch (error) {
266
+ if (current !== generation) return;
267
+ content.replaceChildren(
268
+ el(
269
+ "div",
270
+ { class: "panel" },
271
+ el("h1", {}, "Could not load this page"),
272
+ el("p", { class: "error" }, error.message),
273
+ button("Try again", render),
274
+ link("Projects", "/ui/"),
275
+ ),
276
+ );
277
+ } finally {
278
+ if (current === generation) {
279
+ finishStartup();
280
+ content.inert = false;
281
+ content.removeAttribute("aria-busy");
282
+ pageLoading.hidden = true;
283
+ }
284
+ }
285
+ }
286
+ async function projects(target) {
287
+ const archived = target.params.get("archived") === "true";
288
+ const reach = scopeArgs(target.params);
289
+ delete reach.all_projects;
290
+ const data = await call("project_list", { ...reach, archived });
291
+ const scope = scopeControls(target.params, [], { allowProject: false });
292
+ const toggle = el("input", {
293
+ type: "checkbox",
294
+ checked: archived,
295
+ onchange: () => { const p = new URLSearchParams(target.params);
296
+ if (toggle.checked) p.set("archived", "true"); else p.delete("archived");
297
+ navigate(`/ui/?${p}`); },
298
+ });
299
+ const apply = el("button", { type: "submit" }, "Apply scope");
300
+ const filters = el("form", { class: "project-scope-form", onsubmit: event => {
301
+ event.preventDefault(); navigate(`/ui/?${scope.apply(new URLSearchParams(target.params))}`);
302
+ } }, scope.element, apply, el("label", { class: "inline" }, toggle, "Include archived"));
303
+ const mode = scope.element.querySelector("select");
304
+ mode.parentElement.firstChild.replaceWith(el("span", { class: "sr-only" }, "Scope"));
305
+ apply.hidden = mode.value !== "computer";
306
+ mode.addEventListener("change", () => {
307
+ apply.hidden = mode.value !== "computer";
308
+ if (mode.value !== "computer") filters.requestSubmit();
309
+ });
310
+ return el("section", { class: "projects-page" },
311
+ el("div", { class: "projects-heading" },
312
+ el("div", {}, el("h1", {}, "Your projects"), el("p", { class: "muted" }, `${data.count} projects`)),
313
+ button("New project", () => createProject(actions), "primary")),
314
+ el("div", { class: "projects-toolbar" },
315
+ el("nav", { class: "workspace-nav", "aria-label": "Workspace" },
316
+ el("span", { "aria-current": "page" }, "Projects"),
317
+ link("All tasks", "/ui/?view=tasks"),
318
+ link("My assignments", "/ui/?view=assigned"),
319
+ link("Statistics", "/ui/?view=stats")),
320
+ filters),
321
+ el("div", { class: "projects" }, ...data.items.map(p => linkNode(p))));
322
+ }
323
+ function linkNode(p) {
324
+ return el(
325
+ "a",
326
+ { class: "project", href: projectRoute(p.full_name) },
327
+ el("div", { class: "eyebrow" }, p.role + (p.archived ? " · archived" : "")),
328
+ el("h2", {}, p.name),
329
+ el("p", {}, p.full_name),
330
+ el("p", {}, p.description || "No description"),
331
+ el(
332
+ "div",
333
+ { class: "row spread" },
334
+ el("strong", {}, `${p.open_tasks} open`),
335
+ el("span", { class: "muted" }, `${p.total_tasks} total →`),
336
+ ),
337
+ );
338
+ }
339
+ function boardSection(title, data = { count: 0, items: [] }, explanation) {
340
+ return el("details", { class: "board-summary" },
341
+ el("summary", {}, `${title} (${data.count})`),
342
+ el("p", { class: "muted" }, explanation),
343
+ el("p", { class: "muted" }, `${data.items.length} of ${data.count} shown`),
344
+ data.items.length ? el("ul", {}, ...data.items.map(task =>
345
+ el("li", {}, link(`#${task.id} ${task.title}`, taskRoute(task.id)),
346
+ ` · ${task.status} · ${task.priority}`))) : el("p", {}, "No tasks."));
347
+ }
348
+ async function board(target) {
349
+ const params = target.params;
350
+ const viewKey = `backlog:board-view:${endpoint}:${identity.principal}`;
351
+ let preferredView;
352
+ try {
353
+ preferredView = localStorage.getItem(viewKey);
354
+ } catch {
355
+ preferredView = null;
356
+ }
357
+ const tableView = (params.get("view") || preferredView) === "table";
358
+ const queryText = params.get("q") || "";
359
+ const selectedStatus = [...statuses, "deleted"].includes(params.get("status"))
360
+ ? params.get("status")
361
+ : "";
362
+ const visibleStatuses = selectedStatus ? [selectedStatus] : statuses.slice(0, 4);
363
+ const groups = selectedStatus
364
+ ? [[selectedStatus]]
365
+ : tableView
366
+ ? [["todo", "doing", "blocked"], ["done"]]
367
+ : visibleStatuses.map((status) => [status]);
368
+ async function loadSources(text, priorityValue) {
369
+ if (text) {
370
+ const found = await call("search", {
371
+ project: target.project,
372
+ query: [text],
373
+ kinds: ["tasks"],
374
+ status: visibleStatuses,
375
+ limit: 100,
376
+ });
377
+ const tasks = found.tasks.filter((task) => !priorityValue || task.priority === priorityValue);
378
+ const matches = tableView
379
+ ? [tasks]
380
+ : groups.map((group) => tasks.filter((task) => group.includes(task.status)));
381
+ return matches.map((items) => ({ args: {}, page: { items, count: items.length } }));
382
+ }
383
+ const requests = groups.map((status) => ({
384
+ project: target.project,
385
+ ...(priorityValue ? { priority: priorityValue } : {}),
386
+ status,
387
+ order: ["done", "cancelled", "deleted"].includes(status[0]) ? "recent" : "backlog",
388
+ limit: 50,
389
+ }));
390
+ return Promise.all(
391
+ requests.map(async (args) => ({ args, page: await call("task_list", args) })),
392
+ );
393
+ }
394
+ const [sources, summary] = await Promise.all([
395
+ loadSources(queryText, params.get("priority")),
396
+ call("project_board", { project: target.project }),
397
+ ]);
398
+ const counts = el("span", { class: "muted" });
399
+ const quick = el("input", {
400
+ type: "search",
401
+ placeholder: "Search tasks",
402
+ value: queryText,
403
+ "aria-label": "Search tasks",
404
+ autocomplete: "off",
405
+ });
406
+ const priority = select(["", ...priorities], params.get("priority") || "", {
407
+ "aria-label": "Priority filter",
408
+ });
409
+ priority.options[0].text = "All priorities";
410
+ const statusFilter = select(["", ...statuses, "deleted"], selectedStatus, {
411
+ "aria-label": "Task status",
412
+ });
413
+ statusFilter.options[0].text = "Open and done";
414
+ for (const option of [...statusFilter.options].slice(1))
415
+ option.text = option.value[0].toUpperCase() + option.value.slice(1);
416
+ statusFilter.onchange = () => {
417
+ const p = new URLSearchParams(location.search);
418
+ p.delete("status");
419
+ if (statusFilter.value) p.set("status", statusFilter.value);
420
+ navigate(projectRoute(target.project, p));
421
+ };
422
+ const deletedParams = new URLSearchParams(params);
423
+ deletedParams.set("status", "deleted");
424
+ deletedParams.delete("q");
425
+ deletedParams.delete("priority");
426
+ const apply = () => schedule(0);
427
+ const heading = el(
428
+ "div",
429
+ {},
430
+ el("div", { class: "eyebrow" }, "Project board"),
431
+ el(
432
+ "div",
433
+ { class: "row spread" },
434
+ el("h1", {}, summary.project.name),
435
+ el(
436
+ "div",
437
+ { class: "row" },
438
+ button("Refresh", render),
439
+ link(
440
+ "+ New task",
441
+ "/ui/?view=new&project=" + encodeURIComponent(target.project),
442
+ "button primary",
443
+ ),
444
+ ),
445
+ ),
446
+ el(
447
+ "p",
448
+ { class: "subtitle" },
449
+ `${summary.tasks.open} open · ${summary.tasks.done} done · ${summary.tasks.total} total · `,
450
+ link(`Deleted (${summary.tasks.deleted || 0})`, projectRoute(target.project, deletedParams)),
451
+ ),
452
+ el("div", { class: "board-summaries" },
453
+ boardSection("Ready", summary.ready, "Unassigned todo/doing tasks with no unfinished direct dependencies. Up to 10 tasks are listed."),
454
+ boardSection("My active tasks", summary.claimed, `Open tasks assigned to ${identity.principal}, across all markers. Up to 10 tasks are listed.`)),
455
+ el(
456
+ "form",
457
+ {
458
+ class: "row filters",
459
+ onsubmit: (e) => {
460
+ e.preventDefault();
461
+ apply();
462
+ },
463
+ },
464
+ quick,
465
+ statusFilter,
466
+ priority,
467
+ el("button", { type: "submit" }, "Search"),
468
+ ),
469
+ );
470
+ const switchView = (view) => {
471
+ try {
472
+ localStorage.setItem(viewKey, view);
473
+ } catch {
474
+ notify(new Error("The browser could not save the view preference."));
475
+ }
476
+ const p = new URLSearchParams(location.search);
477
+ p.set("view", view);
478
+ navigate(projectRoute(target.project, p));
479
+ };
480
+ const viewButton = (title, view, selected) => {
481
+ const control = button(title, () => switchView(view));
482
+ control.setAttribute("aria-pressed", String(selected));
483
+ return control;
484
+ };
485
+ const toolbar = el(
486
+ "div",
487
+ { class: "board-toolbar" },
488
+ el(
489
+ "div",
490
+ { class: "view-switch", role: "group", "aria-label": "Task view" },
491
+ viewButton("Kanban", "kanban", !tableView),
492
+ viewButton("Table", "table", tableView),
493
+ button("Settings", () =>
494
+ navigate(projectRoute(target.project, new URLSearchParams({ view: "settings" }))),
495
+ ),
496
+ ),
497
+ counts,
498
+ link("My assignments", "/ui/?view=assigned"),
499
+ link("Statistics", projectRoute(target.project, new URLSearchParams({ view: "stats" }))),
500
+ tableView
501
+ ? el("span", { class: "muted table-scroll-hint" }, "Scroll the table to see all columns")
502
+ : null,
503
+ );
504
+ heading.querySelector(".filters").append(toolbar);
505
+ const message = el("p", { class: "muted", role: "status", "aria-live": "polite" });
506
+ let results = taskResults(sources, tableView, counts, Boolean(queryText), visibleStatuses);
507
+ const panel = el("section", { class: "board-page" }, heading, message, results);
508
+ let revision = 0,
509
+ timer,
510
+ disposed = false;
511
+ function schedule(delay = 250) {
512
+ const current = ++revision;
513
+ clearTimeout(timer);
514
+ results.dispose();
515
+ const p = new URLSearchParams(location.search);
516
+ p.delete("tag");
517
+ p.delete("q");
518
+ p.delete("priority");
519
+ if (quick.value.trim()) p.set("q", quick.value.trim());
520
+ if (priority.value) p.set("priority", priority.value);
521
+ history.replaceState(null, "", projectRoute(target.project, p));
522
+ timer = setTimeout(() => refresh(current), delay);
523
+ }
524
+ async function refresh(current) {
525
+ message.textContent = "Searching…";
526
+ results.setAttribute("aria-busy", "true");
527
+ try {
528
+ const next = await loadSources(quick.value.trim(), priority.value);
529
+ if (disposed || current !== revision) return;
530
+ const replacement = taskResults(
531
+ next,
532
+ tableView,
533
+ counts,
534
+ Boolean(quick.value.trim()),
535
+ visibleStatuses,
536
+ );
537
+ results.replaceWith(replacement);
538
+ results = replacement;
539
+ results.mount();
540
+ message.textContent = "";
541
+ } catch (error) {
542
+ if (!disposed && current === revision) {
543
+ message.replaceChildren(
544
+ el("span", { class: "error" }, error.message),
545
+ button("Retry", () => schedule(0)),
546
+ );
547
+ results.removeAttribute("aria-busy");
548
+ }
549
+ }
550
+ }
551
+ quick.oninput = (event) => {
552
+ if (!event.isComposing) schedule();
553
+ };
554
+ quick.addEventListener("compositionstart", () => {
555
+ revision++;
556
+ clearTimeout(timer);
557
+ });
558
+ quick.addEventListener("compositionend", () => schedule());
559
+ priority.onchange = () => schedule(0);
560
+ panel.mount = () => results.mount();
561
+ panel.dispose = () => {
562
+ disposed = true;
563
+ revision++;
564
+ clearTimeout(timer);
565
+ results.dispose();
566
+ };
567
+ return panel;
568
+ }
569
+ function taskResults(sources, tableView, counts, searching, visibleStatuses) {
570
+ const tasks = [];
571
+ const pagers = [];
572
+ const loaded = new Map();
573
+ function count(key, shown, total) {
574
+ loaded.set(key, { shown, total });
575
+ counts.textContent = `${[...loaded.values()].reduce((n, item) => n + item.shown, 0)} of ${[...loaded.values()].reduce((n, item) => n + item.total, 0)} tasks shown`;
576
+ }
577
+ function finish(...children) {
578
+ const page = el("section", { class: "board-results" }, ...children, note);
579
+ page.mount = () => pagers.forEach((pager) => pager.mount());
580
+ page.dispose = () => pagers.forEach((pager) => pager.dispose());
581
+ return page;
582
+ }
583
+ const note = el(
584
+ "p",
585
+ { class: "muted" },
586
+ searching
587
+ ? "Up to 100 search matches. Refine your query to narrow the results."
588
+ : "Tasks load as you scroll. Refresh to load updates.",
589
+ );
590
+ if (tableView) {
591
+ const table = taskTable([]);
592
+ const pager = taskPagination({
593
+ sources,
594
+ root: table,
595
+ call,
596
+ append: (items) => table.appendTasks(items),
597
+ changed: (shown, total) => count("table", shown, total),
598
+ });
599
+ table.append(pager.sentinel);
600
+ pagers.push(pager);
601
+ return finish(table);
602
+ }
603
+ const columns = el("div", { class: "board" });
604
+ if (visibleStatuses.length === 1) columns.classList.add("single-status");
605
+ for (const [index, status] of visibleStatuses.entries()) {
606
+ const counter = el("span", { class: "count" });
607
+ const column = el(
608
+ "section",
609
+ { class: "column", "data-status": status },
610
+ el("h2", {}, status, counter),
611
+ );
612
+ const stack = el("div", { class: "stack" });
613
+ column.append(stack);
614
+ function append(items) {
615
+ tasks.push(...items);
616
+ for (const task of items) {
617
+ const card = el(
618
+ "article",
619
+ { class: "card", draggable: true, "data-task": task.id },
620
+ el(
621
+ "div",
622
+ { class: "card-meta" },
623
+ `#${task.id}`,
624
+ el("span", { class: `priority ${task.priority}` }, task.priority),
625
+ ),
626
+ link(task.title, taskRoute(task.id)),
627
+ el("div", {}, ...(task.tags || []).map((t) => el("span", { class: "tag" }, t))),
628
+ el(
629
+ "small",
630
+ { class: "muted", title: task.assigned || "Unassigned" },
631
+ task.assigned || "Unassigned",
632
+ ),
633
+ );
634
+ card.ondragstart = (event) => {
635
+ event.dataTransfer.setData("text/plain", String(task.id));
636
+ event.dataTransfer.effectAllowed = "move";
637
+ };
638
+ stack.insertBefore(card, stack.querySelector(".task-pagination"));
639
+ }
640
+ }
641
+ const pager = taskPagination({
642
+ sources: [sources[index]],
643
+ root: stack,
644
+ call,
645
+ append,
646
+ changed: (shown, total) => {
647
+ counter.textContent = `${shown} / ${total}`;
648
+ count(status, shown, total);
649
+ },
650
+ });
651
+ stack.append(pager.sentinel);
652
+ pagers.push(pager);
653
+ column.ondragover = (event) => {
654
+ event.preventDefault();
655
+ event.dataTransfer.dropEffect = "move";
656
+ };
657
+ column.ondrop = async (event) => {
658
+ event.preventDefault();
659
+ const id = Number(event.dataTransfer.getData("text/plain"));
660
+ const task = tasks.find((t) => t.id === id);
661
+ const card = columns.querySelector(`[data-task="${id}"]`);
662
+ if (!task || !card || task.status === status || card.dataset.saving) return;
663
+ const parent = card.parentNode,
664
+ next = card.nextSibling;
665
+ card.dataset.saving = "true";
666
+ stack.prepend(card);
667
+ try {
668
+ await call("task_update", { id, status });
669
+ await render();
670
+ } catch (error) {
671
+ parent.insertBefore(card, next);
672
+ notify(error);
673
+ } finally {
674
+ delete card.dataset.saving;
675
+ }
676
+ };
677
+ columns.append(column);
678
+ }
679
+ return finish(columns);
680
+ }
681
+ async function detail(task) {
682
+ const panel = el("section", { class: "detail" });
683
+ const status = select(
684
+ statuses.includes(task.status) ? statuses : [...statuses, task.status],
685
+ task.status,
686
+ { "aria-label": "Status" },
687
+ );
688
+ const priority = select(priorities, task.priority, { "aria-label": "Priority" });
689
+ for (const [control, key] of [
690
+ [status, "status"],
691
+ [priority, "priority"],
692
+ ])
693
+ control.onchange = async () => {
694
+ control.disabled = true;
695
+ try {
696
+ await call("task_update", { id: task.id, [key]: control.value });
697
+ await render();
698
+ } catch (error) {
699
+ control.value = task[key];
700
+ notify(error);
701
+ } finally {
702
+ control.disabled = false;
703
+ }
704
+ };
705
+ panel.append(
706
+ link(
707
+ "← " + task.project,
708
+ projectRoute(
709
+ task.project,
710
+ task.status === "deleted"
711
+ ? new URLSearchParams({ status: "deleted" })
712
+ : new URLSearchParams(),
713
+ ),
714
+ ),
715
+ el("div", { class: "eyebrow", style: "margin-top:24px" }, `Task #${task.id}`),
716
+ el("h1", {}, task.title),
717
+ task.status === "deleted"
718
+ ? el(
719
+ "p",
720
+ { class: "muted" },
721
+ "This task is deleted. Its description and history are preserved.",
722
+ )
723
+ : null,
724
+ el(
725
+ "div",
726
+ { class: "task-actions" },
727
+ field("Status", status),
728
+ field("Priority", priority),
729
+ await assignmentControl(task, actions),
730
+ link("Edit task", taskRoute(task.id, true), "button"),
731
+ button(
732
+ "Move",
733
+ operation(async () => {
734
+ const result = await call("project_list", { all_computers: true });
735
+ const chooser = select(
736
+ result.items.filter((p) => p.role !== "reader").map((p) => p.full_name),
737
+ task.project,
738
+ );
739
+ const moved = await modal({
740
+ title: "Move task",
741
+ description: task.title,
742
+ content: [field("Destination project", chooser)],
743
+ action: "Move task",
744
+ onSubmit: () => call("task_move", { id: task.id, project: chooser.value }),
745
+ });
746
+ if (moved) await render();
747
+ }),
748
+ ),
749
+ task.status === "deleted"
750
+ ? null
751
+ : button(
752
+ "Delete",
753
+ operation(async () => {
754
+ const removed = await modal({
755
+ title: "Delete task?",
756
+ description: task.title,
757
+ content: [
758
+ el("p", {}, "The task will be marked as deleted and removed from the board."),
759
+ ],
760
+ action: "Delete task",
761
+ danger: true,
762
+ onSubmit: () => call("task_delete", { id: task.id }),
763
+ });
764
+ if (removed) navigate(projectRoute(task.project));
765
+ }),
766
+ "danger",
767
+ ),
768
+ ),
769
+ el(
770
+ "p",
771
+ { class: "muted" },
772
+ `Assigned: ${task.assigned || "Unassigned"} · Created ${date(task.created_at)} by ${task.created_by} · Updated ${date(task.updated_at)} by ${task.updated_by}${task.closed_at ? ` · Closed ${date(task.closed_at)}` : ""}`,
773
+ ),
774
+ el("div", {}, ...(task.tags || []).map((t) => el("span", { class: "tag" }, t))),
775
+ el("div", { class: "panel markdown" }, markdown(task.body || "No description.")),
776
+ );
777
+ const links = el(
778
+ "ul",
779
+ { class: "links" },
780
+ ...(task.links || []).map((item) =>
781
+ el(
782
+ "li",
783
+ {},
784
+ el(
785
+ "div",
786
+ { class: "row" },
787
+ el("span", { class: "tag" }, item.relation),
788
+ link(`#${item.task} ${item.title}`, taskRoute(item.task)),
789
+ el("small", { class: "muted" }, item.status),
790
+ button(
791
+ "Remove",
792
+ operation(async () => {
793
+ const removed = await modal({
794
+ title: "Remove relation?",
795
+ description: item.title,
796
+ content: [
797
+ el("p", {}, `Remove the ${item.relation} relation? Both tasks will be kept.`),
798
+ ],
799
+ action: "Remove relation",
800
+ danger: true,
801
+ onSubmit: () =>
802
+ call("task_unlink", {
803
+ task: task.id,
804
+ target: item.task,
805
+ relation: item.relation,
806
+ }),
807
+ });
808
+ if (removed) await render();
809
+ }),
810
+ "quiet",
811
+ ),
812
+ ),
813
+ el("small", { class: "muted" }, item.reason || ""),
814
+ ),
815
+ ),
816
+ );
817
+ const relation = select(relations, "related_to", { "aria-label": "Relation type" });
818
+ const target = el("input", {
819
+ type: "number",
820
+ min: 1,
821
+ required: true,
822
+ placeholder: "Task ID",
823
+ "aria-label": "Target task ID",
824
+ });
825
+ const reason = el("input", { placeholder: "Reason (optional)", "aria-label": "Relation reason" });
826
+ const picker = taskPicker({
827
+ search: async (query) => {
828
+ const found = await call("search", {
829
+ project: task.project,
830
+ all_computers: true,
831
+ query,
832
+ kinds: ["tasks"],
833
+ limit: 9,
834
+ min_score: 0.12,
835
+ });
836
+ return found.tasks.filter((item) => item.id !== task.id).slice(0, 8);
837
+ },
838
+ onSelect: (item) => {
839
+ target.value = item ? item.id : "";
840
+ },
841
+ });
842
+ target.oninput = () => picker.clearSelection();
843
+ const addRelation = button("Add relation", async () => {
844
+ const added = await modal({
845
+ title: "Add relation",
846
+ description: "Find a task or enter its ID, then choose how it relates to this task.",
847
+ content: [
848
+ picker.element,
849
+ field("Task ID", target),
850
+ field("Relation", relation),
851
+ field("Reason (optional)", reason),
852
+ ],
853
+ action: "Add relation",
854
+ onSubmit: () =>
855
+ call("task_link", {
856
+ task: task.id,
857
+ target: Number(target.value),
858
+ relation: relation.value,
859
+ reason: reason.value,
860
+ }),
861
+ });
862
+ picker.close();
863
+ if (added) await render();
864
+ });
865
+ panel.append(
866
+ el(
867
+ "section",
868
+ { class: "panel relations" },
869
+ el(
870
+ "div",
871
+ { class: "section-heading" },
872
+ el("h2", {}, "Relations ", el("span", { class: "count" }, String(task.links?.length ?? 0))),
873
+ addRelation,
874
+ ),
875
+ task.links?.length ? links : null,
876
+ ),
877
+ );
878
+ const composer = commentComposer({
879
+ taskId: task.id,
880
+ draftKey: `backlog:comment-draft:${JSON.stringify([endpoint, identity.principal, task.id])}`,
881
+ call,
882
+ markdown,
883
+ onAdded: async (added) => {
884
+ if (!panel.isConnected) return;
885
+ await render();
886
+ document.getElementById(`comment-${added.id}`)?.scrollIntoView({ block: "center" });
887
+ },
888
+ });
889
+ const comments = (task.comments || []).map((comment) => {
890
+ const system = comment.kind !== "comment";
891
+ return el(
892
+ "article",
893
+ { class: system ? "comment system-event" : "comment", id: `comment-${comment.id}` },
894
+ el(
895
+ "div",
896
+ { class: "comment-avatar", "aria-hidden": "true" },
897
+ system ? "↳" : comment.principal.slice(0, 1).toUpperCase(),
898
+ ),
899
+ el(
900
+ "div",
901
+ { class: "comment-content" },
902
+ el(
903
+ "div",
904
+ { class: "comment-heading" },
905
+ el("strong", {}, comment.principal),
906
+ system
907
+ ? el("span", { class: "tag" }, comment.kind === "status" ? "Status changed" : "Moved")
908
+ : null,
909
+ el(
910
+ "time",
911
+ { dateTime: new Date(comment.created_at * 1000).toISOString() },
912
+ date(comment.created_at),
913
+ ),
914
+ ),
915
+ el("div", { class: "markdown" }, markdown(comment.body)),
916
+ ),
917
+ );
918
+ });
919
+ panel.append(
920
+ el(
921
+ "section",
922
+ { class: "panel activity" },
923
+ el(
924
+ "div",
925
+ { class: "section-heading" },
926
+ el("h2", {}, "Discussion & activity"),
927
+ el("span", { class: "count" }, String(comments.length)),
928
+ ),
929
+ composer,
930
+ el("div", { class: "timeline" }, ...comments),
931
+ comments.length
932
+ ? null
933
+ : el("p", { class: "empty-state" }, "No activity yet. Start the conversation above."),
934
+ ),
935
+ );
936
+ return panel;
937
+ }
938
+ const dialog = document.querySelector("#search-dialog");
939
+ const syntaxHelp = dialog.querySelector(".search-help");
940
+ const syntaxContent = dialog.querySelector(".search-help-content");
941
+ let syntaxClient;
942
+ syntaxHelp.addEventListener("toggle", async () => {
943
+ if (!syntaxHelp.open || !client || syntaxClient === client) return;
944
+ const source = client;
945
+ syntaxContent.replaceChildren(el("p", {}, "Loading query syntax…"));
946
+ try {
947
+ const response = await source.request("tools/call", {
948
+ name: "guide", arguments: { topic: "search" },
949
+ });
950
+ const text = (response.content || []).filter(item => item.type === "text")
951
+ .map(item => item.text).join("\n");
952
+ if (response.isError || !text) throw new Error(text || "Query syntax is unavailable.");
953
+ if (source !== client) return;
954
+ syntaxContent.replaceChildren(markdown(text));
955
+ syntaxClient = source;
956
+ } catch (error) {
957
+ if (source === client) syntaxContent.replaceChildren(el("p", {}, `${error.message} Close and reopen query syntax to retry.`));
958
+ }
959
+ });
960
+ const searchKinds = [...dialog.querySelectorAll('[name="search-kind"]')];
961
+ const searchLabels = {
962
+ tasks: "Tasks",
963
+ comments: "Comments",
964
+ memory: "Memory",
965
+ projects: "Projects",
966
+ };
967
+ const query = document.querySelector("#search-query"),
968
+ all = document.querySelector("#search-all"),
969
+ results = document.querySelector("#search-results");
970
+ const searchStatus = document.querySelector("#search-status"),
971
+ searchTag = document.querySelector("#search-tag"),
972
+ searchScope = document.querySelector("#search-scope"),
973
+ searchComputer = document.querySelector("#search-computer"),
974
+ searchLimit = document.querySelector("#search-limit"),
975
+ searchScore = document.querySelector("#search-score");
976
+ function syncSearchScope() {
977
+ searchScope.disabled = !all.checked;
978
+ searchComputer.disabled = !all.checked || searchScope.value !== "computer";
979
+ searchComputer.required = !searchComputer.disabled;
980
+ document.querySelector("#search-computer-field").hidden = searchComputer.disabled;
981
+ }
982
+ const historyPanel = dialog.querySelector(".search-history");
983
+ const historyList = document.querySelector("#search-history-list");
984
+ const clearHistory = document.querySelector("#search-history-clear");
985
+ const historyKey = () => `backlog:search-history:${JSON.stringify([endpoint, identity.principal])}`;
986
+ function readSearchHistory() {
987
+ try {
988
+ const items = JSON.parse(localStorage.getItem(historyKey()));
989
+ return Array.isArray(items)
990
+ ? [...new Set(items.filter((item) => typeof item === "string" && item.trim()))].slice(0, 30)
991
+ : [];
992
+ } catch {
993
+ return [];
994
+ }
995
+ }
996
+ function renderSearchHistory() {
997
+ const items = readSearchHistory();
998
+ clearHistory.hidden = !items.length;
999
+ historyList.replaceChildren(...items.map((text) => el("button", {
1000
+ type: "button", class: "quiet",
1001
+ onclick: () => {
1002
+ query.value = text;
1003
+ historyPanel.open = false;
1004
+ query.focus();
1005
+ clearTimeout(searchTimer);
1006
+ search();
1007
+ },
1008
+ }, text)));
1009
+ if (!items.length) historyList.append(el("p", { class: "muted" }, "No recent searches."));
1010
+ }
1011
+ function saveSearchHistory(text) {
1012
+ text = text.trim();
1013
+ if (!text || !identity) return;
1014
+ try {
1015
+ localStorage.setItem(historyKey(), JSON.stringify(
1016
+ [text, ...readSearchHistory().filter((item) => item !== text)].slice(0, 30),
1017
+ ));
1018
+ renderSearchHistory();
1019
+ } catch {
1020
+ notify(new Error("The browser could not save search history."));
1021
+ }
1022
+ }
1023
+ clearHistory.onclick = () => {
1024
+ try {
1025
+ localStorage.removeItem(historyKey());
1026
+ renderSearchHistory();
1027
+ } catch {
1028
+ notify(new Error("The browser could not clear search history."));
1029
+ }
1030
+ };
1031
+ let searchAllPreference = false;
1032
+ const searchPreferenceKey = () => `backlog:search:${endpoint}:${identity.principal}`;
1033
+ function searchPlaceholder() {
1034
+ query.placeholder = all.checked ? "Search across all projects" : `Search in ${project}`;
1035
+ }
1036
+ function openSearch() {
1037
+ if (!identity) return;
1038
+ syntaxHelp.open = false;
1039
+ let saved;
1040
+ try {
1041
+ saved = JSON.parse(localStorage.getItem(searchPreferenceKey()));
1042
+ } catch {
1043
+ saved = null;
1044
+ }
1045
+ searchStatus.value = saved?.status || "";
1046
+ searchTag.value = saved?.tag || "";
1047
+ searchScope.value = ["all", "current", "computer"].includes(saved?.scope) ? saved.scope : "all";
1048
+ searchComputer.value = saved?.computer || "";
1049
+ searchLimit.value = saved?.limit ?? 15;
1050
+ searchScore.value = saved?.min_score ?? 0.12;
1051
+ searchAllPreference = saved?.all === true;
1052
+ for (const input of searchKinds)
1053
+ input.checked = Array.isArray(saved?.kinds) ? saved.kinds.includes(input.value) : true;
1054
+ all.checked = !project || searchAllPreference;
1055
+ all.disabled = !project;
1056
+ syncSearchScope();
1057
+ searchPlaceholder();
1058
+ historyPanel.open = false;
1059
+ renderSearchHistory();
1060
+ dialog.showModal();
1061
+ query.focus();
1062
+ search();
1063
+ }
1064
+ document.querySelector("#search-open").onclick = openSearch;
1065
+ document.querySelector("#search-close").onclick = () => dialog.close();
1066
+ document.addEventListener("keydown", (e) => {
1067
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
1068
+ e.preventDefault();
1069
+ openSearch();
1070
+ }
1071
+ });
1072
+ let searchTimer;
1073
+ query.setAttribute("role", "combobox");
1074
+ query.setAttribute("aria-autocomplete", "list");
1075
+ query.setAttribute("aria-controls", "search-results");
1076
+ query.setAttribute("aria-expanded", "false");
1077
+ results.setAttribute("role", "listbox");
1078
+ results.setAttribute("aria-label", "Search results");
1079
+ let renderedSearchKey = null;
1080
+ let searchPosition = null;
1081
+ function rememberSearchPosition() {
1082
+ if (!dialog.open || !renderedSearchKey) return;
1083
+ const active = results.querySelectorAll("a")[selectedResult];
1084
+ searchPosition = {
1085
+ key: renderedSearchKey, id: active?.id, scroll: results.scrollTop,
1086
+ };
1087
+ }
1088
+ results.addEventListener("scroll", rememberSearchPosition);
1089
+ function searchState(text, loading = false) {
1090
+ renderedSearchKey = null;
1091
+ results.replaceChildren(el("p", { class: "search-state", role: "status" }, text));
1092
+ query.removeAttribute("aria-activedescendant");
1093
+ query.setAttribute("aria-expanded", "false");
1094
+ query.setAttribute("aria-busy", String(loading));
1095
+ }
1096
+ function scheduleSearch() {
1097
+ searchGeneration++;
1098
+ clearTimeout(searchTimer);
1099
+ if (!searchKinds.some((input) => input.checked)) {
1100
+ searchState("Select at least one content type to search.");
1101
+ return;
1102
+ }
1103
+ if (!query.value.trim()) {
1104
+ searchState("Start typing to search the selected content.");
1105
+ return;
1106
+ }
1107
+ searchState("Searching…", true);
1108
+ searchTimer = setTimeout(search, 250);
1109
+ }
1110
+ query.oninput = (event) => {
1111
+ if (!event.isComposing) scheduleSearch();
1112
+ };
1113
+ query.addEventListener("compositionend", scheduleSearch);
1114
+ all.onchange = () => {
1115
+ clearTimeout(searchTimer);
1116
+ if (!all.disabled) searchAllPreference = all.checked;
1117
+ syncSearchScope();
1118
+ searchPlaceholder();
1119
+ try {
1120
+ localStorage.setItem(
1121
+ searchPreferenceKey(),
1122
+ JSON.stringify({
1123
+ all: searchAllPreference,
1124
+ status: searchStatus.value,
1125
+ tag: searchTag.value,
1126
+ scope: searchScope.value,
1127
+ computer: searchComputer.value,
1128
+ limit: searchLimit.value,
1129
+ min_score: searchScore.value,
1130
+ kinds: searchKinds.filter((input) => input.checked).map((input) => input.value),
1131
+ }),
1132
+ );
1133
+ } catch {
1134
+ notify(new Error("The browser could not save search preferences."));
1135
+ }
1136
+ search();
1137
+ };
1138
+ for (const input of [
1139
+ ...searchKinds, searchStatus, searchTag, searchScope, searchComputer, searchLimit, searchScore,
1140
+ ]) input.onchange = all.onchange;
1141
+ dialog.addEventListener("close", () => {
1142
+ searchGeneration++;
1143
+ clearTimeout(searchTimer);
1144
+ query.removeAttribute("aria-activedescendant");
1145
+ query.setAttribute("aria-expanded", "false");
1146
+ query.setAttribute("aria-busy", "false");
1147
+ });
1148
+ async function search() {
1149
+ const current = ++searchGeneration;
1150
+ const kinds = searchKinds.filter((input) => input.checked).map((input) => input.value);
1151
+ if (!kinds.length) {
1152
+ searchState("Select at least one content type to search.");
1153
+ return;
1154
+ }
1155
+ if (!query.value.trim()) {
1156
+ searchState("Start typing to search the selected content.");
1157
+ return;
1158
+ }
1159
+ searchState("Searching…", true);
1160
+ try {
1161
+ if (
1162
+ ![searchLimit, searchScore, searchComputer].every((input) => input.checkValidity()) ||
1163
+ (!searchComputer.disabled && !searchComputer.value.trim())
1164
+ ) {
1165
+ searchState("Check the filters: limit 1–200, similarity -1–1, and a computer name when required.");
1166
+ return;
1167
+ }
1168
+ const args = {
1169
+ query: [query.value], kinds,
1170
+ limit: Number(searchLimit.value), min_score: Number(searchScore.value),
1171
+ };
1172
+ if (searchStatus.value) args.status = [searchStatus.value];
1173
+ if (searchTag.value.trim()) args.tag = searchTag.value.trim();
1174
+ if (!all.checked && project) args.project = project;
1175
+ else if (searchScope.value === "current") args.all_projects = true;
1176
+ else if (searchScope.value === "computer") args.computer = searchComputer.value.trim();
1177
+ else args.all_computers = true;
1178
+ const key = JSON.stringify([endpoint, identity.principal, args]);
1179
+ const position = searchPosition?.key === key ? searchPosition : null;
1180
+ const found = await call("search", args);
1181
+ if (current !== searchGeneration || !identity || !dialog.open) return;
1182
+ query.setAttribute("aria-busy", "false");
1183
+ results.replaceChildren();
1184
+ for (const kind of kinds) {
1185
+ if (!found[kind].length) continue;
1186
+ results.append(el("h3", { role: "presentation" }, searchLabels[kind]));
1187
+ for (const item of found[kind])
1188
+ results.append(
1189
+ el(
1190
+ "a",
1191
+ {
1192
+ class: "search-result",
1193
+ id: `search-${kind}-${item.id}`,
1194
+ role: "option",
1195
+ "aria-selected": "false",
1196
+ href:
1197
+ kind === "memory"
1198
+ ? memoryRoute(item.project, new URLSearchParams({ note: item.id }))
1199
+ : kind === "projects"
1200
+ ? projectRoute(item.full_name)
1201
+ : taskRoute(item.task_id || item.id),
1202
+ onclick: (event) => {
1203
+ if (kind === "tasks" || kind === "comments") saveSearchHistory(args.query[0]);
1204
+ selectedResult = [...results.querySelectorAll("a")].indexOf(event.currentTarget);
1205
+ highlight(false);
1206
+ dialog.close();
1207
+ },
1208
+ },
1209
+ el(
1210
+ "strong",
1211
+ {},
1212
+ kind === "tasks"
1213
+ ? `#${item.id} ${item.title}`
1214
+ : kind === "comments"
1215
+ ? `Comment on #${item.task_id}`
1216
+ : item.title || item.name,
1217
+ ),
1218
+ el(
1219
+ "small",
1220
+ { class: "search-meta" },
1221
+ [item.project || item.full_name, item.status, item.shared ? "Shared" : ""]
1222
+ .filter(Boolean)
1223
+ .join(" · "),
1224
+ ),
1225
+ el("small", {}, (item.snippet || item.body || item.description || "").slice(0, 220)),
1226
+ ),
1227
+ );
1228
+ }
1229
+ if (!results.children.length)
1230
+ searchState("No matches. Try another query or search all projects.");
1231
+ query.setAttribute("aria-expanded", String(Boolean(results.querySelector("a"))));
1232
+ const links = [...results.querySelectorAll("a")];
1233
+ const restoredIndex = position ? links.findIndex((link) => link.id === position.id) : -1;
1234
+ selectedResult = Math.max(0, restoredIndex);
1235
+ results.scrollTop = restoredIndex >= 0 ? position.scroll : 0;
1236
+ renderedSearchKey = key;
1237
+ highlight(false);
1238
+ } catch (error) {
1239
+ if (current === searchGeneration)
1240
+ searchState(`Search failed: ${error.message}. Edit the query to retry.`);
1241
+ }
1242
+ }
1243
+ function highlight(scroll = true) {
1244
+ const links = [...results.querySelectorAll("a")];
1245
+ links.forEach((a, i) => {
1246
+ a.classList.toggle("selected", i === selectedResult);
1247
+ a.setAttribute("aria-selected", String(i === selectedResult));
1248
+ });
1249
+ const active = links[selectedResult];
1250
+ if (active) {
1251
+ query.setAttribute("aria-activedescendant", active.id);
1252
+ if (scroll) {
1253
+ if (active.offsetTop < results.scrollTop) results.scrollTop = active.offsetTop;
1254
+ if (active.offsetTop + active.offsetHeight > results.scrollTop + results.clientHeight)
1255
+ results.scrollTop = active.offsetTop + active.offsetHeight - results.clientHeight;
1256
+ }
1257
+ }
1258
+ rememberSearchPosition();
1259
+ }
1260
+ query.onkeydown = (e) => {
1261
+ if (e.isComposing) return;
1262
+ const links = [...results.querySelectorAll("a")];
1263
+ if (!links.length) return;
1264
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
1265
+ e.preventDefault();
1266
+ selectedResult =
1267
+ (selectedResult + (e.key === "ArrowDown" ? 1 : -1) + links.length) % links.length;
1268
+ highlight();
1269
+ }
1270
+ if (e.key === "Enter") {
1271
+ e.preventDefault();
1272
+ links[selectedResult]?.click();
1273
+ }
1274
+ };
1275
+ document.addEventListener("click", (event) => {
1276
+ if (
1277
+ event.defaultPrevented ||
1278
+ event.button !== 0 ||
1279
+ event.metaKey ||
1280
+ event.ctrlKey ||
1281
+ event.shiftKey ||
1282
+ event.altKey
1283
+ )
1284
+ return;
1285
+ const anchor = event.target.closest("a[href]");
1286
+ if (!anchor || anchor.target || anchor.hasAttribute("download")) return;
1287
+ const url = new URL(anchor.href);
1288
+ if (url.origin !== location.origin || !["/ui", "/ui/"].includes(url.pathname)) return;
1289
+ event.preventDefault();
1290
+ navigate(url.href);
1291
+ });
1292
+ window.addEventListener("popstate", render);
1293
+ window.addEventListener("hashchange", render);
1294
+ connect().catch((error) => {
1295
+ if (error instanceof HttpError && error.status === 401)
1296
+ showLogin(error, Boolean(loadCredentials(endpoint)));
1297
+ else {
1298
+ showLogin();
1299
+ notify(error);
1300
+ }
1301
+ });