fix(runtime): 本地任务恢复 - 恢复本地画布和延迟视频任务

This commit is contained in:
ddCat committed 2026-08-18 15:16:05 +08:00
1 parent ea657f179d
commit bda114b29e
13 files changed
+739 -67

No files matched your search

+67
View File
@@ -98,6 +98,73 @@ test("Canvas Agent UI store contains no Runtime endpoint, bearer, or session fie
expect("session" in state).toBe(false);
});
test("Canvas Agent reconnect intent persists while transient disconnects preserve the active conversation", async () => {
const module = await import("../src/stores/canvas/use-canvas-agent-store").catch(() => ({}));
const connectionStartingPatch = (
module as {
canvasAgentConnectionStartingPatch?: () => Record<string, unknown>;
}
).canvasAgentConnectionStartingPatch;
const transientDisconnectPatch = (
module as {
canvasAgentTransientDisconnectPatch?: (activity: string, connectError: string) => Record<string, unknown>;
}
).canvasAgentTransientDisconnectPatch;
const writeEnabled = (
module as {
writeCanvasAgentEnabledPreference?: (enabled: boolean, storage: { setItem(key: string, value: string): void }) => void;
}
).writeCanvasAgentEnabledPreference;
const readEnabled = (
module as {
readCanvasAgentEnabledPreference?: (storage: { getItem(key: string): string | null }) => boolean;
}
).readCanvasAgentEnabledPreference;
expect(typeof connectionStartingPatch).toBe("function");
expect(typeof transientDisconnectPatch).toBe("function");
expect(typeof writeEnabled).toBe("function");
expect(typeof readEnabled).toBe("function");
if (!connectionStartingPatch || !transientDisconnectPatch || !writeEnabled || !readEnabled) return;
const durable = {
messages: [{ id: "message-1", role: "assistant", text: "kept" }],
threads: [{ id: "thread-1", preview: "kept" }],
activeThreadId: "thread-1",
workspacePath: "D:/workspace",
pendingTool: { requestId: "tool-1", name: "canvas_get_state" },
};
const starting = { ...durable, ...connectionStartingPatch() };
expect(starting).toMatchObject({ enabled: true, connected: false, activity: "连接中", ...durable });
const reconnecting = { ...starting, ...transientDisconnectPatch("正在重连", "连接已断开") };
expect(reconnecting).toMatchObject({ enabled: true, connected: false, activity: "正在重连", connectError: "连接已断开", ...durable });
const values = new Map<string, string>();
const storage = {
getItem: (key: string) => values.get(key) ?? null,
setItem: (key: string, value: string) => values.set(key, value),
};
writeEnabled(true, storage);
expect(readEnabled(storage)).toBe(true);
writeEnabled(false, storage);
expect(readEnabled(storage)).toBe(false);
});
test("Canvas Agent status shows reconnecting instead of a stale connection failure", async () => {
const module = await import("../src/stores/canvas/use-canvas-agent-store").catch(() => ({}));
const statusText = (
module as {
canvasAgentConnectionStatusText?: (state: { enabled: boolean; connected: boolean; activity: string; connectError: string }) => string;
}
).canvasAgentConnectionStatusText;
expect(typeof statusText).toBe("function");
if (!statusText) return;
expect(statusText({ enabled: true, connected: false, activity: "正在重连", connectError: "连接已断开" })).toBe("正在重连");
expect(statusText({ enabled: true, connected: false, activity: "连接失败", connectError: "首次连接失败" })).toBe("连接失败");
});
test("Canvas connection reuses the shared Runtime store and requires the canvas module", async () => {
const module = await import("../src/lib/canvas/local-runtime-connection");
const prepare = (
+134
View File
@@ -335,6 +335,140 @@ test("shared Create and Canvas task projection exposes queued, submitted, genera
expect(distinctUpdates[4]?.resultJson).toContain('"mode":"video"');
});
test("the first local Dreamina submission waits for catalog readiness before invoking the paid Runtime path", async () => {
const order: string[] = [];
let release!: () => void;
const readyGate = new Promise<void>((resolve) => {
release = resolve;
});
const pending = runBackendGenerationTask(
{
mode: "video",
prompt: "first visit",
config: { ...defaultConfig, model: "local:dreamina-cli:seedance2.0mini", videoSeconds: "4", vquality: "720" },
},
{
createTask: async () => {
throw new Error("must not create backend task");
},
waitTask: async () => {
throw new Error("must not wait backend task");
},
ensureLocalDreaminaReady: async () => {
order.push("catalog-start");
await readyGate;
order.push("catalog-ready");
},
runLocal: async () => {
order.push("paid-runtime");
return { mode: "video", video: { dataUrl: "data:video/mp4;base64,AAAA", mimeType: "video/mp4", bytes: 3 } };
},
createId: () => "dreamina-first-ready-0001",
now: () => "2026-08-18T00:00:00.000Z",
},
);
await Promise.resolve();
expect(order).toEqual(["catalog-start"]);
release();
await pending;
expect(order).toEqual(["catalog-start", "catalog-ready", "paid-runtime"]);
});
test("the first local Dreamina batch shares one catalog readiness gate before any paid Runtime call", async () => {
const order: string[] = [];
let release!: () => void;
const readyGate = new Promise<void>((resolve) => {
release = resolve;
});
const pending = runBackendGenerationTaskBatch(
{
mode: "image",
prompt: "first batch",
config: { ...defaultConfig, model: "local:dreamina-cli:5.0Pro", count: "1" },
count: 3,
},
{
createTask: async () => {
throw new Error("must not create backend task");
},
waitTask: async () => {
throw new Error("must not wait backend task");
},
ensureLocalDreaminaReady: async () => {
order.push("catalog-start");
await readyGate;
order.push("catalog-ready");
},
runLocal: async () => {
order.push("paid-runtime");
return { mode: "image", images: [{ dataUrl: "data:image/png;base64,AAAA", mimeType: "image/png", bytes: 3 }] };
},
createId: () => `dreamina-first-batch-${order.length}`,
now: () => "2026-08-18T00:00:00.000Z",
},
);
await Promise.resolve();
expect(order).toEqual(["catalog-start"]);
release();
const settled = await pending;
expect(settled.every((entry) => entry.status === "fulfilled")).toBe(true);
expect(order).toEqual(["catalog-start", "catalog-ready", "paid-runtime", "paid-runtime", "paid-runtime"]);
});
test("local Dreamina terminal projection keeps the latest receipt, observation, and durable outputs", async () => {
const updates: GenerationTask[] = [];
const timestamp = "2026-08-18T00:00:00.000Z";
await runBackendGenerationTask(
{
mode: "video",
prompt: "late result",
config: { ...defaultConfig, model: "local:dreamina-cli:seedance2.0mini", videoSeconds: "4", vquality: "720" },
onTaskUpdate: (task) => updates.push(task),
},
{
createTask: async () => {
throw new Error("must not create backend task");
},
waitTask: async () => {
throw new Error("must not wait backend task");
},
runLocal: async (input, _signal, onTaskUpdate) => {
onTaskUpdate?.({
id: input.idempotencyKey!,
provider: "dreamina-cli",
mode: "video",
operation: "text2video",
model: "seedance2.0mini",
status: "succeeded",
stage: "succeeded",
progress: 100,
receiptRecorded: true,
officialStatus: "completed",
providerObservation: { source: "query_result", status: "completed", observedAt: timestamp },
outputs: [{ outputIndex: 0, mediaType: "video", materializedAssetId: "asset-late-0001" }],
result: { mode: "video", video: { dataUrl: "data:video/mp4;base64,AAAA", mimeType: "video/mp4", bytes: 3 } },
createdAt: timestamp,
updatedAt: timestamp,
});
return { mode: "video", video: { dataUrl: "data:video/mp4;base64,AAAA", mimeType: "video/mp4", bytes: 3 } };
},
createId: () => "dreamina-latest-context-0001",
now: () => timestamp,
},
);
expect(updates.at(-1)).toMatchObject({
status: "succeeded",
stage: "local_cli_succeeded",
receiptRecorded: true,
officialStatus: "completed",
outputs: [{ outputIndex: 0, mediaType: "video", materializedAssetId: "asset-late-0001" }],
});
expect(updates.at(-1)?.resultJson).toContain('"mode":"video"');
});
test("an explicitly cancelled Dreamina task stays cancelled instead of being projected as failed", async () => {
const updates: Array<{ status: string; stage?: string }> = [];
const timestamp = "2026-08-12T00:00:00.000Z";
@@ -213,6 +213,128 @@ test("effective config projects an asynchronously arriving Dreamina catalog with
expect(defaultConfig.channels.some((channel) => channel.id === "local:dreamina-cli")).toBe(false);
});
test("Dreamina catalog readiness is loading immediately and shares one in-flight bootstrap", async () => {
const module = await import("../src/stores/use-local-dreamina-model-store").catch(() => ({}));
const createStore = (
module as {
createLocalDreaminaModelStore?: (dependencies: Record<string, unknown>) => {
getState(): {
state: string;
models: Array<{ id: string }>;
ensureReady(signal?: AbortSignal): Promise<Array<{ id: string }>>;
};
};
}
).createLocalDreaminaModelStore;
expect(typeof createStore).toBe("function");
if (!createStore) return;
let requests = 0;
let release!: () => void;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const store = createStore({
getRuntimeState: () => ({ connection: "connected", modules: [{ id: "dreamina", scopes: ["dreamina:models"] }] }),
getClient: () => ({ request: async () => catalogResponse() }),
loadSnapshot: async () => {
requests += 1;
await gate;
return {
accountBinding: "a".repeat(64),
sessionEpoch: 3,
models: [
{
provider: "dreamina-cli",
id: "seedance2.0mini",
displayName: "seedance2.0mini",
modality: "video",
operations: ["text-to-video"],
adapterSupported: true,
accountEntitlement: "unknown",
currentlyObservedAvailable: "unknown",
settings: { aliases: [], aspects: ["16:9"], maxReferenceImages: 9, minDuration: 4, maxDuration: 15, tiers: ["720p"] },
source: "runtime-execution-contract",
},
],
};
},
});
const first = store.getState().ensureReady();
const second = store.getState().ensureReady();
expect(store.getState().state).toBe("loading");
expect(requests).toBe(1);
release();
const [firstModels, secondModels] = await Promise.all([first, second]);
expect(firstModels.map((item) => item.id)).toEqual(["seedance2.0mini"]);
expect(secondModels).toEqual(firstModels);
expect(store.getState()).toMatchObject({ state: "ready", cacheScope: `${"a".repeat(64)}:3` });
expect(requests).toBe(1);
});
test("Dreamina catalog timeout releases a hung shared request so generation can recover without reload", async () => {
const { createLocalDreaminaModelStore } = await import("../src/stores/use-local-dreamina-model-store");
let requests = 0;
const store = createLocalDreaminaModelStore({
getRuntimeState: () => ({ connection: "connected", modules: [{ id: "dreamina", scopes: ["dreamina:models"] }] }),
getClient: () => ({ request: async () => catalogResponse() }),
requestTimeoutMs: 10,
loadSnapshot: async (_client, signal) => {
requests += 1;
if (requests > 1) return catalogSnapshot("seedance-recovered", 4);
if (!signal) return await new Promise<ReturnType<typeof catalogSnapshot>>(() => undefined);
return await new Promise<ReturnType<typeof catalogSnapshot>>((_resolve, reject) => {
signal.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
});
},
});
const caller = new AbortController();
const first = store.getState().ensureReady(caller.signal);
caller.abort();
await expect(first).rejects.toMatchObject({ name: "AbortError" });
await Bun.sleep(20);
const recovered = await Promise.race([
store.getState().ensureReady(),
Bun.sleep(40).then(() => "stuck" as const),
]);
expect(recovered).not.toBe("stuck");
expect(recovered).toMatchObject([{ id: "seedance-recovered" }]);
expect(store.getState()).toMatchObject({ state: "ready", cacheScope: `${"a".repeat(64)}:4` });
expect(requests).toBe(2);
});
test("Dreamina catalog forced resync ignores a late result from the previous Runtime scope", async () => {
const { createLocalDreaminaModelStore } = await import("../src/stores/use-local-dreamina-model-store");
let requests = 0;
let releaseOld!: (snapshot: ReturnType<typeof catalogSnapshot>) => void;
const oldRequest = new Promise<ReturnType<typeof catalogSnapshot>>((resolve) => {
releaseOld = resolve;
});
const store = createLocalDreaminaModelStore({
getRuntimeState: () => ({ connection: "connected", modules: [{ id: "dreamina", scopes: ["dreamina:models"] }] }),
getClient: () => ({ request: async () => catalogResponse() }),
requestTimeoutMs: 100,
loadSnapshot: async () => {
requests += 1;
return requests === 1 ? oldRequest : catalogSnapshot("seedance-current", 5);
},
});
const oldSync = store.getState().sync();
const currentSync = store.getState().sync();
const currentResult = await Promise.race([currentSync.then(() => "ready" as const), Bun.sleep(40).then(() => "stuck" as const)]);
expect(currentResult).toBe("ready");
expect(requests).toBe(2);
expect(store.getState()).toMatchObject({ state: "ready", cacheScope: `${"a".repeat(64)}:5`, models: [{ id: "seedance-current" }] });
releaseOld(catalogSnapshot("seedance-stale", 3));
await oldSync;
expect(store.getState()).toMatchObject({ state: "ready", cacheScope: `${"a".repeat(64)}:5`, models: [{ id: "seedance-current" }] });
});
test("effective config removes custom channels when administrators disable them", async () => {
const { createModelChannel, effectiveConfigForCustomChannels, normalizeConfigSnapshot } = await import("../src/stores/use-config-store");
const config = normalizeConfigSnapshot({
@@ -264,3 +386,24 @@ function catalogResponse() {
{ status: 200, headers: { "content-type": "application/json" } },
);
}
function catalogSnapshot(id: string, sessionEpoch: number) {
return {
accountBinding: "a".repeat(64),
sessionEpoch,
models: [
{
provider: "dreamina-cli" as const,
id,
displayName: id,
modality: "video" as const,
operations: ["text-to-video" as const],
adapterSupported: true,
accountEntitlement: "unknown" as const,
currentlyObservedAvailable: "unknown" as const,
settings: { aliases: [], aspects: ["16:9"], maxReferenceImages: 9, minDuration: 4, maxDuration: 15, tiers: ["720p"] },
source: "runtime-execution-contract" as const,
},
],
};
}