fix(client): keep the local agent alive during cold startup
This commit is contained in:
parent
dcd68ff494
commit
fd1710b6ee
@ -4,9 +4,9 @@ import { Native98kBroker } from './native-bridge.mjs';
|
||||
const uuid = /^[a-f0-9]{8}-(?:[a-f0-9]{4}-){3}[a-f0-9]{12}$/i;
|
||||
export function startDaemon({runSession, readKnowledge, input=process.stdin, output=process.stdout, parentPid=process.ppid,
|
||||
parentAlive=pid=>{try{process.kill(pid,0);return true;}catch(error){return error.code==='EPERM';}},
|
||||
timeoutMs=2000, intervalMs=100, brokerFactory=config=>new Native98kBroker(config), exit=code=>process.exit(code)}={}) {
|
||||
intervalMs=100, brokerFactory=config=>new Native98kBroker(config), exit=code=>process.exit(code)}={}) {
|
||||
const lines=createInterface({input,crlfDelay:Infinity});
|
||||
let active=null, broker=null, identity=null, closed=false, lastHeartbeat=Date.now(), serial=0;
|
||||
let active=null, broker=null, identity=null, closed=false, serial=0;
|
||||
const waiting=new Map(), seen=new Set(), knowledge=new Map();
|
||||
// Retain unresolved operations across the distinct SDK Host instances owned
|
||||
// by this daemon. Never evict an unresolved identity to make room.
|
||||
@ -20,20 +20,16 @@ export function startDaemon({runSession, readKnowledge, input=process.stdin, out
|
||||
const killTimer=setTimeout(()=>exit(1),500);killTimer.unref?.();
|
||||
try { if(broker)await broker.close({force:true}); } finally {clearTimeout(killTimer);exit(0);}
|
||||
};
|
||||
// A synchronous cold import can delay the event loop while heartbeat bytes
|
||||
// are already waiting in the OS pipe. Yield one short poll opportunity so
|
||||
// Windows can deliver queued pipe completions, then check actual receipt time.
|
||||
let watchdogPending=false;
|
||||
// The native owner times heartbeat acknowledgements. Cold SDK imports can
|
||||
// delay stdin delivery, so the child only monitors the owner and the pipe.
|
||||
const watch=setInterval(()=>{
|
||||
if(watchdogPending)return;
|
||||
watchdogPending=true;
|
||||
setTimeout(()=>{watchdogPending=false;if(!closed && (Date.now()-lastHeartbeat>=timeoutMs || !parentAlive(parentPid)))void stop();},25);
|
||||
if(!parentAlive(parentPid))void stop();
|
||||
},intervalMs);
|
||||
const failure=(runId,error,unknown=false)=>send({type:'complete',runId,value:{error,unknown,reposted:false}});
|
||||
lines.on('line',line=>{
|
||||
if(closed)return;
|
||||
let value;try{if(line.length>2*1024*1024)throw Error();value=JSON.parse(line);}catch{send({type:'fatal',error:'本地消息无效;不会重发'});void stop();return;}
|
||||
if(value?.type==='heartbeat') {lastHeartbeat=Date.now();send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;}
|
||||
if(value?.type==='heartbeat') {send({type:'heartbeat_ack',id:value.id,brokerPid:broker?.child?.pid??null});return;}
|
||||
if(value?.type==='knowledge_cancel' && uuid.test(value.id||'')) {
|
||||
knowledge.get(value.id)?.abort(Error('已取消模板读取,已下载内容保留'));
|
||||
return;
|
||||
|
||||
78
apps/detail-agent-pi/test/desktop-daemon.test.mjs
Normal file
78
apps/detail-agent-pi/test/desktop-daemon.test.mjs
Normal file
@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { PassThrough } from 'node:stream';
|
||||
import { test } from 'node:test';
|
||||
import { startDaemon } from '../src/desktop-daemon.mjs';
|
||||
|
||||
const runId = '9a1ba294-f2c4-4e5f-91e0-ef6002f50e22';
|
||||
const tick = () => new Promise(resolve => setImmediate(resolve));
|
||||
|
||||
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('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]);
|
||||
});
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user