Steps resumed after the worker routes read the game as it is: a sales trial, the intern's PNI round and a failure's incident

While a step of the day waits for the route worker, the player can act. Three steps then resumed on what they had
noted before:
- a sales trial overtaken by an action ran again with the happy customers as indices into S.biz: a customer dropped
  meanwhile made one point past the end and the day stopped on an exception. dayAgain() makes the trial's checks,
  the customer and who is happy again on the game as it is; an offer signed or declined by hand meanwhile is not
  the desk's;
- the intern's PNI round placed the batch's quotes as they were: a PNI ordered by hand while it waited was ordered
  a second time. pniRequote() quotes each order again just before it is placed;
- a failure and the monkey's snip took the last incident after their routing: repaired meanwhile, it was gone or
  another one. They keep their own incident before the routing, and offer a repair only while it stands.
This commit is contained in:
Antoine 2026-11-06 14:14:51 +01:00
parent 3c45d7dca1
commit f3df5e5d23
No known key found for this signature in database
GPG key ID: E1FB0C46A71DA721
8 changed files with 98 additions and 10 deletions

View file

@ -43,6 +43,9 @@ function* slAutoRun(d){if(!slAutoOn())return;const A=S.slAuto,p=slP(),w=Math.flo
// Each trial is a full routing pass: at most SL_TRIALS a day, and an offer that did not fit waits a week.
if(!reqOk(o)||tries>=SL_TRIALS||tried.get(o.id)>d-SL_RETRY)return;tries++;b=offerTrialOf(o);return true;});
if(!todo)continue;
const got=b?yield {trial:b,hx:offerHealthy(b)}:null;
// o: the offer itself, for a trial the page has to run again on the game as it is by then (dayAgain()).
const got=b?yield {trial:b,hx:offerHealthy(b),o}:null;
// Signed or declined by hand while the trial routed: it is not the desk's.
if(!S.offers.includes(o))continue;
opsQuiet(()=>{OFFER_TRIED={o,b:got};try{ACT.accept({id:o.id,auto:true});}finally{OFFER_TRIED=null;}if(!won(o))tried.set(o.id,d);});}
if(dirty)yield;}

View file

@ -206,8 +206,10 @@ const OPS_RUN={
// exchange or a PNI elsewhere, the same figure the PNI list shows. Not the city's whole demand: a network's own
// cache boxes in that POP already serve most of it (#244).
const loc=q=>pniVal(q.net,q.city).want;
for(const q of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}},
// Each order quoted again just before it is placed: the player may have ordered the same PNI by hand while the shift
// let a frame through or waited for a routing, and the batch's quote would order it a second time.
for(const q0 of b.orders.filter(q=>opsHere('pni',q.city)&&loc(q)>=g&&(paid||NET[q.net].pol!=='paid'||paidFree(NET[q.net]))).sort((a,b)=>loc(b)-loc(a))){
const q=pniRequote(q0);if(!q)continue;if(!X.can('pni',q.cost))break;if(X.pay('pni',()=>{if(!spend(q.cost))return false;pniPlace(q);return true;}))X.did('pni',q.city+' '+q.net);yield;}},
// Hand back smaller waves once a bigger link between the same cities carries the pair with a quarter to spare (#102).
// Loads must include what this shift already did (a customer just signed, a repair): opsRun() routes first if a
// job changed the network and anything could go (opsDecomWaits()).

View file

