@abhishek944/pi-tasks 0.5.0 → 0.8.1

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.
@@ -0,0 +1,22 @@
1
+ export function taskCompletion(todo) {
2
+ if (todo.status === "completed")
3
+ return 100;
4
+ const value = todo.completionPercent;
5
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 && value < 100 ? value : null;
6
+ }
7
+ export function workCompletion(work) {
8
+ const tasks = work.tasks.filter((todo) => todo.status !== "cancelled");
9
+ if (tasks.length === 0)
10
+ return work.status === "completed" ? 100 : null;
11
+ let total = 0;
12
+ for (const todo of tasks) {
13
+ const value = taskCompletion(todo);
14
+ if (value === null)
15
+ return null;
16
+ total += value;
17
+ }
18
+ return Math.floor(total / tasks.length);
19
+ }
20
+ export function formatCompletion(value) {
21
+ return value === null ? "—" : `${value}%`;
22
+ }
package/dist/state.d.ts CHANGED
@@ -26,8 +26,8 @@ export declare class TaskState {
26
26
  createWork(workName: string, workInfo: string, status?: WorkStatus): Work;
27
27
  updateWork(workId: string, patch: Partial<Pick<Work, "workName" | "workInfo" | "status">>): Work;
28
28
  deleteWork(workId: string): boolean;
29
- createTodo(workId: string, taskName: string, taskInfo: string, status?: TodoStatus): Todo;
30
- updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status">>): Todo;
29
+ createTodo(workId: string, taskName: string, taskInfo: string, status?: TodoStatus, completionPercent?: number | null): Todo;
30
+ updateTodo(taskId: string, patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status" | "completionPercent">>): Todo;
31
31
  deleteTodo(taskId: string): boolean;
32
32
  private record;
33
33
  private apply;
package/dist/state.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { taskCompletion } from "./progress.js";
1
2
  import { safeSingleLine } from "./text.js";
2
3
  export const TASK_ENTRY_TYPE = "pi-tasks-state";
3
4
  export const MAX_WORKS = 100;
@@ -88,11 +89,12 @@ export class TaskState {
88
89
  this.record({ version: 1, type: "work-deleted", at: Date.now(), workId });
89
90
  return true;
90
91
  }
91
- createTodo(workId, taskName, taskInfo, status = "pending") {
92
+ createTodo(workId, taskName, taskInfo, status = "pending", completionPercent) {
92
93
  if (!this.works.has(workId))
93
94
  throw new Error(`Work ${workId} not found.`);
94
95
  if (this.todos.size >= MAX_TODOS)
95
96
  throw new Error(`Maximum of ${MAX_TODOS} todos reached.`);
97
+ validateCompletion(status, completionPercent);
96
98
  const now = Date.now();
97
99
  const todo = {
98
100
  taskId: `T${this.nextTaskId}`,
@@ -100,6 +102,7 @@ export class TaskState {
100
102
  taskName: requiredName(taskName, "taskName"),
101
103
  taskInfo: requiredText(taskInfo, "taskInfo"),
102
104
  status,
105
+ completionPercent: status === "completed" ? 100 : completionPercent ?? null,
103
106
  createdAt: now,
104
107
  updatedAt: now,
105
108
  };
@@ -107,12 +110,15 @@ export class TaskState {
107
110
  return { ...todo };
108
111
  }
109
112
  updateTodo(taskId, patch) {
110
- if (!this.todos.has(taskId))
113
+ const current = this.todos.get(taskId);
114
+ if (!current)
111
115
  throw new Error(`Todo ${taskId} not found.`);
116
+ validateCompletion(patch.status ?? current.status, patch.completionPercent);
112
117
  const normalized = compactPatch({
113
118
  taskName: patch.taskName === undefined ? undefined : requiredName(patch.taskName, "taskName"),
114
119
  taskInfo: patch.taskInfo === undefined ? undefined : requiredText(patch.taskInfo, "taskInfo"),
115
120
  status: patch.status,
121
+ completionPercent: patch.completionPercent,
116
122
  });
117
123
  if (Object.keys(normalized).length === 0)
118
124
  throw new Error("TodoUpdate requires at least one changed field.");
@@ -162,19 +168,26 @@ export class TaskState {
162
168
  if (typeof event.todo.workId !== "string" || typeof event.todo.taskName !== "string" || typeof event.todo.taskInfo !== "string" || !isTodoStatus(event.todo.status))
163
169
  throw new Error("Malformed todo entry.");
164
170
  if (this.works.has(event.todo.workId))
165
- this.todos.set(event.todo.taskId, { ...event.todo, taskName: safeSingleLine(event.todo.taskName) });
171
+ this.todos.set(event.todo.taskId, {
172
+ ...event.todo,
173
+ taskName: safeSingleLine(event.todo.taskName),
174
+ completionPercent: taskCompletion(event.todo),
175
+ });
166
176
  this.nextTaskId = Math.max(this.nextTaskId, numericId(event.todo.taskId) + 1);
167
177
  break;
168
178
  case "todo-updated": {
169
179
  const todo = this.todos.get(event.taskId);
170
- if (todo)
171
- this.todos.set(event.taskId, {
180
+ if (todo) {
181
+ const updated = {
172
182
  ...todo,
173
183
  ...(typeof event.patch.taskName === "string" ? { taskName: safeSingleLine(event.patch.taskName) } : {}),
174
184
  ...(typeof event.patch.taskInfo === "string" ? { taskInfo: event.patch.taskInfo } : {}),
175
185
  ...(isTodoStatus(event.patch.status) ? { status: event.patch.status } : {}),
186
+ ...(event.patch.completionPercent !== undefined ? { completionPercent: event.patch.completionPercent } : {}),
176
187
  updatedAt: event.at,
177
- });
188
+ };
189
+ this.todos.set(event.taskId, { ...updated, completionPercent: taskCompletion(updated) });
190
+ }
178
191
  break;
179
192
  }
180
193
  case "todo-deleted":
@@ -183,6 +196,16 @@ export class TaskState {
183
196
  }
184
197
  }
185
198
  }
199
+ function validateCompletion(status, value) {
200
+ if (value === undefined || value === null)
201
+ return;
202
+ if (!Number.isInteger(value) || value < 0 || value > 100)
203
+ throw new Error("completionPercent must be an integer from 0 to 100, or null for unknown.");
204
+ if (value === 100 && status !== "completed")
205
+ throw new Error("100% requires verified completion. Set status to completed after verification.");
206
+ if (status === "completed" && value !== 100)
207
+ throw new Error("Completed tasks have 100% progress. Reopen the task before reporting partial progress.");
208
+ }
186
209
  function requiredText(value, field) {
187
210
  const text = value.trim();
188
211
  if (!text)
package/dist/tools.js CHANGED
@@ -1,20 +1,26 @@
1
1
  import { StringEnum } from "@earendil-works/pi-ai";
2
2
  import { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, formatSize, truncateHead } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
+ import { formatCompletion, taskCompletion, workCompletion } from "./progress.js";
4
5
  import { renderTaskCall, renderTaskResult, taskResult } from "./tool-result.js";
5
6
  const WorkStatusSchema = StringEnum(["planned", "active", "blocked", "completed", "cancelled"]);
6
7
  const TodoStatusSchema = StringEnum(["pending", "active", "blocked", "completed", "cancelled"]);
8
+ const CompletionSchema = Type.Union([Type.Integer({ minimum: 0, maximum: 100 }), Type.Null()], {
9
+ description: "AI-reported approximate task completion, not elapsed time or a status-to-percentage mapping. Use null for unknown; reserve 100 for verified completed status. Work progress is the equal average of non-cancelled tasks.",
10
+ });
7
11
  const NameSchema = Type.String({ minLength: 1, maxLength: 240 });
8
- const InfoSchema = Type.String({ minLength: 1, maxLength: 10_000 });
12
+ const DETAILS_GUIDANCE = "Write workInfo and taskInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words.";
13
+ const InfoSchema = Type.String({ minLength: 1, maxLength: 10_000, description: DETAILS_GUIDANCE });
9
14
  export function registerTaskTools(pi, state) {
10
15
  pi.registerTool({
11
16
  name: "WorkCreate",
12
17
  label: "WorkCreate",
13
- description: "Create a session-scoped work item. Use detailed workInfo that preserves the goal, context, scope, constraints, decisions, and expected outcome.",
18
+ description: `Create a session-scoped work item. Use detailed workInfo that preserves the goal, context, scope, constraints, decisions, and expected outcome. ${DETAILS_GUIDANCE}`,
14
19
  promptSnippet: "Create a session-scoped work item before starting substantial actionable work",
15
20
  promptGuidelines: [
16
21
  "Use WorkCreate for normal requests that start new work in the main conversation; never use it during /ask or /btw.",
17
22
  "Before creating work, use WorkList to avoid duplicating an existing work item.",
23
+ DETAILS_GUIDANCE,
18
24
  ],
19
25
  parameters: Type.Object({
20
26
  workName: NameSchema,
@@ -49,9 +55,9 @@ export function registerTaskTools(pi, state) {
49
55
  pi.registerTool({
50
56
  name: "WorkUpdate",
51
57
  label: "WorkUpdate",
52
- description: "Update a work's name, detailed information, or status. Use before implementation to mark relevant work active and after progress to keep its detailed context current.",
58
+ description: `Update a work's name, detailed information, or status. Use before implementation to mark relevant work active and after progress to keep its detailed context current. ${DETAILS_GUIDANCE}`,
53
59
  promptSnippet: "Update work status and detailed context as actionable work progresses",
54
- promptGuidelines: ["Use WorkUpdate and TodoUpdate before and after actionable main-conversation work; never update tracking during /ask or /btw."],
60
+ promptGuidelines: ["Use WorkUpdate and TodoUpdate before and after actionable main-conversation work; never update tracking during /ask or /btw.", DETAILS_GUIDANCE],
55
61
  parameters: Type.Object({
56
62
  workId: Type.String(),
57
63
  workName: Type.Optional(NameSchema),
@@ -84,21 +90,23 @@ export function registerTaskTools(pi, state) {
84
90
  pi.registerTool({
85
91
  name: "TodoCreate",
86
92
  label: "TodoCreate",
87
- description: "Create a todo under an existing work. taskInfo must contain enough detailed context, scope, constraints, expected outcome, and verification guidance to execute the task without guessing.",
93
+ description: `Create a todo under an existing work, optionally reporting approximate completionPercent (0 for known unstarted work, null for unknown). taskInfo must contain enough detailed context, scope, constraints, expected outcome, and verification guidance to execute the task without guessing. ${DETAILS_GUIDANCE}`,
88
94
  promptSnippet: "Create detailed todos under the current work before implementation",
89
95
  promptGuidelines: [
90
96
  "Use TodoCreate only under an existing work and only for actionable main-conversation work; never use it during /ask or /btw.",
91
- "Keep taskInfo detailed, current, and self-contained.",
97
+ "Keep taskInfo detailed, current, and self-contained. Report completionPercent from actual progress; do not infer partial completion just from status.",
98
+ DETAILS_GUIDANCE,
92
99
  ],
93
100
  parameters: Type.Object({
94
101
  workId: Type.String(),
95
102
  taskName: NameSchema,
96
103
  taskInfo: InfoSchema,
97
104
  status: Type.Optional(TodoStatusSchema),
105
+ completionPercent: Type.Optional(CompletionSchema),
98
106
  }, { additionalProperties: false }),
99
107
  execute(_id, params) {
100
- const todo = state.createTodo(params.workId, params.taskName, params.taskInfo, params.status);
101
- return Promise.resolve(taskResult(`Created todo ${todo.taskId} under ${todo.workId}: ${todo.taskName} [${todo.status}]`, "todo-create", { taskId: todo.taskId, workId: todo.workId }));
108
+ const todo = state.createTodo(params.workId, params.taskName, params.taskInfo, params.status, params.completionPercent);
109
+ return Promise.resolve(taskResult(`Created todo ${todo.taskId} under ${todo.workId}: ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} [${todo.status}]`, "todo-create", { taskId: todo.taskId, workId: todo.workId, completionPercent: taskCompletion(todo) }));
102
110
  },
103
111
  renderCall: renderTaskCall("TodoCreate"),
104
112
  renderResult: renderTaskResult,
@@ -125,18 +133,19 @@ export function registerTaskTools(pi, state) {
125
133
  pi.registerTool({
126
134
  name: "TodoUpdate",
127
135
  label: "TodoUpdate",
128
- description: "Update a todo's name, detailed information, or status. Mark a todo active immediately before starting it and completed or blocked after the attempt.",
136
+ description: `Update a todo's name, detailed information, status, or completionPercent. Report approximate progress after meaningful work and explain evidence in taskInfo; blocking retains progress. Reserve completed/100 for verified completion. ${DETAILS_GUIDANCE}`,
129
137
  promptSnippet: "Keep todo status and detailed context synchronized with active work",
130
- promptGuidelines: ["Use TodoUpdate immediately before and after working on a todo in the main conversation; never update tracking during /ask or /btw."],
138
+ promptGuidelines: ["Use TodoUpdate immediately before and after working on a todo in the main conversation; never update tracking during /ask or /btw.", "Update completionPercent after meaningful progress with evidence in taskInfo. Use null to clear an obsolete estimate; only verified completed tasks may reach 100. Work completion is calculated automatically from tasks.", DETAILS_GUIDANCE],
131
139
  parameters: Type.Object({
132
140
  taskId: Type.String(),
133
141
  taskName: Type.Optional(NameSchema),
134
142
  taskInfo: Type.Optional(InfoSchema),
135
143
  status: Type.Optional(TodoStatusSchema),
144
+ completionPercent: Type.Optional(CompletionSchema),
136
145
  }, { additionalProperties: false, minProperties: 2 }),
137
146
  execute(_id, params) {
138
- const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo: params.taskInfo, status: params.status });
139
- return Promise.resolve(taskResult(`Updated todo ${todo.taskId}: ${todo.taskName} [${todo.status}]`, "todo-update", { taskId: todo.taskId, workId: todo.workId }));
147
+ const todo = state.updateTodo(params.taskId, { taskName: params.taskName, taskInfo: params.taskInfo, status: params.status, completionPercent: params.completionPercent });
148
+ return Promise.resolve(taskResult(`Updated todo ${todo.taskId}: ${todo.taskName} · ${formatCompletion(taskCompletion(todo))} [${todo.status}]`, "todo-update", { taskId: todo.taskId, workId: todo.workId, completionPercent: taskCompletion(todo) }));
140
149
  },
141
150
  renderCall: renderTaskCall("TodoUpdate"),
142
151
  renderResult: renderTaskResult,
@@ -161,7 +170,7 @@ function formatWorks(works) {
161
170
  if (works.length === 0)
162
171
  return "No works found in this session.";
163
172
  return works.map((work) => [
164
- `${work.workId} [${work.status}] ${work.workName}`,
173
+ `${work.workId} [${work.status}] ${work.workName} · ${formatCompletion(workCompletion(work))}`,
165
174
  `Work info:\n${work.workInfo}`,
166
175
  work.tasks.length ? `Todos:\n${formatTodos(work.tasks)}` : "Todos: none",
167
176
  ].join("\n")).join("\n\n---\n\n");
@@ -169,7 +178,7 @@ function formatWorks(works) {
169
178
  function formatTodos(todos) {
170
179
  if (todos.length === 0)
171
180
  return "No todos found.";
172
- return todos.map((todo) => `${todo.taskId} [${todo.status}] ${todo.taskName}\nWork: ${todo.workId}\nTask info:\n${todo.taskInfo}`).join("\n\n");
181
+ return todos.map((todo) => `${todo.taskId} [${todo.status}] ${todo.taskName} · ${formatCompletion(taskCompletion(todo))}\nWork: ${todo.workId}\nTask info:\n${todo.taskInfo}`).join("\n\n");
173
182
  }
174
183
  function bounded(text) {
175
184
  const result = truncateHead(text, { maxBytes: DEFAULT_MAX_BYTES, maxLines: DEFAULT_MAX_LINES });
@@ -1,2 +1,3 @@
1
1
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ export declare function areTrackingToolsActive(pi: ExtensionAPI): boolean;
2
3
  export declare function registerTrackingGuidance(pi: ExtensionAPI): void;
package/dist/tracking.js CHANGED
@@ -3,24 +3,31 @@ const TRACKING_GUIDANCE = `[SESSION COORDINATION]
3
3
  Work is the overall outcome being pursued. A todo is a concrete step that belongs to a work. A monitor runs one long-lived background command. A loop schedules a future, recurring, event-driven, or idle continuation.
4
4
 
5
5
  For every normal user request that starts or continues work, keep the session's work and todo records synchronized. Do not skip tracking because the work looks small.
6
+ Write workInfo and taskInfo in normal prose with full sentences and spaces between words. Conversational brevity modes must not compress stored records or concatenate words.
6
7
 
7
8
  Before implementation, investigation, or any other requested work:
8
9
  1. Use WorkList and TodoList to find the relevant existing records and avoid duplicates.
9
10
  2. If no suitable work exists, create one with WorkCreate. Otherwise use WorkUpdate to refresh its detailed workInfo and mark it active.
10
11
  3. Create or update the work's todos so they match the requested scope. Keep taskInfo detailed and self-contained.
11
12
  4. Mark the todo being attempted active with TodoUpdate before doing that work.
13
+ 5. Report completionPercent on TodoCreate/TodoUpdate as an approximate integer from 0 to 100 based on actual work and verification, not elapsed time or a fixed mapping from status. Explicitly use 0 for genuinely unstarted tasks; use null when unknown. Never invent progress to make a work look further along.
12
14
 
13
15
  During and after the attempt:
14
16
  - When available, use MonitorCreate only when a command should continue in the background; inspect it with MonitorList and do not poll it with shell sleep loops.
15
17
  - When available, use LoopCreate only when work needs a future or repeated wake. Do not create a loop for ordinary synchronous work.
16
18
  - A loop or monitor does not replace work and todo status. Update the related todo when its result is known.
17
- - Mark the todo completed, blocked, or cancelled as appropriate and update taskInfo with important current context.
19
+ - After meaningful progress, update the task completionPercent and explain the evidence and remaining work in taskInfo. Keep estimates current, including after scope changes. Work completion is derived as the equal average of non-cancelled task percentages; any unknown child makes it unknown. Do not set an independent work percentage.
20
+ - Mark the todo completed, blocked, or cancelled as appropriate and update taskInfo with important current context. Only use completed/100 after verification. Blocking retains the last percentage; it does not erase completed effort. Reopening a completed task needs a fresh estimate (otherwise it becomes unknown).
21
+ - Percentages are approximate completion, not ETA or proof. Never mark a parent complete to conceal unfinished tasks, and never change statuses merely because a percentage looks complete.
18
22
  - Keep the work active while required todos remain, blocked when progress cannot continue, and completed only when its required todos are complete.
19
23
  - Never create or update works, todos, loops, or monitors during /ask, /btw, or any BTW side thread.`;
24
+ export function areTrackingToolsActive(pi) {
25
+ const active = new Set(pi.getActiveTools());
26
+ return REQUIRED_TRACKING_TOOLS.every((name) => active.has(name));
27
+ }
20
28
  export function registerTrackingGuidance(pi) {
21
29
  pi.on("before_agent_start", (event) => {
22
- const active = new Set(pi.getActiveTools());
23
- if (!REQUIRED_TRACKING_TOOLS.every((name) => active.has(name)))
30
+ if (!areTrackingToolsActive(pi))
24
31
  return;
25
32
  return { systemPrompt: `${event.systemPrompt}\n\n${TRACKING_GUIDANCE}` };
26
33
  });
package/dist/types.d.ts CHANGED
@@ -14,6 +14,7 @@ export interface Todo {
14
14
  taskName: string;
15
15
  taskInfo: string;
16
16
  status: TodoStatus;
17
+ completionPercent?: number | null;
17
18
  createdAt: number;
18
19
  updatedAt: number;
19
20
  }
@@ -46,7 +47,7 @@ export type TaskEvent = {
46
47
  type: "todo-updated";
47
48
  at: number;
48
49
  taskId: string;
49
- patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status">>;
50
+ patch: Partial<Pick<Todo, "taskName" | "taskInfo" | "status" | "completionPercent">>;
50
51
  } | {
51
52
  version: 1;
52
53
  type: "todo-deleted";
@@ -1,17 +1,20 @@
1
1
  import { type ExtensionUIContext, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import type { GitSnapshot, GitStatusCache } from "../git-status.js";
2
3
  import type { TaskState } from "../state.js";
3
4
  import type { TodoStatus, WorkStatus } from "../types.js";
4
5
  export type TasksPanelMode = "floating" | "widget" | "off";
5
6
  export declare class TasksPanelHost {
6
7
  private readonly state;
8
+ private readonly git;
7
9
  private tui;
8
10
  private panel;
9
11
  private handle;
10
12
  private ui;
11
13
  private mode;
12
14
  private minimized;
13
- constructor(state: TaskState);
14
- attach(ui: ExtensionUIContext): void;
15
+ private cwd;
16
+ constructor(state: TaskState, git: GitStatusCache);
17
+ attach(ui: ExtensionUIContext, cwd: string): void;
15
18
  setMode(mode: TasksPanelMode): void;
16
19
  getMode(): TasksPanelMode;
17
20
  setMinimized(minimized: boolean): void;
@@ -20,8 +23,10 @@ export declare class TasksPanelHost {
20
23
  private applyMode;
21
24
  private hideCurrent;
22
25
  }
26
+ export declare function progressName(name: string, completion: number | null, width: number): string;
23
27
  export declare function workIcon(status: WorkStatus, theme: Theme): string;
24
28
  export declare function todoIcon(status: TodoStatus, theme: Theme): string;
25
29
  export declare function frame(content: string, innerWidth: number, theme: Theme): string;
26
30
  export declare function rule(innerWidth: number, theme: Theme): string;
31
+ export declare function gitBorder(innerWidth: number, theme: Theme, snapshot: GitSnapshot): string;
27
32
  export declare function border(innerWidth: number, edge: "top" | "bottom", theme: Theme): string;
package/dist/ui/panel.js CHANGED
@@ -1,21 +1,30 @@
1
+ import { stripVTControlCharacters } from "node:util";
1
2
  import { copyToClipboard } from "@earendil-works/pi-coding-agent";
2
3
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
3
4
  import { formatWorksMarkdown } from "../markdown.js";
5
+ import { openRepository } from "../open-repository.js";
6
+ import { formatCompletion, taskCompletion, workCompletion } from "../progress.js";
4
7
  import { safeSingleLine } from "../text.js";
5
8
  const EMPTY_COMPONENT = { render: () => [], invalidate: () => { } };
9
+ const PROGRESS_VALUE_WIDTH = 4;
10
+ const PROGRESS_COLUMN_WIDTH = PROGRESS_VALUE_WIDTH + 3;
6
11
  export class TasksPanelHost {
7
12
  state;
13
+ git;
8
14
  tui;
9
15
  panel;
10
16
  handle;
11
17
  ui;
12
18
  mode = "floating";
13
19
  minimized = false;
14
- constructor(state) {
20
+ cwd = "";
21
+ constructor(state, git) {
15
22
  this.state = state;
23
+ this.git = git;
16
24
  }
17
- attach(ui) {
25
+ attach(ui, cwd) {
18
26
  this.hideCurrent();
27
+ this.cwd = cwd;
19
28
  this.ui = ui;
20
29
  this.applyMode();
21
30
  }
@@ -53,7 +62,7 @@ export class TasksPanelHost {
53
62
  this.tui = tui;
54
63
  this.panel = new TasksPanel(tui, this.state, theme, "widget", this.minimized, (minimized) => {
55
64
  this.minimized = minimized;
56
- }, (message, type) => ui.notify(message, type));
65
+ }, (message, type) => ui.notify(message, type), this.cwd, this.git);
57
66
  return this.panel;
58
67
  });
59
68
  return;
@@ -62,7 +71,7 @@ export class TasksPanelHost {
62
71
  this.tui = tui;
63
72
  this.panel = new TasksPanel(tui, this.state, theme, "floating", this.minimized, (minimized) => {
64
73
  this.minimized = minimized;
65
- }, (message, type) => ui.notify(message, type));
74
+ }, (message, type) => ui.notify(message, type), this.cwd, this.git);
66
75
  this.handle = tui.showOverlay(this.panel, {
67
76
  anchor: "top-right",
68
77
  width: "42%",
@@ -70,12 +79,17 @@ export class TasksPanelHost {
70
79
  maxHeight: "48%",
71
80
  margin: { top: 1, right: 1 },
72
81
  nonCapturing: true,
73
- visible: (terminalWidth, terminalHeight) => terminalWidth >= 90 && terminalHeight >= 18,
82
+ visible: (terminalWidth, terminalHeight) => {
83
+ const visible = terminalWidth >= 90 && terminalHeight >= 18;
84
+ this.panel?.setVisible(visible);
85
+ return visible;
86
+ },
74
87
  });
75
88
  return EMPTY_COMPONENT;
76
89
  });
77
90
  }
78
91
  hideCurrent() {
92
+ this.panel?.dispose();
79
93
  this.handle?.hide();
80
94
  this.handle = undefined;
81
95
  this.ui?.setWidget("pi-tasks-panel", undefined);
@@ -92,14 +106,20 @@ class TasksPanel {
92
106
  minimized;
93
107
  onMinimizedChange;
94
108
  notify;
109
+ cwd;
110
+ git;
95
111
  scrollOffset = 0;
96
112
  pageSize = 1;
97
113
  contentLength = 0;
98
114
  followTail = true;
99
115
  copying = false;
116
+ opening = false;
117
+ disposed = false;
118
+ unsubscribeGit;
100
119
  copyHitRegion;
120
+ openHitRegion;
101
121
  toggleHitRegion;
102
- constructor(tui, state, theme, placement, minimized, onMinimizedChange, notify) {
122
+ constructor(tui, state, theme, placement, minimized, onMinimizedChange, notify, cwd, git) {
103
123
  this.tui = tui;
104
124
  this.state = state;
105
125
  this.theme = theme;
@@ -107,8 +127,12 @@ class TasksPanel {
107
127
  this.minimized = minimized;
108
128
  this.onMinimizedChange = onMinimizedChange;
109
129
  this.notify = notify;
130
+ this.cwd = cwd;
131
+ this.git = git;
110
132
  }
111
133
  render(width) {
134
+ if (this.placement === "widget")
135
+ this.setVisible(width >= 38);
112
136
  if (width < 38)
113
137
  return [];
114
138
  const works = this.state.listWorks();
@@ -118,19 +142,23 @@ class TasksPanel {
118
142
  if (this.minimized) {
119
143
  const header = this.renderHeader("Works", innerWidth, leftPad.length);
120
144
  return [
121
- border(innerWidth, "top", this.theme),
145
+ gitBorder(innerWidth, this.theme, this.git.getSnapshot()),
122
146
  frame(header, innerWidth, this.theme),
123
147
  border(innerWidth, "bottom", this.theme),
124
148
  ].map((line) => `${leftPad}${line}`);
125
149
  }
150
+ const contentWidth = innerWidth - PROGRESS_COLUMN_WIDTH;
126
151
  const content = [];
127
152
  if (works.length === 0)
128
- content.push(this.theme.fg("muted", "No works yet."));
153
+ content.push(progressColumn(this.theme.fg("muted", "No works yet."), null, innerWidth, this.theme));
129
154
  for (const work of works) {
130
155
  const completed = work.tasks.filter((todo) => todo.status === "completed").length;
131
- content.push(workSummaryLine(work.status, work.workName, `${completed}/${work.tasks.length}`, innerWidth, this.theme));
132
- for (const todo of work.tasks)
133
- content.push(` ${todoIcon(todo.status, this.theme)} ${this.theme.fg(todo.status === "completed" ? "muted" : "text", todo.taskName)}`);
156
+ const summary = workSummaryLine(work.status, work.workName, `${completed}/${work.tasks.length}`, contentWidth, this.theme);
157
+ content.push(progressColumn(summary, workCompletion(work), innerWidth, this.theme));
158
+ for (const todo of work.tasks) {
159
+ const label = ` ${todoIcon(todo.status, this.theme)} ${this.theme.fg(todo.status === "completed" ? "muted" : "text", safeSingleLine(todo.taskName))}`;
160
+ content.push(progressColumn(label, taskCompletion(todo), innerWidth, this.theme));
161
+ }
134
162
  }
135
163
  this.contentLength = content.length;
136
164
  const terminalRows = this.tui.terminal.rows || process.stdout.rows || 30;
@@ -156,15 +184,17 @@ class TasksPanel {
156
184
  }
157
185
  const header = this.renderHeader(title, innerWidth, leftPad.length);
158
186
  const lines = [
159
- border(innerWidth, "top", this.theme),
187
+ gitBorder(innerWidth, this.theme, this.git.getSnapshot()),
160
188
  frame(header, innerWidth, this.theme),
161
- rule(innerWidth, this.theme),
189
+ this.theme.fg("border", `├${"─".repeat(contentWidth + 1)}┬${"─".repeat(PROGRESS_VALUE_WIDTH + 1)}┤`),
162
190
  ...shown.map((line) => frame(line, innerWidth, this.theme)),
163
- border(innerWidth, "bottom", this.theme),
191
+ this.theme.fg("border", `└${"─".repeat(contentWidth + 1)}┴${"─".repeat(PROGRESS_VALUE_WIDTH + 1)}┘`),
164
192
  ];
165
193
  return lines.map((line) => `${leftPad}${line}`);
166
194
  }
167
195
  handleMouse(event) {
196
+ if (this.disposed)
197
+ return undefined;
168
198
  if (event.type === "click" && event.button === "left" && event.y === 1) {
169
199
  if (this.isHit(event.x, this.toggleHitRegion)) {
170
200
  this.setMinimized(!this.minimized);
@@ -174,6 +204,10 @@ class TasksPanel {
174
204
  void this.copyAllAsMarkdown();
175
205
  return { handled: true, render: true };
176
206
  }
207
+ if (this.isHit(event.x, this.openHitRegion)) {
208
+ void this.openInCursor();
209
+ return { handled: true, render: true };
210
+ }
177
211
  }
178
212
  if (this.minimized || this.placement !== "floating" || event.type !== "wheel" || !event.wheelDelta)
179
213
  return undefined;
@@ -181,6 +215,23 @@ class TasksPanel {
181
215
  return { handled: true, render: changed };
182
216
  }
183
217
  invalidate() { }
218
+ dispose() {
219
+ if (this.disposed)
220
+ return;
221
+ this.setVisible(false);
222
+ this.disposed = true;
223
+ }
224
+ setVisible(visible) {
225
+ if (this.disposed)
226
+ return;
227
+ if (visible) {
228
+ this.unsubscribeGit ??= this.git.subscribe(() => this.tui.requestRender());
229
+ }
230
+ else {
231
+ this.unsubscribeGit?.();
232
+ this.unsubscribeGit = undefined;
233
+ }
234
+ }
184
235
  setMinimized(minimized) {
185
236
  if (this.minimized === minimized)
186
237
  return;
@@ -193,21 +244,45 @@ class TasksPanel {
193
244
  const copyAction = this.copying
194
245
  ? this.theme.fg("dim", "[Copying…]")
195
246
  : this.theme.fg("accent", this.theme.bold("[Copy]"));
247
+ const openAction = this.theme.fg(this.opening ? "dim" : "accent", this.theme.bold("[Open]"));
196
248
  const toggleLabel = this.minimized ? "[Maximize]" : "[Minimize]";
197
249
  const toggleAction = this.theme.fg("accent", this.theme.bold(toggleLabel));
198
- const actionsWidth = visibleWidth(copyAction) + 1 + visibleWidth(toggleAction);
250
+ const actionsWidth = visibleWidth(copyAction) + 1 + visibleWidth(openAction) + 1 + visibleWidth(toggleAction);
199
251
  const titleWidth = Math.max(0, width - actionsWidth - 1);
200
252
  const shownTitle = truncateToWidth(title, titleWidth, "");
201
253
  const gap = " ".repeat(Math.max(1, width - visibleWidth(shownTitle) - actionsWidth));
202
254
  const copyStart = leftPadWidth + 1 + visibleWidth(shownTitle) + gap.length;
203
255
  this.copyHitRegion = { start: copyStart, end: copyStart + visibleWidth(copyAction) };
204
- const toggleStart = this.copyHitRegion.end + 1;
256
+ const openStart = this.copyHitRegion.end + 1;
257
+ this.openHitRegion = { start: openStart, end: openStart + visibleWidth(openAction) };
258
+ const toggleStart = this.openHitRegion.end + 1;
205
259
  this.toggleHitRegion = { start: toggleStart, end: toggleStart + visibleWidth(toggleAction) };
206
- return `${shownTitle}${gap}${copyAction} ${toggleAction}`;
260
+ return `${shownTitle}${gap}${copyAction} ${openAction} ${toggleAction}`;
207
261
  }
208
262
  isHit(x, region) {
209
263
  return region !== undefined && x >= region.start && x < region.end;
210
264
  }
265
+ async openInCursor() {
266
+ if (this.opening)
267
+ return;
268
+ this.opening = true;
269
+ this.tui.requestRender();
270
+ try {
271
+ await openRepository(this.cwd);
272
+ if (!this.disposed)
273
+ this.notify("Opened repository in Cursor.", "info");
274
+ }
275
+ catch (error) {
276
+ const reason = error instanceof Error ? ` ${safeSingleLine(error.message)}` : "";
277
+ if (!this.disposed)
278
+ this.notify(`Could not open Cursor. Check that cursor is installed on PATH.${reason}`, "error");
279
+ }
280
+ finally {
281
+ this.opening = false;
282
+ if (!this.disposed)
283
+ this.tui.requestRender();
284
+ }
285
+ }
211
286
  async copyAllAsMarkdown() {
212
287
  if (this.copying)
213
288
  return;
@@ -246,10 +321,21 @@ class TasksPanel {
246
321
  return Math.max(0, this.contentLength - this.pageSize);
247
322
  }
248
323
  }
324
+ export function progressName(name, completion, width) {
325
+ const suffix = ` · ${formatCompletion(completion)}`;
326
+ return `${truncateToWidth(safeSingleLine(name), Math.max(0, width - visibleWidth(suffix)), "…")}${suffix}`;
327
+ }
328
+ function progressColumn(content, completion, width, theme) {
329
+ const contentWidth = width - PROGRESS_COLUMN_WIDTH;
330
+ const left = truncateToWidth(content, contentWidth, "…");
331
+ const padding = " ".repeat(Math.max(0, contentWidth - visibleWidth(left)));
332
+ const value = theme.fg(completion === null ? "muted" : "accent", formatCompletion(completion).padStart(PROGRESS_VALUE_WIDTH));
333
+ return `${left}${padding}${theme.fg("border", " │ ")}${value}`;
334
+ }
249
335
  function workSummaryLine(status, name, count, width, theme) {
250
- const left = `${workIcon(status, theme)} ${theme.fg("text", name)}`;
251
336
  const right = theme.fg("dim", count);
252
337
  const leftWidth = Math.max(0, width - visibleWidth(right) - 1);
338
+ const left = `${workIcon(status, theme)} ${theme.fg("text", safeSingleLine(name))}`;
253
339
  const shownLeft = truncateToWidth(left, leftWidth, "…");
254
340
  const gap = " ".repeat(Math.max(1, width - visibleWidth(shownLeft) - visibleWidth(right)));
255
341
  return `${shownLeft}${gap}${right}`;
@@ -283,6 +369,29 @@ export function frame(content, innerWidth, theme) {
283
369
  export function rule(innerWidth, theme) {
284
370
  return theme.fg("border", `├${"─".repeat(innerWidth)}┤`);
285
371
  }
372
+ export function gitBorder(innerWidth, theme, snapshot) {
373
+ if (snapshot.kind === "not-repository" || innerWidth < 6)
374
+ return border(innerWidth, "top", theme);
375
+ let label;
376
+ if (snapshot.kind === "ready") {
377
+ const clean = snapshot.staged === 0 && snapshot.unstaged === 0 && snapshot.untracked === 0;
378
+ let suffix = clean ? " · clean" : ` · S${snapshot.staged} U${snapshot.unstaged} ?${snapshot.untracked}`;
379
+ if (!clean && visibleWidth(suffix) > innerWidth - 13) {
380
+ const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 0 });
381
+ suffix = ` · S${compact.format(snapshot.staged)} U${compact.format(snapshot.unstaged)} ?${compact.format(snapshot.untracked)}`;
382
+ }
383
+ const branchWidth = Math.max(0, innerWidth - visibleWidth(`git ${suffix}`) - 4);
384
+ label = `git ${truncateToWidth(safeSingleLine(snapshot.branch), branchWidth, "…")}${suffix}`;
385
+ }
386
+ else {
387
+ label = snapshot.kind === "loading" ? "git loading…" : "git unavailable";
388
+ }
389
+ // Truncation may insert ANSI resets; color the complete plain label afterward.
390
+ label = stripVTControlCharacters(truncateToWidth(label, innerWidth - 4, "…"));
391
+ const slack = innerWidth - visibleWidth(label) - 2;
392
+ const left = Math.floor(slack / 2);
393
+ return theme.fg("border", `┌${"─".repeat(left)} ${label} ${"─".repeat(slack - left)}┐`);
394
+ }
286
395
  export function border(innerWidth, edge, theme) {
287
396
  return theme.fg("border", `${edge === "top" ? "┌" : "└"}${"─".repeat(innerWidth)}${edge === "top" ? "┐" : "┘"}`);
288
397
  }