dsh-plugin-inspiration-workbench 0.9.0 → 0.13.2
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/README.md +27 -1
- package/lib/client.js +4191 -185
- package/lib/client.js.map +4 -4
- package/package.json +8 -2
- package/src/client/board.js +500 -30
- package/src/client/card-tools.js +1 -0
- package/src/client/docx-text.js +93 -0
- package/src/client/file-preview.js +103 -0
- package/src/client/file-store.js +74 -0
- package/src/client/flow-recorder.js +58 -0
- package/src/client/index.jsx +3 -4
- package/src/client/persistence.js +31 -0
- package/src/client/popovers.js +2 -2
- package/src/client/render.js +1 -0
- package/src/client/sessions.js +91 -11
- package/src/client/styles.css +116 -2
- package/src/client/task-ai.js +83 -0
- package/src/client/task-controller.js +620 -0
- package/src/client/task-intelligence.js +545 -0
- package/src/client/task-model.js +264 -0
- package/src/client/task-store.js +118 -0
- package/src/client/task-view.css +1263 -0
- package/src/client/task-view.js +1688 -0
- package/src/host/index.js +69 -7
|
@@ -0,0 +1,620 @@
|
|
|
1
|
+
import { normalizeTask, sortTasks } from './task-model.js';
|
|
2
|
+
import {
|
|
3
|
+
parseAIResponse,
|
|
4
|
+
normalizeTopologyPlan,
|
|
5
|
+
validateTopologyPlan,
|
|
6
|
+
createLocalTaskDraft,
|
|
7
|
+
createFallbackTopology,
|
|
8
|
+
computeLayeredLayout,
|
|
9
|
+
} from './task-intelligence.js';
|
|
10
|
+
import { runTaskAnalysis, assistantTextFromView } from './task-ai.js';
|
|
11
|
+
|
|
12
|
+
function hashText(value) {
|
|
13
|
+
let hash = 2166136261;
|
|
14
|
+
for (const char of String(value || '')) {
|
|
15
|
+
hash ^= char.codePointAt(0);
|
|
16
|
+
hash = Math.imul(hash, 16777619);
|
|
17
|
+
}
|
|
18
|
+
return (hash >>> 0).toString(36);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
function asArray(value) {
|
|
22
|
+
return Array.isArray(value) ? value : [];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function text(value, fallback = '') {
|
|
26
|
+
return typeof value === 'string' && value.trim() ? value.trim() : fallback;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function runtimeExecution(view) {
|
|
30
|
+
return {
|
|
31
|
+
running: Boolean(view?.running),
|
|
32
|
+
waiting: view?.waiting || '',
|
|
33
|
+
error: view?.error || view?.lastError || false,
|
|
34
|
+
done: Boolean(view?.ready && !view?.running && (view?.items || []).length),
|
|
35
|
+
activityAt: Date.now(),
|
|
36
|
+
};
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function createTaskController({ adapter, taskStore, flow, t, toast, bridge }) {
|
|
40
|
+
const liveRuntime = new Map();
|
|
41
|
+
const runtimeSignatures = new Map();
|
|
42
|
+
let runtimeSaveTimer = 0;
|
|
43
|
+
|
|
44
|
+
function rawTasks() {
|
|
45
|
+
return taskStore.snapshot().tasks;
|
|
46
|
+
}
|
|
47
|
+
function listWorkspaces() {
|
|
48
|
+
return adapter.listWorkspaces?.() || [];
|
|
49
|
+
}
|
|
50
|
+
function defaultWorkspaceId() {
|
|
51
|
+
const workspaces = listWorkspaces();
|
|
52
|
+
const currentTitle = bridge.getCards().find((card) => card.workspace)?.workspace;
|
|
53
|
+
const current = workspaces.find((workspace) => workspace.title === currentTitle);
|
|
54
|
+
return current?.id || workspaces[0]?.id || '';
|
|
55
|
+
}
|
|
56
|
+
function requireWorkspaceId() {
|
|
57
|
+
const workspaceId = defaultWorkspaceId();
|
|
58
|
+
if (!workspaceId) throw new Error('当前没有可用工作区,请先在 DSH 中添加工作区,再创建会话');
|
|
59
|
+
return workspaceId;
|
|
60
|
+
}
|
|
61
|
+
function canvases() {
|
|
62
|
+
return bridge.getCanvases() || [];
|
|
63
|
+
}
|
|
64
|
+
function taskById(id) {
|
|
65
|
+
return rawTasks().find((task) => task.id === id);
|
|
66
|
+
}
|
|
67
|
+
function canvasNames(ids) {
|
|
68
|
+
return asArray(ids).map((id) => canvases().find((canvas) => canvas.id === id)?.name).filter(Boolean);
|
|
69
|
+
}
|
|
70
|
+
function sessionRuntime(sessionId) {
|
|
71
|
+
return liveRuntime.get(sessionId) || {};
|
|
72
|
+
}
|
|
73
|
+
function allRuntime(task) {
|
|
74
|
+
return {
|
|
75
|
+
...(task.sessionStates || {}),
|
|
76
|
+
...Object.fromEntries((task.sessionIds || []).filter((id) => liveRuntime.has(id)).map((id) => [id, sessionRuntime(id)])),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
function executionFor(task) {
|
|
80
|
+
const states = Object.values(allRuntime(task));
|
|
81
|
+
if (states.some((state) => state.waiting)) return 'needs_input';
|
|
82
|
+
if (states.some((state) => state.error)) return 'blocked';
|
|
83
|
+
if (states.some((state) => state.running)) return 'running';
|
|
84
|
+
const relatedEvents = [...flow.latestByEdge().values()].filter((event) => event.taskId === task.id || (task.canvasIds || []).includes(event.canvasId));
|
|
85
|
+
if (relatedEvents.some((event) => event.status === 'failed')) return 'blocked';
|
|
86
|
+
if (relatedEvents.some((event) => event.status === 'delivering')) return 'running';
|
|
87
|
+
if (states.length && states.every((state) => state.done)) return 'done';
|
|
88
|
+
return task.executionStatus || 'idle';
|
|
89
|
+
}
|
|
90
|
+
function acceptanceFor(task) {
|
|
91
|
+
if (task.acceptanceStatus) return task.acceptanceStatus;
|
|
92
|
+
if (task.reviewStatus === 'accepted') return 'accepted';
|
|
93
|
+
if (task.reviewStatus === 'rejected') return 'rejected';
|
|
94
|
+
if (task.reviewStatus === 'review' || task.reviewStatus === 'pending') return 'review';
|
|
95
|
+
return 'pending';
|
|
96
|
+
}
|
|
97
|
+
function projectNodes(task) {
|
|
98
|
+
const runtime = allRuntime(task);
|
|
99
|
+
const planNodes = Array.isArray(task.plan?.nodes) ? task.plan.nodes : [];
|
|
100
|
+
if (!planNodes.length) {
|
|
101
|
+
return (task.sessionIds || []).map((sessionId, index) => ({
|
|
102
|
+
id: sessionId,
|
|
103
|
+
kind: 'session',
|
|
104
|
+
title: adapter.titleOf(sessionId) || '节点 ' + (index + 1),
|
|
105
|
+
sessionId,
|
|
106
|
+
status: runtimeExecution(runtime[sessionId] || {}).done ? 'done' : runtimeExecution(runtime[sessionId] || {}).running ? 'running' : runtimeExecution(runtime[sessionId] || {}).waiting ? 'needs_input' : runtimeExecution(runtime[sessionId] || {}).error ? 'blocked' : 'idle',
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
return planNodes.map((node, index) => {
|
|
110
|
+
if (node.kind === 'note') {
|
|
111
|
+
const targetId = node.cardId || node.id;
|
|
112
|
+
const event = [...flow.latestByEdge().values()]
|
|
113
|
+
.filter((item) => item.targetKind === 'note' && item.targetId === targetId)
|
|
114
|
+
.sort((left, right) => right.at - left.at)[0];
|
|
115
|
+
return {
|
|
116
|
+
id: node.id,
|
|
117
|
+
kind: 'note',
|
|
118
|
+
title: node.title || '结果便签',
|
|
119
|
+
cardId: node.cardId,
|
|
120
|
+
status: event?.status === 'failed' ? 'blocked' : event?.status === 'delivering' ? 'running' : event?.status === 'delivered' ? 'done' : 'idle',
|
|
121
|
+
activityAt: event?.at || 0,
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
const sessionId = node.sessionId || task.sessionIds?.[index] || '';
|
|
125
|
+
const state = runtime[sessionId] || {};
|
|
126
|
+
return {
|
|
127
|
+
id: node.id,
|
|
128
|
+
kind: 'session',
|
|
129
|
+
title: node.title || adapter.titleOf(sessionId) || '节点 ' + (index + 1),
|
|
130
|
+
sessionId,
|
|
131
|
+
dependsOn: node.dependsOn || [],
|
|
132
|
+
status: state.waiting ? 'needs_input' : state.error ? 'blocked' : state.running ? 'running' : state.done ? 'done' : 'idle',
|
|
133
|
+
activityAt: state.activityAt || 0,
|
|
134
|
+
};
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function projectTask(task) {
|
|
139
|
+
const executionStatus = executionFor(task);
|
|
140
|
+
const acceptanceStatus = acceptanceFor(task);
|
|
141
|
+
const normalized = normalizeTask({ ...task, executionStatus, acceptanceStatus });
|
|
142
|
+
const events = flow.events().filter((event) =>
|
|
143
|
+
event.taskId === task.id ||
|
|
144
|
+
(task.canvasIds || []).includes(event.canvasId) ||
|
|
145
|
+
(task.sessionIds || []).includes(event.sourceSessionId)
|
|
146
|
+
);
|
|
147
|
+
return {
|
|
148
|
+
...task,
|
|
149
|
+
executionStatus,
|
|
150
|
+
acceptanceStatus,
|
|
151
|
+
reviewStatus: acceptanceStatus,
|
|
152
|
+
status: normalized.status,
|
|
153
|
+
canvasNames: canvasNames(task.canvasIds),
|
|
154
|
+
events,
|
|
155
|
+
pending: asArray(task.pending),
|
|
156
|
+
sessionIds: asArray(task.sessionIds),
|
|
157
|
+
canvasIds: asArray(task.canvasIds),
|
|
158
|
+
acceptanceCriteria: asArray(task.acceptanceCriteria),
|
|
159
|
+
deliverables: asArray(task.deliverables),
|
|
160
|
+
nodes: projectNodes(task),
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
function snapshot() {
|
|
164
|
+
return {
|
|
165
|
+
tasks: sortTasks(rawTasks().map(projectTask)),
|
|
166
|
+
canvases: canvases(),
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function noteSessionRuntime(card) {
|
|
171
|
+
if (!card?.sessionId) return;
|
|
172
|
+
const runtime = {
|
|
173
|
+
running: Boolean(card.running),
|
|
174
|
+
waiting: card.waiting || '',
|
|
175
|
+
error: card.view?.lastError || ['error', 'failure'].includes((card.view?.items || []).at(-1)?.k) || false,
|
|
176
|
+
done: Boolean(card.view?.ready && !card.running && (card.view?.items || []).length),
|
|
177
|
+
activityAt: card.activityAt || Date.now(),
|
|
178
|
+
};
|
|
179
|
+
const signature = JSON.stringify(runtime);
|
|
180
|
+
if (runtimeSignatures.get(card.sessionId) === signature) return;
|
|
181
|
+
runtimeSignatures.set(card.sessionId, signature);
|
|
182
|
+
liveRuntime.set(card.sessionId, runtime);
|
|
183
|
+
clearTimeout(runtimeSaveTimer);
|
|
184
|
+
runtimeSaveTimer = setTimeout(() => {
|
|
185
|
+
const next = rawTasks().map((task) => {
|
|
186
|
+
if (!(task.sessionIds || []).includes(card.sessionId)) return task;
|
|
187
|
+
return { ...task, sessionStates: { ...(task.sessionStates || {}), [card.sessionId]: runtime } };
|
|
188
|
+
});
|
|
189
|
+
taskStore.setTasks(next);
|
|
190
|
+
}, 650);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function canvasIdsForSession(sessionId) {
|
|
194
|
+
const ids = [];
|
|
195
|
+
for (const canvas of canvases()) {
|
|
196
|
+
const cards = Array.isArray(canvas.layout?.cards) ? canvas.layout.cards : [];
|
|
197
|
+
if (cards.some((card) => card.sessionId === sessionId)) ids.push(canvas.id);
|
|
198
|
+
}
|
|
199
|
+
const current = bridge.getActiveCanvas();
|
|
200
|
+
if (current && bridge.getCards().some((card) => card.sessionId === sessionId) && !ids.includes(current)) ids.push(current);
|
|
201
|
+
return ids;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
async function listSessions() {
|
|
205
|
+
const recent = adapter.listRecentSessions?.(30) || [];
|
|
206
|
+
const byId = new Map(recent.map((row) => [row.sessionId, row]));
|
|
207
|
+
for (const card of bridge.getCards()) {
|
|
208
|
+
if (!card.sessionId) continue;
|
|
209
|
+
byId.set(card.sessionId, {
|
|
210
|
+
sessionId: card.sessionId,
|
|
211
|
+
title: card.title || adapter.titleOf(card.sessionId) || '未命名会话',
|
|
212
|
+
activityAt: card.activityAt || Date.now(),
|
|
213
|
+
workspace: card.workspace || adapter.workspaceOf?.(card.sessionId)?.title || '',
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return [...byId.values()].map((row) => ({
|
|
217
|
+
...row,
|
|
218
|
+
id: row.sessionId,
|
|
219
|
+
displayTitle: row.title,
|
|
220
|
+
workspaceName: row.workspace,
|
|
221
|
+
updatedAt: row.activityAt,
|
|
222
|
+
canvasIds: canvasIdsForSession(row.sessionId),
|
|
223
|
+
}));
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
async function inspectSessions(sessionIds) {
|
|
227
|
+
const selected = [...new Set(sessionIds)].slice(0, 12);
|
|
228
|
+
const sessions = await listSessions();
|
|
229
|
+
const inspections = [];
|
|
230
|
+
for (const sessionId of selected) {
|
|
231
|
+
const meta = sessions.find((row) => row.sessionId === sessionId) || { sessionId, title: adapter.titleOf(sessionId) || '未命名会话' };
|
|
232
|
+
const existing = bridge.getCards().find((card) => card.sessionId === sessionId);
|
|
233
|
+
let view = existing?.view;
|
|
234
|
+
let stop;
|
|
235
|
+
if (!view) {
|
|
236
|
+
stop = adapter.open(sessionId, () => {});
|
|
237
|
+
try {
|
|
238
|
+
if (adapter.waitForReady) await adapter.waitForReady(sessionId, { timeoutMs: 12000 });
|
|
239
|
+
view = adapter.read(sessionId);
|
|
240
|
+
} finally {
|
|
241
|
+
stop?.();
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
const items = (view?.items || []).filter((item) => item.text && ['user', 'assistant', 'error', 'failure'].includes(item.k)).slice(-12);
|
|
245
|
+
const measuredRuntime = runtimeExecution(view);
|
|
246
|
+
const runtime = existing ? { ...measuredRuntime, ...sessionRuntime(sessionId) } : measuredRuntime;
|
|
247
|
+
liveRuntime.set(sessionId, runtime);
|
|
248
|
+
inspections.push({
|
|
249
|
+
...meta,
|
|
250
|
+
canvasIds: canvasIdsForSession(sessionId),
|
|
251
|
+
runtime,
|
|
252
|
+
lastAssistant: assistantTextFromView(view).slice(0, 3000),
|
|
253
|
+
transcript: items.map((item) => ({ role: item.k, text: String(item.text).slice(0, 1600) })),
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
return inspections;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function localTaskDrafts(inspections) {
|
|
260
|
+
const groups = new Map();
|
|
261
|
+
for (const inspection of inspections) {
|
|
262
|
+
const canvasId = inspection.canvasIds?.[0] || '';
|
|
263
|
+
const canvas = canvases().find((item) => item.id === canvasId);
|
|
264
|
+
const key = canvasId || 'workspace:' + (inspection.workspace || '未分组');
|
|
265
|
+
if (!groups.has(key)) groups.set(key, { key, canvas, sessions: [] });
|
|
266
|
+
groups.get(key).sessions.push(inspection);
|
|
267
|
+
}
|
|
268
|
+
const now = Date.now();
|
|
269
|
+
return [...groups.values()].map((group) => {
|
|
270
|
+
const ids = group.sessions.map((item) => item.sessionId);
|
|
271
|
+
const states = group.sessions.map((item) => item.runtime);
|
|
272
|
+
const executionStatus = states.some((state) => state.waiting) ? 'needs_input'
|
|
273
|
+
: states.some((state) => state.error) ? 'blocked'
|
|
274
|
+
: states.some((state) => state.running) ? 'running'
|
|
275
|
+
: states.every((state) => state.done) ? 'done' : 'idle';
|
|
276
|
+
const title = group.canvas?.name || group.sessions[0].workspace || group.sessions[0].title || '会话任务';
|
|
277
|
+
const pending = group.sessions.filter((item) => item.runtime.waiting || item.runtime.error)
|
|
278
|
+
.map((item) => (item.runtime.error ? '执行失败:' : '等待处理:') + item.title);
|
|
279
|
+
const canvasLayout = group.canvas?.layout?.cards || [];
|
|
280
|
+
return {
|
|
281
|
+
id: 'draft-' + hashText(group.key + ids.join(',')),
|
|
282
|
+
title,
|
|
283
|
+
goal: group.canvas?.goal || '',
|
|
284
|
+
summary: group.sessions.find((item) => item.lastAssistant)?.lastAssistant?.slice(0, 500)
|
|
285
|
+
|| ids.length + ' 个关联会话,等待进一步整理。',
|
|
286
|
+
executionStatus,
|
|
287
|
+
acceptanceStatus: executionStatus === 'done' ? 'review' : 'pending',
|
|
288
|
+
priority: pending.length ? 'high' : 'normal',
|
|
289
|
+
sessionIds: ids,
|
|
290
|
+
canvasIds: group.canvas ? [group.canvas.id] : [],
|
|
291
|
+
pending,
|
|
292
|
+
acceptanceCriteria: [],
|
|
293
|
+
deliverables: group.sessions.filter((item) => item.lastAssistant).map((item) => ({
|
|
294
|
+
id: 'message-' + item.sessionId,
|
|
295
|
+
kind: 'message',
|
|
296
|
+
title: item.title + ' 的最新回复',
|
|
297
|
+
sessionId: item.sessionId,
|
|
298
|
+
})),
|
|
299
|
+
sessionStates: Object.fromEntries(group.sessions.map((item) => [item.sessionId, item.runtime])),
|
|
300
|
+
plan: createLocalTaskDraft({ cards: canvasLayout, sessions: group.sessions, title }),
|
|
301
|
+
source: 'scan',
|
|
302
|
+
createdAt: now,
|
|
303
|
+
updatedAt: now,
|
|
304
|
+
};
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function aiTaskDrafts(parsed, inspections) {
|
|
309
|
+
const candidates = asArray(parsed?.tasks).length ? parsed.tasks : [parsed];
|
|
310
|
+
const selectedIds = new Set(inspections.map((item) => item.sessionId));
|
|
311
|
+
const localBySession = new Map(inspections.map((item) => [item.sessionId, item]));
|
|
312
|
+
const drafts = [];
|
|
313
|
+
for (const raw of candidates) {
|
|
314
|
+
if (!raw || typeof raw !== 'object') continue;
|
|
315
|
+
const ids = asArray(raw.sessionIds || raw.sessions).map(String).filter((id) => selectedIds.has(id));
|
|
316
|
+
if (!ids.length) continue;
|
|
317
|
+
const related = ids.map((id) => localBySession.get(id));
|
|
318
|
+
const canvasIds = [...new Set(related.flatMap((item) => item.canvasIds || []))];
|
|
319
|
+
const runtime = localTaskDrafts(related)[0];
|
|
320
|
+
drafts.push({
|
|
321
|
+
...runtime,
|
|
322
|
+
id: 'draft-' + hashText((raw.title || 'task') + ids.join(',')),
|
|
323
|
+
title: text(raw.title, runtime.title),
|
|
324
|
+
goal: text(raw.goal || raw.objective),
|
|
325
|
+
summary: text(raw.summary || raw.description, runtime.summary),
|
|
326
|
+
pending: asArray(raw.pending || raw.todos).map(String),
|
|
327
|
+
acceptanceCriteria: asArray(raw.acceptanceCriteria || raw.acceptance).map(String),
|
|
328
|
+
priority: ['high', 'normal', 'low'].includes(raw.priority) ? raw.priority : runtime.priority,
|
|
329
|
+
canvasIds,
|
|
330
|
+
sessionIds: ids,
|
|
331
|
+
source: 'scan-ai',
|
|
332
|
+
});
|
|
333
|
+
}
|
|
334
|
+
return drafts;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function listModels() {
|
|
338
|
+
const catalog = await adapter.modelCatalog();
|
|
339
|
+
const models = [];
|
|
340
|
+
for (const group of catalog?.groups || []) {
|
|
341
|
+
for (const model of group.models || []) {
|
|
342
|
+
models.push({
|
|
343
|
+
id: model.id,
|
|
344
|
+
provider: model.provider || group.id,
|
|
345
|
+
name: model.name || model.id,
|
|
346
|
+
reasoningEffort: model.reasoning?.defaultEffort,
|
|
347
|
+
});
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
const firstSession = bridge.getCards().find((card) => card.sessionId)?.sessionId;
|
|
351
|
+
const selected = firstSession ? adapter.selectionOf?.(firstSession) : null;
|
|
352
|
+
const fallback = selected || models[0] || null;
|
|
353
|
+
const defaultModel = fallback ? { model: fallback.model || fallback.id, provider: fallback.provider } : null;
|
|
354
|
+
return { models, defaultModel };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
async function scan({ sessionIds, useAI, model }) {
|
|
358
|
+
const inspections = await inspectSessions(sessionIds);
|
|
359
|
+
if (!inspections.length) return [];
|
|
360
|
+
const local = localTaskDrafts(inspections);
|
|
361
|
+
if (!useAI) return local;
|
|
362
|
+
const prompt = [
|
|
363
|
+
'你是任务整理助手。根据给定的真实 DSH 会话,归纳任务目标、当前进展和待办。',
|
|
364
|
+
'只输出 JSON:{"tasks":[{"title":"...","goal":"...","summary":"...","sessionIds":["..."],"pending":["..."],"acceptanceCriteria":["..."],"priority":"high|normal|low"}]}。',
|
|
365
|
+
'相同目标的会话应合并,不得创造会话中不存在的交付物,不得改写 sessionIds。状态由本地系统计算,不需要你判断。',
|
|
366
|
+
'会话数据:' + JSON.stringify(inspections),
|
|
367
|
+
].join('\n');
|
|
368
|
+
const workspaceId = adapter.listWorkspaces?.().find((workspace) => workspace.title === inspections[0].workspace)?.id || defaultWorkspaceId();
|
|
369
|
+
const result = await runTaskAnalysis({ adapter, prompt, workspaceId });
|
|
370
|
+
const parsed = parseAIResponse(result.text);
|
|
371
|
+
const drafts = aiTaskDrafts(parsed, inspections);
|
|
372
|
+
if (!drafts.length) {
|
|
373
|
+
toast('AI 没有返回可关联的任务,已保留本地整理草案');
|
|
374
|
+
return local;
|
|
375
|
+
}
|
|
376
|
+
return drafts;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function plan({ requirement, workspaceId, useAI, model }) {
|
|
380
|
+
const goal = String(requirement || '').trim();
|
|
381
|
+
if (!goal) throw new Error('先写下你想完成的事情');
|
|
382
|
+
if (!useAI) {
|
|
383
|
+
const fallback = createFallbackTopology({ goal, title: goal.slice(0, 60) });
|
|
384
|
+
fallback.workspaceId = workspaceId || defaultWorkspaceId();
|
|
385
|
+
fallback.acceptanceCriteria = ['结果可验证,并汇总到结果便签'];
|
|
386
|
+
return fallback;
|
|
387
|
+
}
|
|
388
|
+
const prompt = [
|
|
389
|
+
'你是多 Agent 工作流规划助手。把用户需求拆成 2-4 个可执行节点。',
|
|
390
|
+
'只输出 JSON:{"title":"...","goal":"...","acceptanceCriteria":["..."],"nodes":[{"id":"research","kind":"session","title":"...","prompt":"...","dependsOn":[]},{"id":"delivery","kind":"note","title":"结果汇总","note":"# 结果汇总","dependsOn":["research"]}]}。',
|
|
391
|
+
'session 节点必须是真实可执行工作,note 节点只能做最终或中间结果汇点,不能有下游。dependsOn 填上游节点 id。每个 session 的 prompt 要包含目标、输入和期望输出。',
|
|
392
|
+
'用户需求:' + goal,
|
|
393
|
+
].join('\n');
|
|
394
|
+
const result = await runTaskAnalysis({ adapter, prompt, workspaceId: workspaceId || defaultWorkspaceId(), selection: model });
|
|
395
|
+
const parsed = parseAIResponse(result.text);
|
|
396
|
+
const candidate = parsed.plan || parsed.topology || parsed;
|
|
397
|
+
const normalized = normalizeTopologyPlan(candidate);
|
|
398
|
+
const validation = validateTopologyPlan(normalized);
|
|
399
|
+
if (!validation.valid) throw new Error(validation.errors.map((error) => error.message).join(';'));
|
|
400
|
+
normalized.acceptanceCriteria = asArray(candidate.acceptanceCriteria || candidate.acceptance).map(String);
|
|
401
|
+
normalized.workspaceId = workspaceId || defaultWorkspaceId();
|
|
402
|
+
const rawNodes = asArray(candidate.nodes);
|
|
403
|
+
for (const node of normalized.nodes) {
|
|
404
|
+
const raw = rawNodes.find((item) => (item.id || item.key) === node.id);
|
|
405
|
+
node.mode = raw?.mode === 'draft' ? 'draft' : 'send';
|
|
406
|
+
}
|
|
407
|
+
return normalized;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function linkTaskCanvas(task, canvasId) {
|
|
411
|
+
const canvas = canvases().find((item) => item.id === canvasId);
|
|
412
|
+
if (canvas) canvas.taskId = task.id;
|
|
413
|
+
bridge.storeCanvases();
|
|
414
|
+
taskStore.updateTask(task.id, { canvasIds: [...new Set([...(task.canvasIds || []), canvasId])] });
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
async function openTask(task, sessionId) {
|
|
418
|
+
const current = taskById(task.id) || task;
|
|
419
|
+
let canvasId = current.canvasIds?.[0];
|
|
420
|
+
if (!canvasId) {
|
|
421
|
+
const created = await createCanvas(current);
|
|
422
|
+
canvasId = created.canvasId;
|
|
423
|
+
} else if (bridge.getActiveCanvas() !== canvasId) {
|
|
424
|
+
await bridge.requestSwitchCanvas(canvasId);
|
|
425
|
+
}
|
|
426
|
+
bridge.setMode('canvas');
|
|
427
|
+
if (sessionId) {
|
|
428
|
+
const card = bridge.getCards().find((item) => item.sessionId === sessionId);
|
|
429
|
+
if (card) {
|
|
430
|
+
bridge.centerCard(card);
|
|
431
|
+
bridge.flash(card);
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
return canvasId;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async function createCanvas(task) {
|
|
438
|
+
if (task.plan && !(task.sessionIds || []).length) return materializePlan(task.plan, { start: false, task });
|
|
439
|
+
await bridge.requestNewBlankCanvas();
|
|
440
|
+
for (const sessionId of task.sessionIds || []) {
|
|
441
|
+
bridge.addSession({ sessionId, title: adapter.titleOf(sessionId) });
|
|
442
|
+
}
|
|
443
|
+
if (!bridge.saveCanvasAs(task.title || '任务画布')) throw new Error('画布保存失败');
|
|
444
|
+
const canvasId = bridge.getActiveCanvas();
|
|
445
|
+
linkTaskCanvas(task, canvasId);
|
|
446
|
+
bridge.save();
|
|
447
|
+
bridge.setMode('canvas');
|
|
448
|
+
await bridge.fitView();
|
|
449
|
+
return { taskId: task.id, canvasId };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
async function materializePlan(value, options = {}) {
|
|
453
|
+
const plan = normalizeTopologyPlan(value);
|
|
454
|
+
plan.acceptanceCriteria = asArray(value?.acceptanceCriteria || value?.acceptance).map(String);
|
|
455
|
+
plan.workspaceId = value?.workspaceId || '';
|
|
456
|
+
const rawNodes = asArray(value?.nodes);
|
|
457
|
+
for (const node of plan.nodes) {
|
|
458
|
+
const raw = rawNodes.find((item) => (item.id || item.key) === node.id);
|
|
459
|
+
node.mode = raw?.mode === 'draft' ? 'draft' : 'send';
|
|
460
|
+
}
|
|
461
|
+
const validation = validateTopologyPlan(plan);
|
|
462
|
+
if (!validation.valid) throw new Error(validation.errors.map((error) => error.message).join(';'));
|
|
463
|
+
const workspaceId = plan.workspaceId || requireWorkspaceId();
|
|
464
|
+
await bridge.requestNewBlankCanvas();
|
|
465
|
+
const layout = computeLayeredLayout(plan, { nodeWidth: 380, nodeHeight: 500, layerGap: 100, nodeGap: 32, originX: 40, originY: 40 });
|
|
466
|
+
const positions = new Map(layout.nodes.map((node) => [node.id, node]));
|
|
467
|
+
const cards = new Map();
|
|
468
|
+
const createdSessionIds = [];
|
|
469
|
+
try {
|
|
470
|
+
for (const layer of layout.layers) {
|
|
471
|
+
for (const nodeId of layer) {
|
|
472
|
+
const node = plan.nodes.find((item) => item.id === nodeId);
|
|
473
|
+
const position = positions.get(nodeId);
|
|
474
|
+
if (node.kind === 'note') {
|
|
475
|
+
const card = bridge.addNote({ title: node.title, note: node.note || '# 结果汇总', x: position.x, y: position.y, w: 380, h: 500 });
|
|
476
|
+
node.cardId = card.id;
|
|
477
|
+
cards.set(nodeId, card);
|
|
478
|
+
continue;
|
|
479
|
+
}
|
|
480
|
+
const workspace = adapter.listWorkspaces?.().find((item) => item.id === plan.workspaceId || item.title === node.workspace);
|
|
481
|
+
const sessionId = node.sessionId || await adapter.createSession({ workspaceId: workspace?.id || workspaceId });
|
|
482
|
+
const card = bridge.addSession({ sessionId, title: node.title, workspace: workspace?.title || node.workspace || '', x: position.x, y: position.y, w: 380, h: 500 });
|
|
483
|
+
node.sessionId = sessionId;
|
|
484
|
+
cards.set(nodeId, card);
|
|
485
|
+
createdSessionIds.push(sessionId);
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
for (const node of plan.nodes) {
|
|
489
|
+
const targetCard = cards.get(node.id);
|
|
490
|
+
for (const dependency of node.dependsOn) {
|
|
491
|
+
const sourceCard = cards.get(dependency);
|
|
492
|
+
if (!sourceCard || !targetCard) continue;
|
|
493
|
+
const target = { kind: targetCard.kind === 'note' ? 'note' : 'session', id: targetCard.kind === 'note' ? targetCard.id : targetCard.sessionId, mode: node.mode === 'draft' ? 'draft' : 'send' };
|
|
494
|
+
const existing = sourceCard.pipeline?.targets || [];
|
|
495
|
+
bridge.setPipeTargets(sourceCard, [...existing, target]);
|
|
496
|
+
bridge.recordFlow(sourceCard, target, 'waiting', { message: '拓扑已生成,等待上游完成' });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
for (const node of plan.nodes) {
|
|
500
|
+
if (node.kind !== 'session') continue;
|
|
501
|
+
const card = cards.get(node.id);
|
|
502
|
+
card.composerDraft = node.prompt || plan.goal;
|
|
503
|
+
bridge.renderFoot(card);
|
|
504
|
+
}
|
|
505
|
+
const task = options.task || {
|
|
506
|
+
id: 'task-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7),
|
|
507
|
+
title: plan.title,
|
|
508
|
+
goal: plan.goal,
|
|
509
|
+
source: 'plan',
|
|
510
|
+
createdAt: Date.now(),
|
|
511
|
+
};
|
|
512
|
+
task.sessionIds = createdSessionIds;
|
|
513
|
+
task.plan = plan;
|
|
514
|
+
task.acceptanceCriteria = plan.acceptanceCriteria || task.acceptanceCriteria || [];
|
|
515
|
+
task.executionStatus = options.start ? 'running' : 'idle';
|
|
516
|
+
task.acceptanceStatus = task.acceptanceStatus || 'pending';
|
|
517
|
+
task.pending = options.start ? [] : ['检查各节点草稿,确认后启动'];
|
|
518
|
+
task.updatedAt = Date.now();
|
|
519
|
+
if (!bridge.saveCanvasAs(plan.title || task.title)) throw new Error('画布保存失败');
|
|
520
|
+
const canvasId = bridge.getActiveCanvas();
|
|
521
|
+
task.canvasIds = [...new Set([...(task.canvasIds || []), canvasId])];
|
|
522
|
+
linkTaskCanvas(task, canvasId);
|
|
523
|
+
taskStore.addTasks([task]);
|
|
524
|
+
bridge.save();
|
|
525
|
+
bridge.schedulePipelines();
|
|
526
|
+
bridge.setMode('canvas');
|
|
527
|
+
await bridge.fitView();
|
|
528
|
+
|
|
529
|
+
if (options.start) {
|
|
530
|
+
for (const node of plan.nodes) {
|
|
531
|
+
if (node.kind !== 'session' || node.dependsOn.length) continue;
|
|
532
|
+
const card = cards.get(node.id);
|
|
533
|
+
const prompt = node.prompt || plan.goal;
|
|
534
|
+
card.composerDraft = '';
|
|
535
|
+
bridge.renderFoot(card);
|
|
536
|
+
await adapter.prompt(card.sessionId, prompt, 'queue');
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return { taskId: task.id, canvasId };
|
|
540
|
+
} catch (error) {
|
|
541
|
+
// Keep successfully created cards as a recoverable partial work scene.
|
|
542
|
+
if (cards.size) {
|
|
543
|
+
const partialName = (plan.title || '任务画布') + '(部分生成)';
|
|
544
|
+
bridge.saveCanvasAs(partialName);
|
|
545
|
+
bridge.save();
|
|
546
|
+
}
|
|
547
|
+
throw error;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
function continuationDraft(task) {
|
|
552
|
+
return [
|
|
553
|
+
'请继续这项任务,先理解已有上下文,不要重复已经完成的工作。',
|
|
554
|
+
'任务目标:' + (task.goal || task.title || '未命名任务'),
|
|
555
|
+
task.summary ? '当前进展:' + task.summary : '',
|
|
556
|
+
task.pending?.length ? '未完成事项:\n- ' + task.pending.join('\n- ') : '请检查并补齐剩余事项。',
|
|
557
|
+
task.acceptanceCriteria?.length ? '验收条件:\n- ' + task.acceptanceCriteria.join('\n- ') : '',
|
|
558
|
+
task.deliverables?.length ? '已有交付物:\n- ' + task.deliverables.map((item) => item.title).join('\n- ') : '',
|
|
559
|
+
].filter(Boolean).join('\n\n');
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async function continueTask(task) {
|
|
563
|
+
const current = taskById(task.id) || task;
|
|
564
|
+
await openTask(current);
|
|
565
|
+
let sessionId = current.sessionIds?.[0];
|
|
566
|
+
if (!sessionId) {
|
|
567
|
+
sessionId = await adapter.createSession({ workspaceId: requireWorkspaceId() });
|
|
568
|
+
bridge.addSession({ sessionId, title: current.title || '继续任务', focus: true });
|
|
569
|
+
taskStore.updateTask(current.id, { sessionIds: [sessionId] });
|
|
570
|
+
}
|
|
571
|
+
const card = bridge.getCards().find((item) => item.sessionId === sessionId);
|
|
572
|
+
if (!card) throw new Error('没有找到可续做的会话卡');
|
|
573
|
+
card.composerDraft = continuationDraft(current);
|
|
574
|
+
bridge.renderFoot(card);
|
|
575
|
+
bridge.centerCard(card);
|
|
576
|
+
bridge.flash(card);
|
|
577
|
+
toast('已生成续做草稿,检查内容后发送');
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
return {
|
|
581
|
+
snapshot,
|
|
582
|
+
listModels,
|
|
583
|
+
listWorkspaces,
|
|
584
|
+
createWorkspace: ({ path }) => adapter.createWorkspace({ path }),
|
|
585
|
+
listSessions,
|
|
586
|
+
scan,
|
|
587
|
+
plan,
|
|
588
|
+
materializePlan,
|
|
589
|
+
noteSessionRuntime,
|
|
590
|
+
async addTasks(tasks) {
|
|
591
|
+
const normalized = tasks.map((task) => ({ ...task, id: task.id || 'task-' + hashText(task.title + Date.now()), updatedAt: Date.now() }));
|
|
592
|
+
taskStore.addTasks(normalized);
|
|
593
|
+
for (const task of normalized) {
|
|
594
|
+
for (const canvasId of task.canvasIds || []) linkTaskCanvas(task, canvasId);
|
|
595
|
+
}
|
|
596
|
+
},
|
|
597
|
+
async updateTask(task, patch) { taskStore.updateTask(task.id, patch); },
|
|
598
|
+
async deleteTask(task) {
|
|
599
|
+
for (const canvas of canvases()) {
|
|
600
|
+
if (canvas.taskId === task.id) delete canvas.taskId;
|
|
601
|
+
}
|
|
602
|
+
bridge.storeCanvases();
|
|
603
|
+
taskStore.removeTask(task.id);
|
|
604
|
+
},
|
|
605
|
+
async openTask(task) { return openTask(task); },
|
|
606
|
+
async openSession(task, sessionId) { return openTask(task, sessionId); },
|
|
607
|
+
async continueTask(task) { return continueTask(task); },
|
|
608
|
+
async reviewTask(task, accepted) {
|
|
609
|
+
taskStore.updateTask(task.id, accepted ? {
|
|
610
|
+
acceptanceStatus: 'accepted', executionStatus: 'done', pending: [],
|
|
611
|
+
} : {
|
|
612
|
+
acceptanceStatus: 'rejected', executionStatus: 'idle', pending: ['验收未通过,需要返工'],
|
|
613
|
+
});
|
|
614
|
+
toast(accepted ? '任务已验收完成' : '已退回任务,可继续生成返工草稿');
|
|
615
|
+
},
|
|
616
|
+
async createCanvas(task) { return createCanvas(task); },
|
|
617
|
+
continuationDraft,
|
|
618
|
+
dispose() { clearTimeout(runtimeSaveTimer); },
|
|
619
|
+
};
|
|
620
|
+
}
|