@todu/herdr-todu 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Erik Craddock
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # Herdr Todu panel
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A task pane for Herdr Desktop. It follows the focused terminal’s repository. Use the **Status** and **Priority** filters together to narrow the list. Status defaults to open tasks; **All statuses** also includes done and canceled tasks. **Reset** restores the defaults. Select a task to see its description and discussion, including authors and timestamps. **← Tasks** returns to the list; **Refresh (r)** reloads the current view from the daemon. With the panel focused, press **r** in the task list, Task Details, or the project picker. Selecting a task does not change it. In Task Details, click **Status** or **Priority**, then click a value to save just that field. Descriptions and comments use Herdr’s native Markdown preview. Raw HTML is shown literally, and imported content pending approval stays plain text.
4
+
5
+ ### Keyboard navigation
6
+
7
+ With the panel focused, use **j/k** (or ↓/↑) to move the highlight, **g/G** for first/last, and **l** or **Enter** to open. **h** goes from details to tasks or from tasks to projects. **Shift+P** toggles the project picker; choose **Follow current folder** to resume repository-based selection. Browsing another project does not change the terminal’s directory. In Task Details, **j/k** or **↓/↑** scroll by line, **Page Up/Page Down** scroll by page, and **g/G** jump to the top/bottom. On the task list, **s** opens the status filter and **p** opens the priority filter. Use **j/k** to highlight a value and **Enter** to apply it without editing any task. In Task Details, the same keys edit that task’s status or priority; **Enter** saves. **Esc** cancels either chooser. To move keyboard focus from the terminal into a neighboring panel, use Herdr’s pane navigation (⌘⌥→ for a pane on the right in the default macOS bindings).
8
+
9
+ ## Install and open
10
+
11
+ You need Herdr Desktop, Node.js 24+ with npm, Git, and a running Todu daemon on a supported Unix host. To follow a repository automatically, it must be registered with Todu. Installing this panel does not install a daemon service, start a daemon, or register a project.
12
+
13
+ ```sh
14
+ npm install -g @todu/herdr-todu
15
+ herdr-todu install-mod
16
+ ```
17
+
18
+ Run this as the user who runs Herdr. The installer writes the panel into `${HERDR_APP_HOME:-$HOME/.config/herdr-app}/mods/herdr-todu` and records the installed helper and Node executable so the local GUI does not need your interactive shell's PATH. It does not modify your layout, keybindings or other mods. If migrating from the manual preview, move the old mod directory aside and retire its old helper launcher first; the installer will not overwrite an unmanaged mod. Use `command -v herdr-todu` to check which helper your shell is invoking.
19
+
20
+ From a terminal in the registered project inside Herdr, open the panel:
21
+
22
+ ```sh
23
+ herdr-app do pane.split --direction right --mod herdr-todu
24
+ ```
25
+
26
+ The pane title should show the project's name. If several terminals are present, focus the project's terminal once. To diagnose a connection or binding problem, run `herdr-todu tasks` in that terminal. Remote spaces run the helper on the **remote machine**: install the npm package there too and ensure Herdr's remote environment can find Node, Git, and `herdr-todu` on PATH and reach that machine's daemon.
27
+
28
+ ## Update
29
+
30
+ ```sh
31
+ npm install -g @todu/herdr-todu@latest
32
+ herdr-todu install-mod
33
+ ```
34
+
35
+ Close and reopen the panel. Repeat the install commands if you change your Node version manager's active installation or move your npm global prefix. No source checkout, build, or custom launcher is needed.
36
+
37
+ ## How it works
38
+
39
+ The Herdr view invokes a short-lived TypeScript helper with the terminal’s working directory. It uses the workspace CLI’s socket client and configuration; it does not initialize storage or launch a daemon. No Pi extension or Git provider credentials are required.
40
+
41
+ Edits target the task ID. The helper checks its project before saving, but the check and write are separate daemon calls. If another client moves that task between the two calls, the edit can follow it into the destination project.
42
+
43
+ Matching follows the Pi extension’s repository check: prefer `origin`, otherwise use a sole remote. Match the normalized provider and target ref to exactly one repository integration binding (including bindings with sync disabled), then use its project ID. No match, ambiguous remotes or bindings, and unavailable data produce a message rather than a guessed project. The open list includes active, in-progress and waiting tasks, with in-progress tasks first.
package/dist/index.js ADDED
@@ -0,0 +1,68 @@
1
+ #!/usr/bin/env node
2
+ import { parseArgs } from "node:util";
3
+ import { getConfigPath, loadConfig, resolveDataDir } from "@todu/cli/dist/config.js";
4
+ import { formatDaemonCommandError, resolveDaemonSocketPath, } from "@todu/cli/dist/daemon-command-client.js";
5
+ import { createDaemonTransportClient } from "@todu/cli/dist/daemon-transport.js";
6
+ import { isTaskPriority, isTaskStatus } from "@todu/core";
7
+ import { installMod } from "./install-mod.js";
8
+ import { editTask, listProjects, panelData } from "./panel-data.js";
9
+ import { repositoryAt } from "./repository.js";
10
+ async function main() {
11
+ const { positionals: [cmd, id, ...rest], values: { status, priority, project }, } = parseArgs({
12
+ allowPositionals: true,
13
+ options: {
14
+ project: { type: "string" },
15
+ status: { type: "string" },
16
+ priority: { type: "string" },
17
+ },
18
+ });
19
+ if (cmd === "install-mod") {
20
+ if (id !== undefined ||
21
+ rest.length ||
22
+ Object.values({ status, priority, project }).some((v) => v !== undefined))
23
+ throw new Error("Usage: herdr-todu install-mod");
24
+ return { installed: await installMod() };
25
+ }
26
+ if (status !== undefined && status !== "all" && !isTaskStatus(status))
27
+ throw new Error("Invalid status filter.");
28
+ if (priority !== undefined && !isTaskPriority(priority))
29
+ throw new Error("Invalid priority filter.");
30
+ if (!((cmd === "projects" && !id && !status && !priority && !project) ||
31
+ (cmd === "update" &&
32
+ id &&
33
+ project &&
34
+ ((status && status !== "all" && priority === undefined) ||
35
+ (priority && status === undefined))) ||
36
+ (cmd === "tasks" && id === undefined) ||
37
+ (cmd === "detail" && id && status === undefined && priority === undefined)) ||
38
+ rest.length) {
39
+ throw new Error("Usage: herdr-todu projects | tasks [--project ID] [--status STATUS] [--priority PRIORITY] | detail TASK_ID [--project ID] | update TASK_ID --project ID (--status STATUS | --priority PRIORITY)");
40
+ }
41
+ const config = getConfigPath();
42
+ const socketPath = resolveDaemonSocketPath(resolveDataDir(config, loadConfig(config)));
43
+ const client = createDaemonTransportClient({ socketPath });
44
+ const request = async (method, params) => {
45
+ const result = await client.request(method, params);
46
+ if (!result.ok)
47
+ throw new Error(formatDaemonCommandError(result.error));
48
+ return result.value;
49
+ };
50
+ if (cmd === "update") {
51
+ if (id && project && status && isTaskStatus(status))
52
+ return editTask(request, project, id, { status });
53
+ if (id && project && priority)
54
+ return editTask(request, project, id, { priority });
55
+ throw new Error("Choose one task status or priority.");
56
+ }
57
+ if (cmd === "projects")
58
+ return listProjects(request);
59
+ const scope = project ? { projectId: project } : await repositoryAt(process.cwd());
60
+ return panelData(scope, request, id, { status, priority });
61
+ }
62
+ main()
63
+ .then((value) => console.log(JSON.stringify(value)))
64
+ .catch((error) => {
65
+ console.error(error instanceof Error ? error.message : "Cannot read Todu data.");
66
+ process.exitCode = 1;
67
+ });
68
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,44 @@
1
+ import { copyFile, lstat, mkdir, mkdtemp, readFile, rename, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { join, resolve } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const owner = "@todu/herdr-todu\n";
6
+ const marker = ".todu-npm-install";
7
+ const assets = ["context.js", "main.js", "mod.json"];
8
+ export async function installMod(home = process.env.HERDR_APP_HOME || join(homedir(), ".config/herdr-app")) {
9
+ const mods = resolve(home, "mods");
10
+ const target = join(mods, "herdr-todu");
11
+ await mkdir(mods, { recursive: true });
12
+ const stage = await mkdtemp(join(mods, ".herdr-todu-"));
13
+ try {
14
+ for (const file of assets)
15
+ await copyFile(new URL(`../mod/${file}`, import.meta.url), join(stage, file));
16
+ const runtime = {
17
+ node: process.execPath,
18
+ helper: fileURLToPath(new URL("./index.js", import.meta.url)),
19
+ };
20
+ await writeFile(join(stage, "runtime.js"), `export const localRuntime = ${JSON.stringify(runtime)};\n`);
21
+ await writeFile(join(stage, marker), owner);
22
+ const stat = await lstat(target).catch((error) => {
23
+ if (error.code !== "ENOENT")
24
+ throw error;
25
+ return null;
26
+ });
27
+ if (!stat) {
28
+ await rename(stage, target);
29
+ }
30
+ else {
31
+ if (!stat.isDirectory() ||
32
+ (await readFile(join(target, marker), "utf8").catch(() => null)) !== owner)
33
+ throw new Error(`Not replacing an unmanaged mod at ${target}. Move it aside first.`);
34
+ // Replace only our own files. Herdr may keep its own files here too.
35
+ for (const file of ["runtime.js", ...assets])
36
+ await rename(join(stage, file), join(target, file));
37
+ }
38
+ return target;
39
+ }
40
+ finally {
41
+ await rm(stage, { recursive: true, force: true });
42
+ }
43
+ }
44
+ //# sourceMappingURL=install-mod.js.map
@@ -0,0 +1,93 @@
1
+ import { isValidStatusTransition, TASK_STATUSES } from "@todu/core";
2
+ function statusChoices(from) {
3
+ return TASK_STATUSES.filter((to) => isValidStatusTransition(from, to));
4
+ }
5
+ export async function listProjects(request) {
6
+ const projects = await request("project.list", {});
7
+ return {
8
+ projects: projects
9
+ .map(({ id, name, status }) => ({ id, name, status }))
10
+ .sort((a, b) => a.name.localeCompare(b.name)),
11
+ };
12
+ }
13
+ async function projectForRepo(repo, request) {
14
+ const bindings = await request("integration.list", {
15
+ filter: { provider: repo.provider },
16
+ });
17
+ const matches = bindings.filter((b) => b.targetKind === "repository" &&
18
+ b.provider === repo.provider &&
19
+ b.targetRef === repo.targetRef);
20
+ if (!matches.length)
21
+ throw new Error(`No Todu project registered for ${repo.provider}:${repo.targetRef}.`);
22
+ if (matches.length !== 1)
23
+ throw new Error(`Multiple Todu bindings match ${repo.targetRef}.`);
24
+ return matches[0].projectId;
25
+ }
26
+ export async function editTask(request, projectId, id, edit) {
27
+ const task = await request("task.get", { id });
28
+ if (task.projectId !== projectId)
29
+ throw new Error("Task no longer belongs to this project.");
30
+ const updated = await request("task.update", { id, input: edit });
31
+ return {
32
+ id: updated.id,
33
+ status: updated.status,
34
+ priority: updated.priority,
35
+ statusChoices: statusChoices(updated.status),
36
+ };
37
+ }
38
+ export async function panelData(scope, request, taskId, filters = {}) {
39
+ const projectId = "projectId" in scope ? scope.projectId : await projectForRepo(scope, request);
40
+ if (taskId) {
41
+ const task = await request("task.get", { id: taskId });
42
+ if (task.projectId !== projectId)
43
+ throw new Error("Task no longer belongs to this project.");
44
+ const [project, notes, actors] = await Promise.all([
45
+ request("project.get", { id: projectId }),
46
+ request("note.list", { filter: { entityType: "task", entityId: taskId } }),
47
+ request("actor.list"),
48
+ ]);
49
+ const names = new Map(actors.map((a) => [a.id, a.displayName]));
50
+ return {
51
+ projectId,
52
+ project: project.name,
53
+ title: task.title,
54
+ status: task.status,
55
+ statusChoices: statusChoices(task.status),
56
+ priority: task.priority,
57
+ description: task.description ?? "",
58
+ approval: task.descriptionApproval?.state,
59
+ comments: notes
60
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt))
61
+ .map((n) => ({
62
+ id: n.id,
63
+ author: (n.authorActorId && names.get(n.authorActorId)) ||
64
+ n.author ||
65
+ n.authorActorId ||
66
+ "Unknown author",
67
+ createdAt: n.createdAt,
68
+ content: n.content,
69
+ approval: n.contentApproval?.state,
70
+ })),
71
+ };
72
+ }
73
+ const [project, tasks] = await Promise.all([
74
+ request("project.get", { id: projectId }),
75
+ request("task.list", {
76
+ filter: {
77
+ projectId,
78
+ ...(filters.status === "all"
79
+ ? {}
80
+ : { status: filters.status ?? ["active", "inprogress", "waiting"] }),
81
+ ...(filters.priority && { priority: filters.priority }),
82
+ },
83
+ }),
84
+ ]);
85
+ return {
86
+ project: project.name,
87
+ tasks: tasks
88
+ .sort((a, b) => Number(b.status === "inprogress") - Number(a.status === "inprogress") ||
89
+ a.title.localeCompare(b.title))
90
+ .map(({ id, title, status, priority }) => ({ id, title, status, priority })),
91
+ };
92
+ }
93
+ //# sourceMappingURL=panel-data.js.map
@@ -0,0 +1,36 @@
1
+ import { execFile } from "node:child_process";
2
+ import { promisify } from "node:util";
3
+ const exec = promisify(execFile);
4
+ export function selectRemote(names) {
5
+ if (names.includes("origin"))
6
+ return "origin";
7
+ if (names.length === 1)
8
+ return names[0];
9
+ throw new Error(names.length
10
+ ? "Multiple Git remotes and no origin. Cannot select a project."
11
+ : "This repository has no Git remotes.");
12
+ }
13
+ export function normalizeRemote(raw) {
14
+ const match = /^(?:git@([^:/]+):|ssh:\/\/git@([^/]+)\/|https?:\/\/([^/]+)\/)(.+?)\/?$/.exec(raw);
15
+ if (!match)
16
+ throw new Error("Unsupported Git remote format.");
17
+ const host = (match[1] ?? match[2] ?? match[3]).split("@").pop()?.toLowerCase();
18
+ const targetRef = match[4].replace(/^\/+|\/+$/g, "").replace(/\.git$/, "");
19
+ if (!host || !targetRef.includes("/"))
20
+ throw new Error("Unsupported Git remote format.");
21
+ return { provider: host === "github.com" ? "github" : "forgejo", targetRef };
22
+ }
23
+ export async function repositoryAt(cwd) {
24
+ const git = async (...args) => (await exec("git", ["-C", cwd, ...args], { timeout: 5000 })).stdout.trim();
25
+ try {
26
+ await git("rev-parse", "--show-toplevel");
27
+ }
28
+ catch (error) {
29
+ if (error.code === "ENOENT")
30
+ throw new Error("Git is not installed.");
31
+ throw new Error("Cannot find a Git working tree in the focused folder.");
32
+ }
33
+ const name = selectRemote((await git("remote")).split(/\r?\n/).filter(Boolean));
34
+ return normalizeRemote(await git("remote", "get-url", "--", name));
35
+ }
36
+ //# sourceMappingURL=repository.js.map
package/mod/context.js ADDED
@@ -0,0 +1,13 @@
1
+ // When the panel takes focus, continue following the same terminal, not the space folder.
2
+ export function panelContext(focus, allPanes, space, previous) {
3
+ if (!focus || !space) return null;
4
+ const tab = focus.tab;
5
+ const candidates = allPanes.filter(p => p.tab === tab && p.terminal);
6
+ const pane = focus.terminal ? null : candidates.find(p => p.terminal === previous?.terminal)
7
+ ?? (!previous && candidates.length === 1 ? candidates[0] : null);
8
+ const terminal = focus.terminal ?? pane?.terminal;
9
+ const cwd = focus.terminal ? focus.cwd : pane?.cwd;
10
+ if (!terminal || !cwd) return null;
11
+ const on = terminal.includes("/") ? terminal.split("/")[0] : focus.terminal && focus.pane === null ? null : space.machine;
12
+ return { tab, cwd, terminal, on };
13
+ }
package/mod/main.js ADDED
@@ -0,0 +1,325 @@
1
+ import { View, div } from "gpui-kit";
2
+ import { h_flex, ScrollHandle, TextView, v_flex } from "gpui-base";
3
+ import { checking, exec, focused, nextCommand, panes, run, spaces, theme } from "herdr";
4
+ import { panelContext } from "./context.js";
5
+ import { localRuntime } from "./runtime.js";
6
+
7
+ function runHelper(args, {cwd, on}) {
8
+ if (on == null && localRuntime) return exec(localRuntime.node, [localRuntime.helper, ...args], {cwd, on});
9
+ return exec("herdr-todu", args, {cwd, on});
10
+ }
11
+
12
+ function button(id, label, click) {
13
+ return div().id(id).p(6).rounded(5).cursor_pointer().hover(s => s.bg(theme().hover))
14
+ .on_click((_event, cx) => click(cx)).child(label);
15
+ }
16
+
17
+ function statusLabel(status) {
18
+ return { inprogress: "In progress", active: "Active", waiting: "Waiting", done: "Done", canceled: "Canceled" }[status] ?? status;
19
+ }
20
+
21
+ function taskMeta(id, task) {
22
+ return div().text_size(12).text_color(theme().muted)
23
+ .child([id, statusLabel(task.status), task.priority && `${task.priority} priority`].filter(Boolean).join(" · "));
24
+ }
25
+
26
+ const DEFAULT_FILTERS = { status: "open", priority: "any" };
27
+ const FILTER_LABELS = {
28
+ status: { open: "Open", all: "All statuses", active: "Active", inprogress: "In progress", waiting: "Waiting", done: "Done", canceled: "Canceled" },
29
+ priority: { any: "Any", high: "High", medium: "Medium", low: "Low" },
30
+ };
31
+
32
+ function listArgs({ status, priority }) {
33
+ return ["tasks", ...(status === "open" ? [] : ["--status", status]), ...(priority === "any" ? [] : ["--priority", priority])];
34
+ }
35
+
36
+ function filterBar(filters, expanded, highlighted, toggle, select, reset) {
37
+ const t = theme();
38
+ const controls = h_flex().flex_wrap().items_center().gap(6);
39
+ for (const [key, label] of [["status", "Status"], ["priority", "Priority"]]) {
40
+ const value = FILTER_LABELS[key][filters[key]];
41
+ controls.child(button(`filter-${key}`, `${label}: ${value} ▾`, cx => toggle(key, cx))
42
+ .bg(filters[key] !== DEFAULT_FILTERS[key] || expanded === key ? t.selected : t.surface)
43
+ .accessibility_label(`Filter by ${label.toLowerCase()}: ${value}`));
44
+ }
45
+ if (filters.status !== "open" || filters.priority !== "any") {
46
+ controls.child(button("filter-reset", "Reset", reset).text_color(t.muted));
47
+ }
48
+ const bar = v_flex().gap(4).child(controls);
49
+ if (expanded) {
50
+ const choices = h_flex().flex_wrap().gap(4);
51
+ for (const [value, label] of Object.entries(FILTER_LABELS[expanded])) {
52
+ const selected = value === filters[expanded];
53
+ choices.child(button(`choose-${expanded}-${value}`, selected ? `✓ ${label}` : label,
54
+ cx => select({ ...filters, [expanded]: value }, cx)).when(value === highlighted, el => el.bg(t.selected)));
55
+ }
56
+ bar.child(choices);
57
+ }
58
+ return bar;
59
+ }
60
+
61
+ function editValues(field, data) {
62
+ return field === "status" ? data?.statusChoices ?? [] : field === "priority" ? ["high", "medium", "low"] : [];
63
+ }
64
+
65
+ function projectPane(tab) {
66
+ const matches = panes().filter(p => p.tab === tab && p.mod === "herdr-todu");
67
+ return matches.length === 1 ? matches[0] : null;
68
+ }
69
+
70
+ function setProjectTitle(tab, name) {
71
+ if (checking() || !name || !tab || focused()?.tab !== tab) return;
72
+ const pane = projectPane(tab);
73
+ if (pane && pane.name !== name) run("pane.rename", { pane: pane.pane, name });
74
+ }
75
+
76
+ function markdownBody(id, text, approval) {
77
+ if (approval === "pendingApproval") return div().child(text);
78
+ return TextView.markdown(id, text).raw_html(false).selectable(true).scrollable(false).w_full().flex_none();
79
+ }
80
+
81
+ function taskRow(task, click) {
82
+ return v_flex().id(task.id).gap(2).px(6).py(4).rounded(5)
83
+ .cursor_pointer().hover(s => s.bg(theme().hover)).on_click((_event, cx) => click(cx))
84
+ .child(div().font_medium().child(task.title))
85
+ .child(taskMeta(task.id, task));
86
+ }
87
+
88
+ export default class ToduPanel extends View {
89
+ init(_props, cx) {
90
+ this.focusHandle = cx.focus_handle();
91
+ this.scroll = ScrollHandle.new();
92
+ this.projects = new Map();
93
+ this.cursors = new Map();
94
+ this.picking = false;
95
+ if (!checking()) cx.spawn(async () => {
96
+ while (!this.closed) {
97
+ const command = await nextCommand();
98
+ if (!this.closed && command === "focus") this.focusHandle.focus();
99
+ }
100
+ });
101
+ this.key = undefined;
102
+ this.generation = 0;
103
+ this.sources = new Map();
104
+ this.filters = new Map();
105
+ this.expandedFilter = null;
106
+ this.selected = new Map();
107
+ }
108
+
109
+ load(cx, taskId) {
110
+ const generation = ++this.generation;
111
+ const location = this.location;
112
+ this.data = null;
113
+ this.error = null;
114
+ this.taskId = taskId;
115
+ this.editor = null;
116
+ this.editError = null;
117
+ this.markerY = 0;
118
+ if (!location || checking()) return;
119
+ const scope = this.scopeKey();
120
+ if (!this.picking) {
121
+ if (taskId) this.selected.set(scope, taskId);
122
+ else this.selected.delete(scope);
123
+ }
124
+ const args = this.picking ? ["projects"] : taskId ? ["detail", taskId] : listArgs(this.filters.get(scope) ?? DEFAULT_FILTERS);
125
+ if (!this.picking && this.projects.has(this.key)) args.push("--project", this.projects.get(this.key));
126
+ cx.spawn(async cx => {
127
+ try {
128
+ const r = await runHelper(args, location);
129
+ if (generation !== this.generation) return;
130
+ if (r.code !== 0) throw new Error(r.stderr.trim() || "Cannot read Todu data.");
131
+ this.data = JSON.parse(r.stdout);
132
+ setProjectTitle(location.tab, this.picking ? "Projects" : this.data.project);
133
+ this.reveal = true;
134
+ } catch (error) {
135
+ if (generation === this.generation) {
136
+ this.error = String(error);
137
+ setProjectTitle(location.tab, "Todu tasks");
138
+ }
139
+ } finally { if (generation === this.generation) cx.notify(); }
140
+ });
141
+ }
142
+
143
+ scopeKey() { return JSON.stringify([this.key, this.projects.get(this.key)]); }
144
+
145
+ startEdit(field, cx) {
146
+ if (this.saving || !this.data?.projectId || this.editError) return;
147
+ this.editor = {field, index: Math.max(0, editValues(field, this.data).indexOf(this.data[field]))};
148
+ cx.notify();
149
+ }
150
+
151
+ saveEdit(field, value, cx) {
152
+ if (this.saving || this.editError || !this.data?.projectId || !this.taskId || !editValues(field, this.data).includes(value)) return;
153
+ this.editor = null;
154
+ if (value === this.data[field]) { cx.notify(); return; }
155
+ const generation = this.generation, task = this.taskId, {cwd, on} = this.location;
156
+ const args = ["update", task, "--project", this.data.projectId, `--${field}`, value];
157
+ this.saving = true;
158
+ cx.notify();
159
+ cx.spawn(async cx => {
160
+ try {
161
+ const r = await runHelper(args, {cwd, on});
162
+ if (r.code !== 0) throw new Error(r.stderr.trim() || "Task update failed.");
163
+ const updated = JSON.parse(r.stdout);
164
+ if (updated.id !== task || updated[field] !== value) throw new Error("The update was not confirmed.");
165
+ if (generation === this.generation) Object.assign(this.data, {status: updated.status, statusChoices: updated.statusChoices, priority: updated.priority});
166
+ } catch (error) {
167
+ if (generation === this.generation) this.editError = `${error} Refresh to check the task before editing again.`;
168
+ } finally { this.saving = false; if (!this.closed) cx.notify(); }
169
+ });
170
+ }
171
+
172
+ scrollDetail(key, markerIndex) {
173
+ const h = this.scroll.viewport_size().height, y = this.scroll.offset().y;
174
+ const max = Math.max(0, this.scroll.content_size().height - h);
175
+ const dest = ({j:y+40, down:y+40, k:y-40, up:y-40, pagedown:y+h, pageup:y-h, g:0, G:max, "shift-g":max})[key];
176
+ if (dest === undefined) return false;
177
+ const target = Math.max(0, Math.min(max, dest));
178
+ if (h && target !== y) {
179
+ // Reveal a point inside long Markdown blocks, not just the next whole block.
180
+ this.markerY = target > y ? target + h - 1 : target;
181
+ this.scroll.scroll_to_item(markerIndex);
182
+ }
183
+ return true;
184
+ }
185
+
186
+ close() {
187
+ this.closed = true;
188
+ ++this.generation;
189
+ this.scroll.release();
190
+ this.focusHandle.release();
191
+ }
192
+
193
+ render(cx) {
194
+ const f = focused();
195
+ const location = panelContext(f, panes(), spaces().find(s => s.id === f?.space), this.sources.get(f?.tab));
196
+ if (location) this.sources.set(location.tab, location);
197
+ const key = JSON.stringify(location && [location.on, location.tab, location.cwd]);
198
+ if (key !== this.key) {
199
+ this.location = location;
200
+ this.key = key;
201
+ this.expandedFilter = null;
202
+ this.picking = false;
203
+ if (!location) setProjectTitle(f?.tab, "Todu tasks");
204
+ this.load(cx, this.selected.get(this.scopeKey()));
205
+ }
206
+ const action = (c, id) => { this.expandedFilter = null; this.load(c, id); c.notify(); };
207
+ const refresh = c => { if (!this.saving) action(c, this.taskId); };
208
+ const scope = this.scopeKey();
209
+ const cursorKey = this.picking ? `projects:${key}` : scope;
210
+ const filters = this.filters.get(scope) ?? DEFAULT_FILTERS;
211
+ const select = (next, c) => { this.cursors.delete(scope); this.filters.set(scope, next); action(c); };
212
+ const picker = c => { this.picking = !this.picking; action(c, this.picking ? undefined : this.selected.get(scope)); };
213
+ const toggle = (kind, c) => {
214
+ this.expandedFilter = this.expandedFilter === kind ? null : kind;
215
+ this.filterChoice = filters[kind];
216
+ c.notify();
217
+ };
218
+ const data = this.data;
219
+ const section = this.picking ? "Projects" : this.taskId ? "Task details" : (data?.tasks ? `Tasks (${data.tasks.length})` : "Tasks");
220
+ const items = this.picking && data ? [{id: null, name: "↩ Follow current folder"}, ...data.projects] : data?.tasks ?? [];
221
+ let cursor = Math.min(this.cursors.get(cursorKey) ?? 0, Math.max(0, items.length - 1));
222
+ const open = (i, c) => {
223
+ const item = items[i];
224
+ if (!item) return;
225
+ this.cursors.set(cursorKey, i);
226
+ if (this.picking) {
227
+ this.picking = false;
228
+ if (item.id) this.projects.set(key, item.id); else this.projects.delete(key);
229
+ action(c);
230
+ } else action(c, item.id);
231
+ };
232
+ const heading = data?.project && !projectPane(f?.tab) ? `${data.project} · ${section}` : section;
233
+ const rows = [];
234
+ if (!location || this.error || !data) {
235
+ rows.push(div().child(!location ? "Focus a terminal in the project folder." : this.error || "Loading…"));
236
+ } else if (this.picking) {
237
+ items.forEach((p, i) => rows.push(button(`project-${p.id ?? "folder"}`, p.name, c => open(i, c))
238
+ .when(i === cursor, el => el.bg(theme().selected))));
239
+ } else if (this.taskId) {
240
+ rows.push(div().font_semibold().child(data.title), div().text_color(theme().muted).child(this.taskId));
241
+ rows.push(h_flex().flex_wrap().gap(6)
242
+ .child(button("edit-status", `Status: ${statusLabel(data.status)} ▾`, c => this.startEdit("status", c)).bg(theme().surface))
243
+ .child(button("edit-priority", `Priority: ${data.priority} ▾`, c => this.startEdit("priority", c)).bg(theme().surface)));
244
+ if (this.saving || this.editError) rows.push(div().child(this.editError || "Saving…"));
245
+ if (data.approval === "pendingApproval") rows.push(div().child("Imported description · pending approval"));
246
+ rows.push(data.description
247
+ ? markdownBody(`description-${this.taskId}`, data.description, data.approval)
248
+ : div().text_color(theme().muted).child("No description"));
249
+ rows.push(div().font_semibold().child(`Comments (${data.comments.length})`));
250
+ for (const [index, c] of data.comments.entries()) {
251
+ rows.push(div().text_color(theme().muted).child(`${c.author} · ${c.createdAt}${c.approval === "pendingApproval" ? " · pending approval" : ""}`),
252
+ markdownBody(`comment-${this.taskId}-${c.id ?? index}`, c.content, c.approval));
253
+ }
254
+ } else {
255
+ if (!data.tasks.length) rows.push(div().child("No tasks match these filters."));
256
+ items.forEach((task, i) => rows.push(taskRow(task, c => open(i, c))
257
+ .when(i === cursor, el => el.bg(theme().selected))));
258
+ }
259
+ if (this.taskId && data) rows.push(div().absolute().top(this.markerY).left(0).w(1).h(1));
260
+ if (this.reveal) {
261
+ this.scroll.scroll_to_item(this.taskId ? 0 : cursor);
262
+ this.reveal = false;
263
+ }
264
+ const onKey = (e, c) => {
265
+ if (!location || e.modifiers?.platform || e.modifiers?.control || e.modifiers?.alt) return;
266
+ const k = e.key_char?.trim() || e.keystroke;
267
+ const matches = (...keys) => keys.includes(k) || keys.includes(e.keystroke);
268
+ if (this.taskId && this.saving) return;
269
+ if (this.editor) {
270
+ const ed = this.editor, values = editValues(ed.field, data);
271
+ if (matches("escape", "h", "left")) this.editor = null;
272
+ else if (matches("j", "down")) ed.index = Math.min(values.length - 1, ed.index + 1);
273
+ else if (matches("k", "up")) ed.index = Math.max(0, ed.index - 1);
274
+ else if (matches("enter")) this.saveEdit(ed.field, values[ed.index], c);
275
+ else return;
276
+ } else if (matches("P", "shift-p")) {
277
+ picker(c);
278
+ } else if (!this.picking && matches("s", "p")) {
279
+ const field = matches("s") ? "status" : "priority";
280
+ if (this.taskId) this.startEdit(field, c);
281
+ else toggle(field, c);
282
+ } else if (this.taskId && data && this.scrollDetail(k, rows.length - 1)) {
283
+ // The scroll request takes effect on the next render.
284
+ } else if (this.expandedFilter) {
285
+ const field = this.expandedFilter;
286
+ const values = Object.keys(FILTER_LABELS[field]);
287
+ const index = values.indexOf(this.filterChoice);
288
+ if (matches("escape", "h")) this.expandedFilter = null;
289
+ else if (matches("j", "down", "right")) this.filterChoice = values[Math.min(index + 1, values.length - 1)];
290
+ else if (matches("k", "up", "left")) this.filterChoice = values[Math.max(index - 1, 0)];
291
+ else if (matches("enter")) select({ ...filters, [field]: this.filterChoice }, c);
292
+ else return;
293
+ } else if (matches("r") && !e.modifiers?.shift) {
294
+ refresh(c);
295
+ } else if (matches("h", "left", "escape")) {
296
+ if (this.taskId) action(c); else picker(c);
297
+ } else if (items.length && matches("j", "down", "k", "up", "g", "G", "shift-g")) {
298
+ cursor = matches("G", "shift-g") ? items.length - 1 : matches("g") ? 0 : Math.max(0, Math.min(items.length - 1, cursor + (matches("j", "down") ? 1 : -1)));
299
+ this.cursors.set(cursorKey, cursor);
300
+ this.scroll.scroll_to_item(cursor);
301
+ } else if (items.length && matches("l", "right", "enter")) open(cursor, c);
302
+ else return;
303
+ c.stop_propagation(); c.notify();
304
+ };
305
+ return v_flex().id("todu-panel").track_focus(this.focusHandle)
306
+ .on_mouse_down("left", () => this.focusHandle.focus()).on_key_down(onKey)
307
+ .size_full().min_h(0).p(8).gap(6).text_size(13).text_color(theme().foreground)
308
+ .child(h_flex().items_center().gap(8).pb(6).border_b(1).border_color(theme().border)
309
+ .child(div().flex_1().min_w(0).font_semibold().child(heading))
310
+ .when(Boolean(location) && !this.saving, el => el.child(button("todu-projects", this.picking ? "← Back" : "Projects", picker)))
311
+ .when(Boolean(this.taskId) && !this.saving, el => el.child(button("todu-back", "← Tasks", c => action(c))))
312
+ .when(Boolean(location) && !this.saving, el => el.child(button("todu-refresh", "Refresh (r)", refresh))))
313
+ .when(Boolean(location) && !this.taskId && !this.picking, el => el.child(filterBar(filters, this.expandedFilter, this.filterChoice, toggle, select, c => select(DEFAULT_FILTERS, c))))
314
+ .when(Boolean(this.editor), el => {
315
+ const {field, index} = this.editor;
316
+ const choices = h_flex().flex_wrap().gap(4);
317
+ editValues(field, data).forEach((value, i) => choices.child(button(`set-${field}-${value}`,
318
+ `${data[field] === value ? "✓ " : ""}${FILTER_LABELS[field][value]}`, c => this.saveEdit(field, value, c))
319
+ .when(index === i, row => row.bg(theme().selected))));
320
+ return el.child(v_flex().gap(2).child(`Set ${field} · click or press Enter to save`).child(choices));
321
+ })
322
+ .child(v_flex().id("todu-content").relative().track_scroll(this.scroll).flex_1().min_h(0).overflow_y_scrollbar().gap(8).children(rows))
323
+ .child(div().flex_none().text_size(11).text_color(theme().muted).child(this.editor ? "j/k choose · Enter save · Esc cancel" : this.expandedFilter ? "j/k choose · Enter apply filter · Esc cancel" : this.taskId ? "j/k scroll · s status · p priority · P projects · h back" : this.picking ? "j/k move · l open · h back" : "j/k move · l open · s filter status · p filter priority · P projects"));
324
+ }
325
+ }
package/mod/mod.json ADDED
@@ -0,0 +1 @@
1
+ { "place": "none", "title": "Todu tasks", "focusable": true }
package/mod/runtime.js ADDED
@@ -0,0 +1,2 @@
1
+ // The installer records the local npm runtime; remote spaces use their own PATH.
2
+ export const localRuntime = null;
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "@todu/herdr-todu",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Herdr Desktop task panel for Todu",
5
+ "files": ["dist/*.js", "mod/main.js", "mod/context.js", "mod/runtime.js", "mod/mod.json"],
6
+ "engines": { "node": ">=24" },
7
+ "license": "MIT",
8
+ "publishConfig": { "access": "public" },
9
+ "repository": { "type": "git", "url": "https://github.com/evcraddock/todu.git", "directory": "packages/herdr-todu" },
10
+ "type": "module",
11
+ "bin": {
12
+ "herdr-todu": "dist/index.js"
13
+ },
14
+ "scripts": {
15
+ "build": "tsc -p tsconfig.json && chmod +x dist/index.js"
16
+ },
17
+ "dependencies": {
18
+ "@todu/cli": "0.25.2",
19
+ "@todu/core": "^0.28.0"
20
+ }
21
+ }