@lokvis/runtime 0.1.0 → 0.2.0
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/LICENSE +21 -0
- package/dist/asset-store.d.ts +5 -2
- package/dist/asset-store.d.ts.map +1 -1
- package/dist/asset-store.js +93 -3
- package/dist/asset-store.js.map +1 -1
- package/dist/batch-processor.d.ts +200 -0
- package/dist/batch-processor.d.ts.map +1 -0
- package/dist/batch-processor.js +505 -0
- package/dist/batch-processor.js.map +1 -0
- package/dist/capability-registry.d.ts +4 -0
- package/dist/capability-registry.d.ts.map +1 -1
- package/dist/capability-registry.js +19 -2
- package/dist/capability-registry.js.map +1 -1
- package/dist/degradation.d.ts +109 -0
- package/dist/degradation.d.ts.map +1 -0
- package/dist/degradation.js +184 -0
- package/dist/degradation.js.map +1 -0
- package/dist/event-bus.d.ts.map +1 -1
- package/dist/event-bus.js +7 -2
- package/dist/event-bus.js.map +1 -1
- package/dist/executor.d.ts.map +1 -1
- package/dist/executor.js +37 -1
- package/dist/executor.js.map +1 -1
- package/dist/history-store.d.ts +76 -0
- package/dist/history-store.d.ts.map +1 -0
- package/dist/history-store.js +109 -0
- package/dist/history-store.js.map +1 -0
- package/dist/history.d.ts +1 -1
- package/dist/history.d.ts.map +1 -1
- package/dist/history.js +1 -1
- package/dist/history.js.map +1 -1
- package/dist/idb-asset-store.js +1 -1
- package/dist/idb-asset-store.js.map +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- package/dist/memory-guard.d.ts +109 -0
- package/dist/memory-guard.d.ts.map +1 -0
- package/dist/memory-guard.js +161 -0
- package/dist/memory-guard.js.map +1 -0
- package/dist/opfs-asset-store.d.ts +35 -4
- package/dist/opfs-asset-store.d.ts.map +1 -1
- package/dist/opfs-asset-store.js +94 -10
- package/dist/opfs-asset-store.js.map +1 -1
- package/dist/runtime.d.ts +139 -4
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +443 -25
- package/dist/runtime.js.map +1 -1
- package/dist/types.d.ts +101 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/worker-host.d.ts +13 -0
- package/dist/worker-host.d.ts.map +1 -1
- package/dist/worker-host.js +47 -15
- package/dist/worker-host.js.map +1 -1
- package/dist/worker-protocol.d.ts +10 -1
- package/dist/worker-protocol.d.ts.map +1 -1
- package/dist/worker-protocol.js.map +1 -1
- package/dist/workflow-builder.d.ts +124 -0
- package/dist/workflow-builder.d.ts.map +1 -0
- package/dist/workflow-builder.js +240 -0
- package/dist/workflow-builder.js.map +1 -0
- package/package.json +3 -2
- package/src/asset-store.ts +103 -3
- package/src/batch-processor.ts +699 -0
- package/src/capability-registry.ts +19 -2
- package/src/degradation.ts +241 -0
- package/src/event-bus.ts +6 -2
- package/src/executor.ts +46 -1
- package/src/history-store.ts +159 -0
- package/src/history.ts +2 -2
- package/src/idb-asset-store.ts +1 -1
- package/src/index.ts +5 -0
- package/src/memory-guard.ts +202 -0
- package/src/opfs-asset-store.ts +118 -10
- package/src/runtime.ts +482 -21
- package/src/types.ts +98 -1
- package/src/worker-host.ts +56 -16
- package/src/worker-protocol.ts +11 -1
- package/src/workflow-builder.ts +303 -0
package/dist/runtime.js
CHANGED
|
@@ -3,14 +3,30 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Runtime 是整个系统的"浏览器操作系统",唯一职责:Input → Run → Output。
|
|
5
5
|
*/
|
|
6
|
+
import { validateWorkflow } from '@lokvis/schema';
|
|
6
7
|
import { createEventBus } from './event-bus.js';
|
|
7
8
|
import { createAssetStore, createMemoryAssetStore, generateId, } from './asset-store.js';
|
|
8
9
|
import { CapabilityRegistry } from './capability-registry.js';
|
|
9
10
|
import { WorkflowExecutor } from './executor.js';
|
|
11
|
+
import { MAX_WORKFLOW_STEPS } from './workflow-builder.js';
|
|
10
12
|
import { HistoryStack } from './history.js';
|
|
13
|
+
import { createHistoryStore, } from './history-store.js';
|
|
14
|
+
import { BatchProcessor } from './batch-processor.js';
|
|
15
|
+
import { MemoryGuard, DEFAULT_MEMORY_BUDGET } from './memory-guard.js';
|
|
11
16
|
export const RUNTIME_VERSION = '0.1.0';
|
|
12
17
|
/** 默认历史记录上限 */
|
|
13
18
|
const DEFAULT_MAX_HISTORY = 10;
|
|
19
|
+
/**
|
|
20
|
+
* 同时持有的工作流历史栈上限(W2.8 内存治理)。
|
|
21
|
+
*
|
|
22
|
+
* 修复 review 报告:原实现 historyStacks 是无限增长 Map,每次 run() 都加入新
|
|
23
|
+
* workflow.id(ui-react buildLinearWorkflow 用 `wf_${Date.now()}` 每次唯一),
|
|
24
|
+
* 长会话累积导致 Map 引用的 AssetId 无法回收 → 内存泄漏。
|
|
25
|
+
*
|
|
26
|
+
* 32 是经验值:覆盖用户常见使用(多 tab 切换 + undo 范围),超限按 FIFO
|
|
27
|
+
* 清理最旧 stack(reset 触发 onEvict → assetStore.remove 回收资产)。
|
|
28
|
+
*/
|
|
29
|
+
const MAX_CONCURRENT_WORKFLOW_STACKS = 32;
|
|
14
30
|
/** 存储配额超限时抛出(W2.9) */
|
|
15
31
|
export class QuotaExceededError extends Error {
|
|
16
32
|
usage;
|
|
@@ -36,13 +52,6 @@ function estimateSourceSize(source) {
|
|
|
36
52
|
return source.blob.size;
|
|
37
53
|
return 0;
|
|
38
54
|
}
|
|
39
|
-
/**
|
|
40
|
-
* 用配额校验包裹 AssetStore:import/create 超限抛 QuotaExceededError(W2.9)。
|
|
41
|
-
* 内部维护运行中的已用字节数,remove 时回退。
|
|
42
|
-
*
|
|
43
|
-
* 并发安全:import/create/remove 通过 promise 链串行化,避免 check 与 update
|
|
44
|
-
* 之间的 TOCTOU 窗口导致两个并发操作都基于旧 usage 通过校验或回退。
|
|
45
|
-
*/
|
|
46
55
|
function wrapAssetStoreWithQuota(inner, quota) {
|
|
47
56
|
let usage = 0;
|
|
48
57
|
let initialized = false;
|
|
@@ -98,12 +107,23 @@ function wrapAssetStoreWithQuota(inner, quota) {
|
|
|
98
107
|
async create(blob, metadata, type) {
|
|
99
108
|
return runExclusive(async () => {
|
|
100
109
|
await ensureInit();
|
|
101
|
-
|
|
110
|
+
// m8 修复:配额预检与累加使用同一口径(metadata.size),
|
|
111
|
+
// 避免 blob.size 与 metadata.size 漂移导致账面与预检不一致
|
|
112
|
+
assertQuota(metadata.size);
|
|
102
113
|
const asset = await inner.create(blob, metadata, type);
|
|
103
114
|
usage += asset.metadata.size;
|
|
104
115
|
return asset;
|
|
105
116
|
});
|
|
106
117
|
},
|
|
118
|
+
/**
|
|
119
|
+
* m6 优化:暴露配额包装器内部维护的 usage(O(1)),
|
|
120
|
+
* 供 runtime.getStorageUsage 优先使用,避免每次 O(n) 全量 listAssets。
|
|
121
|
+
* 下划线前缀表"内部 API",非 AssetStore 接口一部分。
|
|
122
|
+
* 若 ensureInit 未完成,返回 -1 表示"未就绪",调用方 fallback 到 listAssets。
|
|
123
|
+
*/
|
|
124
|
+
_getQuotaUsage() {
|
|
125
|
+
return initialized ? usage : -1;
|
|
126
|
+
},
|
|
107
127
|
};
|
|
108
128
|
}
|
|
109
129
|
/** Runtime 实现类 */
|
|
@@ -112,19 +132,69 @@ export class LokvisRuntimeImpl {
|
|
|
112
132
|
eventBus;
|
|
113
133
|
config;
|
|
114
134
|
_status = 'idle';
|
|
135
|
+
/**
|
|
136
|
+
* AssetStore 实例。类型为 QuotaAwareAssetStore —— 由 wrapAssetStoreWithQuota
|
|
137
|
+
* 返回(在构造函数中无条件包裹,即使是注入的 assetStore 也会被包装以提供配额校验)。
|
|
138
|
+
* 保留 _getQuotaUsage 内部 API 供 getStorageUsage O(1) 读取 usage。
|
|
139
|
+
* 注:外部注入的 assetStore 在 wrapAssetStoreWithQuota 中同样被包装,
|
|
140
|
+
* 因此所有路径下 this.assetStore 都是 QuotaAwareAssetStore。
|
|
141
|
+
*/
|
|
115
142
|
assetStore;
|
|
116
143
|
capabilityRegistry;
|
|
117
144
|
executor;
|
|
145
|
+
memoryGuard;
|
|
146
|
+
batchProcessor;
|
|
118
147
|
/**
|
|
119
148
|
* 每个工作流独立的 HistoryStack。
|
|
120
|
-
*
|
|
121
|
-
*
|
|
149
|
+
* W7.2 起,栈快照(entries + cursor)连同 initialInputs / currentOutputs
|
|
150
|
+
* 通过 historyStore 持久化到 IndexedDB,刷新后可恢复。
|
|
122
151
|
*/
|
|
123
152
|
historyStacks = new Map();
|
|
124
153
|
/** 记录每个工作流的初始输入 AssetId(undo 回到初始时使用) */
|
|
125
154
|
initialInputsMap = new Map();
|
|
126
155
|
/** 记录每个工作流当前的输出 AssetId(undo/redo 后切换"当前") */
|
|
127
156
|
currentOutputsMap = new Map();
|
|
157
|
+
/**
|
|
158
|
+
* 历史持久化存储(W7.2)。undefined 时退化为仅内存历史(刷新后丢失)。
|
|
159
|
+
* 由 createRuntime 在 enableIndexedDB 时自动创建,或通过 config 注入。
|
|
160
|
+
*/
|
|
161
|
+
historyStore;
|
|
162
|
+
/**
|
|
163
|
+
* 加载持久化历史快照期间的守卫标志。
|
|
164
|
+
* restore() 会触发 onChanged → persistHistory,此时跳过写回,
|
|
165
|
+
* 避免把刚读出的数据又重复写入(冗余 IO + 潜在覆盖竞态)。
|
|
166
|
+
*/
|
|
167
|
+
isLoadingHistory = false;
|
|
168
|
+
/**
|
|
169
|
+
* 加载期间被 onChanged 标记为"dirty"的工作流 ID 集合(W7.2 review 修复)。
|
|
170
|
+
*
|
|
171
|
+
* 原实现:isLoadingHistory 期间所有 persistHistory 调用直接 return,
|
|
172
|
+
* 若加载期间有其他来源(run / undo / 外部事件)触发 onChanged,
|
|
173
|
+
* 这些变更会被永久丢弃(加载结束后不会重发 persist)。
|
|
174
|
+
*
|
|
175
|
+
* 现策略:加载期间被跳过的 persistHistory 把 workflowId 加入此 Set,
|
|
176
|
+
* loadPersistedHistory 结束后逐个补 persist,确保不丢变更。
|
|
177
|
+
* (restore() 自身触发的 onChanged 也加入,但其内容与刚读出的相同,
|
|
178
|
+
* 补 persist 仅多一次等价写回,幂等无害。)
|
|
179
|
+
*/
|
|
180
|
+
dirtyDuringLoad = new Set();
|
|
181
|
+
/**
|
|
182
|
+
* 元数据读取器注册表(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
183
|
+
*
|
|
184
|
+
* Plugin(plugin-image)通过 PluginContext.registerMetadataReader 注册
|
|
185
|
+
* 查询函数(如 'image.read-exif'),Runtime 持有引用并按名调用。
|
|
186
|
+
* 解决了 readExif(Blob→ExifData)不符合 Engine 层 Blob↔Blob 纯函数约束、
|
|
187
|
+
* 也不符合 CapabilityImplementation Asset[]→Asset[] 契约的问题。
|
|
188
|
+
* UI 经 runtime.readAssetExif 间接调用,不直接依赖 plugin/engine。
|
|
189
|
+
*/
|
|
190
|
+
metadataReaders = new Map();
|
|
191
|
+
/**
|
|
192
|
+
* 注册元数据读取器(由 PluginContext.registerMetadataReader 转发)。
|
|
193
|
+
* 下划线前缀表示内部 API,不暴露在 LokvisRuntime 公开接口。
|
|
194
|
+
*/
|
|
195
|
+
_registerMetadataReader(name, reader) {
|
|
196
|
+
this.metadataReaders.set(name, reader);
|
|
197
|
+
}
|
|
128
198
|
constructor(config = {}) {
|
|
129
199
|
this.config = {
|
|
130
200
|
enableOpfs: config.enableOpfs ?? true,
|
|
@@ -132,11 +202,26 @@ export class LokvisRuntimeImpl {
|
|
|
132
202
|
storageQuota: config.storageQuota ?? 1024 * 1024 * 1024, // 1GB
|
|
133
203
|
enableLog: config.enableLog ?? true,
|
|
134
204
|
engineStrategy: config.engineStrategy ?? 'first',
|
|
205
|
+
isPro: config.isPro ?? false,
|
|
206
|
+
memoryBudget: config.memoryBudget ?? DEFAULT_MEMORY_BUDGET,
|
|
135
207
|
};
|
|
136
208
|
this.eventBus = createEventBus();
|
|
137
209
|
// 注入或降级到内存 store;随后用配额校验包裹(W2.9)
|
|
210
|
+
// M6 修复:enableOpfs/enableIndexedDB 仅在 createLokvis()/createRuntime
|
|
211
|
+
// 工厂中生效(工厂按 flag 调 createAssetStore 选择 OPFS→IDB→Memory)。
|
|
212
|
+
// 直接 new LokvisRuntimeImpl 且未传 assetStore 时,无法同步等待 createAssetStore,
|
|
213
|
+
// 兜底用 Memory store;若用户显式期望持久化,提示其用 createLokvis()。
|
|
214
|
+
if (!config.assetStore && (this.config.enableOpfs || this.config.enableIndexedDB)) {
|
|
215
|
+
console.warn('[lokvis] LokvisRuntimeImpl constructed without assetStore: ' +
|
|
216
|
+
'enableOpfs/enableIndexedDB flags are ignored. ' +
|
|
217
|
+
'Use createLokvis() to respect these flags, or pass an assetStore explicitly.');
|
|
218
|
+
}
|
|
138
219
|
const rawStore = config.assetStore ?? createMemoryAssetStore();
|
|
139
220
|
this.assetStore = wrapAssetStoreWithQuota(rawStore, this.config.storageQuota);
|
|
221
|
+
// W7.2 历史持久化:优先用注入的 historyStore;否则在 createRuntime 工厂中
|
|
222
|
+
// 由 createHistoryStore 自动创建并注入。直接 new Impl 时为 undefined,
|
|
223
|
+
// 历史退化为仅内存模式(与 W2 行为一致)。
|
|
224
|
+
this.historyStore = config.historyStore;
|
|
140
225
|
this.capabilityRegistry = new CapabilityRegistry(this.config.engineStrategy);
|
|
141
226
|
this.executor = new WorkflowExecutor({
|
|
142
227
|
assetStore: this.assetStore,
|
|
@@ -144,6 +229,20 @@ export class LokvisRuntimeImpl {
|
|
|
144
229
|
eventBus: this.eventBus,
|
|
145
230
|
enableLog: this.config.enableLog,
|
|
146
231
|
});
|
|
232
|
+
// W3.3 MemoryGuard:追踪中间结果占用,达到 high 阈值时建议 OPFS 溢出。
|
|
233
|
+
// BatchProcessor 据此动态收缩并发槽位(W6.1)。
|
|
234
|
+
this.memoryGuard = new MemoryGuard({
|
|
235
|
+
budget: this.config.memoryBudget,
|
|
236
|
+
assetStore: this.assetStore,
|
|
237
|
+
});
|
|
238
|
+
// W6.1 BatchProcessor:把 W5 playground 的并发/进度/重试逻辑下沉到 runtime。
|
|
239
|
+
// 注入 this(实现 LokvisRuntime 接口),不直接依赖 LokvisRuntimeImpl 避免循环引用。
|
|
240
|
+
this.batchProcessor = new BatchProcessor({
|
|
241
|
+
runtime: this,
|
|
242
|
+
eventBus: this.eventBus,
|
|
243
|
+
isPro: this.config.isPro,
|
|
244
|
+
memoryGuard: this.memoryGuard,
|
|
245
|
+
});
|
|
147
246
|
// 监听 node:finished 事件,自动 append 到 HistoryStack
|
|
148
247
|
this.eventBus.on('node:finished', (event) => {
|
|
149
248
|
this.recordHistoryFromNodeEvent(event);
|
|
@@ -152,21 +251,77 @@ export class LokvisRuntimeImpl {
|
|
|
152
251
|
get status() {
|
|
153
252
|
return this._status;
|
|
154
253
|
}
|
|
254
|
+
get isPro() {
|
|
255
|
+
return this.config.isPro;
|
|
256
|
+
}
|
|
257
|
+
get batch() {
|
|
258
|
+
return this.batchProcessor;
|
|
259
|
+
}
|
|
155
260
|
// ─── 工作流执行 ──────────────────────────────────────
|
|
156
|
-
async run(workflow, inputs) {
|
|
261
|
+
async run(workflow, inputs, options) {
|
|
157
262
|
this._status = 'running';
|
|
158
|
-
//
|
|
159
|
-
//
|
|
160
|
-
//
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
263
|
+
// Schema 层校验:在 executor.execute 之前调用 validateWorkflow,
|
|
264
|
+
// 让结构问题(保留字哨兵 __input__、悬挂 edge、自环、重复 id、真环)
|
|
265
|
+
// 在入口处暴露,错误信息精准(如 "Edge from __input__ references a
|
|
266
|
+
// reserved sentinel id"),而不是被 executor 拓扑排序误判为含糊的 "cycle"。
|
|
267
|
+
// 三层防御的第 3 层(前两层:executor 防御性校验 + 单元测试覆盖)。
|
|
268
|
+
//
|
|
269
|
+
// W10.2/W10.3 增强:
|
|
270
|
+
// - resolveCapability 回调注入 capability 兼容性校验(相邻节点
|
|
271
|
+
// outputTypes 与 inputTypes 必须有交集;输入/输出节点类型与
|
|
272
|
+
// workflow.inputs/outputs.type 兼容)
|
|
273
|
+
// - maxSteps: 5(由 MAX_WORKFLOW_STEPS 常量定义,M1 MVP 约束)
|
|
274
|
+
const validation = validateWorkflow(workflow, {
|
|
275
|
+
maxSteps: MAX_WORKFLOW_STEPS,
|
|
276
|
+
resolveCapability: (name) => {
|
|
277
|
+
const cap = this.capabilityRegistry.get(name);
|
|
278
|
+
if (!cap)
|
|
279
|
+
return undefined;
|
|
280
|
+
return {
|
|
281
|
+
inputTypes: cap.inputTypes,
|
|
282
|
+
outputTypes: cap.outputTypes,
|
|
283
|
+
};
|
|
284
|
+
},
|
|
285
|
+
});
|
|
286
|
+
if (!validation.success) {
|
|
287
|
+
this._status = 'error';
|
|
288
|
+
const error = validation.error.issues
|
|
289
|
+
.map((i) => i.message)
|
|
290
|
+
.join('; ');
|
|
291
|
+
const result = {
|
|
292
|
+
workflowId: workflow.id,
|
|
293
|
+
outputs: [],
|
|
294
|
+
duration: 0,
|
|
295
|
+
status: 'failed',
|
|
296
|
+
error,
|
|
297
|
+
};
|
|
298
|
+
this.eventBus.emit({
|
|
299
|
+
type: 'workflow:completed',
|
|
300
|
+
workflowId: workflow.id,
|
|
301
|
+
result,
|
|
302
|
+
});
|
|
303
|
+
return result;
|
|
164
304
|
}
|
|
165
|
-
//
|
|
305
|
+
// 历史栈管理:
|
|
306
|
+
// - 默认:每次 run() 重置历史(重跑语义),并通过 onEvict 回收旧 outputs 资产
|
|
307
|
+
// - appendHistory:true:保留已有历史栈,支持跨次 undo/redo 链(如连续滤镜)
|
|
166
308
|
const inputIds = await this.collectInputAssetIds(inputs);
|
|
167
|
-
this.
|
|
168
|
-
|
|
169
|
-
|
|
309
|
+
if (options?.appendHistory && this.historyStacks.has(workflow.id)) {
|
|
310
|
+
// 追加模式:保留历史栈与 currentOutputs,仅确保初始输入已记录
|
|
311
|
+
if (!this.initialInputsMap.has(workflow.id)) {
|
|
312
|
+
this.initialInputsMap.set(workflow.id, inputIds);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
// 重置模式(默认):丢弃旧历史,重新初始化
|
|
317
|
+
const existingStack = this.historyStacks.get(workflow.id);
|
|
318
|
+
if (existingStack) {
|
|
319
|
+
existingStack.reset();
|
|
320
|
+
}
|
|
321
|
+
this.initialInputsMap.set(workflow.id, inputIds);
|
|
322
|
+
this.currentOutputsMap.set(workflow.id, inputIds);
|
|
323
|
+
}
|
|
324
|
+
this.enforceHistoryStacksLimit();
|
|
170
325
|
try {
|
|
171
326
|
const result = await this.executor.execute(workflow, inputs);
|
|
172
327
|
this._status = result.status === 'failed' ? 'error' : 'idle';
|
|
@@ -190,11 +345,45 @@ export class LokvisRuntimeImpl {
|
|
|
190
345
|
async resume(workflowId) {
|
|
191
346
|
return this.executor.resume(workflowId);
|
|
192
347
|
}
|
|
348
|
+
/**
|
|
349
|
+
* 销毁指定工作流的运行时状态(W2.8 内存治理)。
|
|
350
|
+
*
|
|
351
|
+
* 调用时机:
|
|
352
|
+
* - ui-react 卸载 Workspace 组件时
|
|
353
|
+
* - 用户主动关闭工作流标签页时
|
|
354
|
+
*
|
|
355
|
+
* 行为:
|
|
356
|
+
* - 调用 stack.reset() 触发 onEvict → assetStore.remove 回收历史 outputs 资产
|
|
357
|
+
* - 从 historyStacks / initialInputsMap / currentOutputsMap 三 Map 中删除 entry
|
|
358
|
+
* - 调用 executor.cancel 取消运行中的执行(若有)
|
|
359
|
+
*
|
|
360
|
+
* 修复 review 报告:原实现无清理入口,Workflow 组件卸载后 Map 中残留 entry,
|
|
361
|
+
* 长会话累积导致内存与 OPFS 空间双泄漏。
|
|
362
|
+
*/
|
|
363
|
+
async disposeWorkflow(workflowId) {
|
|
364
|
+
await this.cancel(workflowId).catch(() => {
|
|
365
|
+
/* 工作流可能未在运行 */
|
|
366
|
+
});
|
|
367
|
+
const stack = this.historyStacks.get(workflowId);
|
|
368
|
+
if (stack) {
|
|
369
|
+
stack.reset();
|
|
370
|
+
this.historyStacks.delete(workflowId);
|
|
371
|
+
}
|
|
372
|
+
this.initialInputsMap.delete(workflowId);
|
|
373
|
+
this.currentOutputsMap.delete(workflowId);
|
|
374
|
+
}
|
|
193
375
|
// ─── 历史与撤销 ──────────────────────────────────────
|
|
194
376
|
async history(workflowId) {
|
|
195
377
|
// 避免对从未运行过的工作流创建空栈:先查 Map,无则直接返回空数组
|
|
196
378
|
return this.historyStacks.get(workflowId)?.list() ?? [];
|
|
197
379
|
}
|
|
380
|
+
async getHistoryState(workflowId) {
|
|
381
|
+
const stack = this.historyStacks.get(workflowId);
|
|
382
|
+
if (!stack)
|
|
383
|
+
return { entries: [], cursor: -1 };
|
|
384
|
+
const snap = stack.snapshot();
|
|
385
|
+
return { entries: snap.entries, cursor: snap.cursor };
|
|
386
|
+
}
|
|
198
387
|
async undo(workflowId) {
|
|
199
388
|
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
200
389
|
const result = stack.undo();
|
|
@@ -217,9 +406,40 @@ export class LokvisRuntimeImpl {
|
|
|
217
406
|
this.currentOutputsMap.set(workflowId, entry.outputs);
|
|
218
407
|
// history:changed 事件由 stack 的 onChanged 回调统一发射,避免双发
|
|
219
408
|
}
|
|
409
|
+
async jumpTo(workflowId, index) {
|
|
410
|
+
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
411
|
+
const result = stack.jumpTo(index);
|
|
412
|
+
if (result === undefined)
|
|
413
|
+
return; // 越界或游标未变,无操作
|
|
414
|
+
// 同 undo/redo:更新当前输出
|
|
415
|
+
const newCurrent = result === null
|
|
416
|
+
? (this.initialInputsMap.get(workflowId) ?? [])
|
|
417
|
+
: result.outputs;
|
|
418
|
+
this.currentOutputsMap.set(workflowId, newCurrent);
|
|
419
|
+
// history:changed 事件由 stack 的 onChanged 回调统一发射
|
|
420
|
+
}
|
|
220
421
|
// ─── Asset 管理 ──────────────────────────────────────
|
|
221
422
|
async importAsset(source) {
|
|
222
|
-
|
|
423
|
+
// 修复 review 报告:原实现直接透传 source 给 assetStore.import,
|
|
424
|
+
// 但 MemoryAssetStore/OpfsAssetStore/IdbAssetStore 的 extractBlobFromSource
|
|
425
|
+
// 仅支持 file/blob 两种 kind,url/opfs 会抛 "not supported"。
|
|
426
|
+
// 这里在 runtime 层兜底处理 url(fetch → blob),opfs 暂不支持(OPFS
|
|
427
|
+
// 路径访问需要 filesystem access permission,未来单独实现)
|
|
428
|
+
let effectiveSource = source;
|
|
429
|
+
if (source.kind === 'url') {
|
|
430
|
+
const resp = await fetch(source.url);
|
|
431
|
+
if (!resp.ok) {
|
|
432
|
+
throw new Error(`Failed to fetch asset from ${source.url}: ${resp.status}`);
|
|
433
|
+
}
|
|
434
|
+
const blob = await resp.blob();
|
|
435
|
+
const name = source.url.split('/').pop()?.split('?')[0] ?? 'asset';
|
|
436
|
+
effectiveSource = { kind: 'blob', blob, name };
|
|
437
|
+
}
|
|
438
|
+
else if (source.kind === 'opfs') {
|
|
439
|
+
throw new Error("AssetSource kind 'opfs' is not yet supported by importAsset; " +
|
|
440
|
+
'use the OPFS-aware AssetStore directly or convert to blob first');
|
|
441
|
+
}
|
|
442
|
+
const asset = await this.assetStore.import(effectiveSource);
|
|
223
443
|
this.eventBus.emit({
|
|
224
444
|
type: 'asset:imported',
|
|
225
445
|
assetId: asset.id,
|
|
@@ -236,13 +456,49 @@ export class LokvisRuntimeImpl {
|
|
|
236
456
|
async exportAsset(id, format) {
|
|
237
457
|
const asset = await this.getAsset(id);
|
|
238
458
|
const blob = await this.assetStore.getBlob(asset.blob);
|
|
459
|
+
// OPFS 存储后端用 .bin 扩展名存储,读取时 fileHandle.getFile() 返回的
|
|
460
|
+
// File.type 可能为空字符串或 'application/octet-stream'(浏览器对未知扩展名
|
|
461
|
+
// 的默认兜底 MIME)。这两种情况都会导致 Object URL 的 Content-Type 退化,
|
|
462
|
+
// 下载时文件扩展名变成 .octet-stream。
|
|
463
|
+
// 用 asset metadata 的 mimeType 补全 Blob type(IDB/Memory 后端不受影响)。
|
|
464
|
+
const OPFS_FALLBACK_MIME = 'application/octet-stream';
|
|
465
|
+
const mimeType = !blob.type || blob.type === OPFS_FALLBACK_MIME
|
|
466
|
+
? asset.metadata.mimeType
|
|
467
|
+
: blob.type;
|
|
468
|
+
// 关键:用 arrayBuffer() 显式读取数据到内存,再构造新 Blob。
|
|
469
|
+
// 不能用 new Blob([blob]) —— 浏览器实现中它可能延迟引用底层 OPFS 文件,
|
|
470
|
+
// WatermarkBatchTool 在 export 后立即 removeAsset 删除 OPFS 文件,
|
|
471
|
+
// 导致后续 downloadBlob 读取悬空引用失败("check internet connection")。
|
|
472
|
+
// arrayBuffer() 立即拉取数据,确保返回的 Blob 完全独立于底层存储。
|
|
473
|
+
const buffer = await blob.arrayBuffer();
|
|
474
|
+
const exported = new Blob([buffer], { type: mimeType });
|
|
239
475
|
this.eventBus.emit({
|
|
240
476
|
type: 'export:completed',
|
|
241
477
|
assetId: id,
|
|
242
478
|
format: format ?? asset.metadata.format,
|
|
243
479
|
size: blob.size,
|
|
244
480
|
});
|
|
245
|
-
return
|
|
481
|
+
return exported;
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* 读取 image 资产的 EXIF 元数据(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
485
|
+
*
|
|
486
|
+
* Runtime 持有 plugin-image 通过 ctx.registerMetadataReader('image.read-exif', fn)
|
|
487
|
+
* 注册的 reader 引用,按名调用。reader 内部调 readExifFromBlob(exifr)。
|
|
488
|
+
* Plugin 未安装时优雅降级返回 null(不抛错)。
|
|
489
|
+
*
|
|
490
|
+
* 架构决策:readExif 是 Blob→ExifData 查询,不符合 Engine 层 Blob↔Blob 纯函数
|
|
491
|
+
* 约束,也不符合 Capability Asset[]→Asset[] 契约,故走 MetadataReader 机制,
|
|
492
|
+
* 不进 engine-image、不走 Capability execute。
|
|
493
|
+
*/
|
|
494
|
+
async readAssetExif(id) {
|
|
495
|
+
const asset = await this.getAsset(id);
|
|
496
|
+
if (asset.type !== 'image')
|
|
497
|
+
return null;
|
|
498
|
+
const reader = this.metadataReaders.get('image.read-exif');
|
|
499
|
+
if (!reader)
|
|
500
|
+
return null; // Plugin 未安装,优雅降级
|
|
501
|
+
return reader(asset);
|
|
246
502
|
}
|
|
247
503
|
async removeAsset(id) {
|
|
248
504
|
await this.assetStore.remove(id);
|
|
@@ -251,6 +507,22 @@ export class LokvisRuntimeImpl {
|
|
|
251
507
|
async listAssets() {
|
|
252
508
|
return this.assetStore.list();
|
|
253
509
|
}
|
|
510
|
+
async getStorageUsage() {
|
|
511
|
+
// m6 优化:优先用配额包装器内部维护的 usage(O(1),import/create/remove
|
|
512
|
+
// 时增量更新),避免每次 O(n) 全量 listAssets 影响 StatusBar 刷新。
|
|
513
|
+
// 包装器未就绪(ensureInit 未完成)返回 -1 时,fallback 到 listAssets
|
|
514
|
+
// 实时计算(source of truth,与 W6.4 富元数据一致)。
|
|
515
|
+
//
|
|
516
|
+
// 类型说明:assetStore 字段类型为 QuotaAwareAssetStore(含 _getQuotaUsage),
|
|
517
|
+
// 由 wrapAssetStoreWithQuota 返回。无需重新断言 —— 类型信息未丢失。
|
|
518
|
+
const cached = this.assetStore._getQuotaUsage();
|
|
519
|
+
if (cached >= 0) {
|
|
520
|
+
return { usage: cached, quota: this.config.storageQuota };
|
|
521
|
+
}
|
|
522
|
+
const all = await this.assetStore.list();
|
|
523
|
+
const usage = all.reduce((sum, a) => sum + a.metadata.size, 0);
|
|
524
|
+
return { usage, quota: this.config.storageQuota };
|
|
525
|
+
}
|
|
254
526
|
// ─── 能力查询 ────────────────────────────────────────
|
|
255
527
|
async capabilities() {
|
|
256
528
|
return this.capabilityRegistry.list();
|
|
@@ -316,11 +588,45 @@ export class LokvisRuntimeImpl {
|
|
|
316
588
|
_getCapabilityRegistry() {
|
|
317
589
|
return this.capabilityRegistry;
|
|
318
590
|
}
|
|
591
|
+
/**
|
|
592
|
+
* 获取 MemoryGuard(内部用,供集成测试驱动内存压力验证 BatchProcessor 收缩)。
|
|
593
|
+
*/
|
|
594
|
+
_getMemoryGuard() {
|
|
595
|
+
return this.memoryGuard;
|
|
596
|
+
}
|
|
319
597
|
/** 获取工作流当前输出 AssetId(undo/redo 后的"当前"状态,内部用) */
|
|
320
598
|
_getCurrentOutputs(workflowId) {
|
|
321
599
|
return this.currentOutputsMap.get(workflowId) ?? [];
|
|
322
600
|
}
|
|
601
|
+
/** 获取工作流当前输出 AssetId(公开 API,供 UI / MCP 查询) */
|
|
602
|
+
async getCurrentOutputs(workflowId) {
|
|
603
|
+
return this._getCurrentOutputs(workflowId);
|
|
604
|
+
}
|
|
323
605
|
// ─── 私有:历史栈管理 ──────────────────────────────
|
|
606
|
+
/**
|
|
607
|
+
* LRU 上限清理:historyStacks 超过 MAX_CONCURRENT_WORKFLOW_STACKS 时
|
|
608
|
+
* 按 FIFO 删除最旧 stack(reset 触发 onEvict → assetStore.remove 回收资产)。
|
|
609
|
+
*
|
|
610
|
+
* Map 的迭代顺序是插入顺序(ES2015+ 规范),所以第一个 entry 即最旧。
|
|
611
|
+
* 注意:当前 run() 的工作流尚未插入 Map(getOrCreateHistoryStack 才会插入),
|
|
612
|
+
* 所以这里清理不会误删当前工作流。
|
|
613
|
+
*/
|
|
614
|
+
enforceHistoryStacksLimit() {
|
|
615
|
+
while (this.historyStacks.size >= MAX_CONCURRENT_WORKFLOW_STACKS) {
|
|
616
|
+
// 取最旧 workflowId(Map 第一个 key)
|
|
617
|
+
const oldestId = this.historyStacks.keys().next().value;
|
|
618
|
+
if (oldestId === undefined)
|
|
619
|
+
break;
|
|
620
|
+
const stack = this.historyStacks.get(oldestId);
|
|
621
|
+
if (stack) {
|
|
622
|
+
// reset 触发 onEvict,回收历史 outputs 资产
|
|
623
|
+
stack.reset();
|
|
624
|
+
}
|
|
625
|
+
this.historyStacks.delete(oldestId);
|
|
626
|
+
this.initialInputsMap.delete(oldestId);
|
|
627
|
+
this.currentOutputsMap.delete(oldestId);
|
|
628
|
+
}
|
|
629
|
+
}
|
|
324
630
|
/** 获取或创建工作流对应的 HistoryStack */
|
|
325
631
|
getOrCreateHistoryStack(workflowId) {
|
|
326
632
|
let stack = this.historyStacks.get(workflowId);
|
|
@@ -335,12 +641,15 @@ export class LokvisRuntimeImpl {
|
|
|
335
641
|
this.assetStore.remove(assetId).catch(() => { });
|
|
336
642
|
}
|
|
337
643
|
},
|
|
338
|
-
onChanged: (wfId, entries) => {
|
|
644
|
+
onChanged: (wfId, entries, currentIndex) => {
|
|
339
645
|
this.eventBus.emit({
|
|
340
646
|
type: 'history:changed',
|
|
341
647
|
workflowId: wfId,
|
|
342
648
|
entries,
|
|
649
|
+
currentIndex,
|
|
343
650
|
});
|
|
651
|
+
// W7.2:持久化快照到 IndexedDB(加载期间跳过,避免冗余写回)
|
|
652
|
+
void this.persistHistory(wfId);
|
|
344
653
|
},
|
|
345
654
|
};
|
|
346
655
|
stack = new HistoryStack(workflowId, stackConfig);
|
|
@@ -380,6 +689,106 @@ export class LokvisRuntimeImpl {
|
|
|
380
689
|
// 更新当前输出为该 node 的 outputs
|
|
381
690
|
this.currentOutputsMap.set(event.workflowId, outputs);
|
|
382
691
|
}
|
|
692
|
+
// ─── 私有:历史持久化(W7.2) ────────────────────────
|
|
693
|
+
/**
|
|
694
|
+
* 把指定工作流的当前历史状态快照写入 historyStore。
|
|
695
|
+
*
|
|
696
|
+
* 时序修复:currentOutputs 从 stack snapshot 派生(cursor === -1 用
|
|
697
|
+
* initialInputs,否则用 entries[cursor].outputs),而非读 currentOutputsMap。
|
|
698
|
+
* 原因:onChanged 在 undo/redo/jumpTo/run 内部同步触发时,map 尚未更新,
|
|
699
|
+
* 会读到旧值(例如 run 后 append 触发 onChanged,但 currentOutputsMap 在
|
|
700
|
+
* append 返回后才 set)。
|
|
701
|
+
*
|
|
702
|
+
* 竞态安全:多个 fire-and-forget save 的 IDB readwrite 事务由 IndexedDB
|
|
703
|
+
* 引擎按发起顺序串行化(同 object store 不重叠),无需应用层加链。
|
|
704
|
+
*
|
|
705
|
+
* - entries 为空时改为 delete,避免残留空记录(reset/clear 后自然清理)
|
|
706
|
+
* - 加载期间(isLoadingHistory=true)跳过写回,但把 workflowId 加入
|
|
707
|
+
* dirtyDuringLoad,loadPersistedHistory 结束后补 persist(避免丢变更)
|
|
708
|
+
*/
|
|
709
|
+
async persistHistory(workflowId) {
|
|
710
|
+
if (!this.historyStore)
|
|
711
|
+
return;
|
|
712
|
+
if (this.isLoadingHistory) {
|
|
713
|
+
this.dirtyDuringLoad.add(workflowId);
|
|
714
|
+
return;
|
|
715
|
+
}
|
|
716
|
+
// fire-and-forget 调用方用 `void this.persistHistory(...)`,故内部必须
|
|
717
|
+
// try/catch,否则 IDB 故障(数据库关闭 / quota exceeded)会变成 unhandled
|
|
718
|
+
// promise rejection。历史持久化是非关键路径,失败只 warn 不抛。
|
|
719
|
+
try {
|
|
720
|
+
const stack = this.historyStacks.get(workflowId);
|
|
721
|
+
// 栈已从内存移除(disposeWorkflow / enforceHistoryStacksLimit 的 reset+delete
|
|
722
|
+
// 后异步到达此处)→ 删除持久化记录,避免孤儿数据跨会话残留
|
|
723
|
+
if (!stack) {
|
|
724
|
+
await this.historyStore.delete(workflowId);
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
const { entries, cursor } = stack.snapshot();
|
|
728
|
+
if (entries.length === 0) {
|
|
729
|
+
await this.historyStore.delete(workflowId);
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
// 从 snapshot 派生 currentOutputs,而非读 currentOutputsMap —— 后者在
|
|
733
|
+
// onChanged 触发时尚未更新(见方法文档注释)
|
|
734
|
+
const initialInputs = this.initialInputsMap.get(workflowId) ?? [];
|
|
735
|
+
const currentOutputs = cursor === -1
|
|
736
|
+
? initialInputs
|
|
737
|
+
: (entries[cursor]?.outputs ?? initialInputs);
|
|
738
|
+
await this.historyStore.save({
|
|
739
|
+
workflowId,
|
|
740
|
+
entries,
|
|
741
|
+
cursor,
|
|
742
|
+
initialInputs,
|
|
743
|
+
currentOutputs,
|
|
744
|
+
updatedAt: Date.now(),
|
|
745
|
+
});
|
|
746
|
+
}
|
|
747
|
+
catch (err) {
|
|
748
|
+
console.warn(`[lokvis] persistHistory failed for workflow ${workflowId}:`, err);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* 从 historyStore 预加载所有持久化的历史快照,恢复到内存。
|
|
753
|
+
*
|
|
754
|
+
* 由 createRuntime 工厂在构造完 impl 后调用一次。加载期间置 isLoadingHistory
|
|
755
|
+
* 守卫,使 restore() 触发的 onChanged → persistHistory 跳过冗余写回;
|
|
756
|
+
* 但被跳过的 workflowId 记入 dirtyDuringLoad,加载结束后补 persist,
|
|
757
|
+
* 避免加载期间其他来源(run / undo / 外部事件)的变更被永久丢弃。
|
|
758
|
+
*
|
|
759
|
+
* 注意:restore 会 emit history:changed 事件,但此时 UI 尚未订阅
|
|
760
|
+
* (runtime-slice.init 在 createRuntime resolve 后才订阅),故无副作用。
|
|
761
|
+
*
|
|
762
|
+
* 非 LokvisRuntime 接口的一部分,仅为 impl 的初始化钩子(工厂调用)。
|
|
763
|
+
*/
|
|
764
|
+
async loadPersistedHistory() {
|
|
765
|
+
if (!this.historyStore)
|
|
766
|
+
return;
|
|
767
|
+
let records = [];
|
|
768
|
+
this.isLoadingHistory = true;
|
|
769
|
+
try {
|
|
770
|
+
records = await this.historyStore.loadAll();
|
|
771
|
+
for (const record of records) {
|
|
772
|
+
// 跳过空记录(理论上 save 已删除,双重防御)
|
|
773
|
+
if (record.entries.length === 0)
|
|
774
|
+
continue;
|
|
775
|
+
const stack = this.getOrCreateHistoryStack(record.workflowId);
|
|
776
|
+
stack.restore({ entries: record.entries, cursor: record.cursor });
|
|
777
|
+
this.initialInputsMap.set(record.workflowId, record.initialInputs);
|
|
778
|
+
this.currentOutputsMap.set(record.workflowId, record.currentOutputs);
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
finally {
|
|
782
|
+
this.isLoadingHistory = false;
|
|
783
|
+
// 加载期间被跳过的 persist 补发:逐个 await 保证顺序
|
|
784
|
+
// 复制一份避免补 persist 过程中新触发 onChanged → dirtyDuringLoad 死循环
|
|
785
|
+
const pending = [...this.dirtyDuringLoad];
|
|
786
|
+
this.dirtyDuringLoad.clear();
|
|
787
|
+
for (const wfId of pending) {
|
|
788
|
+
await this.persistHistory(wfId);
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
}
|
|
383
792
|
}
|
|
384
793
|
/**
|
|
385
794
|
* 创建 Runtime 实例(W2.8 + W2.9)。
|
|
@@ -392,7 +801,16 @@ export class LokvisRuntimeImpl {
|
|
|
392
801
|
export async function createRuntime(config) {
|
|
393
802
|
const assetStore = config?.assetStore ??
|
|
394
803
|
(await createAssetStore({ preferOpfs: config?.enableOpfs ?? true }));
|
|
395
|
-
|
|
804
|
+
// W7.2:历史持久化 —— 优先用注入的 historyStore;否则在 enableIndexedDB 时
|
|
805
|
+
// 通过 createHistoryStore 自动创建(IDB 不可用时返回 undefined,退化仅内存)
|
|
806
|
+
const historyStore = config?.historyStore ??
|
|
807
|
+
((config?.enableIndexedDB ?? true)
|
|
808
|
+
? createHistoryStore(config?.historyStoreOptions)
|
|
809
|
+
: undefined);
|
|
810
|
+
const impl = new LokvisRuntimeImpl({ ...config, assetStore, historyStore });
|
|
811
|
+
// 预加载持久化的历史快照(跨会话恢复 undo/redo 链)
|
|
812
|
+
await impl.loadPersistedHistory();
|
|
813
|
+
return impl;
|
|
396
814
|
}
|
|
397
815
|
/**
|
|
398
816
|
* 把 Capability.params(CapabilityParam[])转换为 JSON Schema 对象,
|