gongxiangp2/apps/detail-agent-pi/test/desktop-daemon.test.mjs
WuYongJie f37cc4e38b 修复小壹制作续写、画布超时与 SKU 资料作用域
按结构读取旧模板与可选配置,递归脱敏 SDK 会话,并覆盖 Windows Node 24 回归用例。
2026-12-05 12:57:43 +08:00

565 lines
26 KiB
JavaScript

import assert from 'node:assert/strict';
import { PassThrough } from 'node:stream';
import { spawn } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { once } from 'node:events';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { createInterface } from 'node:readline';
import { test } from 'node:test';
import { startDaemon } from '../src/desktop-daemon.mjs';
import { ProjectRepository } from '../src/project-repository.mjs';
import { StdioCanvas, canvasToolReceipts } from '../src/stdio-canvas.mjs';
import { observeCanvasCalls, runSession } from '../src/desktop-host.mjs';
import { executionEvent } from '../src/activity-event.mjs';
import { BridgeError } from '../src/bridge-error.mjs';
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
const tick = () => new Promise(resolve => setImmediate(resolve));
test('independent projects run concurrently and a second turn reuses its project agent session', {timeout:60_000}, async t => {
const root=await mkdtemp(path.join(tmpdir(),'xiaoyi-daemon-projects-'));
const input=new PassThrough(), output=new PassThrough();
const frames=createInterface({input:output});
const accountScope='a'.repeat(64), ids=[randomUUID(),randomUUID()];
const originalSessions=new Map(), dispatches=[];
const simultaneous=Promise.withResolvers();
const brokerFactory=({project})=>({
bind(){},close:async()=>{},
info:async()=>({accountScope,accountId:'account',origin:'https://example.invalid',model:{id:'qa',protocol:'openai-chat'}}),
round(){return {id:randomUUID(),fetch:async()=>{
dispatches.push(project);
if (new Set(dispatches).size===2) simultaneous.resolve();
await simultaneous.promise;
const chunk={id:'fixture',model:'qa',choices:[{index:0,delta:{content:'已查看当前项目'},finish_reason:'stop'}]};
return new Response('data: '+JSON.stringify(chunk)+'\n\ndata: [DONE]\n\n',{headers:{'content-type':'text/event-stream'}});
}};},
});
const daemon=startDaemon({input,output,brokerFactory,parentAlive:()=>true,exit(){},
runSession:(config,call,broker,recovery,signal,revoke,_ready,owner)=>runSession(config,call,broker,recovery,signal,revoke,host=>{
if (originalSessions.has(config.project)) assert.equal(host.session,originalSessions.get(config.project));
else originalSessions.set(config.project,host.session);
},owner),
});
t.after(async()=>{simultaneous.resolve();await daemon.stop();frames.close();await rm(root,{recursive:true,force:true});});
const send = frame => input.write(JSON.stringify(frame)+'\n');
const completions=new Map();
frames.on('line',line=>{
const frame=JSON.parse(line);
const {type,accountScope,projectId,runId,id,action}=frame;
if(type==='canvas')send({type:'canvas_result',accountScope,projectId,runId,id,
value:action==='pi-workflow-read'?{available:false,version:1}:{conversationActive:true}});
if(type==='complete')completions.get(runId)?.resolve(frame);
});
const start=projectId=>{
const runId=randomUUID(), complete=Promise.withResolvers();
completions.set(runId,complete);
send({type:'run',accountScope,projectId,runId,config:{root:path.join(root,projectId),documentId:1,
mode:'prompt',text:'查看当前项目'}});
return complete.promise;
};
const replies=await Promise.all(ids.map(start));
assert.deepEqual(replies.map(row=>row.projectId),ids);
assert.deepEqual(replies.map(row=>[row.accountScope,row.value.error ?? row.value.text]),ids.map(()=>[accountScope,'已查看当前项目']));
assert.notEqual(originalSessions.get(ids[0]),originalSessions.get(ids[1]));
const again=await start(ids[0]);
assert.equal(again.value.text,'已查看当前项目');
assert.equal(dispatches.length,3);
});
test('canvas failure receipts retain the cause and distinguish pending dispatch', async () => {
const records = [];
const store = { executionScope: {}, executionHealth: {}, async appendEvent(event) { records.push(event); } };
const call = observeCanvasCalls(store, async (_action, input, accepted) => {
accepted();
if (input.action === 'prepare') throw new BridgeError('同款原图编号无效', 'local_precondition_failed');
return { status: 'pending', requestId: 'original' };
});
await assert.rejects(call('pi-image-request', { action: 'prepare' }), /同款原图编号无效/u);
await call('pi-image-request', { action: 'dispatch' });
assert.deepEqual(records.map(({ status, failureCategory, message, requestId }) =>
[status, failureCategory, message, requestId]), [
['failed', 'local_precondition_failed', '同款原图编号无效', undefined],
['pending', undefined, undefined, 'original'],
]);
});
test('canvas observations save a single receipt and keep routine telemetry in memory',async()=>{
const records=[];
const executionScope={projectId:'project',runId,outputId:'detail',variantId:'oak',revision:7,documentKey:{variantId:'oak'}};
const executionHealth={};
const store={executionScope,executionHealth,async appendEvent(event){records.push(executionEvent(event,executionScope,executionHealth));}};
const visible={outputId:'sku_images',variantId:'stone'};
const enqueued=Promise.withResolvers(), reply=Promise.withResolvers();
const call=observeCanvasCalls(store,async(_action,_input,accepted)=>{
accepted();
await reply.promise;
return {revision:8,viewing:visible};
});
const result=call('pi-detail-copy-apply',{operationId:'copy-1',revision:7},{onEnqueued:enqueued.resolve});
await enqueued.promise;
assert.equal(records.length,0);
reply.resolve();
await result;
await call('pi-state',{});
await call('pi-context-usage',{});
await call('pi-ui-poll',{});
assert.deepEqual(records.map(event=>[event.category,event.phase,event.status,event.revision]),[
['canvas_write','receipt','completed',8],
]);
for(const event of records){
assert.equal(event.projectId,'project');
assert.equal(event.runId,runId);
assert.equal(event.operationId,'copy-1');
assert.equal(event.attempt,1);
assert.equal(event.outputId,'detail');
assert.equal(event.variantId,'oak');
assert.deepEqual(event.documentKey,{variantId:'oak'});
assert.ok(Number.isFinite(event.agentHeartbeat));
assert.equal(event.jobProgress,null);
assert.equal(event.recentDurableCommit,null);
}
assert.ok(Number.isFinite(records[0].uiHeartbeat));
assert.ok(records[0].durationMs >= 0);
assert.equal(executionScope.revision,8);
});
test('a retried canvas read keeps its operation ID and records the next attempt',async()=>{
const attempts=[];
const canvas=new StdioCanvas(async(action,_input,execution)=>{
assert.equal(action,'pi-product-screen');
attempts.push(execution);
if(attempts.length===1)throw new BridgeError('原读屏回执等待超时','transport_interrupted');
return {revision:7};
},27);
assert.deepEqual(await canvas.detailRender({page:0}),{revision:7});
assert.deepEqual(attempts.map(row=>row.attempt),[1,2]);
assert.equal(attempts[0].operationId,attempts[1].operationId);
});
function daemonFixture(t, { runSession, parentAlive = () => true } = {}) {
const input = new PassThrough();
const output = new PassThrough();
const frames = [];
const exits = [];
output.on('data', bytes => frames.push(JSON.parse(bytes.toString())));
const daemon = startDaemon({
input,
output,
parentAlive,
runSession,
brokerFactory: () => ({ close: async () => {} }),
exit: code => exits.push(code),
});
t.after(() => daemon.stop());
const send = value => input.write(JSON.stringify(value) + '\n');
return { input, frames, exits, send };
}
test('local candidate requests report a lost host receipt without replay',async t=>{
t.mock.timers.enable({apis:['setTimeout']});
const {frames,send}=daemonFixture(t,{
runSession:async(_config,call)=>{
await assert.rejects(call('pi-image-request',{action:'product_reference',request:{slotId:'hero'}}),
{category:'transport_interrupted',dispatched:false,message:'本地候选回执超时,请查看目标成品的候选记录'});
return {text:'已返回候选状态'};
},
});
send({type:'run',runId,config:{}});
const sent=frames.find(frame=>frame.type==='canvas');
assert.equal(sent.input.action,'product_reference');
send({type:'canvas_accepted',runId,id:sent.id});
t.mock.timers.tick(180_000);
await tick();
assert.equal(frames.filter(frame=>frame.type==='canvas').length,1);
assert.equal(frames.find(frame=>frame.type==='complete')?.value.text,'已返回候选状态');
});
test('a missing local receipt releases writes while the paid dispatch remains marked for recovery',async t=>{
t.mock.timers.enable({apis:['setTimeout']});
const actions=['pi-write-request','pi-workflow-execute','pi-image-request'];
const {frames,send}=daemonFixture(t,{
runSession:async(_config,call)=>{
await Promise.all(actions.map(action=>assert.rejects(call(action,
action==='pi-image-request'?{action:'dispatch'}:{}),
{category:'transport_interrupted',dispatched:action==='pi-image-request'})));
return {text:'settled'};
},
});
send({type:'run',runId,config:{}});
const requests=frames.filter(frame=>frame.type==='canvas');
assert.deepEqual(requests.map(frame=>frame.action),actions);
send({type:'canvas_accepted',runId,id:requests[1].id});
t.mock.timers.tick(14*60_000);
await tick();
assert.equal(frames.filter(frame=>frame.type==='canvas').length,3);
assert.equal(frames.find(frame=>frame.type==='complete')?.value.text,'settled');
});
test('a heartbeat gap before dispatch keeps the original turn alive', async t => {
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
let resumeStartup;
const startup = new Promise(resolve => { resumeStartup = resolve; });
let dispatches = 0;
const { frames, exits, send } = daemonFixture(t, {
runSession: async () => {
await startup;
dispatches++;
return { text: '首屏候选已完成', unknown: false };
},
});
send({ type: 'heartbeat', id: 1 });
send({ type: 'run', runId, config: {} });
await tick();
t.mock.timers.tick(3000);
t.mock.timers.tick(30);
await tick();
assert.deepEqual(exits, [], 'the owner and the pipe are still alive');
assert.equal(dispatches, 0);
send({ type: 'heartbeat', id: 2 });
resumeStartup();
await tick();
assert.equal(dispatches, 1);
assert.deepEqual(frames.filter(frame => frame.type === 'heartbeat_ack').map(frame => frame.id), [1, 2]);
assert.equal(frames.filter(frame => frame.type === 'complete').length, 1);
assert.deepEqual(frames.at(-1), {
type: 'complete', runId, value: { text: '首屏候选已完成', unknown: false },
});
});
test('the daemon closes when its owner goes away', async t => {
t.mock.timers.enable({ apis: ['Date', 'setInterval', 'setTimeout'] });
let alive = true;
const { exits } = daemonFixture(t, { parentAlive: () => alive });
alive = false;
t.mock.timers.tick(200);
t.mock.timers.tick(30);
await tick();
assert.deepEqual(exits, [0]);
});
test('the daemon closes on EOF even while its owner is alive', async t => {
const { input, exits } = daemonFixture(t);
input.end();
await tick();
assert.deepEqual(exits, [0]);
});
test('legacy production time settings do not interrupt a waiting canvas call', async t => {
t.mock.timers.enable({ apis: ['Date', 'setTimeout', 'setInterval'], now: 10_000 });
let entered = 0;
const { frames, send } = daemonFixture(t, {
runSession: async (config, call, _broker, _recovery, signal) => {
entered++;
assert.equal(config.productionBudgetMinutes, 1);
const result = await call('pi-detail-images', { original: 'original-1' });
assert.equal(signal.aborted, false);
return result;
},
});
send({ type: 'run', runId, config: { productProduction: true, productionDeadline: 11, productionBudgetMinutes: 1 } });
await tick();
t.mock.timers.tick(61_000);
assert.equal(frames.filter(frame => frame.type === 'complete').length, 0);
const {id}=frames.find(frame=>frame.type==='canvas');
send({type:'canvas_result',runId,id,value:{status:'complete'}});
await tick();
assert.equal(entered, 1);
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
assert.deepEqual(frames.at(-1), {
type: 'complete', runId, value: {status:'complete'},
});
});
test('a pause on the bound production stops further tools and leaves the original request for recovery', async t => {
let cancelled = false;
const config = { productProduction: true, documentId: 27, project: 'desk', scope: 'account-a' };
const { frames, send } = daemonFixture(t, {
runSession: async (_, call, _broker, _recovery, signal) => {
await assert.rejects(call('pi-image-request', { action:'dispatch', request:{requestId:'original-1'} }), {category:'cancelled',dispatched:true});
cancelled = signal.aborted;
await assert.rejects(call('pi-detail-images', { original: 'original-1' }), {category:'cancelled',dispatched:false});
return { pending: ['original-1'], unknown: true, reposted: false };
},
});
send({ type: 'run', runId, config });
await tick();
send({ ...config, type: 'production_pause', scope: 'account-b' });
await tick();
assert.equal(cancelled, false);
send({ ...config, type: 'production_pause' });
await tick();
assert.equal(cancelled, true);
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
assert.deepEqual(frames.at(-1), {
type: 'complete', accountScope:'account-a', projectId:'desk', runId, value: { pending: ['original-1'], unknown: true, reposted: false },
});
});
test('explicit exit closes admission immediately and acknowledges only after the run drains', async t => {
const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-graceful-exit-'));
t.after(() => rm(dir, {recursive:true,force:true}));
const repository = () => new ProjectRepository(path.join(dir, 'project-repository.sqlite'),
{accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'});
let release;
const durable = new Promise(resolve => { release = resolve; });
let runs = 0;
const {frames,send,input,exits} = daemonFixture(t, {
runSession: async (_, call, _broker, _recovery, signal) => {
runs++;
await assert.rejects(call('pi-image-request', {action:'dispatch',request:{requestId:'original-image'}}), {category:'cancelled',dispatched:true});
assert.equal(signal.aborted, true);
await assert.rejects(call('pi-edit', {}), {category:'cancelled',dispatched:false});
await durable;
repository().replaceLedger({binding:'template',items:{front:{state:'unknown',
pendingOperation:{operationId:'original-operation',requestId:'original-image'}}}});
return {pending:['original-image'], unknown:true, reposted:false};
},
});
send({type:'run',runId,config:{}});
await tick();
send({type:'prepare_exit'});
const later = '775ac3bd-50da-476c-9051-627e7f26e53b';
send({type:'run',runId:later,config:{}});
await tick();
assert.equal(runs, 1);
assert.equal(frames.filter(frame => frame.type === 'canvas').length, 1);
assert.equal(frames.some(frame => frame.type === 'exit_ready'), false);
assert.equal(repository().readLedger(), null);
assert.match(frames.find(frame => frame.runId === later).value.error, /未派发/);
release();
await tick();
assert.deepEqual(frames.at(-2).value.pending, ['original-image']);
assert.deepEqual(frames.at(-1), {type:'exit_ready'});
input.end();
await tick();
assert.deepEqual(exits, [0]);
assert.deepEqual(repository().readLedger().items.front.pendingOperation,
{operationId:'original-operation',requestId:'original-image'});
});
test('a killed daemon reopens the original ledger without accepting a missing save receipt', {timeout: 15_000}, async t => {
const dir = await mkdtemp(path.join(tmpdir(), 'xiaoyi-exit-'));
t.after(() => rm(dir, {recursive:true,force:true}));
const canvas = path.join(dir, 'canvas.txt');
const script = `
import {startDaemon} from ${JSON.stringify(new URL('../src/desktop-daemon.mjs', import.meta.url).href)};
import {ProjectRepository} from ${JSON.stringify(new URL('../src/project-repository.mjs', import.meta.url).href)};
import {writeFileSync} from 'node:fs';
import {createHash} from 'node:crypto';
const dir = process.argv[1];
const id = 'same-operation';
const requestId = 'same-request';
const file = dir + '/canvas.txt';
const repository = new ProjectRepository(dir + '/project-repository.sqlite',
{accountId:'account',projectId:'project',outputId:'detail',variantId:'oak'});
startDaemon({brokerFactory:()=>({close:async()=>{}}),runSession:async(config,call)=>{
if(config.mode==='first'){
writeFileSync(file,'saved baseline');
const hash=createHash('sha256').update('edited canvas').digest('hex');
repository.replaceLedger({binding:'template',items:{front:{state:'unknown',
pendingAdoption:{operationId:id,requestId,hash}}}});
await call('save-canvas',{operationId:id,requestId});
return {saved:true};
}
const original=repository.readLedger().items.front.pendingAdoption;
return await call('reconcile-original',original);
}});
`;
async function start(mode) {
const child = spawn(process.execPath, ['--input-type=module','-e',script,dir], {windowsHide:true});
const ended = once(child, 'exit');
const lines = createInterface({input:child.stdout});
const frames = lines[Symbol.asyncIterator]();
const next = async () => JSON.parse((await frames.next()).value);
const send = value => child.stdin.write(JSON.stringify(value)+'\n');
t.after(async () => { child.kill(); await ended; });
assert.equal((await next()).type, 'ready');
send({type:'run', runId, config:{mode}});
return {child,ended,send,next};
}
const first = await start('first');
const write = await first.next();
assert.equal(write.action, 'save-canvas');
first.child.kill('SIGKILL');
await first.ended;
assert.equal(await readFile(canvas,'utf8'), 'saved baseline');
const reopened = await start('reopen');
const original = await reopened.next();
assert.equal(original.action, 'reconcile-original');
assert.equal(original.input.operationId, write.input.operationId);
assert.equal(original.input.requestId, write.input.requestId);
const diskHash = createHash('sha256').update(await readFile(canvas)).digest('hex');
assert.notEqual(diskHash, original.input.hash);
reopened.send({type:'canvas_result',runId,id:original.id,value:{saved:false,phase:'unknown'}});
assert.deepEqual((await reopened.next()).value, {saved:false,phase:'unknown'});
reopened.child.stdin.end();
await reopened.ended;
});
test('presentation notifications do not wait for replies and the terminal command still does', async t => {
const {frames,send}=daemonFixture(t,{
runSession:async(_config,call)=>{
await call('pi-delta',{text:'正在写'});
await call('pi-activity',{text:'读取画布'});
await call('pi-end',{text:'写完'});
return {text:'写完'};
},
});
send({type:'run',runId,config:{}});
await tick();
assert.deepEqual(frames.slice(1).map(({type,action})=>[type,action]),[
['presentation','pi-delta'],['presentation','pi-activity'],['canvas','pi-end'],
]);
const {id}=frames.at(-1);
send({type:'canvas_result',runId,id,value:null});
await tick();
assert.equal(frames.at(-1).type,'complete');
});
test('cancellation releases the turn while the host retains the paid image request', async t => {
const nextRunId='9a1ba294-f2c4-4e5f-91e0-ef6002f50e23';
const config={productProduction:true,documentId:27,project:'desk',scope:'account-a',writeEpoch:4};
const accepted=[];
const {frames,send}=daemonFixture(t,{
runSession:async(config,call,_broker,_recovery,signal)=>{
if(config.writeEpoch===5){
const next=await call('pi-state',{});
assert.equal(signal.aborted,false);
return next;
}
const image=call('pi-image-request',{action:'dispatch',request:{requestId:'original-image'}},()=>accepted.push('image'));
await Promise.all([
assert.rejects(call('pi-detail-copy-apply',{}), {category:'cancelled'}),
assert.rejects(image, {category:'cancelled',dispatched:true}),
]);
assert.equal(signal.aborted,true);
return {stopped:true};
},
});
send({type:'run',runId,config});
await tick();
const [image,write]=frames.filter(frame=>frame.type==='canvas');
send({type:'canvas_accepted',runId,id:image.id});
send({...config,type:'production_pause'});
send({type:'canvas_result',runId,id:write.id,value:{applied:1}});
await tick();
assert.deepEqual(accepted,['image']);
assert.deepEqual(frames.at(-1).value,{stopped:true});
const original={requestId:'original-image',status:'complete'};
send({type:'canvas_result',runId,id:image.id,value:original});
await tick();
assert.deepEqual(frames.at(-1).value,{stopped:true});
send({type:'run',runId:nextRunId,config:{...config,writeEpoch:5}});
await tick();
const next=frames.at(-1);
send({...config,type:'production_pause'});
send({type:'canvas_result',runId,id:next.id,value:{revision:99}});
send({type:'canvas_result',runId:nextRunId,id:next.id,value:{revision:7}});
await tick();
assert.deepEqual(frames.at(-1).value,{revision:7});
});
test('the stdio canvas settles save, cancel and state replies ahead of a pending render', async t => {
const observed=[];
const {frames,send}=daemonFixture(t,{
runSession:async(_config,call)=>{
const canvas=new StdioCanvas(call,27);
const screen=canvas.detailRender({page:0}).then(receipt=>observed.push(receipt));
await Promise.all([
canvas.nativeCall({method:'engine.execute',revision:7,params:{command:'file.save',params:{}}}),
canvas.uiCancel('pending-interaction'),
canvas.read(),
].map(promise=>promise.then(receipt=>observed.push(receipt))));
await screen;
return {};
},
});
send({type:'run',runId,config:{}});
await tick();
const requests=frames.filter(frame=>frame.type==='canvas');
assert.deepEqual(requests.map(frame=>frame.action),['pi-product-screen','pi-native-call','pi-ui-cancel','pi-state']);
for(const {id,action} of requests.slice(1))send({type:'canvas_result',runId,id,value:action});
await tick();
assert.deepEqual(observed,['pi-native-call','pi-ui-cancel','pi-state']);
assert.equal(frames.some(frame=>frame.type==='complete'),false);
send({type:'canvas_result',runId,id:requests[0].id,value:{revision:7}});
await tick();
assert.deepEqual(observed.at(-1),{revision:7});
assert.equal(frames.at(-1).type,'complete');
});
test('account revocation rejects a pending write and ignores its late result after a new scope opens', async t => {
const oldScope = 'account-a', newScope = 'account-b';
const nextRun = '170ff5d1-43ad-4f24-b9cb-b0c540e01bc3';
const {frames,send} = daemonFixture(t,{
runSession:async (config,call) => {
if (config.scope === newScope) return {activeScope:config.scope};
await assert.rejects(call('pi-edit', {text:'original edit'}), {category:'scope_changed',dispatched:false});
await assert.rejects(call('pi-image-request', {}), {category:'scope_changed',dispatched:false});
return {phase:'paused'};
},
});
send({type:'run',runId,config:{scope:oldScope}});
await tick();
const edit = frames.find(frame=>frame.action==='pi-edit');
assert.ok(edit);
send({type:'auth_revoke',scope:newScope,category:'scope_changed'});
await tick();
assert.equal(frames.some(frame=>frame.type==='complete'),false);
send({type:'auth_revoke',scope:oldScope,category:'scope_changed'});
await tick();
send({type:'run',runId:nextRun,config:{scope:newScope}});
send({type:'canvas_result',runId,id:edit.id,value:{completed:true}});
await tick();
assert.deepEqual(frames.filter(frame=>frame.type==='complete').map(frame=>frame.value), [
{phase:'paused'}, {activeScope:newScope},
]);
assert.equal(frames.filter(frame=>frame.type==='canvas').length,1);
assert.equal(frames.some(frame=>frame.type==='fatal'),false);
});
test('canvas tools carry local changes once without requesting a canvas read', async () => {
const report={sinceRevision:5,currentRevision:7,total:2,truncated:false,changes:[
{outputId:'detail',variantId:'wood',layerId:7,fieldId:'S01-T01',kinds:['text']},
{outputId:'main_images',variantId:'wood',layerId:8,slotId:'M01-I01',adoptedCandidateId:'candidate-2',origin:'human',kinds:['imageSource']},
]};
let pending=report;
const requests=[];
const canvas=new StdioCanvas(async (action,input)=>{
requests.push(action);
assert.equal(input.reportUserCanvasChanges,true);
const userCanvasChanges=pending;
pending=undefined;
return {__canvasResult:{revision:7},userCanvasChanges};
},7);
const receipt=()=>canvasToolReceipts.run({active:true},()=>canvas.action('pi-production-status'));
assert.deepEqual(await receipt(),{revision:7});
assert.deepEqual(canvas.userCanvasChanges.splice(0),[report]);
await receipt();
assert.deepEqual(canvas.userCanvasChanges,[]);
assert.deepEqual(requests,['pi-production-status','pi-production-status']);
});
test('a canvas tool receipt carries edits through response projection exactly once', async () => {
const report={sinceRevision:5,currentRevision:6,total:1,truncated:false,
changes:[{layerId:7,layerName:'标题',kinds:['visibility']}]};
let pending=report;
const canvas=new StdioCanvas(async (_action,input)=>{
if (!input.reportUserCanvasChanges) return {revision:6};
const userCanvasChanges=pending;
pending=undefined;
return {revision:6,userCanvasChanges};
},7);
await canvas.read();
assert.deepEqual(await canvasToolReceipts.run({active:true},()=>canvas.read()),{revision:6});
assert.deepEqual(canvas.userCanvasChanges.splice(0),[report]);
await canvasToolReceipts.run({active:true},()=>canvas.read());
assert.deepEqual(canvas.userCanvasChanges,[]);
});