@ -13,10 +13,16 @@ function pniPlace(q){const {city,net,tier,g1,ex}=q,lead=pniLead(net);
if(S.conf&&S.conf.until>S.day)S.stats.beerPni=1;
if(ex){ex.up={tier,n:ex.n||1,ready:S.day+lead,g1:false};if(!lead)pniUpDone(ex);}else S.pni.push({id:uid(),city,net,tier,g1:g1||undefined,ready:S.day+lead});
return lead;}
// The ports a pending augment will add, and those of every pending augment at a city: what an order there must leave free.
const pniUpSlots=p=>Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
const pniResv=c=>{let r=0;for(const p of S.pni)if(p.up&&p.city===c)r+=pniUpSlots(p);return r;};
// A batch's order quoted again on the game as it is now: null if it no longer stands (ordered by hand meanwhile, say).
// Earlier orders of the batch, placed by now, are in the PNIs themselves: the same ports the batch reserved for them.
const pniRequote=q=>{const n=pniQuote(q.city,q.net,q.g1?-1:q.tier,pniResv(q.city));return n&&!n.why&&n.ex===q.ex?n:null;};
function pniBatch(net,tier){tier=+tier;const all=net===null;if(!S||(!all&&!isNet(net))||!Number.isInteger(tier)||(tier===-1?all||!pniG1(net):!PORT[tier]||!portShown(tier)))return null;
const shared=[],orders=[],blocked=[],reserved={};let kept=0,cost=0,mo=0,raised=0;
// Pending augments and earlier orders in this batch already own their future ports.
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+Math.max(0,PORT_SLOT(p.up.tier)*(p.up.n||1)-PORT_SLOT(p.tier)*(p.n||1));
for(const p of S.pni)if(p.up)reserved[p.city]=(reserved[p.city]||0)+pniUpSlots(p);
for(const n of all?NETS:[NET[net]])for(const city of n.pops){if(!S.pops[city])continue;shared.push(city);
// Each network at its own minimum: asking everyone for 10G orders 100G from those that start at 100G.
const q=pniQuote(city,n.id,all&&tier>=0?Math.max(tier,pniMin(n.id)):tier,reserved[city]||0);if(!q){kept++;continue;}if(q.why){blocked.push(q);continue;}orders.push(q);if(q.tier>tier&&!q.g1)raised++;cost+=q.cost;reserved[city]=(reserved[city]||0)+q.slots;

View file

@ -27,7 +27,7 @@ if(${dict})self.I18N[${JSON.stringify(L)}]=${dict};
// Gone for good this session: the routing in flight is done here instead, and the day goes on without the worker.
// (A day resting between steps goes on by itself, on the page from then on.)
function rwKill(){RW.dead=true;if(RW.w)try{RW.w.terminate();}catch(e){}RW.w=null;const j=RW.job;if(!j||j.rest)return;RW.job=null;
if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAnswer(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);}
if(j.state!==S){rwDayDone();return;}let v;try{if(j.tr)v=dayAgain(j.tr);else compute();}catch(e){tickErr(e);}rwGo(j.g,v);}
// One day in play (dayRun(), 10-day-tick.js): its steps run here, every routing it asks for runs in the worker.
function rwDay(){rwGo(dayRun());}
// Runs the day's steps up to the next routing, posts it, and returns: rwDone() picks the day up when R is back. At a
@ -59,8 +59,8 @@ function rwDone(m,t0){const j=RW.job;if(!j||m.seq!==j.seq)return;RW.job=null;con
if(j.state!==S){rwDayDone();return;}
let v;
// A sales trial: the customer it signed off, or null. Something routed here meanwhile (an action), or the worker
// failed: the trial runs here, on the game as it is now.
if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAnswer(j.tr):m.ok?j.tr.trial:null;}
// failed: the trial runs again here, checks included, on the game as it is now (dayAgain()).
if(j.tr){if(m.err)console.error('[tubes] route worker',m.err);v=m.err||RW.gen!==j.gen?dayAgain(j.tr):m.ok?j.tr.trial:null;}
else if(m.err){console.error('[tubes] route worker',m.err);compute();}
else if(RW.gen===j.gen){R=rwUnpack(m.R,m.ef);UI.hotMap=hotByCity();}
const t1=performance.now(),st=RW.stat;st.n++;st.apply+=t1-t;st.wait+=t-j.t;st.work+=m.ms||0;

View file

@ -118,11 +118,13 @@ function* failureRun(only){
addInc({type,ref:f,until:S.ev.fab[f],msg:tr('failures.fabric_is_having_a_bad_day',{fabric:FAB[f].name}),cost:0});
}else if(type==='ddos'){ddosAttack(false);yield;yield* ddosNewsRun();return;
}
yield;
// This failure's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const last=S.inc[S.inc.length-1];
yield;
if(!last)return;
last.impact=Math.max(0,before-R.served);
if(before>1&&last.impact<before*0.03&&type!=='ddos'){S.stats.survived++;toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)} ${tr('failures.traffic_rerouted_customers_barely')}`,'good',[],incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
else{const paused=pref('pauseIncident')&&autoPause();toast(`<b>${incTitle(type)}</b><br>${esc(last.msg)}${paused?`<br><b>${tr('common.game_paused')}</b>`:''}`,'bad',(last.cost&&S.inc.includes(last)?[{l:`${last.fix||tr('common.rush_repair')} ${fmt$(last.cost)}`,act:'fixInc',args:{id:last.id}}]:[]).concat(paused?[resumeAct()]:[]),incOpen(last));}
sfx('alert');
}
const gamingCount=()=>S.biz.reduce((n,b)=>n+(BIZ_T[b.type]?.gaming?1:0),0);

View file

@ -39,7 +39,8 @@ function* mkSnipRun(){const M=S.monkey,live=S.links.filter(l=>l.kind!=='vxc'&&!l
const dur=rint(3,4),trc=l.trench||l.id,hit=S.links.filter(x=>(x.trench||x.id)===trc),A=CITY[l.a].name,B=CITY[l.b].name,before=R.served;
hit.forEach(x=>x.cut=Math.max(x.cut||0,S.day+dur));M.n++;M.c=l.a;
addInc({type:'cut',ref:trc,until:S.day+dur,msg:tr(pick(MK_SNIPS),{a:A,b:B}),cost:Math.max(4000,Math.round(hit.reduce((a,x)=>a+x.mo,0)*0.5))},'');
yield;const i=S.inc[S.inc.length-1],imp=Math.max(0,before-R.served);if(i)i.impact=imp;
// The snip's incident, kept before the routing: the player may repair it (or another) while the worker routes.
const i=S.inc[S.inc.length-1];yield;const imp=Math.max(0,before-R.served);if(i)i.impact=imp;
const felt=before>1&&imp>=before*0.03;if(felt)M.hurt++;else S.stats.survived++;
toast(felt?`<b>🐒 ${incTitle('cut')}</b><br>${esc(i?i.msg:'')}`:tr('chaos_monkey.rerouted',{a:A,b:B}),felt?'bad':'good',[],i?incOpen(i):null);sfx(felt?'err':'alert');
if(typeof mkRun==='function'){if(!UI.mk&&CITY[M.c])mkStart(M.c);mkRun(l,1400,felt);}}

View file

@ -13,6 +13,9 @@ function* dayRun(){const d=yield* dayPreRun();if(d===false)return;yield;yield* d
// customer it signs off or null (dayAnswer()): here at once, in play by the route worker.
const dayStep=(g,v)=>{UI.tick=true;try{return g.next(v);}finally{UI.tick=false;}};
const dayAnswer=y=>offerTrial(y.trial,y.hx);
// The same trial overtaken by an action (a customer gone shifts S.biz, so hx no longer points at the right ones):
// its checks, the customer and who is happy, made again on the game as it is now.
const dayAgain=y=>{const o=y.o;if(!o||!S.offers.includes(o))return null;const b=offerTrialOf(o);return b?offerTrial(b,offerHealthy(b)):null;};
function dayGo(g,step=dayStep){let v;for(let s=step(g);!s.done;s=step(g,v)){v=undefined;const y=s.value;if(y===DAY_REST)continue;if(y&&y.trial)v=dayAnswer(y);else compute();}}
function dayTick(){dayGo(dayRun());}
// dayPre(): the world's morning all at once; dayPreRun() the same with a place or two to let a frame through.

View file

@ -168,3 +168,74 @@ test('quiet notifications hold while the worker plays the day', (t) => {
assert.equal(p.ev('UI.tick'), false, 'and it is off between days');
assert.deepEqual(p.errors, []);
});
// What the player does while a step waits for the worker: the step goes on with the game as it is by then.
const TICK_ERR = "window.__te=[];tickErr=e=>__te.push(String(e&&e.stack||e));";
test('a customer dropped while a sales trial routes: the trial runs again on the customers left', (t) => {
const p = played(t);
p.ev(TICK_ERR);
p.ev("window.__ot=0;const ot=offerTrial;offerTrial=(...a)=>{__ot++;return ot(...a);};");
let found = false;
for (let d = 0; d < 20 && !found; d++) {
p.ev('rwDay()');
for (let k = 0; k < 400 && p.ev('!!RW.job'); k++) {
if (p.ev('__later.length')) { p.ev('__later.shift()()'); continue; }
// A trial the offer passes, the last customer among the happy ones: that customer goes, and the trial's list of
// who was happy (indices in S.biz) now points one past the end.
if (!found && p.ev('__q.length&&!!__q[0].trial&&!!__q[0].trial.hx&&__q[0].trial.hx.includes(S.biz.length-1)&&!!offerTrial(__q[0].trial.b,__q[0].trial.hx)')) {
found = true; p.ev('__ot=0;const b=S.biz[S.biz.length-1];UI.confirm=b.id;ACT.dropBiz({id:b.id});');
}
p.pump1();
}
}
assert.ok(found, 'the desk trialled an offer');
assert.equal(p.ev('__ot'), 1, 'the overtaken trial ran again on the page');
assert.equal(p.ev('JSON.stringify(__te)'), '[]');
assert.equal(p.ev('!!RW.job'), false);
assert.equal(p.ev('S.day'), p.ev('S.hist[S.hist.length-1].d'), 'the day was finished');
assert.deepEqual(p.errors, []);
});
test("the intern's PNI round never orders again what the player ordered while it waited", (t) => {
// The round's batch, then its first rest: the player orders every PNI of the batch by hand meanwhile.
const ROUND = (hand) => `while(S.day%7!==3)S.day++;S.ops.on.pni=true;
const pb=pniBatch;pniBatch=(...a)=>window.__b=pb(...a);
window.__b=null;const X=opsShift(),it=OPS_RUN.pni(X),n0=S.pni.length;let hand=0;
for(let s=it.next();!s.done;s=it.next())if(__b&&${hand}&&!hand){hand=1;const af=after;after=()=>{};try{for(const q of __b.orders)ACT.pni({city:q.city,net:q.net,tier:q.g1?-1:q.tier});}finally{after=af;}compute();window.__h=S.pni.length;}
window.__n=S.pni.length-n0;`;
const key = "S.pni.map(p=>p.city+'|'+p.net)";
const ref = open(t, 777), p = open(t, 777);
ref.ev(SETUP); p.ev(SETUP);
ref.ev(ROUND(false));
assert.ok(ref.ev('__b.orders.length') > 0 && ref.ev('__n') > 0, `the intern orders PNIs: ${ref.ev('__n')} of ${ref.ev('__b.orders.length')}`);
p.ev(ROUND(true));
assert.ok(p.ev('__h') > p.ev('S.pni.length') - p.ev('__n'), 'the player ordered some by hand');
assert.equal(p.ev('S.pni.length'), p.ev('__h'), 'the intern ordered nothing more');
const keys = p.ev(key);
assert.equal(new Set(keys).size, keys.length, 'one PNI per city and network');
assert.deepEqual([...ref.errors, ...p.errors], []);
});
test('an incident repaired while its routing runs: the failure and the monkey still tell its own story', (t) => {
const p = open(t, 777);
p.ev(SETUP);
// On land: a repair clears the incident (at sea it would charter a ship).
p.ev("S.rules.sea='timer';S.inc=[];");
// Repaired before the answer, the only incident there was: nothing left to read as "the last one".
p.ev(`const g=failureRun('cut');g.next();window.__i=S.inc[S.inc.length-1];ACT.fixInc({id:__i.id});g.next();`);
assert.equal(p.ev('S.inc.length'), 0);
assert.equal(p.ev('typeof __i.impact'), 'number', 'its impact is its own');
// An older incident stands: the new one's impact is not pinned on it.
p.ev(`runNow(failureRun('cut'));window.__a=S.inc[S.inc.length-1];__a.impact=-7;
const g2=failureRun('cut');g2.next();window.__b=S.inc[S.inc.length-1];ACT.fixInc({id:__b.id});g2.next();`);
assert.equal(p.ev('__a!==__b&&S.inc.includes(__a)&&!S.inc.includes(__b)'), true);
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
assert.equal(p.ev('typeof __b.impact'), 'number');
// The monkey's snip, the same way.
p.ev(`S.monkey={on:1,start:S.day,until:S.day+60,snip:S.day,n:0,hurt:0,c:S.home,next:S.day};
const g3=mkSnipRun();g3.next();window.__c=S.inc[S.inc.length-1];ACT.fixInc({id:__c.id});g3.next();`);
assert.equal(p.ev('__a.impact'), -7, 'the older incident keeps its impact');
assert.equal(p.ev('typeof __c.impact'), 'number');
assert.deepEqual(p.errors, []);
});