Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

feat(cindy-brain): 插件管子长任务续命 + cindy 槽视频代办异步形态 (#303)

Dash64fefea646ab
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
index aeac940b25..ea0be4666e 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/cindySlot.test.ts
@@ -481,3 +481,218 @@ describe('改图代办(edit_image)', () => {
expect(editImage).not.toHaveBeenCalled();
});
});
+
+describe('管子续命挂钩(同步视频代办 hold/release)', () => {
+ it('署名视频代办 hold 预算 = expected×3;完成后 release', async () => {
+ const holdPipeCall = vi.fn();
+ const releasePipeCall = vi.fn();
+ const { slot } = makeSlot({
+ holdPipeCall,
+ releasePipeCall,
+ videoExpectedSeconds: vi.fn(() => 300),
+ } as Partial<CindySlotDeps>);
+ const r = await slot.handleModelRequest('art', {
+ type: 'cindy-request',
+ kind: 'gen_video',
+ prompt: '一只猫奔跑',
+ callId: 'call-9',
+ });
+ expect(r).toMatchObject({ ok: true });
+ expect(holdPipeCall).toHaveBeenCalledWith('art', 'call-9', 900_000);
+ expect(releasePipeCall).toHaveBeenCalledWith('art', 'call-9');
+ });
+
+ it('生成失败同样 release;未署名(无 callId)与图片代办不 hold', async () => {
+ const holdPipeCall = vi.fn();
+ const releasePipeCall = vi.fn();
+ const { slot } = makeSlot({
+ holdPipeCall,
+ releasePipeCall,
+ generateVideo: vi.fn(async () => {
+ throw new Error('通道爆炸');
+ }),
+ } as Partial<CindySlotDeps>);
+ const failed = await slot.handleModelRequest('art', {
+ type: 'cindy-request',
+ kind: 'gen_video',
+ prompt: 'x',
+ callId: 'call-f',
+ });
+ expect(failed).toMatchObject({ ok: false });
+ expect(holdPipeCall).toHaveBeenCalledWith('art', 'call-f', 120 * 3 * 1000); // 未注入 expected → 缺省 120s
+ expect(releasePipeCall).toHaveBeenCalledWith('art', 'call-f');
+
+ holdPipeCall.mockClear();
+ await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'gen_video', prompt: 'x' });
+ expect(holdPipeCall).not.toHaveBeenCalled(); // 未署名单不 hold
+
+ await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'gen_image', prompt: 'x', callId: 'c' });
+ expect(holdPipeCall).not.toHaveBeenCalled(); // 图片代办不 hold
+ });
+});
+
+describe('异步任务(mode:submit / query_job)', () => {
+ function deferred<T>(): { promise: Promise<T>; resolve: (v: T) => void; reject: (e: unknown) => void } {
+ let resolve!: (v: T) => void;
+ let reject!: (e: unknown) => void;
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+ }
+
+ const SUBMIT_REQ = {
+ type: 'cindy-request',
+ kind: 'gen_video',
+ prompt: '一只猫奔跑',
+ mode: 'submit',
+ callId: 'call-a',
+ };
+
+ it('submit 受理即返回 running + jobId;完成后 query 取件,记账带归因号', async () => {
+ const d = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const { slot, saveGhostMedia } = makeSlot({
+ generateVideo: vi.fn(() => d.promise),
+ videoExpectedSeconds: vi.fn(() => 300),
+ } as Partial<CindySlotDeps>);
+
+ const r = await slot.handleModelRequest('art', SUBMIT_REQ);
+ expect(r).toMatchObject({ ok: true, status: 'running', expectedSeconds: 300 });
+ const jobId = (r as { jobId: string }).jobId;
+ expect(jobId.length).toBeGreaterThan(10);
+
+ const q1 = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(q1).toMatchObject({ ok: true, status: 'running' });
+
+ d.resolve({ buffer: new Uint8Array([7, 8, 9]), mimeType: 'video/mp4' });
+ await vi.waitFor(async () => {
+ const q = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(q).toMatchObject({ ok: true, status: 'done', url: 'cindy-media://blobs/abc.png' });
+ });
+ expect(saveGhostMedia).toHaveBeenCalledWith(expect.objectContaining({ ghostId: 'art', callId: 'call-a' }));
+ // 完成结果 TTL 内可反复查(幂等)。
+ const again = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(again).toMatchObject({ ok: true, status: 'done' });
+ });
+
+ it('别的意识查不到我的任务(统一话术不泄露存在性)', async () => {
+ const d = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const { slot } = makeSlot({ generateVideo: vi.fn(() => d.promise) } as Partial<CindySlotDeps>);
+ const r = await slot.handleModelRequest('art', SUBMIT_REQ);
+ const jobId = (r as { jobId: string }).jobId;
+
+ const q = await slot.handleModelRequest('other', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(q).toMatchObject({ ok: false });
+ expect((q as { message: string }).message).toContain('查无此任务');
+ d.resolve({ buffer: new Uint8Array([1]), mimeType: 'video/mp4' });
+ });
+
+ it('后台生成失败 → query 返回结构化失败(人话动词 + 原因)', async () => {
+ const d = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const { slot } = makeSlot({ generateVideo: vi.fn(() => d.promise) } as Partial<CindySlotDeps>);
+ const r = await slot.handleModelRequest('art', SUBMIT_REQ);
+ const jobId = (r as { jobId: string }).jobId;
+
+ d.reject(new Error('通道爆炸'));
+ await vi.waitFor(async () => {
+ const q = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(q).toMatchObject({ ok: false });
+ expect((q as { message: string }).message).toContain('生成视频失败:通道爆炸');
+ });
+ });
+
+ it('后台在途上限:第 3 单拒;完成一单后放行', async () => {
+ const d1 = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const d2 = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const gen = vi
+ .fn<() => Promise<{ buffer: Uint8Array; mimeType: string }>>()
+ .mockImplementationOnce(() => d1.promise)
+ .mockImplementationOnce(() => d2.promise);
+ const { slot } = makeSlot({ generateVideo: gen } as Partial<CindySlotDeps>);
+
+ expect(await slot.handleModelRequest('art', SUBMIT_REQ)).toMatchObject({ ok: true });
+ expect(await slot.handleModelRequest('art', SUBMIT_REQ)).toMatchObject({ ok: true });
+ const third = await slot.handleModelRequest('art', SUBMIT_REQ);
+ expect(third).toMatchObject({ ok: false });
+ expect((third as { message: string }).message).toContain('上限');
+
+ d1.resolve({ buffer: new Uint8Array([1]), mimeType: 'video/mp4' });
+ await vi.waitFor(async () => {
+ expect(await slot.handleModelRequest('art', SUBMIT_REQ)).toMatchObject({ ok: true });
+ });
+ d2.resolve({ buffer: new Uint8Array([2]), mimeType: 'video/mp4' });
+ });
+
+ it('图像代办不支持 submit;mode 乱值拒;jobId 形状不合法拒', async () => {
+ const { slot, generateImage } = makeSlot();
+ const img = await slot.handleModelRequest('art', {
+ type: 'cindy-request',
+ kind: 'gen_image',
+ prompt: 'x',
+ mode: 'submit',
+ });
+ expect(img).toMatchObject({ ok: false });
+ expect((img as { message: string }).message).toContain('视频类');
+ expect(generateImage).not.toHaveBeenCalled();
+
+ expect(
+ await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'gen_video', prompt: 'x', mode: 'async' }),
+ ).toMatchObject({ ok: false });
+ expect(
+ await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId: '' }),
+ ).toMatchObject({ ok: false });
+ expect(
+ await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId: 'x'.repeat(65) }),
+ ).toMatchObject({ ok: false });
+ });
+
+ it('完成态记录按意识限额淘汰最旧(快速失败循环不无限堆表)', async () => {
+ const { slot } = makeSlot({
+ generateVideo: vi.fn(async () => {
+ throw new Error('立即失败');
+ }),
+ } as Partial<CindySlotDeps>);
+
+ const jobIds: string[] = [];
+ for (let i = 0; i < 20; i++) {
+ const r = await slot.handleModelRequest('art', SUBMIT_REQ);
+ expect(r).toMatchObject({ ok: true, status: 'running' });
+ jobIds.push((r as { jobId: string }).jobId);
+ // 让后台链落定(失败出 running 态),下一单才不会被在途闸拦。
+ await vi.waitFor(async () => {
+ const q = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId: jobIds[i] });
+ expect(q).toMatchObject({ ok: false });
+ });
+ }
+
+ // 最早的记录已被限额淘汰(话术与过期一致:查无此任务)。
+ const oldest = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId: jobIds[0] });
+ expect((oldest as { message: string }).message).toContain('查无此任务');
+ // 最近完成的仍在保留窗内可查(失败原因原样返回)。
+ const latest = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId: jobIds[19] });
+ expect((latest as { message: string }).message).toContain('立即失败');
+ });
+
+ it('完成结果过 TTL 清理 → 查无此任务', async () => {
+ vi.useFakeTimers();
+ try {
+ const d = deferred<{ buffer: Uint8Array; mimeType: string }>();
+ const { slot } = makeSlot({ generateVideo: vi.fn(() => d.promise) } as Partial<CindySlotDeps>);
+ const r = await slot.handleModelRequest('art', SUBMIT_REQ);
+ const jobId = (r as { jobId: string }).jobId;
+
+ d.resolve({ buffer: new Uint8Array([1]), mimeType: 'video/mp4' });
+ await vi.advanceTimersByTimeAsync(0); // flush 后台链 microtasks
+ const done = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(done).toMatchObject({ ok: true, status: 'done' });
+
+ vi.advanceTimersByTime(31 * 60_000);
+ const gone = await slot.handleModelRequest('art', { type: 'cindy-request', kind: 'query_job', jobId });
+ expect(gone).toMatchObject({ ok: false });
+ expect((gone as { message: string }).message).toContain('查无此任务');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
index ce30b102ee..ffd5771707 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/pipeDispatcher.test.ts
@@ -248,6 +248,132 @@ describe('超时与收卷', () => {
});
});
+describe('长任务续命(hold / release / tool-progress)', () => {
+ beforeEach(() => vi.useFakeTimers());
+ afterEach(() => vi.useRealTimers());
+
+ it('holdCall 把窗口延到代办预算 + 交卷余量;原基础窗口过点不超时', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));
+ const callId = h.sent[0].callId;
+
+ h.dispatcher.holdCall('art', callId, 5_000); // deadline = 5000 + 60_000 余量
+ vi.advanceTimersByTime(64_999);
+ expect(h.dispatcher.pendingCount()).toBe(1);
+ vi.advanceTimersByTime(1);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+ });
+
+ it('releaseCall 收回长 hold(不短于基础窗口 + 交卷余量);多单代办计数归零才收', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));
+ const callId = h.sent[0].callId;
+
+ h.dispatcher.holdCall('art', callId, 600_000);
+ h.dispatcher.holdCall('art', callId, 600_000);
+ vi.advanceTimersByTime(10_000);
+
+ h.dispatcher.releaseCall('art', callId); // 还有一单在途:不收
+ vi.advanceTimersByTime(120_000); // t=130_000,若已收(70_000 到点)早超了
+ expect(h.dispatcher.pendingCount()).toBe(1);
+
+ h.dispatcher.releaseCall('art', callId); // 全部收工:收到 now + 60_000 余量
+ vi.advanceTimersByTime(59_999);
+ expect(h.dispatcher.pendingCount()).toBe(1);
+ vi.advanceTimersByTime(1);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+ });
+
+ it('tool-progress 心跳每次续满一个基础档;验身与配对同交卷纪律', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));
+ const callId = h.sent[0].callId;
+
+ vi.advanceTimersByTime(800);
+ // 冒名心跳:拒,且不影响窗口。
+ expect(h.dispatcher.handleToolProgress('evil-ghost', { callId }).accepted).toBe(false);
+ // 载荷非法 / 查无 callId:拒不炸。
+ expect(h.dispatcher.handleToolProgress('art', {}).accepted).toBe(false);
+ expect(h.dispatcher.handleToolProgress('art', { callId: 'ghost-town' }).accepted).toBe(false);
+
+ expect(h.dispatcher.handleToolProgress('art', { callId }).accepted).toBe(true); // t=800 → 续到 1800
+ vi.advanceTimersByTime(999);
+ expect(h.dispatcher.pendingCount()).toBe(1);
+ vi.advanceTimersByTime(1);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+ });
+
+ it('续命从派发起算不越过 30 分钟天花板;超时后 hold/心跳皆无效', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ // 天花板从派发时刻起算:这里不用 vi.waitFor(fake timers 下它会偷偷
+ // advance 虚拟时钟,把绝对边界打偏);running 态派发是同步完成的。
+ expect(h.sent).toHaveLength(1);
+ const callId = h.sent[0].callId;
+
+ h.dispatcher.holdCall('art', callId, 10 * 3600_000); // 10 小时预算 → 钳到 30 分钟
+ vi.advanceTimersByTime(30 * 60_000 - 1);
+ expect(h.dispatcher.pendingCount()).toBe(1);
+ vi.advanceTimersByTime(1);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+
+ // 已收卷:心跳拒;hold 静默无害。
+ expect(h.dispatcher.handleToolProgress('art', { callId }).accepted).toBe(false);
+ h.dispatcher.holdCall('art', callId, 1000);
+ expect(h.dispatcher.pendingCount()).toBe(0);
+ });
+
+ it('hold 期间正常交卷照常 resolve', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));
+ const callId = h.sent[0].callId;
+
+ h.dispatcher.holdCall('art', callId, 600_000);
+ vi.advanceTimersByTime(200_000);
+ const outcome = h.dispatcher.handleToolResult('art', {
+ type: 'tool-result',
+ callId,
+ ok: true,
+ result: { url: 'cindy-media://blobs/v.mp4' },
+ });
+ expect(outcome.accepted).toBe(true);
+ await expect(p).resolves.toEqual({ ok: true, result: { url: 'cindy-media://blobs/v.mp4' } });
+ });
+
+ it('hold/release 验身:冒用别人在途的 callId 不能续命、不能收短、不污染计数', async () => {
+ const h = makeHarness({ timeoutMs: 1000 });
+ const p = h.dispatcher.callGhostTool(CALL);
+ await vi.waitFor(() => expect(h.sent).toHaveLength(1));
+ const callId = h.sent[0].callId;
+
+ // 冒名 hold:不生效,窗口仍按基础档到点。
+ h.dispatcher.holdCall('evil-ghost', callId, 600_000);
+ // 真主人 hold 后,冒名 release 也收不走(计数未被污染)。
+ h.dispatcher.holdCall('art', callId, 600_000);
+ h.dispatcher.releaseCall('evil-ghost', callId);
+ vi.advanceTimersByTime(200_000); // 若冒名 release 生效,60s 余量早已到点
+ expect(h.dispatcher.pendingCount()).toBe(1);
+
+ h.dispatcher.releaseCall('art', callId);
+ vi.advanceTimersByTime(60_000);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+ });
+
+ it('注入超大 timeoutMs 被钳到天花板,初始窗口不越界', async () => {
+ const h = makeHarness({ timeoutMs: 2 * 3600_000 }); // 2 小时 → 钳到 30 分钟
+ const p = h.dispatcher.callGhostTool(CALL);
+ expect(h.sent).toHaveLength(1);
+ vi.advanceTimersByTime(30 * 60_000 - 1);
+ expect(h.dispatcher.pendingCount()).toBe(1);
+ vi.advanceTimersByTime(1);
+ await expect(p).resolves.toMatchObject({ ok: false, errorCode: 'TIMEOUT' });
+ });
+});
+
describe('预铸 callId(卡槽③贯通)', () => {
it('传入 callId 时下行载荷使用同一值;交卷按它配对', async () => {
const h = makeHarness();
diff --git a/apps/desktop/src/main/cindy-brain/cindySlot.ts b/apps/desktop/src/main/cindy-brain/cindySlot.ts
index 489badf423..ad49d18452 100644
--- a/apps/desktop/src/main/cindy-brain/cindySlot.ts
+++ b/apps/desktop/src/main/cindy-brain/cindySlot.ts
@@ -22,7 +22,11 @@
* 依赖注入(规则 14):生成/落盘/记账/归属解析全部经 deps,单测直测。
*/
+import { randomUUID } from 'node:crypto';
+
import {
+ GHOST_CINDY_JOB_TTL_MS,
+ GHOST_CINDY_MAX_ASYNC_JOBS,
GHOST_MODEL_TIERS,
type GhostModelTier,
type GhostPipeModelResult,
@@ -92,6 +96,20 @@ export interface CindySlotDeps {
/** tool-call callId(记入 ghostMediaLedger 供 ghost_call 收口带回)。 */
callId?: string;
}): Promise<{ url: string; hash: string; ext: string }>;
+ /**
+ * 管子续命挂钩(pipeDispatcher.holdCall/releaseCall 接线):tool-call
+ * 触发的同步视频代办开始时 hold(budgetMs = 这单的轮询预算),结束时
+ * release——署名单在途期间管子不再按 330s 掐掉。ghostId = 主机反查的
+ * 代办发起方,派发器按它配对验身(冒用别人的 callId 不生效)。可选
+ * 依赖:不注入(纯测试环境)等同不续命。
+ */
+ holdPipeCall?(ghostId: string, callId: string, budgetMs: number): void;
+ releasePipeCall?(ghostId: string, callId: string): void;
+ /**
+ * 视频型号预期耗时(秒;video registry 登记值)。hold 预算与异步受理
+ * 返回的 expectedSeconds 共用。未注入/查无该型号 → null(用缺省)。
+ */
+ videoExpectedSeconds?(model: string): number | null;
log?: {
info: (msg: string, meta?: Record<string, unknown>) => void;
warn: (msg: string, meta?: Record<string, unknown>) => void;
@@ -110,6 +128,41 @@ const MAX_VIDEO_SOURCES = 2;
/** 归因号长度上限(tool-call 配对号量级;超长视为沙箱乱填,拒单防日志注水)。 */
const MAX_CALL_ID_LEN = 128;
+/** 视频预期耗时缺省(秒;与 video/run.ts 的缺省同口径)。 */
+const DEFAULT_VIDEO_EXPECTED_SECONDS = 120;
+
+/** 异步任务号长度上限(主机铸 UUID 量级;超长视为沙箱乱填)。 */
+const MAX_JOB_ID_LEN = 64;
+
+/**
+ * 每意识完成态(done/failed)任务记录保留上限:TTL 之外的第二道闸——
+ * 快速失败/快速完成的 submit 循环不受 running 在途闸限制,没有条数上限
+ * 就能在 TTL 窗口内堆记录。超出即淘汰最旧,正常插件(一次 1–2 单)碰不到。
+ */
+const MAX_SETTLED_JOBS_PER_GHOST = 16;
+
+/** 异步代办任务(mode:'submit')的在途/完成记录。内存表:主进程重启即丢,
+ * query_job 对丢失单统一回"查无此任务",意识按可重新提交处理。 */
+interface CindyAsyncJob {
+ ghostId: string;
+ /** 人话动词(失败话术,来自 KIND_INFO.verb)。 */
+ verb: string;
+ startedAt: number;
+ status: 'running' | 'done' | 'failed';
+ /** done:与同步成功返回同形的取件字段。 */
+ result?: {
+ url: string;
+ hash: string;
+ ext: string;
+ model: string;
+ modelLabel: string;
+ };
+ /** failed:人话失败原因。 */
+ error?: string;
+ /** 完成时刻(done/failed;TTL 从这里起算)。 */
+ doneAt?: number;
+}
+
/** 每种代办类型的静态口径(类目/动作/是否吃源图/人话动词)。 */
interface CindyKindInfo {
category: 'image' | 'video';
@@ -146,6 +199,8 @@ const HASH_RE = /^[0-9a-f]{64}$/;
export class GhostCindySlot {
private readonly inflight = new Map<string, number>();
+ /** 异步代办任务表(jobId → 记录;惰性 sweep,过期即清)。 */
+ private readonly jobs = new Map<string, CindyAsyncJob>();
constructor(private readonly deps: CindySlotDeps) {}
@@ -155,6 +210,7 @@ export class GhostCindySlot {
* 结构化拒绝而不是异常穿透。
*/
async handleModelRequest(ghostId: string, payload: unknown): Promise<GhostPipeModelResult> {
+ this.sweepJobs();
const p = payload as {
kind?: unknown;
prompt?: unknown;
@@ -162,18 +218,36 @@ export class GhostCindySlot {
model?: unknown;
hashes?: unknown;
callId?: unknown;
+ mode?: unknown;
+ jobId?: unknown;
};
+ if (p?.kind === 'query_job') {
+ return this.handleQueryJob(ghostId, p);
+ }
const info = typeof p?.kind === 'string' ? KIND_INFO[p.kind] : undefined;
if (!info) {
- return { ok: false, message: `未知的代办类型(当前支持 ${Object.keys(KIND_INFO).join(' / ')})` };
+ return {
+ ok: false,
+ message: `未知的代办类型(当前支持 ${Object.keys(KIND_INFO).join(' / ')} / query_job)`,
+ };
}
const kind = p.kind as string;
+ if (p.mode !== undefined && p.mode !== 'submit') {
+ return { ok: false, message: "mode 只支持 'submit'(异步提交)或不传(同步等待)" };
+ }
+ if (p.mode === 'submit' && info.category !== 'video') {
+ return {
+ ok: false,
+ message: '异步提交(mode:submit)仅支持视频类代办;图像代办秒级完成,直接同步等待',
+ };
+ }
if (typeof p.prompt !== 'string' || p.prompt.trim().length === 0) {
return { ok: false, message: 'prompt 不能为空' };
}
if (p.prompt.length > MAX_PROMPT_LEN) {
return { ok: false, message: `prompt 过长(上限 ${MAX_PROMPT_LEN} 字符)` };
}
+ const prompt = p.prompt;
// 归因号:可选——tool-call 触发的代办把 callId 原样带回,日志/
// 配额由此对上"哪次调用花的钱";面板交互等自发代办可不带,日志记
// unattributed。带了就必须像样(非空字符串、长度设限),乱填拒单。
@@ -256,13 +330,20 @@ export class GhostCindySlot {
}
this.inflight.set(ghostId, inflight + 1);
+ // 异步受理成功后名额转交后台任务,由它的收尾释放;其余路径 finally 释放。
+ let backgrounded = false;
try {
// 日志口径:发生的事件是"一单 cindy 代办"(kind = 代办类型),槽只是
// 资格概念不进文案;归因三件套 ghostId / kind / callId 三处日志一致。
- this.deps.log?.info(`ghost cindy-request ${kind} start`, { ghostId, model, callId });
+ this.deps.log?.info(`ghost cindy-request ${kind} start`, {
+ ghostId,
+ model,
+ callId,
+ ...(p.mode === 'submit' ? { mode: 'submit' } : {}),
+ });
// 吃源图的代办:逐张查账验归属——任何一张不是它名下的,整单拒
- // (统一话术不泄露细节)。
+ // (统一话术不泄露细节)。异步模式也在受理期同步校验,拒绝立即可见。
const imagePaths: string[] = [];
for (const hash of hashes) {
const abs = await this.deps.resolveOwnedMedia(ghostId, hash);
@@ -272,49 +353,187 @@ export class GhostCindySlot {
imagePaths.push(abs);
}
- let generated: { buffer: Uint8Array; mimeType: string };
- if (kind === 'edit_image') {
- generated = await this.deps.editImage({ prompt: p.prompt, model, imagePaths });
- } else if (kind === 'gen_image') {
- generated = await this.deps.generateImage({ prompt: p.prompt, model });
- } else if (kind === 'edit_video') {
- generated = await this.deps.editVideo({ prompt: p.prompt, model, imagePaths });
- } else {
- generated = await this.deps.generateVideo({ prompt: p.prompt, model });
+ // 单次生成 → 落库 → 组装取件字段(同步返回与异步后台共用一条链;
+ // 抛错由各自调用方折叠成结构化失败)。
+ const runExec = async (): Promise<{
+ url: string;
+ hash: string;
+ ext: string;
+ model: string;
+ modelLabel: string;
+ width?: number;
+ height?: number;
+ }> => {
+ let generated: { buffer: Uint8Array; mimeType: string };
+ if (kind === 'edit_image') {
+ generated = await this.deps.editImage({ prompt, model, imagePaths });
+ } else if (kind === 'gen_image') {
+ generated = await this.deps.generateImage({ prompt, model });
+ } else if (kind === 'edit_video') {
+ generated = await this.deps.editVideo({ prompt, model, imagePaths });
+ } else {
+ generated = await this.deps.generateVideo({ prompt, model });
+ }
+
+ const saved = await this.deps.saveGhostMedia({
+ ghostId,
+ buffer: generated.buffer,
+ mimeType: generated.mimeType,
+ label: prompt.slice(0, 200),
+ // 模型代办产物记账(ghostMediaLedger),随 ghost_call 收口带回;
+ // 未署名('unattributed')不记,与 networkSlot 同契约防并发串账
+ ...(callId !== 'unattributed' ? { callId } : {}),
+ });
+ this.deps.log?.info(`ghost cindy-request ${kind} done`, {
+ ghostId,
+ model,
+ callId,
+ hash: saved.hash,
+ bytes: generated.buffer.byteLength,
+ });
+ // 实际选型随结果回传(主机权威信息):意识交卷 note、会话里的 AI 与
+ // 用户由此看得见"这单是谁画的"。
+ const modelLabel = cfg.models.find((m) => m.id === model)?.label ?? model;
+ // 图片代办附带像素宽高(字节头解析,best-effort):意识供聊天卡片时
+ // 据此精确声明卡高,首帧零跳动;解析不出就缺省,意识回退估计值。
+ const dims =
+ kind === 'gen_image' || kind === 'edit_image' ? probeImageSize(generated.buffer) : null;
+ return { url: saved.url, hash: saved.hash, ext: saved.ext, model, modelLabel, ...(dims ?? {}) };
+ };
+
+ const expectedSeconds =
+ info.category === 'video'
+ ? (this.deps.videoExpectedSeconds?.(model) ?? DEFAULT_VIDEO_EXPECTED_SECONDS)
+ : null;
+
+ if (p.mode === 'submit') {
+ // 异步受理。内置在途闸(用户 inflightLimit 之上的缺省闸):同步代办
+ // 天然被管子超时限流,异步提交是瞬时的,不设闸就能批量刷付费通道。
+ const runningJobs = [...this.jobs.values()].filter(
+ (j) => j.ghostId === ghostId && j.status === 'running',
+ ).length;
+ if (runningJobs >= GHOST_CINDY_MAX_ASYNC_JOBS) {
+ return {
+ ok: false,
+ message: `后台任务已达上限(${GHOST_CINDY_MAX_ASYNC_JOBS} 单):先用 query_job 取回已完成的,或等在途任务结束`,
+ };
+ }
+ this.evictSettledJobs(ghostId);
+ const jobId = randomUUID();
+ const job: CindyAsyncJob = { ghostId, verb: info.verb, startedAt: Date.now(), status: 'running' };
+ this.jobs.set(jobId, job);
+ backgrounded = true;
+ void runExec()
+ .then((result) => {
+ job.status = 'done';
+ job.result = {
+ url: result.url,
+ hash: result.hash,
+ ext: result.ext,
+ model: result.model,
+ modelLabel: result.modelLabel,
+ };
+ job.doneAt = Date.now();
+ })
+ .catch((err: unknown) => {
+ job.status = 'failed';
+ job.error = err instanceof Error ? err.message : String(err);
+ job.doneAt = Date.now();
+ this.deps.log?.warn(`ghost cindy-request ${kind} job failed`, {
+ ghostId,
+ callId,
+ jobId,
+ error: job.error,
+ });
+ })
+ .finally(() => this.releaseInflight(ghostId));
+ return { ok: true, jobId, status: 'running', ...(expectedSeconds !== null ? { expectedSeconds } : {}) };
}
- const saved = await this.deps.saveGhostMedia({
- ghostId,
- buffer: generated.buffer,
- mimeType: generated.mimeType,
- label: p.prompt.slice(0, 200),
- // 模型代办产物记账(ghostMediaLedger),随 ghost_call 收口带回;
- // 未署名('unattributed')不记,与 networkSlot 同契约防并发串账
- ...(callId !== 'unattributed' ? { callId } : {}),
- });
- this.deps.log?.info(`ghost cindy-request ${kind} done`, {
- ghostId,
- model,
- callId,
- hash: saved.hash,
- bytes: generated.buffer.byteLength,
- });
- // 实际选型随结果回传(主机权威信息):意识交卷 note、会话里的 AI 与
- // 用户由此看得见"这单是谁画的"。
- const modelLabel = cfg.models.find((m) => m.id === model)?.label ?? model;
- // 图片代办附带像素宽高(字节头解析,best-effort):意识供聊天卡片时
- // 据此精确声明卡高,首帧零跳动;解析不出就缺省,意识回退估计值。
- const dims =
- kind === 'gen_image' || kind === 'edit_image' ? probeImageSize(generated.buffer) : null;
- return { ok: true, url: saved.url, hash: saved.hash, ext: saved.ext, model, modelLabel, ...(dims ?? {}) };
+ // 同步等待:署名单在途期间替管子那头的 tool-call 续命(hold 预算 =
+ // 这单自己的轮询上限 expected×3,与 video/run.ts 的总超时同口径;
+ // 图片秒级完成,330s 基础窗口足够,不 hold)。
+ const holdBudgetMs = expectedSeconds !== null ? expectedSeconds * 3 * 1000 : 0;
+ const shouldHold = holdBudgetMs > 0 && callId !== 'unattributed';
+ if (shouldHold) this.deps.holdPipeCall?.(ghostId, callId, holdBudgetMs);
+ try {
+ return { ok: true, ...(await runExec()) };
+ } finally {
+ if (shouldHold) this.deps.releasePipeCall?.(ghostId, callId);
+ }
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
this.deps.log?.warn(`ghost cindy-request ${kind} failed`, { ghostId, callId, error: message });
return { ok: false, message: `${info.verb}失败:${message}` };
} finally {
- const left = (this.inflight.get(ghostId) ?? 1) - 1;
- if (left <= 0) this.inflight.delete(ghostId);
- else this.inflight.set(ghostId, left);
+ if (!backgrounded) this.releaseInflight(ghostId);
+ }
+ }
+
+ private releaseInflight(ghostId: string): void {
+ const left = (this.inflight.get(ghostId) ?? 1) - 1;
+ if (left <= 0) this.inflight.delete(ghostId);
+ else this.inflight.set(ghostId, left);
+ }
+
+ /** 惰性清理:完成(done/failed)超过 TTL 的任务记录出表(running 永不清)。 */
+ private sweepJobs(): void {
+ if (this.jobs.size === 0) return;
+ const now = Date.now();
+ for (const [jobId, job] of [...this.jobs]) {
+ if (job.status !== 'running' && now - (job.doneAt ?? 0) > GHOST_CINDY_JOB_TTL_MS) {
+ this.jobs.delete(jobId);
+ }
+ }
+ }
+
+ /**
+ * 新 job 入表前按意识淘汰最旧的完成记录,保住每意识条数上限。
+ * 在途 running(含本单即将占用的名额)都会落成完成记录,一并计入预留,
+ * 上限在任何并发时序下都不被突破。
+ */
+ private evictSettledJobs(ghostId: string): void {
+ const entries = [...this.jobs.entries()].filter(([, j]) => j.ghostId === ghostId);
+ const running = entries.filter(([, j]) => j.status === 'running').length;
+ const settled = entries
+ .filter(([, j]) => j.status !== 'running')
+ .sort((a, b) => (a[1].doneAt ?? 0) - (b[1].doneAt ?? 0));
+ const excess = settled.length - (MAX_SETTLED_JOBS_PER_GHOST - running - 1);
+ for (let i = 0; i < excess; i++) {
+ this.jobs.delete(settled[i][0]);
+ }
+ }
+
+ /**
+ * query_job:取异步任务状态/结果。归属统一话术——查无此单与不是它的单
+ * 同一句,不泄露他人任务存在性;完成结果可反复查(TTL 内幂等)。
+ */
+ private handleQueryJob(ghostId: string, p: { jobId?: unknown }): GhostPipeModelResult {
+ const ghost = this.deps.getGhost(ghostId);
+ if (!ghost || !ghost.enabled) {
+ return { ok: false, message: '意识不在可用状态' };
+ }
+ if (!ghost.manifest.slots?.includes('cindy')) {
+ return { ok: false, message: '本意识未声明 cindy 卡槽,无权请 Cindy 代办' };
+ }
+ if (typeof p.jobId !== 'string' || p.jobId.length === 0 || p.jobId.length > MAX_JOB_ID_LEN) {
+ return { ok: false, message: 'jobId 不合法(mode:submit 受理时返回的任务号)' };
+ }
+ const job = this.jobs.get(p.jobId);
+ if (!job || job.ghostId !== ghostId) {
+ return { ok: false, message: '查无此任务(可能已过期清理或应用重启丢失;请重新提交)' };
+ }
+ if (job.status === 'running') {
+ return {
+ ok: true,
+ jobId: p.jobId,
+ status: 'running',
+ elapsedSeconds: Math.round((Date.now() - job.startedAt) / 1000),
+ };
+ }
+ if (job.status === 'failed' || !job.result) {
+ return { ok: false, message: `${job.verb}失败:${job.error ?? '未知原因'}` };
}
+ return { ok: true, jobId: p.jobId, status: 'done', ...job.result };
}
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index f35df63032..554d588f98 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -891,7 +891,8 @@ cindy.onHostMessage(function (msg) {
// 可经 cindy-ghost://<id>/media/<指纹> 上墙)。工具要吃用户图就读它。
});
-// 交卷(330 秒内必须,超时作废;够覆盖一单大文件上传/取件):
+// 交卷(默认 330 秒内,超时作废;够覆盖一单大文件上传/取件。长任务可续命,
+// 见下方"长任务续命"):
cindy.send({ type: 'tool-result', callId: msg.callId, ok: true, result: {
xdt_image_urls: ["cindy-media://…"], // 顶层带这个字段 → 聊天气泡直接渲染图卡
// xdt_video_urls 同理渲染视频卡。音频用 xdt_audio_tracks(对象数组,逐轨):
@@ -934,6 +935,15 @@ cindy.send({
message: '删除需要确认,请传 confirm:true 后重试',
});
+// 长任务续命(超时窗口默认 330s,从派发起算绝对上限 30 分钟):
+// - 经 cindy-request 请主机代办且带 callId 的署名单(出图/视频)在途时,
+// 主机**自动**替这份卷续命,你不用做任何事;
+// - 自己经 network 槽轮询外部长任务时,期间定期(建议 ≤60s 一次)发心跳:
+// cindy.send({ type: 'tool-progress', callId: msg.callId });
+// 每次心跳把窗口重新续满一个 330s 档;callId 不是派给你的会被静默丢弃。
+// - 预计超过 30 分钟天花板的超长任务,不要吊着一次 tool-call 等:视频代办用
+// mode:'submit' 异步提交(见下),自己的外部任务拆成"提交 + 查询"两个工具。
+
// Cindy 代办(需声明 cindy 槽 + 能力详单;主机出图、落仓、记账,你只拿到指纹字符串):
// 由 tool-call 触发的代办**务必带上收到的 callId**(归因号:让用户在日志/账单里
// 对上"哪次调用花的钱");面板交互等自发代办可不带。
@@ -947,9 +957,20 @@ const r = await cindy.send({ type: 'cindy-request', kind: 'gen_image', prompt: '
// 改图(需详单含 "edit";源图必须是本意识名下的,1–4 张——含用户过户给你的
// args.attachments 指纹):
// { kind: 'edit_image', prompt, hashes: ['<指纹>'] }
-// 视频(需详单 video 类目;分钟级长任务,返回形态同上,url 是 .mp4):
+// 视频(需详单 video 类目;分钟级长任务,返回形态同上,url 是 .mp4。同步等待
+// 期间主机自动替你的 tool-call 续命,分钟级任务放心 await):
// { kind: 'gen_video', prompt } // 文生视频
// { kind: 'edit_video', prompt, hashes: ['<指纹>'] } // 参考图生视频(1–2 张)
+// 视频异步模式(可能超过 30 分钟续命天花板,或不想吊着 tool-call 等时):
+// 加 mode:'submit' → 受理后立即返回 { ok:true, jobId, status:'running',
+// expectedSeconds }(资格审/源图归属仍同步校验,拒绝立即可见),生成在
+// 后台继续;用 { kind:'query_job', jobId } 轮询:进行中 { ok:true,
+// status:'running', elapsedSeconds },完成 { ok:true, status:'done', url,
+// hash, ext, model, modelLabel }(取件字段与同步返回同形),失败
+// { ok:false, message }。完成结果保留 30 分钟(每意识最多缓存 16 单完成
+// 记录,超出淘汰最旧),过期或应用重启后查无此单(按可重新提交处理);
+// 后台在途上限 2 单。建议把插件工具拆成"提交生成 + 查询结果"两个,
+// 让 AI 自己掌握轮询节奏。
// 选型两个可选参数,规则:
// tier:'draft'(快省草稿)| 'standard'(默认)| 'best'(最好)——只表达档位
// 意图,具体用哪个模型由主机决定。这是你唯一该主动用的选型参数。
@@ -1563,7 +1584,8 @@ maxConnections 收紧到 1–8);token ≤4096 字符。新连接添加成功时
其它硬边界:每意识同时在途 4 个请求;媒体取件/上传共用全局串行闸,同时只
处理一单(忙时返回结构化"正忙",稍后重试即可);重定向最多 3 跳且逐跳重验
-白名单;不支持流式/WebSocket。长任务用"提交 + 轮询"两个工具拆开做。
+白名单;不支持流式/WebSocket。长任务用"提交 + 轮询"两个工具拆开做;在一次
+tool-call 内轮询时记得定期发 tool-progress 心跳续命(见 §4"长任务续命")。
## 4.8 设置自绘(settingsHtml)+ 自定义参数存取(/kv)
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 775a6450bf..780c045248 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -1389,6 +1389,22 @@ export function getGhostCindySlot(): GhostCindySlot {
// 在途并发上限:用户级隐藏配置(ghost-cindy-prefs.json 的 inflightLimits),
// 缺省 null = 不限并发;每单现读,改配置即生效。
getInflightLimit: (ghostId) => readGhostCindyInflightLimit(ghostId),
+ // 管子续命挂钩:同步视频代办(署名单)在途期间替 tool-call 续命,
+ // 免得分钟级生成被管子 330s 基础窗口掐掉(任务后台继续烧钱、结果作废)。
+ // ghostId 由派发器配对验身:冒用他人在途 callId 不能续命/收短别人的卷。
+ holdPipeCall: (ghostId, callId, budgetMs) => getGhostPipeDispatcher().holdCall(ghostId, callId, budgetMs),
+ releasePipeCall: (ghostId, callId) => getGhostPipeDispatcher().releaseCall(ghostId, callId),
+ // 视频型号预期耗时(registry 登记值;hold 预算与异步受理返回共用)。
+ // registry 缺席/型号查无 → null,cindySlot 用自己的缺省。
+ videoExpectedSeconds: (model) => {
+ try {
+ const registry = getCindyProxyMediaService().backend.videoRegistry;
+ if (!registry || !registry.hasAny()) return null;
+ return registry.resolveByAlias(model).expectedSeconds;
+ } catch {
+ return null;
+ }
+ },
resolveOwnedMedia: async (ghostId, hash) => {
// 归属(账本)→ 落盘元数据(账本)→ 磁盘路径(指纹仓校验),
// 任一环查无即 null;modelSlot 对外统一话术不泄露差异。
@@ -2159,7 +2175,8 @@ export function registerGhostIpc(): void {
// ── 管子(脑机接口)main 侧 handler(docs/dev-rules/plugin-security-and-authoring.md)──────────────
// 身份不信任 sender 自报,一律按 webContents id 反查绑定表验身。
- // 上行白名单:tool-result(交卷,派发器配对验身)/ host-request(公开宿主上下文)/ cindy-request(cindy 槽
+ // 上行白名单:tool-result(交卷,派发器配对验身)/ tool-progress(长任务
+ // 心跳续命,派发器配对验身)/ host-request(公开宿主上下文)/ cindy-request(cindy 槽
// 代办,返回值即结果)/ card-update(卡槽③供片,cardService 校验链)/
// notify(系统提示,notifySlot 资格审+限速)/ fs-request(fs 槽代写文件,
// fsSlot 三档守门)/ agent-request(Agent 新回合,一次性用户票或后台权限
@@ -2183,6 +2200,13 @@ export function registerGhostIpc(): void {
if (!outcome.accepted) log.warn('ghost tool-result rejected', { id, reason: outcome.reason });
return { ok: true };
}
+ // tool-progress = 长任务心跳续命(配对/验身/天花板都在派发器;
+ // 拒因只进日志,恒回 ok,与 tool-result 同纪律不给沙箱探测面)。
+ if (type === 'tool-progress') {
+ const outcome = getGhostPipeDispatcher().handleToolProgress(id, payload);
+ if (!outcome.accepted) log.warn('ghost tool-progress rejected', { id, reason: outcome.reason });
+ return { ok: true };
+ }
// host-request = 读取宿主公开上下文;不要求卡槽,只返回构建 region,
// 不含登录态/路径/设备信息。未知 kind 明确拒绝,避免接口悄悄扩面。
if (type === 'host-request') {
diff --git a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
index 4048dfb47f..a92d807333 100644
--- a/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
+++ b/apps/desktop/src/main/cindy-brain/pipeDispatcher.ts
@@ -9,6 +9,8 @@
* - 资格审(装没装 / 醒没醒 / 有没有这个工具 / 熔断没)→ 结构化错误码;
* - 按需拉起沙箱(spawn 幂等);
* - callId 配对 + 超时掐断(过期卷子作废丢弃);
+ * - 长任务续命:主机代办在途 hold(cindySlot 接线)与插件 tool-progress
+ * 心跳都能把超时窗口续到 GHOST_PIPE_CALL_MAX_TOTAL_MS 天花板内;
* - 交卷验身:pending 记录派给了谁,别的意识交不了这份卷(不信自报之外
* 的第二道:连"替别人交卷"的通道都没有);
* - 崩溃/熄灯时把在途调用全部按 GHOST_CRASHED/GHOST_ASLEEP 收掉。
@@ -23,7 +25,7 @@ import type {
GhostToolCallResult,
InstalledGhost,
} from '../../shared/ghost.js';
-import { isGhostPluginErrorCode } from '../../shared/ghost.js';
+import { GHOST_PIPE_CALL_MAX_TOTAL_MS, isGhostPluginErrorCode } from '../../shared/ghost.js';
import type { GhostRuntimeState } from './runtime/GhostRuntime.js';
export interface PipeDispatcherDeps {
@@ -47,8 +49,15 @@ export interface PipeDispatcherDeps {
interface PendingCall {
ghostId: string;
+ tool: string;
resolve: (result: GhostToolCallResult) => void;
- timer: ReturnType<typeof setTimeout>;
+ timer: ReturnType<typeof setTimeout> | undefined;
+ /** 派发时刻(续命天花板从这里起算)。 */
+ startedAt: number;
+ /** 当前生效的超时时刻(hold / 心跳只延不缩,release 才收)。 */
+ deadlineAt: number;
+ /** 在途代办 hold 计数(同一卷可并发多单代办,全部收工才收窗)。 */
+ holds: number;
}
/**
@@ -57,9 +66,14 @@ interface PendingCall {
* + 余量——否则意识合法地等一单大上传时,管子先到点向 agent 报 TIMEOUT,
* 而上传仍在后台继续并可能成功,用户被误导重试造成二次全量上传
* (2026-07-13 xd-pages 部署迁移时定为 330s;原 180s)。
+ * 分钟级以上的长任务不再靠调大本值硬扛:主机代办在途自动续命、插件可发
+ * tool-progress 心跳续命,天花板见 GHOST_PIPE_CALL_MAX_TOTAL_MS。
*/
const DEFAULT_TIMEOUT_MS = 330_000;
+/** 代办收工(release)后留给意识做后处理与交卷的余量窗口。 */
+const HOLD_SETTLE_GRACE_MS = 60_000;
+
export class GhostPipeDispatcher {
private readonly pending = new Map<string, PendingCall>();
@@ -115,14 +129,18 @@ export class GhostPipeDispatcher {
const payload: GhostPipeToolCall = { type: 'tool-call', callId, tool, args };
return new Promise<GhostToolCallResult>((resolve) => {
- const setT = this.deps.setTimeoutFn ?? setTimeout;
- const timer = setT(() => {
- if (this.pending.delete(callId)) {
- this.deps.log?.warn('ghost tool call timed out', { ghostId, tool, callId });
- resolve({ ok: false, errorCode: 'TIMEOUT', message: `工具 ${tool} 执行超时` });
- }
- }, this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS);
- this.pending.set(callId, { ghostId, resolve, timer });
+ const startedAt = Date.now();
+ const entry: PendingCall = {
+ ghostId,
+ tool,
+ resolve,
+ timer: undefined,
+ startedAt,
+ deadlineAt: startedAt + this.baseTimeoutMs(),
+ holds: 0,
+ };
+ this.pending.set(callId, entry);
+ this.armTimer(callId, entry);
if (!this.deps.sendToGhost(ghostId, payload)) {
// 逻辑页不在线(拉起后瞬时死亡等):立即收卷。
@@ -131,6 +149,104 @@ export class GhostPipeDispatcher {
});
}
+ /** 基础超时档(注入值钳到天花板内,保证初始 deadline 不越过绝对上限)。 */
+ private baseTimeoutMs(): number {
+ return Math.min(this.deps.timeoutMs ?? DEFAULT_TIMEOUT_MS, GHOST_PIPE_CALL_MAX_TOTAL_MS);
+ }
+
+ /** 按 entry.deadlineAt 重挂超时闹钟(旧闹钟一并清掉)。 */
+ private armTimer(callId: string, entry: PendingCall): void {
+ (this.deps.clearTimeoutFn ?? clearTimeout)(entry.timer);
+ const setT = this.deps.setTimeoutFn ?? setTimeout;
+ entry.timer = setT(() => {
+ if (this.pending.delete(callId)) {
+ this.deps.log?.warn('ghost tool call timed out', {
+ ghostId: entry.ghostId,
+ tool: entry.tool,
+ callId,
+ totalMs: Date.now() - entry.startedAt,
+ });
+ entry.resolve({
+ ok: false,
+ errorCode: 'TIMEOUT',
+ message: `工具 ${entry.tool} 执行超时(任务可能仍在后台继续,稍后重试或许能直接取回已完成的结果)`,
+ });
+ }
+ }, Math.max(0, entry.deadlineAt - Date.now()));
+ }
+
+ /**
+ * 把在途卷的超时时刻至少延到 targetAt:只延不缩,且不超过派发起算的
+ * GHOST_PIPE_CALL_MAX_TOTAL_MS 天花板(到顶后不再续,卷到点照常作废)。
+ */
+ private extendDeadline(callId: string, entry: PendingCall, targetAt: number): void {
+ const cap = entry.startedAt + GHOST_PIPE_CALL_MAX_TOTAL_MS;
+ const next = Math.min(Math.max(targetAt, entry.deadlineAt), cap);
+ // <=:双保险守住"只延不缩"——即使 deadline 因注入值异常已在 cap 之上,
+ // 也绝不反向收短(baseTimeoutMs 的钳制让这理论上不会发生)。
+ if (next <= entry.deadlineAt) return;
+ entry.deadlineAt = next;
+ this.armTimer(callId, entry);
+ }
+
+ /**
+ * 代办 hold:主机自己正为该卷干活(cindy 槽署名代办)时替它续命。
+ * ghostId = 主机反查的代办发起方身份——与交卷/心跳同纪律配对校验,
+ * 沙箱填错/冒用别人在途的 callId 不能续命他人的卷、也不污染其计数。
+ * budgetMs = 这单代办自身的预算(如视频 expected×3);窗口延到
+ * now + budget + 交卷余量。查无此卷/不是它的卷,静默忽略。
+ *
+ * 已知边界:callId 归因是插件自报的(记账同契约),同一意识自己的两个
+ * 并发调用互填 callId 主机无从分辨(沙箱内部并发,主机没有"正在处理哪
+ * 份卷"的会话状态)。错配只伤它自己:错署名的调用不获续命照常超时,
+ * 被错挂的调用最多被延长;release 收窗下限是基础窗口(见 releaseCall),
+ * 不会把任何卷收到无续命机制时的行为之下。
+ */
+ holdCall(ghostId: string, callId: string, budgetMs: number): void {
+ const entry = this.pending.get(callId);
+ if (!entry || entry.ghostId !== ghostId) return;
+ entry.holds += 1;
+ this.extendDeadline(callId, entry, Date.now() + budgetMs + HOLD_SETTLE_GRACE_MS);
+ }
+
+ /**
+ * 代办收工:hold 计数归零时把窗口收回(不短于插件本来的基础窗口,并留
+ * 交卷余量)——不让 16 分钟的 hold 在任务 3 分钟完成后继续吊着失败面。
+ * 验身同 holdCall(冒名 release 不能提前收短别人的窗口)。
+ */
+ releaseCall(ghostId: string, callId: string): void {
+ const entry = this.pending.get(callId);
+ if (!entry || entry.ghostId !== ghostId) return;
+ entry.holds = Math.max(0, entry.holds - 1);
+ if (entry.holds > 0) return;
+ const target = Math.max(entry.startedAt + this.baseTimeoutMs(), Date.now() + HOLD_SETTLE_GRACE_MS);
+ if (target < entry.deadlineAt) {
+ entry.deadlineAt = target;
+ this.armTimer(callId, entry);
+ }
+ }
+
+ /**
+ * 心跳续命(ghost-pipe:send 的 tool-progress 分支)。验身同交卷:callId
+ * 不是派给你的即拒(拒因只进日志,不给沙箱探测面)。每次心跳把窗口
+ * 重新续满一个基础档;天花板由 extendDeadline 统一钳制。
+ */
+ handleToolProgress(senderGhostId: string, payload: unknown): { accepted: boolean; reason?: string } {
+ const p = payload as { callId?: unknown };
+ if (typeof p?.callId !== 'string') {
+ return { accepted: false, reason: 'tool-progress 载荷形状不合法' };
+ }
+ const entry = this.pending.get(p.callId);
+ if (!entry) {
+ return { accepted: false, reason: '卷子不存在或已过期' };
+ }
+ if (entry.ghostId !== senderGhostId) {
+ return { accepted: false, reason: '不是你的卷子' };
+ }
+ this.extendDeadline(p.callId, entry, Date.now() + this.baseTimeoutMs());
+ return { accepted: true };
+ }
+
/**
* 交卷(ghost-pipe:send 的 tool-result 分支)。
* senderGhostId 来自主机按 webContents 反查的身份——callId 配对之外再验
diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.ts
index 5c9a288d2f..e2d718c03b 100644
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@ -2766,6 +2766,27 @@ export type GhostPipeToolResult =
| { type: 'tool-result'; callId: string; ok: true; result: unknown }
| { type: 'tool-result'; callId: string; ok: false; errorCode?: string; message: string };
+/**
+ * 上行:工具调用进度心跳(长任务续命)。在途 tool-call 每收到一次心跳,
+ * 主机把该卷的超时窗口重新续满一个基础档(缺省 330s),从派发起算不超过
+ * GHOST_PIPE_CALL_MAX_TOTAL_MS 天花板。经 cindy-request 请主机代办且带
+ * callId 的署名单在途时主机自动续命,无需心跳;意识自己经 network 槽轮询
+ * 外部长任务时才需要发。验身与交卷同纪律:callId 不是派给你的即丢弃。
+ */
+export interface GhostPipeToolProgress {
+ type: 'tool-progress';
+ callId: string;
+}
+
+/**
+ * 管子 tool-call 从派发起算的绝对上限(毫秒,30 分钟):代办自动续命与
+ * tool-progress 心跳共用的天花板——盖住视频代办 expected×3 的最大轮询
+ * 预算(seedance-pro 为 900s)+ 余量,又不给真死掉的调用无限吊着的机会。
+ * (2026-07-24 管子长任务续命定案:此前 330s 固定超时令分钟级视频代办
+ * 必超时,任务在后台继续烧钱、结果却作废。)
+ */
+export const GHOST_PIPE_CALL_MAX_TOTAL_MS = 30 * 60_000;
+
/** 主机公开给意识的构建区域。与 desktop CURRENT_CINDY_REGION 同口径。 */
export type GhostAppRegion = 'cn' | 'global';
@@ -3199,6 +3220,22 @@ export const GHOST_NOTIFY_MIN_INTERVAL_MS = 5000;
export const GHOST_MODEL_TIERS = ['draft', 'standard', 'best'] as const;
export type GhostModelTier = (typeof GHOST_MODEL_TIERS)[number];
+/**
+ * 异步代办(mode:'submit')完成结果的保留时长(毫秒,30 分钟):完成后
+ * 过期即清,query_job 查无此单。TTL 之外还有每意识完成记录条数上限
+ * (cindySlot 的 settled-job eviction):快速提交循环下最旧的完成记录会
+ * 在 TTL 未到时被提前淘汰。任务表在内存(主进程重启即丢),意识须把
+ * "查无此单"当作可重新提交的正常失败面。
+ */
+export const GHOST_CINDY_JOB_TTL_MS = 30 * 60_000;
+
+/**
+ * 每意识后台异步代办在途上限。同步代办天然被管子超时与 agent 节奏限流,
+ * 异步提交是瞬时的,必须有内置闸防批量提交刷爆付费通道;用户配置的
+ * inflightLimit(同时约束同步+异步)更严时以更严者为准。
+ */
+export const GHOST_CINDY_MAX_ASYNC_JOBS = 2;
+
/**
* 上行:cindy 槽代办请求(请 Cindy 本体出图 / 改图)。协议 type 为
* 'cindy-request'(2026-07-11 由 'model-request' 更名,主机对旧名保持
@@ -3245,6 +3282,13 @@ export type GhostPipeCindyRequest =
model?: string;
/** 归因号(同 gen_image 分支)。 */
callId?: string;
+ /**
+ * 异步模式(仅视频类代办):'submit' = 资格审与源图校验通过后立即
+ * 返回 jobId,生成在后台继续,用 kind:'query_job' 轮询取件。适合
+ * 可能超过管子超时窗口的超长任务;缺省同步等待(主机会为署名单
+ * 自动续命,分钟级任务推荐同步)。
+ */
+ mode?: 'submit';
}
| {
type: 'cindy-request';
@@ -3259,6 +3303,14 @@ export type GhostPipeCindyRequest =
model?: string;
/** 归因号(同 gen_image 分支)。 */
callId?: string;
+ /** 异步模式(同 gen_video 分支)。 */
+ mode?: 'submit';
+ }
+ | {
+ type: 'cindy-request';
+ kind: 'query_job';
+ /** mode:'submit' 受理时返回的任务号(仅本意识自己的任务可查)。 */
+ jobId: string;
};
/** cindy 槽代办的返回(cindy.send 的 resolve 值)。 */
@@ -3283,6 +3335,30 @@ export type GhostPipeModelResult =
width?: number;
height?: number;
}
+ | {
+ ok: true;
+ /** 异步受理(mode:'submit')与 query_job 进行中共用本分支。 */
+ jobId: string;
+ status: 'running';
+ /** 该型号预期耗时(秒;registry 登记值,供意识决定轮询节奏)。 */
+ expectedSeconds?: number;
+ /** 已耗时(秒;仅 query_job 返回)。 */
+ elapsedSeconds?: number;
+ }
+ | {
+ /**
+ * query_job 完成态(独立成员,jobId/status 必填):`'status' in r`
+ * 即可与同步成功分支可靠判别。取件字段与同步成功分支同形。
+ */
+ ok: true;
+ jobId: string;
+ status: 'done';
+ url: string;
+ hash: string;
+ ext: string;
+ model: string;
+ modelLabel: string;
+ }
| { ok: false; message: string };
/* ── 订阅槽①:事件协议(2026-07-12 定案:一种事件模型,两个类型)──────