✨ feat(vscode): 工单挂原型插件,详情面板一键导入 Figma

- prototypeFile 走通 state → Issue → webview 全链路(gitea/youtrack 两个
  loader、两份 KNOWN_STATE_FIELDS、issue/patch、webview types),按 planFile
  同款当共享字段;路径校验换成 .json 版,允许绝对路径
- 详情面板「计划文件」下加「原型插件路径」行:双击开 manifest.json,
  行尾按钮「在 Figma 中导入并打开」;没挂插件时只显示空态
- src/figma/:把 manifest 写进 Figma 桌面版的 localFileExtensions 再拉起
  Figma。坑是 Figma 退出会用内存状态覆盖 settings.json,所以写之前先
  osascript 优雅退出并轮询等它真没了(10s 等不到就让用户手动关,不强杀);
  写前备份 settings.json.bak-<时间戳>;已导入过就跳过写入直接打开;
  非 macOS 只把路径复制到剪贴板
- webhook 里 spec/plan 的 marker 同步改成表驱动,顺带认第三种 prototype
- 提示词:prototype.md 要求画完挂 marker;brainstorm-continue.md 新增
  {prototypeRef} 占位符,有原型插件时让续聊先读它别从零重画,没有时
  连同整段抹掉

Claude-Session: https://claude.ai/code/session_01Kgmb1LvrPmFX3NoUDB4zZC
This commit is contained in:
cruldra committed 2026-09-15 00:11:49 +08:00
1 parent def5f4e88c
commit 142af57d9d
24 files changed
+628 -85

No files matched your search

