miaopanel
1import { computed, reactive } from 'vue'
2import { api } from './api'
3
4export interface Task {
5 id: string
6 app: string
7 app_name: string
8 version: string
9 action: string
10 status: 'running' | 'ok' | 'failed'
11 log: string[]
12 error?: string
13 started_at: number
14 ended_at?: number
15}
16
17export const taskStore = reactive<{
18 items: Task[]
19 updatedAt: number
20}>({ items: [], updatedAt: 0 })
21
22let timer: number | undefined
23let finishHandler: ((task: Task) => void) | null = null
24
25export function setTaskFinishHandler(fn: (task: Task) => void) {
26 finishHandler = fn
27}
28
29export function taskLabel(task: Task): string {
30 const verb = task.action === 'install' ? '安装' : '卸载'
31 return `${verb} ${task.app_name} ${task.version}`
32}
33
34export async function refreshTasks() {
35 try {
36 // logs=0 keeps the 4s background poll small; the detail request pulls logs.
37 const items = await api.get<Task[]>('api/v1/apps/tasks?limit=20&logs=0')
38 const previous = new Map(taskStore.items.map((t) => [t.id, t.status]))
39 taskStore.items = items
40 taskStore.updatedAt = Date.now()
41 if (finishHandler) {
42 for (const t of items) {
43 if (previous.get(t.id) === 'running' && t.status !== 'running') finishHandler(t)
44 }
45 }
46 } catch {
47 /* polling is best effort */
48 }
49}
50
51/** Poll the shared task list while the panel is open. */
52export function startTaskWatch() {
53 if (timer !== undefined) return
54 void refreshTasks()
55 timer = window.setInterval(() => {
56 if (!document.hidden) void refreshTasks()
57 }, 4000)
58}
59
60export function stopTaskWatch() {
61 if (timer !== undefined) {
62 window.clearInterval(timer)
63 timer = undefined
64 }
65}
66
67export const runningTasks = computed(() => taskStore.items.filter((t) => t.status === 'running'))
68export const recentTasks = computed(() => taskStore.items.slice(0, 8))