@lokvis/runtime 0.2.0-beta.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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/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/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/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 +130 -6
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +404 -16
- package/dist/runtime.js.map +1 -1
- package/dist/types.d.ts +106 -1
- 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/degradation.ts +241 -0
- package/src/history-store.ts +159 -0
- 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 +445 -12
- package/src/types.ts +107 -0
- package/src/worker-host.ts +56 -16
- package/src/worker-protocol.ts +11 -1
- package/src/workflow-builder.ts +303 -0
package/src/runtime.ts
CHANGED
|
@@ -11,15 +11,20 @@ import type {
|
|
|
11
11
|
Capability,
|
|
12
12
|
CapabilityParam,
|
|
13
13
|
CapabilityParamType,
|
|
14
|
+
ExifData,
|
|
14
15
|
HistoryEntry,
|
|
15
16
|
LokvisEvent,
|
|
16
17
|
McpManifest,
|
|
17
18
|
McpToolManifest,
|
|
19
|
+
MetadataReader,
|
|
20
|
+
PanelDefinition,
|
|
21
|
+
PluginContext,
|
|
18
22
|
} from '@lokvis/schema';
|
|
19
23
|
import type { Workflow, WorkflowResult } from '@lokvis/schema';
|
|
20
24
|
import { validateWorkflow } from '@lokvis/schema';
|
|
21
25
|
import type {
|
|
22
26
|
LokvisRuntime,
|
|
27
|
+
PluginInstallEntry,
|
|
23
28
|
RuntimeConfig,
|
|
24
29
|
RuntimeStatus,
|
|
25
30
|
ToMcpManifestOptions,
|
|
@@ -34,7 +39,14 @@ import {
|
|
|
34
39
|
} from './asset-store.js';
|
|
35
40
|
import { CapabilityRegistry } from './capability-registry.js';
|
|
36
41
|
import { WorkflowExecutor } from './executor.js';
|
|
42
|
+
import { MAX_WORKFLOW_STEPS } from './workflow-builder.js';
|
|
37
43
|
import { HistoryStack, type HistoryStackConfig } from './history.js';
|
|
44
|
+
import {
|
|
45
|
+
createHistoryStore,
|
|
46
|
+
type HistoryStore,
|
|
47
|
+
} from './history-store.js';
|
|
48
|
+
import { BatchProcessor } from './batch-processor.js';
|
|
49
|
+
import { MemoryGuard, DEFAULT_MEMORY_BUDGET } from './memory-guard.js';
|
|
38
50
|
|
|
39
51
|
export const RUNTIME_VERSION = '0.1.0';
|
|
40
52
|
|
|
@@ -87,7 +99,18 @@ function estimateSourceSize(source: AssetSource): number {
|
|
|
87
99
|
* 并发安全:import/create/remove 通过 promise 链串行化,避免 check 与 update
|
|
88
100
|
* 之间的 TOCTOU 窗口导致两个并发操作都基于旧 usage 通过校验或回退。
|
|
89
101
|
*/
|
|
90
|
-
|
|
102
|
+
/**
|
|
103
|
+
* 配额感知的 AssetStore:在 AssetStore 接口之上扩展 _getQuotaUsage,
|
|
104
|
+
* 供 runtime.getStorageUsage O(1) 读取内部 usage(下划线表"内部 API")。
|
|
105
|
+
*/
|
|
106
|
+
type QuotaAwareAssetStore = AssetStore & {
|
|
107
|
+
_getQuotaUsage: () => number;
|
|
108
|
+
};
|
|
109
|
+
|
|
110
|
+
function wrapAssetStoreWithQuota(
|
|
111
|
+
inner: AssetStore,
|
|
112
|
+
quota: number
|
|
113
|
+
): QuotaAwareAssetStore {
|
|
91
114
|
let usage = 0;
|
|
92
115
|
let initialized = false;
|
|
93
116
|
/** 串行化 import/create/remove 的 chain tail,确保 check-update 原子性 */
|
|
@@ -148,12 +171,23 @@ function wrapAssetStoreWithQuota(inner: AssetStore, quota: number): AssetStore {
|
|
|
148
171
|
async create(blob, metadata, type) {
|
|
149
172
|
return runExclusive(async () => {
|
|
150
173
|
await ensureInit();
|
|
151
|
-
|
|
174
|
+
// m8 修复:配额预检与累加使用同一口径(metadata.size),
|
|
175
|
+
// 避免 blob.size 与 metadata.size 漂移导致账面与预检不一致
|
|
176
|
+
assertQuota(metadata.size);
|
|
152
177
|
const asset = await inner.create(blob, metadata, type);
|
|
153
178
|
usage += asset.metadata.size;
|
|
154
179
|
return asset;
|
|
155
180
|
});
|
|
156
181
|
},
|
|
182
|
+
/**
|
|
183
|
+
* m6 优化:暴露配额包装器内部维护的 usage(O(1)),
|
|
184
|
+
* 供 runtime.getStorageUsage 优先使用,避免每次 O(n) 全量 listAssets。
|
|
185
|
+
* 下划线前缀表"内部 API",非 AssetStore 接口一部分。
|
|
186
|
+
* 若 ensureInit 未完成,返回 -1 表示"未就绪",调用方 fallback 到 listAssets。
|
|
187
|
+
*/
|
|
188
|
+
_getQuotaUsage(): number {
|
|
189
|
+
return initialized ? usage : -1;
|
|
190
|
+
},
|
|
157
191
|
};
|
|
158
192
|
}
|
|
159
193
|
|
|
@@ -162,21 +196,73 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
162
196
|
readonly version = RUNTIME_VERSION;
|
|
163
197
|
readonly eventBus: EventBus;
|
|
164
198
|
|
|
165
|
-
private config: Required<Omit<RuntimeConfig, 'assetStore'>>;
|
|
199
|
+
private config: Required<Omit<RuntimeConfig, 'assetStore' | 'historyStore' | 'historyStoreOptions'>>;
|
|
166
200
|
private _status: RuntimeStatus = 'idle';
|
|
167
|
-
|
|
201
|
+
/**
|
|
202
|
+
* AssetStore 实例。类型为 QuotaAwareAssetStore —— 由 wrapAssetStoreWithQuota
|
|
203
|
+
* 返回(在构造函数中无条件包裹,即使是注入的 assetStore 也会被包装以提供配额校验)。
|
|
204
|
+
* 保留 _getQuotaUsage 内部 API 供 getStorageUsage O(1) 读取 usage。
|
|
205
|
+
* 注:外部注入的 assetStore 在 wrapAssetStoreWithQuota 中同样被包装,
|
|
206
|
+
* 因此所有路径下 this.assetStore 都是 QuotaAwareAssetStore。
|
|
207
|
+
*/
|
|
208
|
+
private assetStore: QuotaAwareAssetStore;
|
|
168
209
|
private capabilityRegistry: CapabilityRegistry;
|
|
169
210
|
private executor: WorkflowExecutor;
|
|
211
|
+
private memoryGuard: MemoryGuard;
|
|
212
|
+
private batchProcessor: BatchProcessor;
|
|
170
213
|
/**
|
|
171
214
|
* 每个工作流独立的 HistoryStack。
|
|
172
|
-
*
|
|
173
|
-
*
|
|
215
|
+
* W7.2 起,栈快照(entries + cursor)连同 initialInputs / currentOutputs
|
|
216
|
+
* 通过 historyStore 持久化到 IndexedDB,刷新后可恢复。
|
|
174
217
|
*/
|
|
175
218
|
private historyStacks = new Map<string, HistoryStack>();
|
|
176
219
|
/** 记录每个工作流的初始输入 AssetId(undo 回到初始时使用) */
|
|
177
220
|
private initialInputsMap = new Map<string, AssetId[]>();
|
|
178
221
|
/** 记录每个工作流当前的输出 AssetId(undo/redo 后切换"当前") */
|
|
179
222
|
private currentOutputsMap = new Map<string, AssetId[]>();
|
|
223
|
+
/**
|
|
224
|
+
* 历史持久化存储(W7.2)。undefined 时退化为仅内存历史(刷新后丢失)。
|
|
225
|
+
* 由 createRuntime 在 enableIndexedDB 时自动创建,或通过 config 注入。
|
|
226
|
+
*/
|
|
227
|
+
private historyStore: HistoryStore | undefined;
|
|
228
|
+
/**
|
|
229
|
+
* 加载持久化历史快照期间的守卫标志。
|
|
230
|
+
* restore() 会触发 onChanged → persistHistory,此时跳过写回,
|
|
231
|
+
* 避免把刚读出的数据又重复写入(冗余 IO + 潜在覆盖竞态)。
|
|
232
|
+
*/
|
|
233
|
+
private isLoadingHistory = false;
|
|
234
|
+
/**
|
|
235
|
+
* 加载期间被 onChanged 标记为"dirty"的工作流 ID 集合(W7.2 review 修复)。
|
|
236
|
+
*
|
|
237
|
+
* 原实现:isLoadingHistory 期间所有 persistHistory 调用直接 return,
|
|
238
|
+
* 若加载期间有其他来源(run / undo / 外部事件)触发 onChanged,
|
|
239
|
+
* 这些变更会被永久丢弃(加载结束后不会重发 persist)。
|
|
240
|
+
*
|
|
241
|
+
* 现策略:加载期间被跳过的 persistHistory 把 workflowId 加入此 Set,
|
|
242
|
+
* loadPersistedHistory 结束后逐个补 persist,确保不丢变更。
|
|
243
|
+
* (restore() 自身触发的 onChanged 也加入,但其内容与刚读出的相同,
|
|
244
|
+
* 补 persist 仅多一次等价写回,幂等无害。)
|
|
245
|
+
*/
|
|
246
|
+
private dirtyDuringLoad = new Set<string>();
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* 元数据读取器注册表(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
250
|
+
*
|
|
251
|
+
* Plugin(plugin-image)通过 PluginContext.registerMetadataReader 注册
|
|
252
|
+
* 查询函数(如 'image.read-exif'),Runtime 持有引用并按名调用。
|
|
253
|
+
* 解决了 readExif(Blob→ExifData)不符合 Engine 层 Blob↔Blob 纯函数约束、
|
|
254
|
+
* 也不符合 CapabilityImplementation Asset[]→Asset[] 契约的问题。
|
|
255
|
+
* UI 经 runtime.readAssetExif 间接调用,不直接依赖 plugin/engine。
|
|
256
|
+
*/
|
|
257
|
+
private metadataReaders = new Map<string, MetadataReader>();
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* 注册元数据读取器(由 PluginContext.registerMetadataReader 转发)。
|
|
261
|
+
* 下划线前缀表示内部 API,不暴露在 LokvisRuntime 公开接口。
|
|
262
|
+
*/
|
|
263
|
+
_registerMetadataReader(name: string, reader: MetadataReader): void {
|
|
264
|
+
this.metadataReaders.set(name, reader);
|
|
265
|
+
}
|
|
180
266
|
|
|
181
267
|
constructor(config: RuntimeConfig = {}) {
|
|
182
268
|
this.config = {
|
|
@@ -185,14 +271,32 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
185
271
|
storageQuota: config.storageQuota ?? 1024 * 1024 * 1024, // 1GB
|
|
186
272
|
enableLog: config.enableLog ?? true,
|
|
187
273
|
engineStrategy: config.engineStrategy ?? 'first',
|
|
274
|
+
isPro: config.isPro ?? false,
|
|
275
|
+
memoryBudget: config.memoryBudget ?? DEFAULT_MEMORY_BUDGET,
|
|
188
276
|
};
|
|
189
277
|
|
|
190
278
|
this.eventBus = createEventBus();
|
|
191
279
|
|
|
192
280
|
// 注入或降级到内存 store;随后用配额校验包裹(W2.9)
|
|
281
|
+
// M6 修复:enableOpfs/enableIndexedDB 仅在 createLokvis()/createRuntime
|
|
282
|
+
// 工厂中生效(工厂按 flag 调 createAssetStore 选择 OPFS→IDB→Memory)。
|
|
283
|
+
// 直接 new LokvisRuntimeImpl 且未传 assetStore 时,无法同步等待 createAssetStore,
|
|
284
|
+
// 兜底用 Memory store;若用户显式期望持久化,提示其用 createLokvis()。
|
|
285
|
+
if (!config.assetStore && (this.config.enableOpfs || this.config.enableIndexedDB)) {
|
|
286
|
+
console.warn(
|
|
287
|
+
'[lokvis] LokvisRuntimeImpl constructed without assetStore: ' +
|
|
288
|
+
'enableOpfs/enableIndexedDB flags are ignored. ' +
|
|
289
|
+
'Use createLokvis() to respect these flags, or pass an assetStore explicitly.'
|
|
290
|
+
);
|
|
291
|
+
}
|
|
193
292
|
const rawStore = config.assetStore ?? createMemoryAssetStore();
|
|
194
293
|
this.assetStore = wrapAssetStoreWithQuota(rawStore, this.config.storageQuota);
|
|
195
294
|
|
|
295
|
+
// W7.2 历史持久化:优先用注入的 historyStore;否则在 createRuntime 工厂中
|
|
296
|
+
// 由 createHistoryStore 自动创建并注入。直接 new Impl 时为 undefined,
|
|
297
|
+
// 历史退化为仅内存模式(与 W2 行为一致)。
|
|
298
|
+
this.historyStore = config.historyStore;
|
|
299
|
+
|
|
196
300
|
this.capabilityRegistry = new CapabilityRegistry(this.config.engineStrategy);
|
|
197
301
|
|
|
198
302
|
this.executor = new WorkflowExecutor({
|
|
@@ -202,6 +306,22 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
202
306
|
enableLog: this.config.enableLog,
|
|
203
307
|
});
|
|
204
308
|
|
|
309
|
+
// W3.3 MemoryGuard:追踪中间结果占用,达到 high 阈值时建议 OPFS 溢出。
|
|
310
|
+
// BatchProcessor 据此动态收缩并发槽位(W6.1)。
|
|
311
|
+
this.memoryGuard = new MemoryGuard({
|
|
312
|
+
budget: this.config.memoryBudget,
|
|
313
|
+
assetStore: this.assetStore,
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
// W6.1 BatchProcessor:把 W5 playground 的并发/进度/重试逻辑下沉到 runtime。
|
|
317
|
+
// 注入 this(实现 LokvisRuntime 接口),不直接依赖 LokvisRuntimeImpl 避免循环引用。
|
|
318
|
+
this.batchProcessor = new BatchProcessor({
|
|
319
|
+
runtime: this,
|
|
320
|
+
eventBus: this.eventBus,
|
|
321
|
+
isPro: this.config.isPro,
|
|
322
|
+
memoryGuard: this.memoryGuard,
|
|
323
|
+
});
|
|
324
|
+
|
|
205
325
|
// 监听 node:finished 事件,自动 append 到 HistoryStack
|
|
206
326
|
this.eventBus.on('node:finished', (event) => {
|
|
207
327
|
this.recordHistoryFromNodeEvent(event as Extract<LokvisEvent, { type: 'node:finished' }>);
|
|
@@ -212,6 +332,14 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
212
332
|
return this._status;
|
|
213
333
|
}
|
|
214
334
|
|
|
335
|
+
get isPro(): boolean {
|
|
336
|
+
return this.config.isPro;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
get batch(): BatchProcessor {
|
|
340
|
+
return this.batchProcessor;
|
|
341
|
+
}
|
|
342
|
+
|
|
215
343
|
// ─── 工作流执行 ──────────────────────────────────────
|
|
216
344
|
|
|
217
345
|
async run(
|
|
@@ -226,7 +354,23 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
226
354
|
// 在入口处暴露,错误信息精准(如 "Edge from __input__ references a
|
|
227
355
|
// reserved sentinel id"),而不是被 executor 拓扑排序误判为含糊的 "cycle"。
|
|
228
356
|
// 三层防御的第 3 层(前两层:executor 防御性校验 + 单元测试覆盖)。
|
|
229
|
-
|
|
357
|
+
//
|
|
358
|
+
// W10.2/W10.3 增强:
|
|
359
|
+
// - resolveCapability 回调注入 capability 兼容性校验(相邻节点
|
|
360
|
+
// outputTypes 与 inputTypes 必须有交集;输入/输出节点类型与
|
|
361
|
+
// workflow.inputs/outputs.type 兼容)
|
|
362
|
+
// - maxSteps: 5(由 MAX_WORKFLOW_STEPS 常量定义,M1 MVP 约束)
|
|
363
|
+
const validation = validateWorkflow(workflow, {
|
|
364
|
+
maxSteps: MAX_WORKFLOW_STEPS,
|
|
365
|
+
resolveCapability: (name) => {
|
|
366
|
+
const cap = this.capabilityRegistry.get(name);
|
|
367
|
+
if (!cap) return undefined;
|
|
368
|
+
return {
|
|
369
|
+
inputTypes: cap.inputTypes,
|
|
370
|
+
outputTypes: cap.outputTypes,
|
|
371
|
+
};
|
|
372
|
+
},
|
|
373
|
+
});
|
|
230
374
|
if (!validation.success) {
|
|
231
375
|
this._status = 'error';
|
|
232
376
|
const error = validation.error.issues
|
|
@@ -328,6 +472,15 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
328
472
|
return this.historyStacks.get(workflowId)?.list() ?? [];
|
|
329
473
|
}
|
|
330
474
|
|
|
475
|
+
async getHistoryState(
|
|
476
|
+
workflowId: string
|
|
477
|
+
): Promise<{ entries: HistoryEntry[]; cursor: number }> {
|
|
478
|
+
const stack = this.historyStacks.get(workflowId);
|
|
479
|
+
if (!stack) return { entries: [], cursor: -1 };
|
|
480
|
+
const snap = stack.snapshot();
|
|
481
|
+
return { entries: snap.entries, cursor: snap.cursor };
|
|
482
|
+
}
|
|
483
|
+
|
|
331
484
|
async undo(workflowId: string): Promise<void> {
|
|
332
485
|
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
333
486
|
const result = stack.undo();
|
|
@@ -352,6 +505,19 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
352
505
|
// history:changed 事件由 stack 的 onChanged 回调统一发射,避免双发
|
|
353
506
|
}
|
|
354
507
|
|
|
508
|
+
async jumpTo(workflowId: string, index: number): Promise<void> {
|
|
509
|
+
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
510
|
+
const result = stack.jumpTo(index);
|
|
511
|
+
if (result === undefined) return; // 越界或游标未变,无操作
|
|
512
|
+
|
|
513
|
+
// 同 undo/redo:更新当前输出
|
|
514
|
+
const newCurrent = result === null
|
|
515
|
+
? (this.initialInputsMap.get(workflowId) ?? [])
|
|
516
|
+
: result.outputs;
|
|
517
|
+
this.currentOutputsMap.set(workflowId, newCurrent);
|
|
518
|
+
// history:changed 事件由 stack 的 onChanged 回调统一发射
|
|
519
|
+
}
|
|
520
|
+
|
|
355
521
|
// ─── Asset 管理 ──────────────────────────────────────
|
|
356
522
|
|
|
357
523
|
async importAsset(source: AssetSource): Promise<AssetId> {
|
|
@@ -394,13 +560,49 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
394
560
|
async exportAsset(id: AssetId, format?: string): Promise<Blob> {
|
|
395
561
|
const asset = await this.getAsset(id);
|
|
396
562
|
const blob = await this.assetStore.getBlob(asset.blob);
|
|
563
|
+
// OPFS 存储后端用 .bin 扩展名存储,读取时 fileHandle.getFile() 返回的
|
|
564
|
+
// File.type 可能为空字符串或 'application/octet-stream'(浏览器对未知扩展名
|
|
565
|
+
// 的默认兜底 MIME)。这两种情况都会导致 Object URL 的 Content-Type 退化,
|
|
566
|
+
// 下载时文件扩展名变成 .octet-stream。
|
|
567
|
+
// 用 asset metadata 的 mimeType 补全 Blob type(IDB/Memory 后端不受影响)。
|
|
568
|
+
const OPFS_FALLBACK_MIME = 'application/octet-stream';
|
|
569
|
+
const mimeType =
|
|
570
|
+
!blob.type || blob.type === OPFS_FALLBACK_MIME
|
|
571
|
+
? asset.metadata.mimeType
|
|
572
|
+
: blob.type;
|
|
573
|
+
// 关键:用 arrayBuffer() 显式读取数据到内存,再构造新 Blob。
|
|
574
|
+
// 不能用 new Blob([blob]) —— 浏览器实现中它可能延迟引用底层 OPFS 文件,
|
|
575
|
+
// WatermarkBatchTool 在 export 后立即 removeAsset 删除 OPFS 文件,
|
|
576
|
+
// 导致后续 downloadBlob 读取悬空引用失败("check internet connection")。
|
|
577
|
+
// arrayBuffer() 立即拉取数据,确保返回的 Blob 完全独立于底层存储。
|
|
578
|
+
const buffer = await blob.arrayBuffer();
|
|
579
|
+
const exported = new Blob([buffer], { type: mimeType });
|
|
397
580
|
this.eventBus.emit({
|
|
398
581
|
type: 'export:completed',
|
|
399
582
|
assetId: id,
|
|
400
583
|
format: format ?? asset.metadata.format,
|
|
401
584
|
size: blob.size,
|
|
402
585
|
});
|
|
403
|
-
return
|
|
586
|
+
return exported;
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* 读取 image 资产的 EXIF 元数据(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
591
|
+
*
|
|
592
|
+
* Runtime 持有 plugin-image 通过 ctx.registerMetadataReader('image.read-exif', fn)
|
|
593
|
+
* 注册的 reader 引用,按名调用。reader 内部调 readExifFromBlob(exifr)。
|
|
594
|
+
* Plugin 未安装时优雅降级返回 null(不抛错)。
|
|
595
|
+
*
|
|
596
|
+
* 架构决策:readExif 是 Blob→ExifData 查询,不符合 Engine 层 Blob↔Blob 纯函数
|
|
597
|
+
* 约束,也不符合 Capability Asset[]→Asset[] 契约,故走 MetadataReader 机制,
|
|
598
|
+
* 不进 engine-image、不走 Capability execute。
|
|
599
|
+
*/
|
|
600
|
+
async readAssetExif(id: AssetId): Promise<ExifData | null> {
|
|
601
|
+
const asset = await this.getAsset(id);
|
|
602
|
+
if (asset.type !== 'image') return null;
|
|
603
|
+
const reader = this.metadataReaders.get('image.read-exif');
|
|
604
|
+
if (!reader) return null; // Plugin 未安装,优雅降级
|
|
605
|
+
return reader(asset) as Promise<ExifData | null>;
|
|
404
606
|
}
|
|
405
607
|
|
|
406
608
|
async removeAsset(id: AssetId): Promise<void> {
|
|
@@ -412,6 +614,23 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
412
614
|
return this.assetStore.list();
|
|
413
615
|
}
|
|
414
616
|
|
|
617
|
+
async getStorageUsage(): Promise<{ usage: number; quota: number }> {
|
|
618
|
+
// m6 优化:优先用配额包装器内部维护的 usage(O(1),import/create/remove
|
|
619
|
+
// 时增量更新),避免每次 O(n) 全量 listAssets 影响 StatusBar 刷新。
|
|
620
|
+
// 包装器未就绪(ensureInit 未完成)返回 -1 时,fallback 到 listAssets
|
|
621
|
+
// 实时计算(source of truth,与 W6.4 富元数据一致)。
|
|
622
|
+
//
|
|
623
|
+
// 类型说明:assetStore 字段类型为 QuotaAwareAssetStore(含 _getQuotaUsage),
|
|
624
|
+
// 由 wrapAssetStoreWithQuota 返回。无需重新断言 —— 类型信息未丢失。
|
|
625
|
+
const cached = this.assetStore._getQuotaUsage();
|
|
626
|
+
if (cached >= 0) {
|
|
627
|
+
return { usage: cached, quota: this.config.storageQuota };
|
|
628
|
+
}
|
|
629
|
+
const all = await this.assetStore.list();
|
|
630
|
+
const usage = all.reduce((sum, a) => sum + a.metadata.size, 0);
|
|
631
|
+
return { usage, quota: this.config.storageQuota };
|
|
632
|
+
}
|
|
633
|
+
|
|
415
634
|
// ─── 能力查询 ────────────────────────────────────────
|
|
416
635
|
|
|
417
636
|
async capabilities(): Promise<Capability[]> {
|
|
@@ -474,18 +693,55 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
474
693
|
};
|
|
475
694
|
}
|
|
476
695
|
|
|
477
|
-
// ───
|
|
696
|
+
// ─── 插件安装 ────────────────────────────────────────
|
|
478
697
|
|
|
479
|
-
/**
|
|
698
|
+
/**
|
|
699
|
+
* 在本 Runtime 上安装一个插件(实现 LokvisRuntime.installPlugin 接口)。
|
|
700
|
+
*
|
|
701
|
+
* 步骤:
|
|
702
|
+
* 1. 注册能力声明(plugin.config.capabilities → CapabilityRegistry)
|
|
703
|
+
* 2. 构造受限 PluginContext(只暴露受限 Runtime API + 注册器 + 日志)
|
|
704
|
+
* 3. 调用 plugin.install(ctx),让插件注册 CapabilityImplementation
|
|
705
|
+
* 4. 发射 `plugin:loaded` 事件
|
|
706
|
+
*
|
|
707
|
+
* 不吞错:plugin.install 抛出的错误原样上抛,由 SDK 包成 PluginLoadError。
|
|
708
|
+
*
|
|
709
|
+
* 此前 SDK 通过 `instanceof LokvisRuntimeImpl` + `_getAssetStore()` /
|
|
710
|
+
* `_getCapabilityRegistry()` 反向访问内部依赖,现改为公共接口调用,
|
|
711
|
+
* SDK 不再依赖具体实现类。
|
|
712
|
+
*/
|
|
713
|
+
async installPlugin(plugin: PluginInstallEntry): Promise<void> {
|
|
714
|
+
for (const capability of plugin.config.capabilities) {
|
|
715
|
+
this.capabilityRegistry.registerCapability(capability);
|
|
716
|
+
}
|
|
717
|
+
const ctx = createPluginContext(plugin.config.name, this);
|
|
718
|
+
await plugin.install(ctx);
|
|
719
|
+
this.eventBus.emit({
|
|
720
|
+
type: 'plugin:loaded',
|
|
721
|
+
name: plugin.config.name,
|
|
722
|
+
version: plugin.config.version,
|
|
723
|
+
});
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// ─── 内部 API(供测试使用,SDK 不再调用) ──────────────
|
|
727
|
+
|
|
728
|
+
/** 获取 AssetStore(仅测试用,SDK 通过 installPlugin 间接访问) */
|
|
480
729
|
_getAssetStore(): AssetStore {
|
|
481
730
|
return this.assetStore;
|
|
482
731
|
}
|
|
483
732
|
|
|
484
|
-
/** 获取 CapabilityRegistry
|
|
733
|
+
/** 获取 CapabilityRegistry(仅测试用,SDK 通过 installPlugin 间接访问) */
|
|
485
734
|
_getCapabilityRegistry(): CapabilityRegistry {
|
|
486
735
|
return this.capabilityRegistry;
|
|
487
736
|
}
|
|
488
737
|
|
|
738
|
+
/**
|
|
739
|
+
* 获取 MemoryGuard(内部用,供集成测试驱动内存压力验证 BatchProcessor 收缩)。
|
|
740
|
+
*/
|
|
741
|
+
_getMemoryGuard(): MemoryGuard {
|
|
742
|
+
return this.memoryGuard;
|
|
743
|
+
}
|
|
744
|
+
|
|
489
745
|
/** 获取工作流当前输出 AssetId(undo/redo 后的"当前"状态,内部用) */
|
|
490
746
|
_getCurrentOutputs(workflowId: string): AssetId[] {
|
|
491
747
|
return this.currentOutputsMap.get(workflowId) ?? [];
|
|
@@ -543,6 +799,8 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
543
799
|
entries,
|
|
544
800
|
currentIndex,
|
|
545
801
|
});
|
|
802
|
+
// W7.2:持久化快照到 IndexedDB(加载期间跳过,避免冗余写回)
|
|
803
|
+
void this.persistHistory(wfId);
|
|
546
804
|
},
|
|
547
805
|
};
|
|
548
806
|
stack = new HistoryStack(workflowId, stackConfig);
|
|
@@ -590,6 +848,107 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
590
848
|
// 更新当前输出为该 node 的 outputs
|
|
591
849
|
this.currentOutputsMap.set(event.workflowId, outputs);
|
|
592
850
|
}
|
|
851
|
+
|
|
852
|
+
// ─── 私有:历史持久化(W7.2) ────────────────────────
|
|
853
|
+
|
|
854
|
+
/**
|
|
855
|
+
* 把指定工作流的当前历史状态快照写入 historyStore。
|
|
856
|
+
*
|
|
857
|
+
* 时序修复:currentOutputs 从 stack snapshot 派生(cursor === -1 用
|
|
858
|
+
* initialInputs,否则用 entries[cursor].outputs),而非读 currentOutputsMap。
|
|
859
|
+
* 原因:onChanged 在 undo/redo/jumpTo/run 内部同步触发时,map 尚未更新,
|
|
860
|
+
* 会读到旧值(例如 run 后 append 触发 onChanged,但 currentOutputsMap 在
|
|
861
|
+
* append 返回后才 set)。
|
|
862
|
+
*
|
|
863
|
+
* 竞态安全:多个 fire-and-forget save 的 IDB readwrite 事务由 IndexedDB
|
|
864
|
+
* 引擎按发起顺序串行化(同 object store 不重叠),无需应用层加链。
|
|
865
|
+
*
|
|
866
|
+
* - entries 为空时改为 delete,避免残留空记录(reset/clear 后自然清理)
|
|
867
|
+
* - 加载期间(isLoadingHistory=true)跳过写回,但把 workflowId 加入
|
|
868
|
+
* dirtyDuringLoad,loadPersistedHistory 结束后补 persist(避免丢变更)
|
|
869
|
+
*/
|
|
870
|
+
private async persistHistory(workflowId: string): Promise<void> {
|
|
871
|
+
if (!this.historyStore) return;
|
|
872
|
+
if (this.isLoadingHistory) {
|
|
873
|
+
this.dirtyDuringLoad.add(workflowId);
|
|
874
|
+
return;
|
|
875
|
+
}
|
|
876
|
+
// fire-and-forget 调用方用 `void this.persistHistory(...)`,故内部必须
|
|
877
|
+
// try/catch,否则 IDB 故障(数据库关闭 / quota exceeded)会变成 unhandled
|
|
878
|
+
// promise rejection。历史持久化是非关键路径,失败只 warn 不抛。
|
|
879
|
+
try {
|
|
880
|
+
const stack = this.historyStacks.get(workflowId);
|
|
881
|
+
// 栈已从内存移除(disposeWorkflow / enforceHistoryStacksLimit 的 reset+delete
|
|
882
|
+
// 后异步到达此处)→ 删除持久化记录,避免孤儿数据跨会话残留
|
|
883
|
+
if (!stack) {
|
|
884
|
+
await this.historyStore.delete(workflowId);
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
const { entries, cursor } = stack.snapshot();
|
|
888
|
+
if (entries.length === 0) {
|
|
889
|
+
await this.historyStore.delete(workflowId);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
// 从 snapshot 派生 currentOutputs,而非读 currentOutputsMap —— 后者在
|
|
893
|
+
// onChanged 触发时尚未更新(见方法文档注释)
|
|
894
|
+
const initialInputs = this.initialInputsMap.get(workflowId) ?? [];
|
|
895
|
+
const currentOutputs = cursor === -1
|
|
896
|
+
? initialInputs
|
|
897
|
+
: (entries[cursor]?.outputs ?? initialInputs);
|
|
898
|
+
await this.historyStore.save({
|
|
899
|
+
workflowId,
|
|
900
|
+
entries,
|
|
901
|
+
cursor,
|
|
902
|
+
initialInputs,
|
|
903
|
+
currentOutputs,
|
|
904
|
+
updatedAt: Date.now(),
|
|
905
|
+
});
|
|
906
|
+
} catch (err) {
|
|
907
|
+
console.warn(
|
|
908
|
+
`[lokvis] persistHistory failed for workflow ${workflowId}:`,
|
|
909
|
+
err
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
/**
|
|
915
|
+
* 从 historyStore 预加载所有持久化的历史快照,恢复到内存。
|
|
916
|
+
*
|
|
917
|
+
* 由 createRuntime 工厂在构造完 impl 后调用一次。加载期间置 isLoadingHistory
|
|
918
|
+
* 守卫,使 restore() 触发的 onChanged → persistHistory 跳过冗余写回;
|
|
919
|
+
* 但被跳过的 workflowId 记入 dirtyDuringLoad,加载结束后补 persist,
|
|
920
|
+
* 避免加载期间其他来源(run / undo / 外部事件)的变更被永久丢弃。
|
|
921
|
+
*
|
|
922
|
+
* 注意:restore 会 emit history:changed 事件,但此时 UI 尚未订阅
|
|
923
|
+
* (runtime-slice.init 在 createRuntime resolve 后才订阅),故无副作用。
|
|
924
|
+
*
|
|
925
|
+
* 非 LokvisRuntime 接口的一部分,仅为 impl 的初始化钩子(工厂调用)。
|
|
926
|
+
*/
|
|
927
|
+
async loadPersistedHistory(): Promise<void> {
|
|
928
|
+
if (!this.historyStore) return;
|
|
929
|
+
let records: Awaited<ReturnType<HistoryStore['loadAll']>> = [];
|
|
930
|
+
this.isLoadingHistory = true;
|
|
931
|
+
try {
|
|
932
|
+
records = await this.historyStore.loadAll();
|
|
933
|
+
for (const record of records) {
|
|
934
|
+
// 跳过空记录(理论上 save 已删除,双重防御)
|
|
935
|
+
if (record.entries.length === 0) continue;
|
|
936
|
+
const stack = this.getOrCreateHistoryStack(record.workflowId);
|
|
937
|
+
stack.restore({ entries: record.entries, cursor: record.cursor });
|
|
938
|
+
this.initialInputsMap.set(record.workflowId, record.initialInputs);
|
|
939
|
+
this.currentOutputsMap.set(record.workflowId, record.currentOutputs);
|
|
940
|
+
}
|
|
941
|
+
} finally {
|
|
942
|
+
this.isLoadingHistory = false;
|
|
943
|
+
// 加载期间被跳过的 persist 补发:逐个 await 保证顺序
|
|
944
|
+
// 复制一份避免补 persist 过程中新触发 onChanged → dirtyDuringLoad 死循环
|
|
945
|
+
const pending = [...this.dirtyDuringLoad];
|
|
946
|
+
this.dirtyDuringLoad.clear();
|
|
947
|
+
for (const wfId of pending) {
|
|
948
|
+
await this.persistHistory(wfId);
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
593
952
|
}
|
|
594
953
|
|
|
595
954
|
/**
|
|
@@ -606,7 +965,81 @@ export async function createRuntime(
|
|
|
606
965
|
const assetStore =
|
|
607
966
|
config?.assetStore ??
|
|
608
967
|
(await createAssetStore({ preferOpfs: config?.enableOpfs ?? true }));
|
|
609
|
-
|
|
968
|
+
// W7.2:历史持久化 —— 优先用注入的 historyStore;否则在 enableIndexedDB 时
|
|
969
|
+
// 通过 createHistoryStore 自动创建(IDB 不可用时返回 undefined,退化仅内存)
|
|
970
|
+
const historyStore =
|
|
971
|
+
config?.historyStore ??
|
|
972
|
+
((config?.enableIndexedDB ?? true)
|
|
973
|
+
? createHistoryStore(config?.historyStoreOptions)
|
|
974
|
+
: undefined);
|
|
975
|
+
const impl = new LokvisRuntimeImpl({ ...config, assetStore, historyStore });
|
|
976
|
+
// 预加载持久化的历史快照(跨会话恢复 undo/redo 链)
|
|
977
|
+
await impl.loadPersistedHistory();
|
|
978
|
+
return impl;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
/**
|
|
982
|
+
* 构造受限 PluginContext(模块级 helper,供 installPlugin 使用)。
|
|
983
|
+
*
|
|
984
|
+
* Plugin 只看到受限的 Runtime API:
|
|
985
|
+
* - getAsset / importAsset / getAssetBlob / createAsset / listCapabilities
|
|
986
|
+
* - 看不到 React / Redux / Cloud
|
|
987
|
+
*
|
|
988
|
+
* registerMetadataReader 把读取函数转发给 runtime._registerMetadataReader
|
|
989
|
+
* (依赖反转:Plugin 提供实现,Runtime 持有引用)。
|
|
990
|
+
*
|
|
991
|
+
* 错误契约:getAsset 在资产不存在时抛 plain Error,message 以 "Asset not found"
|
|
992
|
+
* 开头。SDK 的 fromLokvisError 据此模式匹配转换为 AssetNotFoundError,
|
|
993
|
+
* 保持 SDK 消费者的错误类型契约不变。
|
|
994
|
+
*/
|
|
995
|
+
function createPluginContext(
|
|
996
|
+
pluginName: string,
|
|
997
|
+
runtime: LokvisRuntimeImpl
|
|
998
|
+
): PluginContext {
|
|
999
|
+
const assetStore = runtime._getAssetStore();
|
|
1000
|
+
const capabilityRegistry = runtime._getCapabilityRegistry();
|
|
1001
|
+
return {
|
|
1002
|
+
runtime: {
|
|
1003
|
+
getAsset: async (id) => {
|
|
1004
|
+
const asset = await assetStore.get(id);
|
|
1005
|
+
if (!asset) throw new Error(`Asset not found: ${id}`);
|
|
1006
|
+
return asset;
|
|
1007
|
+
},
|
|
1008
|
+
importAsset: async (file) => {
|
|
1009
|
+
// PluginContext.importAsset 接受 File | Blob,统一转为 AssetSource
|
|
1010
|
+
if (file instanceof File) {
|
|
1011
|
+
const asset = await assetStore.import({ kind: 'file', file });
|
|
1012
|
+
return asset.id;
|
|
1013
|
+
}
|
|
1014
|
+
const asset = await assetStore.import({
|
|
1015
|
+
kind: 'blob',
|
|
1016
|
+
blob: file,
|
|
1017
|
+
name: `blob_${Date.now()}`,
|
|
1018
|
+
});
|
|
1019
|
+
return asset.id;
|
|
1020
|
+
},
|
|
1021
|
+
getAssetBlob: (asset) => assetStore.getBlob(asset.blob),
|
|
1022
|
+
createAsset: (blob, metadata, type) =>
|
|
1023
|
+
assetStore.create(blob, metadata, type),
|
|
1024
|
+
listCapabilities: async () => capabilityRegistry.list(),
|
|
1025
|
+
},
|
|
1026
|
+
eventBus: runtime.eventBus,
|
|
1027
|
+
registerCapability: (impl) =>
|
|
1028
|
+
capabilityRegistry.registerImplementation(impl),
|
|
1029
|
+
registerMetadataReader: <T>(name: string, reader: MetadataReader<T>) => {
|
|
1030
|
+
runtime._registerMetadataReader(name, reader as MetadataReader);
|
|
1031
|
+
},
|
|
1032
|
+
registerPanel: (panel: PanelDefinition) => {
|
|
1033
|
+
// Panel 注册由 UI 层处理,这里仅记录日志
|
|
1034
|
+
void panel;
|
|
1035
|
+
},
|
|
1036
|
+
log: (level, message) => {
|
|
1037
|
+
const prefix = `[${pluginName}]`;
|
|
1038
|
+
if (level === 'error') console.error(`${prefix} ${message}`);
|
|
1039
|
+
else if (level === 'warn') console.warn(`${prefix} ${message}`);
|
|
1040
|
+
else console.log(`${prefix} ${message}`);
|
|
1041
|
+
},
|
|
1042
|
+
};
|
|
610
1043
|
}
|
|
611
1044
|
|
|
612
1045
|
/**
|