+17 -2
View File
@@ -29,12 +29,27 @@ export function getBrainstormPrompt(
return out
}
export function getBrainstormContinuePrompt(ctx: ExtensionContext, vars: { issueNumber: number, issueRef?: string }): string {
export function getBrainstormContinuePrompt(
ctx: ExtensionContext,
vars: { issueNumber: number, issueRef?: string, prototypeFile?: string },
): string {
const tpl = getSettings(ctx).brainstormContinuePrompt
// For youtrack cards the board number is synthetic; substitute the readable
// id (e.g. LXF-12) so the cc agent references the real issue (readable via
// `opencli yt issues show <id>`), not a non-existent gitea number.
return tpl.split('{issueNumber}').join(vars.issueRef ?? String(vars.issueNumber))
const out = tpl.split('{issueNumber}').join(vars.issueRef ?? String(vars.issueNumber))
return fillPrototypeRef(out, vars.prototypeFile)
}
/**
* `{prototypeRef}` 在模板里独占一段:有原型插件就填一段「先读它」的交代,
* 没有就连同前后空行一起抹掉——否则模板里会留下一个空洞段落。
*/
function fillPrototypeRef(tpl: string, prototypeFile: string | undefined): string {
if (!prototypeFile)
return tpl.replace(/\n*\{prototypeRef\}\n*/g, '\n\n').trimEnd()
const para = `工单已有原型插件 ${prototypeFile},先读它了解已经定下来的界面和交互,在此基础上只对齐还不明确的地方,不要从零重画。`
return tpl.split('{prototypeRef}').join(para)
}
export function getImplementPlanPrompt(ctx: ExtensionContext, vars: { planFile: string, issueNumber: number, issueRef?: string }): string {
+196
View File
@@ -0,0 +1,196 @@
/**
* 「在 Figma 中导入并打开」:把工单挂着的 Figma 插件 manifest.json 写进
* Figma 桌面版的已导入插件清单,然后拉起 Figma。
*
* 为什么要自己改配置文件:Figma 没有命令行导入开发插件的入口,UI 上得
* 「Plugins → Development → Import plugin from manifest」一路点。清单本身
* 就是 `~/Library/Application Support/Figma/settings.json` 里的一个数组,
* 直接往里加一条即可。
*
* 最大的坑:**Figma 退出时会用内存里的状态整个覆盖 settings.json**。开着
* Figma 写进去,用户一关 Figma 就全没了。所以写之前必须先把 Figma 关掉,
* 而且要等进程真的退出——不弹窗问用户,问了也只能答「关」。
*
* 只支持 macOS:路径和 `osascript` / `open -a` 都是 mac 专有。
*/
import { execFile } from 'node:child_process'
import * as fs from 'node:fs'
import { promises as fsp } from 'node:fs'
import * as os from 'node:os'
import * as path from 'node:path'
import process from 'node:process'
import { env, window } from 'vscode'
import { logger } from '../logging/logger'
import { appendManifestEntry, asExtensionEntries } from './localExtensions'
/** Figma 桌面版的设置文件(含已导入开发插件清单)。 */
function figmaSettingsPath(): string {
return path.join(os.homedir(), 'Library', 'Application Support', 'Figma', 'settings.json')
}
/** 等 Figma 退出的上限;到点还没退就让用户自己关,绝不 kill -9。 */
const QUIT_TIMEOUT_MS = 10_000
const QUIT_POLL_MS = 400
function run(cmd: string, args: string[]): Promise<{ code: number, stdout: string, stderr: string }> {
return new Promise((resolve) => {
execFile(cmd, args, { timeout: 15_000 }, (err, stdout, stderr) => {
// pgrep 没匹配到进程也是非零退出,所以这里不把非零当失败,交给调用方判。
const code = err ? Number((err as NodeJS.ErrnoException).code ?? 1) : 0
resolve({
code: Number.isFinite(code) ? code : 1,
stdout: (stdout ?? '').toString(),
stderr: (stderr ?? '').toString(),
})
})
})
}
async function isFigmaRunning(): Promise<boolean> {
const { stdout } = await run('pgrep', ['-x', 'Figma'])
return stdout.trim().length > 0
}
/**
* 优雅退出 Figma 并轮询等它真的没了。超时返回 false(调用方报错让用户手动关),
* 不强杀——Figma 被 SIGKILL 会丢用户没保存的画布。
*/
async function quitFigmaAndWait(): Promise<boolean> {
await run('osascript', ['-e', 'quit app "Figma"'])
const deadline = Date.now() + QUIT_TIMEOUT_MS
while (Date.now() < deadline) {
if (!await isFigmaRunning())
return true
await new Promise(resolve => setTimeout(resolve, QUIT_POLL_MS))
}
return !await isFigmaRunning()
}
/** 读 manifest.json 的 `name` 当 Figma 里显示的插件名;没有就用目录名兜底。 */
async function readPluginName(manifestAbs: string): Promise<string> {
const raw = await fsp.readFile(manifestAbs, 'utf8')
const parsed: unknown = JSON.parse(raw)
const name = parsed && typeof parsed === 'object'
? (parsed as { name?: unknown }).name
: undefined
if (typeof name === 'string' && name.trim().length > 0)
return name.trim()
return path.basename(path.dirname(manifestAbs))
}
function fail(message: string, err?: unknown): void {
const details = err === undefined
? undefined
: err instanceof Error
? (err.stack ?? err.message)
: String(err)
logger.add({ level: 'error', source: 'figma', message, details })
void window.showErrorMessage(message)
}
/**
* 主流程。`manifestPath` 可以是仓库相对路径也可以是绝对路径。
* 任何一步失败都出错误提示 + 记日志,不静默。
*/
export async function importPluginIntoFigma(opts: {
issueNumber: number
manifestPath: string
workspaceRoot: string
}): Promise<void> {
const { issueNumber, manifestPath, workspaceRoot } = opts
const manifestAbs = path.isAbsolute(manifestPath)
? manifestPath
: path.join(workspaceRoot, manifestPath)
if (!fs.existsSync(manifestAbs)) {
fail(`#${issueNumber} 的原型插件不存在:${manifestAbs}`)
return
}
// 非 mac 没有这条路径可走,把绝对路径给用户,让他自己在 Figma 里导入。
if (process.platform !== 'darwin') {
await env.clipboard.writeText(manifestAbs)
void window.showWarningMessage(
`当前系统不支持自动导入 Figma 插件,manifest 路径已复制到剪贴板,请在 Figma 里手动导入:${manifestAbs}`,
)
return
}
const settingsPath = figmaSettingsPath()
if (!fs.existsSync(settingsPath)) {
fail(`没找到 Figma 配置文件:${settingsPath}。先装 Figma 桌面版并至少启动一次。`)
return
}
let pluginName: string
try {
pluginName = await readPluginName(manifestAbs)
}
catch (err) {
fail(`读取 manifest.json 失败:${manifestAbs}`, err)
return
}
let settings: Record<string, unknown>
try {
const parsed: unknown = JSON.parse(await fsp.readFile(settingsPath, 'utf8'))
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
throw new TypeError('settings.json 顶层不是对象')
settings = parsed as Record<string, unknown>
}
catch (err) {
fail(`读取 Figma 配置失败:${settingsPath}`, err)
return
}
const entries = asExtensionEntries(settings.localFileExtensions)
const result = appendManifestEntry(entries, { manifestPath: manifestAbs, name: pluginName })
if (result.added) {
// 先关 Figma 再写,否则退出时的内存快照会把这次写入盖掉。
if (await isFigmaRunning()) {
logger.add({ level: 'info', source: 'figma', message: '写配置前先退出 Figma(退出会覆盖 settings.json)' })
if (!await quitFigmaAndWait()) {
fail(`Figma 在 ${QUIT_TIMEOUT_MS / 1000} 秒内没有退出,请手动关掉 Figma 后重试。`)
return
}
}
try {
const backup = `${settingsPath}.bak-${Date.now()}`
await fsp.copyFile(settingsPath, backup)
settings.localFileExtensions = result.entries
await fsp.writeFile(settingsPath, `${JSON.stringify(settings, null, 2)}\n`, 'utf8')
logger.add({
level: 'info',
source: 'figma',
message: `#${issueNumber} 原型插件已写入 Figma 配置:${pluginName}`,
details: `manifest=${manifestAbs} backup=${backup}`,
})
}
catch (err) {
fail(`写入 Figma 配置失败:${settingsPath}`, err)
return
}
}
else {
logger.add({
level: 'info',
source: 'figma',
message: `#${issueNumber} 原型插件已在 Figma 清单中,跳过写入:${result.name}`,
details: `manifest=${manifestAbs}`,
})
}
const open = await run('open', ['-a', 'Figma'])
if (open.code !== 0) {
fail(`拉起 Figma 失败:${open.stderr.trim() || `exit ${open.code}`}`)
return
}
void window.showInformationMessage(
result.added
? `原型插件「${result.name}」已导入 Figma,在 Plugins > Development 里跑它`
: `原型插件「${result.name}」此前已导入,在 Plugins > Development 里跑它`,
)
}
+115
View File
@@ -0,0 +1,115 @@
import { describe, expect, it } from 'vitest'
import {
appendManifestEntry,
asExtensionEntries,
buildManifestEntry,
findManifestEntry,
nextExtensionId,
} from './localExtensions'
/** 造一条 manifest 条目(id 与 codeFileId 成对,和 Figma 真实清单一致)。 */
function manifest(id: number, manifestPath: string) {
return {
id,
manifestPath,
lastKnownName: `plugin-${id}`,
lastKnownPluginId: '',
fileMetadata: { type: 'manifest' as const, codeFileId: id + 1, uiFileIds: [] },
}
}
/** Figma 加载插件后补的 code.js 条目,占的是 manifest 的 codeFileId。 */
function code(id: number, manifestFileId: number, manifestPath: string) {
return {
id,
manifestPath,
fileMetadata: { type: 'code' as const, manifestFileId },
}
}
describe('nextExtensionId', () => {
it('空清单从 1 开始', () => {
expect(nextExtensionId([])).toBe(1)
})
it('取已有条目 id 最大值 +1', () => {
expect(nextExtensionId([manifest(1, '/a/manifest.json'), code(2, 1, '/a/code.js')])).toBe(3)
})
it('codeFileId 预定的号也要算进去(code 条目还没建出来时)', () => {
// id 只到 11,但 11 的 codeFileId 已经把 12 预定了 → 下一个必须是 13
expect(nextExtensionId([
manifest(9, '/a/manifest.json'),
code(10, 9, '/a/code.js'),
manifest(11, '/b/manifest.json'),
])).toBe(13)
})
it('顺序乱了也按最大值算', () => {
expect(nextExtensionId([
code(8, 7, '/b/code.js'),
manifest(3, '/a/manifest.json'),
manifest(7, '/b/manifest.json'),
])).toBe(9)
})
})
describe('findManifestEntry', () => {
const entries = [manifest(1, '/a/manifest.json'), manifest(3, '/b/manifest.json')]
it('按 manifestPath 精确命中', () => {
expect(findManifestEntry(entries, '/b/manifest.json')?.id).toBe(3)
})
it('路径不同就不算重复(同名不同目录)', () => {
expect(findManifestEntry(entries, '/c/manifest.json')).toBeUndefined()
})
})
describe('buildManifestEntry', () => {
it('codeFileId 紧跟 id,给 Figma 之后建 code 条目占号', () => {
expect(buildManifestEntry({ id: 19, manifestPath: '/x/manifest.json', name: 'X Lab' })).toEqual({
id: 19,
manifestPath: '/x/manifest.json',
lastKnownName: 'X Lab',
lastKnownPluginId: '',
fileMetadata: { type: 'manifest', codeFileId: 20, uiFileIds: [] },
})
})
})
describe('appendManifestEntry', () => {
it('新插件追加到末尾,id 接着往下发', () => {
const entries = [manifest(1, '/a/manifest.json'), code(2, 1, '/a/code.js')]
const got = appendManifestEntry(entries, { manifestPath: '/b/manifest.json', name: 'B Lab' })
expect(got.added).toBe(true)
expect(got.entries).toHaveLength(3)
expect(got.entries[2]).toMatchObject({ id: 3, manifestPath: '/b/manifest.json', lastKnownName: 'B Lab' })
// 原数组不被改动
expect(entries).toHaveLength(2)
})
it('已导入过 → 不追加,名字用清单里记的那个', () => {
const entries = [manifest(1, '/a/manifest.json')]
const got = appendManifestEntry(entries, { manifestPath: '/a/manifest.json', name: '新名字' })
expect(got.added).toBe(false)
expect(got.entries).toBe(entries)
expect(got.name).toBe('plugin-1')
})
})
describe('asExtensionEntries', () => {
it('不是数组 → 空清单(Figma 没装过插件时该字段可能缺失)', () => {
expect(asExtensionEntries(undefined)).toEqual([])
expect(asExtensionEntries({})).toEqual([])
})
it('丢掉缺 id / manifestPath 的脏条目', () => {
expect(asExtensionEntries([
manifest(1, '/a/manifest.json'),
{ id: 'x', manifestPath: '/b/manifest.json' },
{ id: 2 },
null,
])).toHaveLength(1)
})
})
+116
View File
@@ -0,0 +1,116 @@
/**
* Figma 桌面版「已导入的开发插件」清单的纯逻辑:算新 id、查重、造条目。
*
* 清单落在 `~/Library/Application Support/Figma/settings.json` 的
* `localFileExtensions` 数组里,一条 manifest 条目长这样:
*
* ```json
* { "id": 9, "manifestPath": "/abs/.../manifest.json",
* "lastKnownName": "Xxx Design Lab", "lastKnownPluginId": "",
* "fileMetadata": { "type": "manifest", "codeFileId": 10, "uiFileIds": [] } }
* ```
*
* 坑:id 是**整个数组共享**的递增计数器,manifest 条目占一个 id,Figma 之后
* 给它的 code.js 建条目时占 `fileMetadata.codeFileId` 那个 id。所以算下一个
* id 时不能只看已有条目的 id,还得把被 codeFileId / manifestFileId 预定掉的
* 号算进去,否则新插件会和 Figma 迟早要建的 code 条目撞号。
*
* 这里不碰文件系统,好单测;读写与关 Figma 在 importPlugin.ts。
*/
export interface FigmaFileMetadata {
type: 'manifest' | 'code' | string
/** manifest 条目专有:预留给同插件 code.js 条目的 id。 */
codeFileId?: number
/** code 条目专有:反指所属 manifest 条目的 id。 */
manifestFileId?: number
uiFileIds?: number[]
}
export interface FigmaLocalFileExtension {
id: number
manifestPath: string
lastKnownName?: string
lastKnownPluginId?: string
fileMetadata?: FigmaFileMetadata
[key: string]: unknown
}
/** 数组里混着 Figma 写的杂项,只把「有数字 id + 字符串 manifestPath」的当条目。 */
export function asExtensionEntries(value: unknown): FigmaLocalFileExtension[] {
if (!Array.isArray(value))
return []
return value.filter((e): e is FigmaLocalFileExtension =>
!!e
&& typeof e === 'object'
&& typeof (e as FigmaLocalFileExtension).id === 'number'
&& typeof (e as FigmaLocalFileExtension).manifestPath === 'string',
)
}
/**
* 下一个可用 id:已有条目 id 与被 codeFileId / manifestFileId 预定的 id 取最大再 +1。
* 空清单从 1 开始(Figma 自己也是从 1 起)。
*/
export function nextExtensionId(entries: FigmaLocalFileExtension[]): number {
let max = 0
for (const e of entries) {
for (const n of [e.id, e.fileMetadata?.codeFileId, e.fileMetadata?.manifestFileId]) {
if (typeof n === 'number' && Number.isFinite(n) && n > max)
max = n
}
}
return max + 1
}
/** 按 manifestPath 精确查重;已导入过就返回那条,用来跳过写入。 */
export function findManifestEntry(
entries: FigmaLocalFileExtension[],
manifestPath: string,
): FigmaLocalFileExtension | undefined {
return entries.find(e => e.manifestPath === manifestPath)
}
/** 造一条 manifest 条目;code 条目留给 Figma 自己建,这里只把 id 号占住。 */
export function buildManifestEntry(opts: {
id: number
manifestPath: string
name: string
}): FigmaLocalFileExtension {
return {
id: opts.id,
manifestPath: opts.manifestPath,
lastKnownName: opts.name,
lastKnownPluginId: '',
fileMetadata: {
type: 'manifest',
codeFileId: opts.id + 1,
uiFileIds: [],
},
}
}
export interface AppendResult {
/** 追加后的完整条目数组;已存在时原样返回。 */
entries: FigmaLocalFileExtension[]
/** false = 已导入过,调用方跳过写文件直接拉起 Figma。 */
added: boolean
/** 这条插件在 Figma 里的显示名(新建用传入名,已存在用清单里记的名)。 */
name: string
}
/** 查重 → 算 id → 追加,一次算完,写文件的那端只管落盘。 */
export function appendManifestEntry(
entries: FigmaLocalFileExtension[],
opts: { manifestPath: string, name: string },
): AppendResult {
const existing = findManifestEntry(entries, opts.manifestPath)
if (existing)
return { entries, added: false, name: existing.lastKnownName || opts.name }
const entry = buildManifestEntry({
id: nextExtensionId(entries),
manifestPath: opts.manifestPath,
name: opts.name,
})
return { entries: [...entries, entry], added: true, name: opts.name }
}
+19
View File
@@ -45,6 +45,19 @@ export function isValidSpxFilePath(v: unknown): v is string {
&& v !== '…'
}
/**
* prototypeFile 指向 Figma 插件的 manifest.json,规则与 isValidSpxFilePath
* 同款,只是后缀换成 .json(可以是仓库相对路径,也可以是绝对路径)。
*/
export function isValidPrototypeFilePath(v: unknown): v is string {
return typeof v === 'string'
&& v.length > 0
&& v.includes('/')
&& v.endsWith('.json')
&& v !== '...'
&& v !== '…'
}
function isValidPrDiffFilePath(v: unknown): v is string {
return typeof v === 'string'
&& /^docs\/pr-diff\/\S+\.md$/.test(v)
@@ -73,6 +86,7 @@ function parseColumnFromComments(comments: GiteaComment[]): {
prototypeProfilePath?: string
specFile?: string
planFile?: string
prototypeFile?: string
prDiffFile?: string
pr?: string
prMerged?: boolean
@@ -121,6 +135,7 @@ function parseColumnFromComments(comments: GiteaComment[]): {
prototypeProfilePath?: unknown
specFile?: unknown
planFile?: unknown
prototypeFile?: unknown
prDiffFile?: unknown
pr?: unknown
prMerged?: unknown
@@ -155,6 +170,7 @@ function parseColumnFromComments(comments: GiteaComment[]): {
: undefined
const specFile = isValidSpxFilePath(obj.specFile) ? obj.specFile : undefined
const planFile = isValidSpxFilePath(obj.planFile) ? obj.planFile : undefined
const prototypeFile = isValidPrototypeFilePath(obj.prototypeFile) ? obj.prototypeFile : undefined
const prDiffFile = isValidPrDiffFilePath(obj.prDiffFile) ? obj.prDiffFile : undefined
const pr = typeof obj.pr === 'string' && obj.pr.length > 0
? obj.pr
@@ -205,6 +221,7 @@ function parseColumnFromComments(comments: GiteaComment[]): {
prototypeProfilePath,
specFile,
planFile,
prototypeFile,
prDiffFile,
pr,
prMerged,
@@ -348,6 +365,7 @@ async function buildIssue(opts: {
prototypeProfilePath,
specFile,
planFile,
prototypeFile,
prDiffFile,
pr,
prMerged: persistedMerged,
@@ -412,6 +430,7 @@ async function buildIssue(opts: {
...(prototypeProfilePath ? { prototypeProfilePath } : {}),
...(specFile ? { specFile } : {}),
...(planFile ? { planFile } : {}),
...(prototypeFile ? { prototypeFile } : {}),
...(prDiffFile ? { prDiffFile } : {}),
...(pr ? { pr } : {}),
...(prMerged !== undefined ? { prMerged } : {}),
+1 -1
View File
@@ -19,7 +19,7 @@ import { listIssueComments, postIssueComment } from './api'
* 普通文本评论、审查评论、Gitea 自动关联评论都不含这些字段,因此从尾往前
* 扫描时会被跳过,避免它们插队后下一次 merge 从空状态开始丢历史。
*/
const KNOWN_STATE_FIELDS = ['column', 'sessionId', 'implementSessionId', 'reviewSessionId', 'testSessionId', 'prototypeSessionId', 'profilePath', 'brainstormProfilePath', 'testProfilePath', 'prototypeProfilePath', 'specFile', 'planFile', 'prDiffFile', 'pr', 'prMerged', 'prMergedAt', 'branch', 'worktreePath', 'implementStatus', 'color', 'autoReview', 'handoffAttachmentId', 'handoffFrom'] as const
const KNOWN_STATE_FIELDS = ['column', 'sessionId', 'implementSessionId', 'reviewSessionId', 'testSessionId', 'prototypeSessionId', 'profilePath', 'brainstormProfilePath', 'testProfilePath', 'prototypeProfilePath', 'specFile', 'planFile', 'prototypeFile', 'prDiffFile', 'pr', 'prMerged', 'prMergedAt', 'branch', 'worktreePath', 'implementStatus', 'color', 'autoReview', 'handoffAttachmentId', 'handoffFrom'] as const
/**
* body 能 parse 成 object 且含至少一个已知 state 字段 → 认为是 state JSON。
+5
View File
@@ -59,6 +59,11 @@ export interface Issue {
* `.claude/plans/<stem>.md`.
*/
planFile?: string
/**
* 原型会话产出的 Figma 插件 `manifest.json` 路径(仓库相对或绝对)。
* cc 画完原型后用 `spx issue marker --type prototype` 挂上来。
*/
prototypeFile?: string
/** Optional workspace-relative path to the generated PR diff summary. */
prDiffFile?: string
/** PR number associated with this issue (set after webhook fires). */
+10
View File
@@ -16,6 +16,7 @@ import * as fs from 'node:fs'
import * as path from 'node:path'
import { env, TabInputTerminal, ThemeColor, Uri, ViewColumn, window, workspace } from 'vscode'
import { deleteToken, getToken } from '../auth/secrets'
import { importPluginIntoFigma } from '../figma/importPlugin'
import { detectRepo } from '../git/remote'
import {
GiteaApiError,
@@ -464,6 +465,15 @@ export class KanbanWebviewPanel {
void issues.handleOpenFile(this, msg.path)
return
}
if (msg.type === 'prototype/open-in-figma') {
const root = workspace.workspaceFolders?.[0]?.uri.fsPath
if (!root) {
void window.showErrorMessage('请先打开一个工作区文件夹')
return
}
void importPluginIntoFigma({ issueNumber: msg.issueNumber, manifestPath: msg.path, workspaceRoot: root })
return
}
if (msg.type === 'issue/implement') {
void this.handleImplement(msg.issueNumber, msg.planFile, msg.profilePath, msg.sessionId)
return
+2 -1
View File
@@ -2314,7 +2314,8 @@ export async function handleOpenFile(panel: KanbanWebviewPanel, relPath: string)
})
return
}
const abs = path.join(workspaceRoot, relPath)
// 多数字段存的是仓库相对路径,但 prototypeFile 允许绝对路径(插件可能在仓库外)。
const abs = path.isAbsolute(relPath) ? relPath : path.join(workspaceRoot, relPath)
const isMarkdown = abs.toLowerCase().endsWith('.md')
try {
if (isMarkdown) {
+9 -1
View File
@@ -947,12 +947,16 @@ export async function handleContinueBrainstorm(panel: KanbanWebviewPanel, issueN
// 头脑风暴只用 brainstormProfilePath;空 = DEFAULT,不回退实施 profile。
let brainstormProfilePath: string | undefined
let sessionId: string | undefined
// 工单已有原型插件时,续聊提示词里让 cc 先读它,别把已经画定的界面又讨论一遍。
let prototypeFile: string | undefined
try {
const stateObj = await panel.readIssueState(issueNumber)
if (stateObj && typeof stateObj.brainstormProfilePath === 'string' && stateObj.brainstormProfilePath.length > 0)
brainstormProfilePath = stateObj.brainstormProfilePath
if (stateObj && typeof stateObj.sessionId === 'string' && stateObj.sessionId.length > 0)
sessionId = stateObj.sessionId
if (stateObj && typeof stateObj.prototypeFile === 'string' && stateObj.prototypeFile.length > 0)
prototypeFile = stateObj.prototypeFile
}
catch (err) {
logger.add({
@@ -963,7 +967,11 @@ export async function handleContinueBrainstorm(panel: KanbanWebviewPanel, issueN
})
}
const prompt = getBrainstormContinuePrompt(panel.context, { issueNumber, issueRef: panel.refFor(issueNumber).externalId })
const prompt = getBrainstormContinuePrompt(panel.context, {
issueNumber,
issueRef: panel.refFor(issueNumber).externalId,
prototypeFile,
})
const terminalName = `issue-${issueNumber}-规划`
// 新建工单流程的 tab 叫 issue-new-{nonce}-规划,只能靠 newIssueTerminals 反查。
const linked = panel.newIssueTerminals.get(issueNumber)
+2 -1
View File
@@ -52,7 +52,7 @@ export type ExtensionToWebview
| { type: 'issues/loaded' }
| { type: 'issues/update', issues: Issue[], scope: 'mine' | 'all', globalAutoReview: boolean, youtrackConfigured: boolean, me?: string, avatars?: Record<string, string> }
| { type: 'issues/error', message: string }
| { type: 'issue/patch', issueNumber: number, patch: { autoReview?: boolean, specFile?: string, planFile?: string, prDiffFile?: string | null, sessionId?: string | null, implementSessionId?: string | null, reviewSessionId?: string | null, reviewSessionFileExists?: boolean, testSessionId?: string | null, prototypeSessionId?: string | null, pr?: string | null, implementStatus?: 'running' | 'done' | 'failed' | null, column?: IssueColumn, worktreePath?: string | null, prMerged?: boolean, prMergedAt?: string | null, branch?: string | null, color?: string, worktreeExists?: boolean, brainstormTabOpen?: boolean, implementTabOpen?: boolean, reviewTabOpen?: boolean, testTabOpen?: boolean, prototypeTabOpen?: boolean, profilePath?: string | null, brainstormProfilePath?: string | null, testProfilePath?: string | null, prototypeProfilePath?: string | null, assignees?: string[], handoffAttachmentId?: string | null, handoffFrom?: string | null } }
| { type: 'issue/patch', issueNumber: number, patch: { autoReview?: boolean, specFile?: string, planFile?: string, prototypeFile?: string, prDiffFile?: string | null, sessionId?: string | null, implementSessionId?: string | null, reviewSessionId?: string | null, reviewSessionFileExists?: boolean, testSessionId?: string | null, prototypeSessionId?: string | null, pr?: string | null, implementStatus?: 'running' | 'done' | 'failed' | null, column?: IssueColumn, worktreePath?: string | null, prMerged?: boolean, prMergedAt?: string | null, branch?: string | null, color?: string, worktreeExists?: boolean, brainstormTabOpen?: boolean, implementTabOpen?: boolean, reviewTabOpen?: boolean, testTabOpen?: boolean, prototypeTabOpen?: boolean, profilePath?: string | null, brainstormProfilePath?: string | null, testProfilePath?: string | null, prototypeProfilePath?: string | null, assignees?: string[], handoffAttachmentId?: string | null, handoffFrom?: string | null } }
/** 某个会话 id 的开 tab 请求已处理完(开成、复用或被拒都算),webview 据此停掉行内 spinner。 */
| { type: 'session/tab-settled', sessionId: string }
| { type: 'issue/pr-diff-summary-done', issueNumber: number }
@@ -203,6 +203,7 @@ export type WebviewToExtension
| { type: 'session/start-review', issueNumber: number }
| { type: 'session/start-test', issueNumber: number }
| { type: 'session/start-prototype', issueNumber: number }
| { type: 'prototype/open-in-figma', issueNumber: number, path: string }
| { type: 'editor/open-file', path: string }
| { type: 'profiles/list' }
| { type: 'issue/implement', issueNumber: number, planFile: string, profilePath?: string, sessionId?: string }
+10 -3
View File
@@ -26,7 +26,11 @@ import { normalizeReleasePrefix } from '../git/release'
*/
const FALLBACK_BRAINSTORM_PROMPT = `我现在有这样一个需求 {userRequest},你用 spx 命令创建 gitea 工单。工单 body 末尾必须包含 <!-- spx:nonce={nonce} -->。创建完工单立即停下汇报,不要擅自实施。`
const FALLBACK_BRAINSTORM_CONTINUE_PROMPT = `/ecc:grilling 讨论下 {issueNumber} 号工单。达成共识后用 ecc:spec 写 .claude/specs/<stem>.md,我确认后用 ecc:plan 出 .claude/plans/<stem>.md,两个文件在 main 上提交并用 spx issue marker 同步 marker。不要 git checkout / 不要写代码 / 不要建 PR。`
const FALLBACK_BRAINSTORM_CONTINUE_PROMPT = `/ecc:grilling 讨论下 {issueNumber} 号工单。
{prototypeRef}
达成共识后用 ecc:spec 写 .claude/specs/<stem>.md,我确认后用 ecc:plan 出 .claude/plans/<stem>.md,两个文件在 main 上提交并用 spx issue marker 同步 marker。不要 git checkout / 不要写代码 / 不要建 PR。`
const FALLBACK_IMPLEMENT_PLAN_PROMPT = `/ecc:tdd @{planFile} 按计划实施,编码派子代理,发起 PR 时在 body 中包含 "Closes #{issueNumber}"。严禁合并 PR。`
@@ -34,7 +38,9 @@ const FALLBACK_TEST_PROMPT = `/pr-acceptance-testing 验收 {issueNumber} 号工
const FALLBACK_REVIEW_PROMPT = `用 tea 拿到 #{prNumber} PR,diff 交给 ecc:code-reviewer 子代理审查。审查意见用 spx pr review-comment 发评论,body 第一行写 <!-- spx:review=1 -->。`
const FALLBACK_PROTOTYPE_PROMPT = `/ecc:figma-plugin-prototyping 给 {issueNumber} 号工单画原型:先读工单正文锁定要画的界面和状态,再写本地 Figma 插件把画板和点击流做出来。画完汇报插件路径和怎么导入,不要改业务代码。`
const FALLBACK_PROTOTYPE_PROMPT = `/ecc:figma-plugin-prototyping 给 {issueNumber} 号工单画原型:先读工单正文锁定要画的界面和状态,再写本地 Figma 插件把画板和点击流做出来。画完汇报插件路径和怎么导入,不要改业务代码。
画完用 \`opencli spx issue marker --issue {issueNumber} --type prototype --value <manifest.json 的仓库相对路径>\` 把原型插件挂到工单上,再汇报。`
type PromptName = 'brainstorm' | 'brainstorm-continue' | 'implement-plan' | 'review' | 'test' | 'prototype'
@@ -84,7 +90,8 @@ export interface Settings {
/**
* Prompt template for continuing brainstorm on an already-existing issue
* (when the user later wants to discuss / write spec/plan in the panel).
* `{issueNumber}` placeholder.
* 占位符 `{issueNumber}` / `{prototypeRef}`(后者由扩展按工单有无原型插件填,
* 无则连同所在段落一起删掉)。
*/
brainstormContinuePrompt: string
/** Prompt template for the implement-plan flow. `{planFile}` placeholder. */
+72 -69
View File
@@ -48,6 +48,38 @@ export interface PendingHook {
feature: string
}
/**
* issue body 里的 spx marker → state JSON 字段。三种 marker 走同一套同步
* 逻辑,这张表是唯一真源(与 cli 的 markerTypeToStateField 对应)。
*
* 路径必须含 `/` 且以对应后缀结尾:cc 在头脑风暴阶段会往 body 里写
* `<!-- spx:spec=... -->` 这种占位说明文,不卡死就会被当成真路径存进去。
*/
const BODY_MARKERS = [
{ type: 'spec', field: 'specFile', ext: 'md' },
{ type: 'plan', field: 'planFile', ext: 'md' },
{ type: 'prototype', field: 'prototypeFile', ext: 'json' },
] as const
/** 本次从 body 里扫出来的 marker 值,按 state JSON 字段名索引。 */
type MarkerPatch = { [K in typeof BODY_MARKERS[number]['field']]?: string }
function parseBodyMarkers(body: string): MarkerPatch {
const out: MarkerPatch = {}
for (const { type, field, ext } of BODY_MARKERS) {
const re = new RegExp(String.raw`<!--\s*spx:${type}=([^\s/>]*\/[^\s>]*\.${ext})\s*-->`)
const m = body.match(re)
if (m)
out[field] = m[1]
}
return out
}
/** 日志用的一行摘要,例如 `spec=a.md plan=<空> prototype=<空>`。 */
function describeMarkers(patch: MarkerPatch): string {
return BODY_MARKERS.map(({ type, field }) => `${type}=${patch[field] ?? '<空>'}`).join(' ')
}
/**
* A {@link PrWebhookEvent} whose `issueNumber` has been resolved (either from
* the legacy `/webhook/:n` path or via PR-body / branch heuristics).
@@ -779,11 +811,10 @@ class WebhookCoordinator {
}
/**
* Issue `edited` payload: cc updates the issue body with `<!-- spx:spec=... -->`
* / `<!-- spx:plan=... -->` annotation lines as it discovers spec/plan files.
* We scan the body for those markers, diff against the state-JSON comment,
* and (if anything changed) merge the new paths in + patch the open panel
* so the detail view refreshes without a full kanban reload.
* Issue `edited` payload: cc 会往 issue body 里追加 `<!-- spx:spec=... -->`
* / `<!-- spx:plan=... -->` / `<!-- spx:prototype=... -->` 三种 marker。
* 这里把 body 里的 marker 扫出来,与 state JSON comment 里的当前值比对,
* 有变化就合并写回,并给打开着的面板推一次 issue/patch,省掉整板刷新。
*/
private async handleIssueEdited(event: IssueWebhookEvent): Promise<void> {
if (!this.ctx)
@@ -817,17 +848,12 @@ class WebhookCoordinator {
return
}
// 路径必须含 `/` 且以 `.md` 结尾,避免 cc 写的 `<!-- spx:spec=... -->` 占位被当真。
const specMatch = event.body.match(/<!--\s*spx:spec=([^\s/>]*\/[^\s>]*\.md)\s*-->/)
const planMatch = event.body.match(/<!--\s*spx:plan=([^\s/>]*\/[^\s>]*\.md)\s*-->/)
const specFile = specMatch ? specMatch[1] : undefined
const planFile = planMatch ? planMatch[1] : undefined
if (!specFile && !planFile) {
const found = parseBodyMarkers(event.body)
if (Object.keys(found).length === 0) {
logger.add({
level: 'info',
source: 'webhook',
message: `issue=#${event.issueNumber} edited body 无 spx:spec/spx:plan 注释,跳过`,
message: `issue=#${event.issueNumber} edited body 无 spx marker 注释,跳过`,
})
return
}
@@ -852,15 +878,19 @@ class WebhookCoordinator {
})
}
const currentSpec = typeof currentState.specFile === 'string' ? currentState.specFile : undefined
const currentPlan = typeof currentState.planFile === 'string' ? currentState.planFile : undefined
// cc only adds or updates; it never deletes. Treat an absent marker
// (undefined) as "no signal", not "clear" — that way deleting a spec
// line by mistake won't lose the existing pointer.
const nextSpec = specFile ?? currentSpec
const nextPlan = planFile ?? currentPlan
if (currentSpec === nextSpec && currentPlan === nextPlan) {
// cc 只增不删:body 里没有某个 marker 当「没信号」,不当「清空」,
// 免得手滑删掉一行就把已有指针丢了。
const next: MarkerPatch = {}
let changed = false
for (const { field } of BODY_MARKERS) {
const current = typeof currentState[field] === 'string' ? currentState[field] as string : undefined
const value = found[field] ?? current
if (value)
next[field] = value
if (value !== current)
changed = true
}
if (!changed) {
// Gitea state JSON 已是最新(spx 同步写过的情况),跳过 mergeStateJsonComment
// 节省一次 API 写。但 webview 内存里可能还是旧值(webview 不轮询,全靠
// coordinator 推 issue/patch),所以**仍然要推一次 patch** 把当前值同步过去,
@@ -868,24 +898,17 @@ class WebhookCoordinator {
logger.add({
level: 'info',
source: 'webhook',
message: `issue=#${event.issueNumber} edited spec/plan 在 state JSON 已同步,跳过 merge 但推 issue/patch 刷 webview (spec=${nextSpec ?? '<空>'} plan=${nextPlan ?? '<空>'})`,
message: `issue=#${event.issueNumber} edited marker 在 state JSON 已同步,跳过 merge 但推 issue/patch 刷 webview (${describeMarkers(next)})`,
})
this.activePanel?.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch: next,
})
if (this.activePanel) {
const patch: { specFile?: string, planFile?: string } = {}
if (nextSpec)
patch.specFile = nextSpec
if (nextPlan)
patch.planFile = nextPlan
this.activePanel.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch,
})
}
return
}
// spec/plan 落库由责任人机器执行;规划阶段还没有实施终端,兜底证据
// marker 落库由责任人机器执行;规划阶段还没有实施终端,兜底证据
// 额外认规划终端。observe 机器只把新值推给本机 webview。
const ownership = await this.resolveOwnership(
event.issueNumber,
@@ -893,27 +916,14 @@ class WebhookCoordinator {
['实施', '测试', '规划'],
)
if (ownership === 'observe') {
if (this.activePanel) {
const patch: { specFile?: string, planFile?: string } = {}
if (specFile)
patch.specFile = specFile
if (planFile)
patch.planFile = planFile
this.activePanel.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch,
})
}
this.activePanel?.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch: found,
})
return
}
const extra: Record<string, unknown> = {}
if (specFile)
extra.specFile = specFile
if (planFile)
extra.planFile = planFile
try {
await mergeStateJsonComment({
host: remote.host,
@@ -921,7 +931,7 @@ class WebhookCoordinator {
repo: remote.repo,
token,
issueNumber: event.issueNumber,
extra,
extra: found,
})
}
catch (err) {
@@ -938,22 +948,15 @@ class WebhookCoordinator {
logger.add({
level: 'info',
source: 'webhook',
message: `issue=#${event.issueNumber} edited spec/plan 已同步`,
details: `spec=${specFile ?? '<未变>'} plan=${planFile ?? '<未变>'}`,
message: `issue=#${event.issueNumber} edited marker 已同步`,
details: describeMarkers(found),
})
if (this.activePanel) {
const patch: { specFile?: string, planFile?: string } = {}
if (specFile)
patch.specFile = specFile
if (planFile)
patch.planFile = planFile
this.activePanel.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch,
})
}
this.activePanel?.postMessage({
type: 'issue/patch',
issueNumber: event.issueNumber,
patch: found,
})
}
/**
+1
View File
@@ -75,6 +75,7 @@ function toIssue(baseUrl: string, it: YouTrackIssue): Issue {
prototypeProfilePath: str(state.prototypeProfilePath),
specFile: str(state.specFile),
planFile: str(state.planFile),
prototypeFile: str(state.prototypeFile),
prDiffFile: str(state.prDiffFile),
pr: str(state.pr),
branch: str(state.branch),
+1 -1
View File
@@ -20,7 +20,7 @@ import { addComment, listComments } from './api'
export const STATE_MARKER = '<!--spx-state-->'
/** Same field set as the Gitea state blob — kept independent to avoid coupling. */
const KNOWN_STATE_FIELDS = ['column', 'sessionId', 'implementSessionId', 'reviewSessionId', 'testSessionId', 'prototypeSessionId', 'profilePath', 'brainstormProfilePath', 'testProfilePath', 'prototypeProfilePath', 'specFile', 'planFile', 'prDiffFile', 'pr', 'prMerged', 'prMergedAt', 'branch', 'worktreePath', 'implementStatus', 'color', 'autoReview', 'handoffAttachmentId', 'handoffFrom'] as const
const KNOWN_STATE_FIELDS = ['column', 'sessionId', 'implementSessionId', 'reviewSessionId', 'testSessionId', 'prototypeSessionId', 'profilePath', 'brainstormProfilePath', 'testProfilePath', 'prototypeProfilePath', 'specFile', 'planFile', 'prototypeFile', 'prDiffFile', 'pr', 'prMerged', 'prMergedAt', 'branch', 'worktreePath', 'implementStatus', 'color', 'autoReview', 'handoffAttachmentId', 'handoffFrom'] as const
/**
* Parse a comment body into a state object, or null if it isn't a state