Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(projects): progress that leaves cancelled issues out, with trend, forecast and CLI (#10626)

Jiayuan Zhang87f8222e15d7
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 590105a74a..20de4abe99 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -980,6 +980,23 @@ multica project get <id>
multica project get <id> --output json
```
+The response includes `progress`: `scope` is every issue except cancelled ones,
+`completed` counts done issues, `started` issues are tracked but do not add to
+`percent`. The table output shows it as a PROGRESS column (`5/11 (45%)`).
+
+### Project Progress
+
+```bash
+multica project progress <id> # summary and forecast
+multica project progress <id> --history # weekly scope / started / completed
+multica project progress <id> --by assignee # per-assignee breakdown
+multica project progress <id> --output json # everything above
+```
+
+The forecast is a completion date from the trailing 4-week completion rate;
+it is omitted when there is less than a week of history or nothing was
+completed recently.
+
### Create Project
```bash
diff --git a/apps/docs/components/demos/project-demo.tsx b/apps/docs/components/demos/project-demo.tsx
index e6ce14c6b7..a319744b79 100644
--- a/apps/docs/components/demos/project-demo.tsx
+++ b/apps/docs/components/demos/project-demo.tsx
@@ -12,8 +12,8 @@ type IssueId = "OPS-41" | "OPS-42" | "OPS-43" | "OPS-44";
const ISSUE_MENU: IssueStatus[] = ["todo", "in_progress", "in_review", "done", "cancelled"];
const PROJECT_MENU: ProjectStatus[] = ["planned", "in_progress", "paused", "completed", "cancelled"];
-// Progress counts issues in the done and closed categories (handler/project.go).
-const finished = (s: IssueStatus) => s === "done" || s === "cancelled";
+// Progress is done ÷ issues still in scope; cancelled ones leave the scope
+// (newProjectProgress in handler/project.go).
const issueDot: Record<IssueStatus, string> = {
todo: "border-muted-foreground",
@@ -60,7 +60,7 @@ const copy = {
firstMenu: "Pick Done.",
second: "Progress went up a step. The partner promotion is no longer happening: set OPS-44 to Cancelled.",
secondMenu: "Pick Cancelled. A cancelled issue has left the project's scope.",
- allDone: "Cancelled counts toward progress too, so the project is at 100%. Its own status is still In Progress: it does not follow the issues. Click the project status.",
+ allDone: "OPS-44 left the scope, so the three remaining issues are all done and the project is at 100%. Its own status is still In Progress: it does not follow the issues. Click the project status.",
projectMenu: "Pick Completed. Changing it would not touch any issue either.",
done: "The project is now Completed; that never happens on its own. Use Replay to watch again.",
},
@@ -101,7 +101,7 @@ const copy = {
firstMenu: "选择已完成。",
second: "进度前进了一格。合作推广不做了:把 OPS-44 改为已取消。",
secondMenu: "选择已取消。取消表示这项工作已从项目范围中结束。",
- allDone: "已取消同样计入进度,项目到了 100%,但项目状态还是进行中:它不跟随任务变化。点击项目状态。",
+ allDone: "OPS-44 移出了范围,剩下 3 个任务都已完成,项目到了 100%,但项目状态还是进行中:它不跟随任务变化。点击项目状态。",
projectMenu: "选择已完成。修改项目状态也不会改动其中的任务。",
done: "项目状态改成了已完成,这一步不会自动发生。点右上角可以重新演示。",
},
@@ -142,7 +142,7 @@ const copy = {
firstMenu: "完了を選んでください。",
second: "進捗が 1 段進みました。パートナーとの共同プロモーションは取りやめになったので、OPS-44 をキャンセル済みにしてください。",
secondMenu: "キャンセル済みを選んでください。キャンセルは、その作業がプロジェクトの範囲から外れたことを表します。",
- allDone: "キャンセル済みも進捗に数えるので、プロジェクトは 100% になりました。それでもプロジェクトのステータスは進行中のままで、タスクには連動しません。プロジェクトのステータスをクリックしてください。",
+ allDone: "OPS-44 は範囲から外れ、残る 3 件がすべて完了したので、プロジェクトは 100% になりました。それでもプロジェクトのステータスは進行中のままで、タスクには連動しません。プロジェクトのステータスをクリックしてください。",
projectMenu: "完了を選んでください。プロジェクトのステータスを変えても、タスクは変わりません。",
done: "プロジェクトが完了になりました。これは自動では起きません。右上から最初に戻せます。",
},
@@ -183,7 +183,7 @@ const copy = {
firstMenu: "완료를 선택하세요.",
second: "진행률이 한 칸 올랐습니다. 파트너 공동 홍보는 하지 않기로 했으니 OPS-44를 취소됨으로 바꾸세요.",
secondMenu: "취소됨을 선택하세요. 취소는 그 작업이 프로젝트 범위에서 끝났다는 뜻입니다.",
- allDone: "취소됨도 진행률에 들어가서 프로젝트가 100%가 됐습니다. 그래도 프로젝트 상태는 여전히 진행 중입니다. 태스크를 따라 바뀌지 않습니다. 프로젝트 상태를 클릭하세요.",
+ allDone: "OPS-44가 범위에서 빠지고 남은 3개가 모두 완료되어 프로젝트가 100%가 됐습니다. 그래도 프로젝트 상태는 여전히 진행 중입니다. 태스크를 따라 바뀌지 않습니다. 프로젝트 상태를 클릭하세요.",
projectMenu: "완료됨을 선택하세요. 프로젝트 상태를 바꿔도 태스크는 바뀌지 않습니다.",
done: "프로젝트가 완료됨이 됐습니다. 이 단계는 자동으로 일어나지 않습니다. 오른쪽 위에서 다시 볼 수 있습니다.",
},
@@ -224,7 +224,7 @@ const copy = {
firstMenu: "Choisissez Terminé.",
second: "L'avancement a progressé d'un cran. La promotion avec le partenaire n'aura pas lieu : passez OPS-44 à Annulé.",
secondMenu: "Choisissez Annulé. Une tâche annulée est sortie du périmètre du projet.",
- allDone: "Annulé compte aussi dans l'avancement : le projet est à 100 %. Son propre statut reste En cours, car il ne suit pas les tâches. Cliquez sur le statut du projet.",
+ allDone: "OPS-44 est sorti du périmètre et les trois tâches restantes sont terminées : le projet est à 100 %. Son propre statut reste En cours, car il ne suit pas les tâches. Cliquez sur le statut du projet.",
projectMenu: "Choisissez Terminé. Changer le statut du projet ne touche à aucune tâche non plus.",
done: "Le projet est maintenant Terminé ; cela n'arrive jamais tout seul. Relancez la démo pour la revoir.",
},
@@ -257,8 +257,9 @@ export function ProjectDemo() {
const shownPhase: Phase = visible ? phase : "idle";
const ids = Object.keys(statuses) as IssueId[];
- const done = ids.filter((id) => finished(statuses[id])).length;
- const percent = Math.round((done / ids.length) * 100);
+ const done = ids.filter((id) => statuses[id] === "done").length;
+ const scope = ids.filter((id) => statuses[id] !== "cancelled").length;
+ const percent = scope > 0 ? Math.floor((done / scope) * 100) : 0;
const step = visible ? SCRIPT[phase] : undefined;
const toggleMenu = () => {
@@ -357,7 +358,7 @@ export function ProjectDemo() {
/>
</span>
<span key={done} className="shrink-0 text-caption tabular-nums text-muted-foreground motion-safe:animate-in motion-safe:fade-in">
- {done}/{ids.length} · {percent}%
+ {done}/{scope} · {percent}%
</span>
</dd>
</dl>
diff --git a/apps/docs/content/docs/projects.fr.mdx b/apps/docs/content/docs/projects.fr.mdx
index d0ccb4fad0..f18f49bfec 100644
--- a/apps/docs/content/docs/projects.fr.mdx
+++ b/apps/docs/content/docs/projects.fr.mdx
@@ -37,10 +37,10 @@ Un projet peut contenir un nombre quelconque de tâches ; une tâche appartient
L'avancement du projet est calculé automatiquement à partir des tâches liées :
```text
-avancement = tâches dont le statut appartient à la catégorie done ou closed ÷ toutes les tâches du projet
+avancement = tâches de la catégorie done ÷ (toutes les tâches du projet − tâches de la catégorie closed)
```
-Parmi les statuts intégrés, ce sont `done` et `cancelled` ; les statuts personnalisés rangés dans ces deux catégories comptent de la même façon. `cancelled` signifie que ce travail a été retiré du périmètre du projet, il compte donc dans l'avancement.
+Parmi les statuts intégrés, `done` compte comme terminé et `cancelled` appartient à closed. Une tâche closed est sortie du périmètre du projet : elle ne compte ni comme terminée ni dans le total, et le projet affiche à part le nombre de tâches annulées à côté de l'avancement. Les statuts personnalisés suivent leur catégorie. Le pourcentage est arrondi à l'inférieur, donc 100 % signifie que toutes les tâches du périmètre sont terminées. Un projet sans tâche dans son périmètre affiche 0 %.
Le statut du projet et celui des tâches sont indépendants : terminer toutes les tâches ne fait pas passer le projet à `completed`, et modifier le statut du projet ne touche pas à ses tâches.
diff --git a/apps/docs/content/docs/projects.ja.mdx b/apps/docs/content/docs/projects.ja.mdx
index 045c7ec9ec..f2f2001f87 100644
--- a/apps/docs/content/docs/projects.ja.mdx
+++ b/apps/docs/content/docs/projects.ja.mdx
@@ -37,10 +37,10 @@ import { ProjectDemo } from "@/components/demos/project-demo";
プロジェクトの進捗は、紐づくタスクから自動的に計算されます。
```text
-進捗 = ステータスが done または closed 分類に属するタスクの数 ÷ プロジェクト内の全タスク数
+進捗 = done 分類のタスク数 ÷(プロジェクト内の全タスク数 − closed 分類のタスク数)
```
-組み込みステータスでは `done` と `cancelled` が該当し、この 2 つの分類に入れたカスタムステータスも同じように数えられます。`cancelled` はその作業がプロジェクトの範囲から外れて終わったことを表すので、進捗に含まれます。
+組み込みステータスでは、`done` が完了、`cancelled` が closed に当たります。closed のタスクはプロジェクトの範囲から外れたものとして、完了にも全体数にも数えられず、キャンセル済みの数は進捗の横に別に表示されます。カスタムステータスは所属する分類に従います。割合は切り捨てなので、100% は範囲内のタスクがすべて完了したことを意味します。範囲内にタスクがないプロジェクトは 0% と表示されます。
プロジェクトのステータスとタスクのステータスは連動しません。すべてのタスクが完了してもプロジェクトは自動では `completed` にならず、プロジェクトのステータスを変えても中のタスクは一括変更されません。
diff --git a/apps/docs/content/docs/projects.ko.mdx b/apps/docs/content/docs/projects.ko.mdx
index 7ebb24a792..2292a14d2f 100644
--- a/apps/docs/content/docs/projects.ko.mdx
+++ b/apps/docs/content/docs/projects.ko.mdx
@@ -37,10 +37,10 @@ import { ProjectDemo } from "@/components/demos/project-demo";
프로젝트 진행률은 연결된 태스크를 기준으로 자동 계산됩니다.
```text
-진행률 = 상태가 done 또는 closed 분류에 속하는 태스크 수 ÷ 프로젝트의 전체 태스크 수
+진행률 = done 분류의 태스크 수 ÷ (프로젝트의 전체 태스크 수 − closed 분류의 태스크 수)
```
-기본 상태로는 `done`과 `cancelled`가 여기에 해당하며, 이 두 분류에 속하는 사용자 지정 상태도 똑같이 포함됩니다. `cancelled`는 해당 작업이 프로젝트 범위에서 종료되었다는 뜻이므로 진행률에 포함됩니다.
+기본 상태로는 `done`이 완료, `cancelled`가 closed에 해당합니다. closed 태스크는 프로젝트 범위에서 빠진 것으로 보아 완료에도 전체 수에도 포함되지 않으며, 취소된 수는 진행률 옆에 따로 표시됩니다. 사용자 지정 상태는 속한 분류를 따릅니다. 비율은 내림하므로 100%는 범위 안의 태스크가 모두 완료되었다는 뜻입니다. 범위 안에 태스크가 없는 프로젝트는 0%로 표시됩니다.
프로젝트 상태와 태스크 상태는 따로 움직입니다. 모든 태스크가 완료되어도 프로젝트가 자동으로 `completed`가 되지 않고, 프로젝트 상태를 바꿔도 그 안의 태스크가 일괄 변경되지 않습니다.
diff --git a/apps/docs/content/docs/projects.mdx b/apps/docs/content/docs/projects.mdx
index fff7739ad2..381a06a7f9 100644
--- a/apps/docs/content/docs/projects.mdx
+++ b/apps/docs/content/docs/projects.mdx
@@ -37,10 +37,10 @@ A project can contain any number of issues; an issue belongs to at most one proj
Project progress is computed automatically from linked issues:
```text
-progress = issues whose status is in the done or closed category ÷ all issues in the project
+progress = issues in the done category ÷ (all issues in the project − issues in the closed category)
```
-Among the built-in statuses that means `done` and `cancelled`; custom statuses in those two categories count as well. `cancelled` means that work has been closed out of the project's scope, so it counts toward progress.
+Among the built-in statuses, `done` counts as completed and `cancelled` is closed. A closed issue has left the project's scope, so it counts neither as completed nor toward the total; the project shows how many were cancelled next to its progress. Custom statuses follow their category. The percentage is rounded down, so 100% means every issue still in scope is done. A project with no issues in scope shows 0%.
Project status and issue status are independent: finishing every issue does not set the project to `completed`, and changing the project's status does not bulk-change its issues.
diff --git a/apps/docs/content/docs/projects.zh-Hant.mdx b/apps/docs/content/docs/projects.zh-Hant.mdx
index 601677a7e4..89331d2be0 100644
--- a/apps/docs/content/docs/projects.zh-Hant.mdx
+++ b/apps/docs/content/docs/projects.zh-Hant.mdx
@@ -37,10 +37,10 @@ import { ProjectDemo } from "@/components/demos/project-demo";
專案進度按關聯任務自動計算:
```text
-進度 = 狀態屬於 done 或 closed 分類的任務數 ÷ 專案中的全部任務數
+進度 = 狀態屬於 done 分類的任務數 ÷(專案中的全部任務數 − 狀態屬於 closed 分類的任務數)
```
-內建狀態裡就是 `done` 和 `cancelled`,歸入這兩個分類的自定義狀態也一樣計入。`cancelled` 表示這項工作已從專案範圍中結束,所以算進進度。
+內建狀態裡,`done` 算作完成,`cancelled` 屬於 closed。closed 的任務已移出專案範圍,既不算完成,也不計入總數;專案會在進度旁單獨顯示已取消的數量。自定義狀態按所屬分類計算。百分比無條件捨去,所以 100% 表示範圍內的任務全部完成。範圍內沒有任務的專案顯示 0%。
專案狀態和任務狀態各管各的:所有任務完成後,專案不會自動變為 `completed`;修改專案狀態,也不會批次修改其中的任務。
diff --git a/apps/docs/content/docs/projects.zh.mdx b/apps/docs/content/docs/projects.zh.mdx
index d78eb0d5e4..ecd0eb65b0 100644
--- a/apps/docs/content/docs/projects.zh.mdx
+++ b/apps/docs/content/docs/projects.zh.mdx
@@ -37,10 +37,10 @@ import { ProjectDemo } from "@/components/demos/project-demo";
项目进度按关联任务自动计算:
```text
-进度 = 状态属于 done 或 closed 分类的任务数 ÷ 项目中的全部任务数
+进度 = 状态属于 done 分类的任务数 ÷(项目中的全部任务数 − 状态属于 closed 分类的任务数)
```
-内置状态里就是 `done` 和 `cancelled`,归入这两个分类的自定义状态也一样计入。`cancelled` 表示这项工作已从项目范围中结束,所以算进进度。
+内置状态里,`done` 算作完成,`cancelled` 属于 closed。closed 的任务已移出项目范围,既不算完成,也不计入总数;项目会在进度旁单独显示已取消的数量。自定义状态按所属分类计算。百分比向下取整,所以 100% 表示范围内的任务全部完成。范围内没有任务的项目显示 0%。
项目状态和任务状态各管各的:所有任务完成后,项目不会自动变为 `completed`;修改项目状态,也不会批量修改其中的任务。
diff --git a/packages/core/api/client.ts b/packages/core/api/client.ts
index dfcac50a8f..eef85fcfa1 100644
--- a/packages/core/api/client.ts
+++ b/packages/core/api/client.ts
@@ -146,6 +146,7 @@ import type {
CancelTaskResponse,
Project,
ArchiveProjectResponse,
+ ProjectProgressDetail,
CreateProjectRequest,
UpdateProjectRequest,
ListProjectsResponse,
@@ -427,6 +428,8 @@ import {
SearchIssuesResponseSchema,
ProjectSchema,
ArchiveProjectResponseSchema,
+ ProjectProgressDetailSchema,
+ EMPTY_PROJECT_PROGRESS_DETAIL,
ListProjectMembersResponseSchema,
ListPrivateProjectsResponseSchema,
ProjectSubscriptionSchema,
@@ -4960,6 +4963,13 @@ export class ApiClient {
return parseWithFallback(raw, ProjectSchema, EMPTY_PROJECT, { endpoint: "GET /api/projects/:id" });
}
+ async getProjectProgress(id: string): Promise<ProjectProgressDetail> {
+ const raw = await this.fetch<unknown>(`/api/projects/${id}/progress`);
+ return parseWithFallback(raw, ProjectProgressDetailSchema, EMPTY_PROJECT_PROGRESS_DETAIL, {
+ endpoint: "GET /api/projects/:id/progress",
+ });
+ }
+
async createProject(data: CreateProjectRequest): Promise<Project> {
const raw = await this.fetch<unknown>("/api/projects", {
method: "POST",
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.ts
index cfc756b93e..6a42f4a4f7 100644
--- a/packages/core/api/schemas.ts
+++ b/packages/core/api/schemas.ts
@@ -80,6 +80,7 @@ import type {
IssueUnread,
Label,
Project,
+ ProjectProgressDetail,
ListProjectsResponse,
MemberWithUser,
IssueProperty,
@@ -1809,6 +1810,16 @@ export const EMPTY_SEARCH_ISSUES_RESPONSE: SearchIssuesResponse = {
issues: [],
};
+const ProjectProgressSchema = z.object({
+ unit: z.literal("issues").catch("issues"),
+ scope: z.number().default(0),
+ completed: z.number().default(0),
+ started: z.number().default(0),
+ unstarted: z.number().default(0),
+ cancelled: z.number().default(0),
+ percent: z.number().default(0),
+}).loose();
+
export const ProjectSchema = z.object({
id: z.string(),
workspace_id: z.string(),
@@ -1832,6 +1843,8 @@ export const ProjectSchema = z.object({
last_activity_at: z.string().optional().catch(undefined),
issue_count: z.number().default(0),
done_count: z.number().default(0),
+ // Older servers omit it; consumers fall back to issue_count / done_count.
+ progress: ProjectProgressSchema.optional().catch(undefined),
resource_count: z.number().default(0),
workflow_id: z.string().nullable().default(null),
archived_at: z.string().nullable().default(null).catch(null),
@@ -1855,6 +1868,34 @@ export const ListProjectsResponseSchema = z.object({
total: z.number().default(0),
}).loose();
+export const ProjectProgressDetailSchema = z.object({
+ progress: ProjectProgressSchema,
+ by_assignee: z.array(z.object({
+ assignee_type: z.enum(["member", "agent", "squad"]).nullable().catch(null),
+ assignee_id: z.string().nullable().default(null),
+ scope: z.number().default(0),
+ completed: z.number().default(0),
+ started: z.number().default(0),
+ }).loose()).default([]),
+ history: z.array(z.object({
+ date: z.string(),
+ scope: z.number().default(0),
+ started: z.number().default(0),
+ completed: z.number().default(0),
+ }).loose()).default([]),
+ forecast: z.object({
+ completion_date: z.string(),
+ weekly_velocity: z.number(),
+ }).loose().nullable().default(null).catch(null),
+}).loose();
+
+export const EMPTY_PROJECT_PROGRESS_DETAIL: ProjectProgressDetail = {
+ progress: { unit: "issues", scope: 0, completed: 0, started: 0, unstarted: 0, cancelled: 0, percent: 0 },
+ by_assignee: [],
+ history: [],
+ forecast: null,
+};
+
export const EMPTY_LIST_PROJECTS_RESPONSE: ListProjectsResponse = { projects: [], total: 0 };
export const ProjectMemberSchema = z.object({
diff --git a/packages/core/projects/queries.ts b/packages/core/projects/queries.ts
index 4213da3b74..e44b391353 100644
--- a/packages/core/projects/queries.ts
+++ b/packages/core/projects/queries.ts
@@ -12,6 +12,9 @@ export const projectKeys = {
// Under `all`, so the project events that already refresh the list refresh
// the owner's overview too.
privateOverview: (wsId: string) => [...projectKeys.all(wsId), "private-overview"] as const,
+ // Under detail so the issue mutations that invalidate projectKeys.all also
+ // refresh the trend and breakdown.
+ progress: (wsId: string, id: string) => [...projectKeys.detail(wsId, id), "progress"] as const,
};
// The cached list includes archived projects: it doubles as the id → project
@@ -33,6 +36,13 @@ export function projectDetailOptions(wsId: string, id: string) {
});
}
+export function projectProgressOptions(wsId: string, id: string) {
+ return queryOptions({
+ queryKey: projectKeys.progress(wsId, id),
+ queryFn: () => api.getProjectProgress(id),
+ });
+}
+
export function projectMembersOptions(wsId: string, id: string) {
return queryOptions({
queryKey: projectKeys.members(wsId, id),
diff --git a/packages/core/types/index.ts b/packages/core/types/index.ts
index bb3b3e0df1..4896e1d8e6 100644
--- a/packages/core/types/index.ts
+++ b/packages/core/types/index.ts
@@ -212,6 +212,11 @@ export type {
ProjectStatus,
ProjectVisibility,
ProjectMember,
+ ProjectProgress,
+ ProjectProgressAssignee,
+ ProjectProgressPoint,
+ ProjectProgressForecast,
+ ProjectProgressDetail,
ListProjectMembersResponse,
PrivateProjectOverview,
ListPrivateProjectsResponse,
diff --git a/packages/core/types/project.ts b/packages/core/types/project.ts
index c81a5a0e46..ef75e9dad5 100644
--- a/packages/core/types/project.ts
+++ b/packages/core/types/project.ts
@@ -46,6 +46,49 @@ export interface ListPrivateProjectsResponse {
total: number;
}
+/**
+ * Issue-count progress of a project. Scope leaves out cancelled issues (the
+ * closed category); started issues are counted but add nothing to percent.
+ */
+export interface ProjectProgress {
+ unit: "issues";
+ scope: number;
+ completed: number;
+ started: number;
+ unstarted: number;
+ cancelled: number;
+ /** completed / scope, rounded down; 0 when scope is 0. */
+ percent: number;
+}
+
+export interface ProjectProgressAssignee {
+ assignee_type: "member" | "agent" | "squad" | null;
+ assignee_id: string | null;
+ scope: number;
+ completed: number;
+ started: number;
+}
+
+/** One weekly sample; `date` is a calendar day ("YYYY-MM-DD"), the last one is today. */
+export interface ProjectProgressPoint {
+ date: string;
+ scope: number;
+ started: number;
+ completed: number;
+}
+
+export interface ProjectProgressForecast {
+ completion_date: string;
+ weekly_velocity: number;
+}
+
+export interface ProjectProgressDetail {
+ progress: ProjectProgress;
+ by_assignee: ProjectProgressAssignee[];
+ history: ProjectProgressPoint[];
+ forecast: ProjectProgressForecast | null;
+}
+
export interface Project {
id: string;
workspace_id: string;
@@ -72,7 +115,10 @@ export interface Project {
*/
last_activity_at?: string;
issue_count: number;
+ /** Done and cancelled issues together; prefer `progress` for completion. */
done_count: number;
+ /** Optional because older servers do not send it. */
+ progress?: ProjectProgress;
resource_count: number;
/**
* The workflow this project uses; null for the workspace Default workflow.
diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.json
index 6ae4ca908d..02cd48fff5 100644
--- a/packages/views/locales/en/projects.json
+++ b/packages/views/locales/en/projects.json
@@ -102,7 +102,29 @@
"toast_project_deleted": "Project deleted",
"toast_move_issue_failed": "Failed to move issue",
"archive_action": "Archive project",
- "restore_action": "Restore project"
+ "restore_action": "Restore project",
+ "progress_panel": {
+ "summary_one": "{{completed}} of {{count}} issue done",
+ "summary_other": "{{completed}} of {{count}} issues done",
+ "legend_completed": "Done",
+ "legend_started": "In progress",
+ "legend_unstarted": "Not started",
+ "cancelled_note_one": "{{count}} cancelled issue isn't counted",
+ "cancelled_note_other": "{{count}} cancelled issues aren't counted",
+ "empty_hint": "Progress and the trend start once issues are added.",
+ "chart_label": "Weekly progress",
+ "chart_today": "Today",
+ "forecast_no_due": "At the recent pace, done by {{date}}",
+ "forecast_ahead_one": "At the recent pace, done by {{date}}, {{count}} day before the due date",
+ "forecast_ahead_other": "At the recent pace, done by {{date}}, {{count}} days before the due date",
+ "forecast_behind_one": "At the recent pace, done by {{date}}, {{count}} day after the due date",
+ "forecast_behind_other": "At the recent pace, done by {{date}}, {{count}} days after the due date",
+ "forecast_on_due": "At the recent pace, done by {{date}}, right on the due date",
+ "forecast_none": "Too few recent completions to forecast a finish date.",
+ "by_assignee": "By assignee",
+ "agent_tag": "Agent",
+ "unassigned": "Unassigned"
+ }
},
"resources": {
"section_header": "Resources",
diff --git a/packages/views/locales/es/projects.json b/packages/views/locales/es/projects.json
index fc67ab4734..4939b7e440 100644
--- a/packages/views/locales/es/projects.json
+++ b/packages/views/locales/es/projects.json
@@ -102,7 +102,29 @@
"back_to_list": "Todos los proyectos",
"empty_issues_add_existing": "Añadir tarea existente",
"archive_action": "Archivar proyecto",
- "restore_action": "Restaurar proyecto"
+ "restore_action": "Restaurar proyecto",
+ "progress_panel": {
+ "summary_one": "{{completed}} de {{count}} tarea hecha",
+ "summary_other": "{{completed}} de {{count}} tareas hechas",
+ "legend_completed": "Hechas",
+ "legend_started": "En curso",
+ "legend_unstarted": "Sin empezar",
+ "cancelled_note_one": "{{count}} tarea cancelada no cuenta",
+ "cancelled_note_other": "{{count}} tareas canceladas no cuentan",
+ "empty_hint": "El progreso y la tendencia empiezan cuando se añaden tareas.",
+ "chart_label": "Progreso semanal",
+ "chart_today": "Hoy",
+ "forecast_no_due": "Al ritmo reciente, terminará el {{date}}",
+ "forecast_ahead_one": "Al ritmo reciente, terminará el {{date}}, {{count}} día antes de la fecha límite",
+ "forecast_ahead_other": "Al ritmo reciente, terminará el {{date}}, {{count}} días antes de la fecha límite",
+ "forecast_behind_one": "Al ritmo reciente, terminará el {{date}}, {{count}} día después de la fecha límite",
+ "forecast_behind_other": "Al ritmo reciente, terminará el {{date}}, {{count}} días después de la fecha límite",
+ "forecast_on_due": "Al ritmo reciente, terminará el {{date}}, justo en la fecha límite",
+ "forecast_none": "Hay muy pocas tareas completadas recientemente para prever una fecha de fin.",
+ "by_assignee": "Por responsable",
+ "agent_tag": "Agente",
+ "unassigned": "Sin asignar"
+ }
},
"resources": {
"section_header": "Recursos",
diff --git a/packages/views/locales/fr/projects.json b/packages/views/locales/fr/projects.json
index 2ae0e1fa9e..c72afba911 100644
--- a/packages/views/locales/fr/projects.json
+++ b/packages/views/locales/fr/projects.json
@@ -102,7 +102,29 @@
"toast_project_deleted": "Projet supprimé",
"toast_move_issue_failed": "Échec du déplacement de la tâche",
"archive_action": "Archiver le projet",
- "restore_action": "Restaurer le projet"
+ "restore_action": "Restaurer le projet",
+ "progress_panel": {
+ "summary_one": "{{completed}} sur {{count}} tâche terminée",
+ "summary_other": "{{completed}} sur {{count}} tâches terminées",
+ "legend_completed": "Terminées",
+ "legend_started": "En cours",
+ "legend_unstarted": "Non commencées",
+ "cancelled_note_one": "{{count}} tâche annulée n'est pas comptée",
+ "cancelled_note_other": "{{count}} tâches annulées ne sont pas comptées",
+ "empty_hint": "La progression et la tendance démarrent dès que des tâches sont ajoutées.",
+ "chart_label": "Progression hebdomadaire",
+ "chart_today": "Aujourd'hui",
+ "forecast_no_due": "Au rythme récent, terminé le {{date}}",
+ "forecast_ahead_one": "Au rythme récent, terminé le {{date}}, {{count}} jour avant l'échéance",
+ "forecast_ahead_other": "Au rythme récent, terminé le {{date}}, {{count}} jours avant l'échéance",
+ "forecast_behind_one": "Au rythme récent, terminé le {{date}}, {{count}} jour après l'échéance",
+ "forecast_behind_other": "Au rythme récent, terminé le {{date}}, {{count}} jours après l'échéance",
+ "forecast_on_due": "Au rythme récent, terminé le {{date}}, pile à l'échéance",
+ "forecast_none": "Trop peu de tâches terminées récemment pour prévoir une date de fin.",
+ "by_assignee": "Par responsable",
+ "agent_tag": "Agent",
+ "unassigned": "Non assigné"
+ }
},
"resources": {
"section_header": "Ressources",
diff --git a/packages/views/locales/ja/projects.json b/packages/views/locales/ja/projects.json
index 56175629e7..6dacfefa19 100644
--- a/packages/views/locales/ja/projects.json
+++ b/packages/views/locales/ja/projects.json
@@ -102,7 +102,25 @@
"toast_project_deleted": "プロジェクトを削除しました",
"toast_move_issue_failed": "タスクを移動できませんでした",
"archive_action": "プロジェクトをアーカイブ",
- "restore_action": "プロジェクトを復元"
+ "restore_action": "プロジェクトを復元",
+ "progress_panel": {
+ "summary_other": "{{count}} 件のタスク中 {{completed}} 件が完了",
+ "legend_completed": "完了",
+ "legend_started": "進行中",
+ "legend_unstarted": "未着手",
+ "cancelled_note_other": "キャンセル済みの {{count}} 件は進捗に含めません",
+ "empty_hint": "タスクを追加すると進捗と推移の計算が始まります。",
+ "chart_label": "週ごとの進捗",
+ "chart_today": "今日",
+ "forecast_no_due": "最近のペースでは {{date}} に完了見込み",
+ "forecast_ahead_other": "最近のペースでは {{date}} に完了見込み(期日の {{count}} 日前)",
+ "forecast_behind_other": "最近のペースでは {{date}} に完了見込み(期日の {{count}} 日後)",
+ "forecast_on_due": "最近のペースでは {{date}} に完了見込み(期日どおり)",
+ "forecast_none": "最近の完了が少ないため、完了日を予測できません。",
+ "by_assignee": "担当者別",
+ "agent_tag": "エージェント",
+ "unassigned": "未割り当て"
+ }
},
"resources": {
"section_header": "リソース",
diff --git a/packages/views/locales/ko/projects.json b/packages/views/locales/ko/projects.json
index 3dfef60fc7..a8e5b32ccb 100644
--- a/packages/views/locales/ko/projects.json
+++ b/packages/views/locales/ko/projects.json
@@ -102,7 +102,25 @@
"toast_project_deleted": "프로젝트를 삭제했습니다",
"toast_move_issue_failed": "태스크를 이동하지 못했습니다",
"archive_action": "프로젝트 보관",
- "restore_action": "프로젝트 복원"
+ "restore_action": "프로젝트 복원",
+ "progress_panel": {
+ "summary_other": "태스크 {{count}}개 중 {{completed}}개 완료",
+ "legend_completed": "완료",
+ "legend_started": "진행 중",
+ "legend_unstarted": "시작 전",
+ "cancelled_note_other": "취소된 {{count}}개는 진행률에 포함하지 않습니다",
+ "empty_hint": "태스크를 추가하면 진행률과 추이 계산이 시작됩니다.",
+ "chart_label": "주간 진행률",
+ "chart_today": "오늘",
+ "forecast_no_due": "최근 속도라면 {{date}}에 완료 예상",
+ "forecast_ahead_other": "최근 속도라면 {{date}}에 완료 예상, 마감일보다 {{count}}일 빠름",
+ "forecast_behind_other": "최근 속도라면 {{date}}에 완료 예상, 마감일보다 {{count}}일 늦음",
+ "forecast_on_due": "최근 속도라면 {{date}}에 완료 예상, 마감일과 같은 날",
+ "forecast_none": "최근 완료된 태스크가 적어 완료일을 예측할 수 없습니다.",
+ "by_assignee": "담당자별",
+ "agent_tag": "에이전트",
+ "unassigned": "미배정"
+ }
},
"resources": {
"section_header": "리소스",
diff --git a/packages/views/locales/ru/projects.json b/packages/views/locales/ru/projects.json
index 2449ba9de4..177fb4d57c 100644
--- a/packages/views/locales/ru/projects.json
+++ b/packages/views/locales/ru/projects.json
@@ -102,7 +102,37 @@
"back_to_list": "Все проекты",
"empty_issues_add_existing": "Добавить существующую задачу",
"archive_action": "Архивировать проект",
- "restore_action": "Восстановить проект"
+ "restore_action": "Восстановить проект",
+ "progress_panel": {
+ "summary_one": "Готово {{completed}} из {{count}} задачи",
+ "summary_few": "Готово {{completed}} из {{count}} задач",
+ "summary_many": "Готово {{completed}} из {{count}} задач",
+ "summary_other": "Готово {{completed}} из {{count}} задачи",
+ "legend_completed": "Готово",
+ "legend_started": "В работе",
+ "legend_unstarted": "Не начато",
+ "cancelled_note_one": "{{count}} отменённая задача не учитывается",
+ "cancelled_note_few": "{{count}} отменённые задачи не учитываются",
+ "cancelled_note_many": "{{count}} отменённых задач не учитываются",
+ "cancelled_note_other": "{{count}} отменённой задачи не учитываются",
+ "empty_hint": "Прогресс и динамика начнут считаться, когда появятся задачи.",
+ "chart_label": "Прогресс по неделям",
+ "chart_today": "Сегодня",
+ "forecast_no_due": "В текущем темпе — к {{date}}",
+ "forecast_ahead_one": "В текущем темпе — к {{date}}, за {{count}} день до срока",
+ "forecast_ahead_few": "В текущем темпе — к {{date}}, за {{count}} дня до срока",
+ "forecast_ahead_many": "В текущем темпе — к {{date}}, за {{count}} дней до срока",
+ "forecast_ahead_other": "В текущем темпе — к {{date}}, за {{count}} дня до срока",
+ "forecast_behind_one": "В текущем темпе — к {{date}}, на {{count}} день позже срока",
+ "forecast_behind_few": "В текущем темпе — к {{date}}, на {{count}} дня позже срока",
+ "forecast_behind_many": "В текущем темпе — к {{date}}, на {{count}} дней позже срока",
+ "forecast_behind_other": "В текущем темпе — к {{date}}, на {{count}} дня позже срока",
+ "forecast_on_due": "В текущем темпе — к {{date}}, точно в срок",
+ "forecast_none": "Недавно завершённых задач слишком мало, чтобы спрогнозировать дату окончания.",
+ "by_assignee": "По исполнителям",
+ "agent_tag": "Агент",
+ "unassigned": "Не назначено"
+ }
},
"resources": {
"section_header": "Ресурсы",
diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.json
index 53d7f004ee..85019f2865 100644
--- a/packages/views/locales/zh-Hans/projects.json
+++ b/packages/views/locales/zh-Hans/projects.json
@@ -102,7 +102,25 @@
"toast_project_deleted": "已删除项目",
"toast_move_issue_failed": "移动任务失败",
"archive_action": "归档项目",
- "restore_action": "恢复项目"
+ "restore_action": "恢复项目",
+ "progress_panel": {
+ "summary_other": "{{count}} 个任务中已完成 {{completed}} 个",
+ "legend_completed": "已完成",
+ "legend_started": "进行中",
+ "legend_unstarted": "未开始",
+ "cancelled_note_other": "另有 {{count}} 个已取消,不计入进度",
+ "empty_hint": "任务加进来之后开始计算进度和趋势。",
+ "chart_label": "每周进度",
+ "chart_today": "今天",
+ "forecast_no_due": "按近期的完成速度,预计 {{date}} 完成",
+ "forecast_ahead_other": "按近期的完成速度,预计 {{date}} 完成,比截止日期早 {{count}} 天",
+ "forecast_behind_other": "按近期的完成速度,预计 {{date}} 完成,比截止日期晚 {{count}} 天",
+ "forecast_on_due": "按近期的完成速度,预计 {{date}} 完成,正好赶上截止日期",
+ "forecast_none": "近期完成的任务太少,暂时无法预测完成日期。",
+ "by_assignee": "按负责人",
+ "agent_tag": "智能体",
+ "unassigned": "未分配"
+ }
},
"resources": {
"section_header": "资源",
diff --git a/packages/views/locales/zh-Hant/projects.json b/packages/views/locales/zh-Hant/projects.json
index b9689341fe..271287bcb0 100644
--- a/packages/views/locales/zh-Hant/projects.json
+++ b/packages/views/locales/zh-Hant/projects.json
@@ -102,7 +102,25 @@
"toast_project_deleted": "已刪除專案",
"toast_move_issue_failed": "移動任務失敗",
"archive_action": "歸檔專案",
- "restore_action": "還原專案"
+ "restore_action": "還原專案",
+ "progress_panel": {
+ "summary_other": "{{count}} 個任務中已完成 {{completed}} 個",
+ "legend_completed": "已完成",
+ "legend_started": "進行中",
+ "legend_unstarted": "未開始",
+ "cancelled_note_other": "另有 {{count}} 個已取消,不計入進度",
+ "empty_hint": "任務加進來之後開始計算進度和趨勢。",
+ "chart_label": "每週進度",
+ "chart_today": "今天",
+ "forecast_no_due": "按近期的完成速度,預計 {{date}} 完成",
+ "forecast_ahead_other": "按近期的完成速度,預計 {{date}} 完成,比截止日期早 {{count}} 天",
+ "forecast_behind_other": "按近期的完成速度,預計 {{date}} 完成,比截止日期晚 {{count}} 天",
+ "forecast_on_due": "按近期的完成速度,預計 {{date}} 完成,正好趕上截止日期",
+ "forecast_none": "近期完成的任務太少,暫時無法預測完成日期。",
+ "by_assignee": "按負責人",
+ "agent_tag": "AI 代理",
+ "unassigned": "未指派"
+ }
},
"resources": {
"section_header": "資源",
diff --git a/packages/views/projects/components/project-board.tsx b/packages/views/projects/components/project-board.tsx
index 3aad89830f..43882ecb23 100644
--- a/packages/views/projects/components/project-board.tsx
+++ b/packages/views/projects/components/project-board.tsx
@@ -31,6 +31,7 @@ import { ProjectIcon } from "./project-icon";
import { ProjectLeadPicker } from "./project-lead-picker";
import { ProjectRowActions } from "./project-row-actions";
import { ProjectDate, projectDueState } from "./project-date";
+import { getProjectProgress } from "./project-issue-metrics";
const COLUMN_WIDTH = 280;
const CARD_WIDTH = COLUMN_WIDTH - 16 - 8;
@@ -231,8 +232,7 @@ function ProjectBoardCardContent({
onUpdate: (data: UpdateProjectRequest) => void;
}) {
const { t } = useT("projects");
- const pct =
- project.issue_count > 0 ? Math.round((project.done_count / project.issue_count) * 100) : 0;
+ const progress = getProjectProgress(project);
return (
<div className="flex flex-col gap-2 rounded-board-card border-[0.5px] border-board-card-border bg-board-card px-[var(--board-card-padding-x,0.625rem)] py-[var(--board-card-padding-y,var(--space-sm,0.75rem))] shadow-[var(--board-card-shadow,var(--surface-shadow))] transition-colors group-hover/card:border-foreground/15 group-hover/card:bg-board-card-hover">
@@ -240,9 +240,9 @@ function ProjectBoardCardContent({
<ProjectIcon project={project} size="sm" />
<span className="min-w-0 flex-1 truncate text-body font-medium">{project.title}</span>
</div>
- {project.issue_count > 0 ? (
+ {progress.scope > 0 ? (
<div className="h-1 overflow-hidden rounded-full bg-muted">
- <div className="h-full rounded-full bg-emerald-500" style={{ width: `${pct}%` }} />
+ <div className="h-full rounded-full bg-emerald-500" style={{ width: `${progress.percent}%` }} />
</div>
) : null}
<div className="flex min-w-0 items-center gap-1.5 text-caption text-muted-foreground">
diff --git a/packages/views/projects/components/project-detail.tsx b/packages/views/projects/components/project-detail.tsx
index e4a130aa05..139cb02437 100644
--- a/packages/views/projects/components/project-detail.tsx
+++ b/packages/views/projects/components/project-detail.tsx
@@ -25,7 +25,7 @@ import { useRecentContextStore } from "@multica/core/chat";
import { useWorkspacePaths } from "@multica/core/paths";
import { useActorName } from "@multica/core/workspace/hooks";
import { PROJECT_STATUS_ORDER, PROJECT_STATUS_CONFIG, PROJECT_PRIORITY_ORDER } from "@multica/core/projects/config";
-import { getProjectIssueMetrics } from "./project-issue-metrics";
+import { ProjectProgressSection } from "./project-progress-section";
import { ActorAvatar } from "../../common/actor-avatar";
import { AppLink, currentPath, useNavigation } from "../../navigation";
import { TitleEditor, ContentEditor, type ContentEditorRef } from "../../editor";
@@ -328,7 +328,6 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
);
}
- const issueMetrics = getProjectIssueMetrics(project);
const archived = !!project.archived_at;
const statusCfg = PROJECT_STATUS_CONFIG[project.status];
@@ -468,32 +467,19 @@ export function ProjectDetail({ projectId }: { projectId: string }) {
</div>
{/* Progress */}
- {issueMetrics.totalCount > 0 && (() => {
- const pct = Math.round((issueMetrics.completedCount / issueMetrics.totalCount) * 100);
- return (
- <div>
- <button
- type="button"
- className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${progressOpen ? "" : "text-muted-foreground hover:text-foreground"}`}
- onClick={() => setProgressOpen(!progressOpen)}
- >
- {t(($) => $.detail.section_progress)}
- <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${progressOpen ? "rotate-90" : ""}`} />
- </button>
- {progressOpen && <div className="pl-2 flex items-center gap-3">
- <div className="relative h-2 flex-1 rounded-full bg-muted overflow-hidden">
- <div
- className="absolute inset-y-0 left-0 rounded-full bg-emerald-500 transition-all"
- style={{ width: `${pct}%` }}
- />
- </div>
- <span className="text-caption text-muted-foreground tabular-nums shrink-0">
- {issueMetrics.completedCount}/{issueMetrics.totalCount}
- </span>
- </div>}
- </div>
- );
- })()}
+ <div>
+ <button
+ type="button"
+ className={`flex w-full items-center gap-1 rounded-md px-2 py-1 text-caption font-medium transition-colors mb-2 hover:bg-accent/70 ${progressOpen ? "" : "text-muted-foreground hover:text-foreground"}`}
+ onClick={() => setProgressOpen(!progressOpen)}
+ >
+ {t(($) => $.detail.section_progress)}
+ <ChevronRight className={`!size-3 shrink-0 stroke-[2.5] text-muted-foreground transition-transform ${progressOpen ? "rotate-90" : ""}`} />
+ </button>
+ {progressOpen && <div className="pl-2">
+ <ProjectProgressSection project={project} />
+ </div>}
+ </div>
{/* Description */}
<div>
diff --git a/packages/views/projects/components/project-issue-metrics.ts b/packages/views/projects/components/project-issue-metrics.ts
index 376a981d54..1e111060d9 100644
--- a/packages/views/projects/components/project-issue-metrics.ts
+++ b/packages/views/projects/components/project-issue-metrics.ts
@@ -1,10 +1,23 @@
-import type { Project } from "@multica/core/types";
+import type { Project, ProjectProgress } from "@multica/core/types";
-export function getProjectIssueMetrics(
- project: Pick<Project, "issue_count" | "done_count">,
-) {
+/**
+ * The project's progress summary. Servers that predate `progress` only send
+ * issue_count / done_count, where done_count also counts cancelled issues;
+ * that older ratio is the best available there.
+ */
+export function getProjectProgress(
+ project: Pick<Project, "issue_count" | "done_count" | "progress">,
+): ProjectProgress {
+ if (project.progress) return project.progress;
+ const scope = project.issue_count;
+ const completed = Math.min(project.done_count, scope);
return {
- totalCount: project.issue_count,
- completedCount: project.done_count,
+ unit: "issues",
+ scope,
+ completed,
+ started: 0,
+ unstarted: scope - completed,
+ cancelled: 0,
+ percent: scope > 0 ? Math.floor((completed * 100) / scope) : 0,
};
}
diff --git a/packages/views/projects/components/project-progress-section.test.tsx b/packages/views/projects/components/project-progress-section.test.tsx
new file mode 100644
index 0000000000..fbebbdf9fd
--- /dev/null
+++ b/packages/views/projects/components/project-progress-section.test.tsx
@@ -0,0 +1,105 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { setApiInstance } from "@multica/core/api";
+import type { ApiClient } from "@multica/core/api/client";
+import { useModalStore } from "@multica/core/modals";
+import type { Project, ProjectProgressDetail } from "@multica/core/types";
+import { renderWithI18n } from "../../test/i18n";
+import { ProjectProgressSection } from "./project-progress-section";
+import { getProjectProgress } from "./project-issue-metrics";
+
+vi.mock("@multica/core/hooks", () => ({ useWorkspaceId: () => "workspace-1" }));
+vi.mock("@multica/core/workspace/hooks", () => ({
+ useActorName: () => ({ getActorName: (_type: string, id: string) => (id === "agent-1" ? "Lambda" : "Chen") }),
+}));
+vi.mock("../../common/actor-avatar", () => ({ ActorAvatar: () => <span data-testid="avatar" /> }));
+
+const getProjectProgressMock = vi.fn();
+
+const baseProject: Project = {
+ id: "project-1",
+ workspace_id: "workspace-1",
+ title: "Mobile 2.0",
+ description: null,
+ icon: null,
+ status: "in_progress",
+ priority: "none",
+ lead_type: null,
+ lead_id: null,
+ start_date: null,
+ due_date: "2026-12-18",
+ created_at: "2026-10-12T00:00:00Z",
+ updated_at: "2026-10-12T00:00:00Z",
+ issue_count: 12,
+ done_count: 6,
+ resource_count: 0,
+ progress: { unit: "issues", scope: 11, completed: 5, started: 3, unstarted: 3, cancelled: 1, percent: 45 },
+};
+
+const detail: ProjectProgressDetail = {
+ progress: baseProject.progress!,
+ by_assignee: [
+ { assignee_type: "agent", assignee_id: "agent-1", scope: 5, completed: 3, started: 2 },
+ { assignee_type: null, assignee_id: null, scope: 1, completed: 0, started: 0 },
+ ],
+ history: [
+ { date: "2026-10-12", scope: 6, started: 1, completed: 0 },
+ { date: "2026-11-09", scope: 11, started: 3, completed: 5 },
+ ],
+ forecast: { completion_date: "2026-12-14", weekly_velocity: 1.25 },
+};
+
+function renderSection(project: Project) {
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ return renderWithI18n(
+ <QueryClientProvider client={queryClient}>
+ <ProjectProgressSection project={project} />
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ getProjectProgressMock.mockReset();
+ setApiInstance({ getProjectProgress: getProjectProgressMock } as unknown as ApiClient);
+});
+
+describe("ProjectProgressSection", () => {
+ it("shows completion against scope, keeps cancelled issues out, and forecasts against the due date", async () => {
+ getProjectProgressMock.mockResolvedValue(detail);
+ renderSection(baseProject);
+
+ expect(screen.getByText("45%")).toBeInTheDocument();
+ expect(screen.getByText("5 of 11 issues done")).toBeInTheDocument();
+ expect(screen.getByText("1 cancelled issue isn't counted")).toBeInTheDocument();
+
+ expect(await screen.findByText(/done by Dec 14, 4 days before the due date/)).toBeInTheDocument();
+ expect(screen.getByText("Lambda")).toBeInTheDocument();
+ expect(screen.getByText("Agent")).toBeInTheDocument();
+ expect(screen.getByText("Unassigned")).toBeInTheDocument();
+ expect(screen.getByText("3/5")).toBeInTheDocument();
+ expect(getProjectProgressMock).toHaveBeenCalledWith("project-1");
+ });
+
+ it("keeps the section on an empty project with ways to add issues", async () => {
+ getProjectProgressMock.mockResolvedValue({ ...detail, progress: { ...detail.progress, scope: 0, completed: 0, started: 0, unstarted: 0, cancelled: 0, percent: 0 }, by_assignee: [], history: [] });
+ const open = vi.spyOn(useModalStore.getState(), "open");
+ renderSection({ ...baseProject, issue_count: 0, done_count: 0, progress: { ...detail.progress, scope: 0, completed: 0, started: 0, unstarted: 0, cancelled: 0, percent: 0 } });
+
+ expect(screen.getByText("0%")).toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "New issue" }));
+ expect(open).toHaveBeenCalledWith("create-issue", { project_id: "project-1" });
+ await userEvent.click(screen.getByRole("button", { name: "Add existing issue" }));
+ expect(open).toHaveBeenCalledWith("project-add-issue", { projectId: "project-1" });
+ });
+});
+
+describe("getProjectProgress", () => {
+ it("falls back to issue_count / done_count from servers without progress", () => {
+ expect(getProjectProgress({ issue_count: 4, done_count: 1 })).toEqual({
+ unit: "issues", scope: 4, completed: 1, started: 0, unstarted: 3, cancelled: 0, percent: 25,
+ });
+ expect(getProjectProgress({ issue_count: 0, done_count: 0 }).percent).toBe(0);
+ });
+});
diff --git a/packages/views/projects/components/project-progress-section.tsx b/packages/views/projects/components/project-progress-section.tsx
new file mode 100644
index 0000000000..a658e87bf2
--- /dev/null
+++ b/packages/views/projects/components/project-progress-section.tsx
@@ -0,0 +1,313 @@
+"use client";
+
+import type { ReactNode } from "react";
+import { useQuery } from "@tanstack/react-query";
+import { Plus, User } from "@multica/ui/icons";
+import { Button } from "@multica/ui/components/ui/button";
+import { cn } from "@multica/ui/lib/utils";
+import type {
+ Project,
+ ProjectProgress,
+ ProjectProgressAssignee,
+ ProjectProgressForecast,
+ ProjectProgressPoint,
+} from "@multica/core/types";
+import { useWorkspaceId } from "@multica/core/hooks";
+import { useModalStore } from "@multica/core/modals";
+import { projectProgressOptions } from "@multica/core/projects/queries";
+import { useActorName } from "@multica/core/workspace/hooks";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { useLocale, useT } from "../../i18n";
+import { getProjectProgress } from "./project-issue-metrics";
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+// Calendar days ("YYYY-MM-DD") are compared and formatted in UTC, the same
+// clock the server samples history on.
+function dayValue(date: string): number {
+ return Date.parse(`${date}T00:00:00Z`);
+}
+
+function daysBetween(from: string, to: string): number {
+ return Math.round((dayValue(to) - dayValue(from)) / DAY_MS);
+}
+
+function useFormatDay() {
+ const locale = useLocale();
+ const format = new Intl.DateTimeFormat(locale, { month: "short", day: "numeric", timeZone: "UTC" });
+ return (date: string) => format.format(dayValue(date));
+}
+
+export function ProjectProgressSection({ project }: { project: Project }) {
+ const wsId = useWorkspaceId();
+ const { data: detail } = useQuery(projectProgressOptions(wsId, project.id));
+ const progress = detail?.progress ?? getProjectProgress(project);
+
+ if (progress.scope === 0) {
+ return <ProjectProgressEmpty project={project} cancelled={progress.cancelled} />;
+ }
+
+ return (
+ <div className="space-y-3">
+ <ProgressSummary progress={progress} />
+ {detail && detail.history.length >= 2 && (
+ <ProgressTrend history={detail.history} forecast={detail.forecast} dueDate={project.due_date} />
+ )}
+ {detail && (
+ <ForecastNote progress={progress} history={detail.history} forecast={detail.forecast} dueDate={project.due_date} />
+ )}
+ {detail && detail.by_assignee.length > 0 && <AssigneeBreakdown rows={detail.by_assignee} />}
+ </div>
+ );
+}
+
+function ProjectProgressEmpty({ project, cancelled }: { project: Project; cancelled: number }) {
+ const { t } = useT("projects");
+ return (
+ <div className="space-y-2">
+ <div className="flex items-baseline gap-2">
+ <span className="text-title font-semibold tabular-nums">0%</span>
+ <span className="text-caption text-muted-foreground">{t(($) => $.detail.no_issues_yet)}</span>
+ </div>
+ <div className="h-2 rounded-full bg-muted" />
+ {cancelled > 0 && <CancelledNote count={cancelled} />}
+ <p className="text-caption text-muted-foreground">{t(($) => $.detail.progress_panel.empty_hint)}</p>
+ <div className="flex flex-wrap gap-2">
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => useModalStore.getState().open("create-issue", { project_id: project.id })}
+ >
+ <Plus aria-hidden="true" />
+ {t(($) => $.detail.empty_issues_new_button)}
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => useModalStore.getState().open("project-add-issue", { projectId: project.id })}
+ >
+ {t(($) => $.detail.empty_issues_add_existing)}
+ </Button>
+ </div>
+ </div>
+ );
+}
+
+function CancelledNote({ count }: { count: number }) {
+ const { t } = useT("projects");
+ return (
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.detail.progress_panel.cancelled_note, { count })}
+ </p>
+ );
+}
+
+function ProgressSummary({ progress }: { progress: ProjectProgress }) {
+ const { t } = useT("projects");
+ const share = (n: number) => `${(n / progress.scope) * 100}%`;
+ const legend = [
+ { key: "completed", label: t(($) => $.detail.progress_panel.legend_completed), count: progress.completed, swatch: "bg-info" },
+ { key: "started", label: t(($) => $.detail.progress_panel.legend_started), count: progress.started, swatch: "bg-warning" },
+ { key: "unstarted", label: t(($) => $.detail.progress_panel.legend_unstarted), count: progress.unstarted, swatch: "bg-muted" },
+ ];
+ return (
+ <div className="space-y-2">
+ <div className="flex items-baseline gap-2">
+ <span className="text-title font-semibold tabular-nums">{progress.percent}%</span>
+ <span className="text-caption text-muted-foreground">
+ {t(($) => $.detail.progress_panel.summary, { count: progress.scope, completed: progress.completed })}
+ </span>
+ </div>
+ <div
+ className="flex h-2 overflow-hidden rounded-full bg-muted"
+ role="img"
+ aria-label={legend.map((item) => `${item.label} ${item.count}`).join(", ")}
+ >
+ <div className="h-full bg-info transition-all" style={{ width: share(progress.completed) }} />
+ <div className="h-full bg-warning transition-all" style={{ width: share(progress.started) }} />
+ </div>
+ <div className="flex flex-wrap gap-x-3 gap-y-1 text-caption text-muted-foreground">
+ {legend.map((item) => (
+ <span key={item.key} className="inline-flex items-center gap-1.5">
+ <span className={cn("size-2 rounded-xs", item.swatch)} aria-hidden="true" />
+ {item.label}
+ <span className="tabular-nums text-foreground">{item.count}</span>
+ </span>
+ ))}
+ </div>
+ {progress.cancelled > 0 && <CancelledNote count={progress.cancelled} />}
+ </div>
+ );
+}
+
+const CHART_W = 280;
+const CHART_H = 96;
+const CHART_TOP = 6;
+
+function ProgressTrend({
+ history,
+ forecast,
+ dueDate,
+}: {
+ history: ProjectProgressPoint[];
+ forecast: ProjectProgressForecast | null;
+ dueDate: string | null;
+}) {
+ const { t } = useT("projects");
+ const formatDay = useFormatDay();
+ const first = history[0]!;
+ const today = history[history.length - 1]!;
+ const due = dueDate && dayValue(dueDate) >= dayValue(first.date) ? dueDate : null;
+ const end = [today.date, due, forecast?.completion_date]
+ .filter((d): d is string => !!d)
+ .reduce((a, b) => (dayValue(b) > dayValue(a) ? b : a));
+ const span = Math.max(daysBetween(first.date, end), 1);
+ const max = Math.max(...history.map((p) => p.scope), 1);
+
+ const x = (date: string) => (daysBetween(first.date, date) / span) * CHART_W;
+ const y = (n: number) => CHART_H - (n / max) * (CHART_H - CHART_TOP);
+ const line = (value: (p: ProjectProgressPoint) => number) =>
+ history.map((p) => `${x(p.date).toFixed(1)},${y(value(p)).toFixed(1)}`).join(" ");
+ const band = (upper: (p: ProjectProgressPoint) => number, lower: (p: ProjectProgressPoint) => number) =>
+ `${line(upper)} ${[...history].reverse().map((p) => `${x(p.date).toFixed(1)},${y(lower(p)).toFixed(1)}`).join(" ")}`;
+
+ return (
+ <figure className="space-y-1" aria-label={t(($) => $.detail.progress_panel.chart_label)}>
+ <svg
+ viewBox={`0 0 ${CHART_W} ${CHART_H}`}
+ preserveAspectRatio="none"
+ className="h-24 w-full overflow-visible"
+ aria-hidden="true"
+ >
+ <line x1={0} y1={CHART_H} x2={CHART_W} y2={CHART_H} stroke="var(--border)" vectorEffect="non-scaling-stroke" />
+ <polygon points={band((p) => p.completed + p.started, (p) => p.completed)} fill="var(--warning)" fillOpacity={0.22} />
+ <polygon points={band((p) => p.completed, () => 0)} fill="var(--info)" fillOpacity={0.22} />
+ <polyline points={line((p) => p.scope)} fill="none" stroke="var(--muted-foreground)" strokeWidth={1.5} vectorEffect="non-scaling-stroke" />
+ <polyline points={line((p) => p.completed + p.started)} fill="none" stroke="var(--warning)" strokeWidth={1.5} vectorEffect="non-scaling-stroke" />
+ <polyline points={line((p) => p.completed)} fill="none" stroke="var(--info)" strokeWidth={2} vectorEffect="non-scaling-stroke" />
+ {forecast && (
+ <>
+ <line
+ x1={x(today.date)} y1={y(today.completed)} x2={x(forecast.completion_date)} y2={y(today.scope)}
+ stroke="var(--info)" strokeWidth={1.5} strokeDasharray="3 3" vectorEffect="non-scaling-stroke"
+ />
+ <line
+ x1={x(forecast.completion_date)} y1={CHART_TOP} x2={x(forecast.completion_date)} y2={CHART_H}
+ stroke="var(--info)" strokeOpacity={0.5} strokeDasharray="2 2" vectorEffect="non-scaling-stroke"
+ />
+ </>
+ )}
+ {due && (
+ <line
+ x1={x(due)} y1={0} x2={x(due)} y2={CHART_H}
+ stroke="var(--destructive)" strokeWidth={1.5} vectorEffect="non-scaling-stroke"
+ />
+ )}
+ </svg>
+ <div className="relative h-4 whitespace-nowrap text-micro text-muted-foreground">
+ <span className="absolute left-0">{formatDay(first.date)}</span>
+ {x(today.date) > CHART_W * 0.2 && (!due || Math.abs(x(due) - x(today.date)) > CHART_W * 0.2) && (
+ <AxisLabel at={x(today.date)}>{t(($) => $.detail.progress_panel.chart_today)}</AxisLabel>
+ )}
+ {due && (
+ <AxisLabel at={x(due)} className="text-destructive">{formatDay(due)}</AxisLabel>
+ )}
+ </div>
+ </figure>
+ );
+}
+
+// Centered under its x position, pinned to the right edge at the end of the axis.
+function AxisLabel({ at, className, children }: { at: number; className?: string; children: ReactNode }) {
+ if (at >= CHART_W * 0.85) {
+ return <span className={cn("absolute right-0", className)}>{children}</span>;
+ }
+ return (
+ <span className={cn("absolute -translate-x-1/2", className)} style={{ left: `${(at / CHART_W) * 100}%` }}>
+ {children}
+ </span>
+ );
+}
+
+function ForecastNote({
+ progress,
+ history,
+ forecast,
+ dueDate,
+}: {
+ progress: ProjectProgress;
+ history: ProjectProgressPoint[];
+ forecast: ProjectProgressForecast | null;
+ dueDate: string | null;
+}) {
+ const { t } = useT("projects");
+ const formatDay = useFormatDay();
+ if (progress.completed >= progress.scope) return null;
+ if (!forecast) {
+ if (history.length < 2) return null;
+ return <p className="text-caption text-muted-foreground">{t(($) => $.detail.progress_panel.forecast_none)}</p>;
+ }
+ const date = formatDay(forecast.completion_date);
+ let text: string;
+ if (!dueDate) {
+ text = t(($) => $.detail.progress_panel.forecast_no_due, { date });
+ } else {
+ const slack = daysBetween(forecast.completion_date, dueDate);
+ if (slack > 0) text = t(($) => $.detail.progress_panel.forecast_ahead, { date, count: slack });
+ else if (slack < 0) text = t(($) => $.detail.progress_panel.forecast_behind, { date, count: -slack });
+ else text = t(($) => $.detail.progress_panel.forecast_on_due, { date });
+ }
+ return (
+ <p className={cn("text-caption", dueDate && daysBetween(forecast.completion_date, dueDate) < 0 ? "text-destructive" : "text-muted-foreground")}>
+ {text}
+ </p>
+ );
+}
+
+function AssigneeBreakdown({ rows }: { rows: ProjectProgressAssignee[] }) {
+ const { t } = useT("projects");
+ const { getActorName } = useActorName();
+ return (
+ <div className="space-y-2">
+ <div className="text-caption font-medium text-muted-foreground">
+ {t(($) => $.detail.progress_panel.by_assignee)}
+ </div>
+ <ul className="space-y-1.5">
+ {rows.map((row) => {
+ const assigned = row.assignee_type && row.assignee_id;
+ const name = assigned
+ ? getActorName(row.assignee_type!, row.assignee_id!)
+ : t(($) => $.detail.progress_panel.unassigned);
+ return (
+ <li key={`${row.assignee_type ?? "none"}:${row.assignee_id ?? ""}`} className="flex items-center gap-2 text-caption">
+ {assigned ? (
+ <ActorAvatar actorType={row.assignee_type!} actorId={row.assignee_id!} size="sm" />
+ ) : (
+ <span className="flex size-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
+ <User className="size-3" aria-hidden="true" />
+ </span>
+ )}
+ <span className="min-w-0 flex-1 truncate">
+ {name}
+ {row.assignee_type === "agent" && (
+ <span className="ml-1.5 rounded-sm border px-1 text-micro text-muted-foreground">
+ {t(($) => $.detail.progress_panel.agent_tag)}
+ </span>
+ )}
+ </span>
+ <span className="h-1.5 w-16 shrink-0 overflow-hidden rounded-full bg-muted">
+ <span
+ className="block h-full rounded-full bg-info"
+ style={{ width: `${row.scope > 0 ? (row.completed / row.scope) * 100 : 0}%` }}
+ />
+ </span>
+ <span className="w-10 shrink-0 text-right tabular-nums text-muted-foreground">
+ {row.completed}/{row.scope}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ );
+}
diff --git a/packages/views/projects/components/projects-page.tsx b/packages/views/projects/components/projects-page.tsx
index ac8c3c6199..67d91a6ca7 100644
--- a/packages/views/projects/components/projects-page.tsx
+++ b/packages/views/projects/components/projects-page.tsx
@@ -100,6 +100,7 @@ import {
type ProjectGroupField,
} from "./project-groups";
import { PriorityIcon } from "../../issues/components/priority-icon";
+import { getProjectProgress } from "./project-issue-metrics";
import { cn } from "@multica/ui/lib/utils";
// Sort order maps for the enum columns (header sort needs a total order).
@@ -118,8 +119,10 @@ const STATUS_ORDER: Record<ProjectStatus, number> = {
cancelled: 4,
};
-const progressOf = (p: Project) =>
- p.issue_count > 0 ? p.done_count / p.issue_count : -1;
+const progressOf = (p: Project) => {
+ const progress = getProjectProgress(p);
+ return progress.scope > 0 ? progress.completed / progress.scope : -1;
+};
// Composite "type:id" lead value so the string[] filter holds member/agent
// refs alike.
@@ -128,15 +131,16 @@ function leadFilterValue(p: Project): string | null {
}
function ProgressRing({ project }: { project: Project }) {
- if (project.issue_count === 0) return <CollectionEmptyValue />;
- const pct = Math.round((project.done_count / project.issue_count) * 100);
+ const progress = getProjectProgress(project);
+ if (progress.scope === 0) return <CollectionEmptyValue />;
+ const pct = progress.percent;
return (
<span className="flex items-center gap-1.5">
<span className="relative h-3.5 w-3.5">
<svg className="h-3.5 w-3.5 -rotate-90" viewBox="0 0 16 16">
<circle className="text-muted" strokeWidth="2" stroke="currentColor" fill="none" r="6" cx="8" cy="8" />
<circle
- className="text-emerald-500"
+ className="text-info"
strokeWidth="2"
stroke="currentColor"
fill="none"
@@ -149,7 +153,7 @@ function ProgressRing({ project }: { project: Project }) {
</svg>
</span>
<span className="tabular-nums">
- {project.done_count}/{project.issue_count}
+ {progress.completed}/{progress.scope}
</span>
</span>
);
diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.go
index 0e8d0506e8..6b07a162f4 100644
--- a/server/cmd/multica/cmd_project.go
+++ b/server/cmd/multica/cmd_project.go
@@ -40,6 +40,22 @@ var projectGetCmd = &cobra.Command{
RunE: runProjectGet,
}
+var projectProgressCmd = &cobra.Command{
+ Use: "progress <id>",
+ Short: "Show project progress: completed vs. scope, weekly trend and forecast",
+ Long: `Show project progress.
+
+Scope is every issue in the project except cancelled ones (closed category).
+Completed counts issues in the done category; started issues are tracked but
+do not add to the percentage. Each issue counts as one.
+
+--history prints the weekly trend (scope, started, completed per week).
+--by assignee breaks scope and completion down per assignee.
+JSON output always carries the full response.`,
+ Args: exactArgs(1),
+ RunE: runProjectProgress,
+}
+
var projectCreateCmd = &cobra.Command{
Use: "create",
Short: "Create a new project",
@@ -174,6 +190,7 @@ func validateProjectStatus(status string) error {
func init() {
projectCmd.AddCommand(projectListCmd)
projectCmd.AddCommand(projectGetCmd)
+ projectCmd.AddCommand(projectProgressCmd)
projectCmd.AddCommand(projectCreateCmd)
projectCmd.AddCommand(projectUpdateCmd)
projectCmd.AddCommand(projectDeleteCmd)
@@ -200,6 +217,10 @@ func init() {
// project get
projectGetCmd.Flags().String("output", "json", "Output format: table or json")
+ projectProgressCmd.Flags().String("output", "table", "Output format: table or json")
+ projectProgressCmd.Flags().Bool("history", false, "Print the weekly trend")
+ projectProgressCmd.Flags().String("by", "", "Break progress down by: assignee")
+
// project create
projectCreateCmd.Flags().String("title", "", "Project title (required)")
projectCreateCmd.Flags().String("description", "", "Project description")
@@ -389,7 +410,7 @@ func runProjectList(cmd *cobra.Command, _ []string) error {
strVal(p, "title"),
strVal(p, "status"),
strVal(p, "priority"),
- formatProjectProgress(p),
+ formatProjectProgress(p["progress"]),
formatLead(p, actors),
strVal(p, "due_date"),
dayOf(strVal(p, "last_activity_at")),
@@ -408,15 +429,6 @@ func dayOf(ts string) string {
return ts
}
-func formatProjectProgress(p map[string]any) string {
- total, _ := p["issue_count"].(float64)
- if total == 0 {
- return ""
- }
- done, _ := p["done_count"].(float64)
- return fmt.Sprintf("%d/%d", int(done), int(total))
-}
-
// resolveProjectLeadFilters turns --lead values into the API's lead refs:
// member:<id>, agent:<id> or none.
func resolveProjectLeadFilters(ctx context.Context, client *cli.APIClient, leads []string) ([]string, error) {
@@ -475,12 +487,13 @@ func runProjectGet(cmd *cobra.Command, args []string) error {
if output == "table" {
actors := loadActorDisplayLookup(ctx, client)
lead := formatLead(project, actors)
- headers := []string{"ID", "TITLE", "STATUS", "LEAD", "ARCHIVED", "DESCRIPTION"}
+ headers := []string{"ID", "TITLE", "STATUS", "LEAD", "PROGRESS", "ARCHIVED", "DESCRIPTION"}
rows := [][]string{{
strVal(project, "id"),
strVal(project, "title"),
strVal(project, "status"),
lead,
+ formatProjectProgress(project["progress"]),
formatProjectArchived(project),
strVal(project, "description"),
}}
@@ -1264,6 +1277,121 @@ func summarizeResourceRef(raw any) string {
// Helpers
+func runProjectProgress(cmd *cobra.Command, args []string) error {
+ by, _ := cmd.Flags().GetString("by")
+ if by != "" && by != "assignee" {
+ return fmt.Errorf("invalid --by %q; valid values: assignee", by)
+ }
+ history, _ := cmd.Flags().GetBool("history")
+ if history && by != "" {
+ return fmt.Errorf("--history and --by cannot be combined")
+ }
+
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+ ctx, cancel := cli.APIContext(context.Background())
+ defer cancel()
+
+ projectRef, err := resolveProjectID(ctx, client, args[0])
+ if err != nil {
+ return fmt.Errorf("resolve project: %w", err)
+ }
+ var resp map[string]any
+ if err := client.GetJSON(ctx, "/api/projects/"+projectRef.ID+"/progress", &resp); err != nil {
+ return fmt.Errorf("get project progress: %w", err)
+ }
+
+ output, _ := cmd.Flags().GetString("output")
+ if output != "table" {
+ return cli.PrintJSON(os.Stdout, resp)
+ }
+ switch {
+ case history:
+ headers, rows := projectProgressHistoryTable(resp)
+ cli.PrintTable(os.Stdout, headers, rows)
+ case by == "assignee":
+ headers, rows := projectProgressAssigneeTable(resp, loadActorDisplayLookup(ctx, client))
+ cli.PrintTable(os.Stdout, headers, rows)
+ default:
+ headers, rows := projectProgressSummaryTable(resp)
+ cli.PrintTable(os.Stdout, headers, rows)
+ }
+ return nil
+}
+
+func progressInt(m map[string]any, key string) int64 {
+ n, _ := m[key].(float64)
+ return int64(n)
+}
+
+// formatProjectProgress renders a progress object as "completed/scope (pct%)".
+func formatProjectProgress(v any) string {
+ p, ok := v.(map[string]any)
+ if !ok {
+ return ""
+ }
+ return fmt.Sprintf("%d/%d (%d%%)", progressInt(p, "completed"), progressInt(p, "scope"), progressInt(p, "percent"))
+}
+
+func projectProgressSummaryTable(resp map[string]any) ([]string, [][]string) {
+ p, _ := resp["progress"].(map[string]any)
+ forecast := ""
+ if f, ok := resp["forecast"].(map[string]any); ok {
+ forecast = fmt.Sprintf("%s (%.2f/week)", strVal(f, "completion_date"), f["weekly_velocity"])
+ }
+ headers := []string{"PROGRESS", "SCOPE", "COMPLETED", "STARTED", "UNSTARTED", "CANCELLED", "FORECAST"}
+ rows := [][]string{{
+ formatProjectProgress(p),
+ fmt.Sprint(progressInt(p, "scope")),
+ fmt.Sprint(progressInt(p, "completed")),
+ fmt.Sprint(progressInt(p, "started")),
+ fmt.Sprint(progressInt(p, "unstarted")),
+ fmt.Sprint(progressInt(p, "cancelled")),
+ forecast,
+ }}
+ return headers, rows
+}
+
+func projectProgressHistoryTable(resp map[string]any) ([]string, [][]string) {
+ points, _ := resp["history"].([]any)
+ rows := make([][]string, 0, len(points))
+ for _, raw := range points {
+ p, _ := raw.(map[string]any)
+ rows = append(rows, []string{
+ strVal(p, "date"),
+ fmt.Sprint(progressInt(p, "scope")),
+ fmt.Sprint(progressInt(p, "started")),
+ fmt.Sprint(progressInt(p, "completed")),
+ })
+ }
+ return []string{"WEEK", "SCOPE", "STARTED", "COMPLETED"}, rows
+}
+
+func projectProgressAssigneeTable(resp map[string]any, actors actorDisplayLookup) ([]string, [][]string) {
+ entries, _ := resp["by_assignee"].([]any)
+ rows := make([][]string, 0, len(entries))
+ for _, raw := range entries {
+ e, _ := raw.(map[string]any)
+ name := actors.actor(strVal(e, "assignee_type"), strVal(e, "assignee_id"))
+ if name == "" {
+ name = "unassigned"
+ }
+ scope, completed := progressInt(e, "scope"), progressInt(e, "completed")
+ percent := int64(0)
+ if scope > 0 {
+ percent = completed * 100 / scope
+ }
+ rows = append(rows, []string{
+ name,
+ fmt.Sprintf("%d/%d (%d%%)", completed, scope, percent),
+ fmt.Sprint(progressInt(e, "started")),
+ })
+ }
+ return []string{"ASSIGNEE", "COMPLETED", "STARTED"}, rows
+}
+
func formatLead(project map[string]any, actors actorDisplayLookup) string {
lType := strVal(project, "lead_type")
lID := strVal(project, "lead_id")
diff --git a/server/cmd/multica/cmd_project_progress_test.go b/server/cmd/multica/cmd_project_progress_test.go
new file mode 100644
index 0000000000..322707d128
--- /dev/null
+++ b/server/cmd/multica/cmd_project_progress_test.go
@@ -0,0 +1,67 @@
+package main
+
+import (
+ "encoding/json"
+ "reflect"
+ "testing"
+)
+
+const sampleProjectProgress = `{
+ "progress": {"unit": "issues", "scope": 11, "completed": 5, "started": 3, "unstarted": 3, "cancelled": 1, "percent": 45},
+ "by_assignee": [
+ {"assignee_type": "agent", "assignee_id": "xyz", "scope": 6, "completed": 3, "started": 2},
+ {"assignee_type": null, "assignee_id": null, "scope": 2, "completed": 0, "started": 0}
+ ],
+ "history": [
+ {"date": "2026-10-12", "scope": 6, "started": 0, "completed": 0},
+ {"date": "2026-11-09", "scope": 11, "started": 3, "completed": 5}
+ ],
+ "forecast": {"completion_date": "2026-12-13", "weekly_velocity": 1.25}
+}`
+
+func decodeSampleProgress(t *testing.T) map[string]any {
+ t.Helper()
+ var resp map[string]any
+ if err := json.Unmarshal([]byte(sampleProjectProgress), &resp); err != nil {
+ t.Fatal(err)
+ }
+ return resp
+}
+
+func TestFormatProjectProgress(t *testing.T) {
+ resp := decodeSampleProgress(t)
+ if got := formatProjectProgress(resp["progress"]); got != "5/11 (45%)" {
+ t.Fatalf("formatProjectProgress = %q", got)
+ }
+ if got := formatProjectProgress(nil); got != "" {
+ t.Fatalf("formatProjectProgress(nil) = %q, want empty for servers without progress", got)
+ }
+}
+
+func TestProjectProgressTables(t *testing.T) {
+ resp := decodeSampleProgress(t)
+
+ _, summary := projectProgressSummaryTable(resp)
+ want := [][]string{{"5/11 (45%)", "11", "5", "3", "3", "1", "2026-12-13 (1.25/week)"}}
+ if !reflect.DeepEqual(summary, want) {
+ t.Errorf("summary = %v, want %v", summary, want)
+ }
+
+ _, history := projectProgressHistoryTable(resp)
+ wantHistory := [][]string{{"2026-10-12", "6", "0", "0"}, {"2026-11-09", "11", "3", "5"}}
+ if !reflect.DeepEqual(history, wantHistory) {
+ t.Errorf("history = %v, want %v", history, wantHistory)
+ }
+
+ actors := actorDisplayLookup{state: &actorDisplayLookupState{
+ agents: map[string]string{"xyz": "CodeBot"},
+ membersLoaded: true,
+ agentsLoaded: true,
+ squadsLoaded: true,
+ }}
+ _, byAssignee := projectProgressAssigneeTable(resp, actors)
+ wantAssignee := [][]string{{"agent:CodeBot", "3/6 (50%)", "2"}, {"unassigned", "0/2 (0%)", "0"}}
+ if !reflect.DeepEqual(byAssignee, wantAssignee) {
+ t.Errorf("by assignee = %v, want %v", byAssignee, wantAssignee)
+ }
+}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index db4d80af36..79588da940 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -2437,6 +2437,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
r.Post("/", h.CreateProject)
r.Route("/{id}", func(r chi.Router) {
r.Get("/", h.GetProject)
+ r.Get("/progress", h.GetProjectProgress)
r.Put("/", h.UpdateProject)
r.Delete("/", h.DeleteProject)
r.With(handler.RequireHumanActor).Post("/join", h.JoinPrivateProject)
diff --git a/server/internal/handler/project.go b/server/internal/handler/project.go
index 54f0583fc9..d644072226 100644
--- a/server/internal/handler/project.go
+++ b/server/internal/handler/project.go
@@ -45,7 +45,10 @@ type ProjectResponse struct {
// latest activity on any of its issues.
LastActivityAt string `json:"last_activity_at"`
IssueCount int64 `json:"issue_count"`
- DoneCount int64 `json:"done_count"`
+ // DoneCount counts every terminal issue, cancelled included. Progress is
+ // the figure to show as completion. (MUL-8879)
+ DoneCount int64 `json:"done_count"`
+ Progress ProjectProgress `json:"progress"`
// ResourceCount is a breadcrumb pointing at the sub-collection at
// /api/projects/{id}/resources. Resources themselves stay out of this
// payload to keep parent metadata and child collections separate; clients
@@ -86,6 +89,7 @@ func projectToResponse(p db.Project) ProjectResponse {
LastActivityAt: timestampToString(p.UpdatedAt),
WorkflowID: uuidToPtr(p.WorkflowID),
Visibility: projectVisibilityOrDefault(p.Visibility),
+ Progress: newProjectProgress(0, 0, 0, 0),
ArchivedAt: timestampToPtr(p.ArchivedAt),
ArchivedByType: textToPtr(p.ArchivedByType),
@@ -102,41 +106,122 @@ func projectVisibilityOrDefault(v string) string {
return v
}
-func (h *Handler) fillProjectIssueStats(ctx context.Context, resp *ProjectResponse, project db.Project) {
- terminalStatusKeys := h.projectTerminalIssueStatusKeys(ctx, project.WorkspaceID)
- stats, err := h.Queries.GetProjectIssueStats(ctx, db.GetProjectIssueStatsParams{
- WorkspaceID: project.WorkspaceID,
- ProjectIds: []pgtype.UUID{project.ID},
- TerminalStatusKeys: terminalStatusKeys,
- })
- if err != nil || len(stats) == 0 {
- return
- }
- applyProjectIssueStats(resp, project.UpdatedAt, stats[0])
+// ProjectProgress is a project's completion, counted in issues. Cancelled
+// (closed-category) issues leave the scope instead of counting as done, and
+// started issues are reported but do not add to Percent. (MUL-8879)
+type ProjectProgress struct {
+ // Unit is what the counts measure; "issues" until estimates exist.
+ Unit string `json:"unit"`
+ Scope int64 `json:"scope"`
+ Completed int64 `json:"completed"`
+ Started int64 `json:"started"`
+ Unstarted int64 `json:"unstarted"`
+ Cancelled int64 `json:"cancelled"`
+ // Percent is Completed / Scope rounded down, so 100 means every issue in
+ // scope is done.
+ Percent int64 `json:"percent"`
+}
+
+func newProjectProgress(total, terminal, completed, started int64) ProjectProgress {
+ cancelled := terminal - completed
+ scope := total - cancelled
+ p := ProjectProgress{
+ Unit: "issues",
+ Scope: scope,
+ Completed: completed,
+ Started: started,
+ Unstarted: scope - completed - started,
+ Cancelled: cancelled,
+ }
+ if scope > 0 {
+ p.Percent = completed * 100 / scope
+ }
+ return p
}
-// applyProjectIssueStats fills the issue counts and moves LastActivityAt to
-// the latest issue activity when that is later than the project's own edit.
+// applyProjectIssueStats fills the issue counts and progress, and moves
+// LastActivityAt to the latest issue activity when that is later than the
+// project's own edit.
func applyProjectIssueStats(resp *ProjectResponse, projectUpdatedAt pgtype.Timestamptz, s db.GetProjectIssueStatsRow) {
resp.IssueCount = s.TotalCount
resp.DoneCount = s.DoneCount
+ resp.Progress = newProjectProgress(s.TotalCount, s.DoneCount, s.CompletedCount, s.StartedCount)
if s.LastIssueActivityAt.Valid &&
(!projectUpdatedAt.Valid || s.LastIssueActivityAt.Time.After(projectUpdatedAt.Time)) {
resp.LastActivityAt = timestampToString(s.LastIssueActivityAt)
}
}
-// projectTerminalIssueStatusKeys keeps project responses useful if the custom
-// status catalog cannot be read. Canonical terminal keys are less complete
-// than the workspace catalog, but they avoid rendering every project as 0/0.
-func (h *Handler) projectTerminalIssueStatusKeys(ctx context.Context, workspaceID pgtype.UUID) []string {
- keys, err := h.terminalIssueStatusKeys(ctx, workspaceID)
- if err == nil {
- return keys
- }
- slog.Warn("expand project terminal status categories failed; using canonical keys",
- "workspace_id", uuidToString(workspaceID), "error", err)
- return []string{issuestatus.Done, issuestatus.Cancelled}
+// projectStatusKeySets holds the status keys of each category project
+// progress counts, for indexed `status = ANY(...)` predicates.
+type projectStatusKeySets struct {
+ terminal []string
+ completed []string
+ started []string
+}
+
+// projectStatusKeySets keeps project responses useful if the custom status
+// catalog cannot be read: the built-in keys are less complete than the
+// workspace catalog, but they avoid rendering every project as 0/0.
+func (h *Handler) projectStatusKeySets(ctx context.Context, workspaceID pgtype.UUID) projectStatusKeySets {
+ custom, err := issuestatus.CustomKeyCategories(ctx, h.Queries, workspaceID)
+ if err != nil {
+ slog.Warn("read project status categories failed; using built-in keys",
+ "workspace_id", uuidToString(workspaceID), "error", err)
+ custom = nil
+ }
+ var sets projectStatusKeySets
+ add := func(key, category string) {
+ switch category {
+ case issuestatus.CategoryDone:
+ sets.completed = append(sets.completed, key)
+ sets.terminal = append(sets.terminal, key)
+ case issuestatus.CategoryClosed:
+ sets.terminal = append(sets.terminal, key)
+ case issuestatus.CategoryStarted:
+ sets.started = append(sets.started, key)
+ }
+ }
+ for _, key := range issuestatus.Canonical() {
+ category, _ := issuestatus.CategoryForBehavior(key)
+ add(key, category)
+ }
+ for key, category := range custom {
+ add(key, category)
+ }
+ return sets
+}
+
+// loadProjectIssueStatsMap returns issue stats keyed by project id. A failed
+// read leaves the map empty, so callers render zero counts rather than fail.
+func (h *Handler) loadProjectIssueStatsMap(ctx context.Context, workspaceID pgtype.UUID, projectIDs []pgtype.UUID) map[string]db.GetProjectIssueStatsRow {
+ out := make(map[string]db.GetProjectIssueStatsRow, len(projectIDs))
+ if len(projectIDs) == 0 {
+ return out
+ }
+ keys := h.projectStatusKeySets(ctx, workspaceID)
+ stats, err := h.Queries.GetProjectIssueStats(ctx, db.GetProjectIssueStatsParams{
+ WorkspaceID: workspaceID,
+ ProjectIds: projectIDs,
+ TerminalStatusKeys: keys.terminal,
+ CompletedStatusKeys: keys.completed,
+ StartedStatusKeys: keys.started,
+ })
+ if err != nil {
+ slog.Warn("load project issue stats failed",
+ "workspace_id", uuidToString(workspaceID), "error", err)
+ return out
+ }
+ for _, s := range stats {
+ out[uuidToString(s.ProjectID)] = s
+ }
+ return out
+}
+
+func (h *Handler) fillProjectIssueStats(ctx context.Context, resp *ProjectResponse, project db.Project) {
+ if s, ok := h.loadProjectIssueStatsMap(ctx, project.WorkspaceID, []pgtype.UUID{project.ID})[uuidToString(project.ID)]; ok {
+ applyProjectIssueStats(resp, project.UpdatedAt, s)
+ }
}
func (h *Handler) loadProjectResourceCount(ctx context.Context, projectID pgtype.UUID) int64 {
@@ -231,24 +316,14 @@ func (h *Handler) ListProjects(w http.ResponseWriter, r *http.Request) {
projects = visible
// Batch-fetch issue stats and resource counts for all projects
- statsMap := make(map[string]db.GetProjectIssueStatsRow)
+ statsMap := map[string]db.GetProjectIssueStatsRow{}
resourceCountMap := make(map[string]int64)
if len(projects) > 0 {
projectIDs := make([]pgtype.UUID, len(projects))
for i, p := range projects {
projectIDs[i] = p.ID
}
- terminalStatusKeys := h.projectTerminalIssueStatusKeys(r.Context(), wsUUID)
- stats, statsErr := h.Queries.GetProjectIssueStats(r.Context(), db.GetProjectIssueStatsParams{
- WorkspaceID: wsUUID,
- ProjectIds: projectIDs,
- TerminalStatusKeys: terminalStatusKeys,
- })
- if statsErr == nil {
- for _, s := range stats {
- statsMap[uuidToString(s.ProjectID)] = s
- }
- }
+ statsMap = h.loadProjectIssueStatsMap(r.Context(), wsUUID, projectIDs)
counts, err := h.Queries.GetProjectResourceCounts(r.Context(), projectIDs)
if err == nil {
for _, c := range counts {
@@ -1149,24 +1224,14 @@ func (h *Handler) SearchProjects(w http.ResponseWriter, r *http.Request) {
}
// Batch-fetch issue stats and resource counts
- statsMap := make(map[string]db.GetProjectIssueStatsRow)
+ statsMap := map[string]db.GetProjectIssueStatsRow{}
resourceCountMap := make(map[string]int64)
if len(results) > 0 {
projectIDs := make([]pgtype.UUID, len(results))
for i, r := range results {
projectIDs[i] = r.project.ID
}
- terminalStatusKeys := h.projectTerminalIssueStatusKeys(ctx, wsUUID)
- stats, statsErr := h.Queries.GetProjectIssueStats(ctx, db.GetProjectIssueStatsParams{
- WorkspaceID: wsUUID,
- ProjectIds: projectIDs,
- TerminalStatusKeys: terminalStatusKeys,
- })
- if statsErr == nil {
- for _, s := range stats {
- statsMap[uuidToString(s.ProjectID)] = s
- }
- }
+ statsMap = h.loadProjectIssueStatsMap(ctx, wsUUID, projectIDs)
counts, err := h.Queries.GetProjectResourceCounts(ctx, projectIDs)
if err == nil {
for _, c := range counts {
diff --git a/server/internal/handler/project_issue_stats_test.go b/server/internal/handler/project_issue_stats_test.go
index 79a656c0d2..62c9fb797b 100644
--- a/server/internal/handler/project_issue_stats_test.go
+++ b/server/internal/handler/project_issue_stats_test.go
@@ -10,17 +10,43 @@ import (
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
-func TestProjectTerminalIssueStatusKeysFallsBackToCanonicalKeys(t *testing.T) {
+func TestProjectStatusKeySetsFallBackToBuiltInKeys(t *testing.T) {
h := *testHandler
h.Queries = db.New(failQueryDBTX{
DBTX: testPool,
- failOn: "SELECT key FROM issue_status",
+ failOn: "FROM issue_status",
err: errors.New("status catalog unavailable"),
})
- got := h.projectTerminalIssueStatusKeys(context.Background(), parseUUID(testWorkspaceID))
- want := []string{issuestatus.Done, issuestatus.Cancelled}
- if !slices.Equal(got, want) {
- t.Fatalf("project terminal keys = %v, want canonical fallback %v", got, want)
+ got := h.projectStatusKeySets(context.Background(), parseUUID(testWorkspaceID))
+ if want := []string{issuestatus.Done, issuestatus.Cancelled}; !slices.Equal(got.terminal, want) {
+ t.Fatalf("terminal keys = %v, want built-in fallback %v", got.terminal, want)
+ }
+ if want := []string{issuestatus.Done}; !slices.Equal(got.completed, want) {
+ t.Fatalf("completed keys = %v, want %v", got.completed, want)
+ }
+ if want := []string{issuestatus.InProgress, issuestatus.InReview, issuestatus.Blocked}; !slices.Equal(sortedCopy(got.started...), sortedCopy(want...)) {
+ t.Fatalf("started keys = %v, want %v", got.started, want)
+ }
+}
+
+func TestNewProjectProgressLeavesCancelledOutOfScope(t *testing.T) {
+ // 12 issues: 5 done, 1 cancelled, 3 started, 3 unstarted.
+ got := newProjectProgress(12, 6, 5, 3)
+ want := ProjectProgress{Unit: "issues", Scope: 11, Completed: 5, Started: 3, Unstarted: 3, Cancelled: 1, Percent: 45}
+ if got != want {
+ t.Fatalf("progress = %+v, want %+v", got, want)
+ }
+
+ if got := newProjectProgress(3, 1, 0, 0); got.Scope != 2 || got.Percent != 0 {
+ t.Fatalf("all-open progress = %+v", got)
+ }
+ // Every remaining issue cancelled: nothing in scope, and no division.
+ if got := newProjectProgress(2, 2, 0, 0); got.Scope != 0 || got.Percent != 0 || got.Cancelled != 2 {
+ t.Fatalf("all-cancelled progress = %+v", got)
+ }
+ // 199 of 200 rounds down, so 100 only means finished.
+ if got := newProjectProgress(200, 199, 199, 0); got.Percent != 99 {
+ t.Fatalf("percent = %d, want 99", got.Percent)
}
}
diff --git a/server/internal/handler/project_list.go b/server/internal/handler/project_list.go
index 23ce6f9b1a..3883396870 100644
--- a/server/internal/handler/project_list.go
+++ b/server/internal/handler/project_list.go
@@ -177,11 +177,13 @@ func (q projectListQuery) page(resp []ProjectResponse) []ProjectResponse {
return resp
}
+// projectProgress sorts by the same completed / scope ratio the list shows;
+// a project with nothing in scope sorts below every project that has work.
func projectProgress(p ProjectResponse) float64 {
- if p.IssueCount == 0 {
+ if p.Progress.Scope == 0 {
return -1
}
- return float64(p.DoneCount) / float64(p.IssueCount)
+ return float64(p.Progress.Completed) / float64(p.Progress.Scope)
}
func compareOptionalDays(a, b *string, desc bool) int {
diff --git a/server/internal/handler/project_list_test.go b/server/internal/handler/project_list_test.go
index 05ab4e6a43..8c5f4dbffe 100644
--- a/server/internal/handler/project_list_test.go
+++ b/server/internal/handler/project_list_test.go
@@ -95,6 +95,25 @@ func TestSortProjectResponsesKeepsUndatedLast(t *testing.T) {
}
}
+func TestSortProjectResponsesByProgressLeavesCancelledOut(t *testing.T) {
+ projects := []ProjectResponse{
+ // 5 cancelled + 5 todo shows 0/5; done_count counts the cancelled.
+ {ID: "cancelled-heavy", IssueCount: 10, DoneCount: 5, Progress: newProjectProgress(10, 5, 0, 0)},
+ {ID: "forty", IssueCount: 10, DoneCount: 4, Progress: newProjectProgress(10, 4, 4, 0)},
+ // Everything cancelled leaves nothing in scope.
+ {ID: "all-cancelled", IssueCount: 3, DoneCount: 3, Progress: newProjectProgress(3, 3, 0, 0)},
+ {ID: "empty"},
+ }
+ sortProjectResponses(projects, "progress", true)
+ got := make([]string, len(projects))
+ for i, p := range projects {
+ got[i] = p.ID
+ }
+ if want := []string{"forty", "cancelled-heavy", "all-cancelled", "empty"}; !slices.Equal(got[:2], want[:2]) {
+ t.Fatalf("desc = %v, want %v first", got, want[:2])
+ }
+}
+
func listProjectsForTest(t *testing.T, query string) (titles []string, total int, hasMore bool) {
t.Helper()
w := httptest.NewRecorder()
diff --git a/server/internal/handler/project_progress.go b/server/internal/handler/project_progress.go
new file mode 100644
index 0000000000..eec2b64d0a
--- /dev/null
+++ b/server/internal/handler/project_progress.go
@@ -0,0 +1,329 @@
+package handler
+
+import (
+ "encoding/json"
+ "math"
+ "net/http"
+ "sort"
+ "time"
+
+ "github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+const (
+ // projectProgressMaxWeeks bounds the history (and the activity rows read
+ // to build it) for long-running projects.
+ projectProgressMaxWeeks = 52
+ // projectProgressVelocityDays is the trailing window the forecast's
+ // weekly completion rate is measured over.
+ projectProgressVelocityDays = 28
+ // projectProgressMaxForecastDays drops forecasts too far out to mean
+ // anything, such as one issue finished in a month against hundreds open.
+ projectProgressMaxForecastDays = 3 * 365
+)
+
+type ProjectProgressAssignee struct {
+ // AssigneeType and AssigneeID are null for unassigned issues.
+ AssigneeType *string `json:"assignee_type"`
+ AssigneeID *string `json:"assignee_id"`
+ Scope int64 `json:"scope"`
+ Completed int64 `json:"completed"`
+ Started int64 `json:"started"`
+}
+
+// ProjectProgressPoint is the project's progress at the end of Date (UTC).
+type ProjectProgressPoint struct {
+ Date string `json:"date"`
+ Scope int64 `json:"scope"`
+ Started int64 `json:"started"`
+ Completed int64 `json:"completed"`
+}
+
+type ProjectProgressForecast struct {
+ // CompletionDate is the calendar day ("YYYY-MM-DD") the remaining scope
+ // is done at the trailing four-week completion rate.
+ CompletionDate string `json:"completion_date"`
+ WeeklyVelocity float64 `json:"weekly_velocity"`
+}
+
+type ProjectProgressResponse struct {
+ Progress ProjectProgress `json:"progress"`
+ ByAssignee []ProjectProgressAssignee `json:"by_assignee"`
+ // History has one point a week from the project's start (at most a year
+ // back) and a final point for today. Scope counts the issues in the
+ // project now, from when each was created: moves between projects are
+ // not recorded, so an issue moved in later counts from its creation.
+ History []ProjectProgressPoint `json:"history"`
+ // Forecast is null until there is a week of history and a positive
+ // completion rate, and once nothing in scope is left.
+ Forecast *ProjectProgressForecast `json:"forecast"`
+}
+
+type progressStatusChange struct {
+ at time.Time
+ from string
+}
+
+type progressIssue struct {
+ status string
+ assigneeType string
+ assigneeID string
+ createdAt time.Time
+ // changes are the issue's status changes after the history window
+ // opens, oldest first.
+ changes []progressStatusChange
+}
+
+// statusAt is the issue's status at t: the "from" of its first change after
+// t, or its current status when nothing changed since.
+func (i progressIssue) statusAt(t time.Time) string {
+ idx := sort.Search(len(i.changes), func(k int) bool { return i.changes[k].at.After(t) })
+ if idx < len(i.changes) && i.changes[idx].from != "" {
+ return i.changes[idx].from
+ }
+ return i.status
+}
+
+func utcDay(t time.Time) time.Time {
+ y, m, d := t.UTC().Date()
+ return time.Date(y, m, d, 0, 0, 0, 0, time.UTC)
+}
+
+// projectProgressWindowStart is the first day of the history: the project's
+// start, or a year before today for an older project.
+func projectProgressWindowStart(start, now time.Time) time.Time {
+ today := utcDay(now)
+ day := utcDay(start)
+ if day.After(today) {
+ return today
+ }
+ if earliest := today.AddDate(0, 0, -7*projectProgressMaxWeeks); day.Before(earliest) {
+ return earliest
+ }
+ return day
+}
+
+func buildProjectProgressHistory(issues []progressIssue, categoryOf func(string) string, windowStart, now time.Time) []ProjectProgressPoint {
+ today := utcDay(now)
+ var days []time.Time
+ for d := utcDay(windowStart); d.Before(today); d = d.AddDate(0, 0, 7) {
+ days = append(days, d)
+ }
+ days = append(days, today)
+
+ points := make([]ProjectProgressPoint, len(days))
+ for i, d := range days {
+ at := d.AddDate(0, 0, 1)
+ if at.After(now) {
+ at = now
+ }
+ p := ProjectProgressPoint{Date: d.Format("2006-01-02")}
+ for _, issue := range issues {
+ if issue.createdAt.After(at) {
+ continue
+ }
+ switch categoryOf(issue.statusAt(at)) {
+ case issuestatus.CategoryClosed:
+ continue
+ case issuestatus.CategoryDone:
+ p.Completed++
+ case issuestatus.CategoryStarted:
+ p.Started++
+ }
+ p.Scope++
+ }
+ points[i] = p
+ }
+ return points
+}
+
+func forecastProjectCompletion(history []ProjectProgressPoint, now time.Time) *ProjectProgressForecast {
+ if len(history) < 2 {
+ return nil
+ }
+ today := utcDay(now)
+ last := history[len(history)-1]
+ remaining := last.Scope - last.Completed
+ if remaining <= 0 {
+ return nil
+ }
+ base := history[0]
+ cutoff := today.AddDate(0, 0, -projectProgressVelocityDays)
+ for _, p := range history[:len(history)-1] {
+ if d, err := time.Parse("2006-01-02", p.Date); err == nil && !d.After(cutoff) {
+ base = p
+ }
+ }
+ baseDay, err := time.Parse("2006-01-02", base.Date)
+ if err != nil {
+ return nil
+ }
+ days := today.Sub(baseDay).Hours() / 24
+ if days < 7 {
+ return nil
+ }
+ velocity := float64(last.Completed-base.Completed) / (days / 7)
+ if velocity <= 0 {
+ return nil
+ }
+ ahead := int(math.Ceil(float64(remaining) / velocity * 7))
+ if ahead > projectProgressMaxForecastDays {
+ return nil
+ }
+ return &ProjectProgressForecast{
+ CompletionDate: today.AddDate(0, 0, ahead).Format("2006-01-02"),
+ WeeklyVelocity: math.Round(velocity*100) / 100,
+ }
+}
+
+func summarizeProjectProgress(issues []progressIssue, categoryOf func(string) string) (ProjectProgress, []ProjectProgressAssignee) {
+ var total, terminal, completed, started int64
+ type key struct{ typ, id string }
+ byAssignee := map[key]*ProjectProgressAssignee{}
+ var order []key
+ for _, issue := range issues {
+ category := categoryOf(issue.status)
+ total++
+ if category == issuestatus.CategoryClosed {
+ terminal++
+ continue
+ }
+ k := key{issue.assigneeType, issue.assigneeID}
+ row, ok := byAssignee[k]
+ if !ok {
+ row = &ProjectProgressAssignee{}
+ if k.typ != "" && k.id != "" {
+ typ, id := k.typ, k.id
+ row.AssigneeType, row.AssigneeID = &typ, &id
+ }
+ byAssignee[k] = row
+ order = append(order, k)
+ }
+ row.Scope++
+ switch category {
+ case issuestatus.CategoryDone:
+ terminal++
+ completed++
+ row.Completed++
+ case issuestatus.CategoryStarted:
+ started++
+ row.Started++
+ }
+ }
+ rows := make([]ProjectProgressAssignee, 0, len(order))
+ for _, k := range order {
+ rows = append(rows, *byAssignee[k])
+ }
+ // Largest share first; unassigned last; ties in a stable order.
+ sort.SliceStable(rows, func(a, b int) bool {
+ ua, ub := rows[a].AssigneeID == nil, rows[b].AssigneeID == nil
+ if ua != ub {
+ return ub
+ }
+ if rows[a].Scope != rows[b].Scope {
+ return rows[a].Scope > rows[b].Scope
+ }
+ if ua {
+ return false
+ }
+ return *rows[a].AssigneeType+*rows[a].AssigneeID < *rows[b].AssigneeType+*rows[b].AssigneeID
+ })
+ return newProjectProgress(total, terminal, completed, started), rows
+}
+
+// GetProjectProgress returns a project's progress with its breakdown by
+// assignee, weekly history and forecast completion date. (MUL-8879)
+func (h *Handler) GetProjectProgress(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ workspaceID := h.resolveWorkspaceID(r)
+ idUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "id"), "project id")
+ if !ok {
+ return
+ }
+ wsUUID, ok := parseUUIDOrBadRequest(w, workspaceID, "workspace id")
+ if !ok {
+ return
+ }
+ project, err := h.Queries.GetProjectInWorkspace(ctx, db.GetProjectInWorkspaceParams{
+ ID: idUUID, WorkspaceID: wsUUID,
+ })
+ if err != nil {
+ writeError(w, http.StatusNotFound, "project not found")
+ return
+ }
+ if !h.requireProjectVisible(w, r, workspaceID, project.ID, http.StatusNotFound, "project not found") {
+ return
+ }
+
+ rows, err := h.Queries.ListProjectProgressIssues(ctx, db.ListProjectProgressIssuesParams{
+ WorkspaceID: wsUUID,
+ ProjectID: project.ID,
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load project progress")
+ return
+ }
+
+ now := time.Now().UTC()
+ start := project.CreatedAt.Time
+ if project.StartDate.Valid && project.StartDate.Time.Before(start) {
+ start = project.StartDate.Time
+ }
+ windowStart := projectProgressWindowStart(start, now)
+
+ issues := make([]progressIssue, len(rows))
+ index := make(map[string]int, len(rows))
+ ids := make([]pgtype.UUID, len(rows))
+ for i, row := range rows {
+ issues[i] = progressIssue{
+ status: row.Status,
+ assigneeType: row.AssigneeType.String,
+ createdAt: row.CreatedAt.Time,
+ }
+ if row.AssigneeType.Valid && row.AssigneeID.Valid {
+ issues[i].assigneeID = uuidToString(row.AssigneeID)
+ } else {
+ issues[i].assigneeType = ""
+ }
+ ids[i] = row.ID
+ index[uuidToString(row.ID)] = i
+ }
+
+ if len(ids) > 0 {
+ changes, err := h.Queries.ListIssueStatusChangesSince(ctx, db.ListIssueStatusChangesSinceParams{
+ WorkspaceID: wsUUID,
+ IssueIds: ids,
+ Since: pgtype.Timestamptz{Time: windowStart, Valid: true},
+ })
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load project progress")
+ return
+ }
+ for _, c := range changes {
+ i, ok := index[uuidToString(c.IssueID)]
+ if !ok {
+ continue
+ }
+ var details struct {
+ From string `json:"from"`
+ }
+ _ = json.Unmarshal(c.Details, &details)
+ issues[i].changes = append(issues[i].changes, progressStatusChange{at: c.CreatedAt.Time, from: details.From})
+ }
+ }
+
+ resolver := issuestatus.NewResolver(wsUUID)
+ categoryOf := func(status string) string { return resolver.Category(ctx, h.Queries, status) }
+
+ progress, byAssignee := summarizeProjectProgress(issues, categoryOf)
+ history := buildProjectProgressHistory(issues, categoryOf, windowStart, now)
+ writeJSON(w, http.StatusOK, ProjectProgressResponse{
+ Progress: progress,
+ ByAssignee: byAssignee,
+ History: history,
+ Forecast: forecastProjectCompletion(history, now),
+ })
+}
diff --git a/server/internal/handler/project_progress_test.go b/server/internal/handler/project_progress_test.go
new file mode 100644
index 0000000000..2fddc774d4
--- /dev/null
+++ b/server/internal/handler/project_progress_test.go
@@ -0,0 +1,229 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/issuestatus"
+)
+
+func builtInCategory(status string) string {
+ category, _ := issuestatus.CategoryForBehavior(status)
+ return category
+}
+
+func day(s string) time.Time {
+ t, err := time.Parse("2006-01-02", s)
+ if err != nil {
+ panic(err)
+ }
+ return t
+}
+
+func TestBuildProjectProgressHistoryReplaysStatusChanges(t *testing.T) {
+ now := day("2026-11-09").Add(15 * time.Hour)
+ issues := []progressIssue{
+ // Done on Oct 20, after starting on Oct 14.
+ {status: "done", createdAt: day("2026-10-12"), changes: []progressStatusChange{
+ {at: day("2026-10-14").Add(time.Hour), from: "todo"},
+ {at: day("2026-10-20").Add(time.Hour), from: "in_progress"},
+ }},
+ // Created on Oct 30, still open.
+ {status: "todo", createdAt: day("2026-10-30")},
+ // Cancelled on Nov 3: in scope before, out of scope after.
+ {status: "cancelled", createdAt: day("2026-10-12"), changes: []progressStatusChange{
+ {at: day("2026-11-03").Add(time.Hour), from: "backlog"},
+ }},
+ }
+
+ got := buildProjectProgressHistory(issues, builtInCategory, day("2026-10-12"), now)
+ want := []ProjectProgressPoint{
+ {Date: "2026-10-12", Scope: 2, Started: 0, Completed: 0},
+ {Date: "2026-10-19", Scope: 2, Started: 1, Completed: 0},
+ {Date: "2026-10-26", Scope: 2, Started: 0, Completed: 1},
+ {Date: "2026-11-02", Scope: 3, Started: 0, Completed: 1},
+ {Date: "2026-11-09", Scope: 2, Started: 0, Completed: 1},
+ }
+ if len(got) != len(want) {
+ t.Fatalf("history = %+v, want %+v", got, want)
+ }
+ for i := range want {
+ if got[i] != want[i] {
+ t.Errorf("point %d = %+v, want %+v", i, got[i], want[i])
+ }
+ }
+}
+
+func TestProjectProgressWindowStartCapsAtAYear(t *testing.T) {
+ now := day("2026-11-09")
+ if got := projectProgressWindowStart(day("2020-01-01"), now); !got.Equal(now.AddDate(0, 0, -7*projectProgressMaxWeeks)) {
+ t.Fatalf("old project window = %s", got)
+ }
+ if got := projectProgressWindowStart(day("2027-01-01"), now); !got.Equal(now) {
+ t.Fatalf("future start window = %s, want today", got)
+ }
+ if got := projectProgressWindowStart(day("2026-10-12").Add(9*time.Hour), now); !got.Equal(day("2026-10-12")) {
+ t.Fatalf("window = %s, want start day", got)
+ }
+}
+
+func TestForecastProjectCompletion(t *testing.T) {
+ now := day("2026-11-09").Add(10 * time.Hour)
+ history := []ProjectProgressPoint{
+ {Date: "2026-10-12", Scope: 6, Completed: 0},
+ {Date: "2026-10-19", Scope: 8, Completed: 1},
+ {Date: "2026-10-26", Scope: 10, Completed: 3},
+ {Date: "2026-11-02", Scope: 12, Completed: 4},
+ {Date: "2026-11-09", Scope: 11, Completed: 5},
+ }
+ // 5 completed over the 4 weeks since Oct 12: 1.25 a week, 6 left, 34 days.
+ got := forecastProjectCompletion(history, now)
+ if got == nil || got.CompletionDate != "2026-12-13" || got.WeeklyVelocity != 1.25 {
+ t.Fatalf("forecast = %+v, want 2026-12-13 at 1.25/week", got)
+ }
+
+ // A project a week old measures from its first point: 1 a week, 6 left.
+ if f := forecastProjectCompletion(history[3:], now); f == nil || f.CompletionDate != "2026-12-21" {
+ t.Fatalf("one-week forecast = %+v, want 2026-12-21", f)
+ }
+ young := []ProjectProgressPoint{{Date: "2026-11-05", Scope: 3}, {Date: "2026-11-09", Scope: 3, Completed: 1}}
+ if f := forecastProjectCompletion(young, now); f != nil {
+ t.Fatalf("under a week of history forecast = %+v, want nil", f)
+ }
+ if f := forecastProjectCompletion([]ProjectProgressPoint{{Date: "2026-11-09", Scope: 3}}, now); f != nil {
+ t.Fatalf("single point forecast = %+v, want nil", f)
+ }
+ flat := []ProjectProgressPoint{{Date: "2026-10-12", Scope: 3, Completed: 1}, {Date: "2026-11-09", Scope: 3, Completed: 1}}
+ if f := forecastProjectCompletion(flat, now); f != nil {
+ t.Fatalf("no velocity forecast = %+v, want nil", f)
+ }
+ done := []ProjectProgressPoint{{Date: "2026-10-12", Scope: 3}, {Date: "2026-11-09", Scope: 3, Completed: 3}}
+ if f := forecastProjectCompletion(done, now); f != nil {
+ t.Fatalf("finished project forecast = %+v, want nil", f)
+ }
+}
+
+func TestSummarizeProjectProgressGroupsByAssignee(t *testing.T) {
+ issues := []progressIssue{
+ {status: "done", assigneeType: "agent", assigneeID: "a1"},
+ {status: "in_progress", assigneeType: "agent", assigneeID: "a1"},
+ {status: "done", assigneeType: "member", assigneeID: "m1"},
+ {status: "todo"},
+ {status: "cancelled", assigneeType: "member", assigneeID: "m1"},
+ }
+ progress, rows := summarizeProjectProgress(issues, builtInCategory)
+ if want := (ProjectProgress{Unit: "issues", Scope: 4, Completed: 2, Started: 1, Unstarted: 1, Cancelled: 1, Percent: 50}); progress != want {
+ t.Fatalf("progress = %+v, want %+v", progress, want)
+ }
+ if len(rows) != 3 {
+ t.Fatalf("rows = %+v", rows)
+ }
+ if rows[0].AssigneeID == nil || *rows[0].AssigneeID != "a1" || rows[0].Scope != 2 || rows[0].Completed != 1 || rows[0].Started != 1 {
+ t.Errorf("first row = %+v, want agent a1 1/2 with 1 started", rows[0])
+ }
+ if rows[1].AssigneeID == nil || *rows[1].AssigneeID != "m1" || rows[1].Scope != 1 {
+ t.Errorf("second row = %+v, want member m1 without the cancelled issue", rows[1])
+ }
+ if rows[2].AssigneeID != nil || rows[2].AssigneeType != nil || rows[2].Scope != 1 {
+ t.Errorf("last row = %+v, want unassigned", rows[2])
+ }
+}
+
+func TestGetProjectProgressEndpoint(t *testing.T) {
+ ctx := context.Background()
+ w := httptest.NewRecorder()
+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{"title": "Progress endpoint"})
+ testHandler.CreateProject(w, req)
+ if w.Code != http.StatusCreated {
+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())
+ }
+ var project ProjectResponse
+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {
+ t.Fatalf("decode project: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(ctx, `DELETE FROM issue WHERE project_id = $1`, project.ID)
+ testPool.Exec(ctx, `DELETE FROM project WHERE id = $1`, project.ID)
+ })
+
+ insert := func(status string) string {
+ t.Helper()
+ var number int
+ if err := testPool.QueryRow(ctx, `
+ UPDATE workspace
+ SET issue_counter = GREATEST(issue_counter, (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)) + 1
+ WHERE id = $1 RETURNING issue_counter
+ `, testWorkspaceID).Scan(&number); err != nil {
+ t.Fatalf("next issue number: %v", err)
+ }
+ var id string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, creator_type, creator_id, title, status, priority, project_id, number, position, assignee_type, assignee_id)
+ VALUES ($1, 'member', $2, 'progress '||$3, $3, 'none', $4, $5, 0, 'member', $2)
+ RETURNING id
+ `, testWorkspaceID, testUserID, status, project.ID, number).Scan(&id); err != nil {
+ t.Fatalf("insert issue: %v", err)
+ }
+ return id
+ }
+ doneID := insert("done")
+ insert("cancelled")
+ insert("in_progress")
+ insert("todo")
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO activity_log (workspace_id, issue_id, actor_type, actor_id, action, details)
+ VALUES ($1, $2, 'member', $3, 'status_changed', '{"from":"in_progress","to":"done"}'::jsonb)
+ `, testWorkspaceID, doneID, testUserID); err != nil {
+ t.Fatalf("insert activity: %v", err)
+ }
+
+ w = httptest.NewRecorder()
+ req = withURLParam(newRequest("GET", "/api/projects/"+project.ID+"/progress", nil), "id", project.ID)
+ testHandler.GetProjectProgress(w, req)
+ if w.Code != http.StatusOK {
+ t.Fatalf("GetProjectProgress: %d %s", w.Code, w.Body.String())
+ }
+ var resp ProjectProgressResponse
+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {
+ t.Fatalf("decode progress: %v", err)
+ }
+ if want := (ProjectProgress{Unit: "issues", Scope: 3, Completed: 1, Started: 1, Unstarted: 1, Cancelled: 1, Percent: 33}); resp.Progress != want {
+ t.Errorf("progress = %+v, want %+v", resp.Progress, want)
+ }
+ if len(resp.ByAssignee) != 1 || resp.ByAssignee[0].Scope != 3 || resp.ByAssignee[0].Completed != 1 {
+ t.Errorf("by_assignee = %+v, want one member row 1/3", resp.ByAssignee)
+ }
+ if len(resp.History) != 1 {
+ t.Fatalf("history = %+v, want today only for a new project", resp.History)
+ }
+ if last := resp.History[0]; last.Scope != 3 || last.Completed != 1 || last.Started != 1 {
+ t.Errorf("today's point = %+v, want it to match current progress", last)
+ }
+ if resp.Forecast != nil {
+ t.Errorf("forecast = %+v, want nil without a week of history", resp.Forecast)
+ }
+
+ // The project response carries the same summary, and keeps done_count's
+ // terminal meaning for older clients.
+ w = httptest.NewRecorder()
+ req = withURLParam(newRequest("GET", "/api/projects/"+project.ID, nil), "id", project.ID)
+ testHandler.GetProject(w, req)
+ var got ProjectResponse
+ if err := json.NewDecoder(w.Body).Decode(&got); err != nil {
+ t.Fatalf("decode project: %v", err)
+ }
+ if got.IssueCount != 4 || got.DoneCount != 2 || got.Progress != resp.Progress {
+ t.Errorf("GetProject = issue_count %d, done_count %d, progress %+v", got.IssueCount, got.DoneCount, got.Progress)
+ }
+
+ w = httptest.NewRecorder()
+ req = withURLParam(newRequest("GET", "/api/projects/00000000-0000-0000-0000-000000000000/progress", nil), "id", "00000000-0000-0000-0000-000000000000")
+ testHandler.GetProjectProgress(w, req)
+ if w.Code != http.StatusNotFound {
+ t.Errorf("missing project: %d, want 404", w.Code)
+ }
+}
diff --git a/server/internal/service/builtin_skills/multica-platform/references/projects.md b/server/internal/service/builtin_skills/multica-platform/references/projects.md
index 89af984298..02568e4228 100644
--- a/server/internal/service/builtin_skills/multica-platform/references/projects.md
+++ b/server/internal/service/builtin_skills/multica-platform/references/projects.md
@@ -26,6 +26,12 @@ multica project get <project-id> --output json
multica project resource list <project-id> --output json
```
+Project progress counts issues: `scope` leaves out cancelled issues, `completed`
+is the done category, and `started` issues are tracked separately without adding
+to `percent`. Read it from `progress` on the project, or from
+`multica project progress` for the weekly history, forecast and per-assignee
+breakdown.
+
Project resources are mutated through project resource commands/endpoints. Issue
comments do not create durable project resources.
@@ -48,6 +54,7 @@ Common resource types:
```bash
multica project list --output json
multica project get <project-id> --output json
+multica project progress <project-id> --output json # scope/completed/started, weekly history, forecast, by assignee
multica project create --title "<title>" --repo <github-url> --output json
multica project create --title "<title>" --start-date 2026-03-01 --due-date 2026-03-31 --output json
multica project update <project-id> --title "<title>" --output json
diff --git a/server/pkg/db/generated/project.sql.go b/server/pkg/db/generated/project.sql.go
index 0af376b1a2..c3e5596324 100644
--- a/server/pkg/db/generated/project.sql.go
+++ b/server/pkg/db/generated/project.sql.go
@@ -203,28 +203,43 @@ const getProjectIssueStats = `-- name: GetProjectIssueStats :many
SELECT project_id,
count(*)::bigint AS total_count,
count(*) FILTER (WHERE status = ANY($1::text[]))::bigint AS done_count,
+ count(*) FILTER (WHERE status = ANY($2::text[]))::bigint AS completed_count,
+ count(*) FILTER (WHERE status = ANY($3::text[]))::bigint AS started_count,
max(GREATEST(updated_at, last_activity_at))::timestamptz AS last_issue_activity_at
FROM issue
-WHERE workspace_id = $2::uuid
- AND project_id = ANY($3::uuid[])
+WHERE workspace_id = $4::uuid
+ AND project_id = ANY($5::uuid[])
GROUP BY project_id
`
type GetProjectIssueStatsParams struct {
- TerminalStatusKeys []string `json:"terminal_status_keys"`
- WorkspaceID pgtype.UUID `json:"workspace_id"`
- ProjectIds []pgtype.UUID `json:"project_ids"`
+ TerminalStatusKeys []string `json:"terminal_status_keys"`
+ CompletedStatusKeys []string `json:"completed_status_keys"`
+ StartedStatusKeys []string `json:"started_status_keys"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectIds []pgtype.UUID `json:"project_ids"`
}
type GetProjectIssueStatsRow struct {
ProjectID pgtype.UUID `json:"project_id"`
TotalCount int64 `json:"total_count"`
DoneCount int64 `json:"done_count"`
+ CompletedCount int64 `json:"completed_count"`
+ StartedCount int64 `json:"started_count"`
LastIssueActivityAt pgtype.Timestamptz `json:"last_issue_activity_at"`
}
+// done_count counts every terminal issue (done and closed categories) and
+// keeps that meaning for older clients; completed_count is the done category
+// alone, so cancelled = done_count - completed_count.
func (q *Queries) GetProjectIssueStats(ctx context.Context, arg GetProjectIssueStatsParams) ([]GetProjectIssueStatsRow, error) {
- rows, err := q.db.Query(ctx, getProjectIssueStats, arg.TerminalStatusKeys, arg.WorkspaceID, arg.ProjectIds)
+ rows, err := q.db.Query(ctx, getProjectIssueStats,
+ arg.TerminalStatusKeys,
+ arg.CompletedStatusKeys,
+ arg.StartedStatusKeys,
+ arg.WorkspaceID,
+ arg.ProjectIds,
+ )
if err != nil {
return nil, err
}
@@ -236,6 +251,8 @@ func (q *Queries) GetProjectIssueStats(ctx context.Context, arg GetProjectIssueS
&i.ProjectID,
&i.TotalCount,
&i.DoneCount,
+ &i.CompletedCount,
+ &i.StartedCount,
&i.LastIssueActivityAt,
); err != nil {
return nil, err
@@ -248,6 +265,94 @@ func (q *Queries) GetProjectIssueStats(ctx context.Context, arg GetProjectIssueS
return items, nil
}
+const listIssueStatusChangesSince = `-- name: ListIssueStatusChangesSince :many
+SELECT issue_id, details, created_at
+FROM activity_log
+WHERE workspace_id = $1::uuid
+ AND issue_id = ANY($2::uuid[])
+ AND action = 'status_changed'
+ AND created_at >= $3::timestamptz
+ORDER BY created_at, id
+`
+
+type ListIssueStatusChangesSinceParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IssueIds []pgtype.UUID `json:"issue_ids"`
+ Since pgtype.Timestamptz `json:"since"`
+}
+
+type ListIssueStatusChangesSinceRow struct {
+ IssueID pgtype.UUID `json:"issue_id"`
+ Details []byte `json:"details"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+func (q *Queries) ListIssueStatusChangesSince(ctx context.Context, arg ListIssueStatusChangesSinceParams) ([]ListIssueStatusChangesSinceRow, error) {
+ rows, err := q.db.Query(ctx, listIssueStatusChangesSince, arg.WorkspaceID, arg.IssueIds, arg.Since)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListIssueStatusChangesSinceRow{}
+ for rows.Next() {
+ var i ListIssueStatusChangesSinceRow
+ if err := rows.Scan(&i.IssueID, &i.Details, &i.CreatedAt); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listProjectProgressIssues = `-- name: ListProjectProgressIssues :many
+SELECT id, status, assignee_type, assignee_id, created_at
+FROM issue
+WHERE workspace_id = $1::uuid
+ AND project_id = $2::uuid
+`
+
+type ListProjectProgressIssuesParams struct {
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ProjectID pgtype.UUID `json:"project_id"`
+}
+
+type ListProjectProgressIssuesRow struct {
+ ID pgtype.UUID `json:"id"`
+ Status string `json:"status"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+func (q *Queries) ListProjectProgressIssues(ctx context.Context, arg ListProjectProgressIssuesParams) ([]ListProjectProgressIssuesRow, error) {
+ rows, err := q.db.Query(ctx, listProjectProgressIssues, arg.WorkspaceID, arg.ProjectID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListProjectProgressIssuesRow{}
+ for rows.Next() {
+ var i ListProjectProgressIssuesRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.Status,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listProjects = `-- name: ListProjects :many
SELECT id, workspace_id, title, description, icon, status, lead_type, lead_id, created_at, updated_at, priority, start_date, due_date, workflow_id, creator_type, creator_id, visibility, archived_at, archived_by_type, archived_by_id, folder_id FROM project
WHERE workspace_id = $1
diff --git a/server/pkg/db/queries/project.sql b/server/pkg/db/queries/project.sql
index 0a545f2e89..95bda5b217 100644
--- a/server/pkg/db/queries/project.sql
+++ b/server/pkg/db/queries/project.sql
@@ -77,11 +77,31 @@ SELECT count(*) FROM issue
WHERE project_id = $1;
-- name: GetProjectIssueStats :many
+-- done_count counts every terminal issue (done and closed categories) and
+-- keeps that meaning for older clients; completed_count is the done category
+-- alone, so cancelled = done_count - completed_count.
SELECT project_id,
count(*)::bigint AS total_count,
count(*) FILTER (WHERE status = ANY(sqlc.arg('terminal_status_keys')::text[]))::bigint AS done_count,
+ count(*) FILTER (WHERE status = ANY(sqlc.arg('completed_status_keys')::text[]))::bigint AS completed_count,
+ count(*) FILTER (WHERE status = ANY(sqlc.arg('started_status_keys')::text[]))::bigint AS started_count,
max(GREATEST(updated_at, last_activity_at))::timestamptz AS last_issue_activity_at
FROM issue
WHERE workspace_id = sqlc.arg('workspace_id')::uuid
AND project_id = ANY(sqlc.arg('project_ids')::uuid[])
GROUP BY project_id;
+
+-- name: ListProjectProgressIssues :many
+SELECT id, status, assignee_type, assignee_id, created_at
+FROM issue
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND project_id = sqlc.arg('project_id')::uuid;
+
+-- name: ListIssueStatusChangesSince :many
+SELECT issue_id, details, created_at
+FROM activity_log
+WHERE workspace_id = sqlc.arg('workspace_id')::uuid
+ AND issue_id = ANY(sqlc.arg('issue_ids')::uuid[])
+ AND action = 'status_changed'
+ AND created_at >= sqlc.arg('since')::timestamptz
+ORDER BY created_at, id;