Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tag-ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ jobs:

deploy:
needs: validate
if: startsWith(github.ref, 'refs/tags/v')
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
uses: FastR-D/FastDeploy/.github/workflows/deploy.yml@9a2c51dcd63f47a0e6c8f6bb07bd22ea589abbd2
with:
app: fastfigure
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ pnpm dev

访问 `http://127.0.0.1:5178`。`pnpm build` 生成 `dist`,`pnpm preview` 在 4178 端口预览构建结果。

共享包从官方 npm registry 消费:`@fastrd/ui-foundation`、`@fastrd/ui-vue`、`@fastrd/harness-transport` 均精确锁定 `0.1.2`。安装使用 `pnpm install --frozen-lockfile --registry=https://registry.npmjs.org/`;更新锁前先用 `npm view <包名>@0.1.2 version dist --json --registry=https://registry.npmjs.org/` 确认版本、tarball 和 provenance。发布尚未可用时等待发布完成,不切换到 GitHub tarball。

## 当前功能

当前优先迭代素材、箭头和样式,新增数据绘图暂停。导出支持 SVG、PNG 和工程 JSON,draw.io / PPTX 导出相关代码已移除。
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@
"start": "bun server-dist/server.mjs"
},
"dependencies": {
"@fastrd/ui-vue": "0.1.2",
"@fastrd/ui-foundation": "0.1.2",
"@fastrd/harness-transport": "0.1.2",
"roughjs": "^4.6.6",
"svgpath": "^2.6.0",
"vue": "^3.5.44",
Expand Down
30 changes: 30 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

19 changes: 13 additions & 6 deletions server/harness/adapters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export interface HarnessAdapter {
kind: HarnessKind
status(): Promise<HarnessStatus>
send(input: HarnessTurn): Promise<string>
dispose(): void
dispose(): void | Promise<void>
}
export interface AdapterOptions { command?: string; args?: string[]; env?: NodeJS.ProcessEnv }
async function cliStatus(kind: HarnessKind, options: AdapterOptions): Promise<HarnessStatus> {
Expand All @@ -36,14 +36,14 @@ export class CodexAdapter implements HarnessAdapter {
'-c', 'features.shell_tool=false', '-c', 'features.unified_exec=false', '-c', 'features.multi_agent=false',
'-c', 'features.apps=false', '-c', 'features.plugins=false', '-c', 'features.hooks=false', '-c', 'web_search="disabled"', '-c', 'mcp_servers={}'], input.cwd, this.options.env)
this.rpc = rpc
const abortInitialization = () => this.dispose()
const abortInitialization = () => { void this.dispose().catch(() => undefined) }
input.signal.addEventListener('abort', abortInitialization, { once: true })
try {
await rpc.request('initialize', { clientInfo: { name: 'fastfigure', version: '0.2.0' } }); rpc.notify('initialized')
const started = record(await rpc.request('thread/start', { cwd: input.cwd, approvalPolicy: 'never', sandbox: 'read-only', ephemeral: true }))
this.threadId = String(record(started.thread).id ?? '')
if (!this.threadId) throw new Error('Codex 未返回会话 ID')
} catch (e) { this.dispose();input.signal.throwIfAborted(); throw e }
} catch (e) { await this.dispose();input.signal.throwIfAborted(); throw e }
finally { input.signal.removeEventListener('abort', abortInitialization) }
}
input.signal.throwIfAborted()
Expand All @@ -52,7 +52,7 @@ export class CodexAdapter implements HarnessAdapter {
let turnId = '', finished = false, finalText = ''
const deltas = new Map<string, string>(), finals = new Map<string, string>(), early: RpcMessageWithParams[] = []
const cleanup = () => { rpc.listeners.delete(handle); rpc.exits.delete(fail); input.signal.removeEventListener('abort', abort) }
const fail = (error: Error) => { if (finished) return; finished = true; cleanup(); this.dispose(); reject(error) }
const fail = (error: Error) => { if (finished) return; finished = true; cleanup(); reject(error) }
const finish = () => { if (finished) return; finished = true; cleanup(); resolve(finalText || [...finals.values()].at(-1) || [...deltas.values()].at(-1) || '') }
const abort = () => {
if (turnId) void rpc.request('turn/interrupt', { threadId: this.threadId, turnId }).catch(() => undefined)
Expand Down Expand Up @@ -94,9 +94,16 @@ export class CodexAdapter implements HarnessAdapter {
if (!turnId) { fail(new Error('Codex 未返回运行 ID')); return }
for (const event of early) handle(event)
}, fail)
})
}).catch(async error => { await this.dispose(); throw error })
}
async dispose(): Promise<void> {
const rpc = this.rpc
this.threadId = ''
if (rpc) {
await rpc.dispose()
if (this.rpc === rpc) this.rpc = undefined
}
}
dispose() { const rpc = this.rpc; this.rpc = undefined; this.threadId = ''; rpc?.dispose() }
}
interface RpcMessageWithParams { method?: string; params: Record<string, unknown> }

