@lokvis/runtime 0.2.0-beta.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/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 +111 -3
- package/dist/runtime.d.ts.map +1 -1
- package/dist/runtime.js +311 -13
- package/dist/runtime.js.map +1 -1
- package/dist/types.d.ts +74 -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 +345 -9
- package/src/types.ts +70 -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,10 +11,12 @@ 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,
|
|
18
20
|
} from '@lokvis/schema';
|
|
19
21
|
import type { Workflow, WorkflowResult } from '@lokvis/schema';
|
|
20
22
|
import { validateWorkflow } from '@lokvis/schema';
|
|
@@ -34,7 +36,14 @@ import {
|
|
|
34
36
|
} from './asset-store.js';
|
|
35
37
|
import { CapabilityRegistry } from './capability-registry.js';
|
|
36
38
|
import { WorkflowExecutor } from './executor.js';
|
|
39
|
+
import { MAX_WORKFLOW_STEPS } from './workflow-builder.js';
|
|
37
40
|
import { HistoryStack, type HistoryStackConfig } from './history.js';
|
|
41
|
+
import {
|
|
42
|
+
createHistoryStore,
|
|
43
|
+
type HistoryStore,
|
|
44
|
+
} from './history-store.js';
|
|
45
|
+
import { BatchProcessor } from './batch-processor.js';
|
|
46
|
+
import { MemoryGuard, DEFAULT_MEMORY_BUDGET } from './memory-guard.js';
|
|
38
47
|
|
|
39
48
|
export const RUNTIME_VERSION = '0.1.0';
|
|
40
49
|
|
|
@@ -87,7 +96,18 @@ function estimateSourceSize(source: AssetSource): number {
|
|
|
87
96
|
* 并发安全:import/create/remove 通过 promise 链串行化,避免 check 与 update
|
|
88
97
|
* 之间的 TOCTOU 窗口导致两个并发操作都基于旧 usage 通过校验或回退。
|
|
89
98
|
*/
|
|
90
|
-
|
|
99
|
+
/**
|
|
100
|
+
* 配额感知的 AssetStore:在 AssetStore 接口之上扩展 _getQuotaUsage,
|
|
101
|
+
* 供 runtime.getStorageUsage O(1) 读取内部 usage(下划线表"内部 API")。
|
|
102
|
+
*/
|
|
103
|
+
type QuotaAwareAssetStore = AssetStore & {
|
|
104
|
+
_getQuotaUsage: () => number;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
function wrapAssetStoreWithQuota(
|
|
108
|
+
inner: AssetStore,
|
|
109
|
+
quota: number
|
|
110
|
+
): QuotaAwareAssetStore {
|
|
91
111
|
let usage = 0;
|
|
92
112
|
let initialized = false;
|
|
93
113
|
/** 串行化 import/create/remove 的 chain tail,确保 check-update 原子性 */
|
|
@@ -148,12 +168,23 @@ function wrapAssetStoreWithQuota(inner: AssetStore, quota: number): AssetStore {
|
|
|
148
168
|
async create(blob, metadata, type) {
|
|
149
169
|
return runExclusive(async () => {
|
|
150
170
|
await ensureInit();
|
|
151
|
-
|
|
171
|
+
// m8 修复:配额预检与累加使用同一口径(metadata.size),
|
|
172
|
+
// 避免 blob.size 与 metadata.size 漂移导致账面与预检不一致
|
|
173
|
+
assertQuota(metadata.size);
|
|
152
174
|
const asset = await inner.create(blob, metadata, type);
|
|
153
175
|
usage += asset.metadata.size;
|
|
154
176
|
return asset;
|
|
155
177
|
});
|
|
156
178
|
},
|
|
179
|
+
/**
|
|
180
|
+
* m6 优化:暴露配额包装器内部维护的 usage(O(1)),
|
|
181
|
+
* 供 runtime.getStorageUsage 优先使用,避免每次 O(n) 全量 listAssets。
|
|
182
|
+
* 下划线前缀表"内部 API",非 AssetStore 接口一部分。
|
|
183
|
+
* 若 ensureInit 未完成,返回 -1 表示"未就绪",调用方 fallback 到 listAssets。
|
|
184
|
+
*/
|
|
185
|
+
_getQuotaUsage(): number {
|
|
186
|
+
return initialized ? usage : -1;
|
|
187
|
+
},
|
|
157
188
|
};
|
|
158
189
|
}
|
|
159
190
|
|
|
@@ -162,21 +193,73 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
162
193
|
readonly version = RUNTIME_VERSION;
|
|
163
194
|
readonly eventBus: EventBus;
|
|
164
195
|
|
|
165
|
-
private config: Required<Omit<RuntimeConfig, 'assetStore'>>;
|
|
196
|
+
private config: Required<Omit<RuntimeConfig, 'assetStore' | 'historyStore' | 'historyStoreOptions'>>;
|
|
166
197
|
private _status: RuntimeStatus = 'idle';
|
|
167
|
-
|
|
198
|
+
/**
|
|
199
|
+
* AssetStore 实例。类型为 QuotaAwareAssetStore —— 由 wrapAssetStoreWithQuota
|
|
200
|
+
* 返回(在构造函数中无条件包裹,即使是注入的 assetStore 也会被包装以提供配额校验)。
|
|
201
|
+
* 保留 _getQuotaUsage 内部 API 供 getStorageUsage O(1) 读取 usage。
|
|
202
|
+
* 注:外部注入的 assetStore 在 wrapAssetStoreWithQuota 中同样被包装,
|
|
203
|
+
* 因此所有路径下 this.assetStore 都是 QuotaAwareAssetStore。
|
|
204
|
+
*/
|
|
205
|
+
private assetStore: QuotaAwareAssetStore;
|
|
168
206
|
private capabilityRegistry: CapabilityRegistry;
|
|
169
207
|
private executor: WorkflowExecutor;
|
|
208
|
+
private memoryGuard: MemoryGuard;
|
|
209
|
+
private batchProcessor: BatchProcessor;
|
|
170
210
|
/**
|
|
171
211
|
* 每个工作流独立的 HistoryStack。
|
|
172
|
-
*
|
|
173
|
-
*
|
|
212
|
+
* W7.2 起,栈快照(entries + cursor)连同 initialInputs / currentOutputs
|
|
213
|
+
* 通过 historyStore 持久化到 IndexedDB,刷新后可恢复。
|
|
174
214
|
*/
|
|
175
215
|
private historyStacks = new Map<string, HistoryStack>();
|
|
176
216
|
/** 记录每个工作流的初始输入 AssetId(undo 回到初始时使用) */
|
|
177
217
|
private initialInputsMap = new Map<string, AssetId[]>();
|
|
178
218
|
/** 记录每个工作流当前的输出 AssetId(undo/redo 后切换"当前") */
|
|
179
219
|
private currentOutputsMap = new Map<string, AssetId[]>();
|
|
220
|
+
/**
|
|
221
|
+
* 历史持久化存储(W7.2)。undefined 时退化为仅内存历史(刷新后丢失)。
|
|
222
|
+
* 由 createRuntime 在 enableIndexedDB 时自动创建,或通过 config 注入。
|
|
223
|
+
*/
|
|
224
|
+
private historyStore: HistoryStore | undefined;
|
|
225
|
+
/**
|
|
226
|
+
* 加载持久化历史快照期间的守卫标志。
|
|
227
|
+
* restore() 会触发 onChanged → persistHistory,此时跳过写回,
|
|
228
|
+
* 避免把刚读出的数据又重复写入(冗余 IO + 潜在覆盖竞态)。
|
|
229
|
+
*/
|
|
230
|
+
private isLoadingHistory = false;
|
|
231
|
+
/**
|
|
232
|
+
* 加载期间被 onChanged 标记为"dirty"的工作流 ID 集合(W7.2 review 修复)。
|
|
233
|
+
*
|
|
234
|
+
* 原实现:isLoadingHistory 期间所有 persistHistory 调用直接 return,
|
|
235
|
+
* 若加载期间有其他来源(run / undo / 外部事件)触发 onChanged,
|
|
236
|
+
* 这些变更会被永久丢弃(加载结束后不会重发 persist)。
|
|
237
|
+
*
|
|
238
|
+
* 现策略:加载期间被跳过的 persistHistory 把 workflowId 加入此 Set,
|
|
239
|
+
* loadPersistedHistory 结束后逐个补 persist,确保不丢变更。
|
|
240
|
+
* (restore() 自身触发的 onChanged 也加入,但其内容与刚读出的相同,
|
|
241
|
+
* 补 persist 仅多一次等价写回,幂等无害。)
|
|
242
|
+
*/
|
|
243
|
+
private dirtyDuringLoad = new Set<string>();
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* 元数据读取器注册表(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
247
|
+
*
|
|
248
|
+
* Plugin(plugin-image)通过 PluginContext.registerMetadataReader 注册
|
|
249
|
+
* 查询函数(如 'image.read-exif'),Runtime 持有引用并按名调用。
|
|
250
|
+
* 解决了 readExif(Blob→ExifData)不符合 Engine 层 Blob↔Blob 纯函数约束、
|
|
251
|
+
* 也不符合 CapabilityImplementation Asset[]→Asset[] 契约的问题。
|
|
252
|
+
* UI 经 runtime.readAssetExif 间接调用,不直接依赖 plugin/engine。
|
|
253
|
+
*/
|
|
254
|
+
private metadataReaders = new Map<string, MetadataReader>();
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* 注册元数据读取器(由 PluginContext.registerMetadataReader 转发)。
|
|
258
|
+
* 下划线前缀表示内部 API,不暴露在 LokvisRuntime 公开接口。
|
|
259
|
+
*/
|
|
260
|
+
_registerMetadataReader(name: string, reader: MetadataReader): void {
|
|
261
|
+
this.metadataReaders.set(name, reader);
|
|
262
|
+
}
|
|
180
263
|
|
|
181
264
|
constructor(config: RuntimeConfig = {}) {
|
|
182
265
|
this.config = {
|
|
@@ -185,14 +268,32 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
185
268
|
storageQuota: config.storageQuota ?? 1024 * 1024 * 1024, // 1GB
|
|
186
269
|
enableLog: config.enableLog ?? true,
|
|
187
270
|
engineStrategy: config.engineStrategy ?? 'first',
|
|
271
|
+
isPro: config.isPro ?? false,
|
|
272
|
+
memoryBudget: config.memoryBudget ?? DEFAULT_MEMORY_BUDGET,
|
|
188
273
|
};
|
|
189
274
|
|
|
190
275
|
this.eventBus = createEventBus();
|
|
191
276
|
|
|
192
277
|
// 注入或降级到内存 store;随后用配额校验包裹(W2.9)
|
|
278
|
+
// M6 修复:enableOpfs/enableIndexedDB 仅在 createLokvis()/createRuntime
|
|
279
|
+
// 工厂中生效(工厂按 flag 调 createAssetStore 选择 OPFS→IDB→Memory)。
|
|
280
|
+
// 直接 new LokvisRuntimeImpl 且未传 assetStore 时,无法同步等待 createAssetStore,
|
|
281
|
+
// 兜底用 Memory store;若用户显式期望持久化,提示其用 createLokvis()。
|
|
282
|
+
if (!config.assetStore && (this.config.enableOpfs || this.config.enableIndexedDB)) {
|
|
283
|
+
console.warn(
|
|
284
|
+
'[lokvis] LokvisRuntimeImpl constructed without assetStore: ' +
|
|
285
|
+
'enableOpfs/enableIndexedDB flags are ignored. ' +
|
|
286
|
+
'Use createLokvis() to respect these flags, or pass an assetStore explicitly.'
|
|
287
|
+
);
|
|
288
|
+
}
|
|
193
289
|
const rawStore = config.assetStore ?? createMemoryAssetStore();
|
|
194
290
|
this.assetStore = wrapAssetStoreWithQuota(rawStore, this.config.storageQuota);
|
|
195
291
|
|
|
292
|
+
// W7.2 历史持久化:优先用注入的 historyStore;否则在 createRuntime 工厂中
|
|
293
|
+
// 由 createHistoryStore 自动创建并注入。直接 new Impl 时为 undefined,
|
|
294
|
+
// 历史退化为仅内存模式(与 W2 行为一致)。
|
|
295
|
+
this.historyStore = config.historyStore;
|
|
296
|
+
|
|
196
297
|
this.capabilityRegistry = new CapabilityRegistry(this.config.engineStrategy);
|
|
197
298
|
|
|
198
299
|
this.executor = new WorkflowExecutor({
|
|
@@ -202,6 +303,22 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
202
303
|
enableLog: this.config.enableLog,
|
|
203
304
|
});
|
|
204
305
|
|
|
306
|
+
// W3.3 MemoryGuard:追踪中间结果占用,达到 high 阈值时建议 OPFS 溢出。
|
|
307
|
+
// BatchProcessor 据此动态收缩并发槽位(W6.1)。
|
|
308
|
+
this.memoryGuard = new MemoryGuard({
|
|
309
|
+
budget: this.config.memoryBudget,
|
|
310
|
+
assetStore: this.assetStore,
|
|
311
|
+
});
|
|
312
|
+
|
|
313
|
+
// W6.1 BatchProcessor:把 W5 playground 的并发/进度/重试逻辑下沉到 runtime。
|
|
314
|
+
// 注入 this(实现 LokvisRuntime 接口),不直接依赖 LokvisRuntimeImpl 避免循环引用。
|
|
315
|
+
this.batchProcessor = new BatchProcessor({
|
|
316
|
+
runtime: this,
|
|
317
|
+
eventBus: this.eventBus,
|
|
318
|
+
isPro: this.config.isPro,
|
|
319
|
+
memoryGuard: this.memoryGuard,
|
|
320
|
+
});
|
|
321
|
+
|
|
205
322
|
// 监听 node:finished 事件,自动 append 到 HistoryStack
|
|
206
323
|
this.eventBus.on('node:finished', (event) => {
|
|
207
324
|
this.recordHistoryFromNodeEvent(event as Extract<LokvisEvent, { type: 'node:finished' }>);
|
|
@@ -212,6 +329,14 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
212
329
|
return this._status;
|
|
213
330
|
}
|
|
214
331
|
|
|
332
|
+
get isPro(): boolean {
|
|
333
|
+
return this.config.isPro;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
get batch(): BatchProcessor {
|
|
337
|
+
return this.batchProcessor;
|
|
338
|
+
}
|
|
339
|
+
|
|
215
340
|
// ─── 工作流执行 ──────────────────────────────────────
|
|
216
341
|
|
|
217
342
|
async run(
|
|
@@ -226,7 +351,23 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
226
351
|
// 在入口处暴露,错误信息精准(如 "Edge from __input__ references a
|
|
227
352
|
// reserved sentinel id"),而不是被 executor 拓扑排序误判为含糊的 "cycle"。
|
|
228
353
|
// 三层防御的第 3 层(前两层:executor 防御性校验 + 单元测试覆盖)。
|
|
229
|
-
|
|
354
|
+
//
|
|
355
|
+
// W10.2/W10.3 增强:
|
|
356
|
+
// - resolveCapability 回调注入 capability 兼容性校验(相邻节点
|
|
357
|
+
// outputTypes 与 inputTypes 必须有交集;输入/输出节点类型与
|
|
358
|
+
// workflow.inputs/outputs.type 兼容)
|
|
359
|
+
// - maxSteps: 5(由 MAX_WORKFLOW_STEPS 常量定义,M1 MVP 约束)
|
|
360
|
+
const validation = validateWorkflow(workflow, {
|
|
361
|
+
maxSteps: MAX_WORKFLOW_STEPS,
|
|
362
|
+
resolveCapability: (name) => {
|
|
363
|
+
const cap = this.capabilityRegistry.get(name);
|
|
364
|
+
if (!cap) return undefined;
|
|
365
|
+
return {
|
|
366
|
+
inputTypes: cap.inputTypes,
|
|
367
|
+
outputTypes: cap.outputTypes,
|
|
368
|
+
};
|
|
369
|
+
},
|
|
370
|
+
});
|
|
230
371
|
if (!validation.success) {
|
|
231
372
|
this._status = 'error';
|
|
232
373
|
const error = validation.error.issues
|
|
@@ -328,6 +469,15 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
328
469
|
return this.historyStacks.get(workflowId)?.list() ?? [];
|
|
329
470
|
}
|
|
330
471
|
|
|
472
|
+
async getHistoryState(
|
|
473
|
+
workflowId: string
|
|
474
|
+
): Promise<{ entries: HistoryEntry[]; cursor: number }> {
|
|
475
|
+
const stack = this.historyStacks.get(workflowId);
|
|
476
|
+
if (!stack) return { entries: [], cursor: -1 };
|
|
477
|
+
const snap = stack.snapshot();
|
|
478
|
+
return { entries: snap.entries, cursor: snap.cursor };
|
|
479
|
+
}
|
|
480
|
+
|
|
331
481
|
async undo(workflowId: string): Promise<void> {
|
|
332
482
|
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
333
483
|
const result = stack.undo();
|
|
@@ -352,6 +502,19 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
352
502
|
// history:changed 事件由 stack 的 onChanged 回调统一发射,避免双发
|
|
353
503
|
}
|
|
354
504
|
|
|
505
|
+
async jumpTo(workflowId: string, index: number): Promise<void> {
|
|
506
|
+
const stack = this.getOrCreateHistoryStack(workflowId);
|
|
507
|
+
const result = stack.jumpTo(index);
|
|
508
|
+
if (result === undefined) return; // 越界或游标未变,无操作
|
|
509
|
+
|
|
510
|
+
// 同 undo/redo:更新当前输出
|
|
511
|
+
const newCurrent = result === null
|
|
512
|
+
? (this.initialInputsMap.get(workflowId) ?? [])
|
|
513
|
+
: result.outputs;
|
|
514
|
+
this.currentOutputsMap.set(workflowId, newCurrent);
|
|
515
|
+
// history:changed 事件由 stack 的 onChanged 回调统一发射
|
|
516
|
+
}
|
|
517
|
+
|
|
355
518
|
// ─── Asset 管理 ──────────────────────────────────────
|
|
356
519
|
|
|
357
520
|
async importAsset(source: AssetSource): Promise<AssetId> {
|
|
@@ -394,13 +557,49 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
394
557
|
async exportAsset(id: AssetId, format?: string): Promise<Blob> {
|
|
395
558
|
const asset = await this.getAsset(id);
|
|
396
559
|
const blob = await this.assetStore.getBlob(asset.blob);
|
|
560
|
+
// OPFS 存储后端用 .bin 扩展名存储,读取时 fileHandle.getFile() 返回的
|
|
561
|
+
// File.type 可能为空字符串或 'application/octet-stream'(浏览器对未知扩展名
|
|
562
|
+
// 的默认兜底 MIME)。这两种情况都会导致 Object URL 的 Content-Type 退化,
|
|
563
|
+
// 下载时文件扩展名变成 .octet-stream。
|
|
564
|
+
// 用 asset metadata 的 mimeType 补全 Blob type(IDB/Memory 后端不受影响)。
|
|
565
|
+
const OPFS_FALLBACK_MIME = 'application/octet-stream';
|
|
566
|
+
const mimeType =
|
|
567
|
+
!blob.type || blob.type === OPFS_FALLBACK_MIME
|
|
568
|
+
? asset.metadata.mimeType
|
|
569
|
+
: blob.type;
|
|
570
|
+
// 关键:用 arrayBuffer() 显式读取数据到内存,再构造新 Blob。
|
|
571
|
+
// 不能用 new Blob([blob]) —— 浏览器实现中它可能延迟引用底层 OPFS 文件,
|
|
572
|
+
// WatermarkBatchTool 在 export 后立即 removeAsset 删除 OPFS 文件,
|
|
573
|
+
// 导致后续 downloadBlob 读取悬空引用失败("check internet connection")。
|
|
574
|
+
// arrayBuffer() 立即拉取数据,确保返回的 Blob 完全独立于底层存储。
|
|
575
|
+
const buffer = await blob.arrayBuffer();
|
|
576
|
+
const exported = new Blob([buffer], { type: mimeType });
|
|
397
577
|
this.eventBus.emit({
|
|
398
578
|
type: 'export:completed',
|
|
399
579
|
assetId: id,
|
|
400
580
|
format: format ?? asset.metadata.format,
|
|
401
581
|
size: blob.size,
|
|
402
582
|
});
|
|
403
|
-
return
|
|
583
|
+
return exported;
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* 读取 image 资产的 EXIF 元数据(W7.3/7.4 长期方案:MetadataReader 依赖反转)。
|
|
588
|
+
*
|
|
589
|
+
* Runtime 持有 plugin-image 通过 ctx.registerMetadataReader('image.read-exif', fn)
|
|
590
|
+
* 注册的 reader 引用,按名调用。reader 内部调 readExifFromBlob(exifr)。
|
|
591
|
+
* Plugin 未安装时优雅降级返回 null(不抛错)。
|
|
592
|
+
*
|
|
593
|
+
* 架构决策:readExif 是 Blob→ExifData 查询,不符合 Engine 层 Blob↔Blob 纯函数
|
|
594
|
+
* 约束,也不符合 Capability Asset[]→Asset[] 契约,故走 MetadataReader 机制,
|
|
595
|
+
* 不进 engine-image、不走 Capability execute。
|
|
596
|
+
*/
|
|
597
|
+
async readAssetExif(id: AssetId): Promise<ExifData | null> {
|
|
598
|
+
const asset = await this.getAsset(id);
|
|
599
|
+
if (asset.type !== 'image') return null;
|
|
600
|
+
const reader = this.metadataReaders.get('image.read-exif');
|
|
601
|
+
if (!reader) return null; // Plugin 未安装,优雅降级
|
|
602
|
+
return reader(asset) as Promise<ExifData | null>;
|
|
404
603
|
}
|
|
405
604
|
|
|
406
605
|
async removeAsset(id: AssetId): Promise<void> {
|
|
@@ -412,6 +611,23 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
412
611
|
return this.assetStore.list();
|
|
413
612
|
}
|
|
414
613
|
|
|
614
|
+
async getStorageUsage(): Promise<{ usage: number; quota: number }> {
|
|
615
|
+
// m6 优化:优先用配额包装器内部维护的 usage(O(1),import/create/remove
|
|
616
|
+
// 时增量更新),避免每次 O(n) 全量 listAssets 影响 StatusBar 刷新。
|
|
617
|
+
// 包装器未就绪(ensureInit 未完成)返回 -1 时,fallback 到 listAssets
|
|
618
|
+
// 实时计算(source of truth,与 W6.4 富元数据一致)。
|
|
619
|
+
//
|
|
620
|
+
// 类型说明:assetStore 字段类型为 QuotaAwareAssetStore(含 _getQuotaUsage),
|
|
621
|
+
// 由 wrapAssetStoreWithQuota 返回。无需重新断言 —— 类型信息未丢失。
|
|
622
|
+
const cached = this.assetStore._getQuotaUsage();
|
|
623
|
+
if (cached >= 0) {
|
|
624
|
+
return { usage: cached, quota: this.config.storageQuota };
|
|
625
|
+
}
|
|
626
|
+
const all = await this.assetStore.list();
|
|
627
|
+
const usage = all.reduce((sum, a) => sum + a.metadata.size, 0);
|
|
628
|
+
return { usage, quota: this.config.storageQuota };
|
|
629
|
+
}
|
|
630
|
+
|
|
415
631
|
// ─── 能力查询 ────────────────────────────────────────
|
|
416
632
|
|
|
417
633
|
async capabilities(): Promise<Capability[]> {
|
|
@@ -486,6 +702,13 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
486
702
|
return this.capabilityRegistry;
|
|
487
703
|
}
|
|
488
704
|
|
|
705
|
+
/**
|
|
706
|
+
* 获取 MemoryGuard(内部用,供集成测试驱动内存压力验证 BatchProcessor 收缩)。
|
|
707
|
+
*/
|
|
708
|
+
_getMemoryGuard(): MemoryGuard {
|
|
709
|
+
return this.memoryGuard;
|
|
710
|
+
}
|
|
711
|
+
|
|
489
712
|
/** 获取工作流当前输出 AssetId(undo/redo 后的"当前"状态,内部用) */
|
|
490
713
|
_getCurrentOutputs(workflowId: string): AssetId[] {
|
|
491
714
|
return this.currentOutputsMap.get(workflowId) ?? [];
|
|
@@ -543,6 +766,8 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
543
766
|
entries,
|
|
544
767
|
currentIndex,
|
|
545
768
|
});
|
|
769
|
+
// W7.2:持久化快照到 IndexedDB(加载期间跳过,避免冗余写回)
|
|
770
|
+
void this.persistHistory(wfId);
|
|
546
771
|
},
|
|
547
772
|
};
|
|
548
773
|
stack = new HistoryStack(workflowId, stackConfig);
|
|
@@ -590,6 +815,107 @@ export class LokvisRuntimeImpl implements LokvisRuntime {
|
|
|
590
815
|
// 更新当前输出为该 node 的 outputs
|
|
591
816
|
this.currentOutputsMap.set(event.workflowId, outputs);
|
|
592
817
|
}
|
|
818
|
+
|
|
819
|
+
// ─── 私有:历史持久化(W7.2) ────────────────────────
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* 把指定工作流的当前历史状态快照写入 historyStore。
|
|
823
|
+
*
|
|
824
|
+
* 时序修复:currentOutputs 从 stack snapshot 派生(cursor === -1 用
|
|
825
|
+
* initialInputs,否则用 entries[cursor].outputs),而非读 currentOutputsMap。
|
|
826
|
+
* 原因:onChanged 在 undo/redo/jumpTo/run 内部同步触发时,map 尚未更新,
|
|
827
|
+
* 会读到旧值(例如 run 后 append 触发 onChanged,但 currentOutputsMap 在
|
|
828
|
+
* append 返回后才 set)。
|
|
829
|
+
*
|
|
830
|
+
* 竞态安全:多个 fire-and-forget save 的 IDB readwrite 事务由 IndexedDB
|
|
831
|
+
* 引擎按发起顺序串行化(同 object store 不重叠),无需应用层加链。
|
|
832
|
+
*
|
|
833
|
+
* - entries 为空时改为 delete,避免残留空记录(reset/clear 后自然清理)
|
|
834
|
+
* - 加载期间(isLoadingHistory=true)跳过写回,但把 workflowId 加入
|
|
835
|
+
* dirtyDuringLoad,loadPersistedHistory 结束后补 persist(避免丢变更)
|
|
836
|
+
*/
|
|
837
|
+
private async persistHistory(workflowId: string): Promise<void> {
|
|
838
|
+
if (!this.historyStore) return;
|
|
839
|
+
if (this.isLoadingHistory) {
|
|
840
|
+
this.dirtyDuringLoad.add(workflowId);
|
|
841
|
+
return;
|
|
842
|
+
}
|
|
843
|
+
// fire-and-forget 调用方用 `void this.persistHistory(...)`,故内部必须
|
|
844
|
+
// try/catch,否则 IDB 故障(数据库关闭 / quota exceeded)会变成 unhandled
|
|
845
|
+
// promise rejection。历史持久化是非关键路径,失败只 warn 不抛。
|
|
846
|
+
try {
|
|
847
|
+
const stack = this.historyStacks.get(workflowId);
|
|
848
|
+
// 栈已从内存移除(disposeWorkflow / enforceHistoryStacksLimit 的 reset+delete
|
|
849
|
+
// 后异步到达此处)→ 删除持久化记录,避免孤儿数据跨会话残留
|
|
850
|
+
if (!stack) {
|
|
851
|
+
await this.historyStore.delete(workflowId);
|
|
852
|
+
return;
|
|
853
|
+
}
|
|
854
|
+
const { entries, cursor } = stack.snapshot();
|
|
855
|
+
if (entries.length === 0) {
|
|
856
|
+
await this.historyStore.delete(workflowId);
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
// 从 snapshot 派生 currentOutputs,而非读 currentOutputsMap —— 后者在
|
|
860
|
+
// onChanged 触发时尚未更新(见方法文档注释)
|
|
861
|
+
const initialInputs = this.initialInputsMap.get(workflowId) ?? [];
|
|
862
|
+
const currentOutputs = cursor === -1
|
|
863
|
+
? initialInputs
|
|
864
|
+
: (entries[cursor]?.outputs ?? initialInputs);
|
|
865
|
+
await this.historyStore.save({
|
|
866
|
+
workflowId,
|
|
867
|
+
entries,
|
|
868
|
+
cursor,
|
|
869
|
+
initialInputs,
|
|
870
|
+
currentOutputs,
|
|
871
|
+
updatedAt: Date.now(),
|
|
872
|
+
});
|
|
873
|
+
} catch (err) {
|
|
874
|
+
console.warn(
|
|
875
|
+
`[lokvis] persistHistory failed for workflow ${workflowId}:`,
|
|
876
|
+
err
|
|
877
|
+
);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
/**
|
|
882
|
+
* 从 historyStore 预加载所有持久化的历史快照,恢复到内存。
|
|
883
|
+
*
|
|
884
|
+
* 由 createRuntime 工厂在构造完 impl 后调用一次。加载期间置 isLoadingHistory
|
|
885
|
+
* 守卫,使 restore() 触发的 onChanged → persistHistory 跳过冗余写回;
|
|
886
|
+
* 但被跳过的 workflowId 记入 dirtyDuringLoad,加载结束后补 persist,
|
|
887
|
+
* 避免加载期间其他来源(run / undo / 外部事件)的变更被永久丢弃。
|
|
888
|
+
*
|
|
889
|
+
* 注意:restore 会 emit history:changed 事件,但此时 UI 尚未订阅
|
|
890
|
+
* (runtime-slice.init 在 createRuntime resolve 后才订阅),故无副作用。
|
|
891
|
+
*
|
|
892
|
+
* 非 LokvisRuntime 接口的一部分,仅为 impl 的初始化钩子(工厂调用)。
|
|
893
|
+
*/
|
|
894
|
+
async loadPersistedHistory(): Promise<void> {
|
|
895
|
+
if (!this.historyStore) return;
|
|
896
|
+
let records: Awaited<ReturnType<HistoryStore['loadAll']>> = [];
|
|
897
|
+
this.isLoadingHistory = true;
|
|
898
|
+
try {
|
|
899
|
+
records = await this.historyStore.loadAll();
|
|
900
|
+
for (const record of records) {
|
|
901
|
+
// 跳过空记录(理论上 save 已删除,双重防御)
|
|
902
|
+
if (record.entries.length === 0) continue;
|
|
903
|
+
const stack = this.getOrCreateHistoryStack(record.workflowId);
|
|
904
|
+
stack.restore({ entries: record.entries, cursor: record.cursor });
|
|
905
|
+
this.initialInputsMap.set(record.workflowId, record.initialInputs);
|
|
906
|
+
this.currentOutputsMap.set(record.workflowId, record.currentOutputs);
|
|
907
|
+
}
|
|
908
|
+
} finally {
|
|
909
|
+
this.isLoadingHistory = false;
|
|
910
|
+
// 加载期间被跳过的 persist 补发:逐个 await 保证顺序
|
|
911
|
+
// 复制一份避免补 persist 过程中新触发 onChanged → dirtyDuringLoad 死循环
|
|
912
|
+
const pending = [...this.dirtyDuringLoad];
|
|
913
|
+
this.dirtyDuringLoad.clear();
|
|
914
|
+
for (const wfId of pending) {
|
|
915
|
+
await this.persistHistory(wfId);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
}
|
|
593
919
|
}
|
|
594
920
|
|
|
595
921
|
/**
|
|
@@ -606,7 +932,17 @@ export async function createRuntime(
|
|
|
606
932
|
const assetStore =
|
|
607
933
|
config?.assetStore ??
|
|
608
934
|
(await createAssetStore({ preferOpfs: config?.enableOpfs ?? true }));
|
|
609
|
-
|
|
935
|
+
// W7.2:历史持久化 —— 优先用注入的 historyStore;否则在 enableIndexedDB 时
|
|
936
|
+
// 通过 createHistoryStore 自动创建(IDB 不可用时返回 undefined,退化仅内存)
|
|
937
|
+
const historyStore =
|
|
938
|
+
config?.historyStore ??
|
|
939
|
+
((config?.enableIndexedDB ?? true)
|
|
940
|
+
? createHistoryStore(config?.historyStoreOptions)
|
|
941
|
+
: undefined);
|
|
942
|
+
const impl = new LokvisRuntimeImpl({ ...config, assetStore, historyStore });
|
|
943
|
+
// 预加载持久化的历史快照(跨会话恢复 undo/redo 链)
|
|
944
|
+
await impl.loadPersistedHistory();
|
|
945
|
+
return impl;
|
|
610
946
|
}
|
|
611
947
|
|
|
612
948
|
/**
|
package/src/types.ts
CHANGED
|
@@ -11,12 +11,15 @@ import type {
|
|
|
11
11
|
AssetSource,
|
|
12
12
|
Capability,
|
|
13
13
|
EngineSelectionStrategy,
|
|
14
|
+
ExifData,
|
|
14
15
|
HistoryEntry,
|
|
15
16
|
McpManifest,
|
|
16
17
|
} from '@lokvis/schema';
|
|
17
18
|
import type { Workflow, WorkflowResult } from '@lokvis/schema';
|
|
18
19
|
import type { EventBus } from '@lokvis/schema';
|
|
19
20
|
import type { AssetStore } from './asset-store.js';
|
|
21
|
+
import type { BatchProcessor } from './batch-processor.js';
|
|
22
|
+
import type { HistoryStore, HistoryStoreOptions } from './history-store.js';
|
|
20
23
|
|
|
21
24
|
/** Runtime 配置 */
|
|
22
25
|
export interface RuntimeConfig {
|
|
@@ -40,6 +43,29 @@ export interface RuntimeConfig {
|
|
|
40
43
|
* 按 OPFS → IndexedDB → Memory 降级。
|
|
41
44
|
*/
|
|
42
45
|
assetStore?: AssetStore;
|
|
46
|
+
/**
|
|
47
|
+
* 注入自定义 HistoryStore(W7.2 历史持久化)。
|
|
48
|
+
* 默认由 createRuntime 在 enableIndexedDB 时通过 createHistoryStore 自动创建;
|
|
49
|
+
* IndexedDB 不可用时为 undefined,历史退化为仅内存模式。
|
|
50
|
+
*/
|
|
51
|
+
historyStore?: HistoryStore;
|
|
52
|
+
/**
|
|
53
|
+
* HistoryStore 工厂选项(W7.2,仅 historyStore 未注入时生效)。
|
|
54
|
+
* 测试可注入 dbInstance 或自定义 dbName。
|
|
55
|
+
*/
|
|
56
|
+
historyStoreOptions?: HistoryStoreOptions;
|
|
57
|
+
/**
|
|
58
|
+
* 是否启用 Pro 模式(W6.2 / PROJECT_PLAN 17.4)。
|
|
59
|
+
* - false(默认):批量上限 10 文件、并发 4、workflow 槽位 5
|
|
60
|
+
* - true:批量无上限、并发 16、workflow 槽位无限
|
|
61
|
+
* 由 cloud 侧 createLokvis({ auth }) 注入 session 后置为 true。
|
|
62
|
+
*/
|
|
63
|
+
isPro?: boolean;
|
|
64
|
+
/**
|
|
65
|
+
* 内存预算(字节,W3.3 MemoryGuard)。
|
|
66
|
+
* 默认 512MB。BatchProcessor 据此在内存压力高时收缩并发槽位。
|
|
67
|
+
*/
|
|
68
|
+
memoryBudget?: number;
|
|
43
69
|
}
|
|
44
70
|
|
|
45
71
|
/** Runtime 状态 */
|
|
@@ -74,6 +100,10 @@ export interface LokvisRuntime {
|
|
|
74
100
|
readonly status: RuntimeStatus;
|
|
75
101
|
/** 事件总线 */
|
|
76
102
|
readonly eventBus: EventBus;
|
|
103
|
+
/** 是否为 Pro 模式(影响批量上限/并发槽位/workflow 数,W6.2) */
|
|
104
|
+
readonly isPro: boolean;
|
|
105
|
+
/** 批量处理器(W6.1:并发控制 + 进度 + 失败重试) */
|
|
106
|
+
readonly batch: BatchProcessor;
|
|
77
107
|
|
|
78
108
|
// ─── 工作流执行 ──────────────────────────────────────
|
|
79
109
|
/** 运行工作流 */
|
|
@@ -104,10 +134,24 @@ export interface LokvisRuntime {
|
|
|
104
134
|
// ─── 历史与撤销 ──────────────────────────────────────
|
|
105
135
|
/** 获取工作流的执行历史 */
|
|
106
136
|
history(workflowId: string): Promise<HistoryEntry[]>;
|
|
137
|
+
/**
|
|
138
|
+
* 获取工作流历史状态(条目 + 当前游标)。
|
|
139
|
+
* 游标 -1 表示无已应用条目(初始状态);i 表示第 i 条已应用。
|
|
140
|
+
* 比 history() 多返回 cursor,UI 据此高亮当前步骤。
|
|
141
|
+
*/
|
|
142
|
+
getHistoryState(
|
|
143
|
+
workflowId: string
|
|
144
|
+
): Promise<{ entries: HistoryEntry[]; cursor: number }>;
|
|
107
145
|
/** 撤销一步 */
|
|
108
146
|
undo(workflowId: string): Promise<void>;
|
|
109
147
|
/** 重做一步 */
|
|
110
148
|
redo(workflowId: string): Promise<void>;
|
|
149
|
+
/**
|
|
150
|
+
* 跳转到指定历史条目(按时间顺序的索引,-1 表示回到初始)。
|
|
151
|
+
* 用于 HistoryPanel 点击条目直接跳转,等价于连续 undo/redo 到目标位置。
|
|
152
|
+
* 越界或游标未变时为 no-op。
|
|
153
|
+
*/
|
|
154
|
+
jumpTo(workflowId: string, index: number): Promise<void>;
|
|
111
155
|
|
|
112
156
|
// ─── Asset 管理 ──────────────────────────────────────
|
|
113
157
|
/** 导入资产 */
|
|
@@ -116,10 +160,36 @@ export interface LokvisRuntime {
|
|
|
116
160
|
getAsset(id: AssetId): Promise<Asset>;
|
|
117
161
|
/** 导出资产为 Blob */
|
|
118
162
|
exportAsset(id: AssetId, format?: string): Promise<Blob>;
|
|
163
|
+
/**
|
|
164
|
+
* 读取 image 资产的 EXIF 元数据(W7.3/7.4)。
|
|
165
|
+
*
|
|
166
|
+
* 长期方案(MetadataReader 依赖反转):Runtime 持有 plugin-image 通过
|
|
167
|
+
* `ctx.registerMetadataReader('image.read-exif', fn)` 注册的读取器引用,
|
|
168
|
+
* 按名调用。Plugin 未安装时优雅降级返回 null。
|
|
169
|
+
* readExif 实现位于 plugin-image(Capability 层),不进 engine-image
|
|
170
|
+
* (不符合 Engine 层 Blob↔Blob 纯函数约束)。
|
|
171
|
+
* UI 通过此方法访问 EXIF,不直接依赖 Engine/Plugin 包(五层架构单向依赖)。
|
|
172
|
+
*
|
|
173
|
+
* @param id 资产 ID(须为 image 类型)
|
|
174
|
+
* @returns ExifData;非 image / 无 EXIF / 解析失败 / reader 未注册返回 null
|
|
175
|
+
*/
|
|
176
|
+
readAssetExif(id: AssetId): Promise<ExifData | null>;
|
|
119
177
|
/** 删除资产 */
|
|
120
178
|
removeAsset(id: AssetId): Promise<void>;
|
|
121
179
|
/** 列出所有资产 */
|
|
122
180
|
listAssets(): Promise<Asset[]>;
|
|
181
|
+
/**
|
|
182
|
+
* 查询存储配额使用情况(W6.7)。
|
|
183
|
+
*
|
|
184
|
+
* 返回 `{ usage, quota }`:
|
|
185
|
+
* - `usage`:当前已用字节数(所有资产 metadata.size 之和)
|
|
186
|
+
* - `quota`:配置的存储配额上限(RuntimeConfig.storageQuota,默认 1GB)
|
|
187
|
+
*
|
|
188
|
+
* UI 据此展示"已用/总额"进度条,接近上限(>=80%)时警告。
|
|
189
|
+
* 注意:usage 基于 listAssets 实时计算,反映 runtime 实际占用,
|
|
190
|
+
* 与浏览器 `navigator.storage.estimate()`(origin 整体 OPFS)不同。
|
|
191
|
+
*/
|
|
192
|
+
getStorageUsage(): Promise<{ usage: number; quota: number }>;
|
|
123
193
|
|
|
124
194
|
// ─── 能力查询 ────────────────────────────────────────
|
|
125
195
|
/** 列出所有已注册能力 */
|