修复 WUI Kanban 看板选择与隔离 (#594)
* fix: add explicit kanban board selection * fix: tighten kanban board counts and management
This commit is contained in:
@@ -98,6 +98,35 @@ export interface KanbanAssignee {
|
||||
counts: Record<string, number> | null
|
||||
}
|
||||
|
||||
export interface KanbanBoard {
|
||||
slug: string
|
||||
name: string
|
||||
description: string
|
||||
icon: string
|
||||
color: string
|
||||
created_at: number | null
|
||||
archived: boolean
|
||||
db_path?: string
|
||||
is_current?: boolean
|
||||
counts: Record<string, number>
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface KanbanBoardCreateRequest {
|
||||
slug: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string
|
||||
color?: string
|
||||
switchCurrent?: boolean
|
||||
}
|
||||
|
||||
export interface KanbanCapabilities {
|
||||
source: 'hermes-cli'
|
||||
supports: Record<string, boolean>
|
||||
missing: string[]
|
||||
}
|
||||
|
||||
export interface KanbanCreateRequest {
|
||||
title: string
|
||||
body?: string
|
||||
@@ -106,68 +135,115 @@ export interface KanbanCreateRequest {
|
||||
tenant?: string
|
||||
}
|
||||
|
||||
// ─── API functions ───────────────────────────────────────────────
|
||||
export interface KanbanBoardOptions {
|
||||
board?: string
|
||||
}
|
||||
|
||||
export async function listTasks(opts?: {
|
||||
export interface KanbanListOptions extends KanbanBoardOptions {
|
||||
status?: string
|
||||
assignee?: string
|
||||
tenant?: string
|
||||
}): Promise<KanbanTask[]> {
|
||||
}
|
||||
|
||||
function normalizedBoard(board?: string): string {
|
||||
const trimmed = board?.trim()
|
||||
return trimmed || 'default'
|
||||
}
|
||||
|
||||
function appendQuery(path: string, params: URLSearchParams): string {
|
||||
const qs = params.toString()
|
||||
return qs ? `${path}?${qs}` : path
|
||||
}
|
||||
|
||||
function boardParams(board?: string): URLSearchParams {
|
||||
const params = new URLSearchParams()
|
||||
params.set('board', normalizedBoard(board))
|
||||
return params
|
||||
}
|
||||
|
||||
// ─── API functions ───────────────────────────────────────────────
|
||||
|
||||
export async function listBoards(opts?: { includeArchived?: boolean }): Promise<KanbanBoard[]> {
|
||||
const params = new URLSearchParams()
|
||||
if (opts?.includeArchived) params.set('includeArchived', 'true')
|
||||
const res = await request<{ boards: KanbanBoard[] }>(appendQuery('/api/hermes/kanban/boards', params))
|
||||
return res.boards
|
||||
}
|
||||
|
||||
export async function createBoard(data: KanbanBoardCreateRequest): Promise<KanbanBoard> {
|
||||
const res = await request<{ board: KanbanBoard }>('/api/hermes/kanban/boards', {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
return res.board
|
||||
}
|
||||
|
||||
export async function archiveBoard(slug: string): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(`/api/hermes/kanban/boards/${encodeURIComponent(slug)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
export async function getCapabilities(): Promise<KanbanCapabilities> {
|
||||
const res = await request<{ capabilities: KanbanCapabilities }>('/api/hermes/kanban/capabilities')
|
||||
return res.capabilities
|
||||
}
|
||||
|
||||
export async function listTasks(opts?: KanbanListOptions): Promise<KanbanTask[]> {
|
||||
const params = boardParams(opts?.board)
|
||||
if (opts?.status) params.set('status', opts.status)
|
||||
if (opts?.assignee) params.set('assignee', opts.assignee)
|
||||
if (opts?.tenant) params.set('tenant', opts.tenant)
|
||||
const qs = params.toString()
|
||||
const res = await request<{ tasks: KanbanTask[] }>(`/api/hermes/kanban${qs ? `?${qs}` : ''}`)
|
||||
const res = await request<{ tasks: KanbanTask[] }>(appendQuery('/api/hermes/kanban', params))
|
||||
return res.tasks
|
||||
}
|
||||
|
||||
export async function getTask(id: string): Promise<KanbanTaskDetail> {
|
||||
return request<KanbanTaskDetail>(`/api/hermes/kanban/${id}`)
|
||||
export async function getTask(id: string, opts?: KanbanBoardOptions): Promise<KanbanTaskDetail> {
|
||||
return request<KanbanTaskDetail>(appendQuery(`/api/hermes/kanban/${encodeURIComponent(id)}`, boardParams(opts?.board)))
|
||||
}
|
||||
|
||||
export async function createTask(data: KanbanCreateRequest): Promise<KanbanTask> {
|
||||
const res = await request<{ task: KanbanTask }>('/api/hermes/kanban', {
|
||||
export async function createTask(data: KanbanCreateRequest, opts?: KanbanBoardOptions): Promise<KanbanTask> {
|
||||
const res = await request<{ task: KanbanTask }>(appendQuery('/api/hermes/kanban', boardParams(opts?.board)), {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
return res.task
|
||||
}
|
||||
|
||||
export async function completeTasks(taskIds: string[], summary?: string): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>('/api/hermes/kanban/complete', {
|
||||
export async function completeTasks(taskIds: string[], summary?: string, opts?: KanbanBoardOptions): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(appendQuery('/api/hermes/kanban/complete', boardParams(opts?.board)), {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ task_ids: taskIds, summary }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function blockTask(taskId: string, reason: string): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(`/api/hermes/kanban/${taskId}/block`, {
|
||||
export async function blockTask(taskId: string, reason: string, opts?: KanbanBoardOptions): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(appendQuery(`/api/hermes/kanban/${encodeURIComponent(taskId)}/block`, boardParams(opts?.board)), {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ reason }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function unblockTasks(taskIds: string[]): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>('/api/hermes/kanban/unblock', {
|
||||
export async function unblockTasks(taskIds: string[], opts?: KanbanBoardOptions): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(appendQuery('/api/hermes/kanban/unblock', boardParams(opts?.board)), {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ task_ids: taskIds }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function assignTask(taskId: string, profile: string): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(`/api/hermes/kanban/${taskId}/assign`, {
|
||||
export async function assignTask(taskId: string, profile: string, opts?: KanbanBoardOptions): Promise<{ ok: boolean }> {
|
||||
return request<{ ok: boolean }>(appendQuery(`/api/hermes/kanban/${encodeURIComponent(taskId)}/assign`, boardParams(opts?.board)), {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ profile }),
|
||||
})
|
||||
}
|
||||
|
||||
export async function getStats(): Promise<KanbanStats> {
|
||||
const res = await request<{ stats: KanbanStats }>('/api/hermes/kanban/stats')
|
||||
export async function getStats(opts?: KanbanBoardOptions): Promise<KanbanStats> {
|
||||
const res = await request<{ stats: KanbanStats }>(appendQuery('/api/hermes/kanban/stats', boardParams(opts?.board)))
|
||||
return res.stats
|
||||
}
|
||||
|
||||
export async function getAssignees(): Promise<KanbanAssignee[]> {
|
||||
const res = await request<{ assignees: KanbanAssignee[] }>('/api/hermes/kanban/assignees')
|
||||
export async function getAssignees(opts?: KanbanBoardOptions): Promise<KanbanAssignee[]> {
|
||||
const res = await request<{ assignees: KanbanAssignee[] }>(appendQuery('/api/hermes/kanban/assignees', boardParams(opts?.board)))
|
||||
return res.assignees
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ const priorityOptions = computed(() => [
|
||||
const assigneeOptions = computed(() => {
|
||||
return kanbanStore.assignees.map(a => {
|
||||
const total = Object.values(a.counts || {}).reduce((s, c) => s + c, 0)
|
||||
return { label: `${a.name} (${total})`, value: a.name }
|
||||
return { label: `${a.name} · ${t('kanban.stats.tasks')}: ${total}`, value: a.name }
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ async function searchTaskSessions() {
|
||||
sessionLoading.value = true
|
||||
try {
|
||||
const res = await request<{ results: any[] }>(
|
||||
`/api/hermes/kanban/search-sessions?task_id=${encodeURIComponent(detail.value.task.id)}&profile=${encodeURIComponent(profile)}`
|
||||
`/api/hermes/kanban/search-sessions?task_id=${encodeURIComponent(detail.value.task.id)}&profile=${encodeURIComponent(profile)}&board=${encodeURIComponent(kanbanStore.selectedBoard)}`
|
||||
)
|
||||
sessionResults.value = res.results
|
||||
} catch {
|
||||
@@ -103,22 +103,29 @@ const historySession = computed<Session | null>(() => {
|
||||
const assigneeOptions = computed(() => {
|
||||
return kanbanStore.assignees.map(a => {
|
||||
const total = Object.values(a.counts || {}).reduce((s, c) => s + c, 0)
|
||||
return { label: `${a.name} (${total})`, value: a.name }
|
||||
return { label: `${a.name} · ${t('kanban.stats.tasks')}: ${total}`, value: a.name }
|
||||
})
|
||||
})
|
||||
|
||||
watch(() => props.taskId, async (id) => {
|
||||
watch(() => [props.taskId, kanbanStore.selectedBoard] as const, async ([id, board]) => {
|
||||
if (!id) {
|
||||
detail.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
detail.value = await getTask(id)
|
||||
const nextDetail = await getTask(id, { board })
|
||||
if (props.taskId === id && kanbanStore.selectedBoard === board) {
|
||||
detail.value = nextDetail
|
||||
}
|
||||
} catch (err: any) {
|
||||
message.error(t('kanban.message.loadFailed'))
|
||||
if (props.taskId === id && kanbanStore.selectedBoard === board) {
|
||||
message.error(t('kanban.message.loadFailed'))
|
||||
}
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (props.taskId === id && kanbanStore.selectedBoard === board) {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
}, { immediate: true })
|
||||
|
||||
@@ -178,7 +185,7 @@ async function handleAssign() {
|
||||
message.success(t('kanban.message.taskAssigned'))
|
||||
assignProfile.value = null
|
||||
if (detail.value) {
|
||||
detail.value = await getTask(props.taskId)
|
||||
detail.value = await getTask(props.taskId, { board: kanbanStore.selectedBoard })
|
||||
}
|
||||
emit('updated')
|
||||
} catch (err: any) {
|
||||
|
||||
@@ -227,6 +227,16 @@ export default {
|
||||
noTasks: 'No tasks',
|
||||
allStatuses: 'All Statuses',
|
||||
allAssignees: 'All Assignees',
|
||||
board: {
|
||||
create: 'New Board',
|
||||
archive: 'Archive Board',
|
||||
slugPlaceholder: 'Board slug, e.g. project-a',
|
||||
namePlaceholder: 'Display name (optional)',
|
||||
slugRequired: 'Board slug is required',
|
||||
created: 'Board created',
|
||||
archived: 'Board archived',
|
||||
archiveConfirm: 'Archive the current board?',
|
||||
},
|
||||
columns: {
|
||||
triage: 'Triage',
|
||||
todo: 'To Do',
|
||||
@@ -300,6 +310,7 @@ export default {
|
||||
},
|
||||
stats: {
|
||||
total: 'Total',
|
||||
tasks: 'Tasks',
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -227,6 +227,16 @@ export default {
|
||||
noTasks: '暂无任务',
|
||||
allStatuses: '全部状态',
|
||||
allAssignees: '全部负责人',
|
||||
board: {
|
||||
create: '新建看板',
|
||||
archive: '归档看板',
|
||||
slugPlaceholder: '看板标识,例如 project-a',
|
||||
namePlaceholder: '显示名称(可选)',
|
||||
slugRequired: '看板标识不能为空',
|
||||
created: '看板已创建',
|
||||
archived: '看板已归档',
|
||||
archiveConfirm: '确定归档当前看板?',
|
||||
},
|
||||
columns: {
|
||||
triage: '待分拣',
|
||||
todo: '待办',
|
||||
@@ -300,6 +310,7 @@ export default {
|
||||
},
|
||||
stats: {
|
||||
total: '总计',
|
||||
tasks: '任务数',
|
||||
},
|
||||
},
|
||||
|
||||
|
||||
@@ -1,83 +1,259 @@
|
||||
import { defineStore } from 'pinia'
|
||||
import { ref } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import * as kanbanApi from '@/api/hermes/kanban'
|
||||
import type { KanbanTask, KanbanStats, KanbanAssignee } from '@/api/hermes/kanban'
|
||||
import type { KanbanTask, KanbanStats, KanbanAssignee, KanbanBoard, KanbanCapabilities } from '@/api/hermes/kanban'
|
||||
|
||||
export const KANBAN_SELECTED_BOARD_STORAGE_KEY = 'hermes.kanban.selectedBoard'
|
||||
export const DEFAULT_KANBAN_BOARD = 'default'
|
||||
|
||||
const BOARD_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
|
||||
|
||||
function safeStorageGet(key: string): string | null {
|
||||
if (typeof window === 'undefined') return null
|
||||
try {
|
||||
return window.localStorage.getItem(key)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function safeStorageSet(key: string, value: string) {
|
||||
if (typeof window === 'undefined') return
|
||||
try {
|
||||
window.localStorage.setItem(key, value)
|
||||
} catch {
|
||||
// Ignore storage failures; selectedBoard still remains explicit in-memory.
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeBoardSlug(board?: string | null): string {
|
||||
const trimmed = board?.trim()
|
||||
if (!trimmed) return DEFAULT_KANBAN_BOARD
|
||||
return BOARD_SLUG_RE.test(trimmed) ? trimmed : DEFAULT_KANBAN_BOARD
|
||||
}
|
||||
|
||||
export const useKanbanStore = defineStore('kanban', () => {
|
||||
const tasks = ref<KanbanTask[]>([])
|
||||
const stats = ref<KanbanStats | null>(null)
|
||||
const assignees = ref<KanbanAssignee[]>([])
|
||||
const boards = ref<KanbanBoard[]>([])
|
||||
const capabilities = ref<KanbanCapabilities | null>(null)
|
||||
const loading = ref(false)
|
||||
const boardsLoading = ref(false)
|
||||
const boardWarning = ref<string | null>(null)
|
||||
|
||||
const selectedBoard = ref(normalizeBoardSlug(safeStorageGet(KANBAN_SELECTED_BOARD_STORAGE_KEY)))
|
||||
|
||||
const filterStatus = ref<string | null>(null)
|
||||
const filterAssignee = ref<string | null>(null)
|
||||
|
||||
let boardGeneration = 0
|
||||
let boardsRequestSeq = 0
|
||||
let tasksRequestSeq = 0
|
||||
let statsRequestSeq = 0
|
||||
let assigneesRequestSeq = 0
|
||||
let loadingRequestSeq = 0
|
||||
|
||||
const activeBoards = computed(() => {
|
||||
const visible = boards.value.filter(board => !board.archived)
|
||||
if (!visible.some(board => board.slug === DEFAULT_KANBAN_BOARD)) {
|
||||
return [{
|
||||
slug: DEFAULT_KANBAN_BOARD,
|
||||
name: 'Default',
|
||||
description: '',
|
||||
icon: '',
|
||||
color: '',
|
||||
created_at: null,
|
||||
archived: false,
|
||||
counts: {},
|
||||
total: 0,
|
||||
}, ...visible]
|
||||
}
|
||||
return visible
|
||||
})
|
||||
|
||||
function boardExists(board: string): boolean {
|
||||
return activeBoards.value.some(item => item.slug === board)
|
||||
}
|
||||
|
||||
function resolveAvailableBoard(candidate?: string | null): string {
|
||||
const normalized = normalizeBoardSlug(candidate)
|
||||
if (boards.value.length > 0 && !boardExists(normalized)) return DEFAULT_KANBAN_BOARD
|
||||
return normalized
|
||||
}
|
||||
|
||||
function clearBoardScopedState() {
|
||||
tasks.value = []
|
||||
stats.value = null
|
||||
assignees.value = []
|
||||
}
|
||||
|
||||
function setSelectedBoard(board?: string | null): string {
|
||||
const resolved = resolveAvailableBoard(board)
|
||||
const changed = selectedBoard.value !== resolved
|
||||
selectedBoard.value = resolved
|
||||
safeStorageSet(KANBAN_SELECTED_BOARD_STORAGE_KEY, resolved)
|
||||
boardWarning.value = null
|
||||
if (changed) {
|
||||
clearBoardScopedState()
|
||||
boardGeneration++
|
||||
}
|
||||
return resolved
|
||||
}
|
||||
|
||||
function recoverSelectedBoard(candidate?: string | null): { board: string; recovered: boolean } {
|
||||
const normalized = normalizeBoardSlug(candidate)
|
||||
const resolved = resolveAvailableBoard(normalized)
|
||||
const recovered = resolved !== normalized
|
||||
setSelectedBoard(resolved)
|
||||
if (recovered) {
|
||||
boardWarning.value = `Board "${normalized}" is unavailable; fell back to "${resolved}".`
|
||||
}
|
||||
return { board: resolved, recovered }
|
||||
}
|
||||
|
||||
function nextRequestContext(nextSeq: () => number) {
|
||||
const seq = nextSeq()
|
||||
const generation = boardGeneration
|
||||
const board = selectedBoard.value
|
||||
return { seq, generation, board }
|
||||
}
|
||||
|
||||
function isCurrentRequest(seq: number, generation: number, board: string, currentSeq: number): boolean {
|
||||
return seq === currentSeq && generation === boardGeneration && board === selectedBoard.value
|
||||
}
|
||||
|
||||
async function fetchBoards(includeArchived = false) {
|
||||
const seq = ++boardsRequestSeq
|
||||
boardsLoading.value = true
|
||||
try {
|
||||
const nextBoards = await kanbanApi.listBoards({ includeArchived })
|
||||
if (seq !== boardsRequestSeq) return
|
||||
boards.value = nextBoards
|
||||
const resolved = resolveAvailableBoard(selectedBoard.value)
|
||||
if (resolved !== selectedBoard.value) recoverSelectedBoard(selectedBoard.value)
|
||||
} catch (err) {
|
||||
if (seq === boardsRequestSeq) console.error('Failed to fetch kanban boards:', err)
|
||||
} finally {
|
||||
if (seq === boardsRequestSeq) boardsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCapabilities() {
|
||||
try {
|
||||
capabilities.value = await kanbanApi.getCapabilities()
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch kanban capabilities:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function createBoard(data: { slug: string; name?: string; description?: string; icon?: string; color?: string; switchCurrent?: boolean }) {
|
||||
const board = await kanbanApi.createBoard(data)
|
||||
await fetchBoards()
|
||||
setSelectedBoard(board.slug)
|
||||
await refreshAll()
|
||||
return board
|
||||
}
|
||||
|
||||
async function archiveSelectedBoard() {
|
||||
const board = selectedBoard.value
|
||||
if (board === DEFAULT_KANBAN_BOARD) throw new Error('Cannot archive the default kanban board')
|
||||
await kanbanApi.archiveBoard(board)
|
||||
await fetchBoards()
|
||||
setSelectedBoard(DEFAULT_KANBAN_BOARD)
|
||||
await refreshAll()
|
||||
}
|
||||
|
||||
async function fetchTasks(silent = false) {
|
||||
const { seq, generation, board } = nextRequestContext(() => ++tasksRequestSeq)
|
||||
const loadingSeq = silent ? 0 : ++loadingRequestSeq
|
||||
if (!silent) loading.value = true
|
||||
try {
|
||||
tasks.value = await kanbanApi.listTasks({
|
||||
const nextTasks = await kanbanApi.listTasks({
|
||||
board,
|
||||
status: filterStatus.value || undefined,
|
||||
assignee: filterAssignee.value || undefined,
|
||||
})
|
||||
if (isCurrentRequest(seq, generation, board, tasksRequestSeq)) tasks.value = nextTasks
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch kanban tasks:', err)
|
||||
if (isCurrentRequest(seq, generation, board, tasksRequestSeq)) console.error('Failed to fetch kanban tasks:', err)
|
||||
} finally {
|
||||
if (!silent) loading.value = false
|
||||
if (!silent && loadingSeq === loadingRequestSeq) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchStats() {
|
||||
const { seq, generation, board } = nextRequestContext(() => ++statsRequestSeq)
|
||||
try {
|
||||
stats.value = await kanbanApi.getStats()
|
||||
const nextStats = await kanbanApi.getStats({ board })
|
||||
if (isCurrentRequest(seq, generation, board, statsRequestSeq)) stats.value = nextStats
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch kanban stats:', err)
|
||||
if (isCurrentRequest(seq, generation, board, statsRequestSeq)) console.error('Failed to fetch kanban stats:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchAssignees() {
|
||||
const { seq, generation, board } = nextRequestContext(() => ++assigneesRequestSeq)
|
||||
try {
|
||||
assignees.value = await kanbanApi.getAssignees()
|
||||
const nextAssignees = await kanbanApi.getAssignees({ board })
|
||||
if (isCurrentRequest(seq, generation, board, assigneesRequestSeq)) assignees.value = nextAssignees
|
||||
} catch (err) {
|
||||
console.error('Failed to fetch kanban assignees:', err)
|
||||
if (isCurrentRequest(seq, generation, board, assigneesRequestSeq)) console.error('Failed to fetch kanban assignees:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function createTask(data: { title: string; body?: string; assignee?: string; priority?: number; tenant?: string }) {
|
||||
const task = await kanbanApi.createTask(data)
|
||||
tasks.value.unshift(task)
|
||||
await fetchStats()
|
||||
const board = selectedBoard.value
|
||||
const task = await kanbanApi.createTask(data, { board })
|
||||
if (board === selectedBoard.value) {
|
||||
tasks.value.unshift(task)
|
||||
await Promise.all([fetchStats(), fetchBoards()])
|
||||
}
|
||||
return task
|
||||
}
|
||||
|
||||
async function completeTasks(taskIds: string[], summary?: string) {
|
||||
await kanbanApi.completeTasks(taskIds, summary)
|
||||
for (const id of taskIds) {
|
||||
const task = tasks.value.find(t => t.id === id)
|
||||
if (task) task.status = 'done'
|
||||
const board = selectedBoard.value
|
||||
await kanbanApi.completeTasks(taskIds, summary, { board })
|
||||
if (board === selectedBoard.value) {
|
||||
for (const id of taskIds) {
|
||||
const task = tasks.value.find(t => t.id === id)
|
||||
if (task) task.status = 'done'
|
||||
}
|
||||
await Promise.all([fetchStats(), fetchBoards()])
|
||||
}
|
||||
await fetchStats()
|
||||
}
|
||||
|
||||
async function blockTask(taskId: string, reason: string) {
|
||||
await kanbanApi.blockTask(taskId, reason)
|
||||
const task = tasks.value.find(t => t.id === taskId)
|
||||
if (task) task.status = 'blocked'
|
||||
await fetchStats()
|
||||
const board = selectedBoard.value
|
||||
await kanbanApi.blockTask(taskId, reason, { board })
|
||||
if (board === selectedBoard.value) {
|
||||
const task = tasks.value.find(t => t.id === taskId)
|
||||
if (task) task.status = 'blocked'
|
||||
await Promise.all([fetchStats(), fetchBoards()])
|
||||
}
|
||||
}
|
||||
|
||||
async function unblockTasks(taskIds: string[]) {
|
||||
await kanbanApi.unblockTasks(taskIds)
|
||||
for (const id of taskIds) {
|
||||
const task = tasks.value.find(t => t.id === id)
|
||||
if (task) task.status = 'ready'
|
||||
const board = selectedBoard.value
|
||||
await kanbanApi.unblockTasks(taskIds, { board })
|
||||
if (board === selectedBoard.value) {
|
||||
for (const id of taskIds) {
|
||||
const task = tasks.value.find(t => t.id === id)
|
||||
if (task) task.status = 'ready'
|
||||
}
|
||||
await Promise.all([fetchStats(), fetchBoards()])
|
||||
}
|
||||
await fetchStats()
|
||||
}
|
||||
|
||||
async function assignTask(taskId: string, profile: string) {
|
||||
await kanbanApi.assignTask(taskId, profile)
|
||||
const task = tasks.value.find(t => t.id === taskId)
|
||||
if (task) task.assignee = profile
|
||||
const board = selectedBoard.value
|
||||
await kanbanApi.assignTask(taskId, profile, { board })
|
||||
if (board === selectedBoard.value) {
|
||||
const task = tasks.value.find(t => t.id === taskId)
|
||||
if (task) task.assignee = profile
|
||||
await Promise.all([fetchStats(), fetchAssignees()])
|
||||
}
|
||||
}
|
||||
|
||||
function setFilter(key: 'status' | 'assignee', value: string | null) {
|
||||
@@ -86,25 +262,39 @@ export const useKanbanStore = defineStore('kanban', () => {
|
||||
}
|
||||
|
||||
async function refreshAll() {
|
||||
await Promise.all([fetchTasks(), fetchStats(), fetchAssignees()])
|
||||
await Promise.all([fetchBoards(), fetchTasks(), fetchStats(), fetchAssignees()])
|
||||
}
|
||||
|
||||
return {
|
||||
tasks,
|
||||
stats,
|
||||
assignees,
|
||||
boards,
|
||||
capabilities,
|
||||
activeBoards,
|
||||
loading,
|
||||
boardsLoading,
|
||||
boardWarning,
|
||||
selectedBoard,
|
||||
filterStatus,
|
||||
filterAssignee,
|
||||
fetchBoards,
|
||||
fetchCapabilities,
|
||||
fetchTasks,
|
||||
fetchStats,
|
||||
fetchAssignees,
|
||||
createTask,
|
||||
createBoard,
|
||||
archiveSelectedBoard,
|
||||
completeTasks,
|
||||
blockTask,
|
||||
unblockTasks,
|
||||
assignTask,
|
||||
setFilter,
|
||||
setSelectedBoard,
|
||||
recoverSelectedBoard,
|
||||
resolveAvailableBoard,
|
||||
clearBoardScopedState,
|
||||
refreshAll,
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1,22 +1,77 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted, onUnmounted } from 'vue'
|
||||
import { NButton, NSelect, NSpin, NCollapse, NCollapseItem } from 'naive-ui'
|
||||
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
|
||||
import { NButton, NSelect, NSpin, NCollapse, NCollapseItem, NModal, NInput, useMessage } from 'naive-ui'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRoute, useRouter } from 'vue-router'
|
||||
import KanbanTaskCard from '@/components/hermes/kanban/KanbanTaskCard.vue'
|
||||
import KanbanTaskDrawer from '@/components/hermes/kanban/KanbanTaskDrawer.vue'
|
||||
import KanbanCreateForm from '@/components/hermes/kanban/KanbanCreateForm.vue'
|
||||
import { useKanbanStore } from '@/stores/hermes/kanban'
|
||||
import { DEFAULT_KANBAN_BOARD, useKanbanStore } from '@/stores/hermes/kanban'
|
||||
import type { KanbanTaskStatus } from '@/api/hermes/kanban'
|
||||
|
||||
const { t } = useI18n()
|
||||
const route = useRoute()
|
||||
const router = useRouter()
|
||||
const message = useMessage()
|
||||
const kanbanStore = useKanbanStore()
|
||||
|
||||
const showCreateForm = ref(false)
|
||||
const showCreateBoardForm = ref(false)
|
||||
const selectedTaskId = ref<string | null>(null)
|
||||
const newBoardSlug = ref('')
|
||||
const newBoardName = ref('')
|
||||
const boardActionLoading = ref(false)
|
||||
const refreshTimer = ref<ReturnType<typeof setInterval> | null>(null)
|
||||
const routeReady = ref(false)
|
||||
|
||||
const boardStatuses: KanbanTaskStatus[] = ['triage', 'todo', 'ready', 'running', 'blocked', 'done', 'archived']
|
||||
|
||||
function firstQueryString(value: unknown): string | null {
|
||||
if (Array.isArray(value)) return typeof value[0] === 'string' ? value[0] : null
|
||||
return typeof value === 'string' ? value : null
|
||||
}
|
||||
|
||||
function routeBoard(): string | null {
|
||||
return firstQueryString(route.query.board)
|
||||
}
|
||||
|
||||
async function replaceRouteBoard(board: string) {
|
||||
if (routeBoard() === board) return
|
||||
await router.replace({ query: { ...route.query, board } })
|
||||
}
|
||||
|
||||
async function applyBoardSelection(candidate: string | null, notify = true, forceRefresh = false) {
|
||||
const previousBoard = kanbanStore.selectedBoard
|
||||
const { board, recovered } = kanbanStore.recoverSelectedBoard(candidate || kanbanStore.selectedBoard || DEFAULT_KANBAN_BOARD)
|
||||
selectedTaskId.value = null
|
||||
showCreateForm.value = false
|
||||
showCreateBoardForm.value = false
|
||||
if (notify && recovered && kanbanStore.boardWarning) message.warning(kanbanStore.boardWarning)
|
||||
await replaceRouteBoard(board)
|
||||
if (forceRefresh || board !== previousBoard) {
|
||||
await kanbanStore.refreshAll()
|
||||
}
|
||||
}
|
||||
|
||||
function taskCountLabel(count: number): string {
|
||||
return `${t('kanban.stats.tasks')}: ${count}`
|
||||
}
|
||||
|
||||
const boardOptions = computed(() => kanbanStore.activeBoards.map(board => {
|
||||
const count = typeof board.total === 'number' ? board.total : 0
|
||||
return {
|
||||
label: `${t('kanban.title')}: ${board.icon ? `${board.icon} ` : ''}${board.name || board.slug} · ${taskCountLabel(count)}`,
|
||||
value: board.slug,
|
||||
}
|
||||
}))
|
||||
|
||||
const selectedBoardValue = computed({
|
||||
get: () => kanbanStore.selectedBoard,
|
||||
set: (value: string) => {
|
||||
void applyBoardSelection(value || DEFAULT_KANBAN_BOARD)
|
||||
},
|
||||
})
|
||||
|
||||
const tasksByStatus = computed(() => {
|
||||
const grouped: Record<string, typeof kanbanStore.tasks> = {}
|
||||
for (const status of boardStatuses) {
|
||||
@@ -36,7 +91,7 @@ const assigneeFilterOptions = computed(() => [
|
||||
{ label: t('kanban.allAssignees'), value: '' },
|
||||
...kanbanStore.assignees.map(a => {
|
||||
const total = Object.values(a.counts || {}).reduce((s, c) => s + c, 0)
|
||||
return { label: `${a.name} (${total})`, value: a.name }
|
||||
return { label: `${t('kanban.detail.assignee')}: ${a.name} · ${taskCountLabel(total)}`, value: a.name }
|
||||
}),
|
||||
])
|
||||
|
||||
@@ -50,11 +105,18 @@ const filterAssigneeValue = computed({
|
||||
set: (v: string) => kanbanStore.setFilter('assignee', v || null),
|
||||
})
|
||||
|
||||
watch(() => route.query.board, async () => {
|
||||
if (!routeReady.value) return
|
||||
await applyBoardSelection(routeBoard(), false)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await kanbanStore.refreshAll()
|
||||
await Promise.all([kanbanStore.fetchBoards(), kanbanStore.fetchCapabilities()])
|
||||
await applyBoardSelection(routeBoard(), true, true)
|
||||
routeReady.value = true
|
||||
refreshTimer.value = setInterval(() => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
void Promise.all([kanbanStore.fetchTasks(true), kanbanStore.fetchStats()])
|
||||
void Promise.all([kanbanStore.fetchBoards(), kanbanStore.fetchTasks(true), kanbanStore.fetchStats()])
|
||||
}
|
||||
}, 15000)
|
||||
})
|
||||
@@ -80,7 +142,46 @@ async function handleApplyFilter() {
|
||||
}
|
||||
|
||||
async function handleTaskCreated() {
|
||||
await Promise.all([kanbanStore.fetchTasks(), kanbanStore.fetchStats()])
|
||||
await Promise.all([kanbanStore.fetchTasks(), kanbanStore.fetchStats(), kanbanStore.fetchBoards()])
|
||||
}
|
||||
|
||||
async function handleCreateBoard() {
|
||||
const slug = newBoardSlug.value.trim()
|
||||
if (!slug) {
|
||||
message.warning(t('kanban.board.slugRequired'))
|
||||
return
|
||||
}
|
||||
boardActionLoading.value = true
|
||||
try {
|
||||
const board = await kanbanStore.createBoard({
|
||||
slug,
|
||||
name: newBoardName.value.trim() || undefined,
|
||||
})
|
||||
newBoardSlug.value = ''
|
||||
newBoardName.value = ''
|
||||
showCreateBoardForm.value = false
|
||||
await replaceRouteBoard(board.slug)
|
||||
message.success(t('kanban.board.created'))
|
||||
} catch (err: any) {
|
||||
message.error(err.message)
|
||||
} finally {
|
||||
boardActionLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function handleArchiveSelectedBoard() {
|
||||
if (kanbanStore.selectedBoard === DEFAULT_KANBAN_BOARD) return
|
||||
if (!window.confirm(t('kanban.board.archiveConfirm'))) return
|
||||
boardActionLoading.value = true
|
||||
try {
|
||||
await kanbanStore.archiveSelectedBoard()
|
||||
await replaceRouteBoard(DEFAULT_KANBAN_BOARD)
|
||||
message.success(t('kanban.board.archived'))
|
||||
} catch (err: any) {
|
||||
message.error(err.message)
|
||||
} finally {
|
||||
boardActionLoading.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -89,6 +190,25 @@ async function handleTaskCreated() {
|
||||
<header class="page-header">
|
||||
<h2 class="header-title">{{ t('kanban.title') }}</h2>
|
||||
<div class="header-actions">
|
||||
<NSelect
|
||||
v-model:value="selectedBoardValue"
|
||||
:options="boardOptions"
|
||||
:loading="kanbanStore.boardsLoading"
|
||||
size="small"
|
||||
style="width: 260px;"
|
||||
/>
|
||||
<NButton size="small" :loading="boardActionLoading" @click="showCreateBoardForm = true">
|
||||
{{ t('common.add') }}
|
||||
</NButton>
|
||||
<NButton
|
||||
size="small"
|
||||
secondary
|
||||
:disabled="kanbanStore.selectedBoard === DEFAULT_KANBAN_BOARD"
|
||||
:loading="boardActionLoading"
|
||||
@click="handleArchiveSelectedBoard"
|
||||
>
|
||||
{{ t('kanban.board.archive') }}
|
||||
</NButton>
|
||||
<NSelect
|
||||
v-model:value="filterStatusValue"
|
||||
:options="statusFilterOptions"
|
||||
@@ -157,6 +277,18 @@ async function handleTaskCreated() {
|
||||
@updated="handleDrawerUpdated"
|
||||
/>
|
||||
|
||||
<!-- Board management -->
|
||||
<NModal v-model:show="showCreateBoardForm" preset="dialog" :title="t('kanban.board.create')" style="width: 420px;">
|
||||
<div class="board-form">
|
||||
<NInput v-model:value="newBoardSlug" :placeholder="t('kanban.board.slugPlaceholder')" />
|
||||
<NInput v-model:value="newBoardName" :placeholder="t('kanban.board.namePlaceholder')" />
|
||||
</div>
|
||||
<template #action>
|
||||
<NButton @click="showCreateBoardForm = false">{{ t('common.cancel') }}</NButton>
|
||||
<NButton type="primary" :loading="boardActionLoading" @click="handleCreateBoard">{{ t('common.create') }}</NButton>
|
||||
</template>
|
||||
</NModal>
|
||||
|
||||
<!-- Create form -->
|
||||
<KanbanCreateForm
|
||||
v-if="showCreateForm"
|
||||
@@ -246,6 +378,12 @@ async function handleTaskCreated() {
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
.board-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
.page-header {
|
||||
padding: 16px 12px 16px 52px;
|
||||
@@ -258,9 +396,5 @@ async function handleTaskCreated() {
|
||||
flex-wrap: wrap;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.kanban-board {
|
||||
padding: 0 12px 12px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -14,10 +14,86 @@ function getLatestRunProfile(detail: { runs: Array<{ profile: string | null }> }
|
||||
return [...detail.runs].reverse().find(run => run.profile)?.profile || null
|
||||
}
|
||||
|
||||
function firstQueryValue(value: string | string[] | undefined): string | undefined {
|
||||
return Array.isArray(value) ? value[0] : value
|
||||
}
|
||||
|
||||
function requestBoard(ctx: Context): string | null {
|
||||
try {
|
||||
return kanbanCli.normalizeBoardSlug(firstQueryValue(ctx.query.board as string | string[] | undefined))
|
||||
} catch {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'invalid board slug' }
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function listBoards(ctx: Context) {
|
||||
const includeArchived = firstQueryValue(ctx.query.includeArchived as string | string[] | undefined) === 'true'
|
||||
try {
|
||||
const boards = await kanbanCli.listBoards({ includeArchived })
|
||||
ctx.body = { boards }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: err.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function createBoard(ctx: Context) {
|
||||
const { slug, name, description, icon, color, switchCurrent } = ctx.request.body as {
|
||||
slug?: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string
|
||||
color?: string
|
||||
switchCurrent?: boolean
|
||||
}
|
||||
if (!slug?.trim()) {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'slug is required' }
|
||||
return
|
||||
}
|
||||
try {
|
||||
const board = await kanbanCli.createBoard({ slug, name, description, icon, color, switchCurrent })
|
||||
ctx.body = { board }
|
||||
} catch (err: any) {
|
||||
ctx.status = err.message?.includes('Invalid kanban board slug') ? 400 : 500
|
||||
ctx.body = { error: err.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveBoard(ctx: Context) {
|
||||
const slug = ctx.params.slug
|
||||
if (!slug?.trim()) {
|
||||
ctx.status = 400
|
||||
ctx.body = { error: 'slug is required' }
|
||||
return
|
||||
}
|
||||
try {
|
||||
await kanbanCli.archiveBoard(slug)
|
||||
ctx.body = { ok: true }
|
||||
} catch (err: any) {
|
||||
ctx.status = err.message?.includes('default') || err.message?.includes('Invalid kanban board slug') ? 400 : 500
|
||||
ctx.body = { error: err.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function capabilities(ctx: Context) {
|
||||
try {
|
||||
const capabilities = await kanbanCli.getCapabilities()
|
||||
ctx.body = { capabilities }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
ctx.body = { error: err.message }
|
||||
}
|
||||
}
|
||||
|
||||
export async function list(ctx: Context) {
|
||||
const { status, assignee, tenant } = ctx.query as Record<string, string | undefined>
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
const tasks = await kanbanCli.listTasks({ status, assignee, tenant })
|
||||
const tasks = await kanbanCli.listTasks({ board, status, assignee, tenant })
|
||||
ctx.body = { tasks }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -26,8 +102,10 @@ export async function list(ctx: Context) {
|
||||
}
|
||||
|
||||
export async function get(ctx: Context) {
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
const detail = await kanbanCli.getTask(ctx.params.id)
|
||||
const detail = await kanbanCli.getTask(ctx.params.id, { board })
|
||||
if (!detail) {
|
||||
ctx.status = 404
|
||||
ctx.body = { error: 'Task not found' }
|
||||
@@ -97,8 +175,10 @@ export async function create(ctx: Context) {
|
||||
ctx.body = { error: 'title is required' }
|
||||
return
|
||||
}
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
const task = await kanbanCli.createTask(title, { body, assignee, priority, tenant })
|
||||
const task = await kanbanCli.createTask(title, { board, body, assignee, priority, tenant })
|
||||
ctx.body = { task }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -116,8 +196,10 @@ export async function complete(ctx: Context) {
|
||||
ctx.body = { error: 'task_ids is required' }
|
||||
return
|
||||
}
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
await kanbanCli.completeTasks(task_ids, summary)
|
||||
await kanbanCli.completeTasks(task_ids, summary, { board })
|
||||
ctx.body = { ok: true }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -132,8 +214,10 @@ export async function block(ctx: Context) {
|
||||
ctx.body = { error: 'reason is required' }
|
||||
return
|
||||
}
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
await kanbanCli.blockTask(ctx.params.id, reason)
|
||||
await kanbanCli.blockTask(ctx.params.id, reason, { board })
|
||||
ctx.body = { ok: true }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -148,8 +232,10 @@ export async function unblock(ctx: Context) {
|
||||
ctx.body = { error: 'task_ids is required' }
|
||||
return
|
||||
}
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
await kanbanCli.unblockTasks(task_ids)
|
||||
await kanbanCli.unblockTasks(task_ids, { board })
|
||||
ctx.body = { ok: true }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -164,8 +250,10 @@ export async function assign(ctx: Context) {
|
||||
ctx.body = { error: 'profile is required' }
|
||||
return
|
||||
}
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
await kanbanCli.assignTask(ctx.params.id, profile)
|
||||
await kanbanCli.assignTask(ctx.params.id, profile, { board })
|
||||
ctx.body = { ok: true }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -174,8 +262,10 @@ export async function assign(ctx: Context) {
|
||||
}
|
||||
|
||||
export async function stats(ctx: Context) {
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
const stats = await kanbanCli.getStats()
|
||||
const stats = await kanbanCli.getStats({ board })
|
||||
ctx.body = { stats }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
@@ -184,8 +274,10 @@ export async function stats(ctx: Context) {
|
||||
}
|
||||
|
||||
export async function assignees(ctx: Context) {
|
||||
const board = requestBoard(ctx)
|
||||
if (!board) return
|
||||
try {
|
||||
const assignees = await kanbanCli.getAssignees()
|
||||
const assignees = await kanbanCli.getAssignees({ board })
|
||||
ctx.body = { assignees }
|
||||
} catch (err: any) {
|
||||
ctx.status = 500
|
||||
|
||||
@@ -3,6 +3,10 @@ import * as ctrl from '../../controllers/hermes/kanban'
|
||||
|
||||
export const kanbanRoutes = new Router()
|
||||
|
||||
kanbanRoutes.get('/api/hermes/kanban/boards', ctrl.listBoards)
|
||||
kanbanRoutes.post('/api/hermes/kanban/boards', ctrl.createBoard)
|
||||
kanbanRoutes.delete('/api/hermes/kanban/boards/:slug', ctrl.archiveBoard)
|
||||
kanbanRoutes.get('/api/hermes/kanban/capabilities', ctrl.capabilities)
|
||||
kanbanRoutes.get('/api/hermes/kanban/stats', ctrl.stats)
|
||||
kanbanRoutes.get('/api/hermes/kanban/assignees', ctrl.assignees)
|
||||
kanbanRoutes.get('/api/hermes/kanban/artifact', ctrl.readArtifact)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { logger } from '../logger'
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const execOpts = { windowsHide: true }
|
||||
const BOARD_SLUG_RE = /^[a-z0-9][a-z0-9-]{0,62}$/
|
||||
|
||||
function resolveHermesBin(): string {
|
||||
const envBin = process.env.HERMES_BIN?.trim()
|
||||
@@ -14,6 +15,19 @@ function resolveHermesBin(): string {
|
||||
|
||||
const HERMES_BIN = resolveHermesBin()
|
||||
|
||||
export function normalizeBoardSlug(board?: string | null): string {
|
||||
const trimmed = board?.trim()
|
||||
if (!trimmed) return 'default'
|
||||
if (!BOARD_SLUG_RE.test(trimmed)) {
|
||||
throw new Error('Invalid kanban board slug')
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
function boardArgs(board?: string | null): string[] {
|
||||
return ['kanban', '--board', normalizeBoardSlug(board)]
|
||||
}
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────────
|
||||
|
||||
export type KanbanTaskStatus = 'triage' | 'todo' | 'ready' | 'running' | 'blocked' | 'done' | 'archived'
|
||||
@@ -84,14 +98,131 @@ export interface KanbanAssignee {
|
||||
counts: Record<string, number> | null
|
||||
}
|
||||
|
||||
export interface KanbanBoard {
|
||||
slug: string
|
||||
name: string
|
||||
description: string
|
||||
icon: string
|
||||
color: string
|
||||
created_at: number | null
|
||||
archived: boolean
|
||||
db_path?: string
|
||||
is_current?: boolean
|
||||
counts: Record<string, number>
|
||||
total: number
|
||||
}
|
||||
|
||||
export interface KanbanBoardCreateOptions {
|
||||
slug: string
|
||||
name?: string
|
||||
description?: string
|
||||
icon?: string
|
||||
color?: string
|
||||
switchCurrent?: boolean
|
||||
}
|
||||
|
||||
export interface KanbanCapabilities {
|
||||
source: 'hermes-cli'
|
||||
supports: Record<string, boolean>
|
||||
missing: string[]
|
||||
}
|
||||
|
||||
export interface KanbanBoardOptions {
|
||||
board?: string
|
||||
}
|
||||
|
||||
// ─── CLI wrappers ───────────────────────────────────────────────
|
||||
|
||||
export async function listBoards(opts?: { includeArchived?: boolean }): Promise<KanbanBoard[]> {
|
||||
const args = ['kanban', 'boards', 'list', '--json']
|
||||
if (opts?.includeArchived) args.push('--all')
|
||||
|
||||
try {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, args, {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
})
|
||||
return JSON.parse(stdout)
|
||||
} catch (err: any) {
|
||||
logger.error(err, 'Hermes CLI: kanban boards list failed')
|
||||
throw new Error(`Failed to list kanban boards: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
async function findBoard(slug: string, includeArchived = true): Promise<KanbanBoard | null> {
|
||||
const boards = await listBoards({ includeArchived })
|
||||
return boards.find(board => board.slug === slug) || null
|
||||
}
|
||||
|
||||
export async function createBoard(opts: KanbanBoardCreateOptions): Promise<KanbanBoard> {
|
||||
const slug = normalizeBoardSlug(opts.slug)
|
||||
const args = ['kanban', 'boards', 'create', slug]
|
||||
if (opts.name?.trim()) args.push('--name', opts.name.trim())
|
||||
if (opts.description?.trim()) args.push('--description', opts.description.trim())
|
||||
if (opts.icon?.trim()) args.push('--icon', opts.icon.trim())
|
||||
if (opts.color?.trim()) args.push('--color', opts.color.trim())
|
||||
if (opts.switchCurrent) args.push('--switch')
|
||||
|
||||
try {
|
||||
await execFileAsync(HERMES_BIN, args, {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
})
|
||||
const board = await findBoard(slug)
|
||||
if (!board) throw new Error('created board was not returned by boards list')
|
||||
return board
|
||||
} catch (err: any) {
|
||||
logger.error(err, 'Hermes CLI: kanban boards create failed')
|
||||
throw new Error(`Failed to create kanban board: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function archiveBoard(slugInput: string): Promise<void> {
|
||||
const slug = normalizeBoardSlug(slugInput)
|
||||
if (slug === 'default') throw new Error('Cannot archive the default kanban board')
|
||||
|
||||
try {
|
||||
await execFileAsync(HERMES_BIN, ['kanban', 'boards', 'rm', slug], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
})
|
||||
} catch (err: any) {
|
||||
logger.error(err, 'Hermes CLI: kanban boards archive failed')
|
||||
throw new Error(`Failed to archive kanban board: ${err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
export async function getCapabilities(): Promise<KanbanCapabilities> {
|
||||
const supports = {
|
||||
explicitBoard: true,
|
||||
boardsList: true,
|
||||
boardCreate: true,
|
||||
boardArchive: true,
|
||||
cliCurrentSwitch: true,
|
||||
taskCrudLite: true,
|
||||
commentsWrite: false,
|
||||
taskLog: false,
|
||||
dispatch: false,
|
||||
events: false,
|
||||
diagnostics: false,
|
||||
bulk: false,
|
||||
}
|
||||
const missing = Object.entries(supports)
|
||||
.filter(([, supported]) => !supported)
|
||||
.map(([name]) => name)
|
||||
return { source: 'hermes-cli', supports, missing }
|
||||
}
|
||||
|
||||
export async function listTasks(opts?: {
|
||||
board?: string
|
||||
status?: string
|
||||
assignee?: string
|
||||
tenant?: string
|
||||
}): Promise<KanbanTask[]> {
|
||||
const args = ['kanban', 'list', '--json']
|
||||
const args = [...boardArgs(opts?.board), 'list', '--json']
|
||||
if (opts?.status) args.push('--status', opts.status)
|
||||
if (opts?.assignee) args.push('--assignee', opts.assignee)
|
||||
if (opts?.tenant) args.push('--tenant', opts.tenant)
|
||||
@@ -109,9 +240,9 @@ export async function listTasks(opts?: {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getTask(taskId: string): Promise<KanbanTaskDetail | null> {
|
||||
export async function getTask(taskId: string, opts?: KanbanBoardOptions): Promise<KanbanTaskDetail | null> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, ['kanban', 'show', taskId, '--json'], {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'show', taskId, '--json'], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
@@ -127,13 +258,14 @@ export async function getTask(taskId: string): Promise<KanbanTaskDetail | null>
|
||||
export async function createTask(
|
||||
title: string,
|
||||
opts?: {
|
||||
board?: string
|
||||
body?: string
|
||||
assignee?: string
|
||||
priority?: number
|
||||
tenant?: string
|
||||
},
|
||||
): Promise<KanbanTask> {
|
||||
const args = ['kanban', 'create', title, '--json']
|
||||
const args = [...boardArgs(opts?.board), 'create', title, '--json']
|
||||
if (opts?.body) args.push('--body', opts.body)
|
||||
if (opts?.assignee) args.push('--assignee', opts.assignee)
|
||||
if (opts?.priority !== undefined) args.push('--priority', String(opts.priority))
|
||||
@@ -152,8 +284,8 @@ export async function createTask(
|
||||
}
|
||||
}
|
||||
|
||||
export async function completeTasks(taskIds: string[], summary?: string): Promise<void> {
|
||||
const args = ['kanban', 'complete', ...taskIds]
|
||||
export async function completeTasks(taskIds: string[], summary?: string, opts?: KanbanBoardOptions): Promise<void> {
|
||||
const args = [...boardArgs(opts?.board), 'complete', ...taskIds]
|
||||
if (summary) args.push('--summary', summary)
|
||||
|
||||
try {
|
||||
@@ -168,9 +300,9 @@ export async function completeTasks(taskIds: string[], summary?: string): Promis
|
||||
}
|
||||
}
|
||||
|
||||
export async function blockTask(taskId: string, reason: string): Promise<void> {
|
||||
export async function blockTask(taskId: string, reason: string, opts?: KanbanBoardOptions): Promise<void> {
|
||||
try {
|
||||
await execFileAsync(HERMES_BIN, ['kanban', 'block', taskId, reason], {
|
||||
await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'block', taskId, reason], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
@@ -181,9 +313,9 @@ export async function blockTask(taskId: string, reason: string): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function unblockTasks(taskIds: string[]): Promise<void> {
|
||||
export async function unblockTasks(taskIds: string[], opts?: KanbanBoardOptions): Promise<void> {
|
||||
try {
|
||||
await execFileAsync(HERMES_BIN, ['kanban', 'unblock', ...taskIds], {
|
||||
await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'unblock', ...taskIds], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
@@ -194,9 +326,9 @@ export async function unblockTasks(taskIds: string[]): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function assignTask(taskId: string, profile: string): Promise<void> {
|
||||
export async function assignTask(taskId: string, profile: string, opts?: KanbanBoardOptions): Promise<void> {
|
||||
try {
|
||||
await execFileAsync(HERMES_BIN, ['kanban', 'assign', taskId, profile], {
|
||||
await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'assign', taskId, profile], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
@@ -207,9 +339,9 @@ export async function assignTask(taskId: string, profile: string): Promise<void>
|
||||
}
|
||||
}
|
||||
|
||||
export async function getStats(): Promise<KanbanStats> {
|
||||
export async function getStats(opts?: KanbanBoardOptions): Promise<KanbanStats> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, ['kanban', 'stats', '--json'], {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'stats', '--json'], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
@@ -221,9 +353,9 @@ export async function getStats(): Promise<KanbanStats> {
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssignees(): Promise<KanbanAssignee[]> {
|
||||
export async function getAssignees(opts?: KanbanBoardOptions): Promise<KanbanAssignee[]> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, ['kanban', 'assignees', '--json'], {
|
||||
const { stdout } = await execFileAsync(HERMES_BIN, [...boardArgs(opts?.board), 'assignees', '--json'], {
|
||||
maxBuffer: 50 * 1024 * 1024,
|
||||
timeout: 30000,
|
||||
...execOpts,
|
||||
|
||||
@@ -8,7 +8,12 @@ vi.mock('../../packages/client/src/api/client', () => ({
|
||||
}))
|
||||
|
||||
import {
|
||||
listBoards,
|
||||
createBoard,
|
||||
archiveBoard,
|
||||
getCapabilities,
|
||||
listTasks,
|
||||
getTask,
|
||||
createTask,
|
||||
completeTasks,
|
||||
blockTask,
|
||||
@@ -23,16 +28,36 @@ describe('Kanban API', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('serializes list filters into query params', async () => {
|
||||
it('serializes board and list filters into query params', async () => {
|
||||
mockRequest.mockResolvedValue({ tasks: [{ id: 'task-1' }] })
|
||||
|
||||
const result = await listTasks({ status: 'blocked', assignee: 'alice', tenant: 'ops' })
|
||||
const result = await listTasks({ board: 'default', status: 'blocked', assignee: 'alice', tenant: 'ops' })
|
||||
|
||||
expect(mockRequest).toHaveBeenCalledWith('/api/hermes/kanban?status=blocked&assignee=alice&tenant=ops')
|
||||
expect(mockRequest).toHaveBeenCalledWith('/api/hermes/kanban?board=default&status=blocked&assignee=alice&tenant=ops')
|
||||
expect(result).toEqual([{ id: 'task-1' }])
|
||||
})
|
||||
|
||||
it('posts create and action payloads in the expected shape', async () => {
|
||||
it('keeps default board explicit when no board is supplied', async () => {
|
||||
mockRequest
|
||||
.mockResolvedValueOnce({ tasks: [] })
|
||||
.mockResolvedValueOnce({ stats: { total: 0, by_status: {}, by_assignee: {} } })
|
||||
.mockResolvedValueOnce({ assignees: [] })
|
||||
.mockResolvedValueOnce({ task: { id: 'task-1' }, comments: [], events: [], runs: [] })
|
||||
|
||||
await listTasks()
|
||||
await getStats()
|
||||
await getAssignees()
|
||||
await getTask('task-1')
|
||||
|
||||
expect(mockRequest.mock.calls.map(call => call[0])).toEqual([
|
||||
'/api/hermes/kanban?board=default',
|
||||
'/api/hermes/kanban/stats?board=default',
|
||||
'/api/hermes/kanban/assignees?board=default',
|
||||
'/api/hermes/kanban/task-1?board=default',
|
||||
])
|
||||
})
|
||||
|
||||
it('posts create and action payloads with explicit board in the URL', async () => {
|
||||
mockRequest
|
||||
.mockResolvedValueOnce({ task: { id: 'task-1' } })
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
@@ -40,27 +65,44 @@ describe('Kanban API', () => {
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
|
||||
expect(await createTask({ title: 'Ship', assignee: 'alice', priority: 3 })).toEqual({ id: 'task-1' })
|
||||
await completeTasks(['task-1'], 'done')
|
||||
await blockTask('task-1', 'waiting')
|
||||
await unblockTasks(['task-1'])
|
||||
await assignTask('task-1', 'bob')
|
||||
expect(await createTask({ title: 'Ship', assignee: 'alice', priority: 3 }, { board: 'project-a' })).toEqual({ id: 'task-1' })
|
||||
await completeTasks(['task-1'], 'done', { board: 'project-a' })
|
||||
await blockTask('task-1', 'waiting', { board: 'project-a' })
|
||||
await unblockTasks(['task-1'], { board: 'project-a' })
|
||||
await assignTask('task-1', 'bob', { board: 'project-a' })
|
||||
|
||||
expect(mockRequest.mock.calls).toEqual([
|
||||
['/api/hermes/kanban', { method: 'POST', body: JSON.stringify({ title: 'Ship', assignee: 'alice', priority: 3 }) }],
|
||||
['/api/hermes/kanban/complete', { method: 'POST', body: JSON.stringify({ task_ids: ['task-1'], summary: 'done' }) }],
|
||||
['/api/hermes/kanban/task-1/block', { method: 'POST', body: JSON.stringify({ reason: 'waiting' }) }],
|
||||
['/api/hermes/kanban/unblock', { method: 'POST', body: JSON.stringify({ task_ids: ['task-1'] }) }],
|
||||
['/api/hermes/kanban/task-1/assign', { method: 'POST', body: JSON.stringify({ profile: 'bob' }) }],
|
||||
['/api/hermes/kanban?board=project-a', { method: 'POST', body: JSON.stringify({ title: 'Ship', assignee: 'alice', priority: 3 }) }],
|
||||
['/api/hermes/kanban/complete?board=project-a', { method: 'POST', body: JSON.stringify({ task_ids: ['task-1'], summary: 'done' }) }],
|
||||
['/api/hermes/kanban/task-1/block?board=project-a', { method: 'POST', body: JSON.stringify({ reason: 'waiting' }) }],
|
||||
['/api/hermes/kanban/unblock?board=project-a', { method: 'POST', body: JSON.stringify({ task_ids: ['task-1'] }) }],
|
||||
['/api/hermes/kanban/task-1/assign?board=project-a', { method: 'POST', body: JSON.stringify({ profile: 'bob' }) }],
|
||||
])
|
||||
})
|
||||
|
||||
it('unwraps stats and assignee response envelopes', async () => {
|
||||
it('lists and manages boards through explicit board endpoints', async () => {
|
||||
mockRequest
|
||||
.mockResolvedValueOnce({ boards: [{ slug: 'default' }] })
|
||||
.mockResolvedValueOnce({ board: { slug: 'project-a' } })
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ capabilities: { source: 'hermes-cli', supports: { boardsList: true }, missing: [] } })
|
||||
.mockResolvedValueOnce({ stats: { total: 3, by_status: {}, by_assignee: {} } })
|
||||
.mockResolvedValueOnce({ assignees: [{ name: 'alice', on_disk: true, counts: { todo: 1 } }] })
|
||||
|
||||
await expect(getStats()).resolves.toEqual({ total: 3, by_status: {}, by_assignee: {} })
|
||||
await expect(getAssignees()).resolves.toEqual([{ name: 'alice', on_disk: true, counts: { todo: 1 } }])
|
||||
await expect(listBoards({ includeArchived: true })).resolves.toEqual([{ slug: 'default' }])
|
||||
await expect(createBoard({ slug: 'project-a', name: 'Project A' })).resolves.toEqual({ slug: 'project-a' })
|
||||
await expect(archiveBoard('project-a')).resolves.toEqual({ ok: true })
|
||||
await expect(getCapabilities()).resolves.toEqual({ source: 'hermes-cli', supports: { boardsList: true }, missing: [] })
|
||||
await expect(getStats({ board: 'project-a' })).resolves.toEqual({ total: 3, by_status: {}, by_assignee: {} })
|
||||
await expect(getAssignees({ board: 'project-a' })).resolves.toEqual([{ name: 'alice', on_disk: true, counts: { todo: 1 } }])
|
||||
|
||||
expect(mockRequest.mock.calls).toEqual([
|
||||
['/api/hermes/kanban/boards?includeArchived=true'],
|
||||
['/api/hermes/kanban/boards', { method: 'POST', body: JSON.stringify({ slug: 'project-a', name: 'Project A' }) }],
|
||||
['/api/hermes/kanban/boards/project-a', { method: 'DELETE' }],
|
||||
['/api/hermes/kanban/capabilities'],
|
||||
['/api/hermes/kanban/stats?board=project-a'],
|
||||
['/api/hermes/kanban/assignees?board=project-a'],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,6 +3,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createPinia, setActivePinia } from 'pinia'
|
||||
|
||||
const mockKanbanApi = vi.hoisted(() => ({
|
||||
listBoards: vi.fn(),
|
||||
createBoard: vi.fn(),
|
||||
archiveBoard: vi.fn(),
|
||||
getCapabilities: vi.fn(),
|
||||
listTasks: vi.fn(),
|
||||
getStats: vi.fn(),
|
||||
getAssignees: vi.fn(),
|
||||
@@ -15,20 +19,43 @@ const mockKanbanApi = vi.hoisted(() => ({
|
||||
|
||||
vi.mock('@/api/hermes/kanban', () => mockKanbanApi)
|
||||
|
||||
import { useKanbanStore } from '@/stores/hermes/kanban'
|
||||
import { KANBAN_SELECTED_BOARD_STORAGE_KEY, useKanbanStore } from '@/stores/hermes/kanban'
|
||||
|
||||
describe('Kanban store', () => {
|
||||
beforeEach(() => {
|
||||
window.localStorage.clear()
|
||||
setActivePinia(createPinia())
|
||||
vi.clearAllMocks()
|
||||
mockKanbanApi.listBoards.mockResolvedValue([
|
||||
{ slug: 'default', name: 'Default', archived: false, counts: {}, total: 0 },
|
||||
{ slug: 'project-a', name: 'Project A', archived: false, counts: { todo: 1 }, total: 1 },
|
||||
])
|
||||
mockKanbanApi.getCapabilities.mockResolvedValue({ source: 'hermes-cli', supports: { boardsList: true }, missing: [] })
|
||||
})
|
||||
|
||||
it('fetchTasks uses active filters and updates loading', async () => {
|
||||
it('persists selected board, including default, and falls back to default for missing boards', async () => {
|
||||
const store = useKanbanStore()
|
||||
await store.fetchBoards()
|
||||
|
||||
expect(store.setSelectedBoard('project-a')).toBe('project-a')
|
||||
expect(window.localStorage.getItem(KANBAN_SELECTED_BOARD_STORAGE_KEY)).toBe('project-a')
|
||||
|
||||
expect(store.setSelectedBoard('default')).toBe('default')
|
||||
expect(window.localStorage.getItem(KANBAN_SELECTED_BOARD_STORAGE_KEY)).toBe('default')
|
||||
|
||||
const recovered = store.recoverSelectedBoard('missing-board')
|
||||
expect(recovered).toEqual({ board: 'default', recovered: true })
|
||||
expect(store.selectedBoard).toBe('default')
|
||||
expect(store.boardWarning).toContain('missing-board')
|
||||
})
|
||||
|
||||
it('fetchTasks uses active filters and selected board while updating loading', async () => {
|
||||
mockKanbanApi.listTasks.mockImplementation(
|
||||
() => new Promise(resolve => setTimeout(() => resolve([{ id: 'task-1', status: 'todo' }]), 0))
|
||||
)
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('project-a')
|
||||
store.setFilter('status', 'blocked')
|
||||
store.setFilter('assignee', 'alice')
|
||||
const promise = store.fetchTasks()
|
||||
@@ -36,20 +63,22 @@ describe('Kanban store', () => {
|
||||
expect(store.loading).toBe(true)
|
||||
await promise
|
||||
|
||||
expect(mockKanbanApi.listTasks).toHaveBeenCalledWith({ status: 'blocked', assignee: 'alice' })
|
||||
expect(mockKanbanApi.listTasks).toHaveBeenCalledWith({ board: 'project-a', status: 'blocked', assignee: 'alice' })
|
||||
expect(store.tasks).toEqual([{ id: 'task-1', status: 'todo' }])
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('create and status actions update local task state and refresh stats', async () => {
|
||||
it('create and status actions pass selected board, update local task state, and refresh board counts', async () => {
|
||||
mockKanbanApi.createTask.mockResolvedValue({ id: 'task-2', status: 'todo', assignee: null })
|
||||
mockKanbanApi.completeTasks.mockResolvedValue({ ok: true })
|
||||
mockKanbanApi.blockTask.mockResolvedValue({ ok: true })
|
||||
mockKanbanApi.unblockTasks.mockResolvedValue({ ok: true })
|
||||
mockKanbanApi.assignTask.mockResolvedValue({ ok: true })
|
||||
mockKanbanApi.getStats.mockResolvedValue({ total: 2, by_status: { done: 1 }, by_assignee: {} })
|
||||
mockKanbanApi.getAssignees.mockResolvedValue([{ name: 'bob', on_disk: true, counts: { ready: 1 } }])
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('project-a')
|
||||
store.tasks = [{ id: 'task-1', status: 'running', assignee: null }] as any
|
||||
|
||||
await store.createTask({ title: 'Ship' })
|
||||
@@ -58,21 +87,125 @@ describe('Kanban store', () => {
|
||||
await store.unblockTasks(['task-2'])
|
||||
await store.assignTask('task-2', 'bob')
|
||||
|
||||
expect(mockKanbanApi.createTask).toHaveBeenCalledWith({ title: 'Ship' }, { board: 'project-a' })
|
||||
expect(mockKanbanApi.completeTasks).toHaveBeenCalledWith(['task-1'], 'done', { board: 'project-a' })
|
||||
expect(mockKanbanApi.blockTask).toHaveBeenCalledWith('task-2', 'waiting', { board: 'project-a' })
|
||||
expect(mockKanbanApi.unblockTasks).toHaveBeenCalledWith(['task-2'], { board: 'project-a' })
|
||||
expect(mockKanbanApi.assignTask).toHaveBeenCalledWith('task-2', 'bob', { board: 'project-a' })
|
||||
expect(mockKanbanApi.listBoards).toHaveBeenCalledTimes(4)
|
||||
expect(mockKanbanApi.getAssignees).toHaveBeenCalledWith({ board: 'project-a' })
|
||||
expect(store.tasks[0]).toMatchObject({ id: 'task-2', status: 'ready', assignee: 'bob' })
|
||||
expect(store.tasks[1]).toMatchObject({ id: 'task-1', status: 'done' })
|
||||
expect(mockKanbanApi.getStats).toHaveBeenCalledTimes(4)
|
||||
})
|
||||
|
||||
it('refreshAll loads tasks, stats, and assignees together', async () => {
|
||||
it('creates and archives boards without relying on CLI current board', async () => {
|
||||
mockKanbanApi.listBoards.mockResolvedValue([
|
||||
{ slug: 'default', name: 'Default', archived: false, counts: {}, total: 0 },
|
||||
{ slug: 'new-board', name: 'New Board', archived: false, counts: {}, total: 0 },
|
||||
])
|
||||
mockKanbanApi.createBoard.mockResolvedValue({ slug: 'new-board', name: 'New Board', archived: false, counts: {}, total: 0 })
|
||||
mockKanbanApi.archiveBoard.mockResolvedValue({ ok: true })
|
||||
mockKanbanApi.listTasks.mockResolvedValue([])
|
||||
mockKanbanApi.getStats.mockResolvedValue({ total: 0, by_status: {}, by_assignee: {} })
|
||||
mockKanbanApi.getAssignees.mockResolvedValue([])
|
||||
|
||||
const store = useKanbanStore()
|
||||
await store.createBoard({ slug: 'new-board', name: 'New Board' })
|
||||
expect(mockKanbanApi.createBoard).toHaveBeenCalledWith({ slug: 'new-board', name: 'New Board' })
|
||||
expect(store.selectedBoard).toBe('new-board')
|
||||
|
||||
await store.archiveSelectedBoard()
|
||||
expect(mockKanbanApi.archiveBoard).toHaveBeenCalledWith('new-board')
|
||||
expect(store.selectedBoard).toBe('default')
|
||||
})
|
||||
|
||||
it('refreshAll loads boards, tasks, stats, and assignees for the same board', async () => {
|
||||
mockKanbanApi.listTasks.mockResolvedValue([{ id: 'task-1' }])
|
||||
mockKanbanApi.getStats.mockResolvedValue({ total: 1, by_status: {}, by_assignee: {} })
|
||||
mockKanbanApi.getAssignees.mockResolvedValue([{ name: 'alice', on_disk: true, counts: { todo: 1 } }])
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('project-a')
|
||||
await store.refreshAll()
|
||||
|
||||
expect(mockKanbanApi.listTasks).toHaveBeenCalledWith({ board: 'project-a', status: undefined, assignee: undefined })
|
||||
expect(mockKanbanApi.getStats).toHaveBeenCalledWith({ board: 'project-a' })
|
||||
expect(mockKanbanApi.getAssignees).toHaveBeenCalledWith({ board: 'project-a' })
|
||||
expect(mockKanbanApi.listBoards).toHaveBeenCalledWith({ includeArchived: false })
|
||||
expect(store.tasks).toEqual([{ id: 'task-1' }])
|
||||
expect(store.stats).toEqual({ total: 1, by_status: {}, by_assignee: {} })
|
||||
expect(store.assignees).toEqual([{ name: 'alice', on_disk: true, counts: { todo: 1 } }])
|
||||
})
|
||||
|
||||
it('ignores stale board-list responses after a newer request', async () => {
|
||||
let resolveSlowBoards: (value: unknown) => void = () => {}
|
||||
mockKanbanApi.listBoards
|
||||
.mockImplementationOnce(() => new Promise(resolve => { resolveSlowBoards = resolve }))
|
||||
.mockResolvedValueOnce([
|
||||
{ slug: 'default', name: 'Default', archived: false, counts: {}, total: 0 },
|
||||
{ slug: 'project-a', name: 'Project A', archived: false, counts: { todo: 2 }, total: 2 },
|
||||
])
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('project-a')
|
||||
const slowFetch = store.fetchBoards()
|
||||
await store.fetchBoards()
|
||||
resolveSlowBoards([{ slug: 'default', name: 'Default', archived: false, counts: {}, total: 0 }])
|
||||
await slowFetch
|
||||
|
||||
expect(store.selectedBoard).toBe('project-a')
|
||||
expect(store.activeBoards).toEqual(expect.arrayContaining([
|
||||
expect.objectContaining({ slug: 'project-a', total: 2 }),
|
||||
]))
|
||||
})
|
||||
|
||||
it('ignores stale same-board fetch responses after a newer request', async () => {
|
||||
let resolveSlow: (value: unknown) => void = () => {}
|
||||
mockKanbanApi.listTasks
|
||||
.mockImplementationOnce(() => new Promise(resolve => { resolveSlow = resolve }))
|
||||
.mockResolvedValueOnce([{ id: 'new-filter-task' }])
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('project-a')
|
||||
const slowFetch = store.fetchTasks()
|
||||
await store.fetchTasks()
|
||||
resolveSlow([{ id: 'old-filter-task' }])
|
||||
await slowFetch
|
||||
|
||||
expect(store.tasks).toEqual([{ id: 'new-filter-task' }])
|
||||
})
|
||||
|
||||
it('does not leave loading stuck when a silent fetch supersedes a visible fetch', async () => {
|
||||
let resolveVisible: (value: unknown) => void = () => {}
|
||||
mockKanbanApi.listTasks
|
||||
.mockImplementationOnce(() => new Promise(resolve => { resolveVisible = resolve }))
|
||||
.mockResolvedValueOnce([{ id: 'silent-task' }])
|
||||
|
||||
const store = useKanbanStore()
|
||||
const visibleFetch = store.fetchTasks()
|
||||
expect(store.loading).toBe(true)
|
||||
await store.fetchTasks(true)
|
||||
resolveVisible([{ id: 'visible-task' }])
|
||||
await visibleFetch
|
||||
|
||||
expect(store.tasks).toEqual([{ id: 'silent-task' }])
|
||||
expect(store.loading).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores stale fetch responses after a board switch', async () => {
|
||||
let resolveSlow: (value: unknown) => void = () => {}
|
||||
mockKanbanApi.listTasks
|
||||
.mockImplementationOnce(() => new Promise(resolve => { resolveSlow = resolve }))
|
||||
.mockResolvedValueOnce([{ id: 'new-board-task' }])
|
||||
|
||||
const store = useKanbanStore()
|
||||
store.setSelectedBoard('default')
|
||||
const slowFetch = store.fetchTasks()
|
||||
store.setSelectedBoard('project-a')
|
||||
await store.fetchTasks()
|
||||
resolveSlow([{ id: 'old-board-task' }])
|
||||
await slowFetch
|
||||
|
||||
expect(store.tasks).toEqual([{ id: 'new-board-task' }])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -37,6 +37,7 @@ vi.mock('@/api/hermes/kanban', () => ({
|
||||
|
||||
vi.mock('@/stores/hermes/kanban', () => ({
|
||||
useKanbanStore: () => ({
|
||||
selectedBoard: 'project-a',
|
||||
assignees: [{ name: 'alice', counts: { todo: 1 } }, { name: 'bob', counts: { ready: 1 } }],
|
||||
completeTasks: mockCompleteTasks,
|
||||
blockTask: mockBlockTask,
|
||||
@@ -198,7 +199,7 @@ describe('KanbanTaskDrawer', () => {
|
||||
await sessionsTitle?.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(mockRequest).toHaveBeenCalledWith('/api/hermes/kanban/search-sessions?task_id=task-2&profile=fresh')
|
||||
expect(mockRequest).toHaveBeenCalledWith('/api/hermes/kanban/search-sessions?task_id=task-2&profile=fresh&board=project-a')
|
||||
await wrapper.find('.session-item').trigger('click')
|
||||
expect(mockRouterPush).toHaveBeenCalledWith({ name: 'hermes.chat', query: { session: 'session-2' } })
|
||||
})
|
||||
|
||||
@@ -3,19 +3,40 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { defineComponent } from 'vue'
|
||||
import { mount, flushPromises } from '@vue/test-utils'
|
||||
|
||||
const routeState = vi.hoisted(() => ({
|
||||
query: { board: 'project-a' } as Record<string, string>,
|
||||
}))
|
||||
|
||||
const routerReplace = vi.hoisted(() => vi.fn())
|
||||
|
||||
const storeState = vi.hoisted(() => ({
|
||||
tasks: [] as Array<{ id: string; title: string; status: string; created_at: number }>,
|
||||
stats: { by_status: { todo: 1, done: 0 }, by_assignee: {}, total: 1 } as Record<string, any>,
|
||||
assignees: [] as Array<{ name: string; counts: Record<string, number> | null }>,
|
||||
activeBoards: [] as Array<{ slug: string; name: string; icon?: string; total?: number }>,
|
||||
loading: false,
|
||||
boardsLoading: false,
|
||||
selectedBoard: 'default',
|
||||
boardWarning: null as string | null,
|
||||
capabilities: null as Record<string, any> | null,
|
||||
filterStatus: null as string | null,
|
||||
filterAssignee: null as string | null,
|
||||
}))
|
||||
|
||||
const mockFetchBoards = vi.hoisted(() => vi.fn())
|
||||
const mockFetchCapabilities = vi.hoisted(() => vi.fn())
|
||||
const mockRefreshAll = vi.hoisted(() => vi.fn())
|
||||
const mockFetchTasks = vi.hoisted(() => vi.fn())
|
||||
const mockFetchStats = vi.hoisted(() => vi.fn())
|
||||
const mockSetFilter = vi.hoisted(() => vi.fn())
|
||||
const mockRecoverSelectedBoard = vi.hoisted(() => vi.fn())
|
||||
const mockCreateBoard = vi.hoisted(() => vi.fn())
|
||||
const mockArchiveSelectedBoard = vi.hoisted(() => vi.fn())
|
||||
|
||||
vi.mock('vue-router', () => ({
|
||||
useRoute: () => routeState,
|
||||
useRouter: () => ({ replace: routerReplace }),
|
||||
}))
|
||||
|
||||
vi.mock('vue-i18n', () => ({
|
||||
useI18n: () => ({
|
||||
@@ -24,12 +45,18 @@ vi.mock('vue-i18n', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('@/stores/hermes/kanban', () => ({
|
||||
DEFAULT_KANBAN_BOARD: 'default',
|
||||
useKanbanStore: () => ({
|
||||
...storeState,
|
||||
fetchBoards: mockFetchBoards,
|
||||
fetchCapabilities: mockFetchCapabilities,
|
||||
refreshAll: mockRefreshAll,
|
||||
fetchTasks: mockFetchTasks,
|
||||
fetchStats: mockFetchStats,
|
||||
setFilter: mockSetFilter,
|
||||
recoverSelectedBoard: mockRecoverSelectedBoard,
|
||||
createBoard: mockCreateBoard,
|
||||
archiveSelectedBoard: mockArchiveSelectedBoard,
|
||||
}),
|
||||
}))
|
||||
|
||||
@@ -58,6 +85,7 @@ vi.mock('@/components/hermes/kanban/KanbanCreateForm.vue', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('naive-ui', () => ({
|
||||
useMessage: () => ({ warning: vi.fn(), error: vi.fn(), success: vi.fn() }),
|
||||
NButton: defineComponent({
|
||||
name: 'NButton',
|
||||
emits: ['click'],
|
||||
@@ -65,9 +93,21 @@ vi.mock('naive-ui', () => ({
|
||||
}),
|
||||
NSelect: defineComponent({
|
||||
name: 'NSelect',
|
||||
props: { value: null, options: { type: Array, default: () => [] } },
|
||||
props: { value: null, options: { type: Array, default: () => [] }, loading: Boolean },
|
||||
emits: ['update:value'],
|
||||
template: '<div class="n-select-stub"></div>',
|
||||
template: '<button class="n-select-stub" @click="$emit(\'update:value\', options[1]?.value || value)"><span v-for="option in options" :key="option.value">{{ option.label }}</span>{{ value }}</button>',
|
||||
}),
|
||||
NInput: defineComponent({
|
||||
name: 'NInput',
|
||||
props: { value: { type: String, default: '' }, placeholder: { type: String, required: false } },
|
||||
emits: ['update:value'],
|
||||
template: '<input class="n-input-stub" :placeholder="placeholder" :value="value" @input="$emit(\'update:value\', $event.target.value)" />',
|
||||
}),
|
||||
NModal: defineComponent({
|
||||
name: 'NModal',
|
||||
props: { show: Boolean },
|
||||
emits: ['update:show', 'close'],
|
||||
template: '<div v-if="show" class="n-modal-stub"><slot /><slot name="action" /></div>',
|
||||
}),
|
||||
NSpin: defineComponent({
|
||||
name: 'NSpin',
|
||||
@@ -91,6 +131,8 @@ describe('KanbanView', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
vi.clearAllMocks()
|
||||
routeState.query = { board: 'project-a' }
|
||||
routerReplace.mockResolvedValue(undefined)
|
||||
storeState.tasks = [
|
||||
{ id: 'task-1', title: 'Task one', status: 'todo', created_at: 10 },
|
||||
{ id: 'task-2', title: 'Task two', status: 'done', created_at: 20 },
|
||||
@@ -101,12 +143,28 @@ describe('KanbanView', () => {
|
||||
total: 2,
|
||||
}
|
||||
storeState.assignees = []
|
||||
storeState.activeBoards = [
|
||||
{ slug: 'default', name: 'Default', total: 0 },
|
||||
{ slug: 'project-a', name: 'Project A', total: 2 },
|
||||
]
|
||||
storeState.loading = false
|
||||
storeState.boardsLoading = false
|
||||
storeState.selectedBoard = 'default'
|
||||
storeState.boardWarning = null
|
||||
storeState.capabilities = null
|
||||
storeState.filterStatus = null
|
||||
storeState.filterAssignee = null
|
||||
mockFetchBoards.mockResolvedValue(undefined)
|
||||
mockFetchCapabilities.mockResolvedValue(undefined)
|
||||
mockRefreshAll.mockResolvedValue(undefined)
|
||||
mockFetchTasks.mockResolvedValue(undefined)
|
||||
mockFetchStats.mockResolvedValue(undefined)
|
||||
mockCreateBoard.mockResolvedValue({ slug: 'new-board' })
|
||||
mockArchiveSelectedBoard.mockResolvedValue(undefined)
|
||||
mockRecoverSelectedBoard.mockImplementation((candidate: string) => {
|
||||
storeState.selectedBoard = candidate || 'default'
|
||||
return { board: storeState.selectedBoard, recovered: false }
|
||||
})
|
||||
mockSetFilter.mockImplementation((key: 'status' | 'assignee', value: string | null) => {
|
||||
if (key === 'status') storeState.filterStatus = value
|
||||
else storeState.filterAssignee = value
|
||||
@@ -117,11 +175,15 @@ describe('KanbanView', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('starts with collapsed panels and refreshes stats alongside tasks', async () => {
|
||||
it('initializes board from route query and refreshes stats alongside tasks', async () => {
|
||||
const wrapper = mount(KanbanView)
|
||||
await flushPromises()
|
||||
|
||||
expect(mockFetchBoards).toHaveBeenCalledOnce()
|
||||
expect(mockFetchCapabilities).toHaveBeenCalledOnce()
|
||||
expect(mockRecoverSelectedBoard).toHaveBeenCalledWith('project-a')
|
||||
expect(mockRefreshAll).toHaveBeenCalledOnce()
|
||||
expect(routerReplace).not.toHaveBeenCalled()
|
||||
expect(wrapper.find('.n-collapse-stub').attributes('data-default-expanded')).toBe('null')
|
||||
|
||||
await wrapper.find('.drawer-updated').trigger('click')
|
||||
@@ -131,7 +193,56 @@ describe('KanbanView', () => {
|
||||
await vi.advanceTimersByTimeAsync(15000)
|
||||
await flushPromises()
|
||||
|
||||
expect(mockFetchBoards).toHaveBeenCalledTimes(2)
|
||||
expect(mockFetchTasks).toHaveBeenCalledTimes(2)
|
||||
expect(mockFetchStats).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('renders board and assignee count labels with explicit context', async () => {
|
||||
storeState.assignees = [{ name: 'alice', counts: { todo: 2, done: 1 } }]
|
||||
const wrapper = mount(KanbanView)
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.text()).toContain('kanban.title: Default · kanban.stats.tasks: 0')
|
||||
expect(wrapper.text()).toContain('kanban.title: Project A · kanban.stats.tasks: 2')
|
||||
expect(wrapper.text()).toContain('kanban.detail.assignee: alice · kanban.stats.tasks: 3')
|
||||
})
|
||||
|
||||
it('creates and archives boards from the board toolbar', async () => {
|
||||
storeState.selectedBoard = 'project-a'
|
||||
const wrapper = mount(KanbanView)
|
||||
await flushPromises()
|
||||
|
||||
await wrapper.findAll('.n-button-stub')[0].trigger('click')
|
||||
await flushPromises()
|
||||
const inputs = wrapper.findAll('.n-input-stub')
|
||||
await inputs[0].setValue('new-board')
|
||||
await inputs[1].setValue('New Board')
|
||||
await wrapper.findAll('.n-button-stub').at(-1)!.trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(mockCreateBoard).toHaveBeenCalledWith({ slug: 'new-board', name: 'New Board' })
|
||||
expect(routerReplace).toHaveBeenCalledWith({ query: { board: 'new-board' } })
|
||||
|
||||
vi.spyOn(window, 'confirm').mockReturnValueOnce(true)
|
||||
await wrapper.findAll('.n-button-stub')[1].trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(mockArchiveSelectedBoard).toHaveBeenCalled()
|
||||
expect(routerReplace).toHaveBeenCalledWith({ query: { board: 'default' } })
|
||||
})
|
||||
|
||||
it('makes default board explicit when route query is absent', async () => {
|
||||
routeState.query = {}
|
||||
mockRecoverSelectedBoard.mockImplementation(() => {
|
||||
storeState.selectedBoard = 'default'
|
||||
return { board: 'default', recovered: false }
|
||||
})
|
||||
|
||||
mount(KanbanView)
|
||||
await flushPromises()
|
||||
|
||||
expect(routerReplace).toHaveBeenCalledWith({ query: { board: 'default' } })
|
||||
expect(mockRefreshAll).toHaveBeenCalledOnce()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -20,19 +20,61 @@ describe('hermes kanban service', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('builds list/create/stats CLI calls correctly', async () => {
|
||||
it('lists boards without mutating or depending on CLI current', async () => {
|
||||
mockExecFileAsync.mockResolvedValueOnce({ stdout: JSON.stringify([{ slug: 'default' }]) })
|
||||
|
||||
await expect(service.listBoards({ includeArchived: true })).resolves.toEqual([{ slug: 'default' }])
|
||||
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', 'boards', 'list', '--json', '--all'])
|
||||
})
|
||||
|
||||
it('creates and archives boards through canonical CLI board commands', async () => {
|
||||
mockExecFileAsync
|
||||
.mockResolvedValueOnce({ stdout: '' })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([{ slug: 'project-a', name: 'Project A' }]) })
|
||||
.mockResolvedValueOnce({ stdout: '' })
|
||||
|
||||
await expect(service.createBoard({ slug: 'project-a', name: 'Project A', description: 'desc', icon: '📌', color: '#8b5cf6', switchCurrent: true })).resolves.toEqual({ slug: 'project-a', name: 'Project A' })
|
||||
await expect(service.archiveBoard('project-a')).resolves.toBeUndefined()
|
||||
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', 'boards', 'create', 'project-a', '--name', 'Project A', '--description', 'desc', '--icon', '📌', '--color', '#8b5cf6', '--switch'])
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', 'boards', 'list', '--json', '--all'])
|
||||
expect(mockExecFileAsync.mock.calls[2][1]).toEqual(['kanban', 'boards', 'rm', 'project-a'])
|
||||
})
|
||||
|
||||
it('exposes capability metadata for WUI/canonical parity gaps', async () => {
|
||||
await expect(service.getCapabilities()).resolves.toMatchObject({
|
||||
source: 'hermes-cli',
|
||||
supports: { boardsList: true, boardCreate: true, commentsWrite: false, dispatch: false },
|
||||
missing: expect.arrayContaining(['commentsWrite', 'dispatch']),
|
||||
})
|
||||
})
|
||||
|
||||
it('builds list/create/stats CLI calls with global --board before the action', async () => {
|
||||
mockExecFileAsync
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([{ id: 'task-1' }]) })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify({ id: 'task-2' }) })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify({ total: 1, by_status: {}, by_assignee: {} }) })
|
||||
|
||||
await expect(service.listTasks({ status: 'todo', assignee: 'alice', tenant: 'ops' })).resolves.toEqual([{ id: 'task-1' }])
|
||||
await expect(service.createTask('Ship', { body: 'write', assignee: 'alice', priority: 3, tenant: 'ops' })).resolves.toEqual({ id: 'task-2' })
|
||||
await expect(service.getStats()).resolves.toEqual({ total: 1, by_status: {}, by_assignee: {} })
|
||||
await expect(service.listTasks({ board: 'project-a', status: 'todo', assignee: 'alice', tenant: 'ops' })).resolves.toEqual([{ id: 'task-1' }])
|
||||
await expect(service.createTask('Ship', { board: 'project-a', body: 'write', assignee: 'alice', priority: 3, tenant: 'ops' })).resolves.toEqual({ id: 'task-2' })
|
||||
await expect(service.getStats({ board: 'project-a' })).resolves.toEqual({ total: 1, by_status: {}, by_assignee: {} })
|
||||
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', 'list', '--json', '--status', 'todo', '--assignee', 'alice', '--tenant', 'ops'])
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', 'create', 'Ship', '--json', '--body', 'write', '--assignee', 'alice', '--priority', '3', '--tenant', 'ops'])
|
||||
expect(mockExecFileAsync.mock.calls[2][1]).toEqual(['kanban', 'stats', '--json'])
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', '--board', 'project-a', 'list', '--json', '--status', 'todo', '--assignee', 'alice', '--tenant', 'ops'])
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', '--board', 'project-a', 'create', 'Ship', '--json', '--body', 'write', '--assignee', 'alice', '--priority', '3', '--tenant', 'ops'])
|
||||
expect(mockExecFileAsync.mock.calls[2][1]).toEqual(['kanban', '--board', 'project-a', 'stats', '--json'])
|
||||
})
|
||||
|
||||
it('normalizes omitted board to default instead of falling through to CLI current', async () => {
|
||||
mockExecFileAsync
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([]) })
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify({ total: 0, by_status: {}, by_assignee: {} }) })
|
||||
|
||||
await service.listTasks()
|
||||
await service.getStats()
|
||||
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', '--board', 'default', 'list', '--json'])
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', '--board', 'default', 'stats', '--json'])
|
||||
})
|
||||
|
||||
it('builds action CLI calls and maps not-found show to null', async () => {
|
||||
@@ -44,18 +86,24 @@ describe('hermes kanban service', () => {
|
||||
.mockResolvedValueOnce({})
|
||||
.mockResolvedValueOnce({ stdout: JSON.stringify([{ name: 'alice' }]) })
|
||||
|
||||
await expect(service.getTask('missing')).resolves.toBeNull()
|
||||
await service.completeTasks(['task-1'], 'done')
|
||||
await service.blockTask('task-1', 'wait')
|
||||
await service.unblockTasks(['task-1'])
|
||||
await service.assignTask('task-1', 'alice')
|
||||
await expect(service.getAssignees()).resolves.toEqual([{ name: 'alice' }])
|
||||
await expect(service.getTask('missing', { board: 'default' })).resolves.toBeNull()
|
||||
await service.completeTasks(['task-1'], 'done', { board: 'default' })
|
||||
await service.blockTask('task-1', 'wait', { board: 'default' })
|
||||
await service.unblockTasks(['task-1'], { board: 'default' })
|
||||
await service.assignTask('task-1', 'alice', { board: 'default' })
|
||||
await expect(service.getAssignees({ board: 'default' })).resolves.toEqual([{ name: 'alice' }])
|
||||
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', 'complete', 'task-1', '--summary', 'done'])
|
||||
expect(mockExecFileAsync.mock.calls[2][1]).toEqual(['kanban', 'block', 'task-1', 'wait'])
|
||||
expect(mockExecFileAsync.mock.calls[3][1]).toEqual(['kanban', 'unblock', 'task-1'])
|
||||
expect(mockExecFileAsync.mock.calls[4][1]).toEqual(['kanban', 'assign', 'task-1', 'alice'])
|
||||
expect(mockExecFileAsync.mock.calls[5][1]).toEqual(['kanban', 'assignees', '--json'])
|
||||
expect(mockExecFileAsync.mock.calls[0][1]).toEqual(['kanban', '--board', 'default', 'show', 'missing', '--json'])
|
||||
expect(mockExecFileAsync.mock.calls[1][1]).toEqual(['kanban', '--board', 'default', 'complete', 'task-1', '--summary', 'done'])
|
||||
expect(mockExecFileAsync.mock.calls[2][1]).toEqual(['kanban', '--board', 'default', 'block', 'task-1', 'wait'])
|
||||
expect(mockExecFileAsync.mock.calls[3][1]).toEqual(['kanban', '--board', 'default', 'unblock', 'task-1'])
|
||||
expect(mockExecFileAsync.mock.calls[4][1]).toEqual(['kanban', '--board', 'default', 'assign', 'task-1', 'alice'])
|
||||
expect(mockExecFileAsync.mock.calls[5][1]).toEqual(['kanban', '--board', 'default', 'assignees', '--json'])
|
||||
})
|
||||
|
||||
it('rejects invalid board slugs before shelling out', async () => {
|
||||
await expect(service.listTasks({ board: 'bad;slug' })).rejects.toThrow('Invalid kanban board slug')
|
||||
expect(mockExecFileAsync).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('wraps CLI failures with service-specific errors', async () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const mockReadFile = vi.hoisted(() => vi.fn())
|
||||
const mockListBoards = vi.hoisted(() => vi.fn())
|
||||
const mockCreateBoard = vi.hoisted(() => vi.fn())
|
||||
const mockArchiveBoard = vi.hoisted(() => vi.fn())
|
||||
const mockGetCapabilities = vi.hoisted(() => vi.fn())
|
||||
const mockListTasks = vi.hoisted(() => vi.fn())
|
||||
const mockGetTask = vi.hoisted(() => vi.fn())
|
||||
const mockCreateTask = vi.hoisted(() => vi.fn())
|
||||
@@ -24,6 +28,15 @@ vi.mock('os', () => ({
|
||||
}))
|
||||
|
||||
vi.mock('../../packages/server/src/services/hermes/hermes-kanban', () => ({
|
||||
normalizeBoardSlug: (board?: string | null) => {
|
||||
const value = board?.trim() || 'default'
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(value)) throw new Error('Invalid kanban board slug')
|
||||
return value
|
||||
},
|
||||
listBoards: mockListBoards,
|
||||
createBoard: mockCreateBoard,
|
||||
archiveBoard: mockArchiveBoard,
|
||||
getCapabilities: mockGetCapabilities,
|
||||
listTasks: mockListTasks,
|
||||
getTask: mockGetTask,
|
||||
createTask: mockCreateTask,
|
||||
@@ -60,12 +73,40 @@ describe('kanban controller', () => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('lists tasks with filters', async () => {
|
||||
it('lists boards and tasks with explicit/default board context', async () => {
|
||||
mockListBoards.mockResolvedValue([{ slug: 'default' }])
|
||||
mockListTasks.mockResolvedValue([{ id: 'task-1' }])
|
||||
const c = ctx({ query: { status: 'todo', assignee: 'alice', tenant: 'ops' } })
|
||||
|
||||
const boardsCtx = ctx({ query: { includeArchived: 'true' } })
|
||||
await ctrl.listBoards(boardsCtx)
|
||||
expect(mockListBoards).toHaveBeenCalledWith({ includeArchived: true })
|
||||
expect(boardsCtx.body).toEqual({ boards: [{ slug: 'default' }] })
|
||||
|
||||
const c = ctx({ query: { board: 'project-a', status: 'todo', assignee: 'alice', tenant: 'ops' } })
|
||||
await ctrl.list(c)
|
||||
expect(mockListTasks).toHaveBeenCalledWith({ status: 'todo', assignee: 'alice', tenant: 'ops' })
|
||||
expect(mockListTasks).toHaveBeenCalledWith({ board: 'project-a', status: 'todo', assignee: 'alice', tenant: 'ops' })
|
||||
expect(c.body).toEqual({ tasks: [{ id: 'task-1' }] })
|
||||
|
||||
mockCreateBoard.mockResolvedValue({ slug: 'project-b' })
|
||||
const createBoardCtx = ctx({ request: { body: { slug: 'project-b', name: 'Project B', switchCurrent: false } } })
|
||||
await ctrl.createBoard(createBoardCtx)
|
||||
expect(mockCreateBoard).toHaveBeenCalledWith({ slug: 'project-b', name: 'Project B', description: undefined, icon: undefined, color: undefined, switchCurrent: false })
|
||||
expect(createBoardCtx.body).toEqual({ board: { slug: 'project-b' } })
|
||||
|
||||
mockArchiveBoard.mockResolvedValue(undefined)
|
||||
const archiveCtx = ctx({ params: { slug: 'project-b' } })
|
||||
await ctrl.archiveBoard(archiveCtx)
|
||||
expect(mockArchiveBoard).toHaveBeenCalledWith('project-b')
|
||||
expect(archiveCtx.body).toEqual({ ok: true })
|
||||
|
||||
mockGetCapabilities.mockResolvedValue({ source: 'hermes-cli', supports: {}, missing: [] })
|
||||
const capabilitiesCtx = ctx()
|
||||
await ctrl.capabilities(capabilitiesCtx)
|
||||
expect(capabilitiesCtx.body).toEqual({ capabilities: { source: 'hermes-cli', supports: {}, missing: [] } })
|
||||
|
||||
const defaultCtx = ctx({ query: { status: 'ready' } })
|
||||
await ctrl.list(defaultCtx)
|
||||
expect(mockListTasks).toHaveBeenLastCalledWith({ board: 'default', status: 'ready', assignee: undefined, tenant: undefined })
|
||||
})
|
||||
|
||||
it('enriches completed task details using the latest run profile', async () => {
|
||||
@@ -85,7 +126,7 @@ describe('kanban controller', () => {
|
||||
messages: [],
|
||||
})
|
||||
|
||||
const c = ctx({ params: { id: 'task-1' } })
|
||||
const c = ctx({ params: { id: 'task-1' }, query: { board: 'project-a' } })
|
||||
await ctrl.get(c)
|
||||
|
||||
expect(mockFindLatestExactSessionId).toHaveBeenCalledWith('task-1', 'fresh')
|
||||
@@ -110,7 +151,7 @@ describe('kanban controller', () => {
|
||||
messages: [{ id: 'm1', role: 'user', content: 'work kanban task t_348bfaaf', timestamp: 1 }],
|
||||
})
|
||||
|
||||
const c = ctx({ params: { id: 't_348bfaaf' } })
|
||||
const c = ctx({ params: { id: 't_348bfaaf' }, query: { board: 'project-a' } })
|
||||
await ctrl.get(c)
|
||||
|
||||
expect(c.body.session).toMatchObject({
|
||||
@@ -176,32 +217,35 @@ describe('kanban controller', () => {
|
||||
path: '/Users/tester/.hermes/kanban/workspaces/task/out.txt',
|
||||
})
|
||||
|
||||
const createCtx = ctx({ request: { body: { title: 'Ship', body: 'x' } } })
|
||||
const createCtx = ctx({ query: { board: 'project-a' }, request: { body: { title: 'Ship', body: 'x' } } })
|
||||
await ctrl.create(createCtx)
|
||||
expect(mockCreateTask).toHaveBeenCalledWith('Ship', { board: 'project-a', body: 'x', assignee: undefined, priority: undefined, tenant: undefined })
|
||||
expect(createCtx.body).toEqual({ task: { id: 'task-2' } })
|
||||
|
||||
const completeCtx = ctx({ request: { body: { task_ids: ['task-1'], summary: 'done' } } })
|
||||
const completeCtx = ctx({ query: { board: 'project-a' }, request: { body: { task_ids: ['task-1'], summary: 'done' } } })
|
||||
await ctrl.complete(completeCtx)
|
||||
expect(mockCompleteTasks).toHaveBeenCalledWith(['task-1'], 'done')
|
||||
expect(mockCompleteTasks).toHaveBeenCalledWith(['task-1'], 'done', { board: 'project-a' })
|
||||
|
||||
const blockCtx = ctx({ params: { id: 'task-1' }, request: { body: { reason: 'wait' } } })
|
||||
const blockCtx = ctx({ query: { board: 'project-a' }, params: { id: 'task-1' }, request: { body: { reason: 'wait' } } })
|
||||
await ctrl.block(blockCtx)
|
||||
expect(mockBlockTask).toHaveBeenCalledWith('task-1', 'wait')
|
||||
expect(mockBlockTask).toHaveBeenCalledWith('task-1', 'wait', { board: 'project-a' })
|
||||
|
||||
const unblockCtx = ctx({ request: { body: { task_ids: ['task-1'] } } })
|
||||
const unblockCtx = ctx({ query: { board: 'project-a' }, request: { body: { task_ids: ['task-1'] } } })
|
||||
await ctrl.unblock(unblockCtx)
|
||||
expect(mockUnblockTasks).toHaveBeenCalledWith(['task-1'])
|
||||
expect(mockUnblockTasks).toHaveBeenCalledWith(['task-1'], { board: 'project-a' })
|
||||
|
||||
const assignCtx = ctx({ params: { id: 'task-1' }, request: { body: { profile: 'alice' } } })
|
||||
const assignCtx = ctx({ query: { board: 'project-a' }, params: { id: 'task-1' }, request: { body: { profile: 'alice' } } })
|
||||
await ctrl.assign(assignCtx)
|
||||
expect(mockAssignTask).toHaveBeenCalledWith('task-1', 'alice')
|
||||
expect(mockAssignTask).toHaveBeenCalledWith('task-1', 'alice', { board: 'project-a' })
|
||||
|
||||
const statsCtx = ctx()
|
||||
const statsCtx = ctx({ query: { board: 'project-a' } })
|
||||
await ctrl.stats(statsCtx)
|
||||
expect(mockGetStats).toHaveBeenCalledWith({ board: 'project-a' })
|
||||
expect(statsCtx.body).toEqual({ stats: { total: 1, by_status: {}, by_assignee: {} } })
|
||||
|
||||
const assigneesCtx = ctx()
|
||||
const assigneesCtx = ctx({ query: { board: 'project-a' } })
|
||||
await ctrl.assignees(assigneesCtx)
|
||||
expect(mockGetAssignees).toHaveBeenCalledWith({ board: 'project-a' })
|
||||
expect(assigneesCtx.body).toEqual({ assignees: [{ name: 'alice' }] })
|
||||
|
||||
const searchCtx = ctx({ query: { task_id: 'task-1', profile: 'alice', q: 'custom' } })
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const handlers = {
|
||||
listBoards: vi.fn(async (ctx: any) => { ctx.body = { boards: [] } }),
|
||||
createBoard: vi.fn(async (ctx: any) => { ctx.body = { board: {} } }),
|
||||
archiveBoard: vi.fn(async (ctx: any) => { ctx.body = { ok: true } }),
|
||||
capabilities: vi.fn(async (ctx: any) => { ctx.body = { capabilities: {} } }),
|
||||
stats: vi.fn(async (ctx: any) => { ctx.body = { stats: {} } }),
|
||||
assignees: vi.fn(async (ctx: any) => { ctx.body = { assignees: [] } }),
|
||||
readArtifact: vi.fn(async (ctx: any) => { ctx.body = { content: 'x' } }),
|
||||
@@ -27,6 +31,9 @@ describe('kanban routes', () => {
|
||||
const paths = kanbanRoutes.stack.map((entry: any) => entry.path)
|
||||
|
||||
expect(paths).toEqual(expect.arrayContaining([
|
||||
'/api/hermes/kanban/boards',
|
||||
'/api/hermes/kanban/boards/:slug',
|
||||
'/api/hermes/kanban/capabilities',
|
||||
'/api/hermes/kanban/stats',
|
||||
'/api/hermes/kanban/assignees',
|
||||
'/api/hermes/kanban/artifact',
|
||||
|
||||
Reference in New Issue
Block a user