Expand Down
56 changes: 56 additions & 0 deletions server/harness/fixtures/transport.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { createInterface } from 'node:readline'
import { writeFileSync } from 'node:fs'
import process from 'node:process'
import { Buffer } from 'node:buffer'

writeFileSync(process.env.FASTFIGURE_TRANSPORT_PID, String(process.pid))
const send = value => process.stdout.write(JSON.stringify(value) + '\n')
const scenario = process.env.FASTFIGURE_TRANSPORT_SCENARIO
const image = process.env.FASTFIGURE_TRANSPORT_IMAGE === '1'
const threadId = 'transport-thread', turnId = 'transport-turn'
let turnRequest
createInterface({ input: process.stdin }).on('line', line => {
const m = JSON.parse(line)
if (m.method === 'initialize') {
if (scenario === 'null') { send(null); return }
if (scenario === 'invalid') { process.stdout.write('{bad\n'); return }
if (scenario === 'frame') { send({ method: 42 }); return }
if (scenario === 'exit') process.exit(9)
if (scenario === 'stall') return
send({ id: m.id, result: {} })
}
if (m.method === 'thread/start') {
if (m.params.sandbox !== (image ? 'workspace-write' : 'read-only') || m.params.approvalPolicy !== 'never' || m.params.ephemeral !== true) process.exit(10)
const args = process.argv.slice(2)
for (const flag of ['features.shell_tool=false','features.unified_exec=false','features.multi_agent=false','features.apps=false','features.plugins=false','features.hooks=false','web_search="disabled"','mcp_servers={}']) if (!args.includes(flag)) process.exit(11)
if (image && !args.includes('image_generation')) process.exit(16)
send({ id: m.id, result: { thread: { id: threadId } } })
}
if (m.method === 'turn/start') {
const policy = m.params.sandboxPolicy
if (policy.type !== (image ? 'workspaceWrite' : 'readOnly') || m.params.approvalPolicy !== 'never') process.exit(12)
if (image && (policy.networkAccess !== false || policy.excludeSlashTmp !== true || policy.excludeTmpdirEnvVar !== true || JSON.stringify(policy.writableRoots) !== JSON.stringify([process.cwd()]))) process.exit(17)
writeFileSync(process.env.FASTFIGURE_TRANSPORT_PID + '.turn', 'started')
if (scenario === 'turn-stall') return
turnRequest = m.id
send({ id: 'approval-command', method: 'item/commandExecution/requestApproval', params: { threadId } })
}
if (m.id === 'approval-command') {
if (m.result?.decision !== 'decline') process.exit(13)
send({ id: 'approval-files', method: 'item/fileChange/requestApproval', params: { threadId } })
}
if (m.id === 'approval-files') {
if (m.result?.decision !== 'decline') process.exit(14)
send({ id: 'tool', method: 'host/unexpectedTool', params: { threadId } })
}
if (m.id === 'tool') {
if (m.error?.code !== -32601) process.exit(15)
send({ id: turnRequest, result: { turn: { id: turnId } } })
if (image) {
send({ method: 'item/completed', params: { threadId, turnId, item: { type: 'imageGeneration', status: 'completed', result: Buffer.alloc(1_600_000, 1).toString('base64') } } })
return
}
send({ method: 'item/agentMessage/delta', params: { threadId, turnId, itemId: 'reply', delta: 'permissions retained' } })
send({ method: 'turn/completed', params: { threadId, turn: { id: turnId, status: 'completed' } } })
}
})
2 changes: 1 addition & 1 deletion server/harness/harness.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const fixture = fileURLToPath(new URL('./fixtures/cli.mjs', import.meta.url))
const options = (scenario = 'proposal', log?: string): AdapterOptions => ({ command: process.execPath, args: [fixture], env: { ...process.env, FASTFIGURE_TEST_SCENARIO: scenario, ...(log ? { FASTFIGURE_TEST_LOG: log } : {}) } })
const adapters: HarnessAdapter[] = [], services: HarnessService[] = [], servers: Server[] = [], dirs: string[] = []
afterEach(async () => {
adapters.splice(0).forEach(a => a.dispose())
await Promise.all(adapters.splice(0).map(a => a.dispose()))
await Promise.all(services.splice(0).map(s => s.dispose()))
await Promise.all(servers.splice(0).map(s => new Promise<void>(resolve => { s.closeAllConnections(); s.close(() => resolve()) })))
await Promise.all(dirs.splice(0).map(d => rm(d, { recursive: true, force: true })))
Expand Down
2 changes: 1 addition & 1 deletion server/harness/repairPlans.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ describe('repair plans',()=>{
const history=service.history(session.id);expect(history.turns).toHaveLength(50);expect(history.omitted).toBe(3)
expect(history.turns.find(t=>t.id===initial.id)).toMatchObject({ordinal:1,available:true,review:'pending'});expect(history.turns.at(-1)?.ordinal).toBe(53)
expect(service.getRun(initial.id).status).toBe('completed');expect(history.turns.filter(t=>t.available).length).toBeLessThanOrEqual(20)
},15_000)
},60_000)
it('retains the selected parent after an unchanged plan while other sessions evict old snapshots',async()=>{
const {service,input,initial,session}=await setup('slow'),job=service.startPlan({...input,content:'RECONSTRUCTION_NO_CHANGE'}),other=service.createSession('codex','Other work')
for(let i=0;i<24;i++){const run=service.start({sessionId:other.id,figure:createExample(),content:`Other ${i}`,selectedIds:[]});await run.done}
Expand Down
85 changes: 25 additions & 60 deletions server/harness/rpc.ts
Original file line number Diff line number Diff line change
@@ -1,69 +1,34 @@
import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'
export interface RpcMessage { id?: number | string; method?: string; params?: unknown; result?: unknown; error?: { message?: string } }
import { JsonlRpcClient, type RpcMessage } from '@fastrd/harness-transport'

export const record = (value: unknown): Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}

/** JSONL RPC based on FastPPT's app-server bridge, with bounded records and explicit process cleanup. */
/** Figure host policy, used by suggestions and image drafts. Wire/process ownership is in transport. */
export class JsonlRpc {
readonly child: ChildProcessWithoutNullStreams
readonly listeners = new Set<(message: RpcMessage) => void>()
readonly exits = new Set<(error: Error) => void>()
private pending = new Map<number, { resolve: (value: unknown) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>()
private sequence = 0
private closed = false
constructor(command: string, args: string[], cwd: string, env = process.env, maxRecordBytes=2_000_000) {
this.child = spawn(command, args, { cwd, env, stdio: 'pipe', windowsHide: true })
let buffer = ''
this.child.stdout.setEncoding('utf8')
this.child.stdout.on('data', (chunk: string) => {
buffer += chunk
if (buffer.length > maxRecordBytes) { this.fail(new Error('Harness 协议记录超出限制')); this.dispose(); return }
let newline: number
while ((newline = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, newline); buffer = buffer.slice(newline + 1)
if (!line.trim()) continue
let message: RpcMessage
try { message = JSON.parse(line) as RpcMessage } catch { this.fail(new Error('Harness 返回了无效的 JSONL')); this.dispose(); return }
if (message.method) {
if (message.id !== undefined) {
// This integration produces structured suggestions; it has no interactive host tools.
this.write({ id: message.id, ...(message.method.endsWith('requestApproval') ? { result: { decision: 'decline' } } : { error: { code: -32601, message: 'FastFigure does not expose this host capability' } }) })
} else for (const listener of this.listeners) listener(message)
} else if (typeof message.id === 'number') {
const pending = this.pending.get(message.id)
if (!pending) continue
this.pending.delete(message.id); clearTimeout(pending.timer)
if (message.error) pending.reject(new Error(message.error.message || 'Harness RPC 失败'))
else pending.resolve(message.result)
}
}
})
// Drain stderr without returning local configuration or credentials to the browser.
this.child.stderr.resume()
this.child.stdin.on('error', error => this.fail(error))
this.child.once('error', error => this.fail(error))
this.child.once('exit', code => this.fail(new Error(`Harness 进程已退出 (${code})`)))
}
private write(message: unknown) { if (!this.closed) this.child.stdin.write(`${JSON.stringify(message)}\n`) }
request(method: string, params: unknown): Promise<unknown> {
if (this.closed) return Promise.reject(new Error('Harness 连接已关闭'))
const id = ++this.sequence
return new Promise((resolve, reject) => {
const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`Harness 请求超时:${method}`)) }, 30_000)
this.pending.set(id, { resolve, reject, timer }); this.write({ id, method, params })
private readonly rpc: JsonlRpcClient
private disposal?: Promise<void>

constructor(command: string, args: string[], cwd: string, env = process.env, maxRecordBytes = 2_000_000) {
this.rpc = new JsonlRpcClient({ commandFactory: () => ({ command, args, cwd, env }),
maxRecordBytes, maxStderrLines: 0, stopTimeoutMs: 1000 })
this.rpc.onMessage(message => {
if (message.id !== undefined && message.method) {
// Both Figure entry points forbid interactive host tools and approvals.
if (message.method.endsWith('requestApproval')) this.rpc.respond(message.id, { decision: 'decline' })
else this.rpc.respondError(message.id, -32601, 'FastFigure does not expose this host capability')
} else if (message.method) for (const listener of this.listeners) listener(message)
})
this.rpc.onExit(error => { for (const listener of this.exits) listener(error) })
this.rpc.start()
}
notify(method: string, params: unknown = {}) { this.write({ method, params }) }
private fail(error: Error) {
if (this.closed) return
this.closed = true
for (const item of this.pending.values()) { clearTimeout(item.timer); item.reject(error) }
this.pending.clear()
for (const listener of this.exits) listener(error)
}
dispose() {
this.fail(new Error('Harness 连接已关闭'))
this.child.kill('SIGTERM')
const timer = setTimeout(() => { if (this.child.exitCode === null) this.child.kill('SIGKILL') }, 1000)
timer.unref(); this.child.once('exit', () => clearTimeout(timer))
request(method: string, params: unknown): Promise<unknown> { return this.rpc.request(method, params) }
notify(method: string, params: unknown = {}): void { this.rpc.notify(method, params) }
dispose(): Promise<void> {
if (!this.disposal) {
this.disposal = this.rpc.stop()
for (const listener of this.exits) listener(new Error('Harness 连接已关闭'))
}
return this.disposal
}
}
Loading
Loading