dsh-task-board-tapd 0.0.0-stage → 0.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/INSTALL.md +137 -0
- package/README.md +139 -2
- package/client.js +691 -0
- package/cordis.patch.yml +19 -0
- package/icon.svg +6 -0
- package/index.js +30 -0
- package/install.ps1 +19 -0
- package/install.sh +19 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +41 -3
- package/src/host/config.js +24 -0
- package/src/host/routes.js +53 -0
- package/src/host/service.js +352 -0
- package/src/host/tapd.js +176 -0
- package/src/host/tools.js +60 -0
- package/src/host/version.js +138 -0
package/cordis.patch.yml
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# dsh-task-board-tapd bundle patch: inserts the dual-face plugin row into the
|
|
2
|
+
# profile roster. The node half (exports ".") runs in the host process; the
|
|
3
|
+
# `dsh.client` declaration in package.json loads the browser half (exports
|
|
4
|
+
# "./client") into the web GUI.
|
|
5
|
+
#
|
|
6
|
+
# Optional row config (all have safe defaults in src/host/tapd.js + index.js):
|
|
7
|
+
# workspaceId: 单个 TAPD 工作区 ID(与 workspaceIds 二选一)
|
|
8
|
+
# workspaceIds: 多个 TAPD 工作区 ID(逗号分隔),环境变量 TAPD_WORKSPACE_IDS 有多个时会显示切换下拉框
|
|
9
|
+
# endpoint: TAPD OpenAPI 端点,默认 https://api.tapd.cn
|
|
10
|
+
# tokenEnv: 承载 Bearer Token 的环境变量名,默认 TAPD_TOKEN
|
|
11
|
+
# refreshSeconds: 看板自动刷新间隔(秒),默认 300
|
|
12
|
+
# listLimit: 每种实体最多拉取的条数,默认 200
|
|
13
|
+
# mineOnly: 只看当前用户负责的工作项(默认 true)
|
|
14
|
+
# allowShowAll: 显式允许界面切换到全部任务(默认 false;默认面板不会显示其他人的任务)
|
|
15
|
+
# owner: 显式指定处理人过滤(默认用当前登录人;不建议关闭 mineOnly)
|
|
16
|
+
- insert:
|
|
17
|
+
- id: tapd-task-board
|
|
18
|
+
name: 'dsh-task-board-tapd'
|
|
19
|
+
config: {}
|
package/icon.svg
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
2
|
+
<rect x="6" y="10" width="52" height="44" rx="6" fill="none" stroke="#247bbf" stroke-width="4"/>
|
|
3
|
+
<path d="M22 10v44M42 10v44" stroke="#247bbf" stroke-width="3" opacity="0.55"/>
|
|
4
|
+
<rect x="12" y="18" width="6" height="14" rx="2" fill="#247bbf"/>
|
|
5
|
+
<rect x="27" y="32" width="10" height="16" rx="2" fill="#7fb8e0"/>
|
|
6
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { TapdClient } from './src/host/tapd.js'
|
|
2
|
+
import { TapdBoardService } from './src/host/service.js'
|
|
3
|
+
import { registerRoutes } from './src/host/routes.js'
|
|
4
|
+
import { registerTools } from './src/host/tools.js'
|
|
5
|
+
import { loadConfig } from './src/host/config.js'
|
|
6
|
+
|
|
7
|
+
export const inject = ['webServer']
|
|
8
|
+
|
|
9
|
+
export function apply(ctx, config = {}) {
|
|
10
|
+
if (config.enabled === false) return () => {}
|
|
11
|
+
const mergedConfig = { ...config, ...loadConfig() }
|
|
12
|
+
const client = new TapdClient(mergedConfig)
|
|
13
|
+
const service = new TapdBoardService(client, mergedConfig, ctx)
|
|
14
|
+
const disposers = []
|
|
15
|
+
if (ctx.webServer) disposers.push(registerRoutes(ctx.webServer, service))
|
|
16
|
+
disposers.push(registerTools(ctx, service))
|
|
17
|
+
if (mergedConfig.announceToAgent) {
|
|
18
|
+
// 本插件只 inject webServer;systemPrompt 未必挂载,访问在部分宿主会抛错,
|
|
19
|
+
// 因此用 try/catch 兜住,声明失败不影响看板主功能,避免启动崩溃循环。
|
|
20
|
+
try {
|
|
21
|
+
if (ctx.systemPrompt?.section) {
|
|
22
|
+
disposers.push(ctx.systemPrompt.section({ name: 'plugin:tapd-task-board', order: 40, text: '本机已安装 TAPD 任务看板插件。可使用 tapd_board_list、tapd_board_get、tapd_board_move、tapd_board_comment、tapd_board_create_story 读取和操作 TAPD 工作项;写操作会真实修改 TAPD 数据。' }))
|
|
23
|
+
}
|
|
24
|
+
} catch (error) {
|
|
25
|
+
console.warn('[tapd-task-board] systemPrompt section skipped:', error?.message || error)
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
service.refresh().catch(error => console.warn('[tapd-task-board] initial refresh failed', error.message))
|
|
29
|
+
return () => disposers.splice(0).forEach(dispose => { try { dispose?.() } catch {} })
|
|
30
|
+
}
|
package/install.ps1
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
param(
|
|
2
|
+
[string]$Profile = 'desktop',
|
|
3
|
+
[string]$Package = ''
|
|
4
|
+
)
|
|
5
|
+
$ErrorActionPreference = 'Stop'
|
|
6
|
+
$root = Split-Path -Parent $MyInvocation.MyCommand.Path
|
|
7
|
+
if ([string]::IsNullOrWhiteSpace($Package)) {
|
|
8
|
+
$Package = Get-ChildItem -Path $root -Filter 'dsh-task-board-tapd-*.tgz' -File | Select-Object -First 1 -ExpandProperty FullName
|
|
9
|
+
}
|
|
10
|
+
if ([string]::IsNullOrWhiteSpace($Package) -or -not (Test-Path -LiteralPath $Package)) {
|
|
11
|
+
throw '找不到插件包 .tgz,请使用 -Package 指定路径。'
|
|
12
|
+
}
|
|
13
|
+
if (-not (Get-Command dsh -ErrorAction SilentlyContinue)) {
|
|
14
|
+
throw '找不到 dsh 命令,请先安装 DeepSeek Harness 或将 dsh 加入 PATH。'
|
|
15
|
+
}
|
|
16
|
+
Write-Host "Installing TAPD board plugin into profile '$Profile'..."
|
|
17
|
+
& dsh plugin --profile $Profile add ("file:" + (Resolve-Path -LiteralPath $Package).Path)
|
|
18
|
+
if ($LASTEXITCODE -ne 0) { throw "插件安装失败,退出码:$LASTEXITCODE" }
|
|
19
|
+
Write-Host '安装成功。请完全退出并重新打开 DeepSeek Harness,然后刷新 Web 页面。'
|
package/install.sh
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
#!/usr/bin/env bash
|
|
2
|
+
set -euo pipefail
|
|
3
|
+
PROFILE="${1:-desktop}"
|
|
4
|
+
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
5
|
+
PACKAGE="${2:-}"
|
|
6
|
+
if [[ -z "$PACKAGE" ]]; then
|
|
7
|
+
PACKAGE="$(find "$ROOT" -maxdepth 1 -type f -name 'dsh-task-board-tapd-*.tgz' -print -quit)"
|
|
8
|
+
fi
|
|
9
|
+
if [[ -z "$PACKAGE" || ! -f "$PACKAGE" ]]; then
|
|
10
|
+
echo '找不到插件包 .tgz,请将包路径作为第二个参数传入。' >&2
|
|
11
|
+
exit 1
|
|
12
|
+
fi
|
|
13
|
+
if ! command -v dsh >/dev/null 2>&1; then
|
|
14
|
+
echo '找不到 dsh 命令,请先安装 DeepSeek Harness 或将 dsh 加入 PATH。' >&2
|
|
15
|
+
exit 1
|
|
16
|
+
fi
|
|
17
|
+
echo "Installing TAPD board plugin into profile '$PROFILE'..."
|
|
18
|
+
dsh plugin --profile "$PROFILE" add "file:$(cd "$(dirname "$PACKAGE")" && pwd)/$(basename "$PACKAGE")"
|
|
19
|
+
echo '安装成功。请完全退出并重新打开 DeepSeek Harness,然后刷新 Web 页面。'
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,44 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-task-board-tapd",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.5.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"description": "TAPD 任务看板插件:在 DeepSeek Harness 客户端内查看与操作 TAPD 需求/任务/缺陷(列看板、搜索、改状态、评论、新建需求、Agent 工具)。",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"dsh",
|
|
9
|
+
"deepseek-harness",
|
|
10
|
+
"tapd",
|
|
11
|
+
"task-board",
|
|
12
|
+
"plugin"
|
|
13
|
+
],
|
|
14
|
+
"exports": {
|
|
15
|
+
".": "./index.js",
|
|
16
|
+
"./client": "./client.js",
|
|
17
|
+
"./locale/*.json": "./locale/*.json",
|
|
18
|
+
"./icon": "./icon.svg"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"index.js",
|
|
22
|
+
"client.js",
|
|
23
|
+
"src/host/*.js",
|
|
24
|
+
"cordis.patch.yml",
|
|
25
|
+
"locale/*.json",
|
|
26
|
+
"icon.svg",
|
|
27
|
+
"README.md",
|
|
28
|
+
"INSTALL.md",
|
|
29
|
+
"install.ps1",
|
|
30
|
+
"install.sh"
|
|
31
|
+
],
|
|
32
|
+
"dsh": {
|
|
33
|
+
"bundle": { "patch": "./cordis.patch.yml" },
|
|
34
|
+
"client": {
|
|
35
|
+
"platform": "web",
|
|
36
|
+
"immediately": true,
|
|
37
|
+
"inject": [
|
|
38
|
+
"@deepseek-ai/dsh-client-ui-layout",
|
|
39
|
+
"@deepseek-ai/dsh-client-ui-sidebar",
|
|
40
|
+
"@deepseek-ai/dsh-client-locale"
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
}
|
|
6
44
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import os from 'node:os'
|
|
4
|
+
|
|
5
|
+
export function configPath() {
|
|
6
|
+
const root = process.env.DSH_PROFILE_DIR || process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
7
|
+
return path.join(root, 'tapd-board-config.json')
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function loadConfig() {
|
|
11
|
+
try {
|
|
12
|
+
const value = JSON.parse(fs.readFileSync(configPath(), 'utf8'))
|
|
13
|
+
return value && typeof value === 'object' ? value : {}
|
|
14
|
+
} catch { return {} }
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function saveConfig(patch) {
|
|
18
|
+
const file = configPath()
|
|
19
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
20
|
+
const current = loadConfig()
|
|
21
|
+
const next = { ...current, ...patch }
|
|
22
|
+
fs.writeFileSync(file, JSON.stringify(next, null, 2), 'utf8')
|
|
23
|
+
return next
|
|
24
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
function isLoopback(address) {
|
|
2
|
+
return address === '127.0.0.1' || address === '::1' || address === '::ffff:127.0.0.1'
|
|
3
|
+
}
|
|
4
|
+
function allowed(req, webServer) {
|
|
5
|
+
try {
|
|
6
|
+
const origin = req.headers.origin
|
|
7
|
+
if (origin) return origin === webServer.getOrigin()
|
|
8
|
+
const site = req.headers['sec-fetch-site']
|
|
9
|
+
if (site === 'same-origin' || site === 'none') return true
|
|
10
|
+
return isLoopback(req.socket?.remoteAddress)
|
|
11
|
+
} catch { return false }
|
|
12
|
+
}
|
|
13
|
+
function send(res, status, body) { res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); res.end(JSON.stringify(body)) }
|
|
14
|
+
async function sendAttachment(res, service, requestUrl) {
|
|
15
|
+
const raw = requestUrl.searchParams.get('path') || ''
|
|
16
|
+
if (!/^\/tfl\/[a-zA-Z0-9_./-]+$/.test(raw) || raw.includes('..')) return send(res, 400, { ok: false, error: 'invalid attachment path' })
|
|
17
|
+
const response = await fetch(`https://www.tapd.cn${raw}`, { headers: { Authorization: `Bearer ${service.client.token()}`, Accept: 'image/*' } })
|
|
18
|
+
const type = response.headers.get('content-type') || ''
|
|
19
|
+
if (!response.ok || !type.startsWith('image/')) return send(res, 404, { ok: false, error: 'TAPD 图片不可用,请确认图片权限' })
|
|
20
|
+
const bytes = Buffer.from(await response.arrayBuffer())
|
|
21
|
+
res.writeHead(200, { 'content-type': type, 'content-length': String(bytes.length), 'cache-control': 'private, max-age=300' })
|
|
22
|
+
res.end(bytes)
|
|
23
|
+
}
|
|
24
|
+
function readJson(req) { return new Promise((resolve, reject) => { let text = ''; req.on('data', chunk => { text += chunk }); req.on('end', () => { try { resolve(text ? JSON.parse(text) : {}) } catch { reject(new Error('请求体不是合法 JSON')) } }); req.on('error', reject) }) }
|
|
25
|
+
|
|
26
|
+
export function registerRoutes(webServer, service) {
|
|
27
|
+
let stateDispose = () => {}
|
|
28
|
+
let actionDispose = () => {}
|
|
29
|
+
let attachmentDispose = () => {}
|
|
30
|
+
// HMR/reinstall can leave an older route generation alive until the Host
|
|
31
|
+
// restarts. Keep activation idempotent in that narrow case; the existing
|
|
32
|
+
// route remains authoritative and the new generation can still register
|
|
33
|
+
// tools and client resources.
|
|
34
|
+
try {
|
|
35
|
+
stateDispose = webServer.register({ kind: 'exact', path: '/api/tapd-board/state', handler: async (req, res) => {
|
|
36
|
+
if (!allowed(req, webServer)) return send(res, 403, { ok: false, error: 'forbidden' })
|
|
37
|
+
try { if (!service.state) await service.refresh(); send(res, 200, { ok: true, state: service.snapshot() }) } catch (error) { send(res, 200, { ok: false, error: error.message }) }
|
|
38
|
+
} })
|
|
39
|
+
} catch (error) { console.warn('[tapd-task-board] state route already registered', error.message) }
|
|
40
|
+
try {
|
|
41
|
+
actionDispose = webServer.register({ kind: 'exact', path: '/api/tapd-board/action', handler: async (req, res) => {
|
|
42
|
+
if (!allowed(req, webServer)) return send(res, 403, { ok: false, error: 'forbidden' })
|
|
43
|
+
try { const body = await readJson(req); const state = await service.apply(body.action, body.payload || {}); send(res, 200, { ok: true, state, message: '操作已完成' }) } catch (error) { send(res, 200, { ok: false, error: error instanceof Error ? error.message : String(error) }) }
|
|
44
|
+
} })
|
|
45
|
+
} catch (error) { console.warn('[tapd-task-board] action route already registered', error.message) }
|
|
46
|
+
try {
|
|
47
|
+
attachmentDispose = webServer.register({ kind: 'exact', path: '/api/tapd-board/attachment', handler: async (req, res) => {
|
|
48
|
+
if (!allowed(req, webServer)) return send(res, 403, { ok: false, error: 'forbidden' })
|
|
49
|
+
try { await sendAttachment(res, service, new URL(req.url, 'http://local')) } catch (error) { send(res, 500, { ok: false, error: error.message }) }
|
|
50
|
+
} })
|
|
51
|
+
} catch (error) { console.warn('[tapd-task-board] attachment route already registered', error.message) }
|
|
52
|
+
return () => { stateDispose(); actionDispose(); attachmentDispose() }
|
|
53
|
+
}
|
|
@@ -0,0 +1,352 @@
|
|
|
1
|
+
import { currentVersion, packageName as installedPackageName, fetchLatest, installVersion, DEFAULT_REGISTRY } from './version.js'
|
|
2
|
+
|
|
3
|
+
function shortId(id) { const s = String(id || ''); return s.length > 7 ? s.slice(-7) : s }
|
|
4
|
+
function cleanOwner(value) { return String(value || '').replace(/;+/g, ', ').replace(/^,\s*|,\s*$/g, '') }
|
|
5
|
+
function urlFor(type, workspaceId, id) {
|
|
6
|
+
const area = type === 'bug' ? 'bugtrace/bugs' : type === 'task' ? 'prong/tasks' : 'prong/stories'
|
|
7
|
+
return `https://www.tapd.cn/${workspaceId}/${area}/view/${id}`
|
|
8
|
+
}
|
|
9
|
+
function normalize(type, row, labels, workspaceId) {
|
|
10
|
+
const status = String(row.status || '')
|
|
11
|
+
if (type === 'bug') return { type, id: String(row.id), workspaceId: String(workspaceId), shortId: shortId(row.id), title: row.title || '', name: row.title || '', status, statusLabel: labels[status] || status, owner: cleanOwner(row.current_owner), creator: row.reporter || '', severity: row.severity || '', priority: row.priority || '', module: row.module || '', created: row.created || '', modified: row.modified || '', iterationId: row.iteration_id || '', description: row.description || '', url: urlFor(type, workspaceId, row.id) }
|
|
12
|
+
return { type, id: String(row.id), workspaceId: String(workspaceId), shortId: shortId(row.id), title: row.name || '', name: row.name || '', status, statusLabel: labels[status] || status, owner: cleanOwner(row.owner), creator: row.creator || '', priority: row.priority_label || row.priority || '', created: row.created || '', modified: row.modified || '', begin: row.begin || '', due: row.due || '', iterationId: row.iteration_id || '', label: row.label || '', progress: row.progress || '', workitemTypeId: row.workitem_type_id || '', description: row.description || '', url: urlFor(type, workspaceId, row.id) }
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export class TapdBoardService {
|
|
16
|
+
constructor(client, config = {}, ctx = {}) {
|
|
17
|
+
this.client = client
|
|
18
|
+
this.config = config
|
|
19
|
+
this.ctx = ctx
|
|
20
|
+
this.revision = 0
|
|
21
|
+
this.state = null
|
|
22
|
+
this.refreshing = null
|
|
23
|
+
this.user = undefined
|
|
24
|
+
this.statuses = { story: {}, task: {}, bug: {} }
|
|
25
|
+
// 面板只显示当前用户(环境变量配置的个人 token 对应账号)负责的工作项;
|
|
26
|
+
// 仅当 allowShowAll 显式配置为 true 时才允许界面切换到“全部”,默认禁止。
|
|
27
|
+
this.mineOnly = config.mineOnly !== false
|
|
28
|
+
this.allowShowAll = config.allowShowAll === true
|
|
29
|
+
this.owner = String(config.owner || '')
|
|
30
|
+
// 版本检查缓存(避免每次打开看板都请求 npm registry)
|
|
31
|
+
this.versionInfo = null
|
|
32
|
+
this.versionCheckedAt = 0
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
snapshot() { return this.state || { revision: 0, workspaceId: this.client.workspaceId, items: { story: [], task: [], bug: [] }, statuses: this.statuses, config: this.viewConfig(), version: this.versionSnapshot(), runs: [], settings: this.settingsSnapshot() } }
|
|
36
|
+
versionSnapshot() {
|
|
37
|
+
const info = this.versionInfo
|
|
38
|
+
return {
|
|
39
|
+
current: currentVersion(),
|
|
40
|
+
packageName: String(process.env.TAPD_BOARD_UPDATE_PACKAGE || this.config.updatePackage || installedPackageName()),
|
|
41
|
+
registry: String(process.env.TAPD_BOARD_UPDATE_REGISTRY || this.config.updateRegistry || DEFAULT_REGISTRY),
|
|
42
|
+
latest: info?.latest || '',
|
|
43
|
+
updateAvailable: Boolean(info?.updateAvailable),
|
|
44
|
+
checkedAt: info?.checkedAt || '',
|
|
45
|
+
error: info?.error || '',
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
workspaceRegistry() {
|
|
49
|
+
try { return this.ctx.get && this.ctx.get('workspaceRegistry') } catch { return undefined }
|
|
50
|
+
}
|
|
51
|
+
dshWorkspaces() {
|
|
52
|
+
const registry = this.workspaceRegistry()
|
|
53
|
+
if (!registry || typeof registry.list !== 'function') return []
|
|
54
|
+
try {
|
|
55
|
+
return registry.list().map(ws => ({ id: String(ws.id || ''), title: String(ws.title || ''), path: String(ws.path || '') }))
|
|
56
|
+
} catch { return [] }
|
|
57
|
+
}
|
|
58
|
+
viewConfig() { return { refreshSeconds: Number(this.config.refreshSeconds || 300), listLimit: Number(this.config.listLimit || 200), endpoint: this.client.endpoint, mineOnly: this.mineOnly, allowShowAll: this.allowShowAll, owner: this.owner || (this.mineOnly && this.user ? this.user.name : ''), workspaceId: this.client.workspaceId, workspaceIds: this.client.workspaceIds, workspacePaths: this.config.workspacePaths || {}, workspaceBindings: this.config.workspaceBindings || {}, dshWorkspaces: this.dshWorkspaces(), model: String(this.config.model || ''), allowAiHandoff: this.config.allowAiHandoff !== false, announceToAgent: this.config.announceToAgent === true, scheduleAvailable: Boolean(this.ctx.get?.('schedule')) } }
|
|
59
|
+
settingsSnapshot() {
|
|
60
|
+
let tokenConfigured = false
|
|
61
|
+
try { tokenConfigured = Boolean(this.client.token()) } catch { tokenConfigured = false }
|
|
62
|
+
let scheduleAvailable = false
|
|
63
|
+
try { scheduleAvailable = Boolean(this.ctx.get?.('schedule')) } catch { scheduleAvailable = false }
|
|
64
|
+
let agentsAvailable = false
|
|
65
|
+
try { agentsAvailable = Boolean(this.ctx.get?.('llm')) } catch { agentsAvailable = false }
|
|
66
|
+
return { tokenEnv: this.client.tokenEnv, tokenConfigured, endpoint: this.client.endpoint, workspaceIds: this.client.workspaceIds, scheduleAvailable, agentsAvailable }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async refresh() {
|
|
70
|
+
if (this.refreshing) return this.refreshing
|
|
71
|
+
this.refreshing = this._refresh().finally(() => { this.refreshing = null })
|
|
72
|
+
return this.refreshing
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async _refresh() {
|
|
76
|
+
const items = { story: [], task: [], bug: [] }
|
|
77
|
+
const errors = []
|
|
78
|
+
try { this.user = await this.client.userInfo() } catch (error) { errors.push(`用户信息:${error.message}`) }
|
|
79
|
+
// 处理人过滤:显式 owner 优先;否则 mineOnly 时用当前登录人
|
|
80
|
+
const owner = this.owner || (this.mineOnly ? this.user?.name : undefined)
|
|
81
|
+
if (this.mineOnly && !owner) {
|
|
82
|
+
// 只看自己的场景拿不到当前用户身份:宁可不加载,也不退化为显示所有人
|
|
83
|
+
errors.push('当前为「只看我的」范围,但无法获取当前用户信息,已暂停加载工作项')
|
|
84
|
+
} else {
|
|
85
|
+
for (const type of ['story', 'task', 'bug']) {
|
|
86
|
+
try { this.statuses[type] = await this.client.fields(type) } catch (error) { errors.push(`${type} 状态:${error.message}`) }
|
|
87
|
+
try {
|
|
88
|
+
const rows = await this.client.list(type, Number(this.config.listLimit || 200), owner)
|
|
89
|
+
items[type] = rows.map(row => normalize(type, row, this.statuses[type], this.client.workspaceId))
|
|
90
|
+
} catch (error) { errors.push(`${type} 列表:${error.message}`) }
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
this.revision += 1
|
|
94
|
+
const previousRuns = this.state?.runs || []
|
|
95
|
+
this.state = { revision: this.revision, fetchedAt: new Date().toISOString(), workspaceId: this.client.workspaceId, user: this.user ? { id: this.user.id, name: this.user.name, email: this.user.user_email || this.user.email } : undefined, statuses: this.statuses, items, config: this.viewConfig(), version: this.versionSnapshot(), settings: this.settingsSnapshot(), runs: previousRuns, errors }
|
|
96
|
+
return this.state
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
async detail(type, id) {
|
|
100
|
+
const row = await this.client.detail(type, id)
|
|
101
|
+
if (!row) throw new Error('TAPD 工作项不存在')
|
|
102
|
+
return normalize(type, row, this.statuses[type] || {}, this.client.workspaceId)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
async apply(action, payload = {}) {
|
|
106
|
+
if (action === 'refresh') return this.refresh()
|
|
107
|
+
if (action === 'saveSettings') {
|
|
108
|
+
const { saveConfig } = await import('./config.js')
|
|
109
|
+
const patch = {}
|
|
110
|
+
if (payload.endpoint !== undefined) patch.endpoint = String(payload.endpoint || '').trim()
|
|
111
|
+
if (payload.workspaceIds !== undefined) patch.workspaceIds = String(payload.workspaceIds || '').split(',').map(v => v.trim()).filter(Boolean).join(',')
|
|
112
|
+
if (payload.refreshSeconds !== undefined) patch.refreshSeconds = Math.max(30, Number(payload.refreshSeconds) || 300)
|
|
113
|
+
if (payload.listLimit !== undefined) patch.listLimit = Math.min(200, Math.max(20, Number(payload.listLimit) || 200))
|
|
114
|
+
if (payload.model !== undefined) patch.model = String(payload.model || '').trim()
|
|
115
|
+
if (payload.announceToAgent !== undefined) patch.announceToAgent = Boolean(payload.announceToAgent)
|
|
116
|
+
if (payload.workspacePaths !== undefined) {
|
|
117
|
+
const raw = payload.workspacePaths && typeof payload.workspacePaths === 'object' ? payload.workspacePaths : {}
|
|
118
|
+
patch.workspacePaths = Object.fromEntries(Object.entries(raw).map(([key, value]) => [String(key).trim(), String(value || '').trim()]).filter(([, value]) => value))
|
|
119
|
+
}
|
|
120
|
+
if (payload.workspaceBindings !== undefined) {
|
|
121
|
+
const raw = payload.workspaceBindings && typeof payload.workspaceBindings === 'object' ? payload.workspaceBindings : {}
|
|
122
|
+
patch.workspaceBindings = Object.fromEntries(Object.entries(raw).map(([key, value]) => [String(key).trim(), String(value || '').trim()]).filter(([, value]) => value))
|
|
123
|
+
}
|
|
124
|
+
saveConfig(patch)
|
|
125
|
+
Object.assign(this.config, patch)
|
|
126
|
+
if (typeof this.client.applyConfig === 'function') this.client.applyConfig(this.config)
|
|
127
|
+
this.owner = String(this.config.owner || '')
|
|
128
|
+
return this.refresh()
|
|
129
|
+
}
|
|
130
|
+
if (action === 'getSettings') return { config: this.viewConfig(), settings: this.settingsSnapshot() }
|
|
131
|
+
if (action === 'registerWorkspace') {
|
|
132
|
+
// 登记一个本地代码工程目录为 DSH 工作区(供定时任务执行绑定)
|
|
133
|
+
const pathToRegister = String(payload.path || '').trim()
|
|
134
|
+
if (!pathToRegister) throw new Error('registerWorkspace 参数需要 path')
|
|
135
|
+
const registry = this.workspaceRegistry()
|
|
136
|
+
if (!registry || typeof registry.create !== 'function') throw new Error('当前 DSH 未启用工作区服务')
|
|
137
|
+
const workspace = await registry.create(pathToRegister, String(payload.title || '').trim() || undefined)
|
|
138
|
+
return { ...this.snapshot(), registeredWorkspace: { id: String(workspace.id || ''), title: String(workspace.title || ''), path: String(workspace.path || '') } }
|
|
139
|
+
}
|
|
140
|
+
if (action === 'switchWorkspace') {
|
|
141
|
+
if (!String(payload.workspaceId || '').trim()) throw new Error('switchWorkspace 参数需要 workspaceId')
|
|
142
|
+
this.client.setWorkspaceId(String(payload.workspaceId).trim())
|
|
143
|
+
this.user = undefined
|
|
144
|
+
return this.refresh()
|
|
145
|
+
}
|
|
146
|
+
if (action === 'scope') {
|
|
147
|
+
if (typeof payload.mineOnly !== 'boolean') throw new Error('scope 参数需要布尔值 mineOnly')
|
|
148
|
+
if (!payload.mineOnly && !this.allowShowAll) throw new Error('面板只显示当前用户的任务,不允许切换到「全部」(如需放开请配置 allowShowAll: true)')
|
|
149
|
+
this.mineOnly = payload.mineOnly
|
|
150
|
+
return this.refresh()
|
|
151
|
+
}
|
|
152
|
+
if (action === 'get') return { ...this.snapshot(), detail: await this.detail(payload.type, payload.id) }
|
|
153
|
+
if (action === 'move') {
|
|
154
|
+
if (!['story', 'task', 'bug'].includes(payload.type) || !payload.id || !payload.status) throw new Error('move 参数不完整')
|
|
155
|
+
await this.client.update(payload.type, payload.id, { status: payload.status })
|
|
156
|
+
return this.refresh()
|
|
157
|
+
}
|
|
158
|
+
if (action === 'comment') {
|
|
159
|
+
if (!payload.type || !payload.id || !String(payload.content || '').trim()) throw new Error('comment 参数不完整')
|
|
160
|
+
await this.client.addComment(payload.type, payload.id, String(payload.content).trim(), this.user?.name)
|
|
161
|
+
return this.refresh()
|
|
162
|
+
}
|
|
163
|
+
if (action === 'createStory') {
|
|
164
|
+
if (!String(payload.name || '').trim()) throw new Error('需求标题不能为空')
|
|
165
|
+
const first = this.snapshot().items.story[0]
|
|
166
|
+
await this.client.createStory({ name: String(payload.name).trim(), description: payload.description || '', owner: payload.owner || this.user?.name, priority: payload.priority, workitemTypeId: this.config.storyWorkitemTypeId || first?.workitemTypeId })
|
|
167
|
+
return this.refresh()
|
|
168
|
+
}
|
|
169
|
+
if (action === 'scheduleTask') {
|
|
170
|
+
// 创建真正的自动执行:注册 DSH 原生 schedule,到点向该 TAPD 工作项投递 Agent 指令,
|
|
171
|
+
// Agent 会自动创建会话并用 tapd_board_* 工具执行(无需手动复制 prompt)。
|
|
172
|
+
return this.scheduleTask(payload)
|
|
173
|
+
}
|
|
174
|
+
if (action === 'deleteSchedule') {
|
|
175
|
+
// 取消一条已注册的自动执行(通过其 scheduleId + 所属 sessionId)
|
|
176
|
+
return this.deleteSchedule(payload)
|
|
177
|
+
}
|
|
178
|
+
if (action === 'listSchedules') {
|
|
179
|
+
// 列出本插件已注册的自动执行
|
|
180
|
+
return this.listSchedules(payload)
|
|
181
|
+
}
|
|
182
|
+
if (action === 'checkVersion') {
|
|
183
|
+
// 查询 npm registry 上的最新版本(默认缓存 10 分钟;设置页「检查更新」可强制刷新)
|
|
184
|
+
return this.checkVersion(payload)
|
|
185
|
+
}
|
|
186
|
+
if (action === 'updatePlugin') {
|
|
187
|
+
// 通过 dsh CLI 安装最新版本;完成后需要重启 DSH 才会加载新版本
|
|
188
|
+
return this.updatePlugin(payload)
|
|
189
|
+
}
|
|
190
|
+
throw new Error(`不支持的动作:${action}`)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
async checkVersion(payload = {}) {
|
|
194
|
+
const cacheMs = 10 * 60 * 1000
|
|
195
|
+
if (payload.force !== true && this.versionInfo && Date.now() - this.versionCheckedAt < cacheMs) {
|
|
196
|
+
return { ...this.snapshot(), version: this.versionSnapshot() }
|
|
197
|
+
}
|
|
198
|
+
const registry = String(payload.registry || process.env.TAPD_BOARD_UPDATE_REGISTRY || this.config.updateRegistry || DEFAULT_REGISTRY)
|
|
199
|
+
const name = String(payload.packageName || process.env.TAPD_BOARD_UPDATE_PACKAGE || this.config.updatePackage || installedPackageName())
|
|
200
|
+
let info
|
|
201
|
+
try {
|
|
202
|
+
const result = await fetchLatest({ registry, packageName: name })
|
|
203
|
+
info = { ...result, checkedAt: new Date().toISOString() }
|
|
204
|
+
} catch (error) {
|
|
205
|
+
info = { latest: '', updateAvailable: false, checkedAt: new Date().toISOString(), error: error instanceof Error ? error.message : String(error), registry, packageName: name }
|
|
206
|
+
}
|
|
207
|
+
this.versionInfo = info
|
|
208
|
+
this.versionCheckedAt = Date.now()
|
|
209
|
+
if (this.state) this.state.version = this.versionSnapshot()
|
|
210
|
+
return { ...this.snapshot(), version: this.versionSnapshot() }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
async updatePlugin(payload = {}) {
|
|
214
|
+
const name = String(payload.packageName || process.env.TAPD_BOARD_UPDATE_PACKAGE || this.config.updatePackage || installedPackageName())
|
|
215
|
+
const registry = String(payload.registry || process.env.TAPD_BOARD_UPDATE_REGISTRY || this.config.updateRegistry || DEFAULT_REGISTRY)
|
|
216
|
+
const version = String(payload.version || this.versionInfo?.latest || '')
|
|
217
|
+
if (!version) throw new Error('没有可用的最新版本:请先点击「检查更新」')
|
|
218
|
+
const result = await installVersion({ profile: process.env.DSH_PROFILE, packageName: name, version, registry })
|
|
219
|
+
this.versionInfo = { ...(this.versionInfo || {}), latest: version, updateAvailable: false, checkedAt: new Date().toISOString() }
|
|
220
|
+
if (this.state) this.state.version = this.versionSnapshot()
|
|
221
|
+
return { ...this.snapshot(), update: { ok: true, ...result, message: `已安装 ${name}@${version},请完全退出并重启 DSH 生效` } }
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async listForTool(type, query) {
|
|
225
|
+
await this.refresh()
|
|
226
|
+
const types = type && type !== 'all' ? [type] : ['story', 'task', 'bug']
|
|
227
|
+
const needle = String(query || '').toLowerCase()
|
|
228
|
+
const result = {}
|
|
229
|
+
for (const key of types) result[key] = (this.snapshot().items[key] || []).filter(item => !needle || `${item.id} ${item.name} ${item.owner} ${item.title}`.toLowerCase().includes(needle)).slice(0, 100)
|
|
230
|
+
return result
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* 为一条 TAPD 工作项注册真正到点自动执行的调度:
|
|
235
|
+
* 1. 解析任务所属 TAPD 工作区对应的 DSH 执行工作区(workspaceBindings 映射,可选):
|
|
236
|
+
* TAPD 工作区是任务“登记”的空间,DSH 工作区是任务“执行”的空间(绑定代码工程目录)。
|
|
237
|
+
* 2. 用 DSH 的 sessionController 在对应 DSH 工作区创建(或复用)一个独立会话;
|
|
238
|
+
* 3. 用 schedule 服务注册到点触发;
|
|
239
|
+
* 4. 到点时向该会话注入「处理这条 TAPD 工作项」的完整 Agent 指令,
|
|
240
|
+
* 由 Agent(具备 tapd_board_* 工具)自动执行,无需用户手动复制 prompt。
|
|
241
|
+
* 5. 每次投递都记录到 state.runs,便于面板展示执行状态。
|
|
242
|
+
*/
|
|
243
|
+
async scheduleTask(payload = {}) {
|
|
244
|
+
const type = String(payload.type || '')
|
|
245
|
+
const id = String(payload.id || '')
|
|
246
|
+
const at = String(payload.at || '')
|
|
247
|
+
if (!['story', 'task', 'bug'].includes(type) || !id) throw new Error('scheduleTask 参数不完整(type/id 必填)')
|
|
248
|
+
const when = new Date(at)
|
|
249
|
+
if (!at || Number.isNaN(when.getTime()) || when.getTime() <= Date.now()) throw new Error('执行时间必须是未来的时间')
|
|
250
|
+
const schedule = this.ctx.get && this.ctx.get('schedule')
|
|
251
|
+
if (!schedule || typeof schedule.create !== 'function') throw new Error('当前 DSH 未启用定时服务')
|
|
252
|
+
const sessions = this.ctx.get && this.ctx.get('sessionController')
|
|
253
|
+
if (!sessions || typeof sessions.create !== 'function') throw new Error('当前 DSH 未启用会话服务')
|
|
254
|
+
|
|
255
|
+
// 任务级执行空间:只使用本次 payload 的显式选择,不按 TAPD 工作区做全局回退
|
|
256
|
+
const workspaceId = String(payload.workspaceId || this.client.workspaceId || '').trim()
|
|
257
|
+
const dshWorkspaceId = payload.dshWorkspaceId !== undefined && payload.dshWorkspaceId !== null ? String(payload.dshWorkspaceId).trim() : ''
|
|
258
|
+
const registry = this.workspaceRegistry()
|
|
259
|
+
const bound = (dshWorkspaceId && registry && typeof registry.get === 'function') ? registry.get(dshWorkspaceId) : undefined
|
|
260
|
+
const boundMeta = bound ? { id: String(bound.id || ''), title: String(bound.title || ''), path: String(bound.path || '') } : undefined
|
|
261
|
+
const workspacePath = String(payload.workspacePath || boundMeta?.path || '').trim()
|
|
262
|
+
|
|
263
|
+
// ② 创建独立会话:配置了 DSH 执行工作区时在对应工作区创建(Agent 拥有该代码工程上下文)
|
|
264
|
+
// 会话标题使用固定格式 `<type>#<id>`(例如 bug#1018732),避免 DSH 会话列表显示「未知」。
|
|
265
|
+
const sessionTitle = `${type}#${id}`
|
|
266
|
+
let sessionId = ''
|
|
267
|
+
const createdSession = async (options) => {
|
|
268
|
+
const created = await sessions.create(options)
|
|
269
|
+
return created?.sessionId || ''
|
|
270
|
+
}
|
|
271
|
+
if (dshWorkspaceId) {
|
|
272
|
+
try {
|
|
273
|
+
sessionId = await createdSession({ workspaceId: dshWorkspaceId })
|
|
274
|
+
} catch (error) {
|
|
275
|
+
// 工作区不可用(如目录缺失)时降级:尝试用其路径,再退回默认
|
|
276
|
+
sessionId = ''
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (!sessionId && workspacePath) {
|
|
280
|
+
try {
|
|
281
|
+
const { existsSync } = await import('node:fs')
|
|
282
|
+
if (existsSync(workspacePath)) {
|
|
283
|
+
sessionId = await createdSession({ cwd: workspacePath })
|
|
284
|
+
}
|
|
285
|
+
} catch { sessionId = '' }
|
|
286
|
+
}
|
|
287
|
+
if (!sessionId) {
|
|
288
|
+
const created = await sessions.create({})
|
|
289
|
+
sessionId = created?.sessionId || ''
|
|
290
|
+
}
|
|
291
|
+
if (!sessionId) throw new Error('无法创建独立会话')
|
|
292
|
+
// 会话创建接口不接收标题,标题通过 rename 设置;rename 失败仅降级,不阻断调度创建
|
|
293
|
+
if (sessionId) {
|
|
294
|
+
try {
|
|
295
|
+
if (typeof sessions.rename === 'function') {
|
|
296
|
+
await sessions.rename({ sessionId, title: sessionTitle })
|
|
297
|
+
}
|
|
298
|
+
} catch (error) {
|
|
299
|
+
console.warn(`[tapd-task-board] rename session ${sessionId} failed: ${error?.message || error}`)
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// ③ 到点触发的 Agent 指令(Agent 具备 tapd_board_* 工具,可读详情、改状态、评论等)
|
|
304
|
+
const item = { type, id, title: payload.title || '', url: payload.url || '' }
|
|
305
|
+
const execLabel = boundMeta ? `${boundMeta.title}(${boundMeta.path || boundMeta.id})` : (workspacePath || '')
|
|
306
|
+
const promptText = [
|
|
307
|
+
`【TAPD 自动执行任务】`,
|
|
308
|
+
`工作项类型:${type}`,
|
|
309
|
+
`工作项 ID:${id}`,
|
|
310
|
+
`TAPD 工作区:${workspaceId || '-'}`,
|
|
311
|
+
item.title ? `标题:${item.title}` : '',
|
|
312
|
+
item.url ? `TAPD 链接:${item.url}` : '',
|
|
313
|
+
execLabel ? `执行工作区:${execLabel}(当前会话已在该 DSH 工作区中打开,可直接读写代码工程文件)` : '',
|
|
314
|
+
``,
|
|
315
|
+
`请处理这条 TAPD 工作项:先用 tapd_board_get 读取最新详情,判断是否需要推进(状态/评论/处理),必要时使用 tapd_board_move / tapd_board_comment 更新,并在 TAPD 评论中总结处理结果。`,
|
|
316
|
+
].filter(Boolean).join('\n')
|
|
317
|
+
|
|
318
|
+
// ④ 注册原生 schedule(到点自动投递给该会话的 Agent 执行)
|
|
319
|
+
const record = await schedule.create(sessionId, {
|
|
320
|
+
title: sessionTitle,
|
|
321
|
+
prompt: promptText,
|
|
322
|
+
at,
|
|
323
|
+
})
|
|
324
|
+
|
|
325
|
+
const run = {
|
|
326
|
+
id: String(record?.id || ''), scheduledAt: at, sessionId, type, itemId: id,
|
|
327
|
+
workspaceId, dshWorkspaceId, workspacePath,
|
|
328
|
+
title: item.title, status: 'scheduled', createdAt: new Date().toISOString(),
|
|
329
|
+
}
|
|
330
|
+
if (this.state) this.state.runs = [run, ...(this.state.runs || []).filter(existing => existing.id !== run.id)]
|
|
331
|
+
return { ...this.snapshot(), scheduleId: run.id, sessionId, scheduledAt: at, workspaceId, dshWorkspaceId, workspacePath }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
async deleteSchedule(payload = {}) {
|
|
335
|
+
const id = String(payload.id || '')
|
|
336
|
+
const sessionId = String(payload.sessionId || '')
|
|
337
|
+
if (!id || !sessionId) throw new Error('deleteSchedule 参数需要 id 和 sessionId')
|
|
338
|
+
const schedule = this.ctx.get && this.ctx.get('schedule')
|
|
339
|
+
if (!schedule || typeof schedule.delete !== 'function') throw new Error('当前 DSH 未启用定时服务')
|
|
340
|
+
await schedule.delete({ sessionId, id })
|
|
341
|
+
if (this.state) this.state.runs = (this.state.runs || []).filter(existing => String(existing.id) !== id)
|
|
342
|
+
return { ...this.snapshot(), deleted: id }
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
async listSchedules() {
|
|
346
|
+
const schedule = this.ctx.get && this.ctx.get('schedule')
|
|
347
|
+
if (!schedule || typeof schedule.catalog !== 'function') return { ...this.snapshot(), catalog: [] }
|
|
348
|
+
const catalog = await schedule.catalog()
|
|
349
|
+
return { ...this.snapshot(), catalog }
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
}
|